AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(extension): save a right-clicked X post as a new note
tianma-ifc85e365f8450
diff --git a/apps/extension/FIREFOX_STORE_LISTING.md b/apps/extension/FIREFOX_STORE_LISTING.mdindex 2923eab5..a7387986 100644--- a/apps/extension/FIREFOX_STORE_LISTING.md+++ b/apps/extension/FIREFOX_STORE_LISTING.md@@ -15,12 +15,13 @@ EdgeEver Web Clipper saves the current webpage, selected text, or a right-clicke- Extract readable article content or preserve the current selection.- Right-click an image and save that image file as a new note.+- On X, right-click a post and save its visible text and photos as one note.- Convert captured HTML to Markdown locally.- Choose a default EdgeEver notebook.- Send content directly to your instance without an EdgeEver-operated relay.- No advertising, analytics, tracking, or telemetry.-Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads and sends page content only after you click **Clip current page**.+Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads and sends page content only after you click **Clip current page**, **Save image to EdgeEver**, or **Save this post to EdgeEver**.## Data collection and transmission@@ -38,7 +39,8 @@ The project maintainers do not receive or retain this data. Instance settings ar4. Open a normal HTTP or HTTPS webpage.5. Open the extension, choose **Clip current page**, and verify that the success message appears.6. On a normal webpage, right-click an image, choose **Save image to EdgeEver**, and verify the new note contains the image.-7. Verify the created notes in the review EdgeEver instance.+7. Open one X post page, right-click the post, choose **Save this post to EdgeEver**, and verify the note contains the visible text and the post link.+8. Verify the created notes in the review EdgeEver instance.Restricted browser pages, extension stores, built-in PDF viewers, and other privileged pages cannot be captured.@@ -66,6 +68,7 @@ EdgeEver 网页裁剪插件可将当前网页、选中的文字,或右键选- 提取适合阅读的文章正文,也可只保存当前选区。- 在图片上右键,把图片文件存成一条新笔记。+- 在 X 上右键一条推文,把已经显示的文字和图片存成同一条笔记。- 在浏览器本地将 HTML 转换为 Markdown。- 可选择默认 EdgeEver 笔记本。- 数据直接发送到用户自己的实例,不经过 EdgeEver 中转服务。diff --git a/apps/extension/README.md b/apps/extension/README.mdindex afd7f10d..778b3c27 100644--- a/apps/extension/README.md+++ b/apps/extension/README.md@@ -9,6 +9,7 @@ Chrome, Edge, and Firefox Manifest V3 extension for saving the current webpage,- Click the extension action to capture the selected content, or extract the article body with Mozilla Readability when there is no selection.- Convert the extracted article HTML into Markdown with Turndown before uploading it.- Right-click an image and choose **Save image to EdgeEver**. The image file is uploaded into a new note in the default notebook, with the source page linked underneath.+- On X, right-click a post and choose **Save this post to EdgeEver**. The visible text, author, time, and photos already shown in that post are saved into one note. A single-post page can be saved immediately. On a timeline, the extension asks once for access to X so it can remember the post under the pointer.- When the page cannot hand over the image bytes, the extension asks once for access to that image's site. After that, later images from the same site save directly.- Create a searchable EdgeEver memo with the source URL and a `web-clip` tag.diff --git a/apps/extension/STORE_LISTING.md b/apps/extension/STORE_LISTING.mdindex cd973dd9..5f762141 100644--- a/apps/extension/STORE_LISTING.md+++ b/apps/extension/STORE_LISTING.md@@ -38,6 +38,7 @@ EdgeEver Web Clipper 可以把当前网页、你选中的内容,或右键选- 自动提取文章正文,并转换为便于搜索和编辑的 Markdown。- 优先保存你在页面中选中的内容。- 在图片上右键,选择“保存图片到 EdgeEver”,把图片文件存成一条新笔记。+- 在 X 上右键一条推文,选择“保存这条推文到 EdgeEver”,把已经显示的文字和图片存成同一条笔记。- 在笔记中保留原始标题、来源网址和剪藏时间。- 可选择默认笔记本,并自动添加 `web-clip` 标签。- 网页内容直接发送到你配置的 EdgeEver 实例,不经过开发者的中转服务器。@@ -61,6 +62,7 @@ Key features:- Extract article content automatically and convert it to searchable, editable Markdown.- Prefer content selected on the page when a selection is available.- Right-click an image and choose “Save image to EdgeEver” to store the image file as a new note.+- On X, right-click a post and choose “Save this post to EdgeEver” to store its visible text and photos in one note.- Preserve the original title, source URL, and clipping time in the note.- Select a default notebook and add the `web-clip` tag automatically.- Send webpage content directly to your configured EdgeEver instance without a developer-operated relay server.@@ -81,7 +83,7 @@ Save the current webpage, user-selected content, or a user-chosen image to the s- `contextMenus`: Add a Save image to EdgeEver item when the user right-clicks an image. It runs only after the user selects that item.- `scripting`: Inject the packaged capture script into the active page after the user initiates a capture.- `storage`: Store the user's EdgeEver instance URL, API token, and default notebook ID locally.-- Optional host permissions: Send API requests only to the EdgeEver instance origin the user approves. If a page cannot provide an image file, the extension can also ask for access to that image's site, or to all sites when the user explicitly chooses that option, and uses it only to download the image the user chose to save.+- Optional host permissions: Send API requests only to the EdgeEver instance origin the user approves. If a page cannot provide an image file, the extension can also ask for access to that image's site, or to all sites when the user explicitly chooses that option, and uses it only to download the image the user chose to save. Saving a post from an X timeline asks for access to X so the extension can remember which post was under the pointer. The script on X only records that target and runs after the user allows it.### Data disclosuresdiff --git a/apps/extension/manifest.base.json b/apps/extension/manifest.base.jsonindex 80883e66..99dcfbb9 100644--- a/apps/extension/manifest.base.json+++ b/apps/extension/manifest.base.json@@ -19,5 +19,18 @@},"default_popup": "popup.html"},- "options_page": "options.html"+ "options_page": "options.html",+ "content_scripts": [+ {+ "matches": [+ "https://x.com/*",+ "https://www.x.com/*",+ "https://twitter.com/*",+ "https://www.twitter.com/*",+ "https://mobile.twitter.com/*"+ ],+ "js": ["assets/tweet-target.js"],+ "run_at": "document_start"+ }+ ]}diff --git a/apps/extension/manifest.test.mjs b/apps/extension/manifest.test.mjsindex ebf45f94..4a8a994a 100644--- a/apps/extension/manifest.test.mjs+++ b/apps/extension/manifest.test.mjs@@ -19,6 +19,19 @@ describe("extension manifests", () => {"http://localhost/*","http://127.0.0.1/*",]);+ expect(manifest.content_scripts).toEqual([+ {+ matches: [+ "https://x.com/*",+ "https://www.x.com/*",+ "https://twitter.com/*",+ "https://www.twitter.com/*",+ "https://mobile.twitter.com/*",+ ],+ js: ["assets/tweet-target.js"],+ run_at: "document_start",+ },+ ]);}});diff --git a/apps/extension/options.html b/apps/extension/options.htmlindex e7745a45..ebb1a0c2 100644--- a/apps/extension/options.html+++ b/apps/extension/options.html@@ -9,6 +9,7 @@<main class="options-shell"><h1 data-i18n="extensionName">EdgeEver Web Clipper</h1><p class="hint" data-i18n="imageSaveHint">Right-click an image on a webpage and choose “Save image to EdgeEver”. It is saved into the default notebook selected below.</p>+ <p class="hint" data-i18n="tweetSaveHint">On X, right-click a post and choose “Save this post to EdgeEver”. The visible text and photos go into one new note in the same notebook.</p><form id="settings-form"><label><span data-i18n="instanceAddress">EdgeEver instance URL</span>diff --git a/apps/extension/package.json b/apps/extension/package.jsonindex 189e51b6..865cbf7f 100644--- a/apps/extension/package.json+++ b/apps/extension/package.json@@ -9,7 +9,7 @@"dev": "vite --config vite.config.ts","lint:firefox": "web-ext lint --source-dir dist-firefox --output text","package:firefox": "bun run build:firefox && bun run lint:firefox && web-ext build --source-dir dist-firefox --artifacts-dir web-ext-artifacts --overwrite-dest",- "test": "bun test manifest.test.mjs image-clip.test.mjs"+ "test": "bun test manifest.test.mjs image-clip.test.mjs tweet-clip.test.mjs"},"dependencies": {"@mozilla/readability": "^0.6.0",diff --git a/apps/extension/popup.html b/apps/extension/popup.htmlindex f7fba486..986afd72 100644--- a/apps/extension/popup.html+++ b/apps/extension/popup.html@@ -14,7 +14,7 @@<p class="hint" data-i18n="webClipper">Web Clipper</p></div></header>- <p class="popup-description" data-i18n="popupDescription">Clip the current page or selection. Right-click an image to save it as a note.</p>+ <p class="popup-description" data-i18n="popupDescription">Clip the current page or selection. Right-click an image to save it, or right-click a post on X to save that post.</p><button id="save" class="save-button" type="button"><svg aria-hidden="true" viewBox="0 0 24 24" width="18" height="18"><path d="M5 4.75A1.75 1.75 0 0 1 6.75 3h8.836c.464 0 .91.184 1.238.513l1.663 1.663c.329.328.513.774.513 1.238v12.836A1.75 1.75 0 0 1 17.25 21H6.75A1.75 1.75 0 0 1 5 19.25V4.75Z" />diff --git a/apps/extension/public/_locales/en/messages.json b/apps/extension/public/_locales/en/messages.jsonindex dd57ef53..84beeabc 100644--- a/apps/extension/public/_locales/en/messages.json+++ b/apps/extension/public/_locales/en/messages.json@@ -12,7 +12,7 @@"message": "Web Clipper"},"popupDescription": {- "message": "Clip the current page or selection. Right-click an image to save it as a note."+ "message": "Clip the current page or selection. Right-click an image to save it, or right-click a post on X to save that post."},"saveCurrentPage": {"message": "Clip current page"@@ -254,5 +254,47 @@},"imageSaveExpired": {"message": "This save has expired. Right-click the image and try again."+ },+ "saveTweetToEdgeEver": {+ "message": "Save this post to EdgeEver"+ },+ "tweetSaveHint": {+ "message": "On X, right-click a post and choose “Save this post to EdgeEver”. The visible text and photos go into one new note in the same default notebook."+ },+ "savingTweet": {+ "message": "Saving this post…"+ },+ "tweetSaved": {+ "message": "Saved this post as a note."+ },+ "tweetNotFound": {+ "message": "Could not find that post. Right-click directly on the post."+ },+ "tweetPermissionIntro": {+ "message": "A timeline has many posts. Allow access to X so the clipper can remember the post under the pointer. After that, right-click the same post once more. Only the post you choose is saved to the clipper's default notebook."+ },+ "tweetPermissionToast": {+ "message": "Allow access to X to choose a post on the timeline. Then right-click that post again."+ },+ "tweetRightClickAgain": {+ "message": "Posts on the timeline can be recognized now. Right-click that post again."+ },+ "allowTweetAccess": {+ "message": "Allow access to X"+ },+ "tweetPermissionDenied": {+ "message": "Access was not allowed. Right-click the post again to retry."+ },+ "tweetPermissionReady": {+ "message": "Access allowed. Go back and right-click that post again."+ },+ "tweetNoteFallbackTitle": {+ "message": "Post"+ },+ "tweetSaveWindowTitle": {+ "message": "Save this post to EdgeEver"+ },+ "tweetTimeLabel": {+ "message": "Time"}}diff --git a/apps/extension/public/_locales/ja/messages.json b/apps/extension/public/_locales/ja/messages.jsonindex 7e04ac6e..2e26801a 100644--- a/apps/extension/public/_locales/ja/messages.json+++ b/apps/extension/public/_locales/ja/messages.json@@ -12,7 +12,7 @@"message": "Web Clipper"},"popupDescription": {- "message": "表示中のページや選択した内容を取り込みます。画像を右クリックしてノートとして保存することもできます。"+ "message": "表示中のページや選択した内容を取り込みます。画像の右クリックで画像を、X 上の投稿の右クリックでその投稿を保存できます。"},"saveCurrentPage": {"message": "このページを取り込む"@@ -254,5 +254,47 @@},"imageSaveExpired": {"message": "この保存は終了しています。画像を右クリックしてやり直してください。"+ },+ "saveTweetToEdgeEver": {+ "message": "この投稿を EdgeEver に保存"+ },+ "tweetSaveHint": {+ "message": "X で投稿を右クリックし、「この投稿を EdgeEver に保存」を選びます。表示中の本文と画像は、上で選んだ既定のノートブックに 1 件のノートとして保存されます。"+ },+ "savingTweet": {+ "message": "この投稿を保存しています…"+ },+ "tweetSaved": {+ "message": "この投稿をノートとして保存しました。"+ },+ "tweetNotFound": {+ "message": "この投稿を特定できませんでした。投稿の上で直接右クリックしてください。"+ },+ "tweetPermissionIntro": {+ "message": "タイムラインには複数の投稿があります。ポインタの下にある投稿を覚えるには、X へのアクセスを許可してください。許可したあと、同じ投稿をもう一度右クリックします。選んだ投稿だけを、クリップ拡張機能の既定ノートブックに保存します。"+ },+ "tweetPermissionToast": {+ "message": "タイムラインで投稿を選ぶには、X へのアクセスを許可してください。そのあと、もう一度右クリックします。"+ },+ "tweetRightClickAgain": {+ "message": "タイムラインの投稿を識別できるようになりました。その投稿をもう一度右クリックしてください。"+ },+ "allowTweetAccess": {+ "message": "X へのアクセスを許可"+ },+ "tweetPermissionDenied": {+ "message": "アクセスは許可されませんでした。投稿をもう一度右クリックしてやり直してください。"+ },+ "tweetPermissionReady": {+ "message": "許可しました。ページに戻り、その投稿をもう一度右クリックしてください。"+ },+ "tweetNoteFallbackTitle": {+ "message": "投稿"+ },+ "tweetSaveWindowTitle": {+ "message": "この投稿を EdgeEver に保存"+ },+ "tweetTimeLabel": {+ "message": "日時"}}diff --git a/apps/extension/public/_locales/zh_CN/messages.json b/apps/extension/public/_locales/zh_CN/messages.jsonindex c7fd52f6..c7b183ef 100644--- a/apps/extension/public/_locales/zh_CN/messages.json+++ b/apps/extension/public/_locales/zh_CN/messages.json@@ -12,7 +12,7 @@"message": "网页剪藏"},"popupDescription": {- "message": "剪藏当前网页或选中内容。在图片上右键,可以把它存成一条笔记。"+ "message": "剪藏当前网页或选中内容。在图片上右键可以保存图片;在 X 上右键可以保存这条推文。"},"saveCurrentPage": {"message": "剪藏当前网页"@@ -254,5 +254,47 @@},"imageSaveExpired": {"message": "这次保存已经结束。请在图片上重新右键。"+ },+ "saveTweetToEdgeEver": {+ "message": "保存这条推文到 EdgeEver"+ },+ "tweetSaveHint": {+ "message": "在 X 上右键一条推文,选择“保存这条推文到 EdgeEver”。已经显示的文字和图片会放进同一条新笔记,笔记本与上面的默认笔记本相同。"+ },+ "savingTweet": {+ "message": "正在保存这条推文……"+ },+ "tweetSaved": {+ "message": "已把这条推文存成一条笔记。"+ },+ "tweetNotFound": {+ "message": "没有定位到这条推文。请直接在推文上右键。"+ },+ "tweetPermissionIntro": {+ "message": "时间线上有很多条推文。允许访问 X 之后,插件才能记住指针下的这一条。允许后,请再在同一条推文上右键一次。只会把你选中的这条存进剪藏插件的默认笔记本。"+ },+ "tweetPermissionToast": {+ "message": "需要允许访问 X,才能在时间线上选中这条推文。允许后请再右键一次。"+ },+ "tweetRightClickAgain": {+ "message": "已经可以识别时间线上的推文。请再在这条推文上右键一次。"+ },+ "allowTweetAccess": {+ "message": "允许访问 X"+ },+ "tweetPermissionDenied": {+ "message": "没有获得访问权限。请再在推文上右键一次来重新授权。"+ },+ "tweetPermissionReady": {+ "message": "已允许。回到页面,再在这条推文上右键一次。"+ },+ "tweetNoteFallbackTitle": {+ "message": "一条推文"+ },+ "tweetSaveWindowTitle": {+ "message": "保存这条推文到 EdgeEver"+ },+ "tweetTimeLabel": {+ "message": "时间"}}diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.tsindex ab83a65a..6ba8e896 100644--- a/apps/extension/src/background.ts+++ b/apps/extension/src/background.ts@@ -22,6 +22,13 @@ import {type StoredImage,type StoredImageFailure,} from "./image-clip";+import {+ canonicalStatusUrl,+ isCapturedTweet,+ saveCapturedTweetNote,+ statusIdFromPageUrl,+ tweetNoteTitle,+} from "./tweet-clip";import { t } from "./i18n";type CapturedPage = {@@ -42,8 +49,18 @@ type PendingImageSave = {};const IMAGE_MENU_ID = "save-image";+const TWEET_MENU_ID = "save-tweet";const PENDING_IMAGE_SAVE_KEY = "pendingImageSave";const IMAGE_SAVE_WINDOW_KEY = "imageSaveWindowId";+const PENDING_TWEET_KEY = "pendingTweetPermission";+const TWEET_WINDOW_KEY = "tweetSaveWindowId";+const TWEET_DOCUMENT_PATTERNS = [+ "https://x.com/*",+ "https://www.x.com/*",+ "https://twitter.com/*",+ "https://www.twitter.com/*",+ "https://mobile.twitter.com/*",+];const toMarkdown = (page: CapturedPage) => {const capturedAt = new Date().toISOString();@@ -270,41 +287,52 @@ const readPendingImageSave = async () => {return isPendingImageSave(stored[PENDING_IMAGE_SAVE_KEY]) ? stored[PENDING_IMAGE_SAVE_KEY] : null;};-const openImagePermissionWindow = async (pending: PendingImageSave) => {- await chrome.storage.session.set({ [PENDING_IMAGE_SAVE_KEY]: pending });- const stored = await chrome.storage.session.get(IMAGE_SAVE_WINDOW_KEY);- const existingId = stored[IMAGE_SAVE_WINDOW_KEY];+const focusExtensionWindow = async (path: string, windowKey: string, height: number) => {+ const stored = await chrome.storage.session.get(windowKey);+ const existingId = stored[windowKey];+ const url = chrome.runtime.getURL(path);if (typeof existingId === "number") {try {const existing = await chrome.windows.get(existingId, { populate: true });- const tabId = existing.tabs?.[0]?.id;- if (tabId) {- await chrome.tabs.update(tabId, { url: chrome.runtime.getURL("image-save.html") });+ const existingTabId = existing.tabs?.[0]?.id;+ if (existingTabId) {+ await chrome.tabs.update(existingTabId, { url });await chrome.windows.update(existingId, { focused: true });return;}} catch {- // The previous permission window has already closed.+ // The previous window has already closed.}}const created = await chrome.windows.create({- url: chrome.runtime.getURL("image-save.html"),+ url,type: "popup",width: 440,- height: 640,+ height,focused: true,});- if (created.id) await chrome.storage.session.set({ [IMAGE_SAVE_WINDOW_KEY]: created.id });+ if (created.id) await chrome.storage.session.set({ [windowKey]: created.id });+};++const openImagePermissionWindow = async (pending: PendingImageSave) => {+ await chrome.storage.session.set({ [PENDING_IMAGE_SAVE_KEY]: pending });+ await focusExtensionWindow("image-save.html", IMAGE_SAVE_WINDOW_KEY, 640);+};++const openTweetPermissionWindow = async (tabId: number | null) => {+ await chrome.storage.session.set({ [PENDING_TWEET_KEY]: { tabId } });+ await focusExtensionWindow("tweet-save.html", TWEET_WINDOW_KEY, 560);};let pendingCapture: ((page: CapturedPage) => void) | null = null;const pendingImageReads = new Map<string, (result: unknown) => void>();-let imageSaveQueue = Promise.resolve();+const pendingTweetReads = new Map<string, (result: unknown) => void>();+let clipQueue = Promise.resolve();let completingImageSave = false;-const enqueueImageSave = (job: () => Promise<void>) => {- const run = imageSaveQueue.then(job, job);- imageSaveQueue = run.then(() => undefined, () => undefined);+const enqueueClip = (job: () => Promise<void>) => {+ const run = clipQueue.then(job, job);+ clipQueue = run.then(() => undefined, () => undefined);return run;};@@ -416,7 +444,142 @@ const saveImageFromMenu = async (}};-const registerImageMenu = () => {+const injectTweetReader = async (tabId: number, frameId: number | null, payload: unknown) => {+ const target = scriptTarget(tabId, frameId);+ await chrome.scripting.executeScript({+ target,+ func: (value: unknown) => {+ (globalThis as { __edgeeverTweetClipPayload?: unknown }).__edgeeverTweetClipPayload = value;+ },+ args: [payload],+ });+ await chrome.scripting.executeScript({+ target,+ files: ["assets/capture-tweet.js"],+ });+};++const injectTweetTarget = async (tabId: number) => {+ await chrome.scripting.executeScript({+ target: { tabId },+ files: ["assets/tweet-target.js"],+ });+};++const readTweetFromPage = async (tabId: number, frameId: number | null, statusId: string) => {+ const requestId = crypto.randomUUID();+ const result = await new Promise<unknown>((resolve, reject) => {+ const timeout = setTimeout(() => {+ pendingTweetReads.delete(requestId);+ reject(new Error("timeout"));+ }, 10_000);+ pendingTweetReads.set(requestId, (value) => {+ clearTimeout(timeout);+ resolve(value);+ });+ void injectTweetReader(tabId, frameId, { requestId, statusId }).catch((error: unknown) => {+ clearTimeout(timeout);+ pendingTweetReads.delete(requestId);+ reject(error);+ });+ });+ return isCapturedTweet(result) ? result : { ok: false as const, reason: "not-found" as const };+};++const hasTweetSitePermission = async (pageUrl: string) => {+ const pattern = imageOriginPattern(pageUrl);+ if (!pattern) return false;+ return chrome.permissions.contains({ origins: [pattern] });+};++const readTweetImage = async (tabId: number, frameId: number | null, url: string, alt: string) => {+ const urls = preferredImageUrls(url);+ try {+ const pageRead = await readImageFromPage(tabId, frameId, urls, url);+ if (pageRead.ok) {+ const image = imageFromBase64(pageRead.base64, pageRead.mimeType, pageRead.byteSize);+ if (!("error" in image)) {+ return { ...image, filename: filenameForImage(url, image.mimeType), alt: alt || pageRead.alt };+ }+ }+ } catch {+ // The page could not hand over this photo. Try a permitted download below.+ }+ if (await hasImagePermission(urls)) {+ const downloaded = await downloadImage(urls);+ if (!("error" in downloaded)) {+ return { ...downloaded, filename: filenameForImage(url, downloaded.mimeType), alt };+ }+ }+ return null;+};++const describeTweetError = (error: unknown) => {+ const message = error instanceof Error ? error.message : "";+ if (message === t("tweetNotFound")) return message;+ return describeImageError(error);+};++const saveTweetFromMenu = async (+ info: { pageUrl?: string; frameId?: number },+ tab?: { id?: number; url?: string },+) => {+ const tabId = typeof tab?.id === "number" ? tab.id : null;+ const frameId = typeof info.frameId === "number" ? info.frameId : null;+ const pageUrl = tab?.url || info.pageUrl || "";+ try {+ const settings = await ensureClipperReady();+ if (!tabId) throw new Error(t("tweetNotFound"));+ const statusId = statusIdFromPageUrl(pageUrl);+ if (!statusId && !await hasTweetSitePermission(pageUrl)) {+ await openTweetPermissionWindow(tabId);+ await showFeedback(tabId, frameId, t("tweetPermissionToast"), "success");+ return;+ }++ await showFeedback(tabId, frameId, t("savingTweet"), "success");+ const tweet = await readTweetFromPage(tabId, frameId, statusId);+ if (!tweet.ok && tweet.reason === "needs-listener") {+ await injectTweetTarget(tabId);+ await showFeedback(tabId, frameId, t("tweetRightClickAgain"), "success");+ return;+ }+ if (!tweet.ok) throw new Error(t("tweetNotFound"));++ const images = [];+ for (const image of tweet.images) {+ const stored = await readTweetImage(tabId, frameId, image.url, image.alt);+ if (stored) images.push(stored);+ }+ await saveCapturedTweetNote(imageNoteClient(settings), {+ notebookId: settings.notebookId,+ title: tweetNoteTitle({ ...tweet, fallback: t("tweetNoteFallbackTitle") }),+ displayName: tweet.displayName,+ handle: tweet.handle,+ text: tweet.text,+ quotedDisplayName: tweet.quotedDisplayName,+ quotedHandle: tweet.quotedHandle,+ quotedText: tweet.quotedText,+ datetime: tweet.datetime,+ statusUrl: tweet.statusUrl || canonicalStatusUrl(pageUrl) || pageUrl,+ images,+ capturedAt: new Date().toISOString(),+ sourceLabel: t("sourceLabel"),+ capturedAtLabel: t("capturedAtLabel"),+ timeLabel: t("tweetTimeLabel"),+ altFallback: t("imageAltFallback"),+ });+ await showFeedback(tabId, frameId, t("tweetSaved"), "success");+ } catch (error) {+ const message = describeTweetError(error);+ if (message === t("completePluginConfiguration") || message === t("instancePermissionRequired")) {+ await chrome.runtime.openOptionsPage();+ }+ await showFeedback(tabId, frameId, message, "error");+ }+};++const registerClipMenus = () => {chrome.contextMenus.create({id: IMAGE_MENU_ID,title: t("saveImageToEdgeEver"),@@ -425,21 +588,37 @@ const registerImageMenu = () => {}, () => {void chrome.runtime.lastError;});+ chrome.contextMenus.create({+ id: TWEET_MENU_ID,+ title: t("saveTweetToEdgeEver"),+ contexts: ["page", "selection", "link", "image", "video"],+ documentUrlPatterns: TWEET_DOCUMENT_PATTERNS,+ }, () => {+ void chrome.runtime.lastError;+ });};-chrome.runtime.onInstalled.addListener(registerImageMenu);-registerImageMenu();+chrome.runtime.onInstalled.addListener(registerClipMenus);+registerClipMenus();chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number; srcUrl?: string; pageUrl?: string; frameId?: number }, tab?: { id?: number; url?: string; title?: string }) => {- if (info.menuItemId !== IMAGE_MENU_ID) return;- void enqueueImageSave(() => saveImageFromMenu(info, tab));+ if (info.menuItemId === IMAGE_MENU_ID) {+ void enqueueClip(() => saveImageFromMenu(info, tab));+ return;+ }+ if (info.menuItemId === TWEET_MENU_ID) {+ void enqueueClip(() => saveTweetFromMenu(info, tab));+ }});chrome.windows.onRemoved.addListener((windowId: number) => {- void chrome.storage.session.get(IMAGE_SAVE_WINDOW_KEY).then((stored: Record<string, unknown>) => {+ void chrome.storage.session.get([IMAGE_SAVE_WINDOW_KEY, TWEET_WINDOW_KEY]).then((stored: Record<string, unknown>) => {if (stored[IMAGE_SAVE_WINDOW_KEY] === windowId) {void chrome.storage.session.remove(IMAGE_SAVE_WINDOW_KEY);}+ if (stored[TWEET_WINDOW_KEY] === windowId) {+ void chrome.storage.session.remove(TWEET_WINDOW_KEY);+ }}).catch(() => undefined);});@@ -456,6 +635,29 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPreturn false;}+ if (message.type === "pageTweetRead" && message.requestId) {+ pendingTweetReads.get(message.requestId)?.(message.result);+ pendingTweetReads.delete(message.requestId);+ return false;+ }++ if (message.type === "activateTweetTarget") {+ void (async () => {+ const stored = await chrome.storage.session.get(PENDING_TWEET_KEY);+ const pending = stored[PENDING_TWEET_KEY] as { tabId?: number | null } | undefined;+ if (typeof pending?.tabId === "number") {+ try {+ await injectTweetTarget(pending.tabId);+ } catch {+ // The tab can be saved on the next right-click after it reloads.+ }+ }+ await chrome.storage.session.remove(PENDING_TWEET_KEY);+ sendResponse({ ok: true });+ })().catch(() => sendResponse({ ok: false }));+ return true;+ }+if (message.type === "getPendingImageSave") {void readPendingImageSave().then((pending) => {sendResponse(pending ? { originPattern: pending.originPattern, host: pending.host } : null);diff --git a/apps/extension/src/capture-tweet.ts b/apps/extension/src/capture-tweet.tsnew file mode 100644index 00000000..4311b62c--- /dev/null+++ b/apps/extension/src/capture-tweet.ts@@ -0,0 +1,129 @@+// Injected on demand. Reads the tweet marked by tweet-target.js, or the tweet+// in the address bar when this page is a single status. Must stay import-free.+(() => {+ const root = globalThis as typeof globalThis & {+ __edgeeverTweetTarget?: boolean;+ __edgeeverTweetClipPayload?: { requestId?: string; statusId?: string };+ };+ const payload = root.__edgeeverTweetClipPayload;+ delete root.__edgeeverTweetClipPayload;+ if (!payload || typeof payload.requestId !== "string") return;+ const requestId = payload.requestId;+ const statusId = typeof payload.statusId === "string" ? payload.statusId : "";++ const finish = (result: Record<string, unknown>) => {+ void chrome.runtime.sendMessage({ type: "pageTweetRead", requestId, result });+ };++ const clean = (value: string) => value.replace(/\s+/g, " ").trim();++ const parseName = (rootNode: Element | null) => {+ if (!rootNode) return { displayName: "", handle: "" };+ const links = [...rootNode.querySelectorAll("a[href]")];+ const handleLink = links.find((link) => clean(link.textContent || "").startsWith("@"));+ const handleFromLink = clean(handleLink?.textContent || "").replace(/^@/, "").split(/\s/)[0] ?? "";+ const handleFromHref = (links.find((link) => /^\/[A-Za-z0-9_]{1,15}$/.test(link.getAttribute("href") || ""))?.getAttribute("href") || "").slice(1);+ const handle = handleFromLink || handleFromHref;+ const nameLink = links.find((link) => {+ const text = clean(link.textContent || "");+ return link !== handleLink && text.length > 0 && !text.startsWith("@");+ });+ return { displayName: clean(nameLink?.textContent || ""), handle };+ };++ const hrefMatchesStatus = (href: string, id: string) => new RegExp(`/status/${id}(?:/|\\?|$)`).test(href);++ const ownStatusHref = (article: Element) => {+ const name = [...article.querySelectorAll('[data-testid="User-Name"]')].find((node) => !node.closest('[role="link"]'))+ ?? article.querySelector('[data-testid="User-Name"]');+ return name?.querySelector("time")?.closest("a")?.getAttribute("href") ?? "";+ };++ const articleFromStatus = () => {+ if (!statusId) return null;+ return [...document.querySelectorAll('article[data-testid="tweet"]')].find((article) => hrefMatchesStatus(ownStatusHref(article), statusId)) ?? null;+ };++ const isPhoto = (src: string) => {+ if (!src || src.startsWith("blob:") || src.startsWith("data:")) return false;+ try {+ const url = new URL(src, location.href);+ const host = url.hostname.toLowerCase();+ if (host !== "pbs.twimg.com" && !host.endsWith(".twimg.com")) return false;+ const path = url.pathname.toLowerCase();+ if (path.includes("/profile_images/") || path.includes("/profile_banners/") || path.includes("/emoji/")) return false;+ if (path.includes("/amplify_video") || path.includes("/ext_tw_video") || path.includes("/tweet_video")) return false;+ return path.includes("/media/") || path.includes("/card_img/");+ } catch {+ return false;+ }+ };++ const absoluteStatus = (href: string) => {+ if (!href) return "";+ try {+ const url = new URL(href, location.href);+ const match = url.pathname.match(/\/([^/]+)\/status\/(\d+)/);+ if (!match?.[1] || !match[2]) return "";+ return `${url.origin}/${match[1]}/status/${match[2]}`;+ } catch {+ return "";+ }+ };++ try {+ const marked = document.querySelector('article[data-testid="tweet"][data-edgeever-tweet-target="1"]');+ const article = marked ?? articleFromStatus();+ if (!article) {+ finish({ ok: false, reason: root.__edgeeverTweetTarget ? "not-found" : "needs-listener" });+ return;+ }++ const names = [...article.querySelectorAll('[data-testid="User-Name"]')];+ const mainName = names.find((node) => !node.closest('[role="link"]')) ?? names[0] ?? null;+ const quoteName = names.find((node) => node !== mainName && Boolean(node.closest('[role="link"]'))) ?? null;+ const texts = [...article.querySelectorAll('[data-testid="tweetText"]')];+ const mainText = texts.find((node) => !node.closest('[role="link"]')) ?? texts[0] ?? null;+ const quoteText = texts.find((node) => node !== mainText && Boolean(node.closest('[role="link"]'))) ?? null;+ const author = parseName(mainName);+ const quoted = parseName(quoteName);+ const images: Array<{ url: string; alt: string }> = [];+ for (const img of article.querySelectorAll("img")) {+ if (img.closest('[data-testid="tweetText"]')) continue;+ if (img.closest('[data-testid="Tweet-User-Avatar"]')) continue;+ if (img.closest('[data-testid="videoPlayer"], [data-testid="videoComponent"]')) continue;+ if (img.naturalWidth > 0 && img.naturalHeight > 0 && img.naturalWidth < 48 && img.naturalHeight < 48) continue;+ const src = img.currentSrc || img.src;+ if (!isPhoto(src) || images.some((image) => image.url === src)) continue;+ images.push({ url: src, alt: clean(img.alt) });+ if (images.length >= 6) break;+ }++ const visibleText = (node: Element | null) => {+ if (!node) return "";+ return ((node as HTMLElement).innerText || node.textContent || "").trim();+ };+ const text = visibleText(mainText);+ const quotedText = visibleText(quoteText);+ const statusUrl = absoluteStatus(ownStatusHref(article));+ if (!author.displayName && !author.handle && !text && !quotedText && images.length === 0) {+ finish({ ok: false, reason: "not-found" });+ return;+ }++ finish({+ ok: true,+ displayName: author.displayName,+ handle: author.handle,+ text,+ quotedDisplayName: quoted.displayName,+ quotedHandle: quoted.handle,+ quotedText,+ datetime: mainName?.querySelector("time")?.getAttribute("datetime") ?? "",+ statusUrl,+ images,+ });+ } catch {+ finish({ ok: false, reason: "not-found" });+ }+})();diff --git a/apps/extension/src/tweet-clip.ts b/apps/extension/src/tweet-clip.tsnew file mode 100644index 00000000..9641e020--- /dev/null+++ b/apps/extension/src/tweet-clip.ts@@ -0,0 +1,238 @@+import { imageAltText, type ImageNoteClient } from "./image-clip";++const TWEET_HOSTS = new Set([+ "x.com",+ "www.x.com",+ "twitter.com",+ "www.twitter.com",+ "mobile.twitter.com",+]);++export type CapturedTweet = {+ ok: true;+ displayName: string;+ handle: string;+ text: string;+ quotedDisplayName: string;+ quotedHandle: string;+ quotedText: string;+ datetime: string;+ statusUrl: string;+ images: Array<{ url: string; alt: string }>;+};++export type CapturedTweetFailure = {+ ok: false;+ reason: "not-found" | "needs-listener";+};++export type TweetNoteImage = {+ resourceId: string;+ alt: string;+};++const escapeMarkdownLabel = (value: string) =>+ value.replace(/[\r\n]+/g, " ").replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");++const markdownDestination = (value: string) =>+ value.replace(/\\/g, "%5C").replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29");++export const statusIdFromPageUrl = (pageUrl: string) => {+ try {+ const url = new URL(pageUrl);+ if (!TWEET_HOSTS.has(url.hostname.toLowerCase())) return "";+ return url.pathname.match(/\/status\/(\d+)/)?.[1] ?? "";+ } catch {+ return "";+ }+};++export const canonicalStatusUrl = (pageUrl: string) => {+ const statusId = statusIdFromPageUrl(pageUrl);+ if (!statusId) return "";+ try {+ const url = new URL(pageUrl);+ const user = url.pathname.match(/\/([^/]+)\/status\/\d+/)?.[1];+ if (!user) return "";+ return `${url.origin}/${user}/status/${statusId}`;+ } catch {+ return "";+ }+};++export const isTweetPhotoUrl = (src: string) => {+ if (!src || src.startsWith("blob:") || src.startsWith("data:")) return false;+ try {+ const url = new URL(src);+ const host = url.hostname.toLowerCase();+ if (host !== "pbs.twimg.com" && !host.endsWith(".twimg.com")) return false;+ const path = url.pathname.toLowerCase();+ if (path.includes("/profile_images/") || path.includes("/profile_banners/") || path.includes("/emoji/")) return false;+ if (path.includes("/amplify_video") || path.includes("/ext_tw_video") || path.includes("/tweet_video")) return false;+ return path.includes("/media/") || path.includes("/card_img/");+ } catch {+ return false;+ }+};++export const cleanTweetText = (value: string) => {+ const lines = value.replace(/\r/g, "").split("\n").map((line) => line.trimEnd());+ while (lines.length > 0 && !lines[lines.length - 1]?.trim()) lines.pop();+ while (lines.length > 0 && /^(显示更多|Show more|もっと見る|さらに表示)$/i.test(lines[lines.length - 1]?.trim() ?? "")) {+ lines.pop();+ }+ return lines.join("\n").trim();+};++export const tweetAuthorLine = (displayName: string, handle: string) => {+ const name = displayName.replace(/\s+/g, " ").trim();+ const user = handle.replace(/^@/, "").replace(/\s+/g, "").trim();+ if (name && user) return `${name} (@${user})`;+ if (user) return `@${user}`;+ return name;+};++export const tweetNoteTitle = (input: { displayName: string; handle: string; text: string; fallback: string }) => {+ const name = input.displayName.replace(/\s+/g, " ").trim()+ || (input.handle.trim() ? `@${input.handle.replace(/^@/, "").trim()}` : "");+ const firstLine = cleanTweetText(input.text).split("\n").map((line) => line.trim()).find(Boolean) ?? "";+ const combined = name && firstLine ? `${name}: ${firstLine}` : (firstLine || name || input.fallback);+ return combined.replace(/\s+/g, " ").trim().slice(0, 160);+};++export const isCapturedTweet = (value: unknown): value is CapturedTweet | CapturedTweetFailure => {+ if (!value || typeof value !== "object") return false;+ const record = value as {+ ok?: unknown;+ reason?: unknown;+ displayName?: unknown;+ handle?: unknown;+ text?: unknown;+ quotedDisplayName?: unknown;+ quotedHandle?: unknown;+ quotedText?: unknown;+ datetime?: unknown;+ statusUrl?: unknown;+ images?: unknown;+ };+ if (record.ok === false) return record.reason === "not-found" || record.reason === "needs-listener";+ if (record.ok !== true) return false;+ if (!Array.isArray(record.images)) return false;+ return typeof record.displayName === "string"+ && typeof record.handle === "string"+ && typeof record.text === "string"+ && typeof record.quotedDisplayName === "string"+ && typeof record.quotedHandle === "string"+ && typeof record.quotedText === "string"+ && typeof record.datetime === "string"+ && typeof record.statusUrl === "string"+ && record.images.every((image) => {+ const item = image as { url?: unknown; alt?: unknown };+ return typeof item?.url === "string" && typeof item?.alt === "string";+ });+};++export const tweetNoteMarkdown = (input: {+ displayName: string;+ handle: string;+ text: string;+ quotedDisplayName: string;+ quotedHandle: string;+ quotedText: string;+ datetime: string;+ statusUrl: string;+ images: TweetNoteImage[];+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+ timeLabel: string;+ altFallback: string;+}) => {+ const blocks: string[] = [];+ const author = tweetAuthorLine(input.displayName, input.handle);+ if (author) blocks.push(author);+ const text = cleanTweetText(input.text);+ if (text) blocks.push(text);+ const quoted = cleanTweetText(input.quotedText);+ if (quoted) {+ const quoteAuthor = tweetAuthorLine(input.quotedDisplayName, input.quotedHandle);+ const lines = quoteAuthor ? [quoteAuthor, ...quoted.split("\n")] : quoted.split("\n");+ blocks.push(lines.map((line) => `> ${line}`).join("\n"));+ }+ if (input.images.length > 0) {+ blocks.push(input.images.map((image) => (+ `}/blob)`+ )).join("\n\n"));+ }+ const footer = [+ `${input.sourceLabel}: [${escapeMarkdownLabel(input.statusUrl)}](${markdownDestination(input.statusUrl)})`,+ input.datetime ? `${input.timeLabel}: ${input.datetime}` : "",+ `${input.capturedAtLabel}: ${input.capturedAt}`,+ ].filter(Boolean);+ blocks.push(footer.join("\n\n"));+ return blocks.join("\n\n");+};++export const saveCapturedTweetNote = async (+ client: ImageNoteClient,+ input: {+ notebookId: string;+ title: string;+ displayName: string;+ handle: string;+ text: string;+ quotedDisplayName: string;+ quotedHandle: string;+ quotedText: string;+ datetime: string;+ statusUrl: string;+ images: Array<{ bytes: Uint8Array; mimeType: string; filename: string; alt: string }>;+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+ timeLabel: string;+ altFallback: string;+ },+) => {+ let notebookId = input.notebookId;+ if (!notebookId) {+ const listed = await client.listNotebooks();+ notebookId = listed.notebooks[0]?.id ?? "";+ }+ if (!notebookId) throw new Error("no-notebook");++ const markdownFor = (images: TweetNoteImage[]) => tweetNoteMarkdown({ ...input, images });+ const created = await client.createMemo({+ notebookId,+ title: input.title,+ contentMarkdown: markdownFor([]),+ tags: ["web-clip"],+ });+ const memoId = created.memo.id;+ if (!memoId) throw new Error("create-missing-id");+ if (input.images.length === 0) return { memoId, resourceIds: [] as string[] };++ const uploaded: TweetNoteImage[] = [];+ for (const image of input.images) {+ try {+ const resource = await client.uploadImage(memoId, image);+ if (resource.id) uploaded.push({ resourceId: resource.id, alt: image.alt });+ } catch {+ // The text note is still useful when one attachment cannot be stored.+ }+ }+ if (uploaded.length === 0) return { memoId, resourceIds: [] as string[] };++ try {+ const session = await client.createEditSession(memoId);+ await client.saveMemo(memoId, {+ editSessionId: session.editSession.id,+ expectedRevision: session.editSession.baseRevision,+ expectedContentHash: session.editSession.baseContentHash,+ contentMarkdown: markdownFor(uploaded),+ });+ } catch {+ // Leave the text note in place when attaching images fails.+ }+ return { memoId, resourceIds: uploaded.map((image) => image.resourceId) };+};diff --git a/apps/extension/src/tweet-save.ts b/apps/extension/src/tweet-save.tsnew file mode 100644index 00000000..f7f4ce6f--- /dev/null+++ b/apps/extension/src/tweet-save.ts@@ -0,0 +1,41 @@+import "./styles.css";+import { localizeDocument, t } from "./i18n";++localizeDocument();+document.title = t("tweetSaveWindowTitle");++const status = document.querySelector<HTMLParagraphElement>("#status");+const allowButton = document.querySelector<HTMLButtonElement>("#allow");++const setStatus = (message: string, kind: "normal" | "error" | "success" = "normal") => {+ if (!status) return;+ status.textContent = message;+ status.dataset.kind = kind;+};++allowButton?.addEventListener("click", () => {+ if (!allowButton) return;+ allowButton.disabled = true;+ void (async () => {+ let granted = false;+ try {+ granted = await chrome.permissions.request({+ origins: ["https://x.com/*", "https://twitter.com/*", "https://mobile.twitter.com/*", "https://www.x.com/*", "https://www.twitter.com/*"],+ });+ } catch {+ granted = false;+ }+ if (!granted) {+ setStatus(t("tweetPermissionDenied"), "error");+ allowButton.disabled = false;+ return;+ }+ try {+ await chrome.runtime.sendMessage({ type: "activateTweetTarget" });+ } catch {+ // The page can still be saved on the next right-click after a reload.+ }+ setStatus(t("tweetPermissionReady"), "success");+ window.setTimeout(() => window.close(), 1600);+ })();+});diff --git a/apps/extension/src/tweet-target.ts b/apps/extension/src/tweet-target.tsnew file mode 100644index 00000000..f78aebc0--- /dev/null+++ b/apps/extension/src/tweet-target.ts@@ -0,0 +1,24 @@+// Content script for x.com and twitter.com. It only remembers which tweet was+// under the pointer so a later menu click can save that post. No imports:+// content scripts are classic scripts, and this file is also injected again+// after the user grants access.+(() => {+ const root = globalThis as typeof globalThis & { __edgeeverTweetTarget?: boolean };+ if (root.__edgeeverTweetTarget) return;+ root.__edgeeverTweetTarget = true;++ document.addEventListener("contextmenu", (event) => {+ const rawTarget = event.target;+ const element = rawTarget instanceof Element+ ? rawTarget+ : rawTarget instanceof Node+ ? rawTarget.parentElement+ : null;+ if (!element) return;+ const article = element.closest('article[data-testid="tweet"]');+ for (const node of document.querySelectorAll("[data-edgeever-tweet-target]")) {+ node.removeAttribute("data-edgeever-tweet-target");+ }+ if (article) article.setAttribute("data-edgeever-tweet-target", "1");+ }, true);+})();diff --git a/apps/extension/tweet-clip.test.mjs b/apps/extension/tweet-clip.test.mjsnew file mode 100644index 00000000..3a22b184--- /dev/null+++ b/apps/extension/tweet-clip.test.mjs@@ -0,0 +1,152 @@+import { describe, expect, test } from "bun:test";+import {+ canonicalStatusUrl,+ cleanTweetText,+ isTweetPhotoUrl,+ saveCapturedTweetNote,+ statusIdFromPageUrl,+ tweetAuthorLine,+ tweetNoteMarkdown,+ tweetNoteTitle,+} from "./src/tweet-clip.ts";++const labels = {+ capturedAt: "2026-09-26T00:00:00.000Z",+ sourceLabel: "来源",+ capturedAtLabel: "抓取时间",+ timeLabel: "时间",+ altFallback: "图片",+};++const tweet = {+ displayName: "火山哥",+ handle: "huoshan007",+ text: "兄弟们,我今天挖到一个真狠活。\n显示更多",+ quotedDisplayName: "Jianying",+ quotedHandle: "jianying",+ quotedText: "无界面后台版",+ datetime: "2026-09-26T01:00:00.000Z",+ statusUrl: "https://x.com/huoshan007/status/123",+ ...labels,+};++describe("tweet addresses", () => {+ test("reads a status id from a post page and ignores a timeline", () => {+ expect(statusIdFromPageUrl("https://x.com/huoshan007/status/123")).toBe("123");+ expect(statusIdFromPageUrl("https://twitter.com/huoshan007/status/123/photo/1")).toBe("123");+ expect(statusIdFromPageUrl("https://x.com/home")).toBe("");+ expect(canonicalStatusUrl("https://x.com/huoshan007/status/123/photo/1?s=20")).toBe("https://x.com/huoshan007/status/123");+ });+});++describe("tweet note content", () => {+ test("keeps the visible post, quote, photo, and source link", () => {+ expect(cleanTweetText(tweet.text)).toBe("兄弟们,我今天挖到一个真狠活。");+ expect(tweetAuthorLine("火山哥", "@huoshan007")).toBe("火山哥 (@huoshan007)");+ expect(tweetNoteTitle({ ...tweet, fallback: "一条推文" })).toBe("火山哥: 兄弟们,我今天挖到一个真狠活。");+ const markdown = tweetNoteMarkdown({+ ...tweet,+ text: cleanTweetText(tweet.text),+ images: [{ resourceId: "res_1", alt: "卡片]图" }],+ });+ expect(markdown.startsWith("火山哥 (@huoshan007)")).toBe(true);+ expect(markdown).toContain("兄弟们,我今天挖到一个真狠活。");+ expect(markdown).toContain("> Jianying (@jianying)\n> 无界面后台版");+ expect(markdown).toContain("");+ expect(markdown).toContain("(https://x.com/huoshan007/status/123)");+ expect(markdown).toContain("时间: 2026-09-26T01:00:00.000Z");+ expect(markdown).not.toContain("pbs.twimg.com");+ });++ test("accepts post photos and skips avatars, emoji, and video posters", () => {+ expect(isTweetPhotoUrl("https://pbs.twimg.com/media/Abc?format=jpg&name=small")).toBe(true);+ expect(isTweetPhotoUrl("https://pbs.twimg.com/card_img/Abc/img")).toBe(true);+ expect(isTweetPhotoUrl("https://pbs.twimg.com/profile_images/Abc/avatar.jpg")).toBe(false);+ expect(isTweetPhotoUrl("https://abs.twimg.com/emoji/v2/svg/1f600.svg")).toBe(false);+ expect(isTweetPhotoUrl("https://pbs.twimg.com/ext_tw_video_thumb/Abc/img.jpg")).toBe(false);+ });+});++describe("saveCapturedTweetNote", () => {+ const client = (overrides = {}) => {+ const order = [];+ const calls = { saved: null, created: null };+ return {+ order,+ calls,+ api: {+ listNotebooks: async () => {+ order.push("list");+ return { notebooks: [{ id: "nb_first" }] };+ },+ createMemo: async (body) => {+ order.push("create");+ calls.created = body;+ return { memo: { id: "memo_1" } };+ },+ uploadImage: async () => {+ order.push("upload");+ return { id: "res_1" };+ },+ createEditSession: async () => {+ order.push("session");+ return { editSession: { id: "edit_1", baseRevision: 0, baseContentHash: "a".repeat(64) } };+ },+ saveMemo: async (_memoId, body) => {+ order.push("save");+ calls.saved = body;+ },+ deleteMemo: async () => {+ order.push("delete");+ },+ ...overrides,+ },+ };+ };++ test("creates a text note when the post has no photo", async () => {+ const fixture = client();+ const saved = await saveCapturedTweetNote(fixture.api, {+ notebookId: "nb_inbox",+ title: "火山哥: 兄弟们",+ ...tweet,+ images: [],+ });+ expect(saved).toEqual({ memoId: "memo_1", resourceIds: [] });+ expect(fixture.order).toEqual(["create"]);+ expect(fixture.calls.created.tags).toEqual(["web-clip"]);+ expect(fixture.calls.created.contentMarkdown).toContain("兄弟们,我今天挖到一个真狠活。");+ });++ test("keeps the text note when a photo cannot be uploaded", async () => {+ const fixture = client({+ uploadImage: async () => {+ throw new Error("Missing required scope: write:resources");+ },+ });+ const saved = await saveCapturedTweetNote(fixture.api, {+ notebookId: "",+ title: "火山哥: 兄弟们",+ ...tweet,+ images: [{ bytes: Uint8Array.of(1), mimeType: "image/jpeg", filename: "Abc.jpg", alt: "卡片" }],+ });+ expect(saved.memoId).toBe("memo_1");+ expect(saved.resourceIds).toEqual([]);+ expect(fixture.order).toEqual(["list", "create"]);+ expect(fixture.calls.created.notebookId).toBe("nb_first");+ });++ test("attaches an uploaded photo to the same note", async () => {+ const fixture = client();+ const saved = await saveCapturedTweetNote(fixture.api, {+ notebookId: "nb_inbox",+ title: "火山哥: 兄弟们",+ ...tweet,+ images: [{ bytes: Uint8Array.of(1), mimeType: "image/jpeg", filename: "Abc.jpg", alt: "卡片" }],+ });+ expect(saved.resourceIds).toEqual(["res_1"]);+ expect(fixture.order).toEqual(["create", "upload", "session", "save"]);+ expect(fixture.calls.saved.contentMarkdown).toContain("](/api/v1/resources/res_1/blob)");+ expect(fixture.calls.created.contentMarkdown.includes("](/api/v1/resources/")).toBe(false);+ });+});diff --git a/apps/extension/tweet-save.html b/apps/extension/tweet-save.htmlnew file mode 100644index 00000000..5d640c0e--- /dev/null+++ b/apps/extension/tweet-save.html@@ -0,0 +1,19 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title data-i18n="tweetSaveWindowTitle">Save this post to EdgeEver</title>+ </head>+ <body>+ <main class="image-save-shell">+ <h1 data-i18n="tweetSaveWindowTitle">Save this post to EdgeEver</h1>+ <p class="hint" data-i18n="tweetPermissionIntro">A timeline has many posts. Allow access to X so the clipper can remember the post under the pointer. After that, right-click the same post once more. Only the post you choose is saved to the clipper's default notebook.</p>+ <div class="image-save-actions">+ <button id="allow" type="button" data-i18n="allowTweetAccess">Allow access to X</button>+ </div>+ <p id="status" class="status" role="status"></p>+ </main>+ <script type="module" src="/src/tweet-save.ts"></script>+ </body>+</html>diff --git a/apps/extension/vite.config.ts b/apps/extension/vite.config.tsindex 7e505722..34538a7b 100644--- a/apps/extension/vite.config.ts+++ b/apps/extension/vite.config.ts@@ -32,6 +32,9 @@ export default defineConfig({background: fileURLToPath(new URL("./src/background.ts", import.meta.url)),capture: fileURLToPath(new URL("./src/capture.ts", import.meta.url)),"capture-image": fileURLToPath(new URL("./src/capture-image.ts", import.meta.url)),+ "capture-tweet": fileURLToPath(new URL("./src/capture-tweet.ts", import.meta.url)),+ "tweet-target": fileURLToPath(new URL("./src/tweet-target.ts", import.meta.url)),+ "tweet-save": fileURLToPath(new URL("./tweet-save.html", import.meta.url)),},output: {entryFileNames: "assets/[name].js",