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
Mobile 0.6.13 slice A: room to read on phones (A1, A2, A4–A7) (#307)
Oleksandr Ivanchenko4f852721431c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 64701ba5..d02cc290 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -10,7 +10,8 @@ import { FirstRunWelcome } from './components/FirstRunWelcome';import { SpaceTile } from './components/Spaces';import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState, SendOptions } from './components/ChatView';import { ReactResult, Reaction, optimisticReplyRef, reactionOf, saveReaction, senderLabel } from './reactReply';-import { ThreadBar, ThreadHeader } from './components/ThreadBar';+import { PhoneTabBar } from './components/PhoneTabBar';+import { ThreadBar, ThreadHeader, ThreadPicker, type ThreadBarProps } from './components/ThreadBar';import { DelegationCard } from './components/DelegationCard';import { ApprovalsOffBadge } from './components/ApprovalsSetting';import { APPROVALS_CHANGED_EVENT, approvalsOff } from './approvalMode';@@ -112,7 +113,7 @@ import {questionsApi,turnsAwaitingAnswer,} from './questions';-import { AwayItem, affectsAway, awayApi, awayTarget, badgeText } from './away';+import { AwayItem, affectsAway, awayApi, awayTarget } from './away';import { Space, eventsUrl, pickInitialChat } from './spaces';import { canRunNow } from './engines';import { useEngines } from './useEngines';@@ -2866,23 +2867,27 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({</button></div>) : null;+ const threadBarProps: ThreadBarProps | null = currentKwant+ ? {+ kwantName: currentKwant.name,+ threads: agentThreads,+ error: threadErrors[currentKwant.id] ?? null,+ openThreadId,+ turns,+ awaiting: awaitingTurns,+ directBadge: threadBadge({ id: currentKwant.id, delegation: null }, turns, awaitingTurns),+ showArchived,+ onToggleArchived: () => setShowArchived((v) => !v),+ onOpenDirect: openDirectChat,+ onOpenThread: (t) => openThread(t.kwant_id, t.id),+ onNewThread: handleNewThread,+ onRetry: () => loadThreads(currentKwant.id),+ }+ : null;+ // Phone: the conversations live in the header's second line (ThreadPicker), not in a bar of their ownconst subHeader = currentKwant ? (<>- <ThreadBar- kwantName={currentKwant.name}- threads={agentThreads}- error={threadErrors[currentKwant.id] ?? null}- openThreadId={openThreadId}- turns={turns}- awaiting={awaitingTurns}- directBadge={threadBadge({ id: currentKwant.id, delegation: null }, turns, awaitingTurns)}- showArchived={showArchived}- onToggleArchived={() => setShowArchived((v) => !v)}- onOpenDirect={openDirectChat}- onOpenThread={(t) => openThread(t.kwant_id, t.id)}- onNewThread={handleNewThread}- onRetry={() => loadThreads(currentKwant.id)}- />+ {!isPhone && threadBarProps && <ThreadBar {...threadBarProps} />}{shownThread && (<ThreadHeaderthread={shownThread}@@ -3207,6 +3212,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({highlightMessageId={highlightMessageId}onHighlightDone={() => setHighlightMessageId(null)}subHeader={subHeader}+ threadLine={isPhone && threadBarProps ? <ThreadPicker {...threadBarProps} /> : undefined}notice={setupBanner}welcome={setupBanner && isChannel ? (@@ -3288,15 +3294,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({) : chat;const phoneTabs: Array<{ id: PhoneTab; label: string; icon: React.ReactNode; badge?: number }> = [- { id: 'chats', label: 'Chats', icon: <MessageSquare size={18} /> },- { id: 'bots', label: 'Bots', icon: <Bot size={18} /> },- { id: 'inbox', label: 'Inbox', icon: <Inbox size={18} />, badge: awayCount },- { id: 'space', label: 'Space', icon: <Settings size={18} /> },+ { id: 'chats', label: 'Chats', icon: <MessageSquare size={20} aria-hidden="true" /> },+ { id: 'bots', label: 'Bots', icon: <Bot size={20} aria-hidden="true" /> },+ { id: 'inbox', label: 'Inbox', icon: <Inbox size={20} aria-hidden="true" />, badge: awayCount },+ { id: 'space', label: 'Space', icon: <Settings size={20} aria-hidden="true" /> },];const showPhoneList = isPhone && phoneView === 'list' && !needsSetup;return (- <div className="relative flex-1 min-w-0 h-full flex flex-col bg-surface-main text-zinc-100 overflow-hidden" data-space={space.id}>+ // overflow: clip, not just hidden: a hidden box can still be scrolled from script (scrollIntoView), which+ // once slid the whole chat under its header (P1-7). Browsers without clip keep hidden.+ <div className="relative flex-1 min-w-0 h-full flex flex-col bg-surface-main text-zinc-100 overflow-hidden [overflow:clip]" data-space={space.id}><div ref={contentRef} className={`flex-1 min-h-0 flex ${isPhone ? 'flex-col' : 'overflow-hidden'}`}>{isPhone ? (<>@@ -3315,42 +3323,24 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({<div className="flex-1 min-h-0 flex">{mainPane}</div>)}{(showPhoneList || needsSetup) && (- <nav aria-label={`${space.name} sections`} className="shrink-0 grid grid-cols-4 border-t border-zinc-800 bg-zinc-900/95 pb-[env(safe-area-inset-bottom)]">- {phoneTabs.map((t) => {- const active = t.id === phoneTab;- return (- <button- key={t.id}- type="button"- aria-current={active ? 'page' : undefined}- onClick={() => {- playSfx('click');- if (t.id === 'inbox') {- showPage('inbox');- return;- }- if (t.id === 'space') {- // Nothing can run yet: the fix is in Accounts, so start there- openSpaceSettings(canRun === false ? 'accounts' : 'general');- return;- }- setPhoneTab(t.id);- }}- className={`relative flex flex-col items-center gap-0.5 py-2 text-[11px] font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500 ${- active ? 'text-sky-300' : 'text-zinc-400 hover:text-zinc-200'- }`}- >- {t.icon}- {t.label}- {!!t.badge && (- <span className="absolute top-1 left-1/2 ml-2 min-w-[16px] px-1 rounded-full bg-amber-500 text-zinc-950 text-[9px] font-semibold text-center">- {badgeText(t.badge)}- </span>- )}- </button>- );- })}- </nav>+ <PhoneTabBar+ label={`${space.name} sections`}+ tabs={phoneTabs}+ active={phoneTab}+ onSelect={(id) => {+ playSfx('click');+ if (id === 'inbox') {+ showPage('inbox');+ return;+ }+ if (id === 'space') {+ // Nothing can run yet: the fix is in Accounts, so start there+ openSpaceSettings(canRun === false ? 'accounts' : 'general');+ return;+ }+ setPhoneTab(id);+ }}+ />)}</>) : (diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 7bd1ccc6..01a092e2 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1,10 +1,13 @@-import React, { useState, useRef, useEffect, useMemo } from 'react';+import React, { useState, useRef, useEffect, useLayoutEffect, useMemo } from 'react';import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { BotHome } from './BotHome';import { ChatHome, answerTarget, goodAt, recipientsOf } from '../botHome';import { moodNoticed } from '../kwantMood';import { NewTag } from './NewTag';+import { PHONE_QUERY, TOUCH_QUERY } from '../layout';+import { useMedia } from '../useMedia';+import { composerStacked, keyboardMode, measureText16, phonePlaceholder } from '../composer';import { markNewSeen } from '../whatsNew';import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';import { MentionPopover, MentionItem } from './MentionPopover';@@ -55,39 +58,12 @@ import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';import { RouteChoiceMeta, parseRouteChoiceMeta, questionsOfReplies } from '../routeChoice';import { SmartActionsSlot, actionClass } from './results/SmartActions';import { WorkingStrip } from './WorkingStrip';+import { ScrollRow } from './ScrollRow';import { COMPOSE_PREFILL_EVENT, withPrefill } from './results/SmartResult';import { FilesPreviewOnly } from './results/Files';import { ReactionButtons, ReplyButton, ReplyChip, ReplyQuote } from './MessageReactions';import { ReactResult, Reaction, ReplyRef, botNameOf, excerptOf, questionMessageId, reactionOf, replyRefOf } from '../reactReply';-/** A swipeable chip row whose right fade edge (phones only, see .kw-scroll-row) goes away once- * it is scrolled to the end, or when everything already fits. */-function ScrollRow({ children, ...rest }: React.HTMLAttributes<HTMLDivElement>) {- const ref = useRef<HTMLDivElement>(null);- const update = () => {- const el = ref.current;- if (el) el.dataset.atEnd = String(el.scrollLeft + el.clientWidth >= el.scrollWidth - 1);- };- useEffect(() => {- const el = ref.current;- if (!el) return;- el.addEventListener('scroll', update, { passive: true });- const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update);- resize?.observe(el);- return () => {- el.removeEventListener('scroll', update);- resize?.disconnect();- };- }, []);- // The chips themselves can change without the row resizing.- useEffect(update);- return (- <div ref={ref} {...rest}>- {children}- </div>- );-}-export interface ChatMessage {id: string;sender_role: 'user' | 'kwant' | 'system';@@ -232,6 +208,8 @@ export interface ChatViewProps {onJumpToLatest?: () => void;/** Under the header: the bot's conversations and the open thread's controls. */subHeader?: React.ReactNode;+ /** Phone only: the header's second line in place of the subtitle (the thread picker in a bot's chat). */+ threadLine?: React.ReactNode;/** A note under the sub-header (the setup banner); hidden while `welcome` fills an empty chat. */notice?: React.ReactNode;/** Drawn in place of an empty chat (the first-run welcome). */@@ -441,6 +419,7 @@ export const ChatView: React.FC<ChatViewProps> = ({viewingHistory,onJumpToLatest,subHeader,+ threadLine,notice,welcome,titleExtra,@@ -471,7 +450,15 @@ export const ChatView: React.FC<ChatViewProps> = ({const toggleVm = onToggleVmPane || (() => setInternalIsVmPaneOpen((prev) => !prev));const [inputVal, setInputVal] = useState('');+ // Phone (spec A1): keyboard mode while the composer has focus on a touch screen; the composer is two+ // rows while in use. Desktop never changes.+ const phone = useMedia(PHONE_QUERY);+ const touch = useMedia(TOUCH_QUERY);+ const [composerFocused, setComposerFocused] = useState(false);+ const kbd = keyboardMode({ phone, touch, focused: composerFocused });+ const [fieldWidth, setFieldWidth] = useState(0);const [uploads, setUploads] = useState<PendingUpload[]>([]);+ const stacked = composerStacked({ phone, focused: composerFocused, hasContent: inputVal.length > 0 || uploads.length > 0 });const [uploadNote, setUploadNote] = useState<string | null>(null);const [dragOver, setDragOver] = useState(false);const uploadFiles = useRef(new Map<string, { file: File; abort: AbortController }>());@@ -664,6 +651,26 @@ export const ChatView: React.FC<ChatViewProps> = ({useEffect(() => {stickRef.current = true;}, [contextKey]);+ // Phone: the field's width picks the placeholder (A1), and its height follows when it moves between+ // one row and two. Keyboard mode keeps the last message in view while the chat follows the bottom.+ useEffect(() => {+ const el = textareaRef.current;+ if (!el || !phone) return;+ const measure = () => setFieldWidth(el.clientWidth);+ measure();+ if (typeof ResizeObserver === 'undefined') return;+ const ro = new ResizeObserver(measure);+ ro.observe(el);+ return () => ro.disconnect();+ }, [phone]);+ useLayoutEffect(() => {+ const el = textareaRef.current;+ if (el && phone && el.value) {+ el.style.height = 'auto';+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;+ }+ if (scrollRef.current && stickRef.current) pinToBottom(scrollRef.current);+ }, [kbd, stacked]);// Back from an older window: land on the newest messageuseEffect(() => {if (!viewingHistory) stickRef.current = true;@@ -1278,6 +1285,16 @@ export const ChatView: React.FC<ChatViewProps> = ({teamName,names: activeKwants.map((k) => k.name).concat(activeTeams.map((t) => t.name)),});+ const toolPhone = 'w-11 h-11 text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06] active:bg-white/[0.06] focus-visible:outline-[#b8adff]';+ // Phone hint row (spec A2): no "@ mention · attach files" on touch, and "Answers:" only where it isn't+ // obvious (channels and team chats, or a direct chat with an @mention typed).+ const showAnswers = !phone || home?.kind !== 'bot' || target.kind === 'mention';+ const showHintText = !(phone && touch);+ const placeholder = phone+ ? phonePlaceholder(title, fieldWidth, (t) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : ''))+ : spaceName && !narrow+ ? `Message ${title} in ${spaceName}`+ : `Message ${title}`;const insertAt = () => {playSfx('click');const el = textareaRef.current;@@ -1288,28 +1305,37 @@ export const ChatView: React.FC<ChatViewProps> = ({};return (- <div className="flex-1 flex flex-col h-full bg-surface-main overflow-hidden">- {/* Channel / bot header */}- <div className="h-14 shrink-0 border-b border-hairline px-2 sm:px-6 gap-2 flex items-center justify-between bg-surface-main/80 backdrop-blur-md select-none">+ <div className="flex-1 flex flex-col h-full bg-surface-main overflow-hidden" data-keyboard-mode={kbd ? 'on' : undefined}>+ {/* Channel / bot header: 56 px on a phone, 48 px in keyboard mode (instant, no animation) */}+ <div+ data-chat-header+ className={`${kbd ? 'h-12' : 'h-14'} shrink-0 border-b border-hairline px-2 sm:px-6 gap-2 flex items-center justify-between bg-surface-main/80 backdrop-blur-md select-none`}+ >{onBack && (<buttontype="button"onClick={onBack}aria-label="Back to chats"- className="shrink-0 p-2 -ml-0.5 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ className="shrink-0 w-11 h-11 -ml-1 inline-flex items-center justify-center rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#b8adff]"><ChevronLeft size={18} /></button>)}{home?.kind === 'bot' && home.bot && (- <ModernAvatar role={home.bot.avatar_sprite} name={home.bot.name} size={34} kwantId={home.bot.id} className="rounded-xl" />+ <ModernAvatar role={home.bot.avatar_sprite} name={home.bot.name} size={phone ? (kbd ? 28 : 32) : 34} kwantId={home.bot.id} className="rounded-xl" />)}<div className="min-w-0 flex-1">- <h2 className="text-body font-semibold text-zinc-50 flex items-center gap-2 min-w-0">+ <h2+ className={`${phone ? (kbd ? 'text-[15px] leading-5' : 'text-base leading-5') : 'text-body'} font-semibold text-zinc-50 flex items-center gap-2 min-w-0`}+ ><span className="truncate">{title}</span>{titleExtra}</h2>- <p className="text-meta text-zinc-400 truncate max-w-lg">{subtitle}</p>+ {kbd ? null : phone && threadLine ? (+ <div className="flex min-w-0 mt-0.5">{threadLine}</div>+ ) : (+ <p className={`${phone ? 'text-[13px] leading-4 mt-0.5' : 'text-meta'} text-zinc-400 truncate max-w-lg`}>{subtitle}</p>+ )}</div><div className="flex items-center gap-0.5 sm:gap-3 shrink-0">@@ -1409,10 +1435,15 @@ export const ChatView: React.FC<ChatViewProps> = ({</div></div>- {subHeader}+ {/* In keyboard mode the thread controls and pinned instructions step aside (display: none) */}+ <div data-thread-bar className={kbd ? 'hidden' : 'contents'}>+ {subHeader}+ </div>{!(welcome && messages.length === 0) && notice}- <PinnedInstructions items={pinned} onEdit={onEditInstructions} />+ <div className={kbd ? 'hidden' : 'contents'}>+ <PinnedInstructions items={pinned} onEdit={onEditInstructions} />+ </div>{/* Discussion In-Flight Banner */}{discussionState?.inProgress && (@@ -1465,7 +1496,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<divref={scrollRef}onScroll={onScroll}- className="flex-1 overflow-y-auto px-3 py-4 sm:p-6 space-y-5 sm:space-y-6"+ className="relative flex-1 overflow-y-auto px-3 py-4 sm:p-6 space-y-5 sm:space-y-6"role="log"aria-label={`Messages in ${title}`}aria-busy={isStreaming}@@ -1635,7 +1666,9 @@ export const ChatView: React.FC<ChatViewProps> = ({/>{/* Modern Composer Input Bar */}- <div className="px-3 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:p-4 border-t border-hairline bg-surface-side/60">+ <div+ className={`px-3 ${phone ? 'pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]' : 'pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]'} sm:p-4 border-t border-hairline bg-surface-side/60`}+ >{teamMembers && teamMembers.length > 0 && (<ScrollRow className="kw-scroll-row max-w-4xl mx-auto mb-2.5 flex items-center gap-1.5 overflow-x-auto text-xs select-none" role="group" aria-label="Ask a member"><span className="shrink-0 text-[11px] font-medium text-zinc-500 whitespace-nowrap">Ask:</span>@@ -1701,8 +1734,16 @@ export const ChatView: React.FC<ChatViewProps> = ({onSubmit={handleSubmit}{...dropHandlers}aria-label={`Message ${title}`}- className={`relative max-w-4xl mx-auto flex flex-wrap items-end gap-1.5 bg-surface-raised border rounded-2xl p-2 shadow-raised transition-colors ${- dragOver ? 'border-sky-500/70 bg-sky-950/30' : 'border-hairline-strong focus-within:border-sky-400/50'+ data-composer-form+ data-stacked={phone ? String(stacked) : undefined}+ className={`relative max-w-4xl mx-auto flex flex-wrap items-end ${stacked ? 'gap-x-1.5 gap-y-1' : 'gap-1.5'} border rounded-2xl p-2 transition-colors ${+ phone ? 'bg-[#1a1538]' : 'bg-surface-raised shadow-raised'+ } ${+ dragOver+ ? 'border-sky-500/70 bg-sky-950/30'+ : phone+ ? 'border-white/10 focus-within:border-[#6c58e0]/70'+ : 'border-hairline-strong focus-within:border-sky-400/50'}`}>{dragOver && (@@ -1756,6 +1797,8 @@ export const ChatView: React.FC<ChatViewProps> = ({aria-autocomplete="list"rows={1}value={inputVal}+ onFocus={() => setComposerFocused(true)}+ onBlur={() => setComposerFocused(false)}onChange={(e) => {const val = e.target.value;setInputVal(val);@@ -1779,11 +1822,15 @@ export const ChatView: React.FC<ChatViewProps> = ({checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);}}}- // Phones drop the space name so the 16px placeholder fits on one line- placeholder={spaceName && !narrow ? `Message ${title} in ${spaceName}` : `Message ${title}`}+ // Phones: "Message {name}" only when it fits on one line, else "Message" (the header names the chat)+ placeholder={placeholder}title="Enter to send, Shift+Enter for a new line, @ to mention"- className="flex-1 min-w-0 bg-transparent px-3 py-1.5 text-body text-zinc-50 placeholder-zinc-400 focus:outline-none resize-none max-h-40 font-sans"+ className={+ phone+ ? `${stacked ? 'basis-full w-full py-2' : 'flex-1 py-2.5'} min-w-0 bg-transparent px-3 text-base leading-6 text-zinc-50 placeholder:text-[#8f88bb] placeholder:whitespace-nowrap placeholder:overflow-hidden placeholder:text-ellipsis focus:outline-none resize-none max-h-40 font-sans`+ : 'flex-1 min-w-0 bg-transparent px-3 py-1.5 text-body text-zinc-50 placeholder-zinc-400 focus:outline-none resize-none max-h-40 font-sans'+ }/><inputref={fileInputRef}@@ -1796,15 +1843,18 @@ export const ChatView: React.FC<ChatViewProps> = ({e.target.value = '';}}/>+ {/* Phone, in use: the tools get their own 44 px row under the text. Elsewhere this wrapper is+ display: contents, so the buttons sit beside the field as before. */}+ <div data-composer-tools className={stacked ? 'basis-full flex items-center h-11' : 'contents'}><buttontype="button"onClick={() => fileInputRef.current?.click()}disabled={uploadSlotsLeft(uploads) === 0}title={uploadSlotsLeft(uploads) === 0 ? `Up to ${MAX_ATTACHMENTS} files per message` : 'Attach files (or drop / paste them here). Max 20 MB each.'}aria-label="Attach files"- className="w-11 h-11 sm:w-9 sm:h-9 rounded-xl flex items-center justify-center flex-shrink-0 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ className={`${phone ? toolPhone : 'w-11 h-11 sm:w-9 sm:h-9 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] focus-visible:outline-sky-400'} rounded-xl flex items-center justify-center flex-shrink-0 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:outline focus-visible:outline-2`}>- <Paperclip size={17} aria-hidden="true" />+ <Paperclip size={phone ? 18 : 17} aria-hidden="true" /></button><buttontype="button"@@ -1814,16 +1864,21 @@ export const ChatView: React.FC<ChatViewProps> = ({}}title="Mention a bot: it answers instead of the default"aria-label="Mention a bot"- className="relative w-11 h-11 sm:w-9 sm:h-9 rounded-xl flex items-center justify-center flex-shrink-0 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ className={`relative ${phone ? toolPhone : 'w-11 h-11 sm:w-9 sm:h-9 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] focus-visible:outline-sky-400'} rounded-xl flex items-center justify-center flex-shrink-0 transition-colors focus-visible:outline focus-visible:outline-2`}>- <AtSign size={17} aria-hidden="true" />+ <AtSign size={phone ? 18 : 17} aria-hidden="true" />+ {/* Phone (spec A5): "New" anchors to the @ button's own box, never on the field's border or an Ask chip */}+ {phone && !isStreaming && (+ <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''}`} />+ )}</button>+ {stacked && <span className="flex-1" aria-hidden="true" />}{/* "New" sits just above the field's top edge, over the "@" button: never on or inside the border.Only the send button follows "@" when it shows: 44px on phones / 36px from sm, plus a 6px gap;11px is the form's border + padding. Hidden (not marked as seen) while a reply streams, so itnever sits on the working strip's edge and comes back after the turn; hidden while the mentionpicker is open, so it never peeks under it. */}- {!isStreaming && (+ {!phone && !isStreaming && (<NewTagid="mention"className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''}`}@@ -1849,32 +1904,44 @@ export const ChatView: React.FC<ChatViewProps> = ({title={stillUploading ? 'Waiting for uploads to finish' : undefined}disabled={!canSend}data-send-ready={canSend ? 'true' : 'false'}- className={`w-11 h-11 sm:w-9 sm:h-9 rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,filter,box-shadow,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-300 ${+ className={`${phone ? 'w-11 h-11 focus-visible:outline-[#b8adff]' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-300'} rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,filter,box-shadow,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 ${canSend- ? 'bg-accent-gradient text-white shadow-glow hover:brightness-110 active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'- : 'bg-surface-overlay text-zinc-400 cursor-not-allowed'+ ? phone+ ? 'bg-[#6c58e0] text-white hover:bg-[#5845bd] active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'+ : 'bg-accent-gradient text-white shadow-glow hover:brightness-110 active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'+ : phone+ ? 'bg-[#2c2552] text-[#5a5383] cursor-not-allowed'+ : 'bg-surface-overlay text-zinc-400 cursor-not-allowed'}`}>- <ArrowUp size={17} strokeWidth={2.4} aria-hidden="true" />+ <ArrowUp size={phone ? 18 : 17} strokeWidth={2.4} aria-hidden="true" /></button>)}+ </div></form>{/* Under the field: who will answer, and what the field understands */}- <div className="max-w-4xl mx-auto mt-1.5 px-1 flex items-center justify-between gap-3 text-meta text-zinc-400" data-composer-hints>- <span- className={`kw-chip shrink-0 ${target.kind === 'laya' ? 'kw-chip-accent' : target.kind === 'mention' ? 'kw-chip-info' : ''}`}- title={target.detail}- data-answer-target={target.kind}- >- {target.kind === 'laya' ? <Sparkles size={12} aria-hidden="true" /> : <AtSign size={12} aria-hidden="true" />}- <span className="text-zinc-400 font-normal">Answers:</span> {target.kind === 'laya' ? target.label : target.label.replace(/^@/, '')}- </span>- <span className="min-w-0 truncate text-right">- <span className="sm:hidden">@ mention · attach files</span>- <span className="hidden sm:inline">- <kbd className="font-sans text-zinc-300">@</kbd> mention a bot · <kbd className="font-sans text-zinc-300">Enter</kbd> send · <kbd className="font-sans text-zinc-300">Shift+Enter</kbd> new line · drop or paste files+ <div+ className={`max-w-4xl mx-auto mt-1.5 px-1 flex items-center justify-between gap-3 text-meta text-zinc-400${kbd || (!showAnswers && !showHintText) ? ' hidden' : ''}`}+ data-composer-hints+ >+ {showAnswers && (+ <span+ className={`kw-chip shrink-0 ${target.kind === 'laya' ? 'kw-chip-accent' : target.kind === 'mention' ? 'kw-chip-info' : ''}`}+ title={target.detail}+ data-answer-target={target.kind}+ >+ {target.kind === 'laya' ? <Sparkles size={12} aria-hidden="true" /> : <AtSign size={12} aria-hidden="true" />}+ <span className="text-zinc-400 font-normal">Answers:</span> {target.kind === 'laya' ? target.label : target.label.replace(/^@/, '')}</span>- </span>+ )}+ {showHintText && (+ <span className="min-w-0 truncate text-right">+ <span className="sm:hidden">@ mention · attach files</span>+ <span className="hidden sm:inline">+ <kbd className="font-sans text-zinc-300">@</kbd> mention a bot · <kbd className="font-sans text-zinc-300">Enter</kbd> send · <kbd className="font-sans text-zinc-300">Shift+Enter</kbd> new line · drop or paste files+ </span>+ </span>+ )}</div></div></div>diff --git a/frontend/src/components/PhoneTabBar.tsx b/frontend/src/components/PhoneTabBar.tsxnew file mode 100644index 00000000..2d452caa--- /dev/null+++ b/frontend/src/components/PhoneTabBar.tsx@@ -0,0 +1,69 @@+import React from 'react';+import { badgeText } from '../away';++export interface PhoneTabItem<T extends string> {+ id: T;+ label: string;+ icon: React.ReactNode;+ badge?: number;+}++/** The phone's bottom tab bar (spec A6): 56px plus the home-indicator inset, the app's own violet+ * palette, a 24×3 bar over the active tab and an 18px amber count on the icon's top-right. */+export function PhoneTabBar<T extends string>({+ label,+ tabs,+ active,+ onSelect,+}: {+ label: string;+ tabs: PhoneTabItem<T>[];+ active: T;+ onSelect: (id: T) => void;+}) {+ return (+ <nav+ aria-label={label}+ data-tab-bar+ className="shrink-0 grid grid-cols-4 border-t border-white/[0.07] bg-[#0e0a21] pb-[env(safe-area-inset-bottom)]"+ >+ {tabs.map((t) => {+ const on = t.id === active;+ return (+ <button+ key={t.id}+ type="button"+ aria-current={on ? 'page' : undefined}+ aria-label={t.badge ? `${t.label}, ${t.badge} waiting` : undefined}+ data-tab={t.id}+ onClick={() => onSelect(t.id)}+ className={`relative h-14 flex flex-col items-center justify-center gap-0.5 text-xs leading-4 font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[#b8adff] ${+ on ? 'text-[#e8e4ff]' : 'text-[#a39dcc] hover:text-[#e8e4ff]'+ }`}+ >+ {on && (+ <span+ aria-hidden="true"+ data-tab-active-bar+ className="absolute top-0 left-1/2 -translate-x-1/2 w-6 h-[3px] rounded-b-sm bg-[#9d8fff]"+ />+ )}+ <span className="relative">+ {t.icon}+ {!!t.badge && (+ <span+ aria-hidden="true"+ data-tab-badge+ className="absolute top-[-4px] left-[10px] h-[18px] min-w-[18px] px-1 rounded-full bg-[#fcd34d] text-[#1b1033] text-[11px] leading-[18px] font-semibold text-center"+ >+ {badgeText(t.badge)}+ </span>+ )}+ </span>+ {t.label}+ </button>+ );+ })}+ </nav>+ );+}diff --git a/frontend/src/components/ScrollRow.tsx b/frontend/src/components/ScrollRow.tsxnew file mode 100644index 00000000..41673faa--- /dev/null+++ b/frontend/src/components/ScrollRow.tsx@@ -0,0 +1,34 @@+import React, { useEffect, useRef } from 'react';++/** A sideways scroller whose right edge fades (phones only, see .kw-scroll-row) while there is+ * more to the right. `data-at-end` is "true" once it is scrolled to the end or everything already+ * fits, and then there is no fade. */+export function ScrollRow({+ as: Tag = 'div',+ children,+ ...rest+}: React.HTMLAttributes<HTMLElement> & { as?: 'div' | 'nav' }) {+ const ref = useRef<HTMLElement>(null);+ const update = () => {+ const el = ref.current;+ if (el) el.dataset.atEnd = String(el.scrollLeft + el.clientWidth >= el.scrollWidth - 1);+ };+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ el.addEventListener('scroll', update, { passive: true });+ const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update);+ resize?.observe(el);+ return () => {+ el.removeEventListener('scroll', update);+ resize?.disconnect();+ };+ }, []);+ // The items themselves can change without the row resizing.+ useEffect(update);+ return (+ <Tag ref={ref as React.RefObject<HTMLDivElement>} {...rest}>+ {children}+ </Tag>+ );+}diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex bd8c9f68..a7ea9943 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -20,6 +20,7 @@ import {Users,X,} from 'lucide-react';+import { ScrollRow } from './ScrollRow';import { playSfx } from '../audio/chiptune';import { SPACE_COLORS, SPACE_ICONS, Space, spaceColor, spaceNameError, spacesApi } from '../spaces';import { useEngines } from '../useEngines';@@ -175,7 +176,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {))}</div>{scope === 'space' && (- <nav aria-label={`${space.name} settings`} className="flex md:flex-col gap-1 px-3 pb-3 md:px-2 overflow-x-auto md:overflow-visible">+ <ScrollRow as="nav" aria-label={`${space.name} settings`} className="kw-scroll-row flex md:flex-col gap-1 px-3 pb-3 md:px-2 overflow-x-auto md:overflow-visible">{TABS.map((t) => (<buttonkey={t.id}@@ -193,7 +194,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {{t.label}</button>))}- </nav>+ </ScrollRow>)}</div>diff --git a/frontend/src/components/ThreadBar.tsx b/frontend/src/components/ThreadBar.tsxindex aa15dc8a..2004698b 100644--- a/frontend/src/components/ThreadBar.tsx+++ b/frontend/src/components/ThreadBar.tsx@@ -1,5 +1,6 @@-import React, { useState } from 'react';-import { Archive, ArchiveRestore, ArrowLeft, ArrowRightLeft, HelpCircle, Loader2, MessageSquare, Plus, RotateCw, Square } from 'lucide-react';+import React, { useEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { Archive, ArchiveRestore, ArrowLeft, ArrowRightLeft, Check, ChevronDown, HelpCircle, Loader2, MessageSquare, Plus, RotateCw, Square } from 'lucide-react';import { Badge, BadgeKind, Thread, TurnMap, sortThreads, threadBadge } from '../threads';const BADGE_STYLE: Record<BadgeKind, string> = {@@ -183,6 +184,199 @@ export const ThreadBar: React.FC<ThreadBarProps> = ({);};+/** The status dot on the phone header's second line: violet while working, amber while it waits on you (never holo). */+export function statusDot(badge: Badge | null): { tone: 'working' | 'waiting'; label: string } | null {+ if (!badge) return null;+ if (badge.kind === 'working') return { tone: 'working', label: badge.label };+ if (badge.kind === 'waiting' || badge.kind === 'queued') return { tone: 'waiting', label: badge.label };+ return null;+}++const sheetRow =+ 'w-full min-h-[52px] flex items-center gap-3 px-4 text-left text-[15px] leading-5 text-zinc-100 hover:bg-white/[0.06] active:bg-white/[0.06] focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[#b8adff]';++/**+ * Phone (spec A2): the bot's conversations folded into the header. Line 2 shows the open one+ * ("Direct chat ▾" or the thread's title) with a status dot; tapping it opens the same list as the+ * desktop thread bar in a bottom sheet, "+ New thread" first.+ */+export const ThreadPicker: React.FC<ThreadBarProps> = ({+ kwantName,+ threads,+ error,+ openThreadId,+ turns,+ awaiting,+ directBadge,+ showArchived,+ onToggleArchived,+ onOpenDirect,+ onOpenThread,+ onNewThread,+ onRetry,+}) => {+ const [open, setOpen] = useState(false);+ const [creating, setCreating] = useState(false);+ const [createError, setCreateError] = useState<string | null>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const sheetRef = useRef<HTMLDivElement>(null);+ const visible = threads ? sortThreads(threads, showArchived) : [];+ const archivedCount = threads?.filter((t) => t.archived).length ?? 0;+ const current = openThreadId ? threads?.find((t) => t.id === openThreadId) : undefined;+ const label = openThreadId ? current?.title ?? 'Conversation' : 'Direct chat';+ const badge = current ? threadBadge(current, turns, awaiting) : openThreadId ? null : directBadge;+ const dot = statusDot(badge);++ const close = () => {+ setOpen(false);+ triggerRef.current?.focus();+ };+ useEffect(() => {+ if (!open) return;+ sheetRef.current?.querySelector<HTMLElement>('button')?.focus();+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ close();+ }+ };+ document.addEventListener('keydown', onKey, true);+ return () => document.removeEventListener('keydown', onKey, true);+ }, [open]);++ const pick = (fn: () => void) => {+ fn();+ setOpen(false);+ };+ const create = async () => {+ setCreating(true);+ setCreateError(null);+ const err = await onNewThread();+ setCreating(false);+ if (err) setCreateError(err);+ else setOpen(false);+ };++ return (+ <>+ <button+ ref={triggerRef}+ type="button"+ data-compact+ data-thread-picker+ onClick={() => {+ setCreateError(null);+ setOpen(true);+ }}+ aria-haspopup="dialog"+ aria-expanded={open}+ aria-label={`${label}${dot ? `, ${dot.label}` : ''}. Switch conversation with ${kwantName}`}+ // The line is 16 px; the ::after reaches up over the name and down to the header's edge for a thumb-sized target+ className="relative flex items-center gap-1.5 min-w-0 max-w-full text-[13px] leading-4 text-[#a39dcc] hover:text-zinc-100 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#b8adff] after:absolute after:-inset-x-1 after:-top-6 after:-bottom-3 after:content-['']"+ >+ {dot && (+ <span+ data-status-dot={dot.tone}+ aria-hidden="true"+ className={`shrink-0 w-1.5 h-1.5 rounded-full ${dot.tone === 'working' ? 'bg-[#9d8fff]' : 'bg-[#fcd34d]'}`}+ />+ )}+ <span className="truncate">{label}</span>+ <ChevronDown size={12} aria-hidden="true" className="shrink-0" />+ </button>+ {open &&+ createPortal(+ <div className="fixed inset-0 z-50 flex flex-col justify-end" data-thread-sheet>+ <button type="button" aria-label="Close" data-compact tabIndex={-1} onClick={close} className="absolute inset-0 bg-black/50 cursor-default" />+ <div+ ref={sheetRef}+ role="dialog"+ aria-modal="true"+ aria-label={`Conversations with ${kwantName}`}+ className="kw-sheet relative max-h-[70vh] flex flex-col rounded-t-2xl bg-[#1a1538] border-t border-white/10 pb-[env(safe-area-inset-bottom)] shadow-2xl"+ >+ <div className="shrink-0 flex justify-center pt-2 pb-1" aria-hidden="true">+ <span className="w-9 h-1 rounded-sm bg-[#3f3868]" />+ </div>+ <ul className="overflow-y-auto py-1" role="list">+ <li>+ <button type="button" onClick={create} disabled={creating} className={`${sheetRow} text-[#b8adff] disabled:opacity-60`}>+ {creating ? <Loader2 size={16} aria-hidden="true" className="animate-spin motion-reduce:animate-none" /> : <Plus size={16} aria-hidden="true" />}+ <span>{creating ? 'Starting…' : 'New thread'}</span>+ </button>+ {createError && (+ <p role="alert" className="px-4 pb-2 text-[13px] text-rose-300">+ {createError}+ </p>+ )}+ </li>+ <li>+ <button type="button" onClick={() => pick(onOpenDirect)} aria-current={!openThreadId ? 'page' : undefined} className={sheetRow}>+ <MessageSquare size={16} aria-hidden="true" className="shrink-0 text-[#a39dcc]" />+ <span className="min-w-0 flex-1 truncate">Direct chat</span>+ {directBadge && <StatusBadge badge={directBadge} />}+ {!openThreadId && <Check size={16} aria-hidden="true" className="shrink-0 text-[#b8adff]" />}+ </button>+ </li>+ {threads === undefined && !error && (+ <li className="flex items-center gap-2 px-4 min-h-[52px] text-[13px] text-[#a39dcc]" aria-live="polite">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />+ Loading conversations…+ </li>+ )}+ {error && (+ <li className="flex items-center gap-3 px-4 min-h-[52px] text-[13px] text-rose-300" role="alert">+ <span className="flex-1">Couldn't load conversations.</span>+ <button type="button" onClick={onRetry} className="inline-flex items-center gap-1 px-3 rounded-lg border border-rose-500/30 hover:bg-rose-500/10">+ <RotateCw size={12} aria-hidden="true" /> Retry+ </button>+ </li>+ )}+ {visible.map((t) => {+ const b = threadBadge(t, turns, awaiting);+ const isOpen = openThreadId === t.id;+ const delegated = t.kind === 'delegation';+ return (+ <li key={t.id}>+ <button+ type="button"+ onClick={() => pick(() => onOpenThread(t))}+ aria-current={isOpen ? 'page' : undefined}+ className={`${sheetRow} ${t.archived ? 'opacity-60' : ''}`}+ >+ {delegated ? (+ <ArrowRightLeft size={16} aria-hidden="true" className="shrink-0 text-amber-300/90" />+ ) : (+ <MessageSquare size={16} aria-hidden="true" className="shrink-0 text-[#a39dcc]" />+ )}+ <span className="min-w-0 flex-1 truncate">+ <span className="sr-only">{delegated ? 'Delegated: ' : 'Conversation: '}</span>+ {t.title}+ {t.archived && <span className="sr-only"> (archived)</span>}+ </span>+ {b && <StatusBadge badge={b} />}+ {isOpen && <Check size={16} aria-hidden="true" className="shrink-0 text-[#b8adff]" />}+ </button>+ </li>+ );+ })}+ {archivedCount > 0 && (+ <li>+ <button type="button" onClick={onToggleArchived} aria-pressed={showArchived} className={`${sheetRow} text-[#a39dcc]`}>+ <Archive size={16} aria-hidden="true" />+ <span>{showArchived ? 'Hide archived' : `Archived (${archivedCount})`}</span>+ </button>+ </li>+ )}+ </ul>+ </div>+ </div>,+ document.body,+ )}+ </>+ );+};+export interface ThreadHeaderProps {thread: Thread;badge: Badge | null;diff --git a/frontend/src/composer.ts b/frontend/src/composer.tsnew file mode 100644index 00000000..8b56fa81--- /dev/null+++ b/frontend/src/composer.ts@@ -0,0 +1,49 @@+// The chat composer on a phone (kwant 0.6.13, spec A1).++/**+ * Keyboard mode: on a phone with a touch screen, while the composer has focus. The header shrinks to+ * 48 px and the thread line, pinned instructions and hint row step aside, so what you answer stays in+ * view above the keyboard. Focus is the signal, not the visual viewport: with+ * interactive-widget=resizes-content (index.html) Android shrinks innerHeight along with the keyboard,+ * so a viewport comparison never fires there. A hardware keyboard compacts it too, which is fine.+ */+export function keyboardMode(s: { phone: boolean; touch: boolean; focused: boolean }): boolean {+ return s.phone && s.touch && s.focused;+}++/**+ * The composer is two rows on a phone (the text full width, the tools under it) while it's in use:+ * focused, or holding text or files. Empty and at rest it's one row, so the chat keeps the room.+ */+export function composerStacked(s: { phone: boolean; focused: boolean; hasContent: boolean }): boolean {+ return s.phone && (s.focused || s.hasContent);+}++/** px-3 on each side of the field. */+export const PLACEHOLDER_PAD = 24;++/**+ * The phone placeholder: "Message {name}" when it fits on one line, else "Message" (the header names+ * the chat). A placeholder never wraps: WebKit ignores text-overflow on a textarea placeholder, so a+ * long one would wrap and be cut mid-glyph. Unknown width (before layout): the short one.+ */+export function phonePlaceholder(name: string, fieldWidth: number, measure: (text: string) => number): string {+ const long = `Message ${name}`;+ if (!(fieldWidth > PLACEHOLDER_PAD)) return 'Message';+ return measure(long) <= fieldWidth - PLACEHOLDER_PAD ? long : 'Message';+}++let ctx: CanvasRenderingContext2D | null | undefined;+/** Width of a text at 16 px in the given font family (canvas), or an estimate where there's no canvas. */+export function measureText16(text: string, family: string): number {+ if (ctx === undefined) {+ try {+ ctx = typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d');+ } catch {+ ctx = null;+ }+ }+ if (!ctx) return text.length * 9;+ ctx.font = `16px ${family || 'Inter, system-ui, sans-serif'}`;+ return ctx.measureText(text).width;+}diff --git a/frontend/src/layout.ts b/frontend/src/layout.tsindex 64377ced..485803c2 100644--- a/frontend/src/layout.ts+++ b/frontend/src/layout.ts@@ -3,3 +3,6 @@ export const PHONE_QUERY = '(max-width: 767px)';/** The phone layout is on: no sidebar, so nothing on screen should be placed from it. */export const isPhoneLayout = (): boolean => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches;++/** A touch screen: the finger is the pointer. With PHONE_QUERY, the phone layout on a phone. */+export const TOUCH_QUERY = '(pointer: coarse)';diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 2f030a96..e98252c6 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -171,23 +171,25 @@}}-/* Phone-width chat: swipeable chip rows without a scrollbar, fading at the right edge, and the- header's action buttons as plain icons so they don't crowd the title. */-@media (max-width: 639px) {+/* Phone widths: sideways scrollers (chip rows, Space settings tabs) without a scrollbar, fading+ 24px at the right edge only while they can scroll further (ScrollRow sets data-at-end). */+@media (max-width: 767px) {.kw-scroll-row {scrollbar-width: none;-webkit-overflow-scrolling: touch;overscroll-behavior-x: contain;- mask-image: linear-gradient(to right, #000 calc(100% - 28px), transparent);- -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 28px), transparent);}.kw-scroll-row::-webkit-scrollbar {display: none;}- .kw-scroll-row[data-at-end='true'] {- mask-image: none;- -webkit-mask-image: none;+ .kw-scroll-row[data-at-end='false'] {+ mask-image: linear-gradient(to right, #000 calc(100% - 24px), transparent);+ -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 24px), transparent);}+}++/* Phone-width chat: the header's action buttons as plain icons so they don't crowd the title. */+@media (max-width: 639px) {.kw-head-btn:not([aria-pressed='true']) {background-color: transparent;border-color: transparent;@@ -541,3 +543,21 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:.kw-react-pop > svg { animation: none; }.kw-flash-quote::after { animation: none; }}++/* Phone bottom sheet (the thread picker, spec A2): slides up in 180 ms, appears at once under reduced motion */+.kw-sheet {+ animation: kw-sheet-in 180ms cubic-bezier(0.2, 0.7, 0.2, 1);+}+@keyframes kw-sheet-in {+ from {+ transform: translateY(100%);+ }+ to {+ transform: translateY(0);+ }+}+@media (prefers-reduced-motion: reduce) {+ .kw-sheet {+ animation: none;+ }+}diff --git a/frontend/src/useMedia.ts b/frontend/src/useMedia.tsnew file mode 100644index 00000000..0464144f--- /dev/null+++ b/frontend/src/useMedia.ts@@ -0,0 +1,15 @@+import { useEffect, useState } from 'react';++/** Whether a media query matches, kept in sync with resizes and rotation. */+export function useMedia(query: string): boolean {+ const [matches, setMatches] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(query).matches);+ useEffect(() => {+ const mq = window.matchMedia?.(query);+ if (!mq) return;+ const on = () => setMatches(mq.matches);+ on();+ mq.addEventListener?.('change', on);+ return () => mq.removeEventListener?.('change', on);+ }, [query]);+ return matches;+}diff --git a/frontend/tests/mobileRoom.test.mjs b/frontend/tests/mobileRoom.test.mjsnew file mode 100644index 00000000..353078c8--- /dev/null+++ b/frontend/tests/mobileRoom.test.mjs@@ -0,0 +1,286 @@+// Mobile 0.6.13 slice A (Mira's spec): A1 keyboard mode, A2 composer placeholder, A5 Answers chip,+// A6 tab bar, thread picker in the header. Every case here fails on main 3ca2bf7.+import assert from "node:assert/strict";+import test from "node:test";+import { JSDOM } from "jsdom";+import { loadBundled } from "./bundle.mjs";++const dom = new JSDOM("<!doctype html><html><body></body></html>", {+ url: "http://localhost/",+ pretendToBeVisual: true,+});+for (const k of [+ "window",+ "document",+ "navigator",+ "HTMLElement",+ "HTMLButtonElement",+ "Element",+ "Node",+ "Event",+ "KeyboardEvent",+ "FocusEvent",+ "MutationObserver",+ "requestAnimationFrame",+ "cancelAnimationFrame",+ "getComputedStyle",+ "CSS",+]) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(globalThis, k, {+ value: dom.window[k],+ configurable: true,+ writable: true,+ });+}+const store = new Map();+const ls = {+ getItem: (k) => (store.has(k) ? store.get(k) : null),+ setItem: (k, v) => void store.set(k, String(v)),+ removeItem: (k) => void store.delete(k),+};+Object.defineProperty(globalThis, "localStorage", {+ value: ls,+ configurable: true,+ writable: true,+});+Object.defineProperty(dom.window, "localStorage", {+ value: ls,+ configurable: true,+});+// Controllable media: a phone with a touch screen unless a test says otherwise.+const media = { phone: true, coarse: true };+dom.window.matchMedia = (q) => ({+ matches: q.includes("pointer: coarse") ? media.coarse : q.includes("max-width: 767px") || q.includes("max-width: 639px") ? media.phone : false,+ media: q,+ addEventListener() {},+ removeEventListener() {},+ addListener() {},+ removeListener() {},+});+globalThis.matchMedia = dom.window.matchMedia;+globalThis.ResizeObserver ??= class {+ observe() {}+ unobserve() {}+ disconnect() {}+};+dom.window.ResizeObserver ??= globalThis.ResizeObserver;+globalThis.IntersectionObserver ??= class {+ observe() {}+ unobserve() {}+ disconnect() {}+};+dom.window.HTMLElement.prototype.scrollIntoView ??= function () {};+dom.window.HTMLElement.prototype.scrollTo ??= function () {};++const ui = await loadBundled(`+ import React from 'react';+ import { flushSync } from 'react-dom';+ import { createRoot } from 'react-dom/client';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { ChatView } from './src/components/ChatView';+ import { PhoneTabBar } from './src/components/PhoneTabBar';+ import { ThreadPicker } from './src/components/ThreadBar';+ export * from './src/composer';+ export const mount = (p) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ const render = (q) => flushSync(() => root.render(React.createElement(ChatView, q)));+ render(p);+ return { host, render, unmount: () => { root.unmount(); host.remove(); } };+ };+ export const mountPicker = (p) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ flushSync(() => root.render(React.createElement(ThreadPicker, p)));+ return { host, unmount: () => { root.unmount(); host.remove(); } };+ };+ export const tabBar = (badge) =>+ renderToStaticMarkup(+ React.createElement(PhoneTabBar, {+ label: 'Demo sections',+ active: 'chats',+ onSelect: () => {},+ tabs: [+ { id: 'chats', label: 'Chats', icon: null },+ { id: 'bots', label: 'Bots', icon: null },+ { id: 'inbox', label: 'Inbox', icon: null, badge },+ { id: 'space', label: 'Space', icon: null },+ ],+ }),+ );+ export const act = (fn) => flushSync(fn);+`);++const props = (extra = {}) => ({+ title: "Dev",+ subtitle: "Backend",+ messages: [],+ streamingText: "",+ streamingThinking: "",+ isStreaming: false,+ pendingApprovals: [],+ onSendMessage: () => {},+ onResolveApproval: () => {},+ onCancelDiscussion: () => {},+ onBack: () => {},+ kwants: [],+ teams: [],+ ...extra,+});++const textarea = (h) => h.querySelector("textarea[data-composer]") ?? h.querySelector("textarea");+const focusIn = (el) => ui.act(() => { el.focus(); });+const blurOut = (el) => ui.act(() => { el.blur(); });++test("A1: focusing the composer on a touch phone turns keyboard mode on, blur turns it off", () => {+ media.phone = true;+ media.coarse = true;+ const v = ui.mount(props({ threadLine: "Direct chat" }));+ try {+ const ta = textarea(v.host);+ assert.ok(ta, "composer rendered");+ assert.equal(v.host.querySelector('[data-keyboard-mode="on"]'), null, "off before focus");+ focusIn(ta);+ assert.ok(v.host.querySelector('[data-keyboard-mode="on"]'), "on while the composer has focus");+ const header = v.host.querySelector("[data-chat-header]");+ assert.match(header.className, /\bh-12\b/, "header shrinks to 48px");+ assert.equal(header.textContent.includes("Direct chat"), false, "header line 2 hidden");+ assert.match(v.host.querySelector("[data-thread-bar]").className, /\bhidden\b/, "thread bar hidden");+ assert.match(v.host.querySelector("[data-composer-hints]").className, /\bhidden\b/, "hints row hidden");+ blurOut(ta);+ assert.equal(v.host.querySelector('[data-keyboard-mode="on"]'), null, "off after blur");+ assert.match(v.host.querySelector("[data-chat-header]").className, /\bh-14\b/);+ assert.ok(v.host.querySelector("[data-chat-header]").textContent.includes("Direct chat"), "line 2 back");+ } finally {+ v.unmount();+ }+});++test("A1: a phone-width window with a mouse (no coarse pointer) never enters keyboard mode", () => {+ media.phone = true;+ media.coarse = false;+ const v = ui.mount(props());+ try {+ focusIn(textarea(v.host));+ assert.equal(v.host.querySelector('[data-keyboard-mode="on"]'), null);+ } finally {+ v.unmount();+ media.coarse = true;+ }+});++test("A1: desktop focus changes nothing", () => {+ media.phone = false;+ media.coarse = false;+ const v = ui.mount(props());+ try {+ focusIn(textarea(v.host));+ assert.equal(v.host.querySelector('[data-keyboard-mode="on"]'), null);+ assert.equal(v.host.querySelector("[data-composer-form]").hasAttribute("data-stacked"), false, "desktop form untouched");+ } finally {+ v.unmount();+ media.phone = true;+ media.coarse = true;+ }+});++test("A2: the composer stacks (text above, tools below) only when focused or holding text", () => {+ const v = ui.mount(props());+ try {+ const form = () => v.host.querySelector("[data-composer-form]");+ assert.equal(form().getAttribute("data-stacked"), "false", "one row at rest");+ focusIn(textarea(v.host));+ assert.equal(form().getAttribute("data-stacked"), "true", "two rows while typing");+ blurOut(textarea(v.host));+ assert.equal(form().getAttribute("data-stacked"), "false");+ } finally {+ v.unmount();+ }+});++test("A2: placeholder falls back to plain \"Message\" when the name does not fit", () => {+ const per = (t) => t.length * 9;+ assert.equal(ui.phonePlaceholder("Dev", 300, per), "Message Dev");+ assert.equal(ui.phonePlaceholder("Booktun.ing Marketer with a long name", 220, per), "Message");+ assert.equal(ui.phonePlaceholder("Dev", 0, per), "Message", "unknown width: the safe short form");+ // 24px is kept free at the right edge+ const w = per("Message Dev");+ assert.equal(ui.phonePlaceholder("Dev", w + ui.PLACEHOLDER_PAD, per), "Message Dev");+ assert.equal(ui.phonePlaceholder("Dev", w + ui.PLACEHOLDER_PAD - 1, per), "Message");+});++test("A5: a direct bot chat on a phone has no Answers chip (it only repeats the header)", () => {+ const home = { kind: "bot", bot: { id: "b1", name: "Dev", title: "Backend", avatar_sprite: "" } };+ const v = ui.mount(props({ home, messages: [{ id: "m1", sender_role: "user", sender_id: "u", text: "hi", created_at: "2026-11-05T00:00:00Z" }] }));+ try {+ assert.equal(v.host.querySelector("[data-answer-target]"), null);+ assert.match(v.host.querySelector("[data-composer-hints]").className, /\bhidden\b/, "touch: no hint text either, so no row");+ } finally {+ v.unmount();+ }+});++test("A6: tab bar uses the app palette, 56px tabs, a 24x3 active bar and an 18px amber badge", () => {+ const html = ui.tabBar(3);+ assert.doesNotMatch(html, /sky-/, "no sky blue left");+ assert.match(html, /bg-\[#0e0a21\]/);+ const doc = new JSDOM(html).window.document;+ const tabs = [...doc.querySelectorAll("[data-tab]")];+ assert.equal(tabs.length, 4);+ for (const t of tabs) assert.match(t.className, /\bh-14\b/);+ const active = doc.querySelector('[aria-current="page"]');+ assert.match(active.className, /text-\[#e8e4ff\]/);+ assert.ok(active.querySelector("[data-tab-active-bar]"));+ assert.match(active.querySelector("[data-tab-active-bar]").className, /w-6 h-\[3px\].*bg-\[#9d8fff\]/);+ assert.match(doc.querySelector('[data-tab="bots"]').className, /text-\[#a39dcc\]/);+ const badge = doc.querySelector("[data-tab-badge]");+ assert.equal(badge.textContent, "3");+ assert.match(badge.className, /h-\[18px\] min-w-\[18px\]/);+ assert.match(badge.className, /bg-\[#fcd34d\] text-\[#1b1033\] text-\[11px\]/);+ assert.equal(doc.querySelector('[data-tab="inbox"]').getAttribute("aria-label"), "Inbox, 3 waiting");+ assert.equal(new JSDOM(ui.tabBar(0)).window.document.querySelector("[data-tab-badge]"), null, "no badge at 0");+});++const pickerProps = (extra = {}) => ({+ kwantName: "Dev",+ threads: [+ { id: "t1", kwant_id: "k1", title: "Fix login", archived: false, created_at: "2026-11-04T00:00:00Z", updated_at: "2026-11-04T00:00:00Z", delegation: null },+ ],+ error: null,+ openThreadId: null,+ turns: {},+ awaiting: new Set(),+ directBadge: null,+ showArchived: false,+ onToggleArchived: () => {},+ onOpenDirect: () => {},+ onOpenThread: () => {},+ onNewThread: async () => {},+ onRetry: () => {},+ ...extra,+});++test("thread picker: header line 2 names the conversation and opens a sheet listing them", () => {+ let opened = null;+ const v = ui.mountPicker(pickerProps({ onOpenThread: (t) => (opened = t.id) }));+ try {+ const btn = v.host.querySelector("[data-thread-picker]");+ assert.ok(btn);+ assert.match(btn.textContent, /Direct chat/);+ ui.act(() => btn.click());+ const sheet = document.querySelector('[role="dialog"]');+ assert.ok(sheet, "sheet open");+ const rows = [...sheet.querySelectorAll("button")].map((b) => b.textContent.trim());+ assert.ok(rows[0].startsWith("New thread"), "New thread first");+ assert.ok(rows.some((r) => r.startsWith("Direct chat")));+ const t1 = [...sheet.querySelectorAll("button")].find((b) => b.textContent.includes("Fix login"));+ ui.act(() => t1.click());+ assert.equal(opened, "t1");+ assert.equal(document.querySelector('[role="dialog"]'), null, "sheet closes after a pick");+ } finally {+ v.unmount();+ }+});diff --git a/frontend/tests/uiRefreshSignature.test.mjs b/frontend/tests/uiRefreshSignature.test.mjsindex 0c39a0aa..e7ffe127 100644--- a/frontend/tests/uiRefreshSignature.test.mjs+++ b/frontend/tests/uiRefreshSignature.test.mjs@@ -281,5 +281,7 @@ test('composer: 44 px buttons on phones; "New" on @ clears when the picker opensassert.match(c, /if \(isMentionOpen\) markNewSeen\('mention'\)/);assert.match(c, /\$\{isMentionOpen \? 'hidden' : ''\}/);// #266 Mira fix 3: hidden (not marked seen) while a reply streams; mounted behaviour is in newOnMentionStreaming.- assert.match(c, /\{!isStreaming && \(\s*<NewTag\s+id="mention"/);+ // 0.6.13 A5: phone anchors it inside the @ button, desktop keeps its spot; both hide while streaming.+ assert.match(c, /\{phone && !isStreaming && \(\s*<NewTag\s+id="mention"/);+ assert.match(c, /\{!phone && !isStreaming && \(\s*<NewTag\s+id="mention"/);});