app.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. const icons = {
  2. menu: '<path d="M4 7h16M4 12h11M4 17h16"/>',
  3. flower: Array.from(
  4. { length: 8 },
  5. (_, index) =>
  6. `<ellipse cx="12" cy="7.3" rx="2.15" ry="4.6" transform="rotate(${index * 45} 12 12)"/>`,
  7. ).join(''),
  8. 'arrow-right': '<path d="M5 12h14m-5-5 5 5-5 5"/>',
  9. 'arrow-up': '<path d="M12 19V5m-6 6 6-6 6 6"/>',
  10. back: '<path d="m14 5-7 7 7 7"/>',
  11. chevron: '<path d="m8 10 4 4 4-4"/>',
  12. right: '<path d="m9 6 6 6-6 6"/>',
  13. plus: '<path d="M12 5v14M5 12h14"/>',
  14. close: '<path d="m6 6 12 12M6 18 18 6"/>',
  15. chat: '<path d="M20 11.5a7.7 7.7 0 0 1-8 7.5 9 9 0 0 1-3-.5L4 20l1.5-4.5A7.2 7.2 0 0 1 4 11.5a8 8 0 0 1 16 0Z"/><path d="M8 10h8M8 14h5"/>',
  16. edit: '<path d="M12 4H4v16h16v-8M10 14l1-4L19 2l3 3-8 8Z"/>',
  17. search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4 4"/>',
  18. people:
  19. '<circle cx="9" cy="8" r="3"/><path d="M3 20v-3a6 6 0 0 1 12 0v3m1-15a3 3 0 0 1 0 6m2 3a5 5 0 0 1 3 4v2"/>',
  20. grid: '<rect x="4" y="4" width="6" height="6" rx="1.5"/><rect x="14" y="4" width="6" height="6" rx="1.5"/><rect x="4" y="14" width="6" height="6" rx="1.5"/><rect x="14" y="14" width="6" height="6" rx="1.5"/>',
  21. user: '<circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
  22. more: '<circle cx="5" cy="12" r=".9"/><circle cx="12" cy="12" r=".9"/><circle cx="19" cy="12" r=".9"/>',
  23. folder: '<path d="M3 7a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/>',
  24. archive: '<rect x="3" y="4" width="18" height="4" rx="1"/><path d="M5 8v12h14V8M10 12h4"/>',
  25. file: '<path d="M14 3H5v18h14V8Zm0 0v6h5M8 13h8M8 17h6"/>',
  26. clip: '<path d="m8 13 7-7a3 3 0 0 1 4 4L9 20a5 5 0 0 1-7-7L13 2"/>',
  27. check: '<path d="m5 12 4 4L19 6"/>',
  28. shield: '<path d="m12 3 8 3v6c0 5-8 9-8 9s-8-4-8-9V6Z"/><path d="m8 12 3 3 5-6"/>',
  29. copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M15 8V3H3v13h5"/>',
  30. moon: '<path d="M20 14A8 8 0 0 1 10 4a8.5 8.5 0 1 0 10 10Z"/>',
  31. bell: '<path d="M5 17h14l-2-4V9a5 5 0 0 0-10 0v4Zm5 3h4"/>',
  32. key: '<circle cx="8" cy="9" r="5"/><path d="m12 13 8 8m-4-4 3-3"/>',
  33. eye: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/>',
  34. logout: '<path d="M10 4H4v16h6m5-12 5 4-5 4m-6-4h11"/>',
  35. link: '<path d="m9 15 6-6m-4-3 2-2a5 5 0 0 1 7 7l-2 2m-5 5-2 2a5 5 0 0 1-7-7l2-2"/>',
  36. wallet: '<rect x="3" y="5" width="18" height="15" rx="2"/><path d="M3 8h18m-5 4h5v5h-5Z"/>',
  37. trash: '<path d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7m4-7v7"/>',
  38. download: '<path d="M12 3v12m-5-5 5 5 5-5M4 16v5h16v-5"/>',
  39. spark: '<path d="m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5Z"/>',
  40. wifi: '<path d="M3 8a15 15 0 0 1 18 0M6 12a10 10 0 0 1 12 0M9 16a5 5 0 0 1 6 0"/><circle cx="12" cy="20" r=".7"/>',
  41. signal: '<path d="M4 19v-3m5 3v-6m5 6V9m5 10V5" stroke-width="2.8"/>',
  42. battery:
  43. '<rect x="2" y="6" width="18" height="12" rx="3"/><path d="M22 10v4M5 9h12v6H5Z" fill="currentColor" stroke="none"/>',
  44. };
  45. const icon = (name, className = '') =>
  46. `<svg class="${className}" viewBox="0 0 24 24" aria-hidden="true">${icons[name] || icons.spark}</svg>`;
  47. const esc = (value) =>
  48. String(value).replace(
  49. /[&<>"']/g,
  50. (character) =>
  51. ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character],
  52. );
  53. const ib = (name, label, action, extra = '') =>
  54. `<button class="icon-button" aria-label="${esc(label)}" data-action="${action}" ${extra}>${icon(name)}</button>`;
  55. const agents = [
  56. {
  57. id: 'a1',
  58. name: '小禾',
  59. role: '研究与写作伙伴',
  60. tone: '',
  61. online: true,
  62. cpu: '12%',
  63. memory: '328 MB',
  64. balance: '128.60',
  65. task: '正在整理产品体验调研',
  66. symbol: 'flower',
  67. },
  68. {
  69. id: 'a2',
  70. name: '阿澈',
  71. role: '开发与技术伙伴',
  72. tone: 'clay',
  73. online: true,
  74. cpu: '8%',
  75. memory: '256 MB',
  76. balance: '86.20',
  77. task: '等待新的协作指令',
  78. symbol: 'grid',
  79. },
  80. {
  81. id: 'a3',
  82. name: '知夏',
  83. role: '设计与创意伙伴',
  84. tone: 'lilac',
  85. online: false,
  86. cpu: '—',
  87. memory: '—',
  88. balance: '42.00',
  89. task: '当前离线,连接恢复后继续协作',
  90. symbol: 'spark',
  91. },
  92. ];
  93. const conversations = [
  94. {
  95. id: 'c1',
  96. title: '把产品的第一印象做好',
  97. agentId: 'a1',
  98. preview: '我整理了三个可以落地的优化方向。',
  99. time: '刚刚',
  100. group: '今天',
  101. workspace: 'w1',
  102. unread: 2,
  103. archived: false,
  104. },
  105. {
  106. id: 'c2',
  107. title: '官网首页的灵感与参考',
  108. agentId: 'a3',
  109. preview: '留白、秩序,以及一点点恰好的温度。',
  110. time: '10:24',
  111. group: '今天',
  112. workspace: 'w1',
  113. unread: 0,
  114. archived: false,
  115. },
  116. {
  117. id: 'c3',
  118. title: '梳理一下这周的工作',
  119. agentId: 'a1',
  120. preview: '已按优先级整理好,随时可以继续。',
  121. time: '昨天',
  122. group: '昨天',
  123. workspace: null,
  124. unread: 0,
  125. archived: false,
  126. },
  127. {
  128. id: 'c4',
  129. title: '登录接口联调记录',
  130. agentId: 'a2',
  131. preview: '接口参数和错误处理已经检查完毕。',
  132. time: '昨天',
  133. group: '昨天',
  134. workspace: 'w2',
  135. unread: 1,
  136. archived: false,
  137. },
  138. {
  139. id: 'c5',
  140. title: '一些还没成形的小想法',
  141. agentId: 'a1',
  142. preview: '我们可以从一个最小的版本开始。',
  143. time: '周五',
  144. group: '更早',
  145. workspace: null,
  146. unread: 0,
  147. archived: false,
  148. },
  149. {
  150. id: 'c6',
  151. title: '上一版品牌文案',
  152. agentId: 'a1',
  153. preview: '品牌文案讨论已归档。',
  154. time: '11/08',
  155. group: '更早',
  156. workspace: 'w1',
  157. unread: 0,
  158. archived: true,
  159. },
  160. ];
  161. let workspaces = [
  162. { id: 'w1', name: '产品与灵感' },
  163. { id: 'w2', name: '研发协作' },
  164. ];
  165. const messages = new Map();
  166. const collaboration = new Map([
  167. ['c1', { kind: 'done', label: '体验优化建议已交付', elapsed: '刚刚完成' }],
  168. ['c2', { kind: 'attention', label: '连接中断,等待恢复', elapsed: '需要关注' }],
  169. ['c3', { kind: 'running', label: '正在整理本周的优先级', elapsed: '已进行 2 分钟' }],
  170. ['c4', { kind: 'running', label: '正在检查接口返回结果', elapsed: '已进行 45 秒' }],
  171. ['c5', { kind: 'idle', label: '等待新的想法', elapsed: '空闲' }],
  172. ]);
  173. const activityNames = { running: '进行中', attention: '待关注', done: '已完成', idle: '空闲' };
  174. const drafts = new Map();
  175. const draftKey = () => (state.page === 'chat' ? state.currentId : 'home');
  176. function saveDraft() {
  177. if (['home', 'chat'].includes(state.page))
  178. drafts.set(draftKey(), { text: state.draft, files: [...state.attachments] });
  179. }
  180. function restoreDraft() {
  181. const draft = drafts.get(draftKey());
  182. state.draft = draft?.text || '';
  183. state.attachments = [...(draft?.files || [])];
  184. }
  185. let preferences = { dark: false, palette: 'forest', font: 14 };
  186. try {
  187. preferences = {
  188. ...preferences,
  189. ...JSON.parse(localStorage.getItem('fmode_mobile_proposal_v1') || '{}'),
  190. };
  191. } catch {}
  192. const state = {
  193. page: 'home',
  194. currentId: 'c1',
  195. agentId: null,
  196. draft: '',
  197. attachments: [],
  198. filter: 'all',
  199. contactFilter: 'agents',
  200. agentFilter: 'all',
  201. keyword: '',
  202. expanded: new Set(),
  203. drawerExpanded: new Set(),
  204. pendingSend: false,
  205. newWorkspace: null,
  206. generating: false,
  207. disconnected: false,
  208. tokenVisible: false,
  209. drawerView: 'recent',
  210. activityFilter: 'all',
  211. activityKeyword: '',
  212. ...preferences,
  213. };
  214. const main = document.querySelector('#main'),
  215. header = document.querySelector('#app-header'),
  216. composerArea = document.querySelector('#composer-area'),
  217. tabbar = document.querySelector('#tabbar'),
  218. overlay = document.querySelector('#overlay-root'),
  219. app = document.querySelector('#app');
  220. let returnFocus, toastTimer, generationTimer;
  221. const getAgent = (agentId) => agents.find((agent) => agent.id === agentId) || agents[0];
  222. const getConversation = (identifier = state.currentId) =>
  223. conversations.find((conversation) => conversation.id === identifier);
  224. const avatar = (agent) => `<span class="avatar ${agent.tone}">${icon(agent.symbol)}</span>`;
  225. const activeConversations = () => conversations.filter((conversation) => !conversation.archived);
  226. const navItems = [
  227. ['messages', 'chat', '会话'],
  228. ['contacts', 'people', '通讯录'],
  229. ['workbench', 'grid', '工作台'],
  230. ['mine', 'user', '我的'],
  231. ];
  232. const emptyState = (title, description = '', symbol = 'search') =>
  233. `<div class="empty-state">${icon(symbol)}<strong>${title}</strong><p>${description}</p></div>`;
  234. const tabs = (items, active, action) =>
  235. `<div class="segmented" aria-label="筛选">${items.map(([value, label]) => `<button data-action="${action}" data-value="${value}" aria-pressed="${value === active}" class="${value === active ? 'active' : ''}">${label}</button>`).join('')}</div>`;
  236. const searchField = (placeholder, action = 'search', value = '') =>
  237. `<label class="search-field">${icon('search')}<input type="search" aria-label="${placeholder}" placeholder="${placeholder}" data-input="${action}" value="${esc(value)}" /></label>`;
  238. const navigation = () =>
  239. navItems
  240. .map(
  241. ([page, symbol, label]) =>
  242. `<button data-action="navigate" data-page="${page}" class="${state.page === page ? 'active' : ''}" ${state.page === page ? 'aria-current="page"' : ''}><span>${icon(symbol)}</span><span>${label}</span></button>`,
  243. )
  244. .join('');
  245. function applyPreferences() {
  246. const device = document.querySelector('#device');
  247. device.classList.toggle('dark', state.dark);
  248. const palettes = {
  249. forest: ['#386b52', '#eaf1e8', '#a4c59a', '#303f30'],
  250. blue: ['#496a96', '#eaf0f8', '#a5bde0', '#2e3c50'],
  251. purple: ['#806495', '#f0eaf5', '#c9acdf', '#403349'],
  252. amber: ['#9a7641', '#f4efdf', '#ddc195', '#443a27'],
  253. };
  254. const palette = palettes[state.palette] || palettes.forest;
  255. device.style.setProperty('--accent', palette[state.dark ? 2 : 0]);
  256. device.style.setProperty('--tint', palette[state.dark ? 3 : 1]);
  257. device.style.setProperty('--chat-font', `${state.font}px`);
  258. try {
  259. localStorage.setItem(
  260. 'fmode_mobile_proposal_v1',
  261. JSON.stringify({ dark: state.dark, palette: state.palette, font: state.font }),
  262. );
  263. } catch {}
  264. }
  265. function navigate(page, identifier) {
  266. const destination =
  267. page === 'chat'
  268. ? `#/chat/${identifier || state.currentId}`
  269. : page === 'agent'
  270. ? `#/agent/${identifier}`
  271. : `#/${page}`;
  272. if (location.hash === destination) readRoute();
  273. else location.hash = destination;
  274. }
  275. function readRoute() {
  276. saveDraft();
  277. const [page = 'home', identifier] = location.hash.replace(/^#\/?/, '').split('/');
  278. state.page = ['home', 'chat', 'messages', 'contacts', 'workbench', 'mine', 'agent'].includes(page)
  279. ? page
  280. : 'home';
  281. if (state.page === 'chat') {
  282. const conversation = getConversation(identifier);
  283. if (conversation) {
  284. state.currentId = identifier;
  285. conversation.unread = 0;
  286. } else state.page = 'messages';
  287. }
  288. if (state.page === 'agent') state.detailAgentId = identifier;
  289. state.keyword = '';
  290. restoreDraft();
  291. closeOverlay();
  292. render();
  293. main.scrollTop = 0;
  294. }
  295. function render() {
  296. const conversation = getConversation(),
  297. agent = getAgent(conversation?.agentId);
  298. if (state.page === 'chat')
  299. header.innerHTML = `${ib('menu', '打开会话侧栏', 'drawer')}<div class="header-center"><button class="header-title" data-action="edit-current-title" aria-label="编辑会话标题:${esc(conversation.title)}"><strong>${esc(conversation.title)}</strong>${icon('edit')}</button><small>${esc(agent.name)}<span class="subtitle-separator">/</span><span class="activity-text ${collaboration.get(conversation.id)?.kind || 'idle'}">${activityNames[collaboration.get(conversation.id)?.kind || 'idle']}</span></small></div>${ib('more', '会话详情', 'details')}`;
  300. else if (state.page === 'home')
  301. header.innerHTML = `${ib('menu', '打开会话侧栏', 'drawer')}<div class="header-brand">${icon('flower')}<strong>fmode</strong></div><button class="profile-button" data-action="navigate" data-page="mine" aria-label="我的">林</button>`;
  302. else if (state.page === 'agent')
  303. header.innerHTML = `${ib('back', '返回通讯录', 'navigate', 'data-page="contacts"')}<strong class="page-title">数字生命设置</strong>`;
  304. else
  305. header.innerHTML = `${ib('menu', '打开会话侧栏', 'drawer')}<strong class="page-title">${navItems.find(([page]) => page === state.page)?.[2]}</strong>${state.page === 'messages' ? ib('edit', '新建对话', 'new-chat') : '<span style="width:44px"></span>'}`;
  306. ({
  307. home: renderHome,
  308. chat: renderChat,
  309. messages: renderMessages,
  310. contacts: renderContacts,
  311. workbench: renderWorkbench,
  312. mine: renderMine,
  313. agent: renderAgent,
  314. })[state.page]();
  315. if (state.page === 'chat' && messages.get(state.currentId)?.length === 0) {
  316. main.innerHTML = `<section class="screen blank-chat"><div class="blank-chat-mark">${icon(agent.symbol)}</div><h1>新的想法,直接说。</h1><p>正在和 ${esc(agent.name)} 对话<br />${esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '日常对话')} · 不影响之前的会话</p></section>`;
  317. }
  318. if (state.page === 'mine')
  319. main
  320. .querySelector('.version-text')
  321. .insertAdjacentHTML(
  322. 'beforeend',
  323. '<br /><button class="text-button" data-action="preview-states">查看加载与反馈状态 · 原型专用</button>',
  324. );
  325. tabbar.innerHTML = ['messages', 'contacts', 'workbench', 'mine'].includes(state.page)
  326. ? navigation()
  327. : '';
  328. if (['home', 'chat'].includes(state.page)) renderComposer();
  329. else composerArea.innerHTML = '';
  330. document
  331. .querySelectorAll('[data-scene]')
  332. .forEach((button) => button.classList.toggle('active', button.dataset.scene === state.page));
  333. applyPreferences();
  334. }
  335. function renderHome() {
  336. main.innerHTML = `<section class="screen home-screen"><div class="home-hero"><div class="hero-art">${icon('flower')}</div><div class="overline">每一个想法,都值得被认真对待</div><h1>让想法,<br />再往前一步。</h1><p>写下想做的事,和你的数字生命一起完成。</p></div><div class="prompts"><button class="prompt" data-action="prompt" data-value="帮我梳理一下这周的工作安排">${icon('file')}梳理思路</button><button class="prompt" data-action="prompt" data-value="帮我写一份产品体验优化方案">${icon('edit')}写点什么</button><button class="prompt" data-action="prompt" data-value="帮我找几个官网设计的灵感方向">${icon('spark')}找点灵感</button></div><div class="recent-block"><div class="section-label"><span>接着上次的想法</span><button class="text-button" data-action="navigate" data-page="messages">全部会话 ${icon('arrow-right')}</button></div>${activeConversations()
  337. .slice(0, 2)
  338. .map(
  339. (conversation) =>
  340. `<button class="recent-row" data-action="open-chat" data-id="${conversation.id}">${icon('chat')}<span class="row-text"><strong>${esc(conversation.title)}</strong><small>${esc(getAgent(conversation.agentId).name)} · ${esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '日常对话')}</small></span><time>${conversation.time}</time></button>`,
  341. )
  342. .join('')}</div></section>`;
  343. }
  344. function renderComposer() {
  345. const agentId = state.page === 'chat' ? getConversation()?.agentId : state.agentId,
  346. agent = agentId ? getAgent(agentId) : null;
  347. composerArea.innerHTML = `<div class="composer"><div class="attachment-list">${state.attachments.map((file, index) => `<span class="attachment-chip">${icon('clip')}<span>${esc(file.name)}</span><button aria-label="移除附件 ${esc(file.name)}" data-action="remove-attachment" data-index="${index}">${icon('close')}</button></span>`).join('')}</div><textarea id="draft" rows="1" aria-label="输入消息" placeholder="说说你的想法…" ${state.generating ? 'disabled' : ''}>${esc(state.draft)}</textarea><div class="composer-tools">${ib('plus', '添加附件', 'attach')}<button class="agent-select" data-action="${state.page === 'home' ? 'pick-agent' : 'agent-info'}">${agent ? '<i class="dot ' + (agent.online ? '' : 'offline') + '"></i>' : icon('flower')}<span>${agent ? esc(agent.name) + ' · ' + agent.role : '选择数字生命'}</span>${state.page === 'home' ? icon('chevron') : ''}</button><button class="send-button" aria-label="${state.generating ? '发送中' : '发送消息'}" data-action="send" ${state.generating || (!state.draft.trim() && !state.attachments.length) ? 'disabled' : ''}>${state.generating ? '<span class="typing"><i></i><i></i><i></i></span>' : icon('arrow-up')}</button></div></div><div class="composer-footnote">${state.page === 'home' ? '和数字生命一起,把想法变成现实' : '内容由 AI 生成,请核实重要信息'} · 演示</div>`;
  348. if (state.page === 'chat') {
  349. const running = activeConversations().filter(
  350. (conversation) => collaboration.get(conversation.id)?.kind === 'running',
  351. ).length;
  352. const attention = activeConversations().filter(
  353. (conversation) => collaboration.get(conversation.id)?.kind === 'attention',
  354. ).length;
  355. composerArea.insertAdjacentHTML(
  356. 'afterbegin',
  357. `<div class="collaboration-rail"><button class="quick-current" data-action="quick-current" aria-label="在当前数字生命 ${esc(agent.name)} 中新建对话">${icon('edit')}<span>新对话</span><span class="quick-agent">· ${esc(agent.name)}</span></button><button class="activity-entry" data-action="activity" aria-label="切换协作,${running} 个进行中,${attention} 个待关注"><span class="activity-orbit ${running ? 'running' : ''}"></span><span>${running ? running + ' 个进行中' : '协作动态'}</span>${attention ? `<span class="attention-count">${attention}</span>` : ''}${icon('chevron')}</button></div>`,
  358. );
  359. }
  360. const textarea = document.querySelector('#draft');
  361. textarea.setAttribute('enterkeyhint', 'enter');
  362. textarea.style.height = 'auto';
  363. textarea.style.height = `${Math.min(textarea.scrollHeight, 116)}px`;
  364. }
  365. function conversationRow(conversation) {
  366. const agent = getAgent(conversation.agentId);
  367. return `<article class="conversation-row"><button class="conversation-open" data-action="open-chat" data-id="${conversation.id}">${avatar(agent)}<span class="conversation-body"><span class="conversation-top"><strong>${esc(conversation.title)}</strong><time>${conversation.time}</time></span><p>${esc(conversation.preview)}</p><span class="conversation-meta">${esc(agent.name)}${conversation.workspace ? ' · ' + esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '工作区') : ''}<span class="inline-activity ${collaboration.get(conversation.id)?.kind || 'idle'}">${activityNames[collaboration.get(conversation.id)?.kind || 'idle']}</span>${conversation.unread ? `<span class="unread">${conversation.unread}</span>` : ''}</span></span></button><button class="row-more" data-action="conversation-menu" data-id="${conversation.id}" aria-label="${esc(conversation.title)} 更多操作">${icon('more')}</button></article>`;
  368. }
  369. function renderMessages() {
  370. main.innerHTML = `<section class="screen"><p class="page-subtitle">每一次对话,都是想法向前的一步。</p>${searchField('搜索会话或数字生命', 'search', state.keyword)}${tabs(
  371. [
  372. ['all', '全部'],
  373. ['unread', '未读'],
  374. ['workspace', '工作区'],
  375. ],
  376. state.filter,
  377. 'message-filter',
  378. )}<div id="conversation-results">${conversationResults()}</div></section>`;
  379. }
  380. function conversationResults() {
  381. const keyword = state.keyword.trim().toLowerCase(),
  382. filtered = activeConversations().filter(
  383. (conversation) =>
  384. (state.filter !== 'unread' || conversation.unread > 0) &&
  385. `${conversation.title} ${getAgent(conversation.agentId).name}`
  386. .toLowerCase()
  387. .includes(keyword),
  388. );
  389. if (state.filter === 'workspace')
  390. return `<button class="text-button" data-action="create-workspace">${icon('plus')} 新建工作区</button>${workspaces
  391. .map((workspace) => {
  392. const rows = filtered.filter((conversation) => conversation.workspace === workspace.id);
  393. if (keyword && !rows.length && !workspace.name.includes(keyword)) return '';
  394. return `<section class="workspace"><header class="workspace-head"><button class="workspace-toggle" data-action="toggle-workspace" data-id="${workspace.id}" aria-expanded="${state.expanded.has(workspace.id)}" aria-controls="workspace-${workspace.id}">${icon(state.expanded.has(workspace.id) ? 'chevron' : 'right')}${icon('folder')} ${esc(workspace.name)}<small>${rows.length}</small></button>${ib('plus', '在 ' + workspace.name + ' 中新建对话', 'workspace-chat', `data-id="${workspace.id}"`)}${ib('more', workspace.name + ' 更多操作', 'workspace-menu', `data-id="${workspace.id}"`)}</header><div id="workspace-${workspace.id}" ${state.expanded.has(workspace.id) || keyword ? '' : 'hidden'}>${rows.length ? rows.map(conversationRow).join('') : emptyState('还没有对话', '在这里开始一个新的想法', 'chat')}</div></section>`;
  395. })
  396. .join('')}`;
  397. if (!filtered.length)
  398. return emptyState(
  399. state.filter === 'unread' ? '未读已清空,安心专注' : '没有找到相关对话',
  400. state.filter === 'unread' ? '新的消息会出现在这里。' : '换个关键词再试试。',
  401. );
  402. return ['今天', '昨天', '更早']
  403. .map((group) => {
  404. const rows = filtered.filter((conversation) => conversation.group === group);
  405. return rows.length
  406. ? `<div class="group-heading">${group}</div>${rows.map(conversationRow).join('')}`
  407. : '';
  408. })
  409. .join('');
  410. }
  411. const sampleAnswer =
  412. '<p>好的。第一印象不一定要做得更满,<br />而是让用户更快地感到:<strong>这里懂我。</strong></p><h2>先把这三件事做好</h2><ul><li><strong>让入口更清楚</strong><br />一个明确的主操作,比同时展示很多功能更有效。</li><li><strong>让阅读更轻松</strong><br />减少卡片边框,拉开段落间距,让内容成为主角。</li><li><strong>让操作有回应</strong><br />无论是发送、等待还是完成,都给出清晰、克制的反馈。</li></ul><blockquote>好的体验,是不用思考下一步该点哪里。</blockquote><p>我把具体建议整理成了一份文档,可以先从首页和对话页开始验证。</p>';
  413. function sampleMessages(conversation) {
  414. if (conversation.id === 'c1')
  415. return [
  416. { role: 'user', text: '我们来想想,怎么把产品的第一印象做得更好?' },
  417. { role: 'assistant', html: sampleAnswer, file: true },
  418. ];
  419. return [
  420. { role: 'user', text: conversation.title },
  421. {
  422. role: 'assistant',
  423. html: `<p>${esc(conversation.preview)}</p><p>这段对话保留在「${esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '日常对话')}」中,你可以接着补充想法。</p><blockquote>这是界面演示内容,不是真实的历史消息。</blockquote>`,
  424. },
  425. ];
  426. }
  427. function fileCard() {
  428. return `<button class="file-card" data-action="preview-file"><span class="file-badge">DOC</span><span><strong>产品初体验优化建议</strong><small>DOCX · 24 KB · 已上传云盘(演示)</small></span>${icon('right')}</button>`;
  429. }
  430. function renderChat() {
  431. const conversation = getConversation(),
  432. agent = getAgent(conversation.agentId);
  433. if (!messages.has(conversation.id)) messages.set(conversation.id, sampleMessages(conversation));
  434. const rows = messages.get(conversation.id);
  435. main.innerHTML = `<section class="screen chat-screen">${state.disconnected ? `<button class="connection-banner" data-action="reconnect">${icon('wifi')}连接已断开,点击重连 ${icon('right')}</button>` : ''}<div class="chat-date">今天 · 10:42</div>${rows.map((message, index) => (message.role === 'user' ? `<div class="user-message"><div class="user-bubble">${esc(message.text).replace(/\n/g, '<br />')}${message.files?.map((name) => `<span class="user-file">${icon('clip')} ${esc(name)}</span>`).join('') || ''}</div></div>` : `<article class="assistant-message"><div class="assistant-heading">${icon(agent.symbol)}<span>${esc(agent.name)}</span><time>演示回复</time></div><details class="process"><summary>${icon('check')} 已完成 ${message.file ? '3' : '2'} 个步骤 · ${message.file ? '12' : '3'} 秒 ${icon('chevron', 'chevron')}</summary><ol><li>理解需求与对话上下文</li><li>整理可执行的建议</li>${message.file ? '<li>生成文档并上传云盘</li>' : ''}</ol></details><div class="assistant-body">${message.html}</div>${message.file ? fileCard() : ''}<div class="message-actions"><button aria-label="复制回复" data-action="copy-message" data-index="${index}">${icon('copy')}</button>${message.file ? `<button aria-label="查看成果文件" data-action="details" data-tab="deliver">${icon('file')}</button>` : ''}<small>AI 生成 · 请核实</small></div></article>`)).join('')}${state.generating && state.generatingId === conversation.id ? '<div class="assistant-heading">' + icon(agent.symbol) + '正在整理你的想法</div><div class="typing" role="status" aria-label="正在生成演示回复"><i></i><i></i><i></i></div>' : ''}</section>`;
  436. }
  437. function renderContacts() {
  438. main.innerHTML = `<section class="screen">${tabs(
  439. [
  440. ['agents', '数字生命'],
  441. ['coworkers', '同事'],
  442. ],
  443. state.contactFilter,
  444. 'contact-filter',
  445. )}${searchField('搜索联系人', 'contact-search', state.keyword)}<div id="contact-results">${contactResults()}</div></section>`;
  446. }
  447. function contactResults() {
  448. if (state.contactFilter === 'coworkers') {
  449. const people = [
  450. { name: '林一', role: '产品设计 · 我', initial: '林' },
  451. { name: '陈序', role: '研发协作', initial: '陈' },
  452. ].filter((person) => person.name.includes(state.keyword));
  453. return people.length
  454. ? `<div class="contact-department">产品与研发 · ${people.length} 人</div>${people.map((person) => `<div class="contact-row"><button data-action="coworker" data-name="${person.name}"><span class="avatar person">${person.initial}</span><span><strong>${person.name}</strong><small>${person.role}</small></span></button>${icon('right')}</div>`).join('')}`
  455. : emptyState('没有找到联系人');
  456. }
  457. const filtered = agents.filter((agent) => `${agent.name} ${agent.role}`.includes(state.keyword));
  458. return filtered.length
  459. ? `<div class="section-label"><span>我的数字伙伴</span><span>${filtered.length} 位</span></div>${filtered.map((agent) => `<div class="contact-row"><button data-action="open-agent" data-id="${agent.id}">${avatar(agent)}<span><strong>${esc(agent.name)}</strong><small>${agent.role} · ${agent.online ? '在线' : '离线'}</small></span></button>${icon('right')}</div>`).join('')}`
  460. : emptyState('没有找到数字生命');
  461. }
  462. function renderWorkbench() {
  463. main.innerHTML = `<section class="screen"><p class="page-subtitle">伙伴们的工作状态,一眼就知道。</p><div class="overview"><div><strong>3</strong><small>数字生命</small></div><div><strong>2<span style="font-size:12px"> / 3</span></strong><small>在线</small></div><div><strong>1</strong><small>离线</small></div></div>${tabs(
  464. [
  465. ['all', '全部'],
  466. ['online', '在线'],
  467. ['offline', '离线'],
  468. ],
  469. state.agentFilter,
  470. 'agent-filter',
  471. )}${searchField('搜索数字生命', 'agent-search', state.keyword)}<div id="agent-results">${agentResults()}</div></section>`;
  472. }
  473. function agentResults() {
  474. const filtered = agents.filter(
  475. (agent) =>
  476. agent.name.includes(state.keyword) &&
  477. (state.agentFilter === 'all' || agent.online === (state.agentFilter === 'online')),
  478. );
  479. return filtered.length
  480. ? filtered
  481. .map(
  482. (agent) =>
  483. `<article class="agent-card"><div class="agent-card-head">${avatar(agent)}<div><h2>${esc(agent.name)}</h2><small>${agent.role}</small></div><span class="tag ${agent.online ? '' : 'offline'}">${agent.online ? '在线' : '离线'}</span></div><p class="agent-current">${agent.task}</p><div class="agent-metrics"><span>CPU <b>${agent.cpu}</b></span><span>内存 <b>${agent.memory}</b></span><span>余额 <b>¥${agent.balance}</b></span></div><div class="agent-actions"><button data-action="channels" data-id="${agent.id}">${icon('link')}通道</button><button data-action="recharge" data-id="${agent.id}">${icon('wallet')}充值</button><button data-action="agent-chat" data-id="${agent.id}">进入会话 ${icon('arrow-right')}</button></div></article>`,
  484. )
  485. .join('')
  486. : emptyState('没有匹配的数字生命');
  487. }
  488. function renderMine() {
  489. main.innerHTML = `<section class="screen"><div class="profile-card"><span class="avatar">林</span><div><h2>林一</h2><p>fmode 体验空间 · 演示账号</p></div></div><section class="settings-group"><h2>外观与阅读</h2><div class="palette-row">${[
  490. ['forest', '#386b52', '森林'],
  491. ['blue', '#496a96', '湖蓝'],
  492. ['purple', '#806495', '暮紫'],
  493. ['amber', '#9a7641', '暖砂'],
  494. ]
  495. .map(
  496. ([value, color, label]) =>
  497. `<button class="palette-option ${state.palette === value ? 'active' : ''}" style="--swatch:${color}" aria-label="${label}配色" aria-pressed="${state.palette === value}" data-action="palette" data-value="${value}"><span></span></button>`,
  498. )
  499. .join(
  500. '',
  501. )}</div><button class="settings-row" data-action="theme" role="switch" aria-checked="${state.dark}">${icon('moon')}深色模式<span class="toggle ${state.dark ? 'on' : ''}"></span></button><button class="settings-row" data-action="font">${icon('file')}对话正文字号<small>${state.font === 14 ? '标准' : state.font === 16 ? '较大' : '大号'}</small>${icon('right')}</button></section><section class="settings-group"><h2>账号与通知</h2><button class="settings-row" data-action="token">${icon('key')}访问 Token<small>仅演示占位</small>${icon('right')}</button><button class="settings-row" data-action="notifications">${icon('bell')}消息与任务通知<small>权限说明</small>${icon('right')}</button><button class="settings-row danger" data-action="logout">${icon('logout')}退出登录${icon('right')}</button></section><div class="version-text">fmode · 人机共生中枢<br />Mobile experience / 01 · 独立体验提案</div></section>`;
  502. }
  503. function renderAgent() {
  504. const agent = getAgent(state.detailAgentId);
  505. main.innerHTML = `<section class="screen"><div class="profile-card">${avatar(agent)}<div><h2>${esc(agent.name)}</h2><p>${agent.role}</p></div></div><section class="settings-group"><h2>容器设置</h2><button class="settings-row" data-action="rename-agent" data-id="${agent.id}">显示名称<small>${esc(agent.name)}</small>${icon('right')}</button><div class="settings-row">连接状态<small>${agent.online ? '在线' : '离线'}</small></div></section><p class="page-subtitle">沿用现有通讯录逻辑:数字生命详情只提供重命名。</p></section>`;
  506. }
  507. function openOverlay(html) {
  508. if (!overlay.childElementCount) returnFocus = document.activeElement;
  509. overlay.innerHTML = html;
  510. app.inert = true;
  511. requestAnimationFrame(() => {
  512. const target = overlay.querySelector('[autofocus]') || overlay.querySelector('button,input,select,summary');
  513. target?.focus({ preventScroll: true });
  514. });
  515. }
  516. function closeOverlay() {
  517. const wasOpen = overlay.childElementCount > 0;
  518. overlay.innerHTML = '';
  519. app.inert = false;
  520. state.pendingSend = false;
  521. if (wasOpen && returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
  522. }
  523. function sheet(title, content, extra = '') {
  524. openOverlay(
  525. `<div class="backdrop" data-action="close" aria-hidden="true"></div><section class="sheet" role="dialog" aria-modal="true" aria-labelledby="sheet-title"><div class="sheet-handle" aria-hidden="true"></div><header class="sheet-header"><h2 id="sheet-title">${title}</h2>${ib('close', '关闭面板', 'close')}</header>${extra}<div class="sheet-body">${content}</div></section>`,
  526. );
  527. }
  528. function drawerHistory(keyword = '') {
  529. if (state.drawerView === 'recent') {
  530. const recent = activeConversations().filter((conversation) =>
  531. `${conversation.title} ${getAgent(conversation.agentId).name} ${workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || ''}`.includes(
  532. keyword,
  533. ),
  534. );
  535. return `<div class="group-heading">最近的协作<span>${recent.length} 段对话</span></div>${recent.map((conversation) => drawerConversation(conversation)).join('') || emptyState('没有找到对话', '换个关键词再试试。')}`;
  536. }
  537. if (state.drawerView === 'agents') {
  538. return (
  539. agents
  540. .map((agent) => {
  541. const rows = activeConversations().filter(
  542. (conversation) =>
  543. conversation.agentId === agent.id &&
  544. `${conversation.title} ${agent.name}`.includes(keyword),
  545. );
  546. if (!rows.length) return '';
  547. const running = rows.filter(
  548. (conversation) => collaboration.get(conversation.id)?.kind === 'running',
  549. ).length;
  550. return `<section class="drawer-agent-group"><div class="drawer-agent-head">${avatar(agent)}<span><strong>${esc(agent.name)}</strong><small>${agent.role}</small></span>${running ? `<span class="inline-activity running">${running} 进行中</span>` : `<small>${rows.length} 段对话</small>`}<button class="drawer-agent-new" data-action="agent-new" data-id="${agent.id}" aria-label="在 ${esc(agent.name)} 中新建对话">${icon('plus')}</button></div>${rows.map((conversation) => drawerConversation(conversation)).join('')}</section>`;
  551. })
  552. .join('') || emptyState('没有找到对话')
  553. );
  554. }
  555. const matches = (conversation) =>
  556. `${conversation.title} ${getAgent(conversation.agentId).name}`.includes(keyword),
  557. row = (conversation) =>
  558. `<button class="drawer-history ${state.page === 'chat' && state.currentId === conversation.id ? 'active' : ''}" data-action="open-chat" data-id="${conversation.id}">${icon('chat')}<span>${esc(conversation.title)}</span></button>`;
  559. return `${workspaces
  560. .map(
  561. (workspace) =>
  562. `<div class="workspace-head"><button class="workspace-toggle" data-action="drawer-workspace" data-id="${workspace.id}" aria-expanded="${state.drawerExpanded.has(workspace.id)}">${icon(state.drawerExpanded.has(workspace.id) ? 'chevron' : 'right')}${icon('folder')}${esc(workspace.name)}</button>${ib('more', workspace.name + ' 更多操作', 'workspace-menu', `data-id="${workspace.id}"`)}</div>${
  563. state.drawerExpanded.has(workspace.id) || keyword
  564. ? activeConversations()
  565. .filter(
  566. (conversation) =>
  567. conversation.workspace === workspace.id && matches(conversation),
  568. )
  569. .map(row)
  570. .join('')
  571. : ''
  572. }`,
  573. )
  574. .join(
  575. '',
  576. )}<button class="text-button" data-action="create-workspace">${icon('plus')} 新建工作区</button><div class="group-heading">日常对话</div>${
  577. activeConversations()
  578. .filter((conversation) => !conversation.workspace && matches(conversation))
  579. .map(row)
  580. .join('') || '<p class="sheet-description">暂无匹配对话</p>'
  581. }<button class="drawer-history" data-action="show-archived">${icon('archive')}已归档 <span style="margin-left:auto">${conversations.filter((conversation) => conversation.archived).length}</span></button>`;
  582. }
  583. function openDrawer() {
  584. openOverlay(
  585. `<div class="backdrop" data-action="close" aria-hidden="true"></div><aside class="drawer" role="dialog" aria-modal="true" aria-label="会话与导航"><div class="drawer-header"><div class="header-brand">${icon('flower')}<strong>fmode</strong></div>${ib('close', '关闭侧栏', 'close')}</div><button class="primary-button" data-action="new-chat">${icon('plus')}新建对话</button>${searchField('搜索历史对话', 'drawer-search')}<div class="drawer-scroll" id="drawer-results">${drawerHistory()}</div><nav class="drawer-nav" aria-label="侧栏导航">${navigation()}</nav><div class="drawer-bottom">林一 · 体验空间 / 演示</div></aside>`,
  586. );
  587. overlay.querySelector('.search-field').insertAdjacentHTML(
  588. 'afterend',
  589. tabs(
  590. [
  591. ['recent', '最近'],
  592. ['agents', '数字生命'],
  593. ['workspace', '工作区'],
  594. ],
  595. state.drawerView,
  596. 'drawer-view',
  597. ),
  598. );
  599. overlay
  600. .querySelector('.drawer-scroll')
  601. .insertAdjacentHTML(
  602. 'afterend',
  603. '<button class="drawer-archive" data-action="show-archived">' +
  604. icon('archive') +
  605. '已归档对话' +
  606. icon('right') +
  607. '</button>',
  608. );
  609. }
  610. function pickAgent(pending = false) {
  611. sheet(
  612. '和谁一起开始?',
  613. `<p class="sheet-description">选择数字生命,草稿和附件会一并保留。</p>${agents.map((agent) => `<button class="sheet-list-button" data-action="choose-agent" data-id="${agent.id}">${avatar(agent)}<span>${esc(agent.name)}<small>${agent.role} · ${agent.online ? '在线' : '离线'}</small></span>${state.agentId === agent.id ? icon('check', 'selected-check') : icon('right')}</button>`).join('')}<p class="sheet-description" style="margin-top:18px">保留「先选择数字生命,再建立会话」的现有流程。</p>`,
  614. );
  615. state.pendingSend = pending;
  616. }
  617. function details(tab = 'task') {
  618. const agent = getAgent(getConversation().agentId),
  619. content = {
  620. task: `<p class="sheet-description">当前会话中的任务,不新增全局任务入口。</p><div class="sheet-item"><span class="tag">已完成</span><strong>产品初体验优化建议</strong><p>分析首页与对话页的体验问题,整理可执行的改进方向。</p><p>3 / 3 步骤完成 · ${esc(agent.name)}</p></div>`,
  621. file: `${fileCard()}<p class="sheet-description">演示文件内容为静态预览,不会上传或读取云盘。</p>`,
  622. deliver: `<div class="sheet-item"><span class="tag">v1.0</span><strong>产品初体验优化建议</strong><p>今天 10:42 · ${esc(agent.name)} 已交付</p>${fileCard()}</div>`,
  623. state: `<div class="sheet-item"><strong>数字生命</strong><p>${esc(agent.name)} · ${agent.online ? '在线' : '离线'}</p></div><div class="sheet-item"><strong>会话连接</strong><p>${state.disconnected ? '连接中断,等待重连' : '已连接 · 当前没有待发送消息'}</p></div><p class="sheet-description" style="margin-top:18px">原型状态演示(不影响实际服务)</p><div class="state-chips"><button data-action="disconnect">模拟断线</button><button data-action="reconnect">恢复连接</button></div>`,
  624. };
  625. if (state.currentId !== 'c1' && tab !== 'state')
  626. content[tab] = emptyState(
  627. tab === 'task' ? '还没有任务' : tab === 'file' ? '还没有文件' : '还没有成果',
  628. '这段对话中的内容会显示在这里。',
  629. tab === 'task' ? 'check' : 'file',
  630. );
  631. sheet(
  632. '会话详情',
  633. content[tab] || content.task,
  634. tabs(
  635. [
  636. ['task', '任务'],
  637. ['file', '文件'],
  638. ['deliver', '成果'],
  639. ['state', '状态'],
  640. ],
  641. tab,
  642. 'detail-tab',
  643. ),
  644. );
  645. }
  646. function previewFile() {
  647. sheet(
  648. '文档预览',
  649. `<p class="sheet-description">产品初体验优化建议.docx · 演示内容</p><article class="preview-document"><div class="eyebrow">FMODE / EXPERIENCE NOTE</div><h1>把第一印象做好</h1><p>一份围绕移动端的体验优化建议<br />2026.11.16 / v1.0</p><h2>01 · 让入口更清楚</h2><p>保留熟悉的导航,用明确的主操作降低理解成本。</p><h2>02 · 让内容回到中心</h2><p>减少无效的视觉容器,用段落、留白与字重建立信息层级。</p><table><thead><tr><th>页面</th><th>体验方向</th></tr></thead><tbody><tr><td>新建对话</td><td>一个输入框,开始协作</td></tr><tr><td>会话详情</td><td>正文优先,过程折叠</td></tr><tr><td>会话列表</td><td>搜索、分组与清晰状态</td></tr></tbody></table><h2>03 · 每次操作都有回应</h2><p>发送、加载、离线和失败状态清晰可见,操作始终可恢复。</p></article><button class="primary-button" data-action="download-demo">${icon('download')}下载演示文稿(TXT)</button><button class="text-button" data-action="details" data-tab="file">${icon('back')}返回会话文件</button>`,
  650. );
  651. }
  652. function formSheet(title, label, value, submitAction, identifier = '') {
  653. sheet(
  654. title,
  655. `<form class="sheet-form" data-form="${submitAction}" data-id="${identifier}"><label for="form-value">${label}</label><input id="form-value" name="value" maxlength="60" value="${esc(value)}" autocomplete="off" autofocus required /><p class="form-error" role="alert"></p><button class="primary-button" type="submit">保存</button></form>`,
  656. );
  657. }
  658. function confirmation(title, description, action, identifier) {
  659. sheet(
  660. title,
  661. `<p class="sheet-description">${description}</p><div class="button-row"><button class="secondary-button" data-action="close">取消</button><button class="secondary-button danger" data-action="${action}" data-id="${identifier || ''}">确认${title.replace('?', '')}</button></div>`,
  662. );
  663. }
  664. function conversationMenu(identifier) {
  665. const conversation = getConversation(identifier);
  666. sheet(
  667. '管理这段对话',
  668. `<p class="sheet-description">${esc(conversation.title)}</p><button class="sheet-list-button" data-action="rename-conversation" data-id="${identifier}">${icon('edit')}重命名</button><button class="sheet-list-button" data-action="move-conversation" data-id="${identifier}">${icon('folder')}移动到工作区</button><button class="sheet-list-button" data-action="archive-conversation" data-id="${identifier}">${icon('archive')}${conversation.archived ? '取消归档' : '归档对话'}</button><button class="sheet-list-button danger" data-action="delete-conversation" data-id="${identifier}">${icon('trash')}删除对话</button>`,
  669. );
  670. }
  671. function drawerConversation(conversation) {
  672. const status = collaboration.get(conversation.id)?.kind || 'idle';
  673. const workspace =
  674. workspaces.find((item) => item.id === conversation.workspace)?.name || '日常对话';
  675. return `<button class="drawer-conversation ${state.page === 'chat' && state.currentId === conversation.id ? 'active' : ''}" data-action="open-chat" data-id="${conversation.id}"><span class="drawer-conversation-title">${esc(conversation.title)}<span class="mini-state ${status}" aria-label="${activityNames[status]}">${status === 'done' ? icon('check') : status === 'attention' ? '!' : ''}</span></span><small>${state.drawerView === 'agents' ? '' : esc(getAgent(conversation.agentId).name) + ' · '}${esc(workspace)}</small></button>`;
  676. }
  677. function activityResults() {
  678. const rows = activeConversations().filter((conversation) => {
  679. const status = collaboration.get(conversation.id)?.kind;
  680. return (
  681. status &&
  682. status !== 'idle' &&
  683. (state.activityFilter === 'all' || status === state.activityFilter) &&
  684. `${conversation.title} ${getAgent(conversation.agentId).name}`.includes(state.activityKeyword)
  685. );
  686. });
  687. return (
  688. ['running', 'attention', 'done']
  689. .map((kind) => {
  690. const group = rows.filter(
  691. (conversation) => collaboration.get(conversation.id)?.kind === kind,
  692. );
  693. if (!group.length) return '';
  694. return `<div class="activity-group-label"><span class="inline-activity ${kind}">${activityNames[kind]}</span><span>${group.length}</span></div>${group
  695. .map((conversation) => {
  696. const activity = collaboration.get(conversation.id);
  697. const agent = getAgent(conversation.agentId);
  698. const workspace =
  699. workspaces.find((item) => item.id === conversation.workspace)?.name || '日常对话';
  700. return `<button class="activity-card ${kind} ${conversation.id === state.currentId ? 'current' : ''}" data-action="activity-open" data-id="${conversation.id}"><span class="activity-card-avatar">${avatar(agent)}<span class="mini-state ${kind}">${kind === 'done' ? icon('check') : kind === 'attention' ? '!' : ''}</span></span><span class="activity-card-content"><strong>${esc(conversation.title)}</strong><small>${esc(agent.name)} · ${esc(workspace)}</small><span class="activity-detail">${esc(activity.label)}</span></span><span class="activity-card-end">${conversation.id === state.currentId ? '<em>当前</em>' : icon('right')}<small>${activity.elapsed}</small></span></button>`;
  701. })
  702. .join('')}`;
  703. })
  704. .join('') || emptyState('这里暂时没有协作动态', '切换筛选,看看其他会话。', 'check')
  705. );
  706. }
  707. function openActivity() {
  708. const count = (kind) =>
  709. activeConversations().filter(
  710. (conversation) => collaboration.get(conversation.id)?.kind === kind,
  711. ).length;
  712. sheet(
  713. '切换协作',
  714. `<p class="sheet-description">不用退出对话,也能知道每件事的进展。</p>${searchField('搜索正在协作的事', 'activity-search', state.activityKeyword)}${tabs(
  715. [
  716. ['all', '全部'],
  717. ['running', '进行中 ' + count('running')],
  718. ['attention', '待关注 ' + count('attention')],
  719. ['done', '已完成 ' + count('done')],
  720. ],
  721. state.activityFilter,
  722. 'activity-filter',
  723. )}<div id="activity-results">${activityResults()}</div><div class="activity-sheet-footer"><span>会话状态演示 · 不等于数字生命在线状态</span><button data-action="complete-demo">模拟完成提醒</button></div>`,
  724. );
  725. overlay.querySelector('.sheet').classList.add('activity-sheet');
  726. }
  727. function quickCurrent() {
  728. if (state.generating) {
  729. toast('演示回复完成后即可新建');
  730. return;
  731. }
  732. const previous = getConversation();
  733. saveDraft();
  734. const identifier = `c${Date.now()}`;
  735. conversations.unshift({
  736. id: identifier,
  737. title: '新对话',
  738. agentId: previous.agentId,
  739. preview: '等待你的第一个想法',
  740. time: '刚刚',
  741. group: '今天',
  742. workspace: previous.workspace,
  743. unread: 0,
  744. archived: false,
  745. });
  746. collaboration.set(identifier, { kind: 'idle', label: '等待新的想法', elapsed: '空闲' });
  747. messages.set(identifier, []);
  748. navigate('chat', identifier);
  749. toast('已在 ' + getAgent(previous.agentId).name + ' 中新建,原对话草稿已保留');
  750. }
  751. function editCurrentTitle() {
  752. const conversation = getConversation();
  753. formSheet(
  754. '给这段对话起个名字',
  755. '会话标题',
  756. conversation.title,
  757. 'rename-conversation',
  758. conversation.id,
  759. );
  760. const form = overlay.querySelector('form');
  761. form.insertAdjacentHTML(
  762. 'beforeend',
  763. `<button class="regenerate-title" type="button" data-action="regenerate-title">${icon('spark')}生成一个候选标题<span>演示</span></button><p class="title-protection">${icon('shield')}只有点保存才会更新。手动标题不会被自动覆盖。</p>`,
  764. );
  765. }
  766. function previewListState(mode) {
  767. saveDraft();
  768. state.page = 'messages';
  769. state.keyword = '';
  770. history.pushState(null, '', '#/messages');
  771. closeOverlay();
  772. render();
  773. const results = document.querySelector('#conversation-results');
  774. if (mode === 'loading') {
  775. results.innerHTML = `<div class="skeleton-list" role="status" aria-label="正在加载会话" aria-busy="true">${Array.from({ length: 5 }, () => '<div class="skeleton-row"><span></span><div><i></i><i></i></div></div>').join('')}</div>`;
  776. setTimeout(() => {
  777. if (results.isConnected) results.innerHTML = conversationResults();
  778. }, 1800);
  779. } else if (mode === 'error') {
  780. results.innerHTML =
  781. emptyState('暂时没连上,不是消息丢了', '网络恢复后可以重试,草稿仍然保留。', 'wifi') +
  782. '<button class="primary-button" data-action="retry-list">重新加载</button>';
  783. } else
  784. results.innerHTML =
  785. emptyState('还没有对话,从一个想法开始', '选择熟悉的数字生命,开始你的第一次协作。', 'chat') +
  786. '<button class="primary-button" data-action="new-chat">开始新对话</button>';
  787. }
  788. function completeDemo() {
  789. const conversation = getConversation('c4');
  790. if (!conversation) {
  791. toast('这条演示会话已删除,刷新可恢复');
  792. return;
  793. }
  794. const activity = collaboration.get(conversation.id);
  795. if (activity?.kind === 'done') {
  796. toast('该协作已完成,可在「已完成」中查看');
  797. return;
  798. }
  799. collaboration.set(conversation.id, {
  800. kind: 'done',
  801. label: '接口检查已完成,结果已整理',
  802. elapsed: '刚刚完成',
  803. });
  804. conversation.unread = 1;
  805. closeOverlay();
  806. render();
  807. document.querySelector('#completion-banner')?.remove();
  808. document
  809. .querySelector('#device')
  810. .insertAdjacentHTML(
  811. 'beforeend',
  812. `<div class="completion-banner" id="completion-banner" role="status"><span class="completion-mark">${icon('check')}</span><button data-action="completion-open" data-id="${conversation.id}"><strong>阿澈的接口检查完成了</strong><small>结果已整理好,点这里接着看 · 演示</small></button><button data-action="dismiss-completion" aria-label="关闭完成提醒">${icon('close')}</button></div>`,
  813. );
  814. }
  815. function send() {
  816. if (state.generating || (!state.draft.trim() && !state.attachments.length)) return;
  817. if (state.disconnected && state.page === 'chat') {
  818. toast('连接已断开,请先重连;草稿已保留');
  819. return;
  820. }
  821. if (state.page === 'home' && !state.agentId) {
  822. pickAgent(true);
  823. return;
  824. }
  825. if (state.page === 'home') {
  826. drafts.delete('home');
  827. const identifier = `c${Date.now()}`;
  828. conversations.unshift({
  829. id: identifier,
  830. title: state.draft.trim().slice(0, 18) || '附件对话',
  831. agentId: state.agentId,
  832. preview: '正在整理你的想法…',
  833. time: '刚刚',
  834. group: '今天',
  835. workspace: state.newWorkspace,
  836. unread: 0,
  837. archived: false,
  838. });
  839. messages.set(identifier, []);
  840. state.currentId = identifier;
  841. state.newWorkspace = null;
  842. state.page = 'chat';
  843. history.pushState(null, '', `#/chat/${identifier}`);
  844. }
  845. const conversation = getConversation(),
  846. rows = messages.get(conversation.id) || sampleMessages(conversation),
  847. question = state.draft.trim(),
  848. files = state.attachments.map((file) => file.name);
  849. rows.push({ role: 'user', text: question || '请查看我添加的附件', files });
  850. if (conversation.title === '新对话' && !conversation.manuallyNamed)
  851. conversation.title = (question || '附件对话').slice(0, 18);
  852. collaboration.set(conversation.id, {
  853. kind: 'running',
  854. label: '正在处理你的消息',
  855. elapsed: '刚刚开始',
  856. });
  857. messages.set(conversation.id, rows);
  858. state.draft = '';
  859. state.attachments = [];
  860. drafts.delete(conversation.id);
  861. state.generating = true;
  862. state.generatingId = conversation.id;
  863. render();
  864. main.scrollTop = main.scrollHeight;
  865. clearTimeout(generationTimer);
  866. generationTimer = setTimeout(() => {
  867. rows.push({
  868. role: 'assistant',
  869. html: `<p>收到,我们就从「<strong>${esc(question || '这份附件')}</strong>」开始。</p><p>我会先把目标、已有信息和下一步梳理清楚,再一起把它变成可执行的行动。</p><blockquote>这是一条本地模拟回复,仅用于体验发送、等待和阅读的完整流程${files.length ? ';附件只展示文件名,未读取或上传' : ''}。</blockquote>`,
  870. });
  871. conversation.preview = '已整理好思路,可以继续讨论。';
  872. collaboration.set(conversation.id, {
  873. kind: 'done',
  874. label: '演示回复已完成',
  875. elapsed: '刚刚完成',
  876. });
  877. state.generating = false;
  878. if (state.page === 'chat' && state.currentId === conversation.id) {
  879. render();
  880. main.scrollTop = main.scrollHeight;
  881. } else if (['home', 'messages'].includes(state.page)) render();
  882. }, 1100);
  883. }
  884. function toast(message) {
  885. const element = document.querySelector('#toast');
  886. element.textContent = message;
  887. element.classList.add('visible');
  888. clearTimeout(toastTimer);
  889. toastTimer = setTimeout(() => element.classList.remove('visible'), 2700);
  890. }
  891. async function copyText(text) {
  892. try {
  893. await navigator.clipboard.writeText(text);
  894. toast('已复制');
  895. } catch {
  896. toast('浏览器未开放剪贴板权限,请手动选择内容复制');
  897. }
  898. }
  899. function downloadDemo() {
  900. const content =
  901. '产品初体验优化建议(演示文稿)\n\n01 让入口更清楚\n保留现有导航与功能,突出主操作。\n\n02 让阅读更轻松\n减少厚重卡片,扩大段落留白。\n\n03 让操作有回应\n清晰呈现加载、断线与错误状态。\n\n本文件为独立 HTML 原型的演示文稿,并非真实云盘文件。',
  902. url = URL.createObjectURL(new Blob([content], { type: 'text/plain;charset=utf-8' })),
  903. link = document.createElement('a');
  904. link.href = url;
  905. link.download = '产品初体验优化建议-演示.txt';
  906. link.click();
  907. setTimeout(() => URL.revokeObjectURL(url), 1000);
  908. toast('演示文稿已下载,不是实际 DOCX 文件');
  909. }
  910. function showArchived() {
  911. sheet(
  912. '已归档对话',
  913. conversations
  914. .filter((conversation) => conversation.archived)
  915. .map(conversationRow)
  916. .join('') || emptyState('没有归档对话', '归档的对话会保留在这里。', 'archive'),
  917. );
  918. }
  919. function newChat(workspace = null, agentId = null) {
  920. if (state.generating) {
  921. toast('演示回复完成后即可新建对话');
  922. return;
  923. }
  924. state.agentId = agentId;
  925. state.newWorkspace = workspace;
  926. navigate('home');
  927. }
  928. const actions = {
  929. 'preview-states': () =>
  930. sheet(
  931. '加载与反馈状态',
  932. '<p class="sheet-description">仅切换演示视图,不改变真实数据或权限。</p><button class="sheet-list-button" data-action="list-state" data-value="loading">' +
  933. icon('more') +
  934. '加载骨架屏</button><button class="sheet-list-button" data-action="list-state" data-value="empty">' +
  935. icon('chat') +
  936. '首次使用空态</button><button class="sheet-list-button" data-action="list-state" data-value="error">' +
  937. icon('wifi') +
  938. '断网与重试</button>',
  939. ),
  940. 'list-state': (button) => previewListState(button.dataset.value),
  941. 'retry-list': renderMessages,
  942. activity: openActivity,
  943. 'activity-filter': (button) => {
  944. state.activityFilter = button.dataset.value;
  945. openActivity();
  946. },
  947. 'activity-open': (button) => {
  948. closeOverlay();
  949. navigate('chat', button.dataset.id);
  950. requestAnimationFrame(() => {
  951. main.scrollTop = main.scrollHeight;
  952. });
  953. },
  954. 'drawer-view': (button) => {
  955. state.drawerView = button.dataset.value;
  956. openDrawer();
  957. },
  958. 'quick-current': quickCurrent,
  959. 'agent-new': (button) => {
  960. newChat(null, button.dataset.id);
  961. toast('已选中 ' + getAgent(button.dataset.id).name + ',不用再次选择');
  962. },
  963. 'edit-current-title': editCurrentTitle,
  964. 'regenerate-title': () => {
  965. const conversation = getConversation();
  966. const rows = messages.get(conversation.id) || [];
  967. const question = [...rows].reverse().find((message) => message.role === 'user')?.text;
  968. overlay.querySelector('#form-value').value =
  969. conversation.id === 'c1'
  970. ? '移动端第一印象与体验优化'
  971. : (question || conversation.title).slice(0, 22);
  972. toast('候选标题已填入,保存后才会更新;未调用 AI');
  973. },
  974. 'complete-demo': completeDemo,
  975. 'dismiss-completion': () => document.querySelector('#completion-banner')?.remove(),
  976. 'completion-open': (button) => {
  977. document.querySelector('#completion-banner')?.remove();
  978. navigate('chat', button.dataset.id);
  979. requestAnimationFrame(() => {
  980. main.scrollTop = main.scrollHeight;
  981. });
  982. },
  983. navigate: (button) => navigate(button.dataset.page),
  984. drawer: openDrawer,
  985. close: closeOverlay,
  986. 'new-chat': () => newChat(),
  987. 'open-chat': (button) => navigate('chat', button.dataset.id),
  988. 'pick-agent': () => pickAgent(false),
  989. 'choose-agent': (button) => {
  990. const pending = state.pendingSend;
  991. state.agentId = button.dataset.id;
  992. closeOverlay();
  993. renderComposer();
  994. if (pending) send();
  995. },
  996. 'agent-info': () => {
  997. const agent = getAgent(getConversation().agentId);
  998. sheet(
  999. '当前数字生命',
  1000. `<div class="profile-card">${avatar(agent)}<div><h2>${esc(agent.name)}</h2><p>${agent.role} · ${agent.online ? '在线' : '离线'}</p></div></div><p class="sheet-description">当前会话固定关联该数字生命。如需更换,请新建对话。</p>`,
  1001. );
  1002. },
  1003. prompt: (button) => {
  1004. state.draft = button.dataset.value;
  1005. renderComposer();
  1006. document.querySelector('#draft').focus();
  1007. },
  1008. send,
  1009. attach: () => {
  1010. if (state.generating) return;
  1011. document.querySelector('#file-input').click();
  1012. },
  1013. 'remove-attachment': (button) => {
  1014. state.attachments.splice(Number(button.dataset.index), 1);
  1015. renderComposer();
  1016. },
  1017. 'message-filter': (button) => {
  1018. state.filter = button.dataset.value;
  1019. renderMessages();
  1020. },
  1021. 'contact-filter': (button) => {
  1022. state.contactFilter = button.dataset.value;
  1023. state.keyword = '';
  1024. renderContacts();
  1025. },
  1026. 'agent-filter': (button) => {
  1027. state.agentFilter = button.dataset.value;
  1028. renderWorkbench();
  1029. },
  1030. 'toggle-workspace': (button) => {
  1031. state.expanded.has(button.dataset.id)
  1032. ? state.expanded.delete(button.dataset.id)
  1033. : state.expanded.add(button.dataset.id);
  1034. document.querySelector('#conversation-results').innerHTML = conversationResults();
  1035. },
  1036. 'drawer-workspace': (button) => {
  1037. state.drawerExpanded.has(button.dataset.id)
  1038. ? state.drawerExpanded.delete(button.dataset.id)
  1039. : state.drawerExpanded.add(button.dataset.id);
  1040. document.querySelector('#drawer-results').innerHTML = drawerHistory(
  1041. document.querySelector('[data-input="drawer-search"]').value,
  1042. );
  1043. },
  1044. 'workspace-chat': (button) => newChat(button.dataset.id),
  1045. 'create-workspace': () =>
  1046. formSheet('新建工作区', '工作区名称(最多 24 字)', '', 'create-workspace'),
  1047. 'workspace-menu': (button) => {
  1048. const workspace = workspaces.find((item) => item.id === button.dataset.id);
  1049. sheet(
  1050. esc(workspace.name),
  1051. `<button class="sheet-list-button" data-action="rename-workspace" data-id="${workspace.id}">${icon('edit')}重命名工作区</button><button class="sheet-list-button danger" data-action="delete-workspace" data-id="${workspace.id}">${icon('trash')}删除工作区</button>`,
  1052. );
  1053. },
  1054. 'rename-workspace': (button) =>
  1055. formSheet(
  1056. '重命名工作区',
  1057. '工作区名称(最多 24 字)',
  1058. workspaces.find((workspace) => workspace.id === button.dataset.id).name,
  1059. 'rename-workspace',
  1060. button.dataset.id,
  1061. ),
  1062. 'delete-workspace': (button) =>
  1063. confirmation(
  1064. '删除工作区?',
  1065. '其中的会话会移到「日常对话」,不会被删除。此操作只影响演示数据。',
  1066. 'confirm-delete-workspace',
  1067. button.dataset.id,
  1068. ),
  1069. 'confirm-delete-workspace': (button) => {
  1070. conversations.forEach((conversation) => {
  1071. if (conversation.workspace === button.dataset.id) conversation.workspace = null;
  1072. });
  1073. workspaces = workspaces.filter((workspace) => workspace.id !== button.dataset.id);
  1074. if (state.newWorkspace === button.dataset.id) state.newWorkspace = null;
  1075. closeOverlay();
  1076. render();
  1077. toast('工作区已删除,会话已移到日常对话');
  1078. },
  1079. 'conversation-menu': (button) => conversationMenu(button.dataset.id),
  1080. 'rename-conversation': (button) =>
  1081. formSheet(
  1082. '重命名对话',
  1083. '对话名称',
  1084. getConversation(button.dataset.id).title,
  1085. 'rename-conversation',
  1086. button.dataset.id,
  1087. ),
  1088. 'move-conversation': (button) =>
  1089. sheet(
  1090. '移动到工作区',
  1091. `<button class="sheet-list-button" data-action="choose-workspace" data-id="${button.dataset.id}" data-workspace="">${icon('chat')}日常对话</button>${workspaces.map((workspace) => `<button class="sheet-list-button" data-action="choose-workspace" data-id="${button.dataset.id}" data-workspace="${workspace.id}">${icon('folder')}${esc(workspace.name)}</button>`).join('')}`,
  1092. ),
  1093. 'choose-workspace': (button) => {
  1094. getConversation(button.dataset.id).workspace = button.dataset.workspace || null;
  1095. closeOverlay();
  1096. render();
  1097. toast('已移动,仅影响本地演示数据');
  1098. },
  1099. 'archive-conversation': (button) => {
  1100. const conversation = getConversation(button.dataset.id);
  1101. conversation.archived = !conversation.archived;
  1102. closeOverlay();
  1103. if (state.page === 'chat' && conversation.archived) navigate('messages');
  1104. else render();
  1105. toast(conversation.archived ? '已归档,可在侧栏中找回' : '已取消归档');
  1106. },
  1107. 'delete-conversation': (button) =>
  1108. confirmation(
  1109. '删除对话?',
  1110. '删除后这条演示对话将从当前预览中移除,刷新页面可恢复。',
  1111. 'confirm-delete-conversation',
  1112. button.dataset.id,
  1113. ),
  1114. 'confirm-delete-conversation': (button) => {
  1115. const index = conversations.findIndex((conversation) => conversation.id === button.dataset.id);
  1116. if (index >= 0) conversations.splice(index, 1);
  1117. messages.delete(button.dataset.id);
  1118. closeOverlay();
  1119. if (state.page === 'chat') navigate('messages');
  1120. else render();
  1121. toast('演示对话已删除');
  1122. },
  1123. 'show-archived': showArchived,
  1124. details: (button) => details(button?.dataset.tab || 'task'),
  1125. 'detail-tab': (button) => details(button.dataset.value),
  1126. 'preview-file': previewFile,
  1127. 'download-demo': downloadDemo,
  1128. 'copy-message': (button) => {
  1129. const message = messages.get(state.currentId)[Number(button.dataset.index)],
  1130. content = document.createElement('div');
  1131. content.innerHTML = message.html;
  1132. copyText(content.textContent);
  1133. },
  1134. disconnect: () => {
  1135. state.disconnected = true;
  1136. closeOverlay();
  1137. renderChat();
  1138. toast('已进入断线演示,草稿不会丢失');
  1139. },
  1140. reconnect: () => {
  1141. state.disconnected = false;
  1142. closeOverlay();
  1143. renderChat();
  1144. toast('演示连接已恢复');
  1145. },
  1146. 'open-agent': (button) => navigate('agent', button.dataset.id),
  1147. 'rename-agent': (button) =>
  1148. formSheet(
  1149. '重命名数字生命',
  1150. '显示名称',
  1151. getAgent(button.dataset.id).name,
  1152. 'rename-agent',
  1153. button.dataset.id,
  1154. ),
  1155. 'agent-chat': (button) => {
  1156. const conversation = activeConversations().find((item) => item.agentId === button.dataset.id);
  1157. conversation ? navigate('chat', conversation.id) : newChat(null, button.dataset.id);
  1158. },
  1159. channels: (button) =>
  1160. sheet(
  1161. '消息通道',
  1162. `<p class="sheet-description">${esc(getAgent(button.dataset.id).name)} · 演示连接信息</p><div class="sheet-item"><span class="tag">${getAgent(button.dataset.id).online ? '已连接' : '离线'}</span><strong>Matrix</strong><p>沿用现有消息通道,不在原型中建立真实连接。</p></div>`,
  1163. ),
  1164. recharge: (button) =>
  1165. sheet(
  1166. '数字生命充值',
  1167. `<p class="sheet-description">${esc(getAgent(button.dataset.id).name)} · 当前演示余额 ¥${getAgent(button.dataset.id).balance}</p><div class="empty-state">${icon('shield')}<strong>这里只预览,不会产生支付</strong><p>正式迁移时继续使用现有充值页面与接口,金额、账单和支付流程均不改变。</p></div>`,
  1168. ),
  1169. coworker: (button) =>
  1170. sheet(
  1171. esc(button.dataset.name),
  1172. `<p class="sheet-description">同事的数字生命 · 演示</p>${agents
  1173. .slice(0, 2)
  1174. .map(
  1175. (agent) =>
  1176. `<button class="sheet-list-button" data-action="open-agent" data-id="${agent.id}">${avatar(agent)}<span>${esc(agent.name)}<small>${agent.role}</small></span>${icon('right')}</button>`,
  1177. )
  1178. .join('')}`,
  1179. ),
  1180. theme: () => {
  1181. state.dark = !state.dark;
  1182. const scroll = main.scrollTop;
  1183. renderMine();
  1184. applyPreferences();
  1185. main.scrollTop = scroll;
  1186. },
  1187. palette: (button) => {
  1188. state.palette = button.dataset.value;
  1189. const scroll = main.scrollTop;
  1190. renderMine();
  1191. applyPreferences();
  1192. main.scrollTop = scroll;
  1193. },
  1194. font: () =>
  1195. sheet(
  1196. '舒适地阅读',
  1197. `<p class="sheet-description">仅调整对话正文,沿用现有字号偏好功能。</p><div class="font-options">${[
  1198. [14, '标准'],
  1199. [16, '较大'],
  1200. [18, '大号'],
  1201. ]
  1202. .map(
  1203. ([value, label]) =>
  1204. `<button data-action="choose-font" data-value="${value}" class="${state.font === value ? 'active' : ''}">${label}</button>`,
  1205. )
  1206. .join(
  1207. '',
  1208. )}</div><div class="assistant-body" id="font-preview" style="font-size:${state.font}px;line-height:1.9;padding:14px 0">让每一个想法,都有舒展的空间。<br />好的阅读体验,从恰好的字号开始。</div>`,
  1209. ),
  1210. 'choose-font': (button) => {
  1211. state.font = Number(button.dataset.value);
  1212. applyPreferences();
  1213. renderMine();
  1214. actions.font();
  1215. },
  1216. token: () =>
  1217. sheet(
  1218. '访问 Token',
  1219. `<p class="sheet-description">演示占位,不读取或展示任何真实凭据。</p><div class="sheet-item"><strong>${state.tokenVisible ? 'DEMO-NOT-A-REAL-TOKEN' : '•••• •••• •••• ••••'}</strong></div><div class="button-row"><button class="secondary-button" data-action="toggle-token">${state.tokenVisible ? '隐藏' : '显示'}占位 Token</button><button class="secondary-button" data-action="copy-token" ${state.tokenVisible ? '' : 'disabled'}>复制占位内容</button></div>`,
  1220. ),
  1221. 'toggle-token': () => {
  1222. state.tokenVisible = !state.tokenVisible;
  1223. actions.token();
  1224. },
  1225. 'copy-token': () => copyText('DEMO-NOT-A-REAL-TOKEN'),
  1226. notifications: () =>
  1227. sheet(
  1228. '消息与任务通知',
  1229. `<p class="sheet-description">继续保留现有通知权限状态和系统设置入口。</p><div class="empty-state">${icon('bell')}<strong>原型不申请系统权限</strong><p>正式版本仍由现有通知服务检查权限,并引导到系统设置。</p></div>`,
  1230. ),
  1231. logout: () =>
  1232. confirmation('退出登录?', '此处仅演示二次确认,不会退出真实项目账号。', 'confirm-logout'),
  1233. 'confirm-logout': () => {
  1234. closeOverlay();
  1235. navigate('home');
  1236. toast('退出交互演示完成;未操作真实账号');
  1237. },
  1238. };
  1239. document.addEventListener('click', (event) => {
  1240. const experience = event.target.closest('[data-experience]');
  1241. if (experience) {
  1242. const type = experience.dataset.experience;
  1243. closeOverlay();
  1244. if (state.page !== 'chat') {
  1245. saveDraft();
  1246. state.page = 'chat';
  1247. state.currentId = 'c1';
  1248. restoreDraft();
  1249. history.pushState(null, '', '#/chat/c1');
  1250. render();
  1251. }
  1252. if (type === 'activity') openActivity();
  1253. if (type === 'title') editCurrentTitle();
  1254. if (type === 'complete') completeDemo();
  1255. return;
  1256. }
  1257. const scene = event.target.closest('[data-scene]');
  1258. if (scene) {
  1259. navigate(scene.dataset.scene, scene.dataset.scene === 'chat' ? 'c1' : undefined);
  1260. return;
  1261. }
  1262. const button = event.target.closest('[data-action]');
  1263. if (button && !button.disabled) actions[button.dataset.action]?.(button);
  1264. });
  1265. document.addEventListener('input', (event) => {
  1266. const element = event.target;
  1267. if (element.id === 'draft') {
  1268. state.draft = element.value;
  1269. element.style.height = 'auto';
  1270. element.style.height = `${Math.min(element.scrollHeight, 116)}px`;
  1271. document.querySelector('.send-button').disabled =
  1272. state.generating || (!state.draft.trim() && !state.attachments.length);
  1273. return;
  1274. }
  1275. const kind = element.dataset.input;
  1276. if (!kind) return;
  1277. if (kind === 'activity-search') {
  1278. state.activityKeyword = element.value;
  1279. document.querySelector('#activity-results').innerHTML = activityResults();
  1280. return;
  1281. }
  1282. if (kind === 'drawer-search') {
  1283. document.querySelector('#drawer-results').innerHTML = drawerHistory(element.value);
  1284. return;
  1285. }
  1286. state.keyword = element.value;
  1287. if (kind === 'search')
  1288. document.querySelector('#conversation-results').innerHTML = conversationResults();
  1289. if (kind === 'contact-search')
  1290. document.querySelector('#contact-results').innerHTML = contactResults();
  1291. if (kind === 'agent-search') document.querySelector('#agent-results').innerHTML = agentResults();
  1292. });
  1293. document.addEventListener('keydown', (event) => {
  1294. if (event.key === 'Escape' && overlay.childElementCount) {
  1295. event.preventDefault();
  1296. closeOverlay();
  1297. return;
  1298. }
  1299. if (event.key === 'Tab' && overlay.childElementCount) {
  1300. const focusable = [
  1301. ...overlay.querySelectorAll('button:not(:disabled),input,select,a[href],summary'),
  1302. ].filter((element) => element.getClientRects().length),
  1303. first = focusable[0],
  1304. last = focusable.at(-1);
  1305. if (event.shiftKey && document.activeElement === first) {
  1306. event.preventDefault();
  1307. last?.focus();
  1308. } else if (!event.shiftKey && document.activeElement === last) {
  1309. event.preventDefault();
  1310. first?.focus();
  1311. }
  1312. }
  1313. });
  1314. let sheetDrag = null;
  1315. overlay.addEventListener('pointerdown', (event) => {
  1316. const handle = event.target.closest('.sheet-handle');
  1317. if (!handle) return;
  1318. sheetDrag = { start: event.clientY, distance: 0, element: handle.closest('.sheet'), handle };
  1319. handle.setPointerCapture(event.pointerId);
  1320. sheetDrag.element.style.transition = 'none';
  1321. sheetDrag.element.style.animation = 'none';
  1322. });
  1323. overlay.addEventListener('pointermove', (event) => {
  1324. if (!sheetDrag) return;
  1325. sheetDrag.distance = Math.max(0, event.clientY - sheetDrag.start);
  1326. sheetDrag.element.style.transform = `translateY(${sheetDrag.distance}px)`;
  1327. });
  1328. overlay.addEventListener('pointerup', () => {
  1329. if (!sheetDrag) return;
  1330. if (sheetDrag.distance > 85) closeOverlay();
  1331. else {
  1332. sheetDrag.element.style.transition = 'transform .2s ease';
  1333. sheetDrag.element.style.transform = '';
  1334. }
  1335. sheetDrag = null;
  1336. });
  1337. overlay.addEventListener('pointercancel', () => {
  1338. if (sheetDrag) sheetDrag.element.style.transform = '';
  1339. sheetDrag = null;
  1340. });
  1341. document.addEventListener('submit', (event) => {
  1342. const form = event.target.closest('[data-form]');
  1343. if (!form) return;
  1344. event.preventDefault();
  1345. const value = new FormData(form).get('value').trim(),
  1346. kind = form.dataset.form,
  1347. identifier = form.dataset.id,
  1348. error = form.querySelector('.form-error');
  1349. if (!value) {
  1350. error.textContent = '名称不能为空';
  1351. return;
  1352. }
  1353. if (kind.includes('workspace')) {
  1354. if (value.length > 24) {
  1355. error.textContent = '工作区名称最多 24 字';
  1356. return;
  1357. }
  1358. if (workspaces.some((workspace) => workspace.name === value && workspace.id !== identifier)) {
  1359. error.textContent = '已有同名工作区,请换一个名称';
  1360. return;
  1361. }
  1362. }
  1363. if (kind === 'create-workspace') workspaces.push({ id: `w${Date.now()}`, name: value });
  1364. if (kind === 'rename-workspace')
  1365. workspaces.find((workspace) => workspace.id === identifier).name = value;
  1366. if (kind === 'rename-conversation') {
  1367. getConversation(identifier).title = value;
  1368. getConversation(identifier).manuallyNamed = true;
  1369. }
  1370. if (kind === 'rename-agent') getAgent(identifier).name = value;
  1371. closeOverlay();
  1372. render();
  1373. toast('已保存,仅影响本地演示数据');
  1374. });
  1375. document.querySelector('#file-input').addEventListener('change', (event) => {
  1376. state.attachments.push(...Array.from(event.target.files));
  1377. event.target.value = '';
  1378. renderComposer();
  1379. toast('附件仅暂存在本页,不会读取或上传');
  1380. });
  1381. window.addEventListener('hashchange', readRoute);
  1382. function syncVisualViewport() {
  1383. if (window.innerWidth <= 520 && window.visualViewport?.scale === 1) {
  1384. document
  1385. .querySelector('#device')
  1386. .style.setProperty('--visual-height', `${window.visualViewport.height}px`);
  1387. } else document.querySelector('#device').style.removeProperty('--visual-height');
  1388. }
  1389. window.visualViewport?.addEventListener('resize', syncVisualViewport);
  1390. window.addEventListener('resize', syncVisualViewport);
  1391. syncVisualViewport();
  1392. document
  1393. .querySelectorAll('[data-icon]')
  1394. .forEach((element) => (element.innerHTML = icon(element.dataset.icon)));
  1395. readRoute();