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
Settings › All spaces: Use kwant bots on your phone (20h PR B) (#691)
Oleksandr Ivanchenko6c0dbfe40f9e
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex cf0bda04..649b4c11 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -11,6 +11,7 @@ import { PHONE_QUERY } from './layout';import { useSettingsCover } from './settingsFocus';import { WhatsNewHost } from './components/WhatsNewSheet';import { GetStarted, GetStartedBanner } from './components/GetStarted';+import { focusPhoneApp } from './components/PhoneAppTip';import { focusDevSettings, markMovedSeen, movedPointerShows, movedSeen, ringDevSettings } from './firstScreen';import { dismiss as dismissGetStarted, isDismissed as getStartedDismissed, showCard as showGetStarted, wasStarted as getStartedWasStarted, whatsNewEstablished as decideWhatsNewEstablished } from './gettingStarted';import { useStartVersion } from './gettingStartedInstall';@@ -4092,6 +4093,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onSwitchSpace={onSwitchSpace}onCreateSpace={onCreateSpace}onOpenSpaceSettings={() => openSpaceSettings('general')}+ onOpenPhoneApp={() => {+ openAppSettings();+ focusPhoneApp();+ }}onOpenArchived={onOpenArchived}onOpenSearch={() => setIsSearchOpen(true)}section={section}diff --git a/frontend/src/authContext.ts b/frontend/src/authContext.tsnew file mode 100644index 00000000..fac5576e--- /dev/null+++ b/frontend/src/authContext.ts@@ -0,0 +1,15 @@+// Who this browser is to the server, shared by AuthGate and anything that reads it. Kept apart from+// AuthGate so reading it doesn't load the gate (which watches every fetch for a 401 on import).+import { createContext, useContext } from 'react';++export interface AuthContextValue {+ /** True when this browser needs the API token (Docker, a VPS reached directly). */+ authRequired: boolean;+ /** This server lets new browsers in from a signed-in one, and lists signed-in browsers. */+ deviceLogin: boolean;+ signOut: () => Promise<void>;+}++export const AuthContext = createContext<AuthContextValue>({ authRequired: false, deviceLogin: false, signOut: async () => undefined });++export const useAuth = () => useContext(AuthContext);diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsxindex ef733953..efaa3c8d 100644--- a/frontend/src/components/AuthGate.tsx+++ b/frontend/src/components/AuthGate.tsx@@ -1,4 +1,4 @@-import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';+import React, { useCallback, useEffect, useRef, useState } from 'react';import { Check, ChevronRight, Copy, KeyRound, Loader2, RefreshCw, Terminal, X } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { DeviceRequestPrompt, DeviceWait } from './DeviceSignIn';@@ -16,18 +16,9 @@ import {redeemSignIn,} from '../auth';import { fillTimeZone } from '../continuity';+import { AuthContext, useAuth } from '../authContext';-interface AuthContextValue {- /** True when this browser needs the API token (Docker, a VPS reached directly). */- authRequired: boolean;- /** This server lets new browsers in from a signed-in one, and lists signed-in browsers. */- deviceLogin: boolean;- signOut: () => Promise<void>;-}--const AuthContext = createContext<AuthContextValue>({ authRequired: false, deviceLogin: false, signOut: async () => undefined });--export const useAuth = () => useContext(AuthContext);+export { useAuth };type GateState =| { kind: 'checking' }diff --git a/frontend/src/components/DeviceSignIn.tsx b/frontend/src/components/DeviceSignIn.tsxindex b7e122a3..15d68cf8 100644--- a/frontend/src/components/DeviceSignIn.tsx+++ b/frontend/src/components/DeviceSignIn.tsx@@ -408,13 +408,13 @@ export type AddState =| { kind: 'error'; message: string };/** The QR code, drawn here: the sign-in code never goes to a QR service. */-export const QrImage: React.FC<{ text: string }> = ({ text }) => {+export const QrImage: React.FC<{ text: string; label?: string }> = ({ text, label = 'QR code for the one-time sign-in link' }) => {const { size, d } = qrPath(text);return (<svgviewBox={`0 0 ${size} ${size}`}role="img"- aria-label="QR code for the one-time sign-in link"+ aria-label={label}shapeRendering="crispEdges"className="block w-full h-auto rounded-lg bg-white">@@ -423,25 +423,35 @@ export const QrImage: React.FC<{ text: string }> = ({ text }) => {);};+/** Where AddDevice sits: Settings › Signed-in devices (`settings`), or step 1 of "Use kwant bots on+ * your phone" (`phone`), where step 2 right below already says to add it to the Home Screen. */+export type AddDeviceVariant = 'settings' | 'phone';++const phonePrimary =+ 'w-full sm:w-auto flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-4 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500';+/** What "Add a phone or browser" shows in each state. Exported for tests. */export const AddDeviceView: React.FC<{state: AddState;now?: number;copied?: 'yes' | 'failed' | null;+ variant?: AddDeviceVariant;onShow: () => void;onHide: () => void;onCopy: () => void;-}> = ({ state, now = Date.now(), copied = null, onShow, onHide, onCopy }) => {+}> = ({ state, now = Date.now(), copied = null, variant = 'settings', onShow, onHide, onCopy }) => {+ const phone = variant === 'phone';+ const linkId = `add-device-link-${variant}`;if (state.kind === 'idle' || state.kind === 'minting' || state.kind === 'error')return (<div className="space-y-2">- <button type="button" onClick={onShow} disabled={state.kind === 'minting'} className={`${secondary} w-full sm:w-auto disabled:opacity-50`}>+ <button type="button" onClick={onShow} disabled={state.kind === 'minting'} className={phone ? phonePrimary : `${secondary} w-full sm:w-auto disabled:opacity-50`}>{state.kind === 'minting' ? (<Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />) : (<QrCode size={14} aria-hidden="true" />)}- Add a phone or browser+ {phone ? 'Show QR code' : 'Add a phone or browser'}</button>{state.kind === 'error' && (<p className="flex items-center gap-1.5 text-[11px] text-rose-300" role="alert">@@ -455,11 +465,12 @@ export const AddDeviceView: React.FC<{return (<div className="space-y-3 rounded-xl border border-emerald-500/30 bg-emerald-500/5 p-4" role="status" aria-live="polite"><p className="flex items-center gap-2 text-xs font-medium text-emerald-200">- <Check size={14} aria-hidden="true" /> Signed in ✓+ <Check size={14} aria-hidden="true" /> Signed in</p><p className="text-[11px] text-zinc-400 leading-relaxed">{state.browser || 'A new browser'} signed in with the code. It’s used up now. If that wasn’t you, sign it out below.</p>+ {phone && <p className="text-[11px] text-zinc-300 leading-relaxed">Next, on the phone: add it to the Home Screen (step 2).</p>}<div className="flex flex-wrap gap-2"><button type="button" onClick={onShow} className={secondary}>Add another@@ -495,16 +506,21 @@ export const AddDeviceView: React.FC<{<div className="mx-auto w-full max-w-[220px]"><QrImage text={link.url} /></div>+ {!phone && (+ <p className="text-[11px] text-zinc-400 leading-relaxed">+ On a phone, then add it to the Home Screen: Share › Add to Home Screen on iPhone, ⋮ › Add to Home screen on Android.+ </p>+ )}<p className="flex items-start gap-1.5 text-[11px] text-amber-200/90 leading-relaxed"><AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden="true" />Anyone who scans this can sign in once. Don’t share or screenshot it.</p><div className="flex gap-2">- <label className="sr-only" htmlFor="add-device-link">+ <label className="sr-only" htmlFor={linkId}>One-time sign-in link</label><input- id="add-device-link"+ id={linkId}readOnlyvalue={link.url}onFocus={(e) => e.currentTarget.select()}@@ -532,8 +548,8 @@ export const AddDeviceView: React.FC<{};/** "Add a phone or browser": mints a one-time link, shows it as a QR code with a countdown, hides it- * when it expires or the page is left, and says "Signed in ✓" once a new browser used it. */-export const AddDevice: React.FC<{ onSignedIn: () => void }> = ({ onSignedIn }) => {+ * when it expires or the page is left, and says "Signed in" (with a tick icon) once a new browser used it. */+export const AddDevice: React.FC<{ onSignedIn: () => void; variant?: AddDeviceVariant }> = ({ onSignedIn, variant = 'settings' }) => {const [state, setState] = useState<AddState>({ kind: 'idle' });const [now, setNow] = useState(() => Date.now());const [copied, setCopied] = useState<'yes' | 'failed' | null>(null);@@ -630,7 +646,7 @@ export const AddDevice: React.FC<{ onSignedIn: () => void }> = ({ onSignedIn })}};- return <AddDeviceView state={state} now={now} copied={copied} onShow={show} onHide={hide} onCopy={copy} />;+ return <AddDeviceView state={state} now={now} copied={copied} variant={variant} onShow={show} onHide={hide} onCopy={copy} />;};/** Settings section: who is signed in, with Sign out for each other browser. */diff --git a/frontend/src/components/InstallAppButton.tsx b/frontend/src/components/InstallAppButton.tsxindex da4d6d38..c4ef5b03 100644--- a/frontend/src/components/InstallAppButton.tsx+++ b/frontend/src/components/InstallAppButton.tsx@@ -1,22 +1,16 @@import React, { useId, useState } from 'react';-import { Download, ExternalLink, Laptop, Share, SquarePlus, X } from 'lucide-react';-import { MAC_DOWNLOAD_URL, desktopInstallKind, isEmbeddedWebView, isIos, isMacSafari, isStandalone, runInstallPrompt } from '../pwa';+import { Download, ExternalLink, Laptop, Share, SquarePlus } from 'lucide-react';+import { type DesktopInstallKind, MAC_DOWNLOAD_URL, desktopInstallKind, isEmbeddedWebView, isIos, isMacSafari, isStandalone, runInstallPrompt } from '../pwa';import { useInstall } from '../useInstall';-import { dismissInstallTip, installTipDismissed } from '../nav';const onMac = () => /Macintosh/.test(navigator.userAgent) && !isIos(navigator);-/** "Install app", on desktop: Chrome and Edge install in one click; other browsers get the steps- * that work there. Gone once kwant runs installed, or in the Mac app. Settings › All spaces always- * has it; the sidebar shows it once as a `tip` until it is dismissed. */-export const InstallAppButton: React.FC<{ className: string; tip?: boolean }> = ({ className, tip = false }) => {+/** What the desktop install entry offers here; null when there's nothing to install (installed,+ * the Mac app, or server rendering in tests). */+export function useDesktopInstallKind(): DesktopInstallKind {const { prompt, installed } = useInstall();- const [open, setOpen] = useState(false);- const [dismissed, setDismissed] = useState(() => tip && installTipDismissed());- const panelId = useId();-- // Server rendering (tests) has no browser to install into.- const kind = typeof window === 'undefined' ? null : desktopInstallKind({+ if (typeof window === 'undefined') return null;+ return desktopInstallKind({standalone: installed || isStandalone(window),embedded: isEmbeddedWebView(navigator),secure: window.isSecureContext,@@ -24,9 +18,16 @@ export const InstallAppButton: React.FC<{ className: string; tip?: boolean }> =macSafari: isMacSafari(navigator),ios: isIos(navigator),});- if (!kind || dismissed) return null;- // A tip that can only say "this can't install here" isn't worth the space.- if (tip && kind === 'insecure') return null;+}++/** "Install app", on desktop: Chrome and Edge install in one click; other browsers get the steps+ * that work there. Gone once kwant runs installed, or in the Mac app. It lives in the footer of+ * Settings › All spaces › Use kwant bots on your phone, as "Install on this computer". */+export const InstallAppButton: React.FC<{ className: string; label?: string }> = ({ className, label = 'Install app' }) => {+ const kind = useDesktopInstallKind();+ const [open, setOpen] = useState(false);+ const panelId = useId();+ if (!kind) return null;const onClick = () => {if (kind === 'prompt') void runInstallPrompt();@@ -34,7 +35,7 @@ export const InstallAppButton: React.FC<{ className: string; tip?: boolean }> =};return (- <div className={tip ? 'hidden md:block rounded-lg border border-zinc-800 bg-zinc-900/60' : 'hidden md:block'} data-install-app={kind} data-install-tip={tip || undefined}>+ <div className="hidden md:block" data-install-app={kind}><div className="flex items-center"><buttontype="button"@@ -43,23 +44,9 @@ export const InstallAppButton: React.FC<{ className: string; tip?: boolean }> =aria-controls={kind === 'prompt' ? undefined : panelId}className={className}>- <Download size={15} className={tip ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />- <span className="truncate flex-1">{tip ? 'Tip: install this as an app' : 'Install app'}</span>+ <Download size={13} className="text-zinc-500" aria-hidden="true" />+ <span className="truncate flex-1">{label}</span></button>- {tip && (- <button- type="button"- onClick={() => {- dismissInstallTip();- setDismissed(true);- }}- aria-label="Dismiss the install tip"- title="Dismiss. Install any time from Settings › All spaces."- className="shrink-0 mr-1 p-1 rounded text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"- >- <X size={12} aria-hidden="true" />- </button>- )}</div>{open && kind !== 'prompt' && (<div id={panelId} className="mx-2.5 mt-1 mb-1.5 rounded-lg border border-zinc-800 bg-zinc-900/70 p-2.5 text-[11px] leading-relaxed text-zinc-400">diff --git a/frontend/src/components/InstallHint.tsx b/frontend/src/components/InstallHint.tsxindex fbe0045d..f20253ec 100644--- a/frontend/src/components/InstallHint.tsx+++ b/frontend/src/components/InstallHint.tsx@@ -1,6 +1,6 @@-import React, { useEffect, useState } from 'react';+import React, { useEffect, useState, useSyncExternalStore } from 'react';import { Download, Share, SquarePlus, X } from 'lucide-react';-import { INSTALL_HINT_DISMISSED_KEY, installHintKind, isIos, isStandalone, runInstallPrompt } from '../pwa';+import { INSTALL_HINT_DISMISSED_KEY, installHintKind, isIos, isPhoneCardOnScreen, isStandalone, runInstallPrompt, subscribePhoneCard } from '../pwa';import { useInstall } from '../useInstall';const PHONE_QUERY = '(max-width: 767px)';@@ -19,6 +19,7 @@ export const InstallHint: React.FC = () => {const { prompt, installed } = useInstall();const [dismissed, setDismissed] = useState(readDismissed);const [phone, setPhone] = useState(() => !!window.matchMedia?.(PHONE_QUERY).matches);+ const phoneCardOnScreen = useSyncExternalStore(subscribePhoneCard, isPhoneCardOnScreen, () => false);useEffect(() => {const mq = window.matchMedia?.(PHONE_QUERY);@@ -36,6 +37,7 @@ export const InstallHint: React.FC = () => {secure: window.isSecureContext,ios: isIos(navigator),canPrompt: !!prompt,+ phoneCardOnScreen,});if (!kind) return null;diff --git a/frontend/src/components/PhoneAppCard.tsx b/frontend/src/components/PhoneAppCard.tsxnew file mode 100644index 00000000..7cc73e72--- /dev/null+++ b/frontend/src/components/PhoneAppCard.tsx@@ -0,0 +1,365 @@+import React, { useEffect, useState } from 'react';+import { AlertTriangle, Check, Copy, Download, EllipsisVertical, ExternalLink, Share, Smartphone, SquarePlus } from 'lucide-react';+import {+ HTTPS_GUIDE_URL,+ PHONE_GUIDE_URL,+ TELEGRAM_GUIDE_URL,+ type PhoneAppKind,+ isAndroid,+ isEmbeddedWebView,+ isIos,+ isStandalone,+ phoneAppKind,+ phoneCardShown,+ runInstallPrompt,+} from '../pwa';+import { useInstall } from '../useInstall';+import { useAuth } from '../authContext';+import { AddDevice, QrImage } from './DeviceSignIn';+import { InstallAppButton, useDesktopInstallKind } from './InstallAppButton';+import { desktopAppOs, inDesktopApp } from '../externalLinks';+import { PHONE_APP_ANCHOR, PHONE_APP_TITLE } from './PhoneAppTip';++// "Use kwant bots on your phone": Settings › All spaces, first card. On a computer it shows a QR code+// (a one-time sign-in link when the server asks for sign-in) and three steps; on a phone it shows how+// to install this phone. On 127.0.0.1 or plain http it says why a phone can't use this address.++/** On a phone, what installing this phone takes: the browser's Install button, the iPhone Share+ * steps, the Android menu steps, or https first. */+export type PhoneInstallCase = 'prompt' | 'ios' | 'android' | 'insecure';+++const link =+ 'inline-flex items-center gap-1 text-[11px] text-sky-300 hover:text-sky-200 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 max-md:min-h-[44px]';+const rowBtn =+ 'flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-300 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70 hover:text-zinc-100 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const copyBtn =+ 'shrink-0 flex items-center justify-center gap-1.5 min-h-[36px] max-md:min-h-[44px] px-3 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const inlineIcon = 'inline -mt-0.5 text-sky-300';++const Ext: React.FC<{ href: string; children: React.ReactNode }> = ({ href, children }) => (+ <a href={href} target="_blank" rel="noopener noreferrer" className={link}>+ {children} <ExternalLink size={11} aria-hidden="true" />+ </a>+);++const Mono: React.FC<{ children: React.ReactNode }> = ({ children }) => <span className="font-mono text-zinc-300">{children}</span>;++const Steps: React.FC<{ items: Array<{ title: React.ReactNode; detail?: React.ReactNode; body?: React.ReactNode }> }> = ({ items }) => (+ <ol className="space-y-4">+ {items.map((it, i) => (+ <li key={i} className="flex gap-3">+ <span+ aria-hidden="true"+ className="h-5 w-5 shrink-0 mt-px rounded-full bg-zinc-800 border border-zinc-700 text-[11px] font-semibold text-zinc-200 flex items-center justify-center"+ >+ {i + 1}+ </span>+ <div className="flex-1 min-w-0 space-y-2">+ <p className="text-xs font-medium text-zinc-200">{it.title}</p>+ {it.detail && <div className="text-[11px] text-zinc-400 leading-relaxed">{it.detail}</div>}+ {it.body}+ </div>+ </li>+ ))}+ </ol>+);++const Note: React.FC<{ warn?: boolean; lead: React.ReactNode; children?: React.ReactNode }> = ({ warn, lead, children }) => (+ <div className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-4 space-y-3">+ <p className="flex items-start gap-2 text-xs text-zinc-200 leading-relaxed">+ {warn && <AlertTriangle size={14} className="mt-0.5 shrink-0 text-amber-300" aria-hidden="true" />}+ <span>{lead}</span>+ </p>+ {children}+ </div>+);++export interface PhoneAppCardViewProps {+ kind: PhoneAppKind;+ /** `phone`: install this phone (phones and tablets). `computer`: get it onto a phone. */+ layout: 'computer' | 'phone';+ /** On a phone: how this phone installs. */+ phoneCase?: PhoneInstallCase;+ /** location.host and location.origin. */+ host: string;+ origin: string;+ /** "Mac" in the Mac app or a Mac browser, else "computer". */+ machine: 'Mac' | 'computer';+ /** The server asks for an access token but has no device login: say so under the QR. */+ tokenSignIn?: boolean;+ /** Step 1 of `signin`: AddDevice, minted on click. A slot so tests can render the card alone. */+ signIn?: React.ReactNode;+ /** The "Install on this computer" row, or null when this browser has nothing to install. */+ installFooter?: React.ReactNode;+ copied?: 'yes' | 'failed' | null;+ onCopy?: () => void;+ onInstall?: () => void;+}++const homeScreenStep = {+ title: 'Add it to the Home Screen',+ detail: (+ <div className="space-y-1">+ <p>+ <span className="text-zinc-200">iPhone or iPad:</span> in Safari, tap <Share size={12} className={inlineIcon} aria-label="Share" /> Share ›+ Add to Home Screen.+ </p>+ <p>+ <span className="text-zinc-200">Android:</span> in Chrome, tap <EllipsisVertical size={12} className={inlineIcon} aria-label="menu" /> › Add to+ Home screen (or Install app).+ </p>+ </div>+ ),+};++const notifyStep = {+ title: 'Turn on notifications',+ detail:+ 'Open kwant bots from the Home Screen, then go to Settings › All spaces › Notifications › Notify me on this device. On an iPhone this only works in the Home Screen app.',+};++const notifyHere = 'Open kwant bots from the Home Screen and turn on Notify me on this device, under Notifications below.';++/** The card, from plain values. Exported for tests. */+export const PhoneAppCardView: React.FC<PhoneAppCardViewProps> = (p) => {+ const phone = p.layout === 'phone';+ const address = `${p.origin}/`;++ let body: React.ReactNode;+ if (phone) {+ if (p.phoneCase === 'insecure' || p.kind === 'insecure' || p.kind === 'loopback') {+ body = (+ <Note warn lead={<>Phones only install apps from an https address. This one is <Mono>{p.origin}</Mono>.</>}>+ <Ext href={HTTPS_GUIDE_URL}>Set up https</Ext>+ </Note>+ );+ } else if (p.phoneCase === 'prompt') {+ body = (+ <div className="space-y-2">+ <button+ type="button"+ onClick={p.onInstall}+ className="w-full flex items-center justify-center gap-1.5 min-h-[44px] px-4 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500"+ >+ <Download size={14} aria-hidden="true" /> Install+ </button>+ <p className="text-[11px] text-zinc-400 leading-relaxed">Then open it from your Home Screen and turn on Notify me on this device, under Notifications below.</p>+ </div>+ );+ } else if (p.phoneCase === 'ios') {+ body = (+ <div className="space-y-3">+ <Steps+ items={[+ {+ title: (+ <>+ Tap <Share size={12} className={inlineIcon} aria-label="Share" /> Share+ </>+ ),+ detail: 'In Safari it’s at the bottom of the screen; on iPad, at the top.',+ },+ {+ title: (+ <>+ Tap <SquarePlus size={12} className={inlineIcon} aria-hidden="true" /> Add to Home Screen, then Add+ </>+ ),+ },+ { title: notifyHere },+ ]}+ />+ <p className="text-[11px] text-zinc-400">No Add to Home Screen? Open this page in Safari.</p>+ </div>+ );+ } else {+ body = (+ <Steps+ items={[+ {+ title: (+ <>+ Tap <EllipsisVertical size={12} className={inlineIcon} aria-label="menu" /> in the browser’s menu+ </>+ ),+ },+ { title: 'Tap Add to Home screen (or Install app)' },+ { title: notifyHere },+ ]}+ />+ );+ }+ } else if (p.kind === 'loopback') {+ body = (+ <Note+ lead={+ <>+ Your phone can’t reach this one. kwant bots runs at <Mono>{p.host}</Mono>, an address only this {p.machine} can open.+ </>+ }+ >+ <p className="text-[11px] text-zinc-400">To have it on your phone:</p>+ <ul className="space-y-2">+ <li className="flex gap-2">+ <span className="h-1 w-1 shrink-0 rounded-full bg-zinc-500 mt-1.5" aria-hidden="true" />+ <div className="space-y-0.5">+ <p className="text-[11px] text-zinc-400 leading-relaxed">+ Run kwant bots on a server with an https address. Open that address on this computer, and this card shows a QR code for your phone.+ </p>+ <Ext href={PHONE_GUIDE_URL}>How to set it up</Ext>+ </div>+ </li>+ <li className="flex gap-2">+ <span className="h-1 w-1 shrink-0 rounded-full bg-zinc-500 mt-1.5" aria-hidden="true" />+ <div className="space-y-0.5">+ <p className="text-[11px] text-zinc-400 leading-relaxed">No server? Talk to your bots from your phone in Telegram.</p>+ <Ext href={TELEGRAM_GUIDE_URL}>Set up Telegram</Ext>+ </div>+ </li>+ </ul>+ </Note>+ );+ } else if (p.kind === 'insecure') {+ body = (+ <Note+ warn+ lead={+ <>+ Phones only install apps from an https address. This one is <Mono>{p.origin}</Mono>, so a phone can open it but can’t add it to the Home+ Screen or get notifications.+ </>+ }+ >+ <p className="text-[11px] text-zinc-400 leading-relaxed">+ Put kwant bots behind an https proxy, then open the https address on this computer. This card then shows a QR code for your phone.+ </p>+ <Ext href={HTTPS_GUIDE_URL}>Set up https</Ext>+ </Note>+ );+ } else {+ const step1 =+ p.kind === 'signin'+ ? { title: 'Scan with your phone’s camera', detail: 'It opens kwant bots on the phone and signs it in once.', body: p.signIn }+ : {+ title: 'Scan with your phone’s camera',+ detail: (+ <>+ It opens kwant bots at <Mono>{p.host}</Mono> on the phone.{p.tokenSignIn && ' Sign in there with your access token.'}+ </>+ ),+ body: (+ <div className="rounded-xl border border-sky-500/30 bg-sky-500/5 p-4 space-y-3" data-phone-qr>+ <div className="mx-auto w-full max-w-[176px]">+ <QrImage text={address} label="QR code for this kwant bots address" />+ </div>+ <div className="flex gap-2">+ <label className="sr-only" htmlFor="phone-app-address">+ kwant bots address+ </label>+ <input+ id="phone-app-address"+ readOnly+ value={address}+ onFocus={(e) => e.currentTarget.select()}+ className="flex-1 min-w-0 rounded-lg bg-zinc-950 border border-zinc-700 px-2.5 text-[11px] font-mono text-zinc-300"+ />+ <button type="button" onClick={p.onCopy} className={copyBtn}>+ {p.copied === 'yes' ? <Check size={14} aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}+ {p.copied === 'yes' ? 'Copied' : 'Copy link'}+ </button>+ </div>+ {p.copied === 'failed' && <p className="text-[11px] text-rose-300">Couldn’t copy. Select the link and copy it yourself.</p>}+ </div>+ ),+ };+ body = (+ <div className="space-y-4">+ <Steps items={[step1, homeScreenStep, notifyStep]} />+ <Ext href={PHONE_GUIDE_URL}>Step-by-step guide</Ext>+ </div>+ );+ }++ return (+ <section+ id={PHONE_APP_ANCHOR}+ aria-labelledby={PHONE_APP_TITLE}+ data-phone-app={p.kind}+ data-phone-layout={p.layout}+ className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-4 space-y-4 scroll-mt-4"+ >+ <div className="flex items-start gap-3">+ <div className="h-9 w-9 shrink-0 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center">+ <Smartphone size={18} className="text-sky-300" aria-hidden="true" />+ </div>+ <div className="min-w-0">+ <h4 id={PHONE_APP_TITLE} tabIndex={-1} className="text-sm font-semibold text-zinc-100 focus:outline-none">+ {phone ? 'Add kwant bots to your Home Screen' : 'Use kwant bots on your phone'}+ </h4>+ <p className="text-[11px] text-zinc-400 leading-relaxed mt-0.5">+ {phone+ ? 'No app store: it opens full screen from your Home Screen, like an app, and can notify you when a bot needs you.'+ : 'No app store: open it in your phone’s browser and add it to the Home Screen. It opens like an app and can notify you when a bot needs you.'}+ </p>+ </div>+ </div>+ {body}+ {!phone && p.installFooter && <div className="pt-3 border-t border-zinc-800">{p.installFooter}</div>}+ </section>+ );+};++/** Phones and tablets install themselves, so they get the phone layout. */+export function usesPhoneLayout(nav: Pick<Navigator, 'userAgent' | 'maxTouchPoints'>, narrow: boolean): boolean {+ return isIos(nav) || isAndroid(nav) || narrow;+}+/** "Mac" in the Mac app or a Mac browser; the Linux app and everything else is "computer". */+const machineName = (): 'Mac' | 'computer' => {+ if (inDesktopApp()) return desktopAppOs() === 'Mac' ? 'Mac' : 'computer';+ return isEmbeddedWebView(navigator) || (/Macintosh/.test(navigator.userAgent) && !isIos(navigator)) ? 'Mac' : 'computer';+};++/** The card, wired: reads this page's address, sign-in and install state. */+export const PhoneAppCard: React.FC<{ phone?: boolean }> = ({ phone: narrow = false }) => {+ const { authRequired, deviceLogin } = useAuth();+ const { prompt, installed } = useInstall();+ const desktopInstall = useDesktopInstallKind();+ const [copied, setCopied] = useState<'yes' | 'failed' | null>(null);+ // While this card is up, the floating InstallHint steps aside: the card already has its steps.+ useEffect(() => phoneCardShown(), []);+ if (typeof window === 'undefined') return null;++ const { hostname, protocol, host, origin } = window.location;+ const kind = phoneAppKind({ hostname, protocol, authRequired, deviceLogin });+ const layout = usesPhoneLayout(navigator, narrow) ? 'phone' : 'computer';+ // The installed app on a phone: nothing left to do here+ if (layout === 'phone' && (installed || isStandalone(window))) return null;++ const phoneCase: PhoneInstallCase = !window.isSecureContext ? 'insecure' : prompt ? 'prompt' : isIos(navigator) ? 'ios' : 'android';+ const copy = async () => {+ try {+ await navigator.clipboard.writeText(`${origin}/`);+ setCopied('yes');+ } catch {+ setCopied('failed');+ }+ };++ return (+ <PhoneAppCardView+ kind={kind}+ layout={layout}+ phoneCase={phoneCase}+ host={host}+ origin={origin}+ machine={machineName()}+ tokenSignIn={authRequired && !deviceLogin}+ signIn={kind === 'signin' ? <AddDevice variant="phone" onSignedIn={() => undefined} /> : null}+ installFooter={desktopInstall ? <InstallAppButton className={rowBtn} label="Install on this computer" /> : null}+ copied={copied}+ onCopy={copy}+ onInstall={() => void runInstallPrompt()}+ />+ );+};diff --git a/frontend/src/components/PhoneAppTip.tsx b/frontend/src/components/PhoneAppTip.tsxnew file mode 100644index 00000000..6f03c635--- /dev/null+++ b/frontend/src/components/PhoneAppTip.tsx@@ -0,0 +1,61 @@+import React, { useState } from 'react';+import { Smartphone, X } from 'lucide-react';+import { isAndroid, isIos } from '../pwa';+import { dismissPhoneTip, phoneTipDismissed } from '../nav';++// The desktop sidebar's way to "Use kwant bots on your phone" (PhoneAppCard, Settings › All spaces).+// Apart from the card so the sidebar doesn't load the card's sign-in pieces.++export const PHONE_APP_ANCHOR = 'phone-app';+export const PHONE_APP_TITLE = 'phone-app-title';++/** Scrolls Settings › All spaces to the card and focuses its title. Settings may still be mounting,+ * so it tries again for a moment. */+export function focusPhoneApp(doc: Document = document, tries = 40): void {+ const el = doc.getElementById(PHONE_APP_ANCHOR);+ if (!el) {+ if (tries > 0) setTimeout(() => focusPhoneApp(doc, tries - 1), 50);+ return;+ }+ const reduce = doc.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;+ el.scrollIntoView?.({ block: 'start', behavior: reduce ? 'auto' : 'smooth' });+ doc.getElementById(PHONE_APP_TITLE)?.focus({ preventScroll: true });+}++/** The desktop sidebar's one-time tip. Clicking it opens the card and counts as seen. */+export const PhoneAppTip: React.FC<{ className: string; onOpen: () => void }> = ({ className, onOpen }) => {+ const [dismissed, setDismissed] = useState(() => phoneTipDismissed());+ if (dismissed) return null;+ if (typeof navigator !== 'undefined' && (isIos(navigator) || isAndroid(navigator))) return null;+ const hide = () => {+ dismissPhoneTip();+ setDismissed(true);+ };+ return (+ <div className="hidden md:block rounded-lg border border-zinc-800 bg-zinc-900/60" data-phone-tip>+ <div className="flex items-center">+ <button+ type="button"+ onClick={() => {+ hide();+ onOpen();+ }}+ className={className}+ >+ <Smartphone size={15} className="shrink-0 text-sky-400" aria-hidden="true" />+ {/* Wraps instead of truncating: the sidebar is ~240 px, and "on your phone" is the point of the tip. */}+ <span className="flex-1 min-w-0 leading-snug">Tip: use kwant bots on your phone</span>+ </button>+ <button+ type="button"+ onClick={hide}+ aria-label="Dismiss the phone tip"+ title="Dismiss. Find it any time in Settings › All spaces."+ className="shrink-0 mr-1 p-1 rounded text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <X size={12} aria-hidden="true" />+ </button>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 416d47b7..83d7e94c 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -14,7 +14,7 @@ import { ApprovalsOffBadge } from './ApprovalsSetting';import { approvalsOff } from '../approvalMode';import { teamChannelOf } from '../teamChannel';import { layaRoutes } from '../channels';-import { InstallAppButton } from './InstallAppButton';+import { PhoneAppTip } from './PhoneAppTip';import { trapFocusTarget } from '../imports';import { type AttentionRow, type NeedsYouRow, PINNED_RANK, NEEDS_YOU_LABEL, workingIds, directIds, rollupLabel } from '../chatsTab';import type { InboxItem } from '../api/inbox';@@ -103,6 +103,8 @@ export interface SidebarProps {onSwitchSpace: (id: string) => void;onCreateSpace: () => void;onOpenSpaceSettings: () => void;+ /** The phone tip: Settings › All spaces, at "Use kwant bots on your phone". */+ onOpenPhoneApp?: () => void;onOpenArchived: () => void;onOpenSearch: () => void;/** Phones show one tab at a time, full width. */@@ -288,6 +290,7 @@ export const Sidebar: React.FC<SidebarProps> = ({onSwitchSpace,onCreateSpace,onOpenSpaceSettings,+ onOpenPhoneApp,onOpenArchived,onOpenSearch,section = 'all',@@ -1108,8 +1111,8 @@ export const Sidebar: React.FC<SidebarProps> = ({</div>)}- {/* Desktop: a one-time tip; Settings › All spaces keeps "Install app" for later */}- {section === 'all' && <InstallAppButton tip className={navRow(false)} />}+ {/* Desktop: a one-time tip; Settings › All spaces keeps "Use kwant bots on your phone" for later */}+ {section === 'all' && onOpenPhoneApp && <PhoneAppTip className={navRow(false)} onOpen={onOpenPhoneApp} />}</div>{/* Footer: what this space's bots run on, from the real checks */}diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex 9b5452cd..5212a67c 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -41,7 +41,7 @@ import { SpaceDocsTab } from './SpaceDocsTab';import type { AppsSection, SettingsScope, SpaceSettingsTab } from '../nav';import { AppsAccounts } from './AppsAccounts';-import { InstallAppButton } from './InstallAppButton';+import { PhoneAppCard } from './PhoneAppCard';import { editorProps, useEscapeLayer } from '../escape';import { devTeamRefs } from '../devMode';@@ -228,6 +228,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {</div>{scope === 'app' ? (<>+ <PhoneAppCard phone={p.isPhone} /><div className={`${card} p-4 space-y-3`} data-all-spaces-spaces><p className="text-xs font-medium text-zinc-200">Spaces</p><p className="text-[11px] text-zinc-500">Switch spaces on the left rail (Ctrl or ⌘ with 1–9). Archived spaces keep their bots and chats until you restore them.</p>@@ -235,7 +236,6 @@ export const SpaceSettings: React.FC<Props> = (p) => {<button type="button" onClick={p.onOpenArchived} className={rowBtn}><Archive size={13} /> Archived spaces</button>- <InstallAppButton className={rowBtn} /></div></div>{p.appSettings}diff --git a/frontend/src/nav.ts b/frontend/src/nav.tsindex 08b0d811..83a9d7fb 100644--- a/frontend/src/nav.ts+++ b/frontend/src/nav.ts@@ -105,19 +105,20 @@ export function viewAfterSpaceSwitch(view: SpaceView | null | undefined): SpaceVreturn view?.kind === 'settings' ? view : null;}-const INSTALL_TIP_KEY = 'kwnt.installTip.dismissed';+const PHONE_TIP_KEY = 'kwnt.phoneTip.dismissed';-/** The desktop "Install app" tip shows until it is dismissed or the app is installed. */-export function installTipDismissed(): boolean {+/** The desktop sidebar's one-time "Tip: use kwant bots on your phone" shows until it is dismissed+ * or clicked. A new key on purpose: people who dismissed the old install tip see this once. */+export function phoneTipDismissed(): boolean {try {- return localStorage.getItem(INSTALL_TIP_KEY) === '1';+ return localStorage.getItem(PHONE_TIP_KEY) === '1';} catch {return false;}}-export function dismissInstallTip() {+export function dismissPhoneTip() {try {- localStorage.setItem(INSTALL_TIP_KEY, '1');+ localStorage.setItem(PHONE_TIP_KEY, '1');} catch {// private mode: it comes back next load}diff --git a/frontend/src/pwa.ts b/frontend/src/pwa.tsindex 757dfab5..e6538f7e 100644--- a/frontend/src/pwa.ts+++ b/frontend/src/pwa.ts@@ -23,10 +23,49 @@ export function isIos(nav: Pick<Navigator, 'userAgent' | 'maxTouchPoints'>): booreturn /iPhone|iPad|iPod/.test(nav.userAgent) || (/Macintosh/.test(nav.userAgent) && nav.maxTouchPoints > 1);}+/** Android phones and tablets, where installing is the browser menu's Add to Home screen or Install app. */+export function isAndroid(nav: Pick<Navigator, 'userAgent'>): boolean {+ return /Android/.test(nav.userAgent);+}++/** 127.0.0.1, localhost, *.localhost, ::1, 0.0.0.0: addresses only this computer can open (the Mac+ * app's This Mac, local dev). A phone scanning a QR of one would open itself. Also `localhost.`+ * (a trailing dot is still this computer) and IPv4-mapped loopback: URL turns+ * `[::ffff:127.0.0.1]` into the hostname `[::ffff:7f00:1]`, so both spellings count. */+export function isLoopbackHost(hostname: string): boolean {+ const h = hostname.replace(/^\[|\]$/g, '').toLowerCase().replace(/\.$/, '');+ return (+ h === 'localhost' ||+ h.endsWith('.localhost') ||+ h === '::1' ||+ h === '0.0.0.0' ||+ /^127\.\d+\.\d+\.\d+$/.test(h) ||+ /^::ffff:(127\.\d+\.\d+\.\d+|7f[0-9a-f]{2}:[0-9a-f]{1,4})$/.test(h)+ );+}++/** What "Use kwant bots on your phone" offers on a computer: a one-time sign-in QR (`signin`), a QR of+ * this address (`address`), why a phone can't reach this computer (`loopback`), or why a phone+ * can't install from plain http (`insecure`). Loopback is checked first: http://127.0.0.1 is not+ * "insecure", it's unreachable. */+export type PhoneAppKind = 'signin' | 'address' | 'loopback' | 'insecure';++export function phoneAppKind(s: { hostname: string; protocol: string; authRequired: boolean; deviceLogin: boolean }): PhoneAppKind {+ if (isLoopbackHost(s.hostname)) return 'loopback';+ if (s.protocol !== 'https:') return 'insecure';+ return s.authRequired && s.deviceLogin ? 'signin' : 'address';+}++/** The kwant.si how-to the card links to, and the https proxy section. */+export const PHONE_GUIDE_URL = 'https://kwant.si/docs/phone.html';+export const TELEGRAM_GUIDE_URL = 'https://kwant.si/docs/telegram.html';+export const HTTPS_GUIDE_URL = 'https://kwant.si/docs/install.html#proxy';+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. */+ * steps (iOS), or none: already installed, dismissed, not a phone, not served over HTTPS, or the+ * "Use kwant bots on your phone" card is on screen and already shows the same steps. */export function installHintKind(s: {standalone: boolean;dismissed: boolean;@@ -34,14 +73,43 @@ export function installHintKind(s: {secure: boolean;ios: boolean;canPrompt: boolean;+ phoneCardOnScreen?: boolean;}): InstallHintKind {- if (s.standalone || s.dismissed || !s.phone || !s.secure) return null;+ if (s.standalone || s.dismissed || !s.phone || !s.secure || s.phoneCardOnScreen) return null;if (s.canPrompt) return 'prompt';return s.ios ? 'ios' : null;}export const INSTALL_HINT_DISMISSED_KEY = 'kwnt.installHint.dismissed';+// Whether a PhoneAppCard is mounted (Settings › All spaces), so the floating InstallHint can step+// aside instead of repeating its steps. A count, so two cards (or a remount) can't clear it early.+let phoneCards = 0;+const phoneCardListeners = new Set<() => void>();+const notifyPhoneCard = () => phoneCardListeners.forEach((fn) => fn());++/** Call when a PhoneAppCard mounts; returns the unmount cleanup. */+export function phoneCardShown(): () => void {+ phoneCards += 1;+ notifyPhoneCard();+ let done = false;+ return () => {+ if (done) return;+ done = true;+ phoneCards -= 1;+ notifyPhoneCard();+ };+}++export const isPhoneCardOnScreen = (): boolean => phoneCards > 0;++export function subscribePhoneCard(fn: () => void): () => void {+ phoneCardListeners.add(fn);+ return () => {+ phoneCardListeners.delete(fn);+ };+}+/** The Mac app's .dmg in the newest release (published by the mac workflow on a mac-v* tag). */export const MAC_DOWNLOAD_URL = 'https://github.com/alexsergivan/kwant/releases/latest/download/kwant_universal.dmg';diff --git a/frontend/tests/addPhone.test.mjs b/frontend/tests/addPhone.test.mjsindex f2cacdb4..35a7b4e4 100644--- a/frontend/tests/addPhone.test.mjs+++ b/frontend/tests/addPhone.test.mjs@@ -88,9 +88,10 @@ test('expired: the code and QR are gone; New code and Hide remain', () => {assert.deepEqual(buttons(html), ['New code', 'Hide']);});-test('signed in: "Signed in ✓" with the browser, no QR, and Add another', () => {+test('signed in: one tick (the icon), "Signed in" with the browser, no QR, and Add another', () => {const html = m.view({ kind: 'signed_in', browser: 'Safari on iPhone' }, NOW);- assert.match(text(html), /Signed in ✓ Safari on iPhone signed in with the code/);+ assert.match(text(html), /Signed in Safari on iPhone signed in with the code/);+ assert.ok(!html.includes('✓'), 'no text tick next to the Check icon');assert.ok(!html.includes('kwnt_token'));assert.deepEqual(buttons(html), ['Add another', 'Done']);});@@ -101,7 +102,7 @@ test('a failed mint says so and keeps the button', () => {assert.deepEqual(buttons(html), ['Add a phone or browser']);});-// ---------------------------------------------------------------- "Signed in ✓" detection+// ---------------------------------------------------------------- "Signed in" detectiontest('only a new link session counts as the phone that scanned', () => {const s = (id, via, current = false) => ({ id, via, current, browser: id, ip: '', created_at: '', last_seen: '' });diff --git a/frontend/tests/ia.test.mjs b/frontend/tests/ia.test.mjsindex 2e1d9c72..e6ad1511 100644--- a/frontend/tests/ia.test.mjs+++ b/frontend/tests/ia.test.mjs@@ -129,14 +129,18 @@ test('the Inbox row keeps the unseen badge and marks the open page', () => {assert.match(ui.sidebar({ ...base, inboxActive: true }), /aria-current="page"[^>]*>(?:(?!<\/button>)[\s\S])*>Inbox</);});-test('Install is a tip that can be dismissed, and stays in Settings › All spaces', () => {- const tip = src('components/InstallAppButton.tsx');- assert.match(tip, /dismissInstallTip\(\)/);- assert.match(tip, /Install any time from Settings › All spaces/);- assert.match(src('components/SpaceSettings.tsx'), /<InstallAppButton/);- assert.equal(nav.installTipDismissed(), false);- nav.dismissInstallTip();- assert.equal(nav.installTipDismissed(), true);+test('the sidebar tip points to the phone card, can be dismissed, and Install moved into that card', () => {+ const card = src('components/PhoneAppCard.tsx') + src('components/PhoneAppTip.tsx');+ assert.match(card, /Tip: use kwant bots on your phone/);+ assert.match(card, /dismissPhoneTip\(\)/);+ assert.match(card, /Find it any time in Settings › All spaces/);+ assert.match(card, /<InstallAppButton className=\{rowBtn\} label="Install on this computer"/);+ assert.match(src('components/Sidebar.tsx'), /<PhoneAppTip /);+ assert.doesNotMatch(src('components/Sidebar.tsx'), /<InstallAppButton/);+ assert.match(src('components/SpaceSettings.tsx'), /<PhoneAppCard /);+ assert.equal(nav.phoneTipDismissed(), false);+ nav.dismissPhoneTip();+ assert.equal(nav.phoneTipDismissed(), true);});// ---------------------------------------------------------------------------diff --git a/frontend/tests/installHintCard.test.mjs b/frontend/tests/installHintCard.test.mjsnew file mode 100644index 00000000..00c54600--- /dev/null+++ b/frontend/tests/installHintCard.test.mjs@@ -0,0 +1,86 @@+// 20h round 2 (Rigel's QA on #691): on an iPhone the floating InstallHint ("Install kwant bots on your+// phone") sat over the PhoneAppCard in Settings › All spaces, which already shows the same steps.+// The hint steps aside while the card is mounted and comes back when it goes; its dismissal is unchanged.+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1';+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'https://kwant.example/settings', pretendToBeVisual: true });+Object.defineProperty(dom.window.navigator, 'userAgent', { value: IPHONE, configurable: true });+Object.defineProperty(dom.window.navigator, 'maxTouchPoints', { value: 5, configurable: true });+Object.defineProperty(dom.window, 'isSecureContext', { value: true, configurable: true });+dom.window.matchMedia = (q) => ({ matches: /max-width: 767px/.test(q), media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'matchMedia']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.IS_REACT_ACT_ENVIRONMENT = false;+g.fetch = g.window.fetch = async () => new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } });++const m = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export { InstallHint } from './src/components/InstallHint';+ export { PhoneAppCard } from './src/components/PhoneAppCard';+ export * from './src/pwa';+`);+const { React, createRoot } = m;+const h = React.createElement;+const settle = async (n = 10) => {+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));+};+const hint = () => document.querySelector('[data-install-hint]');++test('installHintKind: nothing while the phone card is on screen', () => {+ const base = { standalone: false, dismissed: false, phone: true, secure: true, ios: true, canPrompt: false };+ assert.equal(m.installHintKind(base), 'ios');+ assert.equal(m.installHintKind({ ...base, phoneCardOnScreen: true }), null);+ assert.equal(m.installHintKind({ ...base, ios: false, canPrompt: true, phoneCardOnScreen: true }), null, 'Android too');+ assert.equal(m.installHintKind({ ...base, phoneCardOnScreen: false }), 'ios');+});++test('phoneCardShown counts cards: the second unmount clears it, and cleanup twice is harmless', () => {+ let calls = 0;+ const unsub = m.subscribePhoneCard(() => calls++);+ assert.equal(m.isPhoneCardOnScreen(), false);+ const a = m.phoneCardShown();+ const b = m.phoneCardShown();+ a();+ a();+ assert.equal(m.isPhoneCardOnScreen(), true, 'one card still up');+ b();+ assert.equal(m.isPhoneCardOnScreen(), false);+ assert.equal(calls, 4);+ unsub();+});++test('iPhone: the hint shows elsewhere, steps aside while PhoneAppCard is mounted, and comes back after', async () => {+ localStorage.clear();+ const hintHost = document.createElement('div');+ const cardHost = document.createElement('div');+ document.body.append(hintHost, cardHost);+ const hintRoot = createRoot(hintHost);+ hintRoot.render(h(m.InstallHint));+ await settle();+ assert.equal(hint()?.getAttribute('data-install-hint'), 'ios', 'Share steps on any other screen');++ const cardRoot = createRoot(cardHost);+ cardRoot.render(h(m.PhoneAppCard, { phone: true }));+ await settle();+ assert.match(cardHost.textContent, /Add to Home Screen/, 'the card rendered, with the same iPhone steps');+ assert.equal(hint(), null, 'no second copy of the steps over the card');++ cardRoot.unmount();+ await settle();+ assert.equal(hint()?.getAttribute('data-install-hint'), 'ios', 'back once the card is gone');++ // Dismissal is unchanged: the X still hides it for good.+ hint().querySelector('button[aria-label]')?.click();+ await settle();+ assert.equal(localStorage.getItem(m.INSTALL_HINT_DISMISSED_KEY), '1');+ assert.equal(hint(), null);+ hintRoot.unmount();+});diff --git a/frontend/tests/phoneApp.test.mjs b/frontend/tests/phoneApp.test.mjsnew file mode 100644index 00000000..c1bed50b--- /dev/null+++ b/frontend/tests/phoneApp.test.mjs@@ -0,0 +1,197 @@+// 20h: "Use kwant bots on your phone" in Settings › All spaces. Which state this address gets+// (one-time sign-in QR, address QR, loopback, plain http), what each says, and that a loopback or+// plain-http address never gets a QR.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const m = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { PhoneAppCardView, usesPhoneLayout } from './src/components/PhoneAppCard';+ import { AddDeviceView } from './src/components/DeviceSignIn';+ export * from './src/pwa';+ export { usesPhoneLayout };+ const noop = () => {};+ export const card = (props) => renderToStaticMarkup(React.createElement(PhoneAppCardView, props));+ // The wired card passes AddDevice and InstallAppButton; here the views stand in for them.+ export const cardWith = (props, addState) =>+ renderToStaticMarkup(React.createElement(PhoneAppCardView, {+ ...props,+ signIn: addState ? React.createElement(AddDeviceView, { state: addState, variant: 'phone', now: 0, onShow: noop, onHide: noop, onCopy: noop }) : null,+ installFooter: React.createElement('button', { type: 'button' }, 'Install on this computer'),+ }));+ export const addDevice = (state, variant) =>+ renderToStaticMarkup(React.createElement(AddDeviceView, { state, variant, now: 0, onShow: noop, onHide: noop, onCopy: noop }));+`);++const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/'|'|’/g, "'").replace(/&/g, '&').replace(/\s+/g, ' ').replace(/ ([,.])/g, '$1');+const kind = (hostname, protocol = 'https:', authRequired = false, deviceLogin = false) => m.phoneAppKind({ hostname, protocol, authRequired, deviceLogin });++// ---------------------------------------------------------------- the origin helper++test('loopback: 127.x, localhost, *.localhost, ::1 and 0.0.0.0 are only this computer', () => {+ for (const h of ['127.0.0.1', '127.1.2.3', 'localhost', 'LOCALHOST', 'kwant.localhost', '::1', '[::1]', '0.0.0.0']) assert.ok(m.isLoopbackHost(h), h);+ for (const h of ['192.168.1.20', '10.0.0.2', 'kwant.jumpin.games', 'localhost.example.com', '128.0.0.1', '127.0.0', 'mylocalhost', '::2'])+ assert.ok(!m.isLoopbackHost(h), h);+});++test('phoneAppKind: loopback first, then plain http, then sign-in or the address', () => {+ assert.equal(kind('127.0.0.1', 'http:'), 'loopback', 'the Mac app This Mac');+ assert.equal(kind('localhost', 'https:', true, true), 'loopback', 'loopback even over https with sign-in');+ assert.equal(kind('[::1]', 'http:'), 'loopback');+ assert.equal(kind('192.168.1.20', 'http:'), 'insecure');+ assert.equal(kind('kwant.example.com', 'http:', true, true), 'insecure', 'sign-in does not rescue plain http');+ assert.equal(kind('kwant.example.com', 'https:', true, true), 'signin');+ assert.equal(kind('kwant.example.com', 'https:', false, false), 'address');+ assert.equal(kind('kwant.example.com', 'https:', true, false), 'address', 'token sign-in without device login');+ assert.equal(kind('kwant.example.com', 'https:', false, true), 'address');+});++test('phones and tablets use the phone layout; a desktop UA only when narrow', () => {+ const ua = (userAgent, maxTouchPoints = 0) => ({ userAgent, maxTouchPoints });+ assert.ok(m.usesPhoneLayout(ua('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)', 5), false));+ assert.ok(m.usesPhoneLayout(ua('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Safari', 5), false), 'iPadOS says Mac');+ assert.ok(m.usesPhoneLayout(ua('Mozilla/5.0 (Linux; Android 15; SM-X710) Chrome/154'), false), 'Android tablet');+ assert.ok(!m.usesPhoneLayout(ua('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/154'), false));+ assert.ok(m.usesPhoneLayout(ua('Mozilla/5.0 (Windows NT 10.0) Chrome/154'), true));+});++// ---------------------------------------------------------------- the card on a computer++const showing = { kind: 'showing', link: { url: 'https://kwant.example/#kwnt_token=kl1.secret', expiresAt: 15 * 60_000 } };+const base = { layout: 'computer', host: 'kwant.example.com', origin: 'https://kwant.example.com', machine: 'computer' };+const qrs = (html) => (html.match(/role="img"/g) ?? []).length;++test('address: a QR of this address at once, Copy link, the three steps and the guide', () => {+ const html = m.card({ ...base, kind: 'address' });+ const t = text(html);+ assert.match(html, /id="phone-app"/);+ assert.match(html, /data-phone-app="address"/);+ assert.match(t, /Use kwant bots on your phone/);+ assert.match(t, /It opens kwant bots at kwant\.example\.com on the phone\./);+ assert.equal(qrs(html), 1);+ assert.match(html, /aria-label="QR code for this kwant bots address"/);+ assert.match(html, /value="https:\/\/kwant\.example\.com\/"/);+ assert.match(t, /Copy link/);+ assert.match(t, /Add it to the Home Screen/);+ assert.match(t, /iPhone or iPad: in Safari, tap Share › Add to Home Screen\./);+ assert.match(t, /Android: in Chrome, tap › Add to Home screen \(or Install app\)\./);+ assert.match(t, /Turn on notifications/);+ assert.match(t, /Settings › All spaces › Notifications › Notify me on this device/);+ assert.match(html, /href="https:\/\/kwant\.si\/docs\/phone\.html"[^>]*target="_blank"[^>]*rel="noopener noreferrer"/);+ assert.doesNotMatch(t, /Works once|Anyone who scans/, 'the address is not a secret');+ assert.doesNotMatch(t, /access token/);+});++test('address with a token sign-in says to sign in with the access token there', () => {+ assert.match(text(m.card({ ...base, kind: 'address', tokenSignIn: true })), /Sign in there with your access token\./);+});++test('copy: Copied, or the copy-it-yourself line', () => {+ assert.match(text(m.card({ ...base, kind: 'address', copied: 'yes' })), /Copied/);+ assert.match(text(m.card({ ...base, kind: 'address', copied: 'failed' })), /Couldn't copy\. Select the link and copy it yourself\./);+});++test('signin: step 1 is the AddDevice slot, never an address QR', () => {+ const html = m.cardWith({ ...base, kind: 'signin' }, { kind: 'idle' });+ const t = text(html);+ assert.match(t, /It opens kwant bots on the phone and signs it in once\./);+ assert.match(t, /Show QR code/);+ assert.equal(qrs(html), 0, 'no QR until Show QR code mints a link');+ assert.doesNotMatch(html, /data-phone-qr/);+ const shown = m.cardWith({ ...base, kind: 'signin' }, showing);+ assert.equal(qrs(shown), 1, 'one QR: the one-time link, which opens and signs in');+ assert.match(shown, /kwnt_token=kl1\.secret/);+ assert.doesNotMatch(shown, /value="https:\/\/kwant\.example\.com\/"/, 'not the bare address too');+});++test('loopback: no QR anywhere, says this Mac, links to the guide and Telegram', () => {+ const html = m.card({ ...base, kind: 'loopback', host: '127.0.0.1:8799', origin: 'http://127.0.0.1:8799', machine: 'Mac' });+ const t = text(html);+ assert.equal(qrs(html), 0);+ assert.doesNotMatch(html, /127\.0\.0\.1:8799\/"/, 'no address field to copy');+ assert.match(t, /Your phone can't reach this one\. kwant bots runs at 127\.0\.0\.1:8799, an address only this Mac can open\./);+ assert.match(t, /To have it on your phone:/);+ assert.match(html, /href="https:\/\/kwant\.si\/docs\/phone\.html"/);+ assert.match(t, /How to set it up/);+ assert.match(html, /href="https:\/\/kwant\.si\/docs\/telegram\.html"/);+ assert.match(t, /Set up Telegram/);+ assert.match(text(m.card({ ...base, kind: 'loopback', host: 'localhost:5173', machine: 'computer' })), /only this computer can open/);+});++test('insecure: phones need https, the proxy link, no QR', () => {+ const html = m.card({ ...base, kind: 'insecure', host: '192.168.1.20:8799', origin: 'http://192.168.1.20:8799' });+ const t = text(html);+ assert.equal(qrs(html), 0);+ assert.match(t, /Phones only install apps from an https address\. This one is http:\/\/192\.168\.1\.20:8799, so a phone can open it but can't add it/);+ assert.match(html, /href="https:\/\/kwant\.si\/docs\/install\.html#proxy"/);+});++test('the install footer shows only when given, and never on the phone layout', () => {+ assert.doesNotMatch(text(m.card({ ...base, kind: 'address' })), /Install on this computer/);+ for (const kind of ['address', 'signin', 'loopback', 'insecure']) assert.match(text(m.cardWith({ ...base, kind })), /Install on this computer/, kind);+ assert.doesNotMatch(text(m.cardWith({ ...base, layout: 'phone', kind: 'address', phoneCase: 'ios' })), /Install on this computer/);+});++// ---------------------------------------------------------------- the card on a phone++const phone = { ...base, layout: 'phone' };++test('phone: installs this phone, never a QR', () => {+ for (const phoneCase of ['prompt', 'ios', 'android', 'insecure']) {+ const html = m.card({ ...phone, kind: 'signin', phoneCase });+ assert.equal(qrs(html), 0, phoneCase);+ assert.match(text(html), /Add kwant bots to your Home Screen/, phoneCase);+ }+});++test('phone: Install button, iPhone Share steps, Android menu steps, or https first', () => {+ const prompt = text(m.card({ ...phone, kind: 'address', phoneCase: 'prompt' }));+ assert.match(prompt, /Install/);+ assert.match(prompt, /Then open it from your Home Screen and turn on Notify me on this device, under Notifications below\./);+ const ios = text(m.card({ ...phone, kind: 'address', phoneCase: 'ios' }));+ assert.match(ios, /Tap Share/);+ assert.match(ios, /In Safari it's at the bottom of the screen; on iPad, at the top\./);+ assert.match(ios, /Add to Home Screen, then Add/);+ assert.match(ios, /No Add to Home Screen\? Open this page in Safari\./);+ const android = text(m.card({ ...phone, kind: 'address', phoneCase: 'android' }));+ assert.match(android, /in the browser's menu/);+ assert.match(android, /Tap Add to Home screen \(or Install app\)/);+ const http = text(m.card({ ...phone, kind: 'insecure', origin: 'http://192.168.1.20:8799', phoneCase: 'insecure' }));+ assert.match(http, /Phones only install apps from an https address\. This one is http:\/\/192\.168\.1\.20:8799\./);+ assert.doesNotMatch(http, /Tap /);+});++// ---------------------------------------------------------------- AddDevice+++test('Add a phone or browser now says to add it to the Home Screen under the QR', () => {+ assert.match(text(m.addDevice(showing, 'settings')), /On a phone, then add it to the Home Screen: Share › Add to Home Screen on iPhone, ⋮ › Add to Home screen on Android\./);+ assert.doesNotMatch(text(m.addDevice(showing, 'phone')), /On a phone, then add it/, 'the phone card has step 2 for that');+});++test('the phone variant: Show QR code as the primary button, and the next step once signed in', () => {+ const idle = m.addDevice({ kind: 'idle' }, 'phone');+ assert.match(text(idle), /Show QR code/);+ assert.match(idle, /bg-sky-600/);+ assert.match(text(m.addDevice({ kind: 'idle' }, 'settings')), /Add a phone or browser/);+ assert.match(text(m.addDevice({ kind: 'signed_in', browser: 'Safari on iPhone' }, 'phone')), /Next, on the phone: add it to the Home Screen \(step 2\)\./);+ assert.doesNotMatch(text(m.addDevice({ kind: 'signed_in', browser: 'x' }, 'settings')), /Next, on the phone/);+ assert.match(m.addDevice(showing, 'phone'), /id="add-device-link-phone"/);+ assert.match(m.addDevice(showing, 'settings'), /id="add-device-link-settings"/, 'two AddDevice on one page get their own ids');+});++test('loopback edge hosts: localhost. and IPv4-mapped loopback, as URL spells them', () => {+ for (const u of ['http://localhost./', 'http://LOCALHOST.:9465/', 'http://kwant.localhost./', 'http://[::ffff:127.0.0.1]/', 'http://[::ffff:127.1.2.3]:9465/']) {+ const { hostname, protocol } = new URL(u);+ assert.ok(m.isLoopbackHost(hostname), `${u} → ${hostname}`);+ assert.equal(kind(hostname, protocol), 'loopback', u);+ }+ assert.equal(new URL('http://[::ffff:127.0.0.1]/').hostname, '[::ffff:7f00:1]', 'URL normalises the mapped form to hex');+ for (const h of ['::ffff:127.0.0.1', '[::ffff:7f00:1]']) assert.ok(m.isLoopbackHost(h), h);+ for (const u of ['http://[::ffff:192.168.1.20]/', 'http://[::ffff:10.0.0.2]/', 'https://kwant.example./']) {+ const { hostname } = new URL(u);+ assert.ok(!m.isLoopbackHost(hostname), `${u} → ${hostname}`);+ }+});