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
Apps & accounts: one settings page with a 3-step Connect sheet (#542)
Oleksandr Ivanchenko9fe1f5098aaa
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 30277539..fdfeb322 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -3,7 +3,7 @@ import { DecidingMap, applyDecideEvent, decisionsApi, hydrateDeciding } from './import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';import { InboxPage } from './components/InboxPage';-import { InboxTab, SettingsScope, SpaceView, viewSegment } from './nav';+import { AppsSection, InboxTab, SettingsScope, SpaceView, viewSegment } from './nav';import { PHONE_QUERY } from './layout';import { useSettingsCover } from './settingsFocus';import { WhatsNewHost } from './components/WhatsNewSheet';@@ -353,7 +353,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const [claudeSignInFocus, setClaudeSignInFocus] = useState(0);// Set by a routine card's Edit or Pause, so Routines opens at that routine.const [routineFocus, setRoutineFocus] = useState<RoutineFocus | null>(null);- const openSpaceSettings = (tab: SpaceSettingsTab = 'general') => {+ // Apps & accounts opens at a section (AI accounts, Advanced); seq re-scrolls on a second ask.+ const [appsSection, setAppsSection] = useState<{ section: AppsSection; seq: number } | null>(() =>+ initialView?.kind === 'settings' && initialView.scope === 'space' && initialView.section ? { section: initialView.section, seq: 1 } : null,+ );+ const openSpaceSettings = (tab: SpaceSettingsTab = 'general', section?: AppsSection) => {+ setAppsSection(section ? { section, seq: Date.now() } : null);setClaudeSignInFocus(0);if (tab !== 'routines') setRoutineFocus(null);setSettingsScope('space');@@ -366,7 +371,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setSpaceSettingsTab((t) => t ?? 'general');playSfx('click');};- const openSettings = () => openSpaceSettings('accounts');+ const openSettings = () => openSpaceSettings('apps', 'accounts');// Settings › All spaces › Usage, at the daily spending stop's fields.const openUsageSettings = () => {setSettingsFocusRow('spend-stop');@@ -377,7 +382,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setSettingsFocusRow('claude-isolation');openAppSettings();};- const openConnections = () => openSpaceSettings('connections');+ const openConnections = () => openSpaceSettings('apps', 'advanced');// 0.9.0 P5: "See the note" in a chat opens Connections on that one note.const [toolNoteFocus, setToolNoteFocus] = useState<string | null>(null);const openToolNote = (noteId: string) => {@@ -386,8 +391,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({};const openClaudeSignIn = () => {setClaudeSignInFocus(Date.now());+ setAppsSection({ section: 'accounts', seq: Date.now() });setSettingsScope('space');- setSpaceSettingsTab('accounts');+ setSpaceSettingsTab('apps');};// This space's engine checks, shared with the sidebar: the setup banner, the "can't answer"// card and the bots' online dots all read whether anything can run.@@ -3747,13 +3753,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({keepAction: true,title: readyAccounts === 1 ? '1 account ready' : `${readyAccounts} accounts ready`,detail: 'Add another Claude, Codex or Grok sign-in, or an API key.',- action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('accounts') },+ action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('apps', 'accounts') },}: {done: false,title: 'Add an account',detail: 'Sign in with Claude, Codex or Grok, add an API key, or use this machine.',- action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('accounts') },+ action: { label: 'Add an account', icon: <KeyRound size={13} />, onClick: () => openSpaceSettings('apps', 'accounts') },},{done: kwants.length > 0,@@ -3966,9 +3972,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({inboxNav.go = () => showPage('inbox', 'new');const backToList = isPhone ? () => { setPage('chat'); setPhoneView('list'); } : undefined;const parallel = <ParallelPage onBack={backToList} />;- const connectionsPage = (+ // Apps & accounts › Advanced: tool servers, Telegram and notes from bots (AI accounts have their own section).+ const connectionsPage = (chooseComposioBots: () => void) => (<ConnectionsPageembedded+ hideAccounts+ onChooseComposioBots={chooseComposioBots}onOpenTools={() => setIsMcpOpen(true)}onAddTool={() => { setMcpStartAdding(true); setIsMcpOpen(true); }}onOpenAccounts={openSettings}@@ -4213,7 +4222,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setPage('chat');return;}- if (v.kind === 'settings') return v.scope === 'app' ? openAppSettings() : openSpaceSettings(v.tab);+ if (v.kind === 'settings') return v.scope === 'app' ? openAppSettings() : openSpaceSettings(v.tab, v.section);showPage(v.kind, v.kind === 'inbox' ? v.tab : 'new');};useEffect(() => {@@ -4343,7 +4352,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}if (id === 'space') {// Nothing can run yet: the fix is in Accounts, so start there- openSpaceSettings(canRun === false ? 'accounts' : 'general');+ canRun === false ? openSpaceSettings('apps', 'accounts') : openSpaceSettings('general');return;}if (id === 'jar') {@@ -4500,6 +4509,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onScope={setSettingsScope}onOpenArchived={onOpenArchived}connections={connectionsPage}+ appsSection={appsSection}+ toolNoteOpen={!!toolNoteFocus}appSettings={<Suspensefallback={@@ -4513,7 +4524,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({isOpenonClose={closeSpaceSettings}tokensUsed={tokensUsed}- onOpenApiKeys={() => openSpaceSettings('accounts')}+ onOpenApiKeys={() => openSpaceSettings('apps', 'accounts')}focusRow={settingsFocusRow}/></Suspense>diff --git a/frontend/src/Shell.tsx b/frontend/src/Shell.tsxindex a81da281..8d2778c5 100644--- a/frontend/src/Shell.tsx+++ b/frontend/src/Shell.tsx@@ -328,7 +328,7 @@ export const App: React.FC = () => {onCreated={(s, addAccounts) => {setCreating(null);setSpaces((prev) => (prev ? [...prev, s] : [s]));- open(s.id, null, false, addAccounts ? { kind: 'settings', scope: 'space', tab: 'accounts' } : null);+ open(s.id, null, false, addAccounts ? { kind: 'settings', scope: 'space', tab: 'apps', section: 'accounts' } : null);reload();}}/>diff --git a/frontend/src/appsAccounts.ts b/frontend/src/appsAccounts.tsnew file mode 100644index 00000000..d92b42f0--- /dev/null+++ b/frontend/src/appsAccounts.ts@@ -0,0 +1,170 @@+// Settings › Apps & accounts (0.9.5, Mira's audit #3): one page for what bots reach outside kwant+// (apps through Composio, tool servers) and which AI they think with. Connecting an app is a+// three-step sheet; picking bots in step 3 turns the Composio server on for exactly those bots,+// with the same calls the Tools page and the bot editor use (PUT /api/mcp/servers/:id and+// PUT /api/kwants/:id/mcp-servers). Pure helpers here; the page is components/AppsAccounts.tsx.++import type { Connection } from './connections';+import { personFetch } from './auth';+import { formToPayload, serverToForm, type McpServer } from './mcp';++/** Where Apps & accounts opens: at the top, at AI accounts, or with Advanced open. */+export type { AppsSection } from './nav';++export interface AppTile {+ /** Composio's toolkit slug. */+ slug: string;+ name: string;+ /** Under the name on the tile. */+ blurb: string;+ /** "Your bots will be able to …", in plain words. Sending or changing things is said separately. */+ can: string[];+ /** The step that acts for the person (sends, posts, buys): the approvals line goes next to it. */+ acts: string;+ /** Our own tint for the initials on the #231d4b ground (not a brand colour); search hits have none. */+ tint?: string;+}++/** The tiles, in order (brief: Gmail, Google Calendar, Slack, Notion, Shopify, GitHub). */+export const APP_TILES: AppTile[] = [+ { slug: 'gmail', tint: 'text-rose-300', name: 'Gmail', blurb: 'Read mail, write drafts', can: ['Read and search your mail', 'Write drafts for you to check'], acts: 'Send mail' },+ { slug: 'googlecalendar', tint: 'text-blue-300', name: 'Google Calendar', blurb: 'See and add events', can: ['See your calendar', 'Find free time'], acts: 'Add or move events' },+ { slug: 'slack', tint: 'text-amber-200', name: 'Slack', blurb: 'Read and post messages', can: ['Read channels and threads', 'Search messages'], acts: 'Post messages' },+ { slug: 'notion', tint: 'text-zinc-200', name: 'Notion', blurb: 'Read and edit pages', can: ['Read and search your pages', 'Draft new pages'], acts: 'Change or delete pages' },+ { slug: 'shopify', tint: 'text-emerald-300', name: 'Shopify', blurb: 'Orders and products', can: ['See orders, products and customers', 'Look up stock'], acts: 'Change orders or products' },+ { slug: 'github', tint: 'text-violet-200', name: 'GitHub', blurb: 'Issues and pull requests', can: ['Read repositories, issues and pull requests', 'Draft issues and comments'], acts: 'Post, merge or close' },+];++/** A search hit opened in the sheet: what we can say about an app we have no copy for. */+export function tileFor(app: { slug: string; name: string; description?: string | null }): AppTile {+ const known = APP_TILES.find((t) => t.slug === app.slug);+ if (known) return known;+ const what = (app.description ?? '').trim().replace(/\.$/, '');+ return { slug: app.slug, name: app.name, blurb: what, can: [what ? `Use ${app.name}: ${what.charAt(0).toLowerCase()}${what.slice(1)}` : `Use ${app.name}’s tools`], acts: 'Send, post or change things' };+}++/** "M" for Gmail, "GC" for Google Calendar: the plain mark on a tile (no brand logos). */+export function appInitials(name: string): string {+ const words = name.trim().split(/\s+/).filter(Boolean);+ if (words.length === 0) return '?';+ if (words.length === 1) return name.toLowerCase() === 'gmail' ? 'M' : words[0].charAt(0).toUpperCase();+ return (words[0].charAt(0) + words[1].charAt(0)).toUpperCase();+}++// ── Approvals: what the sheet promises about sending ─────────────────────────────────────────++export type Mode = 'ask' | 'smart' | 'off';++/**+ * The line next to "Send mail" etc., from the approvals the chosen bots actually run with+ * (each bot's effective mode; with no bot picked, the space's). Never promises "asks first"+ * when a bot is on "Don't ask".+ */+export function approvalLine(acts: string, bots: Array<{ name: string; approvals_effective?: string | null }>, spaceMode: string | undefined): { text: string; tone: 'ok' | 'warn' } {+ const mode = (m: string | null | undefined): Mode => (m === 'off' || m === 'smart' ? m : 'ask');+ const modes = bots.length ? bots.map((b) => mode(b.approvals_effective ?? spaceMode)) : [mode(spaceMode)];+ const free = bots.filter((b) => mode(b.approvals_effective ?? spaceMode) === 'off').map((b) => b.name);+ // Smart asks before any tool the server doesn't mark read-only, for every engine (Ada, fixes-542 F3), so it reads like ask.+ // Not "every time": the approval can be answered "always allow" for the session.+ if (modes.every((m) => m !== 'off')) return { text: `${acts} only after you say yes`, tone: 'ok' };+ if (modes.every((m) => m === 'off')) return { text: `${acts} without asking you first (approvals are off)`, tone: 'warn' };+ if (free.length) return { text: `${acts}: ${listNames(free)} won’t ask first (approvals off); the others ask you`, tone: 'warn' };+ return { text: `${acts}: ${listNames(free)} won’t ask first (approvals off); the others ask you`, tone: 'warn' };+}++export function listNames(names: string[]): string {+ if (names.length <= 1) return names[0] ?? '';+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;+}++// ── AI accounts: the needs-you count ─────────────────────────────────────────────────────────────++const BAD = new Set(['needs_sign_in', 'error', 'limited', 'locked']);++/** True when an account connection needs the person: it's broken and a bot uses it. */+export const accountNeedsYou = (c: Pick<Connection, 'kind' | 'status' | 'used_by'>): boolean =>+ c.kind === 'account' && BAD.has(c.status) && c.used_by.length > 0;++// ── Giving the Composio server to the chosen bots ────────────────────────────────────────────++/** The MCP server id inside a connection id (`mcp:<id>`). */+export const serverIdOf = (connectionId: string | null | undefined): string | null =>+ connectionId && connectionId.startsWith('mcp:') ? connectionId.slice(4) : null;++/**+ * Each bot's new tool list: the server added for the chosen bots and removed for the rest, with+ * their other tools left as they were. Only bots whose list changes are returned.+ */+export function assignmentsFor(serverId: string, current: Record<string, string[]>, chosen: string[]): Record<string, string[]> {+ const pick = new Set(chosen);+ const out: Record<string, string[]> = {};+ for (const [kwant, ids] of Object.entries(current)) {+ const has = ids.includes(serverId);+ if (pick.has(kwant) && !has) out[kwant] = [...ids, serverId];+ else if (!pick.has(kwant) && has) out[kwant] = ids.filter((id) => id !== serverId);+ }+ return out;+}++export class GiveError extends Error {}++type Fetch = (url: string, init?: RequestInit) => Promise<Response>;++async function json<T>(f: Fetch, url: string, init?: RequestInit): Promise<T> {+ let res: Response;+ try {+ res = await f(url, init);+ } catch {+ throw new GiveError('Couldn’t reach kwant bots. Check your connection and try again.');+ }+ const body = await res.json().catch(() => null);+ if (!res.ok) {+ const err = body && typeof body === 'object' ? (body as { error?: unknown }).error : null;+ throw new GiveError(typeof err === 'string' && err ? err : `Something went wrong (HTTP ${res.status}).`);+ }+ return body as T;+}++/** Which of these bots have the server now. */+export async function botsWithServer(serverId: string, kwantIds: string[], f: Fetch = (u, i) => personFetch(u, i)): Promise<string[]> {+ const lists = await Promise.all(kwantIds.map((id) => json<{ server_ids: string[] }>(f, `/api/kwants/${encodeURIComponent(id)}/mcp-servers`)));+ return kwantIds.filter((_, i) => lists[i].server_ids.includes(serverId));+}++/**+ * Turns the server on and gives it to exactly `chosen` among `kwantIds`: the same two calls the+ * Tools page (enabled) and the bot editor (its tool list) make. With nobody chosen the server is+ * left as it is, only taken away from every bot.+ */+export async function giveServerTo(serverId: string, kwantIds: string[], chosen: string[], f: Fetch = (u, i) => personFetch(u, i)): Promise<void> {+ const current: Record<string, string[]> = {};+ const lists = await Promise.all(kwantIds.map((id) => json<{ server_ids: string[] }>(f, `/api/kwants/${encodeURIComponent(id)}/mcp-servers`)));+ kwantIds.forEach((id, i) => (current[id] = lists[i].server_ids));+ const changes = assignmentsFor(serverId, current, chosen);+ for (const [kwant, ids] of Object.entries(changes)) {+ await json(f, `/api/kwants/${encodeURIComponent(kwant)}/mcp-servers`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ server_ids: ids }),+ });+ }+ if (chosen.length === 0) return;+ const server = await json<McpServer>(f, `/api/mcp/servers/${encodeURIComponent(serverId)}`);+ if (server.enabled) return;+ // Sending the masks back keeps every stored secret (as Tools' on/off switch does).+ await json(f, `/api/mcp/servers/${encodeURIComponent(serverId)}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ...formToPayload(serverToForm(server)), enabled: true }),+ });+}++/** What the page's header says: things that need the person, and what's connected. */+export function pageCounts(connections: Connection[]): string {+ const apps = connections.filter((c) => c.kind === 'mcp' && c.status === 'connected').length;+ const accounts = connections.filter((c) => c.kind === 'account' && c.status === 'connected').length;+ const needs = connections.filter((c) => (c.kind === 'account' ? accountNeedsYou(c) : BAD.has(c.status))).length;+ const parts = [`${accounts} AI ${accounts === 1 ? 'account' : 'accounts'} ready`, `${apps} tool ${apps === 1 ? 'server' : 'servers'} on`];+ if (needs) parts.push(`${needs} ${needs === 1 ? 'needs' : 'need'} you`);+ return parts.join(' · ');+}diff --git a/frontend/src/claudeVm.ts b/frontend/src/claudeVm.tsindex db95a3aa..7dd5b128 100644--- a/frontend/src/claudeVm.ts+++ b/frontend/src/claudeVm.ts@@ -162,7 +162,7 @@ export function stoppedLine(a: AgentVmState): Extract<RowStatus, { kind: 'stoppecase 'relay_down':return { kind: 'stopped', text: 'kwant couldn’t connect Claude to your sign-in. Restart kwant; if it keeps happening, turn this off.', action: null };case 'sign_in_expired':- return { kind: 'stopped', text: 'Your Claude sign-in has expired, so Claude can’t reply. Sign in again in Settings › This space › Accounts.', action: null };+ return { kind: 'stopped', text: 'Your Claude sign-in has expired, so Claude can’t reply. Sign in again in Settings › This space › Apps & accounts.', action: null };default: {const why = a.detail ? sentence(a.detail) : a.reason ? `code ${a.reason}` : null;return {diff --git a/frontend/src/components/AccountPriority.tsx b/frontend/src/components/AccountPriority.tsxindex 44fb1846..c9ed9d86 100644--- a/frontend/src/components/AccountPriority.tsx+++ b/frontend/src/components/AccountPriority.tsx@@ -1,210 +1,469 @@import React, { useEffect, useMemo, useRef, useState } from 'react';-import { ArrowDown, ArrowUp, GripVertical } from 'lucide-react';+import { MoreHorizontal } from 'lucide-react';import { playSfx } from '../audio/chiptune';import type { EngineInfo } from '../engines';+import { useEscapeLayer } from '../escape';import {- FAILOVER_CAPTION,+ accountGroups,+ accountWhere,engineLabel,failoverOrder,moveAccount,moveAnnouncement,+ orderIntro,priorityStatus,priorityUpdates,- splitRanked,} from '../failover';-import { Profile, cardOf, profilesApi } from '../profiles';+import { Profile, activeLimit, cardOf, profilesApi } from '../profiles';+import { listNames } from '../appsAccounts';import { StatusPill } from './EngineAccounts';-const arrowBtn =- 'inline-flex items-center justify-center w-8 h-8 sm:w-7 sm:h-7 rounded-md border border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700 transition-colors disabled:opacity-35 disabled:hover:bg-zinc-800/70 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400';+const smallBtn =+ 'inline-flex items-center justify-center gap-1 min-h-[44px] sm:min-h-[28px] px-2.5 rounded-md border text-[11px] font-medium transition-colors disabled:opacity-40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400';+const plainBtn = `${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-100 hover:bg-zinc-700`;+const iconBtn =+ 'inline-flex items-center justify-center w-11 h-11 sm:w-7 sm:h-7 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400';+const linkBtn = 'inline-flex items-center min-h-[44px] sm:min-h-0 text-[11px] font-medium text-sky-300 hover:text-sky-200 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400 rounded';+const groupTitle = 'text-xs font-semibold text-zinc-200';+const quietGroupTitle = 'text-xs font-semibold text-zinc-400';-/**- * One list across engines, in the order turns try them. The order is the failover priority: it is- * saved as each account's `priority` (PATCH /api/profiles/:id), so the server needs nothing new.- * Drag a row, or use its up and down buttons (they work from the keyboard and on a phone).- */-export const AccountPriority: React.FC<{+export interface AccountPriorityProps {profiles: Profile[];engines: EngineInfo[] | null;onChanged: () => Promise<void>;+ /** The space, for the intro line. */+ spaceName?: string;+ /** Bot names per account id ("Used by Ann, Ben"). With `pinnedOnly`, only bots pinned to the account's+ * engine: bots on auto start on the "Used first" account, so backups and off accounts don't name them. */+ usedBy?: (profileId: string, pinnedOnly?: boolean) => string[];+ /** The existing sign-in and set-up paths (the engine's card under "Sign-ins and settings"). */+ onSignIn?: (p: Profile) => void;+ onSetUp?: (p: Profile) => void;+ onAddAccount?: () => void;+ /** Turns a whole engine back on (the engine's own switch). */+ onEngineOn?: (engine: EngineInfo['id']) => Promise<boolean | void>;+ /** Turns a whole engine off: "Turn off" on the only account its engine has on. */+ onEngineOff?: (engine: EngineInfo['id']) => Promise<boolean | void>;now?: number;-}> = ({ profiles, engines, onChanged, now = Date.now() }) => {+}++/**+ * The AI accounts, the way turns use them: "Used first", then "If it runs out", then "Not used" for the+ * accounts that are off, signed out or not installed. The order is the failover priority, saved as each+ * account's `priority` (PATCH /api/profiles/:id); nothing new on the server. "Use first" is the one+ * visible move; Move up, Move down and Turn off are in each row's More menu, for the keyboard and phones.+ */+export const AccountPriority: React.FC<AccountPriorityProps> = ({+ profiles,+ engines,+ onChanged,+ spaceName,+ usedBy,+ onSignIn,+ onSetUp,+ onAddAccount,+ onEngineOn,+ onEngineOff,+ now = Date.now(),+}) => {// The order shown while a save is in flight; null means "what the server last said".const [pending, setPending] = useState<Profile[] | null>(null);+ const [busy, setBusy] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [announce, setAnnounce] = useState('');- const [dragId, setDragId] = useState<string | null>(null);- const [overId, setOverId] = useState<string | null>(null);const [focusKey, setFocusKey] = useState<string | null>(null);- const listRef = useRef<HTMLOListElement>(null);+ const rootRef = useRef<HTMLElement>(null);const engineOf = (p: Profile) => engines?.find((e) => e.id === cardOf(p));- // Accounts that aren't installed or aren't signed in can't take a turn: they are listed apart, unranked- // and not movable. A move numbers them after the ranked ones, so they join at the bottom later.- const { ranked: servedRanked, unranked } = useMemo(- () => splitRanked(failoverOrder(profiles), (p) => engines?.find((e) => e.id === cardOf(p)), now),+ const groups = useMemo(+ () => accountGroups(failoverOrder(profiles), (p) => engines?.find((e) => e.id === cardOf(p)), now),// eslint-disable-next-line react-hooks/exhaustive-deps[profiles, engines],);- const order = pending ?? servedRanked;+ const used = pending ?? groups.used;+ const rest = groups.notUsed.map((x) => x.p);- // Put keyboard focus back on the button that was used, once the row has moved.+ // Keyboard focus follows the row that moved.useEffect(() => {if (!focusKey) return;- const el = listRef.current?.querySelector<HTMLButtonElement>(`[data-focus-key="${CSS.escape(focusKey)}"]`);- if (el && !el.disabled) el.focus();+ const el = rootRef.current?.querySelector<HTMLButtonElement>(`[data-focus-key="${CSS.escape(focusKey)}"]`);+ // While the save is in flight the row's buttons are disabled: wait for them, then focus.+ if (el?.disabled) return;+ el?.focus();setFocusKey(null);- }, [focusKey, order]);+ }, [focusKey, used, profiles]);++ const nameOf = (p: Profile) => `${engineLabel(p)} (${p.kind === 'system' ? 'on this computer' : p.name})`;+ /** "Used by Ann" on the first row and on Not used. On a backup row the bots there start on it (pinned), so "Cody uses it first". */+ const usedLine = (p: Profile, place: 'first' | 'backup' | 'off' = 'first') => {+ const backup = place === 'backup';+ // Bots on auto start on the "Used first" account; a backup or an off account names only bots pinned to it.+ const names = usedBy?.(p.id, place !== 'first') ?? [];+ if (!names.length) return null;+ const who = names.length > 3 ? `${names.slice(0, 2).join(', ')} and ${names.length - 2} more` : listNames(names);+ return backup ? `${who} ${names.length === 1 ? 'uses' : 'use'} it first` : `Used by ${who}`;+ };++ // The server's own words never reach the person: say what didn't happen, and that nothing changed.+ const fail = (_e: unknown, what: string) => {+ // The alert is read out; the polite status stays quiet so it isn't said twice.+ setError(`${what} It is back as it was.`);+ setAnnounce('');+ };- const save = async (next: Profile[], moved: Profile, to: number) => {- const updates = priorityUpdates(next, unranked);+ const saveOrder = async (next: Profile[], moved: Profile, to: number) => {+ const updates = priorityUpdates(next, rest);if (updates.length === 0) return;setError(null);- // Show the new order at once, with the numbers it will have, so a late reload can't flip it back.- const numbered = next.map((p) => ({ ...p, priority: updates.find((u) => u.id === p.id)?.priority ?? p.priority }));- setPending(numbered);- setAnnounce(moveAnnouncement(moved.kind === 'system' ? `${engineLabel(moved)} on this machine` : moved.name, to, next.length));+ // Shown at once, with the numbers it will have, so a late reload can't flip it back.+ setPending(next.map((p) => ({ ...p, priority: updates.find((u) => u.id === p.id)?.priority ?? p.priority })));+ setAnnounce(moveAnnouncement(nameOf(moved), to, next.length));try {await Promise.all(updates.map((u) => profilesApi.update(u.id, { priority: u.priority })));await onChanged();} catch (e) {- setError(e instanceof Error ? e.message : 'Could not save the order.');- setAnnounce('Could not save the order. It is back as it was.');+ fail(e, 'Could not save the order.');await onChanged().catch(() => undefined);} finally {setPending(null);}};- const move = (index: number, to: number, key?: string) => {- const next = moveAccount(order, index, to);+ const move = (from: number, to: number) => {+ const next = moveAccount(used, from, to);if (!next) return;playSfx('click');- if (key) setFocusKey(key);- void save(next, order[index], to);+ setFocusKey(`${used[from].id}:more`);+ void saveOrder(next, used[from], to);+ };++ /** On again, at the end of "If it runs out": the engine's own switch when the whole engine is off. */+ const turnOn = async (p: Profile, engineOff: boolean) => {+ setError(null);+ setBusy(p.id);+ try {+ // The engine switch says no by returning false (it puts itself back); stop before any "is on".+ if (engineOff && onEngineOn && (await onEngineOn(cardOf(p))) === false) throw new Error('engine switch failed');+ const others = rest.filter((x) => x.id !== p.id);+ const updates = priorityUpdates([...used, p], others);+ const mine = updates.find((u) => u.id === p.id);+ await Promise.all([+ ...(p.enabled && !mine ? [] : [profilesApi.update(p.id, { ...(p.enabled ? {} : { enabled: true }), ...(mine ? { priority: mine.priority } : {}) })]),+ ...updates.filter((u) => u.id !== p.id).map((u) => profilesApi.update(u.id, { priority: u.priority })),+ ]);+ await onChanged();+ setAnnounce(`${nameOf(p)} is on. Your bots use it if the ones above run out.`);+ setFocusKey(`${p.id}:more`);+ } catch (e) {+ fail(e, `Couldn’t turn on ${nameOf(p)}.`);+ await onChanged().catch(() => undefined);+ // A Not used row has no More menu: focus goes back to the row's Turn on.+ setFocusKey(`${p.id}:on`);+ } finally {+ setBusy(null);+ }+ };++ /**+ * Turn off. The server keeps one main (default) account per engine on, so for the main account:+ * another account of that engine that's on becomes the main one first (the next in the failover+ * order); with none, the engine's own switch turns the whole engine off.+ */+ const turnOff = async (p: Profile) => {+ setError(null);+ setBusy(p.id);+ const engine = cardOf(p);+ const next = p.is_default ? failoverOrder(profiles).find((x) => x.id !== p.id && x.enabled && cardOf(x) === engine) : undefined;+ let moved = false;+ try {+ if (p.is_default && !next) {+ if (!onEngineOff) throw new Error('no engine switch');+ if ((await onEngineOff(engine)) === false) throw new Error('engine switch failed');+ await onChanged();+ setAnnounce(`${nameOf(p)} is off. Your bots skip ${engineLabel(p)}.`);+ } else {+ if (next) {+ await profilesApi.update(next.id, { is_default: true });+ moved = true;+ }+ await profilesApi.update(p.id, { enabled: false });+ await onChanged();+ setAnnounce(+ next+ ? `${nameOf(p)} is off. ${next.kind === 'system' ? 'The sign-in on this computer' : next.name} is now ${engineLabel(p)}’s main account.`+ : `${nameOf(p)} is off. Your bots skip it.`,+ );+ }+ setFocusKey(`${p.id}:on`);+ } catch (e) {+ // Half done (the main account moved, this one stayed on): put the main account back.+ if (moved) await profilesApi.update(p.id, { is_default: true }).catch(() => undefined);+ fail(e, `Couldn’t turn off ${nameOf(p)}.`);+ await onChanged().catch(() => undefined);+ setFocusKey(`${p.id}:more`);+ } finally {+ setBusy(null);+ }};- const nameOf = (p: Profile) => (p.kind === 'system' ? 'This machine' : p.name);+ const first = used[0];+ const backups = used.slice(1);+ const ready = (p: Profile) => priorityStatus(p, engineOf(p), now).tone === 'ok';+ const firstOut = first && first.enabled ? activeLimit(first.limited_until, now) : null;+ const stepIn = backups.find(ready);+ const offToTurnOn = groups.notUsed.find((x) => x.reason === 'off');++ const row = (p: Profile, i: number) => {+ const status = priorityStatus(p, engineOf(p), now);+ const line = usedLine(p, i > 0 ? 'backup' : 'first');+ return (+ <li key={p.id} data-account={p.id} data-used-index={i} className="flex items-start gap-2 rounded-lg border border-zinc-800 bg-zinc-950/40 px-3 py-2.5">+ <div className="flex-1 min-w-0">+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="text-xs font-medium text-zinc-100" data-account-title>+ {engineLabel(p)}+ </span>+ <StatusPill tone={status.tone}>{status.label}</StatusPill>+ </p>+ <p className="mt-0.5 text-[11px] text-zinc-400 break-words">+ {accountWhere(p)}+ {line && <span className="text-zinc-300"> · {line}</span>}+ </p>+ {i === 0 && firstOut && (+ <p className={`mt-0.5 text-[11px] ${stepIn ? 'text-zinc-300' : 'text-amber-200'}`} data-step-in>+ {stepIn ? `Bots use ${engineLabel(stepIn)} until then.` : 'Bots wait until then.'}+ </p>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {i > 0 && (+ <button type="button" className={plainBtn} data-use-first data-focus-key={`${p.id}:first`} disabled={!!pending} onClick={() => move(i, 0)}>+ Use first<span className="sr-only"> {nameOf(p)}</span>+ </button>+ )}+ <RowMenu+ label={nameOf(p)}+ focusKey={`${p.id}:more`}+ disabled={!!pending || busy === p.id}+ items={[+ { label: 'Move up', disabled: i === 0, run: () => move(i, i - 1) },+ { label: 'Move down', disabled: i === used.length - 1, run: () => move(i, i + 1) },+ { label: 'Turn off', run: () => void turnOff(p) },+ ]}+ />+ </div>+ </li>+ );+ };return (- <section aria-labelledby="account-priority-title" className="rounded-xl border border-zinc-800 bg-zinc-900/90 p-3 text-xs">- <h3 id="account-priority-title" className="font-semibold text-zinc-100">- Order to use- </h3>- <p id="account-priority-caption" className="mt-0.5 text-[11px] text-zinc-400">- {FAILOVER_CAPTION}+ <section ref={rootRef} aria-labelledby="account-order-title" className="space-y-3 text-xs" data-account-order>+ <p id="account-order-title" className="text-[11px] text-zinc-400">+ {orderIntro(spaceName ?? 'this space')}</p>- {order.length === 0 ? (- <p className="mt-2 text-zinc-500">{unranked.length === 0 ? 'No accounts yet. Add one below.' : 'No account is ready to use yet.'}</p>++ {first ? (+ <div data-group="first">+ <h4 id="account-group-first" className={groupTitle}>+ Used first+ </h4>+ <ul aria-labelledby="account-group-first" className="mt-1.5 space-y-1.5">+ {row(first, 0)}+ </ul>+ </div>) : (- <ol ref={listRef} aria-describedby="account-priority-caption" className="mt-2.5 space-y-1.5">- {order.map((p, i) => {- const status = priorityStatus(p, engineOf(p), now);- const dragging = dragId === p.id;- const over = overId === p.id && dragId !== p.id;- return (+ <p className="text-zinc-400" data-none-ready>+ {groups.notUsed.length === 0 ? 'No AI accounts yet.' : 'No account is ready to use yet. Turn one on or sign in below.'}{' '}+ {groups.notUsed.length === 0 && onAddAccount && (+ <button type="button" className={linkBtn} onClick={onAddAccount}>+ Add an account+ </button>+ )}+ </p>+ )}++ {first && backups.length > 0 && (+ <div data-group="backup">+ <h4 id="account-group-backup" className={groupTitle}>+ If it runs out+ </h4>+ <ul aria-labelledby="account-group-backup" className="mt-1.5 space-y-1.5">+ {backups.map((p, j) => row(p, j + 1))}+ </ul>+ </div>+ )}++ {first && backups.length === 0 && (+ <div data-group="backup">+ <h4 id="account-group-backup" className={groupTitle}>+ If it runs out+ </h4>+ <p className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1.5 rounded-lg border border-dashed border-zinc-800 px-3 py-2.5 text-[11px] text-zinc-400" data-no-backup>+ <span>+ No backup yet. If {engineLabel(first)} runs out, your bots wait until it resets.+ </span>+ {offToTurnOn ? (+ <button+ type="button"+ className={plainBtn}+ disabled={busy === offToTurnOn.p.id}+ onClick={() => void turnOn(offToTurnOn.p, offToTurnOn.engineOff)}+ data-no-backup-action+ >+ Turn on {engineLabel(offToTurnOn.p)}+ </button>+ ) : (+ onAddAccount && (+ <button type="button" className={linkBtn} onClick={onAddAccount} data-no-backup-action>+ Add an account+ </button>+ )+ )}+ </p>+ </div>+ )}++ {groups.notUsed.length > 0 && (+ <div data-group="not-used">+ <h4 id="account-group-off" className={quietGroupTitle}>+ Not used+ </h4>+ <ul aria-labelledby="account-group-off" className="mt-1.5 space-y-1.5">+ {groups.notUsed.map(({ p, reason, engineOff }) => (<likey={p.id}data-account={p.id}- draggable- onDragStart={(e) => {- setDragId(p.id);- e.dataTransfer.effectAllowed = 'move';- e.dataTransfer.setData('text/plain', p.id);- }}- onDragOver={(e) => {- if (!dragId) return;- e.preventDefault();- e.dataTransfer.dropEffect = 'move';- if (overId !== p.id) setOverId(p.id);- }}- onDrop={(e) => {- e.preventDefault();- const from = order.findIndex((x) => x.id === dragId);- setDragId(null);- setOverId(null);- move(from, i);- }}- onDragEnd={() => {- setDragId(null);- setOverId(null);- }}- className={`flex items-center gap-2 rounded-lg border px-2 py-2 transition-colors ${- over ? 'border-sky-500/60 bg-sky-500/5' : 'border-zinc-800 bg-zinc-950/40'- } ${dragging ? 'opacity-50' : ''} ${p.enabled ? '' : 'opacity-75'}`}+ data-not-used={reason}+ className="flex flex-wrap items-center gap-x-2 gap-y-1.5 rounded-lg border border-dashed border-zinc-800 bg-zinc-950/20 px-3 py-2">- <GripVertical size={14} className="shrink-0 text-zinc-600 cursor-grab hidden sm:block" aria-hidden="true" />- <span className="shrink-0 w-4 text-center text-[11px] tabular-nums text-zinc-500" aria-hidden="true">- {i + 1}- </span>- <div className="flex-1 min-w-0">- <p className="text-zinc-100 font-medium truncate">{nameOf(p)}</p>- <div className="mt-0.5 flex items-center gap-x-1.5 gap-y-1 flex-wrap">- <span className="text-[11px] text-zinc-500">{engineLabel(p)}</span>- <StatusPill tone={status.tone}>{status.label}</StatusPill>- </div>+ <div className="flex-1 min-w-[10rem]">+ <p className="text-xs font-medium text-zinc-300" data-account-title>+ {engineLabel(p)}+ </p>+ <p className="mt-0.5 text-[11px] text-zinc-500 break-words">+ {p.kind === 'system' ? 'On this computer' : p.name} ·{' '}+ {reason === 'off' ? 'Turned off' : reason === 'signed_out' ? 'Signed out' : 'Not installed'}+ {usedLine(p, 'off') && <span> · {usedLine(p, 'off')}</span>}+ </p></div>- <div className="flex shrink-0 items-center gap-1">+ {reason === 'off' ? (<buttontype="button"- data-focus-key={`${p.id}:up`}- className={arrowBtn}- disabled={i === 0}- aria-label={`Move ${nameOf(p)} (${engineLabel(p)}) up`}- title="Use it earlier"- onClick={() => move(i, i - 1, i - 1 === 0 ? `${p.id}:down` : `${p.id}:up`)}+ className={plainBtn}+ data-focus-key={`${p.id}:on`}+ data-turn-on+ disabled={busy === p.id}+ onClick={() => void turnOn(p, engineOff)}>- <ArrowUp size={13} aria-hidden="true" />+ Turn on<span className="sr-only"> {nameOf(p)}</span></button>+ ) : reason === 'signed_out' ? (<buttontype="button"- data-focus-key={`${p.id}:down`}- className={arrowBtn}- disabled={i === order.length - 1}- aria-label={`Move ${nameOf(p)} (${engineLabel(p)}) down`}- title="Use it later"- onClick={() => move(i, i + 1, i + 1 === order.length - 1 ? `${p.id}:up` : `${p.id}:down`)}+ className={usedLine(p, 'off') ? `${smallBtn} border-amber-500/40 bg-amber-500/10 text-amber-100 hover:bg-amber-500/20` : linkBtn}+ data-sign-in+ data-quiet-sign-in={usedLine(p, 'off') ? undefined : ''}+ onClick={() => onSignIn?.(p)}+ disabled={!onSignIn}>- <ArrowDown size={13} aria-hidden="true" />+ Sign in<span className="sr-only"> to {nameOf(p)}</span></button>- </div>+ ) : (+ <button type="button" className={plainBtn} data-set-up onClick={() => onSetUp?.(p)} disabled={!onSetUp}>+ Set up<span className="sr-only"> {nameOf(p)}</span>+ </button>+ )}</li>- );- })}- </ol>- )}- {unranked.length > 0 && (- <div data-unranked className="mt-3">- <h4 id="account-unranked-title" className="text-[11px] font-medium text-zinc-400">- Not in the order- </h4>- <p className="mt-0.5 text-[11px] text-zinc-500">These can't run turns until they are installed or signed in.</p>- <ul aria-labelledby="account-unranked-title" className="mt-1.5 space-y-1.5">- {unranked.map((p) => {- const status = priorityStatus(p, engineOf(p), now);- return (- <li key={p.id} data-account={p.id} data-unranked-account className="flex items-center gap-2 rounded-lg border border-dashed border-zinc-800 bg-zinc-950/20 px-2 py-2">- <div className="flex-1 min-w-0">- <p className="text-zinc-300 font-medium truncate">{nameOf(p)}</p>- <div className="mt-0.5 flex items-center gap-x-1.5 gap-y-1 flex-wrap">- <span className="text-[11px] text-zinc-500">{engineLabel(p)}</span>- <StatusPill tone={status.tone}>{status.label}</StatusPill>- </div>- </div>- </li>- );- })}+ ))}</ul></div>)}+<p role="status" aria-live="polite" className="sr-only">{announce}</p>{error && (- <p role="alert" className="mt-2 text-[11px] text-rose-300">+ <p role="alert" className="text-[11px] text-rose-300" data-order-error>{error}</p>)}</section>);};++/** A row's More menu: Move up, Move down, Turn off. Arrow keys move between items; Escape closes it and+ * puts focus back on its button. */+const RowMenu: React.FC<{+ label: string;+ focusKey: string;+ disabled?: boolean;+ items: Array<{ label: string; disabled?: boolean; run: () => void }>;+}> = ({ label, focusKey, disabled, items }) => {+ const [open, setOpen] = useState(false);+ const wrapRef = useRef<HTMLDivElement>(null);+ const btnRef = useRef<HTMLButtonElement>(null);+ const close = (refocus = true) => {+ setOpen(false);+ if (refocus) btnRef.current?.focus();+ };+ useEscapeLayer(wrapRef, open, () => close());++ useEffect(() => {+ if (!open) return;+ wrapRef.current?.querySelector<HTMLButtonElement>('[role="menuitem"]:not([disabled])')?.focus();+ const away = (e: MouseEvent) => {+ if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);+ };+ document.addEventListener('mousedown', away);+ return () => document.removeEventListener('mousedown', away);+ }, [open]);++ const onKey = (e: React.KeyboardEvent) => {+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return;+ const list = [...(wrapRef.current?.querySelectorAll<HTMLButtonElement>('[role="menuitem"]:not([disabled])') ?? [])];+ if (!list.length) return;+ e.preventDefault();+ const at = list.indexOf(document.activeElement as HTMLButtonElement);+ const next = e.key === 'Home' ? 0 : e.key === 'End' ? list.length - 1 : (at + (e.key === 'ArrowDown' ? 1 : -1) + list.length) % list.length;+ list[next].focus();+ };++ return (+ <div ref={wrapRef} className="relative" onKeyDown={onKey}>+ <button+ ref={btnRef}+ type="button"+ className={iconBtn}+ aria-haspopup="menu"+ aria-expanded={open}+ aria-label={`More for ${label}`}+ title="More"+ data-focus-key={focusKey}+ data-row-menu+ disabled={disabled}+ onClick={() => setOpen((o) => !o)}+ >+ <MoreHorizontal size={15} aria-hidden="true" />+ </button>+ {open && (+ <div role="menu" aria-label={`More for ${label}`} className="absolute right-0 top-full z-20 mt-1 w-36 rounded-lg border border-zinc-700 bg-zinc-900 p-1 shadow-xl" data-row-menu-list>+ {items.map((it) => (+ <button+ key={it.label}+ type="button"+ role="menuitem"+ disabled={it.disabled}+ className="block w-full rounded-md px-2.5 py-2 sm:py-1.5 min-h-[44px] sm:min-h-0 text-left text-xs text-zinc-200 hover:bg-zinc-800 focus:bg-zinc-800 focus:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-400 disabled:opacity-40 disabled:hover:bg-transparent"+ onClick={() => {+ close(false);+ it.run();+ }}+ >+ {it.label}+ </button>+ ))}+ </div>+ )}+ </div>+ );+};diff --git a/frontend/src/components/ApiKeysPanel.tsx b/frontend/src/components/ApiKeysPanel.tsxindex 1b455ebc..1e25f101 100644--- a/frontend/src/components/ApiKeysPanel.tsx+++ b/frontend/src/components/ApiKeysPanel.tsx@@ -1,5 +1,5 @@// API keys and the Ollama address: one per provider, shared by every space. They live in-// Settings › This space › Accounts, next to the accounts that use them, and are saved on their+// Settings › This space › Apps & accounts, next to the accounts that use them, and are saved on their// own: only these four fields are sent, so nothing else in App settings changes.import React, { useEffect, useState } from 'react';import { AlertTriangle, Check, ChevronDown, ChevronRight, Globe, Key, Loader2 } from 'lucide-react';diff --git a/frontend/src/components/AppsAccounts.tsx b/frontend/src/components/AppsAccounts.tsxnew file mode 100644index 00000000..8776db56--- /dev/null+++ b/frontend/src/components/AppsAccounts.tsx@@ -0,0 +1,788 @@+// Settings › This space › Apps & accounts (0.9.5): app tiles first, then Composio search, the AI+// accounts the bots think with, and a closed Advanced (tool servers, Telegram, notes from bots).+// Connecting an app is one sheet with three steps; the bots picked in step 3 get it, turned on.++import React, { useCallback, useEffect, useId, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { AlertTriangle, Check, ChevronRight, ExternalLink, Info, Loader2, RefreshCw, X } from 'lucide-react';+import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';+import { CatalogEntry, ComposioApp, Connection, ConnectionsError, ConnectionsList, composioBody, composioErrorText, connectionsApi } from '../connections';+import {+ APP_TILES,+ AppTile,+ AppsSection,+ GiveError,+ accountNeedsYou,+ appInitials,+ approvalLine,+ botsWithServer,+ giveServerTo,+ listNames,+ serverIdOf,+ tileFor,+} from '../appsAccounts';+import { inDesktopApp } from '../externalLinks';+import { useEscapeLayer } from '../escape';+import { ProfilesState, useProfiles } from '../useProfiles';+import { EnginesApi, useEngines } from '../useEngines';+import { parsePick, type EngineInfo } from '../engines';+import { AccountPriority } from './AccountPriority';+import { Profile, cardOf } from '../profiles';+import type { Kwant } from './Sidebar';+import { ComposioAppSearch } from './ConnectionsView';+import { usePhoneLayout } from '../usePhoneLayout';+import { ModernAvatar } from './ModernAvatar';++/** The tile mark: plain initials on the overlay colour, never a brand logo. */+const TILE_BG = '#231d4b';+export const COMPOSIO_HOME = 'https://platform.composio.dev';++const btn =+ 'inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const quietBtn = `${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;+const primaryBtn = `${btn} bg-sky-600 text-white hover:bg-sky-500`;+const linkBtn =+ 'inline-flex items-center gap-1 min-h-[44px] sm:min-h-[32px] text-xs font-medium text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';+const field =+ 'w-full min-h-[40px] sm:min-h-[36px] px-2.5 py-1.5 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 placeholder:text-zinc-500 focus:outline-none focus:border-sky-500 aria-[invalid=true]:border-rose-500/60';+const sectionTitle = 'text-xs font-semibold text-zinc-300 uppercase tracking-wider';++const errText = (e: unknown) => (e instanceof Error ? e.message : 'Something went wrong.');++export const AppMark: React.FC<{ name: string; size?: number; tint?: string }> = ({ name, size = 36, tint = 'text-violet-100' }) => (+ <span+ aria-hidden="true"+ data-app-mark-tint={tint}+ className={`shrink-0 inline-flex items-center justify-center rounded-lg font-semibold ${tint} border border-violet-400/20`}+ style={{ background: TILE_BG, width: size, height: size, fontSize: size * 0.36 }}+ >+ {appInitials(name)}+ </span>+);++// ── The Connect sheet ────────────────────────────────────────────────────────────────────────++export interface ConnectApi {+ addComposio: (body: { url: string; api_key?: string; enabled: boolean }) => Promise<{ connection_id: string }>;+ connect: (slug: string) => Promise<{ redirect_url: string }>;+ give: (serverId: string, kwantIds: string[], chosen: string[]) => Promise<void>;+ botsWith: (serverId: string, kwantIds: string[]) => Promise<string[]>;+}++const defaultConnectApi: ConnectApi = {+ addComposio: (b) => connectionsApi.addComposio(b),+ connect: (slug) => connectionsApi.connectComposioApp(slug),+ give: (s, k, c) => giveServerTo(s, k, c),+ botsWith: (s, k) => botsWithServer(s, k),+};++export interface ConnectSheetProps {+ /** The app being connected; null sets up Composio on its own. */+ app: AppTile | null;+ /** Composio's catalogue entry: added or not, and what kwant can do with it. */+ composio: CatalogEntry;+ kwants: Kwant[];+ spaceName: string;+ spaceMode?: string;+ onClose: () => void;+ /** After the bots have it: which app (null: Composio itself) and the names of the bots that have it now. */+ onDone: (result: { app: AppTile | null; who: string[] }) => void;+ api?: ConnectApi;+ phone?: boolean;+ /** Tests and screenshots: start with these filled in. */+ initial?: { url?: string; picked?: string[]; opened?: boolean; error?: string };+}++/** One numbered step of the sheet. Outside the sheet, so typing in a step keeps its focus.+ * `n` is the step's key (errors, tests); `label` is the number shown (null: a lone step, no number). */+const Step: React.FC<{ n: 1 | 2 | 3; label?: number | null; title: string; done: boolean; error: string | null; errorInChildren?: boolean; children: React.ReactNode }> = ({+ n,+ label = n,+ title,+ done,+ error,+ errorInChildren,+ children,+}) => (+ <li className="flex gap-3" data-sheet-step={n} data-step-label={label ?? undefined} data-done={done || undefined}>+ {label !== null && (+ <span+ aria-hidden="true"+ className={`shrink-0 mt-0.5 w-6 h-6 rounded-full inline-flex items-center justify-center text-[11px] font-semibold ${+ done ? 'bg-emerald-500/20 text-emerald-200 border border-emerald-500/40' : 'bg-zinc-800 text-zinc-200 border border-zinc-700'+ }`}+ >+ {done ? <Check size={12} /> : label}+ </span>+ )}+ <div className="min-w-0 flex-1 space-y-2">+ <p className="text-xs font-medium text-zinc-100">+ {label !== null && <span className="sr-only">Step {label}{done ? ', done' : ''}: </span>}+ {title}+ </p>+ {children}+ {error && !errorInChildren && (+ <p role="alert" className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200" data-sheet-error={n}>+ {error}+ </p>+ )}+ </div>+ </li>+);++export const ConnectSheet: React.FC<ConnectSheetProps> = ({ app, composio, kwants, spaceName, spaceMode, onClose, onDone, api = defaultConnectApi, phone, initial = {} }) => {+ const id = useId();+ const rootRef = useRef<HTMLDivElement>(null);+ const phoneLayout = usePhoneLayout();+ const isPhone = phone ?? phoneLayout;+ // Rendered into <body> once mounted, so it sits above Settings' own layer and the phone install hint.+ // The focus trap starts there too, on the element that stays.+ const [inBody, setInBody] = useState(false);+ useEffect(() => setInBody(true), []);+ useEscapeLayer(rootRef, inBody, onClose, { modal: true });++ // Composio set up already (or just now, if giving it to bots failed after): skip to the app.+ const [serverId, setServerId] = useState<string | null>(composio.added ? serverIdOf(composio.connection_id) : null);+ const ready = composio.added;+ const [opened, setOpened] = useState(!!initial.opened);+ const [url, setUrl] = useState(initial.url ?? '');+ const [key, setKey] = useState('');+ const [showKey, setShowKey] = useState(false);+ const [picked, setPicked] = useState<string[]>(initial.picked ?? []);+ const [pickedLoaded, setPickedLoaded] = useState(!ready || !!initial.picked);+ const [error, setError] = useState<{ step: 1 | 2 | 3; text: string } | null>(initial.error ? { step: 2, text: initial.error } : null);+ const [saving, setSaving] = useState(false);+ const [signingIn, setSigningIn] = useState(false);+ const [signInOpened, setSignInOpened] = useState(false);++ // Already set up: start from the bots that have Composio now (the sheet changes, not adds).+ useEffect(() => {+ if (!ready || !serverId || initial.picked) return;+ let live = true;+ api.botsWith(serverId, kwants.map((k) => k.id)).then(+ (ids) => live && (setPicked(ids), setPickedLoaded(true)),+ () => live && setPickedLoaded(true),+ );+ return () => {+ live = false;+ };+ }, [ready, serverId]); // eslint-disable-line react-hooks/exhaustive-deps++ const title = app ? `Connect ${app.name}` : ready ? 'Choose bots for Composio' : 'Set up Composio';+ const chosenBots = kwants.filter((k) => picked.includes(k.id));+ const approval = approvalLine(app?.acts ?? 'Send, post or change things', chosenBots, spaceMode);+ const toggle = (kid: string) => (setPicked((p) => (p.includes(kid) ? p.filter((x) => x !== kid) : [...p, kid])), setError((x) => (x?.step === 3 ? null : x)));++ const signIn = async () => {+ if (!app) return;+ const tab = typeof window !== 'undefined' && !inDesktopApp() ? window.open('', '_blank') : null;+ if (tab) tab.opener = null;+ setSigningIn(true);+ setError(null);+ try {+ const { redirect_url } = await api.connect(app.slug);+ if (tab) tab.location.href = redirect_url;+ else if (inDesktopApp()) window.location.assign(redirect_url);+ else window.open(redirect_url, '_blank', 'noopener,noreferrer');+ setSignInOpened(true);+ } catch (e) {+ tab?.close();+ // 409: Composio refused the saved key. Anything else (502, no answer) is Composio being down or slow.+ const keyRefused = (e as { status?: number } | null)?.status === 409;+ setError({+ step: 1,+ text: keyRefused+ ? `Composio refused your API key, so the ${app.name} sign-in can’t start here. Fix the key under Advanced › Manage tools, or sign in to ${app.name} on composio.dev.`+ : `Composio couldn’t be reached, so the ${app.name} sign-in didn’t open. Try again in a minute.`,+ });+ } finally {+ setSigningIn(false);+ }+ };++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ setError(null);+ let sid = serverId;+ if (!sid) {+ const body = composioBody(url, key, false);+ if ('error' in body) return setError({ step: 2, text: body.error });+ }+ if (picked.length === 0 && !ready) return setError({ step: 3, text: 'Tick at least one bot. Only the bots you tick can use it.' });+ setSaving(true);+ try {+ if (!sid) {+ const body = composioBody(url, key, false) as { url: string; api_key?: string; enabled: boolean };+ try {+ const r = await api.addComposio(body);+ sid = serverIdOf(r.connection_id);+ setServerId(sid);+ } catch (err) {+ setError({ step: 2, text: composioErrorText(err) });+ return;+ }+ if (!sid) return setError({ step: 2, text: 'Composio was added, but kwant bots didn’t say which server it is. Open Advanced to finish there.' });+ }+ try {+ await api.give(sid, kwants.map((k) => k.id), picked);+ } catch (err) {+ const why = errText(err).replace(/\.$/, '');+ setError({ step: 3, text: ready ? `Giving it to your bots didn’t work: ${why}. Try again.` : `Composio is added, but giving it to your bots didn’t work: ${why}. Try again.` });+ return;+ }+ onDone({ app, who: chosenBots.map((k) => k.name) });+ } finally {+ setSaving(false);+ }+ };++ const stepDone = (n: 1 | 2 | 3) =>+ n === 3 ? picked.length > 0 : n === 1 ? (ready ? signInOpened : opened) : ready || !!serverId || !('error' in composioBody(url, key, false));+ const stepProps = (n: 1 | 2 | 3) => ({ n, done: stepDone(n), error: error?.step === n ? error.text : null });++ const panel = isPhone+ ? 'absolute inset-x-0 bottom-0 max-h-[92vh] rounded-t-2xl border-t'+ : 'absolute right-0 top-0 h-full w-full max-w-[460px] border-l';++ const sheet = (+ <div className="fixed inset-0 z-[60]" data-connect-sheet={app?.slug ?? 'composio'}>+ <div className="absolute inset-0 bg-black/60" aria-hidden="true" onClick={onClose} />+ <div ref={rootRef} role="dialog" aria-modal="true" aria-labelledby={`${id}-t`} tabIndex={-1} className={`${panel} flex flex-col focus:outline-none bg-zinc-900 border-zinc-800 shadow-2xl`}>+ {isPhone && <span aria-hidden="true" className="mx-auto mt-2 h-1 w-10 rounded-full bg-zinc-700" />}+ <div className="flex items-start gap-3 px-4 sm:px-5 pt-4 pb-3 border-b border-zinc-800">+ {app ? <AppMark name={app.name} tint={app.tint} /> : <AppMark name="Composio" />}+ <div className="min-w-0 flex-1">+ <h2 id={`${id}-t`} className="text-sm font-semibold text-zinc-100">+ {title}+ </h2>+ <p className="text-[11px] text-zinc-400">{!ready ? 'Takes about 2 minutes' : app ? 'Composio is set up, so this takes a minute' : 'Picked bots can use every app on your Composio'}</p>+ </div>+ <button type="button" onClick={onClose} aria-label="Close" className="inline-flex items-center justify-center w-11 h-11 sm:w-8 sm:h-8 -mr-2 sm:-mr-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">+ <X size={17} />+ </button>+ </div>++ <form onSubmit={submit} noValidate className="flex-1 min-h-0 flex flex-col" aria-label={title}>+ <div className="flex-1 min-h-0 overflow-y-auto px-4 sm:px-5 py-4 space-y-4">+ <div className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-3 space-y-2" data-sheet-can>+ <p className="text-xs font-medium text-zinc-200">Your bots will be able to</p>+ <ul className="space-y-1">+ {(app?.can ?? ['Use the apps you connect on Composio']).map((c) => (+ <li key={c} className="flex items-start gap-2 text-xs text-zinc-300">+ <Check size={13} className="mt-px shrink-0 text-emerald-400" aria-hidden="true" />+ {c}+ </li>+ ))}+ <li className={`flex items-start gap-2 text-xs ${approval.tone === 'ok' ? 'text-zinc-300' : 'text-amber-200'}`} data-sheet-approval={approval.tone}>+ <span aria-hidden="true" className={`mt-1 shrink-0 w-2 h-2 rounded-full ${approval.tone === 'ok' ? 'bg-sky-400' : 'bg-amber-400'}`} />+ {approval.text}+ </li>+ </ul>+ <p className="text-[11px] text-zinc-400">+ Through Composio, a service with a free plan. {app ? `Your ${app.name} sign-in stays on Composio’s servers, not in kwant bots.` : 'Your app sign-ins stay on Composio’s servers, not in kwant bots.'}+ </p>+ </div>++ <ol className="space-y-4" aria-label="Steps">+ {ready ? (+ app && (+ <Step {...stepProps(1)} title={`Sign in to ${app.name}`}>+ {composio.can_connect ? (+ <>+ <p className="text-[11px] text-zinc-400">Opens {app.name}’s own sign-in on Composio {inDesktopApp() ? 'in your browser' : 'in a new tab'}. Come back here when it says you’re connected.</p>+ <button type="button" className={quietBtn} onClick={signIn} disabled={signingIn} data-sheet-signin>+ {signingIn ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ExternalLink size={12} aria-hidden="true" />}+ {signInOpened ? `Open ${app.name} sign-in again` : `Sign in to ${app.name}`}+ </button>+ {signInOpened && <p className="text-[11px] text-emerald-200">Opened. Finish there, then choose the bots below.</p>}+ </>+ ) : (+ <p className="text-[11px] text-zinc-400">+ On{' '}+ <a href={COMPOSIO_HOME} target="_blank" rel="noopener noreferrer" className="text-sky-300 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 rounded">+ composio.dev ↗+ </a>+ , add {app.name} to the same MCP server you gave kwant bots and sign in there.{' '}+ {composio.can_search+ ? 'kwant bots can’t open this sign-in for you with your Composio link, so sign in there.'+ : 'To sign in from here instead, add your Composio API key under Advanced › Manage tools.'}+ </p>+ )}+ </Step>+ )+ ) : (+ <>+ <Step {...stepProps(1)} title="Make a free Composio account">+ <p className="text-[11px] text-zinc-400">+ Sign up, then {app ? `add ${app.name} and sign in to it there` : 'add the apps you want and sign in to them there'}. Composio keeps that sign-in for your bots.+ </p>+ <a href={COMPOSIO_HOME} target="_blank" rel="noopener noreferrer" className={quietBtn} onClick={() => setOpened(true)} data-sheet-open-composio>+ Open Composio <ExternalLink size={12} aria-hidden="true" />+ <span className="sr-only">(opens in a new tab)</span>+ </a>+ </Step>+ <Step {...stepProps(2)} errorInChildren title="Paste your Composio link">+ <label htmlFor={`${id}-url`} className="sr-only">+ Composio MCP link+ </label>+ <input+ id={`${id}-url`}+ className={field}+ type="url"+ inputMode="url"+ autoComplete="off"+ spellCheck={false}+ placeholder="https://backend.composio.dev/v3/mcp/…"+ value={url}+ onChange={(e) => (setUrl(e.target.value), setError((x) => (x?.step === 2 ? null : x)))}+ aria-describedby={error?.step === 2 ? `${id}-url-e ${id}-url-h` : `${id}-url-h`}+ aria-invalid={error?.step === 2 ? true : undefined}+ disabled={!!serverId}+ />+ {error?.step === 2 && (+ <p id={`${id}-url-e`} role="alert" className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200" data-sheet-error={2}>+ {error.text}+ </p>+ )}+ <p id={`${id}-url-h`} className="text-[11px] text-zinc-400">+ In Composio, open <span className="text-zinc-200">MCP</span> in the left menu, pick your server (or create one with {app ? app.name : 'your apps'}), and copy its URL. It starts with https:// and is on composio.dev.+ </p>+ {showKey ? (+ <div className="space-y-1">+ <label htmlFor={`${id}-key`} className="block text-[11px] font-medium text-zinc-300">+ Composio API key <span className="font-normal text-zinc-500">(optional)</span>+ </label>+ <input id={`${id}-key`} className={field} type="password" autoComplete="off" value={key} onChange={(e) => setKey(e.target.value)} />+ <p className="text-[11px] text-zinc-500">Lets you find and sign in to apps from kwant bots. Kept on this computer and never shown again.</p>+ </div>+ ) : (+ <button type="button" className={linkBtn} onClick={() => setShowKey(true)}>+ Add your API key too (optional)+ </button>+ )}+ </Step>+ </>+ )}+ <Step {...stepProps(3)} label={ready ? (app ? 2 : null) : 3} title="Which bots get it?">+ {!pickedLoaded ? (+ <p className="flex items-center gap-2 text-[11px] text-zinc-400">+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Checking which bots have it…+ </p>+ ) : kwants.length === 0 ? (+ <p className="text-[11px] text-zinc-400">{spaceName} has no bots yet. Make one first, then come back.</p>+ ) : (+ <fieldset>+ <legend className="sr-only">Bots in {spaceName}</legend>+ <div className="flex flex-wrap gap-2">+ {kwants.map((k) => {+ const on = picked.includes(k.id);+ return (+ <label+ key={k.id}+ data-sheet-bot={k.id}+ className={`inline-flex items-center gap-2 min-h-[44px] sm:min-h-[32px] px-3 rounded-full border text-xs cursor-pointer focus-within:outline focus-within:outline-2 focus-within:outline-sky-500 ${+ on ? 'border-sky-500/60 bg-sky-500/15 text-zinc-100' : 'border-zinc-700 bg-zinc-800/60 text-zinc-300 hover:border-zinc-600'+ }`}+ >+ <input type="checkbox" className="accent-sky-500" checked={on} onChange={() => toggle(k.id)} />+ <span aria-hidden="true" className="inline-flex">+ <ModernAvatar role={k.avatar_sprite} name={k.name} size={20} kwantId={k.id} />+ </span>+ {k.name}+ </label>+ );+ })}+ </div>+ </fieldset>+ )}+ <p className="text-[11px] text-zinc-400">+ {picked.length === 0 ? (ready ? 'No bot has it. Tick the ones that should.' : 'None until you tick one.') : `${listNames(chosenBots.map((k) => k.name))} ${chosenBots.length === 1 ? 'gets' : 'get'} it, turned on.`}+ </p>+ <p className="text-[11px] text-zinc-300" data-sheet-one-connection>+ Composio is one connection: the bots you tick can use every app on it{app ? `, not only ${app.name}` : ''}.+ </p>+ </Step>+ </ol>+ </div>+ <div className="flex flex-wrap gap-2 px-4 sm:px-5 py-3 border-t border-zinc-800 bg-zinc-900" style={isPhone ? { paddingBottom: 'max(0.75rem, env(safe-area-inset-bottom))' } : undefined}>+ <button type="submit" className={`${primaryBtn} ${isPhone ? 'flex-1' : ''}`} disabled={saving || !pickedLoaded} data-sheet-submit>+ {saving && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {ready ? 'Save' : title}+ </button>+ <button type="button" className={quietBtn} onClick={onClose}>+ Cancel+ </button>+ </div>+ </form>+ </div>+ </div>+ );+ return inBody ? createPortal(sheet, document.body) : sheet;+};++// ── The page ─────────────────────────────────────────────────────────────────────────────────++export interface AppsAccountsProps {+ spaceName: string;+ spaceMode?: string;+ kwants: Kwant[];+ /** Where to open: the top, AI accounts, or with Advanced open. */+ section?: AppsSection;+ /** Changes when the same section is asked for again, to scroll there again. */+ sectionSeq?: number;+ /** Bumped to open "Sign in with Claude" (it's inside Manage AI accounts). */+ focusClaudeSignIn?: number;+ /** Opens Advanced (a bot's tool note was asked for). */+ openAdvanced?: boolean;+ /** Sign-ins and settings: each AI's sign-in, install and API keys (the old Accounts tab, without its order).+ * Gets the page's own engines and accounts, so both stay in step. */+ manageAccounts: (shared: { engines: EnginesApi; accounts: ProfilesState }) => React.ReactNode;+ /** Every fresh accounts list, so bot pickers stay current. */+ onProfilesChanged?: (profiles: Profile[]) => void;+ /** Advanced: tool servers, Telegram and notes from bots (the old Connections list); gets Composio's "Choose bots". */+ advanced: (chooseComposioBots: () => void) => React.ReactNode;+ onNewBot?: () => void;+ /** Tests and screenshots. */+ data?: ConnectionsList | null;+ profiles?: Profile[] | null;+ engines?: EngineInfo[] | null;+ connectApi?: ConnectApi;+ /** Tests: whether Composio has a sign-in for an app (default: ask Composio). */+ appStatus?: (slug: string) => Promise<{ connected: boolean }>;+ initialSheet?: { slug: string | null; initial?: ConnectSheetProps['initial'] };+ phone?: boolean;+}++// An older server (or an empty reply) may leave out a list; treat it as empty rather than crash.+const tidyList = (d: Partial<ConnectionsList> | null | undefined): ConnectionsList =>+ ({ ...(d && !Array.isArray(d) ? d : {}), connections: Array.isArray(d?.connections) ? d!.connections : [], catalog: Array.isArray(d?.catalog) ? d!.catalog : [] }) as ConnectionsList;++type Load = { state: 'loading' } | { state: 'error'; text: string } | { state: 'token' } | { state: 'ok'; data: ConnectionsList };++export const AppsAccounts: React.FC<AppsAccountsProps> = (p) => {+ const [load, setLoad] = useState<Load>(p.data ? { state: 'ok', data: tidyList(p.data) } : { state: 'loading' });+ const profilesHook = useProfiles(p.profiles === undefined, p.onProfilesChanged);+ const profiles = p.profiles !== undefined ? p.profiles : profilesHook.profiles;+ const enginesHook = useEngines(p.engines === undefined);+ const engines = p.engines !== undefined ? p.engines : enginesHook.engines;+ const accountsState: ProfilesState = p.profiles !== undefined ? { profiles: p.profiles, error: null, reload: async () => {} } : profilesHook;+ const enginesState: EnginesApi = p.engines !== undefined ? { ...enginesHook, engines: p.engines } : enginesHook;+ const [sheet, setSheet] = useState<{ app: AppTile | null; initial?: ConnectSheetProps['initial'] } | null>(+ p.initialSheet ? { app: p.initialSheet.slug ? tileFor(APP_TILES.find((t) => t.slug === p.initialSheet!.slug) ?? { slug: p.initialSheet.slug, name: p.initialSheet.slug }) : null, initial: p.initialSheet.initial } : null,+ );+ // ok: earned (the app is signed in). info: true but not the whole story yet (neutral, not green).+ const [notice, setNotice] = useState<{ text: string; tone: 'ok' | 'info' } | null>(null);+ const [manageOpen, setManageOpen] = useState(!!p.focusClaudeSignIn);+ const [advancedOpen, setAdvancedOpen] = useState(p.section === 'advanced' || !!p.openAdvanced);+ const [connectedApps, setConnectedApps] = useState<Record<string, boolean>>({});+ const accountsRef = useRef<HTMLElement>(null);+ const manageRef = useRef<HTMLDetailsElement>(null);+ const advancedRef = useRef<HTMLDetailsElement>(null);+ const alive = useRef(true);+ const fixed = p.data !== undefined;++ const reload = useCallback(async (): Promise<ConnectionsList | null> => {+ if (fixed) return p.data ? tidyList(p.data) : null;+ try {+ const data = tidyList(await connectionsApi.list());+ if (alive.current) setLoad({ state: 'ok', data });+ return data;+ } catch (e) {+ if (!alive.current) return null;+ if (e instanceof ConnectionsError && e.status === 401) setLoad({ state: 'token' });+ else setLoad({ state: 'error', text: errText(e) });+ return null;+ }+ }, [fixed]); // eslint-disable-line react-hooks/exhaustive-deps++ useEffect(() => {+ alive.current = true;+ reload();+ window.addEventListener(PERSON_SIGNED_IN_EVENT, reload);+ return () => {+ alive.current = false;+ window.removeEventListener(PERSON_SIGNED_IN_EVENT, reload);+ };+ }, [reload]);++ // Opened at a section: scroll there once it's drawn.+ useEffect(() => {+ if (p.section === 'accounts') accountsRef.current?.scrollIntoView({ block: 'start' });+ if (p.section === 'advanced' || p.openAdvanced) (setAdvancedOpen(true), advancedRef.current?.scrollIntoView({ block: 'start' }));+ }, [p.section, p.sectionSeq, p.openAdvanced, load.state === 'ok']); // eslint-disable-line react-hooks/exhaustive-deps++ useEffect(() => {+ if (!p.focusClaudeSignIn) return;+ setManageOpen(true);+ manageRef.current?.scrollIntoView({ block: 'start' });+ }, [p.focusClaudeSignIn]);++ const data = load.state === 'ok' ? load.data : null;+ const composio = data?.catalog.find((e) => e.id === 'composio');++ // Which tiles are signed in on Composio: only when kwant can ask (the link names a user).+ useEffect(() => {+ if (fixed || !composio?.added || !composio.can_connect) return;+ let live = true;+ APP_TILES.forEach((t) =>+ connectionsApi.composioAppStatus(t.slug).then(+ (r) => live && setConnectedApps((m) => ({ ...m, [t.slug]: r.connected })),+ () => undefined,+ ),+ );+ return () => {+ live = false;+ };+ }, [fixed, composio?.added, composio?.can_connect]);++ // The server names bots on auto on every engine's main account; `pinnedOnly` keeps the bots pinned to an engine.+ const usedByOf = (profileId: string, pinnedOnly = false) =>+ (data?.connections.find((c) => c.id === `account:${profileId}`)?.used_by ?? [])+ .filter((u) => {+ const bot = p.kwants.find((k) => k.id === u.id);+ return !pinnedOnly || !bot || parsePick(bot.preferred_model).family !== 'auto';+ })+ .map((u) => u.name);+ const needs = data ? data.connections.filter((c) => accountNeedsYou(c)).length : 0;+ /** Opens "Sign-ins and settings", at one AI's card when given: its existing sign-in or set-up. */+ const openManage = (engineCard?: string) => {+ setManageOpen(true);+ window.setTimeout(() => {+ const card = engineCard ? manageRef.current?.querySelector<HTMLElement>(`[data-engine="${CSS.escape(engineCard)}"]`) : null;+ (card ?? manageRef.current)?.scrollIntoView({ behavior: 'smooth', block: 'start' });+ card?.querySelector<HTMLElement>('button:not([disabled]), a[href]')?.focus({ preventScroll: true });+ }, 50);+ };+ const reloadAccounts = async () => {+ await Promise.all([accountsState.reload(), enginesState.reload(), reload()]);+ };++ /** What to say after a connect: only "Gmail is on for Ann." once Composio confirms a Gmail sign-in (F1). */+ const doneNotice = async (app: AppTile | null, who: string[]) => {+ const fresh = await reload();+ if (!alive.current) return;+ if (!who.length) return setNotice({ text: 'No bot has Composio now.', tone: 'info' });+ const names = listNames(who);+ if (!app) return setNotice({ text: `Composio is on for ${names}.`, tone: 'info' });+ const entry = fresh?.catalog.find((e) => e.id === 'composio') ?? composio;+ let signedIn = false;+ if (entry?.can_connect) {+ try {+ signedIn = (await (p.appStatus ?? connectionsApi.composioAppStatus)(app.slug)).connected;+ if (alive.current) setConnectedApps((m) => ({ ...m, [app.slug]: signedIn }));+ } catch {+ signedIn = false;+ }+ }+ if (!alive.current) return;+ const user = who.length === 1 ? names : 'They';+ setNotice(+ signedIn+ ? { text: `${app.name} is on for ${names}.`, tone: 'ok' }+ : { text: `Composio is on for ${names}. ${user} can use ${app.name} once you’ve signed in to ${app.name} on Composio.`, tone: 'info' },+ );+ };++ const openApp = (app: AppTile | null) => {+ setNotice(null);+ setSheet({ app });+ };++ const searchApi = {+ search: connectionsApi.searchComposioApps,+ connect: connectionsApi.connectComposioApp,+ };++ return (+ <div className="space-y-6" data-apps-accounts>+ <p className="text-xs text-zinc-400">+ The apps your bots can use, and the AI they think with.+ </p>++ <div role="status" aria-live="polite">+ {notice && (+ <p+ className={`flex items-start gap-2 px-3 py-2 rounded-lg border text-xs ${+ notice.tone === 'ok' ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-100' : 'border-zinc-700 bg-zinc-900/60 text-zinc-200'+ }`}+ data-apps-notice={notice.tone}+ >+ {notice.tone === 'ok' ? <Check size={14} className="mt-px shrink-0" aria-hidden="true" /> : <Info size={14} className="mt-px shrink-0 text-zinc-400" aria-hidden="true" />}+ {notice.text}+ </p>+ )}+ </div>++ {load.state === 'error' && (+ <div role="alert" className="flex flex-wrap items-center gap-2 px-3 py-2.5 rounded-xl border border-rose-500/30 bg-rose-500/10 text-xs text-rose-200" data-apps-error>+ <AlertTriangle size={14} className="shrink-0" aria-hidden="true" />+ <span className="flex-1 min-w-0">Couldn’t load your apps and accounts. {load.text}</span>+ <button type="button" className={quietBtn} onClick={() => (setLoad({ state: 'loading' }), reload())}>+ <RefreshCw size={12} aria-hidden="true" /> Try again+ </button>+ </div>+ )}+ {load.state === 'token' && (+ <div className="flex flex-wrap items-center gap-2 px-3 py-2.5 rounded-xl border border-amber-500/30 bg-amber-500/10 text-xs text-amber-100" data-apps-token>+ <span className="flex-1 min-w-0">Only you can see apps and accounts. Confirm it’s you to see them.</span>+ <button type="button" className={quietBtn} onClick={requestPersonToken}>+ Confirm it’s you+ </button>+ </div>+ )}++ {/* Apps */}+ <section aria-labelledby="apps-title" className="space-y-3" data-apps-tiles>+ <div className="flex items-baseline justify-between gap-2">+ <h3 id="apps-title" className={sectionTitle}>+ Apps+ </h3>+ {composio?.added && <span className="text-[11px] text-zinc-500">Through Composio</span>}+ </div>+ <ul className="grid grid-cols-2 sm:grid-cols-3 gap-2" aria-busy={load.state === 'loading'}>+ {APP_TILES.map((t) => {+ const connected = connectedApps[t.slug];+ // Composio is added but kwant can't ask it (no key or no user_id): it may be signed in, we can't tell.+ const unknowable = !connected && !!composio?.added && !composio.can_connect;+ return (+ <li key={t.slug}>+ <button+ type="button"+ data-app-tile={t.slug}+ disabled={!composio}+ onClick={() => openApp(t)}+ className="w-full h-full min-h-[88px] flex flex-col items-start gap-2 p-3 rounded-xl border border-zinc-800 bg-zinc-900/60 text-left hover:border-zinc-600 hover:bg-zinc-900 transition-colors disabled:opacity-60 disabled:cursor-default focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <span className="flex items-center gap-2 w-full min-w-0">+ <AppMark name={t.name} size={30} tint={t.tint} />+ <span className="min-w-0">+ <span className="block text-xs font-medium text-zinc-100 truncate">{t.name}</span>+ <span className="block text-[11px] text-zinc-500 line-clamp-2" title={t.blurb}>{t.blurb}</span>+ </span>+ </span>+ <span className={`mt-auto text-[11px] font-medium ${connected ? 'text-emerald-300' : unknowable ? 'text-zinc-300' : 'text-sky-300'}`} data-tile-state={connected ? 'connected' : unknowable ? 'unknown' : 'connect'}>+ {load.state === 'loading' ? 'Checking…' : connected ? '✓ Connected · Choose bots' : unknowable ? 'Sign in or choose bots' : 'Connect'}+ <span className="sr-only"> {t.name}</span>+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ {data && !composio && <p className="text-[11px] text-zinc-400">This server can’t connect apps yet. Update kwant bots to connect them here.</p>}+ </section>++ {/* Find any other app */}+ {composio && (+ <section aria-labelledby="apps-find" className="space-y-2" data-apps-search>+ <h3 id="apps-find" className={sectionTitle}>+ Another app+ </h3>+ {composio.added ? (+ <ComposioAppSearch+ entry={composio}+ api={searchApi}+ onPick={(a: ComposioApp) => openApp(tileFor(a))}+ />+ ) : (+ <p className="text-[11px] text-zinc-400">+ Composio has hundreds more, like Figma, Linear or HubSpot.{' '}+ <button type="button" className={linkBtn} onClick={() => openApp(null)} data-apps-setup-composio>+ Set up Composio+ </button>{' '}+ and you can search them here.+ </p>+ )}+ </section>+ )}++ {/* AI accounts */}+ <section ref={accountsRef} aria-labelledby="apps-ai" className="space-y-2 scroll-mt-4" data-ai-accounts>+ <div className="flex items-baseline justify-between gap-2">+ <h3 id="apps-ai" className={sectionTitle}>+ AI accounts+ </h3>+ {needs > 0 && (+ <span className="text-[11px] font-medium text-amber-300" data-ai-needs>+ {needs} {needs === 1 ? 'needs' : 'need'} you+ </span>+ )}+ </div>+ {!profiles || (load.state === 'loading' && !data) ? (+ <div className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3 space-y-2" aria-hidden="true" data-ai-loading>+ <div className="h-3 w-40 rounded bg-zinc-800 animate-pulse motion-reduce:animate-none" />+ <div className="h-3 w-56 rounded bg-zinc-800 animate-pulse motion-reduce:animate-none" />+ </div>+ ) : (+ <div className="rounded-xl border border-zinc-800 bg-zinc-900/60 p-3">+ <AccountPriority+ profiles={profiles}+ engines={engines}+ spaceName={p.spaceName}+ usedBy={usedByOf}+ onChanged={reloadAccounts}+ onSignIn={(a) => openManage(cardOf(a))}+ onSetUp={(a) => openManage(cardOf(a))}+ onAddAccount={() => openManage()}+ onEngineOn={(id) => enginesState.setEnabled(id, true)}+ onEngineOff={(id) => enginesState.setEnabled(id, false)}+ />+ </div>+ )}+ <details+ ref={manageRef}+ open={manageOpen}+ onToggle={(e) => setManageOpen((e.target as HTMLDetailsElement).open)}+ className="group rounded-xl border border-zinc-800 scroll-mt-4"+ data-manage-accounts+ >+ <summary className="flex items-center gap-2 min-h-[44px] px-3 cursor-pointer list-none text-xs font-medium text-zinc-300 hover:text-zinc-100 rounded-xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">+ <ChevronRight size={14} className="transition-transform group-open:rotate-90 motion-reduce:transition-none" aria-hidden="true" />+ Sign-ins and settings+ <span className="font-normal text-zinc-500">· add an account or an API key</span>+ </summary>+ {manageOpen && <div className="px-3 pb-3 space-y-3">{p.manageAccounts({ engines: enginesState, accounts: accountsState })}</div>}+ </details>+ </section>++ {/* Advanced */}+ <details+ ref={advancedRef}+ open={advancedOpen}+ onToggle={(e) => setAdvancedOpen((e.target as HTMLDetailsElement).open)}+ className="group rounded-xl border border-zinc-800 scroll-mt-4"+ data-apps-advanced+ >+ <summary className="flex items-center gap-2 min-h-[44px] px-3 cursor-pointer list-none rounded-xl focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">+ <ChevronRight size={14} className="shrink-0 text-zinc-400 transition-transform group-open:rotate-90 motion-reduce:transition-none" aria-hidden="true" />+ <span className="min-w-0">+ <span className="block text-xs font-medium text-zinc-200">Advanced</span>+ <span className="block text-[11px] text-zinc-500">Tool servers (MCP), Telegram, notes from bots, and where logins are kept</span>+ </span>+ </summary>+ {advancedOpen && <div className="px-1 sm:px-3 pb-3" data-settings-connections>{p.advanced(() => void reload().then(() => openApp(null)))}</div>}+ </details>++ {sheet && composio && (+ <ConnectSheet+ app={sheet.app}+ composio={composio}+ kwants={p.kwants}+ spaceName={p.spaceName}+ spaceMode={p.spaceMode}+ api={p.connectApi}+ phone={p.phone}+ initial={sheet.initial}+ onClose={() => setSheet(null)}+ onDone={({ app, who }) => {+ setSheet(null);+ void doneNotice(app, who);+ }}+ />+ )}+ </div>+ );+};++export type { Connection };+export { GiveError };diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsxindex 9e656f51..24e6cb36 100644--- a/frontend/src/components/ConnectionsView.tsx+++ b/frontend/src/components/ConnectionsView.tsx@@ -202,7 +202,9 @@ export const ComposioAppSearch: React.FC<{api?: ComposioSearchApi;/** Tests show results without searching. */initialApps?: ComposioApp[];-}> = ({ entry, api = { search: connectionsApi.searchComposioApps, connect: connectionsApi.connectComposioApp }, initialApps }) => {+ /** Apps & accounts: "Connect" opens the Connect sheet for this app instead of its sign-in. */+ onPick?: (app: ComposioApp) => void;+}> = ({ entry, api = { search: connectionsApi.searchComposioApps, connect: connectionsApi.connectComposioApp }, initialApps, onPick }) => {const id = useId();const [q, setQ] = useState('');const [apps, setApps] = useState<ComposioApp[] | null>(initialApps ?? null);@@ -215,7 +217,7 @@ export const ComposioAppSearch: React.FC<{if (!entry.can_search) {return (<p className="text-[11px] text-zinc-400" data-composio-search="needs-key">- To find apps from here, add your Composio API key as the <code className="text-zinc-300">x-api-key</code> header of the Composio server in Tools.+ To search apps here, add your Composio API key to the Composio server under Advanced › Manage tools (as the header <code className="text-zinc-300">x-api-key</code>).</p>);}@@ -279,7 +281,7 @@ export const ComposioAppSearch: React.FC<{Find</button></form>- {!canConnect && (+ {!canConnect && !onPick && (<p className="text-[11px] text-zinc-400">Your Composio URL has no <code className="text-zinc-300">user_id</code>, so connect apps on composio.dev. If your Composio server lists fixed apps, add the app to it there too.</p>@@ -308,7 +310,11 @@ export const ComposioAppSearch: React.FC<{{a.no_auth ? 'No sign-in needed' : 'Sign-in kept on Composio'}</p></div>- {canConnect && !a.no_auth && (+ {onPick ? (+ <button type="button" className={quietBtn} onClick={() => onPick(a)} data-composio-pick={a.slug}>+ Connect<span className="sr-only"> {a.name}</span>+ </button>+ ) : canConnect && !a.no_auth && (<button type="button" className={quietBtn} disabled={connecting !== null} onClick={() => connect(a)}>{connecting === a.slug ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ExternalLink size={12} aria-hidden="true" />}Connect<span className="sr-only"> {a.name} on Composio (opens in a new tab)</span>@@ -328,6 +334,8 @@ export interface ComposioCardProps {initialOpen?: boolean;onAdd: (url: string, apiKey: string, enabled: boolean) => Promise<string | null>;onOpenTools?: () => void;+ /** Apps & accounts: "Choose bots" opens the Connect sheet (picking bots turns it on). */+ onChooseBots?: () => void;/** Tests: the search box's API and starting results. */searchApi?: ComposioSearchApi;initialApps?: ComposioApp[];@@ -336,7 +344,7 @@ export interface ComposioCardProps {}/** The optional Composio connector: what it is, where it keeps sign-ins, and the add form. */-export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen = false, onAdd, onOpenTools, searchApi, initialApps, openRequest = 0 }) => {+export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen = false, onAdd, onOpenTools, onChooseBots, searchApi, initialApps, openRequest = 0 }) => {const id = useId();const [open, setOpen] = useState(initialOpen);const cardRef = useRef<HTMLLIElement>(null);@@ -387,7 +395,12 @@ export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen =<Plus size={12} aria-hidden="true" /> Add {entry.name}</button>)}- {entry.added && onOpenTools && (+ {entry.added && onChooseBots && (+ <button type="button" className={quietBtn} onClick={onChooseBots} data-composio-choose-bots>+ {entry.enabled ? 'Choose bots' : 'Choose bots to turn it on'}+ </button>+ )}+ {entry.added && !onChooseBots && onOpenTools && (<button type="button" className={quietBtn} onClick={onOpenTools}>{entry.enabled ? 'Manage in Tools' : 'Turn on in Tools'}</button>@@ -591,6 +604,10 @@ export interface ConnectionsViewProps extends ManageLinks {/** Tests and screenshots: the Notes from bots section's api and starting state. */notes?: Partial<ToolNotesSectionProps>;phone?: boolean;+ /** Apps & accounts' Advanced: AI accounts have their own section there, so their group is left out. */+ hideAccounts?: boolean;+ /** Apps & accounts' Advanced: Composio's "Choose bots" (instead of "Turn on in Tools"). */+ onChooseComposioBots?: () => void;}export const ConnectionsView: React.FC<ConnectionsViewProps> = ({@@ -617,6 +634,8 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({onOpenNoteWhere,notes: notesProps = {},phone,+ hideAccounts = false,+ onChooseComposioBots,...links}) => {const phoneLayout = usePhoneLayout();@@ -629,7 +648,7 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({setNoteScroll((n) => n + 1);}};- const groups = data ? groupConnections(data.connections) : [];+ const groups = data ? groupConnections(data.connections).filter((g) => !(hideAccounts && g.key === 'account')) : [];const vault = data?.vault;const [composioRequest, setComposioRequest] = useState(0);const hasComposio = !!data?.catalog.some((e) => e.id === 'composio');@@ -789,6 +808,7 @@ export const ConnectionsView: React.FC<ConnectionsViewProps> = ({initialOpen={composioOpen}onAdd={onAddComposio}onOpenTools={links.onOpenTools}+ onChooseBots={entry.id === 'composio' ? onChooseComposioBots : undefined}openRequest={entry.id === 'composio' ? composioRequest : 0}/>))}@@ -809,9 +829,11 @@ export interface ConnectionsPageProps extends ManageLinks {focusNote?: string | null;onClearFocusNote?: () => void;onOpenNoteWhere?: ToolNotesSectionProps['onOpenWhere'];+ hideAccounts?: boolean;+ onChooseComposioBots?: () => void;}-export const ConnectionsPage: React.FC<ConnectionsPageProps> = ({ onBack, embedded, focusNote, onClearFocusNote, onOpenNoteWhere, ...links }) => {+export const ConnectionsPage: React.FC<ConnectionsPageProps> = ({ onBack, embedded, focusNote, onClearFocusNote, onOpenNoteWhere, hideAccounts, onChooseComposioBots, ...links }) => {const [data, setData] = useState<ConnectionsList | null>(null);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);@@ -891,7 +913,14 @@ export const ConnectionsPage: React.FC<ConnectionsPageProps> = ({ onBack, embeddconst addComposio = async (url: string, apiKey: string, enabled: boolean): Promise<string | null> => {try {await connectionsApi.addComposio(apiKey ? { url, api_key: apiKey, enabled } : { url, enabled });- setNotice({ text: enabled ? 'Composio is added and on.' : 'Composio is added and off. Turn it on in Tools when you want bots to use it.', error: false });+ setNotice({+ text: enabled+ ? 'Composio is added and on.'+ : onChooseComposioBots+ ? 'Composio is added. Choose the bots that get it to turn it on.'+ : 'Composio is added and off. Turn it on in Tools when you want bots to use it.',+ error: false,+ });load();return null;} catch (e) {@@ -920,6 +949,8 @@ export const ConnectionsPage: React.FC<ConnectionsPageProps> = ({ onBack, embeddonClearFocusNote={onClearFocusNote}onOpenNoteWhere={onOpenNoteWhere}onNotesChanged={quietLoad}+ hideAccounts={hideAccounts}+ onChooseComposioBots={onChooseComposioBots}{...links}/>{unlocking && (diff --git a/frontend/src/components/EngineAccounts.tsx b/frontend/src/components/EngineAccounts.tsxindex 89ac9d2f..4620578e 100644--- a/frontend/src/components/EngineAccounts.tsx+++ b/frontend/src/components/EngineAccounts.tsx@@ -7,7 +7,6 @@ import {CUSTOM_PRESETS,customKeyRequired,CustomProtocol,- KIND_LABELS,Login,NewAccountSpec,PROTOCOLS,@@ -61,6 +60,12 @@ export interface RowStatus {detail: string | null;}+/** The built-in login's title: "Signed in" only when it's on and signed in, so it never sits beside "Needs sign-in". */+export function systemTitle(p: Profile, status: RowStatus): string {+ const signedIn = p.enabled && (status.label === 'Ready' || status.label === 'In use' || status.label.startsWith('Out until'));+ return signedIn ? 'Signed in on this computer' : 'On this computer';+}+/** "This machine" is the engine's own login, so its state comes from the engine's check; Off wins either way. */export function accountStatus(p: Profile, engine: EngineInfo, now = Date.now()): RowStatus {if (engine.enabled === false || engine.status === 'disabled') return { tone: 'muted', label: 'Off', detail: `Not checked while ${engine.name} is off` };@@ -557,7 +562,7 @@ const AccountRow: React.FC<{const off = status.label === 'Off';const isClaude = p.engine === 'claude';const kindText = isSystem- ? `The ${engine.name.replace(/ CLI$/, '')} login on this computer`+ ? `Your ${engine.name.replace(/ CLI$/, '')} login`: isCustom? customKindText(p): p.kind === 'api_key'@@ -604,8 +609,8 @@ const AccountRow: React.FC<{</form>) : (<span className="inline-flex items-center gap-1 min-w-0">- <span id={nameId} className={`text-xs font-semibold truncate max-w-[12rem] ${off ? 'text-zinc-400' : 'text-zinc-100'}`}>- {isSystem ? KIND_LABELS.system : p.name}+ <span id={nameId} className={`text-xs font-semibold ${isSystem ? 'break-words' : 'truncate max-w-[12rem]'} ${off ? 'text-zinc-400' : 'text-zinc-100'}`}>+ {isSystem ? systemTitle(p, status) : p.name}</span>{!isSystem && (<button@@ -658,7 +663,7 @@ const AccountRow: React.FC<{<Switchon={p.enabled}disabled={busy}- label={`Use ${isSystem ? KIND_LABELS.system : p.name} for bots`}+ label={isSystem ? `Use ${engine.name.replace(/ CLI$/, '')} on this computer for bots` : `Use ${p.name} for bots`}onChange={(on) => run(() => profilesApi.update(p.id, { enabled: on }))}/></div>diff --git a/frontend/src/components/EnginesPanel.tsx b/frontend/src/components/EnginesPanel.tsxindex 6f47ad11..85c02e67 100644--- a/frontend/src/components/EnginesPanel.tsx+++ b/frontend/src/components/EnginesPanel.tsx@@ -42,7 +42,7 @@ const withCode = (text: string) =>const summaryAccounts = (accounts: Profile[], now: number) =>accounts.map((p) => {const limit = activeLimit(p.limited_until, now);- return { name: p.kind === 'system' ? 'This machine' : p.name, usable: accountUsable(p, now), is_default: p.is_default, priority: p.priority, outUntil: limit ? formatUntil(limit, now) : null };+ return { name: p.kind === 'system' ? 'the sign-in on this computer' : p.name, usable: accountUsable(p, now), is_default: p.is_default, priority: p.priority, outUntil: limit ? formatUntil(limit, now) : null };});/** One engine: its status, switch and models up top, and the accounts it can run on underneath. */@@ -214,12 +214,14 @@ export const RouteSummary: React.FC<{ rows: RouteRow[]; pending: boolean }> = ({/** Settings → "Engines & accounts": one card per engine with the accounts it runs on, ready ones first.* `focusClaudeSignIn` changes to bring "Sign in with Claude" into view and focus it. */-export const EnginesPanel: React.FC<{ api: EnginesApi; accounts?: ProfilesState; now?: number; focusClaudeSignIn?: number }> = ({- api,- accounts,- now = Date.now(),- focusClaudeSignIn,-}) => {+export const EnginesPanel: React.FC<{+ api: EnginesApi;+ accounts?: ProfilesState;+ now?: number;+ focusClaudeSignIn?: number;+ /** Apps & accounts: the AI accounts list above already says what runs the bots, so skip "What runs your kwant bots". */+ hideRoutes?: boolean;+}> = ({ api, accounts, now = Date.now(), focusClaudeSignIn, hideRoutes = false }) => {const { engines, error, rechecking, recheck, setEnabled, reload } = api;const [showAbsent, setShowAbsent] = useState(false);const profiles = accounts?.profiles ?? null;@@ -286,7 +288,7 @@ export const EnginesPanel: React.FC<{ api: EnginesApi; accounts?: ProfilesState;</div>{routes.length > 0 ? (- <RouteSummary rows={routes} pending={!!accounts && !profiles && !accounts.error} />+ hideRoutes ? null : <RouteSummary rows={routes} pending={!!accounts && !profiles && !accounts.error} />) : (<p className="text-[11px] text-zinc-400 leading-relaxed" aria-live="polite">{engines === nulldiff --git a/frontend/src/components/ModelPicker.tsx b/frontend/src/components/ModelPicker.tsxindex 25044738..6fa5512f 100644--- a/frontend/src/components/ModelPicker.tsx+++ b/frontend/src/components/ModelPicker.tsx@@ -171,7 +171,7 @@ const SettingsLink: React.FC<{ onOpenSettings?: () => void }> = ({ onOpenSettingOpen Settings <ChevronRight size={11} /></button>) : (- <span>Check Settings › This space › Accounts.</span>+ <span>Check Settings › This space › Apps & accounts.</span>);/** "Sign in with Claude", when that's what fixes it. */diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex c836b502..6daac991 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -255,7 +255,7 @@ interface SettingsModalProps {tokensUsed?: number;/** Inside Settings › All spaces: no dialog frame, no close button, Escape is the parent's. */embedded?: boolean;- /** Opens Settings › This space › Accounts, where the API keys and Ollama address live. */+ /** Opens Settings › This space › Apps & accounts, where the API keys and Ollama address live. */onOpenApiKeys?: () => void;/** A switch to scroll to and focus once loaded, by its row id ("idea-jar" from the jar's Settings button). */focusRow?: string | null;@@ -689,7 +689,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t{/* Saves at once, so it sits outside the Settings form (its own Create form can't nest). */}<CodingAgents currentSpace={getCurrentSpace()} />- {/* App settings form; API keys moved to Settings › This space › Accounts */}+ {/* App settings form; API keys moved to Settings › This space › Apps & accounts */}<form onSubmit={handleSave} onChange={(e) => isTextField(e.target) && setTyped(true)} {...editorProps(typed)} className="space-y-4">{onOpenApiKeys && (<button@@ -704,7 +704,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t<Key size={14} className="text-violet-400" aria-hidden="true" /><span className="flex-1"><span className="block text-xs font-medium text-zinc-200">API keys and Ollama</span>- <span className="block text-[11px] text-zinc-500">Now in Settings › This space › Accounts, next to the accounts that use them.</span>+ <span className="block text-[11px] text-zinc-500">Now in Settings › This space › Apps & accounts, next to the accounts that use them.</span></span><ChevronRight size={15} className="text-zinc-500" aria-hidden="true" /></button>diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex 5cd65073..6b00a5df 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -9,11 +9,9 @@ import {Download,FileUp,Globe,- KeyRound,- Link2,+ LayoutGrid,Loader2,Pencil,- Plug,Plus,Settings2,Sparkles,@@ -23,10 +21,9 @@ import {import { ScrollRow } from './ScrollRow';import { playSfx } from '../audio/chiptune';import { SPACE_COLORS, SPACE_ICONS, Space, spaceColor, spaceNameError, spacesApi } from '../spaces';-import { useEngines } from '../useEngines';-import { useProfiles } from '../useProfiles';+import type { EnginesApi } from '../useEngines';+import type { ProfilesState } from '../useProfiles';import type { Profile } from '../profiles';-import { AccountPriority } from './AccountPriority';import { EnginesPanel } from './EnginesPanel';import { ApiKeysPanel } from './ApiKeysPanel';import { RoutinesPanel, type RoutineFocus } from './RoutinesPanel';@@ -39,7 +36,8 @@ import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';import { SpaceApprovalsSetting } from './ApprovalsSetting';import { DevModeSettings } from './DevModeSettings';-import type { SettingsScope, SpaceSettingsTab } from '../nav';+import type { AppsSection, SettingsScope, SpaceSettingsTab } from '../nav';+import { AppsAccounts } from './AppsAccounts';import { InstallAppButton } from './InstallAppButton';import { editorProps, useEscapeLayer } from '../escape';import { devTeamRefs } from '../devMode';@@ -48,11 +46,9 @@ export type { SettingsScope, SpaceSettingsTab };const TABS: Array<{ id: SpaceSettingsTab; label: string; icon: React.ReactNode }> = [{ id: 'general', label: 'General', icon: <Settings2 size={15} /> },- { id: 'accounts', label: 'Accounts', icon: <KeyRound size={15} /> },+ { id: 'apps', label: 'Apps & accounts', icon: <LayoutGrid size={15} /> },{ id: 'bots', label: 'Kwant bots', icon: <Bot size={15} /> },{ id: 'teams', label: 'Teams', icon: <Users size={15} /> },- { id: 'connections', label: 'Connections', icon: <Link2 size={15} /> },- { id: 'tools', label: 'Tools', icon: <Plug size={15} /> },{ id: 'skills', label: 'Skills', icon: <Sparkles size={15} /> },{ id: 'routines', label: 'Routines', icon: <CalendarClock size={15} /> },{ id: 'import', label: 'Import & export', icon: <FileUp size={15} /> },@@ -68,15 +64,19 @@ interface Props {tab: SpaceSettingsTab;onTab: (tab: SpaceSettingsTab) => void;onClose: () => void;- /** This space › Connections: the space's connected apps and tools. */- connections: React.ReactNode;+ /** Apps & accounts › Advanced: tool servers, Telegram and notes from bots; gets Composio's "Choose bots". */+ connections: (chooseComposioBots: () => void) => React.ReactNode;+ /** Apps & accounts opens at this section (seq changes to scroll there again). */+ appsSection?: { section: AppsSection; seq: number } | null;+ /** A bot's tool note was asked for: Advanced opens on it. */+ toolNoteOpen?: boolean;/** All spaces: the app-wide settings. */appSettings: React.ReactNode;onOpenArchived: () => void;kwants: Kwant[];channels: Channel[];teams: Team[];- /** Changes to focus "Sign in with Claude" in Accounts. */+ /** Changes to focus "Sign in with Claude" in Apps & accounts. */focusClaudeSignIn?: number;onProfilesChanged?: (profiles: Profile[]) => void;pendingSkills?: Record<string, number>;@@ -142,7 +142,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {className={`${p.isPhone ? 'fixed' : 'absolute'} inset-0 z-40 bg-zinc-950 text-zinc-100 flex flex-col md:flex-row overflow-hidden`}>{/* Tab list: a column on desktop, scrolling chips on phones */}- <div className="md:w-60 shrink-0 border-b md:border-b-0 md:border-r border-zinc-800/80 bg-zinc-900/40 flex flex-col">+ <div className="md:w-60 shrink-0 border-b md:border-b-0 md:border-r border-zinc-800/80 bg-zinc-900/40 flex flex-col md:sticky md:top-0 md:max-h-full md:overflow-y-auto" data-settings-nav><div className="flex items-center gap-2.5 p-3 md:p-4 pb-2 md:pb-3"><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} />@@ -230,18 +230,23 @@ export const SpaceSettings: React.FC<Props> = (p) => {) : (<>{tab === 'general' && <GeneralTab {...p} />}- {tab === 'accounts' && <AccountsTab {...p} />}+ {tab === 'apps' && (+ <AppsAccounts+ key={space.id}+ spaceName={space.name}+ spaceMode={space.approvals}+ kwants={p.kwants}+ section={p.appsSection?.section}+ sectionSeq={p.appsSection?.seq}+ focusClaudeSignIn={p.focusClaudeSignIn}+ openAdvanced={p.toolNoteOpen}+ onProfilesChanged={p.onProfilesChanged}+ manageAccounts={(shared) => <AccountsTab {...p} {...shared} />}+ advanced={p.connections}+ />+ )}{tab === 'bots' && <BotsTab {...tp} />}{tab === 'teams' && <TeamsTab {...p} />}- {tab === 'connections' && <div data-settings-connections>{p.connections}</div>}- {tab === 'tools' && (- <div className={`${card} p-4 space-y-3`}>- <p className="text-xs text-zinc-300">Tool servers (MCP) give the bots in {space.name} abilities like files, web pages or GitHub.</p>- <button type="button" onClick={p.onOpenTools} className={primaryBtn}>- <Plug size={13} /> Manage tools- </button>- </div>- )}{tab === 'skills' && <SkillsTab {...p} />}{tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={toApp} />}{tab === 'import' && <ImportTab {...tp} />}@@ -527,16 +532,12 @@ const GeneralTab: React.FC<Props> = ({ space, spaces, kwants, teams, onSpaceSave);};-const AccountsTab: React.FC<Props> = ({ space, focusClaudeSignIn, onProfilesChanged }) => {- const engines = useEngines(true);- const accounts = useProfiles(true, onProfilesChanged);+// Apps & accounts › Sign-ins and settings: each AI's sign-in, install and API keys. The order lives in the+// AI accounts list above (AccountPriority), so it isn't repeated here.+const AccountsTab: React.FC<Props & { engines: EnginesApi; accounts: ProfilesState }> = ({ focusClaudeSignIn, engines, accounts }) => {return (<div className="space-y-3">- <p className="text-xs text-zinc-400">What runs your kwant bots in {space.name}: the accounts here, and This machine when it’s on.</p>- {accounts.profiles && accounts.profiles.length > 1 && (- <AccountPriority profiles={accounts.profiles} engines={engines.engines} onChanged={accounts.reload} />- )}- <EnginesPanel api={engines} accounts={accounts} focusClaudeSignIn={focusClaudeSignIn} />+ <EnginesPanel api={engines} accounts={accounts} focusClaudeSignIn={focusClaudeSignIn} hideRoutes /><ApiKeysPanelonSaved={() => {// Saving a key or the Ollama address re-checks engines on the server; show the result.diff --git a/frontend/src/connections.ts b/frontend/src/connections.tsindex 0addaab4..b0afc8f4 100644--- a/frontend/src/connections.ts+++ b/frontend/src/connections.ts@@ -186,7 +186,8 @@ export const needsAttention = (status: string) => status === 'needs_sign_in' ||export function countsLine(list: Connection[]): string {if (list.length === 0) return 'Nothing connected yet';const connected = list.filter((c) => c.status === 'connected').length;- const attention = list.filter((c) => needsAttention(c.status)).length;+ // An AI account no bot uses isn't something the person has to fix (Apps & accounts, 0.9.5).+ const attention = list.filter((c) => needsAttention(c.status) && !(c.kind === 'account' && c.used_by.length === 0)).length;const off = list.filter((c) => c.status === 'off').length;const parts = [`${connected} connected`];if (attention) parts.push(`${attention} ${attention === 1 ? 'needs' : 'need'} you`);@@ -242,15 +243,15 @@ export interface ComposioBody {/** The add form as the API wants it, or why it can't be sent yet. */export function composioBody(url: string, apiKey: string, enabled: boolean): ComposioBody | { error: string } {const u = url.trim();- if (!u) return { error: 'Paste the MCP URL from your Composio dashboard.' };- if (!isComposioUrl(u)) return { error: 'That isn’t a Composio address. It should start with https:// and end in composio.dev.' };+ if (!u) return { error: 'Paste your Composio link first. It’s under MCP in Composio.' };+ if (!isComposioUrl(u)) return { error: 'That isn’t a Composio link. Copy the one under MCP in Composio; it starts with https:// and is on composio.dev.' };const key = apiKey.trim();return key ? { url: u, api_key: key, enabled } : { url: u, enabled };}/** What the add form says when the server refuses. */export function composioErrorText(e: unknown): string {- if (e instanceof ConnectionsError && e.status === 409) return 'Composio is already added. Change it under Tools instead.';+ if (e instanceof ConnectionsError && e.status === 409) return 'Composio is already added. Change it under Advanced instead.';if (e instanceof ConnectionsError && e.status === 400) return e.message;return e instanceof Error ? e.message : 'Something went wrong.';}diff --git a/frontend/src/engines.ts b/frontend/src/engines.tsindex e72a295b..9111ce25 100644--- a/frontend/src/engines.ts+++ b/frontend/src/engines.ts@@ -339,7 +339,7 @@ export function engineSummary(e: EngineInfo, accounts: SummaryAccount[] = []): {if (next) return { text: `Off · Turn on to use ${next.name}`, tone: 'muted' };return { text: e.kind === 'local' || accounts.length === 0 ? 'Off · Turn on to use it' : 'Off · Turn on, then sign in to an account', tone: 'muted' };}- if (isUsable(e)) return e.uses ? { text: `Bots use ${e.uses.label}`, tone: 'ok' } : { text: 'Bots can use it', tone: 'ok' };+ if (isUsable(e)) return e.uses ? { text: `Bots use ${e.uses.label === 'This machine' ? 'the sign-in on this computer' : e.uses.label}`, tone: 'ok' } : { text: 'Bots can use it', tone: 'ok' };switch (e.status) {case 'checking':return { text: 'Checking…', tone: 'busy' };@@ -354,7 +354,7 @@ export function engineSummary(e: EngineInfo, accounts: SummaryAccount[] = []): {return { text: `${e.detail ?? 'The check failed'} · Try Re-check`, tone: 'error' };default: {const out = accounts.find((a) => a.outUntil);- if (out) return { text: `${out.name} is out of usage, back ${out.outUntil} · Sign in to another account below`, tone: 'warn' };+ if (out) return { text: `${out.name.charAt(0).toUpperCase()}${out.name.slice(1)} is out of usage, back ${out.outUntil} · Sign in to another account below`, tone: 'warn' };if (accounts.length === 0) return { text: e.detail ?? 'Not signed in', tone: 'warn' };return { text: 'No account is signed in · Sign in to one below', tone: 'warn' };}diff --git a/frontend/src/failover.ts b/frontend/src/failover.tsindex faf77a50..8623a2cd 100644--- a/frontend/src/failover.ts+++ b/frontend/src/failover.ts@@ -1,4 +1,4 @@-// Failover order (Settings › This space › Accounts) and the switch notice in chat. Pure helpers, so the+// Failover order (Settings › This space › Apps & accounts) and the switch notice in chat. Pure helpers, so the// components and the node tests share them. Every word and time shown comes from the server's data;// nothing here makes up a number.@@ -9,6 +9,10 @@ import { parseMetaObject } from './questions';export const FAILOVER_CAPTION = 'When one runs out, kwant bots move to the next that still works, in this order.';+/** The AI accounts intro: what the order means for the person's bots. */+export const orderIntro = (space: string) =>+ `Your bots in ${space} use the first account that’s ready. If it runs out, they switch to the next one by themselves.`;+export const ENGINE_NAMES: Record<Engine, string> = { claude: 'Claude', codex: 'Codex', grok: 'Grok', custom: 'Custom API' };/** The engine and kind in plain words: "Claude", "Claude API key", "Custom API". */@@ -75,6 +79,39 @@ export function splitRanked(return { ranked, unranked };}+/** Why an account sits under "Not used", and so its one button: Turn on, Sign in or Set up. */+export type NotUsedReason = 'off' | 'signed_out' | 'not_installed';++export interface AccountGroups {+ /** On and able to take a turn, in failover order: [0] is "Used first", the rest "If it runs out". */+ used: Profile[];+ /** Off, signed out or not installed: never in the order, each with its reason. */+ notUsed: Array<{ p: Profile; reason: NotUsedReason; engineOff: boolean }>;+}++/** The order split the way the AI accounts list shows it. An account out of usage keeps its place: it+ * comes back by itself. Display only: nothing here changes an account's saved priority. */+export function accountGroups(order: Profile[], engineOf: (p: Profile) => EngineInfo | undefined, now = Date.now()): AccountGroups {+ const used: Profile[] = [];+ const notUsed: AccountGroups['notUsed'] = [];+ for (const p of order) {+ const e = engineOf(p);+ const engineOff = !!e && (e.enabled === false || e.status === 'disabled');+ if (!p.enabled || engineOff) {+ notUsed.push({ p, reason: 'off', engineOff });+ continue;+ }+ const { label } = priorityStatus(p, e, now);+ if (label === 'Not installed') notUsed.push({ p, reason: 'not_installed', engineOff });+ else if (label === 'Signed out') notUsed.push({ p, reason: 'signed_out', engineOff });+ else used.push(p);+ }+ return { used, notUsed };+}++/** Which account a row is, under the AI's name: "Signed in on this computer", or the account's own name. */+export const accountWhere = (p: Pick<Profile, 'kind' | 'name'>): string => (p.kind === 'system' ? 'Signed in on this computer' : p.name);+/** Where a drag or an arrow press puts an account: the new order, or null when nothing moves. */export function moveAccount(order: Profile[], from: number, to: number): Profile[] | null {if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return null;diff --git a/frontend/src/isolationNotice.ts b/frontend/src/isolationNotice.tsindex 0e01b806..ddd238d7 100644--- a/frontend/src/isolationNotice.ts+++ b/frontend/src/isolationNotice.ts@@ -251,9 +251,9 @@ export function isolationCard(m: IsolationFailedMeta, savedText?: string | null)case 'relay_down':return std('relay_down', couldnt, 'kwant couldn’t connect Claude to your sign-in. Restart kwant, then Retry.');case 'sign_in_expired':- return std('sign_in_expired', `${bot} didn’t reply: your Claude sign-in has expired.`, 'Sign in again in Settings › This space › Accounts, then Retry.', ['retry', 'accounts'], null);+ return std('sign_in_expired', `${bot} didn’t reply: your Claude sign-in has expired.`, 'Sign in again in Settings › This space › Apps & accounts, then Retry.', ['retry', 'accounts'], null);case 'no_credential':- return std('no_credential', `${bot} didn’t reply: there’s no Claude sign-in for it on this computer.`, 'Sign in to Claude in Settings › This space › Accounts, then Retry.', ['retry', 'accounts'], null);+ return std('no_credential', `${bot} didn’t reply: there’s no Claude sign-in for it on this computer.`, 'Sign in to Claude in Settings › This space › Apps & accounts, then Retry.', ['retry', 'accounts'], null);case 'host_is_root':return std('host_is_root', couldnt, 'kwant is running as root, so Claude’s sealed box can’t run as you. Start kwant as your normal user, then Retry.');case 'folder_name_unsupported':diff --git a/frontend/src/nav.ts b/frontend/src/nav.tsindex b3b0961c..cd137538 100644--- a/frontend/src/nav.ts+++ b/frontend/src/nav.ts@@ -1,23 +1,30 @@// Where you are inside a space besides a chat: Inbox, Mission board, Parallel Universe, the Dev// desk or Settings. Each has its own address under /s/<space>/, so a reload, a bookmark or a link// lands on the same place. Older names (While you were away, Loose ends, Connections,-// Routines) still resolve and are rewritten to the new address.+// Routines, and Settings' old Accounts, Connections and Tools tabs) still resolve and are+// rewritten to the new address.export type InboxTab = 'new' | 'loose';/** Settings › This space tabs. Kept here, not in the component, so routing stays pure. */-export const SPACE_SETTINGS_TABS = ['general', 'accounts', 'bots', 'teams', 'connections', 'tools', 'skills', 'routines', 'import'] as const;+export const SPACE_SETTINGS_TABS = ['general', 'apps', 'bots', 'teams', 'skills', 'routines', 'import'] as const;export type SpaceSettingsTab = (typeof SPACE_SETTINGS_TABS)[number];export type SettingsScope = 'space' | 'app';+/** Where Apps & accounts opens; the address stays settings/apps. */+export type AppsSection = 'apps' | 'accounts' | 'advanced';++/** Settings' old tabs (0.9.4 and before), now sections of Apps & accounts. */+const OLD_APPS_TABS: Record<string, AppsSection> = { accounts: 'accounts', connections: 'advanced', tools: 'advanced' };+export type SpaceView =| { kind: 'inbox'; tab: InboxTab }| { kind: 'board' }| { kind: 'parallel' }| { kind: 'dev' }| { kind: 'jar' }- | { kind: 'settings'; scope: 'space'; tab: SpaceSettingsTab }+ | { kind: 'settings'; scope: 'space'; tab: SpaceSettingsTab; section?: AppsSection }| { kind: 'settings'; scope: 'app' };/** The address segment after /s/<space>/ for a view. */@@ -43,7 +50,7 @@ const LEGACY: Record<string, SpaceView> = {away: { kind: 'inbox', tab: 'new' },'while-you-were-away': { kind: 'inbox', tab: 'new' },'loose-ends': { kind: 'inbox', tab: 'loose' },- connections: { kind: 'settings', scope: 'space', tab: 'connections' },+ connections: { kind: 'settings', scope: 'space', tab: 'apps', section: 'advanced' },routines: { kind: 'settings', scope: 'space', tab: 'routines' },'mission-board': { kind: 'board' },missions: { kind: 'board' },@@ -78,6 +85,7 @@ export function parseView(segment: string): { view: SpaceView; legacy: boolean }if ((SPACE_SETTINGS_TABS as readonly string[]).includes(sub)) {return { view: { kind: 'settings', scope: 'space', tab: sub as SpaceSettingsTab }, legacy: false };}+ if (OLD_APPS_TABS[sub]) return { view: { kind: 'settings', scope: 'space', tab: 'apps', section: OLD_APPS_TABS[sub] }, legacy: true };return null;}return null;diff --git a/frontend/src/useEngines.ts b/frontend/src/useEngines.tsindex 8ef34e74..64a2ff2d 100644--- a/frontend/src/useEngines.ts+++ b/frontend/src/useEngines.ts@@ -10,7 +10,8 @@ export interface EnginesApi {recheck: () => Promise<void>;/** Reads the cached status again, without re-running the checks. */reload: () => Promise<void>;- setEnabled: (id: EngineInfo['id'], enabled: boolean) => Promise<void>;+ /** True once the server took it; false when it said no (the switch is put back and `error` set). */+ setEnabled: (id: EngineInfo['id'], enabled: boolean) => Promise<boolean>;/** Shows a list the server already answered with (e.g. after signing out). */apply: (engines: EngineInfo[]) => void;}@@ -73,7 +74,7 @@ export function useEngines(active: boolean): EnginesApi {}, []);const setEnabled = useCallback(- async (id: EngineInfo['id'], enabled: boolean) => {+ async (id: EngineInfo['id'], enabled: boolean): Promise<boolean> => {// Shown at once; put back if the server says no.setEngines((list) => list?.map((e) => (e.id === id ? { ...e, enabled } : e)) ?? list);try {@@ -86,10 +87,12 @@ export function useEngines(active: boolean): EnginesApi {const d = await r.json().catch(() => null);if (alive.current && Array.isArray(d?.engines)) setEngines(d.engines);else await load();+ return true;} catch {- if (!alive.current) return;+ if (!alive.current) return false;setEngines((list) => list?.map((e) => (e.id === id ? { ...e, enabled: !enabled } : e)) ?? list);setError(`Couldn't switch ${enabled ? 'on' : 'off'} that engine.`);+ return false;}},[load],diff --git a/frontend/src/whatsnew/0.7.5.json b/frontend/src/whatsnew/0.7.5.jsonindex d28b46b1..89330893 100644--- a/frontend/src/whatsnew/0.7.5.json+++ b/frontend/src/whatsnew/0.7.5.json@@ -35,7 +35,7 @@"title": "Your bots on Telegram","text": "Pair a Telegram chat to write to your bots and get their replies, questions and approvals on your phone.","image": null,- "open": "settings/connections"+ "open": "settings/apps"},{"id": "show-once",diff --git a/frontend/tests/aiAccountsOrder.test.mjs b/frontend/tests/aiAccountsOrder.test.mjsnew file mode 100644index 00000000..eb16bca4--- /dev/null+++ b/frontend/tests/aiAccountsOrder.test.mjs@@ -0,0 +1,417 @@+// AI accounts order (autonomy/apps-accounts/ai-accounts-order.md, from Oleks's "this not very intuitive"):+// rows titled by the AI, grouped Used first / If it runs out / Not used, "Use first" instead of grip,+// number and arrows, Off accounts outside the order with Turn on, and a no-backup line. Display only:+// the order is still each account's priority, saved with PATCH /api/profiles/:id.+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/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'CSS']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.CSS ??= { escape: (s) => String(s).replace(/["\\]/g, '\\$&') };+g.window.CSS ??= g.CSS;++const m = await loadBundled(`+ export { AccountPriority } from './src/components/AccountPriority';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createRoot } from 'react-dom/client';+ export { createElement } from 'react';+ export { act } from 'react';+`);+const h = m.createElement;+const NOW = Date.parse('2026-11-12T20:00:00');++const profile = (over) => ({+ id: 'p', engine: 'claude', name: 'This machine', kind: 'system', enabled: true, is_default: false, priority: 0,+ home_dir: null, has_key: false, signed_in: true, account_label: null, limited_until: null, last_error: null, ...over,+});+const engine = (id, over = {}) => ({ id, name: id, kind: 'cli', status: 'ready', detail: null, version: '1', models: [], checked_at: null, enabled: true, ready: true, uses: null, ...over });++// Oleks's shot: 1 Personal/Claude Ready, 2 This machine/Grok Ready, 3 This machine/Claude Off, 4 This machine/Codex Off.+const oleks = () => [+ profile({ id: 'personal', name: 'Personal', kind: 'cli_home', priority: 10 }),+ profile({ id: 'sys-grok', engine: 'grok', priority: 20 }),+ profile({ id: 'sys-claude', priority: 30, enabled: false }),+ profile({ id: 'sys-codex', engine: 'codex', priority: 40 }),+];+const oleksEngines = [engine('claude'), engine('grok'), engine('codex', { enabled: false, status: 'disabled' })];++// ── A tiny server: GET is the list, PATCH changes one account ─────────────────────────────────+const server = (profiles) => {+ const calls = [];+ g.fetch = async (url, init = {}) => {+ const method = init.method ?? 'GET';+ const body = init.body ? JSON.parse(init.body) : undefined;+ calls.push([method, url, body]);+ const id = decodeURIComponent(url.split('/').pop());+ const p = profiles.find((x) => x.id === id);+ if (method === 'PATCH' && p) Object.assign(p, body);+ return { ok: true, status: 200, json: async () => p ?? profiles };+ };+ return calls;+};++const mounted = [];+afterEach(() => {+ for (const r of mounted.splice(0)) r.unmount();+ document.body.replaceChildren();+});+const settle = async () => {+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));+};+/** Mounts the list; onChanged re-renders it from the fake server, like the page's reload does. */+const mount = async (profiles, engines, extra = {}) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = m.createRoot(host);+ mounted.push(root);+ const engineOn = [];+ const props = () => ({+ profiles: profiles.map((p) => ({ ...p })),+ engines,+ spaceName: 'Binan',+ now: NOW,+ onChanged: async () => root.render(h(m.AccountPriority, props())),+ onEngineOn: async (id) => {+ engineOn.push(id);+ const e = engines.find((x) => x.id === id);+ if (e) Object.assign(e, { enabled: true, status: 'ready' });+ },+ onAddAccount: () => {},+ ...extra,+ });+ root.render(h(m.AccountPriority, props()));+ await settle();+ return { host, engineOn };+};+const text = (el) => (el?.textContent ?? '').replace(/\s+/g, ' ').trim();+const titles = (el) => [...(el?.querySelectorAll('[data-account-title]') ?? [])].map(text);+const click = async (el) => {+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));+ await settle();+};++test('no row is titled "This machine": titles are the AI, and the built-in account says where it is', () => {+ const html = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: oleks(), engines: oleksEngines, onChanged: async () => {}, now: NOW, spaceName: 'Binan' }));+ assert.doesNotMatch(html, /This machine/);+ assert.match(html, /Your bots in Binan use the first account that’s ready\. If it runs out, they switch to the next one by themselves\./);+ assert.match(html, /Signed in on this computer/);+ assert.doesNotMatch(html, /Order to use|draggable|aria-label="Move /, 'no grip, numbers or arrows');+});++test('Oleks’s four accounts: Claude (Personal) first, Grok if it runs out, Claude and Codex on this computer not used, each with Turn on', async () => {+ server(oleks());+ const { host } = await mount(oleks(), oleksEngines.map((e) => ({ ...e })));+ const first = host.querySelector('[data-group="first"]');+ assert.deepEqual(titles(first), ['Claude']);+ assert.match(text(first), /Personal/);+ assert.deepEqual(titles(host.querySelector('[data-group="backup"]')), ['Grok']);+ const notUsed = host.querySelector('[data-group="not-used"]');+ assert.deepEqual(titles(notUsed), ['Claude', 'Codex']);+ assert.deepEqual([...notUsed.querySelectorAll('[data-not-used]')].map((li) => li.getAttribute('data-not-used')), ['off', 'off']);+ assert.equal(notUsed.querySelectorAll('[data-turn-on]').length, 2);+ assert.match(text(notUsed), /On this computer · Turned off/);+ assert.equal(host.querySelector('[data-no-backup]'), null, 'Grok is the backup');+ assert.ok(host.querySelector('[data-group="backup"] [data-use-first]'), 'the backup row has Use first');+ assert.equal(host.querySelector('[data-group="first"] [data-use-first]'), null);+});++test('Turn on saves enabled with a place at the end of "If it runs out", and the row moves there', async () => {+ const profs = oleks();+ const calls = server(profs);+ const engines = oleksEngines.map((e) => ({ ...e }));+ const { host, engineOn } = await mount(profs, engines);+ // Claude on this computer: the account itself is off.+ await click(host.querySelector('[data-account="sys-claude"] [data-turn-on]'));+ const patch = calls.find(([meth, url]) => meth === 'PATCH' && url.endsWith('/sys-claude'));+ assert.equal(patch[2].enabled, true);+ // Its old number (30) already sorts after Grok (20), so it keeps it; any new one must too.+ assert.ok((patch[2].priority ?? profs.find((p) => p.id === 'sys-claude').priority) > 20, `after Grok (${patch[2].priority})`);+ assert.deepEqual(titles(host.querySelector('[data-group="backup"]')), ['Grok', 'Claude']);+ assert.equal(host.querySelector('[data-group="backup"] li:last-child').getAttribute('data-account'), 'sys-claude');+ // Codex: the whole engine is off, so its own switch is turned on too.+ await click(host.querySelector('[data-account="sys-codex"] [data-turn-on]'));+ assert.deepEqual(engineOn, ['codex']);+ assert.deepEqual([...host.querySelectorAll('[data-group="backup"] li')].map((li) => li.getAttribute('data-account')), ['sys-grok', 'sys-claude', 'sys-codex']);+ assert.equal(host.querySelector('[data-group="not-used"]'), null);+});++test('Use first saves the new priorities and puts that account in "Used first"', async () => {+ const profs = oleks();+ const calls = server(profs);+ const { host } = await mount(profs, oleksEngines.map((e) => ({ ...e })));+ await click(host.querySelector('[data-account="sys-grok"] [data-use-first]'));+ const patches = Object.fromEntries(calls.filter(([meth]) => meth === 'PATCH').map(([, url, b]) => [url.split('/').pop(), b.priority]));+ assert.ok(patches['sys-grok'] < (patches.personal ?? 10), `Grok ranks above Personal: ${JSON.stringify(patches)}`);+ assert.deepEqual(titles(host.querySelector('[data-group="first"]')), ['Grok']);+ assert.deepEqual(titles(host.querySelector('[data-group="backup"]')), ['Claude']);+ assert.equal(document.activeElement?.getAttribute('data-focus-key'), 'sys-grok:more', 'focus stays with the row that moved');+});++test('one ready account: "No backup yet" with Turn on for an off one, or Add an account when none is off', async () => {+ const one = [profile({ id: 'personal', name: 'Personal', kind: 'cli_home', priority: 10 }), profile({ id: 'sys-codex', engine: 'codex', priority: 20, enabled: false })];+ server(one);+ const { host } = await mount(one, [engine('claude'), engine('codex')]);+ const line = host.querySelector('[data-no-backup]');+ assert.match(text(line), /^No backup yet\. If Claude runs out, your bots wait until it resets\./);+ assert.equal(text(line.querySelector('[data-no-backup-action]')), 'Turn on Codex');+ assert.equal(host.querySelectorAll('[data-group="backup"] li').length, 0, 'no backup rows');+ assert.ok(host.querySelector('[data-group="backup"] [data-no-backup]'), 'F14: the line sits under If it runs out');+ const alone = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: [one[0]], engines: [engine('claude')], onChanged: async () => {}, onAddAccount: () => {}, now: NOW }));+ assert.match(alone, /No backup yet\./);+ assert.match(alone, /data-no-backup-action="true">Add an account</);+});++test('an account that is out keeps its place and names the account bots use until then', () => {+ const profs = oleks();+ profs[0].limited_until = '2026-11-13T03:00:00';+ const html = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: profs, engines: oleksEngines, onChanged: async () => {}, now: NOW }));+ const first = html.slice(html.indexOf('data-group="first"'), html.indexOf('data-group="backup"'));+ assert.match(first, /Claude/);+ assert.match(first, /Out until/);+ assert.match(first, /data-step-in="true">Bots use Grok until then\./);+});++test('the More menu holds Move up, Move down and Turn off; arrows move in it and Escape returns focus', async () => {+ server(oleks());+ const { host } = await mount(oleks(), oleksEngines.map((e) => ({ ...e })));+ const btn = host.querySelector('[data-account="sys-grok"] [data-row-menu]');+ assert.equal(btn.getAttribute('aria-haspopup'), 'menu');+ assert.equal(btn.getAttribute('aria-label'), 'More for Grok (on this computer)');+ await click(btn);+ const items = [...host.querySelectorAll('[data-row-menu-list] [role="menuitem"]')];+ assert.deepEqual(items.map(text), ['Move up', 'Move down', 'Turn off']);+ assert.ok(items[1].disabled, 'the last used row can’t go down');+ assert.equal(document.activeElement, items[0]);+ items[0].dispatchEvent(new window.KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));+ await settle();+ assert.equal(document.activeElement, items[2], 'skips the disabled item');+ document.activeElement.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));+ await settle();+ assert.equal(host.querySelector('[data-row-menu-list]'), null);+ assert.equal(document.activeElement, btn);+});++// ── Round 3 (design-check-r2 F12–F15) ────────────────────────────────────────────────────────────+const render = (profs, extra = {}) => m.renderToStaticMarkup(h(m.AccountPriority, { profiles: profs, engines: oleksEngines, onChanged: async () => {}, now: NOW, ...extra }));+const group = (html, name) => html.split(`data-group="${name}"`)[1]?.split('data-group=')[0] ?? '';++test('F12: a bot pinned to a backup account "uses it first"; the first row keeps "Used by"', () => {+ const users = { personal: ['Ann', 'Ben'], 'sys-grok': ['Cody'] };+ let html = render(oleks(), { usedBy: (id) => users[id] ?? [] });+ assert.match(group(html, 'first'), /Used by Ann and Ben/);+ assert.match(group(html, 'backup'), /Cody uses it first/);+ assert.doesNotMatch(group(html, 'backup'), /Used by/);+ users['sys-grok'] = ['Cody', 'Dee'];+ assert.match(group(render(oleks(), { usedBy: (id) => users[id] ?? [] }), 'backup'), /Cody and Dee use it first/);+ users['sys-grok'] = ['Cody', 'Dee', 'Eve', 'Fay'];+ assert.match(group(render(oleks(), { usedBy: (id) => users[id] ?? [] }), 'backup'), /Cody, Dee and 2 more use it first/);+ // Not used, signed out: "Used by" explains why Sign in is amber.+ const profs = oleks();+ profs[3] = profile({ id: 'sys-codex', engine: 'codex', priority: 40, signed_in: false });+ html = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: profs, engines: [engine('claude'), engine('grok'), engine('codex', { status: 'signed_out', ready: false })], onChanged: async () => {}, now: NOW, usedBy: (id) => (id === 'sys-codex' ? ['Cody'] : []) }));+ assert.match(group(html, 'not-used'), /Used by Cody/);+});++test('F13: Use first, Turn on, ⋯, links and menu items are 44 px on phones; menu items show keyboard focus', async () => {+ const html = render(oleks(), { onAddAccount: () => {} });+ const cls = (re) => [...html.matchAll(re)].map((x) => x[1]);+ for (const c of cls(/<button[^>]*class="([^"]*)"[^>]*data-use-first/g)) assert.match(c, /min-h-\[44px\] sm:min-h-\[28px\]/);+ for (const c of cls(/<button[^>]*class="([^"]*)"[^>]*data-turn-on/g)) assert.match(c, /min-h-\[44px\] sm:min-h-\[28px\]/);+ const more = cls(/<button[^>]*class="([^"]*)"[^>]*data-row-menu/g);+ assert.ok(more.length > 0);+ for (const c of more) assert.match(c, /w-11 h-11 sm:w-7 sm:h-7/);+ const alone = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: [oleks()[0]], engines: [engine('claude')], onChanged: async () => {}, onAddAccount: () => {}, now: NOW }));+ assert.match(alone, /class="inline-flex items-center min-h-\[44px\] sm:min-h-0[^"]*"[^>]*data-no-backup-action="true">Add an account/);+ server(oleks());+ const { host } = await mount(oleks(), oleksEngines.map((e) => ({ ...e })));+ await click(host.querySelector('[data-account="sys-grok"] [data-row-menu]'));+ for (const it of host.querySelectorAll('[role="menuitem"]')) {+ assert.match(it.className, /min-h-\[44px\] sm:min-h-0/);+ assert.match(it.className, /focus-visible:outline-2/);+ assert.match(it.className, /focus-visible:outline-sky-400/);+ }+});++test('F14: headings are text-xs semibold (Not used quieter), and one ready account still shows "If it runs out"', () => {+ const html = render(oleks());+ assert.match(html, /<h4 id="account-group-first" class="text-xs font-semibold text-zinc-200">Used first/);+ assert.match(html, /<h4 id="account-group-backup" class="text-xs font-semibold text-zinc-200">If it runs out/);+ assert.match(html, /<h4 id="account-group-off" class="text-xs font-semibold text-zinc-400">Not used/);+ const one = [profile({ id: 'personal', name: 'Personal', kind: 'cli_home', priority: 10 }), profile({ id: 'sys-grok', engine: 'grok', priority: 20, enabled: false })];+ const solo = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: one, engines: [engine('claude'), engine('grok')], onChanged: async () => {}, now: NOW }));+ const backup = group(solo, 'backup');+ assert.match(backup, /If it runs out<\/h4>/);+ assert.match(backup, /data-no-backup="true"[^>]*>|class="mt-1\.5[^"]*"[^>]*data-no-backup/);+ assert.match(backup, /No backup yet\. If Claude runs out, your bots wait until it resets\./);+ const at = (t) => solo.indexOf(`>${t}</h4>`);+ assert.ok(at('Used first') > 0 && at('Used first') < at('If it runs out') && at('If it runs out') < at('Not used'), 'Used first → If it runs out → Not used');+});++test('F15: "Bots use Grok until then." is zinc-300; "Bots wait until then." stays amber', () => {+ const profs = oleks();+ profs[0].limited_until = '2026-11-13T03:00:00';+ assert.match(render(profs), /class="mt-0\.5 text-\[11px\] text-zinc-300" data-step-in="true">Bots use Grok until then\./);+ const alone = [{ ...profs[0] }];+ assert.match(m.renderToStaticMarkup(h(m.AccountPriority, { profiles: alone, engines: [engine('claude')], onChanged: async () => {}, now: NOW })), /class="mt-0\.5 text-\[11px\] text-amber-200" data-step-in="true">Bots wait until then\./);+});++// ── Round 5 (Rigel's qa.md item 1): Turn off on an engine's main (default) account ─────────────+const statusText = (host) => text(host.querySelector('[role="status"]'));+const turnOffRow = async (host, id) => {+ await click(host.querySelector(`[data-account="${id}"] [data-row-menu]`));+ const item = [...host.querySelectorAll('[data-row-menu-list] [role="menuitem"]')].find((x) => text(x) === 'Turn off');+ await click(item);+};++test('Turn off, not the main account: only enabled:false is saved', async () => {+ const profs = oleks();+ const calls = server(profs);+ const { host } = await mount(profs, oleksEngines.map((e) => ({ ...e })));+ await turnOffRow(host, 'sys-grok');+ assert.deepEqual(calls.filter((c) => c[0] === 'PATCH').map((c) => [c[1], c[2]]), [['/api/profiles/sys-grok', { enabled: false }]]);+ assert.match(statusText(host), /Grok \(on this computer\) is off/);+ assert.equal(host.querySelector('[data-order-error]'), null);+});++test('Turn off, the main account with another on: the next one becomes main first, then this one goes off', async () => {+ const profs = oleks();+ profs[0].is_default = true; // Personal is Claude's main account+ profs[2].enabled = true; // Claude on this computer is on, further down the order+ const calls = server(profs);+ const { host } = await mount(profs, oleksEngines.map((e) => ({ ...e })));+ await turnOffRow(host, 'personal');+ assert.deepEqual(+ calls.filter((c) => c[0] === 'PATCH').map((c) => [c[1], c[2]]),+ [+ ['/api/profiles/sys-claude', { is_default: true }],+ ['/api/profiles/personal', { enabled: false }],+ ],+ );+ assert.equal(statusText(host), 'Claude (Personal) is off. The sign-in on this computer is now Claude’s main account.');+ assert.equal(host.querySelector('[data-order-error]'), null);+ assert.ok(host.querySelector('[data-group="not-used"] [data-account="personal"]'), 'Personal moved to Not used');+});++test('Turn off, the only account its engine has on: the engine’s own switch, no PATCH', async () => {+ const profs = oleks();+ profs[1].is_default = true; // Grok on this computer: Grok's main and only account+ const calls = server(profs);+ const engines = oleksEngines.map((e) => ({ ...e }));+ const engineOff = [];+ const { host } = await mount(profs, engines, {+ onEngineOff: async (id) => {+ engineOff.push(id);+ Object.assign(engines.find((x) => x.id === id), { enabled: false, status: 'disabled' });+ },+ });+ await turnOffRow(host, 'sys-grok');+ assert.deepEqual(engineOff, ['grok']);+ assert.equal(calls.filter((c) => c[0] === 'PATCH').length, 0);+ assert.ok(host.querySelector('[data-group="not-used"] [data-account="sys-grok"]'), 'the row lands in Not used');+ assert.equal(host.querySelector('[data-order-error]'), null);+});++test('Turn off that fails says so in plain words, never the server’s text, and focus goes back to More', async () => {+ const profs = oleks();+ profs[1].is_default = true;+ profs.push(profile({ id: 'grok-work', engine: 'grok', name: 'Work', kind: 'cli_home', priority: 25 }));+ const calls = server(profs);+ const ok = g.fetch;+ g.fetch = async (url, init = {}) => {+ if (init.method === 'PATCH' && url.endsWith('/sys-grok')) {+ calls.push(['PATCH', url, JSON.parse(init.body)]);+ return { ok: false, status: 400, json: async () => ({ error: "the default profile can't be disabled" }) };+ }+ return ok(url, init);+ };+ const { host } = await mount(profs, oleksEngines.map((e) => ({ ...e })));+ await turnOffRow(host, 'sys-grok');+ const err = text(host.querySelector('[data-order-error]'));+ assert.equal(err, 'Couldn’t turn off Grok (on this computer). It is back as it was.');+ assert.equal(host.innerHTML.includes('default profile'), false, 'no server text anywhere');+ // The main account moved to Work first, so it is put back on this one.+ assert.deepEqual(+ calls.filter((c) => c[0] === 'PATCH').map((c) => [c[1], c[2]]),+ [+ ['/api/profiles/grok-work', { is_default: true }],+ ['/api/profiles/sys-grok', { enabled: false }],+ ['/api/profiles/sys-grok', { is_default: true }],+ ],+ );+ const more = host.querySelector('[data-account="sys-grok"] [data-row-menu]');+ assert.equal(document.activeElement === more, true, 'focus is on the row’s More button');+});++// ── Round 6 (qa.md round 5, item 1 last row): the engine's own switch fails ─────────────────────+test('Turn off whose engine switch fails: "Couldn’t turn off …", no "is off", focus on the row’s More', async () => {+ const profs = oleks();+ profs[1].is_default = true; // Grok on this computer: Grok's main and only account+ const calls = server(profs);+ const engines = oleksEngines.map((e) => ({ ...e }));+ const engineOff = [];+ const { host } = await mount(profs, engines, {+ // Like useEngines.setEnabled on a failed PUT: it puts the switch back and returns false.+ onEngineOff: async (id) => {+ engineOff.push(id);+ return false;+ },+ });+ await turnOffRow(host, 'sys-grok');+ assert.deepEqual(engineOff, ['grok']);+ assert.equal(text(host.querySelector('[data-order-error]')), 'Couldn’t turn off Grok (on this computer). It is back as it was.');+ assert.doesNotMatch(statusText(host), /is off/);+ assert.doesNotMatch(host.textContent, /is off\./, 'no success words anywhere');+ assert.equal(calls.filter((c) => c[0] === 'PATCH').length, 0);+ assert.ok(host.querySelector('[data-group="backup"] [data-account="sys-grok"]'), 'the row stays where it was');+ const more = host.querySelector('[data-account="sys-grok"] [data-row-menu]');+ assert.equal(more.getAttribute('data-focus-key'), 'sys-grok:more');+ assert.equal(document.activeElement === more, true, 'focus is on the row’s More button');+});++test('Turn on whose engine switch fails: "Couldn’t turn on …", no "is on", focus back on the row’s Turn on', async () => {+ const profs = oleks();+ const calls = server(profs);+ const engines = oleksEngines.map((e) => ({ ...e }));+ const engineOn = [];+ const { host } = await mount(profs, engines, {+ onEngineOn: async (id) => {+ engineOn.push(id);+ return false;+ },+ });+ await click(host.querySelector('[data-account="sys-codex"] [data-turn-on]'));+ assert.deepEqual(engineOn, ['codex']);+ assert.equal(text(host.querySelector('[data-order-error]')), 'Couldn’t turn on Codex (on this computer). It is back as it was.');+ assert.doesNotMatch(statusText(host), /is on/);+ assert.doesNotMatch(host.textContent, /is on\. Your bots/, 'no success words anywhere');+ assert.equal(calls.filter((c) => c[0] === 'PATCH').length, 0, 'the account is not turned on without its engine');+ const on = host.querySelector('[data-account="sys-codex"] [data-turn-on]');+ assert.ok(host.querySelector('[data-group="not-used"] [data-account="sys-codex"]'), 'the row stays in Not used');+ assert.equal(document.activeElement === on, true, 'focus is back on the row’s Turn on (Not used rows have no More)');+});++// ── Round 5 (qa.md item 3): bots on auto are named only on "Used first" ─────────────────────────+test('auto bots only on Used first: backup and Not used rows name pinned bots (usedBy pinnedOnly)', () => {+ // Rigel's space: Ann and Ben on auto, Cody pinned to Codex, Gus pinned to Grok; Grok first.+ const profs = [+ profile({ id: 'grok', engine: 'grok', is_default: true, priority: 10 }),+ profile({ id: 'claude', engine: 'claude', is_default: true, priority: 20 }),+ profile({ id: 'codex', engine: 'codex', is_default: true, priority: 30 }),+ ];+ const server = { grok: ['Ann', 'Ben', 'Gus'], claude: ['Ann', 'Ben'], codex: ['Ann', 'Ben', 'Cody'] };+ const auto = new Set(['Ann', 'Ben']);+ const usedBy = (id, pinnedOnly) => (server[id] ?? []).filter((n) => !pinnedOnly || !auto.has(n));+ const engines = [engine('claude'), engine('grok'), engine('codex')];+ const html = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: profs, engines, onChanged: async () => {}, now: NOW, usedBy }));+ assert.match(group(html, 'first'), /Used by Ann, Ben and Gus/);+ const backup = group(html, 'backup');+ assert.match(backup, /Cody uses it first/);+ assert.doesNotMatch(backup, /Ann|Ben/);+ assert.doesNotMatch(backup, /Ann and Ben use it first/);+});diff --git a/frontend/tests/appsAccounts.test.mjs b/frontend/tests/appsAccounts.test.mjsnew file mode 100644index 00000000..7577d635--- /dev/null+++ b/frontend/tests/appsAccounts.test.mjs@@ -0,0 +1,483 @@+// Settings › Apps & accounts (0.9.5, autonomy/apps-accounts/brief.md): app tiles first, a 3-step+// Connect sheet where picking bots turns the app on, AI accounts named by engine with who uses+// them (an unused account never "needs you"), Advanced closed, and old addresses landing here.+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/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });+g.window.HTMLElement.prototype.scrollIntoView ??= () => {};++const m = await loadBundled(`+ export * from './src/appsAccounts';+ export { countsLine } from './src/connections';+ export { parseView, viewSegment, SPACE_SETTINGS_TABS } from './src/nav';+ export { AppsAccounts, ConnectSheet } from './src/components/AppsAccounts';+ export { ConnectionsView } from './src/components/ConnectionsView';+ export { EnginesPanel } from './src/components/EnginesPanel';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createRoot } from 'react-dom/client';+ export { createElement } from 'react';+`);+const h = m.createElement;++const WARNING = "Composio keeps your app sign-ins on Composio's servers.";+const composio = (over = {}) => ({+ id: 'composio', kind: 'mcp', name: 'Composio', description: 'Hundreds of apps.', optional: true, added: false, connection_id: null,+ enabled: false, logins_stored: 'composio', warning: WARNING, add: '/api/connections/composio', ...over,+});+const acct = (id, over = {}) => ({+ id: `account:${id}`, kind: 'account', name: 'This machine', detail: 'claude · [email protected]', status: 'connected', status_detail: null,+ last_check: null, used_by: [], logins_stored: 'kwnt', manage: `/api/profiles/${id}`, ...over,+});+const profile = (id, engine, over = {}) => ({+ id, engine, name: id, kind: 'system', enabled: true, is_default: false, priority: 0, home_dir: null, has_key: false, signed_in: true,+ account_label: null, limited_until: null, last_error: null, ...over,+});+const bots = [+ { id: 'k1', name: 'Ann', approvals_effective: 'ask' },+ { id: 'k2', name: 'Ben', approvals_effective: 'ask' },+ { id: 'k3', name: 'Cody', approvals_effective: 'off' },+];++// ── DOM helpers ──────────────────────────────────────────────────────────────────────────────+const mounted = new Set();+afterEach(() => {+ for (const u of mounted) u();+ document.body.replaceChildren();+});+const settle = async () => {+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));+};+const mount = async (C, props) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = m.createRoot(host);+ root.render(h(C, props));+ await settle();+ const u = () => {+ if (!mounted.delete(u)) return;+ root.unmount();+ host.remove();+ };+ mounted.add(u);+ // The sheet renders into <body>, so look there.+ return document.body;+};+const text = (el) => el.textContent.replace(/\s+/g, ' ').trim();+const button = (host, t) => [...host.querySelectorAll('button')].find((b) => text(b).startsWith(t));+const click = async (el) => {+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));+ await settle();+};+const type = async (el, v) => {+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(el, v);+ el.dispatchEvent(new window.Event('input', { bubbles: true }));+ await settle();+};+const submit = async (host) => {+ host.querySelector('form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));+ await settle();+};++const fakeApi = (over = {}) => {+ const calls = [];+ return {+ calls,+ addComposio: async (b) => (calls.push(['add', b]), { connection_id: 'mcp:cmp1' }),+ connect: async (slug) => (calls.push(['connect', slug]), { redirect_url: 'https://composio.dev/auth/x' }),+ give: async (s, all, chosen) => void calls.push(['give', s, all, chosen]),+ botsWith: async () => ['k2'],+ ...over,+ };+};+const sheetProps = (over = {}) => ({+ app: m.APP_TILES[0], composio: composio(), kwants: bots, spaceName: 'Home', spaceMode: 'ask', onClose: () => {}, onDone: () => {}, phone: false, ...over,+});++// ── The sheet's three steps ──────────────────────────────────────────────────────────────────++test('the sheet says what bots can do and that it goes through Composio, then shows three steps with no bot ticked', () => {+ const html = m.renderToStaticMarkup(h(m.ConnectSheet, sheetProps()));+ for (const t of ['Connect Gmail', 'Your bots will be able to', 'Read and search your mail', 'Through Composio, a service with a free plan', 'Open Composio', 'Paste your Composio link', 'Which bots get it?', 'None until you tick one.']) {+ assert.ok(html.includes(t), `sheet shows "${t}"`);+ }+ assert.equal((html.match(/data-sheet-step="/g) ?? []).length, 3);+ assert.ok(!/type="checkbox"[^>]*checked/.test(html), 'no bot is preselected');+ assert.match(html, /role="dialog"/);+ assert.match(html, /aria-modal="true"/);+ assert.ok(html.includes('MCP</span> in the left menu'), 'step 2 says where the link is');+ assert.ok(!html.includes('Turn on in Tools'));+});++test('a bad link stops at step 2 with words, and no bot stops at step 3', async () => {+ const api = fakeApi();+ const host = await mount(m.ConnectSheet, sheetProps({ api }));+ await submit(host);+ assert.match(text(host.querySelector('[data-sheet-error="2"]')), /^Paste your Composio link first\. It’s under MCP in Composio\.$/);+ await type(host.querySelector('input[type="url"]'), 'https://example.com/mcp');+ await submit(host);+ assert.match(text(host.querySelector('[data-sheet-error="2"]')), /^That isn’t a Composio link\. Copy the one under MCP in Composio; it starts with https:\/\/ and is on composio\.dev\.$/);+ await type(host.querySelector('input[type="url"]'), 'https://backend.composio.dev/v3/mcp/abc');+ await submit(host);+ assert.match(text(host.querySelector('[data-sheet-error="3"]')), /Tick at least one bot/);+ assert.deepEqual(api.calls, [], 'nothing is sent until the form is whole');+});++test('fixing the link or ticking a bot clears that step’s error at once', async () => {+ const host = await mount(m.ConnectSheet, sheetProps({ api: fakeApi() }));+ await type(host.querySelector('input[type="url"]'), 'https://example.com/mcp');+ await submit(host);+ assert.ok(host.querySelector('[data-sheet-error="2"]'));+ await type(host.querySelector('input[type="url"]'), 'https://backend.composio.dev/v3/mcp/abc');+ assert.equal(host.querySelector('[data-sheet-error="2"]'), null, 'the old link error goes as soon as the link changes');+ await submit(host);+ assert.ok(host.querySelector('[data-sheet-error="3"]'));+ await click(host.querySelector('[data-sheet-bot] input'));+ assert.equal(host.querySelector('[data-sheet-error="3"]'), null, 'ticking a bot clears the bot error');+});++test('Composio refusing the link shows its reason at step 2', async () => {+ const { ConnectionsError } = await loadBundled(`export { ConnectionsError } from './src/connections';`);+ const api = fakeApi({ addComposio: async () => { throw new ConnectionsError('Composio didn’t answer.', 400); } });+ const host = await mount(m.ConnectSheet, sheetProps({ api, initial: { url: 'https://backend.composio.dev/v3/mcp/abc', picked: ['k1'] } }));+ await submit(host);+ assert.match(text(host.querySelector('[data-sheet-error="2"]')), /Composio didn’t answer/);+});++test('picking one bot adds Composio and gives it to just that bot, then says so', async () => {+ const api = fakeApi();+ let done = null;+ const host = await mount(m.ConnectSheet, sheetProps({ api, onDone: (r) => (done = r) }));+ await type(host.querySelector('input[type="url"]'), 'https://backend.composio.dev/v3/mcp/abc');+ await click(host.querySelector('[data-sheet-bot="k1"] input'));+ assert.match(text(host), /Ann gets it, turned on/);+ await submit(host);+ assert.deepEqual(api.calls[0], ['add', { url: 'https://backend.composio.dev/v3/mcp/abc', enabled: false }], 'added off: only the picks turn it on');+ assert.deepEqual(api.calls[1], ['give', 'cmp1', ['k1', 'k2', 'k3'], ['k1']]);+ assert.deepEqual({ app: done.app.slug, who: done.who }, { app: 'gmail', who: ['Ann'] }, 'the page words the result once it knows the sign-in');+});++test('with Composio set up the sheet starts at the app’s own sign-in and the bots that have it now', async () => {+ const api = fakeApi();+ const host = await mount(m.ConnectSheet, sheetProps({ api, composio: composio({ added: true, enabled: true, connection_id: 'mcp:cmp1', can_connect: true }) }));+ assert.ok(!host.querySelector('input[type="url"]'), 'no link to paste again');+ assert.equal(host.querySelectorAll('[data-sheet-step]').length, 2);+ assert.ok(host.querySelector('[data-sheet-bot="k2"] input').checked, 'Ben has it already');+ assert.ok(!host.querySelector('[data-sheet-bot="k1"] input').checked);+ g.window.open = () => null;+ await click(host.querySelector('[data-sheet-signin]'));+ assert.deepEqual(api.calls[0], ['connect', 'gmail']);+ await submit(host);+ assert.deepEqual(api.calls[1], ['give', 'cmp1', ['k1', 'k2', 'k3'], ['k2']]);+});++test('Composio down while starting the app sign-in says so at step 1', async () => {+ const api = fakeApi({ connect: async () => { throw new Error("Composio couldn't be reached; try again later."); } });+ const host = await mount(m.ConnectSheet, sheetProps({ api, composio: composio({ added: true, enabled: true, connection_id: 'mcp:cmp1', can_connect: true }) }));+ g.window.open = () => null;+ await click(host.querySelector('[data-sheet-signin]'));+ const t = text(host.querySelector('[data-sheet-error="1"]'));+ assert.match(t, /Composio couldn’t be reached, so the Gmail sign-in didn’t open\. Try again in a minute\./);+ assert.equal(t.match(/try again/gi).length, 1, 'the server\'s own "try again later" isn\'t repeated');+});++test('a refused Composio key says so and doesn’t blame an outage', async () => {+ const { ConnectionsError } = await loadBundled(`export { ConnectionsError } from './src/connections';`);+ const api = fakeApi({ connect: async () => { throw new ConnectionsError('Composio refused the API key saved with the Composio connector.', 409); } });+ const host = await mount(m.ConnectSheet, sheetProps({ api, composio: composio({ added: true, enabled: true, connection_id: 'mcp:cmp1', can_connect: true }) }));+ g.window.open = () => null;+ await click(host.querySelector('[data-sheet-signin]'));+ const t = text(host.querySelector('[data-sheet-error="1"]'));+ assert.match(t, /refused your API key.*Advanced › Manage tools/);+ assert.doesNotMatch(t, /may be down/);+});++test('focus moves into the sheet (a modal: Tab is trapped by useEscapeLayer) and Escape closes it', async () => {+ let closed = 0;+ const host = await mount(m.ConnectSheet, sheetProps({ onClose: () => closed++ }));+ const dialog = host.querySelector('[role="dialog"]');+ assert.ok(dialog.contains(document.activeElement), 'focus moves into the sheet');+ document.activeElement.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));+ await settle();+ assert.equal(closed, 1);+});++test('the approval line follows the bots’ real approvals and never promises "asks first" when off', () => {+ assert.equal(m.approvalLine('Send mail', [bots[0]], 'ask').tone, 'ok');+ assert.equal(m.approvalLine('Send mail', [bots[0]], 'ask').text, 'Send mail only after you say yes');+ assert.match(m.approvalLine('Send mail', [bots[2]], 'ask').text, /without asking/);+ const mixed = m.approvalLine('Send mail', [bots[0], bots[2]], 'ask');+ assert.match(mixed.text, /Cody won’t ask first/);+ assert.doesNotMatch(m.approvalLine('Send mail', [], 'off').text, /say yes/);+ // F3 (Ada): smart asks before anything outward, so it gets the same line as ask.+ assert.deepEqual(m.approvalLine('Send mail', [{ name: 'X', approvals_effective: 'smart' }], 'ask'), { text: 'Send mail only after you say yes', tone: 'ok' });+ assert.match(m.approvalLine('Send mail', [bots[2]], 'ask').text, /\(approvals are off\)$/);+ assert.equal(mixed.text, 'Send mail: Cody won’t ask first (approvals off); the others ask you');+ const html = m.renderToStaticMarkup(h(m.ConnectSheet, sheetProps({ initial: { picked: ['k3'] } })));+ assert.match(html, /data-sheet-approval="warn"/);+ assert.ok(!html.includes('only after you say yes'));+});++// ── A bot pick turns the tool on ─────────────────────────────────────────────────────────────++const fakeServer = ({ enabled = false, lists = { k1: ['s9'], k2: ['s9', 'cmp1'], k3: ['cmp1'] } } = {}) => {+ const calls = [];+ const server = { id: 'cmp1', name: 'Composio', transport: 'http', command: null, args: [], env: {}, url: 'https://backend.composio.dev/v3/mcp/x', headers: { 'x-api-key': '••••' }, enabled, oauth: null, disabled_for_kwants: [] };+ const f = async (url, init = {}) => {+ const method = init.method ?? 'GET';+ calls.push([method, url, init.body ? JSON.parse(init.body) : undefined]);+ const kw = url.match(/^\/api\/kwants\/(\w+)\/mcp-servers$/);+ const ok = (b) => ({ ok: true, status: 200, json: async () => b });+ if (kw && method === 'GET') return ok({ server_ids: lists[kw[1]] });+ if (kw && method === 'PUT') return (lists[kw[1]] = JSON.parse(init.body).server_ids, ok({ server_ids: lists[kw[1]] }));+ if (url === '/api/mcp/servers/cmp1' && method === 'GET') return ok(server);+ if (url === '/api/mcp/servers/cmp1' && method === 'PUT') return (server.enabled = JSON.parse(init.body).enabled, ok(server));+ return { ok: false, status: 404, json: async () => ({ error: 'nope' }) };+ };+ return { f, calls, lists, server };+};++test('a bot pick gives the server to exactly the picked bots and turns it on, keeping their other tools', async () => {+ const s = fakeServer();+ await m.giveServerTo('cmp1', ['k1', 'k2', 'k3'], ['k1'], s.f);+ assert.deepEqual(s.lists, { k1: ['s9', 'cmp1'], k2: ['s9'], k3: [] });+ assert.equal(s.server.enabled, true);+ const put = s.calls.find(([meth, url]) => meth === 'PUT' && url === '/api/mcp/servers/cmp1');+ assert.equal(put[2].enabled, true, 'the same call Tools’ on/off switch makes');+ assert.equal(put[2].url, 'https://backend.composio.dev/v3/mcp/x');+});++test('a server that is already on is not saved again, and no pick only takes it away', async () => {+ const on = fakeServer({ enabled: true });+ await m.giveServerTo('cmp1', ['k1', 'k2', 'k3'], ['k2', 'k3'], on.f);+ assert.ok(!on.calls.some(([meth, url]) => meth === 'PUT' && url.startsWith('/api/mcp/servers/')));+ assert.ok(!on.calls.some(([meth]) => meth === 'PUT'), 'nobody’s list changed');+ const none = fakeServer();+ await m.giveServerTo('cmp1', ['k1', 'k2', 'k3'], [], none.f);+ assert.equal(none.server.enabled, false);+ assert.deepEqual(none.lists, { k1: ['s9'], k2: ['s9'], k3: [] });+});++test('giving fails with the server’s own words', async () => {+ const f = async () => ({ ok: false, status: 500, json: async () => ({ error: 'Database is locked' }) });+ await assert.rejects(m.giveServerTo('cmp1', ['k1'], ['k1'], f), /Database is locked/);+ await assert.rejects(m.giveServerTo('cmp1', ['k1'], ['k1'], async () => { throw new TypeError('fetch failed'); }), /Couldn’t reach kwant/);+});++// ── AI accounts and the needs-you count ──────────────────────────────────────────────────────++test('an unused account that isn’t signed in is a quiet Sign in, never "needs you"', () => {+ const used = acct('p1', { status: 'needs_sign_in', used_by: [{ id: 'k1', name: 'Ann' }] });+ const unused = acct('p2', { name: 'Work', detail: 'codex', status: 'needs_sign_in' });+ assert.equal(m.accountNeedsYou(used), true);+ assert.equal(m.accountNeedsYou(unused), false);+ assert.equal(m.countsLine([used, unused]), '0 connected · 1 needs you');+ assert.equal(m.countsLine([unused]), '0 connected');+ assert.equal(m.pageCounts([used, unused]), '0 AI accounts ready · 0 tool servers on · 1 needs you');+});++// ── The page ─────────────────────────────────────────────────────────────────────────────────++const data = (over = {}) => ({+ connections: [acct('sys', { used_by: [{ id: 'k1', name: 'Ann' }, { id: 'k2', name: 'Ben' }] }), acct('p2', { name: 'Work', detail: 'codex', status: 'needs_sign_in' })],+ counts: {}, vault: { status: 'ok' }, catalog: [composio()], ...over,+});+const pageProps = (over = {}) => ({+ spaceName: 'Home', spaceMode: 'ask', kwants: bots, data: data(), profiles: [profile('sys', 'claude'), profile('p2', 'codex', { kind: 'cli_home', signed_in: false, priority: 1 })],+ engines: [{ id: 'claude', name: 'Claude', kind: 'cli', status: 'ready', enabled: true, ready: true, models: [] }, { id: 'codex', name: 'Codex', kind: 'cli', status: 'ready', enabled: true, ready: true, models: [] }],+ manageAccounts: () => h('p', null, 'MANAGE'), advanced: () => h('p', null, 'ADVANCED'), phone: false, ...over,+});++test('the page puts app tiles first, then another app, AI accounts, and a closed Advanced', () => {+ const html = m.renderToStaticMarkup(h(m.AppsAccounts, pageProps()));+ const order = ['data-apps-tiles', 'data-apps-search', 'data-ai-accounts', 'data-apps-advanced'].map((k) => html.indexOf(k));+ assert.ok(order.every((i, n) => i > 0 && (n === 0 || i > order[n - 1])), `order ${order}`);+ assert.deepEqual([...html.matchAll(/data-app-tile="(\w+)"/g)].map((x) => x[1]), ['gmail', 'googlecalendar', 'slack', 'notion', 'shopify', 'github']);+ assert.ok(html.includes('#231d4b'), 'plain initials on the overlay colour');+ assert.ok(!html.includes('<img'), 'no logos');+ assert.ok(!html.includes('ADVANCED'), 'Advanced is closed');+ assert.ok(html.includes('data-quiet-sign-in'), 'the unused Codex account offers a quiet Sign in');+ assert.ok(!html.includes('data-ai-needs'), 'and nothing "needs you"');+ assert.ok(!html.includes('Turn on in Tools'));+ // Decision 2: the order groups are the list, so each account shows once, with who uses it.+ const ai = html.slice(html.indexOf('data-ai-accounts'), html.indexOf('data-apps-advanced'));+ assert.equal((ai.match(/data-account-title/g) ?? []).length, 2, 'each account once');+ assert.match(ai, /Used by Ann and Ben/);+ assert.match(ai, /Signed in on this computer/);+ assert.doesNotMatch(ai, /This machine|MANAGE/, 'sign-ins and keys stay collapsed');+ assert.match(ai, /Sign-ins and settings/);+ // F10: the intro names both halves.+ assert.match(html, /The apps your bots can use, and the AI they think with\./);+ // F7: each tile has its own initials colour and a two-line blurb.+ const tints = [...html.matchAll(/data-app-mark-tint="([^"]+)"/g)].map((x) => x[1]);+ assert.equal(new Set(tints).size, 6, `six tints: ${tints}`);+ assert.equal((html.match(/line-clamp-2/g) ?? []).length, 6);+ // F8: phone-sized targets on the page's buttons.+ assert.match(html, /min-h-\[44px\] sm:min-h-\[32px\]/);+});++test('a tile opens the Connect sheet and Escape closes it', async () => {+ const host = await mount(m.AppsAccounts, pageProps({ connectApi: fakeApi() }));+ await click(host.querySelector('[data-app-tile="slack"]'));+ assert.equal(text(document.querySelector('[role="dialog"] h2')), 'Connect Slack');+ document.activeElement.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));+ await settle();+ assert.equal(document.querySelector('[data-connect-sheet]'), null);+});++test('opening at Advanced shows it; a used account that can’t run counts as needing you', () => {+ const html = m.renderToStaticMarkup(+ h(m.AppsAccounts, pageProps({ section: 'advanced', data: data({ connections: [acct('sys', { status: 'needs_sign_in', used_by: [{ id: 'k1', name: 'Ann' }] })] }) })),+ );+ assert.ok(html.includes('ADVANCED'));+ assert.match(html, /data-ai-needs[^>]*>1 needs you/);+});++test('Advanced’s Composio card offers Choose bots instead of Turn on in Tools, and leaves AI accounts out', () => {+ const html = m.renderToStaticMarkup(+ h(m.ConnectionsView, {+ data: data({ catalog: [composio({ added: true, connection_id: 'mcp:cmp1' })] }), loading: false, error: null, onRefresh: () => {}, onAddComposio: async () => null,+ embedded: true, hideAccounts: true, onChooseComposioBots: () => {}, onOpenTools: () => {},+ }),+ );+ assert.ok(html.includes('Choose bots to turn it on'));+ assert.ok(!html.includes('Turn on in Tools'));+ assert.ok(!html.includes('Engine accounts'));+});++// ── Old addresses ────────────────────────────────────────────────────────────────────────────++test('old Settings addresses land on Apps & accounts and are rewritten', () => {+ assert.ok(m.SPACE_SETTINGS_TABS.includes('apps'));+ for (const old of ['accounts', 'connections', 'tools']) assert.ok(!m.SPACE_SETTINGS_TABS.includes(old));+ const cases = { 'settings/accounts': 'accounts', 'settings/connections': 'advanced', 'settings/tools': 'advanced', connections: 'advanced' };+ for (const [seg, section] of Object.entries(cases)) {+ const r = m.parseView(seg);+ assert.deepEqual(r, { view: { kind: 'settings', scope: 'space', tab: 'apps', section }, legacy: true }, seg);+ assert.equal(m.viewSegment(r.view), 'settings/apps');+ }+ assert.deepEqual(m.parseView('settings/apps'), { view: { kind: 'settings', scope: 'space', tab: 'apps' }, legacy: false });+});++// ── Mira's design check (design-check.md F1–F9) ──────────────────────────────────────────────++const readyComposio = () => composio({ added: true, enabled: true, connection_id: 'mcp:cmp1', can_connect: true });++test('F1: the done line is green only when Composio confirms the app sign-in; otherwise it says what’s left', async () => {+ for (const [signedIn, tone, want] of [+ [true, 'ok', 'Gmail is on for Ann.'],+ [false, 'info', 'Composio is on for Ann. Ann can use Gmail once you’ve signed in to Gmail on Composio.'],+ ]) {+ const host = await mount(m.AppsAccounts, pageProps({+ data: data({ catalog: [readyComposio()] }), connectApi: fakeApi(), appStatus: async () => ({ connected: signedIn }),+ initialSheet: { slug: 'gmail', initial: { picked: ['k1'] } },+ }));+ await submit(document.querySelector('[data-connect-sheet]'));+ const n = host.querySelector('[data-apps-notice]');+ assert.equal(n?.getAttribute('data-apps-notice'), tone);+ assert.equal(text(n), want);+ for (const u of [...mounted]) u();+ }+});++test('F1: a tile Composio can’t check says "Sign in or choose bots", not Connect or Connected', () => {+ const html = m.renderToStaticMarkup(h(m.AppsAccounts, pageProps({ data: data({ catalog: [composio({ added: true, enabled: true, connection_id: 'mcp:cmp1', can_connect: false })] }) })));+ assert.equal((html.match(/data-tile-state="unknown"/g) ?? []).length, 6);+ assert.match(html, /Sign in or choose bots/);+ const fresh = m.renderToStaticMarkup(h(m.AppsAccounts, pageProps()));+ assert.equal((fresh.match(/data-tile-state="connect"/g) ?? []).length, 6);+});++test('F2: with Composio set up the steps are 1 and 2, and Choose bots alone has no number', () => {+ const ready = m.renderToStaticMarkup(h(m.ConnectSheet, sheetProps({ composio: readyComposio() })));+ assert.deepEqual([...ready.matchAll(/data-step-label="(\d+)"/g)].map((x) => x[1]), ['1', '2']);+ const choose = m.renderToStaticMarkup(h(m.ConnectSheet, sheetProps({ app: null, composio: readyComposio() })));+ assert.match(choose, /Choose bots for Composio/);+ assert.match(choose, /Picked bots can use every app on your Composio/);+ assert.doesNotMatch(choose, /data-step-label=/);+ assert.doesNotMatch(choose, /Step \d/);+});++test('F4: bot chips show the bot’s face and step 3 says Composio is one connection', () => {+ const html = m.renderToStaticMarkup(h(m.ConnectSheet, sheetProps()));+ const chip = html.slice(html.indexOf('data-sheet-bot="k1"'), html.indexOf('data-sheet-bot="k2"'));+ assert.match(chip, /aria-hidden="true"/);+ assert.match(chip, /min-h-\[44px\]/);+ assert.match(html, /data-sheet-one-connection="true">Composio is one connection: the bots you tick can use every app on it, not only Gmail\./);+});++test('F5: the link error sits right under the field and is read with it; a good link ticks step 2', async () => {+ const host = await mount(m.ConnectSheet, sheetProps({ api: fakeApi() }));+ const input = host.querySelector('input[type="url"]');+ await submit(host);+ const err = host.querySelector('[data-sheet-error="2"]');+ assert.equal(err.getAttribute('role'), 'alert');+ assert.ok(input.getAttribute('aria-describedby').split(' ').includes(err.id));+ assert.equal(input.getAttribute('aria-invalid'), 'true');+ const after = [...input.closest('[data-sheet-step]').querySelectorAll('*')];+ assert.ok(after.indexOf(err) > after.indexOf(input), 'error after the input');+ await type(input, 'https://backend.composio.dev/v3/mcp/abc');+ assert.equal(host.querySelector('[data-sheet-step="2"]').getAttribute('data-done'), 'true');+});++test('Sign-ins and settings has no account list of its own: no "What runs your kwant bots" there', () => {+ const { EnginesPanel } = m;+ const engines = [{ id: 'claude', name: 'Claude Code CLI', kind: 'cli', status: 'ready', enabled: true, ready: true, models: [], checked_at: null, uses: { profile_id: 'sys', label: 'This machine' } }];+ const api = { engines, error: null, rechecking: false, recheck: async () => {}, setEnabled: async () => {}, reload: async () => {} };+ const accounts = { profiles: [profile('sys', 'claude')], error: null, reload: async () => {} };+ const full = m.renderToStaticMarkup(h(EnginesPanel, { api, accounts }));+ assert.match(full, /data-route-summary/, 'the panel still has it elsewhere');+ const here = m.renderToStaticMarkup(h(EnginesPanel, { api, accounts, hideRoutes: true }));+ assert.doesNotMatch(here, /data-route-summary|What runs your/);+ assert.match(here, /Claude Code CLI/, 'sign-ins stay');+});++test('F16 and F13: tile labels sit on the tile’s bottom edge; the Sign-ins summary is 44 px', () => {+ const html = m.renderToStaticMarkup(h(m.AppsAccounts, pageProps()));+ const states = [...html.matchAll(/<span class="([^"]*)" data-tile-state=/g)].map((x) => x[1]);+ assert.equal(states.length, 6);+ for (const c of states) assert.match(c, /^mt-auto /);+ assert.match(html, /<summary class="[^"]*min-h-\[44px\][^"]*"[^>]*>[\s\S]*?Sign-ins and settings/);+});++test('round 5 (qa item 3): the page names bots on auto only on "Used first"; backups name bots pinned there', () => {+ // Rigel's space: Ann and Ben on Auto, Cody pinned to Codex, Gus pinned to Grok, and Grok put first.+ // The server lists auto bots on every engine's main account; the page keeps them to the first row.+ const kwants = [+ { id: 'k1', name: 'Ann', approvals_effective: 'ask', preferred_model: 'auto' },+ { id: 'k2', name: 'Ben', approvals_effective: 'ask', preferred_model: '' },+ { id: 'k3', name: 'Cody', approvals_effective: 'ask', preferred_model: 'codex' },+ { id: 'k4', name: 'Gus', approvals_effective: 'ask', preferred_model: 'grok/grok-4' },+ ];+ const [ann, ben, cody, gus] = kwants.map(({ id, name }) => ({ id, name }));+ const html = m.renderToStaticMarkup(+ h(+ m.AppsAccounts,+ pageProps({+ kwants,+ profiles: [profile('grok', 'grok', { is_default: true, priority: 10 }), profile('claude', 'claude', { is_default: true, priority: 20 }), profile('codex', 'codex', { is_default: true, priority: 30 })],+ engines: ['grok', 'claude', 'codex'].map((id) => ({ id, name: id[0].toUpperCase() + id.slice(1), kind: 'cli', status: 'ready', enabled: true, ready: true, models: [] })),+ data: data({+ connections: [+ acct('grok', { detail: 'grok', used_by: [ann, ben, gus] }),+ acct('claude', { detail: 'claude', used_by: [ann, ben] }),+ acct('codex', { detail: 'codex', used_by: [ann, ben, cody] }),+ ],+ }),+ }),+ ),+ );+ const part = (name) => html.split(`data-group="${name}"`)[1]?.split('data-group=')[0] ?? '';+ assert.match(part('first'), /Used by Ann, Ben and Gus/);+ const backup = part('backup');+ assert.match(backup, /Cody uses it first/);+ assert.doesNotMatch(backup, /Ann|Ben/, 'was "Ann, Ben and Cody use it first" and "Ann and Ben use it first"');+});diff --git a/frontend/tests/enginesAccounts.test.mjs b/frontend/tests/enginesAccounts.test.mjsindex 81286a52..da5cbff9 100644--- a/frontend/tests/enginesAccounts.test.mjs+++ b/frontend/tests/enginesAccounts.test.mjs@@ -74,7 +74,7 @@ test('Alex: one Claude card says bots use Personal, with This machine first andassert.match(html, /data-engine="claude" data-status="ready"/);assert.equal(summary(html, 'claude'), 'Bots use Personal');const names = [...card(html, 'claude').matchAll(/id="account-[^"]+-name"[^>]*>([^<]+)</g)].map((x) => x[1]);- assert.deepEqual(names, ['This machine', 'Personal']);+ assert.deepEqual(names, ['On this computer', 'Personal'], 'F11: signed out, so not "Signed in"');// This machine: not signed in, with the Batch 9 sign-in on its row; Personal is in use.const rows = card(html, 'claude').split('data-account=');assert.match(rows[1], /Needs sign-in/);@@ -179,3 +179,35 @@ test('a new space with no keys still offers every engine an account can be addedassert.match(card(html, 'codex'), /> Add account</);assert.match(html, /Not available on this computer \(1\)/, 'only Ollama is folded away');});++// ── F11 (design-check-r2): the sign-in cards never say "This machine" ────────────────────────────+test('F11: the built-in login reads "Signed in on this computer" only when on and signed in, else "On this computer"', () => {+ const signedIn = { ...machine, signed_in: true };+ const ready = engine('claude', { uses: { profile_id: 'prf_system_claude', label: 'This machine' } });+ const on = panel([ready], [signedIn, personal]);+ const names = (html) => [...card(html, 'claude').matchAll(/id="account-[^"]+-name"[^>]*>([^<]+)</g)].map((x) => x[1]);+ assert.equal(names(on)[0], 'Signed in on this computer');+ assert.equal(summary(on, 'claude'), 'Bots use the sign-in on this computer', 'the server label is mapped here; Vega changes the server string');+ assert.match(on, /Your Claude Code login/);+ assert.match(on, /aria-label="Use Claude Code on this computer for bots"/);+ assert.doesNotMatch(card(on, 'claude'), /This machine/, 'the route summary (routing.ts hostName) is a later follow-up and hidden on Apps & accounts');+ // Signed out: never "Signed in" beside "Needs sign-in".+ const out = panel([alexOn], [machine, personal]);+ assert.equal(names(out)[0], 'On this computer');+ assert.doesNotMatch(card(out, 'claude'), /Signed in on this computer/);+ assert.doesNotMatch(card(out, 'claude'), /This machine/);+ // Off: also "On this computer".+ const off = panel([ready], [{ ...signedIn, enabled: false }, personal]);+ assert.equal(names(off)[0], 'On this computer');+ // Off engine with only the built-in login usable: the header names it the same way.+ const offEngine = panel([engine('claude', { enabled: false, status: 'disabled', ready: false })], [signedIn]);+ assert.equal(summary(offEngine, 'claude'), 'Off · Turn on to use the sign-in on this computer');+});++test('R1 (design-check-r3): the built-in login title wraps instead of truncating; other names still truncate', () => {+ const html = panel([engine('claude', { uses: { profile_id: 'prf_system_claude', label: 'This machine' } })], [{ ...machine, signed_in: true }, personal]);+ const cls = (id) => html.match(new RegExp(`<span id="account-${id}-name" class="([^"]*)"`))[1];+ assert.doesNotMatch(cls('prf_system_claude'), /truncate|max-w-/);+ assert.match(cls('prf_system_claude'), /break-words/);+ assert.match(cls('prf_personal'), /truncate max-w-\[12rem\]/);+});diff --git a/frontend/tests/failover.test.mjs b/frontend/tests/failover.test.mjsindex 5bc7cc28..0e42b1ac 100644--- a/frontend/tests/failover.test.mjs+++ b/frontend/tests/failover.test.mjs@@ -72,18 +72,20 @@ test('moving rewrites only the priorities that change', () => {const markup = (props) => m.renderToStaticMarkup(h(m.AccountPriority, { profiles: list, engines: [engine('claude'), engine('codex'), engine('grok')], onChanged: async () => {}, now: NOW, ...props }));-test('the list is an ordered list with the caption, a status per row and labelled arrow buttons', () => {- const html = markup();- assert.match(html, /When one runs out, kwant bots move to the next that still works, in this order\./);- assert.equal((html.match(/<li /g) ?? []).length, 5);- assert.match(html, /<ol /);- assert.match(html, /Claude API key/);- assert.match(html, /Custom API/);- assert.match(html, /Out until/);- assert.match(html, /Signed out/);- assert.match(html, /disabled="" aria-label="Move Work \(Claude\) up"/, 'the first row can not go up');- assert.match(html, /disabled="" aria-label="Move Copilot \(Custom API\) down"/, 'the last row can not go down');- assert.doesNotMatch(html, /disabled="" aria-label="Move Personal \(Codex\) up"/);+test('the list groups accounts by how bots use them, titled by the AI, with a status per row', () => {+ const html = markup({ spaceName: 'Home' });+ assert.match(html, /Your bots in Home use the first account that’s ready\./);+ assert.doesNotMatch(html, /<ol |draggable|aria-label="Move /, 'no numbers, grip or arrows');+ const first = html.slice(html.indexOf('data-group="first"'), html.indexOf('data-group="backup"'));+ assert.equal((first.match(/<li /g) ?? []).length, 1);+ assert.match(first, /Out until/);+ const backup = html.slice(html.indexOf('data-group="backup"'), html.indexOf('data-group="not-used"'));+ assert.equal((backup.match(/data-use-first/g) ?? []).length, 3, 'Codex, Claude API key, Custom API');+ assert.match(backup, /Claude API key/);+ assert.match(backup, /Custom API/);+ const notUsed = html.slice(html.indexOf('data-group="not-used"'));+ assert.match(notUsed, /Grok/);+ assert.match(notUsed, /Signed out/);assert.match(html, /role="status"/);assert.doesNotMatch(html, /[\u{1F300}-\u{1FAFF}]/u, 'no emoji');});@@ -203,16 +205,15 @@ test('a signed-out account between ranked ones ends up after all of them once anassert.equal(m.priorityUpdates(many.slice(0, 1000), many.slice(1000)).at(-1).priority, 10_000);});-test('the list shows Grok under the ranked rows, with its status, no number and no arrows', () => {+test('a not-installed Grok sits under "Not used" with Set up, outside the order', () => {const html = m.renderToStaticMarkup(h(m.AccountPriority, { profiles: sysList, engines: sysEngines, onChanged: async () => {}, now: NOW }));- assert.equal((html.match(/<ol /g) ?? []).length, 1);- const ranked = html.slice(html.indexOf('<ol '), html.indexOf('</ol>'));- assert.equal((ranked.match(/<li /g) ?? []).length, 2, 'two ranked rows');- assert.doesNotMatch(ranked, /Grok|Not installed/);- const rest = html.slice(html.indexOf('</ol>'));- assert.match(rest, /Not in the order/);+ const used = html.slice(0, html.indexOf('data-group="not-used"'));+ assert.equal((used.match(/data-used-index=/g) ?? []).length, 2, 'two used rows');+ assert.doesNotMatch(used, /Grok|Not installed/);+ const rest = html.slice(html.indexOf('data-group="not-used"'));+ assert.match(rest, /Not used/);assert.match(rest, /Grok/);assert.match(rest, /Not installed/);- assert.doesNotMatch(rest, /aria-label="Move /, 'not reorderable');- assert.doesNotMatch(rest, /draggable/);+ assert.match(rest, /data-set-up/);+ assert.doesNotMatch(rest, /data-use-first|data-row-menu/, 'not reorderable');});diff --git a/frontend/tests/ia.test.mjs b/frontend/tests/ia.test.mjsindex 8bb545d5..782d0d3b 100644--- a/frontend/tests/ia.test.mjs+++ b/frontend/tests/ia.test.mjs@@ -46,7 +46,7 @@ test('every canonical address round-trips', () => {assert.ok(nav.sameView(back.view, v), seg);}assert.equal(nav.viewSegment({ kind: 'inbox', tab: 'loose' }), 'inbox/loose-ends');- assert.equal(nav.viewSegment({ kind: 'settings', scope: 'space', tab: 'accounts' }), 'settings/accounts');+ assert.equal(nav.viewSegment({ kind: 'settings', scope: 'space', tab: 'apps' }), 'settings/apps');});test('old addresses resolve to the new place and are flagged for rewriting', () => {@@ -54,7 +54,7 @@ test('old addresses resolve to the new place and are flagged for rewriting', ()away: 'inbox','while-you-were-away': 'inbox','loose-ends': 'inbox/loose-ends',- connections: 'settings/connections',+ connections: 'settings/apps',routines: 'settings/routines','mission-board': 'board',missions: 'board',@@ -79,9 +79,12 @@ test('space paths carry the view, and a view wins over a chat', () => {assert.equal(r.spaceId, 'spc_a');assert.equal(nav.viewSegment(r.view), 'inbox');assert.equal(r.legacy, true);- const s = nav.parseSpacePath('/s/spc_a/settings/accounts');- assert.equal(nav.viewSegment(s.view), 'settings/accounts');+ const s = nav.parseSpacePath('/s/spc_a/settings/apps');+ assert.equal(nav.viewSegment(s.view), 'settings/apps');assert.ok(!s.legacy);+ const old = nav.parseSpacePath('/s/spc_a/settings/accounts');+ assert.equal(nav.viewSegment(old.view), 'settings/apps');+ assert.ok(old.legacy, 'the old Accounts address is rewritten');assert.equal(nav.spacePath('spc_a', null, { kind: 'inbox', tab: 'loose' }), '/s/spc_a/inbox/loose-ends');assert.equal(nav.spacePath('spc_a', { channelId: 'c1' }, { kind: 'board' }), '/s/spc_a/board');assert.ok(!nav.spacePath('spc_a', { channelId: 'c1' }).includes('board'));@@ -176,19 +179,20 @@ test('phones keep exactly one switcher', () => {// Item 11: one Settingsconst settingsProps = (over = {}) => ({- space, scope: 'space', onScope: noop, tab: 'connections', onTab: noop, onClose: noop,- connections: 'CONNECTIONS-HERE', appSettings: 'APP-SETTINGS-HERE', onOpenArchived: noop, kwants, channels: [], teams,+ space, scope: 'space', onScope: noop, tab: 'apps', appsSection: { section: 'advanced', seq: 1 }, onTab: noop, onClose: noop,+ connections: () => 'CONNECTIONS-HERE', appSettings: 'APP-SETTINGS-HERE', onOpenArchived: noop, kwants, channels: [], teams,onSpaceSaved: noop, onArchived: noop, onNewBot: noop, onEditBot: noop, onOpenSkills: noop, onNewTeam: noop, onManageTeam: noop, onOpenTools: noop,...over,});-test('Settings has This space and All spaces, and Connections is a section of This space', () => {+test('Settings has This space and All spaces, and Connections live in Apps & accounts › Advanced', () => {const html = ui.settings(settingsProps());assert.match(html, /data-settings-scope="space"[^>]*>|aria-selected="true"[^>]*data-settings-scope="space"/);assert.match(html, /This space/);assert.match(html, /All spaces/);assert.match(html, /data-settings-connections[^>]*>CONNECTIONS-HERE/);- for (const t of ['General', 'Accounts', 'Connections', 'Routines']) assert.match(html, new RegExp(`>${t}<`), t);+ for (const t of ['General', 'Apps & accounts', 'Routines']) assert.match(html, new RegExp(`>${t}<`), t);+ for (const t of ['Accounts', 'Connections', 'Tools']) assert.doesNotMatch(html, new RegExp(`>${t}</`), `${t} is no longer its own tab`);assert.doesNotMatch(html, /APP-SETTINGS-HERE/);});@@ -200,7 +204,7 @@ test('All spaces shows the app settings, archived spaces and install, not the spassert.doesNotMatch(html, /aria-label="Default settings"/);});-test('API keys live only in This space › Accounts; App settings links there', () => {+test('API keys live only in This space › Apps & accounts; App settings links there', () => {const keys = ui.apiKeys({ defaultOpen: false });assert.match(keys, /API keys and Ollama/);assert.match(keys, /data-api-keys/);@@ -208,9 +212,9 @@ test('API keys live only in This space › Accounts; App settings links there',const app = src('components/SettingsModal.tsx');assert.match(app, /data-api-keys-link/);assert.match(app, /onClick=\{onOpenApiKeys\}|onOpenApiKeys\(\)/);- assert.match(app, /Settings › This space › Accounts/);+ assert.match(app, /Settings › This space › Apps & accounts/);assert.doesNotMatch(app, /Anthropic API Key|placeholder="sk-ant/, 'no key fields left in App settings');- assert.match(src('App.tsx'), /onOpenApiKeys=\{\(\) => openSpaceSettings\('accounts'\)\}/);+ assert.match(src('App.tsx'), /onOpenApiKeys=\{\(\) => openSpaceSettings\('apps', 'accounts'\)\}/);});test('the rail gear opens Settings › All spaces and the header entry opens This space', () => {diff --git a/frontend/tests/isolationNotice.test.mjs b/frontend/tests/isolationNotice.test.mjsindex beb9df0f..4c306365 100644--- a/frontend/tests/isolationNotice.test.mjs+++ b/frontend/tests/isolationNotice.test.mjs@@ -56,8 +56,8 @@ const ROWS = [['download_failed', /sealed box isn’t ready yet\.$/, /^The one-time setup didn’t finish\. Try it again in Computer settings, then Retry\.$/, 'standard', ['retry', 'computer']],['download_needed', /sealed box isn’t ready yet\.$/, /^The one-time setup didn’t finish\./, 'standard', ['retry', 'computer']],['relay_down', /Claude’s sealed box couldn’t start\.$/, /^kwant couldn’t connect Claude to your sign-in\. Restart kwant, then Retry\.$/, 'standard', ['retry', 'computer']],- ['sign_in_expired', /your Claude sign-in has expired\.$/, /^Sign in again in Settings › This space › Accounts, then Retry\.$/, null, ['retry', 'accounts']],- ['no_credential', /there’s no Claude sign-in for it on this computer\.$/, /^Sign in to Claude in Settings › This space › Accounts, then Retry\.$/, null, ['retry', 'accounts']],+ ['sign_in_expired', /your Claude sign-in has expired\.$/, /^Sign in again in Settings › This space › Apps & accounts, then Retry\.$/, null, ['retry', 'accounts']],+ ['no_credential', /there’s no Claude sign-in for it on this computer\.$/, /^Sign in to Claude in Settings › This space › Apps & accounts, then Retry\.$/, null, ['retry', 'accounts']],['host_is_root', /Claude’s sealed box couldn’t start\.$/, /^kwant is running as root, so Claude’s sealed box can’t run as you\./, 'standard', ['retry', 'computer']],['folder_name_unsupported', /Claude can’t take this folder into its sealed box\.$/, /^The folder’s name has characters kwant can’t pass to Claude’s sealed box, like a line break\. Rename the folder, then Retry\.$/, 'nothing_ran', ['retry']],['folder_record_failed', /Claude’s sealed box couldn’t start\.$/, /^kwant couldn’t note that this folder is used by Claude’s sealed box, so it didn’t start Claude\./, 'standard', ['retry', 'computer']],diff --git a/frontend/tests/polish063.test.mjs b/frontend/tests/polish063.test.mjsindex 5175d129..06d6c34a 100644--- a/frontend/tests/polish063.test.mjs+++ b/frontend/tests/polish063.test.mjs@@ -90,15 +90,15 @@ test('1: on phones Settings is still a full-screen dialog', () => {});test('1: picking another space keeps Settings open: This space follows the new space, All spaces stays', () => {- const accounts = { kind: 'settings', scope: 'space', tab: 'accounts' };+ const accounts = { kind: 'settings', scope: 'space', tab: 'apps' };const app = { kind: 'settings', scope: 'app' };assert.deepEqual(m.viewAfterSpaceSwitch(accounts), accounts);assert.deepEqual(m.viewAfterSpaceSwitch(app), app);// Anything else lands in a chat, as before.for (const v of [null, undefined, { kind: 'inbox', tab: 'new' }, { kind: 'board' }, { kind: 'parallel' }]) assert.equal(m.viewAfterSpaceSwitch(v), null);// The new space opens on that view: its address names the new space and the same Settings tab.- assert.equal(m.spacePath('spc_b', null, accounts), '/s/spc_b/settings/accounts');- const r = m.parseSpacePath('/s/spc_b/settings/accounts');+ assert.equal(m.spacePath('spc_b', null, accounts), '/s/spc_b/settings/apps');+ const r = m.parseSpacePath('/s/spc_b/settings/apps');assert.equal(r.spaceId, 'spc_b');assert.ok(m.sameView(r.view, accounts));});@@ -116,7 +116,7 @@ test('2: the rail and Ctrl/⌘ 1–9 both go through the one switch, which carri});test('2: Back after a switch inside Settings steps back to the old space, then out of Settings, without looping', () => {- const view = { kind: 'settings', scope: 'space', tab: 'accounts' };+ const view = { kind: 'settings', scope: 'space', tab: 'apps' };// History: chat in A → Settings in A → (Ctrl+2) Settings in B.const stack = ['/s/spc_a/c/ch1', m.spacePath('spc_a', null, view), m.spacePath('spc_b', null, m.viewAfterSpaceSwitch(view))];assert.equal(new Set(stack).size, 3, 'three distinct entries: Back always moves');diff --git a/frontend/tests/settingsFocus.test.mjs b/frontend/tests/settingsFocus.test.mjsindex 066f1323..b0de8018 100644--- a/frontend/tests/settingsFocus.test.mjs+++ b/frontend/tests/settingsFocus.test.mjs@@ -140,7 +140,7 @@ test('D1: opening Settings moves focus to its title; Close, Back to chats and Es});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' } });+ const v = await mountSpace({ initialView: { kind: 'settings', scope: 'space', tab: 'apps' } });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');diff --git a/frontend/tests/whatsNew076.test.mjs b/frontend/tests/whatsNew076.test.mjsindex 7ce75e5d..d9b73b58 100644--- a/frontend/tests/whatsNew076.test.mjs+++ b/frontend/tests/whatsNew076.test.mjs@@ -63,7 +63,7 @@ test('validator: every bundled whatsnew file keeps the limits, its name matchesfor (const h of e.highlights) if (h.open) assert.ok(s.highlightView(h), `${v} ${h.id}: ${h.open}`);}assert.equal(real['0.7.5'].highlights.find((h) => h.id === 'teams').open, 'settings/teams');- assert.equal(real['0.7.5'].highlights.find((h) => h.id === 'telegram').open, 'settings/connections');+ assert.equal(real['0.7.5'].highlights.find((h) => h.id === 'telegram').open, 'settings/apps');});test('validator: names each broken limit', () => {