Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

37.1 KB
Raw Blame
import { platformText } from '@/lib/platforms';
import type { TFunction } from 'i18next';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
  Bot,
  Check,
  ChevronDown,
  ChevronUp,
  Copy,
  KeyRound,
  Loader2,
  Plus,
  RefreshCw,
  Shield,
  Trash2,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { getEnabledPlatforms, platformSupportsToolcallDelivery } from '../../lib/platforms';
import { FolderBrowser } from '../ui/folder-browser';
import { copyTextToClipboard } from '../../lib/utils';
import { PlatformIcon } from '../visual';
import { RoutingConfigPanel } from '../shared/RoutingConfigPanel';
import { scopeRouteSummary } from '../../lib/scopeRouteSummary';
import { scopeSettingsChange, USER_SCOPE_FIELDS } from '../../lib/scopeSettingsPatch';
import { SearchField, ToggleSwitch } from '../settings/SettingsPrimitives';
import { Button } from '../ui/button';
import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
import { Input } from '../ui/input';

interface UserConfig {
  expected_agent_name?: string | null;
  display_name: string;
  is_admin: boolean;
  bound_at: string;
  enabled: boolean;
  show_message_types: string[];
  custom_cwd: string;
  routing: {
    agent_name?: string | null;
    model?: string | null;
    reasoning_effort?: string | null;
    opencode_agent?: string | null;
    claude_agent?: string | null;
    codex_agent?: string | null;
  };
}

interface BindCodeItem {
  code: string;
  type: string;
  created_at: string;
  expires_at: string | null;
  is_active: boolean;
  used_by: string[];
}

interface AggregatedUser {
  key: string; // `${platform}::${userId}`
  platform: string;
  userId: string;
  config: UserConfig;
}

const AVATAR_TONES = [
  { textCls: 'text-mint-ink', bg: 'rgba(91,255,160,0.12)', border: 'rgba(91,255,160,0.33)' },
  { textCls: 'text-cyan-ink', bg: 'rgba(63,224,229,0.12)', border: 'rgba(63,224,229,0.33)' },
  { textCls: 'text-violet-ink', bg: 'rgba(124,91,255,0.12)', border: 'rgba(124,91,255,0.33)' },
  { textCls: 'text-gold-ink', bg: 'rgba(255,200,87,0.12)', border: 'rgba(255,200,87,0.33)' },
];

const hashCode = (s: string) => {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
  return Math.abs(h);
};

const getInitials = (name: string, fallback: string): string => {
  const trimmed = (name || '').trim();
  if (!trimmed) return (fallback || '??').slice(0, 2).toUpperCase();
  const parts = trimmed.split(/\s+/);
  if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  const onlyAlpha = trimmed.replace(/[^a-zA-Z]/g, '');
  return (onlyAlpha || trimmed).slice(0, 2).toUpperCase();
};

const displayNameForUser = (u: AggregatedUser): string => {
  const name = (u.config.display_name || '').trim();
  return name || u.userId;
};

const formatExpiry = (expiresAt: string | null): string => {
  if (!expiresAt) return '';
  const ms = new Date(expiresAt).getTime() - Date.now();
  if (ms <= 0) return '00:00';
  const totalSeconds = Math.floor(ms / 1000);
  const days = Math.floor(totalSeconds / 86_400);
  if (days > 0) return `${days}d`;
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  if (hours > 0) return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
};

// ─── Bind Code Section ───────────────────────────────────────────────────

interface BindCodeCardProps {
  refreshTrigger: number;
  onCodesChanged: () => void;
}

const BindCodeCard: React.FC<BindCodeCardProps> = ({ refreshTrigger, onCodesChanged }) => {
  const { t } = useTranslation();
  const api = useApi();
  const { showToast } = useToast();
  const [codes, setCodes] = useState<BindCodeItem[]>([]);
  const [showFormModal, setShowFormModal] = useState(false);
  const [showAllModal, setShowAllModal] = useState(false);
  const [newType, setNewType] = useState<'one_time' | 'expiring'>('one_time');
  const [newExpiry, setNewExpiry] = useState('');
  const [copiedCode, setCopiedCode] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [tick, setTick] = useState(0);

  const loadCodes = async () => {
    try {
      const result = await api.getBindCodes();
      if (result.ok) setCodes(result.bind_codes || []);
    } catch (e) {
      console.error('Failed to load bind codes:', e);
    }
  };

  useEffect(() => { loadCodes(); }, [refreshTrigger]);

  // Tick every second to refresh the countdown for expiring codes
  useEffect(() => {
    const id = setInterval(() => setTick((v) => v + 1), 1000);
    return () => clearInterval(id);
  }, []);

  const getCodeStatus = (bc: BindCodeItem) => {
    if (!bc.is_active) return bc.type === 'one_time' && bc.used_by.length > 0 ? 'used' : 'inactive';
    if (bc.type === 'expiring' && bc.expires_at && new Date(bc.expires_at) < new Date()) return 'expired';
    return 'active';
  };

  const activeCodes = useMemo(() => codes.filter((bc) => getCodeStatus(bc) === 'active'), [codes, tick]);
  const otherCodes = useMemo(() => codes.filter((bc) => getCodeStatus(bc) !== 'active'), [codes, tick]);
  const primary = activeCodes[0];
  const moreCount = Math.max(0, activeCodes.length - 1);

  const handleCreate = async () => {
    setLoading(true);
    try {
      const result = await api.createBindCode(newType, newType === 'expiring' ? newExpiry : undefined);
      if (result.ok) {
        showToast(t('bindCode.created'));
        setShowFormModal(false);
        setNewType('one_time');
        setNewExpiry('');
        loadCodes();
        onCodesChanged();
      }
    } catch (e) {
      console.error('Failed to create bind code:', e);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (code: string) => {
    try {
      const result = await api.deleteBindCode(code);
      if (result.ok) {
        showToast(t('bindCode.deleted'));
        loadCodes();
        onCodesChanged();
      }
    } catch (e) {
      console.error('Failed to delete bind code:', e);
    }
  };

  const handleCopy = async (code: string) => {
    const copied = await copyTextToClipboard(`bind ${code}`);
    if (!copied) {
      showToast(t('common.copyFailed'), 'error');
      return;
    }
    setCopiedCode(code);
    setTimeout(() => setCopiedCode(null), 2000);
  };

  return (
    <>
      <div
        className="flex flex-col gap-5 rounded-2xl border bg-surface-2/40 p-5 shadow-[0_24px_48px_-30px_rgba(91,255,160,0.20)] md:flex-row md:flex-wrap md:items-stretch md:justify-between md:gap-6 md:p-6"
        style={{ borderColor: 'rgba(91,255,160,0.33)' }}
      >
        {/* Actions area — appears first on mobile, right on desktop */}
        <div className="-order-1 flex flex-col items-stretch gap-3 md:order-none md:shrink-0 md:items-end">
          {primary ? (
            <ActiveCodeBox
              code={primary}
              onCopy={() => handleCopy(primary.code)}
              copied={copiedCode === primary.code}
              t={t}
            />
          ) : (
            <span className="inline-flex items-center gap-1.5 font-mono text-[10px] font-bold tracking-[0.12em] text-muted">
              <span className="size-1.5 rounded-full bg-muted" />
              {t('bindCode.noActiveCode')}
            </span>
          )}
          <div className="flex flex-wrap items-center gap-2">
            {moreCount > 0 || otherCodes.length > 0 ? (
              <Button
                type="button"
                variant="secondary"
                size="xs"
                onClick={() => setShowAllModal(true)}
                className="text-muted hover:text-foreground"
              >
                {moreCount > 0
                  ? t('bindCode.viewMore', { count: moreCount })
                  : t('bindCode.viewUnavailable', { count: otherCodes.length })}
              </Button>
            ) : null}
            {primary && (
              <Button
                type="button"
                variant="secondary"
                size="xs"
                onClick={() => handleDelete(primary.code)}
                className="text-muted hover:border-destructive/40 hover:text-destructive-ink"
              >
                {t('bindCode.revoke')}
              </Button>
            )}
            <Button type="button" variant="brand" size="xs" onClick={() => setShowFormModal(true)}>
              <Plus size={14} strokeWidth={2.4} />
              {primary ? t('bindCode.newCode') : t('bindCode.createCode')}
            </Button>
          </div>
        </div>

        {/* Invite copy — appears below actions on mobile, left on desktop */}
        <div className="flex min-w-0 flex-col gap-2.5 md:flex-1">
          <span className="inline-flex w-max items-center gap-1.5 rounded-full border border-mint/40 bg-mint-soft px-2.5 py-1 font-mono text-[10px] font-bold tracking-[0.12em] text-mint-ink">
            <KeyRound size={11} strokeWidth={2.4} />
            {t('bindCode.badge')}
          </span>
          <h3 className="text-[18px] font-bold leading-tight tracking-[-0.3px] text-foreground">
            {t('bindCode.inviteTitle')}
          </h3>
          <p className="max-w-[560px] text-[13px] leading-[1.55] text-muted">
            {t('bindCode.inviteDescription')}
          </p>
        </div>
      </div>

      {showFormModal && (
        <Modal title={t('bindCode.newCode')} onClose={() => setShowFormModal(false)}>
          <div className="space-y-4 p-4 text-sm">
            <div className="flex items-center gap-4">
              <span className="text-muted">{t('bindCode.codeType')}</span>
              <label className="flex items-center gap-1.5 text-foreground">
                <input
                  type="radio"
                  checked={newType === 'one_time'}
                  onChange={() => setNewType('one_time')}
                  className="text-mint-ink"
                />
                {t('bindCode.oneTime')}
              </label>
              <label className="flex items-center gap-1.5 text-foreground">
                <input
                  type="radio"
                  checked={newType === 'expiring'}
                  onChange={() => setNewType('expiring')}
                  className="text-mint-ink"
                />
                {t('bindCode.expiring')}
              </label>
            </div>
            {newType === 'expiring' && (
              <div className="flex items-center gap-3">
                <label className="text-muted">{t('bindCode.expirationDate')}</label>
                <Input
                  type="date"
                  value={newExpiry}
                  onChange={(e) => setNewExpiry(e.target.value)}
                  min={new Date().toISOString().split('T')[0]}
                />
              </div>
            )}
            <Button
              type="button"
              variant="brand"
              size="xs"
              onClick={handleCreate}
              disabled={loading || (newType === 'expiring' && !newExpiry)}
            >
              {t('bindCode.generate')}
            </Button>
          </div>
        </Modal>
      )}

      {showAllModal && (
        <Modal title={t('bindCode.allCodesTitle')} onClose={() => setShowAllModal(false)}>
          <div className="max-h-[60vh] overflow-y-auto p-2">
            {codes.length === 0 ? (
              <p className="p-4 text-sm text-muted">{t('bindCode.noCodes')}</p>
            ) : (
              <div className="divide-y divide-border">
                {codes.map((bc) => {
                  const status = getCodeStatus(bc);
                  return (
                    <div key={bc.code} className="flex flex-wrap items-center justify-between gap-3 px-3 py-2.5">
                      <div className="flex flex-wrap items-center gap-2">
                        <code className="rounded border border-border bg-surface px-2 py-0.5 font-mono text-[12px] text-foreground">bind {bc.code}</code>
                        <span
                          className={clsx(
                            'rounded-full border px-2 py-0.5 text-[10px] font-mono font-bold tracking-[0.12em]',
                            status === 'active' && 'border-mint/40 bg-mint-soft text-mint-ink',
                            status === 'used' && 'border-border bg-foreground/[0.04] text-muted',
                            status === 'expired' && 'border-gold/40 bg-gold/10 text-gold-ink',
                            status === 'inactive' && 'border-border bg-foreground/[0.04] text-muted',
                          )}
                        >
                          {t(`bindCode.${status}`)}
                        </span>
                        <span className="text-[11px] text-muted">
                          {bc.type === 'one_time' ? t('bindCode.oneTime') : t('bindCode.expiring')}
                        </span>
                        {bc.used_by.length > 0 && (
                          <span className="text-[11px] text-muted">{t('bindCode.usedBy', { count: bc.used_by.length })}</span>
                        )}
                        {bc.expires_at && (
                          <span className="text-[11px] text-muted">
                            {t('bindCode.expiresAt', { date: new Date(bc.expires_at).toLocaleDateString() })}
                          </span>
                        )}
                      </div>
                      <div className="flex items-center gap-1.5">
                        <button
                          type="button"
                          onClick={() => handleCopy(bc.code)}
                          title={t('bindCode.copy')}
                          className="rounded p-1.5 text-muted transition-colors hover:text-foreground"
                        >
                          {copiedCode === bc.code ? <Check size={14} className="text-mint-ink" /> : <Copy size={14} />}
                        </button>
                        {bc.is_active && (
                          <button
                            type="button"
                            onClick={() => handleDelete(bc.code)}
                            title={t('bindCode.delete')}
                            className="rounded p-1.5 text-muted transition-colors hover:text-destructive-ink"
                          >
                            <Trash2 size={14} />
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </Modal>
      )}
    </>
  );
};

const ActiveCodeBox: React.FC<{
  code: BindCodeItem;
  onCopy: () => void;
  copied: boolean;
  t: TFunction;
}> = ({ code, onCopy, copied, t }) => {
  const expiryLabel = code.type === 'expiring' && code.expires_at
    ? t('bindCode.expiresIn', { time: formatExpiry(code.expires_at) })
    : t('bindCode.noExpiry');

  return (
    <div className="flex flex-col items-stretch gap-1 md:items-end">
      <span className="font-mono text-[10px] font-bold tracking-[0.12em] text-gold-ink">
        {t('bindCode.activeCodeLabel')} · {expiryLabel}
      </span>
      <button
        type="button"
        onClick={onCopy}
        className="inline-flex items-center justify-between gap-2.5 rounded-lg border bg-background px-4 py-2.5 transition-colors hover:brightness-110 md:justify-start"
        style={{ borderColor: 'rgba(255,200,87,0.33)' }}
        title={t('bindCode.copy')}
      >
        <span className="font-mono text-[18px] font-bold tracking-[0.12em] text-gold-ink">bind {code.code}</span>
        {copied ? (
          <Check size={14} className="shrink-0 text-mint-ink" />
        ) : (
          <Copy size={14} className="shrink-0 text-muted" />
        )}
      </button>
    </div>
  );
};

const Modal: React.FC<{ title: string; onClose: () => void; children: React.ReactNode }> = ({ title, onClose, children }) => (
  <Dialog open onOpenChange={(next) => { if (!next) onClose(); }}>
    <DialogContent
      aria-describedby={undefined}
      closeLabel={title}
      className="flex min-w-0 max-h-[calc(100dvh-2rem)] w-full max-w-2xl flex-col overflow-y-auto rounded-2xl border border-border bg-surface-2 p-0 shadow-[0_42px_80px_-42px_rgba(0,0,0,0.85)]"
    >
      <div className="flex min-w-0 items-center justify-between gap-3 border-b border-border px-4 py-3">
        <DialogTitle className="min-w-0 flex-1 break-words text-base font-semibold text-foreground [overflow-wrap:anywhere]">
          {title}
        </DialogTitle>
      </div>
      {children}
    </DialogContent>
  </Dialog>
);

// ─── User List Page ──────────────────────────────────────────────────────

export const UserList: React.FC = () => {
  const { capabilities } = useInstanceAuthorization();
  const canManageAccessMembers = capabilities.can_manage_access_members;
  const { t } = useTranslation();
  const api = useApi();
  const { showToast } = useToast();
  const [savingRows, setSavingRows] = useState<Record<string, number>>({});
  const [newSessionRows, setNewSessionRows] = useState<Record<string, boolean>>({});
  const [usersByPlatform, setUsersByPlatform] = useState<Record<string, Record<string, UserConfig>>>({});
  const [config, setConfig] = useState<any>({});
  const [browsingCwdFor, setBrowsingCwdFor] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [showDisabled, setShowDisabled] = useState(false);
  const [expandedKey, setExpandedKey] = useState<string | null>(null);
  const [searchParams, setSearchParams] = useSearchParams();
  const rowRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const userSaveVersionRef = useRef<Record<string, number>>({});
  const routeSaveVersionRef = useRef<Record<string, number>>({});

  const enabledPlatforms = useMemo(() => getEnabledPlatforms(config), [config]);
  const vibeAgents = config.agent_catalog?.agents || [];
  const defaultAgentName = config.agent_catalog?.default_agent_name || null;
  const agentByName = useMemo(
    () => Object.fromEntries(vibeAgents.map((agent: any) => [agent.name, agent])),
    [vibeAgents]
  );

  useEffect(() => {
    api.getConfig().then(async (loadedConfig) => {
      try {
        const settings = await api.getSettings(loadedConfig.platform);
        setConfig({ ...loadedConfig, agent_catalog: settings.agent_catalog });
      } catch {
        setConfig(loadedConfig);
      }
    });
  }, []);

  const loadAllUsers = async () => {
    if (!enabledPlatforms.length) return;
    const results = await Promise.all(
      enabledPlatforms.map(async (p) => {
        try {
          const r = await api.getUsers(p);
          return [p, r.ok ? (r.users || {}) : {}] as const;
        } catch {
          return [p, {}] as const;
        }
      })
    );
    const next: Record<string, Record<string, UserConfig>> = {};
    for (const [p, u] of results) next[p] = u as Record<string, UserConfig>;
    setUsersByPlatform(next);
    openLinkedUser(next);
  };

  // A chat that cannot show a settings form links to its row (`?platform=…&user=…`):
  // open it once it loads, then drop the link so a reload doesn't reopen it.
  const linkedScrollRef = useRef<string | null>(null);
  const openLinkedUser = (users: Record<string, Record<string, UserConfig>>) => {
    const platform = searchParams.get('platform');
    const userId = searchParams.get('user');
    const linked = platform && userId ? users[platform]?.[userId] : undefined;
    if (!platform || !userId || !linked) return;
    const key = `${platform}::${userId}`;
    setSearchQuery('');
    if (!linked.enabled) setShowDisabled(true);
    setExpandedKey(key);
    linkedScrollRef.current = key;
    setSearchParams((prev) => {
      const params = new URLSearchParams(prev);
      params.delete('platform');
      params.delete('user');
      return params;
    }, { replace: true });
  };
  useEffect(() => {
    if (!expandedKey || linkedScrollRef.current !== expandedKey) return;
    linkedScrollRef.current = null;
    rowRefs.current[expandedKey]?.scrollIntoView?.({ block: 'center' });
  }, [expandedKey]);

  useEffect(() => { loadAllUsers(); }, [enabledPlatforms.join(','), refreshTrigger]);

  // Aggregate users
  const aggregated = useMemo<AggregatedUser[]>(() => {
    const flat: AggregatedUser[] = [];
    for (const [platform, users] of Object.entries(usersByPlatform)) {
      for (const [userId, cfg] of Object.entries(users)) {
        flat.push({ key: `${platform}::${userId}`, platform, userId, config: cfg });
      }
    }
    return flat.sort(
      (a, b) =>
        Number(b.config.is_admin) - Number(a.config.is_admin) ||
        displayNameForUser(a).localeCompare(displayNameForUser(b)) ||
        a.userId.localeCompare(b.userId)
    );
  }, [usersByPlatform]);

  // Filtered and search-applied list
  const visibleUsers = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    return aggregated.filter((u) => {
      if (!showDisabled && !u.config.enabled) return false;
      if (!q) return true;
      const name = (u.config.display_name || '').toLowerCase();
      const id = u.userId.toLowerCase();
      return name.includes(q) || id.includes(q);
    });
  }, [aggregated, searchQuery, showDisabled]);

  // Each edit sends only what it changed on one user; the stored row it gets
  // back replaces the local one unless a newer edit of that user is in flight.
  // The row shows the save in progress; only a failure is announced.
  const persistUser = async (platform: string, userId: string, base: UserConfig, next: UserConfig) => {
    const change = scopeSettingsChange(base, next, USER_SCOPE_FIELDS);
    if (!change) return;
    const rowKey = `${platform}::${userId}`;
    const version = (userSaveVersionRef.current[rowKey] || 0) + 1;
    userSaveVersionRef.current[rowKey] = version;
    // The session note answers the latest route change, whatever else saved since.
    const routeVersion = 'routing' in change.changes ? (routeSaveVersionRef.current[rowKey] || 0) + 1 : null;
    if (routeVersion !== null) routeSaveVersionRef.current[rowKey] = routeVersion;
    setSavingRows((prev) => ({ ...prev, [rowKey]: (prev[rowKey] || 0) + 1 }));
    try {
      const result = await api.patchScopeSettings({ platform, scope: 'user', id: userId, ...change });
      if (routeVersion !== null && routeSaveVersionRef.current[rowKey] === routeVersion) {
        setNewSessionRows((prev) => ({ ...prev, [rowKey]: result.needs_new_session === true }));
      }
      const stored = result.settings as UserConfig | undefined;
      if (userSaveVersionRef.current[rowKey] !== version) return;
      if (stored) {
        setUsersByPlatform((prev) => ({ ...prev, [platform]: { ...(prev[platform] || {}), [userId]: stored } }));
      }
    } catch {
      showToast(t('userList.settingsSaveFailed'), 'error');
      const result = await api.getUsers(platform).catch(() => null);
      if (result?.ok && userSaveVersionRef.current[rowKey] === version) {
        setUsersByPlatform((prev) => ({ ...prev, [platform]: result.users || {} }));
      }
    } finally {
      setSavingRows((prev) => ({ ...prev, [rowKey]: Math.max(0, (prev[rowKey] || 1) - 1) }));
    }
  };

  const updateUser = (platform: string, userId: string, patch: Partial<UserConfig>) => {
    const base = (usersByPlatform[platform] || {})[userId] || defaultUserConfig();
    const next = { ...base, ...patch };
    if (!next.routing || typeof next.routing !== 'object') {
      next.routing = { agent_name: null };
    }
    setUsersByPlatform((prev) => ({ ...prev, [platform]: { ...(prev[platform] || {}), [userId]: next } }));
    void persistUser(platform, userId, base, next);
  };

  const handleToggleAdmin = async (platform: string, userId: string, isAdmin: boolean) => {
    const platformUsers = usersByPlatform[platform] || {};
    const current = platformUsers[userId];
    const adminCount = Object.values(platformUsers).filter((u) => u.is_admin).length;
    if (current?.is_admin && !isAdmin && adminCount <= 1) {
      if (!confirm(t('userList.lastAdminDemoteWarning'))) return;
    }
    try {
      const result = await api.toggleAdmin(userId, isAdmin, platform);
      if (result.ok) {
        showToast(t('userList.adminToggled'));
        loadAllUsers();
      } else {
        showToast(result.error || t('userList.cannotRemoveLastAdmin'), 'error');
      }
    } catch (e) {
      console.error('Failed to toggle admin:', e);
    }
  };

  const handleRemoveUser = async (platform: string, userId: string) => {
    const platformUsers = usersByPlatform[platform] || {};
    const current = platformUsers[userId];
    const adminCount = Object.values(platformUsers).filter((u) => u.is_admin).length;
    const warningKey = current?.is_admin && adminCount <= 1 ? 'userList.lastAdminRemoveWarning' : 'userList.removeConfirm';
    if (!confirm(t(warningKey))) return;
    try {
      const result = await api.removeUser(userId, platform);
      if (result.ok) {
        showToast(t('userList.userRemoved'));
        loadAllUsers();
      } else {
        showToast(result.error || '', 'error');
      }
    } catch (e) {
      console.error('Failed to remove user:', e);
    }
  };

  const defaultUserConfig = (): UserConfig => ({
    display_name: '',
    is_admin: false,
    bound_at: '',
    enabled: true,
    show_message_types: ['assistant'],
    custom_cwd: '',
    routing: {
      agent_name: null,
      model: null,
      reasoning_effort: null,
      opencode_agent: null,
      claude_agent: null,
      codex_agent: null,
    },
  });

  const availableMessageTypes = (platform: string): string[] =>
    platformSupportsToolcallDelivery(config, platform) ? ['assistant', 'toolcall'] : ['assistant'];

  const totalCount = aggregated.length;

  return (
    <>
      <div className="flex h-full flex-col gap-5">
        {/* Page header */}
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex flex-col gap-1.5">
            <h1 className="text-[28px] font-bold leading-tight tracking-[-0.4px] text-foreground">
              {t('userList.title')}
            </h1>
            <p className="text-[14px] leading-[1.55] text-muted">{t('userList.subtitle')}</p>
          </div>
          <div className="flex items-center gap-2">
            <SearchField
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder={t('userList.filterPlaceholder')}
              className="w-full sm:w-[280px]"
            />
            <Button
              type="button"
              variant="secondary"
              size="sm"
              onClick={() => setRefreshTrigger((v) => v + 1)}
              title={t('common.refresh')}
              className="px-3"
            >
              <RefreshCw size={14} />
            </Button>
          </div>
        </div>

        {/* Bind code card */}
        {canManageAccessMembers && <BindCodeCard
          refreshTrigger={refreshTrigger}
          onCodesChanged={() => setRefreshTrigger((v) => v + 1)}
        />}

        {/* List header */}
        <div className="flex items-center justify-between px-1 py-2">
          <div className="flex items-center gap-2">
            <span className="text-[15px] font-semibold text-foreground">{t('userList.allUsers')}</span>
            <span className="rounded-full bg-foreground/[0.08] px-1.5 py-0.5 font-mono text-[11px] font-bold text-muted">
              {totalCount}
            </span>
          </div>
          <label className="flex cursor-pointer items-center gap-1.5 text-[12px] text-muted">
            <span>{t('userList.showDisabled')}</span>
            <ToggleSwitch
              enabled={showDisabled}
              onClick={() => setShowDisabled(!showDisabled)}
            />
          </label>
        </div>

        {/* User cards (ui/design: settings/direct-messages/default) */}
        <div className="flex-1 space-y-3 overflow-y-auto">
          {visibleUsers.length === 0 ? (
            <div className="rounded-xl border border-dashed border-border bg-surface-3/60 p-8 text-center text-[13px] text-muted">
              {searchQuery ? t('userList.noUsersForSearch') : t('userList.noUsers')}
            </div>
          ) : (
            visibleUsers.map((u) => {
              const expanded = expandedKey === u.key;
              const userConfig = u.config;
              const isBot = !userConfig.is_admin && (userConfig.display_name || u.userId).toLowerCase().includes('bot');
              const tone = AVATAR_TONES[hashCode(u.userId) % AVATAR_TONES.length];
              const initials = getInitials(userConfig.display_name, u.userId);
              const displayName = displayNameForUser(u);
              const metaPrefix = userConfig.enabled
                ? scopeRouteSummary(userConfig.routing, agentByName, defaultAgentName, t)
                : t('userList.disabled');
              const saving = (savingRows[u.key] || 0) > 0;

              const updateRow = (patch: Partial<UserConfig>) => updateUser(u.platform, u.userId, patch);
              const toggleEnabled = () => updateRow({ enabled: !userConfig.enabled });
              const toggleAdmin = () => canManageAccessMembers && handleToggleAdmin(u.platform, u.userId, !userConfig.is_admin);

              return (
                <div
                  key={u.key}
                  ref={(element) => { rowRefs.current[u.key] = element; }}
                  className={clsx(
                    'rounded-xl border transition-colors',
                    expanded
                      ? 'border-mint/30 bg-surface-2/70 shadow-glow-lg-mint'
                      : userConfig.enabled
                        ? 'border-border bg-background hover:border-border-strong'
                        : 'border-border bg-background/60 opacity-70'
                  )}
                >
                  {/* Master row — matches /groups layout */}
                  <div
                    role="button"
                    tabIndex={0}
                    onClick={() => setExpandedKey(expanded ? null : u.key)}
                    onKeyDown={(e) => {
                      if (e.target !== e.currentTarget) return;
                      if (e.key === ' ' || e.key === 'Enter') {
                        e.preventDefault();
                        setExpandedKey(expanded ? null : u.key);
                      }
                    }}
                    className="flex w-full cursor-pointer items-center gap-3.5 px-5 py-3.5 text-left"
                  >
                    {/* Enabled toggle */}
                    <span onClick={(e) => e.stopPropagation()}>
                      <ToggleSwitch
                        disabled={!canManageAccessMembers}
                        enabled={userConfig.enabled}
                        onClick={toggleEnabled}
                      />
                    </span>

                    {/* Avatar — tone-colored ring with platform corner badge */}
                    <span className="relative shrink-0">
                      <span
                        className="flex size-[40px] items-center justify-center rounded-full border font-mono text-[13px] font-bold"
                        style={{ backgroundColor: tone.bg, borderColor: tone.border }}
                      >
                        {isBot ? (
                          <Bot size={17} className="text-muted" />
                        ) : (
                          <span className={tone.textCls}>{initials}</span>
                        )}
                      </span>
                      <span
                        className="absolute -bottom-1 -right-1 flex size-[20px] items-center justify-center rounded-full border border-border bg-background shadow-[0_0_0_2px_var(--color-background)]"
                        title={platformText(t, u.platform, 'title')}
                      >
                        <PlatformIcon platform={u.platform} size={13} />
                      </span>
                    </span>

                    {/* Name + meta */}
                    <span className="min-w-0 flex-1">
                      <span className="block truncate text-[13px] font-semibold text-foreground">
                        {displayName}
                      </span>
                      <span className="block truncate font-mono text-[11px] text-muted">
                        {metaPrefix} · {u.userId}
                      </span>
                    </span>

                    {/* Admin badge — clickable; bot renders as static label */}
                    {isBot ? (
                      <span className="inline-flex shrink-0 items-center rounded-full border border-border bg-foreground/[0.04] px-2 py-0.5 text-[11px] font-semibold text-muted">
                        {t('userList.bot')}
                      </span>
                    ) : (
                      <span
                        role="button"
                        tabIndex={canManageAccessMembers ? 0 : -1}
                        aria-disabled={!canManageAccessMembers}
                        aria-pressed={userConfig.is_admin}
                        onClick={(e) => { e.stopPropagation(); toggleAdmin(); }}
                        onKeyDown={(e) => {
                          if (e.key === ' ' || e.key === 'Enter') {
                            e.preventDefault();
                            e.stopPropagation();
                            toggleAdmin();
                          }
                        }}
                        title={userConfig.is_admin
                          ? t('userList.demoteAdminTitle')
                          : t('userList.promoteAdminTitle')}
                        className={clsx(
                          'inline-flex shrink-0 cursor-pointer items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium transition-colors',
                          userConfig.is_admin
                            ? 'border-gold/40 bg-gold/10 font-bold text-gold-ink hover:bg-gold/15'
                            : 'border-border bg-foreground/[0.04] text-muted hover:border-border-strong hover:text-foreground'
                        )}
                      >
                        <Shield size={11} strokeWidth={2.4} />
                        {userConfig.is_admin ? t('userList.admin') : t('userList.user')}
                      </span>
                    )}

                    {saving && (
                      <Loader2 size={14} className="shrink-0 animate-spin text-muted" aria-label={t('common.saving')} />
                    )}

                    {/* Chevron */}
                    {expanded ? (
                      <ChevronUp size={18} className="shrink-0 text-muted" />
                    ) : (
                      <ChevronDown size={18} className="shrink-0 text-muted" />
                    )}
                  </div>

                  {/* Expanded body — RoutingConfigPanel shared with /groups, no @mention toggle (ui/design: settings/direct-messages/expanded) */}
                  {expanded && (
                    <RoutingConfigPanel
                      value={userConfig}
                      onChange={(patch) => updateRow(patch)}
                      onBrowseDirectory={() => setBrowsingCwdFor(u.key)}
                      globalConfig={config}
                      vibeAgents={vibeAgents}
                      defaultAgentName={defaultAgentName}
                      availableMessageTypes={availableMessageTypes(u.platform)}
                      showRequireMention={false}
                      saving={saving}
                      routeNotice={newSessionRows[u.key] ? t('channelList.newSessionHint') : null}
                      footerActions={
                        <Button
                          type="button"
                          variant="secondary"
                          size="xs"
                          disabled={!canManageAccessMembers}
                          onClick={() => handleRemoveUser(u.platform, u.userId)}
                          title={t('userList.removeUser')}
                          className="text-muted hover:border-destructive/40 hover:text-destructive-ink"
                        >
                          <Trash2 size={12} />
                          {t('userList.removeUser')}
                        </Button>
                      }
                    />
                  )}
                </div>
              );
            })
          )}
        </div>
      </div>

      {/* Directory browser modal */}
      {browsingCwdFor && (() => {
        const found = aggregated.find((u) => u.key === browsingCwdFor);
        if (!found) return null;
        return (
          <FolderBrowser
            initialPath={found.config.custom_cwd || config.runtime?.default_cwd || '~/work'}
            onSelect={(path) => {
              updateUser(found.platform, found.userId, { custom_cwd: path });
              setBrowsingCwdFor(null);
            }}
            onClose={() => setBrowsingCwdFor(null)}
          />
        );
      })()}
    </>
  );
};