Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(desktop): import WeChat chat forwards as notes

tianma-ifbf3b41099abe
diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml
index f3a7ce12..b0b38a31 100644
--- a/apps/desktop/electron-builder.yml
+++ b/apps/desktop/electron-builder.yml
@@ -54,6 +54,10 @@ mac:
category: public.app-category.productivity
icon: assets/icon.icns
minimumSystemVersion: "13.0"
+ afterSign: ./scripts/sign-share-extension.cjs
+ extraFiles:
+ - from: share-extension/dist/EdgeEverShare.appex
+ to: PlugIns/EdgeEverShare.appex
extendInfo:
NSScreenCaptureUsageDescription: "EdgeEver captures a screenshot and saves it as a note."
target:
diff --git a/apps/desktop/scripts/sign-share-extension.cjs b/apps/desktop/scripts/sign-share-extension.cjs
new file mode 100644
index 00000000..5218fc34
--- /dev/null
+++ b/apps/desktop/scripts/sign-share-extension.cjs
@@ -0,0 +1,37 @@
+const { spawnSync } = require("node:child_process");
+const { existsSync } = require("node:fs");
+const { join } = require("node:path");
+
+const signingIdentity = (appPath) => {
+ const result = spawnSync("codesign", ["-dvv", appPath], { encoding: "utf8" });
+ const details = `${result.stdout || ""}\n${result.stderr || ""}`;
+ const authority = details.match(/^Authority=(.*)$/m)?.[1]?.trim();
+ if (!authority || authority === "-" || authority.startsWith("Signature=")) return "-";
+ return authority;
+};
+
+const codesign = (identity, args) => {
+ const command = ["--force", "--sign", identity, "--generate-entitlement-der"];
+ if (process.env.CSC_KEYCHAIN) command.push("--keychain", process.env.CSC_KEYCHAIN);
+ if (identity !== "-") command.push("--timestamp");
+ command.push(...args);
+ const result = spawnSync("codesign", command, { encoding: "utf8" });
+ if (result.status !== 0) {
+ throw new Error(result.stderr || result.stdout || "codesign failed");
+ }
+};
+
+// electron-builder signs nested code with the Electron helper entitlements.
+// The share extension has to keep its own sandbox entitlements instead.
+module.exports = async function signShareExtension(context) {
+ if (context.electronPlatformName !== "darwin") return;
+ const appPath = join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`);
+ const appexPath = join(appPath, "Contents", "PlugIns", "EdgeEverShare.appex");
+ if (!existsSync(appexPath)) {
+ throw new Error(`macOS share extension is missing from the app bundle: ${appexPath}`);
+ }
+ const identity = signingIdentity(appPath);
+ const entitlements = join(__dirname, "..", "share-extension", "EdgeEverShare.entitlements");
+ codesign(identity, ["--entitlements", entitlements, appexPath]);
+ codesign(identity, ["--preserve-metadata=entitlements,requirements,flags,runtime", appPath]);
+};
diff --git a/apps/desktop/share-extension/EdgeEverShare.entitlements b/apps/desktop/share-extension/EdgeEverShare.entitlements
new file mode 100644
index 00000000..2f9659c9
--- /dev/null
+++ b/apps/desktop/share-extension/EdgeEverShare.entitlements
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.files.downloads.read-write</key>
+ <true/>
+</dict>
+</plist>
diff --git a/apps/desktop/share-extension/Info.plist b/apps/desktop/share-extension/Info.plist
new file mode 100644
index 00000000..ea3ab654
--- /dev/null
+++ b/apps/desktop/share-extension/Info.plist
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>zh-Hans</string>
+ <key>CFBundleDisplayName</key>
+ <string>EdgeEver</string>
+ <key>CFBundleExecutable</key>
+ <string>EdgeEverShare</string>
+ <key>CFBundleIdentifier</key>
+ <string>org.edgeever.desktop.share</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>EdgeEver</string>
+ <key>CFBundlePackageType</key>
+ <string>XPC!</string>
+ <key>CFBundleShortVersionString</key>
+ <string>__MARKETING_VERSION__</string>
+ <key>CFBundleVersion</key>
+ <string>__BUILD_VERSION__</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>13.0</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionAttributes</key>
+ <dict>
+ <key>NSExtensionActivationRule</key>
+ <dict>
+ <key>NSExtensionActivationDictionaryVersion</key>
+ <integer>2</integer>
+ <key>NSExtensionActivationSupportsFileWithMaxCount</key>
+ <integer>8</integer>
+ </dict>
+ </key>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.share-services</string>
+ <key>NSExtensionPrincipalClass</key>
+ <string>ShareViewController</string>
+ </dict>
+</dict>
+</plist>
diff --git a/apps/desktop/share-extension/ShareViewController.swift b/apps/desktop/share-extension/ShareViewController.swift
new file mode 100644
index 00000000..53aa3ced
--- /dev/null
+++ b/apps/desktop/share-extension/ShareViewController.swift
@@ -0,0 +1,120 @@
+import AppKit
+import UniformTypeIdentifiers
+
+/// Receives WeChat's merged-forward ZIP and hands the file to the EdgeEver app.
+@objc(ShareViewController)
+final class ShareViewController: NSViewController {
+ private let incomingDirectoryName = "EdgeEver Incoming"
+ private var started = false
+
+ override func loadView() {
+ let chinese = Locale.preferredLanguages.first?.hasPrefix("zh") == true
+ let label = NSTextField(labelWithString: chinese ? "正在保存到 EdgeEver…" : "Saving to EdgeEver…")
+ label.frame = NSRect(x: 16, y: 28, width: 248, height: 24)
+ let container = NSView(frame: NSRect(x: 0, y: 0, width: 280, height: 80))
+ container.addSubview(label)
+ view = container
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ beginImport()
+ }
+
+ override func viewDidAppear() {
+ super.viewDidAppear()
+ beginImport()
+ }
+
+ private func beginImport() {
+ guard !started else { return }
+ started = true
+ Task { await importShare() }
+ }
+
+ private func importShare() async {
+ do {
+ let destination = try await copySharedFile()
+ guard let url = shareURL(for: destination) else {
+ throw CocoaError(.fileWriteUnknown)
+ }
+ if let context = extensionContext {
+ _ = await context.open(url)
+ context.completeRequest(returningItems: nil)
+ }
+ } catch {
+ extensionContext?.cancelRequest(withError: error)
+ }
+ }
+
+ private func copySharedFile() async throws -> URL {
+ guard let items = extensionContext?.inputItems as? [NSExtensionItem] else {
+ throw CocoaError(.fileReadNoSuchFile)
+ }
+ for item in items {
+ for provider in item.attachments ?? [] {
+ guard let type = preferredType(for: provider) else { continue }
+ return try await writeProvider(provider, type: type)
+ }
+ }
+ throw CocoaError(.fileReadNoSuchFile)
+ }
+
+ private func preferredType(for provider: NSItemProvider) -> String? {
+ let preferred = [
+ UTType.zip.identifier,
+ UTType.fileURL.identifier,
+ UTType.data.identifier,
+ UTType.item.identifier,
+ ]
+ return preferred.first { provider.hasItemConformingToTypeIdentifier($0) }
+ }
+
+ private func writeProvider(_ provider: NSItemProvider, type: String) async throws -> URL {
+ let downloads = try FileManager.default.url(
+ for: .downloadsDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: true
+ )
+ let batch = downloads
+ .appendingPathComponent(incomingDirectoryName, isDirectory: true)
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ try FileManager.default.createDirectory(at: batch, withIntermediateDirectories: true)
+ let filename = sanitizedFilename(provider.suggestedName)
+ let destination = batch.appendingPathComponent(filename, isDirectory: false)
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
+ provider.loadFileRepresentation(forTypeIdentifier: type) { source, error in
+ guard let source else {
+ continuation.resume(throwing: error ?? CocoaError(.fileReadUnknown))
+ return
+ }
+ do {
+ if FileManager.default.fileExists(atPath: destination.path) {
+ try FileManager.default.removeItem(at: destination)
+ }
+ try FileManager.default.copyItem(at: source, to: destination)
+ continuation.resume()
+ } catch {
+ continuation.resume(throwing: error)
+ }
+ }
+ }
+ return destination
+ }
+
+ private func sanitizedFilename(_ suggested: String?) -> String {
+ let base = ((suggested ?? "聊天记录.zip") as NSString).lastPathComponent
+ let trimmed = base.replacingOccurrences(of: "/", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let name = trimmed.isEmpty ? "聊天记录.zip" : trimmed
+ return (name as NSString).pathExtension.lowercased() == "zip" ? name : "\(name).zip"
+ }
+
+ private func shareURL(for file: URL) -> URL? {
+ var components = URLComponents()
+ components.scheme = "edgeever"
+ components.host = "wechat-import"
+ components.queryItems = [URLQueryItem(name: "path", value: file.path)]
+ return components.url
+ }
+}
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 3bb9b371..918e6937 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -10,6 +10,7 @@ import { SidecarRpcClient } from "./rpc.mjs";
import { resourceRequestHeaders } from "./resource-request.mjs";
import { downloadContentDispositionFromRequest, isSafeResourceId, parseByteRangeHeader, resourceIdFromRequest } from "./resource-url.mjs";
import { isSupportedAssociatedFile } from "./file-association.mjs";
+import { createWeChatShareController } from "./wechat-share-import.mjs";
import { accountDataDirectory, accountScopeKey } from "./account-scope.mjs";
import { rotateDiagnosticLog } from "./diagnostic-log.mjs";
import { restrictDirectory, restrictFile } from "./file-permissions.mjs";
@@ -675,17 +676,54 @@ const flushPendingScheduledTaskRuns = () => {
}
};
-const handleOpenTarget = (commandLine) => {
- const target = commandLine.find((value) => value.startsWith("edgeever://"));
- if (target) {
- try {
- const url = new URL(target);
- const memoMatch = url.pathname.match(/^\/memo\/([^/]+)$/);
- if (memoMatch) sendDesktopCommand(`open-memo:${decodeURIComponent(memoMatch[1])}`);
- } catch {
- // Ignore malformed protocol invocations.
+const pendingWeChatImports = [];
+let wechatShareController = null;
+
+const wechatShare = () => {
+ wechatShareController ??= createWeChatShareController({
+ downloadsPath: () => app.getPath("downloads"),
+ tempPath: () => app.getPath("temp"),
+ sendToRenderer: (payload) => {
+ if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isLoading() || !rendererReady) {
+ pendingWeChatImports.push(payload);
+ return;
+ }
+ mainWindow.webContents.send("desktop:import-wechat-chat", payload);
+ },
+ onActivity: () => {
+ if (process.platform === "darwin") app.show();
+ showWindow(mainWindow);
+ },
+ writeDiagnostic: (event, details) => { void writeDiagnostic(event, details); },
+ });
+ return wechatShareController;
+};
+
+const flushPendingWeChatImports = () => {
+ if (!rendererReady || !mainWindow || mainWindow.isDestroyed()) return;
+ while (pendingWeChatImports.length > 0) {
+ mainWindow.webContents.send("desktop:import-wechat-chat", pendingWeChatImports.shift());
+ }
+};
+
+const handleProtocolUrl = (target) => {
+ if (typeof target !== "string" || !target.startsWith("edgeever://")) return;
+ try {
+ const url = new URL(target);
+ if (url.hostname === "wechat-import") {
+ void wechatShare().importFromProtocolUrl(target);
+ return;
}
+ const memoMatch = url.pathname.match(/^\/memo\/([^/]+)$/);
+ if (memoMatch) sendDesktopCommand(`open-memo:${decodeURIComponent(memoMatch[1])}`);
+ } catch {
+ // Ignore malformed protocol invocations.
}
+};
+
+const handleOpenTarget = (commandLine) => {
+ const target = commandLine.find((value) => value.startsWith("edgeever://"));
+ if (target) handleProtocolUrl(target);
const associatedFile = commandLine.find((value) => !value.startsWith("-") && isSupportedAssociatedFile(value));
if (associatedFile) void importMarkdownFile(associatedFile);
};
@@ -1480,6 +1518,7 @@ const startApplication = async () => {
flushPendingDesktopCommands();
flushPendingMarkdownImport();
flushPendingScreenshotImport();
+ flushPendingWeChatImports();
flushPendingScheduledTaskRuns();
});
ipcMain.on("desktop:renderer-bootstrap-ready", (event) => {
@@ -1757,6 +1796,12 @@ const startApplication = async () => {
bytes: new Uint8Array(await response.arrayBuffer()),
};
});
+ ipcMain.handle("desktop:read-wechat-import-media", async (_event, importId, mediaId) => (
+ wechatShare().readMedia(importId, mediaId)
+ ));
+ ipcMain.handle("desktop:finish-wechat-import", async (_event, importId) => {
+ await wechatShare().finish(importId);
+ });
ipcMain.handle("desktop:remove-staged-resource", async (_event, id) => {
if (!isSafeResourceId(id)) throw new Error("Invalid staged resource id");
const directory = stagedResourceDirectory();
@@ -1776,12 +1821,25 @@ const startApplication = async () => {
await confirmMacInstallation();
configureAutoUpdater();
handleOpenTarget(process.argv);
+ protocolUrlsReady = true;
+ while (pendingProtocolUrls.length > 0) handleProtocolUrl(pendingProtocolUrls.shift());
app.on("activate", () => {
if (!showWindow(mainWindow)) void createWindow();
void checkForDesktopUpdate("activate");
});
};
+const pendingProtocolUrls = [];
+let protocolUrlsReady = false;
+app.on("open-url", (event, url) => {
+ event.preventDefault();
+ if (!protocolUrlsReady) {
+ pendingProtocolUrls.push(url);
+ return;
+ }
+ handleProtocolUrl(url);
+});
+
void app.whenReady().then(startApplication).catch((error) => {
void showMainStartupFailure(error).catch((dialogError) => {
console.error("Failed to show the desktop startup error", dialogError);
diff --git a/apps/desktop/src/main/wechat-chat-archive.mjs b/apps/desktop/src/main/wechat-chat-archive.mjs
new file mode 100644
index 00000000..300985a7
--- /dev/null
+++ b/apps/desktop/src/main/wechat-chat-archive.mjs
@@ -0,0 +1,289 @@
+import { inflateRawSync } from "node:zlib";
+import { posix } from "node:path";
+
+const MAX_ENTRIES = 1000;
+const MAX_EXPANDED_BYTES = 512 * 1024 * 1024;
+const MAX_TEXT_BYTES = 16 * 1024 * 1024;
+const TRANSCRIPT_NAME = "聊天记录.txt";
+const PREFERRED_MEDIA_DIRECTORY = "聊天记录内的图片、视频和文件/";
+const MEDIA_LINE = /^\[(图片|视频|文件|语音)\]\s+(.+?)\s*$/;
+const LINK_LINE = /^\[链接\]\s+(.+)$/;
+const DATE_LINE = /^\d{4}年\d{1,2}月\d{1,2}日 \d{1,2}:\d{2}(?::\d{2})?$/;
+const IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "gif", "webp"]);
+const MIME_TYPES = {
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ png: "image/png",
+ gif: "image/gif",
+ webp: "image/webp",
+ heic: "image/heic",
+ mp4: "video/mp4",
+ mov: "video/quicktime",
+ m4v: "video/mp4",
+ webm: "video/webm",
+ mp3: "audio/mpeg",
+ m4a: "audio/mp4",
+ wav: "audio/wav",
+ pdf: "application/pdf",
+};
+
+const CRC_TABLE = new Uint32Array(256);
+for (let index = 0; index < 256; index += 1) {
+ let value = index;
+ for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
+ CRC_TABLE[index] = value >>> 0;
+}
+
+const crc32 = (bytes) => {
+ let value = 0xffffffff;
+ for (const byte of bytes) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8);
+ return (value ^ 0xffffffff) >>> 0;
+};
+
+const readUInt16 = (bytes, offset) => {
+ if (offset < 0 || offset + 2 > bytes.length) throw new WeChatArchiveError("invalid");
+ return bytes.readUInt16LE(offset);
+};
+
+const readUInt32 = (bytes, offset) => {
+ if (offset < 0 || offset + 4 > bytes.length) throw new WeChatArchiveError("invalid");
+ return bytes.readUInt32LE(offset);
+};
+
+export class WeChatArchiveError extends Error {
+ constructor(code) {
+ super(code);
+ this.name = "WeChatArchiveError";
+ this.code = code;
+ }
+}
+
+const extensionOf = (filename) => filename.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? "";
+
+const mimeTypeFor = (filename) => MIME_TYPES[extensionOf(filename)] ?? "application/octet-stream";
+
+const isImage = (filename) => IMAGE_EXTENSIONS.has(extensionOf(filename));
+
+const escapeMarkdownText = (value) => value.replace(/[\\`*[\]_]/g, "\\$&");
+const escapeMarkdownLabel = (value) => value.replace(/[\\[\]]/g, "\\$&");
+
+const decodeUtf8 = (bytes) => {
+ try {
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
+ } catch {
+ throw new WeChatArchiveError("invalid");
+ }
+};
+
+const assertSafeEntryName = (name) => {
+ if (!name || name.includes("\\") || name.includes("\0")) throw new WeChatArchiveError("invalid");
+ const parts = name.split("/");
+ if (parts.some((part) => part === ".." || part === ".")) throw new WeChatArchiveError("invalid");
+ if (posix.isAbsolute(name)) throw new WeChatArchiveError("invalid");
+};
+
+const readZipEntries = (bytes) => {
+ const data = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
+ if (data.length < 22 || data.length > MAX_EXPANDED_BYTES) throw new WeChatArchiveError("invalid");
+ let end = -1;
+ const earliest = Math.max(0, data.length - 22 - 65535);
+ for (let offset = data.length - 22; offset >= earliest; offset -= 1) {
+ if (readUInt32(data, offset) !== 0x06054b50) continue;
+ if (offset + 22 + readUInt16(data, offset + 20) === data.length) {
+ end = offset;
+ break;
+ }
+ }
+ if (end < 0) throw new WeChatArchiveError("invalid");
+ if (readUInt16(data, end + 4) !== 0 || readUInt16(data, end + 6) !== 0) throw new WeChatArchiveError("invalid");
+ const count = readUInt16(data, end + 8);
+ const listed = readUInt16(data, end + 10);
+ const directorySize = readUInt32(data, end + 12);
+ let cursor = readUInt32(data, end + 16);
+ if (count !== listed || count < 1 || count > MAX_ENTRIES || cursor + directorySize !== end) {
+ throw new WeChatArchiveError("invalid");
+ }
+
+ const entries = [];
+ let expandedTotal = 0;
+ const seen = new Set();
+ for (let index = 0; index < count; index += 1) {
+ if (readUInt32(data, cursor) !== 0x02014b50) throw new WeChatArchiveError("invalid");
+ const flags = readUInt16(data, cursor + 8);
+ const method = readUInt16(data, cursor + 10);
+ const crc = readUInt32(data, cursor + 16);
+ const compressedSize = readUInt32(data, cursor + 20);
+ const expandedSize = readUInt32(data, cursor + 24);
+ const nameLength = readUInt16(data, cursor + 28);
+ const extraLength = readUInt16(data, cursor + 30);
+ const commentLength = readUInt16(data, cursor + 32);
+ const localOffset = readUInt32(data, cursor + 42);
+ if (flags & 1 || ![0, 8].includes(method) || compressedSize === 0xffffffff || expandedSize === 0xffffffff) {
+ throw new WeChatArchiveError("invalid");
+ }
+ const nameBytes = data.subarray(cursor + 46, cursor + 46 + nameLength);
+ const name = decodeUtf8(nameBytes);
+ assertSafeEntryName(name);
+ if (seen.has(name)) throw new WeChatArchiveError("invalid");
+ seen.add(name);
+ expandedTotal += expandedSize;
+ if (expandedTotal > MAX_EXPANDED_BYTES || localOffset >= cursor) throw new WeChatArchiveError("invalid");
+ entries.push({ name, method, crc, compressedSize, expandedSize, localOffset });
+ cursor += 46 + nameLength + extraLength + commentLength;
+ }
+ if (cursor !== end) throw new WeChatArchiveError("invalid");
+
+ return entries.map((entry) => {
+ if (entry.name.endsWith("/")) {
+ if (entry.expandedSize !== 0) throw new WeChatArchiveError("invalid");
+ return { name: entry.name, data: Buffer.alloc(0) };
+ }
+ if (readUInt32(data, entry.localOffset) !== 0x04034b50) throw new WeChatArchiveError("invalid");
+ if (readUInt16(data, entry.localOffset + 8) !== entry.method) throw new WeChatArchiveError("invalid");
+ const start = entry.localOffset + 30 + readUInt16(data, entry.localOffset + 26) + readUInt16(data, entry.localOffset + 28);
+ const compressed = data.subarray(start, start + entry.compressedSize);
+ if (compressed.length !== entry.compressedSize) throw new WeChatArchiveError("invalid");
+ const inflated = entry.method === 0 ? Buffer.from(compressed) : inflateRawSync(compressed);
+ if (inflated.length !== entry.expandedSize || crc32(inflated) !== entry.crc) throw new WeChatArchiveError("invalid");
+ return { name: entry.name, data: inflated };
+ });
+};
+
+const isIgnoredEntry = (name) => {
+ const base = posix.basename(name);
+ return !base || base === ".DS_Store" || name.startsWith("__MACOSX/") || base.startsWith("._");
+};
+
+const isMessageHeader = (lines, index) =>
+ index + 1 < lines.length && lines[index].startsWith("·") && DATE_LINE.test(lines[index + 1].trim());
+
+const parseMessages = (text) => {
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
+ const messages = [];
+ let index = 0;
+ while (index < lines.length) {
+ while (index < lines.length && lines[index].trim() === "") index += 1;
+ if (index >= lines.length) break;
+ if (!isMessageHeader(lines, index)) {
+ index += 1;
+ continue;
+ }
+ const sender = lines[index].slice(1).trim();
+ const time = lines[index + 1].trim();
+ index += 2;
+ const body = [];
+ while (index < lines.length) {
+ if (lines[index].trim() === "") {
+ let next = index + 1;
+ while (next < lines.length && lines[next].trim() === "") next += 1;
+ if (next >= lines.length || isMessageHeader(lines, next)) {
+ index = next;
+ break;
+ }
+ }
+ if (isMessageHeader(lines, index)) break;
+ body.push(lines[index]);
+ index += 1;
+ }
+ messages.push({ sender, time, body });
+ }
+ return messages;
+};
+
+const parseLink = (line) => {
+ const match = LINK_LINE.exec(line.trim());
+ if (!match) return null;
+ const urlMatch = match[1].match(/^(.*?)(https?:\/\/[^\s)]+)$/);
+ if (!urlMatch) return null;
+ const title = urlMatch[1].trim();
+ if (!title) return null;
+ return { title, url: urlMatch[2] };
+};
+
+const mediaMarkdown = (item) => {
+ const label = escapeMarkdownLabel(item.filename);
+ const url = `edgeever-wechat-media://${item.id}`;
+ return isImage(item.filename) ? `![${label}](${url})` : `[附件:${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 link = parseLink(line);
+ if (link) return `[${escapeMarkdownText(link.title)}](${link.url})`;
+ return escapeMarkdownText(line);
+}).join("\n\n");
+
+const archiveTitle = (archiveName) => {
+ const base = posix.basename(archiveName || "").replace(/\.zip$/i, "").trim();
+ return base || "聊天记录";
+};
+
+/**
+ * Turn one WeChat merged-forward ZIP into a note. The archive itself is not
+ * part of the result; pictures land on the message that names them.
+ */
+export const wechatChatNoteFromArchive = (bytes, archiveName = TRANSCRIPT_NAME) => {
+ const entries = readZipEntries(bytes).filter((entry) => !entry.name.endsWith("/") && !isIgnoredEntry(entry.name));
+ const transcript = entries.find((entry) => posix.basename(entry.name) === TRANSCRIPT_NAME);
+ if (!transcript || transcript.data.length === 0 || transcript.data.length > MAX_TEXT_BYTES) {
+ throw new WeChatArchiveError("unrecognized");
+ }
+ let text;
+ try {
+ text = new TextDecoder("utf-8", { fatal: true }).decode(transcript.data).replace(/^\uFEFF/, "");
+ } catch {
+ throw new WeChatArchiveError("unrecognized");
+ }
+
+ const mediaEntries = entries.filter((entry) => entry !== transcript && entry.data.length > 0);
+ const mediaByName = new Map();
+ const ranked = [...mediaEntries].sort((left, right) => {
+ const leftPreferred = left.name.startsWith(PREFERRED_MEDIA_DIRECTORY) ? 1 : 0;
+ const rightPreferred = right.name.startsWith(PREFERRED_MEDIA_DIRECTORY) ? 1 : 0;
+ return leftPreferred - rightPreferred;
+ });
+ const items = [];
+ for (const entry of ranked) {
+ const filename = posix.basename(entry.name);
+ const existing = mediaByName.get(filename);
+ const item = existing ?? {
+ id: `m${items.length + 1}`,
+ filename,
+ mimeType: mimeTypeFor(filename),
+ bytes: entry.data,
+ used: false,
+ };
+ if (!existing) items.push(item);
+ else item.bytes = entry.data;
+ mediaByName.set(filename, item);
+ }
+
+ const messages = parseMessages(text);
+ const sections = messages.length > 0
+ ? messages.map((message) => {
+ const body = renderBody(message.body, mediaByName);
+ const header = `**${escapeMarkdownText(message.sender)}** · ${escapeMarkdownText(message.time)}`;
+ 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();
+ if (!markdown) throw new WeChatArchiveError("unrecognized");
+ return {
+ title: archiveTitle(archiveName),
+ markdown,
+ media: items.map(({ id, filename, mimeType, bytes: mediaBytes }) => ({
+ id,
+ filename,
+ mimeType,
+ bytes: mediaBytes,
+ })),
+ };
+};
diff --git a/apps/desktop/src/main/wechat-chat-archive.test.mjs b/apps/desktop/src/main/wechat-chat-archive.test.mjs
new file mode 100644
index 00000000..33ba122c
--- /dev/null
+++ b/apps/desktop/src/main/wechat-chat-archive.test.mjs
@@ -0,0 +1,117 @@
+import { deflateRawSync } from "node:zlib";
+import { describe, expect, test } from "bun:test";
+import { WeChatArchiveError, wechatChatNoteFromArchive } from "./wechat-chat-archive.mjs";
+
+const CRC_TABLE = new Uint32Array(256);
+for (let index = 0; index < 256; index += 1) {
+ let value = index;
+ for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
+ CRC_TABLE[index] = value >>> 0;
+}
+
+const crc32 = (bytes) => {
+ let value = 0xffffffff;
+ for (const byte of bytes) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8);
+ return (value ^ 0xffffffff) >>> 0;
+};
+
+const u16 = (value) => {
+ const bytes = Buffer.alloc(2);
+ bytes.writeUInt16LE(value);
+ return bytes;
+};
+
+const u32 = (value) => {
+ const bytes = Buffer.alloc(4);
+ bytes.writeUInt32LE(value >>> 0);
+ return bytes;
+};
+
+const zipOf = (entries) => {
+ const locals = [];
+ const centrals = [];
+ let offset = 0;
+ for (const entry of entries) {
+ const name = Buffer.from(entry.name, "utf8");
+ const data = Buffer.from(entry.data);
+ const method = entry.method ?? 0;
+ const compressed = method === 8 ? deflateRawSync(data) : data;
+ const crc = crc32(data);
+ const local = Buffer.concat([
+ u32(0x04034b50), u16(20), u16(0x0800), u16(method), u16(0), u16(0),
+ u32(crc), u32(compressed.length), u32(data.length), u16(name.length), u16(0),
+ name, compressed,
+ ]);
+ const central = Buffer.concat([
+ u32(0x02014b50), u16(20), u16(20), u16(0x0800), u16(method), u16(0), u16(0),
+ u32(crc), u32(compressed.length), u32(data.length), u16(name.length), u16(0), u16(0),
+ u16(0), u16(0), u32(0), u32(offset), name,
+ ]);
+ locals.push(local);
+ centrals.push(central);
+ offset += local.length;
+ }
+ const directory = Buffer.concat(centrals);
+ return Buffer.concat([
+ ...locals,
+ directory,
+ u32(0x06054b50), u16(0), u16(0), u16(entries.length), u16(entries.length),
+ u32(directory.length), u32(offset), u16(0),
+ ]);
+};
+
+const transcript = [
+ "·鱼",
+ "2026年9月22日 22:15",
+ "[链接] 发布说明 https://example.com/post",
+ "",
+ "·Flechazo",
+ "2026年9月22日 22:15",
+ "[图片] 微信图片_202609222215_1.jpg",
+ "",
+ "·鱼",
+ "2026年9月22日 22:16",
+ "[发呆]还没注册",
+ "",
+ "·鱼",
+ "2026年9月22日 22:19",
+ "[动画表情]",
+ "",
+ "·鱼",
+ "2026年9月22日 22:20",
+ "[视频] 微信视频_1.mp4",
+ "",
+].join("\n");
+
+const sampleArchive = () => zipOf([
+ { name: "聊天记录.txt", data: transcript, method: 8 },
+ { name: "聊天记录内的图片、视频和文件/微信图片_202609222215_1.jpg", data: "jpeg-bytes", method: 0 },
+ { name: "聊天记录内的图片、视频和文件/微信视频_1.mp4", data: "video-bytes", method: 8 },
+ { name: "聊天记录内的图片、视频和文件/说明.pdf", data: "pdf-bytes" },
+]);
+
+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("**鱼** · 2026年9月22日 22:15");
+ expect(note.markdown).toContain("[发布说明](https://example.com/post)");
+ expect(note.markdown).toContain("![微信图片_202609222215_1.jpg](edgeever-wechat-media://m1)");
+ 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");
+ expect(note.media.map((item) => [item.filename, item.mimeType, Buffer.from(item.bytes).toString()])).toEqual([
+ ["微信图片_202609222215_1.jpg", "image/jpeg", "jpeg-bytes"],
+ ["微信视频_1.mp4", "video/mp4", "video-bytes"],
+ ["说明.pdf", "application/pdf", "pdf-bytes"],
+ ]);
+ });
+
+ test("rejects archives that are not a WeChat transcript", () => {
+ expect(() => wechatChatNoteFromArchive(zipOf([{ name: "readme.txt", data: "hello" }]))).toThrow(WeChatArchiveError);
+ expect(() => wechatChatNoteFromArchive(Buffer.from("not a zip"))).toThrow(WeChatArchiveError);
+ expect(() => wechatChatNoteFromArchive(zipOf([{ name: "../聊天记录.txt", data: transcript }]))).toThrow(WeChatArchiveError);
+ });
+});
diff --git a/apps/desktop/src/main/wechat-share-import.mjs b/apps/desktop/src/main/wechat-share-import.mjs
new file mode 100644
index 00000000..3b350325
--- /dev/null
+++ b/apps/desktop/src/main/wechat-share-import.mjs
@@ -0,0 +1,152 @@
+import { randomUUID } from "node:crypto";
+import { mkdir, readFile, realpath, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { WeChatArchiveError, wechatChatNoteFromArchive } from "./wechat-chat-archive.mjs";
+
+export const WECHAT_INCOMING_DIRECTORY_NAME = "EdgeEver Incoming";
+const STALE_INCOMING_MS = 24 * 60 * 60 * 1000;
+const SAFE_ID = /^[A-Za-z0-9_-]{1,80}$/;
+
+export const isPathInsideDirectory = (filePath, directory) => {
+ if (!filePath || !directory) return false;
+ const root = resolve(directory);
+ const candidate = resolve(filePath);
+ const fromRoot = relative(root, candidate);
+ return fromRoot !== "" && fromRoot !== ".." && !fromRoot.startsWith(`..${sep}`) && !isAbsolute(fromRoot);
+};
+
+export const wechatImportFilePath = (value) => {
+ let url;
+ try {
+ url = new URL(value);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "edgeever:" || url.hostname !== "wechat-import") return null;
+ const filePath = url.searchParams.get("path");
+ if (!filePath || !isAbsolute(filePath) || filePath.includes("\0")) return null;
+ return filePath;
+};
+
+const incomingDirectory = (downloadsPath) => join(downloadsPath, WECHAT_INCOMING_DIRECTORY_NAME);
+
+const assertIncomingZip = async (filePath, downloadsPath) => {
+ const root = incomingDirectory(downloadsPath);
+ if (!isPathInsideDirectory(filePath, root) || !filePath.toLowerCase().endsWith(".zip")) {
+ throw new WeChatArchiveError("rejected-path");
+ }
+ const [realRoot, realFile] = await Promise.all([realpath(root), realpath(filePath)]);
+ if (!isPathInsideDirectory(realFile, realRoot)) throw new WeChatArchiveError("rejected-path");
+ return realFile;
+};
+
+const removeImportedZip = async (zipPath, downloadsPath) => {
+ if (!zipPath) return;
+ const root = await realpath(incomingDirectory(downloadsPath)).catch(() => null);
+ const parent = dirname(zipPath);
+ const realParent = await realpath(parent).catch(() => null);
+ if (root && realParent && isPathInsideDirectory(realParent, root)) {
+ await rm(realParent, { recursive: true, force: true }).catch(() => {});
+ return;
+ }
+ await rm(zipPath, { force: true }).catch(() => {});
+};
+
+const removeStaleIncoming = async (downloadsPath, keepPath) => {
+ const root = incomingDirectory(downloadsPath);
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
+ const cutoff = Date.now() - STALE_INCOMING_MS;
+ await Promise.all(entries.map(async (entry) => {
+ const path = join(root, entry.name);
+ if (keepPath && (path === keepPath || keepPath.startsWith(`${path}${sep}`))) return;
+ const info = await stat(path).catch(() => null);
+ if (!info || info.mtimeMs > cutoff) return;
+ await rm(path, { recursive: true, force: true }).catch(() => {});
+ }));
+};
+
+export const createWeChatShareController = ({
+ downloadsPath,
+ tempPath,
+ sendToRenderer,
+ onActivity = () => {},
+ writeDiagnostic = () => {},
+}) => {
+ const sessions = new Map();
+
+ const finish = async (importId) => {
+ if (!SAFE_ID.test(importId || "")) return;
+ const session = sessions.get(importId);
+ sessions.delete(importId);
+ if (!session) return;
+ await rm(session.directory, { recursive: true, force: true }).catch(() => {});
+ };
+
+ const readMedia = async (importId, mediaId) => {
+ if (!SAFE_ID.test(importId || "") || !SAFE_ID.test(mediaId || "")) {
+ throw new WeChatArchiveError("rejected-path");
+ }
+ const session = sessions.get(importId);
+ const media = session?.media.get(mediaId);
+ if (!media) throw new WeChatArchiveError("missing-media");
+ const bytes = await readFile(media.path);
+ if (bytes.length !== media.byteSize) throw new WeChatArchiveError("invalid");
+ return { filename: media.filename, mimeType: media.mimeType, bytes };
+ };
+
+ const importFromProtocolUrl = async (value) => {
+ const requestedPath = wechatImportFilePath(value);
+ if (!requestedPath) return;
+ onActivity();
+ const downloads = downloadsPath();
+ let zipPath = null;
+ let preparedDirectory = null;
+ try {
+ await removeStaleIncoming(downloads, requestedPath);
+ zipPath = await assertIncomingZip(requestedPath, downloads);
+ const archive = await readFile(zipPath);
+ const note = wechatChatNoteFromArchive(archive, basename(zipPath));
+ const importId = randomUUID();
+ const directory = join(tempPath(), "edgeever-wechat-import", importId);
+ preparedDirectory = directory;
+ await mkdir(directory, { recursive: true });
+ const media = new Map();
+ const listed = [];
+ for (const item of note.media) {
+ const path = join(directory, `${item.id}.bin`);
+ await writeFile(path, item.bytes);
+ media.set(item.id, {
+ filename: item.filename,
+ mimeType: item.mimeType,
+ byteSize: item.bytes.length,
+ path,
+ });
+ listed.push({
+ id: item.id,
+ filename: item.filename,
+ mimeType: item.mimeType,
+ byteSize: item.bytes.length,
+ });
+ }
+ sessions.set(importId, { directory, media });
+ preparedDirectory = null;
+ sendToRenderer({
+ ok: true,
+ importId,
+ title: note.title,
+ markdown: note.markdown,
+ media: listed,
+ });
+ void writeDiagnostic("wechat-import.accepted", { media: listed.length, bytes: archive.length });
+ } catch (error) {
+ if (preparedDirectory) await rm(preparedDirectory, { recursive: true, force: true }).catch(() => {});
+ const reason = error instanceof WeChatArchiveError ? error.code : "failed";
+ sendToRenderer({ ok: false, reason: reason === "unrecognized" ? "unrecognized" : "failed" });
+ void writeDiagnostic("wechat-import.rejected", { reason });
+ } finally {
+ await removeImportedZip(zipPath, downloads);
+ }
+ };
+
+ return { importFromProtocolUrl, readMedia, finish };
+};
diff --git a/apps/desktop/src/main/wechat-share-import.test.mjs b/apps/desktop/src/main/wechat-share-import.test.mjs
new file mode 100644
index 00000000..b2afb5fc
--- /dev/null
+++ b/apps/desktop/src/main/wechat-share-import.test.mjs
@@ -0,0 +1,134 @@
+import { deflateRawSync } from "node:zlib";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ WECHAT_INCOMING_DIRECTORY_NAME,
+ createWeChatShareController,
+ isPathInsideDirectory,
+ wechatImportFilePath,
+} from "./wechat-share-import.mjs";
+
+const CRC_TABLE = new Uint32Array(256);
+for (let index = 0; index < 256; index += 1) {
+ let value = index;
+ for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
+ CRC_TABLE[index] = value >>> 0;
+}
+const crc32 = (bytes) => {
+ let value = 0xffffffff;
+ for (const byte of bytes) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8);
+ return (value ^ 0xffffffff) >>> 0;
+};
+const u16 = (value) => {
+ const bytes = Buffer.alloc(2);
+ bytes.writeUInt16LE(value);
+ return bytes;
+};
+const u32 = (value) => {
+ const bytes = Buffer.alloc(4);
+ bytes.writeUInt32LE(value >>> 0);
+ return bytes;
+};
+const zipOf = (name, text, extraName, extra) => {
+ const files = [
+ { name, data: Buffer.from(text) },
+ { name: extraName, data: Buffer.from(extra) },
+ ];
+ const locals = [];
+ const centrals = [];
+ let offset = 0;
+ for (const file of files) {
+ const entryName = Buffer.from(file.name, "utf8");
+ const compressed = deflateRawSync(file.data);
+ const crc = crc32(file.data);
+ const local = Buffer.concat([
+ u32(0x04034b50), u16(20), u16(0x0800), u16(8), u16(0), u16(0),
+ u32(crc), u32(compressed.length), u32(file.data.length), u16(entryName.length), u16(0),
+ entryName, compressed,
+ ]);
+ centrals.push(Buffer.concat([
+ u32(0x02014b50), u16(20), u16(20), u16(0x0800), u16(8), u16(0), u16(0),
+ u32(crc), u32(compressed.length), u32(file.data.length), u16(entryName.length), u16(0), u16(0),
+ u16(0), u16(0), u32(0), u32(offset), entryName,
+ ]));
+ locals.push(local);
+ offset += local.length;
+ }
+ const directory = Buffer.concat(centrals);
+ return Buffer.concat([
+ ...locals, directory,
+ u32(0x06054b50), u16(0), u16(0), u16(files.length), u16(files.length),
+ u32(directory.length), u32(offset), u16(0),
+ ]);
+};
+
+const roots = [];
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true })));
+});
+
+describe("WeChat share handoff", () => {
+ test("accepts only an absolute file from the edgeever share URL", () => {
+ expect(wechatImportFilePath("edgeever://wechat-import?path=/Users/me/Downloads/EdgeEver%20Incoming/a/chat.zip")).toBe(
+ "/Users/me/Downloads/EdgeEver Incoming/a/chat.zip",
+ );
+ expect(wechatImportFilePath("edgeever://memo/memo_1")).toBeNull();
+ expect(wechatImportFilePath("https://example.com/chat.zip")).toBeNull();
+ expect(wechatImportFilePath("edgeever://wechat-import?path=chat.zip")).toBeNull();
+ expect(isPathInsideDirectory("/tmp/in/uuid/chat.zip", "/tmp/in")).toBe(true);
+ expect(isPathInsideDirectory("/tmp/in", "/tmp/in")).toBe(false);
+ expect(isPathInsideDirectory("/tmp/other/chat.zip", "/tmp/in")).toBe(false);
+ });
+
+ test("imports a zip from the incoming folder and then deletes it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "edgeever-wechat-share-"));
+ roots.push(root);
+ const downloads = join(root, "Downloads");
+ const temp = join(root, "temp");
+ const batch = join(downloads, WECHAT_INCOMING_DIRECTORY_NAME, "batch");
+ await mkdir(batch, { recursive: true });
+ const zipPath = join(batch, "聊天记录_20260922_223222.zip");
+ await writeFile(zipPath, zipOf(
+ "聊天记录.txt",
+ "·鱼\n2026年9月22日 22:15\n[图片] 微信图片_1.jpg\n",
+ "聊天记录内的图片、视频和文件/微信图片_1.jpg",
+ "jpeg",
+ ));
+ const sent = [];
+ const controller = createWeChatShareController({
+ downloadsPath: () => downloads,
+ tempPath: () => temp,
+ sendToRenderer: (payload) => sent.push(payload),
+ });
+ const url = `edgeever://wechat-import?path=${encodeURIComponent(zipPath)}`;
+ await controller.importFromProtocolUrl(url);
+ expect(sent).toHaveLength(1);
+ expect(sent[0].ok).toBe(true);
+ expect(sent[0].title).toBe("聊天记录_20260922_223222");
+ expect(sent[0].markdown).toContain("![微信图片_1.jpg](edgeever-wechat-media://m1)");
+ const media = await controller.readMedia(sent[0].importId, "m1");
+ expect(Buffer.from(media.bytes).toString()).toBe("jpeg");
+ await expect(stat(zipPath)).rejects.toThrow();
+ await expect(stat(batch)).rejects.toThrow();
+ await controller.finish(sent[0].importId);
+ await expect(readFile(join(temp, "edgeever-wechat-import", sent[0].importId, "m1.bin"))).rejects.toThrow();
+ });
+
+ test("does not read a zip outside the incoming folder", async () => {
+ const root = await mkdtemp(join(tmpdir(), "edgeever-wechat-share-"));
+ roots.push(root);
+ const outside = join(root, "secret.zip");
+ await writeFile(outside, Buffer.from("secret"));
+ const sent = [];
+ const controller = createWeChatShareController({
+ downloadsPath: () => join(root, "Downloads"),
+ tempPath: () => join(root, "temp"),
+ sendToRenderer: (payload) => sent.push(payload),
+ });
+ await controller.importFromProtocolUrl(`edgeever://wechat-import?path=${encodeURIComponent(outside)}`);
+ expect(sent[0]).toEqual({ ok: false, reason: "failed" });
+ expect((await readFile(outside)).toString()).toBe("secret");
+ });
+});
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index 01e4b165..2888a3d6 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -102,6 +102,17 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
}
return () => ipcRenderer.removeListener("desktop:import-markdown", listener);
},
+ readWeChatImportMedia: (importId, mediaId) => ipcRenderer.invoke("desktop:read-wechat-import-media", importId, mediaId).then((file) => ({
+ filename: file.filename,
+ mimeType: file.mimeType,
+ bytes: normalizeIpcBytes(file.bytes),
+ })),
+ finishWeChatImport: (importId) => ipcRenderer.invoke("desktop:finish-wechat-import", importId),
+ onImportWeChatChat: (callback) => {
+ const listener = (_event, payload) => callback(payload);
+ ipcRenderer.on("desktop:import-wechat-chat", listener);
+ return () => ipcRenderer.removeListener("desktop:import-wechat-chat", listener);
+ },
onImportScreenshot: (callback) => {
if (screenshotImportListener) {
ipcRenderer.removeListener("desktop:import-screenshot", screenshotImportListener);
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 20864dbc..58c680e9 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -133,6 +133,7 @@ import { EditorPaneErrorBoundary, EditorRecoveryPane } from "./EditorPaneErrorBo
import { isMarkdownFile, readMarkdownFile } from "@/lib/markdown-file-import";
import { compressImageForUpload } from "@/lib/image-compression";
import { createScreenshotMemo, screenshotFileFromImportPayload, screenshotImportDedupeKey, screenshotImportGate } from "@/lib/screenshot-import";
+import { createWeChatChatMemo } from "@/lib/wechat-chat-import";
import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceUrl } from "@/lib/desktop-resources";
import { findMatchingMemoResource } from "@/lib/staged-resource-repair";
@@ -1763,6 +1764,117 @@ export const WorkspaceApp = ({
const handleImportScreenshotRef = useRef(handleImportScreenshot);
handleImportScreenshotRef.current = handleImportScreenshot;
+ const pendingWeChatImportsRef = useRef<Array<{
+ ok: boolean;
+ reason?: string;
+ importId?: string;
+ title?: string;
+ markdown?: string;
+ media?: Array<{ id: string; filename: string; mimeType: string; byteSize: number }>;
+ }>>([]);
+
+ const handleImportWeChatChat = useCallback(async (payload: {
+ ok: boolean;
+ reason?: string;
+ importId?: string;
+ title?: string;
+ markdown?: string;
+ media?: Array<{ id: string; filename: string; mimeType: string; byteSize: number }>;
+ }) => {
+ const bridge = window.edgeeverDesktop;
+ const finish = () => {
+ if (payload.importId && bridge?.finishWeChatImport) void bridge.finishWeChatImport(payload.importId);
+ };
+ if (!payload.ok || !payload.importId || !payload.markdown) {
+ finish();
+ setAppNoticeDialog({
+ title: t("memoList.importWeChatFailedTitle"),
+ description: payload.reason === "unrecognized"
+ ? t("memoList.importWeChatUnrecognized")
+ : t("memoList.importWeChatFailed"),
+ });
+ return;
+ }
+ const notebookId = selectedNotebookId && notebooks.some((notebook) => notebook.id === selectedNotebookId) && memoView !== "trash"
+ ? selectedNotebookId
+ : defaultMemoNotebookId;
+ if (!notebookId) {
+ pendingWeChatImportsRef.current.push(payload);
+ return;
+ }
+ const importId = payload.importId;
+ const markdown = payload.markdown;
+ setTemplatesOpen(false);
+ setMobileBottomNavActive("home");
+ creatingMemoSelectionRef.current = true;
+ try {
+ const memo = await createWeChatChatMemo({
+ notebookId,
+ title: payload.title?.trim() || "",
+ markdown,
+ media: payload.media ?? [],
+ createMemo: (input) => repository.createMemo(input),
+ readMedia: async (item) => {
+ const file = await bridge?.readWeChatImportMedia?.(importId, item.id);
+ if (!file?.bytes?.byteLength) throw new Error("Missing WeChat attachment");
+ const bytes = file.bytes;
+ const copy = new ArrayBuffer(bytes.byteLength);
+ new Uint8Array(copy).set(bytes);
+ return new File([copy], file.filename || item.filename, { type: file.mimeType || item.mimeType });
+ },
+ prepareFile: async (file) => (imageCompressionEnabled && file.type.startsWith("image/")
+ ? (await compressImageForUpload(file)).file
+ : file),
+ uploadResource: async (memoId, uploadFile) => {
+ try {
+ const { resource } = await repository.uploadMemoResource(memoId, uploadFile);
+ return { url: toDesktopResourceUrl(resource.url) };
+ } catch (error) {
+ if (!isDesktopResourceRuntime()) throw error;
+ const listed = await repository.listResources().catch(() => ({ resources: [] as Array<{ memoId?: string; url: string; filename?: string | null; kind?: string | null }> }));
+ const existing = findMatchingMemoResource(
+ listed.resources.filter((resource) => resource.memoId === memoId),
+ uploadFile.name,
+ uploadFile.type.startsWith("image/") ? "image" : "attachment",
+ );
+ if (existing) return { url: toDesktopResourceUrl(existing.url) };
+ const staged = await stageDesktopResource(memoId, uploadFile);
+ if (!staged) throw error;
+ return { url: `edgeever-staged://${staged.id}` };
+ }
+ },
+ updateMemo: (created, content) => repository.updateMemo(created, {
+ expectedRevision: created.revision,
+ expectedContentHash: created.contentHash,
+ editSessionId: `wechat:${created.id}`,
+ title: created.title ?? payload.title ?? "",
+ contentJson: content.contentJson,
+ contentMarkdown: content.contentMarkdown,
+ tags: created.tags,
+ }),
+ deleteMemo: (memoId) => repository.deleteMemo(memoId, true),
+ });
+ await putLocalMemo(localDataScope, memo);
+ revealCreatedMemo(memo);
+ } catch {
+ creatingMemoSelectionRef.current = false;
+ setAppNoticeDialog({
+ title: t("memoList.importWeChatFailedTitle"),
+ description: t("memoList.importWeChatFailed"),
+ });
+ } finally {
+ finish();
+ }
+ }, [defaultMemoNotebookId, imageCompressionEnabled, localDataScope, memoView, notebooks, repository, selectedNotebookId, t]);
+
+ const handleImportWeChatChatRef = useRef(handleImportWeChatChat);
+ handleImportWeChatChatRef.current = handleImportWeChatChat;
+
+ useEffect(() => {
+ const pending = pendingWeChatImportsRef.current.splice(0);
+ for (const payload of pending) void handleImportWeChatChat(payload);
+ }, [handleImportWeChatChat]);
+
const handleCreateMemo = (kind?: DiagramKind) => {
const targetNotebookId = createMemoNotebookId;
@@ -2424,6 +2536,10 @@ export const WorkspaceApp = ({
}
}
});
+ // The Markdown listener is what marks the renderer ready, so register this first.
+ const removeWeChatListener = bridge.onImportWeChatChat?.((payload) => {
+ void handleImportWeChatChatRef.current(payload);
+ }) ?? (() => {});
const removeMarkdownListener = bridge.onImportMarkdown((payload) => {
const notebookId = selectedNotebookId && notebooks.some((notebook) => notebook.id === selectedNotebookId)
? selectedNotebookId
@@ -2437,6 +2553,7 @@ export const WorkspaceApp = ({
}) ?? (() => {});
return () => {
removeCommandListener();
+ removeWeChatListener();
removeMarkdownListener();
removeScreenshotListener();
};
diff --git a/apps/web/src/lib/wechat-chat-import.test.mjs b/apps/web/src/lib/wechat-chat-import.test.mjs
new file mode 100644
index 00000000..a6905888
--- /dev/null
+++ b/apps/web/src/lib/wechat-chat-import.test.mjs
@@ -0,0 +1,64 @@
+import { describe, expect, test } from "bun:test";
+import { FILE_ATTACHMENT_NODE_TYPE } from "@edgeever/shared";
+import { createWeChatChatMemo } from "./wechat-chat-import.ts";
+
+const memo = {
+ id: "memo_1",
+ revision: 1,
+ contentHash: "hash",
+ title: "聊天记录_20260922_223222",
+ tags: [],
+ contentMarkdown: "",
+};
+
+describe("WeChat chat note", () => {
+ test("stores the picture inline and the video as an attachment", async () => {
+ let updated = null;
+ const result = await createWeChatChatMemo({
+ notebookId: "nb_inbox",
+ title: memo.title,
+ markdown: [
+ "**鱼** · 2026年9月22日 22:15",
+ "",
+ "![微信图片_1.jpg](edgeever-wechat-media://m1)",
+ "",
+ "**鱼** · 2026年9月22日 22:20",
+ "",
+ "[附件:微信视频_1.mp4](edgeever-wechat-media://m2)",
+ ].join("\n"),
+ media: [
+ { id: "m1", filename: "微信图片_1.jpg", mimeType: "image/jpeg", byteSize: 4 },
+ { id: "m2", filename: "微信视频_1.mp4", mimeType: "video/mp4", byteSize: 4 },
+ ],
+ createMemo: async () => ({ memo }),
+ readMedia: async (item) => new File([item.id], item.filename, { type: item.mimeType }),
+ uploadResource: async (_memoId, file) => ({ url: `edgeever-staged://${file.name}` }),
+ updateMemo: async (_created, content) => {
+ updated = content;
+ return { memo: { ...memo, contentMarkdown: content.contentMarkdown } };
+ },
+ });
+ expect(result.contentMarkdown).toContain("edgeever-staged://微信图片_1.jpg");
+ expect(result.contentMarkdown).toContain("edgeever-staged://微信视频_1.mp4");
+ expect(result.contentMarkdown).not.toContain("edgeever-wechat-media://");
+ const saved = JSON.stringify(updated.contentJson);
+ expect(saved).toContain("edgeever-staged://微信图片_1.jpg");
+ expect(saved).toContain(FILE_ATTACHMENT_NODE_TYPE);
+ });
+
+ test("removes the empty note when an attachment cannot be saved", async () => {
+ const deleted = [];
+ await expect(createWeChatChatMemo({
+ notebookId: "nb_inbox",
+ title: "聊天记录",
+ markdown: "![图.jpg](edgeever-wechat-media://m1)",
+ media: [{ id: "m1", filename: "图.jpg", mimeType: "image/jpeg", byteSize: 1 }],
+ createMemo: async () => ({ memo }),
+ readMedia: async () => new File(["x"], "图.jpg", { type: "image/jpeg" }),
+ uploadResource: async () => { throw new Error("offline"); },
+ updateMemo: async () => { throw new Error("should not update"); },
+ deleteMemo: async (id) => { deleted.push(id); },
+ })).rejects.toThrow("offline");
+ expect(deleted).toEqual(["memo_1"]);
+ });
+});
diff --git a/apps/web/src/lib/wechat-chat-import.ts b/apps/web/src/lib/wechat-chat-import.ts
new file mode 100644
index 00000000..cef15a24
--- /dev/null
+++ b/apps/web/src/lib/wechat-chat-import.ts
@@ -0,0 +1,73 @@
+import { docToMarkdown, markdownToDoc, type TiptapDoc } from "@edgeever/shared";
+
+export const WECHAT_MEDIA_URL_PREFIX = "edgeever-wechat-media://";
+
+type WeChatMedia = {
+ id: string;
+ filename: string;
+ mimeType: string;
+ byteSize: number;
+};
+
+type WeChatMemo = {
+ id: string;
+ revision: number;
+ contentHash: string;
+ title: string | null;
+ tags: string[];
+ contentMarkdown: string;
+};
+
+const noteContent = (markdown: string) => {
+ const parsed = markdownToDoc(markdown);
+ const nodes = parsed.content ?? [];
+ const contentJson: TiptapDoc = {
+ type: "doc",
+ content: nodes.at(-1)?.type === "paragraph" ? nodes : [...nodes, { type: "paragraph" }],
+ };
+ return { contentJson, contentMarkdown: docToMarkdown(contentJson) };
+};
+
+export const createWeChatChatMemo = async <TMemo extends WeChatMemo>(input: {
+ notebookId: string;
+ title: string;
+ markdown: string;
+ media: WeChatMedia[];
+ createMemo: (payload: {
+ notebookId: string;
+ title: string;
+ contentMarkdown: string;
+ tags: string[];
+ }) => Promise<{ memo: TMemo }>;
+ readMedia: (media: WeChatMedia) => Promise<File>;
+ prepareFile?: (file: File) => Promise<File>;
+ uploadResource: (memoId: string, file: File) => Promise<{ url: string }>;
+ updateMemo: (
+ memo: TMemo,
+ content: { contentJson: TiptapDoc; contentMarkdown: string },
+ ) => Promise<{ memo: TMemo }>;
+ deleteMemo?: (memoId: string) => Promise<unknown>;
+}) => {
+ const created = await input.createMemo({
+ notebookId: input.notebookId,
+ title: input.title,
+ contentMarkdown: "",
+ tags: [],
+ });
+ try {
+ let markdown = input.markdown;
+ for (const media of input.media) {
+ const file = await input.readMedia(media);
+ const prepared = input.prepareFile ? await input.prepareFile(file) : file;
+ const resource = await input.uploadResource(created.memo.id, prepared);
+ markdown = markdown.replaceAll(`${WECHAT_MEDIA_URL_PREFIX}${media.id}`, resource.url);
+ }
+ if (markdown.includes(WECHAT_MEDIA_URL_PREFIX)) {
+ throw new Error("WeChat chat still contains an unresolved attachment");
+ }
+ return (await input.updateMemo(created.memo, noteContent(markdown))).memo;
+ } catch (error) {
+ await input.deleteMemo?.(created.memo.id).catch(() => undefined);
+ throw error;
+ }
+};
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index fb2e3cd8..3c7cabbf 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -85,6 +85,16 @@ interface EdgeEverDesktopBridge {
}) => void | Promise<void>): () => void;
onImportMarkdown(callback: (payload: { name: string; content: string }) => void): () => void;
onImportScreenshot?(callback: (payload: { captureId?: string; name: string; type: string; title?: string; bytes: Uint8Array }) => void): () => void;
+ readWeChatImportMedia?(importId: string, mediaId: string): Promise<{ filename: string; mimeType: string; bytes: Uint8Array }>;
+ finishWeChatImport?(importId: string): Promise<void>;
+ onImportWeChatChat?(callback: (payload: {
+ ok: boolean;
+ reason?: string;
+ importId?: string;
+ title?: string;
+ markdown?: string;
+ media?: Array<{ id: string; filename: string; mimeType: string; byteSize: number }>;
+ }) => void): () => void;
}
interface DesktopUpdateStatus {
diff --git a/package.json b/package.json
index c3c3ca95..4bcec774 100644
--- a/package.json
+++ b/package.json
@@ -63,7 +63,7 @@
"release": "bun scripts/release.mjs",
"publish:stores": "bun scripts/store-delivery.mjs",
"test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs",
- "test:desktop": "bun test apps/desktop/src/main/account-scope.test.mjs apps/desktop/src/main/app-protocol.test.mjs apps/desktop/src/main/child-process-start.test.mjs apps/desktop/src/main/clipboard-write.test.mjs apps/desktop/src/main/desktop-diagnostics.test.mjs apps/desktop/src/main/desktop-menu.test.mjs apps/desktop/src/main/desktop-update-flow.test.mjs apps/desktop/src/main/diagnostic-log.test.mjs apps/desktop/src/main/file-association.test.mjs apps/desktop/src/main/file-permissions.test.mjs apps/desktop/src/main/installation-location.test.mjs apps/desktop/src/main/local-data-reset.test.mjs apps/desktop/src/main/ai-direct.test.mjs apps/desktop/src/main/plugin-public-network.test.mjs apps/desktop/src/main/renderer-recovery.test.mjs apps/desktop/src/main/renderer-hibernate.test.mjs apps/desktop/src/main/renderer-startup-guard.test.mjs apps/desktop/src/main/renderer-storage-migration.test.mjs apps/desktop/src/main/resource-request.test.mjs apps/desktop/src/main/resource-url.test.mjs apps/desktop/src/main/scheduled-task-scheduler.test.mjs apps/desktop/src/main/screenshot-capture.test.mjs apps/desktop/src/main/staged-resource.test.mjs apps/desktop/src/main/tray-icon.test.mjs apps/desktop/src/main/user-data-directory.test.mjs apps/desktop/src/main/window-open-policy.test.mjs apps/desktop/src/main/window-visibility.test.mjs apps/desktop/src/main/windows-update-trust.test.mjs apps/web/src/lib/api.test.mjs apps/web/src/lib/app-page-path.test.mjs apps/web/src/lib/clipboard.test.mjs apps/web/src/lib/desktop-renderer-ready.test.mjs apps/web/src/lib/desktop-workspace-restore.test.mjs apps/web/src/lib/desktop-repository.test.mjs apps/web/src/lib/desktop-resources.test.mjs apps/web/src/lib/desktop-sync.test.mjs apps/web/src/lib/local-mirror.test.mjs apps/web/src/lib/repository.test.mjs apps/web/src/lib/runtime.test.mjs apps/web/src/lib/screenshot-import.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun run test:desktop:sidecar",
+ "test:desktop": "bun test apps/desktop/src/main/account-scope.test.mjs apps/desktop/src/main/app-protocol.test.mjs apps/desktop/src/main/child-process-start.test.mjs apps/desktop/src/main/clipboard-write.test.mjs apps/desktop/src/main/desktop-diagnostics.test.mjs apps/desktop/src/main/desktop-menu.test.mjs apps/desktop/src/main/desktop-update-flow.test.mjs apps/desktop/src/main/diagnostic-log.test.mjs apps/desktop/src/main/file-association.test.mjs apps/desktop/src/main/wechat-chat-archive.test.mjs apps/desktop/src/main/wechat-share-import.test.mjs apps/desktop/src/main/file-permissions.test.mjs apps/desktop/src/main/installation-location.test.mjs apps/desktop/src/main/local-data-reset.test.mjs apps/desktop/src/main/ai-direct.test.mjs apps/desktop/src/main/plugin-public-network.test.mjs apps/desktop/src/main/renderer-recovery.test.mjs apps/desktop/src/main/renderer-hibernate.test.mjs apps/desktop/src/main/renderer-startup-guard.test.mjs apps/desktop/src/main/renderer-storage-migration.test.mjs apps/desktop/src/main/resource-request.test.mjs apps/desktop/src/main/resource-url.test.mjs apps/desktop/src/main/scheduled-task-scheduler.test.mjs apps/desktop/src/main/screenshot-capture.test.mjs apps/desktop/src/main/staged-resource.test.mjs apps/desktop/src/main/tray-icon.test.mjs apps/desktop/src/main/user-data-directory.test.mjs apps/desktop/src/main/window-open-policy.test.mjs apps/desktop/src/main/window-visibility.test.mjs apps/desktop/src/main/windows-update-trust.test.mjs apps/web/src/lib/api.test.mjs apps/web/src/lib/app-page-path.test.mjs apps/web/src/lib/clipboard.test.mjs apps/web/src/lib/desktop-renderer-ready.test.mjs apps/web/src/lib/desktop-workspace-restore.test.mjs apps/web/src/lib/desktop-repository.test.mjs apps/web/src/lib/desktop-resources.test.mjs apps/web/src/lib/desktop-sync.test.mjs apps/web/src/lib/local-mirror.test.mjs apps/web/src/lib/repository.test.mjs apps/web/src/lib/runtime.test.mjs apps/web/src/lib/screenshot-import.test.mjs apps/web/src/lib/wechat-chat-import.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun run test:desktop:sidecar",
"verify:desktop-renderer": "bun scripts/verify-desktop-renderer.mjs",
"verify:renderer-origin-migration": "bun run --cwd apps/desktop verify-origin-migration",
"verify:desktop-cross-version-startup": "bun scripts/verify-desktop-cross-version-startup.mjs",
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 6adb7f7d..dfd2165f 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1506,6 +1506,9 @@ export const enUS = {
importScreenshotFailedTitle: "Could not save screenshot to note",
importScreenshotEmpty: "The screenshot image was empty. Try capturing again, and allow Screen Recording for EdgeEver in System Settings if this is the first time.",
importScreenshotFailed: "Couldn't save the screenshot as a note. Check the connection and try again.",
+ importWeChatFailedTitle: "Could not save the WeChat chat",
+ importWeChatUnrecognized: "This archive is not a WeChat chat export.",
+ importWeChatFailed: "Couldn't save the chat as a note. Try again.",
loadingMore: "Loading more notes",
openMemo: "Open note",
unpin: "Unpin",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 066072dd..f61dd3a8 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -1506,6 +1506,9 @@ export const ja = {
importScreenshotFailedTitle: "スクリーンショットをノートに保存できませんでした",
importScreenshotEmpty: "スクリーンショット画像が空でした。もう一度撮影してください。初めて使う場合は、システム設定で EdgeEver の画面収録を許可してください。",
importScreenshotFailed: "スクリーンショットをノートとして保存できませんでした。接続を確認して再試行してください。",
+ importWeChatFailedTitle: "WeChat のチャットを保存できませんでした",
+ importWeChatUnrecognized: "このアーカイブは WeChat のチャット書き出しではありません。",
+ importWeChatFailed: "チャットをノートとして保存できませんでした。再試行してください。",
loadingMore: "さらにノートを読み込み中",
openMemo: "ノートを開く",
unpin: "ピン留めを外す",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 33b64029..7fa4a845 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -1506,6 +1506,9 @@ export const zhCN = {
importScreenshotFailedTitle: "无法将截图保存到笔记",
importScreenshotEmpty: "截图图片为空。请重新截取;若是第一次使用,请在系统设置中允许 EdgeEver 使用屏幕录制。",
importScreenshotFailed: "无法将截图保存为笔记。请检查网络后重试。",
+ importWeChatFailedTitle: "无法保存微信聊天记录",
+ importWeChatUnrecognized: "这个压缩包不是微信导出的聊天记录。",
+ importWeChatFailed: "无法把聊天记录保存为笔记。请重试。",
loadingMore: "正在加载更多笔记",
openMemo: "打开笔记",
unpin: "取消置顶",
diff --git a/scripts/build-macos-share-extension.sh b/scripts/build-macos-share-extension.sh
new file mode 100755
index 00000000..05b92c65
--- /dev/null
+++ b/scripts/build-macos-share-extension.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# Build the macOS share extension that receives WeChat's merged-forward ZIP.
+set -euo pipefail
+
+root="$(cd "$(dirname "$0")/.." && pwd)"
+source_directory="$root/apps/desktop/share-extension"
+version="$(node -e "console.log(require('$root/apps/desktop/package.json').version)")"
+arch="${EDGE_EVER_DESKTOP_ARCH:-}"
+if [[ -z "$arch" ]]; then
+ case "$(uname -m)" in
+ arm64) arch="arm64" ;;
+ x86_64) arch="x64" ;;
+ *) echo "Unsupported Mac architecture: $(uname -m)" >&2; exit 1 ;;
+ esac
+fi
+case "$arch" in
+ arm64) target="arm64-apple-macos13.0" ;;
+ x64) target="x86_64-apple-macos13.0" ;;
+ *) echo "EDGE_EVER_DESKTOP_ARCH must be arm64 or x64, received: $arch" >&2; exit 1 ;;
+esac
+
+sdk="$(xcrun --sdk macosx --show-sdk-path)"
+appex="$source_directory/dist/EdgeEverShare.appex"
+rm -rf "$appex"
+mkdir -p "$appex/Contents/MacOS"
+sed \
+ -e "s/__MARKETING_VERSION__/${version}/g" \
+ -e "s/__BUILD_VERSION__/${version}/g" \
+ "$source_directory/Info.plist" > "$appex/Contents/Info.plist"
+swiftc \
+ -O \
+ -target "$target" \
+ -sdk "$sdk" \
+ -module-name EdgeEverShare \
+ -emit-executable \
+ -o "$appex/Contents/MacOS/EdgeEverShare" \
+ "$source_directory/ShareViewController.swift"
+chmod 755 "$appex/Contents/MacOS/EdgeEverShare"
+codesign \
+ --force \
+ --sign - \
+ --entitlements "$source_directory/EdgeEverShare.entitlements" \
+ --generate-entitlement-der \
+ "$appex"
+echo "Built $appex ($target)"
diff --git a/scripts/desktop-build-workflow.test.mjs b/scripts/desktop-build-workflow.test.mjs
index 9872fa66..57d8a8e7 100644
--- a/scripts/desktop-build-workflow.test.mjs
+++ b/scripts/desktop-build-workflow.test.mjs
@@ -28,6 +28,8 @@ describe("desktop release workflow", () => {
].join("\n"));
expect(desktopBuilderConfig).toContain("schemes:\n - edgeever");
expect(desktopBuilderConfig).not.toContain("edgeever-app");
+ expect(desktopBuilderConfig).toContain("PlugIns/EdgeEverShare.appex");
+ expect(desktopBuilderConfig).toContain("afterSign: ./scripts/sign-share-extension.cjs");
});
test("gates Draft release assets on the full project suite in Ubuntu", () => {
@@ -124,6 +126,8 @@ describe("desktop release workflow", () => {
expect(packagedStartupVerifier).toContain('"renderer.origin-ready"');
expect(packagedStartupVerifier).toContain('startsWith("edgeever-app://app/")');
expect(desktopPackageVerifier).toContain("isVisualCppRuntimeDll");
+ expect(desktopPackageVerifier).toContain("EdgeEverShare.appex");
+ expect(desktopPackageVerifier).toContain("com\\.apple\\.share-services");
expect(cargoConfig).toContain('target.x86_64-pc-windows-msvc');
expect(cargoConfig).toContain('target-feature=+crt-static');
expect(desktopBuilderConfig).toContain([
diff --git a/scripts/run-desktop-builder.mjs b/scripts/run-desktop-builder.mjs
index 46201999..836d619f 100644
--- a/scripts/run-desktop-builder.mjs
+++ b/scripts/run-desktop-builder.mjs
@@ -31,6 +31,15 @@ for (const key of [
}
environment.CSC_IDENTITY_AUTO_DISCOVERY ||= "false";
+if (requestedTarget === "mac") {
+ const shareExtension = spawnSync("bash", ["scripts/build-macos-share-extension.sh"], {
+ env: environment,
+ stdio: "inherit",
+ });
+ if (shareExtension.error) throw shareExtension.error;
+ if ((shareExtension.status ?? 1) !== 0) process.exit(shareExtension.status ?? 1);
+}
+
const builderArgs = [
"run",
"--cwd",
diff --git a/scripts/verify-desktop-package.mjs b/scripts/verify-desktop-package.mjs
index fd0564d5..e7f4bd13 100644
--- a/scripts/verify-desktop-package.mjs
+++ b/scripts/verify-desktop-package.mjs
@@ -93,6 +93,12 @@ if (requestedPlatform === "darwin") {
assert.ok(existsSync(sidecar), `macOS app bundle is missing the sidecar: ${sidecar}`);
verifyMachOArch(executable, requestedArch, "Electron executable");
verifyMachOArch(sidecar, requestedArch, "Rust sidecar");
+ const shareExtension = join(unpackedApp, "Contents", "PlugIns", "EdgeEverShare.appex", "Contents", "MacOS", "EdgeEverShare");
+ assert.ok(existsSync(shareExtension), `macOS app bundle is missing the WeChat share extension: ${shareExtension}`);
+ verifyMachOArch(shareExtension, requestedArch, "WeChat share extension");
+ const shareExtensionInfo = readFileSync(join(unpackedApp, "Contents", "PlugIns", "EdgeEverShare.appex", "Contents", "Info.plist"), "utf8");
+ assert.match(shareExtensionInfo, /com\.apple\.share-services/, "WeChat share extension must register a share service");
+ assert.match(shareExtensionInfo, /NSExtensionActivationSupportsFileWithMaxCount/, "WeChat share extension must accept shared files");
const asarPath = join(appResources, "app.asar");
assert.ok(existsSync(asarPath), `macOS app bundle is missing app.asar: ${asarPath}`);
const asarFiles = listAsarFiles(asarPath);