Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Settings: the chat under it is inert, focus goes in and comes back; remove confirm keeps focus
Pixel (kwant bot)b5df86239c15
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 3d32b0a2..f9a3e6ac 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -4,6 +4,7 @@ import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebarimport { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';import { InboxPage } from './components/InboxPage';import { InboxTab, SettingsScope, SpaceView, viewSegment } from './nav';+import { useSettingsCover } from './settingsFocus';import { FirstRunWelcome } from './components/FirstRunWelcome';import { SpaceTile } from './components/Spaces';import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } from './components/ChatView';@@ -302,6 +303,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const engines = useEngines(true);const canRun = canRunNow(engines.engines);const offerClaude = canRun === false && claudeNeedsSignIn(engines.engines);+ // The sidebar and chat under Settings: inert while it's open (the space rail stays usable).+ const contentRef = useRef<HTMLDivElement>(null);+ useSettingsCover(!!spaceSettingsTab, contentRef);const closeSpaceSettings = () => {setSpaceSettingsTab(null);setSettingsClosedCount((n) => n + 1);@@ -3046,67 +3050,69 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({{/* The open space's colour, so it's clear where a message goes */}<div className="h-[3px] shrink-0 opacity-60" style={{ background: spaceColor(space) }} aria-hidden="true" />- {isPhone ? (- <>- {showPhoneList || needsSetup ? (- <div className="flex-1 min-h-0 flex flex-col">- {needsSetup ? (- <>- {sidebar('chats')}- {setupChecklist}- </>- ) : (- sidebar(phoneTab === 'bots' ? 'bots' : 'chats')- )}- </div>- ) : (- <div className="flex-1 min-h-0 flex">{mainPane}</div>- )}- {(showPhoneList || needsSetup) && (- <nav aria-label={`${space.name} sections`} className="shrink-0 grid grid-cols-4 border-t border-zinc-800 bg-zinc-900/95 pb-[env(safe-area-inset-bottom)]">- {phoneTabs.map((t) => {- const active = t.id === phoneTab;- return (- <button- key={t.id}- type="button"- aria-current={active ? 'page' : undefined}- onClick={() => {- playSfx('click');- if (t.id === 'inbox') {- showPage('inbox');- return;- }- if (t.id === 'space') {- // Nothing can run yet: the fix is in Accounts, so start there- openSpaceSettings(canRun === false ? 'accounts' : 'general');- return;- }- setPhoneTab(t.id);- }}- className={`relative flex flex-col items-center gap-0.5 py-2 text-[11px] font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500 ${- active ? 'text-sky-300' : 'text-zinc-400 hover:text-zinc-200'- }`}- >- {t.icon}- {t.label}- {!!t.badge && (- <span className="absolute top-1 left-1/2 ml-2 min-w-[16px] px-1 rounded-full bg-amber-500 text-zinc-950 text-[9px] font-semibold text-center">- {badgeText(t.badge)}- </span>- )}- </button>- );- })}- </nav>- )}- </>- ) : (- <div className="flex-1 min-h-0 flex overflow-hidden">- {sidebar('all')}- {mainPane}- </div>- )}+ <div ref={contentRef} className={`flex-1 min-h-0 flex ${isPhone ? 'flex-col' : 'overflow-hidden'}`}>+ {isPhone ? (+ <>+ {showPhoneList || needsSetup ? (+ <div className="flex-1 min-h-0 flex flex-col">+ {needsSetup ? (+ <>+ {sidebar('chats')}+ {setupChecklist}+ </>+ ) : (+ sidebar(phoneTab === 'bots' ? 'bots' : 'chats')+ )}+ </div>+ ) : (+ <div className="flex-1 min-h-0 flex">{mainPane}</div>+ )}+ {(showPhoneList || needsSetup) && (+ <nav aria-label={`${space.name} sections`} className="shrink-0 grid grid-cols-4 border-t border-zinc-800 bg-zinc-900/95 pb-[env(safe-area-inset-bottom)]">+ {phoneTabs.map((t) => {+ const active = t.id === phoneTab;+ return (+ <button+ key={t.id}+ type="button"+ aria-current={active ? 'page' : undefined}+ onClick={() => {+ playSfx('click');+ if (t.id === 'inbox') {+ showPage('inbox');+ return;+ }+ if (t.id === 'space') {+ // Nothing can run yet: the fix is in Accounts, so start there+ openSpaceSettings(canRun === false ? 'accounts' : 'general');+ return;+ }+ setPhoneTab(t.id);+ }}+ className={`relative flex flex-col items-center gap-0.5 py-2 text-[11px] font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500 ${+ active ? 'text-sky-300' : 'text-zinc-400 hover:text-zinc-200'+ }`}+ >+ {t.icon}+ {t.label}+ {!!t.badge && (+ <span className="absolute top-1 left-1/2 ml-2 min-w-[16px] px-1 rounded-full bg-amber-500 text-zinc-950 text-[9px] font-semibold text-center">+ {badgeText(t.badge)}+ </span>+ )}+ </button>+ );+ })}+ </nav>+ )}+ </>+ ) : (+ <>+ {sidebar('all')}+ {mainPane}+ </>+ )}+ </div>{/* New bot */}<Suspense fallback={null}>diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 917b2c01..bdc4ae0f 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1483,6 +1483,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<textarearef={textareaRef}+ data-composerrows={1}value={inputVal}onChange={(e) => {diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 38f823a9..0fd9e190 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -15,6 +15,7 @@ import { approvalsOff, spaceOffLine } from '../approvalMode';import { teamChannelOf } from '../teamChannel';import { layaRoutes } from '../channels';import { InstallAppButton } from './InstallAppButton';+import { trapFocusTarget } from '../imports';export interface Kwant {id: string;@@ -273,6 +274,21 @@ export const Sidebar: React.FC<SidebarProps> = ({const [switcherOpen, setSwitcherOpen] = useState(false);/** Phones: the member whose actions sheet is open, and whether "Remove" is waiting for a confirm. */const [memberMenu, setMemberMenu] = useState<{ team: Team; kwant: Kwant; confirmRemove?: boolean } | null>(null);+ // Cancel, Escape or Remove: focus goes back to the member's ✕ (or ⋯ on phones), or to the bot's+ // row when it has left the team.+ const asideRef = React.useRef<HTMLElement>(null);+ const memberReturn = React.useRef<{ team: string; kwant: string } | null>(null);+ const closeMemberMenu = () => {+ if (memberMenu) memberReturn.current = { team: memberMenu.team.id, kwant: memberMenu.kwant.id };+ setMemberMenu(null);+ };+ React.useLayoutEffect(() => {+ const r = memberReturn.current;+ if (memberMenu || !r) return;+ memberReturn.current = null;+ const box = asideRef.current;+ (box?.querySelector<HTMLElement>(`[data-member-opener="${r.team}:${r.kwant}"]`) ?? box?.querySelector<HTMLElement>(`[data-bot-row="${r.kwant}"]`))?.focus();+ }, [memberMenu]);const closeSwitcher = useCallback(() => setSwitcherOpen(false), []);const showChats = section !== 'bots';const showBots = section !== 'chats';@@ -340,7 +356,8 @@ export const Sidebar: React.FC<SidebarProps> = ({role="button"tabIndex={0}onClick={() => onSelectKwant(k)}- onKeyDown={(e) => e.key === 'Enter' && onSelectKwant(k)}+ // Only the row's own Enter: Enter on its ✕ or Edit is for that button, not for opening the chat.+ onKeyDown={(e) => e.key === 'Enter' && e.target === e.currentTarget && onSelectKwant(k)}data-bot-row={k.id}className={`group/fleet relative w-full flex items-center gap-2.5 px-2 py-1.5 rounded-xl text-left cursor-pointer transition-all ${active ? 'bg-zinc-800/90 text-zinc-100 shadow-sm border border-zinc-700/60' : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/40 border border-transparent'@@ -393,6 +410,7 @@ export const Sidebar: React.FC<SidebarProps> = ({<buttontype="button"data-remove-member={k.id}+ data-member-opener={`${team!.id}:${k.id}`}onClick={(e) => {e.stopPropagation();// Asks first, like the phone sheet: a stray click can't take a bot out of its team.@@ -425,6 +443,7 @@ export const Sidebar: React.FC<SidebarProps> = ({playSfx('click');setMemberMenu({ team, kwant: k });}}+ data-member-opener={`${team.id}:${k.id}`}aria-haspopup="dialog"aria-label={`More for ${k.name}`}className="-mr-1 shrink-0 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 active:bg-zinc-800 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"@@ -460,7 +479,7 @@ export const Sidebar: React.FC<SidebarProps> = ({role="button"tabIndex={0}onClick={() => onSelectTeam(t)}- onKeyDown={(e) => e.key === 'Enter' && onSelectTeam(t)}+ onKeyDown={(e) => e.key === 'Enter' && e.target === e.currentTarget && onSelectTeam(t)}data-team-row={t.id}title={`Open the @${t.name} team chat`}className={`w-full flex items-center justify-between px-1.5 py-1.5 rounded-lg text-xs font-medium transition-all text-left group cursor-pointer ${@@ -589,6 +608,7 @@ export const Sidebar: React.FC<SidebarProps> = ({return (<aside+ ref={asideRef}aria-label={`${space.name} chats and kwant bots`}className={`${phone ? 'w-full flex-1 min-h-0' : 'w-64 h-full border-r border-zinc-800/80'} bg-zinc-900/40 flex flex-col select-none flex-shrink-0`}>@@ -832,7 +852,7 @@ export const Sidebar: React.FC<SidebarProps> = ({kwant={memberMenu.kwant}isLead={memberMenu.kwant.id === memberMenu.team.lead_kwant_id}confirmRemove={!!memberMenu.confirmRemove}- onClose={() => setMemberMenu(null)}+ onClose={closeMemberMenu}onChat={() => {setMemberMenu(null);onSelectKwant(memberMenu.kwant);@@ -849,7 +869,7 @@ export const Sidebar: React.FC<SidebarProps> = ({onUpdateTeamMembers &&(() => {const { team, kwant } = memberMenu;- setMemberMenu(null);+ closeMemberMenu();onUpdateTeamMembers(team, memberIdsOf(team).filter((id) => id !== kwant.id));})}@@ -882,6 +902,16 @@ const MemberSheet: React.FC<{useEffect(() => {ref.current?.querySelector<HTMLElement>('button')?.focus();}, [confirmRemove]);+ // Tab stays inside the sheet.+ const onKeyDown = (e: React.KeyboardEvent) => {+ if (e.key !== 'Tab' || !ref.current) return;+ const items = Array.from(ref.current.querySelectorAll<HTMLElement>('button:not([disabled])'));+ const to = trapFocusTarget(items.length, items.indexOf(document.activeElement as HTMLElement), e.shiftKey);+ if (to !== null) {+ e.preventDefault();+ items[to]?.focus();+ }+ };const item = 'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left text-sm transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';const titleId = `member-sheet-${kwant.id}`;return (@@ -891,6 +921,7 @@ const MemberSheet: React.FC<{role="dialog"aria-modal="true"aria-labelledby={titleId}+ onKeyDown={onKeyDown}className="kw-sheet w-full max-h-[80vh] overflow-y-auto rounded-t-2xl bg-zinc-900 border-t border-zinc-800 p-3 shadow-2xl md:max-w-sm md:rounded-2xl md:border"><div className="mx-auto mb-2 h-1 w-10 rounded-full bg-zinc-700 md:hidden" aria-hidden="true" />diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex b32afef0..054dff28 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -123,11 +123,20 @@ export const SpaceSettings: React.FC<Props> = (p) => {window.addEventListener('keydown', onKey);return () => window.removeEventListener('keydown', onKey);}, []);+ // 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;+ rootRef.current?.querySelector<HTMLElement>('#space-settings-title')?.focus();+ }, []);return (// A full-screen dialog on phones. On desktop it fills the space's area beside the space rail,// which stays clickable: picking another space keeps Settings open there.<div+ ref={rootRef}role={p.isPhone ? 'dialog' : 'region'}aria-modal={p.isPhone ? true : undefined}aria-labelledby="space-settings-title"@@ -140,7 +149,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {<button type="button" onClick={onClose} aria-label="Back to chats" className="p-1.5 -ml-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800"><ArrowLeft size={17} /></button>- <h2 id="space-settings-title" className="text-sm font-semibold truncate">Settings</h2>+ <h2 id="space-settings-title" tabIndex={-1} className="text-sm font-semibold truncate focus:outline-none">Settings</h2></div>{/* Which settings: this space's, or the ones every space shares */}<div role="tablist" aria-label="Settings scope" className="mx-3 md:mx-2 mb-3 grid grid-cols-2 gap-1 rounded-lg bg-zinc-900 border border-zinc-800 p-0.5">diff --git a/frontend/src/components/Spaces.tsx b/frontend/src/components/Spaces.tsxindex 95983987..ee9ff96d 100644--- a/frontend/src/components/Spaces.tsx+++ b/frontend/src/components/Spaces.tsx@@ -54,6 +54,7 @@ export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, on<buttontype="button"onClick={() => onSwitch(s.id)}+ data-rail-space={s.id}aria-current={active ? 'true' : undefined}aria-label={`${s.name}${unread ? `, ${unread} unread` : ''}`}title={`${s.name}${i < 9 ? ` (Ctrl/⌘ ${i + 1})` : ''}`}@@ -87,6 +88,7 @@ export const SpaceRail: React.FC<RailProps> = ({ spaces, currentId, onSwitch, on<buttontype="button"onClick={onOpenAppSettings}+ data-settings-openeraria-label="Settings (all spaces)"title="Settings (all spaces)"className="w-10 h-10 rounded-xl text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 flex items-center justify-center transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"diff --git a/frontend/src/settingsFocus.ts b/frontend/src/settingsFocus.tsnew file mode 100644index 00000000..88d399d0--- /dev/null+++ b/frontend/src/settingsFocus.ts@@ -0,0 +1,38 @@+// Settings covers the space's sidebar and chat but not the space rail. While it's open, everything+// under it is inert, so Tab, clicks and typing can't reach the hidden composer; when it closes,+// focus goes back to what opened it, or to the composer when that's gone.+import { RefObject, useLayoutEffect, useRef } from 'react';++/** Outside the covered area, but still a way into Settings that focus can go back to. */+export const SETTINGS_OPENER = 'data-settings-opener';++/** Where focus lands after Settings closes when what opened it is gone (a link, a space switch). */+export function focusAfterSettings(opener: HTMLElement | null, content: HTMLElement | null): HTMLElement | null {+ if (opener?.isConnected && !opener.closest('[inert]')) return opener;+ return content?.querySelector<HTMLElement>('[data-composer]') ?? content?.querySelector<HTMLElement>('[data-space-settings-open]') ?? null;+}++/**+ * Makes `content` inert while Settings is open, and puts focus back when it closes. Focus is only+ * moved if it was lost with Settings (Close, Back to chats, Escape); focus elsewhere, such as on+ * the space rail, stays where it is.+ */+export function useSettingsCover(open: boolean, content: RefObject<HTMLElement>) {+ const opener = useRef<HTMLElement | null>(null);+ const wasOpen = useRef(false);+ // A layout effect: it runs before Settings moves focus in, so what opened it is still focused.+ useLayoutEffect(() => {+ const el = content.current;+ if (open && !wasOpen.current) {+ const a = document.activeElement as HTMLElement | null;+ opener.current = a && a !== document.body && (el?.contains(a) || a.hasAttribute(SETTINGS_OPENER)) ? a : null;+ }+ el?.toggleAttribute('inert', open);+ if (!open && wasOpen.current) {+ const lost = !document.activeElement || document.activeElement === document.body;+ if (lost) focusAfterSettings(opener.current, el)?.focus();+ opener.current = null;+ }+ wasOpen.current = open;+ }, [open]);+}diff --git a/frontend/tests/settingsFocus.test.mjs b/frontend/tests/settingsFocus.test.mjsnew file mode 100644index 00000000..066f1323--- /dev/null+++ b/frontend/tests/settingsFocus.test.mjs@@ -0,0 +1,267 @@+// Rigel's D1 (0.6.4 QA): keyboard focus reached the chat behind desktop Settings, so hidden text+// could be typed and sent. While Settings is open the sidebar and chat under it are inert, focus+// moves into Settings and comes back when it closes; the remove-member confirm keeps focus too.+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', 'Lead'), bot('k2', 'Lin', 'Backend')];+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 }],+};+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 { Sidebar } from './src/components/Sidebar';+ export { SpaceSettings } from './src/components/SpaceSettings';+`);+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 the app took it over (preventDefault). */+const key = async (k, shiftKey = false) => {+ const e = new KeyboardEvent('keydown', { key: k, shiftKey, bubbles: true, cancelable: true });+ (document.activeElement ?? document.body).dispatchEvent(e);+ await settle();+ return e.defaultPrevented;+};+/** 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: 2, 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 title = () => q('#space-settings-title');++// ---------------------------------------------------------------------------+// Desktop Settings: what's under it is inert, focus goes in and comes back++test('D1: while desktop Settings is open the sidebar and composer under it are inert; after it closes they work again', async () => {+ const v = await mountSpace();+ const composer = q('[data-composer]');+ const sidebar = q('aside');+ assert.ok(composer && sidebar, 'the chat and sidebar are on screen');+ assert.equal(composer.closest('[inert]'), null, 'nothing is inert before Settings opens');++ const gear = q('[data-space-settings-open]');+ gear.focus();+ await click(gear);+ const settings = q('[data-space-settings]');+ assert.equal(settings.getAttribute('role'), 'region', 'desktop Settings is a region beside the rail');+ const cover = composer.closest('[inert]');+ assert.ok(cover, 'the composer is inert: no Tab, click or typing reaches it');+ assert.ok(sidebar.closest('[inert]') === cover, 'so is the sidebar, with its gear');+ assert.ok(q('[data-space] [aria-label^="Message "]').closest('[inert]'), 'the whole message form');+ assert.equal(settings.closest('[inert]'), null, 'Settings itself is not');+ assert.ok(!cover.contains(settings), 'Settings sits outside the inert part');+ assert.equal(q('[data-space]').hasAttribute('inert'), false, 'only the part under Settings: the space rail beside it is not in it');++ await click(button('Back to chats'));+ assert.equal(q('[data-space-settings]'), null);+ assert.equal(document.querySelectorAll('[inert]').length, 0, 'nothing stays inert');+ focused(gear, 'focus is back on the gear that opened it');+ composer.focus();+ focused(composer, 'the composer takes focus again');+ v.unmount();+});++test('D1: opening Settings moves focus to its title; Close, Back to chats and Escape all return it to the gear', async () => {+ const v = await mountSpace();+ for (const close of ['Close settings', 'Back to chats', 'Escape']) {+ const gear = q('[data-space-settings-open]');+ gear.focus();+ await click(gear);+ focused(title(), `focus moved into Settings (${close})`);+ if (close === 'Escape') await key('Escape');+ else await click(button(close));+ assert.equal(q('[data-space-settings]'), null, `${close} closes Settings`);+ focused(gear, `${close}: focus back on the gear`);+ }+ v.unmount();+});++test('D1: Settings opened from a link puts focus in it, and closing lands on the composer', async () => {+ const v = await mountSpace({ initialView: { kind: 'settings', scope: 'space', tab: 'accounts' } });+ assert.ok(q('[data-space-settings]'));+ focused(title(), 'focus starts in Settings, not on the page');+ assert.ok(q('[data-composer]').closest('[inert]'), 'the chat under it is inert from the start');+ await key('Escape');+ assert.equal(q('[data-space-settings]'), null);+ focused(q('[data-composer]'), 'no gear opened it, so focus goes to the composer');+ v.unmount();+});++test('D1: the gear gone while Settings was open (a space switch): focus goes to the composer', async () => {+ const v = await mountSpace();+ const gear = q('[data-space-settings-open]');+ gear.focus();+ await click(gear);+ gear.remove();+ await click(button('Close settings'));+ focused(q('[data-composer]'), 'focus');+ v.unmount();+});++test('D1: switching space from the rail keeps focus on the rail; Ctrl/⌘ 1–9 and the rail gear move it into Settings', async () => {+ const props = {+ space, spaces: [space], scope: 'space', onScope: noop, tab: 'general', onTab: noop, onClose: noop,+ connections: 'C', appSettings: 'A', onOpenArchived: noop, kwants, channels: [], teams: [team],+ onSpaceSaved: noop, onArchived: noop, onNewBot: noop, onEditBot: noop, onOpenSkills: noop, onNewTeam: noop, onManageTeam: noop, onOpenTools: noop,+ };+ const rail = document.createElement('nav');+ rail.innerHTML = '<button data-rail-space="spc_b">B</button><button data-settings-opener>All spaces</button>';+ document.body.appendChild(rail);+ // A rail click: focus is on the space's button, and stays there.+ rail.firstChild.focus();+ let v = await mount(m.SpaceSettings, props);+ focused(rail.firstChild, 'focus');+ v.unmount();+ // Ctrl+2: focus was in the old space's Settings, which is gone.+ document.activeElement.blur();+ v = await mount(m.SpaceSettings, props);+ focused(title(), 'focus');+ v.unmount();+ // The rail's gear opens All spaces: focus moves in.+ rail.lastChild.focus();+ v = await mount(m.SpaceSettings, { ...props, scope: 'app' });+ focused(title(), 'focus');+ v.unmount();+ rail.remove();+});++test('D1: on phones Settings stays a full-screen dialog, with the space under it inert too', async () => {+ const prev = window.matchMedia;+ window.matchMedia = () => ({ matches: true, addEventListener: noop, removeEventListener: noop });+ try {+ const v = await mountSpace({ initialView: { kind: 'settings', scope: 'space', tab: 'general' } });+ const settings = q('[data-space-settings]');+ assert.equal(settings.getAttribute('role'), 'dialog');+ assert.equal(settings.getAttribute('aria-modal'), 'true');+ assert.match(settings.className, /\bfixed inset-0\b/);+ focused(title(), 'focus');+ const cover = q('[inert]');+ assert.ok(cover && !cover.contains(settings) && cover.querySelector('aside, [data-composer]'), 'the list or chat under it is inert');+ await click(button('Back to chats'));+ assert.equal(document.querySelectorAll('[inert]').length, 0);+ v.unmount();+ } finally {+ window.matchMedia = prev;+ }+});++// ---------------------------------------------------------------------------+// The desktop remove-member confirm++test('D1: the remove confirm keeps Tab inside, closes on Escape and gives focus back to the ✕; Enter on the ✕ only opens the confirm', async () => {+ const calls = [];+ const selected = [];+ const v = await mount(m.Sidebar, {+ space, spaces: [space], onSwitchSpace: noop, onCreateSpace: noop, onOpenSpaceSettings: noop, onOpenArchived: noop, onOpenSearch: noop,+ kwants, channels: [], teams: [team], selectedId: '', isChannel: true, onSelectKwant: (k) => selected.push(k.id), onSelectChannel: noop, onSelectTeam: noop,+ onSummonKwant: noop, onCreateTeam: noop, onOpenInbox: noop, onOpenParallel: noop, onOpenMissions: noop, missionBoard: true,+ onEditKwant: noop, onUpdateTeamMembers: (t, ids) => calls.push([t.id, ids]),+ });+ const x = v.host.querySelector('[data-remove-member="k2"]');+ const inDialog = () => !!document.activeElement?.closest('[role="dialog"]');++ // Enter on the ✕ is for the ✕: it doesn't also open Lin's chat behind the confirm (the row's own Enter does).+ x.focus();+ await key('Enter');+ assert.deepEqual(selected, [], 'Enter on the ✕ leaves the row alone');+ const row = v.host.querySelector('[data-bot-row="k2"]');+ row.focus();+ await key('Enter');+ assert.deepEqual(selected, ['k2'], 'Enter on the row opens its chat');++ x.focus();+ await click(x);+ focused(button('Cancel'), 'focus starts on Cancel');+ // Between the two buttons the browser moves focus; the sheet only steps in at either end.+ assert.equal(await key('Tab', true), true, 'Shift+Tab on Cancel is caught');+ focused(button('Remove'), 'Shift+Tab past Cancel wraps to Remove, not out to the page');+ assert.equal(await key('Tab'), true, 'Tab on Remove is caught');+ focused(button('Cancel'), 'Tab past Remove wraps to Cancel');+ assert.equal(await key('Tab'), false, 'Tab on Cancel is left to the browser, which goes on to Remove');+ assert.ok(inDialog());++ await key('Escape');+ assert.equal(q('[role="dialog"]'), null, 'Escape closes it');+ focused(x, 'focus is back on the ✕');++ await click(x);+ await click(button('Cancel'));+ focused(x, 'Cancel also gives focus back to the ✕');+ assert.deepEqual(calls, [], 'and nothing was removed');+ v.unmount();+});++test('D1: after Remove, focus goes to the bot\'s row, since its ✕ left with the team', async () => {+ const v = await mountSpace();+ const x = q('[data-remove-member="k2"]');+ x.focus();+ await click(x);+ await click(button('Remove'));+ assert.equal(q('[role="dialog"]'), null);+ assert.equal(q('[data-remove-member="k2"]'), null, 'Lin is out of the team');+ focused(q('aside [data-bot-row="k2"]'), 'focus is on Lin\'s row, now outside the team');+ v.unmount();+});