Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Mac and Linux app: a "needs you" nudge when something waits for you (#268)
Oleksandr Ivanchenko81b5a9570205
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.ymlindex 46cda859..d689055d 100644--- a/.github/workflows/linux.yml+++ b/.github/workflows/linux.yml@@ -225,6 +225,53 @@ jobs:cat "$KWNT_DATA_DIR/desktop-app.log" || truetest -n "$ok"echo "$body" | grep -q '"app":"kwnt"'+ # The "needs you" nudge on Linux: the tray icon swaps to the "!" mark and a system notification+ # names who needs you. Runs the built app's --demo-nudge (its own temp data dir and a free port)+ # on a virtual display with a tray (stalonetray) and a notification daemon (dunst), and keeps+ # screenshots as the nudge-linux artifact. Pictures never fail the job; the app crashing does.+ - name: Nudge screenshots (--demo-nudge)+ if: ${{ !startsWith(github.ref, 'refs/tags/') }}+ timeout-minutes: 8+ working-directory: apps/mac/target/release+ run: |+ set -uo pipefail+ out="$RUNNER_TEMP/nudge-linux"+ mkdir -p "$out"+ sudo apt-get install -y --no-install-recommends dunst stalonetray imagemagick x11-utils > /dev/null || true+ cat > "$RUNNER_TEMP/nudge-run.sh" <<'SH'+ #!/bin/bash+ out="$1"; app="$2"+ stalonetray --geometry 6x1+0+0 --icon-size 32 --background '#1e1e1e' > "$out/stalonetray.txt" 2>&1 &+ dunst > "$out/dunst.txt" 2>&1 &+ sleep 2+ "$app" --demo-nudge > "$out/demo-nudge.txt" 2>&1 &+ pid=$!+ shot() { sleep "$2"; command -v import > /dev/null && import -window root "$out/$1.png" || true; }+ waitfor() { for _ in $(seq 1 240); do grep -q "$1" "$out/demo-nudge.txt" && return 0; kill -0 $pid 2> /dev/null || return 1; sleep 0.5; done; return 1; }+ waitfor 'demo-nudge: step 1' && shot 01-tray-and-notification 2+ waitfor 'demo-nudge: step 3' && shot 02-three-waiting 2+ waitfor 'demo-nudge: step 4' && shot 03-four-waiting 2+ if ! kill -0 $pid 2> /dev/null; then+ wait $pid; echo "kwant --demo-nudge exited early with $?" >> "$out/demo-nudge.txt"; exit 1+ fi+ waitfor 'demo-nudge: done'+ wait $pid+ SH+ chmod +x "$RUNNER_TEMP/nudge-run.sh"+ xvfb-run -a -s "-screen 0 1280x800x24" dbus-run-session -- "$RUNNER_TEMP/nudge-run.sh" "$out" "$PWD/kwant"+ status=$?+ cat "$out/demo-nudge.txt" || true+ ls -l "$out"+ test $status -eq 0 || { echo "::error::kwant --demo-nudge crashed or stopped early"; exit 1; }+ grep -q 'demo-nudge: step 4' "$out/demo-nudge.txt" || { echo "::error::the demo never reached step 4"; exit 1; }+ grep -q 'demo-nudge: notification' "$out/demo-nudge.txt" || echo "::warning::no notification was shown (no notification service on the virtual display?)"+ - uses: actions/upload-artifact@v4+ if: ${{ always() && !startsWith(github.ref, 'refs/tags/') }}+ with:+ name: nudge-linux+ path: ${{ runner.temp }}/nudge-linux+ if-no-files-found: ignore+ retention-days: 14- name: Collect the packagesenv:DEB: ${{ steps.bundle.outputs.deb }}diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.ymlindex 2fc514ce..9b99c463 100644--- a/.github/workflows/mac.yml+++ b/.github/workflows/mac.yml@@ -335,6 +335,72 @@ jobs:path: ${{ runner.temp }}/dmg-windowif-no-files-found: ignoreretention-days: 14+ # The "needs you" nudge (apps/mac/src/nudge*.rs): the built app runs as --demo-nudge, where+ # made-up items arrive on a timeline (one, one more, two together, one under Reduce Motion),+ # and each is screenshotted in light or dark mode: the whole screen, the menu bar with the+ # pill under the icon, mid-animation and after it. A crash or a pill that never shows fails+ # the job; the screenshots themselves don't.+ - name: Nudge screenshots (--demo-nudge)+ run: |+ set -euo pipefail+ shots="$RUNNER_TEMP/nudge"+ mkdir -p "$shots"+ out="$shots/demo-nudge.txt"+ app=apps/mac/target/universal-apple-darwin/release/bundle/macos/kwant.app/Contents/MacOS/kwant+ mode() {+ osascript -e "tell application \"System Events\" to tell appearance preferences to set dark mode to $1" || true+ }+ waitfor() {+ for _ in $(seq 1 240); do grep -q "$1" "$out" && return 0; sleep 0.5; done+ echo "never saw: $1"; cat "$out"; return 1+ }+ shot() {+ screencapture -x "$shots/$1-screen.png" || true+ # the pill line says where it is (points); the crop is the menu bar's right end down to+ # under the pill+ local p+ p=$(grep -o 'demo-nudge: pill [0-9-]*,[0-9-]*' "$out" | tail -1 | sed 's/.* //') || true+ if [ -n "$p" ]; then+ local x=${p%,*} y=${p#*,}+ local rx=$(( x > 60 ? x - 60 : 0 ))+ screencapture -x -R "$rx,0,500,$(( y + 110 ))" "$shots/$1-menubar.png" || true+ fi+ }+ # Reduce Motion needs accessibility rights on the runner; the demo's step 4 plays as under it+ defaults write com.apple.universalaccess reduceMotion -bool false 2>/dev/null || true+ mode false+ "$app" --demo-nudge > "$out" 2>&1 &+ pid=$!+ waitfor "demo-nudge: step 1"+ sleep 0.4; shot 1-light-animating+ sleep 1.4; shot 1-light-pill+ mode true+ waitfor "demo-nudge: step 2"+ sleep 0.4; shot 2-dark-animating+ sleep 1.4; shot 2-dark-pill+ waitfor "demo-nudge: step 3"+ sleep 1.8; shot 3-dark-pill-coalesced+ sleep 6; shot 3-dark-resting+ mode false+ waitfor "demo-nudge: step 4"+ sleep 0.15; shot 4-light-reduce-motion-fading+ sleep 1.2; shot 4-light-reduce-motion-pill+ sleep 6; shot 4-light-resting+ ps -p $pid > /dev/null || { echo "the demo app died"; cat "$out"; exit 1; }+ kill $pid || true+ wait $pid 2>/dev/null || true+ mode false+ cat "$out"+ ls -l "$shots"+ test "$(grep -c 'demo-nudge: pill [0-9-]' "$out")" -ge 3+ grep -q 'demo-nudge: pill.*items=2' "$out"+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: nudge+ path: ${{ runner.temp }}/nudge+ if-no-files-found: ignore+ retention-days: 14- uses: actions/upload-artifact@v4with:name: ${{ steps.bundle.outputs.name }}diff --git a/apps/mac/Cargo.lock b/apps/mac/Cargo.lockindex 0b879a0b..01929c14 100644--- a/apps/mac/Cargo.lock+++ b/apps/mac/Cargo.lock@@ -2711,6 +2711,7 @@ version = "0.6.8"dependencies = ["dirs 5.0.1","kwnt",+ "objc2-app-kit","serde_json","tauri","tauri-build",@@ -2719,6 +2720,7 @@ dependencies = ["tokio","tracing","tracing-subscriber",+ "zbus",][[package]]diff --git a/apps/mac/Cargo.toml b/apps/mac/Cargo.tomlindex bf4b69fb..a8379fd2 100644--- a/apps/mac/Cargo.toml+++ b/apps/mac/Cargo.toml@@ -16,7 +16,8 @@ tauri-build = { version = "2", features = [] }[dependencies]kwnt = { path = "../.." }-tauri = { version = "2", features = ["tray-icon", "image-png"] }+# macos-private-api: the "needs you" pill is a transparent window (macOSPrivateApi in tauri.conf.json)+tauri = { version = "2", features = ["tray-icon", "image-png", "macos-private-api"] }tauri-plugin-updater = "2"tokio = { version = "1.40", features = ["rt-multi-thread", "sync", "macros", "time"] }serde_json = "1.0"@@ -28,6 +29,14 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }[target.'cfg(not(target_os = "macos"))'.dependencies]tauri-plugin-single-instance = "2"+# Reads System Settings › Accessibility › Reduce motion for the nudge (already in the tree via Tauri)+[target.'cfg(target_os = "macos")'.dependencies]+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSAccessibility", "NSWorkspace"] }++# Desktop notifications for the nudge over D-Bus (already in the tree via the single-instance plugin)+[target.'cfg(target_os = "linux")'.dependencies]+zbus = "5"+[profile.release]codegen-units = 4lto = "thin"diff --git a/apps/mac/icons/linux/tray-needs-you-dark.png b/apps/mac/icons/linux/tray-needs-you-dark.pngnew file mode 100644index 00000000..572e1466Binary files /dev/null and b/apps/mac/icons/linux/tray-needs-you-dark.png differdiff --git a/apps/mac/icons/linux/tray-needs-you-light.png b/apps/mac/icons/linux/tray-needs-you-light.pngnew file mode 100644index 00000000..43515236Binary files /dev/null and b/apps/mac/icons/linux/tray-needs-you-light.png differdiff --git a/apps/mac/icons/linux/tray-normal-dark.png b/apps/mac/icons/linux/tray-normal-dark.pngnew file mode 100644index 00000000..1d237828Binary files /dev/null and b/apps/mac/icons/linux/tray-normal-dark.png differdiff --git a/apps/mac/icons/linux/tray-normal-light.png b/apps/mac/icons/linux/tray-normal-light.pngnew file mode 100644index 00000000..473cb6e6Binary files /dev/null and b/apps/mac/icons/linux/tray-normal-light.png differdiff --git a/apps/mac/icons/nudge/frame-00.png b/apps/mac/icons/nudge/frame-00.pngnew file mode 100644index 00000000..1de51a09Binary files /dev/null and b/apps/mac/icons/nudge/frame-00.png differdiff --git a/apps/mac/icons/nudge/frame-01.png b/apps/mac/icons/nudge/frame-01.pngnew file mode 100644index 00000000..bc77d7abBinary files /dev/null and b/apps/mac/icons/nudge/frame-01.png differdiff --git a/apps/mac/icons/nudge/frame-02.png b/apps/mac/icons/nudge/frame-02.pngnew file mode 100644index 00000000..783771ebBinary files /dev/null and b/apps/mac/icons/nudge/frame-02.png differdiff --git a/apps/mac/icons/nudge/frame-03.png b/apps/mac/icons/nudge/frame-03.pngnew file mode 100644index 00000000..03febb20Binary files /dev/null and b/apps/mac/icons/nudge/frame-03.png differdiff --git a/apps/mac/icons/nudge/frame-04.png b/apps/mac/icons/nudge/frame-04.pngnew file mode 100644index 00000000..bc77d7abBinary files /dev/null and b/apps/mac/icons/nudge/frame-04.png differdiff --git a/apps/mac/icons/nudge/frame-05.png b/apps/mac/icons/nudge/frame-05.pngnew file mode 100644index 00000000..1de51a09Binary files /dev/null and b/apps/mac/icons/nudge/frame-05.png differdiff --git a/apps/mac/icons/nudge/frame-06.png b/apps/mac/icons/nudge/frame-06.pngnew file mode 100644index 00000000..eee81d20Binary files /dev/null and b/apps/mac/icons/nudge/frame-06.png differdiff --git a/apps/mac/icons/nudge/frame-07.png b/apps/mac/icons/nudge/frame-07.pngnew file mode 100644index 00000000..4c4353baBinary files /dev/null and b/apps/mac/icons/nudge/frame-07.png differdiff --git a/apps/mac/icons/nudge/frame-08.png b/apps/mac/icons/nudge/frame-08.pngnew file mode 100644index 00000000..83144b8dBinary files /dev/null and b/apps/mac/icons/nudge/frame-08.png differdiff --git a/apps/mac/icons/nudge/frame-09.png b/apps/mac/icons/nudge/frame-09.pngnew file mode 100644index 00000000..7ffaae20Binary files /dev/null and b/apps/mac/icons/nudge/frame-09.png differdiff --git a/apps/mac/icons/nudge/frame-10.png b/apps/mac/icons/nudge/frame-10.pngnew file mode 100644index 00000000..44708176Binary files /dev/null and b/apps/mac/icons/nudge/frame-10.png differdiff --git a/apps/mac/icons/nudge/frame-11.png b/apps/mac/icons/nudge/frame-11.pngnew file mode 100644index 00000000..83144b8dBinary files /dev/null and b/apps/mac/icons/nudge/frame-11.png differdiff --git a/apps/mac/icons/nudge/idle.png b/apps/mac/icons/nudge/idle.pngnew file mode 100644index 00000000..1de51a09Binary files /dev/null and b/apps/mac/icons/nudge/idle.png differdiff --git a/apps/mac/icons/nudge/needs-you.png b/apps/mac/icons/nudge/needs-you.pngnew file mode 100644index 00000000..83144b8dBinary files /dev/null and b/apps/mac/icons/nudge/needs-you.png differdiff --git a/apps/mac/loading/nudge.html b/apps/mac/loading/nudge.htmlnew file mode 100644index 00000000..297cd432--- /dev/null+++ b/apps/mac/loading/nudge.html@@ -0,0 +1,153 @@+<!doctype html>+<!-- From Mira's design: /home/maus/shared/ship-software-safely/mac-nudge/design/pill/pill.html (spec.md §2-3). -->+<!-- kwant Mac "needs you" pill window content (spec.md §3, §5). Drop in as apps/mac/loading/nudge.html.+ Rust drives it with window.eval("kwantNudge.show([...])"); it answers by navigating to+ kwant-nudge://open (clicked) or kwant-nudge://hidden (gone), which on_navigation catches and refuses. -->+<html><head><meta charset="utf-8"><meta name="color-scheme" content="light dark">+<style>+html, body { margin: 0; background: transparent; overflow: hidden; }+#slot { position: absolute; left: 10px; top: 4px; }+/* kwant "needs you" pill: one design for the Mac menu-bar pill and the in-app pill.+ Spec: ../spec.md §3. Motion: transform + opacity only. */+.kw-nudge {+ --kw-n-bg: #231d4b; --kw-n-edge: rgb(255 255 255 / .10);+ --kw-n-t1: #f7f6ff; --kw-n-t2: #bcb7de; --kw-n-chev: #9a94c4;+ --kw-n-shadow: 0 10px 28px rgb(0 0 0 / .45), 0 1px 3px rgb(0 0 0 / .35);+ position: relative; box-sizing: border-box;+ display: flex; align-items: center; gap: 10px;+ width: 320px; height: 52px; padding: 0 12px 0 10px; margin: 0;+ border: 0; border-radius: 26px;+ background: var(--kw-n-bg); color: var(--kw-n-t1);+ box-shadow: inset 0 0 0 1px var(--kw-n-edge), var(--kw-n-shadow);+ font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", Inter, "Segoe UI", Roboto, sans-serif;+ text-align: left; cursor: pointer; user-select: none; -webkit-user-select: none;+ transform-origin: 50% 0;+ animation: kw-nudge-rise 200ms cubic-bezier(.34, 1.56, .64, 1) backwards,+ kw-nudge-fade 120ms linear backwards;+ transition: transform 80ms ease-out;+}+.kw-nudge[data-theme="light"] {+ --kw-n-bg: #ffffff; --kw-n-edge: rgb(29 24 64 / .12);+ --kw-n-t1: #1d1840; --kw-n-t2: #5a5383; --kw-n-chev: #78719f;+ --kw-n-shadow: 0 10px 28px rgb(29 24 64 / .18), 0 1px 3px rgb(29 24 64 / .12);+}+.kw-nudge:active { transform: scale(.98); }+.kw-nudge:focus-visible { outline: 2px solid #b8adff; outline-offset: 2px; }+.kw-nudge.is-leaving { animation: kw-nudge-leave 160ms cubic-bezier(.4, 0, 1, 1) forwards; pointer-events: none; }++/* phone (in-app, viewport < 640 px) */+.kw-nudge--phone { width: calc(100vw - 24px); max-width: 420px; height: 56px; border-radius: 28px; padding-left: 12px; }++/* avatar: Mac = initial disc; in-app = <ModernAvatar size={32}> in the same 32 px box */+.kw-nudge__av {+ position: relative; flex: none; width: 32px; height: 32px; border-radius: 50%;+ background: #b8adff; color: #1b1033;+ font-size: 15px; line-height: 32px; font-weight: 700; text-align: center;+ animation: kw-nudge-hop 200ms 200ms backwards;+}+/* in-app: the real avatar fills the box, no disc colour */+.kw-nudge__av--img { background: none; }+.kw-nudge__av > img, .kw-nudge__av > svg.kw-av { width: 32px; height: 32px; border-radius: 50%; display: block; }+/* AvatarMood "needs you" badge: 7x7 plate, 2 px cells, "!" #ffb020 */+.kw-nudge__badge {+ position: absolute; top: -4px; right: -4px; width: 14px; height: 14px; display: block;+ border-radius: 3px; background: #1b1033; box-shadow: 0 0 0 2px var(--kw-n-bg);+ animation: kw-nudge-pop 160ms 200ms cubic-bezier(.34, 1.56, .64, 1) backwards;+}+.kw-nudge__text { flex: 1; min-width: 0; }+.kw-nudge__l1, .kw-nudge__l2 { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.kw-nudge__l1 { font-size: 13px; line-height: 16px; font-weight: 600; letter-spacing: -.08px; }+.kw-nudge__l2 { font-size: 12px; line-height: 16px; font-weight: 400; color: var(--kw-n-t2); }+.kw-nudge__chev { flex: none; width: 14px; height: 14px; color: var(--kw-n-chev); }+.kw-nudge.is-swapping .kw-nudge__text { animation: kw-nudge-fade 120ms linear backwards; }+.kw-nudge.is-swapping .kw-nudge__av { animation: kw-nudge-hop 200ms backwards; }++@keyframes kw-nudge-rise { from { transform: translateY(-16px) scale(.94); } to { transform: none; } }+@keyframes kw-nudge-fade { from { opacity: 0; } to { opacity: 1; } }+@keyframes kw-nudge-leave { to { transform: translateY(-8px); opacity: 0; } }+@keyframes kw-nudge-hop {+ 0% { transform: none; animation-timing-function: cubic-bezier(.2, 0, .4, 1); }+ 50% { transform: translateY(-4px); animation-timing-function: cubic-bezier(.6, 0, .8, 1); }+ 100% { transform: none; }+}+@keyframes kw-nudge-pop { from { transform: scale(.4); opacity: 0; } to { transform: none; opacity: 1; } }+@keyframes kw-nudge-fadeout { to { opacity: 0; } }++@media (prefers-reduced-motion: reduce) {+ .kw-nudge { animation: kw-nudge-fade 160ms linear backwards; transition: none; }+ .kw-nudge:active { transform: none; }+ .kw-nudge.is-leaving { animation: kw-nudge-fadeout 160ms linear forwards; }+ .kw-nudge__av, .kw-nudge__badge, .kw-nudge.is-swapping .kw-nudge__av { animation: none; }+}+</style>+<style>+/* Added for the app (not in Mira's design file): the same as the reduced-motion rules above, for+ when the app turns them on itself (--demo-nudge shows Reduce Motion without changing settings). */+html.kw-reduce .kw-nudge { animation: kw-nudge-fade 160ms linear backwards; transition: none; }+html.kw-reduce .kw-nudge:active { transform: none; }+html.kw-reduce .kw-nudge.is-leaving { animation: kw-nudge-fadeout 160ms linear forwards; }+html.kw-reduce .kw-nudge__av, html.kw-reduce .kw-nudge__badge, html.kw-reduce .kw-nudge.is-swapping .kw-nudge__av { animation: none; }+</style></head>+<body><div id="slot"></div>+<script>+(() => {+ const HOLD = 5000, AFTER_HOVER = 2000, CAP = 12000;+ const VERB = { approval: 'needs your OK', question: 'asked you something', human_step: 'needs you to do a step' };+ const BADGE = '<svg class="kw-nudge__badge" viewBox="0 0 14 14" aria-hidden="true"><rect x="6" y="2" width="2" height="6" fill="#ffb020"/><rect x="6" y="10" width="2" height="2" fill="#ffb020"/></svg>';+ const CHEV = '<svg class="kw-nudge__chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg>';+ const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+ const initial = n => (Array.from(String(n || '?').trim())[0] || '?').toUpperCase();+ const names = list => {+ const u = [...new Set(list.map(i => i.name || 'A bot'))];+ if (u.length === 1) return 'All from ' + u[0];+ if (u.length <= 3) return u.slice(0, -1).join(', ') + ' and ' + u[u.length - 1];+ return u.slice(0, 2).join(', ') + ' and ' + (u.length - 2) + ' more';+ };+ const theme = () => matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';+ let el = null, timer = 0, firstShown = 0, hovered = false;+ const go = what => { location.href = 'kwant-nudge://' + what; };+ // Plain text: escaped where it goes into HTML, as it is in the aria-label (an attribute set+ // through the DOM, never parsed), so "R&D" is read as "R&D".+ const content = items => {+ if (items.length === 1) {+ const i = items[0];+ return { av: initial(i.name), l1: (i.name || 'A bot') + ' ' + (VERB[i.kind] || 'needs you'), l2: String(i.title ?? '') };+ }+ return { av: items.length > 9 ? '9+' : String(items.length), l1: items.length + ' things need you', l2: names(items) };+ };+ // The 12 s cap only limits arrival restarts; after the pointer leaves it always waits the full 2 s.+ const arm = (ms, capped) => { clearTimeout(timer); timer = setTimeout(leave, capped ? Math.max(0, Math.min(ms, CAP - (Date.now() - firstShown))) : ms); };+ function leave() {+ if (!el || hovered) return;+ el.classList.add('is-leaving');+ // a pill that springs in during the slide-out is a new one: leave it alone+ const gone = el;+ setTimeout(() => { gone.remove(); if (el === gone) { el = null; go('hidden'); } }, 160);+ }+ window.kwantNudge = {+ /** items: [{kind:'approval'|'question'|'human_step', name, title}], newest last. Call again to coalesce. */+ show(items) {+ if (!items || !items.length) return;+ const c = content(items);+ const html = `<span class="kw-nudge__av">${esc(c.av)}${BADGE}</span>+ <span class="kw-nudge__text"><span class="kw-nudge__l1">${esc(c.l1)}</span><span class="kw-nudge__l2">${esc(c.l2)}</span></span>${CHEV}`;+ if (el && !el.classList.contains('is-leaving')) {+ el.innerHTML = html; el.classList.remove('is-swapping'); void el.offsetWidth; el.classList.add('is-swapping');+ } else {+ el?.remove();+ el = document.createElement('div');+ el.className = 'kw-nudge'; el.dataset.theme = theme(); el.setAttribute('role', 'button');+ el.innerHTML = html; firstShown = Date.now();+ el.addEventListener('mouseenter', () => { hovered = true; clearTimeout(timer); });+ el.addEventListener('mouseleave', () => { hovered = false; arm(AFTER_HOVER); });+ el.addEventListener('click', () => { clearTimeout(timer); hovered = false; go('open'); const gone = el; gone.classList.add('is-leaving'); setTimeout(() => { gone.remove(); if (el === gone) el = null; }, 120); });+ document.getElementById('slot').appendChild(el);+ }+ el.setAttribute('aria-label', c.l1 + '. ' + c.l2);+ arm(HOLD, true);+ },+ hide() { hovered = false; leave(); },+ };+ if (location.hash === '#demo') kwantNudge.show([{ kind: 'approval', name: 'Juno', title: 'Run migration 0042 on the goals table' }]);+})();+</script></body></html>diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rsindex 8651e7f6..936c5c3d 100644--- a/apps/mac/src/main.rs+++ b/apps/mac/src/main.rs@@ -2,14 +2,25 @@//! menu-bar (tray) icon. Closing the window keeps kwant running; Quit in the menu stops it.mod links;+mod nudge;+#[cfg(target_os = "linux")]+mod nudge_linux;+#[cfg(target_os = "macos")]+mod nudge_mac;mod startup;mod update;+#[cfg(target_os = "linux")]+use nudge_linux as platform;+#[cfg(target_os = "macos")]+use nudge_mac as platform;use startup::PortChoice;-use std::sync::{mpsc, Mutex};-use std::time::Duration;+use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{mpsc, Mutex, OnceLock};+use std::time::{Duration, Instant};use tauri::{- menu::{Menu, MenuItem, PredefinedMenuItem},+ menu::{CheckMenuItem, Menu, MenuItem, PredefinedMenuItem},tray::TrayIconBuilder,webview::NewWindowResponse,Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent,@@ -68,33 +79,30 @@ struct Target {port: u16,}+/// "Show nudges" in the tray menu, saved in the data dir.+struct Nudges {+ data_dir: PathBuf,+ show: AtomicBool,+}++/// Set (to its start) when the app runs as `--demo-nudge`.+static DEMO: OnceLock<Instant> = OnceLock::new();++/// The demo's last step plays as under Reduce Motion, which CI can't switch on.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+fn demo_reduce_motion() -> bool {+ DEMO.get().is_some_and(|t| nudge::demo::step(t.elapsed()) >= nudge::demo::REDUCE_MOTION_STEP)+}+fn main() {fix_path();if std::env::args().any(|a| a == "--check") {std::process::exit(check());}- let mut config = match kwnt::Config::load() {- Ok(c) => c,- Err(e) => fatal(&format!("kwant couldn't read its settings: {e}")),- };- init_logging(&config.data_dir);- // The app is a local window: never listen beyond this machine, whatever config.toml says- config.host = "127.0.0.1".to_string();- let choice = match startup::choose_port(config.port) {- Ok(c) => c,- Err(e) => fatal(&format!("kwant couldn't find a free port: {e}")),- };- let (port, server) = match choice {- PortChoice::Attach(port) => {- tracing::info!(port, "kwant already runs here; attaching to it");- (port, None)- }- PortChoice::Serve(port) => {- config.port = port;- (port, Some(start_server(config)))- }- };+ let demo = std::env::args().any(|a| a == "--demo-nudge");+ let (port, server, data_dir) = if demo { demo_start() } else { normal_start() };+ let show = nudge::Prefs::load(&data_dir).show_nudges;let builder = tauri::Builder::default();// A second launch from the app menu focuses this window instead of opening another kwant.@@ -106,13 +114,28 @@ fn main() {let app = builder.plugin(tauri_plugin_updater::Builder::new().build()).manage(Target { port })+ .manage(Nudges { data_dir, show: AtomicBool::new(show) }).setup(move |app| {if let Some(server) = server {app.manage(server);- update::start(app.handle());+ if !demo {+ update::start(app.handle());+ }}build_tray(app.handle())?;- open_window(app.handle());+ if demo {+ // hidden, so the pill shows (it never covers a focused kwant window); a click on+ // the pill shows it+ make_window(app.handle(), None, false);+ let h = app.handle().clone();+ std::thread::spawn(move || {+ std::thread::sleep(nudge::demo::RUNS_FOR);+ println!("demo-nudge: done");+ h.exit(0);+ });+ } else {+ open_window(app.handle());+ }Ok(())}).on_window_event(|window, event| {@@ -128,11 +151,61 @@ fn main() {app.run(|handle, event| match event {#[cfg(target_os = "macos")]RunEvent::Reopen { .. } => open_window(handle),- RunEvent::Exit => stop_server(handle),+ RunEvent::Exit => {+ stop_server(handle);+ if DEMO.get().is_some() {+ let _ = std::fs::remove_dir_all(&handle.state::<Nudges>().data_dir);+ }+ }_ => {}});}+/// The app's own kwant (or the one already running here), with the person's settings.+fn normal_start() -> (u16, Option<Server>, PathBuf) {+ let mut config = match kwnt::Config::load() {+ Ok(c) => c,+ Err(e) => fatal(&format!("kwant couldn't read its settings: {e}")),+ };+ init_logging(&config.data_dir);+ let data_dir = config.data_dir.clone();+ // The app is a local window: never listen beyond this machine, whatever config.toml says+ config.host = "127.0.0.1".to_string();+ let choice = match startup::choose_port(config.port) {+ Ok(c) => c,+ Err(e) => fatal(&format!("kwant couldn't find a free port: {e}")),+ };+ match choice {+ PortChoice::Attach(port) => {+ tracing::info!(port, "kwant already runs here; attaching to it");+ (port, None, data_dir)+ }+ PortChoice::Serve(port) => {+ config.port = port;+ (port, Some(start_server(config)), data_dir)+ }+ }+}++/// `--demo-nudge`: kwant on a free port with a throwaway data dir, and made-up waiting items+/// (`nudge::demo`) instead of the real ones, so CI can screenshot the nudges. It prints each+/// step and where the icon and the pill are, and quits after `nudge::demo::RUNS_FOR`.+fn demo_start() -> (u16, Option<Server>, PathBuf) {+ let _ = DEMO.set(Instant::now());+ tracing_subscriber::fmt().with_env_filter("info").init();+ let data_dir = std::env::temp_dir().join(format!("kwant-demo-nudge-{}", std::process::id()));+ let port = startup::free_port().unwrap_or_else(|e| fatal(&format!("kwant --demo-nudge: no free port: {e}")));+ let config = kwnt::Config {+ data_dir: data_dir.clone(),+ host: "127.0.0.1".to_string(),+ port,+ laya_managed: false,+ ..Default::default()+ };+ println!("demo-nudge: port {port}");+ (port, Some(start_server(config)), data_dir)+}+/// Finder (and a Linux app menu) starts apps with a bare PATH, so the claude, codex and grok CLIs/// would be missing. Runs before any thread exists, so setting the variable is safe.fn fix_path() {@@ -179,15 +252,41 @@ fn stop_server(handle: &tauri::AppHandle) {/// Shows the window, creating it the first time. It opens on a "Starting kwant…" page and moves/// to kwant's own page once /api/health answers.fn open_window(handle: &tauri::AppHandle) {- if let Some(window) = handle.get_webview_window(MAIN) {- let _ = window.show();- let _ = window.unminimize();- let _ = window.set_focus();+ open_window_at(handle, None)+}++/// Shows the window at one of kwant's pages (`path`, e.g. `/s/spc_default/inbox`): a nudge's+/// item. `None` keeps the page it shows.+fn open_window_at(handle: &tauri::AppHandle, path: Option<&str>) {+ let Some(window) = handle.get_webview_window(MAIN) else {+ make_window(handle, path, true);return;+ };+ if let Some(path) = path {+ let port = handle.state::<Target>().port;+ if let Ok(url) = format!("http://127.0.0.1:{port}{path}").parse() {+ let _ = window.navigate(url);+ }}+ let _ = window.show();+ let _ = window.unminimize();+ let _ = window.set_focus();+}++/// Whether the kwant window has the keyboard (the nudges then stay quiet).+fn main_focused(handle: &tauri::AppHandle) -> bool {+ handle+ .get_webview_window(MAIN)+ .and_then(|w| w.is_focused().ok())+ .unwrap_or(false)+}++fn make_window(handle: &tauri::AppHandle, path: Option<&str>, visible: bool) {let port = handle.state::<Target>().port;+ let path = path.unwrap_or("/").to_string();let window = match WebviewWindowBuilder::new(handle, MAIN, WebviewUrl::App("index.html".into())).title("kwant")+ .visible(visible).inner_size(1280.0, 820.0).min_inner_size(900.0, 600.0).initialization_script(APP_MARK)@@ -223,23 +322,27 @@ fn open_window(handle: &tauri::AppHandle) {let _ = window.eval("document.body.dataset.state = 'failed'");return;}- let url = format!("http://127.0.0.1:{port}/");+ let url = format!("http://127.0.0.1:{port}{path}");if let Ok(url) = url.parse() {let _ = window.navigate(url);}});}-/// The menu-bar icon: Open kwant, a status line, Quit. The status counts approvals waiting.+/// The menu-bar icon: Open kwant, a status line, Show nudges, Quit. The status counts what waits+/// for the person (questions and approvals); the nudges (`nudge.rs`) follow the same poll./// "Update to x.y.z…" appears at the top while a newer version is on offer.fn build_tray(handle: &tauri::AppHandle) -> tauri::Result<()> {let update = MenuItem::with_id(handle, "update", "Update kwant bots…", true, None::<&str>)?;let update_separator = PredefinedMenuItem::separator(handle)?;let open = MenuItem::with_id(handle, "open", "Open kwant", true, None::<&str>)?;let status = MenuItem::with_id(handle, "status", "Starting…", false, None::<&str>)?;+ let show = handle.state::<Nudges>().show.load(Ordering::Relaxed);+ let nudges = CheckMenuItem::with_id(handle, "nudges", "Show nudges", true, show, None::<&str>)?;let quit = MenuItem::with_id(handle, "quit", "Quit kwant", true, Some("CmdOrCtrl+Q"))?;let separator = PredefinedMenuItem::separator(handle)?;- let menu = Menu::with_items(handle, &[&open, &status, &separator, &quit])?;+ let separator2 = PredefinedMenuItem::separator(handle)?;+ let menu = Menu::with_items(handle, &[&open, &status, &separator, &nudges, &separator2, &quit])?;let icon = tauri::image::Image::from_bytes(TRAY_ICON)?;let tray = TrayIconBuilder::with_id("kwant").icon(icon)@@ -256,6 +359,14 @@ fn build_tray(handle: &tauri::AppHandle) -> tauri::Result<()> {}open_window(app);}+ "nudges" => {+ let state = app.state::<Nudges>();+ let on = !state.show.load(Ordering::Relaxed);+ state.show.store(on, Ordering::Relaxed);+ if let Err(e) = (nudge::Prefs { show_nudges: on }).save(&state.data_dir) {+ tracing::warn!(error = %e, "couldn't save Show nudges");+ }+ }"quit" => app.exit(0),_ => {}})@@ -263,12 +374,37 @@ fn build_tray(handle: &tauri::AppHandle) -> tauri::Result<()> {let port = handle.state::<Target>().port;let hub = kwnt::app_update::UpdateHub::shared();+ let app = handle.clone();std::thread::spawn(move || {let mut shown = false;+ let mut checked = show;+ let mut nudger = platform::Nudger::start(&app, tray.clone());+ let mut tracker = nudge::Tracker::default();+ let mut demo_step = 0;loop {- let (line, badge) = status_line(port);- let _ = status.set_text(line);+ let demo = DEMO.get().map(|t| nudge::demo::step(t.elapsed()));+ let waiting = match demo {+ Some(step) => Some(nudge::demo::waiting(step)),+ None => poll_waiting(port),+ };+ let show = app.state::<Nudges>().show.load(Ordering::Relaxed);+ if show != checked {+ checked = nudges.set_checked(show).map(|_| show).unwrap_or(checked);+ }+ let (line, badge) = match &waiting {+ Some(w) => nudge::status_line(w, port),+ None => ("Starting…".to_string(), None),+ };+ let _ = status.set_text(&line);let _ = tray.set_title(badge.as_deref());+ if let Some(w) = &waiting {+ let change = tracker.update(w, Instant::now());+ nudger.on_poll(&app, &change, show);+ }+ if let Some(step) = demo.filter(|s| *s != demo_step) {+ demo_step = step;+ println!("demo-nudge: step {step}: {line}");+ }match update::menu_item(&hub.status()) {Some((text, enabled)) => {if !shown {@@ -284,25 +420,62 @@ fn build_tray(handle: &tauri::AppHandle) -> tauri::Result<()> {}None => {}}- std::thread::sleep(Duration::from_secs(5));+ // the demo moves on a timeline CI screenshots, so it looks every second+ std::thread::sleep(Duration::from_secs(if demo.is_some() { 1 } else { 5 }));}});Ok(())}-/// The menu's status line and the number shown next to the icon (`None`: nothing waiting).-fn status_line(port: u16) -> (String, Option<String>) {+/// What waits for the person in every space (`None`: kwant isn't answering yet). A kwant too old+/// for /api/away still gets its approvals counted, without nudges.+fn poll_waiting(port: u16) -> Option<nudge::Waiting> {if !startup::is_kwant(port) {- return ("Starting…".to_string(), None);+ return None;}- let waiting = startup::http_get(port, "/api/approvals?status=pending", Duration::from_secs(2))- .filter(|(status, _)| *status == 200)- .and_then(|(_, body)| serde_json::from_str::<Vec<serde_json::Value>>(&body).ok())- .map(|rows| rows.len());- match waiting {- Some(0) | None => (format!("Running on port {port}"), None),- Some(1) => ("1 approval waiting for you".to_string(), Some("1".to_string())),- Some(n) => (format!("{n} approvals waiting for you"), Some(n.to_string())),+ let get = |path: &str| {+ startup::http_get(port, path, Duration::from_secs(2))+ .filter(|(status, _)| *status == 200)+ .map(|(_, body)| body)+ };+ let spaces = get("/api/spaces").and_then(|b| nudge::parse_spaces(&b));+ let mut all = nudge::Waiting::default();+ let mut answered = false;+ match spaces {+ Some(ids) if !ids.is_empty() => {+ for id in ids {+ if let Some(w) = get(&nudge::away_path(Some(&id))).and_then(|b| nudge::parse_away(&b, Some(&id))) {+ all.add(w);+ answered = true;+ }+ }+ }+ _ => {+ if let Some(w) = get(&nudge::away_path(None)).and_then(|b| nudge::parse_away(&b, None)) {+ all.add(w);+ answered = true;+ }+ }+ }+ if !answered {+ let approvals = get("/api/approvals?status=pending")+ .and_then(|b| serde_json::from_str::<Vec<serde_json::Value>>(&b).ok())+ .map(|rows| rows.len())+ .unwrap_or(0);+ all.count = approvals;+ }+ Some(all)+}++/// Platforms without a nudge of their own (the app ships for macOS and Linux) keep the count.+#[cfg(not(any(target_os = "macos", target_os = "linux")))]+mod platform {+ pub struct Nudger;+ impl Nudger {+ pub fn start(_: &tauri::AppHandle, _: tauri::tray::TrayIcon) -> Nudger {+ Nudger+ }+ pub fn on_poll(&mut self, _: &tauri::AppHandle, _: &crate::nudge::Change, _: bool) {}}}diff --git a/apps/mac/src/nudge.rs b/apps/mac/src/nudge.rsnew file mode 100644index 00000000..b5c33a13--- /dev/null+++ b/apps/mac/src/nudge.rs@@ -0,0 +1,670 @@+//! "Needs you" nudges: what the menu-bar/tray icon, the macOS pill and the Linux notification+//! know about the things waiting on the person. Plain std + serde_json, so every rule here is+//! tested without a window; the platform parts live in `nudge_mac.rs` and `nudge_linux.rs`.+//!+//! What counts is everything `GET /api/away` lists as `waiting`: open questions and pending+//! approvals, in every space. Finished and failed work never counts.++use std::collections::HashSet;+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++/// A replay of the icon animation while something still waits.+pub const REPLAY_EVERY: Duration = Duration::from_secs(15 * 60);+/// The app's own settings file in the data dir.+pub const PREFS_FILE: &str = "desktop-app.json";+/// `since` far in the future: `/api/away` then lists no finished or failed work, only what+/// waits (which it lists whatever `since` is), so the 5-second poll stays small.+const SINCE_NOTHING: &str = "2999-01-01T00:00:00Z";+/// Seen ids kept before the ones no longer waiting are dropped.+const SEEN_CAP: usize = 1000;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Kind {+ Question,+ Approval,+}++/// One thing waiting on the person, as `/api/away` lists it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Item {+ pub kind: Kind,+ pub id: String,+ pub space_id: Option<String>,+ pub kwant_id: String,+ pub kwant_name: String,+ /// Already clipped and secret-masked by the server.+ pub title: String,+ pub thread_id: Option<String>,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+}++impl Item {+ /// The same item in a seen-set: ids are unique per kind.+ pub fn key(&self) -> String {+ let kind = match self.kind {+ Kind::Question => "q",+ Kind::Approval => "a",+ };+ format!("{kind}:{}", self.id)+ }+}++/// What waits in one space: the listed items and the server's count (which can pass the+/// 50 items a list holds).+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Waiting {+ pub items: Vec<Item>,+ pub count: usize,+}++impl Waiting {+ pub fn add(&mut self, other: Waiting) {+ self.items.extend(other.items);+ self.count += other.count;+ }+}++/// The path of `/api/away` for a space (`None`: the default space).+pub fn away_path(space_id: Option<&str>) -> String {+ match space_id {+ Some(s) => format!("/api/away?since={SINCE_NOTHING}&space={}", encode(s)),+ None => format!("/api/away?since={SINCE_NOTHING}"),+ }+}++/// The ids of the spaces `GET /api/spaces` lists (archived ones aren't listed).+pub fn parse_spaces(body: &str) -> Option<Vec<String>> {+ let rows: Vec<serde_json::Value> = serde_json::from_str(body).ok()?;+ Some(rows.iter().filter_map(|r| r["id"].as_str().map(str::to_string)).collect())+}++/// A `GET /api/away` body: its `waiting` questions and approvals and `unseen.waiting`.+pub fn parse_away(body: &str, space_id: Option<&str>) -> Option<Waiting> {+ let v: serde_json::Value = serde_json::from_str(body).ok()?;+ let rows = v["waiting"].as_array()?;+ let text = |r: &serde_json::Value, k: &str| r[k].as_str().filter(|s| !s.is_empty()).map(str::to_string);+ let items: Vec<Item> = rows+ .iter()+ .filter_map(|r| {+ let kind = match r["kind"].as_str()? {+ "question" => Kind::Question,+ "approval" => Kind::Approval,+ _ => return None,+ };+ let link = &r["link"];+ Some(Item {+ kind,+ id: text(r, "id")?,+ space_id: space_id.map(str::to_string),+ kwant_id: text(r, "kwant_id").unwrap_or_default(),+ kwant_name: text(r, "kwant_name").unwrap_or_else(|| "A bot".to_string()),+ title: text(r, "title").unwrap_or_default(),+ thread_id: text(link, "thread_id"),+ channel_id: text(link, "channel_id"),+ direct_kwant_id: text(link, "direct_kwant_id"),+ })+ })+ .collect();+ let count = v["unseen"]["waiting"]+ .as_u64()+ .map(|n| n as usize)+ .unwrap_or(items.len())+ .max(items.len());+ Some(Waiting { items, count })+}++/// The menu's status line and the number next to the icon (`None`: nothing waits).+/// Approvals keep their wording when only approvals wait; questions get theirs; a mix is "things".+pub fn status_line(waiting: &Waiting, port: u16) -> (String, Option<String>) {+ let n = waiting.count;+ if n == 0 {+ return (format!("Running on port {port}"), None);+ }+ let questions = waiting.items.iter().filter(|i| i.kind == Kind::Question).count();+ let approvals = waiting.items.len() - questions;+ let listed_all = waiting.items.len() == n;+ let noun = match (questions, approvals) {+ (0, _) if listed_all => ("approval", "approvals"),+ (_, 0) if listed_all => ("question", "questions"),+ _ => ("thing", "things"),+ };+ let line = match n {+ 1 => format!("1 {} waiting for you", noun.0),+ _ => format!("{n} {} waiting for you", noun.1),+ };+ (line, Some(n.to_string()))+}++/// What one poll changed.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct Change {+ /// Items not seen before, newest first as the server lists them.+ pub arrived: Vec<Item>,+ /// Play the icon animation (something arrived, or the 15-minute replay is due).+ pub play: bool,+ pub count: usize,+ /// The keys of everything still waiting, so a pill can drop what was answered meanwhile.+ pub live: HashSet<String>,+}++/// Remembers which waiting items the person was already nudged about.+#[derive(Debug, Default)]+pub struct Tracker {+ seen: HashSet<String>,+ last_play: Option<Instant>,+}++impl Tracker {+ pub fn update(&mut self, waiting: &Waiting, now: Instant) -> Change {+ let arrived: Vec<Item> = waiting.items.iter().filter(|i| !self.seen.contains(&i.key())).cloned().collect();+ self.seen.extend(arrived.iter().map(Item::key));+ let live: HashSet<String> = waiting.items.iter().map(Item::key).collect();+ if self.seen.len() > SEEN_CAP {+ // Answered items never come back with the same id; keep only what still waits+ self.seen.retain(|k| live.contains(k));+ }+ let due = waiting.count > 0 && self.last_play.is_some_and(|t| now.duration_since(t) >= REPLAY_EVERY);+ let play = !arrived.is_empty() || due;+ if play {+ self.last_play = Some(now);+ }+ if waiting.count == 0 {+ self.last_play = None;+ }+ Change { arrived, play, count: waiting.count, live }+ }+}++impl Kind {+ /// The name `/api/away` (and the pill page) use.+ #[cfg_attr(not(target_os = "macos"), allow(dead_code))] // only the macOS pill page takes it+ pub fn as_str(&self) -> &'static str {+ match self {+ Kind::Approval => "approval",+ Kind::Question => "question",+ }+ }+}++/// The first line of a nudge for one item.+pub fn headline(item: &Item) -> String {+ match item.kind {+ Kind::Approval => format!("{} needs your OK", item.kwant_name),+ Kind::Question => format!("{} asked you something", item.kwant_name),+ }+}++/// What the pill (or a notification) says, and where a click goes.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Pill {+ pub headline: String,+ pub detail: String,+ /// The avatar's letter; empty for several items.+ pub initial: String,+ /// The kwant page to open, a path such as `/s/spc_default/c/ch1`.+ pub target: String,+}++/// The pill for `items` (newest first), all arriving within one pill's time: one item names its+/// bot and opens its chat; several say how many and open the Inbox.+pub fn pill(items: &[Item]) -> Option<Pill> {+ match items {+ [] => None,+ [one] => Some(Pill {+ headline: headline(one),+ detail: one.title.clone(),+ initial: one.kwant_name.chars().next().map(|c| c.to_uppercase().collect()).unwrap_or_default(),+ target: target_path(one),+ }),+ [first, ..] => {+ let mut names: Vec<&str> = Vec::new();+ for i in items {+ if !names.contains(&i.kwant_name.as_str()) {+ names.push(&i.kwant_name);+ }+ }+ let detail = match names.as_slice() {+ [a] => format!("All from {a}"),+ [a, b] => format!("{a} and {b}"),+ [a, b, c] => format!("{a}, {b} and {c}"),+ [a, b, rest @ ..] => format!("{a}, {b} and {} more", rest.len()),+ [] => String::new(),+ };+ Some(Pill {+ headline: format!("{} things need you", items.len()),+ detail,+ initial: String::new(),+ target: inbox_path(first.space_id.as_deref()),+ })+ }+ }+}++fn space_base(space_id: Option<&str>) -> String {+ format!("/s/{}", encode(space_id.unwrap_or("spc_default")))+}++/// The Inbox of a space.+pub fn inbox_path(space_id: Option<&str>) -> String {+ format!("{}/inbox", space_base(space_id))+}++/// Where an item opens in the kwant window: its channel, else its bot's chat. A thread has no+/// address of its own in the page, so a thread item opens the Inbox, where it is one click away.+pub fn target_path(item: &Item) -> String {+ let base = space_base(item.space_id.as_deref());+ if let Some(c) = &item.channel_id {+ return format!("{base}/c/{}", encode(c));+ }+ if item.thread_id.is_some() {+ return format!("{base}/inbox");+ }+ let bot = item.direct_kwant_id.as_deref().unwrap_or(&item.kwant_id);+ if bot.is_empty() {+ return format!("{base}/inbox");+ }+ format!("{base}/b/{}", encode(bot))+}++/// Percent-encodes everything but RFC 3986 unreserved characters (a path segment or query value).+pub fn encode(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for b in s.bytes() {+ match b {+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),+ _ => out.push_str(&format!("%{b:02X}")),+ }+ }+ out+}++/// Two places of the pill window (points) count as the same within half a point.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))] // only the macOS pill is placed+pub fn same_spot(a: (f64, f64), b: (f64, f64)) -> bool {+ (a.0 - b.0).abs() < 0.5 && (a.1 - b.1).abs() < 0.5+}++/// Waits for the menu-bar icon to stop moving before a fresh pill shows: reads where the pill+/// would go, then again every `every`, until `need` reads in a row agree or `cap` has passed on+/// `elapsed` (the wall clock since the wait began, so slow reads count too; the last read can end+/// up to one read past it). The 0 -> 1 nudge sets the icon's count and AppKit lays the bar out+/// again a moment later, sometimes in two steps (width first, then x), so the first read alone+/// would put the pill ~11 pt off, and two early reads can agree on a spot that still moves.+/// Returns the last read (`None`: the screen couldn't be read) and how many reads it took.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+pub fn settle(+ mut read: impl FnMut() -> Option<(f64, f64)>,+ every: Duration,+ need: usize,+ cap: Duration,+ mut elapsed: impl FnMut() -> Duration,+ mut sleep: impl FnMut(Duration),+) -> (Option<(f64, f64)>, usize) {+ let mut last = read();+ let (mut reads, mut same) = (1, 1);+ while same < need && elapsed() + every <= cap {+ sleep(every);+ let now = read();+ reads += 1;+ let agree = match (last, now) {+ (Some(a), Some(b)) => same_spot(a, b),+ (None, None) => true,+ _ => false,+ };+ same = if agree { same + 1 } else { 1 };+ last = now;+ }+ (last, reads)+}++/// The app's own settings, kept in [`PREFS_FILE`] in the data dir.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Prefs {+ /// Icon animation, pill and notifications. Off keeps the count.+ pub show_nudges: bool,+}++impl Default for Prefs {+ fn default() -> Self {+ Prefs { show_nudges: true }+ }+}++pub fn prefs_path(data_dir: &Path) -> PathBuf {+ data_dir.join(PREFS_FILE)+}++impl Prefs {+ /// The saved settings; a missing or unreadable file means the defaults.+ pub fn load(data_dir: &Path) -> Prefs {+ let saved = std::fs::read_to_string(prefs_path(data_dir))+ .ok()+ .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok());+ Prefs {+ show_nudges: saved.and_then(|v| v["show_nudges"].as_bool()).unwrap_or(true),+ }+ }++ /// Saves the settings, keeping any other keys the file holds.+ pub fn save(&self, data_dir: &Path) -> std::io::Result<()> {+ let path = prefs_path(data_dir);+ let mut v = std::fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())+ .filter(|v| v.is_object())+ .unwrap_or_else(|| serde_json::json!({}));+ v["show_nudges"] = serde_json::Value::Bool(self.show_nudges);+ std::fs::create_dir_all(data_dir)?;+ let tmp = path.with_extension("json.tmp");+ std::fs::write(&tmp, serde_json::to_vec_pretty(&v).unwrap_or_default())?;+ std::fs::rename(tmp, path)+ }+}++/// `--demo-nudge`: made-up waiting items that arrive on a timeline, so CI can screenshot a+/// single pill, a second one, two arriving together (coalesced), and one under Reduce Motion.+pub mod demo {+ use super::{Item, Kind, Waiting};+ use std::time::Duration;++ /// When each step's items appear, counted from the first poll.+ pub const STEPS: [Duration; 4] =+ [Duration::from_secs(6), Duration::from_secs(30), Duration::from_secs(54), Duration::from_secs(78)];+ /// The step whose nudge plays as under Reduce Motion (the runner's setting can't be changed).+ pub const REDUCE_MOTION_STEP: usize = 4;+ /// The demo quits on its own this long after start.+ pub const RUNS_FOR: Duration = Duration::from_secs(100);++ fn item(kind: Kind, id: &str, name: &str, title: &str) -> Item {+ Item {+ kind,+ id: id.to_string(),+ space_id: Some("spc_default".to_string()),+ kwant_id: format!("bot-{}", name.to_lowercase()),+ kwant_name: name.to_string(),+ title: title.to_string(),+ thread_id: None,+ channel_id: None,+ direct_kwant_id: None,+ }+ }++ /// How many steps have happened `elapsed` after start.+ pub fn step(elapsed: Duration) -> usize {+ STEPS.iter().filter(|t| elapsed >= **t).count()+ }++ /// What waits after `step` steps.+ pub fn waiting(step: usize) -> Waiting {+ let all = [+ (1, item(Kind::Approval, "demo-a1", "Juno", "Use Bash (deploy the site to kwant.si)")),+ (2, item(Kind::Question, "demo-q1", "Mira", "Which colour should the sticker badge use?")),+ (3, item(Kind::Approval, "demo-a2", "Rigel", "Use Bash (run the release checks)")),+ (3, item(Kind::Question, "demo-q2", "Pixel", "Ship the sidebar change today?")),+ (4, item(Kind::Question, "demo-q3", "Vega", "Keep the old results view for a week?")),+ ];+ // newest first, as /api/away lists them+ let items: Vec<Item> = all.into_iter().rev().filter(|(s, _)| *s <= step).map(|(_, i)| i).collect();+ Waiting { count: items.len(), items }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn item(kind: Kind, id: &str, name: &str) -> Item {+ Item {+ kind,+ id: id.into(),+ space_id: Some("spc_default".into()),+ kwant_id: format!("k-{id}"),+ kwant_name: name.into(),+ title: format!("title {id}"),+ thread_id: None,+ channel_id: None,+ direct_kwant_id: None,+ }+ }++ fn waiting(items: Vec<Item>) -> Waiting {+ Waiting { count: items.len(), items }+ }++ const AWAY: &str = r#"{+ "since": "2999-01-01T00:00:00.000Z",+ "waiting": [+ {"kind":"approval","id":"ap1","kwant_id":"k1","kwant_name":"Juno","title":"Use Bash","summary":"command: ls",+ "status":"pending","timestamp":"2026-11-03T21:00:00.000Z",+ "link":{"thread_id":null,"channel_id":"ch 1","direct_kwant_id":null},"tool_name":"Bash","details":{}},+ {"kind":"question","id":"q1","kwant_id":"k2","kwant_name":"Mira","title":"Which colour?","summary":"Waiting for your answer",+ "status":"open","timestamp":"2026-11-03T20:00:00.000Z",+ "link":{"thread_id":"t1","channel_id":null,"direct_kwant_id":null},"choices":[]},+ {"kind":"delegation","id":"d1","kwant_id":"k3","title":"stuck","link":{}}+ ],+ "finished": [], "failed": [],+ "unseen": {"waiting": 2, "finished": 0, "failed": 0, "total": 2}+ }"#;++ #[test]+ fn away_lists_questions_and_approvals_with_their_links() {+ let w = parse_away(AWAY, Some("sp1")).unwrap();+ assert_eq!(w.count, 2);+ assert_eq!(w.items.len(), 2, "only questions and approvals count");+ assert_eq!(w.items[0].kind, Kind::Approval);+ assert_eq!(w.items[0].channel_id.as_deref(), Some("ch 1"));+ assert_eq!(w.items[0].space_id.as_deref(), Some("sp1"));+ assert_eq!(w.items[1].kind, Kind::Question);+ assert_eq!(w.items[1].thread_id.as_deref(), Some("t1"));+ assert!(parse_away("not json", None).is_none());+ assert!(parse_away(r#"{"error":"no such space"}"#, None).is_none());+ }++ #[test]+ fn the_count_is_the_server_s_even_past_the_listed_items() {+ let body = r#"{"waiting":[{"kind":"question","id":"q","kwant_name":"A","title":"x","link":{}}],"unseen":{"waiting":57}}"#;+ let w = parse_away(body, None).unwrap();+ assert_eq!((w.count, w.items.len()), (57, 1));+ // a mixed or partly listed count is "things"+ assert_eq!(status_line(&w, 8799).0, "57 things waiting for you");+ }++ #[test]+ fn the_poll_asks_for_waiting_items_only_in_each_space() {+ assert_eq!(away_path(None), "/api/away?since=2999-01-01T00:00:00Z");+ assert_eq!(away_path(Some("sp 1&x")), "/api/away?since=2999-01-01T00:00:00Z&space=sp%201%26x");+ assert_eq!(parse_spaces(r#"[{"id":"spc_default","name":"Home"},{"id":"s2"}]"#).unwrap(), vec!["spc_default", "s2"]);+ assert!(parse_spaces("{}").is_none());+ }++ #[test]+ fn status_line_words_follow_what_waits() {+ assert_eq!(status_line(&Waiting::default(), 8799), ("Running on port 8799".into(), None));+ let one_a = waiting(vec![item(Kind::Approval, "a", "J")]);+ assert_eq!(status_line(&one_a, 1), ("1 approval waiting for you".into(), Some("1".into())));+ let two_a = waiting(vec![item(Kind::Approval, "a", "J"), item(Kind::Approval, "b", "J")]);+ assert_eq!(status_line(&two_a, 1).0, "2 approvals waiting for you");+ let one_q = waiting(vec![item(Kind::Question, "q", "J")]);+ assert_eq!(status_line(&one_q, 1).0, "1 question waiting for you");+ let mix = waiting(vec![item(Kind::Question, "q", "J"), item(Kind::Approval, "a", "J"), item(Kind::Approval, "b", "J")]);+ assert_eq!(status_line(&mix, 1), ("3 things waiting for you".into(), Some("3".into())));+ }++ #[test]+ fn a_new_item_plays_once_and_a_seen_one_never_again() {+ let mut t = Tracker::default();+ let now = Instant::now();+ let w = waiting(vec![item(Kind::Approval, "a", "Juno")]);+ let c = t.update(&w, now);+ assert!(c.play);+ assert_eq!(c.arrived.len(), 1);+ // the same item on the next polls: nothing new, no animation+ for s in 1..10 {+ let c = t.update(&w, now + Duration::from_secs(5 * s));+ assert!(!c.play && c.arrived.is_empty());+ assert_eq!(c.count, 1);+ }+ // a second one arrives: only it is new+ let w2 = waiting(vec![item(Kind::Question, "q", "Mira"), item(Kind::Approval, "a", "Juno")]);+ let c = t.update(&w2, now + Duration::from_secs(60));+ assert!(c.play);+ assert_eq!(c.arrived.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), vec!["q"]);+ }++ #[test]+ fn a_question_and_an_approval_with_the_same_id_are_two_items() {+ let mut t = Tracker::default();+ let now = Instant::now();+ t.update(&waiting(vec![item(Kind::Approval, "x", "J")]), now);+ let c = t.update(&waiting(vec![item(Kind::Question, "x", "J"), item(Kind::Approval, "x", "J")]), now);+ assert_eq!(c.arrived.len(), 1);+ assert_eq!(c.arrived[0].kind, Kind::Question);+ }++ #[test]+ fn the_icon_replays_every_15_minutes_while_something_waits_and_stops_at_zero() {+ let mut t = Tracker::default();+ let start = Instant::now();+ let w = waiting(vec![item(Kind::Approval, "a", "Juno")]);+ assert!(t.update(&w, start).play);+ assert!(!t.update(&w, start + Duration::from_secs(14 * 60 + 59)).play);+ let c = t.update(&w, start + REPLAY_EVERY);+ assert!(c.play && c.arrived.is_empty(), "a replay brings no pill");+ assert!(!t.update(&w, start + REPLAY_EVERY + Duration::from_secs(5)).play);+ // answered: nothing waits, no replays+ assert!(!t.update(&Waiting::default(), start + REPLAY_EVERY * 2).play);+ assert!(!t.update(&Waiting::default(), start + REPLAY_EVERY * 4).play);+ }++ #[test]+ fn the_seen_set_stays_bounded() {+ let mut t = Tracker::default();+ let now = Instant::now();+ for i in 0..(SEEN_CAP + 5) {+ t.update(&waiting(vec![item(Kind::Question, &i.to_string(), "J")]), now);+ }+ assert!(t.seen.len() <= SEEN_CAP);+ // what still waits stays seen+ let last = (SEEN_CAP + 4).to_string();+ assert!(t.update(&waiting(vec![item(Kind::Question, &last, "J")]), now).arrived.is_empty());+ }++ #[test]+ fn one_item_s_pill_names_its_bot_and_opens_its_chat() {+ let mut a = item(Kind::Approval, "a", "juno");+ a.channel_id = Some("ch/1".into());+ let p = pill(std::slice::from_ref(&a)).unwrap();+ assert_eq!(p.headline, "juno needs your OK");+ assert_eq!(p.detail, "title a");+ assert_eq!(p.initial, "J");+ assert_eq!(p.target, "/s/spc_default/c/ch%2F1");+ let q = item(Kind::Question, "q", "Mira");+ let p = pill(&[q]).unwrap();+ assert_eq!(p.headline, "Mira asked you something");+ assert_eq!(p.target, "/s/spc_default/b/k-q");+ assert!(pill(&[]).is_none());+ }++ #[test]+ fn several_arrivals_coalesce_into_one_pill_that_opens_the_inbox() {+ let items = vec![item(Kind::Approval, "a", "Juno"), item(Kind::Question, "q", "Mira"), item(Kind::Question, "r", "Juno")];+ let p = pill(&items).unwrap();+ assert_eq!(p.headline, "3 things need you");+ assert_eq!(p.detail, "Juno and Mira");+ assert_eq!(p.initial, "");+ assert_eq!(p.target, "/s/spc_default/inbox");+ let same = vec![item(Kind::Approval, "a", "Juno"), item(Kind::Approval, "b", "Juno")];+ assert_eq!(pill(&same).unwrap().detail, "All from Juno");+ let three: Vec<Item> = ["Juno", "Iris", "Lin"].iter().map(|n| item(Kind::Question, n, n)).collect();+ assert_eq!(pill(&three).unwrap().detail, "Juno, Iris and Lin");+ let many: Vec<Item> = ["A", "B", "C", "D", "E"].iter().map(|n| item(Kind::Question, n, n)).collect();+ assert_eq!(pill(&many).unwrap().detail, "A, B and 3 more");+ }++ #[test]+ fn targets_follow_the_item_s_link() {+ let mut i = item(Kind::Question, "q", "J");+ i.space_id = Some("my space".into());+ i.direct_kwant_id = Some("k9".into());+ assert_eq!(target_path(&i), "/s/my%20space/b/k9");+ i.thread_id = Some("t1".into());+ assert_eq!(target_path(&i), "/s/my%20space/inbox", "a thread opens the Inbox");+ i.channel_id = Some("c1".into());+ assert_eq!(target_path(&i), "/s/my%20space/c/c1");+ let mut none = item(Kind::Question, "q", "J");+ none.space_id = None;+ none.kwant_id = String::new();+ assert_eq!(target_path(&none), "/s/spc_default/inbox");+ // nothing a title can carry reaches the path+ assert_eq!(encode("../../x?y#z"), "..%2F..%2Fx%3Fy%23z");+ }++ #[test]+ fn a_fresh_pill_waits_until_the_icon_reads_the_same_three_times() {+ let every = Duration::from_millis(30);+ let cap = Duration::from_millis(250);+ // each read costs `cost` ms of wall clock and each sleep its length; (spot, reads, ms)+ let run = |reads: Vec<Option<(f64, f64)>>, cost: u64| {+ let mut it = reads.into_iter();+ let clock = std::cell::Cell::new(Duration::ZERO);+ let read = || {+ clock.set(clock.get() + Duration::from_millis(cost));+ it.next().flatten()+ };+ let (spot, n) = settle(read, every, 3, cap, || clock.get(), |d| clock.set(clock.get() + d));+ (spot, n, clock.get().as_millis())+ };+ let at = |x: f64| Some((x, 26.0));+ // already settled: three reads, 60 ms, never sooner+ assert_eq!(run(vec![at(785.0); 9], 0), (at(785.0), 3, 60));+ // the 0 -> 1 case: the stale rect, then the settled one three times+ assert_eq!(run(vec![at(795.5), at(784.0), at(784.2), at(784.1)], 0), (at(784.1), 4, 90));+ // step 3 on CI: two early reads agree, then macOS moves the item 2 pt; two equal reads+ // are not enough, so it doesn't settle at 30 or 60 ms but on the moved spot at 120 ms+ let late = vec![at(616.0), at(616.0), at(614.0), at(614.0), at(614.0), at(612.0)];+ assert_eq!(run(late, 0), (at(614.0), 5, 120));+ // never settles: gives up at the cap (240 ms, 9 reads) with the newest place+ let drifting: Vec<_> = (0..20).map(|i| at(700.0 + i as f64)).collect();+ assert_eq!(run(drifting.clone(), 0), (at(708.0), 9, 240));+ // slow reads (40 ms each: a read waits for the main thread) count against the cap too+ assert_eq!(run(drifting, 40), (at(703.0), 4, 250));+ // no screen to read: settles on None after three reads+ assert_eq!(run(vec![None; 3], 0), (None, 3, 60));+ assert!(same_spot((1.0, 2.0), (1.4, 1.6)) && !same_spot((1.0, 2.0), (1.5, 2.0)));+ }++ #[test]+ fn show_nudges_is_on_by_default_and_saved_in_the_data_dir() {+ let dir = std::env::temp_dir().join(format!("kwant-prefs-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ assert!(Prefs::load(&dir).show_nudges, "on when nothing is saved");+ Prefs { show_nudges: false }.save(&dir).unwrap();+ assert!(!Prefs::load(&dir).show_nudges);+ // other keys in the file survive a save+ std::fs::write(prefs_path(&dir), r#"{"show_nudges":false,"other":1}"#).unwrap();+ Prefs { show_nudges: true }.save(&dir).unwrap();+ let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(prefs_path(&dir)).unwrap()).unwrap();+ assert_eq!(v["other"], 1);+ assert!(Prefs::load(&dir).show_nudges);+ // a broken file is the defaults+ std::fs::write(prefs_path(&dir), "{oops").unwrap();+ assert!(Prefs::load(&dir).show_nudges);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn the_demo_brings_one_then_one_then_two_together() {+ assert_eq!(demo::step(Duration::from_secs(1)), 0);+ assert_eq!(demo::waiting(0).count, 0);+ let mut t = Tracker::default();+ let now = Instant::now();+ let arrived: Vec<usize> = (1..=4).map(|s| t.update(&demo::waiting(s), now).arrived.len()).collect();+ assert_eq!(arrived, vec![1, 1, 2, 1]);+ assert_eq!(pill(&t.update(&demo::waiting(4), now).arrived), None);+ assert_eq!(demo::step(Duration::from_secs(60)), 3);+ assert_eq!(demo::step(demo::RUNS_FOR), 4);+ assert_eq!(pill(&demo::waiting(3).items[..2]).unwrap().headline, "2 things need you");+ }+}diff --git a/apps/mac/src/nudge_linux.rs b/apps/mac/src/nudge_linux.rsnew file mode 100644index 00000000..9bd2e088--- /dev/null+++ b/apps/mac/src/nudge_linux.rs@@ -0,0 +1,245 @@+//! The Linux side of the "needs you" nudge. Linux panels show tray pictures as they are (no+//! template tinting) and can't say where the icon is, so there is no pill and no frame animation:+//! the icon swaps once to Mira's colour "needs you" mark, the window asks for attention, and a+//! system notification names who needs you. The rules are in `nudge.rs`.+//!+//! Notifications go straight to the freedesktop notification service over D-Bus with zbus,+//! which the app already links (tauri-plugin-single-instance uses it), so no new crate.++use crate::nudge::{self, Change};+use std::collections::HashMap;+use std::sync::{mpsc, Arc, Mutex};+use tauri::{image::Image, tray::TrayIcon, AppHandle, Manager, UserAttentionType};++const NORMAL_DARK: &[u8] = include_bytes!("../icons/linux/tray-normal-dark.png");+const NORMAL_LIGHT: &[u8] = include_bytes!("../icons/linux/tray-normal-light.png");+const NEEDS_YOU_DARK: &[u8] = include_bytes!("../icons/linux/tray-needs-you-dark.png");+const NEEDS_YOU_LIGHT: &[u8] = include_bytes!("../icons/linux/tray-needs-you-light.png");++/// The app icon, sent with each notification: an AppImage installs no themed "kwant" icon, so a+/// name alone shows no picture (dunst: "No icon found in path: 'kwant'").+const APP_ICON: &[u8] = include_bytes!("../icons/128x128.png");++const BUS_NAME: &str = "org.freedesktop.Notifications";+const BUS_PATH: &str = "/org/freedesktop/Notifications";++/// Whether the panel the icon sits on is dark. Mira's rule (spec §6): dark unless the desktop+/// says it is light, because GNOME's top bar is always dark and most default panels are too.+/// GNOME, Ubuntu, Pantheon and Cinnamon count as dark whatever the app theme; elsewhere a light+/// colour scheme (`prefer-light`, or a KDE scheme without "dark" in its name) means light.+pub fn panel_is_dark(desktop: &str, color_scheme: Option<&str>, kde_scheme: Option<&str>) -> bool {+ let desktop = desktop.to_ascii_lowercase();+ if ["gnome", "unity", "ubuntu", "pantheon", "cinnamon"].iter().any(|d| desktop.contains(d)) {+ return true;+ }+ if color_scheme.is_some_and(|s| s.contains("prefer-light")) {+ return false;+ }+ if desktop.contains("kde") {+ if let Some(k) = kde_scheme {+ return k.to_ascii_lowercase().contains("dark");+ }+ }+ true+}++fn detect_dark_panel() -> bool {+ let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();+ let scheme = std::process::Command::new("gsettings")+ .args(["get", "org.gnome.desktop.interface", "color-scheme"])+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).into_owned());+ let kde = dirs::config_dir()+ .and_then(|d| std::fs::read_to_string(d.join("kdeglobals")).ok())+ .and_then(|s| s.lines().find(|l| l.starts_with("ColorScheme=")).map(str::to_string));+ panel_is_dark(&desktop, scheme.as_deref(), kde.as_deref())+}++/// The picture for the tray: Mira's colour mark (design/linux/*-22@2x, 44 px), plain or with the+/// "!" badge.+pub fn tray_icon(needs_you: bool, dark_panel: bool) -> &'static [u8] {+ match (needs_you, dark_panel) {+ (false, true) => NORMAL_DARK,+ (false, false) => NORMAL_LIGHT,+ (true, true) => NEEDS_YOU_DARK,+ (true, false) => NEEDS_YOU_LIGHT,+ }+}++/// Notification bodies may be read as markup; titles are the person's own text.+pub fn escape_markup(s: &str) -> String {+ s.replace('&', "&").replace('<', "<").replace('>', ">")+}++/// The `image-data` hint (`(iiibiiay)`: width, height, rowstride, has alpha, bits per sample,+/// channels, RGBA bytes) for a PNG.+pub fn image_data(png: &[u8]) -> Option<(i32, i32, i32, bool, i32, i32, Vec<u8>)> {+ let img = Image::from_bytes(png).ok()?;+ let (w, h) = (i32::try_from(img.width()).ok()?, i32::try_from(img.height()).ok()?);+ let rgba = img.rgba().to_vec();+ (rgba.len() == (w as usize) * (h as usize) * 4).then_some((w, h, w * 4, true, 8, 4, rgba))+}++pub struct Nudger {+ tray: TrayIcon,+ dark_panel: bool,+ showing_needs_you: bool,+ notify: mpsc::Sender<nudge::Pill>,+}++impl Nudger {+ pub fn start(handle: &AppHandle, tray: TrayIcon) -> Nudger {+ let dark_panel = detect_dark_panel();+ let _ = tray.set_icon(Image::from_bytes(tray_icon(false, dark_panel)).ok());+ let (tx, rx) = mpsc::channel();+ let h = handle.clone();+ std::thread::Builder::new()+ .name("kwant-notify".into())+ .spawn(move || notify_loop(h, rx))+ .expect("notification thread");+ Nudger { tray, dark_panel, showing_needs_you: false, notify: tx }+ }++ /// The "needs you" icon follows the count (state, so it stays with "Show nudges" off); the+ /// attention request and the notification only while nudges are on and kwant isn't focused.+ pub fn on_poll(&mut self, handle: &AppHandle, change: &Change, show: bool) {+ let needs_you = change.count > 0;+ if needs_you != self.showing_needs_you {+ // appindicator writes the picture to a file each time, so only on a real change+ if self.tray.set_icon(Image::from_bytes(tray_icon(needs_you, self.dark_panel)).ok()).is_ok() {+ self.showing_needs_you = needs_you;+ }+ }+ if !show || change.arrived.is_empty() || crate::main_focused(handle) {+ return;+ }+ if let Some(main) = handle.get_webview_window(crate::MAIN) {+ let _ = main.request_user_attention(Some(UserAttentionType::Informational));+ }+ // One notification per poll: several at once say how many and open the Inbox+ if let Some(p) = nudge::pill(&change.arrived) {+ let _ = self.notify.send(p);+ }+ }+}++type Targets = Arc<Mutex<HashMap<u32, String>>>;++fn notify_loop(handle: AppHandle, rx: mpsc::Receiver<nudge::Pill>) {+ let conn = match zbus::blocking::Connection::session() {+ Ok(c) => c,+ Err(e) => {+ tracing::info!(error = %e, "no session bus; nudges won't show notifications");+ while rx.recv().is_ok() {}+ return;+ }+ };+ let proxy = match zbus::blocking::Proxy::new(&conn, BUS_NAME, BUS_PATH, BUS_NAME) {+ Ok(p) => p,+ Err(e) => {+ tracing::info!(error = %e, "no notification service");+ while rx.recv().is_ok() {}+ return;+ }+ };+ let caps: Vec<String> = proxy.call("GetCapabilities", &()).unwrap_or_default();+ let actions = caps.iter().any(|c| c == "actions");+ let body_markup = caps.iter().any(|c| c == "body-markup");+ let icon = image_data(APP_ICON);+ let targets: Targets = Arc::default();+ if actions {+ listen_for_clicks(handle.clone(), proxy.clone(), targets.clone());+ }+ while let Ok(p) = rx.recv() {+ let body = if body_markup { escape_markup(&p.detail) } else { p.detail.clone() };+ // "default" is a click on the notification itself; no Allow/Deny buttons, ever+ let acts: Vec<&str> = if actions { vec!["default", "Open"] } else { vec![] };+ let mut hints: HashMap<&str, zbus::zvariant::Value> = HashMap::new();+ hints.insert("desktop-entry", zbus::zvariant::Value::from("kwant"));+ hints.insert("urgency", zbus::zvariant::Value::from(1u8));+ if let Some(i) = &icon {+ hints.insert("image-data", zbus::zvariant::Value::from(zbus::zvariant::Structure::from(i.clone())));+ }+ // no app_icon name: the picture travels in image-data+ let sent = proxy.call::<_, _, u32>(+ "Notify",+ &("kwant", 0u32, "", p.headline.as_str(), body.as_str(), acts, hints, -1i32),+ );+ match sent {+ Ok(id) => {+ if crate::DEMO.get().is_some() {+ println!("demo-nudge: notification {id} \"{}\"", p.headline);+ }+ if actions {+ let mut t = targets.lock().unwrap();+ if t.len() > 100 {+ t.clear();+ }+ t.insert(id, p.target);+ }+ }+ Err(e) => tracing::info!(error = %e, "the notification wasn't shown"),+ }+ }+}++/// A click on one of our notifications opens its item in the kwant window.+fn listen_for_clicks(handle: AppHandle, proxy: zbus::blocking::Proxy<'static>, targets: Targets) {+ std::thread::Builder::new()+ .name("kwant-notify-clicks".into())+ .spawn(move || {+ let Ok(signals) = proxy.receive_signal("ActionInvoked") else { return };+ for msg in signals {+ let Ok((id, _action)) = msg.body().deserialize::<(u32, String)>() else { continue };+ let Some(target) = targets.lock().unwrap().remove(&id) else { continue };+ let h = handle.clone();+ let _ = handle.run_on_main_thread(move || crate::open_window_at(&h, Some(&target)));+ }+ })+ .expect("notification click thread");+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dark_panels_get_the_light_mark() {+ assert!(panel_is_dark("ubuntu:GNOME", None, None));+ assert!(panel_is_dark("ubuntu:GNOME", Some("'prefer-light'"), None));+ assert!(panel_is_dark("X-Cinnamon", None, None));+ assert!(!panel_is_dark("KDE", None, Some("ColorScheme=BreezeLight")));+ assert!(panel_is_dark("KDE", None, Some("ColorScheme=BreezeDark")));+ assert!(panel_is_dark("KDE", None, None));+ assert!(!panel_is_dark("XFCE", Some("'prefer-light'\n"), None));+ assert!(panel_is_dark("XFCE", Some("'default'"), None));+ // can't tell: dark, as Mira's spec says+ assert!(panel_is_dark("", None, None));+ }++ #[test]+ fn every_tray_picture_decodes() {+ for (n, d) in [(false, false), (false, true), (true, false), (true, true)] {+ let img = Image::from_bytes(tray_icon(n, d)).expect("decodes");+ assert_eq!((img.width(), img.height()), (44, 44));+ }+ }++ #[test]+ fn notifications_carry_the_app_icon_as_image_data() {+ let (w, h, stride, alpha, bits, channels, data) = image_data(APP_ICON).expect("the icon decodes");+ assert_eq!((w, h, stride, alpha, bits, channels), (128, 128, 512, true, 8, 4));+ assert_eq!(data.len(), 128 * 128 * 4);+ assert!(data.chunks(4).any(|px| px[3] > 0), "not a blank picture");+ let v = zbus::zvariant::Value::from(zbus::zvariant::Structure::from((w, h, stride, alpha, bits, channels, data)));+ assert_eq!(v.value_signature().to_string(), "(iiibiiay)");+ assert!(image_data(b"not a png").is_none());+ }++ #[test]+ fn titles_cannot_inject_markup() {+ assert_eq!(escape_markup("<b>x</b> & y"), "<b>x</b> & y");+ }+}diff --git a/apps/mac/src/nudge_mac.rs b/apps/mac/src/nudge_mac.rsnew file mode 100644index 00000000..260cbdcf--- /dev/null+++ b/apps/mac/src/nudge_mac.rs@@ -0,0 +1,396 @@+//! The macOS side of the "needs you" nudge: the menu-bar icon's template-frame animation, the+//! non-activating pill under the icon and the Dock badge. The rules (what is new, when to replay,+//! what the pill says) are in `nudge.rs`; Mira's spec is+//! /home/maus/shared/ship-software-safely/mac-nudge/design/spec.md (§1 and §3).++use crate::nudge::{self, Change, Item};+use std::collections::HashSet;+use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};+use std::time::{Duration, Instant};+use tauri::{image::Image, tray::TrayIcon, AppHandle, LogicalPosition, Manager, WebviewUrl, WebviewWindowBuilder};++/// Mira's frames (design/tray/18pt @2x: 36×36 black + alpha; tray-icon draws the icon 18 pt tall,+/// so each cell lands on 2 device pixels). Frame 11 is the "needs you" rest pose.+const FRAMES: [&[u8]; 12] = [+ include_bytes!("../icons/nudge/frame-00.png"),+ include_bytes!("../icons/nudge/frame-01.png"),+ include_bytes!("../icons/nudge/frame-02.png"),+ include_bytes!("../icons/nudge/frame-03.png"),+ include_bytes!("../icons/nudge/frame-04.png"),+ include_bytes!("../icons/nudge/frame-05.png"),+ include_bytes!("../icons/nudge/frame-06.png"),+ include_bytes!("../icons/nudge/frame-07.png"),+ include_bytes!("../icons/nudge/frame-08.png"),+ include_bytes!("../icons/nudge/frame-09.png"),+ include_bytes!("../icons/nudge/frame-10.png"),+ include_bytes!("../icons/nudge/frame-11.png"),+];+const NEEDS_YOU: &[u8] = include_bytes!("../icons/nudge/needs-you.png");+/// Today's mark drawn on the same 18 pt grid, so the icon doesn't change size between states.+const IDLE: &[u8] = include_bytes!("../icons/nudge/idle.png");+/// 12 frames × 100 ms = 1.2 s, 10 fps.+const FRAME: Duration = Duration::from_millis(100);++const PILL: &str = "nudge";+/// The pill window: the 320 × 52 pill at (10, 4) plus room for its shadow, in points.+const PILL_W: f64 = 340.0;+const PILL_H: f64 = 76.0;+/// The page says when its pill has gone; if it never does (a hide asked for by the app), the+/// window hides after this anyway.+const HIDE_FALLBACK: Duration = Duration::from_millis(600);++/// Whether the person asked macOS to reduce motion (System Settings › Accessibility › Display).+/// Read each time, so a change applies to the next nudge. The pill page follows the same setting+/// through `prefers-reduced-motion`.+pub fn reduce_motion() -> bool {+ if crate::demo_reduce_motion() {+ return true;+ }+ objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()+}++enum Icon {+ /// Play the frames once, then rest on "needs you".+ Play,+ /// Rest on "needs you" (true) or the plain icon (false).+ Rest(bool),+}++enum PillCmd {+ /// A poll while a pill may show: what just arrived, and what still waits.+ Update { arrived: Vec<Item>, live: HashSet<String> },+ /// The kwant window has focus, nudges are off or nothing waits: no pill.+ Quiet,+ /// The page: the pill was clicked.+ Open,+ /// The page: the pill has gone (its time ran out).+ Hidden,+}++pub struct Nudger {+ icon: Sender<Icon>,+ pill: Sender<PillCmd>,+ badge: Option<usize>,+}++impl Nudger {+ pub fn start(handle: &AppHandle, tray: TrayIcon) -> Nudger {+ let (icon_tx, icon_rx) = mpsc::channel();+ let (pill_tx, pill_rx) = mpsc::channel();+ let anim_tray = tray.clone();+ std::thread::Builder::new()+ .name("kwant-nudge-icon".into())+ .spawn(move || animate(anim_tray, icon_rx))+ .expect("nudge icon thread");+ let h = handle.clone();+ let opener = pill_tx.clone();+ std::thread::Builder::new()+ .name("kwant-nudge-pill".into())+ .spawn(move || pill_loop(h, tray, pill_rx, opener))+ .expect("nudge pill thread");+ Nudger { icon: icon_tx, pill: pill_tx, badge: None }+ }++ /// One poll's change. The Dock badge and the resting "needs you" icon follow the count (that+ /// is state, not motion); the animation and the pill only while "Show nudges" is on, and the+ /// pill only while the kwant window isn't focused.+ pub fn on_poll(&mut self, handle: &AppHandle, change: &Change, show: bool) {+ let badge = (change.count > 0).then_some(change.count);+ if badge != self.badge {+ if let Some(main) = handle.get_webview_window(crate::MAIN) {+ if main.set_badge_count(badge.map(|n| n as i64)).is_ok() {+ self.badge = badge;+ }+ }+ }+ let _ = self.icon.send(if show && change.play { Icon::Play } else { Icon::Rest(change.count > 0) });+ let cmd = if !show || change.count == 0 || crate::main_focused(handle) {+ PillCmd::Quiet+ } else {+ PillCmd::Update { arrived: change.arrived.clone(), live: change.live.clone() }+ };+ let _ = self.pill.send(cmd);+ }+}++fn decode(png: &[u8]) -> Option<Image<'static>> {+ Image::from_bytes(png).ok()+}++/// Owns the menu-bar icon picture. Every frame is set as a template: on macOS `set_icon` alone+/// turns the template flag off, and the icon would stop following the menu bar's colour.+fn animate(tray: TrayIcon, rx: Receiver<Icon>) {+ let frames: Vec<Image<'static>> = FRAMES.iter().filter_map(|f| decode(f)).collect();+ let (Some(still), Some(idle)) = (decode(NEEDS_YOU), decode(IDLE)) else {+ tracing::error!("the nudge icons don't decode");+ return;+ };+ let set = |img: &Image<'static>| {+ let _ = tray.set_icon_with_as_template(Some(img.clone()), true);+ };+ set(&idle);+ let mut resting_on_still = false;+ while let Ok(cmd) = rx.recv() {+ match cmd {+ Icon::Play if reduce_motion() => {+ set(&still);+ resting_on_still = true;+ }+ Icon::Play => {+ let mut stop = false;+ for f in &frames {+ set(f);+ std::thread::sleep(FRAME);+ // answered mid-animation: drop the rest of it+ while let Ok(next) = rx.try_recv() {+ if let Icon::Rest(false) = next {+ stop = true;+ }+ }+ if stop {+ break;+ }+ }+ set(if stop { &idle } else { &still });+ resting_on_still = !stop;+ }+ Icon::Rest(waiting) if waiting != resting_on_still => {+ set(if waiting { &still } else { &idle });+ resting_on_still = waiting;+ }+ Icon::Rest(_) => {}+ }+ }+}++/// What the pill page's `kwantNudge.show` takes: every item on the pill, oldest first. The page+/// writes the text in escaped.+fn payload(items: &[Item]) -> String {+ let list: Vec<serde_json::Value> = items+ .iter()+ .map(|i| serde_json::json!({ "kind": i.kind.as_str(), "name": i.kwant_name, "title": i.title }))+ .collect();+ serde_json::Value::Array(list).to_string()+}++fn build_pill(handle: &AppHandle, opener: Sender<PillCmd>) -> Option<tauri::WebviewWindow> {+ if let Some(w) = handle.get_webview_window(PILL) {+ return Some(w);+ }+ let built = WebviewWindowBuilder::new(handle, PILL, WebviewUrl::App("nudge.html".into()))+ .title("kwant needs you")+ .inner_size(PILL_W, PILL_H)+ .resizable(false)+ .decorations(false)+ .transparent(true)+ .shadow(false)+ .always_on_top(true)+ .visible_on_all_workspaces(true)+ .skip_taskbar(true)+ // Never key or main: showing the pill doesn't take focus from the app being typed in+ .focusable(false)+ .focused(false)+ .accept_first_mouse(true)+ .visible(false)+ .on_navigation(move |url| {+ if url.scheme() == "kwant-nudge" {+ // kwant-nudge://open (clicked) or kwant-nudge://hidden (gone); never loaded+ let _ = opener.send(if url.host_str() == Some("open") { PillCmd::Open } else { PillCmd::Hidden });+ return false;+ }+ // only the bundled pill page itself+ url.scheme() == "tauri" || url.host_str() == Some("tauri.localhost")+ })+ .build();+ match built {+ Ok(w) => Some(w),+ Err(e) => {+ tracing::error!(error = %e, "couldn't make the nudge pill");+ None+ }+ }+}++/// How often the pill checks that it is still under the icon while it shows (a backup for+/// shifts after it showed; a fresh pill first waits for the icon to settle).+const FOLLOW_EVERY: Duration = Duration::from_millis(100);+/// A fresh pill re-reads the icon this often until `SETTLE_READS` reads in a row agree (so 60 ms+/// at least), for at most `SETTLE_CAP` of wall clock. A read waits for the main thread and can+/// take tens of ms; the cap counts that, and leaves room for a stale read and three slow ones.+const SETTLE_EVERY: Duration = Duration::from_millis(30);+const SETTLE_READS: usize = 3;+const SETTLE_CAP: Duration = Duration::from_millis(250);++/// Where the pill window goes for the menu-bar icon as it is now: centred on it, 2 pt below it,+/// kept 8 pt inside the screen (at the top right when macOS won't say where the icon is). Also+/// the icon's rect it went by, in points.+fn spot(handle: &AppHandle, tray: &TrayIcon) -> Option<((f64, f64), Option<[f64; 4]>)> {+ let monitor = handle.primary_monitor().ok().flatten()?;+ let scale = monitor.scale_factor();+ let screen = monitor.size().to_logical::<f64>(scale);+ let origin = monitor.position().to_logical::<f64>(scale);+ let rect = tray.rect().ok().flatten().map(|r| {+ let pos = r.position.to_logical::<f64>(scale);+ let size = r.size.to_logical::<f64>(scale);+ [pos.x, pos.y, size.width, size.height]+ });+ let (cx, bottom) = match rect {+ Some([x, y, w, h]) => (x + w / 2.0, y + h),+ None => (origin.x + screen.width - 8.0 - PILL_W / 2.0, origin.y + 24.0),+ };+ let x = (cx - PILL_W / 2.0).clamp(origin.x + 8.0, origin.x + screen.width - 8.0 - PILL_W);+ Some(((x, bottom + 2.0), rect))+}++/// Moves the pill window under the icon. `None` when it is already there (or the screen can't+/// be read). With --demo-nudge it logs the icon rect it went by, for CI.+fn place(+ handle: &AppHandle,+ tray: &TrayIcon,+ pill: &tauri::WebviewWindow,+ now_at: Option<(f64, f64)>,+) -> Option<(f64, f64)> {+ let ((x, y), rect) = spot(handle, tray)?;+ if now_at.is_some_and(|p| nudge::same_spot(p, (x, y))) {+ return None;+ }+ if crate::DEMO.get().is_some() {+ if let Some([rx, ry, rw, rh]) = rect {+ println!("demo-nudge: tray {rx:.0},{ry:.0},{rw:.0},{rh:.0}");+ }+ }+ let _ = pill.set_position(LogicalPosition::new(x, y));+ Some((x, y))+}++/// Drives the pill page: shows and coalesces arrivals, drops what was answered meanwhile, hides it+/// when the person turns to kwant, and opens the item on a click. The page owns the timing (5 s,+/// held while the pointer is on it, 12 s at most) and says when the pill has gone.+///+/// A fresh pill shows only once the icon has settled. Its first item comes with the icon's count+/// changing from none to "1", and AppKit lays the status item out again for the wider title a+/// moment after the title is set; read at once, the rect is ~11 pt off and the pill would jump+/// mid-entrance; the bar can also settle in two steps (width first, then x). So the pill waits+/// until three reads 30 ms apart agree (250 ms of wall clock at most), and+/// while it shows it still follows the icon every 100 ms in case it moves later.+fn pill_loop(handle: AppHandle, tray: TrayIcon, rx: Receiver<PillCmd>, opener: Sender<PillCmd>) {+ // Made ahead, hidden, so the first nudge doesn't wait for a page load+ let mut window = build_pill(&handle, opener.clone());+ // What the pill shows now, oldest first; empty when no pill is up+ let mut shown: Vec<Item> = Vec::new();+ let mut last_show: Option<Instant> = None;+ let mut hide_by: Option<Instant> = None;+ // Where the pill window is while a pill shows, and when that was last checked+ let mut placed: Option<(f64, f64)> = None;+ let mut checked = Instant::now();+ let demo = crate::DEMO.get().is_some();+ let hide_window = |w: &Option<tauri::WebviewWindow>| {+ if let Some(w) = w {+ let _ = w.hide();+ }+ };+ loop {+ match rx.recv_timeout(Duration::from_millis(100)) {+ Ok(PillCmd::Update { arrived, live }) => {+ let before = shown.len();+ shown.retain(|i| live.contains(&i.key()));+ if arrived.is_empty() && shown.len() == before {+ continue;+ }+ if shown.is_empty() && arrived.is_empty() {+ // everything on it was answered elsewhere+ if let Some(w) = &window {+ let _ = w.eval("window.kwantNudge && kwantNudge.hide()");+ }+ hide_by = Some(Instant::now() + HIDE_FALLBACK);+ continue;+ }+ let fresh = shown.is_empty();+ // the server lists newest first; the pill wants oldest first+ shown.extend(arrived.into_iter().rev());+ if window.is_none() {+ window = build_pill(&handle, opener.clone());+ }+ let Some(w) = &window else { continue };+ let reduce = crate::demo_reduce_motion();+ let script = format!(+ "document.documentElement.classList.toggle('kw-reduce', {reduce}); window.kwantNudge && kwantNudge.show({})",+ payload(&shown)+ );+ if fresh {+ let started = Instant::now();+ let read = || spot(&handle, &tray).map(|(p, _)| p);+ let (_, reads) =+ nudge::settle(read, SETTLE_EVERY, SETTLE_READS, SETTLE_CAP, || started.elapsed(), std::thread::sleep);+ if demo {+ println!("demo-nudge: pill settled after {} ms ({reads} reads)", started.elapsed().as_millis());+ }+ }+ let moved = if fresh { place(&handle, &tray, w, None) } else { None };+ if moved.is_some() {+ placed = moved;+ checked = Instant::now();+ }+ let _ = w.eval(&script);+ let _ = w.show();+ last_show = Some(Instant::now());+ hide_by = None;+ if demo {+ match moved {+ Some((x, y)) => println!("demo-nudge: pill {x:.0},{y:.0},{PILL_W:.0},{PILL_H:.0} items={}", shown.len()),+ None => println!("demo-nudge: pill coalesced items={}", shown.len()),+ }+ }+ }+ Ok(PillCmd::Quiet) => {+ if !shown.is_empty() {+ if let Some(w) = &window {+ let _ = w.eval("window.kwantNudge && kwantNudge.hide()");+ }+ shown.clear();+ hide_by = Some(Instant::now() + HIDE_FALLBACK);+ }+ }+ Ok(PillCmd::Open) => {+ if let Some(p) = nudge::pill(&shown) {+ let h = handle.clone();+ let _ = handle.run_on_main_thread(move || crate::open_window_at(&h, Some(&p.target)));+ }+ hide_window(&window);+ shown.clear();+ hide_by = None;+ }+ Ok(PillCmd::Hidden) => {+ // a pill shown a moment ago is a new one; this is the old one's goodbye+ if last_show.is_some_and(|t| t.elapsed() < Duration::from_millis(300)) {+ continue;+ }+ hide_window(&window);+ shown.clear();+ hide_by = None;+ if demo {+ println!("demo-nudge: pill hidden");+ }+ }+ Err(RecvTimeoutError::Timeout) => {}+ Err(RecvTimeoutError::Disconnected) => return,+ }+ if hide_by.is_some_and(|t| Instant::now() >= t) {+ hide_window(&window);+ hide_by = None;+ }+ if shown.is_empty() {+ placed = None;+ } else if placed.is_some() && checked.elapsed() >= FOLLOW_EVERY {+ checked = Instant::now();+ if let Some(w) = &window {+ if let Some((x, y)) = place(&handle, &tray, w, placed) {+ placed = Some((x, y));+ if demo {+ println!("demo-nudge: pill {x:.0},{y:.0},{PILL_W:.0},{PILL_H:.0} items={} moved", shown.len());+ }+ }+ }+ }+ }+}diff --git a/apps/mac/tauri.conf.json b/apps/mac/tauri.conf.jsonindex 1be00175..ea7694a7 100644--- a/apps/mac/tauri.conf.json+++ b/apps/mac/tauri.conf.json@@ -8,6 +8,7 @@},"app": {"withGlobalTauri": false,+ "macOSPrivateApi": true,"windows": [],"security": {"csp": nulldiff --git a/frontend/tests/macNudgePage.test.mjs b/frontend/tests/macNudgePage.test.mjsnew file mode 100644index 00000000..6fdde64f--- /dev/null+++ b/frontend/tests/macNudgePage.test.mjs@@ -0,0 +1,79 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import test from 'node:test';+import vm from 'node:vm';++// The Mac app's "needs you" pill page (apps/mac/loading/nudge.html), run against a tiny DOM.+const html = await readFile(new URL('../../apps/mac/loading/nudge.html', import.meta.url), 'utf8');+const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];++const fakeElement = () => {+ const attrs = new Map();+ const classes = new Set();+ return {+ attrs,+ className: '',+ dataset: {},+ innerHTML: '',+ offsetWidth: 0,+ classList: { add: (c) => classes.add(c), remove: (c) => classes.delete(c), contains: (c) => classes.has(c) },+ setAttribute: (k, v) => attrs.set(k, String(v)),+ getAttribute: (k) => attrs.get(k) ?? null,+ addEventListener() {},+ appendChild() {},+ remove() {},+ };+};++const loadPage = () => {+ const made = [];+ const slot = fakeElement();+ const document = {+ documentElement: fakeElement(),+ getElementById: () => slot,+ createElement: () => {+ const el = fakeElement();+ made.push(el);+ return el;+ },+ };+ const window = {};+ const context = {+ window,+ document,+ location: { hash: '', href: '' },+ matchMedia: () => ({ matches: false }),+ setTimeout: () => 0,+ clearTimeout() {},+ };+ vm.createContext(context);+ vm.runInContext(script, context);+ return { nudge: window.kwantNudge, pill: () => made[made.length - 1] };+};++test('the aria-label reads a bot name with & < > " as it is', () => {+ const { nudge, pill } = loadPage();+ nudge.show([{ kind: 'approval', name: 'R&D', title: 'Use "Bash" for <b>x</b> & y' }]);+ assert.equal(pill().getAttribute('aria-label'), 'R&D needs your OK. Use "Bash" for <b>x</b> & y');+});++test('the same text is escaped where it goes into the pill’s HTML', () => {+ const { nudge, pill } = loadPage();+ nudge.show([{ kind: 'question', name: '<img src=x onerror=alert(1)>', title: 'a & "b"' }]);+ const inner = pill().innerHTML;+ assert.ok(!inner.includes('<img'), inner);+ assert.match(inner, /<img src=x onerror=alert\(1\)> asked you something/);+ assert.match(inner, /a & "b"/);+ // the avatar letter is escaped too+ assert.match(inner, /kw-nudge__av"><</);+});++test('a coalesced pill’s label lists the real names', () => {+ const { nudge, pill } = loadPage();+ nudge.show([+ { kind: 'approval', name: 'R&D', title: 'one' },+ { kind: 'question', name: 'Q<A>', title: 'two' },+ ]);+ assert.equal(pill().getAttribute('aria-label'), '2 things need you. R&D and Q<A>');+ assert.match(pill().innerHTML, /R&D and Q<A>/);+});