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
Perch: desktop island client in the Mac/Windows/Linux app (0.9.14) (#652)
Oleksandr Ivanchenko5adf16a32867
diff --git a/apps/mac/Cargo.lock b/apps/mac/Cargo.lockindex e7fc8d36..6bfccfc8 100644--- a/apps/mac/Cargo.lock+++ b/apps/mac/Cargo.lock@@ -1837,6 +1837,16 @@ dependencies = ["version_check",]+[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix",+ "windows-link",+]+[[package]]name = "getrandom"version = "0.2.17"@@ -1959,6 +1969,24 @@ version = "0.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"+[[package]]+name = "global-hotkey"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"+dependencies = [+ "crossbeam-channel",+ "keyboard-types 0.7.0",+ "objc2",+ "objc2-app-kit",+ "once_cell",+ "serde",+ "thiserror 2.0.21",+ "windows-sys 0.59.0",+ "x11rb",+ "xkeysym",+]+[[package]]name = "gobject-sys"version = "0.18.0"@@ -2695,6 +2723,17 @@ dependencies = ["serde_json",]+[[package]]+name = "keyboard-types"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"+dependencies = [+ "bitflags 2.13.2",+ "serde",+ "unicode-segmentation",+]+[[package]]name = "keyboard-types"version = "0.8.3"@@ -2711,12 +2750,14 @@ version = "0.9.14"dependencies = ["dirs 5.0.1","kwnt",+ "objc2","objc2-app-kit","reqwest 0.12.28","serde_json","tauri","tauri-build","tauri-plugin-dialog",+ "tauri-plugin-global-shortcut","tauri-plugin-single-instance","tauri-plugin-updater","tokio",@@ -3053,7 +3094,7 @@ dependencies = ["crossbeam-channel","dpi","gtk",- "keyboard-types",+ "keyboard-types 0.8.3","objc2","objc2-app-kit","objc2-core-foundation",@@ -5505,6 +5546,21 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-global-shortcut"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93ff17919fe09852d269bd37b1d3d2e993b9dbb514afe7acbf3346c1d3627e2d"+dependencies = [+ "global-hotkey",+ "log",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.21",+]+[[package]]name = "tauri-plugin-single-instance"version = "2.5.5"@@ -6835,6 +6891,15 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets 0.52.6",+]+[[package]]name = "windows-sys"version = "0.61.2"@@ -7154,6 +7219,23 @@ dependencies = ["pkg-config",]+[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "gethostname",+ "rustix",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"+[[package]]name = "xattr"version = "1.6.1"@@ -7164,6 +7246,12 @@ dependencies = ["rustix",]+[[package]]+name = "xkeysym"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"+[[package]]name = "yoke"version = "0.8.3"diff --git a/apps/mac/Cargo.toml b/apps/mac/Cargo.tomlindex 101550cc..df5865ca 100644--- a/apps/mac/Cargo.toml+++ b/apps/mac/Cargo.toml@@ -27,6 +27,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }# The native check and poll of a kwant server (already in the tree via kwnt)reqwest = "0.12"tauri-plugin-dialog = "2"+tauri-plugin-global-shortcut = "2"# A second launch focuses the running app (macOS does this itself)[target.'cfg(not(target_os = "macos"))'.dependencies]@@ -34,7 +35,8 @@ 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"] }+objc2 = "0.6"+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSAccessibility", "NSWorkspace", "NSResponder", "NSWindow", "NSScreen", "NSGraphics"] }# Desktop notifications for the nudge over D-Bus (already in the tree via the single-instance plugin)[target.'cfg(target_os = "linux")'.dependencies]diff --git a/apps/mac/loading/creatures.js b/apps/mac/loading/creatures.jsnew file mode 100644index 00000000..71b2376a--- /dev/null+++ b/apps/mac/loading/creatures.js@@ -0,0 +1,303 @@+// Port of frontend/src/components/ModernAvatar.tsx (main c5978888): same palettes, accessories and pixels.+// Shipped from Mira's mockups (autonomy/desktop-island/mockups/src/creatures.js); regenerate when the app's avatars change.+(function(){+const FRAME = '#4a3f8a';+const PANEL = '#15112e';+const SCAN = '#0d0a1f';+const INK = '#1b1033';+const BLUSH = '#ff6b81';++const PALETTES = {+ yellow: { body: '#fdc934', shade: '#d98a1f', light: '#fff0a0', accent: '#5ce1ff' },+ green: { body: '#3ccf6e', shade: '#1f8f4c', light: '#a8f5bf', accent: '#c6ff6b' },+ pink: { body: '#ff7eb6', shade: '#c9487f', light: '#ffd0e4', accent: '#ffe066' },+ cyan: { body: '#5ce1ff', shade: '#2a92c9', light: '#d2f7ff', accent: '#ff6b81' },+ violet: { body: '#a98bff', shade: '#6d4fd6', light: '#e1d6ff', accent: '#ffd23f' },+ orange: { body: '#ff9f43', shade: '#c4621c', light: '#ffd9a8', accent: '#5ce1ff' },+ blue: { body: '#6d9bff', shade: '#3c5fcf', light: '#cddcff', accent: '#ff7eb6' },+ coral: { body: '#ff8a7a', shade: '#cf5446', light: '#ffd6cf', accent: '#6d4fd6' },+ teal: { body: '#2fd4b5', shade: '#17917c', light: '#b5f5e8', accent: '#ffd23f' },+ red: { body: '#ff6b6b', shade: '#c43c4c', light: '#ffc9c9', accent: '#5ce1ff' },+ gold: { body: '#f7c948', shade: '#c28a14', light: '#fff1b8', accent: '#e5484d' },+ lilac: { body: '#d49cff', shade: '#9a5fd1', light: '#f1ddff', accent: '#f5f2ff' },+ mint: { body: '#9be564', shade: '#5e9e33', light: '#e2ffc7', accent: '#ffe066' },+ sky: { body: '#7cc8ff', shade: '#3f8fd1', light: '#d6efff', accent: '#4b44a6' },+ magenta: { body: '#f06bd8', shade: '#b13a9c', light: '#ffd3f5', accent: '#ffd23f' },+ slate: { body: '#a3aecf', shade: '#66719a', light: '#e3e8f7', accent: '#e5484d' },+ amber: { body: '#ffb347', shade: '#c9771a', light: '#ffe2b8', accent: '#3c5fcf' },+ ocean: { body: '#3fb6c9', shade: '#227b95', light: '#c4f1f7', accent: '#e5484d' },+ berry: { body: '#e0607e', shade: '#a8324f', light: '#ffc2d0', accent: '#ffffff' },+ lime: { body: '#c6f04a', shade: '#86b31f', light: '#f0ffc2', accent: '#ff4d6d' },+ peach: { body: '#ffb894', shade: '#d47a55', light: '#ffe5d6', accent: '#5ce1ff' },+ steel: { body: '#7fa3b8', shade: '#4d7086', light: '#cfe2ec', accent: '#ffc21a' },+ blossom: { body: '#f7b3d2', shade: '#c97aa0', light: '#ffe3f0', accent: '#ffffff' },+};++/** Avatar styles an agent can pick; `avatar_sprite` stores the id. */+const AVATAR_STYLES = [+ { id: 'architect', label: 'Architecture' },+ { id: 'tech_lead', label: 'Tech Lead' },+ { id: 'devops', label: 'DevOps' },+ { id: 'security', label: 'Security' },+ { id: 'fast', label: 'Speed' },+ { id: 'designer', label: 'Design' },+ { id: 'data', label: 'Data' },+ { id: 'qa', label: 'QA' },+ { id: 'product', label: 'Product' },+ { id: 'writer', label: 'Writing' },+ { id: 'research', label: 'Research' },+ { id: 'teacher', label: 'Teacher' },+ { id: 'marketing', label: 'Marketing' },+ { id: 'legal', label: 'Legal' },+ { id: 'coach', label: 'Coach' },+ { id: 'traveler', label: 'Travel' },+ { id: 'chef', label: 'Chef' },+ { id: 'fitness', label: 'Fitness' },+ { id: 'party', label: 'Party' },+ { id: 'builder', label: 'Builder' },+ { id: 'zen', label: 'Wellbeing' },+ { id: 'default', label: 'Droid' },+];++const ROLE_CREATURES = {+ brand: ['yellow', 'antenna'],+ laya: ['violet', 'crown'],+ user: ['blue', 'ears'],+ architect: ['violet', 'horns'],+ tech_lead: ['cyan', 'visor'],+ devops: ['green', 'spikes'],+ security: ['orange', 'ears'],+ fast: ['pink', 'sprout'],+ designer: ['coral', 'beret'],+ data: ['teal', 'glasses'],+ qa: ['red', 'goggles'],+ product: ['gold', 'tie'],+ writer: ['lilac', 'quill'],+ research: ['mint', 'bulb'],+ teacher: ['sky', 'mortarboard'],+ marketing: ['magenta', 'star'],+ legal: ['slate', 'bowtie'],+ coach: ['amber', 'cap'],+ traveler: ['ocean', 'sunhat'],+ chef: ['berry', 'toque'],+ fitness: ['lime', 'headband'],+ party: ['peach', 'partyhat'],+ builder: ['steel', 'hardhat'],+ zen: ['blossom', 'flower'],+};++/** Style ids (picked or saved), as opposed to a title or name passed as a hint. */+const isStyleId = (role) => role === 'default' || Object.prototype.hasOwnProperty.call(ROLE_CREATURES, role);++const hash = (s) => {+ let h = 0;+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;+ return Math.abs(h);+};++function pickCreature(role, name) {+ // An explicitly chosen style wins over hints in the name+ const chosen = ROLE_CREATURES[role];+ if (chosen) return { ...PALETTES[chosen[0]], accessory: chosen[1] };+ const norm = `${role} ${name}`.toLowerCase();+ const rules = [+ [['laya'], 'violet', 'crown'],+ [['user', 'player', 'hero', 'you'], 'blue', 'ears'],+ [['architect', 'cyber_mage', 'mage'], 'violet', 'horns'],+ [['tech', 'ninja', 'pixel', 'lead'], 'cyan', 'visor'],+ [['devops', 'terminal', 'knight', 'shell', 'infra'], 'green', 'spikes'],+ [['security', 'shield', 'guard'], 'orange', 'ears'],+ [['fast', 'grok', 'zap', 'speed'], 'pink', 'sprout'],+ [['design', 'ux'], 'coral', 'beret'],+ [['data', 'analyst'], 'teal', 'glasses'],+ [['qa', 'test'], 'red', 'goggles'],+ [['product', 'manager'], 'gold', 'tie'],+ [['writer', 'docs'], 'lilac', 'quill'],+ [['research', 'scientist'], 'mint', 'bulb'],+ [['teacher', 'tutor'], 'sky', 'mortarboard'],+ [['marketing'], 'magenta', 'star'],+ [['legal', 'lawyer'], 'slate', 'bowtie'],+ [['travel', 'trip'], 'ocean', 'sunhat'],+ [['chef', 'cook', 'recipe'], 'berry', 'toque'],+ [['fitness', 'workout', 'trainer'], 'lime', 'headband'],+ [['party', 'event'], 'peach', 'partyhat'],+ [['diy', 'builder', 'handy'], 'steel', 'hardhat'],+ [['wellbeing', 'mindful', 'zen'], 'blossom', 'flower'],+ [['coach', 'mentor'], 'amber', 'cap'],+ ];+ for (const [keys, palette, accessory] of rules) {+ if (keys.some((k) => norm.includes(k))) return { ...PALETTES[palette], accessory };+ }+ // Unknown roles still get a stable, distinct creature per name+ // Fixed list so adding palettes never recolors existing agents+ const palettes = ['yellow', 'green', 'pink', 'cyan', 'violet', 'orange', 'blue'];+ const accessories = ['antenna', 'spikes', 'ears', 'horns', 'sprout', 'antenna'];+ const h = hash(name || role);+ return {+ ...PALETTES[palettes[h % palettes.length]],+ accessory: accessories[Math.floor(h / 7) % accessories.length],+ };+}++const px = (x, y, w, h, fill, key) => ({ key: key ?? `${x}-${y}-${w}-${h}-${fill}`, s: `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${fill}"/>` });++// Stepped octagon frame, as unions of rects+const FRAME_FILL = [+ [6, 2, 14, 22],+ [4, 3, 18, 20],+ [3, 4, 20, 18],+ [2, 6, 22, 14],+];++function renderAccessory(c) {+ switch (c.accessory) {+ case 'antenna':+ return [px(15, 6, 1, 1, INK), px(15, 3, 2, 2, c.accent), px(15, 3, 1, 1, '#ffffff')];+ case 'spikes':+ return [+ px(10, 5, 1, 2, c.body), px(13, 4, 1, 3, c.body), px(16, 5, 1, 2, c.body),+ px(6, 10, 1, 1, c.shade), px(6, 13, 1, 1, c.shade), px(19, 10, 1, 1, c.shade), px(19, 13, 1, 1, c.shade),+ px(13, 4, 1, 1, c.light),+ ];+ case 'ears':+ return [px(8, 5, 2, 3, c.body), px(16, 5, 2, 3, c.shade), px(8, 6, 1, 1, BLUSH), px(17, 6, 1, 1, BLUSH)];+ case 'horns':+ return [px(8, 5, 1, 2, c.accent), px(9, 6, 1, 1, c.accent), px(17, 5, 1, 2, c.accent), px(16, 6, 1, 1, c.accent)];+ case 'sprout':+ return [px(13, 5, 1, 2, '#3ccf6e'), px(14, 4, 2, 1, '#3ccf6e'), px(11, 4, 2, 1, '#1f8f4c')];+ case 'crown':+ return [+ px(10, 5, 6, 2, c.accent), px(10, 4, 1, 1, c.accent), px(12, 3, 2, 2, c.accent), px(15, 4, 1, 1, c.accent),+ px(12, 5, 2, 1, BLUSH),+ ];+ case 'visor':+ // Headphones+ return [px(9, 5, 8, 1, c.accent), px(8, 6, 1, 3, c.accent), px(17, 6, 1, 3, c.accent), px(6, 10, 2, 3, c.accent), px(18, 10, 2, 3, c.accent)];+ case 'beret':+ return [px(9, 5, 8, 2, c.accent), px(8, 6, 1, 1, c.accent), px(13, 4, 1, 1, c.accent), px(10, 5, 2, 1, '#9a7cff')];+ case 'quill':+ return [+ px(18, 2, 2, 1, '#f5f2ff'), px(17, 3, 3, 1, '#f5f2ff'), px(16, 4, 3, 1, '#f5f2ff'), px(16, 5, 2, 1, '#f5f2ff'),+ px(19, 2, 1, 1, '#c9c2e8'), px(18, 3, 1, 1, '#8f86b8'), px(17, 4, 1, 1, '#8f86b8'), px(16, 5, 1, 1, '#8f86b8'),+ px(16, 6, 1, 1, INK),+ ];+ case 'bulb':+ return [+ px(12, 2, 2, 1, c.accent), px(11, 3, 4, 2, c.accent), px(12, 3, 1, 1, '#ffffff'),+ px(12, 5, 2, 1, '#8a8aa8'), px(12, 6, 2, 1, INK),+ ];+ case 'mortarboard':+ return [px(8, 5, 10, 1, c.accent), px(10, 4, 6, 1, c.accent), px(12, 3, 2, 1, c.accent), px(10, 6, 6, 1, c.accent), px(17, 6, 1, 3, '#ffd23f')];+ case 'star':+ return [+ px(13, 2, 1, 1, c.accent), px(12, 3, 3, 1, c.accent), px(11, 4, 5, 1, c.accent),+ px(12, 5, 3, 1, c.accent), px(11, 6, 1, 1, c.accent), px(15, 6, 1, 1, c.accent), px(13, 3, 1, 1, '#ffffff'),+ ];+ case 'cap':+ return [px(9, 5, 8, 2, c.accent), px(10, 4, 6, 1, c.accent), px(5, 6, 4, 1, c.accent), px(12, 4, 2, 1, '#ffffff')];+ case 'sunhat':+ return [+ px(10, 3, 6, 2, '#f3d27a'), px(9, 4, 8, 1, '#f3d27a'), px(9, 5, 8, 1, c.accent),+ px(5, 6, 16, 1, '#f3d27a'), px(5, 6, 1, 1, '#c99a3c'), px(20, 6, 1, 1, '#c99a3c'), px(11, 3, 2, 1, '#fff1b8'),+ ];+ case 'toque':+ return [+ px(10, 2, 6, 1, '#ffffff'), px(9, 3, 8, 2, '#ffffff'), px(10, 5, 6, 2, '#e3def5'),+ px(12, 3, 1, 1, '#d2cbec'), px(15, 4, 1, 1, '#d2cbec'), px(10, 6, 6, 1, '#c9c2e8'),+ ];+ case 'partyhat':+ return [+ px(12, 2, 2, 1, '#ffe066'), px(12, 3, 2, 1, c.accent), px(11, 4, 4, 1, BLUSH), px(11, 5, 4, 1, c.accent),+ px(10, 6, 6, 1, BLUSH), px(7, 4, 1, 1, '#ffe066'), px(18, 3, 1, 1, c.accent), px(19, 6, 1, 1, BLUSH),+ px(6, 7, 1, 1, '#3ccf6e'),+ ];+ case 'hardhat':+ return [+ px(10, 3, 6, 1, c.accent), px(9, 4, 8, 2, c.accent), px(7, 6, 12, 1, '#d99a00'),+ px(13, 3, 1, 3, '#d99a00'), px(10, 4, 2, 1, '#fff1b8'),+ ];+ case 'flower':+ return [+ px(15, 2, 2, 2, '#ffffff'), px(13, 4, 2, 2, '#ffffff'), px(17, 4, 2, 2, '#ffffff'), px(15, 6, 2, 1, '#ffffff'),+ px(15, 4, 2, 2, '#ffd23f'), px(11, 5, 2, 1, '#3ccf6e'), px(12, 6, 1, 1, '#1f8f4c'),+ ];+ default:+ return [];+ }+}++// Accessories worn in front of the body (on the face or chest)+function renderOverlay(c) {+ switch (c.accessory) {+ case 'glasses':+ return [+ px(9, 9, 4, 1, c.accent), px(13, 9, 4, 1, c.accent), px(9, 10, 1, 2, c.accent), px(16, 10, 1, 2, c.accent),+ px(12, 10, 2, 1, c.accent), px(7, 10, 2, 1, c.shade), px(17, 10, 2, 1, c.shade),+ ];+ case 'goggles':+ return [+ px(7, 8, 12, 1, INK), px(9, 7, 3, 2, c.accent), px(14, 7, 3, 2, c.accent),+ px(9, 7, 1, 1, '#ffffff'), px(14, 7, 1, 1, '#ffffff'),+ ];+ case 'bowtie':+ return [px(10, 16, 2, 2, c.accent), px(14, 16, 2, 2, c.accent), px(12, 16, 2, 1, '#a8323a'), px(12, 17, 2, 1, c.accent)];+ case 'headband':+ return [+ px(8, 8, 10, 1, c.accent), px(7, 9, 12, 1, c.accent),+ px(19, 8, 2, 1, c.accent), px(20, 9, 1, 2, c.accent), px(10, 9, 3, 1, '#ffffff'),+ ];+ case 'tie':+ return [px(12, 16, 2, 1, c.accent), px(12, 17, 2, 1, c.accent), px(12, 18, 2, 1, '#a8323a')];+ default:+ return [];+ }+}++function renderCreature(c) {+ return [+ // Ground shadow+ px(7, 20, 12, 1, '#261d4a', 'shadow'),+ ...renderAccessory(c),+ // Body+ px(9, 7, 8, 1, c.body, 'b1'),+ px(8, 8, 10, 1, c.body, 'b2'),+ px(7, 9, 12, 7, c.body, 'b3'),+ px(8, 16, 10, 1, c.body, 'b4'),+ px(9, 17, 8, 1, c.shade, 'b5'),+ // Shading and highlight+ px(18, 9, 1, 7, c.shade, 's1'),+ px(17, 16, 1, 1, c.shade, 's2'),+ px(7, 15, 1, 1, c.shade, 's3'),+ px(8, 16, 1, 1, c.shade, 's4'),+ px(10, 8, 2, 1, c.light, 'h1'),+ px(9, 9, 1, 1, c.light, 'h2'),+ // Eyes+ px(10, 10, 2, 3, INK, 'e1'),+ px(14, 10, 2, 3, INK, 'e2'),+ px(10, 10, 1, 1, '#f5f2ff', 'e3'),+ px(14, 10, 1, 1, '#f5f2ff', 'e4'),+ // Blush and smile+ px(8, 13, 2, 1, BLUSH, 'k1'),+ px(16, 13, 2, 1, BLUSH, 'k2'),+ px(11, 14, 1, 1, INK, 'm1'),+ px(14, 14, 1, 1, INK, 'm2'),+ px(12, 15, 2, 1, INK, 'm3'),+ // Feet+ px(9, 18, 2, 1, INK, 'f1'),+ px(15, 18, 2, 1, INK, 'f2'),+ ...renderOverlay(c),+ ];+}+++/** The creature as an SVG string, face crop (16x16 cells, viewBox 5 2 16 16), no frame. size in CSS px. */+function creatureSvg(style, name, size, opts) {+ opts = opts || {};+ const c = pickCreature(style && isStyleId(style) ? style : (style || 'default'), name || '');+ let rects = renderCreature(c).filter(r => r.key !== 'shadow');+ let extra = '';+ if (opts.asleep) extra = [px(10,10,2,2,c.body),px(14,10,2,2,c.body),px(10,12,2,1,c.shade),px(14,12,2,1,c.shade)].map(r=>r.s).join('');+ return `<svg class="kw-face" width="${size}" height="${size}" viewBox="5 2 16 16" shape-rendering="crispEdges" aria-hidden="true">${rects.map(r=>r.s).join('')}${extra}</svg>`;+}+window.kwCreature = { pickCreature, renderCreature, creatureSvg, PALETTES, isStyleId };+})();diff --git a/apps/mac/loading/perch.css b/apps/mac/loading/perch.cssnew file mode 100644index 00000000..9f724a66--- /dev/null+++ b/apps/mac/loading/perch.css@@ -0,0 +1,229 @@+/* kwant perch: the page's styles. From Mira's reference CSS (autonomy/desktop-island/mockups/src/perch.css,+ spec design.md). Motion: transform + opacity only. Floating perches follow the system appearance;+ notched ones are always black. */+@font-face { font-family: "Pixelify Sans"; src: url("pixelify-sans.woff2") format("woff2"); font-weight: 400 700; font-display: block; }++.perch {+ /* geometry: Rust sets --notch-w / --notch-h from NSScreen (design.md §2.1); 0 on floating perches */+ --notch-w: 185px; --notch-h: 37px; --ear: 60px; --band: var(--notch-h); --wide: 460px; --cell: 2px;+ /* dark tokens: notch Macs always; floating perches in dark appearance */+ --bg: #120e26; --edge: rgb(255 255 255 / .10);+ --row: #1a1538; --chip: #231d4b; --chip-hover: #2c2552; --chip-edge: rgb(184 173 255 / .22);+ --t1: #f7f6ff; --t2: #bcb7de; --t3: #9a94c4;+ --amber: #ffb020; --amber-ink: #1b1033; --amber-rim: transparent; --needs-head: #ffb020;+ --violet: #b8adff; --ok: #5eead4; --bad: #fda4af;+ --primary: linear-gradient(135deg, #6c58e0 0%, #5b47d6 100%); --on-primary: #ffffff;+ --shadow: drop-shadow(0 10px 22px rgb(0 0 0 / .45)) drop-shadow(0 1px 2px rgb(0 0 0 / .35));+ --focus: #b8adff;+ --num: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", Inter, Roboto, "Noto Sans", sans-serif;+ position: relative; display: inline-block; box-sizing: border-box; color: var(--t1);+ font: 400 12px/16px -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", Inter, Roboto, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji";+ -webkit-font-smoothing: antialiased; user-select: none; -webkit-user-select: none;+ filter: var(--shadow);+ transform-origin: 50% 0;+}+.perch[data-shape="notch"] { --bg: #000000; --edge: transparent; --shadow: drop-shadow(0 8px 18px rgb(0 0 0 / .35)); }+.perch[data-shape="float"] { --notch-w: 0px; --notch-h: 0px; --band: 30px; }+@media (prefers-color-scheme: light) {+ .perch[data-shape="float"] {+ --bg: #ffffff; --edge: rgb(29 24 64 / .14);+ --row: #f5f3ff; --chip: #ece9ff; --chip-hover: #e2ddff; --chip-edge: rgb(58 47 124 / .18);+ --t1: #1d1840; --t2: #5a5383; --t3: #6b6494;+ --amber-rim: #1b1033; --needs-head: #8f5600; --violet: #5845bd; --ok: #0f766e; --bad: #be123c;+ --shadow: drop-shadow(0 10px 22px rgb(29 24 64 / .18)) drop-shadow(0 1px 2px rgb(29 24 64 / .14));+ --focus: #6c58e0;+}+}++/* ---- the shape: square top (it hangs from the top edge), stepped pixel corners at the bottom ---- */+.perch__edge, .perch__fill { position: absolute; inset: 0; pointer-events: none;+ clip-path: polygon(0 0, 100% 0,+ 100% calc(100% - 5 * var(--cell)), calc(100% - 1 * var(--cell)) calc(100% - 5 * var(--cell)),+ calc(100% - 1 * var(--cell)) calc(100% - 3 * var(--cell)), calc(100% - 2 * var(--cell)) calc(100% - 3 * var(--cell)),+ calc(100% - 2 * var(--cell)) calc(100% - 2 * var(--cell)), calc(100% - 3 * var(--cell)) calc(100% - 2 * var(--cell)),+ calc(100% - 3 * var(--cell)) calc(100% - 1 * var(--cell)), calc(100% - 5 * var(--cell)) calc(100% - 1 * var(--cell)),+ calc(100% - 5 * var(--cell)) 100%, calc(5 * var(--cell)) 100%,+ calc(5 * var(--cell)) calc(100% - 1 * var(--cell)), calc(3 * var(--cell)) calc(100% - 1 * var(--cell)),+ calc(3 * var(--cell)) calc(100% - 2 * var(--cell)), calc(2 * var(--cell)) calc(100% - 2 * var(--cell)),+ calc(2 * var(--cell)) calc(100% - 3 * var(--cell)), calc(1 * var(--cell)) calc(100% - 3 * var(--cell)),+ calc(1 * var(--cell)) calc(100% - 5 * var(--cell)), 0 calc(100% - 5 * var(--cell))); }+.perch__edge { background: var(--edge); }+.perch__fill { background: var(--bg); }+.perch[data-shape="float"] .perch__fill { inset: 0 1px 1px; }+.perch[data-state="peek"], .perch[data-state="expanded"] { --cell: 3px; }+.perch > .perch__in { position: relative; }++/* ---- the band: two ears around the notch (floating: the same ears, no gap) ---- */+.perch__band { display: flex; align-items: center; height: var(--band); }+.perch__ear { flex: none; width: var(--ear); height: 100%; display: flex; align-items: center; box-sizing: border-box; }+.perch__ear--l { padding-left: 12px; justify-content: flex-start; }+.perch__ear--r { padding-right: 12px; justify-content: flex-end; }+.perch__gap { flex: 1 0 var(--notch-w); }+.perch[data-shape="float"] .perch__gap { flex: 1 0 8px; }+.perch[data-shape="float"][data-state="rest"] .perch__ear, .perch[data-shape="float"][data-state="celebrate"] .perch__ear { width: auto; padding-left: 10px; padding-right: 10px; }+.perch[data-shape="float"][data-state="rest"] .perch__gap, .perch[data-shape="float"][data-state="celebrate"] .perch__gap { flex: 0 0 0; }++/* faces: the working bots' own pixel creatures, 16 px, overlapping by 4 px, each bobs while it works */+.perch__faces { display: flex; align-items: flex-end; }+.perch__faces .kw-face { display: block; width: var(--face, 20px); height: var(--face, 20px); image-rendering: pixelated; }+.perch[data-shape="float"] { --face: 18px; }+.perch__faces > span { display: block; margin-left: -4px; }+.perch__faces > span:first-child { margin-left: 0; }+.perch__faces > span[data-working] { animation: perch-bob 1200ms steps(1, end) infinite; }+.perch__faces > span[data-working]:nth-child(2) { animation-delay: -400ms; }+.perch__faces > span[data-working]:nth-child(3) { animation-delay: -800ms; }+.perch__more { margin-left: 3px; font: 700 12px/16px var(--num); color: var(--t2); font-variant-numeric: tabular-nums; }+@keyframes perch-bob { 0% { transform: none; } 50% { transform: translateY(-2px); } }++/* right ear: the amber count (needs you), the violet count (only working), or the holo check (celebrate) */+.perch__count { min-width: 20px; height: 20px; padding: 0 5px; box-sizing: border-box; border-radius: 5px;+ display: inline-flex; align-items: center; justify-content: center;+ font: 700 13px/20px var(--num); font-variant-numeric: tabular-nums; }+.perch__count--needs { background: var(--amber); color: var(--amber-ink); box-shadow: inset 0 0 0 1px var(--amber-rim); }+.perch__count--work { color: var(--violet); padding: 0 2px; }+.perch__count[data-pop] { animation: perch-pop 160ms cubic-bezier(.34, 1.56, .64, 1) backwards; }++/* holo check: the app's sticker foil (modern.css .kw-sticker-holo), 20 px square plate */+.perch__holo { position: relative; width: 20px; height: 20px; box-sizing: border-box; border: 2px solid #fff; border-radius: 6px 4px 6px 4px;+ background: #f4f1ff; overflow: hidden; isolation: isolate; transform: rotate(-3deg);+ display: inline-grid; place-items: center; box-shadow: 0 1px 0 rgb(0 0 0 / .3), 0 3px 8px rgb(0 0 0 / .35);+ animation: perch-press 160ms cubic-bezier(.2, .7, .2, 1) backwards; }+.perch__holo::before { content: ''; position: absolute; inset: 0 -50%; z-index: 0; mix-blend-mode: multiply; opacity: .8;+ background: linear-gradient(105deg, #ff6ec7 0%, #ffd36e 10%, #7dffb0 20%, #5ee0ff 30%, #9b7bff 40%, #ff6ec7 50%, #ffd36e 60%, #7dffb0 70%, #5ee0ff 80%, #9b7bff 90%, #ff6ec7 100%);+ animation: perch-drift 200ms cubic-bezier(.2, .7, .2, 1) backwards; }+.perch__holo svg { position: relative; z-index: 1; width: 12px; height: 12px; }+@keyframes perch-press { from { transform: rotate(-3deg) scale(1.25); opacity: 0; } to { transform: rotate(-3deg); opacity: 1; } }+@keyframes perch-drift { from { transform: translateX(-12%); } to { transform: none; } }+@keyframes perch-pop { from { transform: scale(.4); opacity: 0; } to { transform: none; opacity: 1; } }+/* celebrate: the finishing bot hops once (up 3 px, down), then the check stays 2.4 s */+.perch__faces > span[data-hop] { animation: perch-hop 240ms 1 backwards; }+@keyframes perch-hop { 0% { transform: none; } 40% { transform: translateY(-3px); } 100% { transform: none; } }++/* ---- the body: peek and expanded ---- */+.perch__body { padding: 8px 14px 16px; }+.perch[data-shape="float"] .perch__body { padding-top: 4px; }+.perch__item { display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 8px; row-gap: 10px; align-items: center; }+.perch__item .kw-face { width: 20px; height: 20px; display: block; image-rendering: pixelated; }+.perch__line { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 13px; line-height: 20px; color: var(--t2); }+.perch__line b { font-weight: 600; color: var(--t1); display: inline-block; max-width: 40%; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom; }+.perch__head .n { font: 600 12px/20px var(--num); letter-spacing: 0; text-transform: none; font-variant-numeric: tabular-nums; opacity: .9; }+.perch__line bdi { unicode-bidi: isolate; }+.perch__aside { font-size: 12px; line-height: 20px; color: var(--t3); white-space: nowrap; font-variant-numeric: tabular-nums; }+.perch__acts { grid-column: 2 / 4; display: flex; align-items: center; gap: 6px; min-width: 0; }+.perch__where { flex: 1 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--t3); font-size: 12px; line-height: 16px; }+.perch__note { flex: 1 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--t2); font-size: 12px; line-height: 16px; }++.pb { box-sizing: border-box; height: 28px; padding: 0 12px; border: 0; border-radius: 8px; flex: none;+ display: inline-flex; align-items: center; gap: 5px; font: inherit; font-size: 12px; line-height: 16px; font-weight: 600; cursor: pointer;+ background: var(--chip); color: var(--t1); box-shadow: inset 0 0 0 1px var(--chip-edge); transition: transform 80ms ease-out; }+.pb:hover { background: var(--chip-hover); }+.pb:active { transform: scale(.97); }+.pb:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }+.pb--primary { background: var(--primary); color: var(--on-primary); box-shadow: none; }+.pb--ghost { background: transparent; box-shadow: none; color: var(--t2); padding: 0 8px; }+.pb--ghost:hover { background: var(--chip); color: var(--t1); }+.pb svg { width: 13px; height: 13px; flex: none; }+.pb--chip { border-radius: 14px; font-weight: 500; max-width: 132px; flex: 0 1 auto; min-width: 52px; padding: 0 10px; }+.perch__acts:has(.pb--chip) { gap: 4px; }+.perch__card .perch__acts:has(.pb--chip) { grid-column: 1 / 4; }+.perch__acts { overflow: hidden; padding: 2px; margin: -2px; }+.pb--chip > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++/* expanded sections */+.perch__sec + .perch__sec { margin-top: 12px; }+.perch__head { display: flex; align-items: baseline; gap: 6px; height: 20px; margin-bottom: 4px;+ font: 500 12px/20px "Pixelify Sans", monospace; letter-spacing: .06em; text-transform: uppercase; color: var(--t2); }+.perch__head--needs { color: var(--needs-head); }+.perch__head--work { color: var(--violet); }+.perch__card { background: var(--row); border-radius: 10px; padding: 10px; }+.perch__card + .perch__card { margin-top: 6px; }+.perch__row { display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 8px; align-items: center; height: 28px; padding: 0 4px; border-radius: 8px; cursor: pointer; }+.perch__row:hover { background: var(--row); }+.perch__row .kw-face { width: 20px; height: 20px; display: block; image-rendering: pixelated; }+.perch__row .perch__line bdi.t { color: var(--t2); }+.perch__row[data-unseen] .perch__line bdi.t { color: var(--t1); font-weight: 600; }+.perch__more-line { display: block; padding: 4px 4px 0; font-size: 12px; line-height: 20px; color: var(--t2); }+.perch__more-line u { text-decoration: none; color: var(--violet); font-weight: 600; }+.perch__check { font-size: 12px; line-height: 20px; white-space: nowrap; display: inline-flex; align-items: center; gap: 3px; }+.perch__check--ok { color: var(--ok); } .perch__check--none { color: var(--t3); } .perch__check--bad { color: var(--bad); }+.perch__check svg { width: 12px; height: 12px; }++.perch__ask { display: flex; align-items: center; gap: 6px; height: 36px; padding: 0 4px 0 6px; border-radius: 10px; background: var(--row); box-shadow: inset 0 0 0 1px var(--chip-edge); }+.perch__ask-who { position: relative; display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 6px 0 4px; border-radius: 7px; background: var(--chip); font-size: 12px; font-weight: 600; color: var(--t1); flex: none; max-width: 120px; }+.perch__ask-who .kw-face { width: 16px; height: 16px; image-rendering: pixelated; }+.perch__ask-who > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.perch__ask-who svg.chev { width: 12px; height: 12px; color: var(--t3); flex: none; }+.perch__ask input { flex: 1; min-width: 0; height: 28px; border: 0; background: transparent; color: var(--t1); font: inherit; font-size: 13px; outline: none; }+.perch__ask input::placeholder { color: var(--t3); }+.perch__ask .send { width: 28px; height: 28px; padding: 0; justify-content: center; }+.perch__sent { display: flex; align-items: center; gap: 4px; padding: 6px 4px 0; font-size: 12px; color: var(--t2); }+.perch__sent svg { width: 12px; height: 12px; color: var(--ok); }++.perch__places { display: flex; gap: 6px; min-width: 0; }+.perch__place:not(:has(.glyph)) { flex: none; }+.perch__place[aria-current] { flex: none; }+.perch__place { flex: 0 1 auto; min-width: 0; display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px 0 8px; border-radius: 8px;+ background: transparent; border: 0; font-family: inherit; box-shadow: inset 0 0 0 1px var(--chip-edge); color: var(--t2); font-size: 12px; font-weight: 500; cursor: pointer; }+.perch__place[aria-current] { background: var(--chip); color: var(--t1); box-shadow: inset 0 0 0 1px var(--violet); }+.perch__place[data-off] { color: var(--t3); }+.perch__place > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.perch__place .n { flex: none; min-width: 16px; height: 16px; padding: 0 4px; box-sizing: border-box; border-radius: 4px; background: var(--amber); color: var(--amber-ink);+ box-shadow: inset 0 0 0 1px var(--amber-rim); font: 700 11px/16px var(--num); font-variant-numeric: tabular-nums; text-align: center; }+.perch__place svg.glyph { width: 14px; height: 14px; flex: none; image-rendering: pixelated; }+.perch__sec--places { margin-top: 12px; }+.perch__foot { display: flex; align-items: center; justify-content: space-between; margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--chip-edge); }+.perch__keys { font-size: 12px; color: var(--t3); }+.perch__keys kbd { font: inherit; padding: 1px 5px; border-radius: 4px; box-shadow: inset 0 0 0 1px var(--chip-edge); color: var(--t2); }+.perch__quiet { display: flex; align-items: center; gap: 10px; padding: 6px 4px 2px; color: var(--t2); font-size: 13px; }+.perch__quiet .kw-face { width: 32px; height: 32px; image-rendering: pixelated; }++/* ---- motion: enter / grow / leave (Rust resizes the panel; the page animates with transform + opacity) ---- */+.perch[data-enter] { animation: perch-in 200ms cubic-bezier(.34, 1.56, .64, 1) backwards, perch-fade 120ms linear backwards; }+.perch[data-grow] .perch__body { animation: perch-body 160ms cubic-bezier(.2, .7, .2, 1) backwards, perch-fade 120ms 40ms linear backwards; }+.perch[data-leave] { animation: perch-out 160ms cubic-bezier(.4, 0, 1, 1) forwards; }+@keyframes perch-in { from { transform: scale(.82, .6); } to { transform: none; } }+@keyframes perch-body { from { transform: translateY(-6px); } to { transform: none; } }+@keyframes perch-fade { from { opacity: 0; } to { opacity: 1; } }+@keyframes perch-out { to { transform: scale(.9, .7); opacity: 0; } }++@media (prefers-reduced-motion: reduce) {+ .perch[data-enter] { animation: perch-fade 160ms linear backwards; }+ .perch[data-grow] .perch__body { animation: perch-fade 160ms linear backwards; }+ .perch[data-leave] { animation: perch-fadeout 160ms linear forwards; }+ .perch__faces > span[data-working], .perch__faces > span[data-hop], .perch__count[data-pop], .perch__holo, .perch__holo::before { animation: none; }+ .pb:active { transform: none; }+}+@keyframes perch-fadeout { to { opacity: 0; } }++/* ---- widths ---- */+.perch[data-shape="notch"] { width: calc(var(--notch-w) + 2 * var(--ear)); }+.perch[data-state="peek"], .perch[data-state="expanded"] { width: var(--wide); }+.perch[data-shape="float"][data-state="peek"] .perch__band, .perch[data-shape="float"][data-state="expanded"] .perch__band { height: 30px; }+.face { display: inline-block; line-height: 0; }+.ico { display: contents; }++/* ---- the page around the perch ---- */+html, body { margin: 0; background: transparent; overflow: hidden; cursor: default; }+/* open states get 24 px of transparent margin left, right and below for the shadow (perch.rs MARGIN) */+#stage { display: inline-block; vertical-align: top; }+#stage[data-open] { padding: 0 24px 24px; }+/* at rest and celebrate the window has no margin, so a shadow would be cut into a grey box at its edge:+ the perch keeps its 1 px edge ring and drops the shadow (design.md §2.2, §11.14) */+#stage:not([data-open]) .perch { filter: none; }+#stage[hidden] { display: none; }+.perch__band { cursor: pointer; }+.perch__more-line { cursor: pointer; }+.perch__more-line:focus-visible, .perch__row:focus-visible, .perch__place:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }+.perch__ask-who select { position: absolute; inset: 0; width: 100%; opacity: 0; cursor: pointer; font: inherit; }+.perch__ask-who:focus-within { outline: 2px solid var(--focus); outline-offset: 1px; }+.perch__fail { flex: 1 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--bad); font-size: 12px; line-height: 16px; }+.perch__sent u { text-decoration: none; color: var(--violet); font-weight: 600; cursor: pointer; margin-left: 4px; }+.pb[data-busy] { pointer-events: none; opacity: .8; }+.pb[data-busy]::after { content: ''; width: 10px; height: 10px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent; animation: perch-spin 700ms linear infinite; }+.pb[disabled] { cursor: default; opacity: .55; }+@keyframes perch-spin { to { transform: rotate(360deg); } }+.perch__body[data-swap] { animation: perch-fade 120ms linear backwards; }+@media (prefers-reduced-motion: reduce) {+ .pb[data-busy]::after { animation: none; border-right-color: currentColor; opacity: .6; }+ .perch__body[data-swap] { animation: none; }+}diff --git a/apps/mac/loading/perch.html b/apps/mac/loading/perch.htmlnew file mode 100644index 00000000..8b498ffe--- /dev/null+++ b/apps/mac/loading/perch.html@@ -0,0 +1,16 @@+<!doctype html>+<!-- The perch (design: /home/maus/shared/ship-software-safely/autonomy/desktop-island/design.md; Rust side+ src/perch.rs and src/perch_window.rs). A bundled page in its own window ("perch") with no command+ capability. Rust gives it everything with window.eval("kwantPerch.update({...})") and tells it how a+ call went with kwantPerch.done({op, id, ok, code}). The page answers only by navigating to+ kwant-island://… (ready, size, allow, deny, answer, open, ask, place, places, focus, collapse), which+ on_navigation catches and refuses. A thing is named by its place index and its id, never by a name.+ Every server string goes in with textContent; only our own creature SVG and icons use innerHTML. -->+<html><head><meta charset="utf-8"><meta name="color-scheme" content="light dark">+<title>kwant perch</title>+<link rel="stylesheet" href="perch.css">+</head><body>+<div id="stage" hidden></div>+<script src="creatures.js"></script>+<script src="perch.js"></script>+</body></html>diff --git a/apps/mac/loading/perch.js b/apps/mac/loading/perch.jsnew file mode 100644index 00000000..3bf8e9ef--- /dev/null+++ b/apps/mac/loading/perch.js@@ -0,0 +1,531 @@+/* kwant perch: the page. Built from Mira's reference renderer (autonomy/desktop-island/mockups/src/perch.js,+ spec design.md) and wired to Rust (src/perch.rs page_json / parse_perch, src/perch_window.rs).+ Every server string goes in through textContent (never innerHTML). Only our own generated SVG uses+ innerHTML. The page decides peek / expanded / celebrate and its timings; Rust decides what it may do. */+(function () {+ 'use strict';+ var C = window.kwCreature;+ var HOLD = 5000; // a peek shows this long (design.md §6)+ var AFTER_HOVER = 2000; // and closes this long after the pointer leaves+ var CELEBRATE = 2400;+ var SENT_FOR = 3000;+ var CALL_TIMEOUT = 10000; // a call with no answer by then counts as failed+ var ASK_MAX = 8000; // perch.rs ASK_MAX++ // ---------------------------------------------------------------------------------------------+ // Talking to Rust: one navigation at a time (two in the same moment may lose the first).+ var queue = [], pumping = false;+ function send(what) { queue.push(what); if (!pumping) pump(); }+ function pump() {+ var next = queue.shift();+ if (next === undefined) { pumping = false; return; }+ pumping = true;+ location.href = 'kwant-island://' + next;+ setTimeout(pump, 40);+ }+ function thing(p, id) { return 'p=' + Number(p) + '&id=' + encodeURIComponent(id); }++ // ---------------------------------------------------------------------------------------------+ // Building blocks (Mira's)+ function el(tag, attrs, kids) {+ var n = document.createElement(tag);+ for (var k in (attrs || {})) {+ var v = attrs[k]; if (v === false || v == null) continue;+ if (k === 'class') n.className = v; else if (k === 'text') n.textContent = v; else if (k === 'html') n.innerHTML = v; else n.setAttribute(k, v === true ? '' : v);+ }+ [].concat(kids || []).forEach(function (c) { if (c != null && c !== false) n.append(typeof c === 'string' ? document.createTextNode(c) : c); });+ return n;+ }+ var ICON = {+ open: '<path d="M7 7h10v10"/><path d="M7 17 17 7"/>',+ check: '<path d="M20 6 9 17l-5-5"/>',+ x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',+ send: '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',+ chev: '<path d="m6 9 6 6 6-6"/>',+ };+ function icon(name, cls) { return el('span', { class: 'ico', html: '<svg class="' + (cls || '') + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + ICON[name] + '</svg>' }).firstChild; }+ var GLYPH = {+ mac: ['.......', '.#####.', '.#...#.', '.#...#.', '.#####.', '#######', '.......'],+ server: ['.#####.', '.#..#..', '.#####.', '.......', '.#####.', '.#..#..', '.#####.'],+ };+ function glyph(kind) {+ var rows = GLYPH[kind] || GLYPH.server, r = '';+ rows.forEach(function (row, y) { Array.from(row).forEach(function (ch, x) { if (ch === '#') r += '<rect x="' + x + '" y="' + y + '" width="1" height="1"/>'; }); });+ return el('span', { html: '<svg class="glyph" viewBox="0 0 7 7" fill="currentColor" shape-rendering="crispEdges" aria-hidden="true">' + r + '</svg>' }).firstChild;+ }+ // the creature's SVG is ours: the name only picks a palette, it never goes into the markup+ function face(who, size, opts) { who = who || {}; return el('span', { class: 'face', html: C.creatureSvg(who.avatar || null, String(who.name || ''), size, opts) }); }+ function bdi(s, cls) { return el('bdi', { text: String(s || ''), class: cls || false, dir: 'auto' }); }+ function midcut(s, max) { var a = Array.from(String(s || '')); if (a.length <= max) return a.join(''); var keep = max - 1, h = Math.ceil(keep / 2); return a.slice(0, h).join('') + '…' + a.slice(a.length - (keep - h)).join(''); }+ function countLabel(n) { return n > 9 ? '9+' : String(n); }+ function key(p, id) { return p + '#' + id; }+ function ago(since, long) {+ var t = Date.parse(since || '');+ if (!isFinite(t)) return long ? '' : 'now';+ var m = Math.max(0, Math.floor((Date.now() - t) / 60000));+ if (m < 1) return long ? 'just now' : 'now';+ if (m < 60) return long ? m + ' min' : m + 'm';+ var h = Math.floor(m / 60);+ if (h < 24) return h + ' h';+ return Math.floor(h / 24) + ' d';+ }++ // ---------------------------------------------------------------------------------------------+ // State+ var D = null; // the latest update from Rust+ var open = null; // null | 'peek' | 'expanded'+ var openBy = null; // 'key' | 'click' | 'hover' | 'event'+ var peekKey = null; // the item a peek shows+ var lastPeek = null, lastCelebrate = null, celebrateUntil = 0, celebrateKey = null;+ var lastToggles = null;+ var hovering = false, focused = false;+ var holdTimer = null, leaveTimer = null, celebrateTimer = null;+ var busy = {}; // key → {op, timer}: a call on its way+ var failed = {}; // key → true: show "Didn't go through"+ var settled = {}; // key → true: went through, hidden until the next poll drops it+ var ask = { pick: null, text: '', sent: null, failed: false, cid: null };+ var lastSize = '';+ var lastState = 'hidden';+ var stage = document.getElementById('stage');++ function needs() { return (D && D.needs || []).filter(function (n) { return !settled[key(n.p, n.id)]; }); }+ function needsCount() { var all = D ? (D.counts && D.counts.needs) || 0 : 0; var hidden = (D && D.needs || []).length - needs().length; return Math.max(needs().length, all - hidden); }+ function working() { return D && D.working || []; }+ function workingCount() { return Math.max(working().length, D && D.counts ? D.counts.working || 0 : 0); }+ function finished() { return D && D.finished || []; }+ function findNeed(k) { return needs().filter(function (n) { return key(n.p, n.id) === k; })[0] || null; }++ function state() {+ if (!D) return 'hidden';+ if (open) return open;+ if (celebrateKey && Date.now() < celebrateUntil) return 'celebrate';+ if (needsCount() || workingCount()) return 'rest';+ if (D.mode === 'always') return 'rest';+ return 'hidden';+ }++ function clearTimers() { clearTimeout(holdTimer); clearTimeout(leaveTimer); holdTimer = leaveTimer = null; }++ function expand(by) {+ clearTimers();+ open = 'expanded'; openBy = by;+ render();+ }+ function peek(k, by) {+ if (open === 'expanded') return;+ var swap = open === 'peek' && peekKey !== k;+ open = 'peek'; openBy = by; peekKey = k;+ clearTimers();+ if (by !== 'hover') holdTimer = setTimeout(maybeClose, HOLD);+ render(swap);+ }+ function close(tellRust) {+ clearTimers();+ var was = open;+ open = null; openBy = null; peekKey = null;+ if (ask.text === '') ask.sent = null;+ if (was) render();+ if (tellRust) send('collapse');+ }+ // a peek or click-opened panel closes when the time is up, unless it is hovered, focused or typed in+ function maybeClose() {+ holdTimer = null;+ if (!open) return;+ if (open === 'expanded' && (openBy === 'key' || ask.text)) return;+ if (hovering || focused) return;+ close(true);+ }++ // ---------------------------------------------------------------------------------------------+ // The band (both ears)+ function band(st) {+ var left = el('div', { class: 'perch__ear perch__ear--l' });+ var right = el('div', { class: 'perch__ear perch__ear--r' });+ var faces = el('div', { class: 'perch__faces' });+ var who = working().map(function (w) { return w.who; });+ var celebrating = st === 'celebrate' ? finished().filter(function (f) { return key(f.p, f.id) === celebrateKey; })[0] : null;+ if (celebrating) who = [celebrating.who].concat(who.filter(function (w) { return w.name !== celebrating.who.name; }));+ var total = celebrating ? Math.max(who.length, workingCount()) : workingCount();+ var shown = total > 3 ? who.slice(0, 2) : who.slice(0, 3);+ var size = D.shape === 'notch' ? 20 : 18;+ shown.forEach(function (w, i) {+ var f = face(w, size);+ if (celebrating && i === 0) f.setAttribute('data-hop', ''); else f.setAttribute('data-working', '');+ faces.append(f);+ });+ if (total > 3) faces.append(el('span', { class: 'perch__more', text: '+' + (total - 2), 'aria-label': (total - 2) + ' more working' }));+ // Always, nothing going on: the floating tab shows kwant asleep; the notch shows two empty ears+ if (!shown.length && !celebrating && !needsCount() && D.shape !== 'notch' && st === 'rest') {+ faces.append(face({ name: 'kwant', avatar: 'brand' }, size, { asleep: true }));+ }+ left.append(faces);+ var n = needsCount();+ if (celebrating) {+ right.append(el('span', { class: 'perch__holo', role: 'img', 'aria-label': celebrating.who.name + ' finished: checked', html: '<svg viewBox="0 0 24 24" fill="none" stroke="#1b1033" stroke-width="3.5" stroke-linecap="square" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>' }));+ } else if (n) {+ var c = el('span', { class: 'perch__count perch__count--needs', text: countLabel(n), role: 'img', 'aria-label': n + ' need you' });+ if (n !== lastNeeds) c.setAttribute('data-pop', '');+ right.append(c);+ } else if (workingCount()) {+ right.append(el('span', { class: 'perch__count perch__count--work', text: countLabel(workingCount()), role: 'img', 'aria-label': workingCount() + ' working' }));+ }+ lastNeeds = n;+ var b = el('div', { class: 'perch__band', title: D.key ? 'Open the perch (' + D.key + ')' : 'Open the perch' }, [left, el('div', { class: 'perch__gap' }), right]);+ b.addEventListener('click', function () {+ if (open === 'expanded') close(true); else expand('click');+ });+ b.addEventListener('mouseenter', function () {+ if (!open && needs().length) peek(key(needs()[0].p, needs()[0].id), 'hover');+ });+ return b;+ }+ var lastNeeds = 0;++ // ---------------------------------------------------------------------------------------------+ // One needs-you item: the sentence and what you can do+ function verb(it) { return it.kind === 'question' ? ' asks: ' : it.kind === 'approval' ? ' wants your OK: ' : ' needs you: '; }+ function sentence(it) {+ var who = it.who.name;+ return el('div', { class: 'perch__line', title: who + verb(it) + it.title }, [el('b', {}, [bdi(who)]), verb(it), bdi(it.title)]);+ }+ function button(cls, label, onClick, attrs) {+ var b = el('button', Object.assign({ class: 'pb ' + cls, type: 'button' }, attrs || {}), label);+ b.addEventListener('click', function (e) { e.stopPropagation(); onClick(b); });+ return b;+ }+ function openButton(it, label, primary) {+ return button(primary ? 'pb--primary' : 'pb--ghost', [label, icon('open')], function () { send('open?' + thing(it.p, it.id)); }, { 'aria-label': label === 'Open' ? 'Open in kwant' : label });+ }+ function call(it, op, extra) {+ var k = key(it.p, it.id);+ if (busy[k]) return;+ delete failed[k];+ busy[k] = { op: op, timer: setTimeout(function () { finish({ op: op, id: it.id, ok: false, code: 'timeout' }, k); }, CALL_TIMEOUT) };+ send(op + '?' + thing(it.p, it.id) + (extra || ''));+ render();+ }+ function actions(it) {+ var k = key(it.p, it.id);+ var acts = el('div', { class: 'perch__acts' });+ var b = busy[k] ? busy[k].op : null;+ if (failed[k]) {+ acts.append(el('span', { class: 'perch__fail', role: 'status', text: "Didn't go through. Open it in kwant." }), openButton(it, 'Open'));+ return acts;+ }+ var multi = D.multiPlace || D.multiSpace;+ if (it.kind === 'approval' && it.inline === true) {+ var where = [it.space, D.multiPlace && it.place ? midcut(it.place, 24) : null].filter(Boolean).join(' · ');+ if (multi && where) acts.append(el('span', { class: 'perch__where', title: [it.space, it.place].filter(Boolean).join(' · '), text: where }));+ else acts.append(el('span', { style: 'flex:1' }));+ // Allow once is never focused for you: a stray Enter must never approve+ acts.append(+ button('pb--primary', 'Allow once', function () { call(it, 'allow'); }, { 'data-busy': b === 'allow', disabled: !!b }),+ button('', 'Deny', function () { call(it, 'deny'); }, { 'data-busy': b === 'deny', disabled: !!b }),+ openButton(it, 'Open'));+ } else if (it.kind === 'question') {+ (it.choices || []).slice(0, 3).forEach(function (c, i) {+ acts.append(button('pb--chip', [el('span', { text: String(c) })], function () { call(it, 'answer', '&c=' + i); }, { title: String(c), 'data-busy': b === 'answer', disabled: !!b }));+ });+ acts.append(el('span', { style: 'flex:1' }));+ acts.append(openButton(it, it.reply || !(it.choices || []).length ? 'Reply' : 'Open'));+ } else {+ acts.append(el('span', { class: 'perch__note', title: it.why || false, text: 'Decide in kwant: this one needs the full card.' }));+ acts.append(openButton(it, 'Open in kwant', true));+ }+ return acts;+ }+ function needItem(it, inPeek) {+ var more = needsCount() - 1;+ var aside = el('span', { class: 'perch__aside', text: inPeek && more > 0 ? '+' + more + ' more' : ago(it.since) });+ return el('div', { class: 'perch__item' }, [face(it.who, 20), sentence(it), aside, actions(it)]);+ }++ // ---------------------------------------------------------------------------------------------+ // Expanded+ function head(label, cls, extra) { return el('div', { class: 'perch__head ' + (cls || '') }, [label, extra ? el('span', { class: 'n', text: extra }) : null]); }+ function moreLine(n, label, what) {+ var a = el('a', { class: 'perch__more-line', role: 'link', tabindex: '0' }, ['and ' + n + ' more · ', el('u', { text: label })]);+ var go = function () { send('open?what=' + what); };+ a.addEventListener('click', go);+ a.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } });+ return a;+ }+ function row(item, kids, attrs) {+ var r = el('div', Object.assign({ class: 'perch__row', role: 'button', tabindex: '0' }, attrs || {}), kids);+ var go = function () { send('open?' + thing(item.p, item.id)); };+ r.addEventListener('click', go);+ r.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } });+ return r;+ }+ function expanded(compact) {+ var body = el('div', { class: 'perch__body' });+ var ns = needs(), ws = working(), fs = finished().slice().sort(function (a, b) { return (b.unseen ? 1 : 0) - (a.unseen ? 1 : 0); });+ var maxNeeds = compact ? 1 : 2, maxWork = compact ? 1 : 3, maxFin = compact ? 1 : 2;+ if (!ns.length && !ws.length && !fs.length) {+ body.append(el('div', { class: 'perch__quiet' }, [face({ name: 'kwant', avatar: 'brand' }, 32, { asleep: true }), el('span', { text: 'All quiet. Nobody needs you and nobody is working.' })]));+ }+ if (ns.length) {+ var nc = needsCount();+ var s = el('section', { class: 'perch__sec', 'aria-label': 'Needs you' }, [head('Needs you', 'perch__head--needs', '· ' + nc)]);+ ns.slice(0, maxNeeds).forEach(function (it) { s.append(el('div', { class: 'perch__card' }, [needItem(it, false)])); });+ if (nc > maxNeeds) s.append(moreLine(nc - maxNeeds, 'Open Inbox', 'inbox'));+ body.append(s);+ }+ if (ws.length) {+ var wc = workingCount();+ var s2 = el('section', { class: 'perch__sec', 'aria-label': 'Working now' }, [head('Working now', 'perch__head--work', '· ' + wc)]);+ ws.slice(0, maxWork).forEach(function (w) {+ s2.append(row(w, [face(w.who, 20), el('div', { class: 'perch__line', title: w.who.name + ' · ' + w.step }, [el('b', {}, [bdi(w.who.name)]), w.step ? ' · ' : '', bdi(w.step)]), el('span', { class: 'perch__aside', text: ago(w.since, true) })]));+ });+ if (wc > maxWork) s2.append(moreLine(wc - maxWork, 'Open Live now', 'live'));+ body.append(s2);+ }+ if (fs.length) {+ var s3 = el('section', { class: 'perch__sec', 'aria-label': 'Just finished' }, [head('Just finished')]);+ fs.slice(0, maxFin).forEach(function (f) {+ var chk = f.check === 'verified' ? el('span', { class: 'perch__check perch__check--ok' }, [icon('check'), 'Checked'])+ : f.check === 'failed' ? el('span', { class: 'perch__check perch__check--bad' }, [icon('x'), 'Check failed'])+ : el('span', { class: 'perch__check perch__check--none', text: 'Not checked' });+ s3.append(row(f, [face(f.who, 20), el('div', { class: 'perch__line', title: f.who.name + ' · ' + f.title }, [el('b', {}, [bdi(f.who.name)]), ' · ', bdi(f.title, 't')]), chk], { 'data-unseen': !!f.unseen }));+ });+ if (fs.length > maxFin) s3.append(moreLine(fs.length - maxFin, 'Open Activity', 'activity'));+ body.append(s3);+ }+ var targets = D.ask || [];+ if (targets.length) body.append(quickAsk(targets));+ var places = D.places || [];+ if (places.length > 1) {+ var list = el('div', { class: 'perch__places', role: 'group', 'aria-label': 'Places' });+ var show = places.length > 3 ? places.slice(0, 2) : places;+ show.forEach(function (p) {+ var label = p.kind === 'server' ? midcut(p.name, 22) : p.name;+ var tip = p.name + (p.off ? " · Can't reach it" : p.waiting ? ' · ' + p.waiting + ' waiting' : '');+ var b = el('button', { class: 'perch__place', type: 'button', 'aria-current': p.current ? 'true' : false, 'data-off': !!p.off, title: tip, 'aria-label': tip },+ [glyph(p.kind === 'mac' ? 'mac' : 'server'), el('span', { text: label }), p.waiting ? el('span', { class: 'n', text: countLabel(p.waiting) }) : null]);+ b.addEventListener('click', function () { send('place?i=' + Number(p.i)); });+ list.append(b);+ });+ if (places.length > 3) {+ var more = el('button', { class: 'perch__place', type: 'button', title: 'All places', text: '+' + (places.length - 2), 'aria-label': (places.length - 2) + ' more places, show all' });+ more.addEventListener('click', function () { send('places'); });+ list.append(more);+ }+ body.append(el('section', { class: 'perch__sec perch__sec--places', 'aria-label': 'Places' }, [head('Places'), list]));+ }+ var foot = el('div', { class: 'perch__foot' });+ foot.append(D.key ? el('span', { class: 'perch__keys' }, [el('kbd', { text: D.key }), ' opens and closes this']) : el('span'));+ foot.append(button('pb--ghost', ['Open kwant', icon('open')], function () { send('open?what=app'); }));+ body.append(foot);+ return body;+ }++ function quickAsk(targets) {+ // keep the person's pick across updates (by who it is, not by its index)+ var t = targets.filter(function (x) { return ask.pick && x.p === ask.pick.p && x.who.name === ask.pick.name; })[0] || targets[0];+ ask.pick = { p: t.p, name: t.who.name };+ var to = t.who;+ var s = el('section', { class: 'perch__sec', 'aria-label': 'Quick ask' }, [head('Quick ask')]);+ var pick = el('select', { 'aria-label': 'Choose who to ask' });+ targets.forEach(function (x) {+ var o = el('option', { value: String(x.t), text: x.who.name + (x.place ? ' · ' + midcut(x.place, 24) : '') });+ if (x === t) o.selected = true;+ pick.append(o);+ });+ pick.addEventListener('mousedown', function () { send('focus'); });+ pick.addEventListener('change', function () {+ var x = targets.filter(function (y) { return String(y.t) === pick.value; })[0];+ if (x) { ask.pick = { p: x.p, name: x.who.name }; ask.sent = null; render(); focusAsk(); }+ });+ var input = el('input', { type: 'text', id: 'ask', maxlength: String(ASK_MAX), placeholder: 'Ask ' + to.name + ' something…', 'aria-label': 'Message to ' + to.name, autocomplete: 'off', spellcheck: 'true', dir: 'auto' });+ input.value = ask.text;+ var go = button((ask.text.trim() ? 'pb--primary ' : '') + 'send', [icon('send')], function () { submit(t); }, { 'aria-label': 'Send', disabled: !ask.text.trim() || !!ask.cid, 'data-busy': !!ask.cid });+ input.addEventListener('mousedown', function () { send('focus'); });+ input.addEventListener('input', function () {+ ask.text = input.value; ask.failed = false;+ var on = !!ask.text.trim();+ go.disabled = !on || !!ask.cid; go.classList.toggle('pb--primary', on);+ });+ input.addEventListener('keydown', function (e) { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); submit(t); } });+ s.append(el('div', { class: 'perch__ask' }, [+ el('label', { class: 'perch__ask-who', title: 'Choose who to ask' }, [face(to, 16), el('span', {}, [bdi(to.name)]), icon('chev', 'chev'), pick]),+ input, go,+ ]));+ if (ask.failed) {+ s.append(el('div', { class: 'perch__sent', role: 'status' }, [el('span', { class: 'perch__fail', text: "Didn't go through. Try again, or ask in kwant." })]));+ } else if (ask.sent && Date.now() < ask.sent.until) {+ var openChat = el('u', { role: 'link', tabindex: '0', text: 'Open chat' });+ var sent = ask.sent;+ var goChat = function () { send('open?' + thing(sent.p, sent.cid)); };+ openChat.addEventListener('click', goChat);+ openChat.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); goChat(); } });+ s.append(el('div', { class: 'perch__sent', role: 'status' }, [icon('check'), el('span', {}, ['Sent to ', bdi(sent.name), ". It's in your chat."]), openChat]));+ }+ return s;+ }+ function focusAsk() { var i = document.getElementById('ask'); if (i) { send('focus'); i.focus(); } }+ function newCid() {+ var b = new Uint8Array(16); crypto.getRandomValues(b);+ return 'island-' + Array.from(b, function (x) { return (x < 16 ? '0' : '') + x.toString(16); }).join('');+ }+ function submit(t) {+ var text = ask.text.trim();+ if (!text || ask.cid) return;+ ask.cid = newCid(); ask.failed = false; ask.sent = null;+ ask.to = { p: t.p, name: t.who.name };+ clearTimeout(ask.timer);+ ask.timer = setTimeout(function () { finish({ op: 'ask', id: ask.cid, ok: false, code: 'timeout' }); }, CALL_TIMEOUT);+ send('ask?t=' + Number(t.t) + '&text=' + encodeURIComponent(text.slice(0, ASK_MAX)) + '&cid=' + ask.cid);+ render();+ }++ // ---------------------------------------------------------------------------------------------+ // Rendering and the size Rust needs+ var lastRendered = 'hidden';+ function render(swap) {+ var st = state();+ var wasHidden = lastRendered === 'hidden';+ var wasOpen = lastRendered === 'peek' || lastRendered === 'expanded';+ var nowOpen = st === 'peek' || st === 'expanded';+ // keep the Quick ask field's focus and caret through a re-render+ var active = document.activeElement && document.activeElement.id === 'ask' ? document.activeElement : null;+ var caret = active ? [active.selectionStart, active.selectionEnd] : null;+ if (st === 'hidden') {+ lastRendered = st;+ var old = stage.querySelector('.perch');+ if (old && !stage.hidden) {+ old.setAttribute('data-leave', '');+ setTimeout(function () { if (state() === 'hidden') { stage.hidden = true; stage.replaceChildren(); report('hidden', 0, 0); } }, reduced() ? 160 : 160);+ } else {+ stage.hidden = true; report('hidden', 0, 0);+ }+ return;+ }+ var root = el('div', { class: 'perch', 'data-shape': D.shape === 'notch' ? 'notch' : 'float', 'data-state': st, role: 'region', 'aria-label': 'kwant perch' });+ if (D.shape === 'notch' && D.notch) {+ root.style.setProperty('--notch-w', Math.max(80, Math.min(400, Number(D.notch.w) || 185)) + 'px');+ root.style.setProperty('--notch-h', Math.max(16, Math.min(64, Number(D.notch.h) || 37)) + 'px');+ }+ if (wasHidden) root.setAttribute('data-enter', '');+ else if (nowOpen && !wasOpen) root.setAttribute('data-grow', '');+ root.append(el('div', { class: 'perch__edge' }), el('div', { class: 'perch__fill' }));+ var inner = el('div', { class: 'perch__in' });+ inner.append(band(st));+ if (st === 'peek') {+ var it = findNeed(peekKey);+ var b = el('div', { class: 'perch__body', 'data-swap': swap ? '' : false });+ if (it) b.append(needItem(it, true));+ inner.append(b);+ }+ if (st === 'expanded') inner.append(expanded(compact));+ root.append(inner);+ root.addEventListener('mouseenter', function () { hovering = true; clearTimeout(leaveTimer); });+ root.addEventListener('mouseleave', function () {+ hovering = false;+ if (open && !(open === 'expanded' && openBy === 'key')) { clearTimeout(leaveTimer); leaveTimer = setTimeout(maybeClose, AFTER_HOVER); }+ });+ stage.hidden = false;+ stage.toggleAttribute('data-open', nowOpen);+ stage.replaceChildren(root);+ lastRendered = st;+ if (active) { var again = document.getElementById('ask'); if (again) { again.focus(); try { again.setSelectionRange(caret[0], caret[1]); } catch (e) { /* not a text field any more */ } } }+ requestAnimationFrame(function () { measure(st, root); });+ }+ var compact = false;+ function measure(st, root) {+ if (!root.isConnected) return;+ // layout size, not the animated one (transforms don't change offsetWidth)+ var w = Math.ceil(root.offsetWidth), h = Math.ceil(root.offsetHeight);+ // small screens: drop to one row per section when it would come within 80 px of the bottom+ if (st === 'expanded') {+ var room = (window.screen && window.screen.availHeight || 900) - 80;+ if (!compact && h > room) { compact = true; render(); return; }+ if (compact && h < room - 200) { compact = false; render(); return; }+ }+ report(st, w, h);+ }+ function report(st, w, h) {+ var s = 's=' + st + '&w=' + Math.min(9999, w) + '&h=' + Math.min(9999, h);+ if (s === lastSize) return;+ lastSize = s;+ lastState = st;+ send('size?' + s);+ }+ function reduced() { return window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches; }++ // ---------------------------------------------------------------------------------------------+ // What Rust calls+ function update(d) {+ if (!d || typeof d !== 'object') return;+ var first = D === null;+ D = d;+ // things that went through stay hidden until the poll drops them+ Object.keys(settled).forEach(function (k) { if (!(d.needs || []).some(function (n) { return key(n.p, n.id) === k; })) delete settled[k]; });+ // the shortcut: each press flips open / closed (Rust says which in byKey)+ if (first || d.toggles !== lastToggles) {+ var flipped = !first && d.toggles !== lastToggles;+ lastToggles = d.toggles;+ if (d.byKey) { expand('key'); }+ else if (flipped && open) { close(false); }+ }+ // a new need peeks (unless the panel is open)+ var pk = d.peek ? key(d.peek.p, d.peek.id) : null;+ if (pk && pk !== lastPeek) {+ lastPeek = pk;+ if (!open && findNeed(pk)) { peek(pk, 'event'); return; }+ }+ // a verified finish celebrates once, 2.4 s+ var ck = d.celebrate ? key(d.celebrate.p, d.celebrate.id) : null;+ if (ck && ck !== lastCelebrate) {+ lastCelebrate = ck; celebrateKey = ck; celebrateUntil = Date.now() + CELEBRATE;+ clearTimeout(celebrateTimer);+ celebrateTimer = setTimeout(function () { celebrateKey = null; render(); }, CELEBRATE + 20);+ }+ // the peeked item went away: show the next one, or close+ if (open === 'peek' && !findNeed(peekKey)) {+ var next = needs()[0];+ if (next) { peekKey = key(next.p, next.id); render(true); return; }+ close(true); render(); return;+ }+ render();+ }++ function finish(msg, k) {+ msg = msg || {};+ if (msg.op === 'ask') {+ if (msg.id !== ask.cid) return;+ clearTimeout(ask.timer);+ if (msg.ok) { ask.sent = { p: ask.to.p, name: ask.to.name, cid: ask.cid, until: Date.now() + SENT_FOR }; ask.text = ''; setTimeout(render, SENT_FOR + 20); }+ else ask.failed = true;+ ask.cid = null;+ render();+ return;+ }+ // find the item by the op's id (Rust only echoes an id the page sent)+ if (!k) Object.keys(busy).forEach(function (b) { if (b.slice(b.indexOf('#') + 1) === msg.id && busy[b].op === msg.op) k = b; });+ if (!k || !busy[k]) return;+ clearTimeout(busy[k].timer);+ delete busy[k];+ if (msg.ok) {+ settled[k] = true;+ if (open === 'peek' && peekKey === k) {+ var next = needs()[0];+ if (next) { peekKey = key(next.p, next.id); render(true); return; }+ close(true); return;+ }+ } else {+ failed[k] = true;+ }+ render();+ }++ document.addEventListener('keydown', function (e) {+ if (e.key === 'Escape') { e.preventDefault(); close(true); }+ });+ document.addEventListener('focusin', function () { focused = true; clearTimeout(leaveTimer); });+ document.addEventListener('focusout', function () { focused = false; });+ // a click on the shadow margin is a click outside+ stage.addEventListener('mousedown', function (e) { if (e.target === stage && open) close(true); });++ window.kwantPerch = { update: update, done: function (m) { finish(m); }, collapse: function () { close(false); } };+ send('ready');+})();diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rsindex de716d74..85061c5e 100644--- a/apps/mac/src/main.rs+++ b/apps/mac/src/main.rs@@ -17,6 +17,8 @@ mod nudge_linux;mod nudge_mac;#[cfg(windows)]mod nudge_windows;+mod perch;+mod perch_window;mod picker;mod places;mod redact;@@ -252,10 +254,13 @@ struct Shared {picker: Mutex<picker::PickerState>,/// The pages' picker asks, at most one a second per window.asks: Mutex<switcher::RateLimit>,+ /// The perch: its settings, the places' glances and its page (`perch_window.rs`).+ perch: Mutex<perch_window::PerchState>,}impl Shared {fn new(data_dir: PathBuf, config: kwnt::Config, places: Places) -> Shared {+ let perch = Mutex::new(perch_window::PerchState::new(&data_dir));Shared {data_dir,config,@@ -273,6 +278,7 @@ impl Shared {elsewhere: Mutex::new(None),picker: Mutex::new(picker::PickerState::default()),asks: Mutex::new(switcher::RateLimit::default()),+ perch,}}}@@ -322,6 +328,13 @@ fn main() {// (macOS does this itself: a second click on the app reaches RunEvent::Reopen.)#[cfg(not(target_os = "macos"))]let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| show_last(app)));+ // The perch's global shortcut. Not on Wayland, and on Linux only with an X display: the+ // plugin's setup fails without one, and that would stop the app (perch_window.rs).+ let builder = if !demo && perch_window::shortcut_plugin_ok() {+ builder.plugin(tauri_plugin_global_shortcut::Builder::new().build())+ } else {+ builder+ };let app = builder.plugin(tauri_plugin_updater::Builder::new().build()).plugin(tauri_plugin_dialog::init())@@ -348,6 +361,7 @@ fn main() {});}build_tray(handle)?;+ perch_window::apply_shortcut(handle);if demo {// hidden, so the pill shows (it never covers a focused kwant window); a click on// the pill shows it@@ -383,6 +397,10 @@ fn main() {WindowEvent::Focused(false) if window.label() == switcher::PICKER_WINDOW => {picker::blurred(window.app_handle());}+ // a click outside the perch closes what the shortcut or Quick ask opened+ WindowEvent::Focused(false) if window.label() == perch::WINDOW => {+ perch_window::blurred(window.app_handle());+ }_ => {}}).build(tauri::generate_context!())@@ -1205,6 +1223,8 @@ fn set_window_menu(app: &AppHandle, places: &[Place]) {if let Some(window) = bar.get(tauri::menu::WINDOW_SUBMENU_ID).and_then(|k| k.as_submenu().cloned()) {window.append(&PredefinedMenuItem::separator(app)?)?;window.append(&MenuItem::with_id(app, "switch_place", "Switch place…", true, Some("CmdOrCtrl+Shift+O"))?)?;+ // the perch's own shortcut is global (⌥⌘K), so this item names none+ window.append(&MenuItem::with_id(app, "perch", "Open the perch", true, None::<&str>)?)?;for (i, place) in places.iter().enumerate() {let accel = (i < 9).then(|| format!("CmdOrCtrl+{}", i + 1));let text = match place {@@ -1246,6 +1266,10 @@ fn on_menu(app: &AppHandle, id: &str) {}wake(app);}+ "perch" => {+ let app = app.clone();+ std::thread::spawn(move || perch_window::toggle(&app));+ }"add" => show_connect(app),"this_mac" => {let on = !current(app).this_mac;@@ -1311,6 +1335,9 @@ fn build_tray(handle: &AppHandle) -> tauri::Result<()> {let mut status: HashMap<String, menu::Status> = HashMap::new();// what each place said last, so a missed poll doesn't make its items new againlet mut last: HashMap<String, nudge::Waiting> = HashMap::new();+ // the perch's view of each place (GET /api/glance), polled only while it is on+ let mut glances = perch_window::Caches::new();+ let local_client = remote::client();#[cfg(target_os = "macos")]let mut window_menu: Option<Vec<String>> = None;loop {@@ -1377,6 +1404,19 @@ fn build_tray(handle: &AppHandle) -> tauri::Result<()> {*shared.status.lock().unwrap() = status.clone();let counts: Vec<(bool, usize)> = all.iter().map(|p| (*p == Place::ThisMac, status_of(p).count())).collect();picker::set_elsewhere(&app, switcher::waiting_elsewhere(&counts));+ if perch_window::polling(&app) {+ let eager = perch_window::eager(&app);+ let snap = perch_window::snapshot(&all, &mut glances, &last, eager, |place, etag| match place {+ Place::ThisMac => match port {+ Some(port) if !failed => perch_window::local_glance(&local_client, port, etag),+ _ => remote::Glance::Failed,+ },+ Place::Server(_) => polls.get(&place.key()).map_or(remote::Glance::Failed, |p| p.glance(etag)),+ });+ perch_window::on_poll(&app, snap);+ } else {+ glances.clear();+ }*shared.unreachable.lock().unwrap() = all.iter().filter(|p| status_of(p) == menu::Status::Unreachable)@@ -1469,6 +1509,11 @@ impl RemotePoll {};Polled::Ok(collect_waiting(Some(spaces), ok))}++ /// The perch's view of the server, with the same cookie (`poll` reads it).+ fn glance(&self, etag: Option<&str>) -> remote::Glance {+ tauri::async_runtime::block_on(remote::get_glance(&self.client, &self.origin, self.token.as_ref(), etag))+ }}/// What waits for the person in every space (`None`: kwant isn't answering yet).@@ -1868,6 +1913,209 @@ mod tests {let _ = std::fs::remove_dir_all(data_dir);}+ /// Perch settings (`kwant-app://island?…`) are kept only from `main` while it shows This+ /// Mac's own page. A server's window, the picker, Add a server and the perch itself are+ /// ignored before they touch the once-a-second budget, and nothing is saved.+ #[test]+ fn perch_settings_come_only_from_this_mac_s_own_page() {+ let (places, server) = server_place();+ let (app, window, data_dir) = app_with("island-from", MAIN, places);+ let handle = app.handle();+ let before = handle.state::<Shared>().perch.lock().unwrap().prefs;+ let island: Url = "kwant-app://island?mode=off&shortcut=off".parse().unwrap();+ for label in [server.window_label(), switcher::PICKER_WINDOW.into(), CONNECT.into(), perch::WINDOW.into()] {+ for _ in 0..3 {+ assert_eq!(picker::on_app_url(handle, &label, &island), None, "{label}");+ }+ assert!(!route(handle, &server, &island, false), "never loaded");+ }+ // main showing a server's page (or the loading page) can't change them either+ for url in ["https://kwant.example.com/settings", "tauri://localhost/index.html", "http://127.0.0.1:[email protected]/"] {+ window.navigate(url.parse().unwrap()).unwrap();+ assert!(!picker::island(handle, switcher::PerchMode::Off, switcher::PerchShortcut::Off), "{url}");+ }+ assert_eq!(handle.state::<Shared>().perch.lock().unwrap().prefs, before, "unchanged");+ assert!(!nudge::prefs_path(&data_dir).exists(), "nothing saved");+ // This Mac's own Settings page can+ window.navigate("http://127.0.0.1:1/settings".parse().unwrap()).unwrap();+ assert!(picker::island(handle, switcher::PerchMode::Always, switcher::PerchShortcut::Space));+ let now = handle.state::<Shared>().perch.lock().unwrap().prefs;+ assert_eq!((now.mode, now.shortcut), (switcher::PerchMode::Always, switcher::PerchShortcut::Space));+ assert_eq!(perch::Prefs::load(&data_dir), now, "saved");+ let _ = std::fs::remove_dir_all(data_dir);+ }++ /// `main` sends Perch settings at most once a second, on a budget apart from the picker's.+ #[test]+ fn perch_settings_are_taken_at_most_once_a_second() {+ let (app, _window, data_dir) = app("island-rate");+ let handle = app.handle();+ let island: Url = "kwant-app://island?mode=busy&shortcut=k".parse().unwrap();+ assert!(picker::on_app_url(handle, MAIN, &island).is_some(), "the first is taken");+ for _ in 0..50 {+ assert_eq!(picker::on_app_url(handle, MAIN, &island), None, "again within a second: ignored");+ }+ let ask: Url = "kwant-app://places".parse().unwrap();+ assert!(picker::on_app_url(handle, MAIN, &ask).is_some(), "the picker has its own second");+ let _ = std::fs::remove_dir_all(data_dir);+ }++ /// `__KWANT_ISLAND__` goes only to This Mac's page in `main`: never to a server's window,+ /// the picker, Add a server, the perch, or `main` showing anything else.+ #[test]+ fn only_this_mac_s_page_hears_the_perch_settings() {+ let (places, server) = server_place();+ let (app, _window, data_dir) = app_with("island-script", MAIN, places);+ let handle = app.handle();+ let local: Url = "http://127.0.0.1:1/settings".parse().unwrap();+ let remote: Url = "https://kwant.example.com/settings".parse().unwrap();+ let loading: Url = "tauri://localhost/index.html".parse().unwrap();+ let js = perch_window::island_for(handle, MAIN, &local).expect("This Mac's page");+ assert!(js.contains("__KWANT_ISLAND__"), "{js}");+ for (label, url) in [+ (server.window_label(), &remote),+ (server.window_label(), &local),+ (switcher::PICKER_WINDOW.to_string(), &local),+ (CONNECT.to_string(), &local),+ (perch::WINDOW.to_string(), &local),+ (MAIN.to_string(), &remote),+ (MAIN.to_string(), &loading),+ ] {+ assert_eq!(perch_window::island_for(handle, &label, url), None, "{label} at {url}");+ assert_eq!(picker::elsewhere_for(handle, &label, url), None, "{label} at {url}");+ }+ let _ = std::fs::remove_dir_all(data_dir);+ }++ /// The perch is a bundled page in its own window (`perch`), which no capability lists: it+ /// reaches Rust only through `kwant-island://` navigations, never a command.+ #[test]+ fn the_perch_can_call_no_command() {+ let (_app, window, data_dir) = app_with("perch-window", perch::WINDOW, Places::default());+ for from in ["tauri://localhost/perch.html", "http://tauri.localhost/perch.html"] {+ for cmd in COMMANDS {+ let refused = invoke(&window, cmd, from, args());+ assert!(matches!(&refused, Err(serde_json::Value::String(_))), "{cmd} from {from}: {refused:?}");+ }+ }+ nothing_saved(&data_dir);+ let _ = std::fs::remove_dir_all(data_dir);+ }++ /// What the last poll saw on This Mac: an approval the server lets the perch allow, one it+ /// doesn't, and a question with two choices.+ fn perch_snapshot() -> perch::Snapshot {+ let need = |kind, id: &str, inline| perch::Need {+ kind,+ id: id.into(),+ space_id: "spc_default".into(),+ space_name: "Default".into(),+ kwant_name: "Juno".into(),+ avatar: None,+ title: "push the branch".into(),+ since: "2026-11-14T22:00:00Z".into(),+ path: format!("/s/spc_default/b/k1#{id}"),+ inline,+ why_open: String::new(),+ question: None,+ };+ let mut question = need(perch::NeedKind::Question, "q1", false);+ question.question = Some(perch::Question { choices: vec!["Yes".into(), "No".into()], total: 2, allow_text: false });+ perch::Snapshot {+ places: vec![perch::PlaceView {+ key: places::THIS_MAC.into(),+ label: "This Mac".into(),+ this_mac: true,+ off: false,+ current: true,+ glance: perch::Glance {+ needs_count: 3,+ working_count: 0,+ needs: vec![+ need(perch::NeedKind::Approval, "apr-inline", true),+ need(perch::NeedKind::Approval, "apr-full", false),+ question,+ ],+ working: vec![],+ finished: vec![],+ ask: vec![],+ },+ }],+ }+ }++ /// The perch acts only on what its last snapshot shows: Allow once only where the server+ /// said it may, a chip only among the first choices, an unknown or odd address does+ /// nothing, and the same item goes at most once a second.+ #[test]+ fn the_perch_acts_only_on_what_its_snapshot_shows() {+ let (app, _window, data_dir) = app("perch-acts");+ let handle = app.handle();+ perch_window::set_snapshot(handle, perch_snapshot());+ let ask = |u: &str| perch_window::handle(handle, &u.parse::<Url>().unwrap());+ let refused = |op: &'static str, id: &str, code: &'static str| Some((op, id.to_string(), false, code));+ // never sent: not inline, not there, not ours+ assert_eq!(ask("kwant-island://allow?p=0&id=apr-full"), refused("allow", "apr-full", "not_inline"));+ assert_eq!(ask("kwant-island://deny?p=0&id=apr-full"), refused("deny", "apr-full", "not_inline"));+ assert_eq!(ask("kwant-island://allow?p=0&id=q1"), refused("allow", "q1", "not_inline"));+ assert_eq!(ask("kwant-island://allow?p=0&id=apr-gone"), refused("allow", "apr-gone", "gone"));+ assert_eq!(ask("kwant-island://allow?p=1&id=apr-inline"), refused("allow", "apr-inline", "gone"));+ assert_eq!(ask("kwant-island://answer?p=0&id=q1&c=2"), refused("answer", "q1", "not_inline"));+ assert_eq!(ask("kwant-island://answer?p=0&id=apr-inline&c=0"), refused("answer", "apr-inline", "not_inline"));+ assert_eq!(ask("kwant-island://ask?t=0&text=hi&cid=island-abcdef12"), refused("ask", "island-abcdef12", "gone"));+ for odd in [+ "kwant-island://allow?p=0",+ "kwant-island://allow?p=100&id=apr-inline",+ "kwant-island://allow?p=0&id=../../api",+ "kwant-island://resolve?p=0&id=apr-inline",+ "kwant-island://allow?p=x&id=apr-inline",+ "kwant-app://allow?p=0&id=apr-inline",+ "https://kwant.example.com/api/approvals/apr-inline/resolve",+ ] {+ assert_eq!(ask(odd), None, "{odd}");+ }+ assert_eq!(perch_window::probe(handle).1, 0, "nothing in flight");+ assert!(!perch_window::probe(handle).2, "nothing was sent");+ // an inline approval is sent (nothing listens on port 1, so it fails and says so)+ assert_eq!(ask("kwant-island://allow?p=0&id=apr-inline"), Some(("allow", "apr-inline".into(), false, "failed")));+ let (_, in_flight, acted, _) = perch_window::probe(handle);+ assert_eq!((in_flight, acted), (0, true));+ // the same item again within a second: busy, not sent+ for _ in 0..20 {+ assert_eq!(ask("kwant-island://deny?p=0&id=apr-inline"), refused("deny", "apr-inline", "busy"));+ }+ // a chip among the first choices is its own item+ assert_eq!(ask("kwant-island://answer?p=0&id=q1&c=1"), Some(("answer", "q1".into(), false, "failed")));+ nothing_saved(&data_dir);+ let _ = std::fs::remove_dir_all(data_dir);+ }++ /// A `kwant-island://` address is the perch page's alone: from `main` or a server's window it+ /// is never loaded and does nothing.+ #[test]+ fn a_perch_address_from_any_other_window_does_nothing() {+ let (places, server) = server_place();+ let (app, _window, data_dir) = app_with("perch-elsewhere", MAIN, places);+ let handle = app.handle();+ perch_window::set_snapshot(handle, perch_snapshot());+ for u in [+ "kwant-island://allow?p=0&id=apr-inline",+ "kwant-island://ready",+ "kwant-island://focus",+ "kwant-island://open?what=inbox",+ ] {+ let url: Url = u.parse().unwrap();+ for me in [&Place::ThisMac, &server] {+ assert!(!route(handle, me, &url, false), "{u} never loaded");+ assert!(!route(handle, me, &url, true), "{u} nor as a popup");+ }+ }+ std::thread::sleep(std::time::Duration::from_millis(100));+ assert_eq!(perch_window::probe(handle), (false, 0, false, false), "nothing happened");+ nothing_saved(&data_dir);+ let _ = std::fs::remove_dir_all(data_dir);+ }+/// Rigel's F7: Tauri's access check compares only the scheme and the host, so a page at the/// bundled host with a port or a user name gets past it. The command's own check then/// refuses it, and nothing is saved.diff --git a/apps/mac/src/nudge_mac.rs b/apps/mac/src/nudge_mac.rsindex de5fa6b0..e344c9ae 100644--- a/apps/mac/src/nudge_mac.rs+++ b/apps/mac/src/nudge_mac.rs@@ -105,7 +105,7 @@ impl Nudger {}}let _ = self.icon.send(if show && change.play { Icon::Play } else { Icon::Rest(change.count > 0) });- let cmd = if !show || change.count == 0 || crate::kwant_focused(handle) {+ let cmd = if !show || change.count == 0 || crate::kwant_focused(handle) || crate::perch_window::pill_off(handle) {PillCmd::Quiet} else {PillCmd::Update { arrived: change.arrived.clone(), live: change.live.clone() }diff --git a/apps/mac/src/perch.rs b/apps/mac/src/perch.rsnew file mode 100644index 00000000..e0189e32--- /dev/null+++ b/apps/mac/src/perch.rs@@ -0,0 +1,1716 @@+//! The perch (desktop-island/design.md, build-brief.md Part 2): pure rules. No Tauri and no I/O+//! apart from the settings file, so every rule here has a unit test.+//!+//! - **What it shows** comes from each place's `GET /api/glance` (or `/api/away` on an older+//! server). Every string is cleaned and capped here before the page sees it, and the page puts+//! it in with `textContent`.+//! - **What it may ask** comes back as `kwant-island://…` navigations. A thing is named by its+//! place index and its id, and Rust acts only on an id that is in the latest snapshot: Allow+//! once / Deny only for an approval whose `can_allow_inline` is true, a chip only for one of+//! the first 3 choices, a Quick ask only to one of the listed targets.+//! - **Where it hangs** is worked out from the screen's notch metrics, which are checked first.++use crate::nudge;+use crate::switcher::{PerchMode, PerchShortcut};+use serde_json::{json, Value};+use std::collections::{HashMap, HashSet};+use std::path::Path;+use std::time::{Duration, Instant};++/// The perch window's label. It isn't in `capabilities/connect.json`: it can call no command.+pub const WINDOW: &str = "perch";+/// Settings keys in `desktop-app.json` (next to `show_nudges`).+const PREF_MODE: &str = "perch_mode";+const PREF_SHORTCUT: &str = "perch_shortcut";++/// Lists the page gets at most (the server caps them too: impl-server.md).+const MAX_NEEDS: usize = 20;+const MAX_WORKING: usize = 12;+const MAX_FINISHED: usize = 5;+const MAX_ASK: usize = 8;+const MAX_CHOICES: usize = 6;+/// Chips shown for a question (design.md §7.1).+pub const CHIPS: usize = 3;+/// Longest Quick ask (the server's own cap).+pub const ASK_MAX: usize = 8000;+/// Longest `kwant-island://` address read at all (an 8,000-character ask, percent-encoded).+const MAX_URL: usize = 100_000;+/// How long a peek or celebrate stays in the updates the page gets (it shows each one once).+pub const EVENT_CARRY: Duration = Duration::from_secs(10);++// ---------------------------------------------------------------------------------------------+// Settings++/// The perch settings (Settings → App settings → Perch).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Prefs {+ pub mode: PerchMode,+ pub shortcut: PerchShortcut,+}++impl Default for Prefs {+ fn default() -> Prefs {+ Prefs { mode: PerchMode::Busy, shortcut: PerchShortcut::K }+ }+}++impl Prefs {+ /// The saved settings; a missing, unreadable or odd value means the default.+ pub fn load(data_dir: &Path) -> Prefs {+ let saved = std::fs::read_to_string(nudge::prefs_path(data_dir))+ .ok()+ .and_then(|s| serde_json::from_str::<Value>(&s).ok())+ .unwrap_or(Value::Null);+ Prefs::from_json(&saved)+ }++ pub fn from_json(v: &Value) -> Prefs {+ let d = Prefs::default();+ Prefs {+ mode: v[PREF_MODE].as_str().and_then(PerchMode::parse).unwrap_or(d.mode),+ shortcut: v[PREF_SHORTCUT].as_str().and_then(PerchShortcut::parse).unwrap_or(d.shortcut),+ }+ }++ /// Saves the settings, keeping every other key the file holds (`show_nudges`).+ pub fn save(&self, data_dir: &Path) -> std::io::Result<()> {+ let path = nudge::prefs_path(data_dir);+ let mut v = std::fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str::<Value>(&s).ok())+ .filter(|v| v.is_object())+ .unwrap_or_else(|| json!({}));+ v[PREF_MODE] = Value::from(self.mode.as_str());+ v[PREF_SHORTCUT] = Value::from(self.shortcut.as_str());+ std::fs::create_dir_all(data_dir)?;+ let tmp = path.with_extension("json.perch.tmp");+ std::fs::write(&tmp, serde_json::to_vec_pretty(&v).unwrap_or_default())?;+ std::fs::rename(tmp, path)+ }++ /// Whether the perch may show at all (and the Mac pill steps aside).+ pub fn on(&self, available: bool) -> bool {+ available && self.mode != PerchMode::Off+ }++ /// The shortcut to register (none while the mode is Off: Settings disables it then).+ pub fn active_shortcut(&self, available: bool) -> PerchShortcut {+ if self.on(available) {+ self.shortcut+ } else {+ PerchShortcut::Off+ }+ }+}++/// Whether this computer can show a perch: not on Wayland (design.md §8), unless the app runs+/// through XWayland (`GDK_BACKEND=x11`). `os` is `std::env::consts::OS`.+pub fn available(os: &str, wayland_display: Option<&str>, session_type: Option<&str>, gdk_backend: Option<&str>) -> bool {+ if matches!(os, "macos" | "windows") {+ return true;+ }+ let set = |v: Option<&str>| v.is_some_and(|s| !s.trim().is_empty());+ if gdk_backend.is_some_and(|b| b.split(',').next().map(str::trim) == Some("x11")) {+ return true;+ }+ let wayland = session_type.is_some_and(|s| s.trim().eq_ignore_ascii_case("wayland")) || set(wayland_display);+ !wayland+}++/// The global shortcut to register, in the plugin's accelerator words.+pub fn accelerator(shortcut: PerchShortcut, mac: bool) -> Option<&'static str> {+ match (shortcut, mac) {+ (PerchShortcut::K, true) => Some("Alt+Super+K"),+ (PerchShortcut::K, false) => Some("Ctrl+Alt+K"),+ (PerchShortcut::Space, _) => Some("Ctrl+Alt+Space"),+ (PerchShortcut::Off, _) => None,+ }+}++/// The shortcut as the page shows it ("⌥⌘K opens and closes this").+pub fn key_label(shortcut: PerchShortcut, mac: bool) -> Option<&'static str> {+ match (shortcut, mac) {+ (PerchShortcut::K, true) => Some("⌥⌘K"),+ (PerchShortcut::K, false) => Some("Ctrl+Alt+K"),+ (PerchShortcut::Space, true) => Some("⌃⌥Space"),+ (PerchShortcut::Space, false) => Some("Ctrl+Alt+Space"),+ (PerchShortcut::Off, _) => None,+ }+}++// ---------------------------------------------------------------------------------------------+// What a place's kwant says (GET /api/glance)++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NeedKind {+ Approval,+ Question,+ HumanStep,+ Watch,+ Stopped,+}++impl NeedKind {+ fn parse(s: &str) -> Option<NeedKind> {+ Some(match s {+ "approval" => NeedKind::Approval,+ "question" => NeedKind::Question,+ "human_step" => NeedKind::HumanStep,+ "watch" => NeedKind::Watch,+ "stopped" => NeedKind::Stopped,+ _ => return None,+ })+ }+ pub fn as_str(self) -> &'static str {+ match self {+ NeedKind::Approval => "approval",+ NeedKind::Question => "question",+ NeedKind::HumanStep => "human_step",+ NeedKind::Watch => "watch",+ NeedKind::Stopped => "stopped",+ }+ }+}++/// One thing that needs the person.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Need {+ pub kind: NeedKind,+ pub id: String,+ pub space_id: String,+ pub space_name: String,+ pub kwant_name: String,+ pub avatar: Option<String>,+ pub title: String,+ pub since: String,+ pub path: String,+ /// An approval the server lets the perch allow or deny in place.+ pub inline: bool,+ pub why_open: String,+ /// A question's choices (at most 6) and how many it has in all.+ pub question: Option<Question>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Question {+ pub choices: Vec<String>,+ pub total: usize,+ pub allow_text: bool,+}++/// A turn that is running.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Work {+ pub id: String,+ pub kwant_name: String,+ pub avatar: Option<String>,+ pub step: String,+ pub since: String,+ pub path: String,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Check {+ Verified,+ NotChecked,+ Failed,+}++/// Something that just finished.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Done {+ pub id: String,+ pub kwant_name: String,+ pub avatar: Option<String>,+ pub title: String,+ pub unseen: bool,+ pub check: Option<Check>,+ pub path: String,+}++/// A bot the Quick ask may write to.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AskTarget {+ pub kwant_id: String,+ pub name: String,+ pub avatar: Option<String>,+ pub space_id: String,+}++/// One place's glance, cleaned.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Glance {+ pub needs_count: usize,+ pub working_count: usize,+ pub needs: Vec<Need>,+ pub working: Vec<Work>,+ pub finished: Vec<Done>,+ pub ask: Vec<AskTarget>,+}++/// An id as kwant makes them: a UUID or `spc_default`.+pub fn id_ok(s: &str) -> bool {+ !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+}++/// Text for the page: no control or direction-override characters, trimmed, at most `max`+/// characters (cut with "…").+pub fn clean(s: &str, max: usize) -> String {+ let kept: String = s+ .chars()+ .map(|c| if c == '\n' || c == '\r' || c == '\t' { ' ' } else { c })+ .filter(|c| !c.is_control() && !matches!(*c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{200E}' | '\u{200F}' | '\u{FEFF}'))+ .collect();+ let t = kept.trim();+ if t.chars().count() <= max {+ return t.to_string();+ }+ let mut out: String = t.chars().take(max.saturating_sub(1)).collect();+ out.push('…');+ out+}++/// A sprite name (`architect`, `fox`), else `None`: the page then draws the name's creature.+pub fn avatar_ok(v: &Value) -> Option<String> {+ let s = v.as_str()?;+ let ok = !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');+ ok.then(|| s.to_string())+}++/// An in-app path (`/s/spc_default/inbox`): one leading slash, no backslash, no spaces or+/// control characters. Anything else is `None` (the row opens the Inbox instead).+pub fn path_ok(s: &str) -> Option<String> {+ let ok = s.starts_with('/')+ && !s.starts_with("//")+ && s.len() <= 512+ && !s.contains('\\')+ && s.chars().all(|c| c.is_ascii_graphic());+ ok.then(|| s.to_string())+}++/// A timestamp as the server writes them (RFC 3339), else empty.+fn time_ok(v: &Value) -> String {+ let s = v.as_str().unwrap_or("");+ let ok = s.len() <= 40 && s.bytes().all(|b| b.is_ascii_digit() || b"-:.TZ+".contains(&b));+ if ok {+ s.to_string()+ } else {+ String::new()+ }+}++fn s<'a>(v: &'a Value, k: &str) -> &'a str {+ v[k].as_str().unwrap_or("")+}++fn count(v: &Value) -> usize {+ v.as_u64().map(|n| n.min(1_000_000) as usize).unwrap_or(0)+}++fn space_or_default(v: &Value) -> String {+ let id = s(v, "space_id");+ if id_ok(id) {+ id.to_string()+ } else {+ "spc_default".to_string()+ }+}++/// Reads a `/api/glance` answer. `None`: not a glance (the place is shown as before).+pub fn parse_glance(body: &str) -> Option<Glance> {+ let v: Value = serde_json::from_str(body).ok()?;+ if !v.is_object() || !v["counts"].is_object() {+ return None;+ }+ let list = |k: &str| v[k].as_array().cloned().unwrap_or_default();+ let needs: Vec<Need> = list("needs_you")+ .iter()+ .filter_map(|n| {+ let kind = NeedKind::parse(s(n, "kind"))?;+ let id = s(n, "id");+ if !id_ok(id) {+ return None;+ }+ let space_id = space_or_default(n);+ let approval = &n["approval"];+ let inline = kind == NeedKind::Approval && approval["can_allow_inline"].as_bool() == Some(true);+ let question = (kind == NeedKind::Question && n["question"].is_object()).then(|| {+ let q = &n["question"];+ let choices: Vec<String> = q["choices"]+ .as_array()+ .map(|a| a.iter().filter_map(Value::as_str).map(|c| clean(c, 60)).take(MAX_CHOICES).collect())+ .unwrap_or_default();+ let total = q["choices_total"].as_u64().map(|t| t as usize).unwrap_or(choices.len());+ Question { total: total.max(choices.len()).min(1000), choices, allow_text: q["allow_text"].as_bool() == Some(true) }+ });+ Some(Need {+ kind,+ id: id.to_string(),+ path: path_ok(s(n, "path")).unwrap_or_else(|| nudge::inbox_path(Some(&space_id))),+ space_id,+ space_name: clean(s(n, "space_name"), 60),+ kwant_name: clean(s(n, "kwant_name"), 60),+ avatar: avatar_ok(&n["avatar"]),+ title: clean(s(n, "title"), 120),+ since: time_ok(&n["since"]),+ inline,+ why_open: clean(approval["why_open"].as_str().unwrap_or(""), 120),+ question,+ })+ })+ .take(MAX_NEEDS)+ .collect();+ let working: Vec<Work> = list("working")+ .iter()+ .filter_map(|w| {+ let id = s(w, "turn_id");+ if !id_ok(id) {+ return None;+ }+ let space_id = space_or_default(w);+ let since = Some(time_ok(&w["step_started_at"])).filter(|t| !t.is_empty()).unwrap_or_else(|| time_ok(&w["started_at"]));+ Some(Work {+ id: id.to_string(),+ kwant_name: clean(s(w, "kwant_name"), 60),+ avatar: avatar_ok(&w["avatar"]),+ step: clean(s(w, "step"), 80),+ since,+ path: path_ok(s(w, "path")).unwrap_or_else(|| nudge::inbox_path(Some(&space_id))),+ })+ })+ .take(MAX_WORKING)+ .collect();+ let finished: Vec<Done> = list("finished")+ .iter()+ .filter_map(|f| {+ let id = s(f, "id");+ if !id_ok(id) {+ return None;+ }+ let space_id = space_or_default(f);+ let check = match f["check"]["status"].as_str() {+ Some("verified") => Some(Check::Verified),+ Some("not_checked") => Some(Check::NotChecked),+ Some("failed") => Some(Check::Failed),+ _ => None,+ };+ Some(Done {+ id: id.to_string(),+ kwant_name: clean(s(f, "kwant_name"), 60),+ avatar: avatar_ok(&f["avatar"]),+ title: clean(s(f, "title"), 120),+ unseen: f["unseen"].as_bool() == Some(true),+ check,+ path: path_ok(s(f, "path")).unwrap_or_else(|| nudge::inbox_path(Some(&space_id))),+ })+ })+ .take(MAX_FINISHED)+ .collect();+ let ask: Vec<AskTarget> = list("ask_targets")+ .iter()+ .filter_map(|a| {+ let id = s(a, "kwant_id");+ let space = s(a, "space_id");+ let name = clean(s(a, "name"), 60);+ (id_ok(id) && id_ok(space) && !name.is_empty()).then(|| AskTarget {+ kwant_id: id.to_string(),+ name,+ avatar: avatar_ok(&a["avatar"]),+ space_id: space.to_string(),+ })+ })+ .take(MAX_ASK)+ .collect();+ let c = &v["counts"];+ Some(Glance {+ needs_count: count(&c["needs_you"]).max(needs.len()),+ working_count: count(&c["working"]).max(working.len()),+ needs,+ working,+ finished,+ ask,+ })+}++/// What an older server (no `/api/glance`) still tells: what waits, from `/api/away`. Nothing+/// in it can be settled in the perch: every item is "Open in kwant".+pub fn from_waiting(w: &nudge::Waiting) -> Glance {+ let needs: Vec<Need> = w+ .items+ .iter()+ .filter(|i| id_ok(&i.id))+ .map(|i| {+ let space_id = i.space_id.clone().filter(|s| id_ok(s)).unwrap_or_else(|| "spc_default".into());+ Need {+ kind: match i.kind {+ nudge::Kind::Approval => NeedKind::Approval,+ nudge::Kind::Question => NeedKind::Question,+ },+ id: i.id.clone(),+ path: path_ok(&nudge::target_path(i)).unwrap_or_else(|| nudge::inbox_path(Some(&space_id))),+ space_id,+ space_name: String::new(),+ kwant_name: clean(&i.kwant_name, 60),+ avatar: None,+ title: clean(&i.title, 120),+ since: String::new(),+ inline: false,+ why_open: String::new(),+ question: None,+ }+ })+ .take(MAX_NEEDS)+ .collect();+ Glance { needs_count: w.count.max(needs.len()), needs, ..Glance::default() }+}++// ---------------------------------------------------------------------------------------------+// Every place at once++/// One place as the perch sees it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PlaceView {+ /// `this_mac` or a server's origin (as `places::Place::key`).+ pub key: String,+ /// "This Mac" / "This computer", or the host.+ pub label: String,+ pub this_mac: bool,+ /// The place didn't answer (or is signed out).+ pub off: bool,+ pub current: bool,+ pub glance: Glance,+}++/// What every place said at the last poll. Asks from the page are checked against this.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Snapshot {+ pub places: Vec<PlaceView>,+}++impl Snapshot {+ /// Everything that needs the person, newest first, as (place index, need).+ pub fn needs(&self) -> Vec<(usize, &Need)> {+ let mut all: Vec<(usize, &Need)> =+ self.places.iter().enumerate().flat_map(|(p, v)| v.glance.needs.iter().map(move |n| (p, n))).collect();+ // newest first; items with no time keep their order after the dated ones+ all.sort_by(|a, b| b.1.since.cmp(&a.1.since));+ all+ }++ pub fn working(&self) -> Vec<(usize, &Work)> {+ self.places.iter().enumerate().flat_map(|(p, v)| v.glance.working.iter().map(move |w| (p, w))).collect()+ }++ /// Unseen first, then the rest.+ pub fn finished(&self) -> Vec<(usize, &Done)> {+ let mut all: Vec<(usize, &Done)> =+ self.places.iter().enumerate().flat_map(|(p, v)| v.glance.finished.iter().map(move |f| (p, f))).collect();+ all.sort_by_key(|(_, f)| !f.unseen);+ all+ }++ /// The Quick ask list: This Mac's bots first, then each place's, at most 8.+ pub fn ask_targets(&self) -> Vec<(usize, &AskTarget)> {+ self.places+ .iter()+ .enumerate()+ .flat_map(|(p, v)| v.glance.ask.iter().map(move |a| (p, a)))+ .take(MAX_ASK)+ .collect()+ }++ pub fn needs_count(&self) -> usize {+ self.places.iter().map(|p| p.glance.needs_count).sum()+ }++ pub fn working_count(&self) -> usize {+ self.places.iter().map(|p| p.glance.working_count).sum()+ }++ /// Nothing needs the person and nobody is working.+ pub fn quiet(&self) -> bool {+ self.needs_count() == 0 && self.working_count() == 0+ }++ fn need(&self, p: usize, id: &str) -> Option<&Need> {+ self.places.get(p)?.glance.needs.iter().find(|n| n.id == id)+ }+}++/// What the page asked for through `kwant-island://`.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PerchAsk {+ /// The page loaded and can take updates.+ Ready,+ /// What the page needs: its state and content size (CSS px, without the margin).+ Size { state: PageState, w: u32, h: u32 },+ /// Allow once / Deny an approval.+ Allow { p: usize, id: String },+ Deny { p: usize, id: String },+ /// A question's chip.+ Answer { p: usize, id: String, choice: usize },+ /// Open a thing (a need, a turn, a finish) in its place's window.+ Open { p: usize, id: String },+ /// Open one of the fixed pages.+ OpenPage(Page),+ /// Send a Quick ask to target `t` (an index into the snapshot's ask list).+ Ask { t: usize, text: String, cid: String },+ /// Switch to place `i`; `Places`: the picker (the "+N" chip).+ Place { i: usize },+ Places,+ /// Quick ask was clicked: the panel may take keys now.+ Focus,+ /// Esc, a click outside, the time ran out.+ Collapse,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Page {+ /// "and N more · Open Inbox"+ Inbox,+ /// "and N more · Open Live now"+ Live,+ /// "and N more · Open Activity"+ Activity,+ /// "Open kwant"+ App,+}++/// The page's state, as it reports it with its size.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PageState {+ /// Nothing to show: the window hides.+ Hidden,+ Rest,+ Celebrate,+ Peek,+ Expanded,+}++impl PageState {+ fn parse(s: &str) -> Option<PageState> {+ Some(match s {+ "hidden" => PageState::Hidden,+ "rest" => PageState::Rest,+ "celebrate" => PageState::Celebrate,+ "peek" => PageState::Peek,+ "expanded" => PageState::Expanded,+ _ => return None,+ })+ }+ /// Open states get the 24 px shadow margin and may take clicks into Quick ask.+ pub fn open(self) -> bool {+ matches!(self, PageState::Peek | PageState::Expanded)+ }+}++fn split_query(rest: &str) -> (&str, &str) {+ let rest = rest.split('#').next().unwrap_or("");+ rest.split_once('?').unwrap_or((rest, ""))+}++fn param<'a>(query: &'a str, name: &str) -> Option<&'a str> {+ query.split('&').find_map(|pair| {+ let (k, v) = pair.split_once('=').unwrap_or((pair, ""));+ (k == name).then_some(v)+ })+}++/// Digits only, at most `len` of them.+fn small_number(s: &str, len: usize) -> Option<usize> {+ if s.is_empty() || s.len() > len || !s.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ s.parse().ok()+}++/// Percent-decodes a query value (`+` is a space) into UTF-8; `None` for broken escapes or bytes.+pub fn decode(s: &str) -> Option<String> {+ let b = s.as_bytes();+ let mut out = Vec::with_capacity(b.len());+ let mut i = 0;+ while i < b.len() {+ match b[i] {+ b'%' => {+ let hex = |c: u8| (c as char).to_digit(16);+ let hi = hex(*b.get(i + 1)?)?;+ let lo = hex(*b.get(i + 2)?)?;+ out.push((hi * 16 + lo) as u8);+ i += 3;+ }+ b'+' => {+ out.push(b' ');+ i += 1;+ }+ c => {+ out.push(c);+ i += 1;+ }+ }+ }+ String::from_utf8(out).ok()+}++/// Reads a `kwant-island://` address. `None`: not one we know (refused and ignored).+pub fn parse_perch(url: &str) -> Option<PerchAsk> {+ if url.len() > MAX_URL {+ return None;+ }+ let rest = url.strip_prefix("kwant-island://")?;+ let (host, q) = split_query(rest);+ let thing = || -> Option<(usize, String)> {+ let p = small_number(param(q, "p")?, 2)?;+ let id = param(q, "id")?;+ id_ok(id).then(|| (p, id.to_string()))+ };+ Some(match host.trim_end_matches('/') {+ "ready" => PerchAsk::Ready,+ "size" => {+ let state = PageState::parse(param(q, "s")?)?;+ let w = small_number(param(q, "w")?, 4)? as u32;+ let h = small_number(param(q, "h")?, 4)? as u32;+ PerchAsk::Size { state, w, h }+ }+ "allow" => {+ let (p, id) = thing()?;+ PerchAsk::Allow { p, id }+ }+ "deny" => {+ let (p, id) = thing()?;+ PerchAsk::Deny { p, id }+ }+ "answer" => {+ let (p, id) = thing()?;+ let choice = small_number(param(q, "c")?, 1)?;+ PerchAsk::Answer { p, id, choice }+ }+ "open" => match param(q, "what") {+ Some("inbox") => PerchAsk::OpenPage(Page::Inbox),+ Some("live") => PerchAsk::OpenPage(Page::Live),+ Some("activity") => PerchAsk::OpenPage(Page::Activity),+ Some("app") => PerchAsk::OpenPage(Page::App),+ Some(_) => return None,+ None => {+ let (p, id) = thing()?;+ PerchAsk::Open { p, id }+ }+ },+ "ask" => {+ let t = small_number(param(q, "t")?, 1)?;+ let text = decode(param(q, "text")?)?;+ let text = text.trim();+ if text.is_empty() || text.chars().count() > ASK_MAX {+ return None;+ }+ let cid = param(q, "cid")?;+ let tail = cid.strip_prefix("island-")?;+ if tail.len() < 8 || tail.len() > 64 || !tail.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {+ return None;+ }+ PerchAsk::Ask { t, text: text.to_string(), cid: cid.to_string() }+ }+ "place" => PerchAsk::Place { i: small_number(param(q, "i")?, 2)? },+ "places" => PerchAsk::Places,+ "focus" => PerchAsk::Focus,+ "collapse" => PerchAsk::Collapse,+ _ => return None,+ })+}++/// A call to make on a place's kwant, after the ask was checked against the snapshot.+#[derive(Debug, Clone, PartialEq)]+pub struct Call {+ /// The place index in the snapshot (whose window and sign-in it uses).+ pub p: usize,+ pub path: String,+ pub body: Value,+ /// What the page is told when it comes back (`kwantPerch.done({op, id, ok})`).+ pub op: &'static str,+ pub id: String,+}++/// Why an ask was refused (the page shows "Didn't go through. Open it in kwant.").+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Refused {+ /// Not in the latest snapshot (gone, never there, or another place's id).+ NotThere,+ /// In the snapshot, but not something the perch may settle (needs the full card).+ NotInline,+}++/// The call an Allow once / Deny / chip / Quick ask makes, only for a thing in `snap`.+pub fn call_for(snap: &Snapshot, ask: &PerchAsk) -> Result<Call, Refused> {+ match ask {+ PerchAsk::Allow { p, id } | PerchAsk::Deny { p, id } => {+ let need = snap.need(*p, id).ok_or(Refused::NotThere)?;+ if need.kind != NeedKind::Approval || !need.inline {+ return Err(Refused::NotInline);+ }+ let allow = matches!(ask, PerchAsk::Allow { .. });+ Ok(Call {+ p: *p,+ path: format!("/api/approvals/{}/resolve", nudge::encode(id)),+ // never always_allow from the perch+ body: json!({ "decision": if allow { "allow_once" } else { "deny" } }),+ op: if allow { "allow" } else { "deny" },+ id: id.clone(),+ })+ }+ PerchAsk::Answer { p, id, choice } => {+ let need = snap.need(*p, id).ok_or(Refused::NotThere)?;+ let q = need.question.as_ref().filter(|_| need.kind == NeedKind::Question).ok_or(Refused::NotInline)?;+ if *choice >= CHIPS.min(q.choices.len()) || *choice >= q.total {+ return Err(Refused::NotInline);+ }+ Ok(Call {+ p: *p,+ path: format!("/api/questions/{}/answer", nudge::encode(id)),+ body: json!({ "choice": choice }),+ op: "answer",+ id: id.clone(),+ })+ }+ PerchAsk::Ask { t, text, cid } => {+ let targets = snap.ask_targets();+ let (p, target) = targets.get(*t).ok_or(Refused::NotThere)?;+ Ok(Call {+ p: *p,+ path: "/api/glance/ask".to_string(),+ body: json!({ "space_id": target.space_id, "kwant_id": target.kwant_id, "text": text, "client_message_id": cid }),+ op: "ask",+ id: cid.clone(),+ })+ }+ _ => Err(Refused::NotThere),+ }+}++/// Where Open goes: (place index, in-app path). Only for things in `snap`; a page link uses+/// the first place (This Mac when it runs).+pub fn open_target(snap: &Snapshot, ask: &PerchAsk) -> Option<(usize, String)> {+ match ask {+ PerchAsk::Open { p, id } => {+ let g = &snap.places.get(*p)?.glance;+ g.needs+ .iter()+ .find(|n| &n.id == id)+ .map(|n| n.path.clone())+ .or_else(|| g.working.iter().find(|w| &w.id == id).map(|w| w.path.clone()))+ .or_else(|| g.finished.iter().find(|f| &f.id == id).map(|f| f.path.clone()))+ .map(|path| (*p, path))+ }+ PerchAsk::OpenPage(page) => {+ let first = |p: usize, space: Option<&str>| Some((p, nudge::inbox_path(space)));+ match page {+ Page::App => (!snap.places.is_empty()).then(|| (0, "/".to_string())),+ Page::Inbox | Page::Activity => {+ let needs = snap.needs();+ match needs.first() {+ Some((p, n)) => first(*p, Some(&n.space_id)),+ None => (!snap.places.is_empty()).then(|| (0, nudge::inbox_path(None))),+ }+ }+ // there is no Live now page yet: the 4th bot at work's chat (the first not+ // listed), else the Inbox+ Page::Live => match snap.working().get(3) {+ Some((p, w)) => Some((*p, w.path.clone())),+ None => (!snap.places.is_empty()).then(|| (0, nudge::inbox_path(None))),+ },+ }+ }+ _ => None,+ }+}++/// A place-switch ask: the place's key, only for a listed place.+pub fn place_target<'a>(snap: &'a Snapshot, ask: &PerchAsk) -> Option<&'a str> {+ match ask {+ PerchAsk::Place { i } => snap.places.get(*i).map(|p| p.key.as_str()),+ _ => None,+ }+}++// ---------------------------------------------------------------------------------------------+// Peek and celebrate++/// Notices what is new between polls: a new need peeks; a newly seen, unseen finish with a+/// verified check celebrates. A place seen for the first time (app start, a server added) is+/// taken as it is, with no events.+#[derive(Debug, Default)]+pub struct Tracker {+ seen: HashMap<String, (HashSet<String>, HashSet<String>)>,+ peek: Option<(String, String, Instant)>,+ celebrate: Option<(String, String, Instant)>,+}++/// The events the page gets with an update: (place index, id).+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Events {+ pub peek: Option<(usize, String)>,+ pub celebrate: Option<(usize, String)>,+}++impl Tracker {+ /// Takes in a snapshot. `failed`: places whose poll failed this time (their old content+ /// stays in the snapshot; nothing about them is new).+ pub fn update(&mut self, snap: &Snapshot, now: Instant) {+ let keys: HashSet<&str> = snap.places.iter().map(|p| p.key.as_str()).collect();+ self.seen.retain(|k, _| keys.contains(k.as_str()));+ let mut new_need: Option<(String, String, String)> = None; // (since, place, id)+ for place in &snap.places {+ let needs: HashSet<String> = place.glance.needs.iter().map(|n| n.id.clone()).collect();+ let done: HashSet<String> = place.glance.finished.iter().map(|f| f.id.clone()).collect();+ if let Some((old_needs, old_done)) = self.seen.get(&place.key) {+ for n in &place.glance.needs {+ if !old_needs.contains(&n.id) && new_need.as_ref().is_none_or(|(since, _, _)| n.since > *since) {+ new_need = Some((n.since.clone(), place.key.clone(), n.id.clone()));+ }+ }+ for f in &place.glance.finished {+ if !old_done.contains(&f.id) && f.unseen && f.check == Some(Check::Verified) {+ self.celebrate = Some((place.key.clone(), f.id.clone(), now));+ }+ }+ }+ self.seen.insert(place.key.clone(), (needs, done));+ }+ if let Some((_, place, id)) = new_need {+ self.peek = Some((place, id, now));+ }+ }++ /// The events still worth showing (at most `EVENT_CARRY` old, and still in `snap`).+ pub fn events(&self, snap: &Snapshot, now: Instant) -> Events {+ let index = |key: &str| snap.places.iter().position(|p| p.key == key);+ let fresh = |t: &Instant| now.saturating_duration_since(*t) < EVENT_CARRY;+ let peek = self.peek.as_ref().filter(|(_, _, t)| fresh(t)).and_then(|(k, id, _)| {+ let p = index(k)?;+ snap.need(p, id).map(|_| (p, id.clone()))+ });+ let celebrate = self.celebrate.as_ref().filter(|(_, _, t)| fresh(t)).and_then(|(k, id, _)| {+ let p = index(k)?;+ snap.places[p].glance.finished.iter().any(|f| &f.id == id).then(|| (p, id.clone()))+ });+ Events { peek, celebrate }+ }+}++// ---------------------------------------------------------------------------------------------+// What the page gets++/// How the perch hangs on this screen.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum Shape {+ /// Around the notch: notch width and height (pt).+ Notch { w: f64, h: f64 },+ /// A floating tab at the top of the work area.+ Float,+}++/// Everything about the page that isn't the places' content.+#[derive(Debug, Clone, PartialEq)]+pub struct View {+ pub shape: Shape,+ pub mac: bool,+ pub prefs: Prefs,+ /// The shortcut opened it (it stays until Esc, the shortcut again or a click outside).+ pub open_by_key: bool,+ /// Toggle count from the shortcut: each press flips the page between open and closed.+ pub toggles: u64,+}++fn face(name: &str, avatar: &Option<String>) -> Value {+ json!({ "name": name, "avatar": avatar })+}++/// The update for `kwantPerch.update(…)`. Only cleaned values go in, and the page names each+/// thing back by `p` (place index) and `id`.+pub fn page_json(snap: &Snapshot, view: &View, events: &Events) -> Value {+ let multi_place = snap.places.len() > 1;+ let spaces: HashSet<&str> = snap.needs().iter().map(|(_, n)| n.space_id.as_str()).collect();+ let place_label = |p: usize| if multi_place { snap.places[p].label.clone() } else { String::new() };+ let needs: Vec<Value> = snap+ .needs()+ .into_iter()+ .take(MAX_NEEDS)+ .map(|(p, n)| {+ let q = n.question.as_ref();+ json!({+ "p": p, "id": n.id, "kind": n.kind.as_str(),+ "who": face(&n.kwant_name, &n.avatar),+ "title": n.title, "space": n.space_name, "place": place_label(p), "since": n.since,+ "inline": n.kind == NeedKind::Approval && n.inline,+ "why": n.why_open,+ "choices": q.map(|q| q.choices.iter().take(CHIPS.min(q.total)).cloned().collect::<Vec<_>>()).unwrap_or_default(),+ "reply": q.is_some_and(|q| q.total > CHIPS || q.allow_text),+ })+ })+ .collect();+ let working: Vec<Value> = snap+ .working()+ .into_iter()+ .map(|(p, w)| json!({ "p": p, "id": w.id, "who": face(&w.kwant_name, &w.avatar), "step": w.step, "since": w.since }))+ .collect();+ let finished: Vec<Value> = snap+ .finished()+ .into_iter()+ .map(|(p, f)| {+ let check = match f.check {+ Some(Check::Verified) => "verified",+ Some(Check::Failed) => "failed",+ _ => "not_checked",+ };+ json!({ "p": p, "id": f.id, "who": face(&f.kwant_name, &f.avatar), "title": f.title, "check": check, "unseen": f.unseen })+ })+ .collect();+ let ask: Vec<Value> = snap+ .ask_targets()+ .into_iter()+ .enumerate()+ .map(|(t, (p, a))| json!({ "t": t, "p": p, "who": face(&a.name, &a.avatar), "place": place_label(p) }))+ .collect();+ let places: Vec<Value> = if multi_place {+ snap.places+ .iter()+ .enumerate()+ .map(|(i, p)| {+ json!({ "i": i, "kind": if p.this_mac { "mac" } else { "server" }, "name": p.label,+ "current": p.current, "waiting": p.glance.needs_count, "off": p.off })+ })+ .collect()+ } else {+ Vec::new()+ };+ let (shape, notch) = match view.shape {+ Shape::Notch { w, h } => ("notch", json!({ "w": w.round(), "h": h.round() })),+ Shape::Float => ("float", Value::Null),+ };+ json!({+ "shape": shape, "notch": notch, "mac": view.mac,+ "mode": view.prefs.mode.as_str(),+ "key": key_label(view.prefs.active_shortcut(true), view.mac),+ "byKey": view.open_by_key, "toggles": view.toggles,+ "counts": { "needs": snap.needs_count(), "working": snap.working_count() },+ "needs": needs, "working": working, "finished": finished, "ask": ask, "places": places,+ "multiPlace": multi_place, "multiSpace": spaces.len() > 1,+ "peek": events.peek.as_ref().map(|(p, id)| json!({ "p": p, "id": id })),+ "celebrate": events.celebrate.as_ref().map(|(p, id)| json!({ "p": p, "id": id })),+ })+}++/// Whether the window should be on screen, before the page has said anything: hidden in Busy+/// mode when nothing is going on, always hidden when the perch is off.+pub fn wants_window(prefs: &Prefs, available: bool, snap: &Snapshot, open_by_key: bool) -> bool {+ if !prefs.on(available) {+ return false;+ }+ open_by_key || prefs.mode == PerchMode::Always || !snap.quiet()+}++// ---------------------------------------------------------------------------------------------+// Where it hangs++/// A screen's notch as AppKit reports it (points; `None` when the screen has no notch).+#[derive(Debug, Clone, Copy, PartialEq)]+pub struct NotchMetrics {+ /// The screen's width.+ pub screen_w: f64,+ /// `safeAreaInsets.top`.+ pub inset_top: f64,+ /// `auxiliaryTopLeftArea.width` (the menu bar left of the notch).+ pub left_w: f64,+ /// `auxiliaryTopRightArea.width`.+ pub right_w: f64,+}++/// The notch as an offset from the screen's left edge, its width and its height, only when the+/// numbers make sense: finite, a 16–64 pt inset, an 80–400 pt notch, and areas that fit.+pub fn notch(m: &NotchMetrics) -> Option<(f64, f64, f64)> {+ let all = [m.screen_w, m.inset_top, m.left_w, m.right_w];+ if all.iter().any(|v| !v.is_finite() || *v < 0.0) {+ return None;+ }+ if !(16.0..=64.0).contains(&m.inset_top) || m.left_w + m.right_w >= m.screen_w {+ return None;+ }+ let left = m.left_w;+ let w = m.screen_w - m.right_w - m.left_w;+ if !(80.0..=400.0).contains(&w) {+ return None;+ }+ Some((left, w, m.inset_top))+}++/// Ears either side of the notch at rest (design.md §2.1: two 60 pt ears).+pub const EAR: f64 = 60.0;+/// The floating tab's height.+pub const FLOAT_H: f64 = 30.0;+/// The open width, and the shadow margin left, right and below in peek and expanded.+pub const OPEN_W: f64 = 460.0;+pub const MARGIN: f64 = 24.0;+/// The open height the page may ask for.+pub const MIN_H: f64 = 30.0;+pub const MAX_H: f64 = 720.0;+/// The floating tab's widest rest (3 faces, a count, padding).+pub const MAX_REST_W: f64 = 200.0;++/// The perch window's frame in points, relative to the screen's top-left (`screen_w`: the+/// screen's width; `top`: where it hangs, 0 on a notched screen or the work area's top).+/// `content`: the size the page reported for its state.+pub fn frame(shape: Shape, screen_w: f64, notch_left: f64, top: f64, state: PageState, content: (f64, f64)) -> (f64, f64, f64, f64) {+ let ok = |v: f64, lo: f64, hi: f64, d: f64| if v.is_finite() { v.clamp(lo, hi) } else { d };+ let (cw, ch) = content;+ let (centre, w, h) = match (shape, state.open()) {+ (Shape::Notch { w, h }, false) => (notch_left + w / 2.0, w + 2.0 * EAR, h),+ (Shape::Float, false) => (screen_w / 2.0, ok(cw, 40.0, MAX_REST_W, 70.0), FLOAT_H),+ (Shape::Notch { w, h: nh }, true) => (notch_left + w / 2.0, OPEN_W, ok(ch, nh, MAX_H, 120.0)),+ (Shape::Float, true) => (screen_w / 2.0, OPEN_W, ok(ch, MIN_H, MAX_H, 108.0)),+ };+ let margin = if state.open() { MARGIN } else { 0.0 };+ let (fw, fh) = (w + 2.0 * margin, h + margin);+ let x = (centre - fw / 2.0).clamp(0.0, (screen_w - fw).max(0.0));+ (x.round(), top.round(), fw.round(), fh.round())+}++// ---------------------------------------------------------------------------------------------+// One place's glance between polls++/// What a place's glance poll keeps: the last good glance, its ETag, and whether the place+/// answered this time.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct GlanceCache {+ pub etag: Option<String>,+ pub glance: Glance,+ /// It didn't answer (or is signed out, or answered with something unreadable). The last+ /// glance stays, so the perch doesn't flicker over one missed poll.+ pub off: bool,+ /// Polls in a row that came back 304, and rounds skipped since the last poll (the backoff).+ pub unchanged: u32,+ pub skipped: u32,+}++/// Which items have a call in flight or just finished one. An item is busy from the moment its+/// call starts until `every` after that call **ends**, so a slow failure (Windows retries a+/// refused connect for ~2 s) can't be followed by a second send of the same item.+#[derive(Debug, Default)]+pub struct Busy {+ /// `None` while the call is in flight, `Some(when it ended)` after.+ items: HashMap<String, Option<Instant>>,+}++impl Busy {+ /// Starts a call for `key` unless it is in flight or ended less than `every` ago.+ pub fn start(&mut self, key: &str, now: Instant, every: Duration) -> bool {+ self.items.retain(|_, ended| match ended {+ Some(t) => now.saturating_duration_since(*t) < every,+ None => true,+ });+ if self.items.contains_key(key) {+ return false;+ }+ self.items.insert(key.to_string(), None);+ true+ }++ /// The call for `key` ended (either way): it stays busy for `every` from `now`.+ pub fn end(&mut self, key: &str, now: Instant) {+ self.items.insert(key.to_string(), Some(now));+ }+}++/// The longest backoff: a place that keeps answering 304 is asked every 3rd round (15 s).+pub const BACKOFF_MAX: u32 = 3;+/// 304s in a row before each step of the backoff.+pub const BACKOFF_AFTER: u32 = 3;++impl GlanceCache {+ /// Whether to ask this round. Every round while anything changes; after 3 unchanged answers+ /// every 2nd round, after 6 every 3rd. `eager` (the perch is open, or the person just acted+ /// on it) and a place with no ETag or no good answer are always asked.+ pub fn due(&mut self, eager: bool) -> bool {+ let every = if eager || self.etag.is_none() || self.off {+ 1+ } else {+ (1 + self.unchanged / BACKOFF_AFTER).min(BACKOFF_MAX)+ };+ if self.skipped + 1 >= every {+ self.skipped = 0;+ true+ } else {+ self.skipped += 1;+ false+ }+ }++ /// Takes in one answer. `away`: what `/api/away` said this round, used when the place is a+ /// kwant from before the glance (404).+ pub fn take(&mut self, answer: crate::remote::Glance, away: Option<&nudge::Waiting>) {+ use crate::remote::Glance as A;+ match answer {+ A::Fresh { etag, body } => match parse_glance(&body) {+ Some(g) => {+ self.glance = g;+ self.etag = etag;+ self.off = false;+ self.unchanged = 0;+ }+ None => {+ self.etag = None;+ self.off = true;+ }+ },+ A::NotModified if self.etag.is_some() => {+ self.off = false;+ self.unchanged = self.unchanged.saturating_add(1);+ }+ // a 304 to no ETag of ours: odd, so nothing is trusted+ A::NotModified => self.off = true,+ A::Missing => {+ self.etag = None;+ match away {+ Some(w) => {+ self.glance = from_waiting(w);+ self.off = false;+ }+ None => self.off = true,+ }+ }+ A::SignedOut | A::Failed => self.off = true,+ }+ }+}++/// The chat a Quick ask went to (`{"path": "/s/…/b/…"}`), if the answer names a usable one.+pub fn asked_path(body: &str) -> Option<String> {+ let v: Value = serde_json::from_str(body).ok()?;+ path_ok(v["path"].as_str()?)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_glance_poll_keeps_the_last_good_glance() {+ use crate::remote::Glance as A;+ let mut c = GlanceCache::default();+ c.take(A::Fresh { etag: Some("W/\"g-1\"".into()), body: glance_body() }, None);+ assert!(!c.off);+ assert_eq!(c.etag.as_deref(), Some("W/\"g-1\""));+ assert_eq!(c.glance.needs.len(), 3);+ let good = c.glance.clone();+ c.take(A::NotModified, None);+ assert!(!c.off);+ assert_eq!(c.glance, good);+ // a missed poll: off, the glance stays+ c.take(A::Failed, None);+ assert!(c.off);+ assert_eq!(c.glance, good);+ c.take(A::SignedOut, None);+ assert!(c.off);+ // something that isn't a glance: off, and its ETag is dropped+ c.take(A::Fresh { etag: Some("W/\"g-2\"".into()), body: "<html>".into() }, None);+ assert!(c.off);+ assert_eq!(c.etag, None);+ assert_eq!(c.glance, good);+ // a 304 to no ETag of ours isn't trusted+ c.take(A::NotModified, None);+ assert!(c.off);+ }++ #[test]+ fn an_item_stays_busy_until_a_second_after_its_call_ends() {+ let every = Duration::from_secs(1);+ let t0 = Instant::now();+ let mut busy = Busy::default();+ assert!(busy.start("0#apr", t0, every));+ // a slow call: still in flight 2.5 s later, so nothing else for that item+ assert!(!busy.start("0#apr", t0 + Duration::from_millis(2500), every), "in flight");+ assert!(busy.start("0#q1", t0 + Duration::from_millis(10), every), "another item is its own");+ busy.end("0#apr", t0 + Duration::from_secs(3));+ assert!(!busy.start("0#apr", t0 + Duration::from_millis(3100), every), "just ended");+ assert!(!busy.start("0#apr", t0 + Duration::from_millis(3999), every), "still within a second of its end");+ assert!(busy.start("0#apr", t0 + Duration::from_secs(4), every), "a second after it ended");+ // q1 never ended: it is still in flight however long it takes+ assert!(!busy.start("0#q1", t0 + Duration::from_secs(60), every));+ // ended items are forgotten, so the map can't grow without end+ busy.end("0#q1", t0 + Duration::from_secs(60));+ busy.end("0#apr", t0 + Duration::from_secs(60));+ assert!(busy.start("1#x", t0 + Duration::from_secs(62), every));+ assert_eq!(busy.items.len(), 1);+ }++ #[test]+ fn an_unchanged_place_is_asked_less_often_until_it_changes() {+ use crate::remote::Glance as A;+ let mut c = GlanceCache::default();+ let fresh = || A::Fresh { etag: Some("\"g1\"".into()), body: glance_body() };+ // no ETag yet: every round+ assert!(c.due(false));+ c.take(fresh(), None);+ let mut asked = Vec::new();+ for _ in 0..14 {+ let due = c.due(false);+ asked.push(due);+ if due {+ c.take(A::NotModified, None);+ }+ }+ // 3 polls every round, then 3 every 2nd round, then every 3rd (never slower)+ let pattern: String = asked.iter().map(|d| if *d { 'x' } else { '.' }).collect();+ assert_eq!(pattern, "xxx.x.x.x..x..", "{pattern}");+ // open perch (or just acted): every round again+ assert!(c.due(true));+ assert!(c.due(true));+ // a change resets it+ c.take(fresh(), None);+ assert_eq!(c.unchanged, 0);+ assert!(c.due(false));+ assert!(c.due(false));+ // a failed place is asked every round+ c.unchanged = 50;+ c.take(A::Failed, None);+ assert!(c.due(false) && c.due(false));+ }++ #[test]+ fn an_older_kwant_falls_back_to_what_away_said() {+ use crate::remote::Glance as A;+ let mut c = GlanceCache { etag: Some("W/\"g-1\"".into()), ..Default::default() };+ c.take(A::Missing, None);+ assert!(c.off);+ assert_eq!(c.etag, None);+ let w = nudge::Waiting::default();+ c.take(A::Missing, Some(&w));+ assert!(!c.off);+ assert_eq!(c.glance, from_waiting(&w));+ }++ #[test]+ fn a_quick_ask_names_its_chat_only_when_the_path_is_ours() {+ assert_eq!(asked_path(r#"{"path":"/s/spc_default/b/k1","deduped":false}"#).as_deref(), Some("/s/spc_default/b/k1"));+ for body in [r#"{"path":"//evil.example/x"}"#, r#"{"path":"https://evil.example/"}"#, r#"{"path":7}"#, "nope", "{}"] {+ assert_eq!(asked_path(body), None, "{body}");+ }+ }++ fn glance_body() -> String {+ json!({+ "counts": { "needs_you": 3, "working": 2, "finished_unseen": 1 },+ "needs_you": [+ { "kind": "approval", "id": "a1", "space_id": "spc_default", "space_name": "My space", "kwant_id": "k1",+ "kwant_name": "Ben", "avatar": "fox", "title": "Send the invoice", "since": "2026-11-14T21:35:27.000Z",+ "path": "/s/spc_default/b/k1?card=a1", "approval": { "risk": "medium", "can_allow_inline": true, "why_open": null }, "question": null },+ { "kind": "approval", "id": "a2", "space_id": "spc_default", "kwant_name": "Otto", "avatar": null,+ "title": "Pay $420", "since": "2026-11-14T21:30:00.000Z", "path": "/s/spc_default/b/k2?card=a2",+ "approval": { "risk": "high", "can_allow_inline": false, "why_open": "This one involves a payment." } },+ { "kind": "question", "id": "q1", "space_id": "spc_books", "kwant_name": "Ivy", "title": "Which cover?",+ "since": "2026-11-14T21:36:00.000Z", "path": "/s/spc_books/c/ch1?card=q1",+ "question": { "choices": ["Blue", "Sunset", "Neither", "Four", "Five", "Six"], "choices_total": 8, "allow_text": false } }+ ],+ "working": [+ { "turn_id": "t1", "kwant_name": "Nora", "avatar": "architect", "space_id": "spc_default", "step": "Reading acme.com",+ "step_started_at": "2026-11-14T21:30:00Z", "started_at": "2026-11-14T21:20:00Z", "path": "/s/spc_default/b/k3" },+ { "turn_id": "t2", "kwant_name": "Kai", "space_id": "spc_default", "step": "Writing", "path": "//evil.example/x" }+ ],+ "finished": [+ { "kind": "delegation", "id": "f1", "kwant_name": "Kai", "title": "Weekly report", "unseen": true,+ "check": { "status": "verified", "line": "3 of 3" }, "path": "/s/spc_default/b/k4" }+ ],+ "ask_targets": [ { "kwant_id": "k1", "name": "Ben", "avatar": "fox", "space_id": "spc_default" } ]+ })+ .to_string()+ }++ fn snap_one() -> Snapshot {+ Snapshot {+ places: vec![PlaceView {+ key: "this_mac".into(),+ label: "This Mac".into(),+ this_mac: true,+ off: false,+ current: true,+ glance: parse_glance(&glance_body()).unwrap(),+ }],+ }+ }++ #[test]+ fn settings_default_to_busy_and_k_and_keep_other_keys() {+ let dir = std::env::temp_dir().join(format!("perch-prefs-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ assert_eq!(Prefs::load(&dir), Prefs::default());+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(nudge::prefs_path(&dir), r#"{"show_nudges":false,"perch_mode":"weird"}"#).unwrap();+ assert_eq!(Prefs::load(&dir), Prefs::default(), "an odd value is the default");+ let p = Prefs { mode: PerchMode::Always, shortcut: PerchShortcut::Space };+ p.save(&dir).unwrap();+ assert_eq!(Prefs::load(&dir), p);+ let v: Value = serde_json::from_str(&std::fs::read_to_string(nudge::prefs_path(&dir)).unwrap()).unwrap();+ assert_eq!(v["show_nudges"], json!(false), "the nudge setting stays");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn off_means_no_perch_and_no_shortcut() {+ let off = Prefs { mode: PerchMode::Off, shortcut: PerchShortcut::K };+ assert!(!off.on(true));+ assert_eq!(off.active_shortcut(true), PerchShortcut::Off);+ let busy = Prefs::default();+ assert!(busy.on(true));+ assert!(!busy.on(false), "Wayland");+ assert_eq!(busy.active_shortcut(false), PerchShortcut::Off);+ assert_eq!(busy.active_shortcut(true), PerchShortcut::K);+ }++ #[test]+ fn there_is_no_perch_on_wayland() {+ assert!(available("macos", None, None, None));+ assert!(available("windows", Some("wayland-0"), None, None));+ assert!(available("linux", None, Some("x11"), None));+ assert!(!available("linux", Some("wayland-0"), None, None));+ assert!(!available("linux", None, Some("wayland"), None));+ assert!(!available("linux", Some(""), Some("Wayland"), None));+ assert!(available("linux", Some("wayland-0"), Some("wayland"), Some("x11")), "XWayland");+ assert!(available("linux", Some(""), None, None), "an empty WAYLAND_DISPLAY is not Wayland");+ }++ #[test]+ fn shortcuts_have_one_accelerator_and_label_each() {+ assert_eq!(accelerator(PerchShortcut::K, true), Some("Alt+Super+K"));+ assert_eq!(accelerator(PerchShortcut::K, false), Some("Ctrl+Alt+K"));+ assert_eq!(accelerator(PerchShortcut::Space, true), Some("Ctrl+Alt+Space"));+ assert_eq!(accelerator(PerchShortcut::Off, true), None);+ assert_eq!(key_label(PerchShortcut::K, true), Some("⌥⌘K"));+ assert_eq!(key_label(PerchShortcut::Space, true), Some("⌃⌥Space"));+ assert_eq!(key_label(PerchShortcut::K, false), Some("Ctrl+Alt+K"));+ assert_eq!(key_label(PerchShortcut::Off, false), None);+ }++ #[test]+ fn a_glance_is_read_and_cleaned() {+ let g = parse_glance(&glance_body()).unwrap();+ assert_eq!((g.needs_count, g.working_count), (3, 2));+ assert_eq!(g.needs.len(), 3);+ assert!(g.needs[0].inline);+ assert!(!g.needs[1].inline);+ assert_eq!(g.needs[1].why_open, "This one involves a payment.");+ assert_eq!(g.needs[1].avatar, None);+ let q = g.needs[2].question.as_ref().unwrap();+ assert_eq!((q.choices.len(), q.total, q.allow_text), (6, 8, false));+ assert_eq!(g.working[0].since, "2026-11-14T21:30:00Z", "the step's start");+ assert_eq!(g.working[1].path, "/s/spc_default/inbox", "a path to another origin is dropped");+ assert_eq!(g.finished[0].check, Some(Check::Verified));+ assert_eq!(g.ask[0].name, "Ben");+ assert_eq!(parse_glance("not json"), None);+ assert_eq!(parse_glance(r#"{"error":"x"}"#), None);+ assert_eq!(parse_glance(r#"[1,2]"#), None);+ }++ #[test]+ fn hostile_glance_values_are_dropped_or_cut() {+ let body = json!({+ "counts": { "needs_you": -5, "working": "lots" },+ "needs_you": [+ { "kind": "approval", "id": "../../etc", "title": "x" },+ { "kind": "approval", "id": "ok1", "title": "a\u{202E}gnp.exe\u{0007}\nnext", "kwant_name": "<img src=x onerror=alert(1)>",+ "avatar": "<svg onload=alert(1)>", "path": "javascript:alert(1)", "since": "<b>",+ "approval": { "can_allow_inline": "true" } },+ { "kind": "always_allow", "id": "x1" },+ { "kind": "question", "id": "q2", "title": "t".repeat(500), "question": { "choices": [1, "ok", "c".repeat(200)], "choices_total": 1 } }+ ],+ "working": [ { "turn_id": "t 1" } ],+ "ask_targets": [ { "kwant_id": "k1", "name": "", "space_id": "s" }, { "kwant_id": "k2", "name": "Nora", "space_id": "s p" } ]+ })+ .to_string();+ let g = parse_glance(&body).unwrap();+ assert_eq!(g.needs.len(), 2, "a bad id or an unknown kind is skipped");+ let n = &g.needs[0];+ assert_eq!(n.title, "agnp.exe next", "no control or direction override characters");+ assert_eq!(n.kwant_name, "<img src=x onerror=alert(1)>", "kept as text: the page uses textContent");+ assert_eq!(n.avatar, None);+ assert_eq!(n.path, "/s/spc_default/inbox");+ assert_eq!(n.since, "");+ assert!(!n.inline, "only a real true allows inline");+ let q = &g.needs[1];+ assert_eq!(q.title.chars().count(), 120);+ assert!(q.title.ends_with('…'));+ let qq = q.question.as_ref().unwrap();+ assert_eq!(qq.choices.len(), 2, "a non-string choice is skipped");+ assert_eq!(qq.choices[1].chars().count(), 60);+ assert_eq!(qq.total, 2, "the total is never below what is listed");+ assert!(g.working.is_empty());+ assert!(g.ask.is_empty());+ assert_eq!((g.needs_count, g.working_count), (2, 0));+ }++ #[test]+ fn lists_are_capped() {+ let needs: Vec<Value> = (0..50).map(|i| json!({ "kind": "watch", "id": format!("w{i}"), "title": "x" })).collect();+ let body = json!({ "counts": { "needs_you": 50 }, "needs_you": needs }).to_string();+ let g = parse_glance(&body).unwrap();+ assert_eq!(g.needs.len(), MAX_NEEDS);+ assert_eq!(g.needs_count, 50, "the count still says how many");+ }++ #[test]+ fn an_older_server_s_items_can_only_be_opened() {+ let item = nudge::Item {+ kind: nudge::Kind::Approval,+ id: "a9".into(),+ space_id: Some("spc_default".into()),+ kwant_id: "k1".into(),+ kwant_name: "Ben".into(),+ title: "Use Bash".into(),+ thread_id: None,+ channel_id: None,+ direct_kwant_id: None,+ place: "this_mac".into(),+ place_label: String::new(),+ };+ let g = from_waiting(&nudge::Waiting { items: vec![item], count: 4 });+ assert_eq!(g.needs_count, 4);+ assert!(!g.needs[0].inline);+ assert_eq!(g.needs[0].path, "/s/spc_default/b/k1?card=a9");+ let snap = Snapshot {+ places: vec![PlaceView { key: "this_mac".into(), label: "This Mac".into(), this_mac: true, off: false, current: true, glance: g }],+ };+ assert_eq!(call_for(&snap, &PerchAsk::Allow { p: 0, id: "a9".into() }), Err(Refused::NotInline));+ assert_eq!(open_target(&snap, &PerchAsk::Open { p: 0, id: "a9".into() }), Some((0, "/s/spc_default/b/k1?card=a9".into())));+ }++ #[test]+ fn the_page_s_asks_are_parsed_strictly() {+ assert_eq!(parse_perch("kwant-island://ready"), Some(PerchAsk::Ready));+ assert_eq!(parse_perch("kwant-island://allow?p=0&id=a1"), Some(PerchAsk::Allow { p: 0, id: "a1".into() }));+ assert_eq!(parse_perch("kwant-island://deny?p=1&id=a1"), Some(PerchAsk::Deny { p: 1, id: "a1".into() }));+ assert_eq!(parse_perch("kwant-island://answer?p=0&id=q1&c=2"), Some(PerchAsk::Answer { p: 0, id: "q1".into(), choice: 2 }));+ assert_eq!(parse_perch("kwant-island://open?p=0&id=t1"), Some(PerchAsk::Open { p: 0, id: "t1".into() }));+ assert_eq!(parse_perch("kwant-island://open?what=inbox"), Some(PerchAsk::OpenPage(Page::Inbox)));+ assert_eq!(parse_perch("kwant-island://size?s=peek&w=460&h=119"), Some(PerchAsk::Size { state: PageState::Peek, w: 460, h: 119 }));+ assert_eq!(parse_perch("kwant-island://place?i=1"), Some(PerchAsk::Place { i: 1 }));+ assert_eq!(+ parse_perch("kwant-island://ask?t=0&text=Hi%20there%2C%20%F0%9F%91%8B&cid=island-0f8c2a1e-7d"),+ Some(PerchAsk::Ask { t: 0, text: "Hi there, 👋".into(), cid: "island-0f8c2a1e-7d".into() })+ );+ for url in [+ "kwant-island://allow?p=0",+ "kwant-island://allow?id=a1",+ "kwant-island://allow?p=-1&id=a1",+ "kwant-island://allow?p=0&id=a1%27",+ "kwant-island://allow?p=0&id=https://evil",+ "kwant-island://always_allow?p=0&id=a1",+ "kwant-island://answer?p=0&id=q1&c=10",+ "kwant-island://answer?p=0&id=q1",+ "kwant-island://open?what=https://evil.example",+ "kwant-island://open?path=/s/x",+ "kwant-island://size?s=peek&w=460&h=1e3",+ "kwant-island://size?s=huge&w=1&h=1",+ "kwant-island://ask?t=0&text=&cid=island-12345678",+ "kwant-island://ask?t=0&text=%20%20&cid=island-12345678",+ "kwant-island://ask?t=0&text=hi&cid=evil-12345678",+ "kwant-island://ask?t=0&text=hi&cid=island-1",+ "kwant-island://ask?t=0&text=%FF&cid=island-12345678",+ "kwant-island://ask?t=0&text=%2&cid=island-12345678",+ "kwant-island://ask?t=10&text=hi&cid=island-12345678",+ "kwant-places://ready",+ "kwant-app://island?mode=busy&shortcut=k",+ ] {+ assert_eq!(parse_perch(url), None, "{url}");+ }+ let long = format!("kwant-island://ask?t=0&text={}&cid=island-12345678", "a".repeat(ASK_MAX + 1));+ assert_eq!(parse_perch(&long), None, "over 8,000 characters");+ let max = format!("kwant-island://ask?t=0&text={}&cid=island-12345678", "%C3%A9".repeat(ASK_MAX));+ assert!(matches!(parse_perch(&max), Some(PerchAsk::Ask { .. })), "8,000 two-byte characters fit");+ }++ #[test]+ fn allow_once_only_for_an_inline_approval_in_the_snapshot() {+ let snap = snap_one();+ let call = call_for(&snap, &PerchAsk::Allow { p: 0, id: "a1".into() }).unwrap();+ assert_eq!(call.path, "/api/approvals/a1/resolve");+ assert_eq!(call.body, json!({ "decision": "allow_once" }));+ let deny = call_for(&snap, &PerchAsk::Deny { p: 0, id: "a1".into() }).unwrap();+ assert_eq!(deny.body, json!({ "decision": "deny" }));+ // money / risky: the full card only, both ways+ assert_eq!(call_for(&snap, &PerchAsk::Allow { p: 0, id: "a2".into() }), Err(Refused::NotInline));+ assert_eq!(call_for(&snap, &PerchAsk::Deny { p: 0, id: "a2".into() }), Err(Refused::NotInline));+ // not in the snapshot, another place, a question+ assert_eq!(call_for(&snap, &PerchAsk::Allow { p: 0, id: "zzz".into() }), Err(Refused::NotThere));+ assert_eq!(call_for(&snap, &PerchAsk::Allow { p: 1, id: "a1".into() }), Err(Refused::NotThere));+ assert_eq!(call_for(&snap, &PerchAsk::Allow { p: 0, id: "q1".into() }), Err(Refused::NotInline));+ // nothing the page sends can become always_allow+ for ask in [PerchAsk::Allow { p: 0, id: "a1".into() }, PerchAsk::Deny { p: 0, id: "a1".into() }] {+ assert!(!call_for(&snap, &ask).unwrap().body.to_string().contains("always"));+ }+ }++ #[test]+ fn a_chip_answers_only_one_of_the_first_three_choices() {+ let snap = snap_one();+ let call = call_for(&snap, &PerchAsk::Answer { p: 0, id: "q1".into(), choice: 2 }).unwrap();+ assert_eq!(call.path, "/api/questions/q1/answer");+ assert_eq!(call.body, json!({ "choice": 2 }));+ assert_eq!(call_for(&snap, &PerchAsk::Answer { p: 0, id: "q1".into(), choice: 3 }), Err(Refused::NotInline));+ assert_eq!(call_for(&snap, &PerchAsk::Answer { p: 0, id: "a1".into(), choice: 0 }), Err(Refused::NotInline));+ assert_eq!(call_for(&snap, &PerchAsk::Answer { p: 0, id: "q9".into(), choice: 0 }), Err(Refused::NotThere));+ }++ #[test]+ fn a_quick_ask_goes_only_to_a_listed_bot() {+ let snap = snap_one();+ let ask = PerchAsk::Ask { t: 0, text: "Hi".into(), cid: "island-12345678".into() };+ let call = call_for(&snap, &ask).unwrap();+ assert_eq!(call.path, "/api/glance/ask");+ assert_eq!(call.body, json!({ "space_id": "spc_default", "kwant_id": "k1", "text": "Hi", "client_message_id": "island-12345678" }));+ assert_eq!(call_for(&snap, &PerchAsk::Ask { t: 1, text: "Hi".into(), cid: "island-12345678".into() }), Err(Refused::NotThere));+ assert_eq!(call_for(&Snapshot::default(), &ask), Err(Refused::NotThere));+ }++ #[test]+ fn open_uses_the_snapshot_s_path_only() {+ let snap = snap_one();+ assert_eq!(open_target(&snap, &PerchAsk::Open { p: 0, id: "q1".into() }), Some((0, "/s/spc_books/c/ch1?card=q1".into())));+ assert_eq!(open_target(&snap, &PerchAsk::Open { p: 0, id: "t1".into() }), Some((0, "/s/spc_default/b/k3".into())));+ assert_eq!(open_target(&snap, &PerchAsk::Open { p: 0, id: "f1".into() }), Some((0, "/s/spc_default/b/k4".into())));+ assert_eq!(open_target(&snap, &PerchAsk::Open { p: 0, id: "nope".into() }), None);+ assert_eq!(open_target(&snap, &PerchAsk::Open { p: 3, id: "q1".into() }), None);+ assert_eq!(open_target(&snap, &PerchAsk::OpenPage(Page::App)), Some((0, "/".into())));+ // Inbox opens the newest need's space+ assert_eq!(open_target(&snap, &PerchAsk::OpenPage(Page::Inbox)), Some((0, "/s/spc_books/inbox".into())));+ assert_eq!(open_target(&Snapshot::default(), &PerchAsk::OpenPage(Page::App)), None);+ assert_eq!(place_target(&snap, &PerchAsk::Place { i: 0 }), Some("this_mac"));+ assert_eq!(place_target(&snap, &PerchAsk::Place { i: 1 }), None);+ }++ #[test]+ fn a_new_need_peeks_and_a_verified_finish_celebrates_once_primed() {+ let t0 = Instant::now();+ let mut tr = Tracker::default();+ let mut snap = snap_one();+ tr.update(&snap, t0);+ assert_eq!(tr.events(&snap, t0), Events::default(), "what was there at start is not news");+ // a new need and a new verified finish+ let g = &mut snap.places[0].glance;+ let mut n = g.needs[0].clone();+ n.id = "a3".into();+ n.since = "2026-11-14T22:00:00Z".into();+ g.needs.push(n);+ let mut f = g.finished[0].clone();+ f.id = "f2".into();+ g.finished.push(f.clone());+ let mut f3 = f.clone();+ f3.id = "f3".into();+ f3.check = Some(Check::NotChecked);+ g.finished.push(f3);+ tr.update(&snap, t0 + Duration::from_secs(5));+ let ev = tr.events(&snap, t0 + Duration::from_secs(5));+ assert_eq!(ev.peek, Some((0, "a3".into())));+ assert_eq!(ev.celebrate, Some((0, "f2".into())), "a not-checked finish never celebrates");+ // carried for a while, then gone+ assert_eq!(tr.events(&snap, t0 + Duration::from_secs(5) + EVENT_CARRY), Events::default());+ // settled elsewhere: no peek for a thing that left+ tr.update(&snap, t0 + Duration::from_secs(6));+ snap.places[0].glance.needs.retain(|n| n.id != "a3");+ assert_eq!(tr.events(&snap, t0 + Duration::from_secs(6)).peek, None);+ }++ #[test]+ fn a_place_seen_first_brings_no_events() {+ let t0 = Instant::now();+ let mut tr = Tracker::default();+ let mut snap = snap_one();+ tr.update(&snap, t0);+ let mut other = snap.places[0].clone();+ other.key = "https://kwant.example.com".into();+ other.this_mac = false;+ snap.places.push(other);+ tr.update(&snap, t0 + Duration::from_secs(5));+ assert_eq!(tr.events(&snap, t0 + Duration::from_secs(5)), Events::default());+ }++ #[test]+ fn the_page_gets_places_only_with_two_or_more() {+ let view = View { shape: Shape::Float, mac: false, prefs: Prefs::default(), open_by_key: false, toggles: 0 };+ let snap = snap_one();+ let j = page_json(&snap, &view, &Events::default());+ assert_eq!(j["places"], json!([]));+ assert_eq!(j["needs"][0]["place"], json!(""), "no place named with one place");+ assert_eq!(j["needs"][0]["id"], json!("q1"), "newest first");+ assert_eq!(j["needs"][0]["choices"], json!(["Blue", "Sunset", "Neither"]));+ assert_eq!(j["needs"][0]["reply"], json!(true));+ assert_eq!(j["key"], json!("Ctrl+Alt+K"));+ assert_eq!(j["counts"], json!({ "needs": 3, "working": 2 }));+ assert_eq!(j["multiSpace"], json!(true));+ let mut two = snap.clone();+ let mut s = two.places[0].clone();+ s.key = "https://kwant.jumpin.games".into();+ s.label = "kwant.jumpin.games".into();+ s.this_mac = false;+ s.current = false;+ two.places.push(s);+ let j = page_json(&two, &view, &Events { peek: Some((1, "a1".into())), celebrate: None });+ assert_eq!(j["places"].as_array().unwrap().len(), 2);+ assert_eq!(j["places"][1]["kind"], json!("server"));+ assert!(j["needs"].as_array().unwrap().iter().any(|n| n["place"] == json!("kwant.jumpin.games")));+ assert_eq!(j["peek"], json!({ "p": 1, "id": "a1" }));+ assert_eq!(j["ask"].as_array().unwrap().len(), 2);+ // the shortcut label follows the settings; none while Off+ let off = View { prefs: Prefs { mode: PerchMode::Off, shortcut: PerchShortcut::K }, ..view };+ assert_eq!(page_json(&snap, &off, &Events::default())["key"], Value::Null);+ }++ #[test]+ fn busy_mode_hides_when_quiet_and_always_stays() {+ let quiet = Snapshot::default();+ let busy = Prefs::default();+ let always = Prefs { mode: PerchMode::Always, ..busy };+ let off = Prefs { mode: PerchMode::Off, ..busy };+ assert!(!wants_window(&busy, true, &quiet, false));+ assert!(wants_window(&busy, true, &quiet, true), "the shortcut opens it anyway");+ assert!(wants_window(&always, true, &quiet, false));+ assert!(wants_window(&busy, true, &snap_one(), false));+ assert!(!wants_window(&off, true, &snap_one(), true));+ assert!(!wants_window(&always, false, &snap_one(), true), "Wayland");+ }++ #[test]+ fn the_notch_is_read_only_when_it_makes_sense() {+ // MacBook Pro 14": 1512 pt wide, 185 pt notch, 37 pt tall+ let m = NotchMetrics { screen_w: 1512.0, inset_top: 37.0, left_w: 663.5, right_w: 663.5 };+ assert_eq!(notch(&m), Some((663.5, 185.0, 37.0)));+ for bad in [+ NotchMetrics { inset_top: 0.0, ..m },+ NotchMetrics { inset_top: 24.0, left_w: 0.0, right_w: 0.0, ..m },+ NotchMetrics { inset_top: f64::NAN, ..m },+ NotchMetrics { left_w: f64::INFINITY, ..m },+ NotchMetrics { left_w: -1.0, ..m },+ NotchMetrics { left_w: 800.0, right_w: 800.0, ..m },+ NotchMetrics { left_w: 300.0, right_w: 300.0, ..m },+ NotchMetrics { inset_top: 100.0, ..m },+ ] {+ assert_eq!(notch(&bad), None, "{bad:?}");+ }+ }++ #[test]+ fn the_frame_centres_on_the_notch_and_stays_on_screen() {+ let shape = Shape::Notch { w: 185.0, h: 37.0 };+ // rest: notch + two 60 pt ears, no margin, centred on the notch's centre+ assert_eq!(frame(shape, 1512.0, 663.5, 0.0, PageState::Rest, (0.0, 0.0)), (604.0, 0.0, 305.0, 37.0));+ // an off-centre notch is followed+ assert_eq!(frame(shape, 1512.0, 700.0, 0.0, PageState::Rest, (0.0, 0.0)).0, (700.0_f64 + 92.5 - 152.5).round());+ // peek: 460 wide + 24 px margins, height from the page, clamped+ assert_eq!(frame(shape, 1512.0, 663.5, 0.0, PageState::Peek, (460.0, 119.0)), (502.0, 0.0, 508.0, 143.0));+ assert_eq!(frame(shape, 1512.0, 663.5, 0.0, PageState::Expanded, (460.0, 9999.0)).3, MAX_H + MARGIN);+ assert_eq!(frame(shape, 1512.0, 663.5, 0.0, PageState::Expanded, (460.0, 1.0)).3, 37.0 + MARGIN, "never shorter than the notch");+ // floating: centred on the screen, under the menu bar / panel+ assert_eq!(frame(Shape::Float, 1440.0, 0.0, 24.0, PageState::Rest, (106.0, 30.0)), (667.0, 24.0, 106.0, 30.0));+ assert_eq!(frame(Shape::Float, 1440.0, 0.0, 24.0, PageState::Rest, (5000.0, 30.0)).2, MAX_REST_W);+ assert_eq!(frame(Shape::Float, 1440.0, 0.0, 24.0, PageState::Peek, (460.0, 108.0)), (466.0, 24.0, 508.0, 132.0));+ // a tiny screen: pulled back on screen; a NaN size never makes a NaN frame+ let f = frame(Shape::Float, 300.0, 0.0, 0.0, PageState::Expanded, (f64::NAN, f64::NAN));+ assert_eq!(f.0, 0.0);+ assert!(f.3.is_finite());+ }+}diff --git a/apps/mac/src/perch_window.rs b/apps/mac/src/perch_window.rsnew file mode 100644index 00000000..ef78bd0b--- /dev/null+++ b/apps/mac/src/perch_window.rs@@ -0,0 +1,807 @@+//! The perch's window and its talk with the places (desktop-island/design.md, build-brief.md+//! Part 2). The rules are in `perch.rs`; this is the Tauri side.+//!+//! - **The window** `perch` is bundled `loading/perch.html`: no decorations, transparent, always+//! on top, on every Space, never in the taskbar, and never key unless the person clicks into+//! Quick ask or opens it with the shortcut. On a Mac it floats at the status-bar level around+//! the notch (or under the menu bar without one); elsewhere it is a tab at the top of the work+//! area. It is off on Wayland (`perch::available`).+//! - **Its data** comes from the menu's poll (`main.rs` `build_tray`): each place's+//! `GET /api/glance`, with `/api/away`'s answer when a place is too old for it. Only cleaned+//! values reach the page, which puts every string in with `textContent`.+//! - **The page talks back** only by navigating to `kwant-island://…`, which is refused as a+//! navigation and acted on here, and only for things in the latest snapshot (`perch::call_for`).+//! The label `perch` is in no capability file, so the page can call no command.+//! - **Settings** (`kwant-app://island?…`) come only from This Mac's page in `main`+//! (`picker::on_app_url`), and `__KWANT_ISLAND__` goes only there (`island_for`).++use crate::perch::{self, GlanceCache, PageState, PerchAsk, PlaceView, Prefs, Shape, Snapshot, Tracker, View};+use crate::places::{self, Place};+use crate::switcher::{self, PerchMode, PerchShortcut};+use crate::{current, nudge, remote, Goto, Shared, DEMO};+use std::collections::{HashMap, VecDeque};+use std::time::{Duration, Instant};+use tauri::webview::NewWindowResponse;+use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, Runtime, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder};++/// Two shortcut presses this close are one (a key held down repeats).+const TOGGLE_DEBOUNCE: Duration = Duration::from_millis(300);+/// The same item can't be sent again until this long after its last call ended (a double click,+/// or a retry right after a slow failure).+const SAME_ITEM_EVERY: Duration = Duration::from_secs(1);+/// At most this many of the perch's calls in flight at once.+const MAX_IN_FLIGHT: usize = 4;+/// Quick asks remembered for "Open chat".+const ASKED_KEEP: usize = 8;++/// The perch's state, in `Shared`.+pub struct PerchState {+ pub prefs: Prefs,+ /// Whether this computer can show it (not on Wayland).+ pub available: bool,+ /// The page loaded and said `ready`.+ ready: bool,+ snap: Snapshot,+ tracker: Tracker,+ /// What the page reported last: its state and content size (CSS px).+ page: (PageState, f64, f64),+ open_by_key: bool,+ toggles: u64,+ last_toggle: Option<Instant>,+ /// The accelerator registered now.+ shortcut: Option<&'static str>,+ /// The last update the page got (not sent again unchanged).+ last_sent: Option<String>,+ /// Quick asks that went through: (client message id, place index, chat path).+ asked: VecDeque<(String, usize, String)>,+ /// Calls in flight, and when each item was last sent.+ in_flight: usize,+ sent: perch::Busy,+ /// When the person last acted on it (no polling backoff for a while after).+ last_call: Option<Instant>,+}++impl PerchState {+ pub fn new(data_dir: &std::path::Path) -> PerchState {+ let env = |k: &str| std::env::var(k).ok();+ let available = perch::available(+ std::env::consts::OS,+ env("WAYLAND_DISPLAY").as_deref(),+ env("XDG_SESSION_TYPE").as_deref(),+ env("GDK_BACKEND").as_deref(),+ );+ PerchState {+ prefs: Prefs::load(data_dir),+ available,+ ready: false,+ snap: Snapshot::default(),+ tracker: Tracker::default(),+ page: (PageState::Hidden, 0.0, 0.0),+ open_by_key: false,+ toggles: 0,+ last_toggle: None,+ shortcut: None,+ last_sent: None,+ asked: VecDeque::new(),+ in_flight: 0,+ sent: perch::Busy::default(),+ last_call: None,+ }+ }+}++/// Whether the global-shortcut plugin can start here: never on Wayland, and on Linux only with+/// an X display (the plugin's setup fails without one, and that would stop the app).+pub fn shortcut_plugin_ok() -> bool {+ let env = |k: &str| std::env::var(k).ok();+ let available = perch::available(+ std::env::consts::OS,+ env("WAYLAND_DISPLAY").as_deref(),+ env("XDG_SESSION_TYPE").as_deref(),+ env("GDK_BACKEND").as_deref(),+ );+ available && (!cfg!(target_os = "linux") || env("DISPLAY").is_some_and(|d| !d.trim().is_empty()))+}++/// Whether the perch is on (and the Mac pill steps aside). Never in the demo, whose pill CI+/// screenshots.+pub fn on<R: Runtime>(app: &AppHandle<R>) -> bool {+ if DEMO.get().is_some() {+ return false;+ }+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ st.prefs.on(st.available)+}++/// The Mac pill stays away while the perch shows what needs you.+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+pub fn pill_off<R: Runtime>(app: &AppHandle<R>) -> bool {+ on(app)+}++// ---------------------------------------------------------------------------------------------+// Settings++/// `__KWANT_ISLAND__` for a page that just loaded in `label`'s window, if it may have it.+pub fn island_for<R: Runtime>(app: &AppHandle<R>, label: &str, url: &Url) -> Option<String> {+ let port = app.state::<Shared>().local.lock().unwrap().port;+ let (prefs, available) = {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ (st.prefs, st.available)+ };+ switcher::island_script(label, switcher::is_local_page(url.as_str(), port), prefs.mode, prefs.shortcut, available)+}++/// This Mac's page changed the Perch settings (already checked: `main`, This Mac's own page,+/// once a second). Saves them, tells the page, and applies them.+pub fn set_prefs<R: Runtime>(app: &AppHandle<R>, mode: PerchMode, shortcut: PerchShortcut) {+ let prefs = Prefs { mode, shortcut };+ let data_dir = app.state::<Shared>().data_dir.clone();+ {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ if st.prefs == prefs {+ return;+ }+ st.prefs = prefs;+ if !prefs.on(st.available) {+ st.open_by_key = false;+ }+ }+ if let Err(e) = prefs.save(&data_dir) {+ tracing::warn!(error = %e, "couldn't save the Perch settings");+ }+ if let Some(main) = app.get_webview_window(crate::MAIN) {+ if let Some(js) = main.url().ok().and_then(|url| island_for(app, crate::MAIN, &url)) {+ let _ = main.eval(js.as_str());+ }+ }+ apply_shortcut(app);+ refresh(app);+ crate::wake(app);+}++/// Registers the shortcut the settings name (and drops the old one). Without the plugin+/// (Wayland, no display, tests) nothing happens.+pub fn apply_shortcut<R: Runtime>(app: &AppHandle<R>) {+ let want = {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ if DEMO.get().is_some() {+ None+ } else {+ perch::accelerator(st.prefs.active_shortcut(st.available), cfg!(target_os = "macos"))+ }+ };+ let had = app.state::<Shared>().perch.lock().unwrap().shortcut;+ if had == want {+ return;+ }+ let Some(gs) = app.try_state::<tauri_plugin_global_shortcut::GlobalShortcut<R>>() else {+ return;+ };+ if let Some(old) = had {+ if let Err(e) = gs.unregister(old) {+ tracing::info!(error = %e, "couldn't drop the old Perch shortcut");+ }+ }+ let mut now = None;+ if let Some(accel) = want {+ let registered = gs.on_shortcut(accel, |app, _, event| {+ if event.state == tauri_plugin_global_shortcut::ShortcutState::Pressed {+ let app = app.clone();+ std::thread::spawn(move || toggle(&app));+ }+ });+ match registered {+ Ok(()) => now = Some(accel),+ // another app holds it: the perch still works by pointer+ Err(e) => tracing::info!(error = %e, shortcut = accel, "couldn't register the Perch shortcut"),+ }+ }+ app.state::<Shared>().perch.lock().unwrap().shortcut = now;+}++/// The shortcut (or the Window menu's "Open the perch"): opens it expanded with the keyboard,+/// or closes it.+pub fn toggle<R: Runtime>(app: &AppHandle<R>) {+ let open = {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ if !st.prefs.on(st.available) || DEMO.get().is_some() {+ return;+ }+ let now = Instant::now();+ if st.last_toggle.is_some_and(|t| now.saturating_duration_since(t) < TOGGLE_DEBOUNCE) {+ return;+ }+ st.last_toggle = Some(now);+ st.open_by_key = !(st.open_by_key || st.page.0.open());+ st.toggles += 1;+ st.open_by_key+ };+ refresh(app);+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ if open {+ let _ = w.set_focusable(true);+ let _ = w.set_focus();+ } else {+ let _ = w.set_focusable(false);+ }+ }+}++// ---------------------------------------------------------------------------------------------+// Polling++/// Whether the menu's poll should fetch glances this round.+pub fn polling<R: Runtime>(app: &AppHandle<R>) -> bool {+ on(app)+}++/// How long after an Allow once, Deny, chip or Quick ask every place is asked each round.+const EAGER_AFTER_CALL: Duration = Duration::from_secs(15);++/// No backoff while the perch is open or the person just acted on it.+pub fn eager<R: Runtime>(app: &AppHandle<R>) -> bool {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ st.page.0.open() || st.last_call.is_some_and(|t| t.elapsed() < EAGER_AFTER_CALL)+}++/// This Mac's kwant's glance (loopback: no token).+pub fn local_glance(client: &reqwest::Client, port: u16, etag: Option<&str>) -> remote::Glance {+ let Ok(address) = crate::target::parse_address(&format!("http://127.0.0.1:{port}")) else {+ return remote::Glance::Failed;+ };+ tauri::async_runtime::block_on(remote::get_glance(client, &address.origin, None, etag))+}++/// The place's row in the snapshot, from its glance cache.+pub fn view(place: &Place, cache: &GlanceCache) -> PlaceView {+ let (label, this_mac) = match place {+ Place::ThisMac => (places::THIS_MAC_LABEL.to_string(), true),+ Place::Server(origin) => (origin.host(), false),+ };+ PlaceView { key: place.key(), label, this_mac, off: cache.off, current: false, glance: cache.glance.clone() }+}++/// The menu's poll has every place's glance: the perch takes the new snapshot.+pub fn on_poll<R: Runtime>(app: &AppHandle<R>, mut snap: Snapshot) {+ let here = crate::picker::last_place_window(app)+ .and_then(|l| current(app).by_window(&l).map(|p| p.key()));+ for p in &mut snap.places {+ p.current = here.as_deref() == Some(p.key.as_str());+ }+ {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ st.tracker.update(&snap, Instant::now());+ st.snap = snap;+ }+ refresh(app);+}++/// Brings the window in line with the state: made when it is wanted, hidden when it isn't,+/// and the page told what changed.+pub fn refresh<R: Runtime>(app: &AppHandle<R>) {+ if DEMO.get().is_some() {+ return;+ }+ let (wants, update) = {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ let wants = perch::wants_window(&st.prefs, st.available, &st.snap, st.open_by_key);+ let view = View {+ shape: shape_guess(),+ mac: cfg!(target_os = "macos"),+ prefs: st.prefs,+ open_by_key: st.open_by_key,+ toggles: st.toggles,+ };+ let events = st.tracker.events(&st.snap, Instant::now());+ let json = perch::page_json(&st.snap, &view, &events).to_string();+ let update = (st.ready && wants && st.last_sent.as_deref() != Some(json.as_str())).then(|| {+ st.last_sent = Some(json.clone());+ json+ });+ if !wants {+ // the next time it shows, the page gets everything again+ st.last_sent = None;+ }+ (wants, update)+ };+ if !wants {+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ let _ = w.hide();+ }+ return;+ }+ let Some(w) = window(app) else {+ return;+ };+ if let Some(json) = update {+ let _ = w.eval(format!("window.kwantPerch&&kwantPerch.update({json})"));+ }+}++/// The shape the page draws before the window is placed: a notch on a Mac (the real one is+/// measured when it is placed), a tab elsewhere.+fn shape_guess() -> Shape {+ #[cfg(all(target_os = "macos", not(test)))]+ if let Some(s) = mac::last_shape() {+ return s;+ }+ Shape::Float+}++// ---------------------------------------------------------------------------------------------+// The window++/// The perch's window (made hidden the first time).+fn window<R: Runtime>(app: &AppHandle<R>) -> Option<WebviewWindow<R>> {+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ return Some(w);+ }+ let nav_app = app.clone();+ let built = WebviewWindowBuilder::new(app, perch::WINDOW, WebviewUrl::App("perch.html".into()))+ .title("Perch")+ .inner_size(perch::OPEN_W + 2.0 * perch::MARGIN, perch::FLOAT_H)+ .resizable(false)+ .decorations(false)+ .transparent(true)+ .shadow(false)+ .always_on_top(true)+ .visible_on_all_workspaces(true)+ .skip_taskbar(true)+ // never key on its own: it doesn't take the keyboard from the app being typed in+ .focusable(false)+ .focused(false)+ .accept_first_mouse(true)+ .visible(false)+ .on_navigation(move |url| {+ if url.scheme() == "kwant-island" {+ on_perch_url(&nav_app, url);+ return false;+ }+ // only the bundled perch page itself+ crate::links::is_bundled(url)+ })+ .on_new_window(|_, _| NewWindowResponse::Deny)+ .build();+ match built {+ Ok(w) => {+ // never on a test's mock window: its ns_window isn't a real NSWindow+ #[cfg(all(target_os = "macos", not(test)))]+ mac::float_above(&w);+ Some(w)+ }+ Err(e) => {+ tracing::error!(error = %e, "couldn't make the perch");+ None+ }+ }+}++/// The page navigated to `kwant-island://…` (never loaded).+fn on_perch_url<R: Runtime>(app: &AppHandle<R>, url: &Url) {+ let Some(ask) = perch::parse_perch(url.as_str()) else {+ tracing::info!("ignored a perch address the app doesn't know");+ return;+ };+ let app = app.clone();+ // never touch a window inside the webview's own callback+ std::thread::spawn(move || {+ act(&app, ask);+ });+}++/// How a call went, as the page hears it: (op, id, ok, code).+pub type Outcome = (&'static str, String, bool, &'static str);++/// Does what the page asked. A call (Allow once, Deny, a chip, a Quick ask) returns how it went.+fn act<R: Runtime>(app: &AppHandle<R>, ask: PerchAsk) -> Option<Outcome> {+ match ask {+ PerchAsk::Ready => {+ {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ st.ready = true;+ st.last_sent = None;+ }+ refresh(app);+ }+ PerchAsk::Size { state, w, h } => {+ app.state::<Shared>().perch.lock().unwrap().page = (state, w as f64, h as f64);+ place(app, state, (w as f64, h as f64));+ }+ PerchAsk::Focus => {+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ let _ = w.set_focusable(true);+ let _ = w.set_focus();+ }+ }+ PerchAsk::Collapse => {+ app.state::<Shared>().perch.lock().unwrap().open_by_key = false;+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ let _ = w.set_focusable(false);+ }+ refresh(app);+ }+ PerchAsk::Open { .. } | PerchAsk::OpenPage(_) => open(app, &ask),+ PerchAsk::Place { .. } => {+ let key = {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ perch::place_target(&st.snap, &ask).map(str::to_string)+ };+ if let Some(place) = key.and_then(|k| crate::place_by_key(app, &k)) {+ collapse(app);+ crate::picker::switch_from_last(app, &place);+ }+ }+ PerchAsk::Places => {+ collapse(app);+ let from = crate::picker::last_place_window(app);+ crate::picker::open(app, from, None);+ }+ PerchAsk::Allow { .. } | PerchAsk::Deny { .. } | PerchAsk::Answer { .. } | PerchAsk::Ask { .. } => {+ return Some(call(app, &ask));+ }+ }+ None+}++/// The perch page's `kwant-island://` address, handled here and now (tests; the window's own+/// handler does the same on a thread).+#[cfg(test)]+pub fn handle<R: Runtime>(app: &AppHandle<R>, url: &Url) -> Option<Outcome> {+ act(app, perch::parse_perch(url.as_str())?)+}++/// Sets what the last poll saw (tests).+#[cfg(test)]+pub fn set_snapshot<R: Runtime>(app: &AppHandle<R>, snap: Snapshot) {+ app.state::<Shared>().perch.lock().unwrap().snap = snap;+}++/// (ready, calls in flight, acted lately, opened by the shortcut) (tests).+#[cfg(test)]+pub fn probe<R: Runtime>(app: &AppHandle<R>) -> (bool, usize, bool, bool) {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ (st.ready, st.in_flight, st.last_call.is_some(), st.open_by_key)+}++/// Closes the page (after it sent the person somewhere else).+fn collapse<R: Runtime>(app: &AppHandle<R>) {+ app.state::<Shared>().perch.lock().unwrap().open_by_key = false;+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ let _ = w.set_focusable(false);+ let _ = w.eval("window.kwantPerch&&kwantPerch.collapse()");+ }+}++/// The perch lost the keyboard: the page closes what the shortcut opened.+pub fn blurred<R: Runtime>(app: &AppHandle<R>) {+ let by_key = std::mem::take(&mut app.state::<Shared>().perch.lock().unwrap().open_by_key);+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ let _ = w.set_focusable(false);+ if by_key {+ let _ = w.eval("window.kwantPerch&&kwantPerch.collapse()");+ }+ }+}++/// Opens a thing in its place's window, at its page.+fn open<R: Runtime>(app: &AppHandle<R>, ask: &PerchAsk) {+ let target = {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ let found = perch::open_target(&st.snap, ask).map(|(p, path)| (st.snap.places[p].key.clone(), path));+ // "Open chat" after a Quick ask+ found.or_else(|| match ask {+ PerchAsk::Open { p, id } => st+ .asked+ .iter()+ .find(|(cid, ap, _)| cid == id && ap == p)+ .and_then(|(_, p, path)| st.snap.places.get(*p).map(|v| (v.key.clone(), path.clone()))),+ _ => None,+ })+ };+ let Some((key, path)) = target else {+ tracing::info!("the perch asked to open something that isn't there any more");+ return;+ };+ collapse(app);+ if let Some(place) = crate::place_by_key(app, &key) {+ crate::open_place(app, &place, Goto::Path(path));+ }+}++/// Allow once / Deny / a chip / a Quick ask, for a thing in the latest snapshot only.+fn call<R: Runtime>(app: &AppHandle<R>, ask: &PerchAsk) -> Outcome {+ let checked = {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ match perch::call_for(&st.snap, ask) {+ Ok(call) => {+ let key = format!("{}#{}", call.p, call.id);+ if st.in_flight >= MAX_IN_FLIGHT || !st.sent.start(&key, Instant::now(), SAME_ITEM_EVERY) {+ Err((call.op, call.id, "busy"))+ } else {+ st.in_flight += 1;+ st.last_call = Some(Instant::now());+ let place = st.snap.places.get(call.p).map(|v| v.key.clone());+ Ok((call, place, key))+ }+ }+ Err(refused) => {+ let (op, id) = op_of(ask);+ Err((op, id, if refused == perch::Refused::NotInline { "not_inline" } else { "gone" }))+ }+ }+ };+ let (call, key, busy_key) = match checked {+ Ok(c) => c,+ Err((op, id, code)) => {+ tracing::info!(op, code, "the perch's ask was refused");+ done(app, op, &id, false, code);+ return (op, id, false, code);+ }+ };+ let posted = key.and_then(|k| crate::place_by_key(app, &k)).map(|place| post(app, &place, &call.path, &call.body));+ let (ok, code) = match &posted {+ Some(remote::Posted::Ok(body)) => {+ if call.op == "ask" {+ if let Some(path) = perch::asked_path(body) {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ st.asked.push_back((call.id.clone(), call.p, path));+ while st.asked.len() > ASKED_KEEP {+ st.asked.pop_front();+ }+ }+ }+ (true, "ok")+ }+ Some(remote::Posted::Status(409)) => (false, "already"),+ Some(remote::Posted::Status(_)) => (false, "refused"),+ Some(remote::Posted::SignedOut) => (false, "signed_out"),+ Some(remote::Posted::Failed) | None => (false, "failed"),+ };+ {+ let shared = app.state::<Shared>();+ let mut st = shared.perch.lock().unwrap();+ st.in_flight = st.in_flight.saturating_sub(1);+ // busy for a second from now, the call's end, not its start+ st.sent.end(&busy_key, Instant::now());+ st.last_call = Some(Instant::now());+ }+ done(app, call.op, &call.id, ok, code);+ // the next poll shows it answered (or gone)+ crate::wake(app);+ (call.op, call.id, ok, code)+}++fn op_of(ask: &PerchAsk) -> (&'static str, String) {+ match ask {+ PerchAsk::Allow { id, .. } => ("allow", id.clone()),+ PerchAsk::Deny { id, .. } => ("deny", id.clone()),+ PerchAsk::Answer { id, .. } => ("answer", id.clone()),+ PerchAsk::Ask { cid, .. } => ("ask", cid.clone()),+ _ => ("", String::new()),+ }+}++/// Tells the page how a call went. Only our own words and an id the page sent go in.+fn done<R: Runtime>(app: &AppHandle<R>, op: &str, id: &str, ok: bool, code: &str) {+ if let Some(w) = app.get_webview_window(perch::WINDOW) {+ let msg = serde_json::json!({ "op": op, "id": id, "ok": ok, "code": code });+ let _ = w.eval(format!("window.kwantPerch&&kwantPerch.done({msg})"));+ }+}++/// POSTs to a place's kwant: This Mac on loopback (no token), a server with the windows' cookie.+fn post<R: Runtime>(app: &AppHandle<R>, place: &Place, path: &str, body: &serde_json::Value) -> remote::Posted {+ let client = remote::client();+ match place {+ Place::ThisMac => {+ let Some(port) = app.state::<Shared>().local.lock().unwrap().port else {+ return remote::Posted::Failed;+ };+ let Ok(address) = crate::target::parse_address(&format!("http://127.0.0.1:{port}")) else {+ return remote::Posted::Failed;+ };+ tauri::async_runtime::block_on(remote::post_json(&client, &address.origin, None, path, body))+ }+ Place::Server(origin) => {+ let Some(token) = crate::read_token(app, origin) else {+ return remote::Posted::SignedOut;+ };+ tauri::async_runtime::block_on(remote::post_json(&client, origin, Some(&token), path, body))+ }+ }+}++// ---------------------------------------------------------------------------------------------+// Where it hangs++/// Moves and sizes the window for the page's state, and shows or hides it.+fn place<R: Runtime>(app: &AppHandle<R>, state: PageState, content: (f64, f64)) {+ let Some(w) = app.get_webview_window(perch::WINDOW) else {+ return;+ };+ let wants = {+ let shared = app.state::<Shared>();+ let st = shared.perch.lock().unwrap();+ perch::wants_window(&st.prefs, st.available, &st.snap, st.open_by_key)+ };+ if state == PageState::Hidden || !wants {+ let _ = w.hide();+ return;+ }+ let Some(screen) = screen(app, &w) else {+ return;+ };+ let (x, y, fw, fh) = perch::frame(screen.shape, screen.w, screen.notch_left, screen.top, state, content);+ let _ = w.set_size(LogicalSize::new(fw, fh));+ let _ = w.set_position(LogicalPosition::new(screen.x + x, screen.y + y));+ // shown, not focused: the person keeps typing where they were+ let _ = w.show();+}++/// The screen the perch hangs on, in logical points from the primary screen's top-left.+struct Screen {+ shape: Shape,+ /// The screen's (or work area's) left and top edges, and width.+ x: f64,+ y: f64,+ w: f64,+ notch_left: f64,+ /// Where it hangs below `y`.+ top: f64,+}++fn screen<R: Runtime>(app: &AppHandle<R>, perch_window: &WebviewWindow<R>) -> Option<Screen> {+ #[cfg(all(target_os = "macos", not(test)))]+ if let Some(s) = mac::screen(app, perch_window) {+ return Some(s);+ }+ // the work area of the screen the person is on: their last place window's, else the primary+ let monitor = crate::picker::last_place_window(app)+ .and_then(|l| app.get_webview_window(&l))+ .and_then(|w| w.current_monitor().ok().flatten())+ .or_else(|| perch_window.primary_monitor().ok().flatten())?;+ let scale = monitor.scale_factor();+ let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };+ let area = monitor.work_area();+ Some(Screen {+ shape: Shape::Float,+ x: area.position.x as f64 / scale,+ y: area.position.y as f64 / scale,+ w: area.size.width as f64 / scale,+ notch_left: 0.0,+ top: 0.0,+ })+}++/// AppKit: the notch, the status-bar level, every Space. Left out of test builds: the mock+/// runtime's windows aren't NSWindows, and touching one segfaults the test binary.+#[cfg(all(target_os = "macos", not(test)))]+mod mac {+ use super::Screen;+ use crate::perch::{self, NotchMetrics, Shape};+ use objc2::runtime::NSObjectProtocol;+ use objc2::MainThreadMarker;+ use objc2_app_kit::{NSScreen, NSWindow, NSWindowCollectionBehavior};+ use std::sync::Mutex;+ use tauri::{AppHandle, Runtime, WebviewWindow};++ /// NSStatusWindowLevel: above normal and floating windows, like the menu bar's own items.+ const STATUS_LEVEL: isize = 25;++ static LAST: Mutex<Option<Shape>> = Mutex::new(None);++ pub fn last_shape() -> Option<Shape> {+ *LAST.lock().unwrap()+ }++ /// Floats the window at the status-bar level, on every Space and over full-screen apps,+ /// out of ⌘` cycling.+ pub fn float_above<R: Runtime>(w: &WebviewWindow<R>) {+ let Ok(ptr) = w.ns_window() else {+ return;+ };+ let ptr = ptr as usize;+ let _ = w.run_on_main_thread(move || {+ if ptr == 0 || MainThreadMarker::new().is_none() {+ return;+ }+ // SAFETY: Tauri gives the window's live NSWindow, used on the main thread only.+ let window: &NSWindow = unsafe { &*(ptr as *const NSWindow) };+ window.setLevel(STATUS_LEVEL);+ window.setCollectionBehavior(+ NSWindowCollectionBehavior::CanJoinAllSpaces+ | NSWindowCollectionBehavior::Stationary+ | NSWindowCollectionBehavior::IgnoresCycle+ | NSWindowCollectionBehavior::FullScreenAuxiliary,+ );+ window.setHidesOnDeactivate(false);+ });+ }++ /// The main screen's frame, menu bar and notch, read on the main thread.+ pub fn screen<R: Runtime>(app: &AppHandle<R>, w: &WebviewWindow<R>) -> Option<Screen> {+ // AppKit's y runs up from the primary screen's bottom; Tauri's runs down from its top+ let primary = w.primary_monitor().ok().flatten()?;+ let primary_h = primary.size().to_logical::<f64>(primary.scale_factor()).height;+ let (tx, rx) = std::sync::mpsc::channel();+ let _ = app.run_on_main_thread(move || {+ let _ = tx.send(read(primary_h));+ });+ let s = rx.recv_timeout(std::time::Duration::from_secs(2)).ok().flatten()?;+ *LAST.lock().unwrap() = Some(s.shape);+ Some(s)+ }++ fn read(primary_h: f64) -> Option<Screen> {+ let mtm = MainThreadMarker::new()?;+ let screen = NSScreen::mainScreen(mtm)?;+ let f = screen.frame();+ let v = screen.visibleFrame();+ let x = f.origin.x;+ let y = primary_h - (f.origin.y + f.size.height);+ // safeAreaInsets and the auxiliary areas are macOS 12 and later+ let has_notch_api = screen.respondsToSelector(objc2::sel!(safeAreaInsets))+ && screen.respondsToSelector(objc2::sel!(auxiliaryTopLeftArea));+ let notch = has_notch_api+ .then(|| NotchMetrics {+ screen_w: f.size.width,+ inset_top: screen.safeAreaInsets().top,+ left_w: screen.auxiliaryTopLeftArea().size.width,+ right_w: screen.auxiliaryTopRightArea().size.width,+ })+ .and_then(|m| perch::notch(&m));+ Some(match notch {+ Some((left, nw, nh)) => Screen { shape: Shape::Notch { w: nw, h: nh }, x, y, w: f.size.width, notch_left: left, top: 0.0 },+ // no notch: a tab just under the menu bar+ None => {+ let menu_h = (f.origin.y + f.size.height) - (v.origin.y + v.size.height);+ let menu_h = if menu_h.is_finite() { menu_h.clamp(0.0, 64.0) } else { 24.0 };+ Screen { shape: Shape::Float, x, y, w: f.size.width, notch_left: 0.0, top: menu_h }+ }+ })+ }+}++/// The glance caches the menu's poll keeps, one per place key.+pub type Caches = HashMap<String, GlanceCache>;++/// One round of glance polls, given each place's answer (`fetch`), its `/api/away` answer+/// (`away`) and the cache. Returns the snapshot.+pub fn snapshot(+ all: &[Place],+ caches: &mut Caches,+ away: &HashMap<String, nudge::Waiting>,+ eager: bool,+ mut fetch: impl FnMut(&Place, Option<&str>) -> remote::Glance,+) -> Snapshot {+ caches.retain(|k, _| all.iter().any(|p| &p.key() == k));+ let places = all+ .iter()+ .map(|place| {+ let key = place.key();+ let cache = caches.entry(key.clone()).or_default();+ // a place that keeps answering 304 is asked less often (GlanceCache::due)+ if cache.due(eager) {+ let answer = fetch(place, cache.etag.as_deref());+ cache.take(answer, away.get(&key));+ }+ view(place, cache)+ })+ .collect();+ Snapshot { places }+}diff --git a/apps/mac/src/picker.rs b/apps/mac/src/picker.rsindex 0c0bade7..a44eb1f4 100644--- a/apps/mac/src/picker.rs+++ b/apps/mac/src/picker.rs@@ -43,8 +43,17 @@ pub fn on_app_url<R: Runtime>(app: &AppHandle<R>, label: &str, url: &Url) -> Opttracing::info!("ignored a kwant-app address the app doesn't know");return None;};- if !app.state::<Shared>().asks.lock().unwrap().allow(label, Instant::now(), switcher::ASK_EVERY) {- tracing::debug!(window = label, "ignored a second picker ask within a second");+ let key = match &ask {+ // Perch settings: only This Mac's window, on its own budget (its page is checked next)+ AppAsk::Island { .. } if label != MAIN => {+ tracing::info!(window = label, "ignored Perch settings from a window that isn't This Mac's");+ return None;+ }+ AppAsk::Island { .. } => switcher::island_key(label),+ AppAsk::Places { .. } => label.to_string(),+ };+ if !app.state::<Shared>().asks.lock().unwrap().allow(&key, Instant::now(), switcher::ASK_EVERY) {+ tracing::debug!(window = label, "ignored a second ask within a second");return None;}match &ask {@@ -53,10 +62,30 @@ pub fn on_app_url<R: Runtime>(app: &AppHandle<R>, label: &str, url: &Url) -> Opt// never build or show a window inside the webview's own callbackstd::thread::spawn(move || open(&app, Some(label), at));}+ AppAsk::Island { mode, shortcut } => {+ let (app, mode, shortcut) = (app.clone(), *mode, *shortcut);+ std::thread::spawn(move || island(&app, mode, shortcut));+ }}Some(ask)}+/// Perch settings from `main`: kept only while `main` shows This Mac's own page (a server's+/// page loaded there can't change them).+pub fn island<R: Runtime>(app: &AppHandle<R>, mode: switcher::PerchMode, shortcut: switcher::PerchShortcut) -> bool {+ let port = app.state::<Shared>().local.lock().unwrap().port;+ let local = app+ .get_webview_window(MAIN)+ .and_then(|w| w.url().ok())+ .is_some_and(|url| switcher::is_local_page(url.as_str(), port));+ if !switcher::island_allowed(MAIN, local) {+ tracing::info!("ignored Perch settings from a page that isn't This Mac's");+ return false;+ }+ crate::perch_window::set_prefs(app, mode, shortcut);+ true+}+/// The window the person is in: the one that had the keyboard last, while it shows.pub fn last_place_window<R: Runtime>(app: &AppHandle<R>) -> Option<String> {let last = app.state::<Shared>().last_focused.lock().unwrap().clone();@@ -368,6 +397,10 @@ pub fn page_loaded<R: Runtime>(window: &WebviewWindow<R>, url: &Url, event: Pageif let Some(js) = elsewhere_for(window.app_handle(), window.label(), url) {let _ = window.eval(js.as_str());}+ // This Mac's Settings page reads the Perch settings (nothing for any other window or page)+ if let Some(js) = crate::perch_window::island_for(window.app_handle(), window.label(), url) {+ let _ = window.eval(js.as_str());+ }}/// The menu's poll counted what waits in the places other than This Mac: This Mac's page hearsdiff --git a/apps/mac/src/remote.rs b/apps/mac/src/remote.rsindex fa04ca91..cadf2a84 100644--- a/apps/mac/src/remote.rs+++ b/apps/mac/src/remote.rs@@ -240,18 +240,20 @@ pub enum Answer {Failed,}+/// Adds the sign-in cookie (marked sensitive, so it never shows in a debug print). `None`: the+/// token can't be a header value (then the place reads as signed out).+fn with_cookie(request: reqwest::RequestBuilder, token: Option<&Token>) -> Option<reqwest::RequestBuilder> {+ let Some(Token(value)) = token else { return Some(request) };+ let mut header = reqwest::header::HeaderValue::from_str(&format!("{COOKIE}={value}")).ok()?;+ header.set_sensitive(true);+ Some(request.header(reqwest::header::COOKIE, header))+}+/// GET one of kwant's API paths on the server with the sign-in cookie.pub async fn get(client: &reqwest::Client, origin: &Origin, token: Option<&Token>, path: &str) -> Answer {- let mut request = client.get(origin.page(path));- if let Some(Token(value)) = token {- match reqwest::header::HeaderValue::from_str(&format!("{COOKIE}={value}")) {- Ok(mut header) => {- header.set_sensitive(true);- request = request.header(reqwest::header::COOKIE, header);- }- Err(_) => return Answer::SignedOut,- }- }+ let Some(request) = with_cookie(client.get(origin.page(path)), token) else {+ return Answer::SignedOut;+ };let Ok(response) = request.send().await else {return Answer::Failed;};@@ -262,6 +264,92 @@ pub async fn get(client: &reqwest::Client, origin: &Origin, token: Option<&Token}}+/// The most of a glance the app reads (the server's lists are capped: about 40 KB at most).+const GLANCE_LIMIT: usize = 256 * 1024;+/// The most of an answer to the perch's POSTs the app reads.+const POST_LIMIT: usize = 64 * 1024;++/// What `GET /api/glance` gave (the perch's poll, desktop-island/impl-server.md).+#[derive(Debug, PartialEq, Eq)]+pub enum Glance {+ /// A new glance, with its ETag for the next poll (`W/"g-…"`).+ Fresh { etag: Option<String>, body: String },+ /// 304: nothing changed since the ETag sent.+ NotModified,+ /// 404: a kwant from before the glance (the perch falls back to what /api/away said).+ Missing,+ SignedOut,+ Failed,+}++/// An ETag the app sends back: printable ASCII, no comma, at most 64 bytes. Anything else is+/// dropped, so a server can't make the app send odd header bytes.+pub fn etag_ok(s: &str) -> bool {+ !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_graphic() && b != b',')+}++/// `GET {origin}/api/glance`, with `If-None-Match` when the last answer had a usable ETag.+pub async fn get_glance(client: &reqwest::Client, origin: &Origin, token: Option<&Token>, etag: Option<&str>) -> Glance {+ let Some(mut request) = with_cookie(client.get(origin.page("/api/glance")), token) else {+ return Glance::SignedOut;+ };+ if let Some(tag) = etag.filter(|t| etag_ok(t)) {+ request = request.header(reqwest::header::IF_NONE_MATCH, tag);+ }+ let Ok(response) = request.send().await else {+ return Glance::Failed;+ };+ match response.status().as_u16() {+ 200 => {+ let etag = response+ .headers()+ .get(reqwest::header::ETAG)+ .and_then(|v| v.to_str().ok())+ .filter(|t| etag_ok(t))+ .map(str::to_string);+ match body(response, GLANCE_LIMIT, origin).await {+ Ok(body) => Glance::Fresh { etag, body },+ Err(_) => Glance::Failed,+ }+ }+ 304 => Glance::NotModified,+ 404 => Glance::Missing,+ 401 | 403 => Glance::SignedOut,+ _ => Glance::Failed,+ }+}++/// What one of the perch's POSTs gave.+#[derive(Debug, PartialEq, Eq)]+pub enum Posted {+ /// 2xx, with the body (the Quick ask's answer names the chat's path).+ Ok(String),+ /// Another status: 409 already answered or archived, 400, 404.+ Status(u16),+ SignedOut,+ Failed,+}++/// POST a JSON body to one of kwant's API paths with the sign-in cookie. Never logs the body,+/// the token or the answer.+pub async fn post_json(client: &reqwest::Client, origin: &Origin, token: Option<&Token>, path: &str, json: &serde_json::Value) -> Posted {+ let request = client+ .post(origin.page(path))+ .header(reqwest::header::CONTENT_TYPE, "application/json")+ .body(json.to_string());+ let Some(request) = with_cookie(request, token) else {+ return Posted::SignedOut;+ };+ let Ok(response) = request.send().await else {+ return Posted::Failed;+ };+ match response.status().as_u16() {+ 200..=299 => body(response, POST_LIMIT, origin).await.map(Posted::Ok).unwrap_or(Posted::Failed),+ 401 | 403 => Posted::SignedOut,+ code => Posted::Status(code),+ }+}+#[cfg(test)]mod tests {use super::*;@@ -458,4 +546,93 @@ mod tests {assert!(!sign_out(&client(), &origin(&format!("http://127.0.0.1:{port}")), Some(&t)).await);}+ /// A one-shot server that answers with a whole reply and hands back the request it read+ /// (with its body, up to content-length).+ async fn one_reply(reply: String) -> (Origin, tokio::task::JoinHandle<String>) {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let seen = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut buf = vec![0u8; 4096];+ let mut got = Vec::new();+ loop {+ let n = socket.read(&mut buf).await.unwrap();+ if n == 0 {+ break;+ }+ got.extend_from_slice(&buf[..n]);+ let text = String::from_utf8_lossy(&got).to_ascii_lowercase();+ if let Some(end) = text.find("\r\n\r\n") {+ let len = text+ .lines()+ .find_map(|l| l.strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))+ .unwrap_or(0);+ if got.len() >= end + 4 + len {+ break;+ }+ }+ }+ socket.write_all(reply.as_bytes()).await.unwrap();+ String::from_utf8_lossy(&got).into_owned()+ });+ (origin(&format!("http://127.0.0.1:{port}")), seen)+ }++ fn reply(status: &str, headers: &str, body: &str) -> String {+ format!("HTTP/1.1 {status}\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}", body.len())+ }++ #[test]+ fn only_a_plain_etag_is_sent_back() {+ assert!(etag_ok("W/\"g-0123456789abcdef01234567\""));+ for bad in ["", "a b", "a,b", "a\r\nX: y", "a".repeat(65).as_str(), "é"] {+ assert!(!etag_ok(bad), "{bad:?}");+ }+ }++ #[tokio::test]+ async fn the_glance_poll_sends_its_etag_and_reads_the_answer() {+ let t = Token("kd1.TESTONLY".into());+ let (o, seen) = one_reply(reply("200 OK", "etag: W/\"g-abc\"\r\n", r#"{"counts":{}}"#)).await;+ let got = get_glance(&client(), &o, Some(&t), Some("W/\"g-old\"")).await;+ assert_eq!(got, Glance::Fresh { etag: Some("W/\"g-abc\"".into()), body: r#"{"counts":{}}"#.into() });+ let request = seen.await.unwrap().to_ascii_lowercase();+ assert!(request.starts_with("get /api/glance http/1.1\r\n"), "{request}");+ assert!(request.contains("\r\nif-none-match: w/\"g-old\"\r\n"), "{request}");+ assert!(request.contains("\r\ncookie: kwnt_token=kd1.testonly\r\n"), "{request}");+ for (status, want) in [("304 Not Modified", Glance::NotModified), ("404 Not Found", Glance::Missing), ("401 Unauthorized", Glance::SignedOut), ("500 Internal Server Error", Glance::Failed)] {+ let (o, seen) = one_reply(reply(status, "", "")).await;+ assert_eq!(get_glance(&client(), &o, None, Some("bad etag\r\nX: 1")).await, want, "{status}");+ let request = seen.await.unwrap().to_ascii_lowercase();+ assert!(!request.contains("if-none-match"), "an odd ETag is never sent: {request}");+ assert!(!request.contains("cookie"), "no token, no cookie: {request}");+ }+ // an odd ETag from the server isn't kept+ let (o, seen) = one_reply(reply("200 OK", "etag: a,b\r\n", "{}")).await;+ assert_eq!(get_glance(&client(), &o, None, None).await, Glance::Fresh { etag: None, body: "{}".into() });+ seen.await.unwrap();+ }++ #[tokio::test]+ async fn the_perch_posts_json_with_the_cookie_and_reads_the_status() {+ let t = Token("kd1.TESTONLY".into());+ let (o, seen) = one_reply(reply("200 OK", "", r#"{"ok":true}"#)).await;+ let body = serde_json::json!({ "decision": "allow_once" });+ assert_eq!(post_json(&client(), &o, Some(&t), "/api/approvals/a1/resolve", &body).await, Posted::Ok(r#"{"ok":true}"#.into()));+ let request = seen.await.unwrap();+ let lower = request.to_ascii_lowercase();+ assert!(lower.starts_with("post /api/approvals/a1/resolve http/1.1\r\n"), "{request}");+ assert!(lower.contains("\r\ncontent-type: application/json\r\n"), "{request}");+ assert!(lower.contains("\r\ncookie: kwnt_token=kd1.testonly\r\n"), "{request}");+ assert!(!lower.contains("\r\norigin:"), "{request}");+ assert!(request.ends_with(r#"{"decision":"allow_once"}"#), "{request}");+ for (status, want) in [("409 Conflict", Posted::Status(409)), ("404 Not Found", Posted::Status(404)), ("403 Forbidden", Posted::SignedOut)] {+ let (o, seen) = one_reply(reply(status, "", "")).await;+ assert_eq!(post_json(&client(), &o, Some(&t), "/api/glance/ask", &body).await, want, "{status}");+ seen.await.unwrap();+ }+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();+ assert_eq!(post_json(&client(), &origin(&format!("http://127.0.0.1:{port}")), None, "/api/glance/ask", &body).await, Posted::Failed);+ }}diff --git a/apps/mac/src/switcher.rs b/apps/mac/src/switcher.rsindex ae5ecaa2..a232b296 100644--- a/apps/mac/src/switcher.rs+++ b/apps/mac/src/switcher.rs@@ -10,6 +10,9 @@//! - Only This Mac's window (`main`, showing the kwant on 127.0.0.1) learns how many things wait//! in other places (`window.__KWANT_ELSEWHERE__`). A server's page never learns anything about//! any other place.+//! - Perch settings (desktop-island/build-brief.md, Part 2): only This Mac's page learns them+//! (`window.__KWANT_ISLAND__`) and only it may change them (`kwant-app://island?mode=…&shortcut=…`,+//! whitelisted values, at most once a second). The same ask from any other window is ignored.use std::collections::HashMap;use std::time::{Duration, Instant};@@ -39,6 +42,66 @@ const FROM_TOP: f64 = 8.0;pub enum AppAsk {/// Open the picker; `at` is the chip's bottom-left in window (CSS) coordinates, unclamped.Places { at: Option<(f64, f64)> },+ /// Perch settings from This Mac's Settings page (both values are required).+ Island { mode: PerchMode, shortcut: PerchShortcut },+}++/// When the perch shows (design.md §8): "Only when something is happening", "Always", "Off".+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PerchMode {+ Busy,+ Always,+ Off,+}++impl PerchMode {+ pub fn as_str(self) -> &'static str {+ match self {+ PerchMode::Busy => "busy",+ PerchMode::Always => "always",+ PerchMode::Off => "off",+ }+ }+ /// Exactly one of the three words; anything else is `None`.+ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "busy" => Some(PerchMode::Busy),+ "always" => Some(PerchMode::Always),+ "off" => Some(PerchMode::Off),+ _ => None,+ }+ }+}++/// The perch's global shortcut: ⌥⌘K / Ctrl+Alt+K, ⌃⌥Space / Ctrl+Alt+Space, or none.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PerchShortcut {+ K,+ Space,+ Off,+}++impl PerchShortcut {+ pub fn as_str(self) -> &'static str {+ match self {+ PerchShortcut::K => "k",+ PerchShortcut::Space => "space",+ PerchShortcut::Off => "off",+ }+ }+ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "k" => Some(PerchShortcut::K),+ "space" => Some(PerchShortcut::Space),+ "off" => Some(PerchShortcut::Off),+ _ => None,+ }+ }+}++/// The rate-limit key for perch settings from a window (its own budget, apart from the picker's).+pub fn island_key(label: &str) -> String {+ format!("{label}#island")}/// Reads a `kwant-app://` address. `None`: not one we know (it is refused and ignored).@@ -53,6 +116,12 @@ pub fn parse_app(url: &str) -> Option<AppAsk> {let at = query.and_then(|q| param(q, "at")).and_then(parse_at);Some(AppAsk::Places { at })}+ "island" => {+ let q = query?;+ let mode = PerchMode::parse(param(q, "mode")?)?;+ let shortcut = PerchShortcut::parse(param(q, "shortcut")?)?;+ Some(AppAsk::Island { mode, shortcut })+ }_ => None,}}@@ -266,6 +335,26 @@ pub fn elsewhere_script(label: &str, page_is_local: bool, waiting_elsewhere: usi))}+/// Whether a window may read or change perch settings: This Mac's window while it shows This+/// Mac's own kwant. Server windows, the picker, the perch and the loading page may not.+pub fn island_allowed(label: &str, page_is_local: bool) -> bool {+ label == MAIN_WINDOW && page_is_local+}++/// The script that gives This Mac's Settings page the perch settings (`available`: false on+/// Wayland), or `None` for any other window or page.+pub fn island_script(label: &str, page_is_local: bool, mode: PerchMode, shortcut: PerchShortcut, available: bool) -> Option<String> {+ if !island_allowed(label, page_is_local) {+ return None;+ }+ Some(format!(+ "window.__KWANT_ISLAND__=Object.freeze({{mode:\"{}\",shortcut:\"{}\",available:{}}});try{{window.dispatchEvent(new Event('kwant-island'))}}catch(e){{}}",+ mode.as_str(),+ shortcut.as_str(),+ available+ ))+}+/// What waits in the places other than This Mac (`counts`: (is This Mac, count) per place).pub fn waiting_elsewhere(counts: &[(bool, usize)]) -> usize {counts.iter().filter(|(this_mac, _)| !this_mac).map(|(_, n)| *n).sum()@@ -300,9 +389,70 @@ mod tests {#[test]fn unknown_app_asks_are_ignored() {- for url in ["kwant-app://island?mode=off", "kwant-app://", "kwant-app://placesx", "kwant-nudge://open", "https://kwant-app/places"] {+ for url in ["kwant-app://", "kwant-app://placesx", "kwant-app://islandx?mode=off&shortcut=k", "kwant-nudge://open", "https://kwant-app/places"] {+ assert_eq!(parse_app(url), None, "{url}");+ }+ }++ #[test]+ fn perch_settings_take_only_whitelisted_values() {+ assert_eq!(+ parse_app("kwant-app://island?mode=busy&shortcut=k"),+ Some(AppAsk::Island { mode: PerchMode::Busy, shortcut: PerchShortcut::K })+ );+ assert_eq!(+ parse_app("kwant-app://island?shortcut=space&mode=always"),+ Some(AppAsk::Island { mode: PerchMode::Always, shortcut: PerchShortcut::Space })+ );+ assert_eq!(+ parse_app("kwant-app://island/?mode=off&shortcut=off"),+ Some(AppAsk::Island { mode: PerchMode::Off, shortcut: PerchShortcut::Off })+ );+ for url in [+ "kwant-app://island",+ "kwant-app://island?mode=off",+ "kwant-app://island?shortcut=k",+ "kwant-app://island?mode=Busy&shortcut=k",+ "kwant-app://island?mode=busy&shortcut=K",+ "kwant-app://island?mode=busy%20&shortcut=k",+ "kwant-app://island?mode=busy&shortcut=cmd+q",+ "kwant-app://island?mode=&shortcut=",+ "kwant-app://island?mode=always;alert(1)&shortcut=k",+ "kwant-app://island?mode=\"},x:{\"&shortcut=k",+ ] {assert_eq!(parse_app(url), None, "{url}");}+ for m in [PerchMode::Busy, PerchMode::Always, PerchMode::Off] {+ assert_eq!(PerchMode::parse(m.as_str()), Some(m));+ }+ for k in [PerchShortcut::K, PerchShortcut::Space, PerchShortcut::Off] {+ assert_eq!(PerchShortcut::parse(k.as_str()), Some(k));+ }+ }++ #[test]+ fn only_this_mac_s_page_reads_or_changes_perch_settings() {+ for label in ["server-68747470733a2f2f6b77616e742e6a756d70696e2e67616d6573", "server-", "connect", PICKER_WINDOW, "perch", "kwant-nudge-pill"] {+ assert!(!island_allowed(label, true), "{label}");+ assert_eq!(island_script(label, true, PerchMode::Busy, PerchShortcut::K, true), None, "{label}");+ }+ assert!(!island_allowed(MAIN_WINDOW, false), "main on the loading page or a remote page");+ assert_eq!(island_script(MAIN_WINDOW, false, PerchMode::Busy, PerchShortcut::K, true), None);+ let js = island_script(MAIN_WINDOW, true, PerchMode::Always, PerchShortcut::Space, false).unwrap();+ assert!(js.starts_with("window.__KWANT_ISLAND__=Object.freeze({mode:\"always\",shortcut:\"space\",available:false});"), "{js}");+ assert!(js.contains("new Event('kwant-island')"));+ assert!(!js.contains("ELSEWHERE"));+ }++ #[test]+ fn perch_settings_have_their_own_once_a_second_budget() {+ let mut limit = RateLimit::default();+ let t0 = Instant::now();+ assert!(limit.allow(MAIN_WINDOW, t0, ASK_EVERY), "the picker");+ assert!(limit.allow(&island_key(MAIN_WINDOW), t0, ASK_EVERY), "settings don't share the picker's budget");+ let saved = (1..200).filter(|i| limit.allow(&island_key(MAIN_WINDOW), t0 + Duration::from_millis(*i * 4), ASK_EVERY)).count();+ assert_eq!(saved, 0, "200 asks within 0.8 s save nothing more");+ assert!(limit.allow(&island_key(MAIN_WINDOW), t0 + Duration::from_millis(1000), ASK_EVERY));}#[test]