Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Place chip in the Sidebar + Perch settings (desktop app) (#649)

Oleksandr Ivanchenko7addb3384efe
diff --git a/frontend/src/components/PlaceChip.tsx b/frontend/src/components/PlaceChip.tsx
new file mode 100644
index 00000000..9ed1829e
--- /dev/null
+++ b/frontend/src/components/PlaceChip.tsx
@@ -0,0 +1,198 @@
+import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { ChevronsUpDown, Info } from 'lucide-react';
+import {
+ ELSEWHERE_EVENT,
+ PERCH_COPY,
+ chipAriaLabel,
+ elsewhereCount,
+ elsewhereText,
+ HOST_MAX,
+ islandUrl,
+ middleCut,
+ onceEvery,
+ perchModeLine,
+ perchSettings,
+ placeOf,
+ placesUrl,
+ shortcutOptions,
+ showPlaceChip,
+ type PerchMode,
+ type PerchSettings,
+ type PerchShortcut,
+ type PlaceDot,
+} from '../placeChip';
+
+/** 14 px pixel glyphs on a 7x7 grid of 2 px cells (design.md 9.1). */
+const Glyph: React.FC<{ kind: 'local' | 'server' }> = ({ kind }) => (
+ <svg className="kw-place-glyph" viewBox="0 0 14 14" aria-hidden="true" fill="currentColor">
+ {kind === 'local' ? (
+ <path d="M2 2h10v2H2zM2 4h2v4H2zM10 4h2v4h-2zM2 8h10v2H2zM0 10h14v2H0z" />
+ ) : (
+ <path d="M2 1h10v2H2zM2 3h2v2H2zM10 3h2v2h-2zM2 5h10v2H2zM2 8h10v2H2zM2 10h2v2H2zM10 10h2v2h-2zM2 12h10v1H2zM6 3h2v2H6zM6 10h2v2H6z" />
+ )}
+ </svg>
+);
+
+/** The waiting-elsewhere count Rust keeps on the This Mac window; 0 everywhere else. */
+export function useElsewhere(): number {
+ const [n, setN] = useState(() => elsewhereCount());
+ useEffect(() => {
+ const on = () => setN(elsewhereCount());
+ window.addEventListener(ELSEWHERE_EVENT, on);
+ on();
+ return () => window.removeEventListener(ELSEWHERE_EVENT, on);
+ }, []);
+ return n;
+}
+
+type ChipProps = {
+ phone?: boolean;
+ /** Only for shots and tests: a status dot and forced visual states. The app passes none. */
+ dot?: PlaceDot;
+ demo?: 'hover' | 'focus' | 'open';
+};
+
+/** The chip and its row. Renders nothing outside the desktop app. */
+export const PlaceChipRow: React.FC<ChipProps> = ({ phone = false, dot = null, demo }) => {
+ const elsewhere = useElsewhere();
+ const ref = useRef<HTMLButtonElement>(null);
+ const gate = useMemo(() => onceEvery(1000), []);
+ const [open, setOpen] = useState(false);
+ const nameRef = useRef<HTMLSpanElement>(null);
+ // A host that still overflows the Sidebar after the 28-character cut is cut shorter in the middle, so its end
+ // (the part that tells two servers apart) stays visible. The CSS end-ellipsis is only a last resort.
+ const [max, setMax] = useState(HOST_MAX);
+ const [, remeasure] = useState(0);
+ const shown = showPlaceChip();
+ const place = shown ? placeOf() : null;
+ const isServer = place?.kind === 'server';
+ useLayoutEffect(() => {
+ const n = nameRef.current;
+ if (isServer && n && n.scrollWidth > n.clientWidth + 0.5) setMax((m) => (m > 12 ? m - 1 : m));
+ });
+ useEffect(() => {
+ if (!isServer) return;
+ // Widths change once the web font arrives and when the window is resized: start over from 28 then.
+ const again = () => {
+ setMax(HOST_MAX);
+ remeasure((t) => t + 1);
+ };
+ document.fonts?.ready.then(again).catch(() => {});
+ window.addEventListener('resize', again);
+ return () => window.removeEventListener('resize', again);
+ }, [isServer]);
+ if (!shown || !place) return null;
+ const name = place.kind === 'server' ? middleCut(place.full, max) : place.name;
+ // Rust sends the count to This Mac's window only; a server-looking chip never shows or reads one regardless.
+ const waiting = place.kind === 'local' ? elsewhere : 0;
+ const click = () => {
+ if (!gate()) return;
+ const r = ref.current?.getBoundingClientRect();
+ setOpen(true);
+ window.setTimeout(() => setOpen(false), 1000);
+ // Rust's on_navigation refuses this navigation and opens the bundled picker under the chip.
+ window.location.assign(placesUrl(r ? r.left : 0, r ? r.bottom : 0));
+ };
+ return (
+ <div className="kw-place kw-place-row" data-phone={phone ? '' : undefined} data-place-row>
+ <button
+ ref={ref}
+ type="button"
+ onClick={click}
+ className="kw-place-chip"
+ aria-label={chipAriaLabel(place.full, waiting)}
+ aria-haspopup="dialog"
+ aria-expanded={open || demo === 'open'}
+ title={place.full !== name ? place.full : undefined}
+ data-place-chip={place.kind}
+ data-hover={demo === 'hover' ? '' : undefined}
+ data-focus={demo === 'focus' ? '' : undefined}
+ >
+ <Glyph kind={place.kind} />
+ <span ref={nameRef} className="kw-place-name">{name}</span>
+ {waiting > 0 ? (
+ <span className="kw-place-count" aria-hidden="true" data-place-elsewhere>
+ {elsewhereText(waiting)}
+ </span>
+ ) : dot ? (
+ <span className="kw-place-dot" data-dot={dot} aria-hidden="true" />
+ ) : null}
+ <ChevronsUpDown size={13} className="kw-place-chev" aria-hidden="true" />
+ </button>
+ </div>
+ );
+};
+
+/** The 3-row perch mark: a little bar with a stepped lip. */
+const PerchMark = () => (
+ <svg width="18" height="14" viewBox="0 0 18 14" aria-hidden="true" fill="currentColor">
+ <path d="M0 2h18v3H0zM2 5h14v2H2zM5 7h8v2H5z" />
+ </svg>
+);
+
+/** Settings → App settings → Perch. Only in the This Mac window, where Rust sets `__KWANT_ISLAND__`. */
+export const PerchSettingsCard: React.FC<{ initial?: PerchSettings | null }> = ({ initial }) => {
+ const start = initial === undefined ? perchSettings() : initial;
+ const [s, setS] = useState<PerchSettings | null>(start);
+ const gate = useMemo(() => onceEvery(1000), []);
+ const options = useMemo(() => shortcutOptions(), []);
+ if (!s) return null;
+ const off = !s.available;
+ const write = (mode: PerchMode, shortcut: PerchShortcut) => {
+ const url = islandUrl(mode, shortcut);
+ if (!url || off || !gate()) return;
+ setS({ ...s, mode, shortcut });
+ window.location.assign(url);
+ };
+ // On Wayland the note below replaces the mode line, so it is neither shown nor read out.
+ const modeLine = off ? null : perchModeLine(s.mode);
+ return (
+ <section className="kw-perch" aria-labelledby="perch-title" data-perch-settings data-unavailable={off ? '' : undefined}>
+ <div className="kw-perch-title">
+ <PerchMark />
+ <div>
+ <h3 id="perch-title" className="kw-perch-name">{PERCH_COPY.title}</h3>
+ <p className="kw-perch-about">{PERCH_COPY.about}</p>
+ </div>
+ </div>
+ <div role="radiogroup" aria-labelledby="perch-title" aria-describedby={modeLine ? 'perch-mode-line' : undefined} className="kw-perch-seg">
+ {PERCH_COPY.modes.map((m) => (
+ <button
+ key={m.value}
+ type="button"
+ role="radio"
+ aria-checked={s.mode === m.value}
+ disabled={off}
+ onClick={() => s.mode !== m.value && write(m.value, s.shortcut)}
+ data-perch-mode={m.value}
+ >
+ {m.label}
+ </button>
+ ))}
+ </div>
+ {modeLine && <p id="perch-mode-line" className="kw-perch-line">{modeLine}</p>}
+ <div className="kw-perch-short" data-off={off || s.mode === 'off' ? '' : undefined}>
+ <label htmlFor="perch-shortcut">{PERCH_COPY.shortcutLabel}</label>
+ <select
+ id="perch-shortcut"
+ value={s.shortcut}
+ disabled={off || s.mode === 'off'}
+ onChange={(e) => write(s.mode, e.target.value as PerchShortcut)}
+ data-perch-shortcut
+ >
+ {options.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ {off && (
+ <p className="kw-perch-note" data-perch-wayland>
+ <Info size={14} aria-hidden="true" />
+ <span>{PERCH_COPY.wayland}</span>
+ </p>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 228afe81..94b209c6 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
+import { PerchSettingsCard } from './PlaceChip';
import { AuditorSettings, DAILY_CAPS, SETTING_HINT as AUDITOR_HINT, isAuditorModelError, MODEL_ERROR_TEXT as AUDITOR_MODEL_ERROR, parseAuditorSettings } from '../auditor';
import { AuditorModelSetting } from './AuditorModelSetting';
import { Key, X, Settings, Check, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles, KanbanSquare, BellRing } from 'lucide-react';
@@ -673,6 +674,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<VersionCard />
<StarAskSettingsLink />
+ <PerchSettingsCard />
{computer.state.settings && (
<div data-computer-card tabIndex={-1} className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3 focus:outline-none">
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 804cd786..54280cb6 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -27,6 +27,7 @@ import { IdeaJarRow } from './IdeaJarRow';
import { ReadyTeamsSidebarBox } from './ReadyTeamsEntry';
import { BudgetMeter, useBudgets } from './BotBudget';
import { PAUSED_ROW_LINE } from '../botBudget';
+import { PlaceChipRow } from './PlaceChip';
/** A bot's name in its row; the tooltip says what it runs on in the same words as its avatar's model badge. */
const BotName: React.FC<{ kwant: Kwant; className: string }> = ({ kwant: k, className }) => {
@@ -922,6 +923,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
data-kw-sidebar
className={`${phone ? 'w-full flex-1 min-h-0' : 'w-64 h-full border-r border-hairline'} bg-surface-side flex flex-col select-none flex-shrink-0`}
>
+ {/* Which place this window is (This Mac or a server) and the way to the place picker; desktop app only. */}
+ <PlaceChipRow phone={phone} />
{/* The open space. Desktop switches spaces on the rail, so this is its name and settings;
phones have no rail, so here it is their one switcher. */}
<div className="relative p-2 border-b border-zinc-800/60">
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 15986622..9b3b5adc 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -15,6 +15,7 @@ import './styles/devStatus.css';
import './styles/tickets.css';
import './styles/telegram.css';
import './styles/showOnce.css';
+import './styles/placeChip.css';
import './styles/gettingStarted.css';
import './styles/dropLayer.css';
diff --git a/frontend/src/placeChip.ts b/frontend/src/placeChip.ts
new file mode 100644
index 00000000..1895ba7f
--- /dev/null
+++ b/frontend/src/placeChip.ts
@@ -0,0 +1,162 @@
+/**
+ * The place chip at the top of the Sidebar and the Settings "Perch" section (desktop-island/design.md 9.1, 8).
+ *
+ * Contracts with the desktop app (apps/mac, Juno; desktop-island/build-brief.md):
+ * - `window.__KWANT_APP__` ('mac' | 'linux') marks the desktop app. Without it there is no chip.
+ * - `window.__KWANT_ELSEWHERE__` (integer) is how many things wait in the person's OTHER places. Rust sets it
+ * only in the This Mac window and fires `kwant-elsewhere` on window after each change. A server window never
+ * gets it, so its chip shows no count.
+ * - `window.__KWANT_ISLAND__` `{mode, shortcut, available}` exists only in the This Mac window. Without it
+ * there is no Perch section.
+ * - The page reaches Rust only by navigating to `kwant-app://places?at=x,y` and
+ * `kwant-app://island?mode=…&shortcut=…`, which on_navigation catches and refuses. Each at most once a second.
+ */
+import { inDesktopApp } from './externalLinks';
+
+type Win = {
+ __KWANT_APP__?: unknown;
+ __KWANT_ELSEWHERE__?: unknown;
+ __KWANT_ISLAND__?: unknown;
+ location?: { host?: string; hostname?: string; port?: string };
+};
+
+const win = (): unknown => (typeof window !== 'undefined' ? window : undefined);
+
+/** Hostnames of the desktop app's in-process server on this computer. Its port is 8799 unless startup.rs had to
+ * move it (choose_port), so any non-zero port counts: the same rule as Rust's `switcher::is_local_page`. */
+export const LOCAL_HOSTNAMES: readonly string[] = ['127.0.0.1', 'localhost'];
+
+/** Whether `host` ("name:port") is this computer's kwant: a loopback name with an explicit, non-zero port. */
+export function isLocalHost(host: string): boolean {
+ const m = /^([^:]+):(\d+)$/.exec(host.toLowerCase());
+ return !!m && LOCAL_HOSTNAMES.includes(m[1]) && Number(m[2]) > 0 && Number(m[2]) <= 65535;
+}
+
+/** Hosts longer than this are cut in the middle (design.md 9.1). */
+export const HOST_MAX = 28;
+
+/** Cuts the middle of `s` so it is at most `max` characters, keeping its start and end. */
+export function middleCut(s: string, max = HOST_MAX): string {
+ const chars = Array.from(s);
+ if (chars.length <= max) return s;
+ const keep = max - 1;
+ const head = Math.ceil(keep / 2);
+ return `${chars.slice(0, head).join('')}…${chars.slice(chars.length - (keep - head)).join('')}`;
+}
+
+export type PlaceKind = 'local' | 'server';
+
+/** Which place this page is, from its own origin only: nothing about other places reaches a page. */
+export function placeOf(w: unknown = win()): { kind: PlaceKind; name: string; full: string } {
+ const loc = (w as Win | undefined)?.location;
+ const host = (loc?.host || loc?.hostname || '').toLowerCase();
+ if (isLocalHost(host)) {
+ const name = (w as Win).__KWANT_APP__ === 'mac' ? 'This Mac' : 'This computer';
+ return { kind: 'local', name, full: name };
+ }
+ const full = host.replace(/:443$/, '') || 'this server';
+ return { kind: 'server', name: middleCut(full), full };
+}
+
+/** Whether to show the chip: in the desktop app always, even with one place; never in the web build. */
+export const showPlaceChip = (w: unknown = win()): boolean => inDesktopApp(w);
+
+/** How many wait in other places, or 0 when Rust gave nothing (a server window, an older app). */
+export function elsewhereCount(w: unknown = win()): number {
+ const n = (w as Win | undefined)?.__KWANT_ELSEWHERE__;
+ return typeof n === 'number' && Number.isInteger(n) && n > 0 ? Math.min(n, 999) : 0;
+}
+
+export const ELSEWHERE_EVENT = 'kwant-elsewhere';
+
+/** "9+" past nine, like the rest of the app's small badges. */
+export const elsewhereText = (n: number): string => (n > 9 ? '9+' : String(n));
+
+/** Starting… and Didn't start come from the app; a page that answers is running, so no dot by default. */
+export type PlaceDot = 'starting' | 'failed' | null;
+
+export function chipAriaLabel(name: string, elsewhere: number): string {
+ return elsewhere > 0
+ ? `Place: ${name}, ${elsewhere} waiting in other places. Switch place`
+ : `Place: ${name}. Switch place`;
+}
+
+/** The picker URL. x,y is the chip's bottom-left in window coordinates, whole pixels; Rust clamps it. */
+export function placesUrl(x: number, y: number): string {
+ const r = (v: number) => (Number.isFinite(v) ? Math.max(0, Math.round(v)) : 0);
+ return `kwant-app://places?at=${r(x)},${r(y)}`;
+}
+
+/** Lets a call through at most once per `ms`; the rest are dropped, not queued. */
+export function onceEvery(ms: number, now: () => number = () => Date.now()): () => boolean {
+ let last = -Infinity;
+ return () => {
+ const t = now();
+ if (t - last < ms) return false;
+ last = t;
+ return true;
+ };
+}
+
+// ---------- Perch settings ----------
+
+export const PERCH_MODES = ['busy', 'always', 'off'] as const;
+export type PerchMode = (typeof PERCH_MODES)[number];
+/** Shortcut tokens on the wire, the same on every OS: `k` = ⌥⌘K / Ctrl+Alt+K, `space` = ⌃⌥Space / Ctrl+Alt+Space. */
+export const PERCH_SHORTCUTS = ['k', 'space', 'off'] as const;
+export type PerchShortcut = (typeof PERCH_SHORTCUTS)[number];
+
+export type PerchSettings = { mode: PerchMode; shortcut: PerchShortcut; available: boolean };
+
+const isMode = (v: unknown): v is PerchMode => typeof v === 'string' && (PERCH_MODES as readonly string[]).includes(v);
+const isShortcut = (v: unknown): v is PerchShortcut =>
+ typeof v === 'string' && (PERCH_SHORTCUTS as readonly string[]).includes(v);
+
+/** The perch settings Rust gave this window, or null when it gave none (any window but This Mac, the web). */
+export function perchSettings(w: unknown = win()): PerchSettings | null {
+ if (!inDesktopApp(w)) return null;
+ const raw = (w as Win).__KWANT_ISLAND__;
+ if (!raw || typeof raw !== 'object') return null;
+ const r = raw as Record<string, unknown>;
+ return {
+ mode: isMode(r.mode) ? r.mode : 'busy',
+ shortcut: isShortcut(r.shortcut) ? r.shortcut : 'k',
+ available: r.available !== false,
+ };
+}
+
+/** The settings URL, or null for any value outside the whitelist. */
+export function islandUrl(mode: unknown, shortcut: unknown): string | null {
+ if (!isMode(mode) || !isShortcut(shortcut)) return null;
+ return `kwant-app://island?mode=${mode}&shortcut=${shortcut}`;
+}
+
+export const PERCH_COPY = {
+ title: 'Perch',
+ about: 'A small bar at the top of your screen: who is working, what needs you, and quick answers without opening the app.',
+ modes: [
+ { value: 'busy', label: 'When something’s happening', line: 'Shows while bots work or need you, and hides when nothing is going on.' },
+ { value: 'always', label: 'Always', line: 'Stays at the top of the screen, even when nothing is going on.' },
+ { value: 'off', label: 'Off', line: 'No perch. You get the nudge pill, the menu bar mark and the app badge, as before.' },
+ ] as { value: PerchMode; label: string; line: string }[],
+ /** Linux and Windows have a tray mark, not a menu bar mark or a Dock badge. */
+ offLineElsewhere: 'No perch. You get the nudge pill and the tray mark, as before.',
+ shortcutLabel: 'Shortcut to open it',
+ wayland: 'The perch isn’t available on Wayland yet. You still get the tray mark and a notification when a bot needs you.',
+} as const;
+
+/** The line under the mode buttons, in this OS's words. */
+export function perchModeLine(mode: PerchMode, w: unknown = win()): string {
+ if (mode === 'off' && (w as Win | undefined)?.__KWANT_APP__ !== 'mac') return PERCH_COPY.offLineElsewhere;
+ return PERCH_COPY.modes.find((m) => m.value === mode)?.line ?? '';
+}
+
+/** The shortcut choices in this OS's words. */
+export function shortcutOptions(w: unknown = win()): { value: PerchShortcut; label: string }[] {
+ const mac = (w as Win | undefined)?.__KWANT_APP__ === 'mac';
+ return [
+ { value: 'k', label: mac ? '⌥⌘K' : 'Ctrl+Alt+K' },
+ { value: 'space', label: mac ? '⌃⌥Space' : 'Ctrl+Alt+Space' },
+ { value: 'off', label: 'Off' },
+ ];
+}
diff --git a/frontend/src/styles/placeChip.css b/frontend/src/styles/placeChip.css
new file mode 100644
index 00000000..2d4886b6
--- /dev/null
+++ b/frontend/src/styles/placeChip.css
@@ -0,0 +1,113 @@
+/* Place chip (desktop-island/design.md 9.1) and the Settings "Perch" section (8). The app is dark;
+ [data-theme="light"] holds the light values from 4.2 for when it gets a light theme. */
+.kw-place {
+ --pc-row: var(--kw-surface-side, #120e26);
+ --pc-bg: var(--kw-surface-raised, #1a1538);
+ --pc-ring: var(--kw-hairline-strong, rgb(255 255 255 / .14));
+ --pc-hover: #231d4b;
+ --pc-text: #e4e4e7;
+ --pc-text-hi: #fafafa;
+ --pc-glyph: #b8adff;
+ --pc-chev: #a1a1aa;
+ --pc-amber: #ffb020;
+ --pc-amber-ink: #1b1033;
+ --pc-amber-rim: transparent;
+ --pc-focus: #8270f5;
+ --pc-line: rgb(39 39 42 / .6);
+ --pc-dot-start: #fcd34d;
+ --pc-dot-fail: #fda4af;
+}
+[data-theme="light"] .kw-place {
+ --pc-row: #ffffff;
+ --pc-bg: #ece9ff;
+ --pc-ring: rgb(29 24 64 / .14);
+ --pc-hover: #e2ddff;
+ --pc-text: #1d1840;
+ --pc-text-hi: #1d1840;
+ --pc-glyph: #5845bd;
+ --pc-chev: #5a5383;
+ --pc-amber-rim: #1b1033;
+ --pc-focus: #6c58e0;
+ --pc-line: rgb(29 24 64 / .14);
+ --pc-dot-start: #8f5600;
+ --pc-dot-fail: #be123c;
+}
+.kw-place-row {
+ display: flex; align-items: center; height: 44px; padding: 0 8px; flex: none;
+ background: var(--pc-row); border-bottom: 1px solid var(--pc-line);
+}
+.kw-place-row[data-phone] { height: 52px; padding: 0 12px; }
+.kw-place-chip {
+ display: inline-flex; align-items: center; gap: 6px; height: 32px; max-width: 100%;
+ padding: 0 8px 0 10px; border-radius: 9999px; border: 0; cursor: pointer;
+ background: var(--pc-bg); box-shadow: inset 0 0 0 1px var(--pc-ring);
+ color: var(--pc-text); font-size: 13px; font-weight: 500; line-height: 16px; white-space: nowrap;
+ position: relative; transition: background-color 120ms, color 120ms;
+}
+.kw-place-row[data-phone] .kw-place-chip { height: 36px; }
+/* 44 px hit area on phones without growing the chip. */
+.kw-place-row[data-phone] .kw-place-chip::before { content: ''; position: absolute; inset: -4px -2px; min-height: 44px; top: 50%; transform: translateY(-50%); }
+.kw-place-chip:hover, .kw-place-chip[data-hover] { background: var(--pc-hover); color: var(--pc-text-hi); }
+.kw-place-chip:focus { outline: none; }
+.kw-place-chip:focus-visible, .kw-place-chip[data-focus] { outline: 2px solid var(--pc-focus); outline-offset: 2px; }
+.kw-place-chip[aria-expanded="true"] { box-shadow: inset 0 0 0 1px var(--pc-focus); }
+.kw-place-glyph { flex: none; width: 14px; height: 14px; color: var(--pc-glyph); shape-rendering: crispEdges; }
+.kw-place-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+.kw-place-count {
+ flex: none; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 4px;
+ background: var(--pc-amber); color: var(--pc-amber-ink); box-shadow: inset 0 0 0 1px var(--pc-amber-rim);
+ font: 700 11px/16px -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, sans-serif;
+ text-align: center; font-variant-numeric: tabular-nums;
+}
+.kw-place-dot { flex: none; width: 6px; height: 6px; border-radius: 1px; }
+.kw-place-dot[data-dot="starting"] { background: var(--pc-dot-start); }
+.kw-place-dot[data-dot="failed"] { background: var(--pc-dot-fail); }
+.kw-place-chev { flex: none; color: var(--pc-chev); }
+@media (prefers-reduced-motion: reduce) { .kw-place-chip { transition: none; } }
+
+/* Settings → Perch */
+.kw-perch {
+ --pp-card: rgb(9 9 11 / .6); --pp-border: #27272a; --pp-t1: #f4f4f5; --pp-t2: #a1a1aa; --pp-t3: #71717a;
+ --pp-seg: #09090b; --pp-on: #6c58e0; --pp-on-text: #ffffff; --pp-mark: #ffb020; --pp-note: rgb(24 24 27 / .8);
+ --pp-icon: #b8adff; --pp-focus: #8270f5;
+}
+[data-theme="light"] .kw-perch {
+ --pp-card: #ffffff; --pp-border: rgb(29 24 64 / .14); --pp-t1: #1d1840; --pp-t2: #5a5383; --pp-t3: #6b6494;
+ --pp-seg: #f5f3ff; --pp-mark: #8f5600; --pp-note: #f5f3ff;
+ --pp-icon: #5845bd; --pp-focus: #6c58e0;
+}
+.kw-perch { background: var(--pp-card); border: 1px solid var(--pp-border); border-radius: 12px; padding: 16px; }
+.kw-perch-title { display: flex; gap: 8px; align-items: flex-start; }
+.kw-perch-title svg { flex: none; color: var(--pp-mark); margin-top: 1px; shape-rendering: crispEdges; }
+.kw-perch[data-unavailable] .kw-perch-title svg { color: var(--pp-t3); }
+.kw-perch-name { font-size: 12px; font-weight: 500; color: var(--pp-t1); line-height: 16px; }
+.kw-perch-about { font-size: 11px; line-height: 16px; color: var(--pp-t2); margin-top: 2px; }
+.kw-perch-seg {
+ display: grid; grid-template-columns: 1.6fr 1fr 1fr; gap: 4px; margin-top: 12px; padding: 3px;
+ background: var(--pp-seg); border: 1px solid var(--pp-border); border-radius: 10px;
+}
+.kw-perch-seg button {
+ min-height: 32px; padding: 4px 8px; border-radius: 7px; border: 0; background: transparent; cursor: pointer;
+ color: var(--pp-t1); font-size: 12px; line-height: 14px; white-space: nowrap;
+}
+.kw-perch-seg button[aria-checked="true"] { background: var(--pp-on); color: var(--pp-on-text); }
+.kw-perch-seg button:focus-visible { outline: 2px solid var(--pp-focus); outline-offset: 1px; }
+.kw-perch-seg button:disabled { cursor: not-allowed; opacity: .5; }
+.kw-perch-line { margin-top: 8px; font-size: 11px; line-height: 16px; color: var(--pp-t2); }
+.kw-perch-short {
+ display: flex; align-items: center; justify-content: space-between; gap: 12px;
+ margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--pp-border);
+}
+.kw-perch-short label { font-size: 12px; color: var(--pp-t1); }
+.kw-perch-short select {
+ min-height: 32px; min-width: 112px; padding: 0 8px; border-radius: 8px; font-size: 12px;
+ background: var(--pp-seg); color: var(--pp-t1); border: 1px solid var(--pp-border);
+}
+.kw-perch-short select:focus-visible { outline: 2px solid var(--pp-focus); outline-offset: 1px; }
+.kw-perch-short[data-off] label, .kw-perch-short select:disabled { color: var(--pp-t3); }
+.kw-perch-note {
+ display: flex; gap: 8px; align-items: flex-start; margin-top: 12px; padding: 10px 12px; border-radius: 8px;
+ background: var(--pp-note); border: 1px solid var(--pp-border); font-size: 11px; line-height: 16px; color: var(--pp-t1);
+}
+.kw-perch-note svg { flex: none; color: var(--pp-icon); margin-top: 1px; }
+@media (max-width: 480px) { .kw-perch-seg { grid-template-columns: 1fr; } .kw-perch-seg button { min-height: 40px; } }
diff --git a/frontend/tests/placeChip.test.mjs b/frontend/tests/placeChip.test.mjs
new file mode 100644
index 00000000..0f51b227
--- /dev/null
+++ b/frontend/tests/placeChip.test.mjs
@@ -0,0 +1,213 @@
+// Oleks (2026-11-14): an easier way to switch between This Mac and a server in the desktop app, plus settings
+// for the Perch. desktop-island/build-brief.md: the chip only in the app; the waiting-elsewhere count and the
+// Perch section only where Rust sets __KWANT_ELSEWHERE__ / __KWANT_ISLAND__ (the This Mac window).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+// CI runs Node 20, which has no global navigator (Node 21+ does); the Sidebar's InstallAppButton reads it.
+globalThis.navigator ??= { userAgent: 'test' };
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { PlaceChipRow, PerchSettingsCard } from './src/components/PlaceChip';
+ import { Sidebar } from './src/components/Sidebar';
+ export * from './src/placeChip';
+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));
+ export const chip = (p) => r(PlaceChipRow, p);
+ export const perch = (p) => r(PerchSettingsCard, p);
+ const engines = { engines: [], loading: false, error: null, refresh: () => {} };
+ export const sidebar = (p) =>
+ r(Sidebar, {
+ spaces: [], onSwitchSpace() {}, onCreateSpace() {}, onOpenSpaceSettings() {}, onOpenArchived() {}, onOpenSearch() {}, onOpenRoutines() {},
+ channels: [], teams: [], selectedId: '', isChannel: false, onSelectKwant() {}, onSelectChannel() {}, onSelectTeam() {}, onSummonKwant() {}, onCreateTeam() {},
+ engines, kwants: [], ...p,
+ });
+`);
+
+const space = { id: 'spc_1', name: 'Work', icon: '💼', color: null, sort: 0, is_default: false, archived_at: null, created_at: '', general_channel_id: null, counts: { bots: 0, ready_accounts: 1, unread: 0 }, approvals: 'ask' };
+
+/** Renders with `globalThis.window` set to a fake window for the duration of `fn`. */
+function inWindow(props, fn) {
+ const assigned = [];
+ const listeners = {};
+ const w = {
+ location: { host: props.host ?? '127.0.0.1:8799', assign: (u) => assigned.push(u) },
+ addEventListener: (n, f) => (listeners[n] = f),
+ removeEventListener: () => {},
+ setTimeout: () => 0,
+ navigator: { userAgent: "test" },
+ matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
+ ...props.marks,
+ };
+ const before = globalThis.window;
+ globalThis.window = w;
+ try {
+ return fn(w, assigned);
+ } finally {
+ if (before === undefined) delete globalThis.window;
+ else globalThis.window = before;
+ }
+}
+
+test('web build: no chip, in the chip row or in the whole Sidebar', () => {
+ inWindow({ marks: {} }, () => {
+ assert.equal(m.chip({}), '');
+ assert.equal(m.chip({ phone: true }), '');
+ const html = m.sidebar({ space });
+ assert.doesNotMatch(html, /data-place-row|data-place-chip/);
+ });
+ // A window that claims some other mark is still the web build.
+ inWindow({ marks: { __KWANT_APP__: 'windows' } }, () => assert.equal(m.chip({}), ''));
+ inWindow({ marks: { __KWANT_APP__: true } }, () => assert.equal(m.chip({}), ''));
+});
+
+test('desktop app: the chip heads the Sidebar, above the space header, even with one place', () => {
+ inWindow({ marks: { __KWANT_APP__: 'mac' } }, () => {
+ const html = m.sidebar({ space });
+ const row = html.indexOf('data-place-row');
+ assert.ok(row > 0, 'chip row present');
+ assert.ok(html.indexOf('>Work<') > row, 'above the space name');
+ assert.ok(html.indexOf('<aside') < row, 'inside the aside');
+ assert.match(html, /This Mac/);
+ const phone = m.sidebar({ space, phone: true });
+ assert.match(phone, /data-phone="" data-place-row/);
+ });
+});
+
+test('no badge without __KWANT_ELSEWHERE__, and none for zero or junk', () => {
+ inWindow({ marks: { __KWANT_APP__: 'mac' } }, () => {
+ const html = m.chip({});
+ assert.doesNotMatch(html, /data-place-elsewhere/);
+ assert.match(html, /aria-label="Place: This Mac\. Switch place"/);
+ });
+ for (const junk of [0, -2, 1.5, '3', null, {}, NaN]) {
+ inWindow({ marks: { __KWANT_APP__: 'mac', __KWANT_ELSEWHERE__: junk } }, () => {
+ assert.doesNotMatch(m.chip({}), /data-place-elsewhere/, `junk ${String(junk)}`);
+ });
+ }
+});
+
+test('the badge shows the count Rust gave, with the label saying it', () => {
+ inWindow({ marks: { __KWANT_APP__: 'mac', __KWANT_ELSEWHERE__: 2 } }, () => {
+ const html = m.chip({});
+ assert.match(html, /data-place-elsewhere="true">2</);
+ assert.match(html, /aria-label="Place: This Mac, 2 waiting in other places\. Switch place"/);
+ });
+ inWindow({ marks: { __KWANT_APP__: 'mac', __KWANT_ELSEWHERE__: 14 } }, () => {
+ assert.match(m.chip({}), /data-place-elsewhere="true">9\+</);
+ });
+});
+
+test('a server window shows its own host, middle-cut at 28, and never a count it was not given', () => {
+ inWindow({ host: 'kwant.jumpin.games', marks: { __KWANT_APP__: 'mac' } }, () => {
+ const html = m.chip({});
+ assert.match(html, /data-place-chip="server"/);
+ assert.match(html, />kwant\.jumpin\.games</);
+ assert.doesNotMatch(html, /data-place-elsewhere/);
+ });
+ const long = 'very-long-subdomain.kwant.example.com';
+ assert.equal(m.middleCut(long).length, 28);
+ assert.equal(m.middleCut(long), 'very-long-subd…t.example.com');
+ assert.equal(m.middleCut('short.host'), 'short.host');
+ assert.equal(m.placeOf({ location: { host: 'srv.example.com:443' } }).full, 'srv.example.com');
+});
+
+test('This Mac on a Mac, This computer on Linux; localhost counts as this computer', () => {
+ assert.equal(m.placeOf({ __KWANT_APP__: 'mac', location: { host: '127.0.0.1:8799' } }).name, 'This Mac');
+ assert.equal(m.placeOf({ __KWANT_APP__: 'linux', location: { host: '127.0.0.1:8799' } }).name, 'This computer');
+ assert.equal(m.placeOf({ __KWANT_APP__: 'mac', location: { host: 'localhost:8799' } }).kind, 'local');
+ // startup.rs can move kwant off 8799 when that port is taken: any non-zero loopback port is still This Mac
+ // (Rust's switcher::is_local_page), so it never gets the server glyph or the amber count's wrong home.
+ assert.equal(m.placeOf({ __KWANT_APP__: 'mac', location: { host: '127.0.0.1:53412' } }).name, 'This Mac');
+ assert.equal(m.placeOf({ __KWANT_APP__: 'linux', location: { host: 'LOCALHOST:8800' } }).kind, 'local');
+ // Port 0, no port and a bad port are not this computer's kwant.
+ for (const host of ['127.0.0.1:0', '127.0.0.1', 'localhost', '127.0.0.1:99999', '127.0.0.2:8799', 'localhost.example.com:8799'])
+ assert.equal(m.placeOf({ __KWANT_APP__: 'mac', location: { host } }).kind, 'server', host);
+});
+
+test('a server window never shows the amber count, even when the global is set', () => {
+ inWindow({ host: 'kwant.jumpin.games', marks: { __KWANT_APP__: 'mac', __KWANT_ELSEWHERE__: 3 } }, () => {
+ const html = m.chip({});
+ assert.match(html, /data-place-chip="server"/);
+ assert.doesNotMatch(html, /data-place-elsewhere/);
+ assert.doesNotMatch(html, /waiting in other places/);
+ });
+ inWindow({ host: '127.0.0.1:53412', marks: { __KWANT_APP__: 'mac', __KWANT_ELSEWHERE__: 3 } }, () => {
+ assert.match(m.chip({}), /data-place-elsewhere="true">3</);
+ });
+});
+
+test('the picker URL is whole, non-negative window pixels, and clicks pass at most once a second', () => {
+ assert.equal(m.placesUrl(12.4, 44.6), 'kwant-app://places?at=12,45');
+ assert.equal(m.placesUrl(-3, NaN), 'kwant-app://places?at=0,0');
+ let t = 0;
+ const gate = m.onceEvery(1000, () => t);
+ assert.equal(gate(), true);
+ t = 400;
+ assert.equal(gate(), false);
+ t = 999;
+ assert.equal(gate(), false);
+ t = 1000;
+ assert.equal(gate(), true);
+});
+
+test('no Perch section without __KWANT_ISLAND__, nor in the web build', () => {
+ inWindow({ marks: { __KWANT_APP__: 'mac' } }, () => assert.equal(m.perch({}), ''));
+ // A server page that somehow had the variable but no app mark still shows nothing.
+ inWindow({ marks: { __KWANT_ISLAND__: { mode: 'busy', shortcut: 'k', available: true } } }, () => assert.equal(m.perch({}), ''));
+ assert.equal(m.perchSettings({ __KWANT_APP__: 'mac', __KWANT_ISLAND__: 'busy' }), null);
+});
+
+test('Perch section: three modes, the line for the chosen one, the shortcut in this OS’s words', () => {
+ inWindow({ marks: { __KWANT_APP__: 'mac', __KWANT_ISLAND__: { mode: 'always', shortcut: 'k', available: true } } }, () => {
+ const html = m.perch({});
+ assert.match(html, /data-perch-settings/);
+ for (const label of ['When something’s happening', 'Always', 'Off']) assert.ok(html.includes(label), label);
+ assert.match(html, /aria-checked="true"[^>]*data-perch-mode="always"/);
+ assert.match(html, /Stays at the top of the screen/);
+ assert.match(html, /⌥⌘K/);
+ assert.doesNotMatch(html, /data-perch-wayland/);
+ });
+ inWindow({ marks: { __KWANT_APP__: 'linux', __KWANT_ISLAND__: { mode: 'off', shortcut: 'space', available: true } } }, () => {
+ const html = m.perch({});
+ assert.match(html, /Ctrl\+Alt\+K/);
+ assert.match(html, /<select[^>]*disabled/, 'shortcut disabled while Off');
+ });
+});
+
+test('Wayland: the section is disabled and says the perch is not available there', () => {
+ inWindow({ marks: { __KWANT_APP__: 'linux', __KWANT_ISLAND__: { mode: 'off', shortcut: 'k', available: false } } }, () => {
+ const html = m.perch({});
+ assert.match(html, /data-perch-wayland/);
+ assert.match(html, /isn’t available on Wayland yet/);
+ assert.equal((html.match(/role="radio"[^>]*disabled/g) || []).length, 3);
+ // The note replaces the mode line: no repeated text, nothing for aria-describedby to point at.
+ assert.doesNotMatch(html, /perch-mode-line/);
+ assert.doesNotMatch(html, /No perch\./);
+ });
+});
+
+test('the Off line names the tray mark off a Mac, and the menu bar mark and app badge on a Mac', () => {
+ inWindow({ marks: { __KWANT_APP__: 'linux', __KWANT_ISLAND__: { mode: 'off', shortcut: 'k', available: true } } }, () => {
+ const html = m.perch({});
+ assert.match(html, /No perch\. You get the nudge pill and the tray mark, as before\./);
+ assert.doesNotMatch(html, /menu bar|app badge/);
+ assert.match(html, /aria-describedby="perch-mode-line"/);
+ });
+ inWindow({ marks: { __KWANT_APP__: 'mac', __KWANT_ISLAND__: { mode: 'off', shortcut: 'k', available: true } } }, () => {
+ assert.match(m.perch({}), /No perch\. You get the nudge pill, the menu bar mark and the app badge, as before\./);
+ });
+});
+
+test('settings URLs carry whitelisted values only', () => {
+ assert.equal(m.islandUrl('busy', 'k'), 'kwant-app://island?mode=busy&shortcut=k');
+ assert.equal(m.islandUrl('off', 'off'), 'kwant-app://island?mode=off&shortcut=off');
+ assert.equal(m.islandUrl('always&x=1', 'k'), null);
+ assert.equal(m.islandUrl('busy', '⌥⌘K'), null);
+ assert.equal(m.islandUrl(undefined, 'k'), null);
+ // Unknown values from Rust fall back to the defaults instead of showing nothing chosen.
+ assert.deepEqual(m.perchSettings({ __KWANT_APP__: 'mac', __KWANT_ISLAND__: { mode: 'weird', shortcut: 1 } }), { mode: 'busy', shortcut: 'k', available: true });
+});