AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(import): enhance WeChat chat note formatting and image layout
tianma-if628245d2c7d8
diff --git a/apps/desktop/src/main/wechat-chat-archive.mjs b/apps/desktop/src/main/wechat-chat-archive.mjsindex 4192a2c4..dd9cdb29 100644--- a/apps/desktop/src/main/wechat-chat-archive.mjs+++ b/apps/desktop/src/main/wechat-chat-archive.mjs@@ -193,6 +193,135 @@ const parseMessages = (text) => {return sections;};+const WECHAT_EMOJI_MAP = {+ "[微笑]": "😊",+ "[撇嘴]": "🥺",+ "[色]": "😍",+ "[发呆]": "😶",+ "[得意]": "😎",+ "[流泪]": "😭",+ "[害羞]": "😳",+ "[闭嘴]": "🤐",+ "[睡]": "😴",+ "[大哭]": "😭",+ "[尴尬]": "😅",+ "[发怒]": "😡",+ "[调皮]": "😜",+ "[呲牙]": "😁",+ "[惊讶]": "😲",+ "[难过]": "🙁",+ "[抓狂]": "😫",+ "[吐]": "🤮",+ "[偷笑]": "🤭",+ "[愉快]": "😄",+ "[白眼]": "🙄",+ "[傲慢]": "😤",+ "[困]": "🥱",+ "[惊恐]": "😱",+ "[憨笑]": "😄",+ "[悠闲]": "😌",+ "[咒骂]": "🤬",+ "[疑问]": "❓",+ "[嘘]": "🤫",+ "[晕]": "😵",+ "[衰]": "😞",+ "[骷髅]": "💀",+ "[敲打]": "🔨",+ "[再见]": "👋",+ "[擦汗]": "😓",+ "[抠鼻]": "🤏",+ "[鼓掌]": "👏",+ "[坏笑]": "😏",+ "[左哼哼]": "😤",+ "[右哼哼]": "😤",+ "[鄙视]": "😒",+ "[委屈]": "🥺",+ "[快哭了]": "😢",+ "[阴险]": "😏",+ "[亲亲]": "😘",+ "[可怜]": "🥺",+ "[笑脸]": "🙂",+ "[生病]": "🤒",+ "[脸红]": "😳",+ "[破涕为笑]": "😂",+ "[恐惧]": "😨",+ "[失望]": "😞",+ "[无语]": "🙄",+ "[嘿哈]": "🤣",+ "[捂脸]": "🤦",+ "[奸笑]": "😏",+ "[机智]": "🤓",+ "[皱眉]": "😟",+ "[耶]": "✌️",+ "[吃瓜]": "🍉",+ "[加油]": "💪",+ "[汗]": "😅",+ "[天啊]": "😱",+ "[Emm]": "🤔",+ "[社会社会]": "🤝",+ "[旺柴]": "🐕",+ "[好的]": "👌",+ "[打脸]": "🤦",+ "[加油加油]": "🎉",+ "[哇]": "🤩",+ "[翻白眼]": "🙄",+ "[666]": "🤙",+ "[让我看看]": "👀",+ "[叹气]": "😮💨",+ "[苦涩]": "🥲",+ "[裂开]": "💔",+ "[嘴唇]": "💋",+ "[爱心]": "❤️",+ "[心碎]": "💔",+ "[蛋糕]": "🎂",+ "[炸弹]": "💣",+ "[便便]": "💩",+ "[月亮]": "🌙",+ "[太阳]": "☀️",+ "[拥抱]": "🫂",+ "[强]": "👍",+ "[弱]": "👎",+ "[握手]": "🤝",+ "[胜利]": "✌️",+ "[抱拳]": "🤛",+ "[勾引]": "🤙",+ "[拳头]": "✊",+ "[OK]": "👌",+ "[合十]": "🙏",+ "[点赞]": "👍",+ "[玫瑰]": "🌹",+ "[凋谢]": "🥀",+ "[红包]": "🧧",+};++const WECHAT_SPECIAL_TOKENS = new Set([+ "动画表情",+ "视频号",+ "小程序",+ "微信红包",+ "位置",+ "名片",+ "语音通话",+ "视频通话",+ "微信转账",+]);++const renderTextMessage = (line) => {+ let text = line;+ for (const [key, emoji] of Object.entries(WECHAT_EMOJI_MAP)) {+ text = text.replaceAll(key, emoji);+ }+ text = text.replace(/\[([^\]]+)\]/g, (match, inner) => {+ if (WECHAT_SPECIAL_TOKENS.has(inner)) {+ return `\uE000${inner}\uE001`;+ }+ return match;+ });+ let escaped = escapeMarkdownText(text);+ escaped = escaped.replace(/\uE000(.*?)\uE001/g, "*[$1]*");+ return escaped;+};+const parseLink = (line) => {const match = LINK_LINE.exec(line.trim());if (!match) return null;@@ -209,19 +338,161 @@ const mediaMarkdown = (item) => {return isImage(item.filename) ? `` : `[附件:${label}](${url})`;};-const renderBody = (lines, mediaByName) => lines.map((line) => {- const mediaMatch = MEDIA_LINE.exec(line.trim());- if (mediaMatch) {- const item = mediaByName.get(posix.basename(mediaMatch[2]));- if (item) {- item.used = true;- return mediaMarkdown(item);+const QUOTE_SEPARATOR = /^[-—─\s]{5,}$/;++const renderBody = (lines, mediaByName) => {+ const rendered = [];+ let index = 0;++ while (index < lines.length) {+ const line = lines[index];+ const trimmed = line.trim();++ // 识别微信引用回复:以「开头,以」结尾,紧随其后是分隔线+ if (trimmed.startsWith("「")) {+ let quoteEndIndex = -1;+ for (let cursor = index; cursor < lines.length; cursor += 1) {+ if (lines[cursor].includes("」")) {+ quoteEndIndex = cursor;+ break;+ }+ }+ if (quoteEndIndex !== -1 && quoteEndIndex + 1 < lines.length && QUOTE_SEPARATOR.test(lines[quoteEndIndex + 1].trim())) {+ const quoteLines = [];+ for (let cursor = index; cursor <= quoteEndIndex; cursor += 1) {+ let quoteLine = lines[cursor].trim();+ if (cursor === index) quoteLine = quoteLine.replace(/^「/, "");+ if (cursor === quoteEndIndex) quoteLine = quoteLine.replace(/」$/, "");+ if (quoteLine) quoteLines.push(quoteLine);+ }+ if (quoteLines.length > 0) {+ const firstQuote = quoteLines[0];+ const colonMatch = firstQuote.match(/^([^::]+)[::](.*)$/);+ if (colonMatch) {+ rendered.push(`> **${escapeMarkdownText(colonMatch[1].trim())}**:${renderTextMessage(colonMatch[2].trim())}`);+ for (let cursor = 1; cursor < quoteLines.length; cursor += 1) {+ rendered.push(`> ${renderTextMessage(quoteLines[cursor])}`);+ }+ } else {+ for (const q of quoteLines) {+ rendered.push(`> ${renderTextMessage(q)}`);+ }+ }+ }+ index = quoteEndIndex + 2;+ continue;+ }}++ const mediaMatch = MEDIA_LINE.exec(trimmed);+ if (mediaMatch) {+ const item = mediaByName.get(posix.basename(mediaMatch[2]));+ if (item) {+ item.used = true;+ rendered.push(mediaMarkdown(item));+ index += 1;+ continue;+ }+ }++ const link = parseLink(trimmed);+ if (link) {+ rendered.push(`[${escapeMarkdownText(link.title)}](${link.url})`);+ index += 1;+ continue;+ }++ if (trimmed) {+ rendered.push(renderTextMessage(trimmed));+ }+ index += 1;+ }++ return rendered.join("\n\n");+};++const parseTimeMs = (timeStr) => {+ const match = /^(\d{4})年(\d{1,2})月(\d{1,2})日\s+(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(timeStr?.trim() || "");+ if (!match) return null;+ const [, y, m, d, hh, mm, ss] = match;+ return new Date(Number(y), Number(m) - 1, Number(d), Number(hh), Number(mm), ss ? Number(ss) : 0).getTime();+};++const groupMessages = (messages) => {+ const groups = [];+ for (const message of messages) {+ if (message.raw) {+ groups.push(message);+ continue;+ }+ const prev = groups.at(-1);+ if (prev && !prev.raw && prev.sender === message.sender) {+ const prevMs = parseTimeMs(prev.time);+ const currMs = parseTimeMs(message.time);+ const isClose = (prevMs !== null && currMs !== null && Math.abs(currMs - prevMs) <= 3 * 60 * 1000)+ || prev.time === message.time;+ if (isClose) {+ prev.body.push(...message.body);+ continue;+ }+ }+ groups.push({+ sender: message.sender,+ time: message.time,+ body: [...message.body],+ });+ }+ return groups;+};++const formatHeader = (sender, time, state) => {+ const match = /^(\d{4}年\d{1,2}月\d{1,2}日)\s+(\d{1,2}:\d{2})(?::\d{2})?$/.exec(time?.trim() || "");+ if (!match) {+ return `**${escapeMarkdownText(sender)}** · ${escapeMarkdownText(time)}`;}- const link = parseLink(line);- if (link) return `[${escapeMarkdownText(link.title)}](${link.url})`;- return escapeMarkdownText(line);-}).join("\n\n");+ const [, date, clock] = match;+ if (state.lastDate === date) {+ return `**${escapeMarkdownText(sender)}** · ${clock}`;+ }+ state.lastDate = date;+ return `**${escapeMarkdownText(sender)}** · ${date} ${clock}`;+};++const buildSummaryCard = (messages, mediaItems) => {+ const structured = messages.filter((m) => !m.raw && m.sender && m.time);+ if (structured.length < 2) return null;++ const senders = [...new Set(structured.map((m) => m.sender))];+ const firstTime = structured[0]?.time;+ const lastTime = structured.at(-1)?.time;++ let timeRange = firstTime;+ if (lastTime && lastTime !== firstTime) {+ const firstMatch = /^(\d{4}年\d{1,2}月\d{1,2}日)\s+(\d{1,2}:\d{2})/.exec(firstTime || "");+ const lastMatch = /^(\d{4}年\d{1,2}月\d{1,2}日)\s+(\d{1,2}:\d{2})/.exec(lastTime || "");+ if (firstMatch && lastMatch && firstMatch[1] === lastMatch[1]) {+ timeRange = `${firstTime} ~ ${lastMatch[2]}`;+ } else {+ timeRange = `${firstTime} ~ ${lastTime}`;+ }+ }++ const imageCount = mediaItems.filter((item) => isImage(item.filename)).length;+ const otherCount = mediaItems.length - imageCount;+ const mediaSummary = [];+ if (imageCount > 0) mediaSummary.push(`${imageCount} 张图片`);+ if (otherCount > 0) mediaSummary.push(`${otherCount} 个附件`);++ const lines = [+ "> 💬 **微信聊天记录**",+ `> **参与者**:${senders.map(escapeMarkdownText).join("、")}`,+ `> **时间**:${escapeMarkdownText(timeRange)} · 共 ${structured.length} 条消息`,+ ];+ if (mediaSummary.length > 0) {+ lines.push(`> **包含媒体**:${mediaSummary.join("、")}`);+ }+ return lines.join("\n");+};const titleTimestamp = (time) => {const match = /^(\d{4})年(\d{1,2})月(\d{1,2})日 (\d{1,2}):(\d{2})(?::\d{2})?$/.exec(time || "");@@ -284,16 +555,19 @@ export const wechatChatNoteFromArchive = (bytes, archiveName = TRANSCRIPT_NAME)}const messages = parseMessages(text);- const sections = messages.length > 0- ? messages.map((message) => {+ const grouped = groupMessages(messages);+ const dateState = { lastDate: null };+ const sections = grouped.length > 0+ ? grouped.map((message) => {if (message.raw) return renderBody(message.raw, mediaByName);const body = renderBody(message.body, mediaByName);- const header = `**${escapeMarkdownText(message.sender)}** · ${escapeMarkdownText(message.time)}`;+ const header = formatHeader(message.sender, message.time, dateState);return body ? `${header}\n\n${body}` : header;}): [escapeMarkdownText(text.trim())];const unused = items.filter((item) => !item.used).map((item) => mediaMarkdown(item));- const markdown = [...sections, ...unused].filter(Boolean).join("\n\n").trim();+ const summaryCard = buildSummaryCard(messages, items);+ const markdown = [summaryCard, ...sections, ...unused].filter(Boolean).join("\n\n").trim();if (!markdown) throw new WeChatArchiveError("unrecognized");return {title: archiveTitle(archiveName, messages),diff --git a/apps/desktop/src/main/wechat-chat-archive.test.mjs b/apps/desktop/src/main/wechat-chat-archive.test.mjsindex 5990b1e2..6818738d 100644--- a/apps/desktop/src/main/wechat-chat-archive.test.mjs+++ b/apps/desktop/src/main/wechat-chat-archive.test.mjs@@ -94,11 +94,14 @@ describe("WeChat chat archive", () => {test("turns the exported zip into messages, an inline image, and attachments", () => {const note = wechatChatNoteFromArchive(sampleArchive(), "聊天记录_20260922_223222.zip");expect(note.title).toBe("聊天记录_20260922_223222");+ expect(note.markdown).toContain("> 💬 **微信聊天记录**");+ expect(note.markdown).toContain("> **参与者**:鱼、Flechazo");+ expect(note.markdown).toContain("> **包含媒体**:1 张图片、2 个附件");expect(note.markdown).toContain("**鱼** · 2026年9月22日 22:15");expect(note.markdown).toContain("[发布说明](https://example.com/post)");expect(note.markdown).toContain("");- expect(note.markdown).toContain("\\[发呆\\]还没注册");- expect(note.markdown).toContain("\\[动画表情\\]");+ expect(note.markdown).toContain("😶还没注册");+ expect(note.markdown).toContain("*[动画表情]*");expect(note.markdown).toContain("[附件:微信视频_1.mp4](edgeever-wechat-media://m2)");expect(note.markdown).toContain("[附件:说明.pdf](edgeever-wechat-media://m3)");expect(note.markdown).not.toContain(".zip");@@ -109,6 +112,45 @@ describe("WeChat chat archive", () => {]);});+ test("formats quoted replies as markdown blockquotes and maps emoji", () => {+ const quoteTranscript = [+ "·张三",+ "2026年9月24日 10:00",+ "明天开会讨论方案",+ "",+ "·李四",+ "2026年9月24日 10:05",+ "「张三:明天开会讨论方案」",+ "- - - - - - - - - - - - - - -",+ "收到,我准备一下材料[OK]",+ ].join("\n");+ const archive = zipOf([{ name: "聊天记录.txt", data: quoteTranscript }]);+ const note = wechatChatNoteFromArchive(archive, "项目组讨论.zip");+ expect(note.markdown).toContain("> **张三**:明天开会讨论方案");+ expect(note.markdown).toContain("收到,我准备一下材料👌");+ });++ test("simplifies times on the same day and keeps full date across days", () => {+ const multiDayTranscript = [+ "·张三",+ "2026年9月24日 10:00",+ "第一天上午",+ "",+ "·李四",+ "2026年9月24日 10:05",+ "第一天同天回复",+ "",+ "·张三",+ "2026年9月25日 09:00",+ "第二天上午",+ ].join("\n");+ const archive = zipOf([{ name: "聊天记录.txt", data: multiDayTranscript }]);+ const note = wechatChatNoteFromArchive(archive, "跨天讨论.zip");+ expect(note.markdown).toContain("**张三** · 2026年9月24日 10:00");+ expect(note.markdown).toContain("**李四** · 10:05");+ expect(note.markdown).toContain("**张三** · 2026年9月25日 09:00");+ });+test("adds the first message time when WeChat provides only a generic archive name", () => {expect(wechatChatNoteFromArchive(sampleArchive(), "聊天记录.zip").title).toBe("聊天记录 · 2026-09-22 22:15");expect(wechatChatNoteFromArchive(sampleArchive()).title).toBe("聊天记录 · 2026-09-22 22:15");diff --git a/apps/web/src/lib/wechat-chat-import.test.mjs b/apps/web/src/lib/wechat-chat-import.test.mjsindex 452382cf..b3734351 100644--- a/apps/web/src/lib/wechat-chat-import.test.mjs+++ b/apps/web/src/lib/wechat-chat-import.test.mjs@@ -68,4 +68,32 @@ describe("WeChat chat note", () => {})).rejects.toThrow("offline");expect(deleted).toEqual(["memo_1"]);});++ test("groups consecutive images into an image gallery", async () => {+ let updated = null;+ await createWeChatChatMemo({+ notebookId: "nb_inbox",+ title: "多图聊天记录",+ markdown: [+ "",+ "",+ "",+ ].join("\n"),+ media: [+ { id: "m1", filename: "图1.jpg", mimeType: "image/jpeg", byteSize: 2 },+ { id: "m2", filename: "图2.jpg", mimeType: "image/jpeg", byteSize: 2 },+ ],+ createMemo: async () => ({ memo }),+ readMedia: async (item) => new File(["a"], item.filename, { type: item.mimeType }),+ uploadResource: async (_id, file) => ({ url: `edgeever-staged://${file.name}` }),+ updateMemo: async (_created, content) => {+ updated = content;+ return { memo: { ...memo, contentMarkdown: content.contentMarkdown } };+ },+ });+ expect(updated.contentJson.content.some((node) => node.type === "edgeeverImageGallery")).toBe(true);+ const gallery = updated.contentJson.content.find((node) => node.type === "edgeeverImageGallery");+ expect(gallery?.content?.length).toBe(2);+ });});+diff --git a/apps/web/src/lib/wechat-chat-import.ts b/apps/web/src/lib/wechat-chat-import.tsindex ca4b4a24..fb4e20e1 100644--- a/apps/web/src/lib/wechat-chat-import.ts+++ b/apps/web/src/lib/wechat-chat-import.ts@@ -1,4 +1,9 @@-import { docToMarkdown, markdownToDoc, type TiptapDoc } from "@edgeever/shared";+import {+ docToMarkdown,+ groupConsecutiveImagesIntoGalleries,+ markdownToDoc,+ type TiptapDoc,+} from "@edgeever/shared";import { IMAGE_WIDTH_PRESETS } from "@edgeever/shared/image-display";export const WECHAT_MEDIA_URL_PREFIX = "edgeever-wechat-media://";@@ -25,9 +30,10 @@ const noteContent = (markdown: string) => {const nodes = (parsed.content ?? []).map((node) => node.type === "image"? { ...node, attrs: { ...node.attrs, width: WECHAT_IMAGE_WIDTH } }: node);+ const groupedNodes = groupConsecutiveImagesIntoGalleries(nodes);const contentJson: TiptapDoc = {type: "doc",- content: nodes.at(-1)?.type === "paragraph" ? nodes : [...nodes, { type: "paragraph" }],+ content: groupedNodes.at(-1)?.type === "paragraph" ? groupedNodes : [...groupedNodes, { type: "paragraph" }],};return { contentJson, contentMarkdown: docToMarkdown(contentJson) };};