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.

PWA haptics: short vibration on key actions and new replies, with a Settings switch

Pixel (kwant bot)867da6634085
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 844960b6..72378827 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Added
+- **Vibration on Android phones.** The web app gives a short buzz when you send a message, answer a
+ question or approval card, press **Solve it**, **Done**, **Skip** or **Hand back**, and when a puzzle
+ is solved, with a different buzz for errors. A bot reply arriving while the app is on screen gives a
+ light double buzz, at most one per burst. A **Vibration** switch in App settings turns it off; it
+ starts off when the phone asks for reduced motion. iPhones and desktops have no web vibration.
+
### Changed
- A bot reply that ends with a closing line such as "Anything else?", "Should I continue?" or
"Want me to also…?" no longer pulls the person's next message back to that bot. Real questions
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 06ec8cf0..eb0575c9 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -38,6 +38,7 @@ import { NewChannelModal } from './components/NewChannelModal';
import type { NewChannelBody } from './channels';
import { ManageTeamModal } from './components/ManageTeamModal';
import { playSfx } from './audio/chiptune';
+import { haptic, messageHaptic } from './haptics';
import { Toasts, Toast } from './components/Toasts';
import { clearAllTurns, resetTurns, turnEnded, turnStarted } from './kwantActivity';
import {
@@ -1017,6 +1018,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const targetId = streamingContextIdRef.current || selectedIdRef.current;
streamingContextIdRef.current = null;
playSfx('coin');
+ messageHaptic();
refreshContext(targetId).then(() => settle(targetId));
break;
}
@@ -1024,6 +1026,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const ctx = streamTarget(event, streamingContextIdRef.current);
if (ctx === openCtxRef.current) {
playSfx('coin');
+ messageHaptic();
setTokensUsed((prev) => prev + (event.data?.tokens || 0));
}
if (typeof event.turn_id === 'string') completed.add(event.turn_id);
@@ -1175,6 +1178,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
const handleSendMessage = async (text: string, attachments: AttachmentRef[] = []): Promise<boolean> => {
+ haptic('tap');
setHistoryWindow(null);
const targetId = openCtx;
const threadId = openThreadId;
@@ -1242,6 +1246,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return true;
} catch (err) {
console.error('Failed sending chat:', err);
+ haptic('warning');
const rest = (messagesCacheRef.current[targetId] || []).filter((m) => m.id !== tempId);
messagesCacheRef.current[targetId] = rest;
if (openCtxRef.current === targetId) setMessages(rest);
@@ -1259,6 +1264,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
ticketId: string,
decision: 'allow_once' | 'always_allow' | 'deny'
) => {
+ haptic('tap');
try {
const res = await fetch(`/api/approvals/${ticketId}/resolve`, {
method: 'POST',
@@ -1280,10 +1286,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Person-only: the token dialog is open; the card stays so the person can answer again.
pushToast('Enter your access token', 'Answering approval cards needs your token. Then answer the card again.');
} else {
+ haptic('warning');
pushToast("Couldn't send your answer", `Request failed (HTTP ${res.status}). Try again.`);
}
} catch (err) {
console.error('Failed resolving approval:', err);
+ haptic('warning');
pushToast("Couldn't send your answer", 'Check the connection and try again.');
}
};
@@ -1505,6 +1513,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
const handleAnswerQuestion = async (id: string, answer: { choice: number } | { text: string }): Promise<string | void> => {
+ haptic('tap');
try {
const { question } = await questionsApi.answer(id, answer);
setQuestions((prev) => applyQuestion(prev, question));
@@ -1518,6 +1527,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
} catch {
// keep the first error
}
+ haptic('warning');
return `Couldn't send your answer: ${errText(err)}`;
}
};
@@ -1550,9 +1560,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
/** Done or Skip on a browser step. A 409 means it was answered elsewhere: show how it ended. */
const answerHumanStep = async (id: string, which: 'done' | 'decline'): Promise<string | void> => {
+ haptic('tap');
try {
const { step } = await (which === 'done' ? humanStepsApi.done(id) : humanStepsApi.decline(id));
setHumanSteps((prev) => applyHumanStep(prev, step));
+ if (which === 'done') haptic('success');
} catch (err) {
try {
const { step } = await humanStepsApi.get(id);
@@ -1563,6 +1575,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
} catch {
// keep the first error
}
+ haptic('warning');
return `Couldn't send that: ${errText(err)}`;
}
};
@@ -1580,7 +1593,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
waiting={!!turnId && !!turns[turnId]}
onOpenBrowser={(_target, solve) => {
setIsVmPaneOpen(true);
- if (solve) setSolveRequest((v) => v + 1);
+ if (solve) {
+ setSolveRequest((v) => v + 1);
+ haptic('tap');
+ }
playSfx('click');
}}
onDone={(id) => answerHumanStep(id, 'done')}
diff --git a/frontend/src/components/BrowserControlOverlay.tsx b/frontend/src/components/BrowserControlOverlay.tsx
index 00a42bab..507bd643 100644
--- a/frontend/src/components/BrowserControlOverlay.tsx
+++ b/frontend/src/components/BrowserControlOverlay.tsx
@@ -17,6 +17,7 @@ import {
zoomToBox,
} from '../browserGestures';
import { domainOf } from '../humanSteps';
+import { haptic } from '../haptics';
/** Sends one gesture to the page: presses, releases, taps and text wait for an ack, moves don't. */
export function sendPageInput(send: (payload: Record<string, unknown>, input?: boolean) => void, input: PageInput) {
@@ -238,6 +239,11 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
else keys.current?.blur();
}, [tapFocus, openKeyboard]);
+ // The puzzle closing as solved is felt as well as shown
+ useEffect(() => {
+ if (solved) haptic('success');
+ }, [solved]);
+
// The page behind can't scroll or zoom while this is up
useEffect(() => {
const html = document.documentElement;
@@ -277,7 +283,10 @@ export const BrowserControlOverlay: React.FC<BrowserControlOverlayProps> = ({
</button>
<button
type="button"
- onClick={onHandBack}
+ onClick={() => {
+ haptic('tap');
+ onHandBack();
+ }}
className="shrink-0 inline-flex items-center gap-1.5 h-10 px-3 rounded-lg bg-cyan-500 text-zinc-950 text-sm font-semibold"
>
<Hand size={15} aria-hidden="true" /> Hand back
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 539ebda0..5c023174 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
-import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin } from 'lucide-react';
+import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff } from 'lucide-react';
import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';
import {
BROWSER_NOTIFY_KEY,
@@ -17,6 +17,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 { useAuth } from './AuthGate';
import { SignedInDevices } from './DeviceSignIn';
import { signedInDevicesVisible } from '../deviceSignIn';
@@ -69,6 +70,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const computer = useComputerMode(isOpen);
const engines = useEngines(isOpen);
const [sfxMuted, setSfxMuted] = useState(isSfxMuted);
+ const [vibration, setVibration] = useState(hapticsEnabled);
const [settings, setSettings] = useState<SettingsData | null>(null);
const [anthropicKey, setAnthropicKey] = useState('');
const [xaiKey, setXaiKey] = useState('');
@@ -285,6 +287,34 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${!sfxMuted ? 'translate-x-4' : ''}`} />
</button>
</div>
+ {hapticsAvailable() && (
+ <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">
+ {vibration ? <Vibrate size={15} className="text-sky-400" aria-hidden="true" /> : <VibrateOff size={15} className="text-zinc-500" aria-hidden="true" />}
+ <span id="vibration-label">Vibration</span>
+ </span>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={vibration}
+ aria-labelledby="vibration-label"
+ aria-describedby="vibration-hint"
+ onClick={() => {
+ setHapticsEnabled(!vibration);
+ setVibration(!vibration);
+ if (!vibration) haptic('tap');
+ }}
+ className={`relative shrink-0 w-9 h-5 rounded-full transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
+ vibration ? '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 ${vibration ? 'translate-x-4' : ''}`} />
+ </button>
+ <span id="vibration-hint" className="sr-only">
+ A short buzz when you send, answer or solve a puzzle, and when a reply arrives while the app is open.
+ </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/haptics.ts b/frontend/src/haptics.ts
new file mode 100644
index 00000000..83bfa545
--- /dev/null
+++ b/frontend/src/haptics.ts
@@ -0,0 +1,106 @@
+// Short phone vibrations for meaningful actions (send, answer, approve, puzzle steps) and for a
+// bot reply arriving while the app is on screen. Uses navigator.vibrate, which Chrome on Android
+// supports; iOS Safari and desktops have none, so every call there is a silent no-op.
+
+export type HapticKind = 'tap' | 'success' | 'warning' | 'message';
+
+/** Motor on/off times in ms. Kept short: a web app can only set how long the motor runs. */
+export const HAPTIC_PATTERNS: Record<HapticKind, number | number[]> = {
+ tap: 10,
+ success: [15, 40, 15],
+ warning: [30, 60, 30],
+ // A light double buzz, different from the tap a button gives.
+ message: [8, 80, 8],
+};
+
+export const HAPTICS_KEY = 'kwnt_haptics';
+
+/** Several replies landing together give one buzz. */
+export const MESSAGE_GAP_MS = 1500;
+
+/** What the helpers read; the browser's globals by default, fakes in tests. */
+export interface HapticsEnv {
+ navigator?: {
+ vibrate?: (pattern: number | number[]) => boolean;
+ userActivation?: { hasBeenActive?: boolean };
+ };
+ matchMedia?: (query: string) => { matches: boolean };
+ localStorage?: Pick<Storage, 'getItem' | 'setItem'>;
+ document?: { visibilityState?: string };
+}
+
+const browserEnv = (): HapticsEnv => globalThis as unknown as HapticsEnv;
+
+export function canVibrate(env: HapticsEnv = browserEnv()): boolean {
+ return typeof env.navigator?.vibrate === 'function';
+}
+
+/** Whether to offer the Settings switch: desktop Chrome has vibrate too, but no motor. */
+export function hapticsAvailable(env: HapticsEnv = browserEnv()): boolean {
+ if (!canVibrate(env)) return false;
+ try {
+ return !!env.matchMedia?.('(pointer: coarse)').matches;
+ } catch {
+ return false;
+ }
+}
+
+function prefersReducedMotion(env: HapticsEnv): boolean {
+ try {
+ return !!env.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ } catch {
+ return false;
+ }
+}
+
+/** The Settings switch. On by default, off by default when the phone asks for reduced motion. */
+export function hapticsEnabled(env: HapticsEnv = browserEnv()): boolean {
+ let stored: string | null = null;
+ try {
+ stored = env.localStorage?.getItem(HAPTICS_KEY) ?? null;
+ } catch {
+ // storage blocked: fall back to the default
+ }
+ if (stored === 'on') return true;
+ if (stored === 'off') return false;
+ return !prefersReducedMotion(env);
+}
+
+export function setHapticsEnabled(on: boolean, env: HapticsEnv = browserEnv()): void {
+ try {
+ env.localStorage?.setItem(HAPTICS_KEY, on ? 'on' : 'off');
+ } catch {
+ // storage blocked: the choice lasts until reload
+ }
+}
+
+/** Vibrates once if the device can and the person allows it. Never throws; true if it buzzed. */
+export function haptic(kind: HapticKind, env: HapticsEnv = browserEnv()): boolean {
+ const nav = env.navigator;
+ if (!nav || typeof nav.vibrate !== 'function') return false;
+ if (!hapticsEnabled(env)) return false;
+ // Chrome blocks (and logs) vibration before the first tap on the page.
+ if (nav.userActivation && nav.userActivation.hasBeenActive === false) return false;
+ try {
+ return nav.vibrate.call(nav, HAPTIC_PATTERNS[kind]) !== false;
+ } catch {
+ return false;
+ }
+}
+
+let lastMessageAt = -Infinity;
+
+/** A bot's reply arrived: buzz only while the app is on screen, at most once per MESSAGE_GAP_MS. */
+export function messageHaptic(env: HapticsEnv = browserEnv(), now: number = Date.now()): boolean {
+ // In the background the push notification already vibrates.
+ if (env.document && env.document.visibilityState !== 'visible') return false;
+ if (now - lastMessageAt < MESSAGE_GAP_MS) return false;
+ if (!haptic('message', env)) return false;
+ lastMessageAt = now;
+ return true;
+}
+
+/** Tests only. */
+export function resetMessageHaptic(): void {
+ lastMessageAt = -Infinity;
+}
diff --git a/frontend/tests/haptics.test.mjs b/frontend/tests/haptics.test.mjs
new file mode 100644
index 00000000..1e7527a9
--- /dev/null
+++ b/frontend/tests/haptics.test.mjs
@@ -0,0 +1,145 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+const h = await loadBundled(`export * from './src/haptics';`);
+const src = (path) => readFileSync(new URL(`../src/${path}`, import.meta.url), 'utf8');
+
+/** A phone: records every vibrate call, with `this` checked like Chrome does. */
+function phone({ stored = null, reduced = false, active = true, visible = true, coarse = true, vibrate } = {}) {
+ const calls = [];
+ const store = new Map(stored === null ? [] : [[h.HAPTICS_KEY, stored]]);
+ const navigator = {
+ userActivation: { hasBeenActive: active },
+ vibrate:
+ vibrate ??
+ function (pattern) {
+ if (this !== navigator) throw new TypeError('Illegal invocation');
+ calls.push(pattern);
+ return true;
+ },
+ };
+ return {
+ calls,
+ store,
+ env: {
+ navigator,
+ matchMedia: (q) => ({
+ matches: (reduced && q === '(prefers-reduced-motion: reduce)') || (coarse && q === '(pointer: coarse)'),
+ }),
+ localStorage: { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, v) },
+ document: { visibilityState: visible ? 'visible' : 'hidden' },
+ },
+ };
+}
+
+test('patterns stay short and distinct', () => {
+ assert.equal(h.HAPTIC_PATTERNS.tap, 10);
+ assert.deepEqual(h.HAPTIC_PATTERNS.success, [15, 40, 15]);
+ assert.deepEqual(h.HAPTIC_PATTERNS.warning, [30, 60, 30]);
+ const kinds = Object.keys(h.HAPTIC_PATTERNS);
+ assert.equal(new Set(kinds.map((k) => JSON.stringify(h.HAPTIC_PATTERNS[k]))).size, kinds.length);
+ for (const k of kinds) {
+ const total = [h.HAPTIC_PATTERNS[k]].flat().reduce((a, b) => a + b, 0);
+ assert.ok(total <= 150, `${k} runs ${total} ms`);
+ }
+ const p = phone();
+ for (const k of kinds) assert.equal(h.haptic(k, p.env), true);
+ assert.deepEqual(p.calls, kinds.map((k) => h.HAPTIC_PATTERNS[k]));
+});
+
+test('unsupported devices (iOS Safari, desktop) are a silent no-op', () => {
+ assert.equal(h.canVibrate({ navigator: {} }), false);
+ assert.equal(h.haptic('tap', { navigator: {} }), false);
+ assert.equal(h.haptic('tap', {}), false);
+ assert.equal(h.haptic('tap', { navigator: { vibrate: 'nope' } }), false);
+ // Node has no navigator.vibrate either: the default env must not throw.
+ assert.equal(h.haptic('tap'), false);
+ assert.equal(h.messageHaptic(), false);
+ assert.equal(h.canVibrate(phone().env), true);
+});
+
+test('the Settings switch is offered on touch phones only', () => {
+ assert.equal(h.hapticsAvailable(phone().env), true);
+ assert.equal(h.hapticsAvailable(phone({ coarse: false }).env), false, 'desktop Chrome: vibrate exists, no motor');
+ assert.equal(h.hapticsAvailable({ navigator: {}, matchMedia: () => ({ matches: true }) }), false, 'iPhone: no vibrate');
+ assert.equal(h.hapticsAvailable(), false);
+});
+
+test('a throwing or refusing vibrate never throws', () => {
+ const boom = phone({ vibrate: () => { throw new Error('blocked'); } });
+ assert.equal(h.haptic('tap', boom.env), false);
+ const refused = phone({ vibrate: () => false });
+ assert.equal(h.haptic('tap', refused.env), false);
+ const badStore = phone();
+ badStore.env.localStorage = { getItem: () => { throw new Error('denied'); }, setItem: () => { throw new Error('denied'); } };
+ assert.doesNotThrow(() => h.setHapticsEnabled(false, badStore.env));
+ assert.equal(h.haptic('tap', badStore.env), true, 'falls back to the default (on)');
+});
+
+test('switched off in Settings: nothing buzzes', () => {
+ const p = phone();
+ h.setHapticsEnabled(false, p.env);
+ assert.equal(p.store.get(h.HAPTICS_KEY), 'off');
+ assert.equal(h.hapticsEnabled(p.env), false);
+ assert.equal(h.haptic('tap', p.env), false);
+ assert.deepEqual(p.calls, []);
+ h.setHapticsEnabled(true, p.env);
+ assert.equal(h.haptic('tap', p.env), true);
+});
+
+test('reduced motion defaults off, but an explicit choice wins', () => {
+ assert.equal(h.hapticsEnabled(phone({ reduced: true }).env), false);
+ assert.equal(h.haptic('tap', phone({ reduced: true }).env), false);
+ assert.equal(h.hapticsEnabled(phone({ reduced: true, stored: 'on' }).env), true);
+ assert.equal(h.hapticsEnabled(phone({ reduced: false }).env), true);
+ assert.equal(h.hapticsEnabled(phone({ reduced: false, stored: 'off' }).env), false);
+});
+
+test('no vibrate call before the first tap on the page', () => {
+ const p = phone({ active: false });
+ assert.equal(h.haptic('tap', p.env), false);
+ assert.deepEqual(p.calls, []);
+});
+
+test('reply buzz: only on screen, one per burst', () => {
+ h.resetMessageHaptic();
+ const hidden = phone({ visible: false });
+ assert.equal(h.messageHaptic(hidden.env, 1000), false, 'background: the push notification vibrates instead');
+ const p = phone();
+ assert.equal(h.messageHaptic(p.env, 1000), true);
+ assert.equal(h.messageHaptic(p.env, 1000 + h.MESSAGE_GAP_MS - 1), false, 'several bots at once give one buzz');
+ assert.equal(h.messageHaptic(p.env, 1000 + h.MESSAGE_GAP_MS), true);
+ assert.deepEqual(p.calls, [h.HAPTIC_PATTERNS.message, h.HAPTIC_PATTERNS.message]);
+ h.setHapticsEnabled(false, p.env);
+ assert.equal(h.messageHaptic(p.env, 99999), false);
+});
+
+test('wiring: meaningful actions buzz, typing and scrolling do not', () => {
+ const app = src('App.tsx');
+ const body = (name) => {
+ const start = app.indexOf(`const ${name} = async`);
+ assert.ok(start >= 0, name);
+ return app.slice(start, app.indexOf('\n };\n', start));
+ };
+ for (const name of ['handleSendMessage', 'handleResolveApproval', 'handleAnswerQuestion', 'answerHumanStep']) {
+ const b = body(name);
+ assert.match(b, /haptic\('tap'\)/, `${name} taps`);
+ assert.match(b, /haptic\('warning'\)/, `${name} warns on failure`);
+ }
+ assert.match(body('answerHumanStep'), /if \(which === 'done'\) haptic\('success'\)/);
+ assert.match(app, /if \(solve\) \{\s*setSolveRequest\(\(v\) => v \+ 1\);\s*haptic\('tap'\);/, 'Solve it taps');
+ // Replies: on TurnComplete for the open chat and when a discussion ends.
+ assert.equal(app.match(/messageHaptic\(\)/g)?.length, 2);
+ assert.doesNotMatch(app, /onScroll[^\n]*haptic|onChange[^\n]*haptic|onInput[^\n]*haptic/);
+
+ const overlay = src('components/BrowserControlOverlay.tsx');
+ assert.match(overlay, /if \(solved\) haptic\('success'\)/);
+ assert.match(overlay, /haptic\('tap'\);\s*onHandBack\(\);/);
+
+ const settings = src('components/SettingsModal.tsx');
+ assert.match(settings, /hapticsAvailable\(\) && \(/, 'the switch only shows where the phone can vibrate');
+ assert.match(settings, /role="switch"[\s\S]*?aria-checked=\{vibration\}/);
+ assert.match(settings, />Vibration</);
+});