agent-bar.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. 'use client';
  2. import { useState, useEffect, useRef, useCallback } from 'react';
  3. import { motion, AnimatePresence } from 'motion/react';
  4. import { Checkbox } from '@/components/ui/checkbox';
  5. import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
  6. import { cn } from '@/lib/utils';
  7. import { useI18n } from '@/lib/hooks/use-i18n';
  8. import { useSettingsStore } from '@/lib/store/settings';
  9. import { useAgentRegistry } from '@/lib/orchestration/registry/store';
  10. import { resolveAgentVoice, getAvailableProvidersWithVoices } from '@/lib/audio/voice-resolver';
  11. import { playBrowserTTSPreview } from '@/lib/audio/browser-tts-preview';
  12. import {
  13. Sparkles,
  14. ChevronDown,
  15. ChevronUp,
  16. Shuffle,
  17. Volume2,
  18. VolumeX,
  19. Loader2,
  20. MessageSquare,
  21. Minus,
  22. Plus,
  23. } from 'lucide-react';
  24. import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
  25. import type { AgentConfig } from '@/lib/orchestration/registry/types';
  26. import type { TTSProviderId } from '@/lib/audio/types';
  27. import type { ProviderWithVoices } from '@/lib/audio/voice-resolver';
  28. function AgentVoicePill({
  29. agent,
  30. agentIndex,
  31. availableProviders,
  32. disabled,
  33. }: {
  34. agent: AgentConfig;
  35. agentIndex: number;
  36. availableProviders: ProviderWithVoices[];
  37. disabled?: boolean;
  38. }) {
  39. const updateAgent = useAgentRegistry((s) => s.updateAgent);
  40. const ttsProvidersConfig = useSettingsStore((s) => s.ttsProvidersConfig);
  41. const resolved = resolveAgentVoice(agent, agentIndex, availableProviders);
  42. const [popoverOpen, setPopoverOpen] = useState(false);
  43. const [previewingId, setPreviewingId] = useState<string | null>(null);
  44. const previewCancelRef = useRef<(() => void) | null>(null);
  45. const previewAudioRef = useRef<HTMLAudioElement | null>(null);
  46. const previewAbortRef = useRef<AbortController | null>(null);
  47. const displayName = (() => {
  48. for (const p of availableProviders) {
  49. if (p.providerId === resolved.providerId) {
  50. const v = p.voices.find((voice) => voice.id === resolved.voiceId);
  51. if (v) return v.name;
  52. }
  53. }
  54. return resolved.voiceId;
  55. })();
  56. const stopPreview = useCallback(() => {
  57. previewCancelRef.current?.();
  58. previewCancelRef.current = null;
  59. previewAbortRef.current?.abort();
  60. previewAbortRef.current = null;
  61. if (previewAudioRef.current) {
  62. previewAudioRef.current.pause();
  63. previewAudioRef.current.src = '';
  64. previewAudioRef.current = null;
  65. }
  66. setPreviewingId(null);
  67. }, []);
  68. const handlePreview = useCallback(
  69. async (providerId: TTSProviderId, voiceId: string, modelId?: string) => {
  70. const key = `${providerId}::${voiceId}`;
  71. if (previewingId === key) {
  72. stopPreview();
  73. return;
  74. }
  75. stopPreview();
  76. setPreviewingId(key);
  77. const courseLanguage =
  78. (typeof localStorage !== 'undefined' && localStorage.getItem('generationLanguage')) ||
  79. 'zh-CN';
  80. const previewText = courseLanguage === 'en-US' ? 'Welcome to AI Classroom' : '欢迎来到AI课堂';
  81. if (providerId === 'browser-native-tts') {
  82. const { promise, cancel } = playBrowserTTSPreview({ text: previewText, voice: voiceId });
  83. previewCancelRef.current = cancel;
  84. try {
  85. await promise;
  86. } catch {
  87. // ignore abort
  88. }
  89. setPreviewingId(null);
  90. return;
  91. }
  92. // Server TTS
  93. try {
  94. const controller = new AbortController();
  95. previewAbortRef.current = controller;
  96. const providerConfig = ttsProvidersConfig[providerId];
  97. const res = await fetch('/api/generate/tts', {
  98. method: 'POST',
  99. headers: { 'Content-Type': 'application/json' },
  100. body: JSON.stringify({
  101. text: previewText,
  102. audioId: 'voice-preview',
  103. ttsProviderId: providerId,
  104. ttsModelId: modelId || providerConfig?.modelId,
  105. ttsVoice: voiceId,
  106. ttsSpeed: 1,
  107. ttsApiKey: providerConfig?.apiKey,
  108. ttsBaseUrl: providerConfig?.serverBaseUrl || providerConfig?.baseUrl,
  109. }),
  110. signal: controller.signal,
  111. });
  112. if (!res.ok) throw new Error('TTS error');
  113. const data = await res.json();
  114. if (!data.base64) throw new Error('No audio');
  115. const audio = new Audio(`data:audio/${data.format || 'mp3'};base64,${data.base64}`);
  116. previewAudioRef.current = audio;
  117. audio.addEventListener('ended', () => setPreviewingId(null));
  118. audio.addEventListener('error', () => setPreviewingId(null));
  119. await audio.play();
  120. } catch {
  121. setPreviewingId(null);
  122. }
  123. },
  124. [previewingId, stopPreview, ttsProvidersConfig],
  125. );
  126. // Cleanup on unmount
  127. useEffect(() => () => stopPreview(), [stopPreview]);
  128. if (disabled) {
  129. return (
  130. <div
  131. onClick={(e) => e.stopPropagation()}
  132. onPointerDown={(e) => e.stopPropagation()}
  133. className="flex items-center gap-1.5 h-6 w-[100px] rounded-full bg-muted/40 px-2.5 text-[11px] text-muted-foreground/30 shrink-0 cursor-not-allowed"
  134. >
  135. <VolumeX className="size-3 shrink-0" />
  136. <span className="truncate flex-1 text-left">{displayName}</span>
  137. </div>
  138. );
  139. }
  140. return (
  141. <Popover
  142. open={popoverOpen}
  143. onOpenChange={(open) => {
  144. setPopoverOpen(open);
  145. if (!open) stopPreview();
  146. }}
  147. >
  148. <PopoverTrigger asChild>
  149. <button
  150. type="button"
  151. onClick={(e) => e.stopPropagation()}
  152. onPointerDown={(e) => e.stopPropagation()}
  153. className="flex items-center gap-1.5 h-6 w-[100px] rounded-full bg-primary/10 hover:bg-primary/20 dark:bg-primary/25 dark:hover:bg-primary/35 px-2.5 text-[11px] text-primary/80 hover:text-primary dark:text-primary/90 transition-colors shrink-0 cursor-pointer"
  154. >
  155. <Volume2 className="size-3 shrink-0" />
  156. <span className="truncate flex-1 text-left">{displayName}</span>
  157. <ChevronDown className="size-3 shrink-0 opacity-50" />
  158. </button>
  159. </PopoverTrigger>
  160. <PopoverContent
  161. side="bottom"
  162. align="end"
  163. sideOffset={4}
  164. className="w-56 px-1 pb-1 pt-0 max-h-64 overflow-y-auto"
  165. onClick={(e) => e.stopPropagation()}
  166. onPointerDown={(e) => e.stopPropagation()}
  167. >
  168. {availableProviders.map((provider) =>
  169. provider.modelGroups.map((group) => (
  170. <div key={`${provider.providerId}::${group.modelId}`}>
  171. <div className="text-[11px] text-muted-foreground/60 font-medium px-2 py-1 sticky top-0 bg-popover">
  172. {group.modelId
  173. ? `${provider.providerName} · ${group.modelName}`
  174. : provider.providerName}
  175. </div>
  176. {group.voices.map((voice) => {
  177. const isActive =
  178. resolved.providerId === provider.providerId &&
  179. resolved.voiceId === voice.id &&
  180. (resolved.modelId || '') === (group.modelId || '');
  181. const previewKey = `${provider.providerId}::${voice.id}`;
  182. const isPreviewing = previewingId === previewKey;
  183. return (
  184. <div
  185. key={previewKey}
  186. className={cn(
  187. 'flex items-center gap-1.5 rounded-sm transition-colors',
  188. isActive ? 'bg-primary/10' : 'hover:bg-muted',
  189. )}
  190. >
  191. <button
  192. type="button"
  193. onClick={() => {
  194. updateAgent(agent.id, {
  195. voiceConfig: {
  196. providerId: provider.providerId,
  197. modelId: group.modelId || undefined,
  198. voiceId: voice.id,
  199. },
  200. });
  201. setPopoverOpen(false);
  202. }}
  203. className={cn(
  204. 'flex-1 text-left text-[13px] px-2 py-1.5 min-w-0 truncate',
  205. isActive ? 'text-primary font-medium' : 'text-foreground',
  206. )}
  207. >
  208. {voice.name}
  209. </button>
  210. <button
  211. type="button"
  212. onClick={(e) => {
  213. e.stopPropagation();
  214. handlePreview(provider.providerId, voice.id, group.modelId);
  215. }}
  216. className={cn(
  217. 'shrink-0 size-6 flex items-center justify-center rounded-sm transition-colors',
  218. isPreviewing
  219. ? 'text-primary'
  220. : 'text-muted-foreground/40 hover:text-muted-foreground',
  221. )}
  222. >
  223. {isPreviewing ? (
  224. <Loader2 className="size-3.5 animate-spin" />
  225. ) : (
  226. <Volume2 className="size-3.5" />
  227. )}
  228. </button>
  229. </div>
  230. );
  231. })}
  232. </div>
  233. )),
  234. )}
  235. </PopoverContent>
  236. </Popover>
  237. );
  238. }
  239. /**
  240. * Teacher voice pill — reads/writes global ttsProviderId + ttsVoice (single source of truth).
  241. * This ensures lecture and discussion use the same voice for the teacher.
  242. */
  243. function TeacherVoicePill({
  244. availableProviders,
  245. disabled,
  246. }: {
  247. availableProviders: ProviderWithVoices[];
  248. disabled?: boolean;
  249. }) {
  250. const ttsProviderId = useSettingsStore((s) => s.ttsProviderId);
  251. const ttsVoice = useSettingsStore((s) => s.ttsVoice);
  252. const setTTSProvider = useSettingsStore((s) => s.setTTSProvider);
  253. const setTTSVoice = useSettingsStore((s) => s.setTTSVoice);
  254. const setTTSProviderConfig = useSettingsStore((s) => s.setTTSProviderConfig);
  255. const ttsProvidersConfig = useSettingsStore((s) => s.ttsProvidersConfig);
  256. const [popoverOpen, setPopoverOpen] = useState(false);
  257. const [previewingId, setPreviewingId] = useState<string | null>(null);
  258. const previewCancelRef = useRef<(() => void) | null>(null);
  259. const previewAudioRef = useRef<HTMLAudioElement | null>(null);
  260. const previewAbortRef = useRef<AbortController | null>(null);
  261. const displayName = (() => {
  262. for (const p of availableProviders) {
  263. if (p.providerId === ttsProviderId) {
  264. const v = p.voices.find((voice) => voice.id === ttsVoice);
  265. if (v) return v.name;
  266. }
  267. }
  268. return ttsVoice || 'default';
  269. })();
  270. const stopPreview = useCallback(() => {
  271. previewCancelRef.current?.();
  272. previewCancelRef.current = null;
  273. previewAbortRef.current?.abort();
  274. previewAbortRef.current = null;
  275. if (previewAudioRef.current) {
  276. previewAudioRef.current.pause();
  277. previewAudioRef.current.src = '';
  278. previewAudioRef.current = null;
  279. }
  280. setPreviewingId(null);
  281. }, []);
  282. const handlePreview = useCallback(
  283. async (providerId: TTSProviderId, voiceId: string, modelId?: string) => {
  284. const key = `${providerId}::${voiceId}`;
  285. if (previewingId === key) {
  286. stopPreview();
  287. return;
  288. }
  289. stopPreview();
  290. setPreviewingId(key);
  291. const courseLanguage =
  292. (typeof localStorage !== 'undefined' && localStorage.getItem('generationLanguage')) ||
  293. 'zh-CN';
  294. const previewText = courseLanguage === 'en-US' ? 'Welcome to AI Classroom' : '欢迎来到AI课堂';
  295. if (providerId === 'browser-native-tts') {
  296. const { promise, cancel } = playBrowserTTSPreview({ text: previewText, voice: voiceId });
  297. previewCancelRef.current = cancel;
  298. try {
  299. await promise;
  300. } catch {
  301. // ignore abort
  302. }
  303. setPreviewingId(null);
  304. return;
  305. }
  306. try {
  307. const controller = new AbortController();
  308. previewAbortRef.current = controller;
  309. const providerConfig = ttsProvidersConfig[providerId];
  310. const res = await fetch('/api/generate/tts', {
  311. method: 'POST',
  312. headers: { 'Content-Type': 'application/json' },
  313. body: JSON.stringify({
  314. text: previewText,
  315. audioId: 'voice-preview',
  316. ttsProviderId: providerId,
  317. ttsModelId: modelId || providerConfig?.modelId,
  318. ttsVoice: voiceId,
  319. ttsSpeed: 1,
  320. ttsApiKey: providerConfig?.apiKey,
  321. ttsBaseUrl: providerConfig?.serverBaseUrl || providerConfig?.baseUrl,
  322. }),
  323. signal: controller.signal,
  324. });
  325. if (!res.ok) throw new Error('TTS error');
  326. const data = await res.json();
  327. if (!data.base64) throw new Error('No audio');
  328. const audio = new Audio(`data:audio/${data.format || 'mp3'};base64,${data.base64}`);
  329. previewAudioRef.current = audio;
  330. audio.addEventListener('ended', () => setPreviewingId(null));
  331. audio.addEventListener('error', () => setPreviewingId(null));
  332. await audio.play();
  333. } catch {
  334. setPreviewingId(null);
  335. }
  336. },
  337. [previewingId, stopPreview, ttsProvidersConfig],
  338. );
  339. useEffect(() => () => stopPreview(), [stopPreview]);
  340. if (disabled) {
  341. return (
  342. <div
  343. onClick={(e) => e.stopPropagation()}
  344. onPointerDown={(e) => e.stopPropagation()}
  345. className="flex items-center gap-1.5 h-6 w-[100px] rounded-full bg-muted/40 px-2.5 text-[11px] text-muted-foreground/30 shrink-0 cursor-not-allowed"
  346. >
  347. <VolumeX className="size-3 shrink-0" />
  348. <span className="truncate flex-1 text-left">{displayName}</span>
  349. </div>
  350. );
  351. }
  352. return (
  353. <Popover
  354. open={popoverOpen}
  355. onOpenChange={(open) => {
  356. setPopoverOpen(open);
  357. if (!open) stopPreview();
  358. }}
  359. >
  360. <PopoverTrigger asChild>
  361. <button
  362. type="button"
  363. onClick={(e) => e.stopPropagation()}
  364. onPointerDown={(e) => e.stopPropagation()}
  365. className="flex items-center gap-1.5 h-6 w-[100px] rounded-full bg-primary/10 hover:bg-primary/20 dark:bg-primary/25 dark:hover:bg-primary/35 px-2.5 text-[11px] text-primary/80 hover:text-primary dark:text-primary/90 transition-colors shrink-0 cursor-pointer"
  366. >
  367. <Volume2 className="size-3 shrink-0" />
  368. <span className="truncate flex-1 text-left">{displayName}</span>
  369. <ChevronDown className="size-3 shrink-0 opacity-50" />
  370. </button>
  371. </PopoverTrigger>
  372. <PopoverContent
  373. side="bottom"
  374. align="end"
  375. sideOffset={4}
  376. className="w-56 px-1 pb-1 pt-0 max-h-64 overflow-y-auto"
  377. onClick={(e) => e.stopPropagation()}
  378. onPointerDown={(e) => e.stopPropagation()}
  379. >
  380. {availableProviders.map((provider) =>
  381. provider.modelGroups.map((group) => (
  382. <div key={`${provider.providerId}::${group.modelId}`}>
  383. <div className="text-[11px] text-muted-foreground/60 font-medium px-2 py-1 sticky top-0 bg-popover">
  384. {group.modelId
  385. ? `${provider.providerName} · ${group.modelName}`
  386. : provider.providerName}
  387. </div>
  388. {group.voices.map((voice) => {
  389. const currentModelId = ttsProvidersConfig[ttsProviderId]?.modelId || '';
  390. const isActive =
  391. ttsProviderId === provider.providerId &&
  392. ttsVoice === voice.id &&
  393. currentModelId === (group.modelId || '');
  394. const previewKey = `${provider.providerId}::${voice.id}`;
  395. const isPreviewing = previewingId === previewKey;
  396. return (
  397. <div
  398. key={previewKey}
  399. className={cn(
  400. 'flex items-center gap-1.5 rounded-sm transition-colors',
  401. isActive ? 'bg-primary/10' : 'hover:bg-muted',
  402. )}
  403. >
  404. <button
  405. type="button"
  406. onClick={() => {
  407. setTTSProvider(provider.providerId);
  408. setTTSVoice(voice.id);
  409. if (group.modelId) {
  410. setTTSProviderConfig(provider.providerId, { modelId: group.modelId });
  411. }
  412. setPopoverOpen(false);
  413. }}
  414. className={cn(
  415. 'flex-1 text-left text-[13px] px-2 py-1.5 min-w-0 truncate',
  416. isActive ? 'text-primary font-medium' : 'text-foreground',
  417. )}
  418. >
  419. {voice.name}
  420. </button>
  421. <button
  422. type="button"
  423. onClick={(e) => {
  424. e.stopPropagation();
  425. handlePreview(provider.providerId, voice.id, group.modelId);
  426. }}
  427. className={cn(
  428. 'shrink-0 size-6 flex items-center justify-center rounded-sm transition-colors',
  429. isPreviewing
  430. ? 'text-primary'
  431. : 'text-muted-foreground/40 hover:text-muted-foreground',
  432. )}
  433. >
  434. {isPreviewing ? (
  435. <Loader2 className="size-3.5 animate-spin" />
  436. ) : (
  437. <Volume2 className="size-3.5" />
  438. )}
  439. </button>
  440. </div>
  441. );
  442. })}
  443. </div>
  444. )),
  445. )}
  446. </PopoverContent>
  447. </Popover>
  448. );
  449. }
  450. export function AgentBar() {
  451. const { t } = useI18n();
  452. const { listAgents } = useAgentRegistry();
  453. const selectedAgentIds = useSettingsStore((s) => s.selectedAgentIds);
  454. const setSelectedAgentIds = useSettingsStore((s) => s.setSelectedAgentIds);
  455. const maxTurns = useSettingsStore((s) => s.maxTurns);
  456. const setMaxTurns = useSettingsStore((s) => s.setMaxTurns);
  457. const agentMode = useSettingsStore((s) => s.agentMode);
  458. const setAgentMode = useSettingsStore((s) => s.setAgentMode);
  459. const ttsProvidersConfig = useSettingsStore((s) => s.ttsProvidersConfig);
  460. const ttsEnabled = useSettingsStore((s) => s.ttsEnabled);
  461. const [open, setOpen] = useState(false);
  462. const [browserVoices, setBrowserVoices] = useState<SpeechSynthesisVoice[]>([]);
  463. const containerRef = useRef<HTMLDivElement>(null);
  464. // Load browser native TTS voices
  465. useEffect(() => {
  466. if (typeof window === 'undefined' || !window.speechSynthesis) return;
  467. const loadVoices = () => setBrowserVoices(speechSynthesis.getVoices());
  468. loadVoices();
  469. speechSynthesis.addEventListener('voiceschanged', loadVoices);
  470. return () => speechSynthesis.removeEventListener('voiceschanged', loadVoices);
  471. }, []);
  472. const allAgents = listAgents();
  473. const agents = allAgents.filter((a) => !a.isGenerated);
  474. const teacherAgent = agents.find((a) => a.role === 'teacher');
  475. const selectedAgents = agents.filter((a) => selectedAgentIds.includes(a.id));
  476. const nonTeacherSelected = selectedAgents.filter((a) => a.role !== 'teacher');
  477. const serverProviders = getAvailableProvidersWithVoices(ttsProvidersConfig);
  478. const availableProviders: ProviderWithVoices[] = [
  479. ...serverProviders,
  480. ...(browserVoices.length > 0
  481. ? [
  482. {
  483. providerId: 'browser-native-tts' as TTSProviderId,
  484. providerName: 'Browser Native',
  485. voices: browserVoices.map((v) => ({ id: v.voiceURI, name: v.name })),
  486. modelGroups: [
  487. {
  488. modelId: '',
  489. modelName: 'Browser Native',
  490. voices: browserVoices.map((v) => ({ id: v.voiceURI, name: v.name })),
  491. },
  492. ],
  493. },
  494. ]
  495. : []),
  496. ];
  497. const showVoice = availableProviders.length > 0;
  498. useEffect(() => {
  499. if (!open) return;
  500. const handler = (e: MouseEvent) => {
  501. const target = e.target as Node;
  502. if (containerRef.current && containerRef.current.contains(target)) return;
  503. // Don't close if clicking inside a Radix portal (Popover, Select, etc.)
  504. if ((target as Element).closest?.('[data-radix-popper-content-wrapper]')) return;
  505. setOpen(false);
  506. };
  507. document.addEventListener('mousedown', handler);
  508. return () => document.removeEventListener('mousedown', handler);
  509. }, [open]);
  510. const handleModeChange = (mode: 'preset' | 'auto') => {
  511. setAgentMode(mode);
  512. if (mode === 'preset') {
  513. // Remove stale auto-generated agent IDs that may linger from a previous auto classroom
  514. const presetIds = selectedAgentIds.filter((id) => agents.some((a) => a.id === id));
  515. const hasTeacher = presetIds.some((id) => {
  516. const a = agents.find((agent) => agent.id === id);
  517. return a?.role === 'teacher';
  518. });
  519. if (!hasTeacher && teacherAgent) {
  520. presetIds.unshift(teacherAgent.id);
  521. }
  522. setSelectedAgentIds(
  523. presetIds.length > 0 ? presetIds : ['default-1', 'default-2', 'default-3'],
  524. );
  525. }
  526. };
  527. const toggleAgent = (agentId: string) => {
  528. const agent = agents.find((a) => a.id === agentId);
  529. if (agent?.role === 'teacher') return;
  530. if (selectedAgentIds.includes(agentId)) {
  531. setSelectedAgentIds(selectedAgentIds.filter((id) => id !== agentId));
  532. } else {
  533. setSelectedAgentIds([...selectedAgentIds, agentId]);
  534. }
  535. };
  536. const getAgentName = (agent: { id: string; name: string }) => {
  537. const key = `settings.agentNames.${agent.id}`;
  538. const translated = t(key);
  539. return translated !== key ? translated : agent.name;
  540. };
  541. const getAgentRole = (agent: { role: string }) => {
  542. const key = `settings.agentRoles.${agent.role}`;
  543. const translated = t(key);
  544. return translated !== key ? translated : agent.role;
  545. };
  546. const avatarRow = (
  547. <div className="flex items-center gap-1.5 shrink-0">
  548. {teacherAgent && (
  549. <div className="size-8 rounded-full overflow-hidden ring-2 ring-blue-400/40 dark:ring-blue-500/30 shrink-0">
  550. <img
  551. src={teacherAgent.avatar}
  552. alt={getAgentName(teacherAgent)}
  553. className="size-full object-cover"
  554. />
  555. </div>
  556. )}
  557. {agentMode === 'auto' ? (
  558. <>
  559. <div className="flex -space-x-2">
  560. {agents.find((a) => a.role === 'assistant') && (
  561. <div className="size-6 rounded-full overflow-hidden ring-[1.5px] ring-background">
  562. <img
  563. src={agents.find((a) => a.role === 'assistant')!.avatar}
  564. alt=""
  565. className="size-full object-cover"
  566. />
  567. </div>
  568. )}
  569. </div>
  570. <Shuffle className="size-4 text-violet-400 dark:text-violet-500" />
  571. </>
  572. ) : (
  573. <>
  574. {nonTeacherSelected.length > 0 && (
  575. <div className="flex -space-x-2">
  576. {nonTeacherSelected.slice(0, 4).map((agent) => (
  577. <div
  578. key={agent.id}
  579. className="size-6 rounded-full overflow-hidden ring-[1.5px] ring-background"
  580. >
  581. <img
  582. src={agent.avatar}
  583. alt={getAgentName(agent)}
  584. className="size-full object-cover"
  585. />
  586. </div>
  587. ))}
  588. {nonTeacherSelected.length > 4 && (
  589. <div className="size-6 rounded-full bg-muted ring-[1.5px] ring-background flex items-center justify-center">
  590. <span className="text-[9px] font-bold text-muted-foreground">
  591. +{nonTeacherSelected.length - 4}
  592. </span>
  593. </div>
  594. )}
  595. </div>
  596. )}
  597. </>
  598. )}
  599. {showVoice &&
  600. (ttsEnabled ? (
  601. <Volume2 className="size-3.5 text-muted-foreground/40 group-hover:text-muted-foreground/60 transition-colors" />
  602. ) : (
  603. <VolumeX className="size-3.5 text-muted-foreground/30" />
  604. ))}
  605. </div>
  606. );
  607. const renderAgentRow = (agent: AgentConfig, agentIndex: number, isTeacher: boolean) => {
  608. const isSelected = isTeacher || selectedAgentIds.includes(agent.id);
  609. return (
  610. <div
  611. key={agent.id}
  612. onClick={isTeacher ? undefined : () => toggleAgent(agent.id)}
  613. className={cn(
  614. 'w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg transition-colors',
  615. isTeacher ? 'bg-primary/5' : 'cursor-pointer',
  616. !isTeacher && isSelected && 'bg-primary/5',
  617. !isTeacher && !isSelected && 'hover:bg-muted/50',
  618. )}
  619. >
  620. <Checkbox
  621. checked={isSelected}
  622. disabled={isTeacher}
  623. className={cn('pointer-events-none', isTeacher && 'opacity-50')}
  624. />
  625. <div
  626. className="size-7 rounded-full overflow-hidden shrink-0 ring-1 ring-border/40"
  627. style={{ boxShadow: isSelected ? `0 0 0 2px ${agent.color}30` : undefined }}
  628. >
  629. <img src={agent.avatar} alt={getAgentName(agent)} className="size-full object-cover" />
  630. </div>
  631. <span className="text-[13px] font-medium truncate min-w-0 flex-1">
  632. {getAgentName(agent)}
  633. </span>
  634. <span className="text-[10px] text-muted-foreground/50 shrink-0 w-[52px] text-right">
  635. {getAgentRole(agent)}
  636. </span>
  637. {showVoice && (
  638. <AgentVoicePill
  639. agent={agent}
  640. agentIndex={agentIndex}
  641. availableProviders={availableProviders}
  642. disabled={!ttsEnabled}
  643. />
  644. )}
  645. </div>
  646. );
  647. };
  648. return (
  649. <div ref={containerRef} className="relative w-96">
  650. <Tooltip>
  651. <TooltipTrigger asChild>
  652. <button
  653. className={cn(
  654. 'group flex items-center gap-2 cursor-pointer rounded-full px-2.5 py-2 transition-all w-full',
  655. 'border border-border/50 text-muted-foreground/70 hover:text-foreground hover:bg-muted/60',
  656. )}
  657. onClick={() => setOpen(!open)}
  658. >
  659. <span className="text-xs text-muted-foreground/60 group-hover:text-muted-foreground transition-colors hidden sm:block font-medium flex-1 text-left truncate">
  660. {open ? t('agentBar.expandedTitle') : t('agentBar.readyToLearn')}
  661. </span>
  662. {avatarRow}
  663. {open ? (
  664. <ChevronUp className="size-3 text-muted-foreground/40 group-hover:text-muted-foreground/70 transition-colors" />
  665. ) : (
  666. <ChevronDown className="size-3 text-muted-foreground/40 group-hover:text-muted-foreground/70 transition-colors" />
  667. )}
  668. </button>
  669. </TooltipTrigger>
  670. {!open && (
  671. <TooltipContent side="bottom" sideOffset={4}>
  672. {t('agentBar.configTooltip')}
  673. </TooltipContent>
  674. )}
  675. </Tooltip>
  676. <AnimatePresence>
  677. {open && (
  678. <motion.div
  679. initial={{ opacity: 0, y: -4, scale: 0.97 }}
  680. animate={{ opacity: 1, y: 0, scale: 1 }}
  681. exit={{ opacity: 0, y: -4, scale: 0.97 }}
  682. transition={{ duration: 0.2, ease: [0.25, 0.1, 0.25, 1] }}
  683. className="absolute right-0 top-full mt-1 z-50 w-96"
  684. >
  685. <div className="rounded-2xl bg-white/95 dark:bg-slate-800/95 backdrop-blur-sm ring-1 ring-black/[0.04] dark:ring-white/[0.06] shadow-[0_1px_8px_-2px_rgba(0,0,0,0.06)] dark:shadow-[0_1px_8px_-2px_rgba(0,0,0,0.3)] px-2 py-1.5">
  686. {/* Teacher — always visible */}
  687. {teacherAgent && (
  688. <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-primary/5 mb-2">
  689. <div
  690. className="size-7 rounded-full overflow-hidden shrink-0 ring-1 ring-border/40"
  691. style={{ boxShadow: `0 0 0 2px ${teacherAgent.color}30` }}
  692. >
  693. <img
  694. src={teacherAgent.avatar}
  695. alt={getAgentName(teacherAgent)}
  696. className="size-full object-cover"
  697. />
  698. </div>
  699. <span className="text-[13px] font-medium truncate min-w-0 flex-1">
  700. {getAgentName(teacherAgent)}
  701. </span>
  702. {showVoice && (
  703. <TeacherVoicePill
  704. availableProviders={availableProviders}
  705. disabled={!ttsEnabled}
  706. />
  707. )}
  708. </div>
  709. )}
  710. {/* Mode tabs */}
  711. <div className="flex rounded-lg border bg-muted/30 p-0.5 mb-2">
  712. <button
  713. onClick={() => handleModeChange('preset')}
  714. className={cn(
  715. 'flex-1 py-1.5 text-xs font-medium rounded-md transition-all text-center',
  716. agentMode === 'preset'
  717. ? 'bg-background shadow-sm text-foreground'
  718. : 'text-muted-foreground hover:text-foreground',
  719. )}
  720. >
  721. {t('settings.agentModePreset')}
  722. </button>
  723. <button
  724. onClick={() => handleModeChange('auto')}
  725. className={cn(
  726. 'flex-1 py-1.5 text-xs font-medium rounded-md transition-all text-center flex items-center justify-center gap-1',
  727. agentMode === 'auto'
  728. ? 'bg-background shadow-sm text-foreground'
  729. : 'text-muted-foreground hover:text-foreground',
  730. )}
  731. >
  732. <Sparkles className="h-3 w-3" />
  733. {t('settings.agentModeAuto')}
  734. </button>
  735. </div>
  736. {agentMode === 'preset' ? (
  737. <div className="max-h-56 overflow-y-auto -mx-0.5">
  738. {agents
  739. .filter((a) => a.role !== 'teacher')
  740. .map((agent, idx) => renderAgentRow(agent, idx + 1, false))}
  741. </div>
  742. ) : (
  743. <div className="flex flex-col items-center pt-6 pb-3 gap-4">
  744. <div className="relative flex items-center justify-center">
  745. <div className="absolute size-10 rounded-full bg-violet-400/10 dark:bg-violet-400/15 animate-ping [animation-duration:3s]" />
  746. <div className="absolute size-12 rounded-full bg-violet-400/5 dark:bg-violet-400/10 animate-pulse [animation-duration:2.5s]" />
  747. <Shuffle className="relative size-5 text-violet-400 dark:text-violet-500" />
  748. </div>
  749. <div className="flex-1" />
  750. <div className="text-center space-y-1">
  751. <p className="text-[11px] text-muted-foreground/60">
  752. {t('settings.agentModeAutoDesc')}
  753. </p>
  754. <p className="text-[10px] text-muted-foreground/40">
  755. {t('agentBar.voiceAutoAssign')}
  756. </p>
  757. </div>
  758. </div>
  759. )}
  760. {/* Max turns — compact stepper */}
  761. <div className="flex items-center gap-1.5 px-2 py-1 mt-1 border-t border-border/30">
  762. <MessageSquare className="size-3 text-muted-foreground/40 shrink-0" />
  763. <span className="text-[11px] text-muted-foreground/50 flex-1">
  764. {t('settings.maxTurns')}
  765. </span>
  766. <div className="flex items-center rounded-full bg-muted/50 h-5 shrink-0">
  767. <button
  768. type="button"
  769. onClick={(e) => {
  770. e.stopPropagation();
  771. const v = Math.max(1, parseInt(maxTurns || '1') - 1);
  772. setMaxTurns(String(v));
  773. }}
  774. className="size-5 flex items-center justify-center text-muted-foreground/60 hover:text-foreground transition-colors rounded-full hover:bg-muted"
  775. >
  776. <Minus className="size-2.5" />
  777. </button>
  778. <input
  779. type="text"
  780. inputMode="numeric"
  781. value={maxTurns}
  782. onChange={(e) => {
  783. const raw = e.target.value.replace(/\D/g, '');
  784. if (!raw) {
  785. setMaxTurns('');
  786. return;
  787. }
  788. const v = Math.min(20, Math.max(1, parseInt(raw)));
  789. setMaxTurns(String(v));
  790. }}
  791. onBlur={() => {
  792. if (!maxTurns || parseInt(maxTurns) < 1) setMaxTurns('1');
  793. }}
  794. onClick={(e) => e.stopPropagation()}
  795. className="w-5 h-5 text-[11px] font-medium tabular-nums text-center bg-transparent outline-none border-none"
  796. />
  797. <button
  798. type="button"
  799. onClick={(e) => {
  800. e.stopPropagation();
  801. const v = Math.min(20, parseInt(maxTurns || '1') + 1);
  802. setMaxTurns(String(v));
  803. }}
  804. className="size-5 flex items-center justify-center text-muted-foreground/60 hover:text-foreground transition-colors rounded-full hover:bg-muted"
  805. >
  806. <Plus className="size-2.5" />
  807. </button>
  808. </div>
  809. </div>
  810. </div>
  811. </motion.div>
  812. )}
  813. </AnimatePresence>
  814. </div>
  815. );
  816. }