mindferry 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -2
  3. package/README.zh-CN.md +165 -0
  4. package/bin/mindferry.mjs +301 -0
  5. package/examples/demo-en/chatgpt-conversations.json +72 -0
  6. package/examples/demo-en/chatgpt-copied.txt +8 -0
  7. package/examples/demo-en/claude-conversations.json +25 -0
  8. package/examples/demo-en/claude-memories.json +6 -0
  9. package/examples/demo-en/deepseek-conversations.json +39 -0
  10. package/examples/demo-en/gemini-MyActivity.json +18 -0
  11. package/examples/demo-en/grok-export.json +27 -0
  12. package/examples/exports/README.md +4 -0
  13. package/examples/exports/chatgpt-conversations.json +21 -0
  14. package/examples/exports/claude-conversations.json +13 -0
  15. package/examples/exports/claude-memories.json +3 -0
  16. package/examples/exports/deepseek-conversations.json +12 -0
  17. package/examples/exports/gemini-MyActivity.json +5 -0
  18. package/examples/exports/grok-export.json +11 -0
  19. package/examples/exports/open-webui-export.json +13 -0
  20. package/examples/scheduler/crontab.txt +2 -0
  21. package/examples/scheduler/io.github.mindferry.sync.plist +18 -0
  22. package/examples/single-chats/chatgpt-copied.txt +8 -0
  23. package/examples/single-chats/chatgpt-saved-page.html +4 -0
  24. package/examples/single-chats/claude-chat.md +7 -0
  25. package/package.json +55 -4
  26. package/src/connect.mjs +204 -0
  27. package/src/core/archive.mjs +144 -0
  28. package/src/core/card.mjs +64 -0
  29. package/src/core/classify.mjs +81 -0
  30. package/src/core/clients.mjs +63 -0
  31. package/src/core/errors.mjs +146 -0
  32. package/src/core/export.mjs +53 -0
  33. package/src/core/extract.mjs +183 -0
  34. package/src/core/generator.mjs +98 -0
  35. package/src/core/hub.mjs +637 -0
  36. package/src/core/llm.mjs +77 -0
  37. package/src/core/merge.mjs +95 -0
  38. package/src/core/profile.mjs +175 -0
  39. package/src/core/rules.mjs +88 -0
  40. package/src/core/store.mjs +109 -0
  41. package/src/core/text.mjs +82 -0
  42. package/src/demo.mjs +30 -0
  43. package/src/importers/index.mjs +366 -0
  44. package/src/importers/zip.mjs +48 -0
  45. package/src/mcp/server.mjs +272 -0
  46. package/src/remote.mjs +180 -0
  47. package/src/ui/server.mjs +281 -0
  48. package/src/ui/static/app.js +1037 -0
  49. package/src/ui/static/index.html +269 -0
  50. package/src/ui/static/logo.svg +16 -0
  51. package/src/ui/static/mascot-busy.svg +35 -0
  52. package/src/ui/static/mascot-happy.svg +27 -0
  53. package/src/ui/static/mascot-idle.svg +26 -0
  54. package/src/ui/static/mascot-oops.svg +26 -0
  55. package/src/ui/static/style.css +382 -0
  56. package/src/version.mjs +1 -0
  57. package/src/watch.mjs +80 -0
@@ -0,0 +1,1037 @@
1
+ // MindFerry UI. All user/imported text is inserted with textContent (never innerHTML).
2
+ const TOKEN = document.querySelector('meta[name=mindferry-token]').content;
3
+
4
+ const I18N = {
5
+ zh: {
6
+ brandSub: 'AI 记忆中介', tabHome: '首页', tabMemory: '记忆', tabRules: '分享规则', tabConnect: '接入', tabSettings: '设置',
7
+ sampleBanner: '现在看到的是示例人物「林小雨」的数据。拖入你自己的聊天记录时会自动清除。', clearSamples: '清除示例,开始用我自己的',
8
+ demoBanner: '演示模式:这里是虚构人物「林小雨」的数据,关掉后自动丢弃。',
9
+ welcomeTitle: '让你的每个 AI 都认识你', welcomeLead: '把和 ChatGPT、Claude、Gemini、Grok、DeepSeek、Kimi、豆包、通义等的聊天记录拖进来。MindFerry 在你自己的电脑上整理出「关于你」的信息,再按你的规则告诉其他 AI。',
10
+ step1: '拖入聊天记录或粘贴一段对话', step2: '自动整理、去重、标出敏感信息', step3: '一键复制给网页 AI;装在电脑上的 AI(如 Claude Code、Codex)自动读取',
11
+ heroTitle: '同步一次,各聊各的,过段时间再同步', syncNow: '立即同步', syncing: '同步中…',
12
+ autoSync: '自动同步', off: '关闭', every1h: '每小时', every6h: '每 6 小时', every1d: '每天', every7d: '每周',
13
+ lastSync: (t) => `上次同步:${t}`, never: '从未', neverSynced: '还没同步过',
14
+ syncDone: (r) => `同步完成:新增 ${r.added} 条,更新 ${r.updated} 条${r.conflicts ? `,${r.conflicts} 处前后说法不同(已用新的)` : ''}。`,
15
+ dropTitle: '把聊天记录拖到这里', dropSub: '官方导出的 .zip,或单个对话(.html .md .txt .json)· 只在本机处理 · 也可以点这里选文件',
16
+ pasteChat: '粘贴一段对话', tryDemo: '先用示例数据看看', howExport: '怎么导出聊天记录?',
17
+ importing: (n) => `正在读取 ${n}…`,
18
+ imported: (r) => Object.entries(r.imported).map(([c, v]) => `${clientName(c)}:读到 ${v.messages} 条消息,整理出 ${v.new} 条新信息`).join(';') + '。',
19
+ pickSource: '这段内容来自哪个 AI?',
20
+ conflictsTitle: '这些信息有了新说法(已用新的)', conflictLine: (o, n) => `「${o}」→「${n}」`, ack: '知道了',
21
+ viewsTitle: '各家 AI 眼中的你', viewsSub: '每个 AI 只知道你的一部分。同步之后,它们都会知道下面这些(按你的规则)。',
22
+ viewsPrivate: (n) => `🔒 另有 ${n} 条敏感信息,默认不分享`, viewsMore: (n) => `…还有 ${n} 条`,
23
+ yourAis: '你的 AI', moreAis: '添加更多 AI', kindMcp: '本地应用', kindWeb: '网页',
24
+ connected: '已接入 ✓', waiting: '已登记,等它第一次来取', waitingHint: (n) => `重启之后问它:「你知道我什么?」`, notConnected: '未接入', paused: '已暂停', factsFrom: (n) => `来自它 ${n} 条`,
25
+ lastIn: '收到', lastOut: '待发给它',
26
+ copyCard: '复制给它', viewCard: '它看到的内容', connectBtn: '一键接入', pause: '暂停分享', resume: '恢复分享', logBtn: '取用记录',
27
+ importOrPaste: '导入 / 粘贴',
28
+ presetLabel: { summary: '只给摘要', custom: '自定义', everything: '全部' },
29
+ privacyNote: (d) => `数据只存在这台电脑上,MindFerry 自己不联网(具体位置见「设置」页;只有你在「接入」页亲手打开「网页连接」时例外)。健康、财务、证件号、他人隐私、联系方式和拿不准的,默认不分享;证件号、银行卡号、密钥在保存前就已打码,任何设置都不会分享。`,
30
+ memFacts: '整理出的信息', memChats: '原始对话', search: '搜索…', stActive: '当前有效', stSuperseded: '已被新说法替代', stAll: '全部',
31
+ colText: '内容', colCategory: '类别', colSens: '敏感度', colFrom: '来源', noItems: '还没有信息。先回首页拖入聊天记录,或点「先用示例数据看看」。',
32
+ chatsHint: '搜索你导入过的全部对话(包括 AI 的回复)。只有你设为「全部」的 AI 才能搜到这里。', open: '打开', noChats: '没有找到。',
33
+ counts: (n) => `${n} 条`, lock: '永不分享', unlock: '恢复分享', del: '删除', confirmDel: '删除这条信息?',
34
+ replaced: (t) => `替代了:${t}`,
35
+ rulesIntro: '每个 AI 选一次就好,之后全自动。不确定就用「只给摘要」。',
36
+ pSummary: '只给摘要(推荐)', pSummaryD: '只分享安全的信息:职业、偏好、项目、城市等。',
37
+ pCustom: '自定义', pCustomD: '自己勾选可以分享的类别。',
38
+ pEverything: '全部', pEverythingD: '包括健康、财务等敏感信息,还能搜索你的原始对话。只给你最信任的 AI。',
39
+ confirmEverything: (n) => `确定把全部信息(包括敏感信息和原始对话)开放给 ${n} 吗?证件号和密钥仍然不会给。`,
40
+ ruleCats: '允许分享的类别', ruleMax: '最高敏感度', ruleUncertain: '也分享「拿不准」的', ruleOthers: '接收来自其他 AI 的信息', ruleArchive: '允许搜索原始对话',
41
+ ruleChars: '卡片字数上限', ruleLang: '卡片语言', langAuto: '自动', save: '保存', saved: '已保存', preview: '预览它会看到什么',
42
+ localTitle: '装在电脑上的 AI', connectIntro: '点「一键接入」,MindFerry 会把自己登记到这个应用里(会先备份原设置,随时可以断开)。接好后重启那个应用,它就能来看你允许它看的信息,也能把新学到的告诉 MindFerry。',
43
+ disconnect: '断开', reconnect: '重新接入', demoNoConnect: '现在是演示模式,不能接入(演示数据关掉就没了)。关掉演示后,直接运行 mindferry 再来接入。', manual: '手动配置(给懂技术的人)', syncHint: '同步只在你这台电脑里整理,不会发给任何人。导入新聊天记录时会顺手整理一次;想现在整理就点这个按钮。', bigText: '大字', normalText: '标准字号', closeMsg: '关闭',
44
+ restartHow: { 'claude-code': '重启方法:在 Claude Code 的窗口里输入 /exit 按回车退出,再输入 claude 按回车,开一个新对话。', codex: '重启方法:如果是 Codex 命令行窗口,在窗口里同时按 control 和 C(按两次)退出,再输入 codex 按回车;如果是 Codex 桌面应用,完全退出(Mac 按 command+Q)再重新打开。', 'gemini-cli': '重启方法:在 Gemini CLI 的窗口里输入 /quit 按回车退出,再输入 gemini 按回车。', 'claude-desktop': '重启方法:完全退出 Claude 桌面版(Mac 按 command+Q),再重新打开。', cursor: '重启方法:完全退出 Cursor(Mac 按 command+Q),再重新打开。', default: '重启方法:完全退出这个应用再重新打开。' }, connectedOk: (n) => `已登记到 ${n}。`, disconnectedOk: (n) => `已断开 ${n}。`,
45
+ lastSeen: (t) => `上次来取:${t}`,
46
+ webTitle: '网页 AI:怎么拿到聊天记录',
47
+ exportSteps: {
48
+ chatgpt: ['设置 → 数据管控 → 导出数据', '邮件里下载 zip', '整个 zip 拖进来'],
49
+ 'claude-web': ['设置 → 隐私 → 导出数据', '邮件里下载 zip', '整个 zip 拖进来'],
50
+ 'gemini-web': ['打开 takeout.google.com', '只勾选「我的活动」,并在其中只选「Gemini Apps」', '导出后把 zip 拖进来'],
51
+ 'grok-web': ['Grok 设置 → 数据 → 下载你的数据', '下载后把文件拖进来'],
52
+ deepseek: ['设置 → 数据管理 → 导出所有对话', '把下载的文件拖进来'],
53
+ kimi: ['打开一个对话,在文字上点右键 →「全选」→「复制」', '点首页「粘贴一段对话」'],
54
+ doubao: ['打开一个对话,全选并复制', '点首页「粘贴一段对话」'],
55
+ qwen: ['打开一个对话,全选并复制', '点首页「粘贴一段对话」'],
56
+ 'local-llm': ['Open WebUI:设置 → 数据库 → 导出全部聊天', '把 JSON 拖进来'],
57
+ },
58
+ exportNote: '各家界面可能会变,大致位置就在「设置」里的「数据 / 隐私」。单个对话也可以直接全选复制再粘贴。',
59
+ pasteTitle: '粘贴一段对话', pasteHelp: '在 AI 网页里打开那段对话,在对话文字上点鼠标右键 →「全选」,再右键 →「复制」,然后在下面的框里右键 →「粘贴」。(快捷键:Mac 按住 command 键再按 A、C、V;Windows 用 Ctrl。)', pastePh: '粘贴到这里…',
60
+ pasteFrom: '来自', autoDetect: '自动识别', pasteGo: '导入',
61
+ cardWhere: {
62
+ chatgpt: '粘贴到:ChatGPT → 设置 → 个性化 → 自定义指令(或新对话的第一句)', 'claude-web': '粘贴到:Claude → 设置 → 个人资料偏好(或某个 Project 的说明)',
63
+ 'gemini-web': '粘贴到:Gemini 网页 → 左上角「发起新对话」→ 在输入框里粘贴(Mac 按 command+V,Windows 按 Ctrl+V)→ 发送;也可以放进一个 Gem 的说明。整张卡全部粘贴,# 号不用删。', kimi: '粘贴到:Kimi 网页 → 左上角「新建会话」→ 在输入框里粘贴(Mac 按 command+V,Windows 按 Ctrl+V)→ 发送。整张卡全部粘贴,# 号不用删。', doubao: '粘贴到:豆包 → 左边「新对话」→ 在输入框里粘贴 → 发送。整张卡全部粘贴,# 号不用删。', qwen: '粘贴到:通义 → 「新建对话」→ 在输入框里粘贴 → 发送。整张卡全部粘贴,# 号不用删。', deepseek: '粘贴到:DeepSeek → 左上角「开启新对话」→ 在输入框里粘贴 → 发送。整张卡全部粘贴,# 号不用删。', 'grok-web': '粘贴到:Grok → 新对话 → 在输入框里粘贴 → 发送(也可以放进 设置 → 自定义)。整张卡全部粘贴。', default: '粘贴到:在它的网页上新建一个对话,把整张卡粘贴进输入框(Mac 按 command+V,Windows 按 Ctrl+V),发送。# 号不用删。',
64
+ },
65
+ close: '关闭', copy: '复制', copied: '已复制,去粘贴吧', cardHint: (n, t) => `它会看到 ${t} 条信息${n > t ? `(共 ${n} 条可分享,受字数上限)` : ''}。`,
66
+ logTitle: (n) => `${n} 的取用记录`, logEmpty: '还没有取用过。',
67
+ logAction: { pull: '读取了资料卡', 'card copied': '复制了资料卡', search: '搜索', read: '读取了对话', paused: '你暂停了分享', resumed: '你恢复了分享' },
68
+ logLine: (a, n) => `${a}${n ? `(${n} 条)` : ''}`,
69
+ setLang: '语言', setData: '数据', setDataDir: '数据文件夹:', archiveStats: (s) => `共 ${s.messages} 条对话消息,来自 ${s.conversations} 个对话。`,
70
+ setLog: '谁拿走了什么', setLogSub: '每个 AI 每次读取都会记在这里。', setWipe: '删除全部数据', setWipeSub: '删除 MindFerry 保存的所有信息、对话和记录。会先另存一份,7 天内还能找回;7 天后自动彻底删掉。',
71
+ setWipeBtn: '删除全部数据', confirmWipe: '确定删除 MindFerry 里的全部数据吗?7 天内还能在设置里找回。', wiped: '已全部删除。',
72
+ cat: { identity: '基本信息', work: '工作职业', skills: '技能', projects: '项目', goals: '目标', preferences: '偏好习惯', communication: '沟通方式', location: '所在地', contact: '联系方式', health: '健康', finance: '财务', ids: '证件号码', others: '他人信息', other: '其他' },
73
+ sens: { public: '公开', personal: '个人', sensitive: '敏感', secret: '机密', uncertain: '拿不准' },
74
+ },
75
+ en: {
76
+ brandSub: 'cross-AI memory', tabHome: 'Home', tabMemory: 'Memory', tabRules: 'Sharing', tabConnect: 'Connect', tabSettings: 'Settings',
77
+ sampleBanner: 'You are looking at a made-up sample person. It is cleared automatically when you import your own chats.', clearSamples: 'Clear samples and start',
78
+ demoBanner: 'Demo mode: this is a made-up person. It is thrown away when you close MindFerry.',
79
+ welcomeTitle: 'Let every AI you use know you', welcomeLead: 'Drop in your chats with ChatGPT, Claude, Gemini, Grok, DeepSeek and others. MindFerry works out what they know about you — on your own computer — and tells your other AIs, following your rules.',
80
+ step1: 'Drop in a chat export or paste one chat', step2: 'Sorted, de-duplicated, sensitive bits flagged', step3: 'Copy to web AIs; AI apps on your computer (Claude Code, Codex…) read it automatically',
81
+ heroTitle: 'Sync once. Chat separately. Sync again later.', syncNow: 'Sync now', syncing: 'Syncing…',
82
+ autoSync: 'Auto-sync', off: 'Off', every1h: 'Hourly', every6h: 'Every 6 h', every1d: 'Daily', every7d: 'Weekly',
83
+ lastSync: (t) => `Last sync: ${t}`, never: 'never', neverSynced: 'Not synced yet',
84
+ syncDone: (r) => `Synced: ${r.added} new, ${r.updated} updated${r.conflicts ? `; ${r.conflicts} changed fact(s) — the newer one wins` : ''}.`,
85
+ dropTitle: 'Drop your chats here', dropSub: 'An official export .zip, or a single chat (.html .md .txt .json) · processed on this computer · or click to choose',
86
+ pasteChat: 'Paste a conversation', tryDemo: 'Try it with sample data', howExport: 'How do I export my chats?',
87
+ importing: (n) => `Reading ${n}…`,
88
+ imported: (r) => Object.entries(r.imported).map(([c, v]) => `${clientName(c)}: read ${v.messages} message(s), found ${v.new} new fact(s)`).join('; ') + '.',
89
+ pickSource: 'Which AI is this from?',
90
+ conflictsTitle: 'Some facts changed (the newer one is used)', conflictLine: (o, n) => `"${o}" → "${n}"`, ack: 'Got it',
91
+ viewsTitle: 'How each AI sees you', viewsSub: 'Each AI only knows part of you. After a sync, they all know what follows (as your rules allow).',
92
+ viewsPrivate: (n) => `🔒 ${n} sensitive fact(s), not shared by default`, viewsMore: (n) => `…and ${n} more`,
93
+ yourAis: 'Your AIs', moreAis: 'Add more AIs', kindMcp: 'App', kindWeb: 'Web',
94
+ connected: 'Connected ✓', waiting: 'Registered — waiting for its first visit', waitingHint: (n) => `After restarting, ask it: "What do you know about me?"`, notConnected: 'Not connected', paused: 'Paused', factsFrom: (n) => `${n} fact(s) from it`,
95
+ lastIn: 'received', lastOut: 'to send',
96
+ copyCard: 'Copy for it', viewCard: 'What it sees', connectBtn: 'Connect', pause: 'Pause sharing', resume: 'Resume sharing', logBtn: 'Access log',
97
+ importOrPaste: 'Import / paste',
98
+ presetLabel: { summary: 'Summary', custom: 'Custom', everything: 'Everything' },
99
+ privacyNote: (d) => `Your data stays on this computer (the exact folder is on the Settings page); MindFerry doesn't go online by itself (the only exception is the web connection, if you turn it on in Connect). Health, finance, ID numbers, other people, contact details and anything uncertain are not shared by default; ID/card numbers and keys are masked before saving and are never shared.`,
100
+ memFacts: 'Facts', memChats: 'Conversations', search: 'Search…', stActive: 'Current', stSuperseded: 'Replaced by newer', stAll: 'All',
101
+ colText: 'Fact', colCategory: 'Category', colSens: 'Sensitivity', colFrom: 'From', noItems: 'Nothing yet. Drop in a chat export on Home, or try the sample data.',
102
+ chatsHint: 'Search everything you imported (AI replies included). Only AIs you set to "Everything" can search this.', open: 'Open', noChats: 'No results.',
103
+ counts: (n) => `${n} items`, lock: 'Never share', unlock: 'Share again', del: 'Delete', confirmDel: 'Delete this fact?',
104
+ replaced: (t) => `replaces: ${t}`,
105
+ rulesIntro: 'Choose once per AI; everything else is automatic. If unsure, keep "Summary".',
106
+ pSummary: 'Summary (recommended)', pSummaryD: 'Safe facts only: work, preferences, projects, city…',
107
+ pCustom: 'Custom', pCustomD: 'Pick the categories yourself.',
108
+ pEverything: 'Everything', pEverythingD: 'Includes health, money and other sensitive facts, and lets it search your past chats. Only for an AI you fully trust.',
109
+ confirmEverything: (n) => `Give ${n} everything, including sensitive facts and your past conversations? ID numbers and keys are still never shared.`,
110
+ ruleCats: 'Categories to share', ruleMax: 'Max sensitivity', ruleUncertain: 'Also share "uncertain" facts', ruleOthers: 'Accept facts from other AIs', ruleArchive: 'May search past conversations',
111
+ ruleChars: 'Card length limit', ruleLang: 'Card language', langAuto: 'Auto', save: 'Save', saved: 'Saved', preview: 'Preview what it sees',
112
+ localTitle: 'AI apps on your computer', connectIntro: 'Click "Connect" and MindFerry registers itself in that app (your previous settings are backed up; disconnect any time). Restart the app afterwards; it can then read what you allow it to see and tell MindFerry what it learns.',
113
+ disconnect: 'Disconnect', reconnect: 'Reconnect', demoNoConnect: 'This is demo mode, so connecting is off (the demo data disappears when it closes). Close the demo, run mindferry normally, then connect.', manual: 'Manual setup (for technical users)', syncHint: 'Syncing only tidies things up on this computer; nothing is sent anywhere. Importing new chats syncs by itself; click to sync right now.', bigText: 'Larger text', normalText: 'Normal text', closeMsg: 'Close',
114
+ restartHow: { 'claude-code': 'To restart: in the terminal running Claude Code type /exit, then run claude again for a new session.', codex: 'To restart: in the Codex terminal window press Ctrl+C twice, then type codex and press Enter. If you use the Codex desktop app, quit it completely (⌘Q on a Mac) and open it again.', 'gemini-cli': 'To restart: type /quit in Gemini CLI, then run gemini again.', 'claude-desktop': 'To restart: quit Claude Desktop completely (⌘Q on a Mac) and open it again.', cursor: 'To restart: quit Cursor completely (⌘Q on a Mac) and open it again.', default: 'To restart: quit the app completely and open it again.' }, connectedOk: (n) => `Registered in ${n}.`, disconnectedOk: (n) => `${n} disconnected.`,
115
+ lastSeen: (t) => `Last visit: ${t}`,
116
+ webTitle: 'Web AIs: how to get your chats',
117
+ exportSteps: {
118
+ chatgpt: ['Settings → Data controls → Export data', 'Download the zip from the email', 'Drop the whole zip in'],
119
+ 'claude-web': ['Settings → Privacy → Export data', 'Download the zip from the email', 'Drop the whole zip in'],
120
+ 'gemini-web': ['Open takeout.google.com', 'Select only "My Activity", and within it only "Gemini Apps"', 'Export, then drop the zip in'],
121
+ 'grok-web': ['Grok Settings → Data → Download your data', 'Drop the file in'],
122
+ deepseek: ['Settings → Data → Export all chats', 'Drop the file in'],
123
+ kimi: ['Open a chat, right-click the text → Select All → Copy', 'Click "Paste a conversation" on Home'],
124
+ doubao: ['Open a chat, select all and copy', 'Click "Paste a conversation" on Home'],
125
+ qwen: ['Open a chat, select all and copy', 'Click "Paste a conversation" on Home'],
126
+ 'local-llm': ['Open WebUI: Settings → Database → Export all chats', 'Drop the JSON in'],
127
+ },
128
+ exportNote: 'Menus change from time to time; look under Settings → Data / Privacy. For a single chat, select all, copy and paste.',
129
+ pasteTitle: 'Paste a conversation', pasteHelp: 'Open the conversation on the AI\'s website. Right-click the chat text → "Select All", right-click → "Copy", then right-click the box below → "Paste". (Shortcuts: ⌘A ⌘C ⌘V on a Mac, Ctrl+A Ctrl+C Ctrl+V on Windows.)', pastePh: 'Paste here…',
130
+ pasteFrom: 'From', autoDetect: 'Detect automatically', pasteGo: 'Import',
131
+ cardWhere: {
132
+ chatgpt: 'Paste into: ChatGPT → Settings → Personalization → Custom instructions (or the first message of a chat)', 'claude-web': 'Paste into: Claude → Settings → Profile preferences (or a Project\'s instructions)',
133
+ 'gemini-web': 'Paste into: the first message of a chat, or a Gem\'s instructions', default: 'Paste into: start a new chat on its website, paste the whole card into the message box (⌘V on a Mac, Ctrl+V on Windows) and send it. Keep the # signs — they are fine.',
134
+ },
135
+ close: 'Close', copy: 'Copy', copied: 'Copied — now paste it', cardHint: (n, t) => `It will see ${t} fact(s)${n > t ? ` (of ${n} shareable; length limit)` : ''}.`,
136
+ logTitle: (n) => `Access log: ${n}`, logEmpty: 'Nothing taken yet.',
137
+ logAction: { pull: 'read the profile card', 'card copied': 'card copied', search: 'searched', read: 'read a conversation', paused: 'you paused sharing', resumed: 'you resumed sharing' },
138
+ logLine: (a, n) => `${a}${n ? ` (${n})` : ''}`,
139
+ setLang: 'Language', setData: 'Data', setDataDir: 'Data folder:', archiveStats: (s) => `${s.messages} archived messages from ${s.conversations} conversations.`,
140
+ setLog: 'Who took what', setLogSub: 'Every read by every AI is recorded here.', setWipe: 'Delete everything', setWipeSub: 'Deletes all facts, conversations and logs MindFerry stored. A copy is kept for 7 days so you can bring it back; after that it is gone for good.',
141
+ setWipeBtn: 'Delete everything', confirmWipe: 'Delete all MindFerry data? You can bring it back from Settings within 7 days.', wiped: 'Everything was deleted.',
142
+ cat: { identity: 'About me', work: 'Work', skills: 'Skills', projects: 'Projects', goals: 'Goals', preferences: 'Preferences', communication: 'Communication', location: 'Location', contact: 'Contact', health: 'Health', finance: 'Finance', ids: 'ID numbers', others: 'Other people', other: 'Other' },
143
+ sens: { public: 'Public', personal: 'Personal', sensitive: 'Sensitive', secret: 'Secret', uncertain: 'Uncertain' },
144
+ },
145
+ };
146
+
147
+ // v0.2 strings (profile, generator, sync summary, safety)
148
+ Object.assign(I18N.zh, {
149
+ tabProfile: '关于我',
150
+ profTitle: '关于我', profSub: '任何 AI(哪怕是全新的)读了这一页,就知道你是什么样的人。只用你自己说过的话;健康、财务、证件、联系方式、他人信息不会进来。',
151
+ profEmpty: '还没有内容。先回首页拖入聊天记录。', profHide: '不放进档案', profHidden: (n) => `已从档案里拿掉 ${n} 条`, profShow: '放回档案',
152
+ profGive: '生成一份发给某个 AI', profCopyAll: '复制整页', profCopied: '已复制。粘贴到任何 AI 的第一句话里就行。',
153
+ genTitle: (n) => `发给 ${n} 的档案`, genNewAi: '其他 / 新的 AI', genFor: '发给', genPurpose: '用途',
154
+ purpose: { all: '全部', work: '工作', coding: '编程', study: '学习', life: '生活' },
155
+ genHint: '已经按用途帮你勾好了。想多给一点或少给一点,直接点勾选框。', genCount: (n, c, m) => `已选 ${n} 条 · ${c} 字${c > m ? '' : ''}`,
156
+ genCondensed: (m) => `内容较多,已自动精简到 ${m} 字以内(这个 AI 的建议长度)。`,
157
+ genCopy: '复制', genDownload: '存成文件', genNew: '新', genSelectAll: '全选', genSelectNone: '全不选',
158
+ reason: { health: '健康信息', finance: '财务信息', others: '涉及他人', contact: '联系方式', sensitive: '比较私密', uncertain: '拿不准', locked: '你锁定了', secret: '号码/密钥,永不分享' },
159
+ holdNote: '默认没勾,因为:',
160
+ doneTitle: '同步好啦', doneLine: (r) => `新增 ${r.added} 条${r.updated ? `,更新 ${r.updated} 条` : ''} · 可以给 ${r.ais} 个 AI(还没发出去)· ${r.kept} 条私密信息只留在本机`,
161
+ doneNothing: '没有新内容,一切都是最新的。', doneProfile: '看看「关于我」', doneUndo: '撤回这次同步', undone: (n) => `已撤回,移除了 ${n} 条。`, doneClose: '好的',
162
+ toTrash: (n) => `最近删除(${n} 条)→`,
163
+ trashTitle: '最近删除', trashEmpty: '没有删除过的信息。', restore: '恢复', restored: '已恢复。',
164
+ wipeKept: (d) => `已删除。${d} 天内可以在「设置」里找回;想彻底清除,点「永久清除」。`, recoverWiped: '找回删除的全部数据', purgeWiped: '永久清除', purged: '已永久清除。',
165
+ exportTitle: '导出全部数据', exportSub: '想换电脑、备份或者不用了,都可以把全部信息带走。', exportMd: '导出为 Markdown', exportJson: '导出为 JSON',
166
+ advTitle: '高级', advSub: '给喜欢折腾的人:命令行、配置片段、本地接口。不用这些也完全没问题。',
167
+ deletedUndo: '已删除。', undo: '撤销',
168
+ });
169
+ Object.assign(I18N.en, {
170
+ tabProfile: 'About me',
171
+ profTitle: 'About me', profSub: "Any AI, even a brand-new one, can read this page and know what kind of person you are. Built only from things you said. Health, money, ID numbers, contact details and other people never go in.",
172
+ profEmpty: 'Nothing yet. Go to Home and drop in some chats first.', profHide: 'Leave out', profHidden: (n) => `${n} left out of the profile`, profShow: 'Put back',
173
+ profGive: 'Make one for an AI', profCopyAll: 'Copy the page', profCopied: 'Copied. Paste it as the first message in any AI.',
174
+ genTitle: (n) => `Profile for ${n}`, genNewAi: 'Another / a new AI', genFor: 'For', genPurpose: 'Use it for',
175
+ purpose: { all: 'Everything', work: 'Work', coding: 'Coding', study: 'Study', life: 'Life' },
176
+ genHint: "Already ticked for this use. Tick or untick anything you like.", genCount: (n, c) => `${n} selected · ${c} characters`,
177
+ genCondensed: (m) => `Shortened to fit ${m} characters (the suggested length for this AI).`,
178
+ genCopy: 'Copy', genDownload: 'Save as a file', genNew: 'new', genSelectAll: 'All', genSelectNone: 'None',
179
+ reason: { health: 'health', finance: 'money', others: 'about someone else', contact: 'contact details', sensitive: 'private', uncertain: 'not sure', locked: 'you locked it', secret: 'a number or key: never shared' },
180
+ holdNote: 'Not ticked: ',
181
+ doneTitle: 'All synced', doneLine: (r) => `${r.added} new${r.updated ? `, ${r.updated} updated` : ''} · ready for ${r.ais} AI${r.ais === 1 ? '' : 's'} (nothing sent yet) · ${r.kept} private fact${r.kept === 1 ? '' : 's'} kept on this computer`,
182
+ doneNothing: 'Nothing new. Everything is up to date.', doneProfile: 'See "About me"', doneUndo: 'Undo this sync', undone: (n) => `Undone: ${n} fact${n === 1 ? '' : 's'} removed.`, doneClose: 'OK',
183
+ toTrash: (n) => `Recently deleted (${n}) →`,
184
+ trashTitle: 'Recently deleted', trashEmpty: 'Nothing deleted.', restore: 'Restore', restored: 'Restored.',
185
+ wipeKept: (d) => `Deleted. You can bring it back from Settings for ${d} days; to remove it for good, click "Delete for good".`, recoverWiped: 'Bring back the deleted data', purgeWiped: 'Delete for good', purged: 'Deleted for good.',
186
+ exportTitle: 'Export everything', exportSub: 'New computer, a backup, or leaving: take all your data with you.', exportMd: 'Export as Markdown', exportJson: 'Export as JSON',
187
+ advTitle: 'Advanced', advSub: 'For tinkerers: command line, config snippets, local API. You never need these.',
188
+ deletedUndo: 'Deleted.', undo: 'Undo',
189
+ });
190
+
191
+ let lang = localStorage.getItem('mindferry-lang') || (navigator.language?.toLowerCase().startsWith('zh') ? 'zh' : 'en');
192
+ // v0.2 extras: web connection, smarter tidy-up, Downloads watcher, advanced, next step.
193
+ Object.assign(I18N.zh, {
194
+ viewGive: (n) => `生成给 ${n} 的「关于我」`, viewSee: '看看它会读到什么',
195
+ deletedWhere: '已删除。想找回的话:点表格下面的「最近删除」。',
196
+ sampleNoConnect: '现在是示例数据:先在页面顶上点「清除示例,开始用我自己的」,再来接入。',
197
+ sampleRow: '示例中,暂不能接入',
198
+ changedWhere: (f, b) => `改动的位置:${f}${b ? `;原来的设置备份在:${b}` : ''}。点「断开」就能完全撤回。`,
199
+ genericErr: '出了点小问题,请再试一次;一直不行就刷新页面。', copyManual: '浏览器没让自动复制。文字已经帮你选好了,按 Ctrl+C(Mac 上是 ⌘+C)就复制好了。',
200
+ purgeOne: '彻底删除', purgeOneConfirm: '彻底删除这条?连聊天记录里的原话也会一起抹掉,找不回来。', purgedOne: '已彻底删除,聊天记录里的原话也抹掉了。',
201
+ webConnTitle: '网页 AI 自己来取(可选)',
202
+ webConnIntro: '支持「自定义连接器」的网页 AI(ChatGPT、Claude.ai、Grok 等)可以直接来 MindFerry 读你的档案,不用每次复制粘贴。默认关闭;打开后每个 AI 有自己的专属地址,默认只能读。',
203
+ wcOff: '现在是关着的。', wcOnLocal: '已打开,但只有这台电脑能访问(网页 AI 连不上)。', wcOnPublic: '已打开,网页 AI 可以用下面的地址连接。',
204
+ wcUntil: (x) => `会在 ${x} 自动关闭。`, wcForever: '会一直开着,直到你关闭 MindFerry。',
205
+ wcHours: '开多久', wcH1: '1 小时', wcH4: '4 小时', wcH24: '1 天', wcH0: '一直开着', wcStart: '打开', wcStop: '关闭',
206
+ wcNoTunnel: '要让网页 AI 连得上,需要先装一个免费的小工具 cloudflared(Cloudflare 官方,不用注册),装好后重新点「打开」。', wcGet: '去官方页面下载',
207
+ wcAddrNote: '每次重新打开,地址都会变;记得到 AI 的设置里更新。',
208
+ wcCopy: '复制地址', wcCopied: '地址已复制', wcWrite: '允许它保存新的信息', wcRotate: '换一个新地址', wcRotated: '旧地址已作废',
209
+ wcHow: (n) => `怎么在 ${n} 里添加`, wcMayChange: '(菜单名称可能已经变了)',
210
+ wcDemo: '演示模式下不能打开网页连接。',
211
+ wcSteps: {
212
+ chatgpt: ['设置 → 应用与连接器 → 高级 → 打开「开发者模式」', '点「创建」,名字填 MindFerry,粘贴上面的地址,认证选「无」', '新对话里打开 MindFerry,说一句「先读我的档案」'],
213
+ 'claude-web': ['设置 → 连接器 → 添加自定义连接器', '名字填 MindFerry,粘贴上面的地址', '在对话的工具菜单里打开它'],
214
+ default: ['在这个 AI 的设置里找「连接器」「MCP」或「应用」', '添加一个新的,粘贴上面的地址,不需要登录', '在对话里打开它,说一句「先读我的档案」'],
215
+ },
216
+ pasteBusy: '正在整理…',
217
+ smartTitle: '更聪明的整理(可选)',
218
+ smartSub: '默认只用内置规则,所有东西都不离开这台电脑。下面更聪明的方式都要你自己打开。',
219
+ smartLocal: (k, m) => `找到了这台电脑上的 ${k} 模型「${m}」。`, smartTidy: '用我电脑上的模型整理一遍', smartTidying: '正在整理,可能要几分钟……',
220
+ smartTidied: (r) => `整理完了:看了 ${r.messages} 条消息,找到 ${r.facts} 条新信息。`,
221
+ smartEmbedOnly: '找到了本地模型程序,但里面的模型只能做搜索、不能聊天,所以没法整理。装一个能聊天的模型后再来。',
222
+ smartNone: '如果你装了 Ollama 或 LM Studio,MindFerry 可以用它更好地读懂聊天记录,内容同样不离开这台电脑。',
223
+ smartOrgConfirm: (n) => `确定让 ${n} 来读你写过的原话吗?随时可以改回「不用」。`,
224
+ smartOrg: '让一个已连接的 AI 帮忙整理', smartOrgOff: '不用(推荐)',
225
+ smartOrgWarn: '注意:被选中的 AI 会读到你自己写过的原话(不只是档案)。它的分享规则不允许的句子(默认是健康、财务、证件、他人、联系方式,以及宗教、政治、性取向等话题)会先遮掉;MindFerry 判断不了的句子会照原样给它看——这正是要它帮忙整理的部分。遮挡靠关键词,可能有漏网的。每次读取都记在「谁拿走了什么」里。',
226
+ watchTitle: '自动导入下载的聊天记录', watchSub: '打开后,你从 AI 网站下载的聊天导出文件一到「下载」文件夹,就会自动导入并同步。',
227
+ advCli: '命令行(在终端里用)', advApi: '本地接口和适配器',
228
+ advApiSub: '网页连接用的是标准 MCP(HTTP)。想给新的 AI 写导入器,看适配器开发文档:',
229
+ nsProfile: '下一步:把「关于我」交给一个 AI,它马上就认识你。', nsProfileBtn: '去复制',
230
+ nsConnect: '下一步:连接一个电脑上的 AI 应用,它就能自己读你的档案。', nsConnectBtn: '去连接',
231
+ nsSync: '有一阵子没同步了,同步一下吧。', nsSyncBtn: '同步',
232
+ nsDone: '都好了。换到新的 AI 时,把「关于我」给它就行。',
233
+ });
234
+ Object.assign(I18N.en, {
235
+ viewGive: (n) => `Make an "About me" for ${n}`, viewSee: 'See what it will read',
236
+ deletedWhere: 'Deleted. To bring it back, click "Recently deleted" below the table.',
237
+ sampleNoConnect: 'You are looking at sample data: first click "Clear samples and start" at the top of the page, then connect.',
238
+ sampleRow: 'Not while showing samples',
239
+ changedWhere: (f, b) => `Changed: ${f}${b ? `; your previous settings were backed up to ${b}` : ''}. Click Disconnect to undo it completely.`,
240
+ genericErr: 'Something didn\u2019t work. Please try again; if it keeps happening, reload the page.', copyManual: 'Your browser blocked automatic copying. The text is selected for you: press Ctrl+C (⌘+C on a Mac).',
241
+ purgeOne: 'Delete for good', purgeOneConfirm: 'Delete this for good? Its words are also removed from your saved chats. This cannot be undone.', purgedOne: 'Deleted for good, including its words in your saved chats.',
242
+ webConnTitle: 'Let web AIs fetch it themselves (optional)',
243
+ webConnIntro: 'Web AIs that support custom connectors (ChatGPT, Claude.ai, Grok and others) can read your profile straight from MindFerry, with no copy-paste each time. Off by default. When on, each AI gets its own address and can only read.',
244
+ wcOff: 'It is off.', wcOnLocal: 'On, but only this computer can reach it (web AIs cannot yet).', wcOnPublic: 'On. Web AIs can connect with the addresses below.',
245
+ wcUntil: (x) => `It turns off by itself at ${x}.`, wcForever: 'It stays on until you close MindFerry.',
246
+ wcHours: 'For how long', wcH1: '1 hour', wcH4: '4 hours', wcH24: '1 day', wcH0: 'Until I close MindFerry', wcStart: 'Turn on', wcStop: 'Turn off',
247
+ wcNoTunnel: 'For web AIs to reach it, first install a small free tool, cloudflared (from Cloudflare, no account needed), then click Turn on again.', wcGet: 'Get it from the official page',
248
+ wcAddrNote: 'The address changes every time you turn it on again; update it in the AI’s settings.',
249
+ wcCopy: 'Copy address', wcCopied: 'Address copied', wcWrite: 'Allow it to save new facts', wcRotate: 'New address', wcRotated: 'The old address no longer works',
250
+ wcHow: (n) => `How to add it in ${n}`, wcMayChange: '(menu names may have changed)',
251
+ wcDemo: 'The web connection is not available in demo mode.',
252
+ wcSteps: {
253
+ chatgpt: ['Settings → Apps & Connectors → Advanced → turn on Developer mode', 'Click Create, name it MindFerry, paste the address above, choose no authentication', 'In a new chat, turn on MindFerry and say "Read my profile first"'],
254
+ 'claude-web': ['Settings → Connectors → Add custom connector', 'Name it MindFerry and paste the address above', 'Turn it on from the tools menu in a chat'],
255
+ default: ['In the AI’s settings, look for Connectors, MCP or Apps', 'Add a new one and paste the address above; no sign-in needed', 'Turn it on in a chat and say "Read my profile first"'],
256
+ },
257
+ pasteBusy: 'Working on it…',
258
+ smartTitle: 'Smarter tidy-up (optional)',
259
+ smartSub: 'By default MindFerry uses its built-in rules and nothing leaves this computer. The smarter options below stay off until you turn them on.',
260
+ smartLocal: (k, m) => `Found the ${k} model "${m}" on this computer.`, smartTidy: 'Tidy up with my local model', smartTidying: 'Tidying up, this can take a few minutes…',
261
+ smartTidied: (r) => `Done: read ${r.messages} messages and found ${r.facts} new facts.`,
262
+ smartEmbedOnly: 'Found a local model app, but it only has an embedding model, which cannot tidy up. Install a chat model and come back.',
263
+ smartNone: 'If you install Ollama or LM Studio, MindFerry can use it to understand your chats better. Everything still stays on this computer.',
264
+ smartOrgConfirm: (n) => `Let ${n} read your own words? You can switch back to No at any time.`,
265
+ smartOrg: 'Let a connected AI help tidy up', smartOrgOff: 'No (recommended)',
266
+ smartOrgWarn: 'Note: the AI you pick reads your own words, not just the profile. Sentences its sharing rule doesn\'t allow (by default health, money, IDs, other people, contact details, and topics like religion, politics or sexuality) are blanked first; sentences MindFerry can\'t place are shown as they are, since that is what it is there to sort out. Blanking uses keyword lists and can miss things. Every read is listed in "Who took what".',
267
+ watchTitle: 'Auto-import chats you download', watchSub: 'When on, chat exports you download from AI websites are imported and synced as soon as they land in your Downloads folder.',
268
+ advCli: 'Command line (in a terminal)', advApi: 'Local API and adapters',
269
+ advApiSub: 'The web connection is standard MCP over HTTP. To add an importer for another AI, see the adapter guide:',
270
+ nsProfile: 'Next: give your "About me" to an AI and it knows you right away.', nsProfileBtn: 'Copy it',
271
+ nsConnect: 'Next: connect an AI app on this computer so it can read your profile by itself.', nsConnectBtn: 'Connect',
272
+ nsSync: 'It has been a while since the last sync.', nsSyncBtn: 'Sync',
273
+ nsDone: 'All set. When you try a new AI, just give it your "About me".',
274
+ });
275
+
276
+ let META = null, STATUS = null, ruleClient = 'claude-code', memMode = 'facts';
277
+ const t = (k, ...a) => { const v = I18N[lang][k]; return typeof v === 'function' ? v(...a) : v ?? k; };
278
+ const $ = (s) => document.querySelector(s);
279
+ const clientInfoOk = (id) => !!META?.clients.some((c) => c.id === id);
280
+ const clientName = (id) => META?.clients.find((c) => c.id === id)?.name[lang] || id;
281
+ // Neutral initial-letter chip for each AI (never a vendor logo). Color picked from a soft palette by id.
282
+ function aiChip(id) {
283
+ const name = clientName(id);
284
+ const words = name.split(/\s+/).filter(Boolean);
285
+ let letters = [...(words[0] || '?')][0];
286
+ if (/^[A-Za-z]/.test(letters) && words[1] && /^[A-Za-z]/.test(words[1])) letters += words[1][0];
287
+ let n = 0; for (const ch of id) n = (n * 31 + ch.charCodeAt(0)) >>> 0;
288
+ return h('span', { class: 'ai-chip ai-c' + (n % 8), 'aria-hidden': 'true' }, letters.toUpperCase());
289
+ }
290
+ const fmtTime = (iso) => (iso ? new Date(iso).toLocaleString(lang === 'zh' ? 'zh-CN' : 'en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : t('never'));
291
+
292
+ function h(tag, attrs = {}, ...children) {
293
+ const el = document.createElement(tag);
294
+ for (const [k, v] of Object.entries(attrs)) {
295
+ if (v === undefined || v === null || v === false) continue;
296
+ if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
297
+ else if (k === 'class') el.className = v;
298
+ else if (['checked', 'disabled', 'selected', 'value', 'open'].includes(k)) el[k] = v;
299
+ else el.setAttribute(k, v);
300
+ }
301
+ for (const c of children.flat()) if (c !== null && c !== undefined && c !== false) el.append(c instanceof Node ? c : document.createTextNode(String(c)));
302
+ return el;
303
+ }
304
+
305
+ class ApiError extends Error { constructor(code, msg) { super(msg); this.code = code; } }
306
+ async function api(path, opts = {}) {
307
+ let res;
308
+ try {
309
+ res = await fetch(path, { ...opts, headers: { 'X-MindFerry-Token': TOKEN, ...(opts.json ? { 'Content-Type': 'application/json' } : {}), ...(opts.headers || {}) }, body: opts.json ? JSON.stringify(opts.json) : opts.body });
310
+ } catch {
311
+ throw new ApiError('OFFLINE', lang === 'zh' ? 'MindFerry 已关闭。下一步:在终端里重新运行 mindferry,然后刷新本页。' : 'MindFerry is not running. Next step: run mindferry again in your terminal, then refresh this page.');
312
+ }
313
+ const data = await res.json().catch(() => ({}));
314
+ if (!res.ok) throw new ApiError(data.error || 'INTERNAL', data.message?.[lang] || res.statusText);
315
+ return data;
316
+ }
317
+
318
+ let toastTimer;
319
+ function toast(text, error = false) {
320
+ const n = $('#toast');
321
+ // A modal dialog sits on top of everything else, so show the message inside it.
322
+ const open = document.querySelector('dialog[open]');
323
+ if (n.parentElement !== (open || document.body)) (open || document.body).append(n);
324
+ const stack = error && !n.classList.contains('hidden') && n.classList.contains('error');
325
+ if (stack) { n.querySelector('.toast-close')?.remove(); n.append(h('br'), text); } else n.textContent = text;
326
+ n.classList.toggle('error', error);
327
+ n.classList.remove('hidden');
328
+ n.append(' ', h('button', { class: 'toast-close', 'aria-label': t('closeMsg'), onclick: () => n.classList.add('hidden') }, '×'));
329
+ clearTimeout(toastTimer);
330
+ if (!error) toastTimer = setTimeout(() => n.classList.add('hidden'), 9000); // errors stay until closed
331
+ }
332
+ // Plain words for anything that isn't one of MindFerry's own messages (no raw browser errors).
333
+ const guard = (fn) => async (...a) => { try { await fn(...a); } catch (e) { toast('⚠ ' + (e instanceof ApiError ? e.message : t('genericErr')), true); } };
334
+
335
+ /**
336
+ * Copy text with feedback next to the button. Tries the clipboard, then the selected-text
337
+ * fallback; if the browser blocks both, the text is left selected with a plain-language note.
338
+ */
339
+ async function copyText(text, area, btn, doneLabel = t('copied')) {
340
+ let ok = false;
341
+ try { await navigator.clipboard.writeText(text); ok = true; } catch {}
342
+ if (!ok && area) { try { area.focus(); area.select(); ok = document.execCommand('copy'); } catch {} }
343
+ let note = btn.parentElement.querySelector('.copy-note');
344
+ if (!note) { note = h('p', { class: 'copy-note small', role: 'status' }); btn.parentElement.append(note); }
345
+ if (ok) {
346
+ const was = btn.dataset.label || btn.textContent;
347
+ btn.dataset.label = was;
348
+ btn.textContent = '✓ ' + doneLabel;
349
+ note.textContent = '';
350
+ setTimeout(() => { btn.textContent = was; }, 2500);
351
+ } else {
352
+ if (!area) { // nothing on screen to select: show the text in a box, selected
353
+ area = btn.parentElement.querySelector('textarea.copy-fallback') || h('textarea', { class: 'copy-fallback', readonly: 'readonly', rows: '8' });
354
+ area.value = text;
355
+ btn.parentElement.append(area);
356
+ }
357
+ area.focus(); area.select();
358
+ note.textContent = t('copyManual');
359
+ }
360
+ return ok;
361
+ }
362
+
363
+ function applyI18n() {
364
+ document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en';
365
+ document.title = lang === 'zh' ? 'MindFerry · AI 记忆中介' : 'MindFerry · cross-AI memory';
366
+ document.querySelectorAll('[data-i18n]').forEach((el) => { el.textContent = t(el.dataset.i18n); });
367
+ document.querySelectorAll('[data-i18n-ph]').forEach((el) => { el.placeholder = t(el.dataset.i18nPh); });
368
+ $('#lang').textContent = lang === 'zh' ? 'English' : '中文';
369
+ }
370
+
371
+ // ---------------- Home ----------------
372
+ async function refresh() {
373
+ STATUS = await api('/api/status');
374
+ const empty = STATUS.items === 0 && STATUS.archive.messages === 0;
375
+ $('#welcome').classList.toggle('hidden', !empty);
376
+ $('#syncBar').classList.toggle('hidden', empty);
377
+ $('#demoBtn').classList.toggle('hidden', !empty);
378
+ const banner = $('#demoBanner');
379
+ banner.classList.toggle('hidden', !STATUS.demo && !STATUS.sample);
380
+ if (STATUS.sample) banner.replaceChildren(t('sampleBanner'), ' ', h('button', { class: 'small-btn', onclick: guard(async () => { await api('/api/sample/clear', { method: 'POST' }); await refresh(); switchTab(document.querySelector('nav button.active')?.dataset.tab || 'home'); }) }, t('clearSamples')));
381
+ else banner.textContent = t('demoBanner');
382
+ $('#lastSync').textContent = STATUS.lastSyncAt ? t('lastSync', fmtTime(STATUS.lastSyncAt)) : t('neverSynced');
383
+ $('#autoSync').value = String(STATUS.settings.autoSyncMinutes || 0);
384
+ $('#privacyNote').textContent = t('privacyNote', STATUS.dataDir);
385
+ $('#syncBtn').title = t('syncHint');
386
+ $('#syncHint').textContent = t('syncHint');
387
+ renderClients();
388
+ renderNextStep();
389
+ await Promise.all([renderViews(), renderConflicts()]);
390
+ }
391
+
392
+ async function renderViews() {
393
+ const views = await api('/api/views');
394
+ const sources = Object.keys(views).filter((k) => views[k].length);
395
+ $('#viewsSection').classList.toggle('hidden', !sources.length);
396
+ $('#views').replaceChildren(...sources.map((src) => {
397
+ const all = views[src];
398
+ const open = all.filter((i) => ['public', 'personal'].includes(i.sensitivity));
399
+ const hidden = all.length - open.length;
400
+ const shown = open.slice(0, 6);
401
+ return h('div', { class: 'view' },
402
+ h('h3', {}, aiChip(src), h('span', {}, ...(lang === 'zh' ? [h('b', {}, clientName(src)), ' 眼中的你'] : ['How ', h('b', {}, clientName(src)), ' sees you']))),
403
+ h('ul', {},
404
+ shown.map((i) => h('li', {}, i.text)),
405
+ open.length > shown.length ? h('li', { class: 'private' }, t('viewsMore', open.length - shown.length)) : null,
406
+ hidden ? h('li', { class: 'private' }, t('viewsPrivate', hidden)) : null),
407
+ // One obvious next step per AI: web AIs get a profile to paste, apps show what they'll read.
408
+ META.clients.find((c) => c.id === src)?.kind === 'web'
409
+ ? h('button', { class: 'ghost small-btn', onclick: guard(() => openGenerator(src)) }, t('viewGive', clientName(src)))
410
+ : h('button', { class: 'ghost small-btn', onclick: guard(() => openCard(src, true)) }, t('viewSee')));
411
+ }));
412
+ }
413
+
414
+ function clientCard(c) {
415
+ const info = META.clients.find((x) => x.id === c.id);
416
+ const isMcp = c.kind === 'mcp';
417
+ const status = c.paused ? h('span', { class: 'badge paused' }, t('paused'))
418
+ : isMcp ? h('span', { class: 'badge' + (c.lastSeenAt ? ' ok' : c.connectedAt ? ' wait' : '') }, c.lastSeenAt ? t('connected') : c.connectedAt ? t('waiting') : t('notConnected'))
419
+ : h('span', { class: 'badge' }, t('kindWeb'));
420
+ const actions = [];
421
+ if (!c.enabled) {
422
+ if (isMcp) actions.push(h('button', { class: 'primary', onclick: guard(() => (STATUS.demo || STATUS.sample ? switchTab('connect') : doConnect(c.id))) }, t('connectBtn')));
423
+ else actions.push(h('button', { onclick: () => openPaste(c.id) }, t('importOrPaste')));
424
+ } else {
425
+ if (!isMcp) actions.push(h('button', { class: 'primary', onclick: guard(() => openGenerator(c.id)) }, t('copyCard')));
426
+ else if (!c.lastSeenAt && !c.connectedAt) actions.push(h('button', { class: 'primary', onclick: guard(() => (STATUS.demo || STATUS.sample ? switchTab('connect') : doConnect(c.id))) }, t('connectBtn')));
427
+ else if (!c.lastSeenAt) actions.push(h('div', { class: 'muted small hint' }, (t('restartHow')[c.id] || t('restartHow').default)));
428
+ else actions.push(h('button', { onclick: guard(() => openCard(c.id, true)) }, t('viewCard')));
429
+ actions.push(h('button', { class: 'ghost', onclick: guard(async () => { await api(`/api/clients/${c.id}/paused`, { method: 'PUT', json: { paused: !c.paused } }); refresh(); }) }, c.paused ? t('resume') : t('pause')));
430
+ actions.push(h('button', { class: 'ghost', onclick: guard(() => openLog(c.id)) }, t('logBtn')));
431
+ }
432
+ return h('div', { class: 'client' },
433
+ h('h3', {}, h('span', { class: 'ai-name' }, aiChip(c.id), h('span', {}, info.name[lang])), status),
434
+ info.note ? h('div', { class: 'muted small' }, info.note[lang]) : null,
435
+ c.enabled ? h('div', { class: 'muted small' }, isMcp && c.lastSeenAt ? t('lastSeen', fmtTime(c.lastSeenAt)) : t('lastSync', fmtTime(c.lastSyncAt))) : null,
436
+ c.enabled ? h('div', { class: 'stats' },
437
+ h('span', {}, h('b', {}, c.known), ' ', h('span', { class: 'muted small' }, lang === 'zh' ? '条来自它' : 'from it')),
438
+ h('span', {}, h('b', {}, '+' + c.pendingOut), ' ', h('span', { class: 'muted small' }, t('lastOut'))),
439
+ h('button', { class: 'badge ' + (c.rule.preset === 'everything' ? 'all' : ''), title: t('tabRules'), onclick: () => { ruleClient = c.id; switchTab('rules'); } }, t('presetLabel')[c.rule.preset])) : null,
440
+ h('div', { class: 'actions' }, actions));
441
+ }
442
+
443
+ function renderClients() {
444
+ const on = STATUS.clients.filter((c) => c.enabled);
445
+ const off = STATUS.clients.filter((c) => !c.enabled);
446
+ $('#aisSection h2').classList.toggle('hidden', !on.length);
447
+ $('#clients').replaceChildren(...on.map(clientCard));
448
+ $('#clientsMore').replaceChildren(...off.map(clientCard));
449
+ $('#moreAis').open = !on.length;
450
+ }
451
+
452
+ async function renderConflicts() {
453
+ const box = $('#conflicts');
454
+ if (!STATUS.conflicts) { box.classList.add('hidden'); return; }
455
+ const { items } = await api('/api/items?status=active');
456
+ const open = items.filter((i) => i.conflict && !i.conflict.acknowledged);
457
+ box.replaceChildren(
458
+ h('h4', {}, t('conflictsTitle')),
459
+ h('ul', {}, open.map((i) => h('li', {}, t('conflictLine', i.conflict.previousText, i.text), ' ',
460
+ h('button', { class: 'link', onclick: guard(async () => { await api(`/api/items/${i.id}`, { method: 'PATCH', json: { ackConflict: true } }); refresh(); }) }, t('ack'))))));
461
+ box.classList.toggle('hidden', !open.length);
462
+ }
463
+
464
+ const doSync = guard(async () => {
465
+ const b = $('#syncBtn');
466
+ b.disabled = true; b.textContent = t('syncing');
467
+ b.classList.add('busy'); $('#syncBar').classList.add('busy');
468
+ try { const r = await api('/api/sync', { method: 'POST' }); await refresh(); showDone(r); }
469
+ finally { b.disabled = false; b.textContent = t('syncNow'); b.classList.remove('busy'); $('#syncBar').classList.remove('busy'); }
470
+ });
471
+
472
+ async function importFiles(files, client) {
473
+ $('#drop').classList.add('busy');
474
+ try { await importFilesInner(files, client); } finally { $('#drop').classList.remove('busy'); }
475
+ }
476
+ async function importFilesInner(files, client) {
477
+ for (const f of files) {
478
+ toast(t('importing', f.name));
479
+ try {
480
+ const r = await api('/api/import' + (client ? `?client=${client}` : ''), { method: 'POST', body: f, headers: { 'X-Filename': encodeURIComponent(f.name) } });
481
+ $('#toast').classList.add('hidden');
482
+ if (r.sync) { lastDone = r.sync; doneNotes.push(t('imported', r)); }
483
+ } catch (e) {
484
+ if (e.code === 'FILE_UNRECOGNIZED') pickSource((id) => importFiles([f], id));
485
+ else toast('⚠ ' + f.name + ' — ' + e.message, true);
486
+ }
487
+ }
488
+ await refresh();
489
+ if (lastDone) { showDone(lastDone, doneNotes.splice(0)); lastDone = null; }
490
+ }
491
+
492
+ function pickSource(then) {
493
+ $('#pickButtons').replaceChildren(...META.clients.filter((c) => c.kind === 'web').map((c) =>
494
+ h('button', { type: 'button', onclick: () => { $('#pickDialog').close(); then(c.id); } }, c.name[lang])));
495
+ $('#pickDialog').showModal();
496
+ }
497
+
498
+ function openPaste(client) {
499
+ $('#pasteClient').replaceChildren(
500
+ h('option', { value: '' }, t('autoDetect')),
501
+ ...META.clients.filter((c) => c.kind === 'web').map((c) => h('option', { value: c.id, selected: c.id === client }, c.name[lang])));
502
+ // Keep an unfinished paste: closing the box by accident (Esc, a click) must not lose it.
503
+ $('#pasteDialog').showModal();
504
+ $('#pasteText').focus();
505
+ }
506
+
507
+ async function submitPaste(e) {
508
+ e.preventDefault();
509
+ const text = $('#pasteText').value;
510
+ const client = $('#pasteClient').value || undefined;
511
+ const go = $('#pasteGo');
512
+ const label = go.textContent;
513
+ go.disabled = true; go.textContent = t('pasteBusy');
514
+ try {
515
+ const r = await api('/api/paste', { method: 'POST', json: { text, client } });
516
+ $('#pasteText').value = '';
517
+ $('#pasteDialog').close();
518
+ await refresh();
519
+ showDone(r.sync, [t('imported', r)]);
520
+ } catch (err) {
521
+ if (err.code === 'FILE_UNRECOGNIZED') { $('#pasteDialog').close(); pickSource(async (id) => { try { const r = await api('/api/paste', { method: 'POST', json: { text, client: id } }); toast(t('imported', r)); await refresh(); } catch (e2) { toast('⚠ ' + e2.message, true); } }); }
522
+ else toast('⚠ ' + err.message, true);
523
+ } finally { go.disabled = false; go.textContent = label; }
524
+ }
525
+
526
+ /** Which AI the "About me" maker starts on: the last one picked, else the web AI you have used. */
527
+ function defaultGenFor() {
528
+ const last = localStorage.getItem('mindferry-gen-for');
529
+ if (last && (last === 'new-ai' || META.clients.some((c) => c.id === last))) return last;
530
+ const used = STATUS.clients.filter((c) => c.kind === 'web' && c.enabled).sort((a, b) => String(b.lastSyncAt || '').localeCompare(String(a.lastSyncAt || '')));
531
+ return used[0]?.id || 'new-ai';
532
+ }
533
+
534
+ async function openCard(id, viewOnly = false) {
535
+ const card = await api('/api/card/' + id);
536
+ $('#cardTitle').textContent = clientName(id);
537
+ $('#toast').classList.add('hidden');
538
+ $('#cardWhere').textContent = viewOnly ? '' : (t('cardWhere')[id] || t('cardWhere').default);
539
+ $('#cardText').value = card.text;
540
+ $('#cardHint').textContent = t('cardHint', card.total, card.itemIds.length);
541
+ const copy = $('#copyBtn');
542
+ copy.classList.toggle('hidden', viewOnly);
543
+ copy.textContent = t('copy');
544
+ copy.onclick = guard(async (e) => {
545
+ e.preventDefault();
546
+ await copyText(card.text, $('#cardText'), copy);
547
+ await api(`/api/card/${id}/delivered`, { method: 'POST' });
548
+ refresh();
549
+ });
550
+ $('#cardDialog').showModal();
551
+ $('#cardText').scrollTop = 0;
552
+ (viewOnly ? $('#cardDialog button[value=cancel]') : copy).focus();
553
+ }
554
+
555
+ async function openLog(id) {
556
+ const { log } = await api('/api/access-log?client=' + id);
557
+ $('#logTitle').textContent = t('logTitle', clientName(id));
558
+ $('#logList').replaceChildren(...(log.length ? log.map(logLi) : [h('li', { class: 'muted' }, t('logEmpty'))]));
559
+ $('#logDialog').showModal();
560
+ }
561
+ const logLi = (e) => h('li', {}, h('span', { class: 'muted' }, fmtTime(e.at) + ' · '), h('b', {}, clientName(e.client)), ' ',
562
+ t('logLine', t('logAction')[e.action] || e.action, e.count), e.detail ? h('span', { class: 'muted' }, ` “${e.detail}”`) : null);
563
+
564
+ async function doConnect(id) {
565
+ const r = await api('/api/connect/' + id, { method: 'POST' });
566
+ toast(t('connectedOk', clientName(id)) + ' ' + t('changedWhere', r.how, r.backup) + ' ' + (t('restartHow')[id] || t('restartHow').default) + ' ' + t('waitingHint', clientName(id)));
567
+ await refresh();
568
+ if (document.querySelector('nav button.active').dataset.tab === 'connect') renderConnect();
569
+ }
570
+
571
+ // ---------------- Memory ----------------
572
+ async function renderMemory() {
573
+ $('#factsPane').classList.toggle('hidden', memMode !== 'facts');
574
+ $('#chatsPane').classList.toggle('hidden', memMode !== 'chats');
575
+ $('#statusFilter').classList.toggle('hidden', memMode !== 'facts');
576
+ document.querySelectorAll('[data-mem]').forEach((b) => b.classList.toggle('active', b.dataset.mem === memMode));
577
+ return memMode === 'facts' ? renderItems() : renderChats();
578
+ }
579
+
580
+ async function renderItems() {
581
+ const q = encodeURIComponent($('#q').value.trim());
582
+ const { items } = await api(`/api/items?status=${$('#statusFilter').value}&q=${q}`);
583
+ $('#counts').textContent = t('counts', items.length);
584
+ $('#emptyItems').classList.toggle('hidden', items.length > 0);
585
+ api('/api/trash').then((tr) => {
586
+ const b = $('#toTrash');
587
+ b.classList.toggle('hidden', !tr.items.length);
588
+ b.textContent = t('toTrash', tr.items.length);
589
+ b.onclick = async () => { await switchTab('settings'); $('#trashList').previousElementSibling?.scrollIntoView({ block: 'start' }); };
590
+ }).catch(() => {});
591
+ const patch = guard(async (id, body) => { await api(`/api/items/${id}`, { method: 'PATCH', json: body }); renderItems(); });
592
+ $('#itemRows').replaceChildren(...items.map((i) => h('tr', { class: i.locked ? 'locked' : '' },
593
+ h('td', {}, i.text, i.conflict ? h('span', { class: 'tag-conflict' }, t('replaced', i.conflict.previousText)) : null),
594
+ h('td', {}, h('select', { 'aria-label': t('colCategory'), onchange: (e) => patch(i.id, { category: e.target.value }) },
595
+ META.categories.map((c) => h('option', { value: c, selected: c === i.category }, t('cat')[c])))),
596
+ h('td', {}, i.locked ? h('span', { class: 'sens-secret' }, '🔒 ' + t('lock')) : i.sensitivity === 'secret' ? h('span', { class: 'sens-secret' }, t('sens').secret)
597
+ : h('select', { class: 'sens-' + i.sensitivity, 'aria-label': t('colSens'), onchange: (e) => patch(i.id, { sensitivity: e.target.value }) },
598
+ META.sensitivities.filter((s) => s !== 'secret').map((s) => h('option', { value: s, selected: s === i.sensitivity }, t('sens')[s])))),
599
+ h('td', { class: 'small muted' }, i.sources.map((s) => clientName(s.client)).join(', ')),
600
+ h('td', { class: 'small' },
601
+ h('button', { class: 'link', onclick: () => patch(i.id, { locked: !i.locked }) }, i.locked ? t('unlock') : t('lock')), ' · ',
602
+ h('button', { class: 'link', onclick: async () => { if (confirm(t('confirmDel'))) { await patch(i.id, { delete: true }); toast(t('deletedWhere')); } } }, t('del'))))));
603
+ }
604
+
605
+ async function renderChats() {
606
+ const q = $('#q').value.trim();
607
+ const { results } = await api('/api/archive?q=' + encodeURIComponent(q));
608
+ $('#counts').textContent = q ? t('counts', results.length) : '';
609
+ $('#chatResults').replaceChildren(...(q && !results.length ? [h('li', { class: 'muted empty-li' }, t('noChats'))] : results.map((r) => h('li', {},
610
+ h('div', { class: 'meta' }, `${clientName(r.client)} · ${r.title || ''} · ${r.role === 'user' ? (lang === 'zh' ? '你' : 'you') : 'AI'} · ${fmtTime(r.at)} `,
611
+ r.conv ? h('button', { class: 'link', onclick: guard(() => openConversation(r.client, r.conv, r.title)) }, t('open')) : null),
612
+ h('div', {}, r.snippet)))));
613
+ }
614
+
615
+ async function openConversation(client, conv, title) {
616
+ const { messages } = await api(`/api/conversation?client=${encodeURIComponent(client)}&conv=${encodeURIComponent(conv)}`);
617
+ $('#logTitle').textContent = `${clientName(client)} · ${title || ''}`;
618
+ $('#logList').replaceChildren(...messages.map((m) => h('li', {}, h('b', {}, m.role === 'user' ? (lang === 'zh' ? '你:' : 'You: ') : clientName(client) + ': '), m.text)));
619
+ $('#logDialog').showModal();
620
+ }
621
+
622
+ // ---------------- Rules ----------------
623
+ function renderRules() {
624
+ $('#ruleClients').replaceChildren(...STATUS.clients.map((c) => h('li', {},
625
+ h('button', { class: c.id === ruleClient ? 'active' : '', onclick: () => { ruleClient = c.id; renderRules(); } },
626
+ h('span', { class: 'ai-name' }, aiChip(c.id), h('span', {}, clientName(c.id))), h('span', { class: 'badge' + (c.rule.preset === 'everything' ? ' all' : '') }, t('presetLabel')[c.rule.preset])))));
627
+ const c = STATUS.clients.find((x) => x.id === ruleClient);
628
+ const r = c.rule;
629
+ const setPreset = guard(async (preset) => {
630
+ if (preset === 'everything' && r.preset !== 'everything' && !confirm(t('confirmEverything', clientName(ruleClient)))) return;
631
+ await api('/api/rules/' + ruleClient, { method: 'PUT', json: preset === 'custom' ? { ...r, preset: 'custom' } : { preset } });
632
+ toast(t('saved')); await refresh(); renderRules();
633
+ });
634
+ const presets = h('div', { class: 'presets' },
635
+ [['summary', 'pSummary', 'pSummaryD'], ['custom', 'pCustom', 'pCustomD'], ['everything', 'pEverything', 'pEverythingD']].map(([p, k, d]) =>
636
+ h('button', { type: 'button', class: 'preset' + (r.preset === p ? ' active' : ''), 'aria-pressed': String(r.preset === p), onclick: () => setPreset(p) }, h('b', {}, t(k)), h('span', {}, t(d)))));
637
+ const cats = META.categories.filter((x) => x !== 'ids');
638
+ const custom = h('form', { class: r.preset === 'custom' ? '' : 'hidden', onsubmit: guard(async (e) => {
639
+ e.preventDefault();
640
+ const fd = new FormData(e.target);
641
+ await api('/api/rules/' + ruleClient, { method: 'PUT', json: {
642
+ preset: 'custom', categories: fd.getAll('cat'), maxSensitivity: fd.get('max'), includeUncertain: fd.get('unc') === 'on',
643
+ acceptFromOthers: fd.get('oth') === 'on', archiveAccess: fd.get('arc') === 'on', maxChars: Number(fd.get('chars')), lang: fd.get('lang'),
644
+ } });
645
+ toast(t('saved')); await refresh(); renderRules();
646
+ }) },
647
+ h('strong', {}, t('ruleCats')),
648
+ h('div', { class: 'cats' }, cats.map((k) => h('label', {}, h('input', { type: 'checkbox', name: 'cat', value: k, checked: r.categories.includes(k) }), ' ', t('cat')[k]))),
649
+ h('div', { class: 'row' },
650
+ h('label', {}, t('ruleMax') + ' ', h('select', { name: 'max' }, ['public', 'personal', 'sensitive'].map((s) => h('option', { value: s, selected: s === r.maxSensitivity }, t('sens')[s])))),
651
+ h('label', {}, t('ruleChars') + ' ', h('input', { type: 'number', name: 'chars', min: 200, max: 20000, step: 100, value: String(r.maxChars) })),
652
+ h('label', {}, t('ruleLang') + ' ', h('select', { name: 'lang' }, [['auto', t('langAuto')], ['zh', '中文'], ['en', 'English']].map(([v, l]) => h('option', { value: v, selected: v === r.lang }, l))))),
653
+ h('div', { class: 'row' },
654
+ h('label', {}, h('input', { type: 'checkbox', name: 'unc', checked: r.includeUncertain }), ' ', t('ruleUncertain')),
655
+ h('label', {}, h('input', { type: 'checkbox', name: 'oth', checked: r.acceptFromOthers }), ' ', t('ruleOthers')),
656
+ h('label', {}, h('input', { type: 'checkbox', name: 'arc', checked: r.archiveAccess }), ' ', t('ruleArchive'))),
657
+ h('div', { class: 'row' }, h('button', { class: 'primary', type: 'submit' }, t('save'))));
658
+ $('#ruleEditor').replaceChildren(h('h3', {}, h('span', { class: 'ai-name' }, aiChip(ruleClient), h('span', {}, clientName(ruleClient)))), presets, custom,
659
+ h('div', { class: 'row' }, h('button', { type: 'button', class: 'ghost', onclick: guard(() => openCard(ruleClient, true)) }, t('preview'))));
660
+ }
661
+
662
+ // ---------------- Connect ----------------
663
+ function renderConnect() {
664
+ const mcp = STATUS.clients.filter((c) => c.kind === 'mcp');
665
+ $('#connectList').replaceChildren(...(STATUS.demo || STATUS.sample ? [h('p', { class: 'conflicts' }, STATUS.demo ? t('demoNoConnect') : t('sampleNoConnect'))] : []), ...mcp.map((c) => {
666
+ const info = META.clients.find((x) => x.id === c.id);
667
+ const can = META.autoConnect[c.id];
668
+ return h('div', { class: 'connect-item' },
669
+ h('header', {},
670
+ h('div', {}, h('h3', {}, h('span', { class: 'ai-name' }, aiChip(c.id), h('span', {}, info.name[lang]))),
671
+ h('div', { class: 'muted small' }, c.lastSeenAt ? `${t('connected')} · ${t('lastSeen', fmtTime(c.lastSeenAt))}` : c.connectedAt ? `${t('waiting')} — ${t('restartHow')[c.id] || t('restartHow').default}` : (info.note?.[lang] || t('notConnected')))),
672
+ h('div', { class: 'row' },
673
+ can && (STATUS.demo || STATUS.sample) ? h('span', { class: 'muted small' }, t('sampleRow')) : null,
674
+ can && !STATUS.demo && !STATUS.sample ? h('button', { class: c.lastSeenAt || c.connectedAt ? '' : 'primary', onclick: guard(() => doConnect(c.id)) }, c.lastSeenAt || c.connectedAt ? t('reconnect') : t('connectBtn')) : null,
675
+ can && !STATUS.demo && !STATUS.sample && (c.connectedAt || c.lastSeenAt) ? h('button', { class: 'ghost', onclick: guard(async () => { await api('/api/disconnect/' + c.id, { method: 'POST' }); toast(t('disconnectedOk', info.name[lang])); await refresh(); renderConnect(); }) }, t('disconnect')) : null)),
676
+ h('details', {}, h('summary', { class: 'small muted' }, t('manual')), h('pre', { class: 'snip' }, META.snippets[c.id] || '')));
677
+ }));
678
+ $('#exportSteps').replaceChildren(
679
+ ...Object.entries(t('exportSteps')).map(([id, steps]) => h('div', { class: 'card' }, h('h3', {}, clientName(id)), h('ol', { class: 'small' }, steps.map((s) => h('li', {}, s))))),
680
+ h('p', { class: 'muted small' }, t('exportNote')));
681
+ }
682
+
683
+ // ---------------- Settings ----------------
684
+ async function renderSettings() {
685
+ $('#dataDir').textContent = STATUS.dataDir;
686
+ $('#archiveStats').textContent = t('archiveStats', STATUS.archive);
687
+ const { log } = await api('/api/access-log');
688
+ $('#globalLog').replaceChildren(...(log.length ? log.slice(0, 100).map(logLi) : [h('li', { class: 'muted' }, t('logEmpty'))]));
689
+ }
690
+
691
+ // ---------------- Sync summary (a good ending for every sync) ----------------
692
+ let lastDone = null;
693
+ const doneNotes = [];
694
+ function showDone(r, notes = []) {
695
+ const box = $('#done');
696
+ if (!r) return;
697
+ const nothing = !r.added && !r.updated;
698
+ box.classList.toggle('nothing', nothing);
699
+ box.replaceChildren(
700
+ ...(nothing ? [] : [h('span', { class: 'confetti', 'aria-hidden': 'true' }, ...Array.from({ length: 14 }, () => h('i')))]),
701
+ h('div', { class: 'done-mascot', 'aria-hidden': 'true' }, mascot(nothing ? 'idle' : 'happy')),
702
+ h('div', { class: 'done-body' },
703
+ h('h2', {}, t('doneTitle')),
704
+ h('p', {}, nothing ? t('doneNothing') : t('doneLine', r)),
705
+ ...notes.map((n) => h('p', { class: 'muted small' }, n)),
706
+ h('div', { class: 'row' },
707
+ nothing ? null : h('button', { class: 'primary', onclick: () => { box.classList.add('hidden'); switchTab('profile'); } }, t('doneProfile')),
708
+ r.canUndo && !nothing ? h('button', { class: 'ghost', onclick: guard(async () => { const u = await api('/api/sync/undo', { method: 'POST' }); box.classList.add('hidden'); toast(t('undone', u.removed)); await refresh(); }) }, t('doneUndo')) : null,
709
+ h('button', { class: 'ghost', onclick: () => box.classList.add('hidden') }, t('doneClose')))));
710
+ box.classList.remove('hidden', 'pop');
711
+ void box.offsetWidth;
712
+ box.classList.add('pop');
713
+ box.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'nearest' });
714
+ }
715
+
716
+ // ---------------- Mascot: Ferry, a little paper boat that carries memory notes ----------------
717
+ function mascot(mood = 'idle') {
718
+ const ns = 'http://www.w3.org/2000/svg';
719
+ const wrap = document.createElement('span');
720
+ wrap.className = 'mascot mascot-' + mood;
721
+ const img = document.createElement('img');
722
+ img.src = `mascot-${mood}.svg`;
723
+ img.alt = '';
724
+ img.width = 96; img.height = 96;
725
+ wrap.append(img);
726
+ return wrap;
727
+ }
728
+
729
+ // ---------------- About me ----------------
730
+ async function renderProfile() {
731
+ const [p, { items }] = await Promise.all([api('/api/profile?lang=' + lang), api('/api/items?status=active')]);
732
+ const hidden = items.filter((i) => i.profileHidden);
733
+ const box = $('#profileBody');
734
+ if (!p.itemIds.length) { box.replaceChildren(h('div', { class: 'empty-state' }, mascot('idle'), h('p', {}, t('profEmpty')))); return; }
735
+ box.replaceChildren(
736
+ ...p.sections.map((sec) => h('div', { class: 'prof-sec' },
737
+ h('h3', {}, sec.title),
738
+ h('ul', {}, sec.items.map((it) => h('li', {},
739
+ h('span', {}, it.text),
740
+ h('button', { class: 'ghost tiny', title: t('profHide'), onclick: guard(async () => { await api(`/api/items/${it.id}`, { method: 'PATCH', json: { profileHidden: true } }); renderProfile(); }) }, '✕ ' + t('profHide'))))))),
741
+ ...(hidden.length ? [h('details', { class: 'more' }, h('summary', {}, t('profHidden', hidden.length)),
742
+ h('ul', {}, hidden.map((it) => h('li', {}, h('span', { class: 'muted' }, it.text), ' ',
743
+ h('button', { class: 'ghost tiny', onclick: guard(async () => { await api(`/api/items/${it.id}`, { method: 'PATCH', json: { profileHidden: false } }); renderProfile(); }) }, t('profShow'))))))] : []));
744
+ $('#profCopy').onclick = guard(async (e) => { if (await copyText(p.text, null, e.currentTarget, t('copied'))) toast(t('profCopied')); });
745
+ }
746
+
747
+ // ---------------- Profile generator (web AIs, or any new AI) ----------------
748
+ let GEN = null;
749
+ // Copy / Save must never use a preview that is still being rebuilt: count work in flight and wait.
750
+ let genBusy = 0;
751
+ async function genSettled() {
752
+ for (let i = 0; genBusy > 0 && i < 100; i++) await new Promise((r) => setTimeout(r, 30));
753
+ return GEN.text;
754
+ }
755
+
756
+ async function openGenerator(clientId = 'new-ai', purpose = null) {
757
+ genBusy++;
758
+ try { await openGeneratorNow(clientId, purpose); } finally { genBusy--; }
759
+ }
760
+
761
+ async function openGeneratorNow(clientId, purpose) {
762
+ const g = await api(`/api/generator?client=${encodeURIComponent(clientId)}&lang=${lang}${purpose ? '&purpose=' + purpose : ''}`);
763
+ GEN = { clientId, purpose: g.purpose, items: g.items, maxChars: g.maxChars };
764
+ localStorage.setItem('mindferry-gen-for', clientId);
765
+ const sel = $('#genFor');
766
+ sel.replaceChildren(h('option', { value: 'new-ai' }, t('genNewAi')),
767
+ ...META.clients.filter((c) => c.kind === 'web').map((c) => h('option', { value: c.id, selected: c.id === clientId }, c.name[lang])));
768
+ sel.value = clientId;
769
+ $('#genTitle').textContent = t('genTitle', clientId === 'new-ai' ? t('genNewAi') : clientName(clientId));
770
+ $('#genWhere').textContent = clientId === 'new-ai' ? t('cardWhere').default : (t('cardWhere')[clientId] || t('cardWhere').default);
771
+ $('#genPurposes').replaceChildren(...['all', 'work', 'coding', 'study', 'life'].map((k) =>
772
+ h('button', { type: 'button', class: 'chip' + (k === GEN.purpose ? ' on' : ''), 'aria-pressed': String(k === GEN.purpose), onclick: guard(() => openGenerator(GEN.clientId, k)) }, t('purpose')[k])));
773
+ renderGenList();
774
+ await renderGenPreview();
775
+ if (!$('#genDialog').open) $('#genDialog').showModal();
776
+ $('#genCopy').focus();
777
+ }
778
+
779
+ function renderGenList() {
780
+ const groups = new Map();
781
+ for (const x of GEN.items) { const k = x.reason ? 'held' : x.category; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(x); }
782
+ const keys = [...groups.keys()].sort((a, b) => (a === 'held') - (b === 'held'));
783
+ $('#genList').replaceChildren(...keys.map((k) => {
784
+ const list = groups.get(k);
785
+ const allOn = list.filter((x) => x.canTick).every((x) => x.ticked);
786
+ return h('fieldset', { class: 'gen-group' + (k === 'held' ? ' held' : '') },
787
+ h('legend', {},
788
+ h('label', {}, h('input', { type: 'checkbox', checked: allOn, disabled: !list.some((x) => x.canTick), onchange: (e) => { for (const x of list) if (x.canTick) x.ticked = e.target.checked; renderGenList(); renderGenPreview(); } }),
789
+ ' ', k === 'held' ? (lang === 'zh' ? '私密,默认不给' : 'Private, not given by default') : t('cat')[k] || k)),
790
+ list.map((x) => h('label', { class: 'gen-item' + (x.canTick ? '' : ' locked') },
791
+ h('input', { type: 'checkbox', checked: x.ticked, disabled: !x.canTick, onchange: (e) => { x.ticked = e.target.checked; renderGenPreview(); } }),
792
+ h('span', {}, x.text),
793
+ x.isNew ? h('span', { class: 'badge new' }, t('genNew')) : null,
794
+ x.reason ? h('span', { class: 'why' }, t('holdNote') + t('reason')[x.reason]) : null)));
795
+ }));
796
+ }
797
+
798
+ let genTimer;
799
+ let genTimerPending = false;
800
+ function renderGenPreview() {
801
+ clearTimeout(genTimer);
802
+ if (!genTimerPending) { genTimerPending = true; genBusy++; }
803
+ return new Promise((done) => { genTimer = setTimeout(async () => {
804
+ genTimerPending = false;
805
+ let r;
806
+ try { r = await api(`/api/generate/${GEN.clientId}`, { method: 'POST', json: genBody(false) }); } finally { genBusy--; }
807
+ GEN.text = r.text;
808
+ $('#genText').value = r.text;
809
+ $('#genText').scrollTop = 0;
810
+ $('#genCount').textContent = t('genCount', r.ticked, r.chars, r.maxChars);
811
+ $('#genCondensed').textContent = r.condensed ? t('genCondensed', r.maxChars) : '';
812
+ done();
813
+ }, 120); });
814
+ }
815
+
816
+ function genBody(copied) {
817
+ const on = GEN.items.filter((x) => x.ticked).map((x) => x.id);
818
+ const off = GEN.items.filter((x) => !x.ticked).map((x) => x.id);
819
+ return { purpose: GEN.purpose, on, off, lang, copied };
820
+ }
821
+
822
+ // ---------------- Settings: export, trash, recover ----------------
823
+ async function download(path, name, type) {
824
+ const res = await fetch(path, { headers: { 'X-MindFerry-Token': TOKEN } });
825
+ const blob = new Blob([await res.text()], { type });
826
+ const a = h('a', { href: URL.createObjectURL(blob), download: name });
827
+ document.body.append(a); a.click(); a.remove();
828
+ }
829
+
830
+ async function renderSafety() {
831
+ const tr = await api('/api/trash');
832
+ $('#trashList').replaceChildren(...(tr.items.length ? tr.items.slice(0, 30).map((x) => h('li', {}, h('span', {}, x.text), ' ',
833
+ h('button', { class: 'ghost tiny', onclick: guard(async () => { await api(`/api/trash/${x.id}/restore`, { method: 'POST' }); toast(t('restored')); renderSafety(); refresh(); }) }, t('restore')), ' ',
834
+ h('button', { class: 'ghost tiny', onclick: guard(async () => { if (!confirm(t('purgeOneConfirm'))) return; await api(`/api/trash/${x.id}/purge`, { method: 'POST' }); toast(t('purgedOne')); renderSafety(); }) }, t('purgeOne'))))
835
+ : [h('li', { class: 'muted' }, t('trashEmpty'))]));
836
+ const has = tr.deleted.length > 0;
837
+ $('#wipedRow').classList.toggle('hidden', !has);
838
+ }
839
+
840
+ // ---------------- v0.2 extras: next step, web connection, smarter tidy-up, advanced ----------------
841
+ function renderNextStep() {
842
+ const box = $('#nextStep');
843
+ const empty = STATUS.items === 0 && STATUS.archive.messages === 0;
844
+ if (empty) { box.classList.add('hidden'); return; }
845
+ // Has any AI actually received the profile? (A web AI's lastSeenAt only means its chats were imported.)
846
+ const given = STATUS.clients.some((c) => c.lastDeliveredAt || (c.kind === 'mcp' && c.lastSeenAt));
847
+ const stale = STATUS.lastSyncAt && Date.now() - Date.parse(STATUS.lastSyncAt) > 7 * 864e5;
848
+ const [text, btn, go] = !given ? [t('nsProfile'), t('nsProfileBtn'), () => openGenerator(defaultGenFor())]
849
+ : stale ? [t('nsSync'), t('nsSyncBtn'), () => $('#syncBtn').click()]
850
+ : [t('nsDone'), null, null];
851
+ box.replaceChildren(h('span', {}, text), ...(btn ? [h('button', { class: 'primary small-btn', onclick: guard(go) }, btn)] : []));
852
+ box.classList.remove('hidden');
853
+ }
854
+
855
+ const CLOUDFLARED_URL = 'https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/';
856
+ async function renderWebConn() {
857
+ const box = $('#webConn');
858
+ if (STATUS.demo) { box.replaceChildren(h('p', { class: 'muted' }, t('wcDemo'))); return; }
859
+ const r = await api('/api/remote');
860
+ const state = !r.on ? t('wcOff') : r.tunnel ? t('wcOnPublic') : t('wcOnLocal');
861
+ const hours = h('select', { id: 'wcHours' }, [['1', 'wcH1'], ['4', 'wcH4'], ['24', 'wcH24'], ['0', 'wcH0']].map(([v, k]) => h('option', { value: v }, t(k))));
862
+ const top = h('div', { class: 'row' },
863
+ h('p', {}, h('b', {}, state), ' ', r.on ? (r.until ? t('wcUntil', fmtTime(r.until)) : t('wcForever')) : ''),
864
+ r.on ? h('button', { class: 'ghost', onclick: guard(async () => { await api('/api/remote/stop', { method: 'POST' }); renderWebConn(); }) }, t('wcStop'))
865
+ : h('label', { class: 'muted small' }, t('wcHours'), ' ', hours),
866
+ r.on ? null : h('button', { class: 'primary', onclick: guard(async (e) => { e.target.disabled = true; await api('/api/remote/start', { method: 'POST', json: { hours: Number(hours.value) } }).finally(() => { e.target.disabled = false; }); renderWebConn(); }) }, t('wcStart')));
867
+ const parts = [top];
868
+ if (r.error) parts.push(h('p', { class: 'conflicts small' }, r.error));
869
+ if (!r.cloudflared) parts.push(h('p', { class: 'muted small' }, t('wcNoTunnel'), ' ', h('a', { href: CLOUDFLARED_URL, target: '_blank', rel: 'noopener' }, t('wcGet'))));
870
+ if (r.on) {
871
+ if (r.tunnel) parts.push(h('p', { class: 'muted small' }, t('wcAddrNote')));
872
+ // Without a public address only local MCP apps can use it, so don't offer web AIs a link that cannot work.
873
+ for (const c of r.clients.filter((x) => r.tunnel || x.id === 'other-mcp')) {
874
+ const steps = t('wcSteps')[c.id] || t('wcSteps').default;
875
+ parts.push(h('div', { class: 'wc-item' },
876
+ h('div', { class: 'ai-name' }, aiChip(c.id), h('b', {}, clientName(c.id))),
877
+ h('div', { class: 'row' },
878
+ h('input', { class: 'wc-url', readonly: 'readonly', value: c.url, 'aria-label': clientName(c.id), onfocus: (e) => e.target.select() }),
879
+ h('button', { onclick: guard(async (e) => { await copyText(c.url, e.currentTarget.previousElementSibling, e.currentTarget, t('wcCopied')); }) }, t('wcCopy'))),
880
+ h('div', { class: 'row small' },
881
+ h('label', {}, h('input', { type: 'checkbox', checked: c.write, onchange: guard(async (e) => { await api('/api/remote/write/' + c.id, { method: 'PUT', json: { write: e.target.checked } }); }) }), ' ', t('wcWrite')),
882
+ h('button', { class: 'ghost tiny', onclick: guard(async () => { await api('/api/remote/rotate/' + c.id, { method: 'POST' }); toast(t('wcRotated')); renderWebConn(); }) }, t('wcRotate'))),
883
+ h('details', {}, h('summary', { class: 'small muted' }, t('wcHow', clientName(c.id))),
884
+ h('ol', { class: 'small' }, steps.map((s) => h('li', {}, s))), h('p', { class: 'muted small' }, t('wcMayChange')))));
885
+ }
886
+ }
887
+ box.replaceChildren(...parts);
888
+ }
889
+
890
+ async function renderSmart() {
891
+ const box = $('#smartCard');
892
+ const s = await api('/api/smart');
893
+ const parts = [h('h3', {}, t('smartTitle')), h('p', { class: 'muted small' }, t('smartSub'))];
894
+ if (s.local?.model) {
895
+ parts.push(h('p', {}, t('smartLocal', s.local.kind === 'ollama' ? 'Ollama' : 'LM Studio', s.local.model)),
896
+ h('button', { onclick: guard(async (e) => {
897
+ e.target.disabled = true; e.target.textContent = t('smartTidying');
898
+ try { const r = await api('/api/smart/tidy', { method: 'POST' }); toast(t('smartTidied', r)); await refresh(); }
899
+ finally { e.target.disabled = false; e.target.textContent = t('smartTidy'); }
900
+ }) }, t('smartTidy')));
901
+ } else parts.push(h('p', { class: 'muted small' }, s.local?.onlyEmbedding ? t('smartEmbedOnly') : t('smartNone')));
902
+ const mcp = STATUS.clients.filter((c) => c.kind === 'mcp' && (c.connectedAt || c.lastSeenAt));
903
+ // Picking an organizer gives it your own words, so the warning comes first and needs a yes.
904
+ const sel = h('select', { onchange: guard(async (e) => {
905
+ const v = e.target.value || null;
906
+ if (v && !confirm(t('smartOrgWarn') + '\n\n' + t('smartOrgConfirm', clientName(v)))) { e.target.value = s.organizer || ''; return; }
907
+ await api('/api/settings', { method: 'PUT', json: { organizer: v } }); s.organizer = v; warn.classList.toggle('hidden', !v);
908
+ }) },
909
+ h('option', { value: '' }, t('smartOrgOff')), mcp.map((c) => h('option', { value: c.id, selected: s.organizer === c.id }, clientName(c.id))));
910
+ const warn = h('p', { class: 'conflicts small' + (s.organizer ? '' : ' hidden') }, t('smartOrgWarn'));
911
+ if (mcp.length || s.organizer) parts.push(h('label', { class: 'small' }, t('smartOrg'), ' ', sel), warn);
912
+ parts.push(h('h3', {}, t('watchTitle')), h('p', { class: 'muted small' }, t('watchSub')),
913
+ h('label', {}, h('input', { type: 'checkbox', checked: !!STATUS.settings.watchDownloads, disabled: !!STATUS.demo,
914
+ onchange: guard(async (e) => { await api('/api/settings', { method: 'PUT', json: { watchDownloads: e.target.checked } }); STATUS.settings.watchDownloads = e.target.checked; }) }), ' ', t('watchTitle')));
915
+ box.replaceChildren(...parts);
916
+ }
917
+
918
+ function renderAdvanced() {
919
+ const cli = ['mindferry # open the app', 'mindferry demo # a made-up person', 'mindferry status', 'mindferry import <file> [--client chatgpt]', 'mindferry sync', 'mindferry profile [ai]', 'mindferry items --json --q "keyword"', 'mindferry card <ai>', 'mindferry connect <ai> / disconnect <ai>', 'mindferry undo', 'mindferry export <folder | file.md | file.json>', 'mindferry mcp --client <ai> # MCP over stdio', 'mindferry --help'];
920
+ $('#advBody').replaceChildren(h('h3', {}, t('advCli')), h('pre', { class: 'snip' }, cli.join('\n')),
921
+ h('h3', {}, t('advApi')), h('p', { class: 'muted small' }, t('advApiSub'), ' ', h('a', { href: `https://github.com/cmy515006420/mindferry/blob/main/docs/${lang === 'zh' ? 'zh/适配器开发.md' : 'en/ADAPTERS.md'}`, target: '_blank', rel: 'noopener' }, lang === 'zh' ? '适配器开发' : 'ADAPTERS.md')));
922
+ }
923
+
924
+ // ---------------- wiring ----------------
925
+ function switchTab(name) {
926
+ if (location.hash.slice(1).split('&')[0] !== name) history.replaceState(null, '', name === 'home' ? location.pathname : '#' + name);
927
+ document.querySelectorAll('nav button').forEach((b) => b.classList.toggle('active', b.dataset.tab === name));
928
+ document.querySelectorAll('.tab').forEach((s) => s.classList.toggle('active', s.id === 'tab-' + name));
929
+ window.scrollTo(0, 0);
930
+ const run = guard(async () => {
931
+ if (name === 'memory') await renderMemory();
932
+ if (name === 'rules') renderRules();
933
+ if (name === 'connect') { renderConnect(); await renderWebConn(); }
934
+ if (name === 'settings') { await renderSettings(); await renderSafety(); renderAdvanced(); await renderSmart(); }
935
+ if (name === 'profile') await renderProfile();
936
+ });
937
+ return run();
938
+ }
939
+
940
+ function applyZoom() {
941
+ const big = localStorage.getItem('mindferry-big') === '1';
942
+ document.documentElement.style.zoom = big ? '1.4' : '';
943
+ document.documentElement.classList.toggle('big', big);
944
+ $('#bigText').textContent = big ? t('normalText') : t('bigText');
945
+ }
946
+
947
+ function setLang(l) {
948
+ lang = l;
949
+ localStorage.setItem('mindferry-lang', lang);
950
+ api('/api/settings', { method: 'PUT', json: { uiLang: lang } }).catch(() => {});
951
+ applyI18n();
952
+ applyZoom();
953
+ refresh().then(() => switchTab(document.querySelector('nav button.active').dataset.tab)).catch((e) => toast('⚠ ' + e.message, true));
954
+ }
955
+
956
+ document.querySelectorAll('nav button').forEach((b) => b.addEventListener('click', () => switchTab(b.dataset.tab)));
957
+ $('#lang').addEventListener('click', () => setLang(lang === 'zh' ? 'en' : 'zh'));
958
+ $('#bigText').addEventListener('click', () => { localStorage.setItem('mindferry-big', localStorage.getItem('mindferry-big') === '1' ? '0' : '1'); applyZoom(); });
959
+ document.querySelectorAll('[data-setlang]').forEach((b) => b.addEventListener('click', () => setLang(b.dataset.setlang)));
960
+ $('#syncBtn').addEventListener('click', doSync);
961
+ $('#autoSync').addEventListener('change', guard((e) => api('/api/settings', { method: 'PUT', json: { autoSyncMinutes: Number(e.target.value) } })));
962
+ $('#pasteBtn').addEventListener('click', () => openPaste());
963
+ $('#pasteForm').addEventListener('submit', submitPaste);
964
+ $('#demoBtn').addEventListener('click', guard(async () => { await api('/api/demo', { method: 'POST', json: { lang } }); await refresh(); }));
965
+ $('#howExport').addEventListener('click', (e) => { e.preventDefault(); switchTab('connect'); setTimeout(() => $('#exportGuide').scrollIntoView({ behavior: 'smooth' }), 50); });
966
+ $('#wipeBtn').addEventListener('click', guard(async () => {
967
+ if (!confirm(t('confirmWipe'))) return;
968
+ const w = await api('/api/wipe', { method: 'POST', json: { confirm: 'DELETE' } });
969
+ toast(w.recoverable ? t('wipeKept', w.keepDays) : t('wiped')); await refresh(); renderSettings(); renderSafety();
970
+ }));
971
+ document.querySelectorAll('[data-mem]').forEach((b) => b.addEventListener('click', () => { memMode = b.dataset.mem; guard(renderMemory)(); }));
972
+ const drop = $('#drop');
973
+ drop.addEventListener('click', () => $('#fileInput').click());
974
+ drop.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $('#fileInput').click(); } });
975
+ $('#fileInput').addEventListener('change', (e) => { importFiles([...e.target.files]); e.target.value = ''; });
976
+ drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over'); });
977
+ drop.addEventListener('dragleave', () => drop.classList.remove('over'));
978
+ drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('over'); importFiles([...e.dataTransfer.files]); });
979
+ // Dropping anywhere on the page works too (no accidental navigation to the file).
980
+ window.addEventListener('dragover', (e) => e.preventDefault());
981
+ window.addEventListener('drop', (e) => { if (!drop.contains(e.target)) { e.preventDefault(); if (e.dataTransfer?.files?.length) importFiles([...e.dataTransfer.files]); } });
982
+ let qTimer;
983
+ $('#q').addEventListener('input', () => { clearTimeout(qTimer); qTimer = setTimeout(guard(renderMemory), 220); });
984
+ $('#statusFilter').addEventListener('change', guard(renderItems));
985
+ setInterval(() => {
986
+ const tab = document.querySelector('nav button.active').dataset.tab;
987
+ if (document.hidden || document.querySelector('dialog[open]') || !['home', 'connect'].includes(tab)) return;
988
+ const waiting = STATUS?.clients?.some((c) => c.connectedAt && !c.lastSeenAt);
989
+ if (!waiting && (Date.now() - (window.__lastAuto || 0)) < 15000) return;
990
+ window.__lastAuto = Date.now();
991
+ refresh().then(() => { if (tab === 'connect') renderConnect(); }).catch(() => {});
992
+ }, 4000);
993
+
994
+ try {
995
+ META = await api('/api/meta');
996
+ if (!localStorage.getItem('mindferry-lang') && (META.lang === 'zh' || META.lang === 'en')) lang = META.lang; // --lang or the last choice saved in MindFerry wins over the browser's language
997
+ // Deep links: #memory, #rules, #connect, #settings, #home&card=chatgpt, #home&paste, …&lang=en
998
+ const hp = new URLSearchParams(location.hash.slice(1));
999
+ if (hp.get('lang') === 'zh' || hp.get('lang') === 'en') lang = hp.get('lang');
1000
+ applyI18n();
1001
+ applyZoom();
1002
+ if (STATUS === null && META) api('/api/settings', { method: 'PUT', json: { uiLang: lang } }).catch(() => {});
1003
+ await refresh();
1004
+ const tab = [...hp.keys()].find((k) => ['home', 'profile', 'memory', 'rules', 'connect', 'settings'].includes(k));
1005
+ if (tab && tab !== 'home') switchTab(tab);
1006
+ if (hp.get('rule') && clientInfoOk(hp.get('rule'))) { ruleClient = hp.get('rule'); switchTab('rules'); }
1007
+ if (hp.get('card') && clientInfoOk(hp.get('card'))) await (META.clients.find((c) => c.id === hp.get('card')).kind === 'web' ? openGenerator(hp.get('card')) : openCard(hp.get('card'), true));
1008
+ if (hp.get('gen')) await openGenerator(hp.get('gen'), hp.get('purpose'));
1009
+ if (hp.has('paste')) openPaste();
1010
+ if (hp.get('q')) { $('#q').value = hp.get('q'); if (hp.get('mem') === 'chats') memMode = 'chats'; await renderMemory(); }
1011
+ } catch (e) {
1012
+ applyI18n();
1013
+ toast('⚠ ' + e.message, true);
1014
+ }
1015
+
1016
+ // v0.2 wiring
1017
+ $('#genFor').addEventListener('change', guard((e) => openGenerator(e.target.value, GEN?.purpose)));
1018
+ $('#genCopy').addEventListener('click', guard(async (e) => {
1019
+ e.preventDefault();
1020
+ await copyText(await genSettled(), $('#genText'), $('#genCopy'));
1021
+ await api(`/api/generate/${GEN.clientId}`, { method: 'POST', json: genBody(true) });
1022
+ refresh();
1023
+ }));
1024
+ $('#genDownload').addEventListener('click', async (e) => {
1025
+ e.preventDefault();
1026
+ await genSettled();
1027
+ const a = h('a', { href: URL.createObjectURL(new Blob([GEN.text], { type: 'text/markdown' })), download: lang === 'zh' ? '关于我.md' : 'about-me.md' });
1028
+ document.body.append(a); a.click(); a.remove();
1029
+ api(`/api/generate/${GEN.clientId}`, { method: 'POST', json: genBody(true) }).catch(() => {});
1030
+ });
1031
+ $('#genAll').addEventListener('click', (e) => { e.preventDefault(); for (const x of GEN.items) if (x.canTick) x.ticked = true; renderGenList(); renderGenPreview(); });
1032
+ $('#genNone').addEventListener('click', (e) => { e.preventDefault(); for (const x of GEN.items) x.ticked = false; renderGenList(); renderGenPreview(); });
1033
+ $('#profGive').addEventListener('click', guard(() => openGenerator(defaultGenFor())));
1034
+ $('#exportMd').addEventListener('click', guard(() => download('/api/export?format=md', 'mindferry-export.md', 'text/markdown')));
1035
+ $('#exportJson').addEventListener('click', guard(() => download('/api/export?format=json', 'mindferry-export.json', 'application/json')));
1036
+ $('#recoverWiped').addEventListener('click', guard(async () => { await api('/api/deleted/restore', { method: 'POST' }); toast(t('restored')); await refresh(); renderSettings(); renderSafety(); }));
1037
+ $('#purgeWiped').addEventListener('click', guard(async () => { if (!confirm(t('confirmWipe'))) return; await api('/api/deleted/purge', { method: 'POST' }); toast(t('purged')); renderSafety(); }));