Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Install kwant bots on a phone: web app manifest, service worker, phone layout
Pixel (kwant bot)c3ce7c368764
diff --git a/frontend/index.html b/frontend/index.htmlindex 5e3a753c..6100ae2f 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -2,8 +2,16 @@<html lang="en"><head><meta charset="UTF-8" />- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 26 26' shape-rendering='crispEdges'><path fill='%234a3f8a' d='M5 1h16v1h2v1h1v2h1v16h-1v2h-1v1h-2v1H5v-1H3v-1H2v-2H1V5h1V3h1V2h2z'/><path fill='%2315112e' d='M6 2h14v1h2v1h1v2h1v14h-1v2h-1v1h-2v1H6v-1H4v-1H3v-2H2V6h1V4h1V3h2z'/><rect x='15' y='3' width='2' height='2' fill='%235ce1ff'/><rect x='15' y='6' width='1' height='1' fill='%231b1033'/><rect x='9' y='7' width='8' height='1' fill='%23fdc934'/><rect x='8' y='8' width='10' height='1' fill='%23fdc934'/><rect x='7' y='9' width='12' height='7' fill='%23fdc934'/><rect x='8' y='16' width='10' height='1' fill='%23fdc934'/><rect x='9' y='17' width='8' height='1' fill='%23d98a1f'/><rect x='18' y='9' width='1' height='7' fill='%23d98a1f'/><rect x='10' y='10' width='2' height='3' fill='%231b1033'/><rect x='14' y='10' width='2' height='3' fill='%231b1033'/><rect x='10' y='10' width='1' height='1' fill='%23fff'/><rect x='14' y='10' width='1' height='1' fill='%23fff'/><rect x='8' y='13' width='2' height='1' fill='%23ff6b81'/><rect x='16' y='13' width='2' height='1' fill='%23ff6b81'/><rect x='12' y='15' width='2' height='1' fill='%231b1033'/></svg>" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <link rel="icon" type="image/svg+xml" href="/icon.svg" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content" />+ <meta name="description" content="Your team of AI bots" />+ <meta name="theme-color" content="#120e26" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />+ <meta name="apple-mobile-web-app-capable" content="yes" />+ <meta name="mobile-web-app-capable" content="yes" />+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />+ <meta name="apple-mobile-web-app-title" content="kwant bots" /><title>kwant bots: your team of AI bots</title><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>diff --git a/frontend/public/icon.svg b/frontend/public/icon.svgnew file mode 100644index 00000000..56d80d98--- /dev/null+++ b/frontend/public/icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 26" shape-rendering="crispEdges"><path fill="#4a3f8a" d="M5 1h16v1h2v1h1v2h1v16h-1v2h-1v1h-2v1H5v-1H3v-1H2v-2H1V5h1V3h1V2h2z"/><path fill="#15112e" d="M6 2h14v1h2v1h1v2h1v14h-1v2h-1v1h-2v1H6v-1H4v-1H3v-2H2V6h1V4h1V3h2z"/><rect x="15" y="3" width="2" height="2" fill="#5ce1ff"/><rect x="15" y="6" width="1" height="1" fill="#1b1033"/><rect x="9" y="7" width="8" height="1" fill="#fdc934"/><rect x="8" y="8" width="10" height="1" fill="#fdc934"/><rect x="7" y="9" width="12" height="7" fill="#fdc934"/><rect x="8" y="16" width="10" height="1" fill="#fdc934"/><rect x="9" y="17" width="8" height="1" fill="#d98a1f"/><rect x="18" y="9" width="1" height="7" fill="#d98a1f"/><rect x="10" y="10" width="2" height="3" fill="#1b1033"/><rect x="14" y="10" width="2" height="3" fill="#1b1033"/><rect x="10" y="10" width="1" height="1" fill="#fff"/><rect x="14" y="10" width="1" height="1" fill="#fff"/><rect x="8" y="13" width="2" height="1" fill="#ff6b81"/><rect x="16" y="13" width="2" height="1" fill="#ff6b81"/><rect x="12" y="15" width="2" height="1" fill="#1b1033"/></svg>diff --git a/frontend/public/icons/apple-touch-icon.png b/frontend/public/icons/apple-touch-icon.pngnew file mode 100644index 00000000..03c09894Binary files /dev/null and b/frontend/public/icons/apple-touch-icon.png differdiff --git a/frontend/public/icons/icon-192.png b/frontend/public/icons/icon-192.pngnew file mode 100644index 00000000..39d2be5fBinary files /dev/null and b/frontend/public/icons/icon-192.png differdiff --git a/frontend/public/icons/icon-512.png b/frontend/public/icons/icon-512.pngnew file mode 100644index 00000000..b1995b88Binary files /dev/null and b/frontend/public/icons/icon-512.png differdiff --git a/frontend/public/icons/icon-maskable-192.png b/frontend/public/icons/icon-maskable-192.pngnew file mode 100644index 00000000..6e29e330Binary files /dev/null and b/frontend/public/icons/icon-maskable-192.png differdiff --git a/frontend/public/icons/icon-maskable-512.png b/frontend/public/icons/icon-maskable-512.pngnew file mode 100644index 00000000..f3a1d865Binary files /dev/null and b/frontend/public/icons/icon-maskable-512.png differdiff --git a/frontend/public/manifest.webmanifest b/frontend/public/manifest.webmanifestnew file mode 100644index 00000000..7876764f--- /dev/null+++ b/frontend/public/manifest.webmanifest@@ -0,0 +1,19 @@+{+ "id": "/",+ "name": "kwant bots",+ "short_name": "kwant bots",+ "description": "Your team of AI bots",+ "start_url": "/",+ "scope": "/",+ "display": "standalone",+ "orientation": "any",+ "background_color": "#120e26",+ "theme_color": "#120e26",+ "icons": [+ { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },+ { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },+ { "src": "/icons/icon-maskable-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },+ { "src": "/icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },+ { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }+ ]+}diff --git a/frontend/src/Shell.tsx b/frontend/src/Shell.tsxindex caba5829..15dfe4b7 100644--- a/frontend/src/Shell.tsx+++ b/frontend/src/Shell.tsx@@ -7,6 +7,7 @@ import { SpaceApp, SpaceTarget } from './App';import type { SpaceSettingsTab } from './components/SpaceSettings';import { ArchivedSpacesModal, NewSpaceModal, SpaceRail } from './components/Spaces';import { Toasts, Toast } from './components/Toasts';+import { InstallHint } from './components/InstallHint';import { playSfx } from './audio/chiptune';import {Space,@@ -186,7 +187,7 @@ export const App: React.FC = () => {if (!spaces || !current) {return (- <div className="h-[100dvh] w-screen flex items-center justify-center bg-zinc-950 text-zinc-400 text-xs">+ <div className="h-[var(--kwnt-app-height,100dvh)] w-screen flex items-center justify-center bg-zinc-950 text-zinc-400 text-xs">{loadError ? (<div role="alert" className="flex flex-col items-center gap-3"><p className="flex items-center gap-2 text-rose-300">@@ -208,7 +209,7 @@ export const App: React.FC = () => {}return (- <div className="h-[100dvh] w-screen flex bg-zinc-950 text-zinc-100 overflow-hidden font-sans">+ <div className="h-[var(--kwnt-app-height,100dvh)] w-screen flex bg-zinc-950 text-zinc-100 overflow-hidden font-sans pt-[env(safe-area-inset-top)] pl-[env(safe-area-inset-left)] pr-[env(safe-area-inset-right)]"><SpaceRail spaces={spaces} currentId={current.id} onSwitch={switchTo} onCreate={openCreate} onOpenAppSettings={() => setAppSettingsOpen(true)} /><SpaceAppkey={current.id}@@ -265,6 +266,7 @@ export const App: React.FC = () => {<SettingsModal isOpen={appSettingsOpen} onClose={() => setAppSettingsOpen(false)} tokensUsed={tokensUsed} /></Suspense><Toasts toasts={toasts} onDismiss={dismissToast} position="top" />+ <InstallHint /></div>);};diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsxindex 1b9c6924..5016e782 100644--- a/frontend/src/components/AuthGate.tsx+++ b/frontend/src/components/AuthGate.tsx@@ -31,6 +31,13 @@ type GateState =installUnauthorizedListener();+/** What the start screen says when the server didn't answer. */+export function offlineMessage(e: unknown, online: boolean): string {+ if (!online) return "You're offline. kwant bots opens once your phone is connected again.";+ if (e instanceof Error && e.message !== 'Failed to fetch' && e.message !== 'Load failed') return e.message;+ return "Can't reach the kwant bots server. Check that it's running and that this device can reach it.";+}+/** Shows its children once the API answers, and the token screen while it needs a token. */export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children }) => {const [state, setState] = useState<GateState>({ kind: 'checking' });@@ -51,7 +58,7 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })const s = await fetchAuthStatus();setState(s.auth_required && !s.authenticated ? { kind: 'locked', notice } : { kind: 'ready', authRequired: s.auth_required });} catch (e) {- setState({ kind: 'offline', message: e instanceof Error && e.message !== 'Failed to fetch' ? e.message : "Can't reach the kwant bots server. Is it running?" });+ setState({ kind: 'offline', message: offlineMessage(e, navigator.onLine) });} finally {checking.current = false;}@@ -67,12 +74,16 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })const onHash = () => {if (window.location.hash.includes('kwnt_token=')) consumeTokenLink().then((linkError) => check(linkError));};+ // Back on the network (the installed app opened offline): try again without a tap.+ const onOnline = () => check();window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);window.addEventListener('hashchange', onHash);+ window.addEventListener('online', onOnline);return () => {cancelled = true;window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);window.removeEventListener('hashchange', onHash);+ window.removeEventListener('online', onOnline);};}, [check]);@@ -105,7 +116,7 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })}return (- <div className="min-h-screen w-screen flex items-center justify-center bg-zinc-950 text-zinc-100 p-4 font-sans">+ <div className="min-h-[100dvh] w-screen flex items-center justify-center bg-zinc-950 text-zinc-100 p-4 pt-[max(1rem,env(safe-area-inset-top))] pb-[max(1rem,env(safe-area-inset-bottom))] font-sans"><div className="w-full max-w-md bg-zinc-900 border border-zinc-800 rounded-2xl p-6 shadow-2xl space-y-5"><div className="flex items-center gap-3"><ModernAvatar role="brand" name="kwant bots" size={36} />@@ -128,7 +139,7 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })setState({ kind: 'checking' });check();}}- className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 transition-colors"+ className="flex items-center gap-1.5 min-h-[44px] px-4 rounded-lg text-xs font-medium bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 transition-colors"><RefreshCw size={13} /> Try again</button>diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex ccac038b..7a99efa6 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -919,7 +919,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<buttontype="button"onClick={onEditInstructions}- className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"+ className="flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"title="Pin instructions every bot reads in this channel"aria-label="Pin instructions">@@ -959,7 +959,7 @@ export const ChatView: React.FC<ChatViewProps> = ({playSfx('click');toggleVm();}}- className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-colors border shadow-sm cursor-pointer ${+ className={`flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-full text-xs font-medium transition-colors border shadow-sm cursor-pointer ${vmOpen? 'text-sky-300 bg-sky-500/20 border-sky-500/40': 'text-zinc-300 bg-zinc-900 hover:bg-zinc-800 border-zinc-700/60 hover:text-zinc-100'diff --git a/frontend/src/components/InstallHint.tsx b/frontend/src/components/InstallHint.tsxnew file mode 100644index 00000000..a542ae53--- /dev/null+++ b/frontend/src/components/InstallHint.tsx@@ -0,0 +1,113 @@+import React, { useEffect, useState } from 'react';+import { Download, Share, SquarePlus, X } from 'lucide-react';+import { INSTALL_HINT_DISMISSED_KEY, installHintKind, isIos, isStandalone } from '../pwa';++/** Chrome's install event: not in the DOM types yet. */+interface InstallPromptEvent extends Event {+ prompt: () => Promise<void>;+ userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;+}++const PHONE_QUERY = '(max-width: 767px)';++const readDismissed = () => {+ try {+ return localStorage.getItem(INSTALL_HINT_DISMISSED_KEY) === '1';+ } catch {+ return false;+ }+};++/** "Install on your phone": the browser's install button on Android, the Share steps on iPhone.+ * Sits above the phone tab bar until it's installed or dismissed. */+export const InstallHint: React.FC = () => {+ const [prompt, setPrompt] = useState<InstallPromptEvent | null>(null);+ const [dismissed, setDismissed] = useState(readDismissed);+ const [installed, setInstalled] = useState(() => isStandalone(window));+ const [phone, setPhone] = useState(() => !!window.matchMedia?.(PHONE_QUERY).matches);++ useEffect(() => {+ const onPrompt = (e: Event) => {+ // Keep Chrome's own mini bar away; the hint offers the same install.+ e.preventDefault();+ setPrompt(e as InstallPromptEvent);+ };+ const onInstalled = () => setInstalled(true);+ const mq = window.matchMedia?.(PHONE_QUERY);+ const onMq = () => setPhone(!!mq?.matches);+ window.addEventListener('beforeinstallprompt', onPrompt);+ window.addEventListener('appinstalled', onInstalled);+ mq?.addEventListener('change', onMq);+ return () => {+ window.removeEventListener('beforeinstallprompt', onPrompt);+ window.removeEventListener('appinstalled', onInstalled);+ mq?.removeEventListener('change', onMq);+ };+ }, []);++ const kind = installHintKind({+ standalone: installed,+ dismissed,+ phone,+ secure: window.isSecureContext,+ ios: isIos(navigator),+ canPrompt: !!prompt,+ });+ if (!kind) return null;++ const dismiss = () => {+ setDismissed(true);+ try {+ localStorage.setItem(INSTALL_HINT_DISMISSED_KEY, '1');+ } catch {+ // Private browsing: it comes back next time, which is fine.+ }+ };++ const install = async () => {+ if (!prompt) return;+ await prompt.prompt();+ const { outcome } = await prompt.userChoice.catch(() => ({ outcome: 'dismissed' as const }));+ // A prompt works once; Chrome sends a new event if it can be offered again.+ setPrompt(null);+ if (outcome === 'accepted') setInstalled(true);+ };++ return (+ <aside+ aria-label="Install on your phone"+ data-install-hint={kind}+ className="fixed inset-x-3 z-[55] bottom-[calc(env(safe-area-inset-bottom)+4.25rem)] flex items-start gap-3 rounded-xl border border-sky-500/30 bg-zinc-900/95 p-3 shadow-xl text-xs backdrop-blur"+ >+ <img src="/icons/icon-192.png" alt="" width={36} height={36} className="shrink-0 rounded-lg [image-rendering:pixelated]" />+ <div className="flex-1 min-w-0">+ <p className="font-medium text-zinc-100">Install kwant bots on your phone</p>+ {kind === 'prompt' ? (+ <>+ <p className="mt-0.5 text-zinc-400">It opens full screen from your home screen, like an app.</p>+ <button+ type="button"+ onClick={install}+ className="mt-2 inline-flex min-h-[44px] items-center gap-1.5 rounded-lg bg-sky-600 px-4 font-medium text-white hover:bg-sky-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400"+ >+ <Download size={14} aria-hidden="true" /> Install+ </button>+ </>+ ) : (+ <p className="mt-0.5 text-zinc-400 leading-relaxed">+ Tap <Share size={13} className="inline -mt-0.5 text-sky-300" aria-label="Share" /> Share, then{' '}+ <SquarePlus size={13} className="inline -mt-0.5 text-sky-300" aria-hidden="true" /> Add to Home Screen.+ </p>+ )}+ </div>+ <button+ type="button"+ onClick={dismiss}+ aria-label="Not now"+ className="-m-1 flex h-11 w-11 shrink-0 items-center justify-center rounded-lg text-zinc-500 hover:bg-zinc-800 hover:text-zinc-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <X size={16} />+ </button>+ </aside>+ );+};diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 03440930..80d8aa0e 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -434,7 +434,7 @@ export const Sidebar: React.FC<SidebarProps> = ({playSfx('click');onManageTeam(t);}}- className="opacity-0 group-hover:opacity-100 p-1 hover:text-zinc-100 hover:bg-zinc-700/60 rounded transition-all text-zinc-400"+ className="opacity-0 group-hover:opacity-100 max-md:opacity-100 p-1 hover:text-zinc-100 hover:bg-zinc-700/60 rounded transition-all text-zinc-400"title={`Team settings for @${t.name}`}><Settings2 size={12} />diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex dceb86b0..86a455bb 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -369,7 +369,7 @@ const GeneralTab: React.FC<Props> = ({ space, spaces, kwants, onSpaceSaved, onAraria-pressed={icon === i}aria-label={`Icon ${i}`}onClick={() => setIcon(i)}- className={`w-9 h-9 rounded-lg text-lg flex items-center justify-center border ${icon === i ? 'border-sky-400 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-600'}`}+ className={`w-9 h-9 max-md:w-11 max-md:h-11 rounded-lg text-lg flex items-center justify-center border ${icon === i ? 'border-sky-400 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-600'}`}>{i}</button>diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 795b1bc8..fcf6b475 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -3,8 +3,12 @@ import ReactDOM from 'react-dom/client';import { App } from './Shell';import { SandboxViewer } from './components/SandboxViewer';import { AuthGate } from './components/AuthGate';+import { registerServiceWorker, trackAppHeight } from './pwa';import './styles/modern.css';+registerServiceWorker();+trackAppHeight();+const sandboxMatch = window.location.pathname.match(/^\/sandbox\/([^/]+)\/?$/);ReactDOM.createRoot(document.getElementById('root')!).render(diff --git a/frontend/src/pwa.ts b/frontend/src/pwa.tsnew file mode 100644index 00000000..5feabf2e--- /dev/null+++ b/frontend/src/pwa.ts@@ -0,0 +1,64 @@+// Installing kwant bots on a phone: the service worker, the install hint and the app height.++/** Registers /sw.js (built by vite.config.ts). Only in a build, and only where browsers allow+ * one: HTTPS or localhost. Plain http on a home network still works, just not installed. */+export function registerServiceWorker(win: Window = window, prod: boolean = import.meta.env.PROD): boolean {+ if (!prod || !win.isSecureContext || !('serviceWorker' in win.navigator)) return false;+ const register = () => {+ win.navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => undefined);+ };+ if (win.document.readyState === 'complete') register();+ else win.addEventListener('load', register, { once: true });+ return true;+}++/** Whether this is the installed app (home screen), not a browser tab. */+export function isStandalone(win: Pick<Window, 'matchMedia' | 'navigator'>): boolean {+ if ((win.navigator as Navigator & { standalone?: boolean }).standalone === true) return true;+ return !!win.matchMedia?.('(display-mode: standalone)').matches;+}++/** iPhone and iPad, where installing is Share, then Add to Home Screen. iPadOS says it's a Mac. */+export function isIos(nav: Pick<Navigator, 'userAgent' | 'maxTouchPoints'>): boolean {+ return /iPhone|iPad|iPod/.test(nav.userAgent) || (/Macintosh/.test(nav.userAgent) && nav.maxTouchPoints > 1);+}++export type InstallHintKind = 'prompt' | 'ios' | null;++/** Which install hint to show: the browser's own install button (Android, Chrome), the Share+ * steps (iOS), or none: already installed, dismissed, not a phone, or not served over HTTPS. */+export function installHintKind(s: {+ standalone: boolean;+ dismissed: boolean;+ phone: boolean;+ secure: boolean;+ ios: boolean;+ canPrompt: boolean;+}): InstallHintKind {+ if (s.standalone || s.dismissed || !s.phone || !s.secure) return null;+ if (s.canPrompt) return 'prompt';+ return s.ios ? 'ios' : null;+}++export const INSTALL_HINT_DISMISSED_KEY = 'kwnt.installHint.dismissed';++/** Keeps --kwnt-app-height at the visible height, so the iOS keyboard doesn't cover the message+ * box (Android resizes the page itself: interactive-widget=resizes-content in index.html). */+export function trackAppHeight(win: Window = window): () => void {+ const vv = win.visualViewport;+ if (!vv) return () => undefined;+ const root = win.document.documentElement;+ const update = () => {+ // Pinch zoom shrinks the visible area too; times the zoom it's the page height again.+ root.style.setProperty('--kwnt-app-height', `${Math.round(vv.height * vv.scale)}px`);+ // iOS scrolls the whole page up to show the field; the app already fits, so undo that.+ if (vv.scale === 1 && (vv.offsetTop > 0 || win.scrollY > 0)) win.scrollTo(0, 0);+ };+ update();+ vv.addEventListener('resize', update);+ vv.addEventListener('scroll', update);+ return () => {+ vv.removeEventListener('resize', update);+ vv.removeEventListener('scroll', update);+ };+}diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 6f8a4285..28e421cb 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -141,3 +141,33 @@box-shadow: 0 0 0 2px theme('colors.amber.400 / 70%');}}++/* Phones: every control is at least 44px to tap, and text fields are 16px so iOS doesn't zoom+ in on them. Only on touch screens below 768px, so desktop and narrow mouse windows keep the+ compact look. Toggle switches, checkboxes and links inside text keep their size; anything else+ that must stay small can opt out with data-compact. */+@media (max-width: 767px) and (pointer: coarse) {+ :is(button, [role='button'], [role='tab'], [role='menuitem'], [role='option'], select, summary):not([role='switch'], [data-compact], .prose *) {+ min-height: 44px;+ }+ /* Icon-only buttons get the width too, with the icon centred */+ button:not([role='switch'], [data-compact], .hidden, :has(> :not(svg, img))):has(> svg, > img) {+ min-width: 44px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ }+ /* Colour swatches and other empty buttons: a full square */+ button:empty:not([role='switch'], [data-compact]) {+ min-width: 44px;+ }+ textarea,+ input:not([type='checkbox'], [type='radio'], [type='range'], [type='color'], [type='file'], [type='hidden']) {+ min-height: 44px;+ }+ input:not([type='checkbox'], [type='radio'], [type='range'], [type='color'], [type='file']),+ textarea,+ select {+ font-size: 16px;+ }+}diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.tsnew file mode 100644index 00000000..11f02fe2--- /dev/null+++ b/frontend/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/frontend/sw.js b/frontend/sw.jsnew file mode 100644index 00000000..dc6ea374--- /dev/null+++ b/frontend/sw.js@@ -0,0 +1,61 @@+// kwant bots service worker: keeps the app shell (index.html, the built JS/CSS, icons) on the+// device so the installed app opens fast and shows "can't reach the server" instead of a blank+// page when the server is down. It never stores anything else: the API, the event stream, the+// browser stream, uploads and other sites always go straight to the network, untouched.+//+// vite.config.ts fills in the version and the file list for each build (see pwaServiceWorker),+// so a new build installs a new cache and drops the old one.++const VERSION = '__KWNT_SW_VERSION__';+const SHELL = __KWNT_SW_SHELL__;+const CACHE = `kwnt-shell-${VERSION}`;+const INDEX = '/index.html';++/** Whether a request is one the worker answers. Anything else is left to the network. */+function handles(request, origin) {+ if (request.method !== 'GET') return false;+ const url = new URL(request.url);+ if (url.origin !== origin) return false;+ if (url.pathname === '/api' || url.pathname.startsWith('/api/')) return false;+ if (request.headers.get('range')) return false;+ if ((request.headers.get('accept') || '').includes('text/event-stream')) return false;+ if (request.mode === 'navigate') return true;+ return SHELL.includes(url.pathname);+}++self.addEventListener('install', (event) => {+ event.waitUntil(+ caches+ .open(CACHE)+ .then((cache) => cache.addAll(SHELL))+ .then(() => self.skipWaiting()),+ );+});++self.addEventListener('activate', (event) => {+ event.waitUntil(+ caches+ .keys()+ .then((keys) => Promise.all(keys.filter((k) => k.startsWith('kwnt-shell-') && k !== CACHE).map((k) => caches.delete(k))))+ .then(() => self.clients.claim()),+ );+});++self.addEventListener('fetch', (event) => {+ const { request } = event;+ if (!handles(request, self.location.origin)) return;+ if (request.mode === 'navigate') {+ // The page itself: the server first, so an update shows on the next load; the stored copy+ // only when the server can't be reached. The app then says so itself.+ event.respondWith(+ fetch(request).catch(() =>+ caches.open(CACHE).then((cache) => cache.match(INDEX)).then((hit) => hit || Response.error()),+ ),+ );+ return;+ }+ // Built files have a hash in their name and never change: the stored copy first.+ event.respondWith(+ caches.open(CACHE).then((cache) => cache.match(request).then((hit) => hit || fetch(request))),+ );+});diff --git a/frontend/tests/pwa.test.mjs b/frontend/tests/pwa.test.mjsnew file mode 100644index 00000000..4dda21fd--- /dev/null+++ b/frontend/tests/pwa.test.mjs@@ -0,0 +1,247 @@+// Installing kwant bots on a phone: the service worker's cache rules, the manifest and icons,+// the install hint and the offline message.+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, 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 ORIGIN = 'https://kwant.example';+const SHELL = ['/', '/assets/index-abc123.js', '/assets/index-def456.css', '/icons/icon-192.png', '/index.html', '/manifest.webmanifest'];++/** Runs sw.js against fake caches and network; returns what it did. */+function loadWorker({ source, version = 'v2', shell = SHELL, oldCaches = [] } = {}) {+ const code = (source ?? readFileSync(`${root}/sw.js`, 'utf8'))+ .replace('__KWNT_SW_VERSION__', version)+ .replace('__KWNT_SW_SHELL__', JSON.stringify(shell));+ const stores = new Map(oldCaches.map((k) => [k, new Map()]));+ const log = { put: [], fetched: [], deleted: [], skipWaiting: 0, claimed: 0 };+ const store = (name) => {+ if (!stores.has(name)) stores.set(name, new Map());+ const m = stores.get(name);+ const key = (r) => new URL(typeof r === 'string' ? r : r.url, ORIGIN).pathname;+ return {+ addAll: async (paths) => paths.forEach((p) => { log.put.push(p); m.set(key(p), `cached ${key(p)}`); }),+ put: async (r, res) => { log.put.push(key(r)); m.set(key(r), res); },+ match: async (r) => m.get(key(r)),+ };+ };+ const handlers = {};+ let online = true;+ const self = {+ location: { origin: ORIGIN },+ addEventListener: (type, fn) => { handlers[type] = fn; },+ skipWaiting: async () => { log.skipWaiting++; },+ clients: { claim: async () => { log.claimed++; } },+ };+ const context = {+ self,+ URL,+ Response: { error: () => 'network error' },+ caches: {+ open: async (name) => store(name),+ keys: async () => [...stores.keys()],+ delete: async (name) => { log.deleted.push(name); return stores.delete(name); },+ },+ fetch: async (r) => {+ log.fetched.push(new URL(r.url).pathname);+ if (!online) throw new TypeError('Failed to fetch');+ return `network ${new URL(r.url).pathname}`;+ },+ };+ vm.runInNewContext(code, context);+ const run = async (type, extra = {}) => {+ let waited;+ let responded;+ handlers[type]({ ...extra, waitUntil: (p) => { waited = p; }, respondWith: (p) => { responded = p; } });+ await waited;+ return responded === undefined ? undefined : await responded;+ };+ const request = (path, { method = 'GET', mode = 'cors', headers = {}, origin = ORIGIN } = {}) => ({+ url: new URL(path, origin).href,+ method,+ mode,+ headers: new Headers(headers),+ });+ return {+ log,+ stores,+ request,+ install: () => run('install'),+ activate: () => run('activate'),+ fetch: (req) => run('fetch', { request: req }),+ setOnline: (v) => { online = v; },+ };+}++test('the worker never answers or stores the API, the event stream, uploads or other sites', async () => {+ const sw = loadWorker();+ await sw.install();+ const putBefore = sw.log.put.length;+ const passThrough = [+ sw.request('/api'),+ sw.request('/api/spaces'),+ sw.request('/api/auth/status'),+ sw.request('/api/events', { headers: { accept: 'text/event-stream' } }),+ sw.request('/api/browser/ws'),+ sw.request('/api/kwants', { method: 'POST' }),+ sw.request('/api/uploads/x', { method: 'PUT' }),+ // Even a page load under /api is the server's, never index.html+ sw.request('/api/export', { mode: 'navigate' }),+ sw.request('/events', { headers: { accept: 'text/event-stream' } }),+ sw.request('/assets/index-abc123.js', { headers: { range: 'bytes=0-10' } }),+ sw.request('/assets/index-abc123.js', { origin: 'https://cdn.example' }),+ sw.request('/', { origin: 'https://other.example', mode: 'navigate' }),+ sw.request('/', { method: 'POST', mode: 'navigate' }),+ sw.request('/files/report.pdf'),+ ];+ for (const r of passThrough) {+ assert.equal(await sw.fetch(r), undefined, `${r.method} ${r.url} must go straight to the network`);+ }+ assert.equal(sw.log.put.length, putBefore, 'nothing new is stored');+ assert.deepEqual(sw.log.fetched, [], 'the worker made no requests of its own');+ for (const [, m] of sw.stores) {+ assert.ok(![...m.keys()].some((k) => k === '/api' || k.startsWith('/api/')), 'no /api entry in any cache');+ }+});++test('install stores exactly the app shell, under a cache named for this build', async () => {+ const sw = loadWorker({ version: 'abc' });+ await sw.install();+ assert.deepEqual(sw.log.put, SHELL);+ assert.deepEqual([...sw.stores.keys()], ['kwnt-shell-abc']);+ assert.equal(sw.log.skipWaiting, 1, 'the new build takes over without waiting for every tab to close');+});++test('activate drops caches from older builds but leaves other caches alone', async () => {+ const sw = loadWorker({ version: 'new', oldCaches: ['kwnt-shell-old', 'kwnt-shell-older', 'someone-elses-cache'] });+ await sw.install();+ await sw.activate();+ assert.deepEqual(sw.log.deleted.sort(), ['kwnt-shell-old', 'kwnt-shell-older']);+ assert.deepEqual([...sw.stores.keys()].sort(), ['kwnt-shell-new', 'someone-elses-cache']);+ assert.equal(sw.log.claimed, 1);+});++test('pages come from the server first and from the stored index.html only when it is unreachable', async () => {+ const sw = loadWorker();+ await sw.install();+ assert.equal(await sw.fetch(sw.request('/channels/abc', { mode: 'navigate' })), 'network /channels/abc');+ sw.setOnline(false);+ assert.equal(await sw.fetch(sw.request('/channels/abc', { mode: 'navigate' })), 'cached /index.html');+});++test('with nothing stored yet, an offline page load is a plain network error, not a blank page', async () => {+ const sw = loadWorker();+ sw.setOnline(false);+ assert.equal(await sw.fetch(sw.request('/', { mode: 'navigate' })), 'network error');+});++test('built files come from the store first, so the installed app opens without the server', async () => {+ const sw = loadWorker();+ await sw.install();+ sw.setOnline(false);+ assert.equal(await sw.fetch(sw.request('/assets/index-abc123.js')), 'cached /assets/index-abc123.js');+ assert.deepEqual(sw.log.fetched, []);+});++const built = `${root}/dist/sw.js`;+test('the build fills in the version and the shell list', { skip: !existsSync(built) && 'run npm run build first' }, async () => {+ const source = readFileSync(built, 'utf8');+ assert.ok(!source.includes('__KWNT_SW_'), 'no placeholders left');+ const version = source.match(/const VERSION = '([0-9a-f]{12})'/);+ assert.ok(version, 'a 12-character build version');+ const shell = JSON.parse(source.match(/const SHELL = (\[.*\]);/)[1]);+ assert.ok(shell.includes('/index.html'));+ assert.ok(shell.includes('/manifest.webmanifest'));+ assert.ok(shell.some((p) => /^\/assets\/index-.*\.js$/.test(p)));+ assert.ok(!shell.some((p) => p.startsWith('/api')), 'the API is never part of the shell');+ assert.ok(!shell.some((p) => p.endsWith('.map') || p === '/sw.js'));+ for (const p of shell) assert.ok(existsSync(`${root}/dist${p}`), `${p} is in dist`);+ // The built worker keeps the same rules as the template+ const sw = loadWorker({ source: source.replace(version[1], '__KWNT_SW_VERSION__').replace(/const SHELL = \[.*\];/, 'const SHELL = __KWNT_SW_SHELL__;') });+ await sw.install();+ assert.equal(await sw.fetch(sw.request('/api/spaces')), undefined);+});++test('the manifest makes kwant bots installable, and every icon it names exists', () => {+ const m = JSON.parse(readFileSync(`${root}/public/manifest.webmanifest`, 'utf8'));+ assert.equal(m.name, 'kwant bots');+ assert.equal(m.short_name, 'kwant bots');+ assert.equal(m.start_url, '/');+ assert.equal(m.scope, '/');+ assert.equal(m.display, 'standalone');+ assert.match(m.theme_color, /^#[0-9a-f]{6}$/i);+ assert.match(m.background_color, /^#[0-9a-f]{6}$/i);+ const sizes = (purpose) => m.icons.filter((i) => (i.purpose ?? 'any').split(' ').includes(purpose)).map((i) => i.sizes);+ for (const s of ['192x192', '512x512']) {+ assert.ok(sizes('any').includes(s), `${s} icon`);+ assert.ok(sizes('maskable').includes(s), `${s} maskable icon`);+ }+ for (const i of m.icons) assert.ok(existsSync(`${root}/public${i.src}`), `${i.src} exists`);++ const html = readFileSync(`${root}/index.html`, 'utf8');+ assert.match(html, /<link rel="manifest" href="\/manifest\.webmanifest"/);+ assert.match(html, /<link rel="apple-touch-icon" href="\/icons\/apple-touch-icon\.png"/);+ assert.match(html, /name="apple-mobile-web-app-capable" content="yes"/);+ assert.match(html, new RegExp(`name="theme-color" content="${m.theme_color}"`));+ assert.match(html, /viewport-fit=cover/);+ assert.ok(existsSync(`${root}/public/icons/apple-touch-icon.png`));+});++const pwa = await loadBundled(`export * from './src/pwa.ts'; export { offlineMessage } from './src/components/AuthGate.tsx';`);++test('the install hint: install button on Android, Share steps on iPhone, nothing otherwise', () => {+ const base = { standalone: false, dismissed: false, phone: true, secure: true, ios: false, canPrompt: false };+ assert.equal(pwa.installHintKind({ ...base, canPrompt: true }), 'prompt');+ assert.equal(pwa.installHintKind({ ...base, ios: true }), 'ios');+ assert.equal(pwa.installHintKind(base), null, 'no install route to offer');+ assert.equal(pwa.installHintKind({ ...base, canPrompt: true, standalone: true }), null, 'already installed');+ assert.equal(pwa.installHintKind({ ...base, ios: true, dismissed: true }), null, 'dismissed');+ assert.equal(pwa.installHintKind({ ...base, canPrompt: true, phone: false }), null, 'not on a phone');+ assert.equal(pwa.installHintKind({ ...base, ios: true, secure: false }), null, 'plain http cannot install');+});++test('iPhone and iPad are recognised, including iPadOS calling itself a Mac', () => {+ assert.ok(pwa.isIos({ userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)', maxTouchPoints: 5 }));+ assert.ok(pwa.isIos({ userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari', maxTouchPoints: 5 }));+ assert.ok(!pwa.isIos({ userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari', maxTouchPoints: 0 }));+ assert.ok(!pwa.isIos({ userAgent: 'Mozilla/5.0 (Linux; Android 15; Pixel 9) Chrome/154', maxTouchPoints: 5 }));+});++test('standalone means the installed app, on iOS or Android', () => {+ const win = (standalone, matches) => ({ navigator: { standalone }, matchMedia: () => ({ matches }) });+ assert.ok(pwa.isStandalone(win(true, false)));+ assert.ok(pwa.isStandalone(win(undefined, true)));+ assert.ok(!pwa.isStandalone(win(undefined, false)));+});++test('the service worker registers only in a build over HTTPS or localhost', () => {+ const win = (secure) => {+ const calls = [];+ return {+ calls,+ isSecureContext: secure,+ document: { readyState: 'complete' },+ addEventListener: () => {},+ navigator: { serviceWorker: { register: (...a) => { calls.push(a); return Promise.resolve(); } } },+ };+ };+ const ok = win(true);+ assert.equal(pwa.registerServiceWorker(ok, true), true);+ assert.deepEqual(ok.calls, [['/sw.js', { scope: '/' }]]);+ const dev = win(true);+ assert.equal(pwa.registerServiceWorker(dev, false), false);+ assert.deepEqual(dev.calls, []);+ const http = win(false);+ assert.equal(pwa.registerServiceWorker(http, true), false);+ assert.deepEqual(http.calls, []);+});++test('the offline screen says offline, or that the server cannot be reached, never a raw fetch error', () => {+ assert.match(pwa.offlineMessage(new TypeError('Failed to fetch'), false), /You're offline/);+ assert.match(pwa.offlineMessage(new TypeError('Failed to fetch'), true), /Can't reach the kwant bots server/);+ assert.match(pwa.offlineMessage(new TypeError('Load failed'), true), /Can't reach the kwant bots server/);+ assert.equal(pwa.offlineMessage(new Error('Server returned 502'), true), 'Server returned 502');+});diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 75f54b93..e7226d48 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -1,8 +1,51 @@-import { defineConfig } from 'vite';+import { defineConfig, Plugin } from 'vite';import react from '@vitejs/plugin-react';+import { createHash } from 'node:crypto';+import { readFileSync, readdirSync } from 'node:fs';+import { join, relative } from 'node:path';++const files = (dir: string): string[] =>+ readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : [join(dir, e.name)]));++/** Emits sw.js with this build's app shell (every built file plus public/) and a version that+ * changes whenever any of them does, so phones pick up a new build on the next load. */+function pwaServiceWorker(): Plugin {+ let publicDir = '';+ return {+ name: 'kwnt-pwa-service-worker',+ apply: 'build',+ // After Vite's own HTML plugin, so index.html is in the bundle too+ enforce: 'post',+ configResolved(config) {+ publicDir = config.publicDir;+ },+ generateBundle(_options, bundle) {+ const hash = createHash('sha256');+ const shell = new Set<string>();+ for (const [name, chunk] of Object.entries(bundle)) {+ if (name.endsWith('.map')) continue;+ shell.add(`/${name}`);+ hash.update(name).update(chunk.type === 'chunk' ? chunk.code : chunk.source);+ }+ for (const file of files(publicDir)) {+ shell.add(`/${relative(publicDir, file).split('\\').join('/')}`);+ hash.update(file).update(readFileSync(file));+ }+ const template = readFileSync(new URL('./sw.js', import.meta.url), 'utf8');+ hash.update(template);+ this.emitFile({+ type: 'asset',+ fileName: 'sw.js',+ source: template+ .replace('__KWNT_SW_VERSION__', hash.digest('hex').slice(0, 12))+ .replace('__KWNT_SW_SHELL__', JSON.stringify([...shell].sort())),+ });+ },+ };+}export default defineConfig({- plugins: [react()],+ plugins: [react(), pwaServiceWorker()],server: {port: 5199,proxy: {