Skip to content

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

fix(desktop): recover WeChat shares when app handoff fails

tianma-ife351abcb79b2
diff --git a/apps/desktop/share-extension/ShareViewController.swift b/apps/desktop/share-extension/ShareViewController.swift
index c3337a8f..42c075cf 100644
--- a/apps/desktop/share-extension/ShareViewController.swift
+++ b/apps/desktop/share-extension/ShareViewController.swift
@@ -38,9 +38,10 @@ final class ShareViewController: NSViewController {
guard let url = shareURL(for: destination) else {
throw CocoaError(.fileWriteUnknown)
}
- guard let context = extensionContext, await context.open(url) else {
+ guard let context = extensionContext else {
throw CocoaError(.fileReadUnknown)
}
+ _ = NSWorkspace.shared.open(url)
context.completeRequest(returningItems: nil)
} catch {
extensionContext?.cancelRequest(withError: error)
@@ -83,6 +84,7 @@ final class ShareViewController: NSViewController {
try FileManager.default.createDirectory(at: batch, withIntermediateDirectories: true)
let filename = sanitizedFilename(provider.suggestedName)
let destination = batch.appendingPathComponent(filename, isDirectory: false)
+ let partial = batch.appendingPathComponent("\(filename).partial", isDirectory: false)
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
provider.loadFileRepresentation(forTypeIdentifier: type) { source, error in
guard let source else {
@@ -90,10 +92,8 @@ final class ShareViewController: NSViewController {
return
}
do {
- if FileManager.default.fileExists(atPath: destination.path) {
- try FileManager.default.removeItem(at: destination)
- }
- try FileManager.default.copyItem(at: source, to: destination)
+ try FileManager.default.copyItem(at: source, to: partial)
+ try FileManager.default.moveItem(at: partial, to: destination)
continuation.resume()
} catch {
continuation.resume(throwing: error)
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 1b6de6da..2ffa8e42 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -1838,6 +1838,10 @@ const startApplication = async () => {
handleOpenTarget(process.argv);
protocolUrlsReady = true;
while (pendingProtocolUrls.length > 0) handleProtocolUrl(pendingProtocolUrls.shift());
+ if (process.platform === "darwin" && app.isPackaged) {
+ void wechatShare().importPending();
+ setInterval(() => { void wechatShare().importPending(); }, 2_000).unref();
+ }
app.on("activate", () => {
if (!showWindow(mainWindow)) void createWindow();
void checkForDesktopUpdate("activate");
diff --git a/apps/desktop/src/main/wechat-share-import.mjs b/apps/desktop/src/main/wechat-share-import.mjs
index 3b350325..40ceeafb 100644
--- a/apps/desktop/src/main/wechat-share-import.mjs
+++ b/apps/desktop/src/main/wechat-share-import.mjs
@@ -73,6 +73,8 @@ export const createWeChatShareController = ({
writeDiagnostic = () => {},
}) => {
const sessions = new Map();
+ const inFlightPaths = new Set();
+ const completedPaths = new Set();
const finish = async (importId) => {
if (!SAFE_ID.test(importId || "")) return;
@@ -96,7 +98,8 @@ export const createWeChatShareController = ({
const importFromProtocolUrl = async (value) => {
const requestedPath = wechatImportFilePath(value);
- if (!requestedPath) return;
+ if (!requestedPath || inFlightPaths.has(requestedPath) || completedPaths.has(requestedPath)) return;
+ inFlightPaths.add(requestedPath);
onActivity();
const downloads = downloadsPath();
let zipPath = null;
@@ -130,6 +133,7 @@ export const createWeChatShareController = ({
}
sessions.set(importId, { directory, media });
preparedDirectory = null;
+ completedPaths.add(requestedPath);
sendToRenderer({
ok: true,
importId,
@@ -145,8 +149,25 @@ export const createWeChatShareController = ({
void writeDiagnostic("wechat-import.rejected", { reason });
} finally {
await removeImportedZip(zipPath, downloads);
+ inFlightPaths.delete(requestedPath);
}
};
- return { importFromProtocolUrl, readMedia, finish };
+ const importPending = async () => {
+ const root = incomingDirectory(downloadsPath());
+ const batches = await readdir(root, { withFileTypes: true }).catch(() => []);
+ for (const batch of batches) {
+ if (!batch.isDirectory()) continue;
+ const directory = join(root, batch.name);
+ const files = await readdir(directory, { withFileTypes: true }).catch(() => []);
+ for (const file of files) {
+ if (!file.isFile() || !file.name.toLowerCase().endsWith(".zip")) continue;
+ const url = new URL("edgeever://wechat-import");
+ url.searchParams.set("path", join(directory, file.name));
+ await importFromProtocolUrl(url.href);
+ }
+ }
+ };
+
+ return { importFromProtocolUrl, importPending, readMedia, finish };
};
diff --git a/apps/desktop/src/main/wechat-share-import.test.mjs b/apps/desktop/src/main/wechat-share-import.test.mjs
index b2afb5fc..77a5fa35 100644
--- a/apps/desktop/src/main/wechat-share-import.test.mjs
+++ b/apps/desktop/src/main/wechat-share-import.test.mjs
@@ -1,5 +1,5 @@
import { deflateRawSync } from "node:zlib";
-import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, rename, 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";
@@ -131,4 +131,30 @@ describe("WeChat share handoff", () => {
expect(sent[0]).toEqual({ ok: false, reason: "failed" });
expect((await readFile(outside)).toString()).toBe("secret");
});
+
+ test("picks up a completed share without a protocol URL and ignores a duplicate URL", async () => {
+ const root = await mkdtemp(join(tmpdir(), "edgeever-wechat-share-"));
+ roots.push(root);
+ const downloads = join(root, "Downloads");
+ const batch = join(downloads, WECHAT_INCOMING_DIRECTORY_NAME, "batch");
+ await mkdir(batch, { recursive: true });
+ const zipPath = join(batch, "聊天记录.zip");
+ const partialPath = `${zipPath}.partial`;
+ await writeFile(partialPath, zipOf("聊天记录.txt", "·鱼\n2026年9月22日 22:15\n你好\n", "附件/readme.txt", "hello"));
+ const sent = [];
+ const controller = createWeChatShareController({
+ downloadsPath: () => downloads,
+ tempPath: () => join(root, "temp"),
+ sendToRenderer: (payload) => sent.push(payload),
+ });
+ await controller.importPending();
+ expect(sent).toHaveLength(0);
+ await rename(partialPath, zipPath);
+ const url = `edgeever://wechat-import?path=${encodeURIComponent(zipPath)}`;
+ await Promise.all([controller.importPending(), controller.importFromProtocolUrl(url)]);
+ expect(sent).toHaveLength(1);
+ expect(sent[0].ok).toBe(true);
+ await controller.importFromProtocolUrl(url);
+ expect(sent).toHaveLength(1);
+ });
});