store.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /**
  2. * Agent Registry Store
  3. * Manages configurable AI agents using Zustand with localStorage persistence
  4. */
  5. import { create } from 'zustand';
  6. import { persist } from 'zustand/middleware';
  7. import type { AgentConfig } from './types';
  8. import { getActionsForRole } from './types';
  9. import type { TTSProviderId } from '@/lib/audio/types';
  10. import { USER_AVATAR } from '@/lib/types/roundtable';
  11. import type { Participant, ParticipantRole } from '@/lib/types/roundtable';
  12. import { useUserProfileStore } from '@/lib/store/user-profile';
  13. import type { AgentInfo } from '@/lib/generation/pipeline-types';
  14. interface AgentRegistryState {
  15. agents: Record<string, AgentConfig>; // Map of agentId -> config
  16. // Actions
  17. addAgent: (agent: AgentConfig) => void;
  18. updateAgent: (id: string, updates: Partial<AgentConfig>) => void;
  19. deleteAgent: (id: string) => void;
  20. getAgent: (id: string) => AgentConfig | undefined;
  21. listAgents: () => AgentConfig[];
  22. }
  23. // Action types available to agents
  24. const WHITEBOARD_ACTIONS = [
  25. 'wb_open',
  26. 'wb_close',
  27. 'wb_draw_text',
  28. 'wb_draw_shape',
  29. 'wb_draw_chart',
  30. 'wb_draw_latex',
  31. 'wb_draw_table',
  32. 'wb_draw_line',
  33. 'wb_clear',
  34. 'wb_delete',
  35. ];
  36. const SLIDE_ACTIONS = ['spotlight', 'laser', 'play_video'];
  37. // Default agents - always available on both server and client
  38. const DEFAULT_AGENTS: Record<string, AgentConfig> = {
  39. 'default-1': {
  40. id: 'default-1',
  41. name: 'AI teacher',
  42. role: 'teacher',
  43. persona: `You are the lead teacher of this classroom. You teach with clarity, warmth, and genuine enthusiasm for the subject matter.
  44. Your teaching style:
  45. - Explain concepts step by step, building from what students already know
  46. - Use vivid analogies, real-world examples, and visual aids to make abstract ideas concrete
  47. - Pause to check understanding — ask questions, not just lecture
  48. - Adapt your pace: slow down for difficult parts, move briskly through familiar ground
  49. - Encourage students by name when they contribute, and gently correct mistakes without embarrassment
  50. You can spotlight or laser-point at slide elements, and use the whiteboard for hand-drawn explanations. Use these actions naturally as part of your teaching flow. Never announce your actions; just teach.
  51. Tone: Professional yet approachable. Patient. Encouraging. You genuinely care about whether students understand.`,
  52. avatar: '/avatars/teacher.png',
  53. color: '#3b82f6',
  54. allowedActions: [...SLIDE_ACTIONS, ...WHITEBOARD_ACTIONS],
  55. priority: 10,
  56. createdAt: new Date(),
  57. updatedAt: new Date(),
  58. isDefault: true,
  59. },
  60. 'default-2': {
  61. id: 'default-2',
  62. name: 'AI助教',
  63. role: 'assistant',
  64. persona: `You are the teaching assistant. You support the lead teacher by filling in gaps, answering side questions, and making sure no student is left behind.
  65. Your style:
  66. - When a student is confused, rephrase the teacher's explanation in simpler terms or from a different angle
  67. - Provide concrete examples, especially practical or everyday ones that make concepts relatable
  68. - Proactively offer background context that the teacher might skip over
  69. - Summarize key takeaways after complex explanations
  70. - You can use the whiteboard to sketch quick clarifications when needed
  71. You play a supportive role — you don't take over the lesson, but you make sure everyone keeps up.
  72. Tone: Friendly, warm, down-to-earth. Like a helpful older classmate who just "gets it."`,
  73. avatar: '/avatars/assist.png',
  74. color: '#10b981',
  75. allowedActions: [...WHITEBOARD_ACTIONS],
  76. priority: 7,
  77. createdAt: new Date(),
  78. updatedAt: new Date(),
  79. isDefault: true,
  80. },
  81. 'default-3': {
  82. id: 'default-3',
  83. name: '显眼包',
  84. role: 'student',
  85. persona: `You are the class clown — the student everyone notices. You bring energy and laughter to the classroom with your witty comments, playful observations, and unexpected takes on the material.
  86. Your personality:
  87. - You crack jokes and make humorous connections to the topic being discussed
  88. - You sometimes exaggerate your confusion for comedic effect, but you're actually paying attention
  89. - You use pop culture references, memes, and funny analogies
  90. - You're not disruptive — your humor makes the class more engaging and helps everyone relax
  91. - Occasionally you stumble onto surprisingly insightful points through your jokes
  92. You keep things light. When the class gets too heavy or boring, you're the one who livens it up. But you also know when to dial it back during serious moments.
  93. Tone: Playful, energetic, a little cheeky. You speak casually, like you're chatting with friends. Keep responses SHORT — one-liners and quick reactions, not paragraphs.`,
  94. avatar: '/avatars/clown.png',
  95. color: '#f59e0b',
  96. allowedActions: [...WHITEBOARD_ACTIONS],
  97. priority: 4,
  98. createdAt: new Date(),
  99. updatedAt: new Date(),
  100. isDefault: true,
  101. },
  102. 'default-4': {
  103. id: 'default-4',
  104. name: '好奇宝宝',
  105. role: 'student',
  106. persona: `You are the endlessly curious student. You always have a question — and your questions often push the whole class to think deeper.
  107. Your personality:
  108. - You ask "why" and "how" constantly — not to be annoying, but because you genuinely want to understand
  109. - You notice details others miss and ask about edge cases, exceptions, and connections to other topics
  110. - You're not afraid to say "I don't get it" — your honesty helps other students who were too shy to ask
  111. - You get excited when you learn something new and express that enthusiasm openly
  112. - You sometimes ask questions that are slightly ahead of the current topic, pulling the discussion forward
  113. You represent the voice of genuine curiosity. Your questions make the teacher's explanations better for everyone.
  114. Tone: Eager, enthusiastic, occasionally puzzled. You speak with the excitement of someone discovering things for the first time. Keep questions concise and direct.`,
  115. avatar: '/avatars/curious.png',
  116. color: '#ec4899',
  117. allowedActions: [...WHITEBOARD_ACTIONS],
  118. priority: 5,
  119. createdAt: new Date(),
  120. updatedAt: new Date(),
  121. isDefault: true,
  122. },
  123. 'default-5': {
  124. id: 'default-5',
  125. name: '笔记员',
  126. role: 'student',
  127. persona: `You are the dedicated note-taker of the class. You listen carefully, organize information, and love sharing your structured summaries with everyone.
  128. Your personality:
  129. - You naturally distill complex explanations into clear, organized bullet points
  130. - After a key concept is taught, you offer a quick summary or recap for the class
  131. - You use the whiteboard to write down key formulas, definitions, or structured outlines
  132. - You notice when something important was said but might have been missed, and you flag it
  133. - You occasionally ask the teacher to clarify something so your notes are accurate
  134. You're the student everyone wants to sit next to during exams. Your notes are legendary.
  135. Tone: Organized, helpful, slightly studious. You speak clearly and precisely. When sharing notes, use structured formats — numbered lists, key terms bolded, clear headers.`,
  136. avatar: '/avatars/note-taker.png',
  137. color: '#06b6d4',
  138. allowedActions: [...WHITEBOARD_ACTIONS],
  139. priority: 5,
  140. createdAt: new Date(),
  141. updatedAt: new Date(),
  142. isDefault: true,
  143. },
  144. 'default-6': {
  145. id: 'default-6',
  146. name: '思考者',
  147. role: 'student',
  148. persona: `You are the deep thinker of the class. While others focus on understanding the basics, you're already connecting ideas, questioning assumptions, and exploring implications.
  149. Your personality:
  150. - You make unexpected connections between the current topic and other fields or concepts
  151. - You challenge ideas respectfully — "But what if..." and "Doesn't that contradict..." are your signature phrases
  152. - You think about the bigger picture: philosophical implications, real-world consequences, ethical dimensions
  153. - You sometimes play devil's advocate to push the discussion deeper
  154. - Your contributions often spark the most interesting class discussions
  155. You don't speak as often as others, but when you do, it changes the direction of the conversation. You value depth over breadth.
  156. Tone: Thoughtful, measured, intellectually curious. You pause before speaking. Your sentences are deliberate and carry weight. Ask provocative questions that make everyone stop and think.`,
  157. avatar: '/avatars/thinker.png',
  158. color: '#8b5cf6',
  159. allowedActions: [...WHITEBOARD_ACTIONS],
  160. priority: 6,
  161. createdAt: new Date(),
  162. updatedAt: new Date(),
  163. isDefault: true,
  164. },
  165. };
  166. /**
  167. * Return the built-in default agents as lightweight AgentInfo objects
  168. * suitable for the generation pipeline (no UI-only fields like avatar/color).
  169. */
  170. export function getDefaultAgents(): AgentInfo[] {
  171. return Object.values(DEFAULT_AGENTS).map((a) => ({
  172. id: a.id,
  173. name: a.name,
  174. role: a.role,
  175. persona: a.persona,
  176. }));
  177. }
  178. export const useAgentRegistry = create<AgentRegistryState>()(
  179. persist(
  180. (set, get) => ({
  181. // Initialize with default agents so they're available on server
  182. agents: { ...DEFAULT_AGENTS },
  183. addAgent: (agent) =>
  184. set((state) => ({
  185. agents: { ...state.agents, [agent.id]: agent },
  186. })),
  187. updateAgent: (id, updates) =>
  188. set((state) => ({
  189. agents: {
  190. ...state.agents,
  191. [id]: { ...state.agents[id], ...updates, updatedAt: new Date() },
  192. },
  193. })),
  194. deleteAgent: (id) =>
  195. set((state) => {
  196. const { [id]: _removed, ...rest } = state.agents;
  197. return { agents: rest };
  198. }),
  199. getAgent: (id) => get().agents[id],
  200. listAgents: () => Object.values(get().agents),
  201. }),
  202. {
  203. name: 'agent-registry-storage',
  204. version: 11, // Bumped: add voiceOverrides field to AgentConfig
  205. migrate: (persistedState: unknown) => persistedState,
  206. // Merge persisted state with default agents
  207. // Default agents always use code-defined values (not cached)
  208. // Custom agents use persisted values
  209. merge: (persistedState: unknown, currentState) => {
  210. const persisted = persistedState as Record<string, unknown> | undefined;
  211. const persistedAgents = (persisted?.agents || {}) as Record<string, AgentConfig>;
  212. const mergedAgents: Record<string, AgentConfig> = { ...DEFAULT_AGENTS };
  213. // Only preserve non-default, non-generated (custom) agents from cache
  214. // Generated agents are loaded on-demand from IndexedDB per stage
  215. for (const [id, agent] of Object.entries(persistedAgents)) {
  216. const agentConfig = agent as AgentConfig;
  217. if (!id.startsWith('default-') && !agentConfig.isGenerated) {
  218. mergedAgents[id] = agentConfig;
  219. }
  220. }
  221. return {
  222. ...currentState,
  223. agents: mergedAgents,
  224. };
  225. },
  226. },
  227. ),
  228. );
  229. /**
  230. * Convert agents to roundtable participants
  231. * Maps agent roles to participant roles for the UI
  232. * @param t - i18n translation function for localized display names
  233. */
  234. export function agentsToParticipants(
  235. agentIds: string[],
  236. t?: (key: string) => string,
  237. ): Participant[] {
  238. const registry = useAgentRegistry.getState();
  239. const participants: Participant[] = [];
  240. let hasTeacher = false;
  241. // Resolve agents and sort: teacher first (by role then priority desc)
  242. const resolved = agentIds
  243. .map((id) => registry.getAgent(id))
  244. .filter((a): a is AgentConfig => a != null);
  245. resolved.sort((a, b) => {
  246. if (a.role === 'teacher' && b.role !== 'teacher') return -1;
  247. if (a.role !== 'teacher' && b.role === 'teacher') return 1;
  248. return (b.priority ?? 0) - (a.priority ?? 0);
  249. });
  250. for (const agent of resolved) {
  251. // Map agent role to participant role:
  252. // The first agent with role "teacher" becomes the left-side teacher.
  253. // If no agent has role "teacher", the highest-priority agent becomes teacher.
  254. let role: ParticipantRole = 'student';
  255. if (!hasTeacher) {
  256. role = 'teacher';
  257. hasTeacher = true;
  258. }
  259. // Use i18n name for default agents, fall back to registry name
  260. const i18nName = t?.(`settings.agentNames.${agent.id}`);
  261. const displayName =
  262. i18nName && i18nName !== `settings.agentNames.${agent.id}` ? i18nName : agent.name;
  263. participants.push({
  264. id: agent.id,
  265. name: displayName,
  266. role,
  267. avatar: agent.avatar,
  268. isOnline: true,
  269. isSpeaking: false,
  270. });
  271. }
  272. // Always add user participant — use profile store when available
  273. const userProfile = useUserProfileStore.getState();
  274. const userName = userProfile.nickname || t?.('common.you') || 'You';
  275. const userAvatar = userProfile.avatar || USER_AVATAR;
  276. participants.push({
  277. id: 'user-1',
  278. name: userName,
  279. role: 'user',
  280. avatar: userAvatar,
  281. isOnline: true,
  282. isSpeaking: false,
  283. });
  284. return participants;
  285. }
  286. /**
  287. * Load generated agents for a stage from IndexedDB into the registry.
  288. * Clears any previously loaded generated agents first.
  289. * Returns the loaded agent IDs.
  290. */
  291. export async function loadGeneratedAgentsForStage(stageId: string): Promise<string[]> {
  292. const { getGeneratedAgentsByStageId } = await import('@/lib/utils/database');
  293. const records = await getGeneratedAgentsByStageId(stageId);
  294. const registry = useAgentRegistry.getState();
  295. // Always clear previously loaded generated agents — even when the new stage
  296. // has none — to prevent stale agents from a prior auto-classroom leaking
  297. // into the current preset classroom.
  298. const currentAgents = registry.listAgents();
  299. for (const agent of currentAgents) {
  300. if (agent.isGenerated) {
  301. registry.deleteAgent(agent.id);
  302. }
  303. }
  304. if (records.length === 0) return [];
  305. // Add new ones
  306. const ids: string[] = [];
  307. for (const record of records) {
  308. registry.addAgent({
  309. ...record,
  310. allowedActions: getActionsForRole(record.role),
  311. isDefault: false,
  312. isGenerated: true,
  313. boundStageId: record.stageId,
  314. createdAt: new Date(record.createdAt),
  315. updatedAt: new Date(record.createdAt),
  316. });
  317. ids.push(record.id);
  318. }
  319. return ids;
  320. }
  321. /**
  322. * Save generated agents to IndexedDB and registry.
  323. * Clears old generated agents for this stage first.
  324. */
  325. export async function saveGeneratedAgents(
  326. stageId: string,
  327. agents: Array<{
  328. id: string;
  329. name: string;
  330. role: string;
  331. persona: string;
  332. avatar: string;
  333. color: string;
  334. priority: number;
  335. voiceConfig?: { providerId: string; voiceId: string };
  336. }>,
  337. ): Promise<string[]> {
  338. const { db } = await import('@/lib/utils/database');
  339. // Clear old generated agents for this stage
  340. await db.generatedAgents.where('stageId').equals(stageId).delete();
  341. // Clear from registry
  342. const registry = useAgentRegistry.getState();
  343. for (const agent of registry.listAgents()) {
  344. if (agent.isGenerated) registry.deleteAgent(agent.id);
  345. }
  346. // Write to IndexedDB
  347. const records = agents.map((a) => ({ ...a, stageId, createdAt: Date.now() }));
  348. await db.generatedAgents.bulkPut(records);
  349. // Add to registry
  350. for (const record of records) {
  351. const { voiceConfig, ...rest } = record;
  352. registry.addAgent({
  353. ...rest,
  354. allowedActions: getActionsForRole(record.role),
  355. isDefault: false,
  356. isGenerated: true,
  357. boundStageId: stageId,
  358. createdAt: new Date(record.createdAt),
  359. updatedAt: new Date(record.createdAt),
  360. ...(voiceConfig
  361. ? {
  362. voiceConfig: {
  363. providerId: voiceConfig.providerId as TTSProviderId,
  364. voiceId: voiceConfig.voiceId,
  365. },
  366. }
  367. : {}),
  368. });
  369. }
  370. return records.map((r) => r.id);
  371. }