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
UI refresh PR 1: app shell, Bot home, avatar moods and stickers (0.6.9) (#264)
Oleksandr Ivanchenko5e8fec51e651
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex c87c1bf0..8a2d357f 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -55,6 +55,10 @@ import { playSfx } from './audio/chiptune';import { haptic, messageHaptic } from './haptics';import { Toasts, Toast } from './components/Toasts';import { clearAllTurns, resetTurns, turnEnded, turnStarted } from './kwantActivity';+import { clearMoods, moodOutput, moodTurnEnded, moodTurnStarted, restingUntil, setMoodNeedsYou, setMoodResting } from './kwantMood';+import { browserTabDoc, createTabSignal, needsYouCount } from './tabSignal';+import { recentWork, type ChatHome } from './botHome';+import { approvalsDiffers } from './components/Sidebar';import { botStatuses, busyLines } from './botStatus';import {ChatLoads,@@ -106,7 +110,7 @@ import {turnsAwaitingAnswer,} from './questions';import { AwayItem, affectsAway, awayApi, awayTarget, badgeText } from './away';-import { Space, eventsUrl, pickInitialChat, spaceColor } from './spaces';+import { Space, eventsUrl, pickInitialChat } from './spaces';import { canRunNow } from './engines';import { useEngines } from './useEngines';import { claudeNeedsSignIn } from './claudeLogin';@@ -827,13 +831,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const key = d.turn_id ?? d.context_id;if (event.type === 'turn_ended' || event.type === 'TurnEnded') {turnEnded(d.kwant_id, key);+ moodTurnEnded(d.kwant_id, d.outcome);starAskStore().turnFinished();if (d.turn_id) completed.delete(d.turn_id);// The reply is saved by now; TurnComplete's load may have come back without itif (reloadOnTurnEnd(d.turn_id)) refreshContext(ctx).then(() => settle(ctx));else settle(ctx);} else {- if (event.type === 'turn_started' || event.type === 'TurnStarted') turnStarted(d.kwant_id, key);+ if (event.type === 'turn_started' || event.type === 'TurnStarted') {+ turnStarted(d.kwant_id, key);+ moodTurnStarted(d.kwant_id);+ }if (!discussionInProgressRef.current || ctx !== streamingContextIdRef.current) markLive(ctx, kwantName(d.kwant_id));}break;@@ -1002,6 +1010,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({break;case 'TextDelta':case 'ThinkingDelta': {+ moodOutput(event.kwant_id);// Each chat streams into its own buffer; only the open chat's is drawn.const ctx = streamTarget(event, streamingContextIdRef.current);if (!ctx) break;@@ -1028,6 +1037,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}case 'activity':case 'Activity': {+ moodOutput(event.kwant_id);const step = parseStep(event.data?.step);const ctx = streamTarget(event, streamingContextIdRef.current);const turnId: string | undefined = typeof event.turn_id === 'string' ? event.turn_id : undefined;@@ -1282,6 +1292,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({return () => {sse.close();clearAllTurns();+ clearMoods();};}, [refreshProfiles]);@@ -2633,7 +2644,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({) : null;const pendingSkillCounts = pendingByKwant(pendingSkills);const pendingHere = currentKwant ? pendingSkillCounts[currentKwant.id] ?? 0 : 0;- const approvalsBadge = approvalsOff(currentKwant) ? (+ // "Approvals off" is said once in the sidebar for the whole space; here only a bot that differs says it.+ const approvalsBadge = approvalsOff(currentKwant) && approvalsDiffers(currentKwant!, space.approvals) ? (<ApprovalsOffBadge onClick={() => currentKwant && openAgentSettings(currentKwant)} title={`${currentKwant?.name} acts without asking, including deletions, publishing and sign-ins. Payments still ask you. Open its settings to change it.`} />) : null;const skillsBadge =@@ -2651,6 +2663,45 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const busyKwants = busyLines({ turns: Object.values(turns), openCtx, awaiting: awaitingTurns, browser: browserTurns, describe: describeContext });const botStatus = botStatuses({ turns: Object.values(turns), awaiting: awaitingTurns, needsYou: needsYouByKwant });+ // Avatar moods and the background-tab signal come from the same state as the sidebar's dots.+ const needsYouNow = Object.entries(botStatus).filter(([, st]) => st === 'needs_you').map(([id]) => id);+ const needsYouKey = needsYouNow.join(',');+ useEffect(() => setMoodNeedsYou(needsYouKey ? needsYouKey.split(',') : []), [needsYouKey]);+ useEffect(() => {+ const apply = () => {+ const now = Date.now();+ setMoodResting(Object.fromEntries(kwants.map((k) => [k.id, restingUntil(k.preferred_model, profiles, now)])));+ };+ apply();+ const t = setInterval(apply, 30_000);+ return () => clearInterval(t);+ }, [kwants, profiles]);+ const tabSignal = useMemo(() => createTabSignal(browserTabDoc()), []);+ const tabNeedsYou = needsYouCount(botStatus, pendingApprovals.length);+ const anyRunning = Object.values(turns).some((t) => t.state === 'running');+ useEffect(() => {+ tabSignal.setNeedsYou(tabNeedsYou);+ // Something else (the sandbox viewer) may set the title later: put the count back in front.+ const el = document.querySelector('title');+ if (!el || typeof MutationObserver === 'undefined') return;+ const mo = new MutationObserver(() => tabSignal.setNeedsYou(tabNeedsYou));+ mo.observe(el, { childList: true, characterData: true, subtree: true });+ return () => mo.disconnect();+ }, [tabSignal, tabNeedsYou]);+ useEffect(() => {+ void tabSignal.setWorking(anyRunning);+ }, [tabSignal, anyRunning]);++ // What the empty chat shows: a bot's home, #general's, or nothing special for a team or other channel.+ const chatHome: ChatHome = currentKwant+ ? {+ kind: 'bot',+ bot: currentKwant,+ recent: recentWork(threadsByKwant[currentKwant.id]),+ onOpenRecent: (id: string) => openThread(currentKwant.id, id),+ }+ : { kind: isGeneral ? 'general' : currentTeam ? 'team' : 'channel' };+// Delete is off while the bot runs anywhere, the open chat included.const workingKwants = new Set(Object.values(turns).map((t) => t.kwant_id));@@ -2972,6 +3023,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({streamingText={isCurrentContextStreaming ? streamingText : ''}streamingThinking={isCurrentContextStreaming ? streamingThinking : ''}pendingApprovals={approvalsHere}+ home={chatHome}isStreaming={isCurrentContextStreaming}streamingSpeakerName={live[openCtx] || undefined}onSendMessage={handleSendMessage}@@ -3117,10 +3169,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const showPhoneList = isPhone && phoneView === 'list' && !needsSetup;return (- <div className="relative flex-1 min-w-0 h-full flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden" data-space={space.id}>- {/* The open space's colour, so it's clear where a message goes */}- <div className="h-[3px] shrink-0 opacity-60" style={{ background: spaceColor(space) }} aria-hidden="true" />-+ <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}><div ref={contentRef} className={`flex-1 min-h-0 flex ${isPhone ? 'flex-col' : 'overflow-hidden'}`}>{isPhone ? (<>diff --git a/frontend/src/botHome.ts b/frontend/src/botHome.tsnew file mode 100644index 00000000..da63c313--- /dev/null+++ b/frontend/src/botHome.ts@@ -0,0 +1,139 @@+// What the empty-chat "bot home" and the composer's answer pill say, worked out from data the client+// already has: no new requests. Pure, so tests can check the words.++export interface HomeBot {+ id: string;+ name: string;+ title: string;+ avatar_sprite: string;+ /** "Good for" phrases routing reads; absent on older servers. */+ covers?: string[];+ preferred_model?: string;+ approvals_effective?: string | null;+}++export interface RecentItem {+ id: string;+ title: string;+ updated_at: string;+}++/** What the chat pane is: a bot's own chat, #general, a team's chat, or another channel. */+export type ChatKind = 'bot' | 'general' | 'team' | 'channel';++export interface ChatHome {+ kind: ChatKind;+ /** The bot, for a direct chat. */+ bot?: HomeBot;+ /** The bot's most recent other conversations, newest first; absent until they are loaded. */+ recent?: RecentItem[];+ onOpenRecent?: (id: string) => void;+}++const MAX_CHIPS = 4;+const MAX_CHIP_LEN = 32;++const clean = (s: string) => s.replace(/\s+/g, ' ').trim();++/**+ * "Good at" chips: the bot's own "Good for" phrases (covers), at most four, short, no repeats.+ * Nothing beyond its role means none: the role is already the subtitle, so echoing it adds nothing.+ * Phrases that only repeat the role are dropped for the same reason.+ */+export function goodAt(bot: Pick<HomeBot, 'title' | 'covers'>): string[] {+ const role = clean(bot.title || '').toLowerCase();+ const parts = (bot.covers ?? []).map(clean).filter((p) => p && p.toLowerCase() !== role);+ const seen = new Set<string>();+ const out: string[] = [];+ for (const p of parts) {+ const text = p.length > MAX_CHIP_LEN ? `${p.slice(0, MAX_CHIP_LEN - 1).trimEnd()}…` : p;+ const key = text.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(text);+ if (out.length === MAX_CHIPS) break;+ }+ return out;+}++/** The two newest chats that aren't archived, from a bot's thread list. */+export function recentWork(+ threads: Array<{ id: string; title: string; updated_at: string; archived?: boolean; kind?: string }> | undefined,+ limit = 2,+): RecentItem[] | undefined {+ if (!threads) return undefined;+ return threads+ .filter((t) => !t.archived && t.title && t.kind !== 'delegation')+ .sort((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))+ .slice(0, limit)+ .map(({ id, title, updated_at }) => ({ id, title, updated_at }));+}++/** Starter cards: the suggested prompts, capped, each with a first-letter capital. */+export function starterCards(prompts: string[], max = 4): string[] {+ return prompts+ .map(clean)+ .filter(Boolean)+ .slice(0, max)+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1));+}++export interface AnswerTarget {+ kind: 'laya' | 'bot' | 'team' | 'mention';+ /** The pill's words: "Laya picks", "@Nutritionist", "@Kitchen team". */+ label: string;+ /** The full sentence for the tooltip and screen readers. */+ detail: string;+}++/** Who will answer what's typed: a leading or inline @Name wins, otherwise the chat decides. */+export function answerTarget(opts: {+ kind: ChatKind;+ text: string;+ botName?: string;+ teamName?: string;+ names: string[];+}): AnswerTarget {+ const m = opts.text.match(/(?:^|\s)@([a-zA-Z0-9_-]+)/);+ if (m) {+ const hit = opts.names.find((n) => n.toLowerCase() === m[1].toLowerCase());+ if (hit) return { kind: 'mention', label: `@${hit}`, detail: `@${hit} will answer, because you mentioned them.` };+ }+ if (opts.kind === 'bot') {+ return { kind: 'bot', label: `@${opts.botName ?? 'bot'}`, detail: `${opts.botName ?? 'This bot'} answers in this chat.` };+ }+ if (opts.kind === 'general') {+ return { kind: 'laya', label: 'Laya picks', detail: 'Laya picks the best bot to answer. Type @ and a name to choose one yourself.' };+ }+ if (opts.kind === 'team') {+ const t = opts.teamName ? `@${opts.teamName} team` : 'The team';+ return { kind: 'team', label: t, detail: `${t} answers. Type @ and a name to ask one member.` };+ }+ return { kind: 'team', label: 'This channel', detail: 'The bots in this channel answer. Type @ and a name to ask one.' };+}++/** "5m ago", "2h ago", "3d ago", else the date: short, for the recent-work cards. */+export function ago(iso: string, now: number = Date.now()): string {+ const t = Date.parse(iso.includes('T') || iso.endsWith('Z') ? iso : `${iso.replace(' ', 'T')}Z`);+ if (Number.isNaN(t)) return '';+ const s = Math.max(0, Math.round((now - t) / 1000));+ if (s < 60) return 'just now';+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ if (s < 86400 * 7) return `${Math.floor(s / 86400)}d ago`;+ return new Date(t).toISOString().slice(0, 10);+}++/**+ * Which bots a message goes to as written: the bot whose own chat it is, plus every bot @mentioned+ * by name (case-insensitive, whole word). Laya's pick isn't known until she answers, so it isn't here.+ */+export function recipientsOf(text: string, bots: Array<{ id: string; name: string }>, directId?: string): string[] {+ const out = new Set<string>();+ if (directId) out.add(directId);+ for (const b of bots) {+ const esc = b.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ if (esc && new RegExp(`(?:^|\\s)@${esc}(?![\\w-])`, 'i').test(text)) out.add(b.id);+ }+ return [...out];+}diff --git a/frontend/src/botStatus.ts b/frontend/src/botStatus.tsindex bad2fec1..d5205075 100644--- a/frontend/src/botStatus.ts+++ b/frontend/src/botStatus.ts@@ -58,7 +58,7 @@ export const statusText = (name: string | undefined, status: BotStatus): string/** The dot's classes; Working pulses unless the person asked for less motion. */export const STATUS_DOT: Record<BotStatus, string> = {needs_you: 'bg-amber-400',- working: 'bg-sky-400 animate-pulse motion-reduce:animate-none',+ working: 'bg-[#9d8fff] animate-pulse motion-reduce:animate-none',queued: 'bg-zinc-950 border-2 border-zinc-400',cant_run: 'bg-zinc-600',available: 'bg-emerald-400',diff --git a/frontend/src/components/AvatarMood.tsx b/frontend/src/components/AvatarMood.tsxnew file mode 100644index 00000000..5ce02a82--- /dev/null+++ b/frontend/src/components/AvatarMood.tsx@@ -0,0 +1,107 @@+import React, { useCallback, useSyncExternalStore } from 'react';+import { moodOf, noticesOf, subscribeMood, type Mood } from '../kwantMood';++const noop = () => undefined;++/** A bot's mood now, re-rendering only when it (or its own turns) change. "idle" means nothing to show. */+export function useKwantMood(kwantId: string | undefined): Mood {+ const subscribe = useCallback((on: () => void) => (kwantId ? subscribeMood(kwantId, on) : noop), [kwantId]);+ return useSyncExternalStore(subscribe, () => moodOf(kwantId), () => moodOf(kwantId));+}++/** How many times the person has messaged this bot; the avatar blinks once per change. */+export function useKwantNotices(kwantId: string | undefined): number {+ const subscribe = useCallback((on: () => void) => (kwantId ? subscribeMood(kwantId, on) : noop), [kwantId]);+ return useSyncExternalStore(subscribe, () => noticesOf(kwantId), () => noticesOf(kwantId));+}++const INK = '#1b1033';++type Cell = [number, number];+const row = (y: number): Cell[] => [0, 1, 2, 3, 4].map((x) => [x, y] as Cell);++/**+ * Glyphs on their own 5x5 grid (spec.md §2), drawn on a 7x7 ink plate at whole-pixel cells, so they+ * stay crisp at 24-28 px. Coordinates are (x, y) in the 5x5 grid.+ */+export const MOOD_GLYPHS: Record<'thinking' | 'failed' | 'needs_you' | 'resting', { color: string; cells: Cell[] }> = {+ thinking: { color: '#e1d6ff', cells: [[0, 2], [2, 2], [4, 2]] },+ failed: { color: '#ff5d6c', cells: [[0, 0], [4, 0], [1, 1], [3, 1], [2, 2], [1, 3], [3, 3], [0, 4], [4, 4]] },+ // "!" rather than a raised hand: at 96 px the hand read as a crown (Ada's decision).+ needs_you: { color: '#ffb020', cells: [[2, 0], [2, 1], [2, 2], [2, 4]] },+ resting: { color: '#b8adff', cells: [...row(0), [3, 1], [2, 2], [1, 3], ...row(4)] },+};+/** Just finished: a sparkle that grows over three frames (0 / 60 / 120 ms), centre white. */+const SPARK = '#ffe066';+const F2: Cell[] = [[2, 1], [1, 2], [3, 2], [2, 3]];+const F3: Cell[] = [[2, 0], [0, 2], [4, 2], [2, 4]];++const cell = ([x, y]: Cell, fill: string, key: string, className?: string) => (+ <rect key={key} className={className} x={x + 1} y={y + 1} width={1} height={1} fill={fill} />+);++function glyph(mood: Mood): React.ReactNode[] {+ switch (mood) {+ case 'thinking':+ return MOOD_GLYPHS.thinking.cells.map((c, i) => cell(c, MOOD_GLYPHS.thinking.color, `d${i}`, `kw-mood-dot kw-mood-dot-${i}`));+ case 'finished':+ return [+ ...F3.map((c, i) => cell(c, SPARK, `f3${i}`, 'kw-mood-f3')),+ ...F2.map((c, i) => cell(c, SPARK, `f2${i}`, 'kw-mood-f2')),+ cell([2, 2], '#ffffff', 'f1'),+ ];+ case 'failed':+ case 'needs_you':+ case 'resting':+ return MOOD_GLYPHS[mood].cells.map((c, i) => cell(c, MOOD_GLYPHS[mood].color, `g${i}`));+ default:+ return [];+ }+}++/** Badge geometry for an avatar size: 2 px cells up to 40 px, 4 px from 64 px (96 px Bot home). */+export function moodBadge(size: number): { cellPx: number; px: number; offset: number; radius: number; cut: number } {+ const big = size >= 64;+ const cellPx = big ? 4 : 2;+ return { cellPx, px: cellPx * 7, offset: big ? -6 : -4, radius: big ? 4 : 2, cut: big ? 2 : 1 };+}++export interface AvatarMoodProps {+ mood: Mood;+ /** Pixel size of the avatar this sits on. */+ size: number;+}++/**+ * The mood badge for a pixel avatar: a 7x7 ink plate at its top-right with a 5x5 pixel glyph, cut out+ * of the surface by a 1-2 px ring (--kw-avatar-cut, default the sidebar #0e0a21). "working" and "idle"+ * draw nothing here (the avatar's own bob and violet ring cover working). Decorative: the words live on+ * the avatar's title and screen-reader label (moodLabel). ModernAvatar renders it when given a kwantId;+ * use this directly only on a custom avatar.+ */+export const AvatarMood: React.FC<AvatarMoodProps> = ({ mood, size }) => {+ const drawn = glyph(mood);+ if (!drawn.length) return null;+ const b = moodBadge(size);+ return (+ <svg+ viewBox="0 0 7 7"+ width={b.px}+ height={b.px}+ className={`kw-mood kw-mood-${mood} pointer-events-none absolute`}+ style={{+ top: b.offset,+ right: b.offset,+ borderRadius: b.radius,+ boxShadow: `0 0 0 ${b.cut}px var(--kw-avatar-cut, #0e0a21)`,+ shapeRendering: 'crispEdges',+ imageRendering: 'pixelated',+ }}+ aria-hidden="true"+ data-mood={mood}+ >+ <rect x={0} y={0} width={7} height={7} fill={INK} />+ {drawn}+ </svg>+ );+};diff --git a/frontend/src/components/BotHome.tsx b/frontend/src/components/BotHome.tsxnew file mode 100644index 00000000..d054d494--- /dev/null+++ b/frontend/src/components/BotHome.tsx@@ -0,0 +1,149 @@+import React from 'react';+import { ArrowRight, AtSign, Clock, Lightbulb, ListChecks, MessageSquareText, Sparkles, Wand2 } from 'lucide-react';+import { ModernAvatar } from './ModernAvatar';+import { useKwantMood } from './AvatarMood';+import { NewTag } from './NewTag';+import { markNewSeen } from '../whatsNew';+import { ChatHome, ago, goodAt, starterCards } from '../botHome';++const ICONS = [Sparkles, ListChecks, Lightbulb, Wand2];++interface BotHomeProps {+ home: ChatHome;+ spaceName?: string;+ /** Every bot in the space, for #general's row of faces. */+ team?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;+ prompts: string[];+ /** false while no account can run a turn: the cards say so and stay still. */+ canRun?: boolean | null;+ onPick: (prompt: string) => void;+}++/**+ * The empty chat. A bot's own chat opens on a big living avatar, what it's good at and four things to+ * try; #general opens on "Laya picks" with the team's faces. Everything comes from what the client+ * already has. It waits 220ms before showing (.kw-home) so a chat still loading its messages never flashes it.+ */+export const BotHome: React.FC<BotHomeProps> = ({ home, spaceName, team = [], prompts, canRun, onPick }) => {+ const bot = home.kind === 'bot' ? home.bot : undefined;+ const cards = starterCards(prompts);+ const chips = bot ? goodAt(bot) : [];+ const shown = team.slice(0, 8);+ const extra = team.length - shown.length;+ // Breathing is the working signal: only a working bot's glow moves (violet, like its dot).+ const working = useKwantMood(bot?.id) === 'working';++ return (+ <section className="kw-home mx-auto flex w-full max-w-3xl flex-col items-center px-1 pb-6 pt-4 text-center sm:pt-10" aria-label={bot ? `${bot.name}, home` : 'Start a conversation'} data-bot-home={home.kind}>+ {/* The hero: a soft glow behind the floating avatar. Static at .35; it breathes in violet only while the bot works. */}+ <div className="relative mb-4 flex h-36 w-36 items-center justify-center sm:h-44 sm:w-44">+ <span+ className={`absolute inset-0 rounded-full blur-2xl ${working ? 'kw-glow bg-[#9d8fff] opacity-60 motion-reduce:opacity-50' : 'bg-accent-gradient opacity-35'}`}+ data-glow={working ? 'working' : 'still'}+ aria-hidden="true"+ />+ {bot ? (+ // 96 px with 4 px mood cells (spec.md §2); the mood badge is cut out of the main surface+ <span className="kw-float relative" style={{ '--kw-avatar-cut': 'var(--kw-surface-main, #120e26)' } as React.CSSProperties}>+ <ModernAvatar role={bot.avatar_sprite} name={bot.name} size={96} kwantId={bot.id} className="rounded-2xl shadow-raised" />+ </span>+ ) : (+ <span className="relative flex -space-x-5" aria-hidden="true">+ {shown.slice(0, 3).map((k, i) => (+ <span key={k.id} className={`kw-float rounded-2xl ring-4 ring-[var(--kw-surface-main)] ${i === 1 ? 'z-10 scale-110' : ''}`} style={{ animationDelay: `${i * 300}ms` }}>+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={72} kwantId={k.id} />+ </span>+ ))}+ {shown.length === 0 && <Sparkles size={56} className="text-sky-200" />}+ </span>+ )}+ </div>++ <h2 className="text-display font-bold text-zinc-50">{bot ? bot.name : spaceName ? `Ask anything in ${spaceName}` : 'Ask anything'}</h2>+ <p className="mt-1 max-w-md text-body text-zinc-300">+ {bot ? bot.title : 'Laya picks who answers. Or type @ and a name to choose a bot yourself.'}+ </p>++ {bot ? (+ chips.length > 0 && (+ <div className="mt-4 flex max-w-xl flex-wrap items-center justify-center gap-1.5" role="list" aria-label={`${bot.name} is good at`}>+ <span className="mr-0.5 text-meta font-medium text-zinc-400">Good at</span>+ {chips.map((c) => (+ <span key={c} role="listitem" className="kw-chip kw-chip-accent">+ {c}+ </span>+ ))}+ </div>+ )+ ) : (+ shown.length > 0 && (+ <div className="mt-4 flex flex-wrap items-center justify-center gap-1.5" role="list" aria-label="Bots Laya can pick from">+ {shown.map((k) => (+ <span key={k.id} role="listitem" className="kw-chip pl-1" title={k.title}>+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={18} />+ {k.name}+ </span>+ ))}+ {extra > 0 && <span role="listitem" className="kw-chip">+{extra} more</span>}+ </div>+ )+ )}++ {cards.length > 0 && (+ <div className="mt-8 w-full text-left">+ <p className="mb-2 flex items-center gap-1.5 text-meta font-semibold uppercase tracking-wider text-zinc-400">+ <MessageSquareText size={13} aria-hidden="true" /> Try asking <NewTag id="starters" className="ml-1.5 normal-case tracking-normal" />+ </p>+ <div className="kw-stagger grid grid-cols-1 gap-2.5 sm:grid-cols-2" role="group" aria-label="Suggested prompts">+ {cards.map((prompt, i) => {+ const Icon = ICONS[i % ICONS.length];+ return (+ <button+ key={prompt}+ type="button"+ style={{ '--i': i } as React.CSSProperties}+ onClick={() => {+ markNewSeen('starters');+ onPick(prompt);+ }}+ disabled={canRun === false}+ title={canRun === false ? 'Add an account first' : 'Fills the message box so you can edit it before sending'}+ className="kw-card-interactive group flex min-h-[72px] items-start gap-3 p-3.5"+ >+ <span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-accent-soft text-sky-200">+ <Icon size={16} aria-hidden="true" />+ </span>+ <span className="min-w-0 flex-1 text-body font-medium leading-snug text-zinc-100">{prompt}</span>+ <ArrowRight size={16} className="mt-1 shrink-0 text-zinc-500 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-sky-300 motion-reduce:transition-none" aria-hidden="true" />+ </button>+ );+ })}+ </div>+ </div>+ )}++ {bot && home.recent && home.recent.length > 0 && (+ <div className="mt-6 w-full text-left">+ <p className="mb-2 flex items-center gap-1.5 text-meta font-semibold uppercase tracking-wider text-zinc-400">+ <Clock size={13} aria-hidden="true" /> Pick up where you left off+ </p>+ <ul className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {home.recent.map((r) => (+ <li key={r.id}>+ <button type="button" onClick={() => home.onOpenRecent?.(r.id)} className="kw-card-interactive flex w-full items-center justify-between gap-3 px-3.5 py-2.5">+ <span className="min-w-0 truncate text-body text-zinc-100">{r.title}</span>+ <span className="shrink-0 text-meta text-zinc-400">{ago(r.updated_at)}</span>+ </button>+ </li>+ ))}+ </ul>+ </div>+ )}++ <p className="mt-8 flex items-center gap-1.5 text-meta text-zinc-400">+ <AtSign size={13} aria-hidden="true" />+ {home.kind === 'general' ? 'Type @ to ask a specific bot instead of letting Laya pick.' : 'Type @ to bring another bot into the conversation.'}+ </p>+ </section>+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 5159f9e1..f24adc0b 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1,6 +1,11 @@import React, { useState, useRef, useEffect, useMemo } from 'react';-import { ArrowDown, ArrowUp, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, Loader2 } from 'lucide-react';+import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, Loader2 } 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 { markNewSeen } from '../whatsNew';import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';import { MentionPopover, MentionItem } from './MentionPopover';import { MarkdownRenderer } from './MarkdownRenderer';@@ -166,6 +171,8 @@ export interface ChatViewProps {teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;/** Prompts offered above an empty chat, made from who is in it; none hides the bar. */suggestions?: string[];+ /** What kind of chat this is, for the empty-chat home and the composer's "who answers" pill. */+ home?: ChatHome;discussionState?: DiscussionState;routingState?: RoutingState | null;onCancelDiscussion?: () => void;@@ -491,6 +498,7 @@ export const ChatView: React.FC<ChatViewProps> = ({kwants: kwantsProp,teams: teamsProp,suggestions = [],+ home,discussionState,routingState,onCancelDiscussion,@@ -607,6 +615,7 @@ export const ChatView: React.FC<ChatViewProps> = ({id: k.id,name: k.name,title: k.title,+ goodAt: goodAt(k),avatar_sprite: k.avatar_sprite,})),...activeTeams.map((t) => ({@@ -646,7 +655,8 @@ export const ChatView: React.FC<ChatViewProps> = ({const q = mentionQuery.toLowerCase();return (item.name.toLowerCase().includes(q) ||- (item.title && item.title.toLowerCase().includes(q))+ (item.title && item.title.toLowerCase().includes(q)) ||+ (item.goodAt?.some((g) => g.toLowerCase().includes(q)) ?? false));}): [];@@ -660,12 +670,17 @@ export const ChatView: React.FC<ChatViewProps> = ({useEffect(() => {setSelectedIndex(0);}, [mentionQuery]);+ // The picker opening by any route (typing "@" or the button) counts as using the new mention: "New" goes.+ useEffect(() => {+ if (isMentionOpen) markNewSeen('mention');+ }, [isMentionOpen]);const handleSelectMention = (item: MentionItem) => {if (mentionStartIndex < 0) return;const cursorPos = textareaRef.current?.selectionStart ?? inputVal.length;const textBefore = inputVal.slice(0, mentionStartIndex);const textAfter = inputVal.slice(cursorPos);+ markNewSeen('mention');const mentionText = `@${item.name} `;const newVal = `${textBefore}${mentionText}${textAfter}`;setInputVal(newVal);@@ -871,6 +886,8 @@ export const ChatView: React.FC<ChatViewProps> = ({playSfx('click');stickRef.current = true;onSendMessage(inputVal.trim(), readyAttachments(uploads));+ // The bots this goes to blink once, so you see who received it.+ recipientsOf(inputVal, activeKwants, home?.kind === 'bot' ? home.bot?.id : undefined).forEach(moodNoticed);setInputVal('');setUploads([]);setUploadNote(null);@@ -1202,10 +1219,30 @@ export const ChatView: React.FC<ChatViewProps> = ({);};+ // The empty chat shows the bot home (a bot's own chat, or #general) instead of a bare pane and a row of chips+ const showHome =+ !!home && (home.kind === 'bot' || home.kind === 'general') && !welcome && messages.length === 0 && !isStreaming && !queued && !deciding && pendingApprovals.length === 0;+ // Who answers what's typed: the chat decides, an @mention overrides+ const target = answerTarget({+ kind: home?.kind ?? 'channel',+ text: inputVal,+ botName: home?.bot?.name ?? title,+ teamName,+ names: activeKwants.map((k) => k.name).concat(activeTeams.map((t) => t.name)),+ });+ const insertAt = () => {+ playSfx('click');+ const el = textareaRef.current;+ const next = inputVal && !/\s$/.test(inputVal) ? `${inputVal} @` : `${inputVal}@`;+ setInputVal(next);+ el?.focus();+ requestAnimationFrame(() => checkMention(next, next.length));+ };+return (- <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">+ <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-zinc-800/80 px-2 sm:px-6 gap-2 flex items-center justify-between bg-zinc-900/30 backdrop-blur-sm select-none">+ <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">{onBack && (<buttontype="button"@@ -1216,12 +1253,15 @@ export const ChatView: React.FC<ChatViewProps> = ({<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" />+ )}<div className="min-w-0 flex-1">- <h2 className="text-sm font-semibold text-zinc-100 flex items-center gap-2 min-w-0">+ <h2 className="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-[11px] text-zinc-400 truncate max-w-lg mt-0.5">{subtitle}</p>+ <p className="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">@@ -1261,7 +1301,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<buttontype="button"onClick={onManageTeam}- className="kw-head-btn flex items-center justify-center gap-1.5 max-sm:min-w-11 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"+ className="kw-head-btn flex items-center justify-center gap-1.5 max-sm:min-w-11 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] hover:text-zinc-50 border border-hairline-strong transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"title="Team members and settings"aria-label="Manage team">@@ -1276,7 +1316,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<buttontype="button"onClick={onEditInstructions}- className="kw-head-btn flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"+ className="kw-head-btn flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] hover:text-zinc-50 border border-hairline-strong transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"title="Pin instructions every bot reads in this channel"aria-label="Pin instructions">@@ -1289,7 +1329,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<buttontype="button"onClick={onEditKwant}- className="kw-head-btn flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"+ className="kw-head-btn flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] hover:text-zinc-50 border border-hairline-strong transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"title={`Edit ${title}'s name, avatar, model and persona`}aria-label={`Edit ${title}`}>@@ -1316,10 +1356,10 @@ export const ChatView: React.FC<ChatViewProps> = ({playSfx('click');toggleVm();}}- className={`kw-head-btn flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-full text-xs font-medium transition-colors border shadow-sm cursor-pointer ${+ className={`kw-head-btn flex items-center justify-center gap-1.5 max-md:min-w-11 px-2.5 py-1 rounded-full text-xs font-medium transition-colors border cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${vmOpen- ? 'text-sky-300 bg-sky-500/20 border-sky-500/40'- : 'text-zinc-300 bg-zinc-900 hover:bg-zinc-800 border-zinc-700/60 hover:text-zinc-100'+ ? 'text-sky-200 bg-sky-400/15 border-sky-300/40'+ : 'text-zinc-200 bg-white/[0.04] hover:bg-white/[0.09] border-hairline-strong hover:text-zinc-50'}`}title="Show or hide the bot's browser"aria-label="Bot browser"@@ -1393,6 +1433,11 @@ export const ChatView: React.FC<ChatViewProps> = ({aria-busy={isStreaming}>{welcome && messages.length === 0 && welcome}+ {showHome && home && (+ <div className="flex min-h-full items-center justify-center">+ <BotHome home={home} spaceName={spaceName} team={activeKwants} prompts={suggestions} canRun={canRun} onPick={handlePromptSuggestion} />+ </div>+ )}{groupDiscussionThreads(messages).map((item) => {if (item.kind === 'message') return renderMessage(item.message);const threadKey = `thread:${item.id}`;@@ -1522,7 +1567,7 @@ export const ChatView: React.FC<ChatViewProps> = ({</div>{/* Suggested prompts for who is in this chat: one swipeable row on phones */}- {messages.length <= 1 && suggestions.length > 0 && (+ {messages.length <= 1 && suggestions.length > 0 && !showHome && (<ScrollRowclassName="kw-scroll-row px-3 sm:px-6 py-2 flex flex-nowrap sm:flex-wrap items-center gap-2 overflow-x-auto sm:overflow-visible select-none"role="group"@@ -1545,7 +1590,7 @@ 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-zinc-800/80 bg-zinc-900/30">+ <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">{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>@@ -1611,8 +1656,8 @@ 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-2 bg-zinc-900 border rounded-2xl p-2 shadow-sm transition-all ${- dragOver ? 'border-sky-500/70 bg-sky-950/30' : 'border-zinc-800 focus-within:border-zinc-700'+ 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'}`}>{dragOver && (@@ -1650,6 +1695,11 @@ export const ChatView: React.FC<ChatViewProps> = ({<textarearef={textareaRef}data-composer+ role="combobox"+ aria-expanded={isMentionOpen}+ aria-controls={isMentionOpen ? 'kw-mention-list' : undefined}+ aria-activedescendant={isMentionOpen ? `kw-mention-${safeSelectedIndex}` : undefined}+ aria-autocomplete="list"rows={1}value={inputVal}onChange={(e) => {@@ -1679,7 +1729,7 @@ export const ChatView: React.FC<ChatViewProps> = ({placeholder={spaceName && !narrow ? `Message ${title} in ${spaceName}` : `Message ${title}`}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-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"+ 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"/><inputref={fileInputRef}@@ -1698,16 +1748,38 @@ export const ChatView: React.FC<ChatViewProps> = ({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-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0 text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ 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"+ >+ <Paperclip size={17} aria-hidden="true" />+ </button>+ <button+ type="button"+ onClick={() => {+ markNewSeen('mention');+ insertAt();+ }}+ 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">- <Paperclip size={16} aria-hidden="true" />+ <AtSign size={17} aria-hidden="true" /></button>+ {/* "New" sits just above the field's top edge, over the "@" button: never on or inside the border.+ Each button after "@" (stop, send) is 44px on phones / 36px from sm, plus a 6px gap; 9px is the+ form's border + padding. Hidden while the mention picker is open, so it never peeks under it. */}+ <NewTag+ id="mention"+ className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''}`}+ style={{+ right: `calc(11px + var(--kw-cbtn-step) * ${(isStreaming ? 1 : 0) + (isStreaming && (discussionState?.inProgress || !canSend) ? 0 : 1)})`,+ }}+ />{isStreaming && (<buttontype="button"onClick={onCancelDiscussion}- className="w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 bg-red-500/20 hover:bg-red-500/30 text-red-400 border border-red-500/30 shadow-sm cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-500"+ className="w-11 h-11 sm:w-9 sm:h-9 rounded-xl flex items-center justify-center transition-colors flex-shrink-0 bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-400/30 cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-rose-400"title={discussionState?.inProgress ? 'Stop Discussion' : 'Stop generation'}aria-label={discussionState?.inProgress ? 'Stop discussion' : 'Stop the reply'}>@@ -1720,16 +1792,34 @@ export const ChatView: React.FC<ChatViewProps> = ({aria-label={stillUploading ? 'Send (waiting for uploads)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}title={stillUploading ? 'Waiting for uploads to finish' : undefined}disabled={!canSend}- className={`w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${+ 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 ${canSend- ? 'bg-sky-500 text-white hover:bg-sky-400 shadow-sm'- : 'bg-zinc-800 text-zinc-500 cursor-not-allowed'+ ? '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'}`}>- <ArrowUp size={16} strokeWidth={2.4} />+ <ArrowUp size={17} strokeWidth={2.4} aria-hidden="true" /></button>)}</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+ </span>+ </span>+ </div></div></div>diff --git a/frontend/src/components/MentionPopover.tsx b/frontend/src/components/MentionPopover.tsxindex 6a765656..9f080996 100644--- a/frontend/src/components/MentionPopover.tsx+++ b/frontend/src/components/MentionPopover.tsx@@ -7,6 +7,8 @@ export interface MentionItem {id: string;name: string;title?: string;+ /** One-line "good at" phrases (same source as the bot home chips); shown instead of the title. */+ goodAt?: string[];avatar_sprite?: string;memberCount?: number;}@@ -40,7 +42,10 @@ export const MentionPopover: React.FC<MentionPopoverProps> = ({return (<div- className="absolute bottom-full left-0 mb-2 bg-zinc-900 border border-zinc-800 rounded-xl shadow-2xl p-1.5 min-w-[240px] max-w-sm max-h-64 overflow-y-auto z-50 backdrop-blur-md"+ role="listbox"+ aria-label="Mention a bot"+ id="kw-mention-list"+ className="kw-fade-in absolute bottom-full left-0 right-0 sm:right-auto mb-2 bg-surface-overlay border border-hairline-strong rounded-xl shadow-raised p-1.5 min-w-[260px] sm:w-[min(22rem,calc(100vw-2rem))] max-h-72 overflow-y-auto z-50"style={position? { top: `${position.top}px`, left: `${position.left}px`, bottom: 'auto' }@@ -56,30 +61,34 @@ export const MentionPopover: React.FC<MentionPopoverProps> = ({return (<React.Fragment key={`${item.type}-${item.id}`}>{showSectionHeader && (- <div className="text-[10px] font-semibold text-zinc-500 uppercase tracking-wider px-2.5 py-1 select-none">+ <div className="text-2xs font-semibold text-zinc-400 uppercase tracking-wider px-2.5 py-1 select-none">{item.type === 'kwant' ? 'Bots' : 'Teams'}</div>)}<buttontype="button"+ role="option"+ id={`kw-mention-${index}`}+ aria-selected={isSelected}ref={(el) => (itemRefs.current[index] = el)}onClick={() => onSelect(item)}onMouseDown={(e) => {// Prevent input blur before click event firese.preventDefault();}}- className={`w-full flex items-center justify-between gap-3 px-2.5 py-1.5 rounded-lg text-left transition-colors text-xs ${+ className={`w-full flex items-center justify-between gap-3 px-2.5 py-2 min-h-[44px] sm:min-h-0 sm:py-1.5 rounded-lg text-left transition-colors text-xs focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${isSelected- ? 'bg-zinc-800 text-zinc-100'- : 'text-zinc-300 hover:bg-zinc-800/60 hover:text-zinc-100'+ ? 'bg-white/[0.1] text-zinc-50 ring-1 ring-inset ring-sky-400/40'+ : 'text-zinc-200 hover:bg-white/[0.06] hover:text-zinc-50'}`}><div className="flex items-center gap-2.5 min-w-0">{item.type === 'kwant' ? (<ModernAvatar- role={item.title || item.name}+ role={item.avatar_sprite || item.title || item.name}name={item.name}- size={24}+ size={32}+ kwantId={item.id}/>) : (<div className="w-6 h-6 rounded-lg bg-sky-500/10 border border-sky-500/20 text-sky-400 flex items-center justify-center flex-shrink-0">@@ -88,12 +97,12 @@ export const MentionPopover: React.FC<MentionPopoverProps> = ({)}<div className="min-w-0 truncate">- <div className="font-medium truncate text-zinc-100">+ <div className="font-semibold text-body truncate text-zinc-50">@{item.name}</div>- {item.title && (- <div className="text-[10px] text-zinc-400 truncate">- {item.title}+ {(item.goodAt?.length || item.title) && (+ <div className="text-meta text-zinc-300 truncate" data-good-at>+ {item.goodAt?.length ? `Good at ${item.goodAt.slice(0, 3).join(' · ')}` : item.title}</div>)}</div>diff --git a/frontend/src/components/ModernAvatar.tsx b/frontend/src/components/ModernAvatar.tsxindex 6e1d1a01..9512a8cf 100644--- a/frontend/src/components/ModernAvatar.tsx+++ b/frontend/src/components/ModernAvatar.tsx@@ -1,5 +1,7 @@import React, { useCallback, useSyncExternalStore } from 'react';import { isKwantWorking, subscribeKwant } from '../kwantActivity';+import { AvatarMood, useKwantMood, useKwantNotices } from './AvatarMood';+import { moodLabel, restingUntilOf } from '../kwantMood';import { STATUS_DOT, STATUS_PRIORITY, statusText, type BotStatus } from '../botStatus';interface ModernAvatarProps {@@ -336,7 +338,11 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({const working = useKwantWorking(kwantId);// Never green (or idle grey) while a turn runs: the turn stream wins over a stale status.const shown = status && working && STATUS_PRIORITY.indexOf(status) > STATUS_PRIORITY.indexOf('working') ? 'working' : status;- const label = shown ? statusText(name, shown) : name ? (working ? `${name} is working…` : name) : undefined;+ // The mood (thinking, finished, failed, needs you, resting) adds a pixel mark and its own words.+ const mood = useKwantMood(kwantId);+ const notices = useKwantNotices(kwantId);+ const moodText = moodLabel(mood, name, restingUntilOf(kwantId));+ const label = moodText ?? (shown ? statusText(name, shown) : name ? (working ? `${name} is working…` : name) : undefined);const creature = pickCreature(role, name);// At tiny sizes the frame would dominate, so zoom in on the creature aloneconst framed = size > 20;@@ -345,11 +351,12 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({return (<div- className={`kw-avatar relative inline-flex flex-shrink-0 select-none ${working ? 'kw-avatar-working' : ''} ${className}`}+ className={`kw-avatar relative inline-flex flex-shrink-0 select-none ${working ? 'kw-avatar-working' : ''} ${mood === 'resting' ? 'kw-avatar-resting' : ''} ${className}`}style={{ width: size, height: size }}title={label}data-working={working || undefined}data-status={shown}+ data-mood={mood === 'idle' ? undefined : mood}>{working && <span className="kw-avatar-ring" aria-hidden="true" />}<svg@@ -368,10 +375,19 @@ export const ModernAvatar: React.FC<ModernAvatarProps> = ({<g transform={compact ? 'translate(13 13.2) scale(1.2) translate(-13 -12)' : undefined}><g className="kw-avatar-body">{renderCreature(creature).filter((r) => framed && !compact || r.key !== 'shadow')}+ {/* One blink when the person sends this bot a message: the eyes close for 160 ms. */}+ {notices > 0 && (+ <g key={notices} className="kw-avatar-blink">+ {px(10, 10, 2, 3, creature.body, 'bl1')}+ {px(14, 10, 2, 3, creature.body, 'bl2')}+ {px(10, 12, 2, 1, creature.shade, 'bl3')}+ {px(14, 12, 2, 1, creature.shade, 'bl4')}+ </g>+ )}</g></g></svg>- {working && <span className="kw-avatar-pip" aria-hidden="true" />}+ <AvatarMood mood={mood} size={size} />{shown && (<><span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full ring-2 ring-zinc-950 ${STATUS_DOT[shown]}`} aria-hidden="true" />diff --git a/frontend/src/components/NewTag.tsx b/frontend/src/components/NewTag.tsxnew file mode 100644index 00000000..88d0fa30--- /dev/null+++ b/frontend/src/components/NewTag.tsx@@ -0,0 +1,36 @@+import React, { useEffect, useState, useSyncExternalStore } from 'react';+import { isNewThing, subscribeNew, type NewId } from '../whatsNew';+import { Sticker } from './Sticker';++const FADE_MS = 160;++/**+ * A small ink "New" sticker for something 0.6.9 changed; gone for good once the person has used it.+ * When it goes it fades to 0 over 160 ms, then unmounts (at once under reduced motion).+ */+export const NewTag: React.FC<{ id: NewId; className?: string; style?: React.CSSProperties }> = ({ id, className = '', style }) => {+ const show = useSyncExternalStore(subscribeNew, () => isNewThing(id), () => false);+ const [leaving, setLeaving] = useState(false);+ const [wasShown, setWasShown] = useState(show);+ if (show && !wasShown) setWasShown(true);+ useEffect(() => {+ if (show || !wasShown) return;+ const reduce = typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;+ if (reduce) {+ setWasShown(false);+ return;+ }+ setLeaving(true);+ const t = window.setTimeout(() => {+ setLeaving(false);+ setWasShown(false);+ }, FADE_MS);+ return () => window.clearTimeout(t);+ }, [show, wasShown]);+ if (!show && !wasShown) return null;+ return (+ <span className={`kw-new-tag pointer-events-none ${className}`} data-new-tag={id} data-leaving={leaving || !show ? '' : undefined} style={style} aria-hidden={!show || undefined}>+ <Sticker tone="ink" size="sm" tilt={2}>New</Sticker>+ </span>+ );+};diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 5aa3392c..a7abd4d3 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useState } from 'react';-import { Hash, Plus, CheckCircle2, KeyRound, Loader2, Users, ChevronDown, Settings, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, ShieldOff, Split, Hand, MoreHorizontal, UserMinus, MessageSquare, KanbanSquare } from 'lucide-react';+import { Hash, Plus, CheckCircle2, ShieldCheck, KeyRound, Loader2, Users, ChevronDown, Settings, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, ShieldOff, Split, Hand, MoreHorizontal, UserMinus, MessageSquare, KanbanSquare } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import { badgeText } from '../away';@@ -124,9 +124,13 @@ export interface SidebarProps {engines?: EnginesApi;}+/** A bot's own approvals setting differs from its space's: the only time its row says anything about it. */+export const approvalsDiffers = (k: { approvals_effective?: string | null }, spaceApprovals: string | undefined): boolean =>+ !!k.approvals_effective && !!spaceApprovals && k.approvals_effective !== spaceApprovals;+const navRow = (active: boolean) =>- `w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${- active ? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50' : 'text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800/50 border border-transparent'+ `w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-xl text-body font-medium transition-colors text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${+ active ? 'bg-accent-soft text-zinc-50 shadow-card border border-sky-300/25' : 'text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.05] border border-transparent'}`;export const memberIdsOf = (t: Team): string[] =>@@ -333,19 +337,20 @@ export const Sidebar: React.FC<SidebarProps> = ({const offLine = spaceOffLine(space.approvals, kwants);// Phones: section titles stay pinned while their list scrolls, so they are never cut off- const sectionHead = `px-2 py-1 flex items-center justify-between text-[11px] font-semibold text-zinc-500 uppercase tracking-wider${+ const sectionHead = `px-2 py-1 min-w-0 flex items-center justify-between gap-2 text-2xs font-semibold text-zinc-400 uppercase tracking-wider${phone ? ' kw-sticky-head sticky top-0 z-10' : ''}`;- // Phones: "New …" is a plain + icon (44px to tap) instead of a boxed button- const phoneAdd = (label: string, onClick: () => void) => (+ // Phones: "+ Team" / "+ Bot" as plain text buttons, at least 44x44 to tap+ const phoneAdd = (word: string, label: string, onClick: () => void) => (<buttontype="button"onClick={onClick}aria-label={label}title={label}- className="-mr-1 rounded-full text-sky-400 hover:text-sky-300 hover:bg-sky-500/10 active:bg-sky-500/15 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ className="-mr-1 min-h-11 px-3 shrink-0 whitespace-nowrap inline-flex items-center gap-1 rounded-full text-meta font-medium normal-case tracking-normal text-sky-400 hover:text-sky-300 hover:bg-sky-500/10 active:bg-sky-500/15 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">- <Plus size={18} aria-hidden="true" />+ <Plus size={14} aria-hidden="true" />+ <span>{word}</span></button>);@@ -366,8 +371,8 @@ export const Sidebar: React.FC<SidebarProps> = ({// Only the row's own Enter: Enter on its ✕ or Edit is for that button, not for opening the chat.onKeyDown={(e) => e.key === 'Enter' && e.target === e.currentTarget && onSelectKwant(k)}data-bot-row={k.id}- className={`group/fleet relative w-full flex items-center gap-2.5 px-2 py-1.5 rounded-xl text-left cursor-pointer transition-all ${- active ? 'bg-zinc-800/90 text-zinc-100 shadow-sm border border-zinc-700/60' : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/40 border border-transparent'+ className={`group/fleet relative w-full flex items-center gap-2.5 px-2 py-1.5 rounded-xl text-left cursor-pointer transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 ${+ active ? 'bg-accent-soft text-zinc-50 shadow-card border border-sky-300/25' : 'text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.05] border border-transparent'}`}><span className="shrink-0" title={status === 'cant_run' ? "Can't run yet: no account works here" : statusText(k.name, status)}>@@ -377,25 +382,34 @@ export const Sidebar: React.FC<SidebarProps> = ({{/* Desktop: on hover or focus the name makes room for Edit and Remove instead of sitting under them */}<div data-bot-name-line className={`flex items-start gap-1 ${!phone && hasRowActions ? 'group-hover/fleet:pr-9 group-focus-within/fleet:pr-9' : ''}`}>{/* The full name, on up to two lines (QA a); what it runs on is in the tooltip */}- <span data-bot-name className="min-w-0 text-xs font-semibold leading-4 text-zinc-200 line-clamp-2 [overflow-wrap:anywhere]" title={`${k.name} · ${engineTip(k.preferred_model)}`}>+ <span data-bot-name className="min-w-0 text-body font-semibold leading-5 text-zinc-100 line-clamp-2 [overflow-wrap:anywhere]" title={`${k.name} · ${engineTip(k.preferred_model)}`}>{k.name}</span>{isLead && (- <span className="shrink-0 flex items-center gap-0.5 h-4 text-[9px] uppercase tracking-wide text-amber-300/90" title={`Leads @${team!.name}`}>+ <span className="shrink-0 flex items-center gap-0.5 h-5 text-2xs uppercase tracking-wide text-amber-300" title={`Leads @${team!.name}`}><Crown size={10} aria-hidden="true" />lead</span>)}{needsYou[k.id] > 0 && (<span- className="shrink-0 inline-flex items-center gap-1 px-1.5 py-px rounded-full text-[10px] font-medium bg-amber-400/15 text-amber-200 border border-amber-400/30"+ className="shrink-0 inline-flex items-center gap-1 px-1.5 py-px rounded-full text-2xs font-medium bg-amber-300/10 text-warn border border-amber-300/30"title={`${k.name} needs you in the browser`}><Hand size={10} aria-hidden="true" />Needs you{needsYou[k.id] > 1 ? ` · ${needsYou[k.id]}` : ''}</span>)}- {approvalsOff(k) && <ApprovalsOffBadge compact title={`${k.name} acts without asking. Payments still ask you.`} />}+ {/* The space header already says when approvals are off for everyone: a bot only gets its own mark when it differs */}+ {approvalsDiffers(k, space.approvals) &&+ (approvalsOff(k) ? (+ <ApprovalsOffBadge compact title={`${k.name} acts without asking. Payments still ask you.`} />+ ) : (+ <span className="shrink-0 inline-flex items-center text-teal-300" title={`${k.name} still asks before acting, unlike the rest of ${space.name}.`}>+ <ShieldCheck size={12} aria-hidden="true" />+ <span className="sr-only">Asks before acting</span>+ </span>+ ))}{/* Over the row's right edge, so a long name gets the full width until you hover */}{!phone && (<span className="absolute right-1.5 top-1.5 flex items-center gap-0.5 rounded-md bg-zinc-800/95 opacity-0 group-hover/fleet:opacity-100 group-focus-within/fleet:opacity-100 empty:hidden">@@ -434,11 +448,12 @@ export const Sidebar: React.FC<SidebarProps> = ({)}</div>{busyKwants[k.id] ? (- <p className="text-[11px] text-sky-300 truncate" title={busyKwants[k.id]}>- {busyKwants[k.id]}+ <p className={`flex items-center gap-1.5 text-meta truncate ${status === 'needs_you' ? 'text-warn' : status === 'queued' ? 'text-zinc-300' : 'text-[#b8adff]'}`} title={busyKwants[k.id]} data-bot-busy>+ <span className={`kw-status-dot !h-1.5 !w-1.5 ${status === 'needs_you' ? 'kw-status-warn' : status === 'queued' ? 'kw-status-idle' : 'bg-[#9d8fff] kw-pulse'}`} aria-hidden="true" />+ <span className="truncate">{busyKwants[k.id]}</span></p>) : (- <p className="text-[11px] text-zinc-500 truncate">{k.title}</p>+ <p className="text-meta text-zinc-400 truncate">{k.title}</p>)}</div>{/* Phones: one button at the row's end; in a team it opens the member's actions */}@@ -489,8 +504,8 @@ export const Sidebar: React.FC<SidebarProps> = ({onKeyDown={(e) => e.key === 'Enter' && e.target === e.currentTarget && onSelectTeam(t)}data-team-row={t.id}title={`Open the @${t.name} team chat`}- className={`w-full flex items-center justify-between px-1.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left group cursor-pointer ${- active ? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50' : 'text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800/50 border border-transparent'+ className={`w-full flex items-center justify-between px-1.5 py-1.5 rounded-lg text-body font-medium transition-colors text-left group cursor-pointer ${+ active ? 'bg-accent-soft text-zinc-50 shadow-card border border-sky-300/25' : 'text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.05] border border-transparent'}`}><div className="flex items-center gap-1.5 min-w-0">@@ -513,7 +528,7 @@ export const Sidebar: React.FC<SidebarProps> = ({</div><div className="flex items-center gap-1 flex-shrink-0">{(!expanded || !withMembers) && (- <span className="text-[10px] px-1.5 py-0.5 rounded-full tabular-nums bg-zinc-800/80 text-zinc-400 border border-zinc-800" title={`${count} ${count === 1 ? 'member' : 'members'}`}>+ <span className="text-2xs px-1.5 py-0.5 rounded-full tabular-nums bg-white/[0.05] text-zinc-300 border border-hairline" title={`${count} ${count === 1 ? 'member' : 'members'}`}>{count}</span>)}@@ -598,18 +613,20 @@ export const Sidebar: React.FC<SidebarProps> = ({};const groups = botGroups(teams, kwants);- const headButton = (label: string, title: string, onClick: () => void) =>+ // "+ Team", "+ Bot", "+ Channel": the + says new and the heading says what kind; the full phrase is the label.+ const headButton = (word: string, label: string, title: string, onClick: () => void) =>phone ? (- phoneAdd(title, onClick)+ phoneAdd(word, label, onClick)) : (<buttontype="button"onClick={onClick}- className="flex items-center gap-1 text-[10px] font-medium text-sky-400 hover:text-sky-300 hover:bg-sky-500/10 px-1.5 py-0.5 rounded border border-sky-500/20 transition-all normal-case tracking-normal focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ aria-label={label}+ className="shrink-0 whitespace-nowrap flex items-center gap-1 text-2xs font-medium text-sky-300 hover:text-sky-200 hover:bg-sky-500/10 px-2 py-0.5 rounded-full border border-sky-400/25 transition-all normal-case tracking-normal focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"title={title}>- <Plus size={11} />- <span>{label}</span>+ <Plus size={11} aria-hidden="true" />+ <span>{word}</span></button>);@@ -617,7 +634,7 @@ export const Sidebar: React.FC<SidebarProps> = ({<asideref={asideRef}aria-label={`${space.name} chats and kwant bots`}- className={`${phone ? 'w-full flex-1 min-h-0' : 'w-64 h-full border-r border-zinc-800/80'} bg-zinc-900/40 flex flex-col select-none flex-shrink-0`}+ className={`${phone ? 'w-full flex-1 min-h-0' : 'w-64 h-full border-r border-hairline'} bg-surface-side flex flex-col select-none flex-shrink-0`}>{/* The open space. Desktop switches spaces on the rail, so this is its name and settings;phones have no rail, so here it is their one switcher. */}@@ -636,8 +653,8 @@ export const Sidebar: React.FC<SidebarProps> = ({><SpaceTile space={space} size={32} /><span className="flex-1 min-w-0">- <span className="block text-sm font-semibold text-zinc-100 truncate">{space.name}</span>- <span className="block text-[11px] text-zinc-500 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>+ <span className="block text-body font-semibold text-zinc-50 truncate">{space.name}</span>+ <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span></span><ChevronDown size={14} className={`shrink-0 text-zinc-500 transition-transform ${switcherOpen ? 'rotate-180' : ''}`} aria-hidden="true" /></button>@@ -645,8 +662,8 @@ export const Sidebar: React.FC<SidebarProps> = ({<div className="flex items-center gap-2.5 px-1.5 py-1.5" data-space-header><SpaceTile space={space} size={32} /><span className="flex-1 min-w-0">- <h1 className="text-sm font-semibold text-zinc-100 truncate">{space.name}</h1>- <span className="block text-[11px] text-zinc-500 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span>+ <h1 className="text-body font-semibold text-zinc-50 truncate">{space.name}</h1>+ <span className="block text-meta text-zinc-400 truncate" title={spaceSummaryTitle(space.counts)}>{spaceSummary(space.counts)}</span></span><buttontype="button"@@ -668,7 +685,7 @@ export const Sidebar: React.FC<SidebarProps> = ({type="button"onClick={onOpenSpaceSettings}title="Bots here act without asking, including deletions, publishing and sign-ins. Payments still ask you. Change it in Settings › This space."- className="mt-1 w-full flex items-center gap-1.5 px-2 py-1 rounded-md border border-amber-500/30 bg-amber-500/10 text-[11px] font-medium text-amber-200 hover:bg-amber-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"+ className="mt-1.5 w-full flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl border border-amber-300/30 bg-amber-300/10 text-meta font-medium text-warn hover:bg-amber-300/15 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-300"><ShieldOff size={12} aria-hidden="true" className="shrink-0" /><span className="truncate">{offLine}</span>@@ -694,7 +711,7 @@ export const Sidebar: React.FC<SidebarProps> = ({<button type="button" onClick={onOpenSearch} className={navRow(false)}><Search size={15} className="text-zinc-500" aria-hidden="true" /><span className="truncate flex-1">Search {space.name}</span>- {!phone && <kbd className="shrink-0 text-[10px] font-sans text-zinc-500">{isMac ? '⌘K' : 'Ctrl K'}</kbd>}+ {!phone && <kbd className="shrink-0 rounded border border-hairline-strong px-1 text-2xs font-sans text-zinc-400">{isMac ? '⌘K' : 'Ctrl K'}</kbd>}</button>{/* Phones have Inbox as a tab */}{onOpenInbox && !phone && (@@ -734,8 +751,8 @@ export const Sidebar: React.FC<SidebarProps> = ({{showChats && (<div><div className={sectionHead}>- <span>Channels</span>- {onCreateChannel && kwants.length > 0 && headButton('New channel', `New channel in ${space.name}`, onCreateChannel)}+ <span className="whitespace-nowrap shrink-0">Channels</span>+ {onCreateChannel && kwants.length > 0 && headButton('Channel', 'New channel', `New channel in ${space.name}`, onCreateChannel)}</div><div className="mt-1 space-y-0.5">{displayChannels.map((c) => {@@ -746,7 +763,7 @@ export const Sidebar: React.FC<SidebarProps> = ({onClick={() => onSelectChannel(c)}// The channel's header says it too; no pill on every rowtitle={layaRoutes(c, kwants.length) ? 'Laya picks who answers here' : undefined}- className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left ${+ className={`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-xl text-body font-medium transition-colors text-left ${active? 'bg-zinc-800 text-zinc-100 shadow-sm border border-zinc-700/50': 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/50'@@ -782,10 +799,10 @@ export const Sidebar: React.FC<SidebarProps> = ({{showBots && (<div data-bot-list><div className={sectionHead}>- <h2>Bots ({kwants.length})</h2>- <span className="flex items-center gap-1">- {headButton('New team', `New team in ${space.name}`, onCreateTeam)}- {headButton('New bot', `New bot in ${space.name}`, () => onSummonKwant())}+ <h2 className="whitespace-nowrap shrink-0">Bots ({kwants.length})</h2>+ <span className="flex items-center gap-1 shrink-0">+ {headButton('Team', 'New team', `New team in ${space.name}`, onCreateTeam)}+ {headButton('Bot', 'New bot', `New bot in ${space.name}`, () => onSummonKwant())}</span></div><div className="mt-1 space-y-2">@@ -825,7 +842,7 @@ export const Sidebar: React.FC<SidebarProps> = ({{/* Footer: what this space's bots run on, from the real checks */}{/* On the phone's Chats tab only while nothing can run, so setup is never hidden there */}{engines.engines?.length !== 0 && (section !== 'chats' || canRun === false) ? (- <div className="p-3 border-t border-zinc-800/60 bg-zinc-950/40 text-[11px] text-zinc-500">+ <div className="p-3 border-t border-hairline bg-surface-rail/60 text-meta text-zinc-400"><buttontype="button"onClick={offerClaude ? onSignInClaude : onOpenAccounts}diff --git a/frontend/src/components/Spaces.tsx b/frontend/src/components/Spaces.tsxindex 80ff855c..4ebc1316 100644--- a/frontend/src/components/Spaces.tsx+++ b/frontend/src/components/Spaces.tsx@@ -44,7 +44,7 @@ interface RailProps {}export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, onCreate, onOpenAppSettings }) => (- <nav aria-label="Spaces" className="hidden md:flex w-[68px] shrink-0 flex-col items-center gap-2 py-3 border-r border-zinc-800/80 bg-zinc-950 select-none">+ <nav aria-label="Spaces" className="hidden md:flex w-[68px] shrink-0 flex-col items-center gap-2 py-3 border-r border-hairline bg-surface-rail select-none"><ul className="flex flex-col items-center gap-2 flex-1 overflow-y-auto overflow-x-hidden w-full">{spaces.map((s, i) => {const active = s.id === currentId;diff --git a/frontend/src/components/Sticker.tsx b/frontend/src/components/Sticker.tsxnew file mode 100644index 00000000..c075f7a4--- /dev/null+++ b/frontend/src/components/Sticker.tsx@@ -0,0 +1,87 @@+import React, { useRef } from 'react';++export type StickerTone = 'holo' | 'ink';+export type StickerSize = 'md' | 'sm';++/** Tilt in degrees, kept to the -3..3 the style allows; anything else (or NaN) falls back to `fallback`. */+export const clampTilt = (tilt: number | undefined, fallback = 0): number =>+ typeof tilt === 'number' && Number.isFinite(tilt) ? Math.max(-3, Math.min(3, tilt)) : fallback;++const reducedMotion = () =>+ typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;++export interface StickerProps {+ /** "holo": earned things only (verified, picked, goal kept). "ink": a plain plate, e.g. "New". Default "ink". */+ tone?: StickerTone;+ /** "md" 24 px (default) or "sm" 18 px. The class kw-sticker-sm does the same as size="sm". */+ size?: StickerSize;+ /** -3 to 3 degrees. Default: -2 for holo, 2 for ink. */+ tilt?: number;+ /** A small lucide icon (12 px on md, 10 px on sm) shown before the text. */+ icon?: React.ReactNode;+ /** Hover text. */+ title?: string;+ /** Spoken label when the text alone isn't enough. */+ ariaLabel?: string;+ /** Makes it clickable: the sticker sits inside a 44x44 button (.kw-sticker-hit). */+ onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;+ /** On the outermost element (the hit button when clickable), so positioning classes work either way. */+ className?: string;+ children: React.ReactNode;+}++/**+ * A die-cut sticker (spec.md §1). Holo is earned: use it only for results a check produced, at most one+ * per card. Warnings, errors, needs you and Approvals off stay plain chips (kw-chip-warn / kw-chip-bad).+ */+export const Sticker: React.FC<StickerProps> = ({ tone = 'ink', size, tilt, icon, title, ariaLabel, onClick, className = '', children }) => {+ const ref = useRef<HTMLSpanElement | null>(null);+ const deg = clampTilt(tilt, tone === 'holo' ? -2 : 2);+ const sm = size === 'sm' || /\bkw-sticker-sm\b/.test(className);+ // The sheen follows a mouse or pen through CSS variables (registered with @property, so it glides);+ // nothing re-renders. Touch and reduced motion keep the static 30% / 20%.+ const track = (e: React.PointerEvent<HTMLElement>) => {+ const el = ref.current;+ if (!el || tone !== 'holo' || e.pointerType === 'touch' || reducedMotion()) return;+ const r = el.getBoundingClientRect();+ if (!r.width || !r.height) return;+ const clamp = (v: number) => Math.max(0, Math.min(100, Math.round(v)));+ el.style.setProperty('--mx', `${clamp(((e.clientX - r.left) / r.width) * 100)}%`);+ el.style.setProperty('--my', `${clamp(((e.clientY - r.top) / r.height) * 100)}%`);+ };+ const reset = () => {+ const el = ref.current;+ if (!el) return;+ el.style.removeProperty('--mx');+ el.style.removeProperty('--my');+ };+ const sticker = (outer: boolean) => (+ <span+ ref={ref}+ className={`kw-sticker kw-sticker-${tone} ${sm ? 'kw-sticker-sm' : ''} ${outer ? className.replace(/\bkw-sticker-sm\b/, '') : ''}`.replace(/\s+/g, ' ').trim()}+ style={{ ['--kw-tilt' as string]: `${deg}deg` } as React.CSSProperties}+ title={outer ? title : undefined}+ aria-label={outer ? ariaLabel : undefined}+ data-sticker={tone}+ onPointerMove={outer ? track : undefined}+ onPointerLeave={outer ? reset : undefined}+ >+ {icon}+ <span>{children}</span>+ </span>+ );+ if (!onClick) return sticker(true);+ return (+ <button+ type="button"+ onClick={onClick}+ onPointerMove={track}+ onPointerLeave={reset}+ title={title}+ aria-label={ariaLabel}+ className={`kw-sticker-hit ${className.replace(/\bkw-sticker-sm\b/, '')}`.replace(/\s+/g, ' ').trim()}+ >+ {sticker(false)}+ </button>+ );+};diff --git a/frontend/src/kwantMood.ts b/frontend/src/kwantMood.tsnew file mode 100644index 00000000..9fd2439d--- /dev/null+++ b/frontend/src/kwantMood.ts@@ -0,0 +1,168 @@+// What a bot's avatar shows about it besides "working": thinking, just finished, failed, needs you,+// resting (out of quota). Worked out on the client from events and data it already has: turn start/end+// (with the outcome), the first streamed output, open questions and browser steps, and the engine+// accounts' limited_until. Pure selection plus a small per-kwant store, like kwantActivity.++import { isKwantWorking, subscribeKwant } from './kwantActivity';+import { parsePick } from './engines';+import { activeLimit, type Profile } from './profiles';++export type Mood = 'resting' | 'needs_you' | 'thinking' | 'working' | 'failed' | 'finished' | 'idle';++/** How long "just finished" and "failed" stay on the avatar. */+export const FINISHED_MS = 3000;+export const FAILED_MS = 10 * 60_000;++export type TurnOutcome = 'completed' | 'failed' | 'cancelled';++export interface MoodInputs {+ /** A turn is running (kwantActivity). */+ working: boolean;+ /** A turn started and nothing has streamed yet. */+ thinking?: boolean;+ /** A question or browser step waits for the person. */+ needsYou?: boolean;+ /** The bot's engine accounts are all out of usage until then. */+ restingUntil?: Date | null;+ /** How the last turn ended, and when (ms). */+ last?: { outcome: TurnOutcome; at: number } | null;+ now: number;+}++/**+ * One mood per bot. Something that needs the person beats everything; a running turn beats the+ * resting look (the bot is running, so it isn't out); a failure stays until the next turn; "just+ * finished" fades after a moment. A cancelled turn shows nothing.+ */+export function selectMood(i: MoodInputs): Mood {+ if (i.needsYou) return 'needs_you';+ if (i.working) return i.thinking ? 'thinking' : 'working';+ if (i.restingUntil && i.restingUntil.getTime() > i.now) return 'resting';+ if (i.last?.outcome === 'failed' && i.now - i.last.at < FAILED_MS) return 'failed';+ if (i.last?.outcome === 'completed' && i.now - i.last.at < FINISHED_MS) return 'finished';+ return 'idle';+}++const pad = (n: number) => String(n).padStart(2, '0');+/** "03:00" in the person's zone, with the day when it isn't today. */+export function restingClock(at: Date, now = Date.now()): string {+ const time = `${pad(at.getHours())}:${pad(at.getMinutes())}`;+ return at.toDateString() === new Date(now).toDateString() ? time : `${at.toLocaleDateString(undefined, { weekday: 'short' })} ${time}`;+}++/** Words for the avatar's tooltip and screen readers; null when the mood adds nothing. */+export function moodLabel(mood: Mood, name: string | undefined, until?: Date | null, now = Date.now()): string | null {+ const who = name || 'This bot';+ switch (mood) {+ case 'resting': return until ? `Resting until ${restingClock(until, now)}` : `${who} is resting`;+ case 'needs_you': return `${who} needs you`;+ case 'thinking': return `${who} is thinking`;+ case 'failed': return `${who}'s last turn failed`;+ case 'finished': return `${who} just finished`;+ default: return null;+ }+}++/**+ * When a bot's engine accounts come back, or null while any of them can run. A bot that picked an+ * engine family rests when every switched-on account of that family is out; a bot on "auto" rests+ * only when every switched-on account is. The earliest return time wins.+ */+export function restingUntil(preferredModel: string | null | undefined, profiles: Profile[] | null | undefined, now = Date.now()): Date | null {+ if (!profiles?.length) return null;+ const { family } = parsePick(preferredModel);+ const scope = profiles.filter((p) => p.enabled && (family && family !== 'auto' ? p.engine === family : true));+ if (!scope.length) return null;+ let earliest: Date | null = null;+ for (const p of scope) {+ const limit = activeLimit(p.limited_until, now);+ if (!limit) return null;+ if (!earliest || limit < earliest) earliest = limit;+ }+ return earliest;+}++// ---- The store ----++interface BotMood {+ thinking: boolean;+ needsYou: boolean;+ until: Date | null;+ last: { outcome: TurnOutcome; at: number } | null;+ /** Bumps each time the person sends this bot a message: the avatar blinks once. */+ notices: number;+}++const state = new Map<string, BotMood>();+const listeners = new Map<string, Set<() => void>>();+const timers = new Map<string, ReturnType<typeof setTimeout>>();++const get = (id: string): BotMood => state.get(id) ?? { thinking: false, needsYou: false, until: null, last: null, notices: 0 };+const notify = (id: string) => listeners.get(id)?.forEach((l) => l());++function patch(id: string, next: Partial<BotMood>): void {+ const before = get(id);+ const after = { ...before, ...next };+ const changed = (Object.keys(next) as Array<keyof BotMood>).some((k) => {+ const a = before[k];+ const b = after[k];+ return a instanceof Date || b instanceof Date ? (a as Date | null)?.getTime() !== (b as Date | null)?.getTime() : JSON.stringify(a) !== JSON.stringify(b);+ });+ if (!changed) return;+ state.set(id, after);+ notify(id);+}++/** Re-render when "just finished" or "failed" runs out. */+function expireLater(id: string, ms: number) {+ clearTimeout(timers.get(id));+ timers.set(id, setTimeout(() => notify(id), ms + 20));+}++export const moodTurnStarted = (id: string) => id && patch(id, { thinking: true, last: null });+/** First streamed text or step of a turn: no longer "thinking". */+export const moodOutput = (id: string) => id && patch(id, { thinking: false });+export function moodTurnEnded(id: string, outcome: string | undefined, now = Date.now()): void {+ if (!id) return;+ const o: TurnOutcome = outcome === 'failed' ? 'failed' : outcome === 'cancelled' ? 'cancelled' : 'completed';+ patch(id, { thinking: false, last: { outcome: o, at: now } });+ if (o !== 'cancelled') expireLater(id, o === 'failed' ? FAILED_MS : FINISHED_MS);+}+/** Which bots wait for the person right now (replaces the previous set). */+export function setMoodNeedsYou(ids: Iterable<string>): void {+ const want = new Set(ids);+ for (const id of new Set([...state.keys(), ...want])) patch(id, { needsYou: want.has(id) });+}+/** Each bot's return time while resting (replaces the previous map). */+export function setMoodResting(untilByBot: Record<string, Date | null>): void {+ for (const id of new Set([...state.keys(), ...Object.keys(untilByBot)])) patch(id, { until: untilByBot[id] ?? null });+}+/** The person just sent this bot a message. */+export const moodNoticed = (id: string) => id && patch(id, { notices: get(id).notices + 1 });+export const noticesOf = (id: string | undefined): number => (id ? get(id).notices : 0);+export const restingUntilOf = (id: string | undefined): Date | null => (id ? get(id).until : null);+export function clearMoods(): void {+ const ids = [...state.keys()];+ state.clear();+ timers.forEach(clearTimeout);+ timers.clear();+ ids.forEach(notify);+}++export function moodOf(id: string | undefined, now = Date.now()): Mood {+ if (!id) return 'idle';+ const s = get(id);+ return selectMood({ working: isKwantWorking(id), thinking: s.thinking, needsYou: s.needsYou, restingUntil: s.until, last: s.last, now });+}++export function subscribeMood(id: string, listener: () => void): () => void {+ const set = listeners.get(id) ?? new Set();+ set.add(listener);+ listeners.set(id, set);+ const offActivity = subscribeKwant(id, listener);+ return () => {+ set.delete(listener);+ if (!set.size) listeners.delete(id);+ offActivity();+ };+}diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 3b503185..eb9f464e 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -2,13 +2,32 @@@tailwind components;@tailwind utilities;+/* Design tokens (UI refresh, 0.6.9). Surfaces get lighter as they rise; hairlines are white at low+ alpha so they work on every surface. Tailwind names for these: bg-surface-*, border-hairline,+ text-ok / warn / bad / info / muted, bg-accent-gradient, shadow-card / raised / glow. */+:root {+ --kw-surface-rail: #0a0719;+ --kw-surface-side: #0e0a21;+ --kw-surface-main: #120e26;+ --kw-surface-raised: #1a1538;+ --kw-surface-overlay: #231d4b;+ --kw-hairline: rgb(255 255 255 / 0.07);+ --kw-hairline-strong: rgb(255 255 255 / 0.14);+ --kw-ok: #5eead4;+ --kw-warn: #fcd34d;+ --kw-bad: #fda4af;+ --kw-info: #b8adff;+ --kw-muted: #a39dcc;+ --kw-ease: cubic-bezier(0.2, 0.7, 0.2, 1);+}+@layer base {* {border-color: theme('colors.zinc.800');}body {- background-color: theme('colors.zinc.950');+ background-color: var(--kw-surface-main);color: theme('colors.zinc.100');font-family: theme('fontFamily.sans');}@@ -67,11 +86,6 @@50% { opacity: 0.95; transform: scale(1.07); }}-@keyframes kw-avatar-pip {- 0%, 100% { opacity: 0.4; transform: scale(0.8); }- 50% { opacity: 1; transform: scale(1); }-}-.kw-avatar-working .kw-avatar-body {transform-box: fill-box;transform-origin: center bottom;@@ -82,30 +96,14 @@position: absolute;inset: -2px;border-radius: 30%;- box-shadow: 0 0 0 1.5px theme('colors.sky.400'), 0 0 8px 1px rgb(56 189 248 / 0.55);+ box-shadow: 0 0 0 1.5px #9d8fff, 0 0 8px 1px rgb(157 143 255 / 0.55);pointer-events: none;animation: kw-avatar-ring 1.4s ease-in-out infinite;}-.kw-avatar-pip {- position: absolute;- top: -2px;- right: -2px;- width: 30%;- max-width: 8px;- min-width: 4px;- aspect-ratio: 1;- border-radius: 9999px;- background: theme('colors.sky.300');- box-shadow: 0 0 0 1.5px theme('colors.zinc.950');- pointer-events: none;- animation: kw-avatar-pip 0.7s ease-in-out infinite;-}-@media (prefers-reduced-motion: reduce) {.kw-avatar-working .kw-avatar-body,- .kw-avatar-ring,- .kw-avatar-pip {+ .kw-avatar-ring {animation: none;}.kw-avatar-ring { opacity: 0.9; }@@ -268,3 +266,264 @@display: inline-block;}}++/* ------------------------------------------------------------------------------------------------+ Semantic classes (UI refresh). Use these rather than repeating long utility strings.+ .kw-card a raised surface: hairline, 12px corners, soft shadow+ .kw-card-interactive the same, tappable: lifts 1px and brightens its hairline on hover/focus+ .kw-chip a pill label; add .kw-chip-ok / -warn / -bad / -info / -accent for a status colour+ .kw-btn-primary the accent gradient button (one per view); .kw-btn-ghost a quiet button+ .kw-status-dot a 8px dot; .kw-status-ok / -warn / -bad / -idle, .kw-pulse while something is live+ .kw-focus the focus ring (2px accent, 2px offset); already on every .kw-card-interactive+ .kw-fade-in enters in 160ms (opacity + 6px slide); .kw-stagger delays children by --i * 40ms+ Motion is 120-200ms, transform and opacity only, and off under prefers-reduced-motion.+ ------------------------------------------------------------------------------------------------ */+@layer components {+ .kw-card {+ @apply rounded-2xl border border-hairline bg-surface-raised shadow-card;+ }+ .kw-card-interactive {+ @apply kw-card text-left cursor-pointer;+ transition: transform 160ms var(--kw-ease), border-color 160ms var(--kw-ease), background-color 160ms var(--kw-ease);+ }+ .kw-card-interactive:hover:not(:disabled) {+ transform: translateY(-1px);+ border-color: rgb(157 143 255 / 0.45);+ background-color: var(--kw-surface-overlay);+ }+ .kw-card-interactive:active:not(:disabled) {+ transform: translateY(0) scale(0.995);+ }+ .kw-card-interactive:disabled {+ @apply opacity-50 cursor-not-allowed;+ }+ .kw-card-interactive,+ .kw-focus {+ @apply focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400;+ }++ .kw-chip {+ @apply inline-flex items-center gap-1 rounded-full border border-hairline-strong bg-white/[0.04] px-2.5 py-0.5 text-meta font-medium text-zinc-300;+ }+ .kw-chip-ok { @apply border-teal-400/30 bg-teal-400/10 text-ok; }+ /* Plain, never holo: needs you / Approvals off (amber), failed (rose). spec.md §1 "Rule". */+ .kw-chip-warn { @apply border-amber-300/35 text-warn; background-color: rgb(252 211 77 / 0.12); }+ .kw-chip-bad { @apply border-rose-300/35 text-bad; background-color: rgb(253 164 175 / 0.12); }+ .kw-chip-info { @apply border-sky-300/30 bg-sky-300/10 text-info; }+ .kw-chip-accent { @apply border-transparent bg-accent-soft text-sky-200; }++ .kw-btn-primary {+ @apply inline-flex items-center justify-center gap-1.5 rounded-xl bg-accent-gradient px-3.5 py-1.5 text-body font-semibold text-white shadow-card;+ transition: transform 140ms var(--kw-ease), filter 140ms var(--kw-ease), box-shadow 140ms var(--kw-ease);+ }+ .kw-btn-primary:hover:not(:disabled) { filter: brightness(1.12); box-shadow: theme('boxShadow.glow'); }+ .kw-btn-primary:active:not(:disabled) { transform: scale(0.97); }+ .kw-btn-primary:disabled { @apply cursor-not-allowed; background-image: none; background-color: var(--kw-surface-overlay); color: theme('colors.zinc.400'); box-shadow: none; }+ .kw-btn-ghost {+ @apply inline-flex items-center justify-center gap-1.5 rounded-xl border border-hairline-strong bg-white/[0.03] px-3 py-1.5 text-meta font-medium text-zinc-200 transition-colors hover:bg-white/[0.08] hover:text-zinc-50;+ }+ .kw-btn-primary,+ .kw-btn-ghost {+ @apply focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400;+ }++ .kw-status-dot { @apply inline-block h-2 w-2 shrink-0 rounded-full; }+ .kw-status-ok { @apply bg-teal-300; }+ .kw-status-warn { @apply bg-amber-300; }+ .kw-status-bad { @apply bg-rose-300; }+ .kw-status-idle { @apply bg-zinc-500; }+}++@keyframes kw-pulse {+ 0%, 100% { opacity: 1; transform: scale(1); }+ 50% { opacity: 0.45; transform: scale(0.8); }+}+.kw-pulse { animation: kw-pulse 1.4s ease-in-out infinite; }++@keyframes kw-fade-in {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: translateY(0); }+}+.kw-fade-in { animation: kw-fade-in 160ms var(--kw-ease) both; }+.kw-stagger > * { animation: kw-fade-in 180ms var(--kw-ease) both; animation-delay: calc(var(--i, 0) * 40ms); }++/* Bot home: the avatar floats and the glow breathes. Transform and opacity only. */+@keyframes kw-float {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-4px); }+}+@keyframes kw-glow-breathe {+ 0%, 100% { opacity: 0.55; transform: scale(1); }+ 50% { opacity: 0.9; transform: scale(1.08); }+}+@keyframes kw-home-in {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}+.kw-float { animation: kw-float 3.2s ease-in-out infinite; }+.kw-glow { animation: kw-glow-breathe 3.6s ease-in-out infinite; }+/* The home waits 220ms before it shows, so a chat whose messages are still loading never flashes it */+.kw-home { animation: kw-home-in 180ms var(--kw-ease) 220ms both; }++@media (prefers-reduced-motion: reduce) {+ .kw-pulse,+ .kw-float,+ .kw-glow { animation: none; }+ .kw-fade-in,+ .kw-stagger > * { animation: none; }+ .kw-home { animation: kw-home-fade 1ms linear 220ms both; }+ .kw-card-interactive,+ .kw-btn-primary { transition: none; }+ .kw-card-interactive:hover:not(:disabled),+ .kw-card-interactive:active:not(:disabled),+ .kw-btn-primary:active:not(:disabled) { transform: none; }+}+@keyframes kw-home-fade {+ from { opacity: 0; }+ to { opacity: 1; }+}++/* ---------------------------------------------------------------------------------------------+ Stickers (Mira's spec.md §1): a die-cut plate, 2px white edge, soft shadow, slight tilt. Pure CSS.+ tone "holo" is only for earned things (verified, picked, goal kept): a vivid foil sweep multiplied+ into the light plate plus a soft-light glint and grain, so ink text only gains contrast (worst 7.19:1).+ tone "ink" is the plain plate (e.g. "New"). Needs you, failed, Approvals off: plain chips, never this.+ --mx/--my are set by <Sticker> on pointer move and glide through @property.+ --------------------------------------------------------------------------------------------- */+@property --mx { syntax: '<percentage>'; inherits: true; initial-value: 30%; }+@property --my { syntax: '<percentage>'; inherits: true; initial-value: 20%; }+.kw-sticker {+ --mx: 30%;+ --my: 20%;+ --kw-tilt: 0deg;+ position: relative;+ box-sizing: border-box;+ display: inline-flex;+ align-items: center;+ gap: 4px;+ height: 24px;+ max-width: 100%;+ padding: 0 10px;+ border: 2px solid #fff;+ border-radius: 11px 7px 11px 7px;+ background: #f4f1ff;+ color: #1b1033;+ font: 700 12px/16px theme('fontFamily.sans');+ letter-spacing: 0.01em;+ white-space: nowrap;+ vertical-align: middle;+ isolation: isolate;+ overflow: hidden;+ box-shadow: 0 1px 0 rgb(0 0 0 / 0.3), 0 5px 12px rgb(0 0 0 / 0.35);+ transform: rotate(var(--kw-tilt));+ transition: transform 160ms cubic-bezier(.2,.7,.2,1), box-shadow 160ms cubic-bezier(.2,.7,.2,1), --mx 120ms linear, --my 120ms linear;+}+.kw-sticker svg { width: 12px; height: 12px; flex-shrink: 0; }+.kw-sticker-sm {+ height: 18px;+ padding: 0 6px;+ gap: 3px;+ border-radius: 8px 5px 8px 5px;+ font: 700 11px/14px theme('fontFamily.sans');+ box-shadow: 0 1px 0 rgb(0 0 0 / 0.3), 0 3px 8px rgb(0 0 0 / 0.35);+}+.kw-sticker-sm svg { width: 10px; height: 10px; }+.kw-sticker > * { position: relative; z-index: 2; }+/* A clickable sticker is a span inside this button: a 44x44 target around an 18-24px sticker. */+.kw-sticker-hit {+ display: inline-grid;+ place-items: center;+ min-width: 44px;+ min-height: 44px;+ padding: 0;+ border: 0;+ background: transparent;+ cursor: pointer;+ border-radius: 12px;+}+.kw-sticker-hit:focus { outline: none; }+.kw-sticker-hit:focus-visible > .kw-sticker,+a.kw-sticker:focus-visible { outline: 2px solid #b8adff; outline-offset: 3px; }+.kw-sticker-hit:hover > .kw-sticker,+a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow: 0 1px 0 rgb(0 0 0 / 0.3), 0 8px 16px rgb(0 0 0 / 0.4); }+.kw-sticker-holo::before,+.kw-sticker-holo::after {+ content: '';+ position: absolute;+ pointer-events: none;+}+/* The foil (review-pr264 §2, v2): a 105deg two-cycle linear sweep, 200% wide, slid with transform only,+ so a flat pill always shows the full rainbow. --my is no longer read; the pointer code still sets it. */+.kw-sticker-holo::before {+ inset: 0 -50%;+ z-index: 0;+ background: linear-gradient(105deg,+ #ff6ec7 0%, #ffd36e 10%, #7dffb0 20%, #5ee0ff 30%, #9b7bff 40%,+ #ff6ec7 50%, #ffd36e 60%, #7dffb0 70%, #5ee0ff 80%, #9b7bff 90%, #ff6ec7 100%);+ mix-blend-mode: multiply;+ opacity: 0.8;+ transform: translateX(calc((50% - var(--mx)) / 4));+}+/* A glint band that follows --mx, plus a fine foil grain. Soft-light white only lightens. */+.kw-sticker-holo::after {+ inset: 0;+ z-index: 1;+ background:+ linear-gradient(105deg, transparent calc(var(--mx) - 14%), rgb(255 255 255 / 0.7) var(--mx), transparent calc(var(--mx) + 14%)),+ repeating-linear-gradient(115deg, transparent 0 3px, rgb(255 255 255 / 0.22) 3px 4px);+ mix-blend-mode: soft-light;+}+.kw-sticker-ink { background: #e9e4ff; }+/* "New" leaving after first use: fade, then NewTag unmounts it. */+.kw-new-tag { transition: opacity 160ms linear; }+.kw-new-tag[data-leaving] { opacity: 0; }+@keyframes kw-sticker-drift {+ from { transform: translateX(calc((50% - var(--mx)) / 4 - 8%)); }+ to { transform: translateX(calc((50% - var(--mx)) / 4)); }+}+@keyframes kw-sticker-press {+ from { transform: rotate(var(--kw-tilt)) scale(1.08); }+ to { transform: rotate(var(--kw-tilt)) scale(1); }+}+/* S1: the Verified stamp presses in once when it appears. */+.kw-sticker-press { animation: kw-sticker-press 160ms cubic-bezier(.2,.7,.2,1) 1 both; }+/* No pointer on a phone: the sheen drifts once when the sticker appears. */+@media (pointer: coarse) {+ .kw-sticker-holo::before { animation: kw-sticker-drift 160ms cubic-bezier(.2,.7,.2,1) 1 both; }+}+@media (prefers-reduced-motion: reduce) {+ .kw-sticker { --mx: 30% !important; --my: 20% !important; transition: none; }+ .kw-sticker-holo::before,+ .kw-sticker-press { animation: none; }+ .kw-sticker-hit:hover > .kw-sticker,+ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)); }+ .kw-new-tag { transition: none; }+}++/* ---------------------------------------------------------------------------------------------+ Avatar moods (AvatarMood / ModernAvatar). Opacity and transform only, 120-200ms or a slow loop;+ static under prefers-reduced-motion.+ --------------------------------------------------------------------------------------------- */+.kw-avatar-resting > svg:not(.kw-mood) { opacity: 0.55; filter: saturate(0.5); }+@keyframes kw-mood-dot { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }+.kw-mood-dot { animation: kw-mood-dot 1.2s ease-in-out infinite; }+.kw-mood-dot-1 { animation-delay: 0.2s; }+.kw-mood-dot-2 { animation-delay: 0.4s; }+@keyframes kw-mood-pop { from { opacity: 0; transform: scale(0.4); } to { opacity: 1; transform: scale(1); } }+.kw-mood-needs_you,+.kw-mood-failed { transform-origin: center; animation: kw-mood-pop 160ms var(--kw-ease) 1 both; }+/* Just finished: frames at 0 / 60 / 120 ms (steps), held to 3 s, then a 160 ms fade. */+@keyframes kw-mood-frame { from { opacity: 0; } to { opacity: 1; } }+@keyframes kw-mood-out { from { opacity: 1; } to { opacity: 0; } }+.kw-mood-f2 { animation: kw-mood-frame 1ms steps(1) 60ms 1 both; }+.kw-mood-f3 { animation: kw-mood-frame 1ms steps(1) 120ms 1 both; }+.kw-mood-finished { animation: kw-mood-out 160ms linear 2840ms 1 forwards; }+@keyframes kw-avatar-blink { from { opacity: 1; } to { opacity: 0; } }+.kw-avatar-blink { animation: kw-avatar-blink 1ms linear 160ms 1 both; opacity: 1; }+@media (prefers-reduced-motion: reduce) {+ .kw-mood-dot { animation: none; opacity: 0.8; }+ .kw-mood-finished, .kw-mood-needs_you, .kw-mood-failed,+ .kw-mood-f2, .kw-mood-f3 { animation: none; }+ .kw-avatar-blink { display: none; }+}+diff --git a/frontend/src/tabSignal.ts b/frontend/src/tabSignal.tsnew file mode 100644index 00000000..fd99eecb--- /dev/null+++ b/frontend/src/tabSignal.ts@@ -0,0 +1,104 @@+// The browser tab says what the page can't while it is in the background: the title carries how many+// things need the person, and the favicon gets a violet dot while any bot works. Pure helpers plus a+// small controller that tests drive with a fake document.++const COUNT_PREFIX = /^\(\d+\)\s*/;++/** "(2) kwant" for 2 things that need you; the plain title for none. Keeps whatever title the page has. */+export function tabTitle(current: string, needsYou: number): string {+ const base = (current || 'kwant').replace(COUNT_PREFIX, '');+ return needsYou > 0 ? `(${needsYou > 99 ? '99+' : needsYou}) ${base}` : base;+}++/** What needs the person: bots waiting on a question or browser step, plus approvals waiting. */+export function needsYouCount(botStatus: Readonly<Record<string, string>>, pendingApprovals: number): number {+ return Object.values(botStatus).filter((s) => s === 'needs_you').length + Math.max(0, pendingApprovals);+}++/** The dot: bottom-right, a quarter of the icon, with a ring in the icon's dark so it reads on any tab. */+export function dotGeometry(size: number): { cx: number; cy: number; r: number; ring: number } {+ const r = Math.round(size * 0.2);+ const ring = Math.max(1, Math.round(size * 0.05));+ return { cx: size - r - ring - 1, cy: size - r - ring - 1, r, ring };+}++interface LinkLike { href: string; type?: string }+export interface TabDoc {+ title: string;+ iconLink(): LinkLike | null;+ /** The icon with the violet dot as an image URL, or null when it can't be drawn. */+ drawDotted(originalHref: string): Promise<string | null>;+}++/** Applies the count to the title and the dot to the icon; each call is idempotent. */+export function createTabSignal(doc: TabDoc) {+ let original: { href: string; type?: string } | null = null;+ let wantDot = false;+ let drawing = 0;+ return {+ setNeedsYou(n: number) {+ const next = tabTitle(doc.title, n);+ if (doc.title !== next) doc.title = next;+ },+ async setWorking(working: boolean) {+ const link = doc.iconLink();+ if (!link || wantDot === working) return;+ wantDot = working;+ if (working) {+ original ??= { href: link.href, type: link.type };+ const ticket = ++drawing;+ const url = await doc.drawDotted(original.href);+ // Idle again (or a newer draw) while the image was loading: leave the icon alone.+ if (url && wantDot && ticket === drawing) {+ link.href = url;+ link.type = 'image/png';+ }+ } else {+ drawing++;+ if (original) {+ link.href = original.href;+ if (original.type !== undefined) link.type = original.type;+ }+ }+ },+ };+}++/** The real document: draws icon.svg (or whatever the page links) onto a canvas with the dot on it. */+export function browserTabDoc(): TabDoc {+ return {+ get title() { return document.title; },+ set title(v: string) { document.title = v; },+ iconLink: () => {+ let el = document.querySelector<HTMLLinkElement>('link[rel~="icon"]');+ if (!el) {+ el = document.createElement('link');+ el.rel = 'icon';+ document.head.appendChild(el);+ }+ return el;+ },+ drawDotted: (href) =>+ new Promise((resolve) => {+ const img = new Image();+ img.onload = () => {+ try {+ const size = 64;+ const c = document.createElement('canvas');+ c.width = c.height = size;+ const g = c.getContext('2d');+ if (!g) return resolve(null);+ g.drawImage(img, 0, 0, size, size);+ const { cx, cy, r, ring } = dotGeometry(size);+ g.fillStyle = '#120e26';+ g.beginPath(); g.arc(cx, cy, r + ring, 0, Math.PI * 2); g.fill();+ g.fillStyle = '#a78bfa';+ g.beginPath(); g.arc(cx, cy, r, 0, Math.PI * 2); g.fill();+ resolve(c.toDataURL('image/png'));+ } catch { resolve(null); }+ };+ img.onerror = () => resolve(null);+ img.src = href;+ }),+ };+}diff --git a/frontend/src/whatsNew.ts b/frontend/src/whatsNew.tsnew file mode 100644index 00000000..46ab70c8--- /dev/null+++ b/frontend/src/whatsNew.ts@@ -0,0 +1,48 @@+// "New" stickers for what 0.6.9 changed: shown until the person uses the thing once, then gone for good.+// Stored per browser in localStorage; a missing or blocked storage just shows nothing.++export const NEW_VERSION = '0.6.9';+export type NewId = 'mention' | 'starters';++export interface KeyValueStore {+ getItem(k: string): string | null;+ setItem(k: string, v: string): void;+}++export const newKey = (id: NewId, version = NEW_VERSION) => `kwant:new:${version}:${id}`;++const defaultStore = (): KeyValueStore | null => {+ try {+ return typeof localStorage === 'undefined' ? null : localStorage;+ } catch {+ return null;+ }+};++/** Still to be shown: not used yet. With no usable storage it stays hidden rather than nagging every visit. */+export function isNewThing(id: NewId, store: KeyValueStore | null = defaultStore()): boolean {+ if (!store) return false;+ try {+ return store.getItem(newKey(id)) === null;+ } catch {+ return false;+ }+}++const listeners = new Set<() => void>();+export const subscribeNew = (l: () => void) => {+ listeners.add(l);+ return () => void listeners.delete(l);+};++/** The person used it: hide its sticker everywhere, for good. */+export function markNewSeen(id: NewId, store: KeyValueStore | null = defaultStore()): void {+ if (!store) return;+ try {+ if (store.getItem(newKey(id)) !== null) return;+ store.setItem(newKey(id), '1');+ } catch {+ return;+ }+ listeners.forEach((l) => l());+}diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.jsindex ab9a3a34..786e5038 100644--- a/frontend/tailwind.config.js+++ b/frontend/tailwind.config.js@@ -14,7 +14,8 @@ export default {200: '#d9d6f0',300: '#bcb7de',400: '#9a94c4',- 500: '#78719f',+ // Lifted from #78719f: that was 4.2:1 on the page, so small grey text failed AA. Now 5.6:1.+ 500: '#8d87b8',600: '#5a5383',700: '#3f3868',800: '#2c2552',@@ -43,12 +44,51 @@ export default {600: '#0284c7',},},- // Squarer, pixel-friendly corners+ // Layered surfaces, dark to light: rail < side < main < raised < overlay. Use these instead of+ // picking a zinc shade, so depth reads the same everywhere. Backed by CSS variables (modern.css).+ backgroundColor: {+ 'surface-rail': 'var(--kw-surface-rail)',+ 'surface-side': 'var(--kw-surface-side)',+ 'surface-main': 'var(--kw-surface-main)',+ 'surface-raised': 'var(--kw-surface-raised)',+ 'surface-overlay': 'var(--kw-surface-overlay)',+ },+ borderColor: {+ hairline: 'var(--kw-hairline)',+ 'hairline-strong': 'var(--kw-hairline-strong)',+ },+ // Status colours, one meaning each: ok = healthy/kept; working = #9d8fff, warn = needs you, bad = failed, info = neutral news.+ textColor: {+ ok: 'var(--kw-ok)',+ warn: 'var(--kw-warn)',+ bad: 'var(--kw-bad)',+ info: 'var(--kw-info)',+ muted: 'var(--kw-muted)',+ },+ backgroundImage: {+ // The one accent gradient: primary buttons, the active item, the bot-home hero glow+ 'accent-gradient': 'linear-gradient(135deg, #7a62f0 0%, #5b47d6 100%)',+ 'accent-soft': 'linear-gradient(135deg, rgb(122 98 240 / 0.22) 0%, rgb(91 71 214 / 0.10) 100%)',+ },+ boxShadow: {+ card: '0 1px 0 0 rgb(255 255 255 / 0.04) inset, 0 1px 2px 0 rgb(6 3 20 / 0.5)',+ raised: '0 1px 0 0 rgb(255 255 255 / 0.05) inset, 0 6px 18px -6px rgb(6 3 20 / 0.7)',+ glow: '0 0 0 1px rgb(157 143 255 / 0.35), 0 8px 24px -8px rgb(122 98 240 / 0.55)',+ },+ // Softer corners: buttons 8-10px, cards 12px, panels 16px (chips use rounded-full)borderRadius: {- lg: '0.375rem',- xl: '0.5rem',- '2xl': '0.625rem',- '3xl': '0.75rem',+ lg: '0.5rem',+ xl: '0.625rem',+ '2xl': '0.75rem',+ '3xl': '1rem',+ },+ // A named type scale. `text-2xs` is the smallest allowed (badges only); body copy is 14px.+ fontSize: {+ '2xs': ['0.6875rem', { lineHeight: '1rem' }],+ meta: ['0.75rem', { lineHeight: '1.125rem' }],+ body: ['0.875rem', { lineHeight: '1.375rem' }],+ title: ['1.0625rem', { lineHeight: '1.5rem', letterSpacing: '-0.01em' }],+ display: ['1.5rem', { lineHeight: '1.875rem', letterSpacing: '-0.02em' }],},fontFamily: {sans: ['Inter', '-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Roboto', 'sans-serif'],diff --git a/frontend/tests/approvalsOff.test.mjs b/frontend/tests/approvalsOff.test.mjsindex 84e15a52..e9365685 100644--- a/frontend/tests/approvalsOff.test.mjs+++ b/frontend/tests/approvalsOff.test.mjs@@ -236,8 +236,13 @@ test('every approvals-off hover hint says payments still ask: badge, sidebar rowassert.match(m.badge({}), /title="[^"]*Payments still ask you\.[^"]*"/);const html = m.sidebar({ space: space('off'), kwants: [bot('k1', 'Dev', 'inherit', 'off')] });const tips = [...html.matchAll(/title="([^"]*without asking[^"]*)"/g)].map((x) => x[1]);- assert.equal(tips.length, 2, 'the space header line and the bot row');+ assert.equal(tips.length, 1, 'said once, on the space header line: a bot that matches the space adds no icon');for (const t of tips) assert.match(t, /Payments still ask you\./);+ const differing = m.sidebar({ space: space('ask'), kwants: [bot('k1', 'Dev', 'off', 'off')] });+ const botTips = [...differing.matchAll(/title="([^"]*without asking[^"]*)"/g)].map((x) => x[1]);+ assert.equal(botTips.length, 2, 'the space header summary and the bot that differs from the space');+ assert.ok(botTips.some((t) => /^Dev acts without asking/.test(t)), 'a bot that differs from the space still shows its own icon');+ for (const t of botTips) assert.match(t, /Payments still ask you\./);assert.match(m.spaceSetting({ value: 'off' }), /title="Approvals are off in Work\. Payments still ask you\."/);// The chat header badge lives in App.tsx, which doesn't render here: check every title passed to the marker.const { readFile } = await import('node:fs/promises');diff --git a/frontend/tests/uiRefreshSignature.test.mjs b/frontend/tests/uiRefreshSignature.test.mjsnew file mode 100644index 00000000..0b647f3b--- /dev/null+++ b/frontend/tests/uiRefreshSignature.test.mjs@@ -0,0 +1,283 @@+// PR 1 of the 0.6.9 UI refresh: bot home helpers, avatar moods, tab signal, stickers, "New" tags.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const store = new Map();+globalThis.localStorage = { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => void store.set(k, String(v)), removeItem: (k) => void store.delete(k) };++const m = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { Sticker } from './src/components/Sticker';+ import { AvatarMood } from './src/components/AvatarMood';+ import { ModernAvatar } from './src/components/ModernAvatar';+ import { MentionPopover } from './src/components/MentionPopover';+ import { BotHome } from './src/components/BotHome';+ export * from './src/botHome';+ export * from './src/kwantMood';+ export * from './src/tabSignal';+ export * from './src/whatsNew';+ export { clampTilt } from './src/components/Sticker';+ export { MOOD_GLYPHS, moodBadge } from './src/components/AvatarMood';+ export { turnStarted, turnEnded, clearAllTurns } from './src/kwantActivity';+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));+ export const sticker = (p, kids = 'Verified') => r(Sticker, p, kids);+ export const mood = (p) => r(AvatarMood, p);+ export const avatar = (p) => r(ModernAvatar, p);+ export const mentions = (p) => r(MentionPopover, p);+ export const botHome = (p) => r(BotHome, p);+`);++// ---- bot home helpers+test('goodAt: only the bot\'s own covers; none beyond the role means no chips; four at most, short, no repeats', () => {+ assert.deepEqual(m.goodAt({ title: 'Nutrition & Diet Advisor' }), []);+ assert.deepEqual(m.goodAt({ title: 'Nutritionist', covers: ['nutritionist', ' '] }), []);+ assert.deepEqual(m.goodAt({ title: 'x', covers: ['meal plans', 'Meal plans', 'macros'] }), ['meal plans', 'macros']);+ assert.equal(m.goodAt({ title: 'x', covers: ['a', 'b', 'c', 'd', 'e', 'f'] }).length, 4);+ assert.ok(m.goodAt({ title: 'x', covers: ['y'.repeat(80)] })[0].length <= 32);+});++test('recentWork: newest two chats that are not archived or delegations; undefined until loaded', () => {+ assert.equal(m.recentWork(undefined), undefined);+ const t = (id, at, extra = {}) => ({ id, title: id, updated_at: at, ...extra });+ const out = m.recentWork([t('a', '2026-11-01'), t('b', '2026-11-03'), t('c', '2026-11-02', { archived: true }), t('d', '2026-11-02', { kind: 'delegation' }), t('e', '2026-11-02')]);+ assert.deepEqual(out.map((x) => x.id), ['b', 'e']);+});++test('recipientsOf: the bot whose chat it is plus every @mentioned bot, whole names only', () => {+ const bots = [{ id: '1', name: 'Dev' }, { id: '2', name: 'Dev Ops' }, { id: '3', name: 'Ana.lyst' }];+ assert.deepEqual(m.recipientsOf('hello', bots, '1'), ['1']);+ assert.deepEqual(m.recipientsOf('hi @dev please', bots), ['1']);+ assert.deepEqual(m.recipientsOf('@Dev Ops and @Ana.lyst', bots).sort(), ['1', '2', '3']);+ assert.deepEqual(m.recipientsOf('mail [email protected]', bots), [], 'an email address is not a mention');+ assert.deepEqual(m.recipientsOf('@Developer', bots), [], 'only whole names');+});++// ---- mood selection+const now = 1_000_000;+const base = { working: false, now };+test('selectMood: needs you beats everything; a running turn beats resting; thinking is a running turn with no output yet', () => {+ assert.equal(m.selectMood({ ...base, working: true, needsYou: true }), 'needs_you');+ assert.equal(m.selectMood({ ...base, working: true, thinking: true }), 'thinking');+ assert.equal(m.selectMood({ ...base, working: true }), 'working');+ const later = new Date(now + 60_000);+ assert.equal(m.selectMood({ ...base, working: true, restingUntil: later }), 'working');+ assert.equal(m.selectMood({ ...base, restingUntil: later }), 'resting');+ assert.equal(m.selectMood({ ...base, restingUntil: new Date(now - 1) }), 'idle', 'a limit that has passed is gone');+});+test('selectMood: finished fades after a moment, failed stays until the next turn or ten minutes, cancelled shows nothing', () => {+ assert.equal(m.selectMood({ ...base, last: { outcome: 'completed', at: now - 1000 } }), 'finished');+ assert.equal(m.selectMood({ ...base, last: { outcome: 'completed', at: now - m.FINISHED_MS - 1 } }), 'idle');+ assert.equal(m.selectMood({ ...base, last: { outcome: 'failed', at: now - 5 * 60_000 } }), 'failed');+ assert.equal(m.selectMood({ ...base, last: { outcome: 'failed', at: now - m.FAILED_MS - 1 } }), 'idle');+ assert.equal(m.selectMood({ ...base, last: { outcome: 'cancelled', at: now } }), 'idle');+ assert.equal(m.selectMood({ ...base, working: true, last: { outcome: 'failed', at: now } }), 'working');+});+test('moodLabel: words for the tooltip, "Resting until 03:00" for quota', () => {+ const at = new Date(2026, 10, 3, 3, 0);+ assert.equal(m.moodLabel('resting', 'Dev', at, new Date(2026, 10, 3, 1, 0).getTime()), 'Resting until 03:00');+ assert.equal(m.moodLabel('needs_you', 'Dev'), 'Dev needs you');+ assert.equal(m.moodLabel('failed', 'Dev'), "Dev's last turn failed");+ assert.equal(m.moodLabel('idle', 'Dev'), null);+ assert.equal(m.moodLabel('working', 'Dev'), null, "working keeps the avatar's own words");+});+test('restingUntil: a family rests when every switched-on account of it is out; auto only when all are', () => {+ const t = (mins) => new Date(Date.now() + mins * 60_000).toISOString();+ const p = (engine, limited_until, enabled = true) => ({ engine, limited_until, enabled });+ const profiles = [p('claude', t(30)), p('claude', t(90)), p('codex', null)];+ assert.ok(m.restingUntil('claude', profiles), 'claude is out');+ const until = m.restingUntil('claude', profiles);+ assert.ok(Math.abs(until.getTime() - Date.parse(t(30))) < 5000, 'the earliest return wins');+ assert.equal(m.restingUntil('codex', profiles), null);+ assert.equal(m.restingUntil('auto', profiles), null, 'codex can still run');+ assert.equal(m.restingUntil('auto', [p('claude', t(30)), p('codex', t(60))]).getTime() > Date.now(), true);+ assert.equal(m.restingUntil('claude', [p('claude', t(30), false)]), null, 'a switched-off account is not a limit');+ assert.equal(m.restingUntil('claude', undefined), null);+});++// ---- the store and the component+test('mood store: thinking until output, finished then fades, failed sticks; noticed bumps the blink counter', () => {+ m.clearMoods();+ m.clearAllTurns();+ m.turnStarted('k1', 't1');+ m.moodTurnStarted('k1');+ assert.equal(m.moodOf('k1'), 'thinking');+ m.moodOutput('k1');+ assert.equal(m.moodOf('k1'), 'working');+ m.turnEnded('k1', 't1');+ m.moodTurnEnded('k1', 'completed');+ assert.equal(m.moodOf('k1'), 'finished');+ m.moodTurnStarted('k1');+ m.moodTurnEnded('k1', 'failed');+ assert.equal(m.moodOf('k1'), 'failed');+ m.setMoodNeedsYou(['k1']);+ assert.equal(m.moodOf('k1'), 'needs_you');+ m.setMoodNeedsYou([]);+ m.setMoodResting({ k1: new Date(Date.now() + 3_600_000) });+ assert.equal(m.moodOf('k1'), 'resting');+ assert.equal(m.noticesOf('k1'), 0);+ m.moodNoticed('k1');+ assert.equal(m.noticesOf('k1'), 1);+ m.clearMoods();+});+test('AvatarMood draws a mark per mood, nothing for working or idle', () => {+ for (const mood of ['thinking', 'finished', 'failed', 'needs_you', 'resting']) assert.match(m.mood({ mood, size: 32 }), new RegExp(`data-mood="${mood}"`), mood);+ assert.equal(m.mood({ mood: 'working', size: 32 }), '');+ assert.equal(m.mood({ mood: 'idle', size: 32 }), '');+});+test('AvatarMood badge: own 7x7 grid, 2 px cells to 40 px, 4 px at 96 px; "!" for needs you', () => {+ assert.deepEqual(m.moodBadge(24), { cellPx: 2, px: 14, offset: -4, radius: 2, cut: 1 });+ assert.deepEqual(m.moodBadge(40), { cellPx: 2, px: 14, offset: -4, radius: 2, cut: 1 });+ assert.deepEqual(m.moodBadge(96), { cellPx: 4, px: 28, offset: -6, radius: 4, cut: 2 });+ assert.match(m.mood({ mood: 'failed', size: 96 }), /width="28"/);+ assert.match(m.mood({ mood: 'failed', size: 28 }), /viewBox="0 0 7 7"/);+ assert.deepEqual(m.MOOD_GLYPHS.needs_you.cells, [[2, 0], [2, 1], [2, 2], [2, 4]]);+ assert.equal(m.MOOD_GLYPHS.needs_you.color, '#ffb020');+ for (const g of Object.values(m.MOOD_GLYPHS)) for (const [x, y] of g.cells) assert.ok(x >= 0 && x < 5 && y >= 0 && y < 5);+});+test('ModernAvatar with a kwantId carries the mood and its words', () => {+ m.clearMoods();+ m.setMoodNeedsYou(['kx']);+ const html = m.avatar({ role: 'qa', name: 'Dev', size: 32, kwantId: 'kx' });+ assert.match(html, /data-mood="needs_you"/);+ assert.match(html, /title="Dev needs you"/);+ m.setMoodNeedsYou([]);+ m.setMoodResting({ kx: new Date(Date.now() + 3_600_000) });+ assert.match(m.avatar({ role: 'qa', name: 'Dev', size: 32, kwantId: 'kx' }), /kw-avatar-resting/);+ m.clearMoods();+ assert.doesNotMatch(m.avatar({ role: 'qa', name: 'Dev', size: 32, kwantId: 'kx' }), /data-mood/);+});++// ---- tab signal+test('tabTitle: "(N) kwant" for N things that need you, the plain title for none, a page title kept', () => {+ assert.equal(m.tabTitle('kwant', 2), '(2) kwant');+ assert.equal(m.tabTitle('(2) kwant', 0), 'kwant');+ assert.equal(m.tabTitle('(2) kwant', 3), '(3) kwant');+ assert.equal(m.tabTitle('Sandbox · kwant bots browser', 1), '(1) Sandbox · kwant bots browser');+ assert.equal(m.tabTitle('kwant', 120), '(99+) kwant');+ assert.equal(m.tabTitle('', 1), '(1) kwant');+});+test('needsYouCount: bots waiting on you plus approvals', () => {+ assert.equal(m.needsYouCount({ a: 'needs_you', b: 'working', c: 'needs_you' }, 1), 3);+ assert.equal(m.needsYouCount({}, 0), 0);+ assert.equal(m.needsYouCount({ a: 'available' }, -2), 0);+});+test('tab signal: title follows the count; the dotted icon is set while working and restored when idle', async () => {+ const link = { href: '/icon.svg', type: 'image/svg+xml' };+ const doc = { title: 'kwant bots', iconLink: () => link, drawDotted: async () => 'data:image/png;base64,AAA' };+ const sig = m.createTabSignal(doc);+ sig.setNeedsYou(2);+ assert.equal(doc.title, '(2) kwant bots');+ sig.setNeedsYou(0);+ assert.equal(doc.title, 'kwant bots');+ await sig.setWorking(true);+ assert.equal(link.href, 'data:image/png;base64,AAA');+ await sig.setWorking(false);+ assert.equal(link.href, '/icon.svg');+ assert.equal(link.type, 'image/svg+xml');+ // Idle again before the image finished drawing: the icon is left alone.+ let release;+ const slow = { title: 't', iconLink: () => link, drawDotted: () => new Promise((r) => (release = r)) };+ const sig2 = m.createTabSignal(slow);+ const pending = sig2.setWorking(true);+ await sig2.setWorking(false);+ release('data:image/png;base64,BBB');+ await pending;+ assert.equal(link.href, '/icon.svg');+});+test('dotGeometry sits in the bottom-right corner inside the icon', () => {+ const g = m.dotGeometry(64);+ assert.ok(g.cx + g.r + g.ring <= 64 + 1 && g.cy + g.r + g.ring <= 64 + 1 && g.cx > 32 && g.cy > 32);+});++// ---- stickers and "New" tags+test('Sticker: tone, clamped tilt, button only when clickable', () => {+ assert.match(m.sticker({ tone: 'holo' }), /kw-sticker-holo/);+ assert.match(m.sticker({ tone: 'holo' }), /--kw-tilt:-2deg/);+ assert.match(m.sticker({}), /kw-sticker-ink/);+ assert.match(m.sticker({ tilt: 9 }), /--kw-tilt:3deg/);+ assert.match(m.sticker({ tilt: -9 }), /--kw-tilt:-3deg/);+ assert.equal(m.clampTilt(Number.NaN, 1), 1);+ assert.match(m.sticker({}), /^<span/);+ assert.match(m.sticker({ onClick() {} }), /^<button type="button"[^>]*class="kw-sticker-hit"/);+ assert.match(m.sticker({ size: 'sm' }), /kw-sticker-sm/);+});+test('what\'s new: shown until used once, then gone for good; no storage shows nothing', () => {+ const mem = new Map();+ const s = { getItem: (k) => (mem.has(k) ? mem.get(k) : null), setItem: (k, v) => void mem.set(k, v) };+ assert.equal(m.isNewThing('mention', s), true);+ m.markNewSeen('mention', s);+ assert.equal(m.isNewThing('mention', s), false);+ assert.equal(m.isNewThing('starters', s), true, 'each thing is tracked on its own');+ assert.equal(m.isNewThing('mention', null), false);+ assert.match(m.newKey('mention'), /0\.6\.9/);+});++// ---- mention picker and bot home+test('mention picker: avatar, name and a one-line "good at", options a screen reader can follow', () => {+ const html = m.mentions({ selectedIndex: 1, onSelect() {}, items: [+ { type: 'kwant', id: 'a', name: 'Dev', title: 'Engineer', goodAt: ['code review', 'refactors'], avatar_sprite: 'tech_lead' },+ { type: 'kwant', id: 'b', name: 'Ana', title: 'Analyst' },+ ] });+ assert.match(html, /role="listbox"/);+ assert.equal((html.match(/role="option"/g) ?? []).length, 2);+ assert.match(html, /aria-selected="true"/);+ assert.match(html, /Good at code review · refactors/);+ assert.match(html, />Analyst</, 'falls back to the role when there is no good-at');+ assert.match(html, /kw-avatar/);+});+test('bot home: name, role, good-at chips and starter cards', () => {+ const html = m.botHome({ home: { kind: 'bot', bot: { id: 'n', name: 'Nora', title: 'Nutrition & Diet Advisor', avatar_sprite: 'chef' }, recent: [] }, spaceName: 'Home', team: [], prompts: ['plan my week', 'count macros'], canRun: true, onPick() {} });+ assert.match(html, /Nora/);+ assert.match(html, /Nutrition/);+ assert.match(html, /Plan my week/);+});++// ---- Mira's review of PR #264 (design/review-pr264.md)+import { readFileSync } from 'node:fs';+const css = readFileSync(new URL('../src/styles/modern.css', import.meta.url), 'utf8');+const src = (f) => readFileSync(new URL(`../src/components/${f}`, import.meta.url), 'utf8');++test('holo v2: a two-cycle 105deg linear foil at .8 slid by transform, a glint band on --mx; no conic', () => {+ const before = [...css.matchAll(/\.kw-sticker-holo::before \{[^}]*\}/g)].map((x) => x[0]).find((b) => b.includes('background'));+ assert.match(before, /linear-gradient\(105deg/);+ assert.match(before, /opacity: 0\.8;/);+ assert.match(before, /transform: translateX\(calc\(\(50% - var\(--mx\)\) \/ 4\)\)/);+ assert.doesNotMatch(css, /conic-gradient/);+ assert.match([...css.matchAll(/\.kw-sticker-holo::after \{[^}]*\}/g)].at(-1)[0], /rgb\(255 255 255 \/ 0\.7\) var\(--mx\)/);+ assert.match(css, /@keyframes kw-sticker-drift \{\s*from \{ transform: translateX\(calc\(\(50% - var\(--mx\)\) \/ 4 - 8%\)\); \}/);+});++test('bot home glow: still at .35 when idle, breathes in violet only while working', () => {+ const idle = m.botHome({ home: { kind: 'bot', bot: { id: 'glow-idle', name: 'Ann', title: 'Writer', avatar_sprite: 'x' } }, prompts: [], onPick: () => {} });+ assert.match(idle, /data-glow="still"/);+ assert.doesNotMatch(idle, /kw-glow/);+ assert.match(idle, /opacity-35/);+ m.turnStarted('glow-busy', 't1');+ m.moodTurnStarted('glow-busy');+ m.moodOutput('glow-busy');+ const busy = m.botHome({ home: { kind: 'bot', bot: { id: 'glow-busy', name: 'Bo', title: 'Writer', avatar_sprite: 'x' } }, prompts: [], onPick: () => {} });+ assert.match(busy, /kw-glow bg-\[#9d8fff\]/);+ assert.match(busy, /motion-reduce:opacity-50/);+ m.clearAllTurns();+ m.clearMoods();+});++test('sidebar heads say "+ Team" / "+ Bot" / "+ Channel" with the full phrase as the label, and never wrap', () => {+ const s = src('Sidebar.tsx');+ for (const [w, l] of [['Team', 'New team'], ['Bot', 'New bot'], ['Channel', 'New channel']]) assert.ok(s.includes(`headButton('${w}', '${l}'`), w);+ assert.match(s, /className="shrink-0 whitespace-nowrap flex items-center gap-1 text-2xs/);+ assert.match(s, /min-h-11 px-3 shrink-0 whitespace-nowrap/);+ assert.match(s, /whitespace-nowrap shrink-0">Bots \(/);+ // Working in the busy line is violet, like the avatar dot; never teal+ assert.match(s, /'text-\[#b8adff\]'/);+ assert.match(s, /'bg-\[#9d8fff\] kw-pulse'/);+});++test('composer: 44 px buttons on phones; "New" on @ clears when the picker opens and hides under it', () => {+ const c = src('ChatView.tsx');+ assert.equal((c.match(/w-11 h-11 sm:w-9 sm:h-9/g) || []).length, 4);+ assert.match(c, /if \(isMentionOpen\) markNewSeen\('mention'\)/);+ assert.match(c, /\$\{isMentionOpen \? 'hidden' : ''\}/);+});