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
Add agent continuity UI: instructions, search, memory, routines, notifications
Lin (kwant bot)826eed18b8d3
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 666de52e..0704b497 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -3,7 +3,6 @@ import { AppHeader } from './components/AppHeader';import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';import { ChatView, ChatMessage, DiscussionState, RoutingState } from './components/ChatView';import { PendingApproval } from './components/ModernApprovalCard';-import { SettingsModal } from './components/SettingsModal';import type { AgentFormData } from './components/NewAgentModal';import { NewTeamModal } from './components/NewTeamModal';import { ManageTeamModal } from './components/ManageTeamModal';@@ -11,12 +10,29 @@ import { playSfx } from './audio/chiptune';import { Toasts, Toast } from './components/Toasts';import { clearAllTurns, turnEnded, turnStarted } from './kwantActivity';import { Profile, describeProfileSwitch, profilesApi } from './profiles';+import {+ NotifyEvent,+ SearchHit,+ browserNotifyEnabled,+ channelLabel,+ continuityApi,+ emitContinuity,+ notificationPermission,+ shouldShowOsNotification,+} from './continuity';+import type { PinnedItem } from './components/Instructions';// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),// so both load right after start-up and opening them never waits.const NewAgentModal = lazy(() => import('./components/NewAgentModal').then((m) => ({ default: m.NewAgentModal })));const McpServersModal = lazy(() => import('./components/McpServersModal').then((m) => ({ default: m.McpServersModal })));const ProfilesModal = lazy(() => import('./components/ProfilesModal').then((m) => ({ default: m.ProfilesModal })));+const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal })));+const ChannelInstructionsModal = lazy(() =>+ import('./components/ChannelInstructionsModal').then((m) => ({ default: m.ChannelInstructionsModal })),+);+const SearchModal = lazy(() => import('./components/SearchModal').then((m) => ({ default: m.SearchModal })));+const RoutinesModal = lazy(() => import('./components/RoutinesModal').then((m) => ({ default: m.RoutinesModal })));export const App: React.FC = () => {const [kwants, setKwants] = useState<Kwant[]>([]);@@ -60,10 +76,34 @@ export const App: React.FC = () => {const [isSettingsOpen, setIsSettingsOpen] = useState(false);const [isMcpOpen, setIsMcpOpen] = useState(false);const [isProfilesOpen, setIsProfilesOpen] = useState(false);+ const [isSearchOpen, setIsSearchOpen] = useState(false);+ const [isRoutinesOpen, setIsRoutinesOpen] = useState(false);+ const [editingChannelInstructions, setEditingChannelInstructions] = useState<Channel | null>(null);+ const [highlightMessageId, setHighlightMessageId] = useState<string | null>(null);const [profiles, setProfiles] = useState<Profile[]>([]);const [toasts, setToasts] = useState<Toast[]>([]);const toastIdRef = useRef(0);const dismissToast = useCallback((id: number) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);+ // Set each render once the select handlers exist; the SSE handler and notification clicks go through it.+ const openTargetRef = useRef<(t: { channel_id: string | null; kwant_id: string | null }) => boolean>(() => false);+ const showNotification = (n: NotifyEvent) => {+ if (!document.hidden && n.kind === 'routine_failed') {+ const id = ++toastIdRef.current;+ setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body }]);+ return;+ }+ if (!shouldShowOsNotification({ enabled: browserNotifyEnabled(), permission: notificationPermission(), hidden: document.hidden, kind: n.kind })) return;+ try {+ const note = new Notification(n.title, { body: n.body, tag: `kwnt-${n.kind}-${n.channel_id ?? n.kwant_id}` });+ note.onclick = () => {+ window.focus();+ openTargetRef.current({ channel_id: n.channel_id, kwant_id: n.kwant_id });+ note.close();+ };+ } catch {+ // Some mobile browsers only allow notifications from a service worker.+ }+ };const refreshProfiles = useCallback(() => {profilesApi.list().then(setProfiles, () => undefined);}, []);@@ -192,6 +232,18 @@ export const App: React.FC = () => {refreshProfiles();break;}+ case 'memory_changed':+ case 'MemoryChanged':+ emitContinuity({ type: 'memory_changed', data: event.data });+ break;+ case 'routine_run':+ case 'RoutineRun':+ emitContinuity({ type: 'routine_run', data: event.data });+ break;+ case 'notify':+ case 'Notify':+ showNotification(event.data as NotifyEvent);+ break;case 'TextDelta':setStreamingText((prev) => prev + event.data);playSfx('blip');@@ -650,6 +702,68 @@ export const App: React.FC = () => {playSfx('click');};+ /** Opens a channel, or the direct chat with a kwant when there's no channel. False if it's gone. */+ const openTarget = (t: { channel_id: string | null; kwant_id: string | null }): boolean => {+ if (t.channel_id) {+ const channel = channels.find((c) => c.id === t.channel_id);+ if (!channel) return false;+ if (selectedIdRef.current !== channel.id) handleSelectChannel(channel);+ return true;+ }+ const kwant = kwants.find((k) => k.id === t.kwant_id);+ if (!kwant) return false;+ if (selectedIdRef.current !== kwant.id) handleSelectKwant(kwant);+ return true;+ };+ openTargetRef.current = openTarget;++ const pushToast = (title: string, detail?: string) => {+ const id = ++toastIdRef.current;+ setToasts((prev) => [...prev.slice(-2), { id, title, detail }]);+ };++ // Search result picked: open its chat, then scroll to the message if it's among the ones loaded.+ const handleJump = async (hit: SearchHit) => {+ const targetId = hit.channel_id ?? hit.kwant_id;+ if (!targetId || !openTarget(hit)) {+ pushToast('That chat no longer exists.');+ return;+ }+ try {+ const res = await fetch(`/api/channels/${encodeURIComponent(targetId)}/messages`);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data: ChatMessage[] = await res.json();+ messagesCacheRef.current[targetId] = data;+ if (selectedIdRef.current === targetId) setMessages(data);+ if (data.some((m) => m.id === hit.message_id)) setHighlightMessageId(hit.message_id);+ else pushToast('Opened the chat', 'That message is older than the latest 100 shown here.');+ } catch {+ pushToast('Could not load that chat.');+ }+ };++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') {+ e.preventDefault();+ setIsSearchOpen((v) => !v);+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);++ const saveChannelInstructions = async (text: string): Promise<string | void> => {+ const channel = editingChannelInstructions;+ if (!channel) return;+ try {+ const updated = await continuityApi.setChannelInstructions(channel.id, text);+ setChannels((prev) => prev.map((c) => (c.id === channel.id ? { ...c, instructions: updated.instructions } : c)));+ } catch (err) {+ return err instanceof Error ? err.message : 'Could not save.';+ }+ };+const saveKwantMcpServers = async (kwantId: string, serverIds: string[] | undefined): Promise<string | void> => {if (serverIds === undefined) return;const res = await fetch(`/api/kwants/${kwantId}/mcp-servers`, {@@ -810,6 +924,7 @@ export const App: React.FC = () => {repo_url?: string;lead_kwant_id: string;member_kwants: string[];+ instructions?: string;}) => {try {@@ -1072,6 +1187,11 @@ export const App: React.FC = () => {const closeProfiles = useCallback(() => setIsProfilesOpen(false), []);const isCurrentContextStreaming = isStreaming && streamingContextId === selectedId;+ const pinned: PinnedItem[] = [];+ if (currentTeam?.instructions?.trim()) pinned.push({ label: `Team @${currentTeam.name}`, text: currentTeam.instructions });+ if (isChannel && currentChannel?.instructions?.trim())+ pinned.push({ label: `Channel ${channelLabel(currentChannel.name)}`, text: currentChannel.instructions });+const isDiscussionActiveHere =discussionState.inProgress &&(discussionState.contextId === selectedId ||@@ -1084,6 +1204,8 @@ export const App: React.FC = () => {<AppHeaderonOpenSettings={() => setIsSettingsOpen(true)}onOpenTools={() => setIsMcpOpen(true)}+ onOpenSearch={() => setIsSearchOpen(true)}+ onOpenRoutines={() => setIsRoutinesOpen(true)}tokensUsed={tokensUsed}activeModel={currentKwant?.preferred_model || 'auto'}/>@@ -1168,6 +1290,17 @@ export const App: React.FC = () => {onRefreshVm={handleRefreshVm}onRestartVm={handleRestartVm}onNavigateVm={handleNavigateVm}+ pinned={pinned}+ onEditInstructions={+ isChannel && currentChannel+ ? () => {+ setEditingChannelInstructions(currentChannel);+ playSfx('click');+ }+ : undefined+ }+ highlightMessageId={highlightMessageId}+ onHighlightDone={() => setHighlightMessageId(null)}/></div>@@ -1192,6 +1325,8 @@ export const App: React.FC = () => {isOpen={!!editingKwant}initial={editingKwant}kwantId={editingKwant?.id}+ kwants={kwants}+ channels={channels}profiles={profiles}onManageProfiles={() => setIsProfilesOpen(true)}onManageServers={() => setIsMcpOpen(true)}@@ -1219,25 +1354,40 @@ export const App: React.FC = () => {/>{/* Settings Modal */}- <SettingsModal- isOpen={isSettingsOpen}- onClose={() => setIsSettingsOpen(false)}- onOpenTools={() => {- setIsSettingsOpen(false);- setIsMcpOpen(true);- }}- onOpenProfiles={() => {- setIsSettingsOpen(false);- setIsProfilesOpen(true);- }}- />+ <Suspense fallback={null}>+ <SettingsModal+ isOpen={isSettingsOpen}+ onClose={() => setIsSettingsOpen(false)}+ onOpenTools={() => {+ setIsSettingsOpen(false);+ setIsMcpOpen(true);+ }}+ onOpenProfiles={() => {+ setIsSettingsOpen(false);+ setIsProfilesOpen(true);+ }}+ />+ </Suspense>{/* MCP tool servers (opened last so it sits above the agent modal) */}<Suspense fallback={null}><McpServersModal isOpen={isMcpOpen} onClose={() => setIsMcpOpen(false)} kwants={kwants} /><ProfilesModal isOpen={isProfilesOpen} onClose={closeProfiles} onProfilesChanged={setProfiles} />+ {isSearchOpen && <SearchModal isOpen onClose={() => setIsSearchOpen(false)} kwants={kwants} onJump={handleJump} />}+ {isRoutinesOpen && <RoutinesModal isOpen onClose={() => setIsRoutinesOpen(false)} kwants={kwants} channels={channels} />}</Suspense>+ {editingChannelInstructions && (+ <Suspense fallback={null}>+ <ChannelInstructionsModal+ channelLabel={channelLabel(editingChannelInstructions.name)}+ initial={editingChannelInstructions.instructions ?? ''}+ onClose={() => setEditingChannelInstructions(null)}+ onSave={saveChannelInstructions}+ />+ </Suspense>+ )}+<Toasts toasts={toasts} onDismiss={dismissToast} /></div>);diff --git a/frontend/src/components/AppHeader.tsx b/frontend/src/components/AppHeader.tsxindex e669b7df..9cbaccbf 100644--- a/frontend/src/components/AppHeader.tsx+++ b/frontend/src/components/AppHeader.tsx@@ -1,15 +1,19 @@import React from 'react';-import { Settings, Volume2, VolumeX, Cpu, Plug } from 'lucide-react';+import { Settings, Volume2, VolumeX, Cpu, Plug, Search, CalendarClock } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { isSfxMuted, toggleSfxMute, playSfx } from '../audio/chiptune';interface AppHeaderProps {onOpenSettings: () => void;onOpenTools: () => void;+ onOpenSearch: () => void;+ onOpenRoutines: () => void;tokensUsed: number;activeModel?: string;}+const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);+type LayaState = 'unknown' | 'external' | 'installing' | 'starting' | 'online' | 'offline' | 'failed';interface LayaStatus {@@ -67,6 +71,8 @@ const layaPill = (status: LayaStatus | null, activeModel: string) => {export const AppHeader: React.FC<AppHeaderProps> = ({onOpenSettings,onOpenTools,+ onOpenSearch,+ onOpenRoutines,tokensUsed,activeModel = 'auto',}) => {@@ -123,6 +129,34 @@ export const AppHeader: React.FC<AppHeaderProps> = ({{sfxMuted ? <VolumeX size={17} /> : <Volume2 size={17} />}</button>+ <button+ onClick={() => {+ playSfx('click');+ onOpenSearch();+ }}+ title="Search all chats (Ctrl/⌘ K)"+ aria-label="Search"+ aria-keyshortcuts="Control+K Meta+K"+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"+ >+ <Search size={14} className="text-zinc-400" />+ <span className="hidden md:inline">Search</span>+ <kbd className="hidden md:inline text-[10px] font-mono text-zinc-500">{isMac ? '⌘K' : 'Ctrl K'}</kbd>+ </button>++ <button+ onClick={() => {+ playSfx('click');+ onOpenRoutines();+ }}+ title="Routines: scheduled work for your kwants"+ aria-label="Routines"+ className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700/80 border border-zinc-700/60 transition-all hover:border-zinc-600 shadow-sm"+ >+ <CalendarClock size={14} className="text-amber-300" />+ <span className="hidden sm:inline">Routines</span>+ </button>+{/* MCP Tools Button */}<buttononClick={() => {diff --git a/frontend/src/components/ChannelInstructionsModal.tsx b/frontend/src/components/ChannelInstructionsModal.tsxnew file mode 100644index 00000000..e2716248--- /dev/null+++ b/frontend/src/components/ChannelInstructionsModal.tsx@@ -0,0 +1,99 @@+import React, { useEffect, useRef, useState } from 'react';+import { Pin, X } from 'lucide-react';+import { MAX_INSTRUCTIONS } from '../continuity';+import { playSfx } from '../audio/chiptune';+import { InstructionsField } from './Instructions';++/** Edits one channel's pinned instructions. */+export const ChannelInstructionsModal: React.FC<{+ channelLabel: string | null;+ initial: string;+ onClose: () => void;+ onSave: (text: string) => Promise<string | void>;+}> = ({ channelLabel, initial, onClose, onSave }) => {+ const [text, setText] = useState(initial);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const closeRef = useRef(onClose);+ closeRef.current = onClose;++ useEffect(() => {+ setText(initial);+ setError(null);+ }, [initial, channelLabel]);++ useEffect(() => {+ if (!channelLabel) return;+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeRef.current();+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [channelLabel]);++ if (!channelLabel) return null;+ const over = text.length > MAX_INSTRUCTIONS;++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (over) return;+ setSaving(true);+ setError(null);+ const err = await onSave(text.trim());+ setSaving(false);+ if (err) setError(err);+ else {+ playSfx('coin');+ onClose();+ }+ };++ return (+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <form+ role="dialog"+ aria-modal="true"+ aria-labelledby="chan-instr-title"+ onSubmit={submit}+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[94vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-4"+ >+ <div className="flex items-center justify-between border-b border-zinc-800 pb-3">+ <div className="flex items-center gap-2">+ <div className="w-7 h-7 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-center justify-center text-amber-300">+ <Pin size={14} />+ </div>+ <h2 id="chan-instr-title" className="text-sm font-semibold">+ Instructions for {channelLabel}+ </h2>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors">+ <X size={17} />+ </button>+ </div>+ <InstructionsField+ value={text}+ onChange={setText}+ autoFocus+ label="Channel instructions"+ hint="Every kwant reads these before each turn in this channel. Leave empty to unpin."+ rows={7}+ />+ {error && (+ <p className="text-[11px] text-rose-400" role="alert">+ {error}+ </p>+ )}+ <div className="flex items-center justify-end gap-2.5 pt-2 border-t border-zinc-800">+ <button type="button" onClick={onClose} className="px-3.5 py-2 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors">+ Cancel+ </button>+ <button+ type="submit"+ disabled={saving || over}+ className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50"+ >+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+ </form>+ </div>+ );+};diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex d5d3fb60..a822077d 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1,5 +1,5 @@import React, { useState, useRef, useEffect } from 'react';-import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu, Users, Square, Settings2, Folder, GitBranch, Pencil } from 'lucide-react';+import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';import { MentionPopover, MentionItem } from './MentionPopover';@@ -8,6 +8,7 @@ import { ToolCallsList } from './ToolCallsList';import { VirtualMachinePane, TerminalLogEntry } from './VirtualMachinePane';import { playSfx } from '../audio/chiptune';import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThreads';+import { PinnedInstructions, PinnedItem } from './Instructions';export interface ChatMessage {id: string;@@ -87,6 +88,13 @@ export interface ChatViewProps {onRefreshVm?: () => void;onRestartVm?: () => void;onNavigateVm?: (url: string) => void;+ /** Pinned team/channel instructions, shown collapsed above the messages. */+ pinned?: PinnedItem[];+ /** Opens the channel's instructions editor; only for channels. */+ onEditInstructions?: () => void;+ /** A message to scroll to and flash (from search). */+ highlightMessageId?: string | null;+ onHighlightDone?: () => void;}export const renderFormattedText = (text: string): React.ReactNode => {@@ -211,6 +219,10 @@ export const ChatView: React.FC<ChatViewProps> = ({onRefreshVm,onRestartVm,onNavigateVm,+ pinned = [],+ onEditInstructions,+ highlightMessageId,+ onHighlightDone,}) => {const [internalIsVmPaneOpen, setInternalIsVmPaneOpen] = useState(false);const vmOpen = isVmPaneOpen !== undefined ? isVmPaneOpen : internalIsVmPaneOpen;@@ -347,6 +359,31 @@ export const ChatView: React.FC<ChatViewProps> = ({}}, [messages, streamingText, streamingThinking, pendingApproval, routingState]);+ // Jump to a search hit: open its folded discussion if needed, then centre and flash it.+ // Runs after the auto-scroll above, so it wins.+ const [flashId, setFlashId] = useState<string | null>(null);+ useEffect(() => {+ if (!highlightMessageId || !messages.some((m) => m.id === highlightMessageId)) return;+ const thread = groupDiscussionThreads(messages).find(+ (item) => item.kind === 'thread' && item.turns.some((t) => t.id === highlightMessageId),+ );+ if (thread && thread.kind === 'thread' && !openThoughts[`thread:${thread.id}`]) {+ setOpenThoughts((prev) => ({ ...prev, [`thread:${thread.id}`]: true }));+ return;+ }+ const el = scrollRef.current?.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(highlightMessageId)}"]`);+ if (!el) return;+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;+ el.scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' });+ setFlashId(highlightMessageId);+ onHighlightDone?.();+ }, [highlightMessageId, messages, openThoughts, onHighlightDone]);+ useEffect(() => {+ if (!flashId) return;+ const t = setTimeout(() => setFlashId(null), 2400);+ return () => clearTimeout(t);+ }, [flashId]);+const toggleThought = (id: string) => {setOpenThoughts((prev) => ({ ...prev, [id]: !prev[id] }));};@@ -419,7 +456,10 @@ export const ChatView: React.FC<ChatViewProps> = ({return (<divkey={msg.id}- className={`flex items-start gap-3.5 w-full max-w-5xl ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''}`}+ data-message-id={msg.id}+ className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${isUser ? 'ml-auto flex-row-reverse justify-start' : ''} ${+ flashId === msg.id ? 'kw-flash' : ''+ }`}><ModernAvatarrole={isUser ? 'user' : title}@@ -562,6 +602,19 @@ export const ChatView: React.FC<ChatViewProps> = ({</div>)}+ {onEditInstructions && pinned.length === 0 && (+ <button+ type="button"+ onClick={onEditInstructions}+ className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-zinc-300 bg-zinc-800/80 hover:bg-zinc-700/80 hover:text-zinc-100 border border-zinc-700/60 transition-colors shadow-sm cursor-pointer"+ title="Pin instructions every kwant reads in this channel"+ aria-label="Pin instructions"+ >+ <Pin size={12} className="text-amber-300" />+ <span className="hidden sm:inline">Pin</span>+ </button>+ )}+{onEditKwant && (<buttontype="button"@@ -610,6 +663,8 @@ export const ChatView: React.FC<ChatViewProps> = ({</div></div>+ <PinnedInstructions items={pinned} onEdit={onEditInstructions} />+{/* Discussion In-Flight Banner */}{discussionState?.inProgress && (<div className="px-6 pt-3 select-none flex-shrink-0">diff --git a/frontend/src/components/Instructions.tsx b/frontend/src/components/Instructions.tsxnew file mode 100644index 00000000..ceec6c6a--- /dev/null+++ b/frontend/src/components/Instructions.tsx@@ -0,0 +1,98 @@+import React, { useId, useState } from 'react';+import { ChevronDown, ChevronRight, Pencil, Pin } from 'lucide-react';+import { MAX_INSTRUCTIONS } from '../continuity';++/** Instructions textarea with a live character counter; turns red past the limit. */+export const InstructionsField: React.FC<{+ value: string;+ onChange: (v: string) => void;+ label: string;+ hint: string;+ rows?: number;+ autoFocus?: boolean;+}> = ({ value, onChange, label, hint, rows = 5, autoFocus }) => {+ const id = useId();+ const over = value.length > MAX_INSTRUCTIONS;+ return (+ <div>+ <div className="flex items-center justify-between mb-1">+ <label htmlFor={id} className="text-xs font-medium text-zinc-400">+ {label}+ </label>+ <span id={`${id}-count`} className={`text-[10px] font-mono ${over ? 'text-rose-400' : 'text-zinc-500'}`} aria-live="polite">+ {value.length}/{MAX_INSTRUCTIONS}+ </span>+ </div>+ <textarea+ id={id}+ rows={rows}+ value={value}+ autoFocus={autoFocus}+ onChange={(e) => onChange(e.target.value)}+ aria-describedby={`${id}-hint ${id}-count`}+ aria-invalid={over}+ placeholder="e.g. Answer in British English. Our repo is kwant-rust; never push to main."+ className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:outline-none transition-colors resize-y ${+ over ? 'border-rose-500/70 focus:border-rose-500' : 'border-zinc-800 focus:border-sky-500'+ }`}+ />+ <p id={`${id}-hint`} className="mt-1 text-[11px] text-zinc-500">+ {over ? `${value.length - MAX_INSTRUCTIONS} characters over the limit.` : hint}+ </p>+ </div>+ );+};++export interface PinnedItem {+ label: string;+ text: string;+}++/** Pinned team/channel instructions at the top of a chat, collapsed to one line until opened. */+export const PinnedInstructions: React.FC<{ items: PinnedItem[]; onEdit?: () => void }> = ({ items, onEdit }) => {+ const [open, setOpen] = useState(false);+ const panelId = useId();+ if (items.length === 0) return null;+ const preview = items.map((i) => i.text.replace(/\s+/g, ' ')).join(' · ');+ return (+ <div className="px-3 sm:px-6 pt-3 flex-shrink-0">+ <div className="rounded-xl border border-amber-500/20 bg-amber-500/5 text-xs">+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ aria-controls={panelId}+ className="flex-1 min-w-0 flex items-center gap-2 px-3 py-2 text-left text-amber-100/90 hover:text-amber-50 rounded-xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ {open ? <ChevronDown size={13} className="shrink-0 text-amber-300" /> : <ChevronRight size={13} className="shrink-0 text-amber-300" />}+ <Pin size={12} className="shrink-0 text-amber-300" aria-hidden="true" />+ <span className="font-medium shrink-0">Pinned</span>+ {!open && <span className="truncate text-zinc-400">{preview}</span>}+ </button>+ {onEdit && (+ <button+ type="button"+ onClick={onEdit}+ aria-label="Edit pinned instructions"+ title="Edit pinned instructions"+ className="mr-1.5 p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"+ >+ <Pencil size={12} />+ </button>+ )}+ </div>+ {open && (+ <div id={panelId} className="px-3 pb-3 space-y-2 max-h-60 overflow-y-auto">+ {items.map((i) => (+ <div key={i.label}>+ <p className="text-[10px] uppercase tracking-wide text-amber-300/80 font-semibold">{i.label}</p>+ <p className="text-zinc-300 whitespace-pre-wrap break-words">{i.text}</p>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+};diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsxindex 845aed1e..7ea20727 100644--- a/frontend/src/components/ManageTeamModal.tsx+++ b/frontend/src/components/ManageTeamModal.tsx@@ -4,6 +4,8 @@ import { ModernAvatar } from './ModernAvatar';import { Team, Kwant } from './Sidebar';import { FolderBrowserModal } from './FolderBrowserModal';import { playSfx } from '../audio/chiptune';+import { InstructionsField } from './Instructions';+import { MAX_INSTRUCTIONS } from '../continuity';interface ManageTeamModalProps {isOpen: boolean;@@ -19,6 +21,7 @@ interface ManageTeamModalProps {repo_url?: string;lead_kwant_id: string;member_kwants: string[];+ instructions?: string;}) => Promise<void>;onDeleteTeam: (id: string) => Promise<void>;@@ -34,6 +37,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({}) => {const [name, setName] = useState('');const [description, setDescription] = useState('');+ const [instructions, setInstructions] = useState('');const [workspaceType, setWorkspaceType] = useState<'local' | 'repo' | 'default'>('default');const [workspacePath, setWorkspacePath] = useState('');const [repoUrl, setRepoUrl] = useState('');@@ -73,6 +77,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({if (team) {setName(team.name);setDescription(team.description || '');+ setInstructions(team.instructions || '');setLeadKwantId(team.lead_kwant_id || (kwants[0]?.id ?? ''));if (team.workspace_path) {@@ -132,6 +137,10 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({setError('Select at least one agent for this team.');return;}+ if (instructions.length > MAX_INSTRUCTIONS) {+ setError(`Team instructions can be at most ${MAX_INSTRUCTIONS} characters.`);+ return;+ }try {setIsSaving(true);@@ -143,6 +152,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({repo_url: workspaceType === 'repo' && repoUrl.trim() ? repoUrl.trim() : undefined,lead_kwant_id: leadKwantId || memberIds[0],member_kwants: memberIds,+ instructions: instructions.trim(),});playSfx('fanfare');setIsSaving(false);@@ -174,7 +184,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({return (<div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-sm flex items-center justify-center p-4 select-none animate-in fade-in duration-150">- <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full p-6 text-zinc-100 shadow-2xl space-y-5">+ <div role="dialog" aria-modal="true" aria-labelledby="manage-team-title" className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[94vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5">{/* Header */}<div className="flex items-center justify-between border-b border-zinc-800 pb-3"><div className="flex items-center gap-2.5">@@ -182,7 +192,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({<Users size={16} /></div><div>- <h3 className="text-sm font-semibold text-zinc-100">Manage Team: @{team.name}</h3>+ <h3 id="manage-team-title" className="text-sm font-semibold text-zinc-100">Manage Team: @{team.name}</h3><p className="text-[11px] text-zinc-400">Configure team roster, lead agent, and permissions</p></div></div>@@ -232,6 +242,14 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({/></div>+ <InstructionsField+ value={instructions}+ onChange={setInstructions}+ label="Team instructions"+ hint="Pinned for every kwant in this team, before each turn. Leave empty to unpin."+ rows={4}+ />+{/* Team Workspace */}<div><label className="block text-xs font-medium text-zinc-400 mb-1.5">diff --git a/frontend/src/components/MemoryPanel.tsx b/frontend/src/components/MemoryPanel.tsxnew file mode 100644index 00000000..aba1b328--- /dev/null+++ b/frontend/src/components/MemoryPanel.tsx@@ -0,0 +1,268 @@+import React, { useCallback, useEffect, useState } from 'react';+import { Bot, Check, Loader2, Pencil, Plus, RefreshCw, Trash2, User, X } from 'lucide-react';+import { MAX_MEMORIES, MAX_MEMORY, Memory, continuityApi, formatWhen, onContinuity } from '../continuity';+import { playSfx } from '../audio/chiptune';++const smallBtn =+ 'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const quietBtn = `${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700`;+const inputClass =+ 'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors resize-none';++const SourceBadge: React.FC<{ source: Memory['source'] }> = ({ source }) =>+ source === 'agent' ? (+ <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-violet-500/10 text-violet-300 border border-violet-500/20">+ <Bot size={10} aria-hidden="true" /> Agent+ </span>+ ) : (+ <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-sky-500/10 text-sky-300 border border-sky-500/20">+ <User size={10} aria-hidden="true" /> You+ </span>+ );++const MemoryRow: React.FC<{+ memory: Memory;+ onSave: (text: string) => Promise<string | void>;+ onDelete: () => Promise<string | void>;+}> = ({ memory, onSave, onDelete }) => {+ const [editing, setEditing] = useState(false);+ const [text, setText] = useState(memory.text);+ const [busy, setBusy] = useState(false);+ const [confirm, setConfirm] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!editing) setText(memory.text);+ }, [memory.text, editing]);++ const save = async () => {+ const t = text.trim();+ if (!t || t.length > MAX_MEMORY) return;+ setBusy(true);+ const err = await onSave(t);+ setBusy(false);+ if (err) setError(err);+ else {+ setError(null);+ setEditing(false);+ }+ };++ const remove = async () => {+ if (!confirm) {+ setConfirm(true);+ return;+ }+ setBusy(true);+ const err = await onDelete();+ setBusy(false);+ setConfirm(false);+ if (err) setError(err);+ };++ return (+ <li className="p-2.5 rounded-lg border border-zinc-800 bg-zinc-950/60 space-y-1.5">+ <div className="flex items-center gap-2 text-[10px] text-zinc-500">+ <SourceBadge source={memory.source} />+ <span title={`Added ${formatWhen(memory.created_at)}`}>+ {memory.updated_at !== memory.created_at ? 'Edited ' : ''}+ {formatWhen(memory.updated_at)}+ </span>+ <span className="ml-auto flex items-center gap-1">+ {!editing && (+ <button type="button" onClick={() => setEditing(true)} className={quietBtn} aria-label="Edit memory">+ <Pencil size={11} />+ </button>+ )}+ <button+ type="button"+ onClick={remove}+ onBlur={() => setConfirm(false)}+ disabled={busy}+ className={`${smallBtn} ${confirm ? 'border-rose-500/50 bg-rose-500/15 text-rose-200' : 'border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200'}`}+ aria-label={confirm ? 'Confirm delete' : 'Delete memory'}+ >+ <Trash2 size={11} />+ {confirm && <span>Delete?</span>}+ </button>+ </span>+ </div>+ {editing ? (+ <div className="space-y-1.5">+ <textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ rows={3}+ autoFocus+ aria-label="Memory text"+ onKeyDown={(e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ setEditing(false);+ }+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) save();+ }}+ className={inputClass}+ />+ <div className="flex items-center gap-1.5">+ <span className={`text-[10px] font-mono ${text.length > MAX_MEMORY ? 'text-rose-400' : 'text-zinc-500'}`}>+ {text.length}/{MAX_MEMORY}+ </span>+ <button type="button" onClick={() => setEditing(false)} className={`${quietBtn} ml-auto`}>+ <X size={11} /> Cancel+ </button>+ <button+ type="button"+ onClick={save}+ disabled={busy || !text.trim() || text.length > MAX_MEMORY}+ className={`${smallBtn} border-sky-500/50 bg-sky-600 text-white hover:bg-sky-500`}+ >+ <Check size={11} /> Save+ </button>+ </div>+ </div>+ ) : (+ <p className="text-xs text-zinc-200 whitespace-pre-wrap break-words">{memory.text}</p>+ )}+ {error && (+ <p className="text-[11px] text-rose-400" role="alert">+ {error}+ </p>+ )}+ </li>+ );+};++/** A kwant's memory: what it keeps between chats. Refreshes live when the kwant changes it. */+export const MemoryPanel: React.FC<{ kwantId: string; kwantName: string }> = ({ kwantId, kwantName }) => {+ const [memories, setMemories] = useState<Memory[] | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [draft, setDraft] = useState('');+ const [adding, setAdding] = useState(false);+ const [addError, setAddError] = useState<string | null>(null);++ const reload = useCallback(async () => {+ try {+ setMemories(await continuityApi.memories(kwantId));+ setLoadError(null);+ } catch (e) {+ setLoadError(e instanceof Error ? e.message : 'Could not load memories.');+ }+ }, [kwantId]);++ useEffect(() => {+ setMemories(null);+ reload();+ return onContinuity('memory_changed', (d) => {+ if (d.kwant_id === kwantId) reload();+ });+ }, [kwantId, reload]);++ const add = async (e: React.FormEvent) => {+ e.preventDefault();+ const t = draft.trim();+ if (!t || t.length > MAX_MEMORY) return;+ setAdding(true);+ try {+ await continuityApi.addMemory(kwantId, t);+ setDraft('');+ setAddError(null);+ playSfx('coin');+ await reload();+ } catch (err) {+ setAddError(err instanceof Error ? err.message : 'Could not add it.');+ } finally {+ setAdding(false);+ }+ };++ const wrap = (fn: () => Promise<unknown>) => async () => {+ try {+ await fn();+ await reload();+ } catch (err) {+ return err instanceof Error ? err.message : 'That failed.';+ }+ };++ const full = (memories?.length ?? 0) >= MAX_MEMORIES;++ return (+ <div className="space-y-3">+ <p className="text-[11px] text-zinc-500 leading-relaxed">+ {kwantName} reads these at the start of every turn and can add to them itself. Newest are kept when the list gets long.+ </p>++ <form onSubmit={add} className="space-y-1.5">+ <label htmlFor="memory-new" className="block text-xs font-medium text-zinc-400">+ Add a memory+ </label>+ <textarea+ id="memory-new"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ rows={2}+ disabled={full}+ placeholder={full ? `${MAX_MEMORIES} memories is the limit; delete one first.` : 'e.g. Oleks prefers short answers with a code sample.'}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) add(e);+ }}+ className={inputClass}+ />+ <div className="flex items-center gap-2">+ <span className={`text-[10px] font-mono ${draft.length > MAX_MEMORY ? 'text-rose-400' : 'text-zinc-500'}`}>+ {draft.length}/{MAX_MEMORY}+ </span>+ {addError && (+ <span className="text-[11px] text-rose-400" role="alert">+ {addError}+ </span>+ )}+ <button+ type="submit"+ disabled={adding || full || !draft.trim() || draft.length > MAX_MEMORY}+ className={`${smallBtn} ml-auto border-sky-500/50 bg-sky-600 text-white hover:bg-sky-500`}+ >+ {adding ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" /> : <Plus size={11} />} Add+ </button>+ </div>+ </form>++ {loadError && (+ <div className="flex items-center justify-between gap-2 bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs" role="alert">+ <span>{loadError}</span>+ <button type="button" onClick={reload} className={quietBtn}>+ <RefreshCw size={12} /> Retry+ </button>+ </div>+ )}+ {!memories && !loadError && (+ <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading memories…+ </p>+ )}+ {memories && memories.length === 0 && (+ <p className="text-xs text-zinc-500 border border-dashed border-zinc-800 rounded-lg p-4 text-center">+ Nothing remembered yet. Add something above, or ask {kwantName} to remember it.+ </p>+ )}+ {memories && memories.length > 0 && (+ <>+ <p className="text-[10px] text-zinc-500">+ {memories.length} of {MAX_MEMORIES} · newest first+ </p>+ <ul className="space-y-1.5" aria-label={`${kwantName}'s memories`}>+ {[...memories].reverse().map((m) => (+ <MemoryRow+ key={m.id}+ memory={m}+ onSave={(t) => wrap(() => continuityApi.updateMemory(kwantId, m.id, t))()}+ onDelete={wrap(() => continuityApi.removeMemory(kwantId, m.id))}+ />+ ))}+ </ul>+ </>+ )}+ </div>+ );+};diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsxindex 95f8cc2d..88d12cc5 100644--- a/frontend/src/components/NewAgentModal.tsx+++ b/frontend/src/components/NewAgentModal.tsx@@ -1,11 +1,21 @@import React, { useEffect, useState } from 'react';-import { X, Sparkles, Pencil, ChevronRight } from 'lucide-react';+import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound } from 'lucide-react';import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';import { playSfx } from '../audio/chiptune';import { KwantToolsPicker } from './KwantToolsPicker';import { McpServer, defaultKwantServerIds } from '../mcp';import { ENGINES, Profile, engineOfModel, profileStatus, profilesForEngine } from '../profiles';+import { MemoryPanel } from './MemoryPanel';+import { RoutinesPanel } from './RoutinesPanel';+import type { Channel, Kwant } from './Sidebar';++type EditTab = 'profile' | 'memory' | 'routines';+const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [+ { id: 'profile', label: 'Profile', Icon: UserRound },+ { id: 'memory', label: 'Memory', Icon: Brain },+ { id: 'routines', label: 'Routines', Icon: CalendarClock },+];export interface AgentFormData {name: string;@@ -48,6 +58,9 @@ interface NewAgentModalProps {onManageProfiles?: () => void;/** Resolves to an error message when saving failed. */onSubmit: (data: AgentFormData) => Promise<string | void> | void;+ /** For the Routines tab when editing. */+ kwants?: Kwant[];+ channels?: Channel[];}export const NewAgentModal: React.FC<NewAgentModalProps> = ({@@ -61,7 +74,10 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({profiles = [],onManageProfiles,onSubmit,+ kwants = [],+ channels = [],}) => {+ const [tab, setTab] = useState<EditTab>('profile');const [name, setName] = useState('');const [title, setTitle] = useState('');const [roleStyle, setRoleStyle] = useState('architect');@@ -89,6 +105,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({setSoul(initial?.soul ?? '');setSubmitting(false);setError(null);+ setTab('profile');setPresetId(null);setMcpIds(undefined);setProfileId(initial?.profile_id ?? null);@@ -168,13 +185,18 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({return (<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">- <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-6 text-zinc-100 shadow-2xl space-y-5">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="agent-modal-title"+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5"+ ><div className="flex items-center justify-between border-b border-zinc-800 pb-3"><div className="flex items-center gap-2"><div className="w-7 h-7 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">{isEdit ? <Pencil size={14} /> : <Sparkles size={15} />}</div>- <h3 className="text-sm font-semibold text-zinc-100">+ <h3 id="agent-modal-title" className="text-sm font-semibold text-zinc-100">{isEdit ? `Edit ${initial?.name}` : joinTeamName ? `New Agent for @${joinTeamName}` : 'Create New AI Agent'}</h3></div>@@ -183,13 +205,49 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({playSfx('click');onClose();}}+ aria-label="Close"className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"><X size={17} /></button></div>- <form onSubmit={handleSubmit} className="space-y-4">+ {isEdit && kwantId && (+ <div className="flex p-0.5 rounded-lg bg-zinc-950 border border-zinc-800" role="tablist" aria-label="Agent settings">+ {EDIT_TABS.map(({ id, label, Icon }) => (+ <button+ key={id}+ type="button"+ role="tab"+ id={`agent-tab-${id}`}+ aria-selected={tab === id}+ aria-controls={`agent-panel-${id}`}+ onClick={() => {+ playSfx('click');+ setTab(id);+ }}+ className={`flex-1 flex items-center justify-center gap-1.5 py-1.5 rounded-md text-[11px] font-medium transition-colors ${+ tab === id ? 'bg-sky-500/15 text-sky-200' : 'text-zinc-500 hover:text-zinc-300'+ }`}+ >+ <Icon size={12} aria-hidden="true" /> {label}+ </button>+ ))}+ </div>+ )}++ {isEdit && kwantId && tab === 'memory' && (+ <div role="tabpanel" id="agent-panel-memory" aria-labelledby="agent-tab-memory">+ <MemoryPanel kwantId={kwantId} kwantName={initial?.name ?? 'This kwant'} />+ </div>+ )}+ {isEdit && kwantId && tab === 'routines' && (+ <div role="tabpanel" id="agent-panel-routines" aria-labelledby="agent-tab-routines">+ <RoutinesPanel kwantId={kwantId} kwants={kwants} channels={channels} />+ </div>+ )}++ <form onSubmit={handleSubmit} className="space-y-4" hidden={isEdit && !!kwantId && tab !== 'profile'} role={isEdit && kwantId ? 'tabpanel' : undefined} id="agent-panel-profile">{!isEdit && (<div><div className="flex items-center justify-between mb-1.5">diff --git a/frontend/src/components/RoutinesModal.tsx b/frontend/src/components/RoutinesModal.tsxnew file mode 100644index 00000000..67277b48--- /dev/null+++ b/frontend/src/components/RoutinesModal.tsx@@ -0,0 +1,58 @@+import React, { useEffect, useRef } from 'react';+import { CalendarClock, X } from 'lucide-react';+import { RoutinesPanel } from './RoutinesPanel';+import type { Channel, Kwant } from './Sidebar';+import { playSfx } from '../audio/chiptune';++/** Every kwant's routines in one list. */+export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwants: Kwant[]; channels: Channel[] }> = ({+ isOpen,+ onClose,+ kwants,+ channels,+}) => {+ const closeRef = useRef(onClose);+ closeRef.current = onClose;+ useEffect(() => {+ if (!isOpen) return;+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeRef.current();+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [isOpen]);++ if (!isOpen) return null;+ return (+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="routines-title"+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-2xl w-full max-h-[94vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5"+ >+ <div className="flex items-center justify-between border-b border-zinc-800 pb-4">+ <div className="flex items-center gap-2.5">+ <div className="w-8 h-8 rounded-lg bg-sky-500/10 border border-sky-500/20 flex items-center justify-center text-sky-400">+ <CalendarClock size={16} />+ </div>+ <div>+ <h2 id="routines-title" className="text-sm font-semibold text-zinc-100">Routines</h2>+ <p className="text-xs text-zinc-400">Scheduled work for all your kwants</p>+ </div>+ </div>+ <button+ type="button"+ onClick={() => {+ playSfx('click');+ onClose();+ }}+ aria-label="Close"+ className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors"+ >+ <X size={18} />+ </button>+ </div>+ <RoutinesPanel kwants={kwants} channels={channels} />+ </div>+ </div>+ );+};diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsxnew file mode 100644index 00000000..4bcd0e80--- /dev/null+++ b/frontend/src/components/RoutinesPanel.tsx@@ -0,0 +1,477 @@+import React, { useCallback, useEffect, useId, useState } from 'react';+import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Trash2 } from 'lucide-react';+import {+ Routine,+ RoutineRun,+ RunStatus,+ ScheduleForm,+ WEEKDAYS,+ channelLabel,+ continuityApi,+ defaultTimeZone,+ describeSchedule,+ emptyScheduleForm,+ formFromSchedule,+ formatWhen,+ onContinuity,+ scheduleFromForm,+ timeZoneOptions,+} from '../continuity';+import type { Channel, Kwant } from './Sidebar';+import { playSfx } from '../audio/chiptune';++const smallBtn =+ 'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const quietBtn = `${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700`;+const inputClass =+ 'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors';+const labelClass = 'block text-xs font-medium text-zinc-400 mb-1';++const STATUS: Record<RunStatus, { label: string; cls: string }> = {+ running: { label: 'Running', cls: 'bg-sky-500/10 text-sky-300 border-sky-500/20' },+ ok: { label: 'OK', cls: 'bg-emerald-500/10 text-emerald-300 border-emerald-500/20' },+ error: { label: 'Failed', cls: 'bg-rose-500/10 text-rose-300 border-rose-500/20' },+ skipped: { label: 'Skipped', cls: 'bg-zinc-700/30 text-zinc-400 border-zinc-700' },+};++const StatusBadge: React.FC<{ status: RunStatus }> = ({ status }) => (+ <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${STATUS[status]?.cls ?? STATUS.skipped.cls}`}>+ {status === 'running' && <Loader2 size={9} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {STATUS[status]?.label ?? status}+ </span>+);++interface FormState {+ kwantId: string;+ channelId: string;+ name: string;+ instructions: string;+ enabled: boolean;+ schedule: ScheduleForm;+}++const RoutineForm: React.FC<{+ initial?: Routine;+ fixedKwantId?: string;+ kwants: Kwant[];+ channels: Channel[];+ onCancel: () => void;+ onSaved: () => void;+}> = ({ initial, fixedKwantId, kwants, channels, onCancel, onSaved }) => {+ const uid = useId();+ const [f, setF] = useState<FormState>(() => ({+ kwantId: initial?.kwant_id ?? fixedKwantId ?? kwants[0]?.id ?? '',+ channelId: initial?.channel_id ?? '',+ name: initial?.name ?? '',+ instructions: initial?.instructions ?? '',+ enabled: initial?.enabled ?? true,+ schedule: initial ? formFromSchedule(initial.schedule) : emptyScheduleForm(),+ }));+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const s = f.schedule;+ const setS = (patch: Partial<ScheduleForm>) => setF((prev) => ({ ...prev, schedule: { ...prev.schedule, ...patch } }));++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!f.name.trim()) return setError('Give the routine a name.');+ if (!f.instructions.trim()) return setError('Say what the kwant should do.');+ if (!f.kwantId) return setError('Pick a kwant.');+ const built = scheduleFromForm(s);+ if ('error' in built) return setError(built.error);+ setSaving(true);+ setError(null);+ const body = {+ kwant_id: f.kwantId,+ channel_id: f.channelId || null,+ name: f.name.trim(),+ instructions: f.instructions.trim(),+ schedule: built.schedule,+ enabled: f.enabled,+ };+ try {+ if (initial) await continuityApi.updateRoutine(initial.id, body);+ else await continuityApi.createRoutine(body);+ playSfx('coin');+ onSaved();+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Saving failed.');+ setSaving(false);+ }+ };++ const id = (k: string) => `${uid}-${k}`;++ return (+ <form onSubmit={submit} noValidate className="p-3 rounded-xl border border-sky-500/30 bg-zinc-950/70 space-y-3" aria-label={initial ? `Edit ${initial.name}` : 'New routine'}>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor={id('name')} className={labelClass}>Name</label>+ <input id={id('name')} value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} placeholder="Morning digest" className={inputClass} autoFocus />+ </div>+ {!fixedKwantId && (+ <div>+ <label htmlFor={id('kwant')} className={labelClass}>Kwant</label>+ <select id={id('kwant')} value={f.kwantId} onChange={(e) => setF({ ...f, kwantId: e.target.value })} className={inputClass}>+ {kwants.map((k) => (+ <option key={k.id} value={k.id}>{k.name}</option>+ ))}+ </select>+ </div>+ )}+ <div>+ <label htmlFor={id('channel')} className={labelClass}>Posts in</label>+ <select id={id('channel')} value={f.channelId} onChange={(e) => setF({ ...f, channelId: e.target.value })} className={inputClass}>+ <option value="">Direct chat with the kwant</option>+ {channels.map((c) => (+ <option key={c.id} value={c.id}>{channelLabel(c.name)}</option>+ ))}+ </select>+ </div>+ </div>++ <div>+ <label htmlFor={id('instr')} className={labelClass}>What to do</label>+ <textarea+ id={id('instr')}+ rows={3}+ value={f.instructions}+ onChange={(e) => setF({ ...f, instructions: e.target.value })}+ placeholder="Summarise yesterday's open pull requests and flag anything blocked."+ className={`${inputClass} resize-y`}+ />+ </div>++ <fieldset className="space-y-2">+ <legend className={labelClass}>When</legend>+ <div className="grid grid-cols-4 gap-1 p-1 bg-zinc-950 rounded-lg border border-zinc-800" role="radiogroup" aria-label="Repeat">+ {(['once', 'daily', 'weekly', 'interval'] as const).map((t) => (+ <button+ key={t}+ type="button"+ role="radio"+ aria-checked={s.type === t}+ onClick={() => setS({ type: t })}+ className={`py-1 rounded-md text-[11px] font-medium transition-colors ${s.type === t ? 'bg-sky-500/15 text-sky-200' : 'text-zinc-500 hover:text-zinc-300'}`}+ >+ {t === 'once' ? 'Once' : t === 'daily' ? 'Daily' : t === 'weekly' ? 'Weekly' : 'Every…'}+ </button>+ ))}+ </div>++ {s.type === 'once' && (+ <div>+ <label htmlFor={id('at')} className="sr-only">Date and time</label>+ <input id={id('at')} type="datetime-local" value={s.onceAt} onChange={(e) => setS({ onceAt: e.target.value })} className={inputClass} />+ <p className="mt-1 text-[11px] text-zinc-500">In your browser's time zone ({defaultTimeZone()}). Turns itself off after it runs.</p>+ </div>+ )}++ {(s.type === 'daily' || s.type === 'weekly') && (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <div>+ <label htmlFor={id('time')} className="text-[11px] text-zinc-500">At</label>+ <input id={id('time')} type="time" value={s.time} onChange={(e) => setS({ time: e.target.value })} className={inputClass} />+ </div>+ <div>+ <label htmlFor={id('tz')} className="text-[11px] text-zinc-500">Time zone</label>+ <input id={id('tz')} list={id('tzs')} value={s.tz} onChange={(e) => setS({ tz: e.target.value })} className={inputClass} spellCheck={false} />+ <datalist id={id('tzs')}>+ {timeZoneOptions(s.tz).map((z) => (+ <option key={z} value={z} />+ ))}+ </datalist>+ </div>+ </div>+ )}++ {s.type === 'weekly' && (+ <div className="flex flex-wrap gap-1" role="group" aria-label="Days">+ {WEEKDAYS.map((d) => {+ const on = s.weekdays.includes(d.id);+ return (+ <button+ key={d.id}+ type="button"+ aria-pressed={on}+ onClick={() => setS({ weekdays: on ? s.weekdays.filter((w) => w !== d.id) : [...s.weekdays, d.id] })}+ className={`px-2 py-1 rounded-md text-[11px] font-medium border transition-colors ${+ on ? 'border-sky-500/50 bg-sky-500/15 text-sky-200' : 'border-zinc-800 text-zinc-500 hover:text-zinc-300'+ }`}+ >+ {d.label}+ </button>+ );+ })}+ </div>+ )}++ {s.type === 'interval' && (+ <div className="flex items-center gap-2">+ <label htmlFor={id('every')} className="text-[11px] text-zinc-500 shrink-0">Every</label>+ <input+ id={id('every')}+ type="number"+ min={5}+ max={10080}+ step={5}+ value={s.everyMinutes}+ onChange={(e) => setS({ everyMinutes: e.target.value })}+ className={`${inputClass} w-24`}+ />+ <span className="text-[11px] text-zinc-500">minutes (5 to 10080)</span>+ </div>+ )}+ </fieldset>++ <label className="flex items-center gap-2 text-[11px] text-zinc-300">+ <input type="checkbox" checked={f.enabled} onChange={(e) => setF({ ...f, enabled: e.target.checked })} className="accent-sky-500" />+ Enabled+ </label>++ {error && (+ <p className="text-[11px] text-rose-400 flex items-center gap-1.5" role="alert">+ <AlertTriangle size={12} /> {error}+ </p>+ )}+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onCancel} className="px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors">+ Cancel+ </button>+ <button type="submit" disabled={saving} className="px-3.5 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50">+ {saving ? 'Saving…' : initial ? 'Save routine' : 'Create routine'}+ </button>+ </div>+ </form>+ );+};++const RunHistory: React.FC<{ routineId: string; tick: number }> = ({ routineId, tick }) => {+ const [runs, setRuns] = useState<RoutineRun[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ let cancelled = false;+ continuityApi.routineRuns(routineId).then(+ (r) => !cancelled && (setRuns(r), setError(null)),+ (e) => !cancelled && setError(e instanceof Error ? e.message : 'Could not load runs.'),+ );+ return () => {+ cancelled = true;+ };+ }, [routineId, tick]);+ if (error) return <p className="text-[11px] text-rose-400" role="alert">{error}</p>;+ if (!runs) return <p className="text-[11px] text-zinc-500" role="status">Loading runs…</p>;+ if (runs.length === 0) return <p className="text-[11px] text-zinc-500">No runs yet.</p>;+ return (+ <ol className="space-y-1" aria-label="Run history">+ {runs.map((r) => (+ <li key={r.id} className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-zinc-400">+ <StatusBadge status={r.status} />+ <span>{formatWhen(r.started_at)}</span>+ <span className="text-zinc-600">{r.trigger === 'manual' ? 'Run now' : 'Scheduled'}</span>+ {r.error && <span className="basis-full text-rose-300/90 break-words">{r.error}</span>}+ </li>+ ))}+ </ol>+ );+};++const RoutineRow: React.FC<{+ routine: Routine;+ kwantName?: string;+ placeLabel: string;+ tick: number;+ onEdit: () => void;+ onChanged: () => void;+}> = ({ routine, kwantName, placeLabel, tick, onEdit, onChanged }) => {+ const [open, setOpen] = useState(false);+ const [busy, setBusy] = useState(false);+ const [confirm, setConfirm] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const historyId = useId();++ const act = async (fn: () => Promise<unknown>) => {+ setBusy(true);+ setError(null);+ try {+ await fn();+ onChanged();+ } catch (e) {+ setError(e instanceof Error ? e.message : 'That failed.');+ } finally {+ setBusy(false);+ }+ };++ const runNow = () =>+ act(async () => {+ const run = await continuityApi.runRoutine(routine.id);+ setNotice(run.status === 'skipped' ? 'Already running; this one was skipped.' : 'Started.');+ setOpen(true);+ playSfx('click');+ });++ return (+ <li className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-3 space-y-2">+ <div className="flex items-start gap-2.5">+ <label className="relative inline-flex items-center p-1 -m-1 mt-0 cursor-pointer" title={routine.enabled ? 'Turn off' : 'Turn on'}>+ <input+ type="checkbox"+ role="switch"+ className="sr-only peer"+ checked={routine.enabled}+ disabled={busy}+ aria-label={`${routine.name} enabled`}+ onChange={(e) => act(() => continuityApi.updateRoutine(routine.id, { enabled: e.target.checked }))}+ />+ <span className="w-7 h-4 rounded-full bg-zinc-700 peer-checked:bg-sky-600 peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-sky-500 transition-colors" />+ <span className="absolute left-1.5 top-1.5 w-3 h-3 rounded-full bg-white transition-transform motion-reduce:transition-none peer-checked:translate-x-3" />+ </label>+ <div className="flex-1 min-w-0">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="text-xs font-medium text-zinc-100 break-words">{routine.name}</span>+ {routine.last_status && <StatusBadge status={routine.last_status} />}+ </div>+ <p className="text-[11px] text-zinc-500 break-words">+ {kwantName ? `${kwantName} · ` : ''}+ {placeLabel} · {describeSchedule(routine.schedule)}+ </p>+ <p className="text-[11px] text-zinc-400">+ Next run: <span className="text-zinc-200">{routine.enabled ? formatWhen(routine.next_run_at) : 'off'}</span>+ {routine.last_run_at && <span className="text-zinc-500"> · last {formatWhen(routine.last_run_at)}</span>}+ </p>+ </div>+ </div>+ <div className="flex flex-wrap items-center gap-1.5 pl-9">+ <button type="button" onClick={runNow} disabled={busy} className={`${smallBtn} border-sky-500/40 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20`}>+ <Play size={11} /> Run now+ </button>+ <button type="button" onClick={() => setOpen((v) => !v)} aria-expanded={open} aria-controls={historyId} className={quietBtn}>+ {open ? <ChevronDown size={11} /> : <ChevronRight size={11} />} <History size={11} /> History+ </button>+ <button type="button" onClick={onEdit} className={quietBtn}>+ <Pencil size={11} /> Edit+ </button>+ <button+ type="button"+ disabled={busy}+ onBlur={() => setConfirm(false)}+ onClick={() => (confirm ? act(() => continuityApi.removeRoutine(routine.id)) : setConfirm(true))}+ className={`${smallBtn} ${confirm ? 'border-rose-500/50 bg-rose-500/15 text-rose-200' : 'border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200'}`}+ >+ <Trash2 size={11} /> {confirm ? 'Delete?' : 'Delete'}+ </button>+ {notice && <span className="text-[11px] text-zinc-400" role="status">{notice}</span>}+ </div>+ {error && <p className="pl-9 text-[11px] text-rose-400" role="alert">{error}</p>}+ {open && (+ <div id={historyId} className="pl-9 pt-1">+ <RunHistory routineId={routine.id} tick={tick} />+ </div>+ )}+ </li>+ );+};++/** Routines for one kwant (`kwantId`) or for everyone. Live: refetches on `routine_run`. */+export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channels: Channel[] }> = ({ kwantId, kwants, channels }) => {+ const [routines, setRoutines] = useState<Routine[] | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [editing, setEditing] = useState<Routine | 'new' | null>(null);+ const [tick, setTick] = useState(0);++ const reload = useCallback(async () => {+ try {+ const all = await continuityApi.routines();+ setRoutines(kwantId ? all.filter((r) => r.kwant_id === kwantId) : all);+ setLoadError(null);+ } catch (e) {+ setLoadError(e instanceof Error ? e.message : 'Could not load routines.');+ }+ }, [kwantId]);++ useEffect(() => {+ reload();+ return onContinuity('routine_run', () => {+ reload();+ setTick((t) => t + 1);+ });+ }, [reload]);++ const kwantName = (id: string) => kwants.find((k) => k.id === id)?.name;+ const place = (r: Routine) => {+ if (!r.channel_id) return 'direct chat';+ const c = channels.find((ch) => ch.id === r.channel_id);+ return c ? channelLabel(c.name) : 'a deleted channel';+ };+ const saved = () => {+ setEditing(null);+ reload();+ };++ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-2">+ <p className="text-[11px] text-zinc-500 leading-relaxed">+ A routine posts its instructions to the kwant on a schedule, then the kwant answers as usual.+ </p>+ {editing !== 'new' && (+ <button+ type="button"+ onClick={() => setEditing('new')}+ disabled={kwants.length === 0}+ className={`${smallBtn} shrink-0 border-sky-500/50 bg-sky-600 text-white hover:bg-sky-500`}+ >+ <Plus size={11} /> New routine+ </button>+ )}+ </div>++ {editing === 'new' && (+ <RoutineForm fixedKwantId={kwantId} kwants={kwants} channels={channels} onCancel={() => setEditing(null)} onSaved={saved} />+ )}++ {loadError && (+ <div className="flex items-center justify-between gap-2 bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs" role="alert">+ <span>{loadError}</span>+ <button type="button" onClick={reload} className={quietBtn}>+ <RefreshCw size={12} /> Retry+ </button>+ </div>+ )}+ {!routines && !loadError && (+ <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading routines…+ </p>+ )}+ {routines && routines.length === 0 && editing !== 'new' && (+ <div className="text-xs text-zinc-500 border border-dashed border-zinc-800 rounded-lg p-4 text-center space-y-1">+ <CalendarClock size={18} className="mx-auto text-zinc-600" aria-hidden="true" />+ <p>No routines yet.</p>+ </div>+ )}+ {routines && routines.length > 0 && (+ <ul className="space-y-2" aria-label="Routines">+ {routines.map((r) =>+ editing !== 'new' && editing?.id === r.id ? (+ <li key={r.id}>+ <RoutineForm initial={r} fixedKwantId={kwantId} kwants={kwants} channels={channels} onCancel={() => setEditing(null)} onSaved={saved} />+ </li>+ ) : (+ <RoutineRow+ key={r.id}+ routine={r}+ kwantName={kwantId ? undefined : kwantName(r.kwant_id) ?? 'deleted kwant'}+ placeLabel={place(r)}+ tick={tick}+ onEdit={() => setEditing(r)}+ onChanged={reload}+ />+ ),+ )}+ </ul>+ )}+ </div>+ );+};diff --git a/frontend/src/components/SearchModal.tsx b/frontend/src/components/SearchModal.tsxnew file mode 100644index 00000000..38b02434--- /dev/null+++ b/frontend/src/components/SearchModal.tsx@@ -0,0 +1,190 @@+import React, { useEffect, useMemo, useRef, useState } from 'react';+import { Hash, Loader2, MessageSquare, Search, X } from 'lucide-react';+import { SearchHit, continuityApi, formatWhen, groupHits, snippetParts } from '../continuity';+import type { Kwant } from './Sidebar';++/** Renders a server snippet as text; only the `<mark>` hits become elements. */+export const Snippet: React.FC<{ text: string }> = ({ text }) => (+ <>+ {snippetParts(text).map((p, i) =>+ p.hit ? (+ <mark key={i} className="bg-amber-400/25 text-amber-100 rounded px-0.5">+ {p.text}+ </mark>+ ) : (+ <React.Fragment key={i}>{p.text}</React.Fragment>+ ),+ )}+ </>+);++const DEBOUNCE_MS = 200;++/** Search every chat; picking a result jumps to that message. */+export const SearchModal: React.FC<{+ isOpen: boolean;+ onClose: () => void;+ kwants: Kwant[];+ onJump: (hit: SearchHit) => void;+}> = ({ isOpen, onClose, kwants, onJump }) => {+ const [q, setQ] = useState('');+ const [hits, setHits] = useState<SearchHit[] | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [active, setActive] = useState(0);+ const inputRef = useRef<HTMLInputElement>(null);+ const listRef = useRef<HTMLDivElement>(null);+ const seqRef = useRef(0);++ useEffect(() => {+ if (isOpen) {+ setActive(0);+ requestAnimationFrame(() => inputRef.current?.select());+ }+ }, [isOpen]);++ useEffect(() => {+ if (!isOpen) return;+ const term = q.trim();+ const seq = ++seqRef.current;+ if (!/[\p{L}\p{N}]/u.test(term)) {+ setHits(null);+ setError(null);+ setLoading(false);+ return;+ }+ setLoading(true);+ const t = setTimeout(() => {+ continuityApi.search(term).then(+ (r) => {+ if (seq !== seqRef.current) return;+ setHits(r);+ setError(null);+ setActive(0);+ setLoading(false);+ },+ (e) => {+ if (seq !== seqRef.current) return;+ setError(e instanceof Error ? e.message : 'Search failed.');+ setLoading(false);+ },+ );+ }, DEBOUNCE_MS);+ return () => clearTimeout(t);+ }, [q, isOpen]);++ const groups = useMemo(() => groupHits(hits ?? [], (id) => kwants.find((k) => k.id === id)?.name), [hits, kwants]);+ const flat = useMemo(() => groups.flatMap((g) => g.hits), [groups]);++ useEffect(() => {+ listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: 'nearest' });+ }, [active]);++ if (!isOpen) return null;++ const pick = (h: SearchHit) => {+ onJump(h);+ onClose();+ };++ const onKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ onClose();+ } else if (e.key === 'ArrowDown' && flat.length) {+ e.preventDefault();+ setActive((a) => (a + 1) % flat.length);+ } else if (e.key === 'ArrowUp' && flat.length) {+ e.preventDefault();+ setActive((a) => (a - 1 + flat.length) % flat.length);+ } else if (e.key === 'Enter' && flat[active]) {+ e.preventDefault();+ pick(flat[active]);+ }+ };++ let index = -1;+ return (+ <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-start justify-center p-2 sm:p-4 sm:pt-[12vh]" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div+ role="dialog"+ aria-modal="true"+ aria-label="Search chats"+ onKeyDown={onKeyDown}+ className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-xl w-full max-h-[86vh] flex flex-col text-zinc-100 shadow-2xl overflow-hidden"+ >+ <div className="flex items-center gap-2 px-3 sm:px-4 border-b border-zinc-800">+ {loading ? (+ <Loader2 size={16} className="text-zinc-500 animate-spin motion-reduce:animate-none shrink-0" aria-hidden="true" />+ ) : (+ <Search size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ )}+ <input+ ref={inputRef}+ value={q}+ onChange={(e) => setQ(e.target.value)}+ placeholder="Search all chats…"+ role="combobox"+ aria-expanded={flat.length > 0}+ aria-controls="search-results"+ aria-activedescendant={flat[active] ? `search-hit-${flat[active].message_id}` : undefined}+ aria-label="Search all chats"+ className="flex-1 min-w-0 bg-transparent py-3.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none"+ />+ <button type="button" onClick={onClose} aria-label="Close search" className="p-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors">+ <X size={16} />+ </button>+ </div>++ <div ref={listRef} id="search-results" role="listbox" aria-label="Results" className="flex-1 overflow-y-auto p-2">+ {error && (+ <p className="m-2 text-xs text-rose-300" role="alert">+ {error}+ </p>+ )}+ {!hits && !error && (+ <p className="m-3 text-xs text-zinc-500">Type a word to search every channel and direct chat. ↑↓ to move, Enter to open.</p>+ )}+ {hits && hits.length === 0 && !loading && (+ <p className="m-3 text-xs text-zinc-500" role="status">+ No messages match “{q.trim()}”.+ </p>+ )}+ {groups.map((g) => (+ <div key={g.key} role="group" aria-label={g.label} className="mb-2">+ <p className="flex items-center gap-1.5 px-2 py-1 text-[10px] uppercase tracking-wide font-semibold text-zinc-500">+ {g.channel_id ? <Hash size={11} aria-hidden="true" /> : <MessageSquare size={11} aria-hidden="true" />}+ {g.label}+ </p>+ {g.hits.map((h) => {+ index += 1;+ const i = index;+ const isActive = i === active;+ return (+ <div+ key={h.message_id}+ id={`search-hit-${h.message_id}`}+ data-index={i}+ role="option"+ aria-selected={isActive}+ onMouseMove={() => setActive(i)}+ onClick={() => pick(h)}+ className={`px-2.5 py-2 rounded-lg cursor-pointer ${isActive ? 'bg-sky-500/10 ring-1 ring-sky-500/30' : 'hover:bg-zinc-800/60'}`}+ >+ <div className="flex items-center gap-2 text-[11px] text-zinc-400">+ <span className="font-medium text-zinc-200 truncate">{h.author === 'PlayerHero' ? 'You' : h.author}</span>+ <span className="ml-auto shrink-0 text-zinc-500">{formatWhen(h.created_at)}</span>+ </div>+ <p className="mt-0.5 text-xs text-zinc-300 break-words line-clamp-3">+ <Snippet text={h.snippet} />+ </p>+ </div>+ );+ })}+ </div>+ ))}+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex 67e31e0d..bbc02591 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -1,5 +1,14 @@-import React, { useState, useEffect } from 'react';-import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut } from 'lucide-react';+import React, { useState, useEffect, useRef } from 'react';+import { Cpu, Key, Globe, X, Sparkles, Check, Plug, ChevronRight, UserRound, LogOut, Bell, AlertTriangle } from 'lucide-react';+import {+ BROWSER_NOTIFY_KEY,+ MASK,+ NOTIFY_KINDS,+ NotifyKind,+ browserNotifyEnabled,+ notificationPermission,+ webhookUrlError,+} from '../continuity';import { playSfx } from '../audio/chiptune';import { useAuth } from './AuthGate';@@ -14,6 +23,9 @@ interface SettingsData {grok_cli_path: string | null;codex_cli_found: boolean;codex_cli_path: string | null;+ /** "••••••••" when one is saved, "" otherwise. */+ notify_webhook_url?: string;+ notify_on?: NotifyKind[];}interface SettingsModalProps {@@ -32,9 +44,27 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oconst [ollamaUrl, setOllamaUrl] = useState('http://localhost:11434/v1');const [saving, setSaving] = useState(false);const [saveSuccess, setSaveSuccess] = useState(false);+ const [saveError, setSaveError] = useState<string | null>(null);+ const [webhookUrl, setWebhookUrl] = useState('');+ const [notifyOn, setNotifyOn] = useState<NotifyKind[]>(NOTIFY_KINDS.map((k) => k.id));+ const [browserNotify, setBrowserNotify] = useState(browserNotifyEnabled);+ const [permission, setPermission] = useState(notificationPermission);+ const webhookError = webhookUrlError(webhookUrl);++ const closeRef = useRef(onClose);+ closeRef.current = onClose;+ useEffect(() => {+ if (!isOpen) return;+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeRef.current();+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [isOpen]);useEffect(() => {if (isOpen) {+ setSaveError(null);+ setPermission(notificationPermission());+ setBrowserNotify(browserNotifyEnabled());fetch('/api/settings').then((r) => r.json()).then((data: SettingsData) => {@@ -43,6 +73,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, osetXaiKey(data.xai_api_key);setOpenaiKey(data.openai_api_key);setOllamaUrl(data.ollama_url || 'http://localhost:11434/v1');+ setWebhookUrl(data.notify_webhook_url ?? '');+ if (Array.isArray(data.notify_on)) setNotifyOn(data.notify_on);}).catch((err) => console.error('Failed to load settings:', err));}@@ -50,8 +82,27 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oif (!isOpen) return null;+ // Permission is only ever asked from this click, never on load.+ const toggleBrowserNotify = async () => {+ playSfx('click');+ if (browserNotify) {+ localStorage.setItem(BROWSER_NOTIFY_KEY, 'off');+ setBrowserNotify(false);+ return;+ }+ let p = notificationPermission();+ if (p === 'default') p = await Notification.requestPermission();+ setPermission(p);+ if (p === 'granted') {+ localStorage.setItem(BROWSER_NOTIFY_KEY, 'on');+ setBrowserNotify(true);+ }+ };+const handleSave = async (e: React.FormEvent) => {e.preventDefault();+ if (webhookError) return;+ setSaveError(null);setSaving(true);playSfx('click');@@ -64,16 +115,23 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oxai_api_key: xaiKey,openai_api_key: openaiKey,ollama_url: ollamaUrl,+ notify_webhook_url: webhookUrl.trim(),+ notify_on: notifyOn,}),});if (res.ok) {setSaveSuccess(true);+ if (webhookUrl.trim() && webhookUrl.trim() !== MASK) setWebhookUrl(MASK);playSfx('coin');setTimeout(() => setSaveSuccess(false), 2500);+ } else {+ const data = await res.json().catch(() => null);+ setSaveError(data && typeof data.error === 'string' ? data.error : `Saving failed (HTTP ${res.status}).`);}} catch (err) {console.error('Failed to save settings:', err);+ setSaveError('Could not reach the server.');} finally {setSaving(false);}@@ -81,7 +139,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, oreturn (<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">- <div className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-6 text-zinc-100 shadow-2xl space-y-6">+ <div role="dialog" aria-modal="true" aria-labelledby="settings-title" className="bg-zinc-900 border border-zinc-800 rounded-2xl max-w-lg w-full max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-6">{/* Header */}<div className="flex items-center justify-between border-b border-zinc-800 pb-4"><div className="flex items-center gap-2.5">@@ -89,7 +147,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o<Sparkles size={17} /></div><div>- <h2 className="text-sm font-semibold text-zinc-100">Fleet & Engine Settings</h2>+ <h2 id="settings-title" className="text-sm font-semibold text-zinc-100">Fleet & Engine Settings</h2><p className="text-xs text-zinc-400">Configure local CLI routing and cloud provider credentials</p></div></div>@@ -250,6 +308,102 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</div></div>+ <fieldset className="space-y-3 pt-2 border-t border-zinc-800">+ <legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">+ <Bell size={14} className="text-amber-300" />+ <span>Notifications</span>+ </legend>++ <div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">+ <div className="flex-1">+ <p id="browser-notify-label" className="text-xs font-medium text-zinc-200">Notify me on this computer</p>+ <p className="text-[11px] text-zinc-500">+ Only while kwnt is in a background tab.+ {permission === 'denied' && <span className="text-amber-300"> Blocked by your browser; allow notifications for this site in its settings.</span>}+ {permission === 'unsupported' && <span className="text-amber-300"> This browser can't show notifications.</span>}+ </p>+ </div>+ <button+ type="button"+ role="switch"+ aria-checked={browserNotify}+ aria-labelledby="browser-notify-label"+ disabled={permission === 'unsupported' || (permission === 'denied' && !browserNotify)}+ onClick={toggleBrowserNotify}+ className={`relative shrink-0 w-9 h-5 rounded-full transition-colors disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${+ browserNotify ? 'bg-sky-600' : 'bg-zinc-700'+ }`}+ >+ <span+ className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${browserNotify ? 'translate-x-4' : ''}`}+ />+ </button>+ </div>++ <div>+ <label htmlFor="notify-webhook" className="block text-xs font-medium text-zinc-400 mb-1">+ Phone webhook (optional)+ </label>+ <div className="flex gap-1.5">+ <input+ id="notify-webhook"+ type={webhookUrl === MASK ? 'password' : 'url'}+ value={webhookUrl}+ onChange={(e) => setWebhookUrl(e.target.value)}+ onFocus={() => webhookUrl === MASK && setWebhookUrl('')}+ onBlur={() => !webhookUrl.trim() && settings?.notify_webhook_url === MASK && setWebhookUrl(MASK)}+ placeholder="https://ntfy.sh/your-secret-topic"+ aria-invalid={!!webhookError}+ aria-describedby="notify-webhook-hint"+ autoComplete="off"+ spellCheck={false}+ className={`flex-1 min-w-0 bg-zinc-950 border rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:outline-none transition-colors ${+ webhookError ? 'border-rose-500/70' : 'border-zinc-800 focus:border-sky-500'+ }`}+ />+ {settings?.notify_webhook_url === MASK && (+ <button+ type="button"+ onClick={() => setWebhookUrl('')}+ className="px-2.5 rounded-lg text-[11px] font-medium text-zinc-300 border border-zinc-800 hover:text-rose-200 hover:bg-zinc-800 transition-colors"+ >+ Remove+ </button>+ )}+ </div>+ <p id="notify-webhook-hint" className={`mt-1 text-[11px] ${webhookError ? 'text-rose-400' : 'text-zinc-500'}`}>+ {webhookError ??+ (webhookUrl === MASK+ ? 'A webhook is saved. Type a new URL to replace it.'+ : settings?.notify_webhook_url === MASK && !webhookUrl.trim()+ ? 'Saving will remove the webhook.'+ : 'https only. kwnt posts a short title and line, never message text.')}+ </p>+ </div>++ <div className="space-y-1.5" role="group" aria-labelledby="notify-kinds-label">+ <p id="notify-kinds-label" className="text-xs font-medium text-zinc-400">Tell me when</p>+ {NOTIFY_KINDS.map((k) => (+ <label key={k.id} className="flex items-center gap-2 text-[11px] text-zinc-300">+ <input+ type="checkbox"+ className="accent-sky-500"+ checked={notifyOn.includes(k.id)}+ onChange={(e) => setNotifyOn((prev) => (e.target.checked ? [...prev, k.id] : prev.filter((x) => x !== k.id)))}+ />+ {k.label}+ </label>+ ))}+ </div>+ </fieldset>++ {saveError && (+ <div className="bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs flex items-center gap-2" role="alert">+ <AlertTriangle size={14} />+ <span>{saveError}</span>+ </div>+ )}+{saveSuccess && (<div className="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-3 py-2 rounded-lg text-xs flex items-center gap-2"><Check size={14} />@@ -283,8 +437,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, o</button><buttontype="submit"- disabled={saving}- className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"+ disabled={saving || !!webhookError}+ className="px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50">{saving ? 'Saving...' : 'Save Settings'}</button>diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex ed651749..13573d76 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -25,6 +25,8 @@ export interface Channel {lead_kwant_id: string;member_kwants: string[];routing_mode: string;+ /** Pinned for every turn in this channel; null when unset. */+ instructions?: string | null;}export interface Team {@@ -36,6 +38,8 @@ export interface Team {icon: string;lead_kwant_id: string;member_kwants: string[];+ /** Pinned for every turn in the team's channels; null when unset. */+ instructions?: string | null;}export interface SidebarProps {diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.tsnew file mode 100644index 00000000..4670eb3e--- /dev/null+++ b/frontend/src/continuity.ts@@ -0,0 +1,430 @@+// Agent continuity: pinned instructions, chat search, kwant memory, routines and notifications.+// Shapes follow /home/maus/shared/ship-software-safely/agent-continuity/contract.md ("Lin's implementation notes").++export const MAX_INSTRUCTIONS = 4000;+export const MAX_MEMORY = 500;+export const MAX_MEMORIES = 100;++export interface SearchHit {+ message_id: string;+ /** null: a direct chat with `kwant_id`. */+ channel_id: string | null;+ channel_name: string | null;+ kwant_id: string | null;+ author: string;+ /** Raw message text with `<mark>…</mark>` around hits. Not HTML-escaped. */+ snippet: string;+ created_at: string | null;+}++export interface Memory {+ id: string;+ text: string;+ source: 'user' | 'agent';+ created_at: string;+ updated_at: string;+}++export type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';+export const WEEKDAYS: Array<{ id: Weekday; label: string }> = [+ { id: 'mon', label: 'Mon' },+ { id: 'tue', label: 'Tue' },+ { id: 'wed', label: 'Wed' },+ { id: 'thu', label: 'Thu' },+ { id: 'fri', label: 'Fri' },+ { id: 'sat', label: 'Sat' },+ { id: 'sun', label: 'Sun' },+];++export type Schedule =+ | { type: 'once'; at: string }+ | { type: 'daily'; time: string; tz: string }+ | { type: 'weekly'; time: string; weekdays: Weekday[]; tz: string }+ | { type: 'interval'; every_minutes: number };++export type RunStatus = 'running' | 'ok' | 'error' | 'skipped';++export interface Routine {+ id: string;+ kwant_id: string;+ /** null: the kwant's direct chat. */+ channel_id: string | null;+ name: string;+ instructions: string;+ schedule: Schedule;+ enabled: boolean;+ next_run_at: string | null;+ last_run_at: string | null;+ last_status: RunStatus | null;+ created_at: string;+}++export interface RoutineRun {+ id: string;+ routine_id: string;+ trigger: 'schedule' | 'manual';+ started_at: string;+ ended_at: string | null;+ status: RunStatus;+ error: string | null;+ message_id: string | null;+}++export interface RoutineInput {+ kwant_id: string;+ channel_id: string | null;+ name: string;+ instructions: string;+ schedule: Schedule;+ enabled: boolean;+}++export type NotifyKind = 'turn_finished' | 'approval_needed' | 'routine_failed';+export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [+ { id: 'turn_finished', label: 'A kwant finished replying' },+ { id: 'approval_needed', label: 'A kwant needs your approval' },+ { id: 'routine_failed', label: 'A routine failed' },+];++export interface NotifyEvent {+ kind: NotifyKind;+ kwant_id: string;+ kwant_name: string;+ channel_id: string | null;+ title: string;+ body: string;+}++// ---------------------------------------------------------------------------+// Search snippets++export interface SnippetPart {+ text: string;+ hit: boolean;+}++/**+ * Splits a snippet into plain-text parts, marking the ones the server wrapped in `<mark>`.+ * Everything is rendered as text, so any other markup in a message stays inert; only `<mark>`+ * survives, as the `hit` flag.+ */+export function snippetParts(snippet: string): SnippetPart[] {+ const parts: SnippetPart[] = [];+ let hit = false;+ for (const piece of snippet.split(/(<\/?mark>)/)) {+ if (piece === '<mark>') hit = true;+ else if (piece === '</mark>') hit = false;+ else if (piece) {+ const last = parts[parts.length - 1];+ if (last && last.hit === hit) last.text += piece;+ else parts.push({ text: piece, hit });+ }+ }+ return parts;+}++const HTML_ESCAPES: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };++/** The same rule as an HTML string: everything escaped, then only `<mark>`/`</mark>` re-allowed. */+export function sanitizeSnippet(snippet: string): string {+ return snippetParts(snippet)+ .map((p) => {+ const text = p.text.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);+ return p.hit ? `<mark>${text}</mark>` : text;+ })+ .join('');+}++export interface HitGroup {+ key: string;+ channel_id: string | null;+ kwant_id: string | null;+ label: string;+ hits: SearchHit[];+}++/** Groups hits by where they were said, keeping the server's ranking (best group first). */+export function groupHits(hits: SearchHit[], kwantName: (id: string) => string | undefined): HitGroup[] {+ const groups = new Map<string, HitGroup>();+ for (const h of hits) {+ const key = h.channel_id ? `c:${h.channel_id}` : `k:${h.kwant_id ?? ''}`;+ let g = groups.get(key);+ if (!g) {+ const label = h.channel_id+ ? channelLabel(h.channel_name ?? h.channel_id)+ : `Direct chat · ${(h.kwant_id && kwantName(h.kwant_id)) || 'kwant'}`;+ g = { key, channel_id: h.channel_id, kwant_id: h.channel_id ? null : h.kwant_id, label, hits: [] };+ groups.set(key, g);+ }+ g.hits.push(h);+ }+ return Array.from(groups.values());+}++export const channelLabel = (name: string) => (name.startsWith('team-') ? `@${name.slice(5)}` : `#${name}`);++// ---------------------------------------------------------------------------+// Routine schedules++export interface ScheduleForm {+ type: Schedule['type'];+ /** `datetime-local` value, in the browser's time zone. */+ onceAt: string;+ time: string;+ weekdays: Weekday[];+ tz: string;+ everyMinutes: string;+}++/**+ * Browsers (ICU) still report some zones by their old names, which newer system tz databases+ * (e.g. Ubuntu 24.04 without tzdata-legacy) no longer ship, so the server would reject them.+ */+const LEGACY_TZ: Record<string, string> = {+ 'Africa/Asmera': 'Africa/Asmara',+ 'America/Buenos_Aires': 'America/Argentina/Buenos_Aires',+ 'America/Catamarca': 'America/Argentina/Catamarca',+ 'America/Cordoba': 'America/Argentina/Cordoba',+ 'America/Godthab': 'America/Nuuk',+ 'America/Indianapolis': 'America/Indiana/Indianapolis',+ 'America/Jujuy': 'America/Argentina/Jujuy',+ 'America/Louisville': 'America/Kentucky/Louisville',+ 'America/Mendoza': 'America/Argentina/Mendoza',+ 'Asia/Calcutta': 'Asia/Kolkata',+ 'Asia/Katmandu': 'Asia/Kathmandu',+ 'Asia/Rangoon': 'Asia/Yangon',+ 'Asia/Saigon': 'Asia/Ho_Chi_Minh',+ 'Atlantic/Faeroe': 'Atlantic/Faroe',+ 'Europe/Kiev': 'Europe/Kyiv',+ 'Pacific/Enderbury': 'Pacific/Kanton',+ 'Pacific/Ponape': 'Pacific/Pohnpei',+ 'Pacific/Truk': 'Pacific/Chuuk',+};++/** The current IANA name for a zone the browser may report by an old one. */+export const canonicalTimeZone = (tz: string) => LEGACY_TZ[tz] ?? tz;++/** The browser's IANA time zone, or UTC when it can't tell. */+export function defaultTimeZone(): string {+ try {+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return tz ? canonicalTimeZone(tz) : 'UTC';+ } catch {+ return 'UTC';+ }+}++const pad = (n: number) => String(n).padStart(2, '0');++/** A `datetime-local` value for a Date, in local time. */+export function toLocalInput(d: Date): string {+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;+}++export function emptyScheduleForm(now = new Date(), tz = defaultTimeZone()): ScheduleForm {+ const soon = new Date(now.getTime() + 60 * 60 * 1000);+ soon.setMinutes(0, 0, 0);+ return { type: 'daily', onceAt: toLocalInput(soon), time: '09:00', weekdays: ['mon', 'tue', 'wed', 'thu', 'fri'], tz, everyMinutes: '60' };+}++export function formFromSchedule(s: Schedule, now = new Date()): ScheduleForm {+ const base = emptyScheduleForm(now, 'tz' in s ? s.tz : defaultTimeZone());+ switch (s.type) {+ case 'once': {+ const at = new Date(s.at);+ return { ...base, type: 'once', onceAt: Number.isNaN(at.getTime()) ? base.onceAt : toLocalInput(at) };+ }+ case 'daily':+ return { ...base, type: 'daily', time: s.time };+ case 'weekly':+ return { ...base, type: 'weekly', time: s.time, weekdays: s.weekdays };+ case 'interval':+ return { ...base, type: 'interval', everyMinutes: String(s.every_minutes) };+ }+}++/** The JSON the API takes, or a message for the first thing to fix. Mirrors the server's checks. */+export function scheduleFromForm(f: ScheduleForm, now = Date.now()): { schedule: Schedule } | { error: string } {+ switch (f.type) {+ case 'once': {+ const at = new Date(f.onceAt);+ if (!f.onceAt || Number.isNaN(at.getTime())) return { error: 'Pick a date and time.' };+ if (at.getTime() <= now) return { error: 'Pick a time in the future.' };+ return { schedule: { type: 'once', at: at.toISOString() } };+ }+ case 'daily':+ case 'weekly': {+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(f.time)) return { error: 'Use a time like 09:00.' };+ const tz = canonicalTimeZone(f.tz.trim());+ if (!tz) return { error: 'Pick a time zone.' };+ if (f.type === 'daily') return { schedule: { type: 'daily', time: f.time, tz } };+ if (f.weekdays.length === 0) return { error: 'Pick at least one day.' };+ const days = WEEKDAYS.map((d) => d.id).filter((d) => f.weekdays.includes(d));+ return { schedule: { type: 'weekly', time: f.time, weekdays: days, tz } };+ }+ case 'interval': {+ const n = Number(f.everyMinutes);+ if (!Number.isInteger(n) || n < 5 || n > 10080) return { error: 'Repeat every 5 to 10080 minutes.' };+ return { schedule: { type: 'interval', every_minutes: n } };+ }+ }+}++export function describeSchedule(s: Schedule): string {+ switch (s.type) {+ case 'once':+ return `Once, ${formatWhen(s.at)}`;+ case 'daily':+ return `Every day at ${s.time} (${s.tz})`;+ case 'weekly': {+ const days = s.weekdays.length === 7 ? 'every day' : s.weekdays.map((d) => WEEKDAYS.find((w) => w.id === d)?.label ?? d).join(', ');+ return `${days} at ${s.time} (${s.tz})`;+ }+ case 'interval':+ return s.every_minutes % 60 === 0+ ? `Every ${s.every_minutes / 60} h`+ : `Every ${s.every_minutes} min`;+ }+}++export function formatWhen(iso: string | null): string {+ if (!iso) return '—';+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return '—';+ return d.toLocaleString(undefined, { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });+}++/** Time zones for the picker: the browser's list when it has one, with the current value kept. */+export function timeZoneOptions(current: string): string[] {+ let list: string[] = [];+ try {+ const intl = Intl as unknown as { supportedValuesOf?: (k: string) => string[] };+ list = intl.supportedValuesOf?.('timeZone') ?? [];+ } catch {+ list = [];+ }+ const all = new Set(['UTC'].concat(list.map(canonicalTimeZone)));+ if (current) all.add(current);+ return Array.from(all);+}++// ---------------------------------------------------------------------------+// Notifications++export const BROWSER_NOTIFY_KEY = 'kwnt.notify.browser';+export const MASK = '••••••••';++/** Only https webhooks; the saved mask (unchanged) and "" (remove) are fine too. */+export function webhookUrlError(url: string): string | null {+ const v = url.trim();+ if (!v || v === MASK) return null;+ let u: URL;+ try {+ u = new URL(v);+ } catch {+ return 'Enter a full URL, like https://ntfy.sh/your-topic.';+ }+ if (u.protocol !== 'https:') return 'Use an https:// URL.';+ if (u.username || u.password) return 'Leave the user name and password out of the URL.';+ return null;+}++/**+ * OS notifications only when the person turned them on here, granted permission, and isn't+ * looking at kwnt. The server already drops kinds unticked in `notify_on`.+ */+export function shouldShowOsNotification(opts: {+ enabled: boolean;+ permission: NotificationPermission | 'unsupported';+ hidden: boolean;+ kind: string;+}): boolean {+ return opts.enabled && opts.permission === 'granted' && opts.hidden && NOTIFY_KINDS.some((k) => k.id === opts.kind);+}++/** Whether this browser has OS notifications switched on for kwnt (stored per browser). */+export function browserNotifyEnabled(storage: Pick<Storage, 'getItem'> | undefined = globalThis.localStorage): boolean {+ try {+ return storage?.getItem(BROWSER_NOTIFY_KEY) === 'on';+ } catch {+ return false;+ }+}++export function notificationPermission(): NotificationPermission | 'unsupported' {+ return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission;+}++// ---------------------------------------------------------------------------+// Live updates: App's single EventSource re-broadcasts these for whoever is open.++export type ContinuityEvent =+ | { type: 'memory_changed'; data: { kwant_id: string } }+ | { type: 'routine_run'; data: { routine_id: string; run_id: string; status: RunStatus } };++const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;++export function emitContinuity(e: ContinuityEvent) {+ bus?.dispatchEvent(new CustomEvent(e.type, { detail: e.data }));+}++export function onContinuity<T extends ContinuityEvent['type']>(+ type: T,+ fn: (data: Extract<ContinuityEvent, { type: T }>['data']) => void,+): () => void {+ const listener = (ev: Event) => fn((ev as CustomEvent).detail);+ bus?.addEventListener(type, listener);+ return () => bus?.removeEventListener(type, listener);+}++// ---------------------------------------------------------------------------+// API++async function request<T>(method: string, url: string, body?: unknown): Promise<T> {+ const res = await fetch(url, {+ method,+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ if (!res.ok) {+ let message = res.status === 404 ? 'It no longer exists.' : `Request failed (HTTP ${res.status}).`;+ try {+ const data = await res.json();+ if (data && typeof data.error === 'string' && data.error) message = data.error;+ } catch {+ // no JSON body+ }+ throw new Error(message);+ }+ if (res.status === 204) return undefined as T;+ return res.json();+}++const enc = encodeURIComponent;++export const continuityApi = {+ setTeamInstructions: (id: string, instructions: string) =>+ request<{ instructions: string | null }>('PATCH', `/api/teams/${enc(id)}`, { instructions }),+ setChannelInstructions: (id: string, instructions: string) =>+ request<{ instructions: string | null }>('PATCH', `/api/channels/${enc(id)}`, { instructions }),++ search: (q: string, opts: { channel_id?: string; kwant_id?: string; limit?: number } = {}) => {+ const p = new URLSearchParams({ q, limit: String(opts.limit ?? 30) });+ if (opts.channel_id) p.set('channel_id', opts.channel_id);+ if (opts.kwant_id) p.set('kwant_id', opts.kwant_id);+ return request<SearchHit[]>('GET', `/api/search?${p}`);+ },++ memories: (kwantId: string) => request<Memory[]>('GET', `/api/kwants/${enc(kwantId)}/memories`),+ addMemory: (kwantId: string, text: string) => request<Memory>('POST', `/api/kwants/${enc(kwantId)}/memories`, { text }),+ updateMemory: (kwantId: string, id: string, text: string) =>+ request<Memory>('PATCH', `/api/kwants/${enc(kwantId)}/memories/${enc(id)}`, { text }),+ removeMemory: (kwantId: string, id: string) => request<void>('DELETE', `/api/kwants/${enc(kwantId)}/memories/${enc(id)}`),++ routines: () => request<Routine[]>('GET', '/api/routines'),+ createRoutine: (body: RoutineInput) => request<Routine>('POST', '/api/routines', body),+ updateRoutine: (id: string, body: Partial<RoutineInput>) => request<Routine>('PATCH', `/api/routines/${enc(id)}`, body),+ removeRoutine: (id: string) => request<void>('DELETE', `/api/routines/${enc(id)}`),+ runRoutine: (id: string) => request<RoutineRun>('POST', `/api/routines/${enc(id)}/run`),+ routineRuns: (id: string, limit = 20) => request<RoutineRun[]>('GET', `/api/routines/${enc(id)}/runs?limit=${limit}`),+};diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 0ad7ac16..6f8a4285 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -124,3 +124,20 @@@media (prefers-reduced-motion: reduce) {.kw-toast { animation: none; }}++/* A message reached from search glows briefly; without motion it is just outlined. */+@keyframes kw-flash {+ 0%, 60% { box-shadow: 0 0 0 2px theme('colors.amber.400 / 70%'); background: theme('colors.amber.400 / 8%'); }+ 100% { box-shadow: 0 0 0 2px transparent; background: transparent; }+}++.kw-flash {+ animation: kw-flash 2.4s ease-out;+}++@media (prefers-reduced-motion: reduce) {+ .kw-flash {+ animation: none;+ box-shadow: 0 0 0 2px theme('colors.amber.400 / 70%');+ }+}diff --git a/frontend/tests/continuity.test.mjs b/frontend/tests/continuity.test.mjsnew file mode 100644index 00000000..a0278f6c--- /dev/null+++ b/frontend/tests/continuity.test.mjs@@ -0,0 +1,158 @@+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import test from 'node:test';+import ts from 'typescript';++const load = async (path) => {+ const source = await readFile(new URL(path, import.meta.url), 'utf8');+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext } });+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);+};++const c = await load('../src/continuity.ts');++test('snippets escape everything except <mark>', () => {+ const raw = 'see <script>alert("x")</script> & <b>the</b> <mark>plan</mark> <img src=x onerror=alert(1)>';+ const html = c.sanitizeSnippet(raw);+ assert.equal(+ html,+ 'see <script>alert("x")</script> & <b>the</b> <mark>plan</mark> <img src=x onerror=alert(1)>',+ );+ assert.ok(!/<(?!\/?mark>)/.test(html), 'no tag other than mark survives');+});++test('markup inside a hit stays text, and attributes on mark are not trusted', () => {+ assert.equal(c.sanitizeSnippet('<mark><i>x</i></mark>'), '<mark><i>x</i></mark>');+ assert.equal(c.sanitizeSnippet('<mark onclick="x">y</mark>'), '<mark onclick="x">y');+ assert.deepEqual(c.snippetParts('a <mark>b</mark> c <mark>d</mark>'), [+ { text: 'a ', hit: false },+ { text: 'b', hit: true },+ { text: ' c ', hit: false },+ { text: 'd', hit: true },+ ]);+ assert.deepEqual(c.snippetParts(''), []);+});++test('groups hits by channel or direct chat, keeping rank order', () => {+ const hit = (id, channel_id, channel_name, kwant_id) => ({ message_id: id, channel_id, channel_name, kwant_id, author: 'a', snippet: '', created_at: null });+ const groups = c.groupHits(+ [hit('1', 'c1', 'general', null), hit('2', null, null, 'k1'), hit('3', 'c2', 'team-core', null), hit('4', 'c1', 'general', null)],+ (id) => (id === 'k1' ? 'Ada' : undefined),+ );+ assert.deepEqual(groups.map((g) => [g.label, g.hits.map((h) => h.message_id)]), [+ ['#general', ['1', '4']],+ ['Direct chat · Ada', ['2']],+ ['@core', ['3']],+ ]);+ assert.equal(groups[1].kwant_id, 'k1');+});++const form = (over) => ({ ...c.emptyScheduleForm(new Date('2026-10-17T08:00:00Z'), 'Europe/Kyiv'), ...over });+const NOW = Date.parse('2026-10-17T08:00:00Z');++test('schedule form → JSON for each type', () => {+ const local = '2026-10-18T09:30';+ assert.deepEqual(c.scheduleFromForm(form({ type: 'once', onceAt: local }), NOW), {+ schedule: { type: 'once', at: new Date(local).toISOString() },+ });+ assert.deepEqual(c.scheduleFromForm(form({ type: 'daily', time: '07:05' }), NOW), {+ schedule: { type: 'daily', time: '07:05', tz: 'Europe/Kyiv' },+ });+ assert.deepEqual(c.scheduleFromForm(form({ type: 'weekly', time: '18:00', weekdays: ['sun', 'mon', 'wed'] }), NOW), {+ schedule: { type: 'weekly', time: '18:00', weekdays: ['mon', 'wed', 'sun'], tz: 'Europe/Kyiv' },+ });+ assert.deepEqual(c.scheduleFromForm(form({ type: 'interval', everyMinutes: '90' }), NOW), {+ schedule: { type: 'interval', every_minutes: 90 },+ });+});++test('schedule form rejects what the server rejects', () => {+ const err = (over) => c.scheduleFromForm(form(over), NOW).error;+ assert.ok(err({ type: 'once', onceAt: '2026-10-01T09:00' }));+ assert.ok(err({ type: 'once', onceAt: '' }));+ assert.ok(err({ type: 'daily', time: '24:00' }));+ assert.ok(err({ type: 'daily', time: '9:00' }));+ assert.ok(err({ type: 'daily', tz: ' ' }));+ assert.ok(err({ type: 'weekly', weekdays: [] }));+ for (const n of ['4', '10081', '7.5', '', 'abc']) assert.ok(err({ type: 'interval', everyMinutes: n }), n);+ assert.equal(err({ type: 'interval', everyMinutes: '5' }), undefined);+ assert.equal(err({ type: 'interval', everyMinutes: '10080' }), undefined);+});++test('a saved schedule round-trips through the form', () => {+ for (const s of [+ { type: 'daily', time: '06:15', tz: 'America/New_York' },+ { type: 'weekly', time: '12:00', weekdays: ['tue', 'fri'], tz: 'UTC' },+ { type: 'interval', every_minutes: 45 },+ { type: 'once', at: '2026-12-01T10:00:00.000Z' },+ ]) {+ assert.deepEqual(c.scheduleFromForm(c.formFromSchedule(s), NOW).schedule, s);+ }+});++test('time zone defaults to the browser and falls back to UTC', () => {+ assert.equal(c.defaultTimeZone(), Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');+ assert.equal(c.emptyScheduleForm().tz, c.defaultTimeZone());+ const original = Intl.DateTimeFormat;+ try {+ Intl.DateTimeFormat = () => ({ resolvedOptions: () => ({ timeZone: undefined }) });+ assert.equal(c.defaultTimeZone(), 'UTC');+ Intl.DateTimeFormat = () => {+ throw new Error('no Intl');+ };+ assert.equal(c.defaultTimeZone(), 'UTC');+ } finally {+ Intl.DateTimeFormat = original;+ }+ assert.ok(c.timeZoneOptions('Mars/Base').includes('Mars/Base'));+ try {+ Intl.DateTimeFormat = () => ({ resolvedOptions: () => ({ timeZone: 'Asia/Calcutta' }) });+ assert.equal(c.defaultTimeZone(), 'Asia/Kolkata');+ } finally {+ Intl.DateTimeFormat = original;+ }+ assert.ok(!c.timeZoneOptions('UTC').includes('Europe/Kiev'));+ assert.deepEqual(c.scheduleFromForm(form({ type: 'daily', tz: 'Europe/Kiev' }), NOW).schedule.tz, 'Europe/Kyiv');+ assert.ok(c.timeZoneOptions('').includes('UTC'));+});++test('OS notifications only when on, granted, hidden and a known kind', () => {+ const ok = { enabled: true, permission: 'granted', hidden: true, kind: 'turn_finished' };+ assert.equal(c.shouldShowOsNotification(ok), true);+ assert.equal(c.shouldShowOsNotification({ ...ok, kind: 'routine_failed' }), true);+ assert.equal(c.shouldShowOsNotification({ ...ok, enabled: false }), false);+ assert.equal(c.shouldShowOsNotification({ ...ok, permission: 'default' }), false);+ assert.equal(c.shouldShowOsNotification({ ...ok, permission: 'denied' }), false);+ assert.equal(c.shouldShowOsNotification({ ...ok, permission: 'unsupported' }), false);+ assert.equal(c.shouldShowOsNotification({ ...ok, hidden: false }), false);+ assert.equal(c.shouldShowOsNotification({ ...ok, kind: 'something_else' }), false);+});++test('browser toggle is read per browser and defaults off', () => {+ const store = (v) => ({ getItem: (k) => (k === c.BROWSER_NOTIFY_KEY ? v : null) });+ assert.equal(c.browserNotifyEnabled(store('on')), true);+ assert.equal(c.browserNotifyEnabled(store('off')), false);+ assert.equal(c.browserNotifyEnabled(store(null)), false);+ assert.equal(c.browserNotifyEnabled(undefined), false);+ assert.equal(c.browserNotifyEnabled({ getItem: () => { throw new Error('blocked'); } }), false);+});++test('webhook URL: https only, no credentials; mask and empty pass', () => {+ assert.equal(c.webhookUrlError(''), null);+ assert.equal(c.webhookUrlError(c.MASK), null);+ assert.equal(c.webhookUrlError('https://ntfy.sh/topic'), null);+ assert.ok(c.webhookUrlError('http://ntfy.sh/topic'));+ assert.ok(c.webhookUrlError('ftp://x'));+ assert.ok(c.webhookUrlError('ntfy.sh/topic'));+ assert.ok(c.webhookUrlError('https://user:[email protected]/topic'));+});++test('continuity bus delivers to subscribers until they unsubscribe', () => {+ const seen = [];+ const off = c.onContinuity('memory_changed', (d) => seen.push(d.kwant_id));+ c.emitContinuity({ type: 'memory_changed', data: { kwant_id: 'k1' } });+ c.emitContinuity({ type: 'routine_run', data: { routine_id: 'r', run_id: 'x', status: 'ok' } });+ off();+ c.emitContinuity({ type: 'memory_changed', data: { kwant_id: 'k2' } });+ assert.deepEqual(seen, ['k1']);+});