Skip to content

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

feat: add optional desktop PicGo image uploads

tianma-if435376ca568b
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index fddb5916..c75b5ce9 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -51,6 +51,7 @@ import electronUpdater from "electron-updater";
import { createUpdateDiagnostic } from "./update-diagnostics.mjs";
import { normalizeUpdateProgress } from "./update-progress.mjs";
import { inspectWindowsTaskbarShortcuts } from "./windows-taskbar-diagnostics.mjs";
+import { testPicGoConnection, createPicGoUploadQueue } from "./picgo.mjs";
import { createPluginPublicNetworkRuntime } from "./plugin-public-network.mjs";
import { createAiDirectRuntime } from "./ai-direct.mjs";
import { createAcpHostRuntime, registerAcpIpc } from "./acp-host.mjs";
@@ -1722,6 +1723,27 @@ const startApplication = async () => {
await saveDesktopSessionToken("");
return { stored: false };
});
+ ipcMain.handle("desktop:picgo-test", (event, endpoint) => {
+ if (event.sender !== mainWindow?.webContents) throw new Error("PicGo requests must come from the main window");
+ return testPicGoConnection(endpoint);
+ });
+ // Serialize uploads and error dialogs across rapid pastes and multi-image batches.
+ const queuePicGoUpload = createPicGoUploadQueue({
+ isActive: () => Boolean(mainWindow && !mainWindow.webContents.isDestroyed()),
+ chooseFailure: async (input) => {
+ const copy = input.copy;
+ const { response } = await dialog.showMessageBox(mainWindow, {
+ type: "warning", title: copy.title, message: copy.message,
+ detail: String(input.filename), buttons: [copy.retry, copy.fallback, copy.cancel],
+ defaultId: 2, cancelId: 2, noLink: true,
+ });
+ return response;
+ },
+ });
+ ipcMain.handle("desktop:picgo-upload", (event, input) => {
+ if (event.sender !== mainWindow?.webContents) throw new Error("PicGo requests must come from the main window");
+ return queuePicGoUpload(input, () => event.sender === mainWindow?.webContents && !event.sender.isDestroyed());
+ });
ipcMain.handle("desktop:public-network-fetch", async (event, requestId, input) => {
if (event.sender !== mainWindow?.webContents) throw new Error("Public network requests must come from the main window");
return pluginPublicNetwork.fetch(requestId, input);
diff --git a/apps/desktop/src/main/picgo.mjs b/apps/desktop/src/main/picgo.mjs
new file mode 100644
index 00000000..d7b791cf
--- /dev/null
+++ b/apps/desktop/src/main/picgo.mjs
@@ -0,0 +1,86 @@
+// PicGo owns uploader credentials. This bridge only sends image bytes to its
+// local HTTP server; it never reads the clipboard or writes temporary files.
+export const normalizePicGoEndpoint = (value) => {
+ const url = new URL(value);
+ if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
+ || url.username || url.password || url.hash || url.search || url.pathname !== "/upload") {
+ throw new Error("Use a local PicGo address such as http://127.0.0.1:36677/upload");
+ }
+ return url;
+};
+
+const request = async (url, body, fetchImpl, timeoutMs) => {
+ const response = await fetchImpl(url, {
+ method: "POST", body, redirect: "error", signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!response.ok) throw new Error(`PicGo HTTP ${response.status}`);
+ const reader = response.body?.getReader();
+ if (!reader) throw new Error("PicGo returned an empty response");
+ const chunks = [];
+ let length = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ length += value.byteLength;
+ if (length > 65536) throw new Error("PicGo response is too large");
+ chunks.push(value);
+ }
+ } finally {
+ await reader.cancel().catch(() => {});
+ reader.releaseLock();
+ }
+ const bytes = new Uint8Array(length);
+ let offset = 0;
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
+ return JSON.parse(new TextDecoder().decode(bytes));
+};
+
+export const testPicGoConnection = async (endpoint, { fetchImpl = fetch, timeoutMs = 5000 } = {}) => {
+ const url = normalizePicGoEndpoint(endpoint);
+ url.pathname = "/heartbeat";
+ const data = await request(url, undefined, fetchImpl, timeoutMs);
+ if (data?.success !== true || data.result !== "alive") throw new Error("The local service did not identify itself as PicGo");
+ return true;
+};
+
+export const uploadPicGoImage = async (input, { fetchImpl = fetch, timeoutMs = 60000 } = {}) => {
+ const url = normalizePicGoEndpoint(input.endpoint);
+ const bytes = input.bytes;
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > 50 * 1024 * 1024
+ || typeof input.mimeType !== "string" || !input.mimeType.startsWith("image/")) {
+ throw new Error("PicGo requires an image of up to 50 MB");
+ }
+ const form = new FormData();
+ form.append("files", new Blob([bytes], { type: input.mimeType }), String(input.filename || "image.png"));
+ const data = await request(url, form, fetchImpl, timeoutMs);
+ if (data?.success !== true || !Array.isArray(data.result) || data.result.length !== 1) {
+ throw new Error("PicGo did not return an uploaded image URL");
+ }
+ const result = new URL(data.result[0]);
+ if (!["http:", "https:"].includes(result.protocol) || result.username || result.password) {
+ throw new Error("PicGo returned an invalid image URL");
+ }
+ return { url: result.href };
+};
+
+export const createPicGoUploadQueue = ({ upload = uploadPicGoImage, chooseFailure, isActive }) => {
+ let queue = Promise.resolve();
+ return (input, isRequestActive = isActive) => {
+ const run = async () => {
+ while (true) {
+ if (!isRequestActive()) throw new Error("The editor closed");
+ try { return await upload(input); }
+ catch {
+ if (!isRequestActive()) throw new Error("The editor closed");
+ const response = await chooseFailure(input);
+ if (response === 1) return { fallback: true };
+ if (response !== 0) throw new Error("PicGo upload cancelled");
+ }
+ }
+ };
+ const pending = queue.then(run);
+ queue = pending.catch(() => {});
+ return pending;
+ };
+};
diff --git a/apps/desktop/src/main/picgo.test.mjs b/apps/desktop/src/main/picgo.test.mjs
new file mode 100644
index 00000000..0a0e3135
--- /dev/null
+++ b/apps/desktop/src/main/picgo.test.mjs
@@ -0,0 +1,98 @@
+import { afterEach, expect, test } from "bun:test";
+import { createPicGoUploadQueue, normalizePicGoEndpoint, testPicGoConnection, uploadPicGoImage } from "./picgo.mjs";
+
+const servers = [];
+afterEach(() => { for (const server of servers.splice(0)) server.stop(true); });
+const serve = (handler) => {
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler });
+ servers.push(server);
+ return `http://127.0.0.1:${server.port}/upload`;
+};
+const image = (endpoint) => ({ endpoint, filename: "截图.png", mimeType: "image/png", bytes: new Uint8Array([137, 80, 78, 71]) });
+
+test("connection check uses heartbeat and never uploads or reads the clipboard", async () => {
+ const requests = [];
+ const endpoint = serve(async (request) => {
+ requests.push([new URL(request.url).pathname, request.method, await request.text()]);
+ return Response.json({ success: true, result: "alive" });
+ });
+ expect(await testPicGoConnection(endpoint)).toBe(true);
+ expect(requests).toEqual([["/heartbeat", "POST", ""]]);
+});
+
+test("sends captured image bytes using PicGo multipart protocol and preserves returned URL", async () => {
+ const endpoint = serve(async (request) => {
+ expect(new URL(request.url).pathname).toBe("/upload");
+ const form = await request.formData();
+ const file = form.get("files");
+ expect(file.name).toBe("截图.png");
+ expect(file.type).toBe("image/png");
+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(image("").bytes);
+ return Response.json({ success: true, result: ["https://images.example.com/picture.png?q=a%20b"] });
+ });
+ expect(await uploadPicGoImage(image(endpoint))).toEqual({ url: "https://images.example.com/picture.png?q=a%20b" });
+});
+
+test("rejects wrong services, failed uploads and unsafe or ambiguous URLs", async () => {
+ const wrong = serve(() => Response.json({ ok: true }));
+ await expect(testPicGoConnection(wrong)).rejects.toThrow();
+ for (const response of [
+ { success: false, result: [] },
+ { success: true, result: ["javascript:alert(1)"] },
+ { success: true, result: ["https://user:[email protected]/image.png"] },
+ { success: true, result: [null] },
+ { success: true, result: ["https://example.com/a", "https://example.com/b"] },
+ ]) {
+ await expect(uploadPicGoImage(image(serve(() => Response.json(response))))).rejects.toThrow();
+ }
+});
+
+test("only accepts local upload endpoints and image bytes", async () => {
+ for (const endpoint of ["https://example.com/upload", "http://192.168.0.1/upload", "http://127.0.0.1/other", "http://user:pass@localhost/upload", "http://localhost/upload?secret=foo", "http://localhost/upload#foo"]) {
+ expect(() => normalizePicGoEndpoint(endpoint)).toThrow();
+ }
+ expect(normalizePicGoEndpoint("http://[::1]:36677/upload").hostname).toBe("[::1]");
+ const endpoint = serve(() => { throw new Error("Should not send non-images"); });
+ await expect(uploadPicGoImage({ ...image(endpoint), mimeType: "application/pdf" })).rejects.toThrow();
+ await expect(uploadPicGoImage({ ...image(endpoint), bytes: new Uint8Array() })).rejects.toThrow();
+});
+
+test("does not follow redirects or wait indefinitely", async () => {
+ let reached = false;
+ const target = serve(() => { reached = true; return Response.json({ success: true, result: ["https://example.com/a"] }); });
+ await expect(uploadPicGoImage(image(serve(() => Response.redirect(target))))).rejects.toThrow();
+ expect(reached).toBe(false);
+ const slow = serve(async () => { await new Promise((resolve) => setTimeout(resolve, 80)); return Response.json({ success: true, result: "alive" }); });
+ await expect(testPicGoConnection(slow, { timeoutMs: 10 })).rejects.toThrow();
+});
+
+test("retries only on explicit choice, serializes batches and recovers after cancellation", async () => {
+ const calls = [];
+ const choices = [0, 1, 2];
+ const upload = createPicGoUploadQueue({
+ isActive: () => true,
+ upload: async (input) => {
+ calls.push(input);
+ await Promise.resolve();
+ if (input !== "success") throw new Error("Unavailable");
+ return { url: "https://example.com/image.png" };
+ },
+ chooseFailure: async () => choices.shift(),
+ });
+ const first = upload("fallback");
+ const second = upload("cancel");
+ const third = upload("success");
+ expect(await first).toEqual({ fallback: true });
+ await expect(second).rejects.toThrow("cancelled");
+ expect(await third).toEqual({ url: "https://example.com/image.png" });
+ expect(calls).toEqual(["fallback", "fallback", "cancel", "success"]);
+});
+
+test("closed editor stops queued work before uploading or prompting", async () => {
+ const upload = createPicGoUploadQueue({
+ isActive: () => false,
+ upload: () => { throw new Error("Must not upload"); },
+ chooseFailure: () => { throw new Error("Must not prompt"); },
+ });
+ await expect(upload(image(""))).rejects.toThrow("editor closed");
+});
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index 9dd1d587..de405251 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -42,6 +42,8 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
copyImage: (bytes) => ipcRenderer.invoke("desktop:copy-image", bytes),
setSessionToken: (value) => ipcRenderer.invoke("desktop:set-session-token", value),
clearSessionToken: () => ipcRenderer.invoke("desktop:clear-session-token"),
+ testPicGoConnection: (endpoint) => ipcRenderer.invoke("desktop:picgo-test", endpoint),
+ uploadPicGoImage: (input) => ipcRenderer.invoke("desktop:picgo-upload", input),
publicNetworkFetch: (requestId, input) => ipcRenderer.invoke("desktop:public-network-fetch", requestId, input),
cancelPublicNetworkFetch: async (requestId) => { ipcRenderer.send("desktop:cancel-public-network-fetch", requestId); },
openAiProviderStream: (requestId, input) => ipcRenderer.invoke("desktop:ai-direct-open", requestId, input),
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index c322e74f..392fd238 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -161,6 +161,7 @@ import { NEW_IMAGE_WIDTH_PERCENT } from "@edgeever/shared/image-display";
import { EdgeEverLink } from "@edgeever/shared/editor-link";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
import { codeBlockLowlight, EdgeEverCodeBlock } from "@/lib/code-block";
+import { shouldUploadWithPicGo, uploadImageWithPicGo } from "@/lib/picgo";
import { compressImageForUpload } from "@/lib/image-compression";
import { LOCAL_DATABASE_INTERRUPTED_EVENT, localDb, selectNewestLocalDraft, type MemoUpdateSyncPayload } from "@/lib/local-db";
import { persistEmergencyDraft, readEmergencyDraft, removeEmergencyDraft } from "@/lib/emergency-draft";
@@ -992,6 +993,18 @@ const RichEditorPane = ({
}, [focusMobileInputTarget, isMobileViewport, memo?.id, mobileDefaultEditMemoId, onMobileDefaultEditConsumed, readOnly]);
const uploadEditorResource = useCallback(async (targetMemoId: string, uploadFile: File, isImage: boolean) => {
+ if (isImage && shouldUploadWithPicGo()) {
+ const instanceKey = editorInstanceMemoIdentityRef.current.instanceKey;
+ const external = await uploadImageWithPicGo(uploadFile, {
+ title: t("settings.picgo.failedTitle"), message: t("settings.picgo.failedMessage"),
+ retry: t("settings.picgo.retry"), fallback: t("settings.picgo.fallback"), cancel: t("settings.picgo.cancel"),
+ });
+ // PicGo or its failure dialog may outlive the original note/instance.
+ if (memoRef.current?.id !== targetMemoId || editorInstanceMemoIdentityRef.current.instanceKey !== instanceKey) {
+ throw new Error("The active note changed during image upload");
+ }
+ if (external) return external;
+ }
try {
const resource = (await repository.uploadMemoResource(targetMemoId, uploadFile)).resource;
return { ...resource, url: toDesktopResourceUrl(resource.url) };
@@ -1022,7 +1035,7 @@ const RichEditorPane = ({
url: `edgeever-staged://${staged.id}`,
};
}
- }, [repository]);
+ }, [repository, t]);
const insertResourceFiles = useCallback((files: File[]) => {
const currentMemo = memoRef.current;
diff --git a/apps/web/src/components/settings/PicGoSettingsItem.tsx b/apps/web/src/components/settings/PicGoSettingsItem.tsx
new file mode 100644
index 00000000..38c2c530
--- /dev/null
+++ b/apps/web/src/components/settings/PicGoSettingsItem.tsx
@@ -0,0 +1,81 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Image } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { hasPicGoBridge, readPicGoPreference, writePicGoPreference, type PicGoPreference } from "@/lib/picgo";
+import { SETTINGS_ITEM_DESCRIPTION_CLASSNAME, SETTINGS_ITEM_TITLE_CLASSNAME } from "./settings-ui";
+
+export const PicGoSettingsItem = () => {
+ const { t } = useTranslation();
+ const [saved, setSaved] = useState(readPicGoPreference);
+ const [draft, setDraft] = useState(saved);
+ const [testedEndpoint, setTestedEndpoint] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [status, setStatus] = useState("");
+ const desktopAvailable = hasPicGoBridge();
+ const dirty = draft.provider !== saved.provider || draft.endpoint !== saved.endpoint;
+ const canSave = dirty && (draft.provider === "edgeever" || (desktopAvailable && testedEndpoint === draft.endpoint));
+
+ const testConnection = async () => {
+ setBusy(true);
+ setTestedEndpoint(null);
+ setStatus("");
+ try {
+ await window.edgeeverDesktop!.testPicGoConnection(draft.endpoint);
+ setTestedEndpoint(draft.endpoint);
+ setStatus(t("settings.picgo.connected"));
+ } catch {
+ setStatus(t("settings.picgo.connectionFailed"));
+ } finally { setBusy(false); }
+ };
+ const save = () => {
+ try {
+ writePicGoPreference(draft);
+ setSaved(draft);
+ setStatus(t("settings.picgo.saved"));
+ } catch { setStatus(t("settings.picgo.saveFailed")); }
+ };
+
+ return (
+ <div className="grid gap-3 px-4 py-3">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex min-w-0 items-center gap-3">
+ <Image className="h-4 w-4 shrink-0 text-slate-500" />
+ <div className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.title")}</div>
+ </div>
+ <Select value={draft.provider} disabled={busy} onValueChange={(provider) => {
+ setDraft({ ...draft, provider: provider as PicGoPreference["provider"] });
+ setStatus("");
+ }}>
+ <SelectTrigger className="h-9 w-full sm:w-80" aria-label={t("settings.picgo.title")}><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="edgeever">{t("settings.picgo.builtin")}</SelectItem>
+ <SelectItem value="picgo">PicGo</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ {draft.provider === "picgo" ? (
+ <div className="grid gap-2 sm:ml-7">
+ {!desktopAvailable ? <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.webPreview")}</p> : null}
+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.description")}</p>
+ <label htmlFor="picgo-endpoint" className={SETTINGS_ITEM_TITLE_CLASSNAME}>{t("settings.picgo.endpoint")}</label>
+ <Input id="picgo-endpoint" value={draft.endpoint} disabled={busy} onChange={(event) => {
+ setDraft({ ...draft, endpoint: event.target.value.trim() });
+ setTestedEndpoint(null);
+ setStatus("");
+ }} spellCheck={false} />
+ <p className={SETTINGS_ITEM_DESCRIPTION_CLASSNAME}>{t("settings.picgo.externalImages")}</p>
+ </div>
+ ) : null}
+ <div className="flex flex-wrap items-center gap-2 sm:ml-7">
+ {draft.provider === "picgo" ? <Button variant="outline" size="sm" disabled={busy || !desktopAvailable} onClick={() => void testConnection()}>
+ {t(busy ? "settings.picgo.testing" : "settings.picgo.test")}
+ </Button> : null}
+ {dirty ? <Button size="sm" disabled={busy || !canSave} onClick={save}>{t("settings.picgo.save")}</Button> : null}
+ <span role="status" className="text-xs text-slate-500">{status}</span>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/src/components/settings/PreferenceCard.tsx b/apps/web/src/components/settings/PreferenceCard.tsx
index 56aa7122..84e57f86 100644
--- a/apps/web/src/components/settings/PreferenceCard.tsx
+++ b/apps/web/src/components/settings/PreferenceCard.tsx
@@ -49,6 +49,7 @@ import {
import { applyUiFontPreference, readUiFontPreference, writeUiFontPreference } from "@/lib/ui-font";
import { syncPublishedNoteBodyFont } from "@/lib/published-note-body-font";
import { useShowDescendantNotesPreference, writeShowDescendantNotesPreference } from "@/lib/descendant-notes-preference";
+import { PicGoSettingsItem } from "./PicGoSettingsItem";
import { NoteProseCssEditor } from "./NoteProseCssEditor";
import { NoteProseCssPreview } from "./NoteProseCssPreview";
@@ -558,6 +559,7 @@ export const PreferenceCard = ({
</PreferenceSection>
<PreferenceSection title={t("settings.groups.editing")}>
+ <PicGoSettingsItem />
<div className="flex min-h-16 flex-col items-start gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="flex min-w-0 items-center gap-3">
<Image className="h-4 w-4 shrink-0 text-slate-500" />
diff --git a/apps/web/src/lib/picgo.test.mjs b/apps/web/src/lib/picgo.test.mjs
new file mode 100644
index 00000000..6b9dc0f1
--- /dev/null
+++ b/apps/web/src/lib/picgo.test.mjs
@@ -0,0 +1,57 @@
+import { afterEach, expect, test } from "bun:test";
+import { PICGO_STORAGE_KEY, DEFAULT_PICGO_ENDPOINT, readPicGoPreference, shouldUploadWithPicGo, uploadImageWithPicGo, writePicGoPreference } from "./picgo.ts";
+
+const previousWindow = globalThis.window;
+afterEach(() => {
+ if (previousWindow === undefined) delete globalThis.window;
+ else globalThis.window = previousWindow;
+});
+const setup = (upload) => {
+ const storage = new Map();
+ globalThis.window = {
+ localStorage: { getItem: (key) => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, value) },
+ edgeeverDesktop: upload ? { uploadPicGoImage: upload, testPicGoConnection: async () => true } : undefined,
+ };
+ return storage;
+};
+const copy = { title: "Failed", message: "Retry?", retry: "Retry", fallback: "EdgeEver", cancel: "Cancel" };
+const file = () => new File([new Uint8Array([137, 80, 78, 71])], "image.png", { type: "image/png" });
+
+test("default, corrupt settings and ordinary Web runtime retain attachment uploads", async () => {
+ const storage = setup();
+ expect(readPicGoPreference()).toEqual({ provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT });
+ storage.set(PICGO_STORAGE_KEY, "corrupt");
+ expect(shouldUploadWithPicGo()).toBe(false);
+ writePicGoPreference({ provider: "picgo", endpoint: DEFAULT_PICGO_ENDPOINT });
+ expect(shouldUploadWithPicGo()).toBe(false);
+ expect(await uploadImageWithPicGo(file(), copy)).toBeNull();
+});
+
+test("configured but disabled PicGo never sends an image", async () => {
+ setup(() => { throw new Error("Should not upload"); });
+ writePicGoPreference({ provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT });
+ expect(shouldUploadWithPicGo()).toBe(false);
+ expect(await uploadImageWithPicGo(file(), copy)).toBeNull();
+});
+
+test("enabled PicGo passes actual bytes and returns an external image for either editor mode", async () => {
+ setup(async (input) => {
+ expect(input.endpoint).toBe(DEFAULT_PICGO_ENDPOINT);
+ expect(input.bytes).toEqual(new Uint8Array([137, 80, 78, 71]));
+ expect(input.copy).toEqual(copy);
+ return { url: "https://images.example.com/image.png" };
+ });
+ writePicGoPreference({ provider: "picgo", endpoint: DEFAULT_PICGO_ENDPOINT });
+ expect(shouldUploadWithPicGo()).toBe(true);
+ expect(await uploadImageWithPicGo(file(), copy)).toEqual({
+ kind: "image", url: "https://images.example.com/image.png", filename: "image.png", mimeType: "image/png", byteSize: 4,
+ });
+});
+
+test("only explicit fallback returns to attachment storage; cancellation stays a failure", async () => {
+ setup(async () => ({ fallback: true }));
+ writePicGoPreference({ provider: "picgo", endpoint: DEFAULT_PICGO_ENDPOINT });
+ expect(await uploadImageWithPicGo(file(), copy)).toBeNull();
+ window.edgeeverDesktop.uploadPicGoImage = async () => { throw new Error("Cancelled"); };
+ await expect(uploadImageWithPicGo(file(), copy)).rejects.toThrow("Cancelled");
+});
diff --git a/apps/web/src/lib/picgo.ts b/apps/web/src/lib/picgo.ts
new file mode 100644
index 00000000..4907266d
--- /dev/null
+++ b/apps/web/src/lib/picgo.ts
@@ -0,0 +1,35 @@
+export const PICGO_STORAGE_KEY = "edgeever.desktop.picgo.v1";
+export const DEFAULT_PICGO_ENDPOINT = "http://127.0.0.1:36677/upload";
+export type PicGoPreference = { provider: "edgeever" | "picgo"; endpoint: string };
+
+export const readPicGoPreference = (): PicGoPreference => {
+ const fallback: PicGoPreference = { provider: "edgeever", endpoint: DEFAULT_PICGO_ENDPOINT };
+ try {
+ const value = JSON.parse(window.localStorage.getItem(PICGO_STORAGE_KEY) ?? "null");
+ if (!value || typeof value.endpoint !== "string") return fallback;
+ return { provider: value.provider === "picgo" ? "picgo" : "edgeever", endpoint: value.endpoint };
+ } catch { return fallback; }
+};
+
+export const writePicGoPreference = (value: PicGoPreference) => {
+ // Fail visibly when persistence is unavailable; never claim a provider changed.
+ window.localStorage.setItem(PICGO_STORAGE_KEY, JSON.stringify(value));
+};
+
+export const hasPicGoBridge = () => Boolean(window.edgeeverDesktop?.uploadPicGoImage && window.edgeeverDesktop?.testPicGoConnection);
+
+export const shouldUploadWithPicGo = () => hasPicGoBridge() && readPicGoPreference().provider === "picgo";
+
+export type PicGoFailureCopy = { title: string; message: string; retry: string; fallback: string; cancel: string };
+
+export const uploadImageWithPicGo = async (file: File, copy: PicGoFailureCopy) => {
+ const preference = readPicGoPreference();
+ if (preference.provider !== "picgo" || !hasPicGoBridge()) return null;
+ const result = await window.edgeeverDesktop!.uploadPicGoImage({
+ endpoint: preference.endpoint, bytes: new Uint8Array(await file.arrayBuffer()),
+ filename: file.name, mimeType: file.type, copy,
+ });
+ return "url" in result ? {
+ kind: "image" as const, url: result.url, filename: file.name, mimeType: file.type, byteSize: file.size,
+ } : null;
+};
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 3704ebf9..4857a323 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -40,6 +40,11 @@ interface EdgeEverDesktopBridge {
copyImage(bytes: Uint8Array): Promise<boolean>;
setSessionToken(value: string): Promise<{ stored: boolean }>;
clearSessionToken(): Promise<{ stored: false }>;
+ testPicGoConnection(endpoint: string): Promise<boolean>;
+ uploadPicGoImage(input: {
+ endpoint: string; bytes: Uint8Array; filename: string; mimeType: string;
+ copy: import("@/lib/picgo").PicGoFailureCopy;
+ }): Promise<{ url: string } | { fallback: true }>;
publicNetworkFetch(requestId: string, input: import("@edgeever/shared").PluginPublicFetchRequest): Promise<import("@edgeever/shared").PluginPublicFetchResponse>;
cancelPublicNetworkFetch(requestId: string): Promise<void>;
openAiProviderStream(requestId: string, input: {
diff --git a/package.json b/package.json
index 029a00b9..ee07d985 100644
--- a/package.json
+++ b/package.json
@@ -64,7 +64,7 @@
"publish:stores": "bun scripts/store-delivery.mjs",
"publish:extension": "bun scripts/publish-web-clipper.mjs",
"test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs",
- "test:desktop": "bun test apps/desktop/src/main/global-shortcut.test.mjs 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/update-diagnostics.test.mjs apps/desktop/src/main/update-progress.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/share-extension-registration.test.mjs apps/desktop/src/main/windows-share-menu.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/staged-resource-alias.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/desktop/src/main/windows-taskbar-diagnostics.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-acp.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/shared-file-import.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun test --cwd apps/desktop src/main/acp-adapter-manager.test.mjs src/main/acp-host.test.mjs src/main/workbuddy-auth.test.mjs src/main/antigravity-proxy.test.mjs src/main/acp-mcp-bridge.test.mjs && bun run test:desktop:sidecar",
+ "test:desktop": "bun test apps/desktop/src/main/global-shortcut.test.mjs 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/update-diagnostics.test.mjs apps/desktop/src/main/update-progress.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/share-extension-registration.test.mjs apps/desktop/src/main/windows-share-menu.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/picgo.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/staged-resource-alias.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/desktop/src/main/windows-taskbar-diagnostics.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-acp.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/picgo.test.mjs apps/web/src/lib/screenshot-import.test.mjs apps/web/src/lib/wechat-chat-import.test.mjs apps/web/src/lib/shared-file-import.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun test --cwd apps/desktop src/main/acp-adapter-manager.test.mjs src/main/acp-host.test.mjs src/main/workbuddy-auth.test.mjs src/main/antigravity-proxy.test.mjs src/main/acp-mcp-bridge.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 5b9bbf1f..37e17f04 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -968,6 +968,26 @@ export const enUS = {
},
languageTitle: "Interface language",
systemLanguage: "Follow system",
+ picgo: {
+ webPreview: "Preview the PicGo configuration here. Image uploads currently require the desktop app. Test the connection and enable PicGo in EdgeEver for desktop.",
+ title: "Image upload destination",
+ builtin: "EdgeEver attachments (default)",
+ endpoint: "PicGo server address",
+ description: "Run PicGo 2.4.0 or later with its local server enabled. Images use the default image host configured in PicGo. This setting stays on this desktop.",
+ externalImages: "External images depend on your image host. EdgeEver does not store a backup of these images or guarantee offline access.",
+ test: "Test connection",
+ testing: "Testing…",
+ connected: "Connected to PicGo. You can now save this setting.",
+ connectionFailed: "Could not connect. Check the local address and that PicGo Server is enabled without authentication.",
+ save: "Save",
+ saved: "Saved",
+ saveFailed: "Could not save the setting.",
+ failedTitle: "PicGo upload failed",
+ failedMessage: "Check that PicGo is running and its image host is configured. Retrying may upload the image again.",
+ retry: "Retry",
+ fallback: "Save to EdgeEver",
+ cancel: "Cancel",
+ },
imageCompressionTitle: "Compress note images",
imageCompressionAria: "Compress note images",
showDescendantNotesTitle: "Show notes from sub-notebooks",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 6bdb0715..752dfee1 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -957,6 +957,26 @@ export const ja = {
},
languageTitle: "表示言語",
systemLanguage: "システムに合わせる",
+ picgo: {
+ webPreview: "ここでは PicGo の設定をプレビューできます。画像のアップロードは現在デスクトップ版のみ対応しています。EdgeEver デスクトップ版で接続をテストして有効にしてください。",
+ title: "画像のアップロード先",
+ builtin: "EdgeEver 添付ファイル(既定)",
+ endpoint: "PicGo サーバーアドレス",
+ description: "PicGo 2.4.0 以降を起動し、ローカルサーバーを有効にしてください。PicGo の既定の画像ホストを使用します。この設定はこのデスクトップにのみ保存されます。",
+ externalImages: "外部画像は画像ホストに依存します。EdgeEver はこれらの画像をバックアップせず、オフライン表示も保証しません。",
+ test: "接続テスト",
+ testing: "テスト中…",
+ connected: "PicGo に接続しました。設定を保存できます。",
+ connectionFailed: "接続できません。アドレスを確認し、PicGo サーバーを認証なしで有効にしてください。",
+ save: "保存",
+ saved: "保存しました",
+ saveFailed: "設定を保存できませんでした。",
+ failedTitle: "PicGo のアップロードに失敗しました",
+ failedMessage: "PicGo の起動と画像ホストの設定を確認してください。再試行すると画像が再度アップロードされる場合があります。",
+ retry: "再試行",
+ fallback: "EdgeEver に保存",
+ cancel: "キャンセル",
+ },
imageCompressionTitle: "ノート内の画像を圧縮",
imageCompressionAria: "ノート内の画像を圧縮する",
showDescendantNotesTitle: "サブノートブックのノートを表示",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 6a9e03d1..349490fb 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -957,6 +957,26 @@ export const pl = {
},
languageTitle: "Język interfejsu",
systemLanguage: "Zgodnie z systemem",
+ picgo: {
+ webPreview: "Tutaj możesz zobaczyć konfigurację PicGo. Przesyłanie obrazów wymaga obecnie aplikacji komputerowej. Przetestuj połączenie i włącz PicGo w EdgeEver na komputerze.",
+ title: "Miejsce przesyłania obrazów",
+ builtin: "Załączniki EdgeEver (domyślne)",
+ endpoint: "Adres serwera PicGo",
+ description: "Uruchom PicGo 2.4.0 lub nowszy i włącz lokalny serwer. Obrazy trafiają do domyślnego hostingu w PicGo. Ustawienie jest zapisane tylko na tym komputerze.",
+ externalImages: "Obrazy zewnętrzne zależą od hostingu. EdgeEver nie zapisuje ich kopii zapasowych ani nie gwarantuje dostępu offline.",
+ test: "Testuj połączenie",
+ testing: "Testowanie…",
+ connected: "Połączono z PicGo. Możesz zapisać ustawienie.",
+ connectionFailed: "Nie udało się połączyć. Sprawdź adres i włącz serwer PicGo bez uwierzytelniania.",
+ save: "Zapisz",
+ saved: "Zapisano",
+ saveFailed: "Nie udało się zapisać ustawienia.",
+ failedTitle: "Przesyłanie do PicGo nie powiodło się",
+ failedMessage: "Sprawdź, czy PicGo działa i hosting jest skonfigurowany. Ponowienie może przesłać obraz ponownie.",
+ retry: "Ponów",
+ fallback: "Zapisz w EdgeEver",
+ cancel: "Anuluj",
+ },
imageCompressionTitle: "Kompresuj obrazy w notatkach",
imageCompressionAria: "Kompresuj obrazy w notatkach",
showDescendantNotesTitle: "Pokazuj notatki z podnotatników",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 5b027461..bd53bef6 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -968,6 +968,26 @@ export const zhCN = {
},
languageTitle: "界面语言",
systemLanguage: "跟随系统",
+ picgo: {
+ webPreview: "此处可预览 PicGo 配置。图片上传目前仅支持桌面端,请在 EdgeEver 桌面端测试连接并启用。",
+ title: "图片上传方式",
+ builtin: "EdgeEver 附件(默认)",
+ endpoint: "PicGo 服务地址",
+ description: "请启动 PicGo 2.4.0 或更新版本并开启本地服务。图片使用 PicGo 配置的默认图床,此设置仅保存在这台桌面设备上。",
+ externalImages: "外链图片依赖图床持续可用,EdgeEver 不保存这些图片的备份,也不保证离线可用。",
+ test: "测试连接",
+ testing: "测试中…",
+ connected: "已连接 PicGo,可以保存设置。",
+ connectionFailed: "连接失败,请检查本地地址,确认 PicGo 服务已开启且未启用鉴权。",
+ save: "保存",
+ saved: "已保存",
+ saveFailed: "无法保存设置。",
+ failedTitle: "PicGo 上传失败",
+ failedMessage: "请检查 PicGo 是否运行及图床配置。重试可能会再次上传图片。",
+ retry: "重试",
+ fallback: "改存 EdgeEver",
+ cancel: "取消",
+ },
imageCompressionTitle: "压缩笔记内图片",
imageCompressionAria: "是否压缩笔记内图片",
showDescendantNotesTitle: "父笔记本中显示子笔记本笔记",