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.

Web/PWA "needs you" nudge (0.6.9): pill, tab favicon and count, app badge, haptic (#267)

Oleksandr Ivanchenkoa61f63520138
diff --git a/frontend/public/icon-needs-you.svg b/frontend/public/icon-needs-you.svg
new file mode 100644
index 00000000..7f1a87f8
--- /dev/null
+++ b/frontend/public/icon-needs-you.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 1 16 16" shape-rendering="crispEdges"><defs><mask id="kw-cut" maskUnits="userSpaceOnUse" x="0" y="1" width="16" height="16"><rect x="0" y="1" width="16" height="16" fill="#fff"/><g fill="#000"><rect x="10" y="1" width="1" height="1"/><rect x="10" y="2" width="1" height="1"/><rect x="10" y="3" width="1" height="1"/><rect x="10" y="4" width="1" height="1"/><rect x="10" y="5" width="1" height="1"/><rect x="10" y="6" width="1" height="1"/><rect x="11" y="0" width="1" height="1"/><rect x="11" y="1" width="1" height="1"/><rect x="11" y="2" width="1" height="1"/><rect x="11" y="3" width="1" height="1"/><rect x="11" y="4" width="1" height="1"/><rect x="11" y="5" width="1" height="1"/><rect x="11" y="6" width="1" height="1"/><rect x="11" y="7" width="1" height="1"/><rect x="12" y="0" width="1" height="1"/><rect x="12" y="1" width="1" height="1"/><rect x="12" y="2" width="1" height="1"/><rect x="12" y="3" width="1" height="1"/><rect x="12" y="4" width="1" height="1"/><rect x="12" y="5" width="1" height="1"/><rect x="12" y="6" width="1" height="1"/><rect x="12" y="7" width="1" height="1"/><rect x="13" y="0" width="1" height="1"/><rect x="13" y="1" width="1" height="1"/><rect x="13" y="2" width="1" height="1"/><rect x="13" y="3" width="1" height="1"/><rect x="13" y="4" width="1" height="1"/><rect x="13" y="5" width="1" height="1"/><rect x="13" y="6" width="1" height="1"/><rect x="13" y="7" width="1" height="1"/><rect x="14" y="0" width="1" height="1"/><rect x="14" y="1" width="1" height="1"/><rect x="14" y="2" width="1" height="1"/><rect x="14" y="3" width="1" height="1"/><rect x="14" y="4" width="1" height="1"/><rect x="14" y="5" width="1" height="1"/><rect x="14" y="6" width="1" height="1"/><rect x="14" y="7" width="1" height="1"/><rect x="15" y="0" width="1" height="1"/><rect x="15" y="1" width="1" height="1"/><rect x="15" y="2" width="1" height="1"/><rect x="15" y="3" width="1" height="1"/><rect x="15" y="4" width="1" height="1"/><rect x="15" y="5" width="1" height="1"/><rect x="15" y="6" width="1" height="1"/><rect x="15" y="7" width="1" height="1"/><rect x="16" y="1" width="1" height="1"/><rect x="16" y="2" width="1" height="1"/><rect x="16" y="3" width="1" height="1"/><rect x="16" y="4" width="1" height="1"/><rect x="16" y="5" width="1" height="1"/><rect x="16" y="6" width="1" height="1"/></g></mask></defs><g mask="url(#kw-cut)"><rect x="0" y="1" width="16" height="16" rx="3" fill="#4024a8"/><rect x="10" y="4" width="1" height="1" fill="#1d1147"/><rect x="10" y="1" width="2" height="2" fill="#ddd5ff"/><rect x="4" y="5" width="8" height="1" fill="#fff"/><rect x="3" y="6" width="10" height="1" fill="#fff"/><rect x="2" y="7" width="12" height="7" fill="#fff"/><rect x="3" y="14" width="10" height="1" fill="#fff"/><rect x="4" y="15" width="8" height="1" fill="#ddd5ff"/><rect x="13" y="7" width="1" height="7" fill="#ddd5ff"/><rect x="5" y="8" width="2" height="3" fill="#1d1147"/><rect x="9" y="8" width="2" height="3" fill="#1d1147"/><rect x="3" y="11" width="2" height="1" fill="#b8a9fb"/><rect x="11" y="11" width="2" height="1" fill="#b8a9fb"/><rect x="6" y="12" width="1" height="1" fill="#1d1147"/><rect x="9" y="12" width="1" height="1" fill="#1d1147"/><rect x="7" y="13" width="2" height="1" fill="#1d1147"/><rect x="4" y="16" width="2" height="1" fill="#ddd5ff"/><rect x="10" y="16" width="2" height="1" fill="#ddd5ff"/></g><g fill="#ffb020"><rect x="11" y="2" width="1" height="1"/><rect x="11" y="3" width="1" height="1"/><rect x="11" y="4" width="1" height="1"/><rect x="11" y="5" width="1" height="1"/><rect x="12" y="1" width="1" height="1"/><rect x="12" y="2" width="1" height="1"/><rect x="12" y="3" width="1" height="1"/><rect x="12" y="4" width="1" height="1"/><rect x="12" y="5" width="1" height="1"/><rect x="12" y="6" width="1" height="1"/><rect x="13" y="1" width="1" height="1"/><rect x="13" y="4" width="1" height="1"/><rect x="13" y="6" width="1" height="1"/><rect x="14" y="1" width="1" height="1"/><rect x="14" y="2" width="1" height="1"/><rect x="14" y="3" width="1" height="1"/><rect x="14" y="4" width="1" height="1"/><rect x="14" y="5" width="1" height="1"/><rect x="14" y="6" width="1" height="1"/><rect x="15" y="2" width="1" height="1"/><rect x="15" y="3" width="1" height="1"/><rect x="15" y="4" width="1" height="1"/><rect x="15" y="5" width="1" height="1"/></g><g fill="#1b1033"><rect x="13" y="2" width="1" height="1"/><rect x="13" y="3" width="1" height="1"/><rect x="13" y="5" width="1" height="1"/></g></svg>
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 8a2d357f..dd6e66fb 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4,6 +4,7 @@ import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar
import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';
import { InboxPage } from './components/InboxPage';
import { InboxTab, SettingsScope, SpaceView, viewSegment } from './nav';
+import { PHONE_QUERY } from './layout';
import { useSettingsCover } from './settingsFocus';
import { FirstRunWelcome } from './components/FirstRunWelcome';
import { SpaceTile } from './components/Spaces';
@@ -118,6 +119,8 @@ import { personFetch } from './auth';
import { teamChannelOf, teamOfChannel } from './teamChannel';
import { PromptContext, suggestedPrompts } from './suggestedPrompts';
import { isNotificationOpen, showDeviceNotification } from './push';
+import { EMPTY_PILL, NUDGES_SETTING_EVENT, browserIconDoc, createArrivals, createNudgeIcon, nudgesEnabled, pillAdd, pillPrune, setAppBadgeCount, shouldPill, type Nudge, type PillState } from './attention';
+import { NeedsYouPill } from './components/NeedsYouPill';
import { inDesktopApp, leaveForSignIn, mcpSignIn, pollUntil, signInChanged } from './externalLinks';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
@@ -158,8 +161,6 @@ export interface SpaceAppProps {
onChatChange: (target: SpaceTarget) => void;
}
-const PHONE_QUERY = '(max-width: 767px)';
-
/** Below 768px the space is one column: a list or a chat, with a tab bar. */
function useIsPhone(): boolean {
const [phone, setPhone] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches);
@@ -350,6 +351,22 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// A task to open on the board once it shows (from a lesson on a bot's Memory tab).
const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);
const [awayCount, setAwayCount] = useState(0);
+ // "Needs you" nudges (attention.ts): what waits on the person, the pill, and the "Show nudges" setting.
+ const [awayWaiting, setAwayWaiting] = useState(0);
+ const [pill, setPill] = useState<PillState>(EMPTY_PILL);
+ const [nudgesOn, setNudgesOn] = useState(nudgesEnabled);
+ const nudgesOnRef = useRef(nudgesOn);
+ nudgesOnRef.current = nudgesOn;
+ const pageRef = useRef(page);
+ pageRef.current = page;
+ const arrivalsRef = useRef(createArrivals());
+ const offerNudges = (arrivals: Nudge[]) => {
+ const view = { openCtx: pageRef.current === 'chat' ? openCtxRef.current : null, onInbox: pageRef.current === 'inbox', hidden: document.hidden, enabled: nudgesOnRef.current };
+ const shown = arrivals.filter((n) => shouldPill(n, view));
+ if (!shown.length) return;
+ setPill((prev) => pillAdd(prev, shown));
+ haptic('warning');
+ };
const awaySinceRef = useRef<string | null>(null);
const awayTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const refreshAwayCount = (delay = 0) => {
@@ -357,6 +374,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
awayTimerRef.current = setTimeout(() => {
awayApi.get().then((r) => {
setAwayCount(r.unseen.total);
+ setAwayWaiting(r.unseen.waiting);
+ const fresh = arrivalsRef.current.fromAway(r.waiting);
+ setPill((prev) => pillPrune(prev, new Set(r.waiting.map((i) => `${i.kind}:${i.id}`))));
+ offerNudges(fresh);
const fromServer = approvalsFromAway(r.waiting);
const live = liveApprovalIdsRef.current;
setPendingApprovals((prev) => syncApprovals(prev, fromServer, live));
@@ -382,6 +403,16 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (n.kind === 'automation_suggested') emitContinuity({ type: 'automation_suggested', data: n });
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
// Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.
+ // A question or browser step gets the "needs you" pill instead of a toast (approvals get it from the away list too).
+ if (!document.hidden && nudgesOnRef.current && (n.kind === 'question_asked' || n.kind === 'human_step')) {
+ if (pageRef.current === 'chat' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (n.kind === 'human_step') {
+ const nudge = arrivalsRef.current.fromHumanStep(n);
+ if (nudge) offerNudges([nudge]);
+ } else refreshAwayCount(300);
+ playSfx('alert');
+ return;
+ }
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && n.kind !== 'tier_proposed' && n.kind !== 'fact_disputed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
const id = ++toastIdRef.current;
@@ -2677,7 +2708,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return () => clearInterval(t);
}, [kwants, profiles]);
const tabSignal = useMemo(() => createTabSignal(browserTabDoc()), []);
- const tabNeedsYou = needsYouCount(botStatus, pendingApprovals.length);
+ // The title counts what /api/away says waits (questions + approvals) or Pixel's bot count, whichever is
+ // higher (browser steps are only in the latter); "Show nudges" off keeps the plain title.
+ const tabNeedsYou = nudgesOn ? Math.max(needsYouCount(botStatus, pendingApprovals.length), awayWaiting) : 0;
const anyRunning = Object.values(turns).some((t) => t.state === 'running');
useEffect(() => {
tabSignal.setNeedsYou(tabNeedsYou);
@@ -2688,9 +2721,33 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
mo.observe(el, { childList: true, characterData: true, subtree: true });
return () => mo.disconnect();
}, [tabSignal, tabNeedsYou]);
+ // While something waits the "!" favicon wins over the working dot; the app icon badge always shows the count.
+ const nudgeIcon = useMemo(() => createNudgeIcon(browserIconDoc()), []);
+ const markIcon = nudgesOn && awayWaiting > 0;
+ useEffect(() => {
+ void nudgeIcon.set(markIcon);
+ void tabSignal.setWorking(anyRunning && !markIcon);
+ }, [nudgeIcon, tabSignal, anyRunning, markIcon]);
+ useEffect(() => {
+ setAppBadgeCount(awayWaiting);
+ }, [awayWaiting]);
+ useEffect(() => {
+ const on = (e: Event) => setNudgesOn(Boolean((e as CustomEvent<boolean>).detail));
+ window.addEventListener(NUDGES_SETTING_EVENT, on);
+ return () => window.removeEventListener(NUDGES_SETTING_EVENT, on);
+ }, []);
useEffect(() => {
- void tabSignal.setWorking(anyRunning);
- }, [tabSignal, anyRunning]);
+ if (!nudgesOn) setPill(EMPTY_PILL);
+ }, [nudgesOn]);
+ const dismissPill = useCallback((rev: number) => setPill((p) => (p.rev === rev ? EMPTY_PILL : p)), []);
+ const openPill = (items: Nudge[]) => {
+ setPill(EMPTY_PILL);
+ const n = items[0];
+ if (items.length > 1 || !n) return showPage('inbox');
+ if (n.away) return openAwayItem(n.away);
+ openNotified({ kind: 'human_step', kwant_id: n.kwantId, channel_id: n.channelId ?? null });
+ };
+ const spriteOf = useCallback((id: string) => kwants.find((k) => k.id === id)?.avatar_sprite, [kwants]);
// What the empty chat shows: a bot's home, #general's, or nothing special for a team or other channel.
const chatHome: ChatHome = currentKwant
@@ -3406,6 +3463,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
<StarAsk needsYou={Object.keys(needsYouByKwant).length > 0} waiting={awaitingTurns.size > 0 || pendingApprovals.length > 0} />
<Toasts toasts={toasts} onDismiss={dismissToast} />
+ <NeedsYouPill items={pill.items} rev={pill.rev} spriteOf={spriteOf} onOpen={openPill} onDismiss={dismissPill} />
</div>
);
};
diff --git a/frontend/src/attention.ts b/frontend/src/attention.ts
new file mode 100644
index 00000000..099d71b8
--- /dev/null
+++ b/frontend/src/attention.ts
@@ -0,0 +1,338 @@
+// "Needs you" nudges for the web app and the PWA (0.6.9): an in-app pill when a NEW question, approval
+// or browser step arrives for a chat the person isn't looking at, the "!" favicon while something
+// waits, and the installed app's icon badge. Pure rules plus small browser helpers that tests drive
+// with fakes. The counts come from /api/away (`unseen.waiting`); nothing here invents a number.
+
+import type { AwayItem } from './away';
+import { awayTarget } from './away';
+import { dotGeometry } from './tabSignal';
+
+export type NudgeKind = 'question' | 'approval' | 'human_step';
+
+/** One thing the pill can show. `away` (questions, approvals) or `kwantId`/`channelId` (browser steps) say where a click goes. */
+export interface Nudge {
+ key: string;
+ kind: NudgeKind;
+ kwantId: string;
+ kwantName: string;
+ title: string;
+ /** The chat it belongs to: a thread id, a channel id or the bot's direct chat id. */
+ ctx: string;
+ away?: AwayItem;
+ channelId?: string | null;
+}
+
+/** How long the pill stays when nobody hovers or focuses it (Mira's pill: 5 s, then 2 s after the pointer leaves). */
+export const PILL_MS = 5000;
+export const PILL_AFTER_HOVER_MS = 2000;
+/** Hard cap from when the pill first appeared: a stream of arrivals can't pin it (hover and focus still hold it). */
+export const PILL_CAP_MS = 12000;
+
+/**
+ * How long the pill waits before it goes, counted from now. `elapsed` is the time since it first appeared;
+ * `held` means the pointer or focus has been on it and left. After a hold it goes 2 s later, whatever the
+ * cap says, so nobody is cut off mid-read. Otherwise 5 s from the last arrival, but never past the cap.
+ */
+export function pillHoldMs(elapsed: number, held: boolean): number {
+ if (held) return PILL_AFTER_HOVER_MS;
+ return Math.max(0, Math.min(PILL_MS, PILL_CAP_MS - elapsed));
+}
+/** The leave animation before it unmounts. */
+export const PILL_LEAVE_MS = 160;
+/** The same browser step announced twice within this window is one arrival. */
+export const STEP_DEDUPE_MS = 60_000;
+
+export const NUDGES_KEY = 'kwnt_nudges';
+export const NUDGES_SETTING_EVENT = 'kwnt-nudges-setting';
+
+/** The chat an away item lives in, the same id the app uses for the open chat. */
+export function awayCtx(item: Pick<AwayItem, 'kwant_id' | 'link'>): string {
+ const t = awayTarget(item);
+ return 'thread' in t ? t.thread : 'channel' in t ? t.channel : t.direct;
+}
+
+export function nudgeFromAway(item: AwayItem): Nudge | null {
+ if (item.kind !== 'question' && item.kind !== 'approval') return null;
+ return {
+ key: `${item.kind}:${item.id}`,
+ kind: item.kind,
+ kwantId: item.kwant_id,
+ kwantName: item.kwant_name,
+ title: item.title,
+ ctx: awayCtx(item),
+ away: item,
+ };
+}
+
+/** What the person is looking at right now. `looking` is the open chat id, or 'inbox' on the Inbox. */
+export interface AttentionView {
+ /** The open chat (thread, channel or direct chat id) while a chat is on screen, else null. */
+ openCtx: string | null;
+ /** On the Inbox every waiting item is already in front of them. */
+ onInbox: boolean;
+ /** The tab is in the background: the OS notification or push covers it. */
+ hidden: boolean;
+ /** The "Show nudges" setting. */
+ enabled: boolean;
+}
+
+/** Whether a new arrival gets the pill. It is marked seen either way, so it never pops later. */
+export function shouldPill(n: Pick<Nudge, 'ctx'>, view: AttentionView): boolean {
+ if (!view.enabled || view.hidden || view.onInbox) return false;
+ return view.openCtx !== n.ctx;
+}
+
+/**
+ * Remembers which waiting ids it has seen. The first list primes it (what already waits when the
+ * app opens is shown by the badge, title and Inbox, not by a pill); after that only ids it has
+ * never seen are arrivals.
+ */
+export function createArrivals() {
+ let primed = false;
+ const seen = new Set<string>();
+ const steps = new Map<string, number>();
+ return {
+ /** The waiting list from /api/away: the new items, in the server's order (newest first). */
+ fromAway(items: readonly AwayItem[]): Nudge[] {
+ const nudges = items.map(nudgeFromAway).filter((n): n is Nudge => !!n);
+ const fresh = primed ? nudges.filter((n) => !seen.has(n.key)) : [];
+ for (const n of nudges) seen.add(n.key);
+ primed = true;
+ // Keep the set small: ids that stopped waiting can't come back under the same id.
+ if (seen.size > 500) {
+ const live = new Set(nudges.map((n) => n.key));
+ for (const k of seen) if (!live.has(k)) seen.delete(k);
+ }
+ return fresh;
+ },
+ /** A browser step the bot handed over (not in /api/away): one arrival per bot and title a minute. */
+ fromHumanStep(ev: { kwant_id: string; kwant_name: string; channel_id: string | null; title: string; body?: string }, now = Date.now()): Nudge | null {
+ const title = ev.body || ev.title;
+ const key = `human_step:${ev.kwant_id}:${title}`;
+ const last = steps.get(key);
+ steps.set(key, now);
+ if (last !== undefined && now - last < STEP_DEDUPE_MS) return null;
+ return { key, kind: 'human_step', kwantId: ev.kwant_id, kwantName: ev.kwant_name, title, ctx: ev.channel_id ?? ev.kwant_id, channelId: ev.channel_id };
+ },
+ get primed() {
+ return primed;
+ },
+ };
+}
+
+/** The pill's queue: arrivals while it shows coalesce into one "N things need you". */
+export interface PillState {
+ items: Nudge[];
+ /** Bumped on every change, so the 5 s timer restarts when more arrive. */
+ rev: number;
+}
+
+export const EMPTY_PILL: PillState = { items: [], rev: 0 };
+
+export function pillAdd(state: PillState, arrivals: readonly Nudge[]): PillState {
+ const keys = new Set(state.items.map((n) => n.key));
+ const add = arrivals.filter((n) => !keys.has(n.key) && (keys.add(n.key), true));
+ if (!add.length) return state;
+ return { items: [...add, ...state.items], rev: state.rev + 1 };
+}
+
+/** Drops questions and approvals that stopped waiting (answered elsewhere) while the pill shows. */
+export function pillPrune(state: PillState, waitingKeys: ReadonlySet<string>): PillState {
+ const items = state.items.filter((n) => n.kind === 'human_step' || waitingKeys.has(n.key));
+ return items.length === state.items.length ? state : { items, rev: state.rev + 1 };
+}
+
+/** Who several items are from (Mira's pill, line 2): "All from Juno", "Juno and Lin", "Juno, Lin and 2 more". */
+export function fromNames(items: readonly Pick<Nudge, 'kwantName'>[]): string {
+ const u = [...new Set(items.map((i) => i.kwantName || 'A bot'))];
+ if (u.length === 1) return `All from ${u[0]}`;
+ if (u.length <= 3) return `${u.slice(0, -1).join(', ')} and ${u[u.length - 1]}`;
+ return `${u.slice(0, 2).join(', ')} and ${u.length - 2} more`;
+}
+
+const VERB: Record<NudgeKind, string> = { approval: 'needs your OK', question: 'asked you something', human_step: 'needs you to do a step' };
+
+/** The pill's two lines. One item: who and what; several: how many and from whom, and it opens the Inbox. */
+export function pillText(items: readonly Pick<Nudge, 'kind' | 'kwantName' | 'title'>[]): { headline: string; detail: string; action: string } {
+ if (items.length > 1) return { headline: `${items.length} things need you`, detail: fromNames(items), action: 'Open the Inbox' };
+ const n = items[0];
+ if (!n) return { headline: '', detail: '', action: '' };
+ return { headline: `${n.kwantName || 'A bot'} ${VERB[n.kind]}`, detail: n.title, action: 'Open the chat' };
+}
+
+// ---------------------------------------------------------------------------
+// Browser glue. Each helper takes an env (the browser's globals by default) and never throws.
+
+export interface AttentionEnv {
+ navigator?: {
+ setAppBadge?: (n?: number) => Promise<void>;
+ clearAppBadge?: () => Promise<void>;
+ };
+ matchMedia?: (query: string) => { matches: boolean };
+ localStorage?: Pick<Storage, 'getItem' | 'setItem'>;
+ dispatchEvent?: (e: Event) => boolean;
+}
+
+const browserEnv = (): AttentionEnv => globalThis as unknown as AttentionEnv;
+
+/** "Show nudges": on unless the person switched it off. */
+export function nudgesEnabled(env: AttentionEnv = browserEnv()): boolean {
+ try {
+ return env.localStorage?.getItem(NUDGES_KEY) !== 'off';
+ } catch {
+ return true;
+ }
+}
+
+export function setNudgesEnabled(on: boolean, env: AttentionEnv = browserEnv()): void {
+ try {
+ env.localStorage?.setItem(NUDGES_KEY, on ? 'on' : 'off');
+ } catch {
+ // storage blocked: the choice lasts until reload
+ }
+ try {
+ if (typeof CustomEvent !== 'undefined') env.dispatchEvent?.(new CustomEvent(NUDGES_SETTING_EVENT, { detail: on }));
+ } catch {
+ // no event target
+ }
+}
+
+/** The pill's entrance: a drop with a small spring, or a plain fade when the device asks for less motion. */
+export function pillMotion(env: AttentionEnv = browserEnv()): 'drop' | 'fade' {
+ try {
+ return env.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 'fade' : 'drop';
+ } catch {
+ return 'drop';
+ }
+}
+
+/** Whether this browser can badge the installed app's icon (Chrome/Edge desktop, Android, iOS 16.4+ home-screen apps). */
+export function canBadge(env: AttentionEnv = browserEnv()): boolean {
+ return typeof env.navigator?.setAppBadge === 'function';
+}
+
+/** The app icon shows how many things wait; cleared at 0. Information, not motion: the setting doesn't turn it off. */
+export function setAppBadgeCount(waiting: number, env: AttentionEnv = browserEnv()): 'set' | 'cleared' | 'unsupported' {
+ const nav = env.navigator;
+ if (!nav || typeof nav.setAppBadge !== 'function') return 'unsupported';
+ try {
+ if (waiting > 0) {
+ nav.setAppBadge.call(nav, waiting)?.catch?.(() => undefined);
+ return 'set';
+ }
+ if (typeof nav.clearAppBadge === 'function') nav.clearAppBadge.call(nav)?.catch?.(() => undefined);
+ else nav.setAppBadge.call(nav, 0)?.catch?.(() => undefined);
+ return 'cleared';
+ } catch {
+ return 'unsupported';
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The "!" favicon. Pixel's tab signal (tabSignal.ts) owns the violet "working" dot; while something
+// waits the "!" wins and the app passes working=false to it.
+
+/** Fallback drawing colours (the AvatarMood "needs you" amber) for a page whose icon has no "!" variant. */
+export const NUDGE_ICON = { fill: '#ffb020', ring: '#120e26', ink: '#1b1033' };
+
+interface LinkLike { href: string; type?: string }
+export interface IconDoc {
+ iconLink(): LinkLike | null;
+ /** The icon with the "!" badge as an image URL, or null when it can't be drawn. */
+ drawMarked(originalHref: string): Promise<string | null>;
+}
+
+/**
+ * Whether two icon hrefs are the same address. A real <link>'s href reads back absolute
+ * ("https://host/icon-needs-you.svg") while the one set may be relative, so compare them resolved.
+ */
+export function sameUrl(a: string, b: string): boolean {
+ if (a === b) return true;
+ try {
+ // Resolve against the page, then the set href against the link's own (absolute) address.
+ const base = typeof location !== 'undefined' && location.href ? location.href : 'http://localhost/';
+ const abs = new URL(a, base).href;
+ return new URL(b, abs).href === abs;
+ } catch {
+ return false;
+ }
+}
+
+export function createNudgeIcon(doc: IconDoc) {
+ const first = doc.iconLink();
+ const original = first ? { href: first.href, type: first.type } : null;
+ let want = false;
+ let ticket = 0;
+ let marked: string | null = null;
+ return {
+ async set(on: boolean) {
+ const link = doc.iconLink();
+ if (!link || !original || want === on) return;
+ want = on;
+ const mine = ++ticket;
+ if (on) {
+ const url = marked ?? (await doc.drawMarked(original.href));
+ if (url) marked = url;
+ if (url && want && mine === ticket) {
+ link.href = url;
+ link.type = /\.svg(\?|$)/.test(url) ? 'image/svg+xml' : 'image/png';
+ }
+ } else if (marked && sameUrl(link.href, marked)) {
+ link.href = original.href;
+ if (original.type !== undefined) link.type = original.type;
+ }
+ },
+ };
+}
+
+/** Mira's "!" favicon (design/web/icon-needs-you.svg), shipped next to icon.svg. */
+export const NEEDS_YOU_ICON = '/icon-needs-you.svg';
+
+/** The "!" variant of a page icon: Mira's SVG for kwant's own icon, else null (draw one). */
+export function markedIconFor(href: string): string | null {
+ try {
+ const u = new URL(href, 'http://x');
+ return u.pathname === '/icon.svg' ? NEEDS_YOU_ICON : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The real document: Mira's "!" icon, or the page's icon on a canvas with an amber "!" badge. */
+export function browserIconDoc(): IconDoc {
+ return {
+ iconLink: () => document.querySelector<HTMLLinkElement>('link[rel~="icon"]'),
+ drawMarked: (href) =>
+ markedIconFor(href) ? Promise.resolve(markedIconFor(href)) : new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => {
+ try {
+ const size = 64;
+ const c = document.createElement('canvas');
+ c.width = c.height = size;
+ const g = c.getContext('2d');
+ if (!g) return resolve(null);
+ g.drawImage(img, 0, 0, size, size);
+ const { cx, cy, ring } = dotGeometry(size);
+ const r = Math.round(size * 0.24);
+ const x = Math.min(cx, size - r - ring - 1);
+ const y = Math.min(cy, size - r - ring - 1);
+ g.fillStyle = NUDGE_ICON.ring;
+ g.beginPath(); g.arc(x, y, r + ring, 0, Math.PI * 2); g.fill();
+ g.fillStyle = NUDGE_ICON.fill;
+ g.beginPath(); g.arc(x, y, r, 0, Math.PI * 2); g.fill();
+ // "!" in whole pixels: a bar and a dot.
+ const w = Math.max(2, Math.round(r * 0.32));
+ g.fillStyle = NUDGE_ICON.ink;
+ g.fillRect(Math.round(x - w / 2), Math.round(y - r * 0.62), w, Math.round(r * 0.78));
+ g.fillRect(Math.round(x - w / 2), Math.round(y + r * 0.3), w, w);
+ resolve(c.toDataURL('image/png'));
+ } catch {
+ resolve(null);
+ }
+ };
+ img.onerror = () => resolve(null);
+ img.src = href;
+ }),
+ };
+}
diff --git a/frontend/src/components/NeedsYouPill.tsx b/frontend/src/components/NeedsYouPill.tsx
new file mode 100644
index 00000000..0c31d2cf
--- /dev/null
+++ b/frontend/src/components/NeedsYouPill.tsx
@@ -0,0 +1,193 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { ChevronRight } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { AvatarMood } from './AvatarMood';
+import { isPhoneLayout } from '../layout';
+import { PILL_LEAVE_MS, pillHoldMs, pillMotion, pillText, type Nudge } from '../attention';
+
+export interface NeedsYouPillProps {
+ items: Nudge[];
+ /** Bumped when more arrive: the 5 s start again and the text swaps in. */
+ rev: number;
+ /** The avatar sprite for a bot, when the roster has it. */
+ spriteOf: (kwantId: string) => string | undefined;
+ /** One item opens its chat; several open the Inbox. */
+ onOpen: (items: Nudge[]) => void;
+ /** The pill has slid out: clear `rev`, unless more arrived since (then the app keeps them). */
+ onDismiss: (rev: number) => void;
+}
+
+const AVATAR = 32;
+
+/**
+ * Where the main pane starts on desktop (the sidebar's right edge), measured while the pill shows. 0 in the
+ * phone layout (below 768 px, App's PHONE_QUERY), where there is no sidebar: measuring one there put the pill
+ * off-screen between 640 and 767 px (Rigel's R-1).
+ *
+ * A resize is measured again two frames later, once React has swapped the layout: widening from the phone
+ * layout fires `resize` while the full-width chat list is still in the sidebar's place, and measuring only
+ * then left the pill at the window's right edge (Rigel's R-2). A "sidebar" that spans the window is that
+ * list, never the desktop sidebar, so it does not count either.
+ */
+function useMainPaneLeft(showing: boolean): number {
+ const [left, setLeft] = useState(0);
+ useEffect(() => {
+ if (!showing || typeof window === 'undefined') return;
+ const measure = () => {
+ const side = isPhoneLayout() ? null : document.querySelector('[data-kw-sidebar]');
+ const r = side?.getBoundingClientRect();
+ setLeft(r && r.width > 0 && r.right < window.innerWidth - 1 ? Math.round(r.right) : 0);
+ };
+ const raf = window.requestAnimationFrame?.bind(window) ?? ((f: FrameRequestCallback) => window.setTimeout(() => f(0), 16));
+ const caf = window.cancelAnimationFrame?.bind(window) ?? window.clearTimeout.bind(window);
+ let frame = 0;
+ const onResize = () => {
+ measure();
+ caf(frame);
+ frame = raf(() => { frame = raf(measure); });
+ };
+ measure();
+ window.addEventListener('resize', onResize);
+ return () => {
+ window.removeEventListener('resize', onResize);
+ caf(frame);
+ };
+ }, [showing]);
+ return left;
+}
+
+/**
+ * The in-app "needs you" pill (0.6.9, Mira's mac-nudge/design/pill): drops from the top of the app for
+ * 5 s when a bot needs the person in a chat they aren't looking at. More arriving restarts the 5 s, but
+ * never past 12 s after it first appeared. Hover or keyboard focus holds it for as long as it lasts
+ * (WCAG 2.2.1), then it goes 2 s after the pointer or focus leaves. Esc dismisses it, a click goes
+ * there. Always dark: the app is dark only (Mira's spec §2). It never decides anything: there is no
+ * Allow or Deny here.
+ */
+export const NeedsYouPill: React.FC<NeedsYouPillProps> = ({ items, rev, spriteOf, onOpen, onDismiss }) => {
+ const [hovered, setHovered] = useState(false);
+ const [focused, setFocused] = useState(false);
+ const [heldOnce, setHeldOnce] = useState(false);
+ const [leaving, setLeaving] = useState(false);
+ const [motion] = useState(pillMotion);
+ const showing = items.length > 0;
+ // The rev the current pill opened with: a later rev means more arrived and the text swaps in.
+ const firstRev = useRef(rev);
+ const wasShowing = useRef(false);
+ // When the current pill first appeared: arrivals restart the hold only up to PILL_CAP_MS after this.
+ const shownAt = useRef(0);
+ if (showing && !wasShowing.current) {
+ firstRev.current = rev;
+ shownAt.current = Date.now();
+ }
+ wasShowing.current = showing;
+
+ // A new pill starts fresh; more arriving swaps the text in place.
+ useEffect(() => {
+ if (!showing) {
+ setHovered(false);
+ setFocused(false);
+ setHeldOnce(false);
+ setLeaving(false);
+ }
+ }, [showing]);
+
+ // The rev the pill was showing when it began to slide out. If more arrive during the slide-out, that
+ // exit must not take them with it (the race Lin found in the Mac pill, #268): a fresh pill drops in
+ // instead, and the app is only told to clear the rev that actually left.
+ // An item answered elsewhere during the slide-out bumps rev too, but that is not an arrival: keep going.
+ const leavingRev = useRef(rev);
+ const leavingKeys = useRef<ReadonlySet<string>>(new Set());
+ const leave = () => {
+ leavingRev.current = rev;
+ leavingKeys.current = new Set(items.map((n) => n.key));
+ setLeaving(true);
+ };
+ useEffect(() => {
+ if (!leaving) return;
+ if (rev !== leavingRev.current) {
+ if (items.some((n) => !leavingKeys.current.has(n.key))) {
+ firstRev.current = rev;
+ shownAt.current = Date.now();
+ setHeldOnce(false);
+ setLeaving(false);
+ return;
+ }
+ leavingRev.current = rev;
+ }
+ const gone = rev;
+ const t = setTimeout(() => onDismiss(gone), PILL_LEAVE_MS);
+ return () => clearTimeout(t);
+ }, [leaving, rev, items, onDismiss]);
+
+ useEffect(() => {
+ if (!showing || hovered || focused || leaving) return;
+ const t = setTimeout(leave, pillHoldMs(Date.now() - shownAt.current, heldOnce));
+ return () => clearTimeout(t);
+ }, [showing, hovered, focused, leaving, heldOnce, rev]);
+
+ // Desktop: centred on the main pane, not the window (Mira's spec §4), so it starts where the sidebar ends.
+ const paneLeft = useMainPaneLeft(showing);
+
+ const text = pillText(items);
+ const lead = items[0];
+ const many = items.length > 1;
+ const swapping = showing && rev !== firstRev.current;
+
+ return (
+ <div
+ className="kw-nudge-region"
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ style={paneLeft ? ({ '--kw-nudge-left': `${paneLeft}px` } as React.CSSProperties) : undefined}
+ >
+ {showing && lead && (
+ <button
+ type="button"
+ className={`kw-nudge${leaving ? ' is-leaving' : ''}${swapping ? ' is-swapping' : ''}`}
+ key={firstRev.current}
+ data-motion={motion}
+ data-count={items.length}
+ onClick={() => onOpen(items)}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => {
+ setHovered(false);
+ setHeldOnce(true);
+ }}
+ onFocus={() => setFocused(true)}
+ onBlur={() => {
+ setFocused(false);
+ setHeldOnce(true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ leave();
+ }
+ }}
+ >
+ <span className="kw-nudge__av" key={`av${rev}`} aria-hidden="true">
+ {many ? (
+ <span className="kw-nudge__count">{items.length > 9 ? '9+' : items.length}</span>
+ ) : (
+ <ModernAvatar role={spriteOf(lead.kwantId)} name={lead.kwantName} size={AVATAR} />
+ )}
+ <AvatarMood mood="needs_you" size={AVATAR} />
+ </span>
+ <span className="kw-nudge__text" key={`t${rev}`}>
+ <span className="kw-nudge__l1">{text.headline}</span>
+ {text.detail && (
+ <>
+ <span className="sr-only">: </span>
+ <span className="kw-nudge__l2">{text.detail}</span>
+ </>
+ )}
+ <span className="sr-only">. {text.action}. Escape dismisses.</span>
+ </span>
+ <ChevronRight className="kw-nudge__chev" size={14} strokeWidth={2.25} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 11bdf712..c52867e4 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,7 +1,7 @@
import React, { useState, useEffect, useRef } from 'react';
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 } from 'lucide-react';
+import { Key, X, Settings, Check, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles, KanbanSquare, BellRing } from 'lucide-react';
import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';
import { DailyUsagePanel } from './DailyUsage';
import {
@@ -23,6 +23,7 @@ import { deviceNotifyHint, deviceNotifySupport, isAndroid, notifyEnv as browserN
const readNotifyEnv = () => ({ ...browserNotifyEnv(), android: isAndroid(navigator) });
import { isSfxMuted, playSfx, toggleSfxMute } from '../audio/chiptune';
import { haptic, hapticsAvailable, hapticsEnabled, setHapticsEnabled } from '../haptics';
+import { nudgesEnabled, setNudgesEnabled } from '../attention';
import { useAuth } from './AuthGate';
import { SignedInDevices } from './DeviceSignIn';
import { signedInDevicesVisible } from '../deviceSignIn';
@@ -297,6 +298,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const computer = useComputerMode(isOpen);
const [sfxMuted, setSfxMuted] = useState(isSfxMuted);
const [vibration, setVibration] = useState(hapticsEnabled);
+ const [nudges, setNudges] = useState(nudgesEnabled);
const [settings, setSettings] = useState<SettingsData | null>(null);
const [saving, setSaving] = useState(false);
const [saveSuccess, setSaveSuccess] = useState(false);
@@ -587,6 +589,31 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</span>
</div>
)}
+ <div className="flex items-center gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">
+ <span className="flex-1 text-xs font-medium text-zinc-200 flex items-center gap-2">
+ <BellRing size={15} className={nudges ? 'text-amber-400' : 'text-zinc-500'} aria-hidden="true" />
+ <span id="nudges-label">Show nudges</span>
+ </span>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={nudges}
+ aria-labelledby="nudges-label"
+ aria-describedby="nudges-hint"
+ onClick={() => {
+ setNudgesEnabled(!nudges);
+ setNudges(!nudges);
+ }}
+ className={`relative shrink-0 w-9 h-5 rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ nudges ? 'bg-sky-600' : 'bg-zinc-700'
+ }`}
+ >
+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${nudges ? 'translate-x-4' : ''}`} />
+ </button>
+ <span id="nudges-hint" className="sr-only">
+ A short note at the top of the app when a bot needs you in another chat, and a mark on the tab. The app icon count stays.
+ </span>
+ </div>
<div className="flex items-center gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">
<Gauge size={15} className="text-zinc-500" aria-hidden="true" />
<span className="flex-1 text-xs font-medium text-zinc-200">Token usage, open chat</span>
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index a7abd4d3..2aa539d6 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -634,6 +634,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
<aside
ref={asideRef}
aria-label={`${space.name} chats and kwant bots`}
+ 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`}
>
{/* The open space. Desktop switches spaces on the rail, so this is its name and settings;
diff --git a/frontend/src/layout.ts b/frontend/src/layout.ts
new file mode 100644
index 00000000..64377ced
--- /dev/null
+++ b/frontend/src/layout.ts
@@ -0,0 +1,5 @@
+/** Below 768 px the app is one column (a list or a chat, with a tab bar) and the sidebar is not shown. */
+export const PHONE_QUERY = '(max-width: 767px)';
+
+/** The phone layout is on: no sidebar, so nothing on screen should be placed from it. */
+export const isPhoneLayout = (): boolean => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches;
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index c3823cf1..43805edf 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -7,6 +7,7 @@ import { captureInstallPrompt, registerServiceWorker, trackAppHeight } from './p
import './styles/fonts.css';
import './styles/modern.css';
import './styles/stream.css';
+import './styles/needsYou.css';
registerServiceWorker();
captureInstallPrompt();
diff --git a/frontend/src/styles/needsYou.css b/frontend/src/styles/needsYou.css
new file mode 100644
index 00000000..0a4b55d1
--- /dev/null
+++ b/frontend/src/styles/needsYou.css
@@ -0,0 +1,89 @@
+/* The in-app "needs you" pill (0.6.9, NeedsYouPill.tsx). Values from Mira's
+ /home/maus/shared/ship-software-safely/mac-nudge/design/pill/pill.css: one design for the Mac
+ menu-bar pill and the in-app pill. Motion: transform and opacity only. Always dark: the app is dark
+ only, so the light tokens are for Lin's Mac pill webview alone (spec §2). Own file so Pixel's
+ modern.css stays untouched. */
+.kw-nudge-region {
+ position: fixed;
+ top: calc(env(safe-area-inset-top, 0px) + 12px);
+ /* Centred on the main pane: NeedsYouPill sets --kw-nudge-left to where the sidebar ends (desktop only). */
+ left: var(--kw-nudge-left, 0px);
+ right: 0;
+ z-index: 70;
+ display: flex;
+ justify-content: center;
+ padding: 0 12px;
+ pointer-events: none;
+}
+
+.kw-nudge {
+ --kw-n-bg: #231d4b; --kw-n-edge: rgb(255 255 255 / .10);
+ --kw-n-t1: #f7f6ff; --kw-n-t2: #bcb7de; --kw-n-chev: #9a94c4;
+ --kw-n-shadow: 0 10px 28px rgb(0 0 0 / .45), 0 1px 3px rgb(0 0 0 / .35);
+ pointer-events: auto;
+ position: relative; box-sizing: border-box;
+ display: flex; align-items: center; gap: 10px;
+ width: 320px; max-width: 100%; height: 52px; padding: 0 12px 0 10px; margin: 0;
+ border: 0; border-radius: 26px;
+ background: var(--kw-n-bg); color: var(--kw-n-t1);
+ box-shadow: inset 0 0 0 1px var(--kw-n-edge), var(--kw-n-shadow);
+ text-align: left; cursor: pointer; user-select: none; -webkit-user-select: none;
+ transform-origin: 50% 0;
+ animation: kw-nudge-rise 200ms cubic-bezier(.34, 1.56, .64, 1) backwards,
+ kw-nudge-fade 120ms linear backwards;
+ transition: transform 80ms ease-out;
+}
+.kw-nudge:active { transform: scale(.98); }
+.kw-nudge:focus-visible { outline: 2px solid #b8adff; outline-offset: 2px; }
+.kw-nudge.is-leaving { animation: kw-nudge-leave 160ms cubic-bezier(.4, 0, 1, 1) forwards; pointer-events: none; }
+
+/* Avatar: ModernAvatar size 32 in Mira's 32 px box; several = the count on her lavender disc. */
+.kw-nudge__av {
+ position: relative; flex: none; width: 32px; height: 32px; border-radius: 50%;
+ display: inline-flex; align-items: center; justify-content: center;
+ --kw-avatar-cut: var(--kw-n-bg);
+ animation: kw-nudge-hop 200ms 200ms backwards;
+}
+.kw-nudge__count {
+ width: 32px; height: 32px; border-radius: 50%;
+ background: #b8adff; color: #1b1033;
+ font-size: 15px; line-height: 32px; font-weight: 700; text-align: center;
+}
+/* AvatarMood "needs you" badge (7x7 plate, 2 px cells, "!" #ffb020) pops in after the drop. */
+.kw-nudge__av .kw-mood { animation: kw-nudge-pop 160ms 200ms cubic-bezier(.34, 1.56, .64, 1) backwards; }
+.kw-nudge__text { flex: 1; min-width: 0; }
+.kw-nudge__l1, .kw-nudge__l2 { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.kw-nudge__l1 { font-size: 13px; line-height: 16px; font-weight: 600; letter-spacing: -.08px; }
+.kw-nudge__l2 { font-size: 12px; line-height: 16px; font-weight: 400; color: var(--kw-n-t2); }
+.kw-nudge__chev { flex: none; width: 14px; height: 14px; color: var(--kw-n-chev); }
+.kw-nudge.is-swapping .kw-nudge__text { animation: kw-nudge-fade 120ms linear backwards; }
+.kw-nudge.is-swapping .kw-nudge__av { animation: kw-nudge-hop 200ms backwards; }
+
+/* Phone layout (viewport < 768 px, App's PHONE_QUERY): full width less 12 px a side, 56 px tall. */
+@media (max-width: 767px) {
+ .kw-nudge-region { top: calc(env(safe-area-inset-top, 0px) + 8px); left: 0; }
+ .kw-nudge { width: calc(100vw - 24px); max-width: 420px; height: 56px; border-radius: 28px; padding-left: 12px; }
+}
+
+@keyframes kw-nudge-rise { from { transform: translateY(-16px) scale(.94); } to { transform: none; } }
+@keyframes kw-nudge-fade { from { opacity: 0; } to { opacity: 1; } }
+@keyframes kw-nudge-leave { to { transform: translateY(-8px); opacity: 0; } }
+@keyframes kw-nudge-hop {
+ 0% { transform: none; animation-timing-function: cubic-bezier(.2, 0, .4, 1); }
+ 50% { transform: translateY(-4px); animation-timing-function: cubic-bezier(.6, 0, .8, 1); }
+ 100% { transform: none; }
+}
+@keyframes kw-nudge-pop { from { transform: scale(.4); opacity: 0; } to { transform: none; opacity: 1; } }
+@keyframes kw-nudge-fadeout { to { opacity: 0; } }
+
+/* Reduce Motion: fade in and out only. data-motion="fade" is the same for browsers that report it to JS only. */
+@media (prefers-reduced-motion: reduce) {
+ .kw-nudge { animation: kw-nudge-fade 160ms linear backwards; transition: none; }
+ .kw-nudge:active { transform: none; }
+ .kw-nudge.is-leaving { animation: kw-nudge-fadeout 160ms linear forwards; }
+ .kw-nudge__av, .kw-nudge__av .kw-mood, .kw-nudge.is-swapping .kw-nudge__av { animation: none; }
+}
+.kw-nudge[data-motion="fade"] { animation: kw-nudge-fade 160ms linear backwards; transition: none; }
+.kw-nudge[data-motion="fade"].is-leaving { animation: kw-nudge-fadeout 160ms linear forwards; }
+.kw-nudge[data-motion="fade"] .kw-nudge__av,
+.kw-nudge[data-motion="fade"] .kw-nudge__av .kw-mood { animation: none; }
diff --git a/frontend/sw.js b/frontend/sw.js
index 9b55b9a3..643f51e2 100644
--- a/frontend/sw.js
+++ b/frontend/sw.js
@@ -83,6 +83,9 @@ function inFront(client) {
return client.focused && client.visibilityState === 'visible';
}
+/** Pushes that mean a bot is waiting on the person (src/server/push.rs). */
+const NEEDS_YOU_KINDS = new Set(['approval_needed', 'question_asked', 'human_step']);
+
self.addEventListener('push', (event) => {
let p = {};
try {
@@ -101,6 +104,16 @@ self.addEventListener('push', (event) => {
event.waitUntil(
windows().then((list) => {
if (list.some(inFront)) return undefined;
+ // Something needs the person: a dot on the installed app's icon even while it is closed. The
+ // page sets the exact count when it opens. Feature-detected: not every browser badges.
+ if (NEEDS_YOU_KINDS.has(p.kind)) {
+ try {
+ const badged = self.navigator?.setAppBadge?.();
+ if (badged && typeof badged.catch === 'function') badged.catch(() => undefined);
+ } catch {
+ // no badge on this platform
+ }
+ }
return self.registration.showNotification(title, {
body: typeof p.body === 'string' ? p.body : '',
tag: typeof p.tag === 'string' && p.tag ? p.tag : undefined,
diff --git a/frontend/tests/attention.test.mjs b/frontend/tests/attention.test.mjs
new file mode 100644
index 00000000..02df15a3
--- /dev/null
+++ b/frontend/tests/attention.test.mjs
@@ -0,0 +1,348 @@
+// "Needs you" nudges for the web app and PWA (attention.ts, NeedsYouPill.tsx, sw.js badge).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import vm from 'node:vm';
+import { fileURLToPath } from 'node:url';
+import { loadBundled } from './bundle.mjs';
+
+const root = fileURLToPath(new URL('..', import.meta.url));
+const a = await loadBundled(`export * from './src/attention';`);
+const ui = await loadBundled(`
+ export { NeedsYouPill } from './src/components/NeedsYouPill';
+ export { createElement } from 'react';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+`);
+
+const item = (id, kind = 'question', link = { thread_id: null, channel_id: null, direct_kwant_id: 'k1' }, extra = {}) => ({
+ kind, id, kwant_id: 'k1', kwant_name: 'Juno', title: `Title ${id}`, summary: '', status: 'open', timestamp: '2026-11-03T21:00:00Z', link, ...extra,
+});
+const view = (o = {}) => ({ openCtx: null, onInbox: false, hidden: false, enabled: true, ...o });
+
+test('the first waiting list primes: what already waits never pops a pill', () => {
+ const arr = a.createArrivals();
+ assert.deepEqual(arr.fromAway([item('q1'), item('a1', 'approval')]), []);
+ assert.equal(arr.primed, true);
+});
+
+test('only ids never seen before are arrivals; the same id again is not', () => {
+ const arr = a.createArrivals();
+ arr.fromAway([item('q1')]);
+ const fresh = arr.fromAway([item('a2', 'approval'), item('q1')]);
+ assert.deepEqual(fresh.map((n) => n.key), ['approval:a2']);
+ assert.deepEqual(arr.fromAway([item('a2', 'approval'), item('q1')]), []);
+ // Gone and back under the same id stays seen: an answered card never nudges twice.
+ arr.fromAway([]);
+ assert.deepEqual(arr.fromAway([item('q1')]), []);
+});
+
+test('a question and an approval with the same id are different things', () => {
+ const arr = a.createArrivals();
+ arr.fromAway([item('x')]);
+ assert.deepEqual(arr.fromAway([item('x'), item('x', 'approval')]).map((n) => n.key), ['approval:x']);
+});
+
+test('finished, failed and handoff items never nudge', () => {
+ const arr = a.createArrivals();
+ arr.fromAway([]);
+ assert.deepEqual(arr.fromAway([item('d1', 'delegation'), item('r1', 'routine_run')]), []);
+});
+
+test('an item belongs to its thread, channel or direct chat', () => {
+ assert.equal(a.awayCtx(item('1', 'question', { thread_id: 't9', channel_id: 'c1', direct_kwant_id: null })), 't9');
+ assert.equal(a.awayCtx(item('1', 'question', { thread_id: null, channel_id: 'c1', direct_kwant_id: null })), 'c1');
+ assert.equal(a.awayCtx(item('1', 'question', { thread_id: null, channel_id: null, direct_kwant_id: null })), 'k1');
+});
+
+test('no pill for the chat you are looking at, on the Inbox, in a background tab, or with nudges off', () => {
+ const n = { ctx: 'k1' };
+ assert.equal(a.shouldPill(n, view()), true);
+ assert.equal(a.shouldPill(n, view({ openCtx: 'k2' })), true);
+ assert.equal(a.shouldPill(n, view({ openCtx: 'k1' })), false);
+ assert.equal(a.shouldPill(n, view({ onInbox: true })), false);
+ assert.equal(a.shouldPill(n, view({ hidden: true })), false);
+ assert.equal(a.shouldPill(n, view({ enabled: false })), false);
+});
+
+test('a browser step is one arrival per bot and title a minute', () => {
+ const arr = a.createArrivals();
+ const ev = { kwant_id: 'k1', kwant_name: 'Juno', channel_id: null, title: 'Juno needs a hand', body: 'Solve the CAPTCHA' };
+ const n = arr.fromHumanStep(ev, 1000);
+ assert.equal(n.kind, 'human_step');
+ assert.equal(n.ctx, 'k1');
+ assert.equal(n.title, 'Solve the CAPTCHA');
+ assert.equal(arr.fromHumanStep(ev, 30_000), null);
+ assert.ok(arr.fromHumanStep(ev, 30_000 + a.STEP_DEDUPE_MS));
+});
+
+test('arrivals while the pill shows coalesce, newest first, without duplicates', () => {
+ const arr = a.createArrivals();
+ arr.fromAway([]);
+ let s = a.pillAdd(a.EMPTY_PILL, arr.fromAway([item('q1')]));
+ assert.equal(s.items.length, 1);
+ const rev = s.rev;
+ s = a.pillAdd(s, arr.fromAway([item('a2', 'approval'), item('q3'), item('q1')]));
+ assert.deepEqual(s.items.map((n) => n.key), ['approval:a2', 'question:q3', 'question:q1']);
+ assert.ok(s.rev > rev, 'the 5 s start again');
+ assert.equal(a.pillAdd(s, [s.items[0]]), s, 'the same key twice changes nothing');
+ assert.equal(a.pillText(s.items).headline, '3 things need you');
+});
+
+test('something answered elsewhere leaves the pill; browser steps stay until it closes', () => {
+ const step = { key: 'human_step:k1:x', kind: 'human_step', kwantId: 'k1', kwantName: 'Juno', title: 'x', ctx: 'k1' };
+ const s = a.pillAdd(a.EMPTY_PILL, [a.nudgeFromAway(item('q1')), a.nudgeFromAway(item('a2', 'approval')), step]);
+ const pruned = a.pillPrune(s, new Set(['approval:a2']));
+ assert.deepEqual(pruned.items.map((n) => n.key), ['approval:a2', 'human_step:k1:x']);
+ assert.equal(a.pillPrune(pruned, new Set(['approval:a2'])), pruned);
+});
+
+test('the words: who and what for one, a count for several', () => {
+ assert.equal(a.pillText([a.nudgeFromAway(item('a1', 'approval'))]).headline, 'Juno needs your OK');
+ assert.equal(a.pillText([a.nudgeFromAway(item('q1'))]).headline, 'Juno asked you something');
+ assert.equal(a.pillText([a.nudgeFromAway(item('q1'))]).detail, 'Title q1');
+ assert.equal(a.pillText([{ kind: 'human_step', kwantName: 'Juno', title: 'x' }]).headline, 'Juno needs you to do a step');
+ assert.equal(a.pillText([a.nudgeFromAway(item('q1')), a.nudgeFromAway(item('q2'))]).detail, 'All from Juno');
+ assert.equal(a.fromNames([{ kwantName: 'Juno' }, { kwantName: 'Lin' }]), 'Juno and Lin');
+ assert.equal(a.fromNames([{ kwantName: 'Juno' }, { kwantName: 'Lin' }, { kwantName: 'Vega' }]), 'Juno, Lin and Vega');
+ assert.equal(a.fromNames(['A', 'B', 'C', 'D', 'E'].map((kwantName) => ({ kwantName }))), 'A, B and 3 more');
+ assert.equal(a.pillText([{ kind: 'question', kwantName: '', title: '' }]).headline, 'A bot asked you something');
+ assert.equal(a.pillText([]).headline, '');
+});
+
+const env = ({ stored = null, reduced = false, nav } = {}) => {
+ const store = new Map(stored === null ? [] : [[a.NUDGES_KEY, stored]]);
+ const events = [];
+ return {
+ store,
+ events,
+ env: {
+ navigator: nav,
+ matchMedia: (q) => ({ matches: reduced && q === '(prefers-reduced-motion: reduce)' }),
+ localStorage: { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, v) },
+ dispatchEvent: (e) => events.push(e.type) > 0,
+ },
+ };
+};
+
+test('"Show nudges" is on by default, remembers off, and tells the app', () => {
+ assert.equal(a.nudgesEnabled(env().env), true);
+ const e = env();
+ a.setNudgesEnabled(false, e.env);
+ assert.equal(e.store.get(a.NUDGES_KEY), 'off');
+ assert.equal(a.nudgesEnabled(e.env), false);
+ assert.deepEqual(e.events, [a.NUDGES_SETTING_EVENT]);
+ assert.equal(a.nudgesEnabled({ localStorage: { getItem: () => { throw new Error('blocked'); } } }), true);
+});
+
+test('Reduce Motion: the pill fades instead of dropping', () => {
+ assert.equal(a.pillMotion(env().env), 'drop');
+ assert.equal(a.pillMotion(env({ reduced: true }).env), 'fade');
+ assert.equal(a.pillMotion({}), 'drop');
+});
+
+test('app badge: feature-detected, the exact count, cleared at 0, never throws', async () => {
+ assert.equal(a.canBadge({}), false);
+ assert.equal(a.setAppBadgeCount(3, {}), 'unsupported');
+ assert.equal(a.setAppBadgeCount(3, { navigator: {} }), 'unsupported');
+ const calls = [];
+ const nav = {
+ setAppBadge(n) { if (this !== nav) throw new TypeError('Illegal invocation'); calls.push(['set', n]); return Promise.resolve(); },
+ clearAppBadge() { calls.push(['clear']); return Promise.resolve(); },
+ };
+ assert.equal(a.canBadge({ navigator: nav }), true);
+ assert.equal(a.setAppBadgeCount(2, { navigator: nav }), 'set');
+ assert.equal(a.setAppBadgeCount(0, { navigator: nav }), 'cleared');
+ assert.deepEqual(calls, [['set', 2], ['clear']]);
+ // Only setAppBadge (older Safari): 0 clears it.
+ const only = { setAppBadge: (n) => { calls.push(['only', n]); return Promise.resolve(); } };
+ assert.equal(a.setAppBadgeCount(0, { navigator: only }), 'cleared');
+ assert.deepEqual(calls.at(-1), ['only', 0]);
+ // A rejected promise (permission, not installed) is swallowed.
+ const rejecting = { setAppBadge: () => Promise.reject(new Error('NotAllowed')) };
+ assert.equal(a.setAppBadgeCount(1, { navigator: rejecting }), 'set');
+ const throwing = { setAppBadge: () => { throw new Error('nope'); } };
+ assert.equal(a.setAppBadgeCount(1, { navigator: throwing }), 'unsupported');
+ await new Promise((r) => setTimeout(r, 0));
+});
+
+test('kwant\'s own icon uses Mira\'s "!" SVG; any other icon is drawn', () => {
+ assert.equal(a.markedIconFor('/icon.svg'), '/icon-needs-you.svg');
+ assert.equal(a.markedIconFor('https://kwant.example/icon.svg'), '/icon-needs-you.svg');
+ assert.equal(a.markedIconFor('/other.png'), null);
+ const svg = readFileSync(`${root}/public/icon-needs-you.svg`, 'utf8');
+ assert.doesNotMatch(svg, /<script|\son\w+=/i);
+});
+
+test('an SVG "!" icon keeps the SVG type', async () => {
+ const link = { href: '/icon.svg', type: 'image/svg+xml' };
+ const icon = a.createNudgeIcon({ iconLink: () => link, drawMarked: async () => '/icon-needs-you.svg' });
+ await icon.set(true);
+ assert.deepEqual(link, { href: '/icon-needs-you.svg', type: 'image/svg+xml' });
+});
+
+test('the "!" favicon goes on while something waits and gives the icon back after', async () => {
+ const link = { href: '/icon.svg', type: 'image/svg+xml' };
+ let draws = 0;
+ const icon = a.createNudgeIcon({ iconLink: () => link, drawMarked: async () => (draws++, 'data:image/png;base64,MARK') });
+ await icon.set(true);
+ assert.equal(link.href, 'data:image/png;base64,MARK');
+ assert.equal(link.type, 'image/png');
+ await icon.set(true);
+ await icon.set(false);
+ assert.deepEqual(link, { href: '/icon.svg', type: 'image/svg+xml' });
+ await icon.set(true);
+ assert.equal(draws, 1, 'drawn once, reused');
+ // Something else changed the icon meanwhile (the working dot): left alone.
+ link.href = 'data:image/png;base64,DOT';
+ await icon.set(false);
+ assert.equal(link.href, 'data:image/png;base64,DOT');
+});
+
+test('the "!" favicon comes back off when the link reads its href back absolute, like a real <link>', async () => {
+ // A browser's HTMLLinkElement.href always returns the resolved URL, whatever was set.
+ const base = 'https://kwant.example/chat/abc';
+ let raw = '/icon.svg';
+ const link = { type: 'image/svg+xml', get href() { return new URL(raw, base).href; }, set href(v) { raw = v; } };
+ const icon = a.createNudgeIcon({ iconLink: () => link, drawMarked: async () => '/icon-needs-you.svg' });
+ await icon.set(true);
+ assert.equal(link.href, 'https://kwant.example/icon-needs-you.svg');
+ await icon.set(false);
+ assert.equal(link.href, 'https://kwant.example/icon.svg', 'the last answer gives the normal icon back');
+ assert.ok(a.sameUrl('/x.svg', '/x.svg'));
+ assert.ok(!a.sameUrl('/x.svg', '/y.svg'));
+});
+
+test('the favicon draw resolving after nothing waits any more leaves the icon alone', async () => {
+ const link = { href: '/icon.svg' };
+ let release;
+ const icon = a.createNudgeIcon({ iconLink: () => link, drawMarked: () => new Promise((r) => (release = r)) });
+ const on = icon.set(true);
+ await icon.set(false);
+ release('data:x');
+ await on;
+ assert.equal(link.href, '/icon.svg');
+});
+
+// The component, rendered to markup.
+
+const render = (items, matchMedia) => {
+ const before = globalThis.matchMedia;
+ globalThis.matchMedia = matchMedia;
+ try {
+ return ui.renderToStaticMarkup(ui.createElement(ui.NeedsYouPill, { items, rev: 1, spriteOf: () => 'violet', onOpen: () => {}, onDismiss: () => {} }));
+ } finally {
+ globalThis.matchMedia = before;
+ }
+};
+
+test('the pill is a polite live region with a button that goes there, and no Allow or Deny', () => {
+ const html = render([a.nudgeFromAway(item('a1', 'approval'))]);
+ assert.match(html, /role="status"/);
+ assert.match(html, /aria-live="polite"/);
+ assert.match(html, /Juno needs your OK/);
+ assert.match(html, /Title a1/);
+ assert.match(html, /Open the chat/);
+ assert.match(html, /Escape dismisses/);
+ assert.match(html, /data-mood="needs_you"/);
+ assert.doesNotMatch(html, /Allow|Deny|Approve/i);
+ assert.match(html, /data-motion="drop"/);
+});
+
+test('the pill under Reduce Motion is marked to fade', () => {
+ const html = render([a.nudgeFromAway(item('q1'))], (q) => ({ matches: q === '(prefers-reduced-motion: reduce)' }));
+ assert.match(html, /data-motion="fade"/);
+});
+
+test('the pill is always dark, whatever the OS colour scheme', () => {
+ for (const scheme of ['light', 'dark']) {
+ const html = render([a.nudgeFromAway(item('q1'))], (q) => ({ matches: q === `(prefers-color-scheme: ${scheme})` }));
+ assert.doesNotMatch(html, /data-theme/);
+ }
+ const css = readFileSync(`${root}/src/styles/needsYou.css`, 'utf8');
+ assert.doesNotMatch(css, /data-theme|prefers-color-scheme/);
+ assert.doesNotMatch(css, /#ffffff/i);
+ assert.match(css, /--kw-n-bg: #231d4b/);
+ const src = readFileSync(`${root}/src/components/NeedsYouPill.tsx`, 'utf8');
+ assert.doesNotMatch(src, /prefers-color-scheme/);
+});
+
+test('the hold: 5 s from the last arrival, never past 12 s from first showing, 2 s after a hover or focus leaves', () => {
+ assert.equal(a.pillHoldMs(0, false), 5000);
+ assert.equal(a.pillHoldMs(8000, false), 4000);
+ assert.equal(a.pillHoldMs(11000, false), 1000);
+ assert.equal(a.pillHoldMs(13000, false), 0);
+ assert.equal(a.pillHoldMs(13000, true), 2000);
+ assert.equal(a.pillHoldMs(1000, true), 2000);
+});
+
+test('several in the pill read as a count that opens the Inbox', () => {
+ const html = render([a.nudgeFromAway(item('q1')), a.nudgeFromAway(item('a2', 'approval'))]);
+ assert.match(html, /2 things need you/);
+ assert.match(html, /Open the Inbox/);
+ assert.match(html, /data-count="2"/);
+});
+
+test('nothing waiting: the live region stays, empty', () => {
+ const html = render([]);
+ assert.match(html, /role="status"/);
+ assert.doesNotMatch(html, /kw-nudge-main/);
+});
+
+test('reduced-motion CSS turns the drop and the hop off', () => {
+ const css = readFileSync(`${root}/src/styles/needsYou.css`, 'utf8');
+ const block = css.slice(css.indexOf('@media (prefers-reduced-motion: reduce)'));
+ assert.match(block, /kw-nudge-fade/);
+ assert.match(block, /\.kw-nudge__av, \.kw-nudge__av \.kw-mood, [^{]*\{ animation: none; \}/);
+ // Tap targets: 52 px desktop, 56 px phone.
+ assert.match(css, /height: 52px/);
+ assert.match(css, /height: 56px/);
+});
+
+// sw.js: a needs-you push badges the app icon even while kwant is closed.
+
+function worker({ badge = true, front = false } = {}) {
+ const code = readFileSync(`${root}/sw.js`, 'utf8').replace('__KWNT_SW_VERSION__', 'v').replace('__KWNT_SW_SHELL__', '[]');
+ const handlers = {};
+ const log = { badged: 0, shown: 0 };
+ const self = {
+ location: { origin: 'https://kwant.example' },
+ addEventListener: (type, fn) => { handlers[type] = fn; },
+ navigator: badge ? { setAppBadge: () => { log.badged++; return Promise.resolve(); } } : {},
+ registration: { showNotification: async () => { log.shown++; } },
+ clients: {
+ matchAll: async () => (front ? [{ url: 'https://kwant.example/', focused: true, visibilityState: 'visible' }] : []),
+ openWindow: async () => undefined,
+ claim: async () => undefined,
+ },
+ };
+ vm.runInNewContext(code, { self, URL, caches: {}, fetch: async () => ({ ok: true }) });
+ return {
+ log,
+ push: async (kind) => {
+ let waited;
+ handlers.push({ data: { json: () => ({ title: 't', kind }) }, waitUntil: (p) => { waited = p; } });
+ await waited;
+ },
+ };
+}
+
+test('sw.js: approvals, questions and browser steps badge the icon; other pushes do not', async () => {
+ for (const kind of ['approval_needed', 'question_asked', 'human_step']) {
+ const w = worker();
+ await w.push(kind);
+ assert.equal(w.log.badged, 1, kind);
+ assert.equal(w.log.shown, 1);
+ }
+ const other = worker();
+ await other.push('delegation_finished');
+ assert.equal(other.log.badged, 0);
+});
+
+test('sw.js: no badge API, or kwant in front, still works without one', async () => {
+ const none = worker({ badge: false });
+ await none.push('approval_needed');
+ assert.equal(none.log.shown, 1);
+ const front = worker({ front: true });
+ await front.push('approval_needed');
+ assert.equal(front.log.badged, 0, 'the open page sets the exact count itself');
+});
diff --git a/frontend/tests/needsYouPillExitRace.test.mjs b/frontend/tests/needsYouPillExitRace.test.mjs
new file mode 100644
index 00000000..cd70e6d2
--- /dev/null
+++ b/frontend/tests/needsYouPillExitRace.test.mjs
@@ -0,0 +1,111 @@
+// The in-app pill's slide-out race (Lin found it in the Mac pill, #268; Mira's note for #267): an exit
+// must only clear the pill it is exiting. Something that arrives during the 160 ms slide-out drops in as
+// a fresh pill instead of being swallowed, and an item answered elsewhere during it doesn't bring it back.
+import assert from 'node:assert/strict';
+import test, { mock } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'Element', 'Node', 'Event', 'FocusEvent', 'MouseEvent', 'KeyboardEvent', 'getComputedStyle']) {
+ if (k in dom.window) Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+dom.window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+globalThis.matchMedia = dom.window.matchMedia;
+
+const ui = await loadBundled(`
+ export { NeedsYouPill } from './src/components/NeedsYouPill';
+ export { nudgeFromAway, pillAdd, pillPrune, EMPTY_PILL } from './src/attention';
+ export { createElement } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+`);
+
+const item = (id) => ({
+ kind: 'question', id, kwant_id: 'k1', kwant_name: 'Juno', title: `Title ${id}`, summary: '', status: 'open',
+ timestamp: '2026-11-03T21:00:00Z', link: { thread_id: null, channel_id: null, direct_kwant_id: 'k1' },
+});
+const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r)); };
+
+function mount() {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = ui.createRoot(host);
+ let pill = ui.EMPTY_PILL;
+ const draw = () =>
+ ui.flushSync(() => {
+ root.render(ui.createElement(ui.NeedsYouPill, {
+ items: pill.items, rev: pill.rev, spriteOf: () => 'violet', onOpen: () => {},
+ // The same guard App's dismissPill has: only clear the rev that left.
+ onDismiss: (rev) => { if (pill.rev === rev) { pill = ui.EMPTY_PILL; draw(); } },
+ }));
+ });
+ return {
+ async arrive(id) { pill = ui.pillAdd(pill, [ui.nudgeFromAway(item(id))]); draw(); await settle(); },
+ async prune(keep) { pill = ui.pillPrune(pill, new Set(keep.map((id) => `question:${id}`))); draw(); await settle(); },
+ async act(fn) { ui.flushSync(fn); await settle(); },
+ async tick(ms) { ui.flushSync(() => mock.timers.tick(ms)); await settle(); },
+ button: () => host.querySelector('button.kw-nudge'),
+ showing() { const b = host.querySelector('button.kw-nudge'); return !!b && !b.classList.contains('is-leaving'); },
+ count: () => host.querySelector('button.kw-nudge')?.dataset.count,
+ items: () => pill.items.length,
+ unmount() { ui.flushSync(() => root.unmount()); host.remove(); },
+ };
+}
+
+test('an arrival during the timed slide-out mounts a fresh pill with a full 5 s', async () => {
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
+ const p = mount();
+ try {
+ await p.arrive('q0');
+ const first = p.button();
+ await p.tick(5000);
+ assert.ok(!p.showing(), 'sliding out at 5 s');
+ await p.tick(80);
+ await p.arrive('q1');
+ assert.ok(p.showing(), 'back up, not leaving');
+ assert.notEqual(p.button(), first, 'a fresh pill, not the one that was leaving');
+ await p.tick(1000);
+ assert.ok(p.showing(), 'the old exit timer did not remove it');
+ assert.equal(p.items(), 2, 'the app still has what arrived');
+ await p.tick(3900);
+ assert.ok(p.showing(), 'still up 4.9 s after it came back');
+ await p.tick(100);
+ assert.ok(!p.showing());
+ await p.tick(200);
+ assert.equal(p.button(), null);
+ assert.equal(p.items(), 0);
+ } finally { p.unmount(); mock.timers.reset(); }
+});
+
+test('an arrival during an Esc slide-out is not swallowed either', async () => {
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
+ const p = mount();
+ try {
+ await p.arrive('q0');
+ await p.act(() => p.button().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
+ assert.ok(!p.showing(), 'Esc starts the slide-out');
+ await p.tick(100);
+ await p.arrive('q1');
+ await p.tick(500);
+ assert.ok(p.showing());
+ assert.equal(p.items(), 2);
+ } finally { p.unmount(); mock.timers.reset(); }
+});
+
+test('an item answered elsewhere during the slide-out does not bring the pill back', async () => {
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
+ const p = mount();
+ try {
+ await p.arrive('q0');
+ await p.arrive('q1');
+ await p.tick(5000);
+ assert.ok(!p.showing());
+ await p.tick(80);
+ await p.prune(['q1']);
+ assert.ok(!p.showing(), 'still leaving');
+ await p.tick(200);
+ assert.equal(p.button(), null, 'gone');
+ assert.equal(p.items(), 0, 'and cleared');
+ } finally { p.unmount(); mock.timers.reset(); }
+});
diff --git a/frontend/tests/needsYouPillTiming.test.mjs b/frontend/tests/needsYouPillTiming.test.mjs
new file mode 100644
index 00000000..39b849a5
--- /dev/null
+++ b/frontend/tests/needsYouPillTiming.test.mjs
@@ -0,0 +1,242 @@
+// The in-app "needs you" pill's timing (Mira's spec §2, Ada's call on the cap): 5 s from the last arrival,
+// a hard 12 s cap on arrival restarts, and hover or focus holds it past the cap until 2 s after it leaves.
+import assert from 'node:assert/strict';
+import test, { mock } from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'Element', 'Node', 'Event', 'FocusEvent', 'MouseEvent', 'KeyboardEvent', 'getComputedStyle']) {
+ if (k in dom.window) Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+// Width queries answer against window.innerWidth, the way a browser does; anything else (reduced motion) is off.
+dom.window.matchMedia = (q) => {
+ const max = /\(max-width:\s*(\d+)px\)/.exec(q);
+ const min = /\(min-width:\s*(\d+)px\)/.exec(q);
+ const matches = max ? dom.window.innerWidth <= Number(max[1]) : min ? dom.window.innerWidth >= Number(min[1]) : false;
+ return { matches, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} };
+};
+globalThis.matchMedia = dom.window.matchMedia;
+
+const ui = await loadBundled(`
+ export { NeedsYouPill } from './src/components/NeedsYouPill';
+ export { nudgeFromAway, pillAdd, EMPTY_PILL } from './src/attention';
+ export { PHONE_QUERY } from './src/layout';
+ export { createElement } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+`);
+
+const item = (id) => ({
+ kind: 'question', id, kwant_id: 'k1', kwant_name: 'Juno', title: `Title ${id}`, summary: '', status: 'open',
+ timestamp: '2026-11-03T21:00:00Z', link: { thread_id: null, channel_id: null, direct_kwant_id: 'k1' },
+});
+
+// React runs effects and continuous-priority updates (hover) on its scheduler, which uses setImmediate:
+// the mocked clock leaves that alone, so each step lets it drain.
+const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r)); };
+
+function mount() {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = ui.createRoot(host);
+ let pill = ui.EMPTY_PILL;
+ let dismissed = false;
+ const draw = () =>
+ ui.flushSync(() => {
+ root.render(ui.createElement(ui.NeedsYouPill, {
+ items: pill.items, rev: pill.rev, spriteOf: () => 'violet', onOpen: () => {},
+ onDismiss: () => { pill = ui.EMPTY_PILL; dismissed = true; },
+ }));
+ });
+ return {
+ async arrive(id) { pill = ui.pillAdd(pill, [ui.nudgeFromAway(item(id))]); draw(); await settle(); },
+ async act(fn) { ui.flushSync(fn); await settle(); },
+ button: () => host.querySelector('button.kw-nudge'),
+ showing() { const b = host.querySelector('button.kw-nudge'); return !!b && !b.classList.contains('is-leaving'); },
+ count: () => host.querySelector('button.kw-nudge')?.dataset.count,
+ async tick(ms) {
+ ui.flushSync(() => mock.timers.tick(ms));
+ await settle();
+ // The app clears its pill state when the pill says it has gone; do the same here.
+ if (dismissed) { dismissed = false; draw(); await settle(); }
+ },
+ unmount() { ui.flushSync(() => root.unmount()); host.remove(); },
+ };
+}
+
+test('arrivals at 0, 4, 8 and 11 s swap in place but the pill is gone by about 12 s', async () => {
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
+ const p = mount();
+ try {
+ await p.arrive('q0');
+ const first = p.button();
+ await p.tick(4000); await p.arrive('q4');
+ await p.tick(4000); await p.arrive('q8');
+ await p.tick(3000); await p.arrive('q11');
+ assert.ok(p.showing(), 'still up at 11 s');
+ assert.equal(p.button(), first, 'coalescing swaps the content in the same pill');
+ assert.equal(p.count(), '4');
+ await p.tick(900);
+ assert.ok(p.showing(), 'still up at 11.9 s');
+ await p.tick(100);
+ assert.ok(!p.showing(), 'leaving at 12 s, not 16 s');
+ await p.tick(200);
+ assert.equal(p.button(), null, 'gone after the slide out');
+ // An arrival after it has gone springs a fresh pill with a full 5 s.
+ await p.arrive('q13');
+ assert.ok(p.showing());
+ assert.equal(p.count(), '1');
+ await p.tick(4900);
+ assert.ok(p.showing());
+ await p.tick(100);
+ assert.ok(!p.showing());
+ } finally {
+ p.unmount();
+ mock.timers.reset();
+ }
+});
+
+test('with focus inside it stays past the 12 s cap and goes 2 s after blur', async () => {
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
+ const p = mount();
+ try {
+ await p.arrive('q0');
+ await p.act(() => p.button().focus());
+ await p.tick(4000); await p.arrive('q4');
+ await p.tick(9000);
+ assert.ok(p.showing(), 'still there at 13 s with focus inside');
+ await p.act(() => p.button().blur());
+ await p.tick(1900);
+ assert.ok(p.showing(), 'still there 1.9 s after blur');
+ await p.tick(100);
+ assert.ok(!p.showing(), 'goes 2 s after blur');
+ } finally {
+ p.unmount();
+ mock.timers.reset();
+ }
+});
+
+test('hover holds it past the cap too, and it goes 2 s after the pointer leaves', async () => {
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 0 });
+ const p = mount();
+ try {
+ await p.arrive('q0');
+ // React listens for mouseover/mouseout to synthesize enter and leave.
+ await p.act(() => p.button().dispatchEvent(new MouseEvent('mouseover', { bubbles: true, relatedTarget: document.body })));
+ await p.tick(15000);
+ assert.ok(p.showing(), 'still there at 15 s while hovered');
+ await p.act(() => p.button().dispatchEvent(new MouseEvent('mouseout', { bubbles: true, relatedTarget: document.body })));
+ await p.tick(1900);
+ assert.ok(p.showing());
+ await p.tick(100);
+ assert.ok(!p.showing());
+ } finally {
+ p.unmount();
+ mock.timers.reset();
+ }
+});
+
+test('desktop: the pill is centred on the main pane, starting where the sidebar ends; phone: the whole width', async () => {
+ const side = document.createElement('aside');
+ side.setAttribute('data-kw-sidebar', '');
+ side.getBoundingClientRect = () => ({ left: 56, right: 312, width: 256, top: 0, bottom: 900, height: 900 });
+ document.body.appendChild(side);
+ const region = () => document.querySelector('.kw-nudge-region');
+ try {
+ for (const [w, want] of [[1440, '312px'], [390, '']]) {
+ window.innerWidth = w;
+ const p = mount();
+ try {
+ await p.arrive('q' + w);
+ assert.equal(region().style.getPropertyValue('--kw-nudge-left'), want);
+ } finally {
+ p.unmount();
+ }
+ }
+ } finally {
+ side.remove();
+ }
+});
+
+// Rigel's R-1: between 640 and 767 px the app is in its phone layout (no sidebar shown), but the pill still
+// measured the sidebar and slid off-screen. The pill and its CSS now switch at the app's own breakpoint.
+test('R-1: at 700 px (phone layout) the pill is full width, not placed from the sidebar; at 768 px it is centred on the main pane', async () => {
+ const side = document.createElement('aside');
+ side.setAttribute('data-kw-sidebar', '');
+ // In the phone layout the sidebar can still be in the DOM with a size (an off-canvas drawer): it must not count.
+ side.getBoundingClientRect = () => ({ left: 56, right: 312, width: 256, top: 0, bottom: 900, height: 900 });
+ document.body.appendChild(side);
+ const region = () => document.querySelector('.kw-nudge-region');
+ try {
+ for (const [w, want] of [[700, ''], [767, ''], [768, '312px']]) {
+ window.innerWidth = w;
+ const p = mount();
+ try {
+ await p.arrive('r1-' + w);
+ assert.equal(region().style.getPropertyValue('--kw-nudge-left'), want, `at ${w} px`);
+ } finally {
+ p.unmount();
+ }
+ }
+ } finally {
+ side.remove();
+ }
+});
+
+test('R-1: the pill CSS switches to its full-width phone style at the same breakpoint as the app layout', () => {
+ const css = readFileSync(new URL('../src/styles/needsYou.css', import.meta.url), 'utf8');
+ const phone = /@media\s*(\(max-width:\s*\d+px\))\s*\{\s*\.kw-nudge-region\s*\{[^}]*left:\s*0/.exec(css);
+ assert.ok(phone, 'the phone block resets the region to the full width');
+ assert.equal(phone[1], ui.PHONE_QUERY);
+});
+
+// Rigel's R-2: widening from the phone layout while the pill shows fires `resize` before React swaps the layout,
+// so the full-width chat list still sits where the sidebar goes. The pill must measure again once the layout
+// has settled, and never be placed at the window's right edge.
+test('R-2: widening 700 -> 900 and 767 -> 768 while the pill shows keeps it on the main pane, not off-screen', async () => {
+ const side = document.createElement('aside');
+ side.setAttribute('data-kw-sidebar', '');
+ document.body.appendChild(side);
+ const region = () => document.querySelector('.kw-nudge-region');
+ // Animation frames run when the test says so, as a browser paints after React commits.
+ let frames = [];
+ const origRaf = window.requestAnimationFrame;
+ const origCaf = window.cancelAnimationFrame;
+ window.requestAnimationFrame = (f) => { frames.push(f); return frames.length; };
+ window.cancelAnimationFrame = () => {};
+ const paint = async () => {
+ for (let i = 0; i < 4 && frames.length; i++) { const run = frames; frames = []; ui.flushSync(() => run.forEach((f) => f(0))); }
+ await settle();
+ };
+ try {
+ for (const [from, to] of [[700, 900], [767, 768]]) {
+ window.innerWidth = from;
+ // Phone layout: the chat list fills the window where the sidebar goes.
+ side.getBoundingClientRect = () => ({ left: 0, right: from, width: from, top: 0, bottom: 900, height: 900 });
+ const p = mount();
+ try {
+ await p.arrive(`r2-${from}`);
+ assert.equal(region().style.getPropertyValue('--kw-nudge-left'), '', `at ${from} px`);
+ // Widen: resize fires while the phone layout is still on screen.
+ window.innerWidth = to;
+ side.getBoundingClientRect = () => ({ left: 0, right: to, width: to, top: 0, bottom: 900, height: 900 });
+ await p.act(() => window.dispatchEvent(new window.Event('resize')));
+ const early = region().style.getPropertyValue('--kw-nudge-left');
+ assert.ok(early === '' || parseInt(early, 10) < to, `${from} -> ${to}: not at the right edge right after resize (got ${early})`);
+ // React swaps in the desktop layout: a 256 px sidebar after the 56 px rail.
+ side.getBoundingClientRect = () => ({ left: 56, right: 312, width: 256, top: 0, bottom: 900, height: 900 });
+ await paint();
+ assert.equal(region().style.getPropertyValue('--kw-nudge-left'), '312px', `${from} -> ${to}: centred on the main pane`);
+ assert.ok(p.showing(), 'still showing');
+ } finally {
+ p.unmount();
+ }
+ }
+ } finally {
+ window.requestAnimationFrame = origRaf;
+ window.cancelAnimationFrame = origCaf;
+ side.remove();
+ }
+});