Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Escape keeps typed text in Settings; bot editor and Manage team close on Escape; roster from the keyboard; checkpoints reload after restore

Pixel (kwant bot)cbb2fae42907
diff --git a/frontend/src/components/ApiKeysPanel.tsx b/frontend/src/components/ApiKeysPanel.tsx
index 5d600c62..1b455ebc 100644
--- a/frontend/src/components/ApiKeysPanel.tsx
+++ b/frontend/src/components/ApiKeysPanel.tsx
@@ -4,6 +4,7 @@
import React, { useEffect, useState } from 'react';
import { AlertTriangle, Check, ChevronDown, ChevronRight, Globe, Key, Loader2 } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
+import { editorProps } from '../escape';
const DEFAULT_OLLAMA = 'http://localhost:11434/v1';
@@ -26,6 +27,8 @@ const input =
export const ApiKeysPanel: React.FC<{ onSaved?: () => void; defaultOpen?: boolean }> = ({ onSaved, defaultOpen = false }) => {
const [open, setOpen] = useState(defaultOpen);
const [keys, setKeys] = useState<Keys | null>(null);
+ // What's saved, so Escape keeps keys typed but not saved yet.
+ const [loaded, setLoaded] = useState<Keys | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
@@ -38,14 +41,16 @@ export const ApiKeysPanel: React.FC<{ onSaved?: () => void; defaultOpen?: boolea
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
- .then((d: Partial<Keys>) =>
- setKeys({
+ .then((d: Partial<Keys>) => {
+ const k = {
anthropic_api_key: d.anthropic_api_key ?? '',
xai_api_key: d.xai_api_key ?? '',
openai_api_key: d.openai_api_key ?? '',
ollama_url: d.ollama_url || DEFAULT_OLLAMA,
- }),
- )
+ };
+ setKeys(k);
+ setLoaded(k);
+ })
.catch(() => setLoadError('Couldn’t load your keys.'));
};
useEffect(load, []);
@@ -99,7 +104,7 @@ export const ApiKeysPanel: React.FC<{ onSaved?: () => void; defaultOpen?: boolea
{open ? <ChevronDown size={15} className="text-zinc-500" aria-hidden="true" /> : <ChevronRight size={15} className="text-zinc-500" aria-hidden="true" />}
</button>
- <form id="space-api-keys" hidden={!open} onSubmit={save} className="space-y-3 px-3 pb-3">
+ <form id="space-api-keys" hidden={!open} onSubmit={save} {...editorProps(JSON.stringify(keys) !== JSON.stringify(loaded))} className="space-y-3 px-3 pb-3">
<p className="text-[11px] text-zinc-500">
One key per provider for the API-key engines. To keep several keys for one provider, add them as accounts above.
</p>
diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsx
index f21277e5..a72d04bd 100644
--- a/frontend/src/components/ConnectionsView.tsx
+++ b/frontend/src/components/ConnectionsView.tsx
@@ -23,6 +23,7 @@ import {
usedByText,
} from '../connections';
import { inDesktopApp } from '../externalLinks';
+import { editorProps } from '../escape';
const TONES: Record<Tone, string> = {
amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
@@ -355,7 +356,7 @@ export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen =
{entry.added && <ComposioAppSearch entry={entry} api={searchApi} initialApps={initialApps} />}
{open && !entry.added && (
- <form onSubmit={submit} className="space-y-3" aria-label={`Add ${entry.name}`} noValidate>
+ <form onSubmit={submit} {...editorProps(!!(url.trim() || key.trim() || enabled))} className="space-y-3" aria-label={`Add ${entry.name}`} noValidate>
<div className="space-y-1">
<label htmlFor={`${id}-url`} className="block text-xs font-medium text-zinc-200">
MCP URL
@@ -448,8 +449,9 @@ export const AddConnectionMenu: React.FC<{ choices: AddChoice[]; disabled?: bool
if (!open) return;
wrapRef.current?.querySelector<HTMLButtonElement>('[data-add-choice]')?.focus();
const onKey = (e: KeyboardEvent) => {
- if (e.key !== 'Escape') return;
- e.stopPropagation();
+ if (e.key !== 'Escape' || e.defaultPrevented) return;
+ // Closes the menu only, not Settings around it.
+ e.preventDefault();
setOpen(false);
buttonRef.current?.focus();
};
diff --git a/frontend/src/components/EngineAccounts.tsx b/frontend/src/components/EngineAccounts.tsx
index 1168562f..9a0585a0 100644
--- a/frontend/src/components/EngineAccounts.tsx
+++ b/frontend/src/components/EngineAccounts.tsx
@@ -1,6 +1,7 @@
import React, { useEffect, useRef, useState } from 'react';
import { Check, ChevronDown, ChevronRight, Copy, ExternalLink, KeyRound, Loader2, LogIn, LogOut, Pencil, Plus, RefreshCw, Server, Star, Trash2, Wrench } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
+import { editorProps } from '../escape';
import type { EngineInfo, Tone } from '../engines';
import {
CUSTOM_PRESETS,
@@ -224,12 +225,7 @@ const KeyOrLoginForm: React.FC<{
return (
<form
onSubmit={submit}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.stopPropagation();
- onCancel();
- }
- }}
+ {...editorProps(!!(name.trim() || apiKey.trim() || homeDir.trim() || isDefault), onCancel)}
className="bg-zinc-950/60 border border-sky-500/30 rounded-lg p-3 space-y-3"
aria-label="New account"
>
@@ -299,6 +295,9 @@ export const CustomServerForm: React.FC<{
const listed = c?.status === 'ready' ? c.models : [];
const [typing, setTyping] = useState(!!c?.model && !listed.some((m) => m.id === c.model));
const active = CUSTOM_PRESETS.find((p) => p.id === preset);
+ // Escape cancels an untouched form and keeps one with changes.
+ const unsaved =
+ !!(name.trim() || apiKey.trim() || isDefault) || protocol !== (c?.protocol ?? 'openai-chat') || baseUrl !== (c?.base_url ?? '') || model !== (c?.model ?? '');
const applyPreset = (id: string) => {
const p = CUSTOM_PRESETS.find((x) => x.id === id);
@@ -354,12 +353,7 @@ export const CustomServerForm: React.FC<{
return (
<form
onSubmit={submit}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.stopPropagation();
- onCancel();
- }
- }}
+ {...editorProps(unsaved, onCancel)}
data-custom-form={editing ? 'edit' : 'new'}
className="bg-zinc-950/60 border border-sky-500/30 rounded-lg p-3 space-y-3"
aria-label={editing ? `Server for ${account!.name}` : 'New custom server'}
@@ -586,6 +580,7 @@ const AccountRow: React.FC<{
{editingName ? (
<form
className="flex items-center gap-1.5"
+ {...editorProps(name !== p.name, () => setEditingName(false))}
onSubmit={(e) => {
e.preventDefault();
saveName();
@@ -600,13 +595,6 @@ const AccountRow: React.FC<{
maxLength={60}
value={name}
onChange={(e) => setName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.stopPropagation();
- setName(p.name);
- setEditingName(false);
- }
- }}
className={`${input} py-1 w-36`}
/>
<button type="submit" disabled={busy} className={quietBtn} aria-label="Save name">
diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsx
index f658a829..897145fb 100644
--- a/frontend/src/components/ImportDialog.tsx
+++ b/frontend/src/components/ImportDialog.tsx
@@ -19,6 +19,7 @@ import {
toolNote,
trapFocusTarget,
} from '../imports';
+import { useEscapeLayer } from '../escape';
const btn =
'flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-zinc-300 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70 hover:text-zinc-100 transition-colors disabled:opacity-50';
@@ -395,14 +396,8 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })
importApi.prompts().then(setPrompts, setPromptsError);
};
useEffect(loadPrompts, []);
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- // Space settings underneath leaves Escape to this dialog while it's open.
- if (e.key === 'Escape') closeRef.current();
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, []);
+ // Escape closes this dialog and not Settings under it, and keeps a pasted reply that isn't imported yet.
+ useEscapeLayer(dialogRef, true, () => closeRef.current(), { unsaved: reply.trim() !== '' && !applied });
// Focus goes back to whatever opened the dialog when it closes.
useEffect(() => {
const opener = document.activeElement as HTMLElement | null;
diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsx
index 2cefb54b..4f2991ca 100644
--- a/frontend/src/components/ManageTeamModal.tsx
+++ b/frontend/src/components/ManageTeamModal.tsx
@@ -7,6 +7,7 @@ import { playSfx } from '../audio/chiptune';
import { InstructionsField } from './Instructions';
import { MAX_INSTRUCTIONS } from '../continuity';
import { teamNameToSave } from '../teamChannel';
+import { useEscapeLayer } from '../escape';
interface ManageTeamModalProps {
isOpen: boolean;
@@ -93,6 +94,33 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
}
};
+ // Escape closes Manage team when nothing differs from the saved team, and keeps it open otherwise.
+ const saved = team
+ ? {
+ name: team.name,
+ description: team.description || '',
+ instructions: team.instructions || '',
+ workspace: team.workspace_path ? `local:${team.workspace_path}` : team.repo_url ? `repo:${team.repo_url}` : 'default',
+ lead: team.lead_kwant_id || (kwants[0]?.id ?? ''),
+ members: [...memberIdsOf(team)].sort().join(','),
+ }
+ : null;
+ const edited = {
+ name,
+ description,
+ instructions,
+ workspace: workspaceType === 'local' ? `local:${workspacePath}` : workspaceType === 'repo' ? `repo:${repoUrl}` : 'default',
+ lead: leadKwantId,
+ members: [...memberIds].sort().join(','),
+ };
+ const unsaved = !!saved && (Object.keys(saved) as (keyof typeof saved)[]).some((k) => saved[k] !== edited[k]);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useEscapeLayer(rootRef, isOpen && !!team, onClose, {
+ modal: true,
+ unsaved,
+ fallback: () => [...document.querySelectorAll<HTMLElement>('[data-composer]')].find((el) => !el.closest('[inert]')),
+ });
+
useEffect(() => {
if (team) {
setName(team.name);
@@ -212,7 +240,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
return (
<div className="kw-dialog 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 role="dialog" aria-modal="true" aria-labelledby="manage-team-title" className="kw-dialog-panel 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">
+ <div ref={rootRef} tabIndex={-1} role="dialog" aria-modal="true" aria-labelledby="manage-team-title" className="kw-dialog-panel outline-none 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">
@@ -225,6 +253,8 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
</div>
</div>
<button
+ type="button"
+ aria-label="Close"
onClick={() => {
playSfx('click');
onClose();
@@ -444,54 +474,58 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
</select>
</div>
- {/* Members Roster Checklist */}
+ {/* Members Roster Checklist: each row is a toggle button (Tab to it, Space or Enter) */}
<div>
<div className="flex items-center justify-between mb-1.5">
- <label className="block text-xs font-medium text-zinc-400">
+ <p id="team-roster-label" className="block text-xs font-medium text-zinc-400">
Team Roster ({memberIds.length}/{kwants.length} Assigned)
- </label>
- <span className="text-[11px] text-zinc-500">Click to add/remove</span>
+ </p>
+ <span className="text-[11px] text-zinc-500">Select a bot to add or remove it</span>
</div>
- <div className="space-y-1.5 max-h-48 overflow-y-auto p-1 bg-zinc-950/60 border border-zinc-800/80 rounded-xl">
+ <div role="group" aria-labelledby="team-roster-label" className="space-y-1.5 max-h-48 overflow-y-auto p-1 bg-zinc-950/60 border border-zinc-800/80 rounded-xl">
{kwants.map((k) => {
const isMember = memberIds.includes(k.id);
const isLead = leadKwantId === k.id;
return (
- <div
+ <button
+ type="button"
key={k.id}
+ aria-pressed={isMember}
+ data-roster-row={k.id}
onClick={() => handleToggleMember(k.id)}
- className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-all border ${
+ className={`w-full text-left flex items-center justify-between p-2 rounded-lg cursor-pointer transition-all border focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400 ${
isMember
? 'bg-zinc-800/70 border-sky-500/30 text-zinc-100'
: 'bg-zinc-900/30 border-zinc-800/40 text-zinc-400 hover:bg-zinc-800/30 hover:text-zinc-200'
}`}
>
- <div className="flex items-center gap-2.5 min-w-0">
+ <span className="flex items-center gap-2.5 min-w-0">
<ModernAvatar role={k.avatar_sprite} name={k.name} size={28} />
- <div className="min-w-0">
- <div className="flex items-center gap-1.5">
+ <span className="block min-w-0">
+ <span className="flex items-center gap-1.5">
<span className="text-xs font-medium text-zinc-200 truncate">{k.name}</span>
{isLead && (
<span className="text-[9px] font-semibold uppercase px-1 py-0.2 rounded bg-sky-500/20 text-sky-300 border border-sky-500/30 flex items-center gap-0.5">
- <ShieldCheck size={9} />
+ <ShieldCheck size={9} aria-hidden="true" />
Lead
</span>
)}
- </div>
- <p className="text-[10px] text-zinc-400 truncate">{k.title}</p>
- </div>
- </div>
-
- <div
- className={`w-5 h-5 rounded flex items-center justify-center border transition-all ${
+ </span>
+ <span className="block text-[10px] text-zinc-400 truncate">{k.title}</span>
+ </span>
+ </span>
+
+ <span
+ aria-hidden="true"
+ className={`w-5 h-5 shrink-0 rounded flex items-center justify-center border transition-all ${
isMember
? 'bg-sky-500 text-white border-sky-400'
: 'border-zinc-700 bg-zinc-900 text-transparent'
}`}
>
<Check size={13} strokeWidth={2.5} />
- </div>
- </div>
+ </span>
+ </button>
);
})}
</div>
diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsx
index bc06ac7b..b8c7fcfb 100644
--- a/frontend/src/components/McpServersModal.tsx
+++ b/frontend/src/components/McpServersModal.tsx
@@ -58,6 +58,7 @@ import {
isBlankRequired,
} from '../mcp';
import { inDesktopApp, leaveForSignIn, pollUntil, signInChanged } from '../externalLinks';
+import { useEscapeLayer } from '../escape';
interface McpServersModalProps {
isOpen: boolean;
@@ -372,6 +373,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
// Form view: null = list, 'new' = adding, otherwise the id being edited.
const [editing, setEditing] = useState<string | null>(null);
const [form, setForm] = useState<McpFormState>(emptyMcpForm());
+ const [formStart, setFormStart] = useState<McpFormState | null>(null);
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
// Catalog step before the form when adding, its search, and the preset the form came from.
@@ -491,17 +493,10 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
useEffect(() => stopWatchingPopup, [stopWatchingPopup]);
- useEffect(() => {
- if (!isOpen) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key !== 'Escape') return;
- if (editing) setEditing(null);
- else if (picking) setPicking(false);
- else onClose();
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [isOpen, editing, picking, onClose]);
+ // Escape steps back (form or catalog to the list), then closes; it keeps a form with changes.
+ const rootRef = useRef<HTMLDivElement>(null);
+ const formDirty = editing !== null && JSON.stringify(form) !== JSON.stringify(formStart);
+ useEscapeLayer(rootRef, isOpen, () => (editing ? setEditing(null) : picking ? setPicking(false) : onClose()), { modal: true, unsaved: formDirty });
if (!isOpen) return null;
@@ -606,14 +601,11 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
setFormError(null);
setPicking(false);
setPresetId(preset?.id ?? null);
- if (target === 'new') {
- setEditing('new');
- const f = preset?.form;
- setForm(f ? { ...f, env: f.env.map((r) => ({ ...r })), headers: f.headers.map((r) => ({ ...r })) } : emptyMcpForm());
- } else {
- setEditing(target.id);
- setForm(serverToForm(target));
- }
+ const f = preset?.form;
+ const start = target !== 'new' ? serverToForm(target) : f ? { ...f, env: f.env.map((r) => ({ ...r })), headers: f.headers.map((r) => ({ ...r })) } : emptyMcpForm();
+ setEditing(target === 'new' ? 'new' : target.id);
+ setForm(start);
+ setFormStart(start);
};
const handleSave = async (e: React.FormEvent) => {
@@ -1157,10 +1149,12 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
return (
<div className="kw-dialog 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 && close()}>
<div
+ ref={rootRef}
+ tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby="mcp-title"
- className="kw-dialog-panel bg-zinc-900 border border-zinc-800 rounded-2xl max-w-2xl w-full max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5"
+ className="kw-dialog-panel outline-none bg-zinc-900 border border-zinc-800 rounded-2xl max-w-2xl 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 gap-3 border-b border-zinc-800 pb-4">
<div className="flex items-center gap-2.5 min-w-0">
diff --git a/frontend/src/components/MemoryPanel.tsx b/frontend/src/components/MemoryPanel.tsx
index 6ca5667e..4795d903 100644
--- a/frontend/src/components/MemoryPanel.tsx
+++ b/frontend/src/components/MemoryPanel.tsx
@@ -4,6 +4,7 @@ import { UndoNotice } from './UndoNotice';
import { Bot, Check, Loader2, Pencil, Pin, PinOff, Plus, RefreshCw, Trash2, User, X } from 'lucide-react';
import { MAX_MEMORIES, MAX_MEMORY, MAX_PINNED, Memory, continuityApi, formatWhen, memoriesForDisplay, onContinuity } from '../continuity';
import { playSfx } from '../audio/chiptune';
+import { editorProps } from '../escape';
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';
@@ -117,7 +118,7 @@ export const MemoryRow: React.FC<{
</span>
</div>
{editing ? (
- <div className="space-y-1.5">
+ <div className="space-y-1.5" {...editorProps(text !== memory.text, () => setEditing(false))}>
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
@@ -125,10 +126,6 @@ export const MemoryRow: React.FC<{
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}
@@ -137,7 +134,14 @@ export const MemoryRow: React.FC<{
<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`}>
+ <button
+ type="button"
+ onClick={() => {
+ setText(memory.text);
+ setEditing(false);
+ }}
+ className={`${quietBtn} ml-auto`}
+ >
<X size={11} /> Cancel
</button>
<button
@@ -223,7 +227,7 @@ export const MemoryPanel: React.FC<{ kwantId: string; kwantName: string }> = ({
list gets long, the newest of the rest are shown and {kwantName} can search the others.
</p>
- <form onSubmit={add} className="space-y-1.5">
+ <form onSubmit={add} {...editorProps(!!draft.trim())} className="space-y-1.5">
<label htmlFor="memory-new" className="block text-xs font-medium text-zinc-400">
Add a memory
</label>
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 9251a943..9edb2134 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -1715,10 +1715,15 @@ export const RestoreSection: React.FC<{
setUndoId(null);
}, [task.id]);
+ const taskId = useRef(task.id);
+ taskId.current = task.id;
const load = async () => {
setErr(null);
+ const id = task.id;
try {
- setList(await api.checkpoints(task.id));
+ const cps = await api.checkpoints(id);
+ // Another task opened meanwhile: its own list loads instead.
+ if (taskId.current === id) setList(cps);
} catch (e) {
setErr(restoreErrorText(e));
onError?.(e);
@@ -1747,7 +1752,9 @@ export const RestoreSection: React.FC<{
setUndoId(r.before_restore_checkpoint_id);
setPicked(null);
setPreview(null);
+ // The list now has the checkpoint taken before the restore, for "Undo this restore".
setList(null);
+ void load();
onRestored?.(r, opts.rerun);
} catch (e) {
setErr(restoreErrorText(e));
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 108dcc83..fef1504e 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
import { TagListInput } from './TagListInput';
import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2, Gauge } from 'lucide-react';
import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
@@ -16,6 +16,7 @@ import { UsagePanel } from './UsagePanel';
import type { Channel, Kwant } from './Sidebar';
import { BotApprovalsSetting } from './ApprovalsSetting';
import { FlightSchoolPanel } from './FlightSchoolPanel';
+import { useEscapeLayer } from '../escape';
export type EditTab = 'profile' | 'memory' | 'skills' | 'routines' | 'usage';
const EDIT_TABS: Array<{ id: EditTab; label: string; Icon: typeof Brain }> = [
@@ -83,6 +84,8 @@ interface NewAgentModalProps {
approvalsOff?: boolean;
}
+type ProfileFields = { name: string; title: string; roleStyle: string; model: string; prompt: string; soul: string; profileId: string | null; failover: boolean; covers: string; avoids: string };
+
export const NewAgentModal: React.FC<NewAgentModalProps> = ({
isOpen,
onClose,
@@ -133,8 +136,35 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const engine = engineOfModel(model);
const engineProfiles = profilesForEngine(profiles, engine);
+ // The profile as it opened (or as a preset filled it in): Escape keeps the editor open while it differs.
+ const [base, setBase] = useState<ProfileFields | null>(null);
+ const current: ProfileFields = { name, title, roleStyle, model, prompt, soul, profileId, failover, covers: covers.join('\n'), avoids: avoids.join('\n') };
+ const unsaved = !!base && (Object.keys(base) as (keyof ProfileFields)[]).some((k) => base[k] !== current[k]);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useEscapeLayer(rootRef, isOpen, onClose, {
+ modal: true,
+ unsaved,
+ // Opened from a menu that has gone: back to the bot in the sidebar, or the composer.
+ fallback: () =>
+ [kwantId ? `[data-bot-row="${kwantId}"]` : '', '[data-composer]']
+ .map((sel) => (sel ? document.querySelector<HTMLElement>(sel) : null))
+ .find((el) => el && !el.closest('[inert]')),
+ });
+
useEffect(() => {
if (!isOpen) return;
+ setBase({
+ name: initial?.name ?? '',
+ title: initial?.title ?? '',
+ roleStyle: initial?.avatar_sprite || 'architect',
+ model: initial?.preferred_model || 'auto',
+ prompt: initial?.persona_prompt ?? '',
+ soul: initial?.soul ?? '',
+ profileId: initial?.profile_id ?? null,
+ failover: initial?.profile_failover ?? true,
+ covers: (initial?.covers ?? []).join('\n'),
+ avoids: (initial?.avoids ?? []).join('\n'),
+ });
setName(initial?.name ?? '');
setTitle(initial?.title ?? '');
setRoleStyle(initial?.avatar_sprite || 'architect');
@@ -174,12 +204,21 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
playSfx('click');
setPresetId(preset?.id ?? null);
setError(null);
- setName(preset ? uniqueAgentName(preset.name, takenNames) : '');
- setTitle(preset?.title ?? '');
- setRoleStyle(preset?.avatar_sprite ?? 'architect');
- setModel(preset?.preferred_model ?? 'auto');
- setPrompt(preset?.persona_prompt ?? '');
- setSoul(preset?.soul ?? '');
+ const filled = {
+ name: preset ? uniqueAgentName(preset.name, takenNames) : '',
+ title: preset?.title ?? '',
+ roleStyle: preset?.avatar_sprite ?? 'architect',
+ model: preset?.preferred_model ?? 'auto',
+ prompt: preset?.persona_prompt ?? '',
+ soul: preset?.soul ?? '',
+ };
+ setName(filled.name);
+ setTitle(filled.title);
+ setRoleStyle(filled.roleStyle);
+ setModel(filled.model);
+ setPrompt(filled.prompt);
+ setSoul(filled.soul);
+ setBase((b) => (b ? { ...b, ...filled } : b));
};
if (!isOpen) return null;
@@ -224,10 +263,12 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
return (
<div className="kw-dialog fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 select-none">
<div
+ ref={rootRef}
+ tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby="agent-modal-title"
- className="kw-dialog-panel 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"
+ className="kw-dialog-panel outline-none 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">
@@ -354,8 +395,9 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
)}
<div>
- <label className="block text-xs font-medium text-zinc-400 mb-1">Name</label>
+ <label htmlFor="agent-name" className="block text-xs font-medium text-zinc-400 mb-1">Name</label>
<input
+ id="agent-name"
type="text"
required
value={name}
diff --git a/frontend/src/components/PasswordStorePanel.tsx b/frontend/src/components/PasswordStorePanel.tsx
index 922fe180..f96a37da 100644
--- a/frontend/src/components/PasswordStorePanel.tsx
+++ b/frontend/src/components/PasswordStorePanel.tsx
@@ -17,6 +17,7 @@ import {
storeApi,
unlockProblemText,
} from '../passwordStore';
+import { useEscapeLayer } from '../escape';
export interface PasswordStoreState {
status: StoreStatus | null;
@@ -314,14 +315,11 @@ export const BitwardenLoginForm: React.FC<{
/** The unlock form in a dialog, from the "Locked" state of the list or the store bar. */
export const UnlockDialog: React.FC<{ status: StoreStatus | null; onClose: () => void; onUnlocked: (s: StoreStatus) => void }> = ({ status, onClose, onUnlocked }) => {
const id = useId();
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [onClose]);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useEscapeLayer(rootRef, true, onClose, { modal: true });
return (
<div className="kw-dialog kw-dialog-bottom fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
- <div role="dialog" aria-modal="true" aria-labelledby={`${id}-h`} className="kw-dialog-panel relative w-full max-w-sm rounded-2xl border border-zinc-800 bg-zinc-900 p-4 shadow-2xl" data-unlock-dialog>
+ <div ref={rootRef} tabIndex={-1} role="dialog" aria-modal="true" aria-labelledby={`${id}-h`} className="kw-dialog-panel outline-none relative w-full max-w-sm rounded-2xl border border-zinc-800 bg-zinc-900 p-4 shadow-2xl" data-unlock-dialog>
<h2 id={`${id}-h`} className="sr-only">
Unlock Bitwarden
</h2>
diff --git a/frontend/src/components/RoutinesModal.tsx b/frontend/src/components/RoutinesModal.tsx
index f7050c15..abf77520 100644
--- a/frontend/src/components/RoutinesModal.tsx
+++ b/frontend/src/components/RoutinesModal.tsx
@@ -1,8 +1,9 @@
-import React, { useEffect, useRef } from 'react';
+import React, { useRef } from 'react';
import { CalendarClock, X } from 'lucide-react';
import { RoutinesPanel } from './RoutinesPanel';
import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
+import { useEscapeLayer } from '../escape';
/** Every kwant's routines in one list. */
export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwants: Kwant[]; channels: Channel[]; onOpenSettings?: () => void }> = ({
@@ -12,23 +13,19 @@ export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwa
channels,
onOpenSettings,
}) => {
- 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]);
+ const rootRef = useRef<HTMLDivElement>(null);
+ useEscapeLayer(rootRef, isOpen, onClose, { modal: true });
if (!isOpen) return null;
return (
<div className="kw-dialog 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
+ ref={rootRef}
+ tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby="routines-title"
- className="kw-dialog-panel 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"
+ className="kw-dialog-panel outline-none 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">
diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsx
index a63bd651..0e3a0ded 100644
--- a/frontend/src/components/RoutinesPanel.tsx
+++ b/frontend/src/components/RoutinesPanel.tsx
@@ -24,6 +24,7 @@ import { asSchedule, scheduleWords } from '../botActions';
import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
import { SuggestedRoutines } from './SuggestedRoutines';
+import { editorProps } from '../escape';
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';
@@ -112,7 +113,7 @@ export const RoutineForm: React.FC<{
const base = initial ?? seed;
const initialChannel = base?.thread_id ? IN_THREAD : base?.channel_id ?? '';
const initialSchedule = base ? asSchedule(base.schedule) : null;
- const [f, setF] = useState<FormState>(() => ({
+ const [start] = useState<FormState>(() => ({
kwantId: base?.kwant_id ?? fixedKwantId ?? kwants[0]?.id ?? '',
channelId: initialChannel,
name: base?.name ?? '',
@@ -120,6 +121,9 @@ export const RoutineForm: React.FC<{
enabled: initial?.enabled ?? true,
schedule: initialSchedule ? formFromSchedule(initialSchedule) : emptyScheduleForm(),
}));
+ const [f, setF] = useState<FormState>(start);
+ // Escape closes an untouched form and keeps one with changes (and Settings around it) open.
+ const unsaved = JSON.stringify(f) !== JSON.stringify(start);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const s = f.schedule;
@@ -161,7 +165,7 @@ export const RoutineForm: React.FC<{
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={label ?? (initial ? `Edit ${initial.name}` : 'New routine')}>
+ <form onSubmit={submit} noValidate {...editorProps(unsaved, onCancel)} className="p-3 rounded-xl border border-sky-500/30 bg-zinc-950/70 space-y-3" aria-label={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>
@@ -488,7 +492,7 @@ export const RoutineRow: React.FC<{
<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}>
+ <button type="button" onClick={onEdit} className={quietBtn} data-routine-edit={routine.id}>
<Pencil size={11} /> Edit
</button>
<button
@@ -571,9 +575,19 @@ export const RoutinesPanel: React.FC<{
setEditing(null);
reload();
};
+ // A form that closes (Escape, Cancel, Save) gives focus back to New routine or the routine's Edit.
+ const wrapRef = useRef<HTMLDivElement>(null);
+ const wasEditing = useRef<Routine | 'new' | null>(null);
+ useEffect(() => {
+ const was = wasEditing.current;
+ wasEditing.current = editing;
+ const a = document.activeElement;
+ if (editing || !was || (a && a !== document.body && a.isConnected)) return;
+ wrapRef.current?.querySelector<HTMLElement>(was === 'new' ? '[data-routine-new]' : `[data-routine-edit="${was.id}"]`)?.focus();
+ }, [editing]);
return (
- <div className="space-y-3">
+ <div ref={wrapRef} 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 bot on a schedule, then the bot answers as usual.
@@ -583,6 +597,7 @@ export const RoutinesPanel: React.FC<{
type="button"
onClick={() => setEditing('new')}
disabled={kwants.length === 0}
+ data-routine-new
className={`${smallBtn} shrink-0 border-sky-500/50 bg-sky-600 text-white hover:bg-sky-500`}
>
<Plus size={11} /> New routine
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 41ab1dce..e78d4342 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -50,6 +50,7 @@ import {
} from '../missions';
import { FlightSchoolSettings, TIERS, TIER_HINTS, TIER_LABELS, Tier, parseFlightSchoolSettings } from '../flightSchool';
import { DISCOVERY_CAPS, DISCOVERY_SETTING_EVENT, parseDiscoverySettings } from '../automationDiscovery';
+import { editorProps, isTextField } from '../escape';
const RECOVERY_PCTS = [0, 10, 25, 50, 100];
@@ -299,6 +300,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const [saving, setSaving] = useState(false);
const [saveSuccess, setSaveSuccess] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
+ // Text typed into the form and not saved yet: Escape keeps it (and Settings) open.
+ const [typed, setTyped] = useState(false);
// A 400 about the audit model shows next to that picker, not only at the bottom.
const modelError = isAuditorModelError(saveError);
// null until loaded (or from a server without the setting), and then left out of the save
@@ -347,7 +350,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
closeRef.current = onClose;
useEffect(() => {
if (!isOpen || embedded) return;
- const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeRef.current();
+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !e.defaultPrevented && closeRef.current();
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [isOpen, embedded]);
@@ -470,6 +473,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
if (res.ok) {
setSaveSuccess(true);
+ setTyped(false);
if (missionBoard !== null) window.dispatchEvent(new CustomEvent(MISSION_BOARD_SETTING_EVENT, { detail: missionBoard }));
if (discovery) window.dispatchEvent(new CustomEvent(DISCOVERY_SETTING_EVENT, { detail: discovery }));
if (webhookUrl.trim() && webhookUrl.trim() !== MASK) setWebhookUrl(MASK);
@@ -602,7 +606,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
)}
{/* App settings form; API keys moved to Settings › This space › Accounts */}
- <form onSubmit={handleSave} className="space-y-4">
+ <form onSubmit={handleSave} onChange={(e) => isTextField(e.target) && setTyped(true)} {...editorProps(typed)} className="space-y-4">
{onOpenApiKeys && (
<button
type="button"
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index 054dff28..6e462266 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -38,6 +38,7 @@ import { SpaceApprovalsSetting } from './ApprovalsSetting';
import type { SettingsScope, SpaceSettingsTab } from '../nav';
import { InstallAppButton } from './InstallAppButton';
+import { editorProps, useEscapeLayer } from '../escape';
export type { SettingsScope, SpaceSettingsTab };
@@ -113,19 +114,12 @@ export const SpaceSettings: React.FC<Props> = (p) => {
// Bumped after the dialog imports or undoes, so the Import tab's list loads again.
const [importsSeq, setImportsSeq] = useState(0);
const tp: TabProps = { ...p, onOpenImport: () => setImportOpen(true), importsSeq };
- const closeRef = useRef(onClose);
- closeRef.current = onClose;
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- // Dialogs opened from here (bot editor, tools) close themselves first.
- if (e.key === 'Escape' && !document.querySelector('[role="dialog"]:not([data-space-settings])')) closeRef.current();
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, []);
+ const rootRef = useRef<HTMLDivElement>(null);
+ // Escape closes Settings, but not while a dialog opened from here is open (the bot editor, Tools),
+ // and not while an editor in it holds typed text.
+ useEscapeLayer(rootRef, true, onClose, { covered: () => !!document.querySelector('[role="dialog"]:not([data-space-settings])') });
// Focus starts on the title (from the gear, Ctrl/⌘ 1–9 or a link), unless a tab already focused
// something inside, or a space was picked on the rail, which keeps focus there.
- const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const a = document.activeElement;
if (rootRef.current?.contains(a) || a?.closest('[data-rail-space]')) return;
@@ -407,7 +401,7 @@ const GeneralTab: React.FC<Props> = ({ space, spaces, kwants, onSpaceSaved, onAr
return (
<>
- <form onSubmit={save} className={`${card} p-4 space-y-4`}>
+ <form onSubmit={save} {...editorProps(dirty)} className={`${card} p-4 space-y-4`}>
<div className="flex items-center gap-3">
<SpaceTile space={{ id: space.id, icon, color: color || null }} size={44} />
<div className="flex-1 min-w-0">
diff --git a/frontend/src/components/Spaces.tsx b/frontend/src/components/Spaces.tsx
index ee9ff96d..80ff855c 100644
--- a/frontend/src/components/Spaces.tsx
+++ b/frontend/src/components/Spaces.tsx
@@ -13,6 +13,7 @@ import {
spaceSummaryTitle,
spacesApi,
} from '../spaces';
+import { useEscapeLayer } from '../escape';
const badge = (n: number) => (n > 99 ? '99+' : String(n));
@@ -194,28 +195,27 @@ export const SpaceSwitcher: React.FC<SwitcherProps> = ({ spaces, currentId, onSw
// ---------------------------------------------------------------------------
// Dialog frame shared by the space dialogs
-const Dialog: React.FC<{ title: string; subtitle?: string; labelId: string; onClose: () => void; children: React.ReactNode; wide?: boolean }> = ({
- title,
- subtitle,
- labelId,
- onClose,
- children,
- wide,
-}) => {
- const closeRef = useRef(onClose);
- closeRef.current = onClose;
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => e.key === 'Escape' && closeRef.current();
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, []);
+const Dialog: React.FC<{
+ title: string;
+ subtitle?: string;
+ labelId: string;
+ onClose: () => void;
+ children: React.ReactNode;
+ wide?: boolean;
+ /** Changes Escape would lose: it does nothing while there are some. */
+ unsaved?: boolean;
+}> = ({ title, subtitle, labelId, onClose, children, wide, unsaved }) => {
+ const rootRef = useRef<HTMLDivElement>(null);
+ useEscapeLayer(rootRef, true, onClose, { modal: true, unsaved });
return (
<div className="kw-dialog kw-dialog-bottom fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-end sm:items-center justify-center sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div
+ ref={rootRef}
+ tabIndex={-1}
role="dialog"
aria-modal="true"
aria-labelledby={labelId}
- className={`kw-dialog-panel bg-zinc-900 border border-zinc-800 rounded-t-2xl sm:rounded-2xl w-full ${wide ? 'sm:max-w-xl' : 'sm:max-w-md'} max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5`}
+ className={`kw-dialog-panel outline-none bg-zinc-900 border border-zinc-800 rounded-t-2xl sm:rounded-2xl w-full ${wide ? 'sm:max-w-xl' : 'sm:max-w-md'} max-h-[92vh] overflow-y-auto p-4 sm:p-6 text-zinc-100 shadow-2xl space-y-5`}
>
<div className="flex items-start justify-between gap-3">
<div>
@@ -275,7 +275,7 @@ export const NewSpaceModal: React.FC<NewSpaceProps> = ({ spaces, onClose, onCrea
const preview = { id: 'preview', icon, color };
return (
- <Dialog title="New space" subtitle="Its own bots, teams, accounts and chats. Nothing is shared with your other spaces." labelId="new-space-title" onClose={onClose}>
+ <Dialog title="New space" subtitle="Its own bots, teams, accounts and chats. Nothing is shared with your other spaces." labelId="new-space-title" onClose={onClose} unsaved={!!name.trim()}>
<form onSubmit={submit} className="space-y-4" noValidate>
<div className="flex items-center gap-3">
<SpaceTile space={preview} size={48} />
diff --git a/frontend/src/escape.ts b/frontend/src/escape.ts
new file mode 100644
index 00000000..284da817
--- /dev/null
+++ b/frontend/src/escape.ts
@@ -0,0 +1,133 @@
+// Escape works the same in Settings and in the dialogs over it: it closes the top one, never the
+// one under it, and never throws away typed text.
+//
+// An inline editor handles Escape first, with `editorProps`: it closes when nothing in it is
+// unsaved and otherwise does nothing. Either way it calls preventDefault, which every layer
+// around it respects. Editors also mark their root `data-editor`, plus `data-unsaved` while they
+// hold changes, so Escape pressed elsewhere in the layer keeps them too. Text typed into any other
+// field counts as unsaved while focus stays in that field.
+import type React from 'react';
+import { RefObject, useEffect, useRef } from 'react';
+import { trapFocusTarget } from './imports';
+
+const TEXT_TYPES = new Set(['text', 'search', 'url', 'email', 'password', 'tel', 'number']);
+type TextField = HTMLInputElement | HTMLTextAreaElement;
+export const isTextField = (el: EventTarget | null): el is TextField =>
+ el instanceof Element && (el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && TEXT_TYPES.has((el as HTMLInputElement).type)));
+
+/** Props for an inline editor's root (usually its form). `close` is left out for one that stays on screen. */
+export function editorProps(unsaved: boolean, close?: () => void) {
+ return {
+ 'data-editor': '',
+ 'data-unsaved': unsaved ? '' : undefined,
+ onKeyDown: (e: React.KeyboardEvent) => {
+ if (e.key !== 'Escape' || e.defaultPrevented) return;
+ // Clean and nothing of its own to close: the layer around it closes.
+ if (!unsaved && !close) return;
+ e.preventDefault();
+ if (!unsaved) close?.();
+ },
+ };
+}
+
+/** The field focus is in and what it held when focus got there. */
+type Typing = { el: TextField; value: string } | null;
+
+/** Whether Escape would lose something in `root`: a marked editor, or text typed into the focused field. */
+export function keepsText(root: Element, typing: Typing): boolean {
+ if (root.querySelector('[data-unsaved]')) return true;
+ if (!typing) return false;
+ const { el, value } = typing;
+ return el.isConnected && root.contains(el) && !el.closest('[data-editor]') && el.value !== value;
+}
+
+const FOCUSABLE = 'button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';
+const FOLLOWING = 4; // Node.DOCUMENT_POSITION_FOLLOWING
+
+/** A dialog that came after `root` in the page (opened from it, so above it), such as Tools over the bot editor. */
+function dialogAbove(root: Element): boolean {
+ return [...document.querySelectorAll('[role="dialog"], [role="alertdialog"]')].some(
+ (d) => d !== root && !root.contains(d) && !d.contains(root) && !!(root.compareDocumentPosition(d) & FOLLOWING),
+ );
+}
+
+/** Open layers, oldest first. Only the last one acts on Escape. */
+const layers: object[] = [];
+
+export interface LayerOptions {
+ /** Changes held by the layer itself, such as a dialog's own form. */
+ unsaved?: boolean;
+ /** Something that isn't a layer is on top, checked when Escape is pressed. Dialogs default to one opened after them. */
+ covered?: () => boolean;
+ /** A dialog: focus moves in when it opens, Tab stays inside, and focus goes back to the opener when it closes. */
+ modal?: boolean;
+ /** Where focus goes when the opener is gone. */
+ fallback?: () => HTMLElement | null | undefined;
+}
+
+/**
+ * Escape closes this layer when it's on top and nothing in it is unsaved. The decision waits for
+ * every keydown listener, so a dialog or editor inside that handles Escape (preventDefault) wins
+ * whatever order the listeners were added in.
+ */
+export function useEscapeLayer(rootRef: RefObject<HTMLElement>, open: boolean, close: () => void, opts: LayerOptions = {}) {
+ const latest = useRef({ close, opts });
+ latest.current = { close, opts };
+ // Read while rendering: an autoFocus inside would take focus before any effect runs.
+ const opener = useRef<HTMLElement | null>(null);
+ const wasOpen = useRef(false);
+ if (open && !wasOpen.current && typeof document !== 'undefined') opener.current = document.activeElement as HTMLElement | null;
+ wasOpen.current = open;
+
+ useEffect(() => {
+ if (!open) return;
+ const me = {};
+ layers.push(me);
+ const root = rootRef.current;
+ const modal = !!latest.current.opts.modal;
+ let typing: Typing = null;
+ const track = (el: Element | null) => {
+ if (isTextField(el)) typing = { el, value: el.value };
+ };
+ const onFocus = (e: FocusEvent) => track(e.target as Element);
+ root?.addEventListener('focusin', onFocus);
+ if (root?.contains(document.activeElement)) track(document.activeElement);
+ else if (modal) root?.focus();
+
+ const timers = new Set<number>();
+ const onKey = (e: KeyboardEvent) => {
+ if (layers[layers.length - 1] !== me || !root) return;
+ const { opts: o } = latest.current;
+ if (e.key === 'Tab' && modal && root.contains(document.activeElement)) {
+ const items = [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => el.offsetParent !== null || el === document.activeElement);
+ const next = trapFocusTarget(items.length, items.indexOf(document.activeElement as HTMLElement), e.shiftKey);
+ if (next === null) return;
+ e.preventDefault();
+ items[next].focus();
+ return;
+ }
+ if (e.key !== 'Escape' || (o.covered ? o.covered() : dialogAbove(root))) return;
+ const t = window.setTimeout(() => {
+ timers.delete(t);
+ const { close: done, opts: now } = latest.current;
+ if (e.defaultPrevented || !root.isConnected || now.unsaved || keepsText(root, typing)) return;
+ done();
+ });
+ timers.add(t);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => {
+ layers.splice(layers.indexOf(me), 1);
+ root?.removeEventListener('focusin', onFocus);
+ window.removeEventListener('keydown', onKey);
+ timers.forEach((t) => window.clearTimeout(t));
+ if (!modal) return;
+ // Only when focus was lost with the dialog: a choice that moved it on (a link) keeps it.
+ const a = document.activeElement;
+ if (a && a !== document.body && a.isConnected) return;
+ const o = opener.current;
+ const back = o && o !== document.body && o.isConnected && !o.closest('[inert]') ? o : latest.current.opts.fallback?.();
+ back?.focus();
+ };
+ }, [open]);
+}
diff --git a/frontend/tests/afterLaunch.test.mjs b/frontend/tests/afterLaunch.test.mjs
new file mode 100644
index 00000000..73afbac4
--- /dev/null
+++ b/frontend/tests/afterLaunch.test.mjs
@@ -0,0 +1,336 @@
+// Rigel's minor findings from the 0.6.4 QA, fixed after the launch: Escape never throws away typed
+// text in Settings, Escape closes the bot editor and Manage team (focus goes back to what opened
+// them), the Manage team roster works from the keyboard, and the checkpoint list reloads after a
+// restore so "Undo this restore" finds its checkpoint.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+class FakeEvents {
+ addEventListener() {}
+ removeEventListener() {}
+ close() {}
+}
+g.EventSource = g.window.EventSource = FakeEvents;
+
+const bot = (id, name, title = 'Role') => ({ id, name, title, persona_prompt: '', avatar_sprite: 'mouse', driver_type: 'claude', preferred_model: '' });
+const kwants = [{ ...bot('k1', 'Ada', 'Tech lead'), covers: ['invoices'], avoids: [] }, bot('k2', 'Lin', 'Backend'), bot('k3', 'Rigel', 'QA')];
+const team = { id: 't1', name: 'Ship', icon: '🚢', lead_kwant_id: 'k1', member_kwants: ['k1', 'k2'] };
+const routes = {
+ '/api/kwants': kwants,
+ '/api/channels': [{ id: 'ch1', name: 'general', kwant_ids: ['k1', 'k2'], created_at: '' }],
+ '/api/teams': [team],
+ '/api/engines': [{ id: 'claude', kind: 'cli', enabled: true, status: 'ready', ready: true }],
+ '/api/automation-discovery': { setting: 'off', daily_cap: 3, blocked_by: [], last_scan_at: null, suggestions: [], stats: {} },
+};
+const json = (b) => new Response(JSON.stringify(b), { status: 200, headers: { 'Content-Type': 'application/json' } });
+g.fetch = g.window.fetch = async (url, init) => {
+ const path = String(url).split('?')[0];
+ return json(path in routes ? routes[path] : init?.method === 'PUT' ? {} : []);
+};
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { SpaceApp } from './src/App';
+ export { ManageTeamModal } from './src/components/ManageTeamModal';
+ export { RestoreSection } from './src/components/MissionBoardView';
+`);
+const { React } = m;
+const noop = () => {};
+const settle = async () => {
+ for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+/** Presses a key on whatever has focus; true when something took it over (preventDefault). */
+const key = async (k) => {
+ const e = new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true });
+ (document.activeElement ?? document.body).dispatchEvent(e);
+ await settle();
+ return e.defaultPrevented;
+};
+/** Types into a controlled field the way React sees it. */
+const type = async (el, text) => {
+ el.focus();
+ const proto = el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, text);
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+};
+/** Identity check on the focused element (assert.equal would diff React's internals on failure). */
+const focused = (el, msg) => assert.ok(el && document.activeElement === el, `${msg}: focus is on ${describe(document.activeElement)}`);
+const describe = (el) => (el ? `<${el.tagName.toLowerCase()}> "${el.getAttribute('aria-label') ?? el.textContent.trim().slice(0, 30)}"` : 'nothing');
+
+const space = { id: 'spc_default', name: 'Default', icon: '💼', color: '#f59e0b', sort: 0, is_default: true, archived_at: null,
+ created_at: '', general_channel_id: 'ch1', counts: { bots: 3, ready_accounts: 1, unread: 0 } };
+
+// Whatever a failed test left mounted is unmounted too, or its timers would keep the run going.
+const mounted = new Set();
+afterEach(() => {
+ for (const unmount of mounted) unmount();
+ document.body.replaceChildren();
+});
+const mount = async (C, props) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(React.createElement(C, props));
+ await settle();
+ const unmount = () => {
+ if (!mounted.delete(unmount)) return;
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(unmount);
+ return { host, unmount };
+};
+const mountSpace = (over = {}) => mount(m.SpaceApp, {
+ space, spaces: [space], initialTarget: null, onSwitchSpace: noop, onCreateSpace: noop, onOpenArchived: noop,
+ onSpacesChanged: noop, onSpaceArchived: noop, onChatChange: noop, ...over,
+});
+const q = (sel) => document.querySelector(sel);
+const button = (label) => [...document.querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === label || b.textContent.trim() === label);
+const settingsOpen = () => !!q('[data-space-settings]');
+const settingsAt = (tab) => mountSpace({ initialView: { kind: 'settings', scope: 'space', tab } });
+const botEditor = () => q('[role="dialog"][aria-labelledby="agent-modal-title"]');
+const teamDialog = () => q('[role="dialog"][aria-labelledby="manage-team-title"]');
+
+// ---------------------------------------------------------------------------
+// 1. Escape in Settings never throws away typed text
+
+test('after launch 1: Escape in a New routine form with a draft keeps the draft and Settings, wherever focus is in the form', async () => {
+ const v = await settingsAt('routines');
+ const newBtn = q('[data-routine-new]');
+ assert.ok(newBtn, 'Settings › Routines has New routine');
+ newBtn.focus();
+ await click(newBtn);
+ const form = q('form[aria-label="New routine"]');
+ const text = form.querySelector('textarea');
+ await type(text, 'Read the support inbox and list what needs me');
+
+ assert.equal(await key('Escape'), true, 'the form takes Escape');
+ assert.ok(settingsOpen(), 'Settings stays open');
+ assert.ok(form.isConnected, 'the form stays open');
+ assert.equal(text.value, 'Read the support inbox and list what needs me', 'with the draft');
+
+ // Focus on a button in the form, not the field: still kept.
+ button('Cancel').focus();
+ await key('Escape');
+ assert.ok(settingsOpen() && form.isConnected && text.value.startsWith('Read the support'), 'kept from anywhere in the form');
+
+ // Cancel throws it away on purpose, and focus goes back to New routine.
+ await click(button('Cancel'));
+ assert.ok(!q('form[aria-label="New routine"]'));
+ focused(q('[data-routine-new]'), 'after Cancel');
+ v.unmount();
+});
+
+test('after launch 1: Escape closes an untouched routine form first, then Settings (focus as in D1)', async () => {
+ const v = await settingsAt('routines');
+ await click(q('[data-routine-new]'));
+ assert.ok(q('form[aria-label="New routine"]'));
+ await key('Escape');
+ assert.ok(!q('form[aria-label="New routine"]'), 'the untouched form closes');
+ assert.ok(settingsOpen(), 'Settings is still open');
+ focused(q('[data-routine-new]'), 'focus is back on New routine');
+ await key('Escape');
+ assert.equal(settingsOpen(), false, 'the next Escape closes Settings');
+ focused(q('[data-composer]'), 'and focus lands on the composer');
+ v.unmount();
+});
+
+test('after launch 1: the space rename keeps a changed name on Escape; Settings closes once it matches again', async () => {
+ const v = await settingsAt('general');
+ const nameField = q('[data-space-settings] form input[type="text"], [data-space-settings] form input:not([type])');
+ assert.ok(nameField, 'the space name field');
+ await type(nameField, 'Renamed');
+ await key('Escape');
+ assert.ok(settingsOpen(), 'a changed name keeps Settings open');
+ assert.equal(nameField.value, 'Renamed');
+ await type(nameField, 'Default');
+ await key('Escape');
+ assert.equal(settingsOpen(), false, 'unchanged: Escape closes Settings');
+ v.unmount();
+});
+
+// ---------------------------------------------------------------------------
+// 2. Escape closes the bot editor and Manage team; focus goes back to the opener
+
+test('after launch 2: over Settings, Escape closes a clean bot editor only, and focus goes back to its Edit button', async () => {
+ const v = await settingsAt('bots');
+ const edit = button('Edit Ada');
+ edit.focus();
+ await click(edit);
+ assert.ok(botEditor(), 'the bot editor is open');
+ assert.ok(botEditor().contains(document.activeElement), 'focus moved into it');
+
+ await key('Escape');
+ assert.ok(!botEditor(), 'Escape closes the editor');
+ assert.ok(settingsOpen(), 'and only the editor: Settings under it stays');
+ focused(edit, 'focus is back on Edit Ada');
+
+ // With a changed name it does nothing (there's no Discard dialog in the app).
+ await click(edit);
+ const name = q('#agent-name');
+ await type(name, 'Ada2');
+ await key('Escape');
+ assert.ok(botEditor(), 'a changed bot stays open');
+ assert.equal(q('#agent-name').value, 'Ada2');
+ assert.ok(settingsOpen());
+ await type(q('#agent-name'), 'Ada');
+ await key('Escape');
+ assert.ok(!botEditor(), 'changed back: Escape closes it again');
+ focused(edit, 'focus');
+ v.unmount();
+});
+
+test('after launch 2: a changed Good for list keeps the bot editor open on Escape', async () => {
+ const v = await settingsAt('bots');
+ const edit = button('Edit Ada');
+ await click(edit);
+ assert.ok(button('Remove invoices'), 'Ada\'s Good for list is in the editor');
+ await key('Escape');
+ assert.ok(!botEditor(), 'untouched, Escape closes it');
+ await click(edit);
+ await click(button('Remove invoices'));
+ await key('Escape');
+ assert.ok(botEditor(), 'a removed Good for phrase keeps it open');
+ assert.ok(settingsOpen());
+ v.unmount();
+});
+
+test('after launch 2: over Settings, Escape closes a clean Manage team only and focus goes back to Manage; a change keeps it open', async () => {
+ const v = await settingsAt('teams');
+ const manage = button('Manage @Ship');
+ manage.focus();
+ await click(manage);
+ assert.ok(teamDialog(), 'Manage team is open');
+ assert.ok(teamDialog().contains(document.activeElement), 'focus moved into it');
+ await key('Escape');
+ assert.ok(!teamDialog(), 'Escape closes it');
+ assert.ok(settingsOpen(), 'Settings stays');
+ focused(manage, 'focus is back on Manage @Ship');
+
+ await click(manage);
+ await click(q('[data-roster-row="k2"]'));
+ assert.ok(q('[data-team-removals]'), 'Lin is unticked');
+ await key('Escape');
+ assert.ok(teamDialog(), 'an unsaved roster change keeps it open');
+ assert.ok(q('[data-team-removals]'), 'with the change');
+ await click(button('Close'));
+ focused(manage, 'the ✕ gives focus back too');
+ v.unmount();
+});
+
+test('after launch 2: from the sidebar, Escape closes Manage team and focus goes back to the team gear', async () => {
+ const v = await mountSpace();
+ const gear = button('Team settings for @Ship');
+ gear.focus();
+ await click(gear);
+ assert.ok(teamDialog());
+ await key('Escape');
+ assert.ok(!teamDialog());
+ focused(gear, 'focus is back on the gear');
+ v.unmount();
+});
+
+test('after launch 2: Tab stays inside Manage team', async () => {
+ const v = await mount(m.ManageTeamModal, { isOpen: true, team, kwants, onClose: noop, onUpdateTeam: async () => {}, onDeleteTeam: async () => {} });
+ const d = teamDialog();
+ const items = [...d.querySelectorAll('button:not([disabled]), input:not([disabled]), textarea, select')];
+ items.at(-1).focus();
+ assert.equal(await key('Tab'), true, 'Tab past the last control is caught');
+ assert.ok(d.contains(document.activeElement), 'and focus wraps inside the dialog');
+ v.unmount();
+});
+
+// ---------------------------------------------------------------------------
+// 3. The Manage team roster works from the keyboard
+
+test('after launch 3: each roster row is a toggle button (Tab reaches it, Space and Enter press it), with its state and a visible focus ring', async () => {
+ const saved = [];
+ const v = await mount(m.ManageTeamModal, { isOpen: true, team, kwants, onClose: noop, onUpdateTeam: async (id, d) => saved.push(d.member_kwants), onDeleteTeam: async () => {} });
+ const rows = [...document.querySelectorAll('[data-roster-row]')];
+ assert.equal(rows.length, 3);
+ for (const r of rows) {
+ // A real <button>: browsers put it in the Tab order and press it with Space and Enter.
+ assert.equal(r.tagName, 'BUTTON', 'a button, not a clickable div');
+ assert.equal(r.getAttribute('type'), 'button', 'that never submits the form');
+ assert.notEqual(r.tabIndex, -1, 'in the Tab order');
+ assert.match(r.className, /focus-visible:outline/, 'with a focus ring');
+ }
+ const lin = q('[data-roster-row="k2"]');
+ const rigel = q('[data-roster-row="k3"]');
+ assert.equal(lin.getAttribute('aria-pressed'), 'true', 'a member is pressed');
+ assert.equal(rigel.getAttribute('aria-pressed'), 'false');
+ assert.match(teamDialog().textContent, /Select a bot to add or remove it/);
+ assert.doesNotMatch(teamDialog().textContent, /Click to add/, 'the hint doesn\'t assume a mouse');
+ assert.ok(q('[role="group"][aria-labelledby="team-roster-label"]'), 'the rows are a labelled group');
+
+ await click(lin);
+ assert.equal(lin.getAttribute('aria-pressed'), 'false');
+ assert.match(q('[data-team-removals]').textContent, /Saving removes Lin from @Ship/, 'the removals line updates');
+ await click(rigel);
+ assert.equal(rigel.getAttribute('aria-pressed'), 'true');
+ await click(lin);
+ assert.ok(!q('[data-team-removals]'));
+ await click(rigel);
+
+ // The lead rules are unchanged: unticking the lead hands Lead to the next member, and the last
+ // member can't be unticked.
+ await click(q('[data-roster-row="k1"]'));
+ assert.doesNotMatch(q('[data-roster-row="k1"]').textContent, /Lead/);
+ assert.match(q('[data-roster-row="k2"]').textContent, /Lead/);
+ await click(lin);
+ assert.equal(lin.getAttribute('aria-pressed'), 'true', 'the last member stays');
+ assert.match(teamDialog().textContent, /A team needs at least one bot\./);
+ assert.deepEqual(saved, [], 'toggling saves nothing');
+ v.unmount();
+});
+
+// ---------------------------------------------------------------------------
+// 4. The checkpoint list reloads after a restore
+
+test('after launch 4: after a restore the checkpoint list loads again, with the before-restore checkpoint, and Undo finds it', async () => {
+ const cp = (id, kind) => ({ id, kind, attempt: 1, created_at: '2026-11-01T10:00:00Z', files: 2, effects_after: { external: [] }, restorable: true, error: null });
+ let cps = [cp('cp1', 'before_run')];
+ const calls = [];
+ const api = {
+ checkpoints: async (id) => {
+ calls.push(['list', id]);
+ return cps;
+ },
+ restorePreview: async (id, c) => {
+ calls.push(['preview', c]);
+ return { checkpoint_id: c, preview_sha256: `sha-${c}`, changes: [{ path: 'a.txt', action: 'overwrite' }], conflicts: [], skipped: [], external_not_undone: [], not_undone_note: '', effects_known: true, task_state_after: 'ready', refused: null };
+ },
+ restore: async (id, c) => {
+ calls.push(['restore', c]);
+ cps = [...cps, cp('cp_before', 'before_restore')];
+ return { before_restore_checkpoint_id: 'cp_before', restored: 1, removed: 0, task: { id, state: 'ready' } };
+ },
+ };
+ const task = { id: 'tk1', state: 'failed', checkpoint_count: 1 };
+ const v = await mount(m.RestoreSection, { task, api, now: Date.parse('2026-11-01T12:00:00Z'), titleOf: () => undefined });
+ await click(q('[data-restore-open]'));
+ await click(q('[data-checkpoint="cp1"]'));
+ await click(q('[data-restore]'));
+ assert.deepEqual(calls.filter((c) => c[0] === 'list').length, 2, 'the list is fetched again after the restore');
+ assert.doesNotMatch(v.host.textContent, /Loading checkpoints/, 'and doesn\'t hang on Loading');
+ assert.ok(q('[data-checkpoint="cp_before"]'), 'it shows the checkpoint taken before the restore');
+
+ await click(q('[data-restore-undo]'));
+ assert.deepEqual(calls.at(-1), ['preview', 'cp_before'], 'Undo this restore previews that checkpoint');
+ assert.ok(q('[data-restore-preview]'), 'and shows what it would put back');
+ v.unmount();
+});
diff --git a/frontend/tests/polish063.test.mjs b/frontend/tests/polish063.test.mjs
index f1d2122f..ad896e6b 100644
--- a/frontend/tests/polish063.test.mjs
+++ b/frontend/tests/polish063.test.mjs
@@ -191,7 +191,7 @@ test('4: Manage team names who Save will remove before it happens', async () =>
const saved = [];
const v = await mount(m.ManageTeamModal, { isOpen: true, team, kwants, onClose: noop, onUpdateTeam: async (id, d) => saved.push(d.member_kwants), onDeleteTeam: async () => {} });
assert.equal(document.querySelector('[data-team-removals]'), null);
- const row = [...document.querySelectorAll('div')].find((d) => d.className.includes('cursor-pointer') && d.textContent.includes('Customer-Success-Manager-Extraordinaire'));
+ const row = [...document.querySelectorAll('[data-roster-row]')].find((d) => d.textContent.includes('Customer-Success-Manager-Extraordinaire'));
await click(row);
assert.deepEqual(saved, [], 'unticking saves nothing');
assert.match(document.querySelector('[data-team-removals]').textContent, /Saving removes Customer-Success-Manager-Extraordinaire from @Ship\./);