LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: add keyboard shortcut for web clipping
nash_su44d6081f1f7d
diff --git a/README.md b/README.mdindex 698d8ac0..ea647622 100644--- a/README.md+++ b/README.md@@ -417,6 +417,7 @@ npm run tauri build # Production build2. Enable "Developer mode"3. Click "Load unpacked"4. Select the `extension/` directory+5. Clip the current page with `Alt+Shift+L` (`Command+Shift+L` on macOS). Customize it at `chrome://extensions/shortcuts`.## Quick Startdiff --git a/README_CN.md b/README_CN.mdindex 832f72a0..58177284 100644--- a/README_CN.md+++ b/README_CN.md@@ -417,6 +417,7 @@ npm run tauri build # 生产构建2. 启用「开发者模式」3. 点击「加载已解压的扩展程序」4. 选择 `extension/` 目录+5. 使用 `Alt+Shift+L`(macOS 为 `Command+Shift+L`)直接剪藏当前页面;可在 `chrome://extensions/shortcuts` 中自定义快捷键## 快速开始diff --git a/README_JA.md b/README_JA.mdindex 0028a8c9..245161ec 100644--- a/README_JA.md+++ b/README_JA.md@@ -426,6 +426,7 @@ npm run tauri build # 本番ビルド2. 「デベロッパーモード」を有効にする3. 「パッケージ化されていない拡張機能を読み込む」をクリック4. `extension/` ディレクトリを選択+5. `Alt+Shift+L`(macOS は `Command+Shift+L`)で現在のページを直接クリップ。`chrome://extensions/shortcuts` で変更できます## クイックスタートdiff --git a/README_KO.md b/README_KO.mdindex 10d67e0e..c8609f5d 100644--- a/README_KO.md+++ b/README_KO.md@@ -426,6 +426,7 @@ npm run tauri build # Production build2. "Developer mode"를 활성화합니다3. "Load unpacked"를 클릭합니다4. `extension/` 디렉터리를 선택합니다+5. `Alt+Shift+L`(macOS에서는 `Command+Shift+L`)로 현재 페이지를 바로 클립합니다. `chrome://extensions/shortcuts`에서 단축키를 변경할 수 있습니다## 빠른 시작diff --git a/extension/background.js b/extension/background.jsnew file mode 100644index 00000000..dda47a08--- /dev/null+++ b/extension/background.js@@ -0,0 +1,56 @@+importScripts("clipper-core.js");++const COMMAND_NAME = "clip-current-page";+let badgeTimer;+let clipInFlight = false;++async function setBadge(text, color, title, clearAfterMs = 0) {+ clearTimeout(badgeTimer);+ await chrome.action.setBadgeBackgroundColor({ color });+ await chrome.action.setBadgeText({ text });+ if (title) await chrome.action.setTitle({ title });+ if (clearAfterMs > 0) {+ badgeTimer = setTimeout(() => {+ void chrome.action.setBadgeText({ text: "" });+ void chrome.action.setTitle({ title: "LLM Wiki Clipper" });+ }, clearAfterMs);+ }+}++async function clipCurrentPage(commandTab) {+ if (clipInFlight) {+ await setBadge("…", "#4f46e5", "A page clip is already in progress");+ return;+ }+ clipInFlight = true;+ const core = globalThis.LLMWikiClipper;+ try {+ await setBadge("…", "#4f46e5", "Clipping current page...");+ const settings = await core.loadSettings();+ const connection = {+ serverUrl: settings.serverUrl,+ accessToken: settings.accessToken,+ };+ const { projects, baseUrl } = await core.loadProjects(connection);+ connection.serverUrl = baseUrl;+ const project = core.selectProject(projects, settings.preferredProjectPath);+ if (!project) throw new Error("No LLM Wiki project is available");++ const page = await core.extractActiveTab(commandTab);+ const submitted = await core.submitClip(page, project.path, connection);+ await chrome.storage.local.set({+ serverUrl: submitted.baseUrl,+ });+ await setBadge("✓", "#059669", `Saved to ${project.name || "LLM Wiki"}`, 4000);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ console.error("[LLM Wiki Clipper] shortcut failed:", error);+ await setBadge("!", "#dc2626", `Clip failed: ${message}`, 7000);+ } finally {+ clipInFlight = false;+ }+}++chrome.commands.onCommand.addListener((command, tab) => {+ if (command === COMMAND_NAME) void clipCurrentPage(tab);+});diff --git a/extension/clipper-core.js b/extension/clipper-core.jsnew file mode 100644index 00000000..9338ab38--- /dev/null+++ b/extension/clipper-core.js@@ -0,0 +1,226 @@+(function initializeClipperCore(global) {+ const DEFAULT_API_URLS = ["http://127.0.0.1:19827", "http://localhost:19827"];+ const MAX_EXTRACTED_CONTENT_CHARS = 1_000_000;+ const TRUNCATION_NOTICE = "\n\n[LLM Wiki Clipper: page content truncated at 1,000,000 characters.]";++ function limitExtractedContent(content) {+ const value = String(content || "");+ if (value.length <= MAX_EXTRACTED_CONTENT_CHARS) return value;+ return `${value.slice(0, MAX_EXTRACTED_CONTENT_CHARS)}${TRUNCATION_NOTICE}`;+ }++ function normalizeServerUrl(value) {+ let candidate = String(value || "").trim();+ if (!candidate) return DEFAULT_API_URLS[0];+ if (!/^https?:\/\//i.test(candidate)) candidate = `http://${candidate}`;+ const parsed = new URL(candidate);+ if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password) {+ throw new Error("Use an http(s) address without embedded credentials");+ }+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) {+ throw new Error("Enter only the server origin, without a path, query, or fragment");+ }+ if (!parsed.port) parsed.port = "19827";+ return parsed.origin;+ }++ async function loadSettings() {+ const saved = await chrome.storage.local.get([+ "serverUrl",+ "accessToken",+ "preferredProjectPath",+ ]);+ let serverUrl;+ try {+ serverUrl = normalizeServerUrl(saved.serverUrl || DEFAULT_API_URLS[0]);+ } catch {+ serverUrl = DEFAULT_API_URLS[0];+ }+ return {+ serverUrl,+ accessToken: String(saved.accessToken || ""),+ preferredProjectPath: String(saved.preferredProjectPath || ""),+ };+ }++ function requestHeaders(accessToken, options) {+ const headers = new Headers(options?.headers || {});+ if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);+ return headers;+ }++ async function clipFetch(path, options, connection) {+ const method = String(options?.method || "GET").toUpperCase();+ const serverUrl = normalizeServerUrl(connection?.serverUrl || DEFAULT_API_URLS[0]);+ // A POST is never retried because the first request may have reached the+ // Clip Server even when its response was lost.+ const isDefaultLocalAddress = DEFAULT_API_URLS.includes(serverUrl);+ const urls = method === "GET" && isDefaultLocalAddress+ ? [serverUrl, ...DEFAULT_API_URLS.filter((url) => url !== serverUrl)]+ : [serverUrl];+ let lastError;++ for (const baseUrl of urls) {+ try {+ const response = await fetch(`${baseUrl}${path}`, {+ ...options,+ headers: requestHeaders(connection?.accessToken, options),+ });+ return { response, baseUrl };+ } catch (error) {+ lastError = error;+ }+ }+ throw lastError || new Error("Unable to connect to LLM Wiki");+ }++ // This function is serialized into the active tab by chrome.scripting, so it+ // must remain self-contained and must not capture extension-scope variables.+ function extractReadablePage() {+ try {+ const documentClone = document.cloneNode(true);+ const reader = new window.Readability(documentClone);+ const article = reader.parse();+ if (!article || !article.content) {+ return { error: "Readability could not extract content" };+ }++ const turndown = new window.TurndownService({+ headingStyle: "atx",+ codeBlockStyle: "fenced",+ bulletListMarker: "-",+ });+ turndown.addRule("tableCell", {+ filter: ["th", "td"],+ replacement: (content) => ` ${content.trim()} |`,+ });+ turndown.addRule("tableRow", {+ filter: "tr",+ replacement: (content) => `|${content}\n`,+ });+ turndown.addRule("table", {+ filter: "table",+ replacement: (content) => {+ const lines = content.trim().split("\n");+ if (lines.length > 0) {+ const columns = (lines[0].match(/\|/g) || []).length - 1;+ lines.splice(1, 0, `|${" --- |".repeat(columns)}`);+ }+ return `\n\n${lines.join("\n")}\n\n`;+ },+ });+ turndown.addRule("removeSmallImages", {+ filter: (node) => {+ if (node.nodeName !== "IMG") return false;+ const width = parseInt(node.getAttribute("width") || "999");+ const height = parseInt(node.getAttribute("height") || "999");+ return width < 10 || height < 10;+ },+ replacement: () => "",+ });++ return {+ title: article.title || document.title || "Untitled",+ content: turndown.turndown(article.content),+ excerpt: article.excerpt || "",+ };+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error) };+ }+ }++ function extractFallbackPage() {+ const clone = document.body?.cloneNode(true);+ if (!clone) return "";+ ["script", "style", "nav", "header", "footer", ".sidebar", ".ad", ".comments"]+ .forEach((selector) => clone.querySelectorAll(selector).forEach((element) => element.remove()));+ return clone.innerText+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ .join("\n\n");+ }++ async function extractActiveTab(commandTab) {+ // Chrome passes the exact shortcut target to commands.onCommand together+ // with the temporary activeTab grant. Popup callers do not have that value+ // and intentionally resolve their own currently active tab instead.+ const tab = commandTab?.id+ ? commandTab+ : (await chrome.tabs.query({ active: true, currentWindow: true }))[0];+ if (!tab?.id) throw new Error("No active browser tab");+ if (!/^https?:\/\//i.test(tab.url || "")) {+ throw new Error("This browser page cannot be clipped");+ }++ await chrome.scripting.executeScript({+ target: { tabId: tab.id },+ files: ["Readability.js", "Turndown.js"],+ });+ const results = await chrome.scripting.executeScript({+ target: { tabId: tab.id },+ func: extractReadablePage,+ });+ const extracted = results?.[0]?.result;+ let content = extracted?.content || "";+ if (!content) {+ const fallback = await chrome.scripting.executeScript({+ target: { tabId: tab.id },+ func: extractFallbackPage,+ });+ content = fallback?.[0]?.result || "";+ }+ if (!content.trim()) throw new Error(extracted?.error || "Failed to extract page content");+ content = limitExtractedContent(content);++ return {+ title: extracted?.title || tab.title || "Untitled",+ url: tab.url || "",+ content,+ excerpt: extracted?.excerpt || "",+ };+ }++ async function loadProjects(connection) {+ const { response, baseUrl } = await clipFetch("/projects", { method: "GET" }, connection);+ if (response.status === 401) throw new Error("Access token required or invalid");+ const data = await response.json();+ if (!response.ok || !data.ok) throw new Error(data.error || "Failed to load projects");+ return { projects: data.projects || [], baseUrl };+ }++ function selectProject(projects, preferredProjectPath) {+ return projects.find((project) => project.path === preferredProjectPath)+ || projects.find((project) => project.current)+ || projects[0]+ || null;+ }++ async function submitClip(page, projectPath, connection) {+ const { response, baseUrl } = await clipFetch("/clip", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ title: page.title,+ url: page.url,+ content: page.content,+ projectPath,+ }),+ }, connection);+ const data = await response.json();+ if (!response.ok || !data.ok) throw new Error(data.error || `Clip failed: HTTP ${response.status}`);+ return { data, baseUrl };+ }++ global.LLMWikiClipper = Object.freeze({+ DEFAULT_API_URLS,+ MAX_EXTRACTED_CONTENT_CHARS,+ normalizeServerUrl,+ loadSettings,+ clipFetch,+ extractActiveTab,+ loadProjects,+ selectProject,+ submitClip,+ });+})(globalThis);diff --git a/extension/manifest.json b/extension/manifest.jsonindex 3829f2d0..a69c2497 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -20,6 +20,18 @@"128": "icon128.png"}},+ "background": {+ "service_worker": "background.js"+ },+ "commands": {+ "clip-current-page": {+ "suggested_key": {+ "default": "Alt+Shift+L",+ "mac": "Command+Shift+L"+ },+ "description": "Clip the current page to LLM Wiki"+ }+ },"icons": {"16": "icon16.png","48": "icon48.png",diff --git a/extension/popup.html b/extension/popup.htmlindex 61402bfb..f8599367 100644--- a/extension/popup.html+++ b/extension/popup.html@@ -178,9 +178,11 @@</div><div class="footer">- Content will be saved and auto-ingested into your wiki+ <div>Content will be saved and auto-ingested into your wiki</div>+ <div id="shortcutHint" style="margin-top: 2px; color: #6b7280;">Loading shortcut...</div></div>+ <script src="clipper-core.js"></script><script src="popup.js"></script></body></html>diff --git a/extension/popup.js b/extension/popup.jsindex 3f4e0208..63205448 100644--- a/extension/popup.js+++ b/extension/popup.js@@ -1,4 +1,4 @@-const API_URLS = ["http://127.0.0.1:19827", "http://localhost:19827"];+const clipperCore = globalThis.LLMWikiClipper;const statusBar = document.getElementById("statusBar");const titleInput = document.getElementById("titleInput");@@ -10,68 +10,28 @@ const serverUrlInput = document.getElementById("serverUrlInput");const accessTokenInput = document.getElementById("accessTokenInput");const saveConnectionBtn = document.getElementById("saveConnectionBtn");const connectionSettings = document.getElementById("connectionSettings");+const shortcutHint = document.getElementById("shortcutHint");let extractedContent = "";let pageUrl = "";-let apiUrl = API_URLS[0];+let apiUrl = clipperCore.DEFAULT_API_URLS[0];let accessToken = "";-function normalizeServerUrl(value) {- let candidate = String(value || "").trim();- if (!candidate) return API_URLS[0];- if (!/^https?:\/\//i.test(candidate)) candidate = `http://${candidate}`;- const parsed = new URL(candidate);- if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password) {- throw new Error("Use an http(s) address without embedded credentials");- }- if (parsed.pathname !== "/" || parsed.search || parsed.hash) {- throw new Error("Enter only the server origin, without a path, query, or fragment");- }- if (!parsed.port) parsed.port = "19827";- return parsed.origin;-}-async function loadConnectionSettings() {- const saved = await chrome.storage.local.get(["serverUrl", "accessToken"]);- try {- apiUrl = normalizeServerUrl(saved.serverUrl || API_URLS[0]);- } catch {- apiUrl = API_URLS[0];- connectionSettings.open = true;- }- accessToken = String(saved.accessToken || "");+ const saved = await clipperCore.loadSettings();+ apiUrl = saved.serverUrl;+ accessToken = saved.accessToken;serverUrlInput.value = apiUrl;accessTokenInput.value = accessToken;}-function requestHeaders(options) {- const headers = new Headers(options?.headers || {});- if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);- return headers;-}-async function clipFetch(path, options) {- const method = String(options?.method || "GET").toUpperCase();- // Only retry idempotent reads across host aliases. Retrying POST /clip can- // duplicate a clip if the server handled the first request but the response- // failed before the extension received it.- const isDefaultLocalAddress = API_URLS.includes(apiUrl);- const urls = method === "GET" && isDefaultLocalAddress- ? [apiUrl, ...API_URLS.filter((url) => url !== apiUrl)]- : [apiUrl];- let lastError;-- for (const baseUrl of urls) {- try {- const res = await fetch(`${baseUrl}${path}`, { ...options, headers: requestHeaders(options) });- apiUrl = baseUrl;- return res;- } catch (err) {- lastError = err;- }- }-- throw lastError || new Error("Unable to connect to LLM Wiki");+ const result = await clipperCore.clipFetch(path, options, {+ serverUrl: apiUrl,+ accessToken,+ });+ apiUrl = result.baseUrl;+ return result.response;}async function checkConnection() {@@ -104,14 +64,20 @@ async function loadProjects() {const res = await clipFetch("/projects", { method: "GET" });const data = await res.json();if (data.ok && data.projects?.length > 0) {+ const { preferredProjectPath } = await clipperCore.loadSettings();projectSelect.innerHTML = "";for (const proj of data.projects) {const opt = document.createElement("option");opt.value = proj.path;opt.textContent = proj.name + (proj.current ? " (current)" : "");- if (proj.current) opt.selected = true;+ if (proj.path === preferredProjectPath || (!preferredProjectPath && proj.current)) {+ opt.selected = true;+ }projectSelect.appendChild(opt);}+ if (!projectSelect.value && data.projects[0]) {+ projectSelect.value = data.projects[0].path;+ }return;}} catch {}@@ -130,146 +96,20 @@ async function loadProjects() {async function extractContent() {try {- const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });- if (!tab?.id) return;-- pageUrl = tab.url || "";- titleInput.value = tab.title || "Untitled";+ const page = await clipperCore.extractActiveTab();+ pageUrl = page.url;+ titleInput.value = page.title;urlPreview.textContent = pageUrl;-- // First inject Readability.js and Turndown.js into the page- await chrome.scripting.executeScript({- target: { tabId: tab.id },- files: ["Readability.js", "Turndown.js"],- });-- // Then extract content using them- const results = await chrome.scripting.executeScript({- target: { tabId: tab.id },- func: () => {- try {- // Use Readability to extract article content- const documentClone = document.cloneNode(true);- const reader = new window.Readability(documentClone);- const article = reader.parse();-- if (!article || !article.content) {- return { error: "Readability could not extract content" };- }-- // Use Turndown to convert HTML to Markdown- const turndown = new window.TurndownService({- headingStyle: "atx",- codeBlockStyle: "fenced",- bulletListMarker: "-",- });-- // Add table support- turndown.addRule("tableCell", {- filter: ["th", "td"],- replacement: (content) => ` ${content.trim()} |`,- });- turndown.addRule("tableRow", {- filter: "tr",- replacement: (content) => `|${content}\n`,- });- turndown.addRule("table", {- filter: "table",- replacement: (content) => {- // Add header separator after first row- const lines = content.trim().split("\n");- if (lines.length > 0) {- const cols = (lines[0].match(/\|/g) || []).length - 1;- const separator = "|" + " --- |".repeat(cols);- lines.splice(1, 0, separator);- }- return "\n\n" + lines.join("\n") + "\n\n";- },- });-- // Remove images that are tracking pixels or tiny- turndown.addRule("removeSmallImages", {- filter: (node) => {- if (node.nodeName !== "IMG") return false;- const w = parseInt(node.getAttribute("width") || "999");- const h = parseInt(node.getAttribute("height") || "999");- return w < 10 || h < 10;- },- replacement: () => "",- });-- const markdown = turndown.turndown(article.content);-- return {- title: article.title,- content: markdown,- excerpt: article.excerpt || "",- siteName: article.siteName || "",- length: article.length || 0,- };- } catch (err) {- return { error: err.message };- }- },- });-- if (results?.[0]?.result) {- const result = results[0].result;-- if (result.error) {- contentPreview.textContent = `Extraction failed: ${result.error}. Falling back...`;- await fallbackExtract(tab.id);- return;- }-- // Use Readability's title if better- if (result.title && result.title.length > 5) {- titleInput.value = result.title;- }-- extractedContent = result.content;- contentPreview.textContent = extractedContent;-- if (result.excerpt) {- contentPreview.textContent = "📝 " + result.excerpt + "\n\n---\n\n" + extractedContent;- }-- clipBtn.disabled = false;- } else {- await fallbackExtract(tab.id);- }+ extractedContent = page.content;+ contentPreview.textContent = page.excerpt+ ? `📝 ${page.excerpt}\n\n---\n\n${extractedContent}`+ : extractedContent;+ clipBtn.disabled = false;} catch (err) {contentPreview.textContent = `Error: ${err.message}`;}}-// Fallback: simple DOM extraction if Readability fails-async function fallbackExtract(tabId) {- const results = await chrome.scripting.executeScript({- target: { tabId },- func: () => {- const clone = document.body.cloneNode(true);- ["script", "style", "nav", "header", "footer", ".sidebar", ".ad", ".comments"]- .forEach((sel) => clone.querySelectorAll(sel).forEach((el) => el.remove()));-- return clone.innerText- .split("\n")- .map((l) => l.trim())- .filter((l) => l.length > 0)- .join("\n\n")- .slice(0, 50000);- },- });-- if (results?.[0]?.result) {- extractedContent = results[0].result;- contentPreview.textContent = extractedContent;- clipBtn.disabled = false;- } else {- contentPreview.textContent = "Failed to extract content";- }-}-async function sendClip() {const selectedProject = projectSelect.value;if (!selectedProject) {@@ -283,29 +123,23 @@ async function sendClip() {statusBar.textContent = "⏳ Sending to LLM Wiki...";try {- const res = await clipFetch("/clip", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- title: titleInput.value,- url: pageUrl,- content: extractedContent,- projectPath: selectedProject,- }),+ const result = await clipperCore.submitClip({+ title: titleInput.value,+ url: pageUrl,+ content: extractedContent,+ }, selectedProject, {+ serverUrl: apiUrl,+ accessToken,});-- const data = await res.json();-- if (data.ok) {- const projectName = projectSelect.options[projectSelect.selectedIndex]?.textContent || "project";- statusBar.className = "status success";- statusBar.textContent = `✓ Saved to ${projectName}`;- clipBtn.textContent = "✓ Clipped!";- } else {- statusBar.className = "status error";- statusBar.textContent = `✗ Error: ${data.error}`;- clipBtn.disabled = false;- }+ apiUrl = result.baseUrl;+ await chrome.storage.local.set({+ serverUrl: apiUrl,+ preferredProjectPath: selectedProject,+ });+ const projectName = projectSelect.options[projectSelect.selectedIndex]?.textContent || "project";+ statusBar.className = "status success";+ statusBar.textContent = `✓ Saved to ${projectName}`;+ clipBtn.textContent = "✓ Clipped!";} catch (err) {statusBar.className = "status error";statusBar.textContent = `✗ Connection failed: ${err.message}`;@@ -315,9 +149,15 @@ async function sendClip() {clipBtn.addEventListener("click", sendClip);+projectSelect.addEventListener("change", () => {+ if (projectSelect.value) {+ void chrome.storage.local.set({ preferredProjectPath: projectSelect.value });+ }+});+saveConnectionBtn.addEventListener("click", async () => {try {- const nextUrl = normalizeServerUrl(serverUrlInput.value);+ const nextUrl = clipperCore.normalizeServerUrl(serverUrlInput.value);const originPattern = `${new URL(nextUrl).origin}/*`;const granted = await chrome.permissions.request({ origins: [originPattern] });if (!granted) throw new Error("Host permission was not granted");@@ -348,6 +188,11 @@ function resizePreview() {}(async () => {+ const commands = await chrome.commands.getAll();+ const clipCommand = commands.find((command) => command.name === "clip-current-page");+ shortcutHint.textContent = clipCommand?.shortcut+ ? `Shortcut: ${clipCommand.shortcut}`+ : "Set a shortcut at chrome://extensions/shortcuts";await loadConnectionSettings();const connected = await checkConnection();// Always extract content so user can preview, even if app not running