-
-
{tx("OpenAI-compatible provider", "OpenAI 兼容接口配置")}
-
+
+
+
+ {provider.model.trim() || tx("No model configured", "未配置模型")}
+
+
+ {safeEndpointHost(provider.endpoint)} · {provider.timeoutSeconds}s
+
+
+ {apiKeyConfigured === null
+ ? tx("Checking secret…", "检查密钥中…")
+ : apiKeyConfigured
+ ? tx("Secret ready", "密钥就绪")
+ : tx("Secret missing", "需配置密钥")}
+
+
+
+
+
+
+
+
+
+ {providerExpanded && (
+
+
+
+
{tx("OpenAI-compatible provider", "OpenAI 兼容接口配置")}
+
+ {tx(
+ "Endpoint, model, and timeout sync across your account and this browser. The API key is read by the Worker from ",
+ "接口地址、模型与超时会同步至云端账户及当前浏览器;API 密钥由 Worker 从 ",
+ )}
+ DOCKMARK_AI_API_KEY
+ {tx(".", " 读取,绝不暴露给前端。")}
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
- {tx("Set the secret with ", "使用 ")}
- npx wrangler secret put DOCKMARK_AI_API_KEY
- {tx(
- " or in the Cloudflare dashboard. The endpoint must be public HTTPS.",
- " 或在 Cloudflare 控制台配置密钥;接口地址须为公网 HTTPS。",
- )}
-
-
+
+
+ )}
@@ -540,7 +646,9 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro
? tx("Review or discard current suggestions first", "请先处理当前预览建议")
: apiKeyConfigured === false
? tx("Configure Worker AI secret first", "请先配置 Worker AI 密钥")
- : tx(`Generate suggestions (${selectedIds.size})`, `生成建议 (${selectedIds.size})`)}
+ : !provider.model.trim()
+ ? tx("Configure AI model first", "请先配置 AI 模型")
+ : tx(`Generate suggestions (${selectedIds.size})`, `生成建议 (${selectedIds.size})`)}
diff --git a/apps/web/src/AiProviderSettingsPage.tsx b/apps/web/src/AiProviderSettingsPage.tsx
new file mode 100644
index 0000000..4e482dd
--- /dev/null
+++ b/apps/web/src/AiProviderSettingsPage.tsx
@@ -0,0 +1,390 @@
+/**
+ * [INPUT]: depends on DEFAULT_AI_SETTINGS and AiSettings from @dockmark/core; fetchAiSettings, saveCloudAiSettings, getAiProviderStatus, MIN_AI_TIMEOUT_SECONDS, MAX_AI_TIMEOUT_SECONDS from ./ai-organization; useI18n from ./i18n
+ * [OUTPUT]: exports AiProviderSettingsPage component for /app/settings/ai configuration and Worker secret diagnostics
+ * [POS]: Mounted by SettingsPage under /app/settings/ai. Manages D1-synced non-secret AI endpoint/model/timeout settings and DOCKMARK_AI_API_KEY readiness checks.
+ * [PROTOCOL]: Update this header on change, then check GEMINI.md
+ */
+import { useCallback, useEffect, useState, type FormEvent } from "react";
+import { DEFAULT_AI_SETTINGS, type AiSettings } from "@dockmark/core";
+import {
+ fetchAiSettings,
+ getAiProviderStatus,
+ MAX_AI_TIMEOUT_SECONDS,
+ MIN_AI_TIMEOUT_SECONDS,
+ saveCloudAiSettings,
+} from "./ai-organization";
+import { useI18n } from "./i18n";
+
+interface ProviderPreset {
+ id: string;
+ labelEn: string;
+ labelZh: string;
+ endpoint: string;
+ defaultModel: string;
+}
+
+const PROVIDER_PRESETS: ProviderPreset[] = [
+ {
+ id: "openai",
+ labelEn: "OpenAI",
+ labelZh: "OpenAI",
+ endpoint: "https://api.openai.com/v1/chat/completions",
+ defaultModel: "gpt-4o-mini",
+ },
+ {
+ id: "deepseek",
+ labelEn: "DeepSeek",
+ labelZh: "DeepSeek",
+ endpoint: "https://api.deepseek.com/v1/chat/completions",
+ defaultModel: "deepseek-chat",
+ },
+ {
+ id: "openrouter",
+ labelEn: "OpenRouter",
+ labelZh: "OpenRouter",
+ endpoint: "https://openrouter.ai/api/v1/chat/completions",
+ defaultModel: "openai/gpt-4o-mini",
+ },
+ {
+ id: "siliconflow",
+ labelEn: "SiliconFlow",
+ labelZh: "SiliconFlow 硅基流动",
+ endpoint: "https://api.siliconflow.cn/v1/chat/completions",
+ defaultModel: "Qwen/Qwen2.5-72B-Instruct",
+ },
+ {
+ id: "gemini",
+ labelEn: "Gemini",
+ labelZh: "Gemini",
+ endpoint: "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
+ defaultModel: "gemini-2.5-flash",
+ },
+ {
+ id: "groq",
+ labelEn: "Groq",
+ labelZh: "Groq",
+ endpoint: "https://api.groq.com/openai/v1/chat/completions",
+ defaultModel: "llama-3.3-70b-versatile",
+ },
+];
+
+const WRANGLER_SECRET_COMMAND = "npx wrangler secret put DOCKMARK_AI_API_KEY";
+
+function navigateApp(path: string) {
+ window.history.pushState({}, "", path);
+ window.dispatchEvent(new PopStateEvent("popstate"));
+}
+
+function formatSyncTime(value: string | null, locale: string, tx: (en: string, zh: string) => string) {
+ if (!value) return tx("Not saved to cloud yet", "尚未保存到云端");
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return tx("Synced", "已同步");
+ const formatted = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(date);
+ return tx(`Synced ${formatted}`, `同步于 ${formatted}`);
+}
+
+export function AiProviderSettingsPage() {
+ const { locale, tx } = useI18n();
+ const [settings, setSettings] = useState(DEFAULT_AI_SETTINGS);
+ const [endpoint, setEndpoint] = useState(DEFAULT_AI_SETTINGS.endpoint);
+ const [model, setModel] = useState(DEFAULT_AI_SETTINGS.model);
+ const [timeoutSeconds, setTimeoutSeconds] = useState(DEFAULT_AI_SETTINGS.timeoutSeconds);
+ const [apiKeyConfigured, setApiKeyConfigured] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [checkingKey, setCheckingKey] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [copiedCmd, setCopiedCmd] = useState(false);
+ const [error, setError] = useState(null);
+ const [notice, setNotice] = useState(null);
+
+ const hydrate = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const [cloudSettings, status] = await Promise.all([
+ fetchAiSettings(),
+ getAiProviderStatus().catch(() => null),
+ ]);
+ setSettings(cloudSettings);
+ setEndpoint(cloudSettings.endpoint);
+ setModel(cloudSettings.model);
+ setTimeoutSeconds(cloudSettings.timeoutSeconds);
+ setApiKeyConfigured(status ? status.apiKeyConfigured : null);
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : tx("Could not load AI settings.", "无法加载 AI 服务配置。"));
+ } finally {
+ setLoading(false);
+ }
+ }, [tx]);
+
+ useEffect(() => {
+ void hydrate();
+ }, [hydrate]);
+
+ useEffect(() => {
+ const onSettingsChanged = (event: Event) => {
+ const detail = (event as CustomEvent).detail;
+ if (!detail) return;
+ setSettings(detail);
+ setEndpoint(detail.endpoint);
+ setModel(detail.model);
+ setTimeoutSeconds(detail.timeoutSeconds);
+ };
+ window.addEventListener("dockmark:ai-settings", onSettingsChanged);
+ return () => window.removeEventListener("dockmark:ai-settings", onSettingsChanged);
+ }, []);
+
+ async function recheckStatus() {
+ setCheckingKey(true);
+ setError(null);
+ try {
+ const status = await getAiProviderStatus();
+ setApiKeyConfigured(status.apiKeyConfigured);
+ setNotice(
+ status.apiKeyConfigured
+ ? tx("Worker secret DOCKMARK_AI_API_KEY is configured and ready.", "检测到 Worker 密钥 DOCKMARK_AI_API_KEY 已配置就绪。")
+ : tx("Worker secret DOCKMARK_AI_API_KEY is not configured yet.", "尚未检测到 Worker 密钥 DOCKMARK_AI_API_KEY。"),
+ );
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : tx("Could not verify Worker secret status.", "检测 Worker 密钥状态失败。"));
+ } finally {
+ setCheckingKey(false);
+ }
+ }
+
+ function applyPreset(preset: ProviderPreset) {
+ setEndpoint(preset.endpoint);
+ if (!model.trim() || PROVIDER_PRESETS.some((candidate) => candidate.defaultModel === model.trim())) {
+ setModel(preset.defaultModel);
+ }
+ setNotice(null);
+ setError(null);
+ }
+
+ async function handleSubmit(event: FormEvent) {
+ event.preventDefault();
+ setSaving(true);
+ setError(null);
+ setNotice(null);
+ const trimmedEndpoint = endpoint.trim();
+ const clampedTimeout = Math.min(
+ MAX_AI_TIMEOUT_SECONDS,
+ Math.max(MIN_AI_TIMEOUT_SECONDS, Math.round(Number(timeoutSeconds) || DEFAULT_AI_SETTINGS.timeoutSeconds)),
+ );
+ try {
+ const saved = await saveCloudAiSettings({
+ endpoint: trimmedEndpoint,
+ model: model.trim(),
+ timeoutSeconds: clampedTimeout,
+ });
+ setSettings(saved);
+ setEndpoint(saved.endpoint);
+ setModel(saved.model);
+ setTimeoutSeconds(saved.timeoutSeconds);
+ setNotice(
+ tx(
+ "AI settings saved to D1 and synced locally across Inbox and Bookmarks.",
+ "AI 配置已保存至 D1 并同步到本地,收件箱与书签整理将立即生效。",
+ ),
+ );
+ } catch (caught) {
+ setError(caught instanceof Error ? caught.message : tx("Could not save AI settings.", "保存 AI 配置失败。"));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function copySecretCommand() {
+ try {
+ await navigator.clipboard.writeText(WRANGLER_SECRET_COMMAND);
+ setCopiedCmd(true);
+ window.setTimeout(() => setCopiedCmd(false), 1800);
+ } catch {
+ setError(tx("Could not copy command automatically. Copy it manually from the box.", "无法自动复制命令,请手动选中复制。"));
+ }
+ }
+
+ const normalizedEndpoint = endpoint.trim();
+ const isDirty =
+ normalizedEndpoint !== settings.endpoint ||
+ model.trim() !== settings.model ||
+ Number(timeoutSeconds) !== settings.timeoutSeconds;
+
+ return (
+
+
+
+
{tx("AI Service", "AI 服务")}
+
+ {tx(
+ "Configure your OpenAI-compatible Chat Completions endpoint and model once. Settings sync via D1 while your API key stays strictly inside Cloudflare Worker secrets.",
+ "统一配置 OpenAI 兼容的 Chat Completions 接口与模型。非敏感配置通过 D1 跨设备同步,API 密钥仅保留在 Cloudflare Worker Secret 中。",
+ )}
+
+
+
+ {isDirty ? tx("Unsaved edits", "有未保存修改") : tx("Cloud synced", "云端已同步")}
+ {loading ? tx("Loading AI settings…", "正在加载配置…") : formatSyncTime(settings.updatedAt, locale, tx)}
+
+
+
+ {error && {error}
}
+ {notice && {notice}
}
+
+
+
+
+
+
{tx("Provider Endpoint & Model", "服务商接口与模型")}
+
+ {tx(
+ "Pick a 1-click preset or enter any HTTPS OpenAI-compatible Chat Completions URL.",
+ "可一键填入常用服务商预设,或手动填写任意 HTTPS OpenAI 兼容接口地址。",
+ )}
+
+
+
+
+
+
{tx("Quick Presets", "快捷预设")}
+
+ {PROVIDER_PRESETS.map((preset) => (
+
+ ))}
+
+
+
+
+
+
+
+
+
+
{tx("Worker Secret Status", "Worker 密钥状态")}
+
{tx("Bound server-side via Cloudflare Workers secrets.", "由 Cloudflare Workers 服务端密钥安全注入。")}
+
+
+
+
+
+
+ {apiKeyConfigured === true
+ ? tx("DOCKMARK_AI_API_KEY · Ready", "DOCKMARK_AI_API_KEY · 已配置 Ready")
+ : apiKeyConfigured === false
+ ? tx("DOCKMARK_AI_API_KEY · Missing", "DOCKMARK_AI_API_KEY · 未配置 Missing")
+ : tx("Checking status…", "正在检测状态…")}
+
+
+
+
+
+ {WRANGLER_SECRET_COMMAND}
+
+
+
+
+ {tx(
+ "Run the Wrangler command above in your Dockmark deployment directory. Your API key stays encrypted inside Cloudflare Workers and never leaves the server.",
+ "在部署目录执行上方 Wrangler 命令即可写入密钥。密钥全程加密保存在 Cloudflare Workers 运行时内,不会暴露给前端或浏览器。",
+ )}
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index b27a26c..6118136 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -1,17 +1,20 @@
/**
- * [INPUT]: depends on @dockmark/core domain types, ./api, ./browser-bridge, ./i18n, ./LauncherDashboard, and workspace section manager views
- * [OUTPUT]: exports App root workspace shell with sticky 64px topbar, command palette launcher, and section router
+ * [INPUT]: depends on @dockmark/core domain types, ./api, ./browser-bridge, ./BrowserSettingsManager, ./i18n, ./LauncherDashboard, and workspace section manager views
+ * [OUTPUT]: exports App root workspace shell with sticky 64px topbar, customizable command palette shortcuts, and section router
* [POS]: Primary authenticated workspace mounted by PrivateRoot for /app and /app/(workspaces|sessions|bookmarks|search|transfer|extension).
* [PROTOCOL]: Update this header on change, then check GEMINI.md
*/
import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
-import type {
- Bookmark,
- Category,
- CommandResult,
- SearchEngine,
- SessionWithItems,
- WorkspaceWithItems,
+import {
+ normalizeBrowserSettings,
+ type Bookmark,
+ type BrowserSettings,
+ type Category,
+ type CommandResult,
+ type LauncherShortcutKey,
+ type SearchEngine,
+ type SessionWithItems,
+ type WorkspaceWithItems,
} from "@dockmark/core";
import {
activateBridgeTab,
@@ -29,6 +32,13 @@ import {
listSessions,
listWorkspaces,
} from "./api";
+import {
+ BROWSER_SETTINGS_EVENT,
+ BROWSER_SETTINGS_STORAGE_KEY,
+ fetchCloudBrowserSettings,
+ readLocalBrowserSettings,
+ writeLocalBrowserSettings,
+} from "./BrowserSettingsManager";
import { useI18n } from "./i18n";
import { listInbox } from "./inbox-api";
import {
@@ -79,9 +89,27 @@ function openUrls(urls: string[]) {
}
}
+function matchesLauncherShortcut(event: KeyboardEvent, shortcut: LauncherShortcutKey): boolean {
+ const key = event.key.toLowerCase();
+ if (shortcut === "mod-j") {
+ return (event.metaKey || event.ctrlKey) && !event.altKey && key === "j";
+ }
+ if (shortcut === "alt-k") {
+ return event.altKey && !event.metaKey && !event.ctrlKey && key === "k";
+ }
+ return (event.metaKey || event.ctrlKey) && !event.altKey && key === "k";
+}
+
+function shortcutBadgeLabel(shortcut: LauncherShortcutKey): string {
+ if (shortcut === "mod-j") return "⌘ J";
+ if (shortcut === "alt-k") return "⌥ K";
+ return "⌘ K";
+}
+
export function App() {
const { locale, tx } = useI18n();
const [view, setView] = useState(() => viewFromPath(window.location.pathname));
+ const [browserSettings, setBrowserSettings] = useState(() => readLocalBrowserSettings());
const [query, setQuery] = useState("");
const [selectedIndex, setSelectedIndex] = useState(0);
const [bookmarks, setBookmarks] = useState([]);
@@ -174,6 +202,33 @@ export function App() {
};
}, [refreshBridge]);
+ useEffect(() => {
+ const onBrowserSettings = (event: Event) => {
+ const detail = (event as CustomEvent).detail;
+ setBrowserSettings(detail ? normalizeBrowserSettings(detail) : readLocalBrowserSettings());
+ };
+ const onStorage = (event: StorageEvent) => {
+ if (event.key === BROWSER_SETTINGS_STORAGE_KEY) {
+ setBrowserSettings(readLocalBrowserSettings());
+ }
+ };
+ window.addEventListener(BROWSER_SETTINGS_EVENT, onBrowserSettings);
+ window.addEventListener("storage", onStorage);
+ let cancelled = false;
+ void fetchCloudBrowserSettings()
+ .then((cloud) => {
+ if (cancelled) return;
+ setBrowserSettings(cloud);
+ writeLocalBrowserSettings(cloud);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ window.removeEventListener(BROWSER_SETTINGS_EVENT, onBrowserSettings);
+ window.removeEventListener("storage", onStorage);
+ };
+ }, []);
+
useEffect(() => {
const focusLauncher = () => {
navigateView("launcher");
@@ -182,11 +237,12 @@ export function App() {
requestAnimationFrame(() => commandInputRef.current?.focus());
};
const onGlobalKeyDown = (event: KeyboardEvent) => {
- if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
+ if (matchesLauncherShortcut(event, browserSettings.launcherShortcut)) {
event.preventDefault();
focusLauncher();
return;
}
+ if (!browserSettings.slashFocus) return;
if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
const target = event.target;
if (
@@ -202,7 +258,7 @@ export function App() {
};
window.addEventListener("keydown", onGlobalKeyDown);
return () => window.removeEventListener("keydown", onGlobalKeyDown);
- }, [refreshBridge]);
+ }, [browserSettings.launcherShortcut, browserSettings.slashFocus, refreshBridge]);
const defaultEngine = useMemo(
() => searchEngines.find((engine) => engine.isDefault) ?? searchEngines[0] ?? null,
@@ -531,7 +587,7 @@ export function App() {
×
)}
- ⌘ K
+ {shortcutBadgeLabel(browserSettings.launcherShortcut)}
@@ -577,6 +633,7 @@ export function App() {
launcherStatus={launcherStatus}
loading={loading}
locale={locale}
+ slashFocus={browserSettings.slashFocus}
onSelectIndex={setSelectedIndex}
onExecute={executeResult}
/>
diff --git a/apps/web/src/BookmarkManagerLegacy.tsx b/apps/web/src/BookmarkManagerLegacy.tsx
index 07722d5..7a3ab54 100644
--- a/apps/web/src/BookmarkManagerLegacy.tsx
+++ b/apps/web/src/BookmarkManagerLegacy.tsx
@@ -1,11 +1,11 @@
/**
- * [INPUT]: depends on Bookmark, Category, CreateBookmarkInput from @dockmark/core; bookmark/category APIs from ./api, ./bookmark-details-api, ./bookmark-search, ./reorder-api; useI18n from ./i18n; BookmarkFavicon, BookmarkFields, HealthBadge, BookmarkCategorySidebar
- * [OUTPUT]: exports BookmarkManager component (library CRUD, filtering, drag-and-drop reordering, and quick health checks)
+ * [INPUT]: depends on useEffect, useMemo, useState from react; Bookmark, Category, CreateBookmarkInput from @dockmark/core; bookmark/category APIs from ./api, ./bookmark-details-api, ./bookmark-search, ./reorder-api; useI18n from ./i18n; BookmarkFavicon, BookmarkFields, HealthBadge, BookmarkCategorySidebar
+ * [OUTPUT]: exports BookmarkManager component (library CRUD, ?q= deep-linked search filtering, drag-and-drop reordering, and quick health checks)
* [POS]: main Library tab body rendered inside BookmarkManager.tsx
* [PROTOCOL]: Update this header on change, then check GEMINI.md
*/
-import { useMemo, useState, type DragEvent, type FormEvent } from "react";
+import { useEffect, useMemo, useState, type DragEvent, type FormEvent } from "react";
import type { Bookmark, Category, CreateBookmarkInput } from "@dockmark/core";
import {
checkBookmarkHealth,
@@ -87,6 +87,25 @@ function moveByOffset(ids: string[], id: string, offset: -1 | 1) {
return next;
}
+function readInitialQueryParam(): string {
+ try {
+ return new URLSearchParams(window.location.search).get("q") ?? "";
+ } catch {
+ return "";
+ }
+}
+
+function clearQueryParamFromUrl() {
+ try {
+ const url = new URL(window.location.href);
+ if (!url.searchParams.has("q")) return;
+ url.searchParams.delete("q");
+ window.history.replaceState({}, "", `${url.pathname}${url.search}${url.hash}`);
+ } catch {
+ // Ignore invalid location environments.
+ }
+}
+
export function BookmarkManager({ bookmarks, categories, bookmarkTags, loading, onChanged }: Props) {
const { tx } = useI18n();
const [draft, setDraft] = useState(emptyDraft);
@@ -95,7 +114,19 @@ export function BookmarkManager({ bookmarks, categories, bookmarkTags, loading,
const [newCategory, setNewCategory] = useState("");
const [editingCategoryId, setEditingCategoryId] = useState(null);
const [editingCategoryName, setEditingCategoryName] = useState("");
- const [query, setQuery] = useState("");
+ const [query, setQuery] = useState(() => readInitialQueryParam());
+
+ useEffect(() => {
+ clearQueryParamFromUrl();
+ const onPopState = () => {
+ const next = readInitialQueryParam();
+ if (!next) return;
+ setQuery(next);
+ clearQueryParamFromUrl();
+ };
+ window.addEventListener("popstate", onPopState);
+ return () => window.removeEventListener("popstate", onPopState);
+ }, []);
const [activeTag, setActiveTag] = useState(null);
const [busy, setBusy] = useState(false);
const [creatingBookmark, setCreatingBookmark] = useState(false);
@@ -502,6 +533,16 @@ export function BookmarkManager({ bookmarks, categories, bookmarkTags, loading,
placeholder={tx("Search title, URL, description, category, or #tag…", "搜索标题、网址、描述、分类或 #标签…")}
aria-label={tx("Search bookmark library", "搜索书签库")}
/>
+ {query && (
+
+ )}
{tx(
diff --git a/apps/web/src/BrowserSettingsManager.tsx b/apps/web/src/BrowserSettingsManager.tsx
index 95e4c45..a22515b 100644
--- a/apps/web/src/BrowserSettingsManager.tsx
+++ b/apps/web/src/BrowserSettingsManager.tsx
@@ -1,7 +1,7 @@
/**
- * [INPUT]: depends on DEFAULT_BROWSER_SETTINGS, normalizeBrowserSettings, BrowserSettings, SearchEngine from @dockmark/core; useI18n from ./i18n; and ./settings.css
- * [OUTPUT]: exports BrowserSettingsManager panel for local-first and cloud-synced New Tab and bookmark conflict policies
- * [POS]: Shared between SettingsPage (/app/settings/browser) and BrowserExtensionManager (/app/extension). Persists settings to localStorage and PATCH /api/settings/browser.
+ * [INPUT]: depends on DEFAULT_BROWSER_SETTINGS, normalizeBrowserSettings, BrowserSettings, LauncherShortcutKey, SearchEngine from @dockmark/core; useI18n from ./i18n; and ./settings.css
+ * [OUTPUT]: exports BROWSER_SETTINGS_STORAGE_KEY, BROWSER_SETTINGS_EVENT, readLocalBrowserSettings, and BrowserSettingsManager panel for launcher shortcuts, New Tab preferences, and bookmark conflict policies
+ * [POS]: Shared between SettingsPage (/app/settings/browser) and BrowserExtensionManager (/app/extension). Persists settings to localStorage, broadcasts dockmark:browser-settings, and syncs via PATCH /api/settings/browser.
* [PROTOCOL]: Update this header on change, then check GEMINI.md
*/
import { useEffect, useMemo, useState } from "react";
@@ -9,27 +9,35 @@ import {
DEFAULT_BROWSER_SETTINGS,
normalizeBrowserSettings,
type BrowserSettings,
+ type LauncherShortcutKey,
type SearchEngine,
} from "@dockmark/core";
import { useI18n } from "./i18n";
import "./settings.css";
-const LOCAL_SETTINGS_KEY = "dockmarkBrowserSettingsV1";
+export const BROWSER_SETTINGS_STORAGE_KEY = "dockmarkBrowserSettingsV1";
+export const BROWSER_SETTINGS_EVENT = "dockmark:browser-settings";
-function readLocalSettings() {
+export function readLocalBrowserSettings(): BrowserSettings {
try {
- const raw = window.localStorage.getItem(LOCAL_SETTINGS_KEY);
+ const raw = window.localStorage.getItem(BROWSER_SETTINGS_STORAGE_KEY);
return raw ? normalizeBrowserSettings(JSON.parse(raw)) : normalizeBrowserSettings(DEFAULT_BROWSER_SETTINGS);
} catch {
return normalizeBrowserSettings(DEFAULT_BROWSER_SETTINGS);
}
}
-function writeLocalSettings(settings: BrowserSettings) {
- window.localStorage.setItem(LOCAL_SETTINGS_KEY, JSON.stringify(settings));
+export function writeLocalBrowserSettings(settings: BrowserSettings) {
+ const normalized = normalizeBrowserSettings(settings);
+ try {
+ window.localStorage.setItem(BROWSER_SETTINGS_STORAGE_KEY, JSON.stringify(normalized));
+ } catch {
+ // Ignore storage quota or private-browsing failures.
+ }
+ window.dispatchEvent(new CustomEvent(BROWSER_SETTINGS_EVENT, { detail: normalized }));
}
-async function fetchCloudSettings() {
+export async function fetchCloudBrowserSettings(): Promise {
const response = await fetch("/api/settings/browser", {
headers: { accept: "application/json" },
cache: "no-store",
@@ -58,6 +66,8 @@ async function saveCloudSettings(settings: BrowserSettings) {
},
body: JSON.stringify({
conflictPreference: settings.conflictPreference,
+ launcherShortcut: settings.launcherShortcut,
+ slashFocus: settings.slashFocus,
newTab: settings.newTab,
}),
});
@@ -79,7 +89,7 @@ function dateLabel(value: string | null, locale: string, tx: (en: string, zh: st
export function BrowserSettingsManager() {
const { locale, tx } = useI18n();
- const [settings, setSettings] = useState(() => readLocalSettings());
+ const [settings, setSettings] = useState(() => readLocalBrowserSettings());
const [engines, setEngines] = useState([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -88,12 +98,12 @@ export function BrowserSettingsManager() {
useEffect(() => {
let cancelled = false;
- void Promise.all([fetchCloudSettings(), fetchSearchEngines()])
+ void Promise.all([fetchCloudBrowserSettings(), fetchSearchEngines()])
.then(([cloud, nextEngines]) => {
if (cancelled) return;
setSettings(cloud);
setEngines(nextEngines);
- writeLocalSettings(cloud);
+ writeLocalBrowserSettings(cloud);
setDirty(false);
setMessage(null);
})
@@ -117,7 +127,7 @@ export function BrowserSettingsManager() {
function update(next: BrowserSettings) {
setSettings(next);
- writeLocalSettings(next);
+ writeLocalBrowserSettings(next);
setDirty(true);
setMessage(tx("Saved locally. Sync to cloud to share this policy with Dockmark New Tab.", "已在本地保存,点击同步后将推送到云端及 Dockmark New Tab。"));
}
@@ -141,7 +151,7 @@ export function BrowserSettingsManager() {
try {
const saved = await saveCloudSettings(settings);
setSettings(saved);
- writeLocalSettings(saved);
+ writeLocalBrowserSettings(saved);
setDirty(false);
setMessage(tx("Settings synced. New Tab will pick them up on its next refresh.", "设置已同步,新标签页将在下次刷新时生效。"));
} catch (error) {
@@ -236,6 +246,64 @@ export function BrowserSettingsManager() {
+
+
+
+
{tx("Launcher shortcuts", "启动台快捷键")}
+
+ {tx(
+ "Choose the keyboard shortcut that jumps straight into the Dockmark command bar across Web workspace views.",
+ "自定义在网页工作台任意页面快速唤起 Dockmark 命令框的键盘快捷键。",
+ )}
+
+
+
+
+
+
{tx("Command palette shortcut", "唤起命令框快捷键")}
+
+ {([
+ ["mod-k", "⌘K / Ctrl+K"],
+ ["mod-j", "⌘J / Ctrl+J"],
+ ["alt-k", "Alt+K"],
+ ] as Array<[LauncherShortcutKey, string]>).map(([shortcutValue, label]) => (
+
+ ))}
+
+
+
+
+
+
+ {tx(
+ "Tip: To customize the browser-wide Dockmark extension shortcut (default ",
+ "提示:如需修改浏览器全局唤起扩展的快捷键(默认 ",
+ )}
+ Alt+Shift+D
+ {tx("), open ", "),请在浏览器地址栏打开 ")}
+ chrome://extensions/shortcuts
+ {tx(".", " 进行自定义。")}
+
+
+
+
diff --git a/apps/web/src/DuplicateReviewPage.tsx b/apps/web/src/DuplicateReviewPage.tsx
index 4c59eb5..c702380 100644
--- a/apps/web/src/DuplicateReviewPage.tsx
+++ b/apps/web/src/DuplicateReviewPage.tsx
@@ -1,17 +1,19 @@
/**
- * [INPUT]: depends on useEffect, useMemo, useState from react; HEALTH_POLICY_LABELS, HEALTH_STATUS_LABELS, ResolvedLocale from @dockmark/core; getDuplicateReview, DuplicateCandidateKind, DuplicateReviewCandidate, DuplicateReviewMember, DuplicateReviewResult from ./duplicate-review-api; useI18n from ./i18n; BookmarkFavicon, safeDomainLabel from ./BookmarkFavicon; ./duplicate-review.css
- * [OUTPUT]: exports DuplicateReviewPage component for read-only side-by-side inspection of conservative duplicate bookmark pairs
- * [POS]: top-level /app/duplicates workspace; displays URL/metadata evidence without mutating bookmarks
+ * [INPUT]: depends on useEffect, useMemo, useState from react; formatRelativeTime, HEALTH_POLICY_LABELS, HEALTH_STATUS_LABELS, ResolvedLocale from @dockmark/core; textMatchesQuery from ./bookmark-search; maintainLibraryBatch from ./library-maintenance-api; getDuplicateReview and DuplicateReview types from ./duplicate-review-api; useI18n from ./i18n; BookmarkFavicon, safeDomainLabel from ./BookmarkFavicon; ./duplicate-review.css
+ * [OUTPUT]: exports DuplicateReviewPage component for side-by-side duplicate bookmark inspection, URL diff highlighting, safe reviewed archive/undo, and Library deep-linking
+ * [POS]: top-level /app/duplicates workspace; never auto-mutates bookmarks and records explicit archive/restore actions in the Change Journal
* [PROTOCOL]: Update this header on change, then check GEMINI.md
*/
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useState, type ReactNode } from "react";
import {
+ formatRelativeTime,
HEALTH_POLICY_LABELS,
HEALTH_STATUS_LABELS,
type ResolvedLocale,
} from "@dockmark/core";
import { BookmarkFavicon, safeDomainLabel } from "./BookmarkFavicon";
+import { textMatchesQuery } from "./bookmark-search";
import {
getDuplicateReview,
type DuplicateCandidateKind,
@@ -20,17 +22,24 @@ import {
type DuplicateReviewResult,
} from "./duplicate-review-api";
import { useI18n } from "./i18n";
+import { maintainLibraryBatch } from "./library-maintenance-api";
import "./duplicate-review.css";
type TxFn = (en: string, zh: string) => string;
+interface ArchiveNotice {
+ archivedId: string;
+ archivedTitle: string;
+ keptTitle: string;
+}
+
const KNOWN_REASON_ZH: Record
= {
"Saved page metadata points these bookmarks at the same canonical target.":
"已保存的页面元数据显示这两条书签指向同一个规范链接目标。",
"Saved metadata shows these bookmarks resolving to the same final target.":
"已保存的页面元数据显示这两条书签最终跳转到同一个目标地址。",
"The URLs become equivalent after ignoring protocol/www, fragments, trailing slashes and known tracking parameters.":
- "忽略协议/www、锚点片段、末尾斜杠及常见追踪参数后,两条链接等价。",
+ "忽略协议/www、文档锚点、末尾斜杠及常见追踪参数后,两条链接等价。",
};
function kindLabel(kind: DuplicateCandidateKind, tx: TxFn): string {
@@ -70,7 +79,7 @@ function healthStatusLabel(status: string, locale: ResolvedLocale): string {
return labels[status] ?? status;
}
-function formatFetchedDate(value: string, locale: ResolvedLocale): string {
+function formatFullDate(value: string, locale: ResolvedLocale): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat(locale, {
@@ -82,10 +91,43 @@ function formatFetchedDate(value: string, locale: ResolvedLocale): string {
}).format(date);
}
+function renderUrlWithDiff(url: string, otherUrl: string): ReactNode {
+ const leftChars = Array.from(url);
+ const rightChars = Array.from(otherUrl);
+ let prefixLen = 0;
+ while (
+ prefixLen < leftChars.length &&
+ prefixLen < rightChars.length &&
+ leftChars[prefixLen] === rightChars[prefixLen]
+ ) {
+ prefixLen += 1;
+ }
+
+ let suffixLen = 0;
+ while (
+ suffixLen < leftChars.length - prefixLen &&
+ suffixLen < rightChars.length - prefixLen &&
+ leftChars[leftChars.length - 1 - suffixLen] === rightChars[rightChars.length - 1 - suffixLen]
+ ) {
+ suffixLen += 1;
+ }
+
+ const diff = leftChars.slice(prefixLen, leftChars.length - suffixLen).join("");
+ if (!diff) return url;
+ const prefix = leftChars.slice(0, prefixLen).join("");
+ const suffix = suffixLen > 0 ? leftChars.slice(leftChars.length - suffixLen).join("") : "";
+
+ return (
+ <>
+ {prefix}
+ {diff}
+ {suffix}
+ >
+ );
+}
+
function matches(candidate: DuplicateReviewCandidate, query: string): boolean {
- const normalized = query.trim().toLocaleLowerCase();
- if (!normalized) return true;
- const haystack = [
+ return textMatchesQuery(query, [
candidate.left.title,
candidate.left.url,
candidate.left.categoryName ?? "",
@@ -93,24 +135,30 @@ function matches(candidate: DuplicateReviewCandidate, query: string): boolean {
candidate.right.url,
candidate.right.categoryName ?? "",
candidate.evidenceUrl ?? "",
- ]
- .join("\n")
- .toLocaleLowerCase();
- return normalized.split(/\s+/).every((token) => haystack.includes(token));
+ ]);
+}
+
+function locateInLibrary(title: string) {
+ window.history.pushState({}, "", `/app/bookmarks?q=${encodeURIComponent(title)}`);
+ window.dispatchEvent(new PopStateEvent("popstate"));
}
function MemberCard({
side,
- candidate,
+ bookmark,
+ otherUrl,
locale,
tx,
}: {
side: "left" | "right";
- candidate: DuplicateReviewCandidate;
+ bookmark: DuplicateReviewMember;
+ otherUrl: string;
locale: ResolvedLocale;
tx: TxFn;
}) {
- const bookmark = candidate[side] as DuplicateReviewMember & { iconUrl?: string | null };
+ const timestamp = bookmark.updatedAt ?? bookmark.createdAt ?? null;
+ const relativeUpdated = timestamp ? formatRelativeTime(timestamp, locale) : null;
+
return (
@@ -125,16 +173,25 @@ function MemberCard({
{side === "left" ? "A" : "B"}
{bookmark.title}
-
- {safeDomainLabel(bookmark.url)} · {bookmark.categoryName ?? tx("Uncategorized", "未分类")} ·{" "}
- {healthPolicyLabel(bookmark.healthPolicy, locale)} ·{" "}
- {healthStatusLabel(bookmark.healthStatus, locale)}
-
+
+ {safeDomainLabel(bookmark.url)}
+
+ {bookmark.categoryName ?? tx("Uncategorized", "未分类")}
+
+
+ {healthPolicyLabel(bookmark.healthPolicy, locale)} · {healthStatusLabel(bookmark.healthStatus, locale)}
+
+ {relativeUpdated && timestamp && (
+
+ {tx(`Updated ${relativeUpdated}`, `更新于 ${relativeUpdated}`)}
+
+ )}
+
-
- {bookmark.url}
+
+ {renderUrlWithDiff(bookmark.url, otherUrl)}
{bookmark.description && {bookmark.description}
}
@@ -155,8 +212,8 @@ function MemberCard({
{bookmark.metadataFetchedAt && (
{tx(
- `Metadata fetched ${formatFetchedDate(bookmark.metadataFetchedAt, locale)}`,
- `元数据抓取于 ${formatFetchedDate(bookmark.metadataFetchedAt, locale)}`,
+ `Metadata fetched ${formatFullDate(bookmark.metadataFetchedAt, locale)}`,
+ `元数据抓取于 ${formatFullDate(bookmark.metadataFetchedAt, locale)}`,
)}
)}
@@ -174,13 +231,21 @@ export function DuplicateReviewPage() {
const [query, setQuery] = useState("");
const [kind, setKind] = useState<"all" | DuplicateCandidateKind>("all");
const [hiddenIds, setHiddenIds] = useState>(() => new Set());
+ const [busyCandidateId, setBusyCandidateId] = useState(null);
+ const [undoBusy, setUndoBusy] = useState(false);
+ const [archiveNotice, setArchiveNotice] = useState(null);
+ const [restoreNotice, setRestoreNotice] = useState(null);
- async function refresh() {
+ async function refresh(options?: { keepHidden?: boolean; keepNotices?: boolean }) {
setLoading(true);
setError(null);
+ if (!options?.keepNotices) {
+ setArchiveNotice(null);
+ setRestoreNotice(null);
+ }
try {
setResult(await getDuplicateReview());
- setHiddenIds(new Set());
+ if (!options?.keepHidden) setHiddenIds(new Set());
} catch (caught) {
setError(
caught instanceof Error
@@ -211,7 +276,64 @@ export function DuplicateReviewPage() {
setHiddenIds((current) => new Set(current).add(id));
}
+ async function archiveDuplicate(candidate: DuplicateReviewCandidate, keepSide: "left" | "right") {
+ const kept = candidate[keepSide];
+ const archived = keepSide === "left" ? candidate.right : candidate.left;
+ setBusyCandidateId(candidate.id);
+ setError(null);
+ setRestoreNotice(null);
+ try {
+ await maintainLibraryBatch({ bookmarkIds: [archived.id], action: "archive" });
+ setArchiveNotice({
+ archivedId: archived.id,
+ archivedTitle: archived.title,
+ keptTitle: kept.title,
+ });
+ await refresh({ keepHidden: true, keepNotices: true });
+ } catch (caught) {
+ setError(
+ caught instanceof Error
+ ? caught.message
+ : tx("Could not archive the duplicate bookmark.", "无法归档该重复书签。"),
+ );
+ } finally {
+ setBusyCandidateId(null);
+ }
+ }
+
+ async function undoArchive() {
+ if (!archiveNotice) return;
+ const target = archiveNotice;
+ setUndoBusy(true);
+ setError(null);
+ try {
+ await maintainLibraryBatch({ bookmarkIds: [target.archivedId], action: "restore" });
+ setArchiveNotice(null);
+ setRestoreNotice(
+ tx(
+ `Restored “${target.archivedTitle}” back to your library.`,
+ `已将「${target.archivedTitle}」恢复至书签库。`,
+ ),
+ );
+ await refresh({ keepHidden: true, keepNotices: true });
+ } catch (caught) {
+ setError(
+ caught instanceof Error
+ ? caught.message
+ : tx("Could not restore the archived bookmark.", "无法撤销归档该书签。"),
+ );
+ } finally {
+ setUndoBusy(false);
+ }
+ }
+
const stats = result?.stats;
+ const kindOptions: Array<{ id: "all" | DuplicateCandidateKind; label: string; count: number }> = [
+ { id: "all", label: tx("All", "全部"), count: stats?.totalCandidates ?? 0 },
+ { id: "canonical", label: tx("Canonical", "规范链接"), count: stats?.canonicalCandidates ?? 0 },
+ { id: "resolved", label: tx("Resolved", "跳转目标"), count: stats?.resolvedCandidates ?? 0 },
+ { id: "normalized", label: tx("URL variants", "URL 变体"), count: stats?.normalizedCandidates ?? 0 },
+ ];
return (
@@ -220,8 +342,8 @@ export function DuplicateReviewPage() {
{tx("Duplicate Review", "重复项审查")}
{tx(
- "Compare saved URLs with canonical and resolved metadata evidence. Read-only — Dockmark never merges, edits, or deletes bookmarks automatically.",
- "结合规范链接与跳转目标元数据识别候选重复书签。仅提供审查建议,不会自动合并、修改或删除书签。",
+ "Compare saved URLs with canonical and resolved metadata evidence. Nothing mutates automatically — keep one side to safely archive the duplicate with instant undo and Change Journal tracking.",
+ "结合规范链接与跳转目标元数据识别候选重复书签。不会自动修改数据,可手动保留一侧并安全归档另一侧,支持一键撤销与变更日志追踪。",
)}
@@ -243,6 +365,49 @@ export function DuplicateReviewPage() {
{error &&