// ==UserScript== // @name [LINUX DO] 🌟 话题 & 回复 总结 [20260830] v1.0.17 // @namespace 0_V userscripts/[LINUX DO] 🌟 主题 & 回复 总结 // @description 在 Linux.do 的话题页和列表页一键生成结构化总结,支持自动总结、历史回看、Toast 提醒、配置导入导出与 Google Drive 同步。 // @version [20260830] v1.0.17 // @update-log [20260830] v1.0.17: Toast 长标题截断省略,固定卡片宽度;重试文案不再重复完整标题。 // @update-log [20260830] v1.0.16: 对照 A-E 补齐 toast/已总结同步:本地已有则停重试;busy 世代不错清;关掉 toast 立即取消;进列表取消过期自动总结。 // @update-log [20260830] v1.0.15: 纠正 toast 与已总结状态不同步;已有总结则停止重试;关掉 toast 会取消过期请求。 // @update-log [20260830] v1.0.14: 切左侧 tab 不再整窗重排,去掉 hover 位移,切换更跟手。 // @update-log [20260830] v1.0.13: 设置弹窗标题栏垂直对齐;折叠侧栏图标改为正文色,不再用蓝色。 // @update-log [20260830] v1.0.12: 提高当前子 tab 与其他子 tab 的对比度;选中用实色填充,未选中改弱对比。 // @update-log [20260830] v1.0.11: API 配置增加复制按钮;图片设置默认折叠。 // @update-log [20260830] v1.0.10: DeArrow 子 tab「开关」改为「自动」。 // @update-log [20260830] v1.0.9: DeArrow 设置拆成开关 / 提示词 / 模型与范围 三个子 tab。 // @update-log [20260830] v1.0.8: 选中 tab 沿用原填充底色,去掉 accent 混色与描边;焦点环只给键盘。 // @update-log [20260830] v1.0.7: 打开设置不再聚焦左上角折叠按钮;tab 选中改填充,焦点环只给键盘。 // @update-log [20260830] v1.0.6: 锁定设置弹窗外壳高度,切 tab 不再上下跳;面板内滚动。 // @update-log [20260830] v1.0.5: 设置输入字号对齐 --font-0;密钥查看改为 FormKit 风格图标钮。 // @update-log [20260830] v1.0.4: 恢复 4px 圆角 + 实色 accent 焦点环;token 走 --d-input-* / --ld-accent。 // @update-log [20260830] v1.0.3: 按钮统一 8px / 40px,与输入同套 focus-visible;保存/删除/添加/侧栏操作。 // @update-log [20260830] v1.0.2: 输入框统一 token、8px 圆角、半透明 focus-visible;密钥/开关/滑块/只读主题 ID。 // @update-log [20260830] v1.0.1: 设置弹窗高度跟随视口,面板内滚动;去掉标题冗余版本字。 // @original WhalelnColdSky // @match https://linux.do/* // @run-at document-end // @grant GM_setValue // @grant GM_getValue // @grant GM_xmlhttpRequest // @grant GM_registerMenuCommand // @connect oauth2.googleapis.com // @connect www.googleapis.com // @connect content.googleapis.com // @connect www.googleapis.cn // @connect linux.do // @connect *.linux.do // @connect ldstatic.com // @connect *.ldstatic.com // @connect discourse-cdn.com // @connect *.discourse-cdn.com // @icon data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGRlZnM+CiAgICAgIDxsaW5lYXJHcmFkaWVudCBpZD0icXVhbnR1bUdyYWRpZW50IiB4MT0iMCUiIHkxPSIwJSIgeDI9IjEwMCUiIHkyPSIxMDAlIj4KICAgICAgICAgIDxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiMxQTIwMjgiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgICAgICAgPHN0b3Agb2Zmc2V0PSI1MCUiIHN0b3AtY29sb3I9IiMyQzM2NDIiIHN0b3Atb3BhY2l0eT0iMC44Ii8+CiAgICAgICAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiMxRTI3MzMiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgICA8L2xpbmVhckdyYWRpZW50PgogICAgICA8cGF0dGVybiBpZD0icXVhbnR1bUdyaWQiIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+CiAgICAgICAgICA8cGF0aCBkPSJNMTAgMCBMMCAwIDAgMTAiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzNFNEE1NiIgc3Ryb2tlLXdpZHRoPSIwLjciIHN0cm9rZS1kYXNoYXJyYXk9IjEsMSIvPgogICAgICA8L3BhdHRlcm4+CiAgICAgIDxjbGlwUGF0aCBpZD0ic3BoZXJlQ2xpcCI+CiAgICAgICAgICA8Y2lyY2xlIGN4PSI2MCIgY3k9IjYwIiByPSI0NyIvPgogICAgICA8L2NsaXBQYXRoPgogICAgICA8ZmlsdGVyIGlkPSJxdWFudHVtUHVsc2UiPgogICAgICAgICAgPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iMyIvPgogICAgICAgICAgPGZlQ29sb3JNYXRyaXggdHlwZT0ibWF0cml4IiB2YWx1ZXM9IjEgMCAwIDAgMCAgMCAxIDAgMCAwICAwIDAgMSAwIDAgIDAgMCAwIDAuNiAwIi8+CiAgICAgICAgICA8ZmVCbGVuZCBtb2RlPSJzY3JlZW4iIGluMj0iU291cmNlR3JhcGhpYyIvPgogICAgICA8L2ZpbHRlcj4KICA8L2RlZnM+CiAgPGNpcmNsZSBjeD0iNjAiIGN5PSI2MCIgcj0iNTAiIGZpbGw9InVybCgjcXVhbnR1bUdyYWRpZW50KSIvPgogIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSJ1cmwoI3F1YW50dW1HcmlkKSIgb3BhY2l0eT0iMC4zIi8+CiAgPGcgY2xpcC1wYXRoPSJ1cmwoI3NwaGVyZUNsaXApIj4KICAgICAgPGc+CiAgICAgICAgICA8cmVjdCB4PSIxMCIgeT0iMTAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMzAiIGZpbGw9IiMxQzFDMUUiIHJ4PSI4IiByeT0iOCIgb3BhY2l0eT0iMC45Ij4KICAgICAgICAgICAgICA8YW5pbWF0ZSBhdHRyaWJ1dGVOYW1lPSJvcGFjaXR5IiB2YWx1ZXM9IjAuNzswLjk7MC43IiBkdXI9IjRzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIvPgogICAgICAgICAgPC9yZWN0PgogICAgICAgICAgPGc+CiAgICAgICAgICAgICAgPHJlY3QgeD0iMTAiIHk9IjQwIiB3aWR0aD0iMTAwIiBoZWlnaHQ9IjQwIiBmaWxsPSIjRjBGMEYwIiByeD0iOCIgcnk9IjgiLz4KICAgICAgICAgICAgICA8ZyBzdHJva2U9IiMyQzMwMzYiIHN0cm9rZS13aWR0aD0iMC43IiBmaWxsPSJub25lIiBvcGFjaXR5PSIwLjciPgogICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTUgNTAgSDEwNSBNMTUgNjAgSDEwNSBNMTUgNzAgSDEwNSIgc3Ryb2tlLWRhc2hhcnJheT0iMywyIi8+CiAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0yNSA0NSBWNzUgTTQ1IDQ1IFY3NSBNNjUgNDUgVjc1IE04NSA0NSBWNzUiIHN0cm9rZS1kYXNoYXJyYXk9IjIsMiIvPgogICAgICAgICAgICAgIDwvZz4KICAgICAgICAgIDwvZz4KICAgICAgICAgIDxyZWN0IHg9IjEwIiB5PSI4MCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIzMCIgZmlsbD0iI0ZGQjAwMyIgcng9IjgiIHJ5PSI4IiBvcGFjaXR5PSIwLjgiPgogICAgICAgICAgICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9Im9wYWNpdHkiIHZhbHVlcz0iMC42OzAuOTswLjYiIGR1cj0iNHMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+CiAgICAgICAgICA8L3JlY3Q+CiAgICAgIDwvZz4KICAgICAgPGc+CiAgICAgICAgICA8Y2lyY2xlIGN4PSI2MCIgY3k9IjYwIiByPSIxNSIgZmlsbD0iI0ZGNDUwMCIgZmlsdGVyPSJ1cmwoI3F1YW50dW1QdWxzZSkiIG9wYWNpdHk9IjAuOCI+CiAgICAgICAgICAgICAgPGFuaW1hdGUgYXR0cmlidXRlTmFtZT0iciIgdmFsdWVzPSIxMjsyMDsxMiIgZHVyPSI0cyIgcmVwZWF0Q291bnQ9ImluZGVmaW5pdGUiLz4KICAgICAgICAgIDwvY2lyY2xlPgogICAgICAgICAgPGc+CiAgICAgICAgICAgICAgPGNpcmNsZSBjeD0iNjAiIGN5PSI2MCIgcj0iMjUiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI0ZGNjM0NyIgc3Ryb2tlLXdpZHRoPSIyIiBvcGFjaXR5PSIwLjQiPgogICAgICAgICAgICAgICAgICA8YW5pbWF0ZSBhdHRyaWJ1dGVOYW1lPSJyIiB2YWx1ZXM9IjI1OzUwOzI1IiBkdXI9IjRzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIvPgogICAgICAgICAgICAgICAgICA8YW5pbWF0ZSBhdHRyaWJ1dGVOYW1lPSJvcGFjaXR5IiB2YWx1ZXM9IjAuNDswOzAuNCIgZHVyPSI0cyIgcmVwZWF0Q291bnQ9ImluZGVmaW5pdGUiLz4KICAgICAgICAgICAgICA8L2NpcmNsZT4KICAgICAgICAgICAgICA8Y2lyY2xlIGN4PSI2MCIgY3k9IjYwIiByPSIzNSIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjRkY3RjUwIiBzdHJva2Utd2lkdGg9IjEiIG9wYWNpdHk9IjAuMiI+CiAgICAgICAgICAgICAgICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9InIiIHZhbHVlcz0iMzU7NjA7MzUiIGR1cj0iNHMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+CiAgICAgICAgICAgICAgICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9Im9wYWNpdHkiIHZhbHVlcz0iMC4yOzA7MC4yIiBkdXI9IjRzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIvPgogICAgICAgICAgICAgIDwvY2lyY2xlPgogICAgICAgICAgPC9nPgogICAgICA8L2c+CiAgPC9nPgogIDxjaXJjbGUgY3g9IjYwIiBjeT0iNjAiIHI9IjU1IiBmaWxsPSJub25lIiBzdHJva2U9InVybCgjcXVhbnR1bUdyYWRpZW50KSIgc3Ryb2tlLXdpZHRoPSI0IiBvcGFjaXR5PSIwLjYiLz4KPC9zdmc+ // ==/UserScript== /* ===================== IMPORTANT · NOTICE · START ===================== * * 1. [编辑指引 | Edit Guidance] * • ⚠️ 这是一个自动生成的文件:请在新的 `src/` ESM 源码目录中进行修改,然后运行 `npm run build` 在 `dist/` 目录下重新生成。 * • ⚠️ This project bundles auto-generated artifacts. Make changes inside the new ESM source tree under `src/`, then run `npm run build` to regenerate everything under `dist/`. * * ---------------------------------------------------------------------- * * 2. ... * * ====================== IMPORTANT · NOTICE · END ====================== */ (() => { var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/platform/gm.js function resolveDirectGrant(name) { switch (name) { case "GM_setValue": return typeof GM_setValue === "function" ? GM_setValue : null; case "GM_getValue": return typeof GM_getValue === "function" ? GM_getValue : null; case "GM_xmlhttpRequest": return typeof GM_xmlhttpRequest === "function" ? GM_xmlhttpRequest : null; case "GM_registerMenuCommand": return typeof GM_registerMenuCommand === "function" ? GM_registerMenuCommand : null; default: return null; } } function resolveGrantFunction(name, fallbackNames = []) { const directGrant = resolveDirectGrant(name); if (typeof directGrant === "function") { return directGrant; } const globalObject = typeof globalThis !== "undefined" ? globalThis : null; const directGlobal = globalObject?.[name]; if (typeof directGlobal === "function") { return directGlobal.bind(globalObject); } const gmObject = globalObject?.GM; if (gmObject) { for (const fallbackName of fallbackNames) { const candidate = gmObject[fallbackName]; if (typeof candidate === "function") { return candidate.bind(gmObject); } } } throw new Error(`Missing required GM API: ${name}`); } function createGrantCaller(name, fallbackNames = []) { return (...args) => resolveGrantFunction(name, fallbackNames)(...args); } var gmSetValue = createGrantCaller("GM_setValue", ["setValue"]); var gmGetValue = createGrantCaller("GM_getValue", ["getValue"]); var gmXmlhttpRequest = createGrantCaller("GM_xmlhttpRequest", ["xmlHttpRequest", "xmlhttpRequest"]); var gmRegisterMenuCommand = createGrantCaller("GM_registerMenuCommand", ["registerMenuCommand"]); // src/state/appState.js var appState = { activeToastsByTopic: {}, topicTitleMap: {}, topicTitleFetchPromises: /* @__PURE__ */ new Map(), summarizingTopics: /* @__PURE__ */ new Set(), expandedSummaryRows: /* @__PURE__ */ new Set(), driveSummaryDirtyTopicIds: /* @__PURE__ */ new Set() }; // src/stores/configStore.js var defaultSummaryOutputFilters = { enabled: true, leadingTokens: ["```html"], trailingTokens: ["```"] }; var DEFAULT_AUTO_RETRY_COUNT = 5; var DEFAULT_AUTO_RETRY_INTERVAL = 6; var LEGACY_AUTO_RETRY_COUNT_KEY = "autoRetryCount"; var LEGACY_AUTO_RETRY_INTERVAL_KEY = "autoRetryInterval"; var DEFAULT_SUMMARY_WIDTH_OFFSET = 20; var LEGACY_SUMMARY_WIDTH_OFFSETS = /* @__PURE__ */ new Set([-40, -90]); var DEFAULT_API_CONFIGURATION = { name: "新API配置", url: "https://api.openai.com/v1/chat/completions", key: "", model: "gpt-4o-mini", imageInputEnabled: false, imageDetail: "auto", maxImagesPerRequest: 6, maxImageBytes: 4 * 1024 * 1024, maxTotalImageBytes: 12 * 1024 * 1024 }; var IMAGE_DETAIL_OPTIONS = /* @__PURE__ */ new Set(["auto", "low", "high"]); var defaultDriveSummarySettings = { enabled: false, clientId: "", clientSecret: "", refreshToken: "" }; function normalizeSummaryFilterList(list, fallback) { if (!Array.isArray(list)) return fallback.slice(); return list.map((item) => String(item).trim()).filter(Boolean); } function normalizeSummaryOutputFilters(filters) { if (!filters || typeof filters !== "object") { return { enabled: true, leadingTokens: defaultSummaryOutputFilters.leadingTokens.slice(), trailingTokens: defaultSummaryOutputFilters.trailingTokens.slice() }; } return { enabled: filters.enabled !== false, leadingTokens: normalizeSummaryFilterList(filters.leadingTokens, defaultSummaryOutputFilters.leadingTokens), trailingTokens: normalizeSummaryFilterList(filters.trailingTokens, defaultSummaryOutputFilters.trailingTokens) }; } function normalizeAutoRetryCount(value, fallback = DEFAULT_AUTO_RETRY_COUNT) { const fallbackValue = Number.isFinite(Number(fallback)) ? Math.min(10, Math.max(1, parseInt(fallback, 10))) : DEFAULT_AUTO_RETRY_COUNT; const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) return fallbackValue; return Math.min(10, Math.max(1, parsed)); } function normalizeAutoRetryInterval(value, fallback = DEFAULT_AUTO_RETRY_INTERVAL) { const fallbackValue = Number.isFinite(Number(fallback)) ? Math.min(600, Math.max(1, parseInt(fallback, 10))) : DEFAULT_AUTO_RETRY_INTERVAL; const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) return fallbackValue; return Math.min(600, Math.max(1, parsed)); } function normalizeImageDetail(value, fallback = DEFAULT_API_CONFIGURATION.imageDetail) { const normalized = typeof value === "string" ? value.trim().toLowerCase() : ""; if (IMAGE_DETAIL_OPTIONS.has(normalized)) return normalized; return IMAGE_DETAIL_OPTIONS.has(fallback) ? fallback : DEFAULT_API_CONFIGURATION.imageDetail; } function normalizeMaxImagesPerRequest(value, fallback = DEFAULT_API_CONFIGURATION.maxImagesPerRequest) { const fallbackValue = Number.isFinite(Number(fallback)) ? Math.min(20, Math.max(1, parseInt(fallback, 10))) : DEFAULT_API_CONFIGURATION.maxImagesPerRequest; const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) return fallbackValue; return Math.min(20, Math.max(1, parsed)); } function normalizeImageByteLimit(value, fallback = DEFAULT_API_CONFIGURATION.maxImageBytes) { const fallbackValue = Number.isFinite(Number(fallback)) ? Math.min(20 * 1024 * 1024, Math.max(256 * 1024, parseInt(fallback, 10))) : DEFAULT_API_CONFIGURATION.maxImageBytes; const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) return fallbackValue; return Math.min(20 * 1024 * 1024, Math.max(256 * 1024, parsed)); } function normalizeTotalImageByteLimit(value, fallback = DEFAULT_API_CONFIGURATION.maxTotalImageBytes) { const fallbackValue = Number.isFinite(Number(fallback)) ? Math.min(60 * 1024 * 1024, Math.max(256 * 1024, parseInt(fallback, 10))) : DEFAULT_API_CONFIGURATION.maxTotalImageBytes; const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) return fallbackValue; return Math.min(60 * 1024 * 1024, Math.max(256 * 1024, parsed)); } function normalizeApiConfiguration(config, retryFallback = {}) { const source = config && typeof config === "object" ? config : {}; const fallbackRetryCount = normalizeAutoRetryCount( retryFallback.retryCount, DEFAULT_AUTO_RETRY_COUNT ); const fallbackRetryInterval = normalizeAutoRetryInterval( retryFallback.retryInterval, DEFAULT_AUTO_RETRY_INTERVAL ); return { name: typeof source.name === "string" && source.name.trim() ? source.name.trim() : DEFAULT_API_CONFIGURATION.name, url: typeof source.url === "string" && source.url.trim() ? source.url.trim() : DEFAULT_API_CONFIGURATION.url, key: source.key === null || source.key === void 0 ? "" : String(source.key), model: typeof source.model === "string" && source.model.trim() ? source.model.trim() : DEFAULT_API_CONFIGURATION.model, retryCount: normalizeAutoRetryCount(source.retryCount, fallbackRetryCount), retryInterval: normalizeAutoRetryInterval(source.retryInterval, fallbackRetryInterval), imageInputEnabled: source.imageInputEnabled === true, imageDetail: normalizeImageDetail(source.imageDetail), maxImagesPerRequest: normalizeMaxImagesPerRequest(source.maxImagesPerRequest), maxImageBytes: normalizeImageByteLimit(source.maxImageBytes), maxTotalImageBytes: normalizeTotalImageByteLimit(source.maxTotalImageBytes) }; } function createDefaultApiConfiguration(overrides = {}, retryFallback = {}) { return normalizeApiConfiguration( { ...DEFAULT_API_CONFIGURATION, ...overrides }, retryFallback ); } function normalizeApiConfigurations(configurations, retryFallback = {}) { const sourceList = Array.isArray(configurations) ? configurations : []; const normalized = sourceList.map((config) => normalizeApiConfiguration(config, retryFallback)); if (normalized.length > 0) return normalized; return [createDefaultApiConfiguration({}, retryFallback)]; } function normalizeCurrentApiIndex(index, configurations = []) { const maxIndex = Array.isArray(configurations) && configurations.length > 0 ? configurations.length - 1 : 0; const parsed = parseInt(index, 10); if (Number.isNaN(parsed) || parsed < 0) return 0; return Math.min(parsed, maxIndex); } function normalizeDriveSummarySettings(settings) { if (!settings || typeof settings !== "object") { return { ...defaultDriveSummarySettings }; } return { enabled: settings.enabled === true, clientId: typeof settings.clientId === "string" ? settings.clientId.trim() : "", clientSecret: typeof settings.clientSecret === "string" ? settings.clientSecret.trim() : "", refreshToken: typeof settings.refreshToken === "string" ? settings.refreshToken.trim() : "" }; } function normalizeSummaryWidthOffset(value, fallback = DEFAULT_SUMMARY_WIDTH_OFFSET) { const parsedFallback = parseInt(fallback, 10); const normalizedFallback = Number.isNaN(parsedFallback) ? DEFAULT_SUMMARY_WIDTH_OFFSET : LEGACY_SUMMARY_WIDTH_OFFSETS.has(parsedFallback) ? DEFAULT_SUMMARY_WIDTH_OFFSET : Math.min(200, Math.max(-200, parsedFallback)); const parsed = parseInt(value, 10); if (Number.isNaN(parsed)) return normalizedFallback; if (LEGACY_SUMMARY_WIDTH_OFFSETS.has(parsed)) { return DEFAULT_SUMMARY_WIDTH_OFFSET; } return Math.min(200, Math.max(-200, parsed)); } function normalizeSummaryTopicId(topicId) { if (topicId === null || topicId === void 0) return ""; const normalized = String(topicId).trim(); return normalized || ""; } function sanitizeSummaryTopicIds(raw) { if (!Array.isArray(raw)) return []; const unique = /* @__PURE__ */ new Set(); raw.forEach((topicId) => { const normalized = normalizeSummaryTopicId(topicId); if (normalized) unique.add(normalized); }); return Array.from(unique); } // src/stores/historyStore.js var SUMMARY_HTML_HINT_RE = /<\/?[a-z][\w:-]*(\s[^<>]*?)?>/i; var SUMMARY_MARKDOWN_HINT_RE = /(^|\n)\s*(#{1,6}\s|[-*+]\s|\d+\.\s|>\s|```|~~~|---\s*$)/m; function normalizeSummaryRenderMode(renderMode, fallback = "") { const normalized = typeof renderMode === "string" ? renderMode.trim().toLowerCase() : ""; if (normalized.includes("markdown")) return "markdown"; if (normalized.includes("html")) return "html"; if (!fallback) return ""; const normalizedFallback = typeof fallback === "string" ? fallback.trim().toLowerCase() : ""; if (!normalizedFallback || normalizedFallback === normalized) return ""; return normalizeSummaryRenderMode(normalizedFallback, ""); } function inferSummaryRenderModeFromSummary(summary, fallback = "html") { const text = summary === null || summary === void 0 ? "" : String(summary).trim(); if (!text) return normalizeSummaryRenderMode(fallback, "html") || "html"; if (SUMMARY_HTML_HINT_RE.test(text)) return "html"; if (SUMMARY_MARKDOWN_HINT_RE.test(text)) return "markdown"; return normalizeSummaryRenderMode(fallback, "html") || "html"; } function normalizeSummaryHistoryItemForStorage(item) { if (!item || typeof item !== "object") return null; const normalized = { summary: item.summary === null || item.summary === void 0 ? "" : String(item.summary), timestamp: item.timestamp === null || item.timestamp === void 0 ? "" : String(item.timestamp), model: item.model === null || item.model === void 0 ? "" : String(item.model) }; const renderMode = normalizeSummaryRenderMode(item.renderMode, ""); if (renderMode) { normalized.renderMode = renderMode; } else if (normalized.summary.trim()) { normalized.renderMode = inferSummaryRenderModeFromSummary(normalized.summary, "html"); } if (!normalized.summary && !normalized.timestamp && !normalized.model && !normalized.renderMode) return null; return normalized; } function normalizeSummaryHistoryListForStorage(list) { if (!Array.isArray(list)) return []; const normalized = []; list.forEach((item) => { const normalizedItem = normalizeSummaryHistoryItemForStorage(item); if (normalizedItem) normalized.push(normalizedItem); }); return normalized; } function areSummaryHistoryListsEqual(left, right) { const normalizedLeft = normalizeSummaryHistoryListForStorage(left); const normalizedRight = normalizeSummaryHistoryListForStorage(right); if (normalizedLeft.length !== normalizedRight.length) return false; for (let index = 0; index < normalizedLeft.length; index += 1) { const current = normalizedLeft[index]; const next = normalizedRight[index]; if (!next) return false; if (current.summary !== next.summary || current.timestamp !== next.timestamp || current.model !== next.model || (current.renderMode || "") !== (next.renderMode || "")) { return false; } } return true; } function normalizeSummaryHistoryMapForStorage(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const normalized = {}; Object.keys(raw).forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (!normalizedTopicId) return; const list = normalizeSummaryHistoryListForStorage(raw[topicId]); if (list.length > 0 || Array.isArray(raw[topicId])) { normalized[normalizedTopicId] = list; } }); return normalized; } function getLatestSummaryTimestamp(list) { if (!Array.isArray(list)) return 0; let latest = 0; list.forEach((item) => { if (!item || typeof item !== "object") return; const time = Date.parse(item.timestamp || ""); if (Number.isFinite(time) && time > latest) { latest = time; } }); return latest; } function trimSummaryHistoryToLatestTopics(historyMap, limit) { if (!historyMap || typeof historyMap !== "object") return {}; const topics = Object.keys(historyMap).map((topicId, index) => ({ topicId, time: getLatestSummaryTimestamp(historyMap[topicId]), sequence: index })); if (topics.length <= limit) { return historyMap; } topics.sort((a, b2) => { if (b2.time !== a.time) return b2.time - a.time; return a.sequence - b2.sequence; }); const trimmed = {}; topics.slice(0, limit).forEach(({ topicId }) => { trimmed[topicId] = historyMap[topicId]; }); return trimmed; } // src/stores/questionStore.js var defaultQuestionPromptPresets = Object.freeze([ Object.freeze({ id: "builtin-resolved", name: "是否解决", prompt: "请判断这个话题中的主要问题或诉求是否已经解决。请用 Markdown 输出:结论、关键依据、仍需确认的点。" }), Object.freeze({ id: "builtin-best-solution", name: "最佳方案", prompt: "请从这个话题及回复中提炼当前最佳方案。请用 Markdown 输出:推荐方案、操作步骤、适用条件、风险或替代方案。" }) ]); function normalizeText(value) { return value === null || value === void 0 ? "" : String(value).trim(); } const SECRET_ICON_EYE = ''; const SECRET_ICON_EYE_SLASH = ''; function paintSecretToggle(button, revealed) { if (!button) return; const showLabel = button.getAttribute("data-show-label") || "显示密钥"; const hideLabel = button.getAttribute("data-hide-label") || "隐藏密钥"; button.innerHTML = revealed ? SECRET_ICON_EYE_SLASH : SECRET_ICON_EYE; button.setAttribute("aria-pressed", revealed ? "true" : "false"); button.setAttribute("aria-label", revealed ? hideLabel : showLabel); button.setAttribute("title", revealed ? hideLabel : showLabel); } function bindSecretField(wrap, options = {}) { if (!wrap || wrap.dataset.secretToggleBound === "true") return; const input = wrap.querySelector(".ld-secret-input") || wrap.querySelector("input, textarea"); const button = wrap.querySelector(".ld-secret-toggle"); if (!input || !button) return; wrap.dataset.secretToggleBound = "true"; const isTextarea = input.tagName === "TEXTAREA"; let revealed = false; const apply = () => { if (isTextarea) { input.classList.toggle("is-revealed", revealed); input.style.webkitTextSecurity = revealed ? "none" : "disc"; } else { input.type = revealed ? "text" : "password"; } wrap.classList.toggle("is-revealed", revealed); paintSecretToggle(button, revealed); if (typeof options.onRevealChange === "function") options.onRevealChange(revealed, input); }; const syncFocus = () => { wrap.classList.toggle("is-focused", wrap.contains(document.activeElement)); }; button.addEventListener("click", (event) => { event.preventDefault(); revealed = !revealed; apply(); if (typeof input.focus === "function") input.focus({ preventScroll: true }); }); wrap.addEventListener("focusin", syncFocus); wrap.addEventListener("focusout", syncFocus); apply(); } function createFallbackPresetId(index) { return `custom-${index + 1}`; } function normalizeQuestionPromptPreset(preset, index = 0) { if (!preset || typeof preset !== "object") return null; const name = normalizeText(preset.name); const prompt = normalizeText(preset.prompt); if (!name && !prompt) return null; const rawId = normalizeText(preset.id); return { id: rawId || createFallbackPresetId(index), name: name || `自定义预设 ${index + 1}`, prompt }; } function normalizeQuestionPromptPresets(presets) { if (!Array.isArray(presets)) return []; const normalized = []; const seen = /* @__PURE__ */ new Set(); presets.forEach((preset, index) => { const item = normalizeQuestionPromptPreset(preset, index); if (!item || seen.has(item.id)) return; seen.add(item.id); normalized.push(item); }); return normalized; } function getAllQuestionPromptPresets(customPresets = []) { return [ ...defaultQuestionPromptPresets.map((preset) => ({ ...preset, builtin: true })), ...normalizeQuestionPromptPresets(customPresets).map((preset) => ({ ...preset, builtin: false })) ]; } function normalizeTopicQuestionHistoryItemForStorage(item) { if (!item || typeof item !== "object") return null; const normalized = { id: normalizeText(item.id), question: item.question === null || item.question === void 0 ? "" : String(item.question), answer: item.answer === null || item.answer === void 0 ? "" : String(item.answer), presetId: normalizeText(item.presetId), presetName: normalizeText(item.presetName), timestamp: item.timestamp === null || item.timestamp === void 0 ? "" : String(item.timestamp), model: item.model === null || item.model === void 0 ? "" : String(item.model), renderMode: "markdown" }; if (!normalized.question && !normalized.answer && !normalized.timestamp && !normalized.model) { return null; } return normalized; } function normalizeTopicQuestionHistoryListForStorage(list) { if (!Array.isArray(list)) return []; const normalized = []; list.forEach((item) => { const normalizedItem = normalizeTopicQuestionHistoryItemForStorage(item); if (normalizedItem) normalized.push(normalizedItem); }); return normalized; } function normalizeTopicQuestionHistoryMapForStorage(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const normalized = {}; Object.keys(raw).forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (!normalizedTopicId) return; const list = normalizeTopicQuestionHistoryListForStorage(raw[topicId]); if (list.length > 0 || Array.isArray(raw[topicId])) { normalized[normalizedTopicId] = list; } }); return normalized; } function buildTopicQuestionHistoryEntryKey(item) { const id = normalizeText(item?.id); if (id) return `id:${id}`; return [ normalizeText(item?.timestamp), normalizeText(item?.model), normalizeText(item?.presetId), item?.question === null || item?.question === void 0 ? "" : String(item.question), item?.answer === null || item?.answer === void 0 ? "" : String(item.answer) ].join("::"); } function mergeTopicQuestionHistoryList(baseList, incomingList) { const combined = []; const seen = /* @__PURE__ */ new Set(); const addItem = (item) => { const normalizedItem = normalizeTopicQuestionHistoryItemForStorage(item); if (!normalizedItem) return; const key = buildTopicQuestionHistoryEntryKey(normalizedItem); if (seen.has(key)) return; seen.add(key); combined.push(normalizedItem); }; normalizeTopicQuestionHistoryListForStorage(baseList).forEach(addItem); normalizeTopicQuestionHistoryListForStorage(incomingList).forEach(addItem); combined.sort((a, b2) => { const timeA = Date.parse(a?.timestamp || ""); const timeB = Date.parse(b2?.timestamp || ""); if (!Number.isFinite(timeA) && !Number.isFinite(timeB)) return 0; if (!Number.isFinite(timeA)) return 1; if (!Number.isFinite(timeB)) return -1; return timeB - timeA; }); return combined; } // src/features/importExport/index.js function initializeImportExportFeature(deps) { const { createToast: createToast2, createSettingsToast: createSettingsToast2, exportSettingsObject, importSettings, getSummaryHistoryMap, setSummaryHistoryMap, getTopicQuestionHistoryMap, setTopicQuestionHistoryMap, getDeArrowTopicStates, setDeArrowTopicStates, normalizeDeArrowTopicStates: normalizeDeArrowTopicStates2, syncSummaryTopicIdsFromSources: syncSummaryTopicIdsFromSources2, replaceSummaryTopicIdsFromHistoryMap: replaceSummaryTopicIdsFromHistoryMap2, markDriveSummaryTopicsDirty: markDriveSummaryTopicsDirty2, markDriveDeArrowDirty: markDriveDeArrowDirty2, scheduleDriveSummarySync: scheduleDriveSummarySync2, updateAllSummaryButtonsAndContainers, syncDriveSummarySettingsUI: syncDriveSummarySettingsUI2, persistDriveSummarySettings: persistDriveSummarySettings2, getDriveSummarySettings, uploadSummaryHistoryToDrive: uploadSummaryHistoryToDrive2, rebuildSummaryTopicIdsFromDrive: rebuildSummaryTopicIdsFromDrive2 } = deps; function ready(fn) { if (document.readyState !== "loading") { fn(); } else { document.addEventListener("DOMContentLoaded", fn, { once: true }); } } function readSummaryHistory() { return typeof getSummaryHistoryMap === "function" ? getSummaryHistoryMap() : {}; } function readTopicQuestionHistory() { return typeof getTopicQuestionHistoryMap === "function" ? getTopicQuestionHistoryMap() : {}; } function readDeArrowTopicStates() { return typeof getDeArrowTopicStates === "function" ? getDeArrowTopicStates() : {}; } function isPlainObject(value) { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } function normalizeImportedSummaryHistoryOrThrow(summaryHistory, label = "已总结内容") { if (!isPlainObject(summaryHistory)) { throw new Error(`${label}格式无效`); } const hasInvalidTopicEntries = Object.keys(summaryHistory).some((topicId) => !Array.isArray(summaryHistory[topicId])); if (hasInvalidTopicEntries) { throw new Error(`${label}格式无效`); } return normalizeSummaryHistoryMapForStorage(summaryHistory); } function normalizeImportedTopicQuestionHistoryOrThrow(questionHistory, label = "问答历史") { if (!isPlainObject(questionHistory)) { throw new Error(`${label}格式无效`); } const hasInvalidTopicEntries = Object.keys(questionHistory).some((topicId) => !Array.isArray(questionHistory[topicId])); if (hasInvalidTopicEntries) { throw new Error(`${label}格式无效`); } return normalizeTopicQuestionHistoryMapForStorage(questionHistory); } function normalizeImportedDeArrowStatesOrThrow(topicStates, label = "DeArrow 状态") { if (!isPlainObject(topicStates)) { throw new Error(`${label}格式无效`); } const hasInvalidTopicEntries = Object.values(topicStates).some((entry) => !isPlainObject(entry)); if (hasInvalidTopicEntries) { throw new Error(`${label}格式无效`); } return typeof normalizeDeArrowTopicStates2 === "function" ? normalizeDeArrowTopicStates2(topicStates) : topicStates; } function writeSummaryHistory(summaryHistory, { preservedTopicIds = [] } = {}) { const normalizedSummaryHistory = normalizeSummaryHistoryMapForStorage(summaryHistory); if (typeof setSummaryHistoryMap === "function") { setSummaryHistoryMap(normalizedSummaryHistory); } if (typeof syncSummaryTopicIdsFromSources2 === "function") { syncSummaryTopicIdsFromSources2(normalizedSummaryHistory, preservedTopicIds); } else if (typeof replaceSummaryTopicIdsFromHistoryMap2 === "function") { replaceSummaryTopicIdsFromHistoryMap2(normalizedSummaryHistory); } if (typeof markDriveSummaryTopicsDirty2 === "function") { markDriveSummaryTopicsDirty2(Object.keys(normalizedSummaryHistory)); } if (typeof scheduleDriveSummarySync2 === "function") { scheduleDriveSummarySync2("import"); } if (typeof updateAllSummaryButtonsAndContainers === "function") { updateAllSummaryButtonsAndContainers(); } } function writeTopicQuestionHistory(questionHistory) { const normalizedQuestionHistory = normalizeTopicQuestionHistoryMapForStorage(questionHistory); if (typeof setTopicQuestionHistoryMap === "function") { setTopicQuestionHistoryMap(normalizedQuestionHistory); } if (typeof markDriveSummaryTopicsDirty2 === "function") { markDriveSummaryTopicsDirty2(Object.keys(normalizedQuestionHistory)); } if (typeof scheduleDriveSummarySync2 === "function") { scheduleDriveSummarySync2("import"); } } function writeDeArrowTopicStates(topicStates) { const normalized = typeof normalizeDeArrowTopicStates2 === "function" ? normalizeDeArrowTopicStates2(topicStates) : topicStates; if (typeof setDeArrowTopicStates === "function") { setDeArrowTopicStates(normalized); } if (typeof markDriveDeArrowDirty2 === "function") { markDriveDeArrowDirty2(); } if (typeof scheduleDriveSummarySync2 === "function") { scheduleDriveSummarySync2("import"); } } function downloadJson(obj, baseName) { const blob = new Blob([JSON.stringify(obj, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]; a.href = url; a.download = `${baseName}_${date}.json`; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 0); } function exportSummaryContent() { try { downloadJson(readSummaryHistory(), "总结内容 - [LINUX DO] 🌟 主题 & 回复 总结"); createSettingsToast2?.("已总结内容已导出!", "success", 3e3); } catch (error) { createSettingsToast2?.("导出失败", "error", 3e3); console.error("exportSummaryContent failed", error); } } function importSummaryContent(data) { try { const normalizedSummaryHistory = normalizeImportedSummaryHistoryOrThrow(data); writeSummaryHistory(normalizedSummaryHistory); createSettingsToast2?.("已总结内容导入完成!", "success", 3e3); } catch (error) { createSettingsToast2?.(`导入失败:${error.message}`, "error", 3e3); console.error("importSummaryContent failed", error); } } function exportAllData() { try { const bundle = { settings: exportSettingsObject(), summaryHistory: readSummaryHistory(), topicQuestionHistory: readTopicQuestionHistory(), dearrowTopicStates: readDeArrowTopicStates() }; downloadJson(bundle, "全部数据 - [LINUX DO] 🌟 主题 & 回复 总结"); createSettingsToast2?.("全部数据已导出!", "success", 3e3); } catch (error) { createSettingsToast2?.("导出失败", "error", 3e3); console.error("exportAllData failed", error); } } function importAllData(bundle) { try { if (!isPlainObject(bundle)) { createSettingsToast2?.("导入失败:数据无效", "error", 3e3); return; } const hasSummaryHistory = Object.prototype.hasOwnProperty.call(bundle, "summaryHistory"); const normalizedSummaryHistory = hasSummaryHistory ? normalizeImportedSummaryHistoryOrThrow(bundle.summaryHistory) : null; const hasTopicQuestionHistory = Object.prototype.hasOwnProperty.call(bundle, "topicQuestionHistory"); const normalizedQuestionHistory = hasTopicQuestionHistory ? normalizeImportedTopicQuestionHistoryOrThrow(bundle.topicQuestionHistory) : null; const hasDeArrowTopicStates = Object.prototype.hasOwnProperty.call(bundle, "dearrowTopicStates"); const normalizedDeArrowTopicStates = hasDeArrowTopicStates ? normalizeImportedDeArrowStatesOrThrow(bundle.dearrowTopicStates) : null; if (bundle.settings && typeof importSettings === "function") { const settingsImported = importSettings(bundle.settings); if (settingsImported === false) { throw new Error("脚本设置导入失败"); } } if (normalizedSummaryHistory) { writeSummaryHistory(normalizedSummaryHistory, { preservedTopicIds: bundle.settings?.summaryTopicIds }); } if (normalizedQuestionHistory) { writeTopicQuestionHistory(normalizedQuestionHistory); } if (normalizedDeArrowTopicStates) { writeDeArrowTopicStates(normalizedDeArrowTopicStates); } createSettingsToast2?.("全部数据导入完成!", "success", 3e3); } catch (error) { createSettingsToast2?.(`导入失败:${error.message}`, "error", 3e3); console.error("importAllData failed", error); } } function buildDriveUI(container) { if (!container || container.dataset.driveInitialized === "true") { return; } container.dataset.driveInitialized = "true"; const section = document.createElement("div"); section.className = "settings-card drive-summary-section"; section.innerHTML = ` 1. Google Drive 总结 / 问答 / DeArrow 数据:
(同步文件夹:[LINUX DO] 🌟 话题 & 回复 总结)
(文件格式:总结内容 - [LINUX DO] 🌟 主题 & 回复 总结_yyyy-mm-dd.json)
`; container.appendChild(section2); const section3 = document.createElement("div"); section3.className = "import-export-section settings-card"; section3.innerHTML = ` 3. 脚本配置 + 总结 / 问答 / DeArrow 数据:(文件格式:全部数据 - [LINUX DO] 🌟 主题 & 回复 总结_yyyy-mm-dd.json)
`; container.appendChild(section3); const importSummaryFile = section2.querySelector("#import-summary-file"); const importAllFile = section3.querySelector("#import-all-file"); section2.querySelector("#export-summary-button").addEventListener("click", exportSummaryContent); section2.querySelector("#import-summary-button").addEventListener("click", () => importSummaryFile.click()); importSummaryFile.addEventListener("change", (event) => { const file = event.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = (loadEvent) => { try { importSummaryContent(JSON.parse(loadEvent.target.result)); } catch (error) { createToast2?.("导入失败:格式有误", "error"); console.error(error); } finally { importSummaryFile.value = ""; } }; reader.readAsText(file); }); section3.querySelector("#export-all-button").addEventListener("click", exportAllData); section3.querySelector("#import-all-button").addEventListener("click", () => importAllFile.click()); importAllFile.addEventListener("change", (event) => { const file = event.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = (loadEvent) => { try { importAllData(JSON.parse(loadEvent.target.result)); } catch (error) { createToast2?.("导入失败:格式有误", "error"); console.error(error); } finally { importAllFile.value = ""; } }; reader.readAsText(file); }); } function mountPanels() { const importExportTab = document.getElementById("import-export-settings"); const driveTab = document.getElementById("drive-settings"); if (importExportTab) { buildImportExportUI(importExportTab); } if (driveTab) { buildDriveUI(driveTab); } return Boolean(importExportTab && driveTab); } ready(() => { if (mountPanels()) { return; } const modalObserver = new MutationObserver((_2, observer) => { if (mountPanels()) { observer.disconnect(); } }); modalObserver.observe(document.body, { childList: true, subtree: true }); }); return { exportSummaryContent, exportAllData, importAllData, importSummaryContent, mountPanels }; } // src/services/apiClient.js function stringifyErrorPayload(payload) { if (payload === null || payload === void 0) return ""; if (typeof payload === "string") return payload; try { return JSON.stringify(payload, null, 2); } catch (_2) { return String(payload); } } function getContentFilterFinishReason(result) { const choices = Array.isArray(result?.choices) ? result.choices : []; const matchedChoice = choices.find((choice) => { const finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : ""; return finishReason.toLowerCase().includes("content_filter"); }); return typeof matchedChoice?.finish_reason === "string" ? matchedChoice.finish_reason : ""; } async function readResponseText(response) { try { return await response.text(); } catch (_2) { return ""; } } async function requestChatCompletion({ currentApi, messages, fetchImpl = fetch, signal = null }) { if (!currentApi?.key) { throw new Error("API Key is not set."); } if (!Array.isArray(messages) || messages.length === 0) { throw new Error("Messages are required."); } const headers = { "Content-Type": "application/json", "Authorization": `Bearer ${currentApi.key}` }; const data = { model: currentApi.model, messages, stream: false }; let response; try { response = await fetchImpl(currentApi.url, { method: "POST", headers, body: JSON.stringify(data), signal: signal || void 0 }); } catch (error) { if (error?.name === "AbortError") { const cancelled = new Error("总结已取消"); cancelled.code = "SUMMARY_CANCELLED"; cancelled.retryable = false; throw cancelled; } throw error; } if (!response.ok) { const error2 = new Error(`HTTP error! status: ${response.status}`); const responseBody = await readResponseText(response); if (responseBody) { error2.details = [ `HTTP status: ${response.status}`, "Response body:", responseBody ].join("\n"); } throw error2; } const result = await response.json(); if (result.choices && result.choices.length > 0 && result.choices[0].message) { return result.choices[0].message.content; } const contentFilterFinishReason = getContentFilterFinishReason(result); if (contentFilterFinishReason) { const error2 = new Error(`模型内容安全策略拦截,未返回内容(${contentFilterFinishReason})`); error2.code = "CONTENT_FILTER_BLOCKED"; error2.retryable = false; error2.details = [ `Finish reason: ${contentFilterFinishReason}`, "Actual response JSON:", stringifyErrorPayload(result) ].join("\n"); throw error2; } const error = new Error("Invalid response format from API"); error.details = [ "Expected OpenAI-compatible response shape: choices[0].message.content", "Actual response JSON:", stringifyErrorPayload(result) ].join("\n"); throw error; } function buildUserContentWithImages(text, imageInputs = []) { const normalizedText = text === null || text === void 0 ? "" : String(text); const normalizedImages = Array.isArray(imageInputs) ? imageInputs.map((image) => { const url = typeof image?.url === "string" ? image.url.trim() : ""; if (!url) return null; const detail = typeof image?.detail === "string" && image.detail.trim() ? image.detail.trim() : void 0; const imageUrl = detail ? { url, detail } : { url }; return { type: "image_url", image_url: imageUrl }; }).filter(Boolean) : []; if (normalizedImages.length === 0) { return normalizedText; } return [ { type: "text", text: normalizedText }, ...normalizedImages ]; } async function requestSummaryCompletion({ currentApi, promptConfig, txt, imageInputs = [], fetchImpl = fetch, signal = null }) { const systemPrompt = `${promptConfig.summaryMethod} ${promptConfig.outputFormat}`; return requestChatCompletion({ currentApi, messages: [ { role: "system", content: systemPrompt }, { role: "user", content: buildUserContentWithImages(txt, imageInputs) } ], fetchImpl, signal }); } // src/shared/topic.js function normalizeTopicIdForTitle(topicId) { if (topicId === null || topicId === void 0) return ""; const normalized = String(topicId).trim(); return normalized || ""; } var TOAST_TITLE_MAX_WIDTH = 28; function measureToastTextWidth(text) { const value = typeof text === "string" ? text : ""; let width = 0; for (const char of value) { width += char.charCodeAt(0) > 255 ? 2 : 1; } return width; } function truncateToastTopicTitle(title, maxWidth = TOAST_TITLE_MAX_WIDTH) { const normalized = typeof title === "string" ? title.replace(/\s+/g, " ").trim() : ""; if (!normalized) return ""; if (measureToastTextWidth(normalized) <= maxWidth) return normalized; let width = 0; let out = ""; for (const char of normalized) { const next = char.charCodeAt(0) > 255 ? 2 : 1; if (width + next > maxWidth - 2) break; out += char; width += next; } return `${out}…`; } function formatToastTopicLabel(topicId, topicTitle) { const normalizedTopicId = topicId === null || topicId === void 0 ? "" : String(topicId).trim(); const fallback = normalizedTopicId ? `话题#${normalizedTopicId}` : "话题"; const normalizedTitle = typeof topicTitle === "string" ? topicTitle.trim() : ""; return `📌 ${truncateToastTopicTitle(normalizedTitle) || fallback}`; } // src/shared/summarySync.js var DRIVE_TOPIC_SHARD_FILE_NAME_RE = /^topic-(.+)\.json$/; function sortSummaryTopicIds(topicIds = []) { return Array.from(topicIds).sort((left, right) => { const leftNumber = Number(left); const rightNumber = Number(right); if (Number.isFinite(leftNumber) && Number.isFinite(rightNumber)) { return leftNumber - rightNumber; } return String(left).localeCompare(String(right)); }); } function shouldAttemptTopicHistoryDrivePull({ hasLocalHistory = false, hasSummaryState = false, forceDrivePull = false } = {}) { return forceDrivePull === true || !hasLocalHistory && hasSummaryState; } function extractTopicIdFromDriveShardFileName(fileName) { const text = typeof fileName === "string" ? fileName.trim() : ""; if (!text) return ""; const match = text.match(DRIVE_TOPIC_SHARD_FILE_NAME_RE); if (!match) return ""; return normalizeSummaryTopicId(match[1]); } function collectDriveRebuildTopicIds({ indexTopics = {}, shardTopicIds = [], legacyHistoryMap = {} } = {}) { const topicIds = /* @__PURE__ */ new Set(); const normalizedIndexTopics = indexTopics && typeof indexTopics === "object" && !Array.isArray(indexTopics) ? indexTopics : {}; const normalizedShardTopicIds = Array.isArray(shardTopicIds) ? shardTopicIds : shardTopicIds instanceof Set ? Array.from(shardTopicIds) : []; const normalizedLegacyHistoryMap = legacyHistoryMap && typeof legacyHistoryMap === "object" && !Array.isArray(legacyHistoryMap) ? legacyHistoryMap : {}; Object.keys(normalizedIndexTopics).forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (normalizedTopicId) topicIds.add(normalizedTopicId); }); normalizedShardTopicIds.forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (normalizedTopicId) topicIds.add(normalizedTopicId); }); Object.keys(normalizedLegacyHistoryMap).forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (normalizedTopicId) topicIds.add(normalizedTopicId); }); return { topicIds: sortSummaryTopicIds(topicIds), source: [ Object.keys(normalizedIndexTopics).length > 0 ? "v2-index" : "", normalizedShardTopicIds.length > 0 ? "v2-shards" : "", Object.keys(normalizedLegacyHistoryMap).length > 0 ? "legacy" : "" ].filter(Boolean).join("+") || "none" }; } function collectLegacyDriveMigrationTopicIds({ indexTopics = {}, legacyHistoryMap = {} } = {}) { const normalizedIndexTopics = indexTopics && typeof indexTopics === "object" && !Array.isArray(indexTopics) ? indexTopics : {}; const normalizedLegacyHistoryMap = legacyHistoryMap && typeof legacyHistoryMap === "object" && !Array.isArray(legacyHistoryMap) ? legacyHistoryMap : {}; const indexedTopicIds = /* @__PURE__ */ new Set(); const migrationTopicIds = /* @__PURE__ */ new Set(); Object.keys(normalizedIndexTopics).forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (normalizedTopicId) indexedTopicIds.add(normalizedTopicId); }); Object.keys(normalizedLegacyHistoryMap).forEach((topicId) => { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (!normalizedTopicId || indexedTopicIds.has(normalizedTopicId)) return; migrationTopicIds.add(normalizedTopicId); }); return sortSummaryTopicIds(migrationTopicIds); } function selectUniqueDriveEntryId(entries, { itemLabel = "Drive 项目", itemName = "" } = {}) { const normalizedEntries = Array.isArray(entries) ? entries.filter((entry) => entry && typeof entry === "object") : []; if (normalizedEntries.length === 0) return null; if (normalizedEntries.length === 1) { const resolvedId = typeof normalizedEntries[0]?.id === "string" ? normalizedEntries[0].id.trim() : ""; return resolvedId || null; } const normalizedLabel = typeof itemLabel === "string" && itemLabel.trim() ? itemLabel.trim() : "Drive 项目"; const normalizedName = typeof itemName === "string" ? itemName.trim() : ""; const detail = normalizedName ? `:${normalizedName}` : ""; throw new Error(`Drive 中存在多个同名${normalizedLabel}${detail},无法安全确定同步目标。请先清理重复项后再试。`); } function resolveImportedSidebarSettings(importedSettings = {}, currentSettings = {}) { return { sidebarWidth: importedSettings?.sidebarWidth ?? currentSettings.sidebarWidth ?? "15%", sidebarPosition: importedSettings?.sidebarPosition ?? currentSettings.sidebarPosition ?? "left", sidebarTopDistance: importedSettings?.sidebarTopDistance ?? currentSettings.sidebarTopDistance ?? "5%", sidebarBottomDistance: importedSettings?.sidebarBottomDistance ?? currentSettings.sidebarBottomDistance ?? "5%" }; } // src/stores/dearrowStore.js var DEFAULT_DEARROW_SCOPE_URL = "https://linux.do/latest?order=created"; var DEFAULT_DEARROW_TOP_SCOPE_URL = "https://linux.do/top?ascending=false&order=views"; var DEFAULT_DEARROW_SCOPE_URLS = Object.freeze([ DEFAULT_DEARROW_SCOPE_URL, DEFAULT_DEARROW_TOP_SCOPE_URL ]); var DEFAULT_DEARROW_JUDGMENT_PROMPT = [ "你是论坛标题质量判定器。你只能根据给定的标题判断,不得臆测帖子内容。", "如果标题包含明显夸张、误导、刻意制造紧迫/恐慌,或用“震惊”“万万没想到”“这件事”等方式隐去关键信息诱导点击,标记为标题党。", "普通的疑问、求助、幽默、简短或主观表达本身不等于标题党。", '仅返回严格 JSON:{"results":[{"topicId":"...","verdict":true,"reason":"简短原因"}]}。', "每个输入 topicId 必须恰好返回一次。" ].join("\n"); var DEFAULT_DEARROW_REWRITE_PROMPT = [ "你负责根据论坛主题首帖改写标题。", "新标题必须具体、中立、不夸张,直接表达首帖的实际主题。", "不得补充首帖不存在的事实;保留重要的技术名称、产品名、版本号和数值。", '仅返回严格 JSON:{"title":"单行新标题"}。不要返回 HTML、Markdown 或解释。' ].join("\n"); var defaultDeArrowSettings = Object.freeze({ dearrowEnabled: false, dearrowAutoRewrite: false, dearrowJudgmentApiIndex: 0, dearrowRewriteApiIndex: 0, dearrowJudgmentPrompt: DEFAULT_DEARROW_JUDGMENT_PROMPT, dearrowRewritePrompt: DEFAULT_DEARROW_REWRITE_PROMPT, dearrowScopeRules: DEFAULT_DEARROW_SCOPE_URLS }); var DEARROW_STATE_FIELDS = Object.freeze({ verdict: ["verdict", "verdictReason", "verdictModel", "verdictUpdatedAt"], rewrite: ["rewrittenTitle", "rewriteModel", "rewrittenAt"] }); function normalizeString(value) { if (value === null || value === void 0) return ""; return String(value).trim(); } function normalizeDeArrowPrompt(value, fallback = "") { return normalizeString(value) || normalizeString(fallback); } function normalizeTopicId(value) { return normalizeString(value); } function normalizeTimestamp(value) { const normalized = normalizeString(value); if (!normalized) return ""; const timestamp = Date.parse(normalized); return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : ""; } function timestampValue(value) { const parsed = Date.parse(value || ""); return Number.isFinite(parsed) ? parsed : 0; } function latestTimestamp(...values) { let latest = ""; let latestValue = 0; values.forEach((value) => { const normalized = normalizeTimestamp(value); const parsed = timestampValue(normalized); if (parsed > latestValue || parsed === latestValue && normalized > latest) { latest = normalized; latestValue = parsed; } }); return latest; } function escapeRegExp(value) { return String(value).replace(/[|\\{}()[\]^$+?.]/g, "\\$&"); } function stripHash(value) { const hashIndex = value.indexOf("#"); return hashIndex === -1 ? value : value.slice(0, hashIndex); } function parseScopeRule(rule) { const normalized = stripHash(normalizeString(rule)); if (!normalized) { return { ok: false, error: "作用范围 URL 不能为空" }; } const wildcardMarker = "dearrow-wildcard-placeholder"; let parsed; try { parsed = new URL(normalized.replaceAll("*", wildcardMarker)); } catch (_2) { return { ok: false, error: `无效的完整 URL:${normalized}` }; } if (parsed.protocol !== "https:" || parsed.hostname !== "linux.do" || parsed.port || parsed.username || parsed.password) { return { ok: false, error: `仅支持 https://linux.do 下的 URL:${normalized}` }; } parsed.hash = ""; return { ok: true, rule: parsed.href.replaceAll(wildcardMarker, "*") }; } function validateDeArrowScopeRules(rawRules) { const source = Array.isArray(rawRules) ? rawRules : typeof rawRules === "string" ? rawRules.split(/\r?\n/) : []; const rules = []; const errors = []; const seen = /* @__PURE__ */ new Set(); source.forEach((rawRule, index) => { if (!normalizeString(rawRule)) return; const result = parseScopeRule(rawRule); if (!result.ok) { errors.push({ index, rule: normalizeString(rawRule), message: result.error }); return; } if (!seen.has(result.rule)) { seen.add(result.rule); rules.push(result.rule); } }); if (rules.length === 0 && errors.length === 0) { errors.push({ index: -1, rule: "", message: "至少需要一条作用范围 URL" }); } return { valid: errors.length === 0 && rules.length > 0, rules, errors }; } function normalizeDeArrowScopeRules(rawRules, fallback = defaultDeArrowSettings.dearrowScopeRules) { const validated = validateDeArrowScopeRules(rawRules); if (validated.valid) return validated.rules; const fallbackValidation = validateDeArrowScopeRules(fallback); return fallbackValidation.valid ? fallbackValidation.rules : [...DEFAULT_DEARROW_SCOPE_URLS]; } function normalizeDeArrowApiIndex(value, apiConfigurations2 = []) { const maxIndex = Array.isArray(apiConfigurations2) && apiConfigurations2.length > 0 ? apiConfigurations2.length - 1 : 0; const parsed = Number.parseInt(value, 10); if (!Number.isFinite(parsed) || parsed < 0 || parsed > maxIndex) return 0; return parsed; } function normalizeDeArrowSettings(raw = {}, apiConfigurations2 = raw?.apiConfigurations) { const source = raw && typeof raw === "object" ? raw : {}; const legacyApiIndex = source.dearrowApiIndex; return { dearrowEnabled: source.dearrowEnabled === true, dearrowAutoRewrite: source.dearrowAutoRewrite === true, dearrowJudgmentApiIndex: normalizeDeArrowApiIndex( source.dearrowJudgmentApiIndex ?? legacyApiIndex, apiConfigurations2 ), dearrowRewriteApiIndex: normalizeDeArrowApiIndex( source.dearrowRewriteApiIndex ?? legacyApiIndex, apiConfigurations2 ), dearrowJudgmentPrompt: normalizeDeArrowPrompt( source.dearrowJudgmentPrompt, defaultDeArrowSettings.dearrowJudgmentPrompt ), dearrowRewritePrompt: normalizeDeArrowPrompt( source.dearrowRewritePrompt, defaultDeArrowSettings.dearrowRewritePrompt ), dearrowScopeRules: normalizeDeArrowScopeRules(source.dearrowScopeRules) }; } function compileDeArrowScopeRule(rule) { const result = parseScopeRule(rule); if (!result.ok) return null; const pattern = result.rule.split("*").map(escapeRegExp).join(".*"); return new RegExp(`^${pattern}$`); } function normalizeDeArrowPageUrl(value) { try { const parsed = new URL(String(value || "")); if (parsed.protocol !== "https:" || parsed.hostname !== "linux.do" || parsed.port) return ""; parsed.hash = ""; return parsed.href; } catch (_2) { return ""; } } function isDeArrowScopeUrl(value, rawRules = defaultDeArrowSettings.dearrowScopeRules) { const normalizedUrl = normalizeDeArrowPageUrl(value); if (!normalizedUrl) return false; const rules = normalizeDeArrowScopeRules(rawRules); return rules.some((rule) => compileDeArrowScopeRule(rule)?.test(normalizedUrl) === true); } function stableSerialize(value) { if (value === null || typeof value !== "object") { return JSON.stringify(value); } if (Array.isArray(value)) { return `[${value.map(stableSerialize).join(",")}]`; } const keys = Object.keys(value).sort(); return `{${keys.map((key) => `${JSON.stringify(key)}:${stableSerialize(value[key])}`).join(",")}}`; } function normalizeDeArrowTopicState(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; const originalTitle = normalizeString(raw.originalTitle); if (!originalTitle) return null; const normalized = { originalTitle }; if (typeof raw.verdict === "boolean") { normalized.verdict = raw.verdict; const verdictReason = normalizeString(raw.verdictReason ?? raw.reason); const verdictModel = normalizeString(raw.verdictModel); const verdictUpdatedAt = normalizeTimestamp(raw.verdictUpdatedAt); if (verdictReason) normalized.verdictReason = verdictReason; if (verdictModel) normalized.verdictModel = verdictModel; if (verdictUpdatedAt) normalized.verdictUpdatedAt = verdictUpdatedAt; } const rewrittenTitle = normalizeString(raw.rewrittenTitle); if (rewrittenTitle) { normalized.rewrittenTitle = rewrittenTitle; const rewriteModel = normalizeString(raw.rewriteModel ?? raw.rewrittenModel); const rewrittenAt = normalizeTimestamp(raw.rewrittenAt); if (rewriteModel) normalized.rewriteModel = rewriteModel; if (rewrittenAt) normalized.rewrittenAt = rewrittenAt; } const updatedAt = latestTimestamp( raw.updatedAt, normalized.verdictUpdatedAt, normalized.rewrittenAt ); if (updatedAt) normalized.updatedAt = updatedAt; return normalized; } function normalizeDeArrowTopicStates(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; const normalized = {}; Object.entries(raw).forEach(([topicId, state2]) => { const id = normalizeTopicId(topicId); const nextState = normalizeDeArrowTopicState(state2); if (id && nextState) normalized[id] = nextState; }); return normalized; } function chooseTimedBundle(left, right, field, bundleFields) { if (!left) return right; if (!right) return left; const leftTime = timestampValue(left?.[field]); const rightTime = timestampValue(right?.[field]); if (leftTime !== rightTime) return rightTime > leftTime ? right : left; const leftBundle = {}; const rightBundle = {}; bundleFields.forEach((key) => { if (left && Object.hasOwn(left, key)) leftBundle[key] = left[key]; if (right && Object.hasOwn(right, key)) rightBundle[key] = right[key]; }); return stableSerialize(rightBundle) > stableSerialize(leftBundle) ? right : left; } function copyBundle(target, source, fields) { fields.forEach((field) => { if (source && Object.hasOwn(source, field)) target[field] = source[field]; }); } function mergeDeArrowTopicState(leftRaw, rightRaw) { const left = normalizeDeArrowTopicState(leftRaw); const right = normalizeDeArrowTopicState(rightRaw); if (!left) return right; if (!right) return left; if (left.originalTitle !== right.originalTitle) { const leftTime = timestampValue(left.updatedAt); const rightTime = timestampValue(right.updatedAt); if (leftTime !== rightTime) return rightTime > leftTime ? right : left; return stableSerialize(right) > stableSerialize(left) ? right : left; } const merged = { originalTitle: left.originalTitle }; const verdictSource = chooseTimedBundle( typeof left.verdict === "boolean" ? left : null, typeof right.verdict === "boolean" ? right : null, "verdictUpdatedAt", DEARROW_STATE_FIELDS.verdict ); const rewriteSource = chooseTimedBundle( left.rewrittenTitle ? left : null, right.rewrittenTitle ? right : null, "rewrittenAt", DEARROW_STATE_FIELDS.rewrite ); copyBundle(merged, verdictSource, DEARROW_STATE_FIELDS.verdict); copyBundle(merged, rewriteSource, DEARROW_STATE_FIELDS.rewrite); const updatedAt = latestTimestamp(left.updatedAt, right.updatedAt, merged.verdictUpdatedAt, merged.rewrittenAt); if (updatedAt) merged.updatedAt = updatedAt; return normalizeDeArrowTopicState(merged); } function mergeDeArrowTopicStates(leftRaw, rightRaw) { const left = normalizeDeArrowTopicStates(leftRaw); const right = normalizeDeArrowTopicStates(rightRaw); const merged = { ...left }; Object.entries(right).forEach(([topicId, state2]) => { merged[topicId] = mergeDeArrowTopicState(merged[topicId], state2); }); return normalizeDeArrowTopicStates(merged); } function updateDeArrowVerdictState(rawState, { originalTitle, verdict, reason = "", model = "", timestamp = (/* @__PURE__ */ new Date()).toISOString() } = {}) { const existing = normalizeDeArrowTopicState(rawState); const title = normalizeString(originalTitle || existing?.originalTitle); if (!title || typeof verdict !== "boolean") return null; const normalizedTimestamp = normalizeTimestamp(timestamp) || (/* @__PURE__ */ new Date()).toISOString(); const base = existing?.originalTitle === title ? existing : { originalTitle: title }; return normalizeDeArrowTopicState({ ...base, originalTitle: title, verdict, verdictReason: normalizeString(reason), verdictModel: normalizeString(model), verdictUpdatedAt: normalizedTimestamp, updatedAt: latestTimestamp(base.updatedAt, normalizedTimestamp) }); } function updateDeArrowRewriteState(rawState, { originalTitle, rewrittenTitle, model = "", timestamp = (/* @__PURE__ */ new Date()).toISOString() } = {}) { const existing = normalizeDeArrowTopicState(rawState); const title = normalizeString(originalTitle || existing?.originalTitle); const rewritten = normalizeString(rewrittenTitle); if (!title || !rewritten) return null; const normalizedTimestamp = normalizeTimestamp(timestamp) || (/* @__PURE__ */ new Date()).toISOString(); const base = existing?.originalTitle === title ? existing : { originalTitle: title }; return normalizeDeArrowTopicState({ ...base, originalTitle: title, rewrittenTitle: rewritten, rewriteModel: normalizeString(model), rewrittenAt: normalizedTimestamp, updatedAt: latestTimestamp(base.updatedAt, normalizedTimestamp) }); } // node_modules/marked/lib/marked.esm.js function z() { return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null }; } var T = z(); function G(u3) { T = u3; } var _ = { exec: () => null }; function k(u3, e = "") { let t = typeof u3 == "string" ? u3 : u3.source, n = { replace: (r, i) => { let s = typeof i == "string" ? i : i.source; return s = s.replace(m.caret, "$1"), t = t.replace(r, s), n; }, getRegex: () => new RegExp(t, e) }; return n; } var Re = (() => { try { return !!new RegExp("(?<=1)(?/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (u3) => new RegExp(`^( {0,3}${u3})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`), hrRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}#`), htmlBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}<(?:[a-z].*>|!--)`, "i"), blockquoteBeginRegex: (u3) => new RegExp(`^ {0,${Math.min(3, u3 - 1)}}>`) }; var Te = /^(?:[ \t]*(?:\n|$))+/; var Oe = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; var we = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; var C = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; var ye = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; var Q = / {0,3}(?:[*+-]|\d{1,9}[.)])/; var ie = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/; var oe = k(ie).replace(/bull/g, Q).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex(); var Pe = k(ie).replace(/bull/g, Q).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(); var j = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; var Se = /^[^\n]+/; var F = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/; var $e = k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", F).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(); var Le = k(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, Q).getRegex(); var v = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; var U = /|$))/; var _e = k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", U).replace("tag", v).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); var ae = k(j).replace("hr", C).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(); var Me = k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", ae).getRegex(); var K = { blockquote: Me, code: Oe, def: $e, fences: we, heading: ye, hr: C, html: _e, lheading: oe, list: Le, newline: Te, paragraph: ae, table: _, text: Se }; var re = k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", C).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(); var ze = { ...K, lheading: Pe, table: re, paragraph: k(j).replace("hr", C).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", re).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex() }; var Ee = { ...K, html: k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?\\1> *(?:\\n{2,}|\\s*$)|' + (n ? i : O(i, true)) + `
` : "" + (n ? i : O(i, true)) + `
`;
}
blockquote({ tokens: e }) {
return `${this.parser.parse(e)}`; } html({ text: e }) { return e; } def(e) { return ""; } heading({ tokens: e, depth: t }) { return `
${this.parser.parseInline(e)}
`; } table(e) { let t = "", n = ""; for (let i = 0; i < e.header.length; i++) n += this.tablecell(e.header[i]); t += this.tablerow({ text: n }); let r = ""; for (let i = 0; i < e.rows.length; i++) { let s = e.rows[i]; n = ""; for (let a = 0; a < s.length; a++) n += this.tablecell(s[a]); r += this.tablerow({ text: n }); } return r && (r = `${r}`), `${O(e, true)}`;
}
br(e) {
return "An error occurred:
" + O(n.message + "", true) + ""; return t ? Promise.resolve(r) : r; } if (t) return Promise.reject(n); throw n; }; } }; var M = new D(); function g(u3, e) { return M.parse(u3, e); } g.options = g.setOptions = function(u3) { return M.setOptions(u3), g.defaults = M.defaults, G(g.defaults), g; }; g.getDefaults = z; g.defaults = T; g.use = function(...u3) { return M.use(...u3), g.defaults = M.defaults, G(g.defaults), g; }; g.walkTokens = function(u3, e) { return M.walkTokens(u3, e); }; g.parseInline = M.parseInline; g.Parser = b; g.parser = b.parse; g.Renderer = y; g.TextRenderer = L; g.Lexer = x; g.lexer = x.lex; g.Tokenizer = w; g.Hooks = P; g.parse = g; var jt = g.options; var Ft = g.setOptions; var Ut = g.use; var Kt = g.walkTokens; var Wt = g.parseInline; var Jt = b.parse; var Vt = x.lex; // src/features/historyState/index.js var SUMMARY_HISTORY_STORAGE_KEY = "summaryHistory"; var SUMMARY_HISTORY_CACHE_MAX_AGE_MS = 3e4; function createHistoryStateFeature({ GM_getValue: GM_getValue2, GM_setValue: GM_setValue2, getSummaryOutputFilters, getPromptConfigurations, getCurrentPromptIndex, getCurrentApiConfiguration: getCurrentApiConfiguration2, setSummaryElementHtml: setSummaryElementHtml2 } = {}) { let summaryHistoryCacheMap = null; let summaryHistoryCacheUpdatedAt = 0; function getSummaryHistoryMapSnapshot2(options = {}) { const force = options.force === true; const maxAgeMs = Number.isFinite(options.maxAgeMs) ? Math.max(0, Number(options.maxAgeMs)) : SUMMARY_HISTORY_CACHE_MAX_AGE_MS; const now = Date.now(); const cacheExpired = now - summaryHistoryCacheUpdatedAt > maxAgeMs; if (force || !summaryHistoryCacheMap || cacheExpired) { const stored = GM_getValue2(SUMMARY_HISTORY_STORAGE_KEY, {}); summaryHistoryCacheMap = normalizeSummaryHistoryMapForStorage(stored); summaryHistoryCacheUpdatedAt = Date.now(); } return summaryHistoryCacheMap; } function setSummaryHistoryMapSnapshot2(historyMap) { const normalized = normalizeSummaryHistoryMapForStorage(historyMap); summaryHistoryCacheMap = normalized; summaryHistoryCacheUpdatedAt = Date.now(); GM_setValue2(SUMMARY_HISTORY_STORAGE_KEY, normalized); return normalized; } function getSummaryHistory2(topicId) { const normalizedTopicId = normalizeSummaryTopicId(topicId); if (!normalizedTopicId) return []; const historyMap = getSummaryHistoryMapSnapshot2(); return historyMap[normalizedTopicId] || []; } function getPromptSummaryRenderMode(promptConfig) { return normalizeSummaryRenderMode(promptConfig?.outputFormat, "html") || "html"; } function getCurrentSummaryRenderMode() { const promptConfigurations2 = typeof getPromptConfigurations === "function" ? getPromptConfigurations() : []; const currentPromptIndex2 = typeof getCurrentPromptIndex === "function" ? getCurrentPromptIndex() : 0; return getPromptSummaryRenderMode(promptConfigurations2[currentPromptIndex2]); } function resolveSummaryRenderMode2(renderMode, rawSummary) { return normalizeSummaryRenderMode(renderMode, "") || inferSummaryRenderModeFromSummary(rawSummary, "html"); } function captureCurrentSummaryRequestContext2() { const currentApi = typeof getCurrentApiConfiguration2 === "function" ? getCurrentApiConfiguration2() : null; return { model: currentApi?.model ?? "未知模型", renderMode: getCurrentSummaryRenderMode() }; } function escapeRegExp2(value) { return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function applySummaryOutputFilters(text) { if (text === null || text === void 0) return ""; const rawText = String(text); const filterConfig = normalizeSummaryOutputFilters( typeof getSummaryOutputFilters === "function" ? getSummaryOutputFilters() : null ); if (!filterConfig.enabled) return rawText; let output = rawText; filterConfig.leadingTokens.forEach((token) => { if (!token) return; const pattern = new RegExp(`^\\s*${escapeRegExp2(token)}\\s*`, "i"); output = output.replace(pattern, ""); }); filterConfig.trailingTokens.forEach((token) => { if (!token) return; const pattern = new RegExp(`\\s*${escapeRegExp2(token)}\\s*$`, "i"); output = output.replace(pattern, ""); }); return output; } function renderSummaryMarkup(rawSummary, options = {}) { const filteredSummary = applySummaryOutputFilters(rawSummary); if (!filteredSummary) { return options.emptyHtml || ""; } const renderMode = resolveSummaryRenderMode2(options.renderMode, filteredSummary); if (renderMode === "markdown") { return `
总结内容为空。
" }); const timestampText = timestamp ? new Date(timestamp).toLocaleString() : "未知"; const historyHtml = `🕒 时间:${timestampText}
🤖 模型:${model || "未知"}
`; return updateSummaryHtml2(target, historyHtml, { preserveSelection }); } function renderListSummaryContent2(target, rawSummary, options = {}) { if (!target) return false; const preserveSelection = options.preserveSelection !== false; clearSummaryRenderPayload2(target); const summaryHtml = renderSummaryMarkup(rawSummary, { renderMode: options.renderMode, emptyHtml: options.emptyHtml || "总结加载失败或为空。
" }); return updateSummaryHtml2(target, summaryHtml, { preserveSelection }); } function renderTopicHistoryRecord2(target, record, options = {}) { if (!target) return false; const preserveSelection = options.preserveSelection !== false; const rawSummary = record?.summary === null || record?.summary === void 0 ? "" : String(record.summary); const timestamp = record?.timestamp === null || record?.timestamp === void 0 ? "" : String(record.timestamp); const model = record?.model === null || record?.model === void 0 ? "" : String(record.model); clearSummaryRenderPayload2(target); const summaryHtml = renderSummaryMarkup(rawSummary, { renderMode: record?.renderMode, emptyHtml: "总结内容为空。
" }); const historyHtml = `🕒 ${timestamp ? new Date(timestamp).toLocaleString() : "未知"} | 🤖 ${model || "未知"}
`; return updateSummaryHtml2(target, historyHtml, { preserveSelection }); } function normalizeHistoryListForDisplay2(rawHistory) { if (!Array.isArray(rawHistory)) return []; const normalized = []; rawHistory.forEach((item) => { const normalizedItem = normalizeSummaryHistoryItemForStorage(item); if (!normalizedItem) return; normalized.push(normalizedItem); }); return normalized; } return { getSummaryHistoryMapSnapshot: getSummaryHistoryMapSnapshot2, setSummaryHistoryMapSnapshot: setSummaryHistoryMapSnapshot2, getSummaryHistory: getSummaryHistory2, getPromptSummaryRenderMode, getCurrentSummaryRenderMode, resolveSummaryRenderMode: resolveSummaryRenderMode2, captureCurrentSummaryRequestContext: captureCurrentSummaryRequestContext2, applySummaryOutputFilters, renderSummaryMarkup, clearSummaryRenderPayload: clearSummaryRenderPayload2, renderSidebarSummaryContent: renderSidebarSummaryContent2, renderSidebarHistoryRecord: renderSidebarHistoryRecord2, renderListSummaryContent: renderListSummaryContent2, renderTopicHistoryRecord: renderTopicHistoryRecord2, normalizeHistoryListForDisplay: normalizeHistoryListForDisplay2, normalizeSummaryHistoryItemForStorage, normalizeSummaryHistoryListForStorage, normalizeSummaryHistoryMapForStorage, updateSummaryHtml: updateSummaryHtml2 }; } // src/ui/icons.js var ASK_BUTTON_ICON_SVG = ``; function renderAskButtonIcon(button, label = "提问 / 追问") { if (!button) return false; const hasIcon = Boolean(button.querySelector?.(".ask-button-icon")); const hasExactMarkup = String(button.innerHTML || "").trim() === ASK_BUTTON_ICON_SVG.trim(); if (!hasIcon && !hasExactMarkup) { button.textContent = ""; button.innerHTML = ASK_BUTTON_ICON_SVG; } button.title = label; button.setAttribute?.("aria-label", label); return !hasIcon && !hasExactMarkup; } var CONTENT_FILTER_REFRESH_EVENT = "content-blocker:navigation"; var CONTENT_FILTER_REFRESH_DELAY = 120; var contentFilterRefreshTimer = null; var contentFilterRefreshDispatching = false; function dispatchContentFilterRefreshEvent() { try { window.dispatchEvent(new Event(CONTENT_FILTER_REFRESH_EVENT)); return true; } catch (error) { console.warn("[LINUX DO Summary] Failed to dispatch content filter refresh event:", error); return false; } } function scheduleContentFilterRefreshEvent() { if (contentFilterRefreshDispatching) return false; if (contentFilterRefreshTimer !== null) { clearTimeout(contentFilterRefreshTimer); } contentFilterRefreshTimer = setTimeout(() => { contentFilterRefreshTimer = null; if (contentFilterRefreshDispatching) return; contentFilterRefreshDispatching = true; try { dispatchContentFilterRefreshEvent(); } finally { contentFilterRefreshDispatching = false; } }, CONTENT_FILTER_REFRESH_DELAY); return true; } function mutationBatchAddsTopicRows(mutations) { for (const mutation of mutations || []) { if (mutation?.type !== "childList" || !mutation.addedNodes?.length) continue; for (const node of mutation.addedNodes) { if (!node || node.nodeType !== 1) continue; if (node.matches?.(".topic-list-item") || node.querySelector?.(".topic-list-item")) { return true; } } } return false; } // src/features/listPage/index.js var TOPIC_SUMMARY_VIEW_MODE = Object.freeze({ SUMMARY: "summary", HISTORY: "history", QUESTION: "question" }); function createTopicListFeature(deps = {}) { const { state: state2, pendingManualAfterDriveFailTopics: pendingManualAfterDriveFailTopics2, createToast: createToast2, createSummarizingToast: createSummarizingToast2, captureCurrentSummaryRequestContext: captureCurrentSummaryRequestContext2, clearSummaryRenderPayload: clearSummaryRenderPayload2, renderListSummaryContent: renderListSummaryContent2, renderTopicHistoryRecord: renderTopicHistoryRecord2, resolveSummaryRenderMode: resolveSummaryRenderMode2, setListSummaryHtml, applySummaryWidthSettings: applySummaryWidthSettings2, getSummaryHistoryMapSnapshot: getSummaryHistoryMapSnapshot3, getSummaryHistory: getSummaryHistory2, isTopicMarkedSummarized: isTopicMarkedSummarized2, hasDriveSummaryCredentials: hasDriveSummaryCredentials2, pullTopicHistoryFromDrive: pullTopicHistoryFromDrive2, areSummaryHistoryListsEqual: areSummaryHistoryListsEqual2, saveSummaryHistory: saveSummaryHistory2, autoShowHistoryIfExists: autoShowHistoryIfExists2, loadHistoryForCurrentTopic: loadHistoryForCurrentTopic2, updateSidebarSubmitButtonState: updateSidebarSubmitButtonState2, getFullFloorRangeForTopic, getCurrentApiConfiguration: getCurrentApiConfiguration2, main, extractTopicIdFromElement: extractTopicIdFromElement2, isListSummaryPageUrl: isListSummaryPageUrl2, isSummarySelectionLocked: isSummarySelectionLocked2, openListQuestionPanel, beginSummaryOperation, finishSummaryOperation, isSummaryStopError: isSummaryStopError2 } = deps; const LIST_SUMMARY_INTERNAL_SELECTOR = ".topic-summary-row, .topic-summary-container, .topic-summary-button, .topic-dearrow-button, .topic-question-button, .topic-summary-button-group, .topic-summary-control-button, .topic-summary-history-browser, .topic-summary-history-content, .topic-summary-content, .topic-summary-history-indicator, .topic-question-panel, .topic-question-header, .topic-question-title, .topic-question-presets, .topic-question-preset-button, .topic-question-preset-menu, .topic-question-preset-menu-item, .topic-question-history, .topic-question-compose, .topic-question-input-shell, .topic-question-input, .topic-question-compose-actions, .topic-question-send, .topic-question-status"; const LIST_SUMMARY_TOPIC_CONTAINER_SELECTOR = ".topic-list, .topic-list-body, .topic-list-item"; let listSummaryRefreshTimer = null; let listSummaryPostRenderTimer = null; const topicSummaryViewModeByTopic = /* @__PURE__ */ new Map(); const topicSummaryHistoryCursorByTopic = /* @__PURE__ */ new Map(); const listDriveHistoryPullingTopics = /* @__PURE__ */ new Set(); function normalizeTopicId4(topicId) { if (topicId === null || topicId === void 0) return ""; return String(topicId).trim(); } function escapeHtml(value) { return String(value ?? "").replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]); } function normalizeErrorMessage(error, fallback = "未知错误") { if (error instanceof Error && error.message) return error.message; if (error && typeof error.message === "string" && error.message) return error.message; const text = String(error ?? "").trim(); return text || fallback; } function stringifyErrorDetailValue(value) { if (value === null || value === void 0) return ""; if (typeof value === "string") return value; try { return JSON.stringify(value, null, 2); } catch (_2) { return String(value); } } function collectErrorDetails(error, sections, seen = /* @__PURE__ */ new Set(), label = "") { if (!error || typeof error !== "object" && typeof error !== "function") { return; } if (seen.has(error)) { sections.push(`${label || "Error"}: [Circular reference]`); return; } seen.add(error); const prefix = label ? `${label}: ` : ""; if (error instanceof Error) { sections.push(`${prefix}${error.name || "Error"}: ${error.message || "未知错误"}`); if (error.details) { sections.push(`${label ? `${label} ` : ""}Details: ${stringifyErrorDetailValue(error.details)}`); } if (error.stack) { sections.push(`${label ? `${label} ` : ""}Stack: ${error.stack}`); } if (error.cause) { collectErrorDetails(error.cause, sections, seen, "Cause"); } return; } sections.push(`${prefix}${stringifyErrorDetailValue(error)}`); } function buildTopicSummaryErrorDetails({ title, topicId, error, message, action }) { const sections = [ `${title}:${message}` ]; if (topicId) { sections.push(`话题 ID:${topicId}`); } collectErrorDetails(error, sections); if (action) { sections.push(`建议操作:${action}`); } return sections.map((section) => String(section || "").trim()).filter(Boolean).join("\n\n"); } async function copyTextToClipboard(text) { const value = String(text ?? ""); if (!value) return false; if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(value); return true; } if (typeof document === "undefined" || !document.body || typeof document.createElement !== "function") { throw new Error("当前环境不支持剪贴板复制"); } const textarea = document.createElement("textarea"); textarea.value = value; textarea.setAttribute("readonly", ""); textarea.style.position = "fixed"; textarea.style.top = "-9999px"; textarea.style.opacity = "0"; document.body.appendChild(textarea); textarea.select(); const copied = document.execCommand?.("copy") === true; textarea.remove(); if (!copied) { throw new Error("浏览器拒绝复制操作"); } return true; } function bindTopicSummaryErrorControls(contentWrapper) { if (!contentWrapper) return; contentWrapper.querySelectorAll?.(".topic-summary-error-toggle").forEach((button) => { if (button.dataset.bound === "true") return; button.dataset.bound = "true"; button.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); const errorBox = button.closest?.(".topic-summary-error"); const details = errorBox?.querySelector?.(".topic-summary-error-details"); if (!details) return; const expanded = button.getAttribute("aria-expanded") === "true"; const nextExpanded = !expanded; details.hidden = !nextExpanded; button.setAttribute("aria-expanded", String(nextExpanded)); button.textContent = nextExpanded ? "收起" : "详情"; button.title = nextExpanded ? "收起完整报错" : "展开完整报错"; }); }); contentWrapper.querySelectorAll?.(".topic-summary-error-copy").forEach((button) => { if (button.dataset.bound === "true") return; button.dataset.bound = "true"; button.addEventListener("click", async (event) => { event.preventDefault(); event.stopPropagation(); const originalText = button.textContent || "复制"; try { const errorBox = button.closest?.(".topic-summary-error"); const detailsText = errorBox?.querySelector?.(".topic-summary-error-details-text")?.textContent || ""; await copyTextToClipboard(detailsText); button.textContent = "已复制"; createToast2?.("完整报错已复制", "success", 1800); setTimeout(() => { button.textContent = originalText; }, 1400); } catch (copyError) { const message = normalizeErrorMessage(copyError, "复制失败"); button.textContent = "复制失败"; createToast2?.(`复制失败:${message}`, "error", 2600); setTimeout(() => { button.textContent = originalText; }, 1800); } }); }); } function isSoftHidden(elem) { if (!elem) return false; const cs = getComputedStyle(elem); if (cs.display === "none") return true; if (cs.visibility === "collapse" || cs.visibility === "hidden") return true; if (cs.position === "absolute") { const left = parseInt(cs.left, 10); if (!Number.isNaN(left) && left < -900) return true; } return false; } function canAttemptDrivePull() { if (!state2.driveSummarySettings?.enabled) return false; if (typeof hasDriveSummaryCredentials2 === "function") { return hasDriveSummaryCredentials2(); } return true; } function getTopicSummaryState(topicId) { const normalizedTopicId = normalizeTopicId4(topicId); const hasLocalHistory = normalizedTopicId ? getSummaryHistory2(normalizedTopicId).length > 0 : false; const hasSummaryState = normalizedTopicId ? hasLocalHistory || isTopicMarkedSummarized2(normalizedTopicId) : false; return { topicId: normalizedTopicId, hasLocalHistory, hasSummaryState }; } function getListSummaryButtonModel(topicId) { const normalizedTopicId = normalizeTopicId4(topicId); const { hasLocalHistory, hasSummaryState } = getTopicSummaryState(normalizedTopicId); const isSummarizing = state2.summarizingTopics.has(normalizedTopicId); const isDrivePulling = listDriveHistoryPullingTopics.has(normalizedTopicId); const isBusy = isSummarizing || isDrivePulling; if (isBusy) { return { hasLocalHistory, hasSummaryState, isBusy: true, isCompleted: false, text: isDrivePulling ? "☁️ 拉取中..." : "⏳ 总结中...", className: "loading" }; } if (hasLocalHistory) { return { hasLocalHistory, hasSummaryState, isBusy: false, isCompleted: true, text: "📝 已总结", className: "has-summary" }; } if (hasSummaryState && canAttemptDrivePull()) { return { hasLocalHistory, hasSummaryState, isBusy: false, isCompleted: false, text: "☁️ 拉取", className: "" }; } return { hasLocalHistory, hasSummaryState, isBusy: false, isCompleted: false, text: "📝 总结", className: "" }; } function isTopicDrivePulling(topicId) { const normalizedTopicId = normalizeTopicId4(topicId); if (!normalizedTopicId) return false; return listDriveHistoryPullingTopics.has(normalizedTopicId); } function isTopicSummaryBusy(topicId) { const normalizedTopicId = normalizeTopicId4(topicId); if (!normalizedTopicId) return false; return state2.summarizingTopics.has(normalizedTopicId) || listDriveHistoryPullingTopics.has(normalizedTopicId); } function getTopicSummaryBusyButtonLabel(topicId) { return isTopicDrivePulling(topicId) ? "☁️ 拉取中..." : "⏳ 总结中..."; } function getTopicSummaryBusyLoadingMessage(topicId) { return isTopicDrivePulling(topicId) ? "正在从 Drive 拉取总结,请稍候..." : "正在生成总结,请稍候..."; } function getTopicSummaryBusyToastMessage(topicId) { return isTopicDrivePulling(topicId) ? "该话题正在从 Drive 拉取总结,请稍候..." : "该话题正在总结中,请稍候..."; } function renderTopicSummaryError(container, buttonGroup, topicId, error, options = {}) { const normalizedTopicId = normalizeTopicId4(topicId); if (!container || !normalizedTopicId) return false; const { contentWrapper, historyBrowser } = ensureTopicSummaryContentElements(container, buttonGroup); if (!contentWrapper) return false; const summaryRow = typeof container.closest === "function" ? container.closest(".topic-summary-row") : null; if (summaryRow) summaryRow.style.display = "table-row"; container.style.display = "block"; if (buttonGroup) buttonGroup.style.display = "flex"; if (historyBrowser) historyBrowser.style.display = "none"; contentWrapper.style.display = "block"; syncTopicSummaryHistoryButtonState(buttonGroup, false); setTopicSummaryViewMode(normalizedTopicId, TOPIC_SUMMARY_VIEW_MODE.SUMMARY); const title = options.title || "总结生成失败"; const message = normalizeErrorMessage(error); const action = options.action ? `总结加载失败或为空。
", renderMode }); const preferredMode = normalizeTopicSummaryViewMode( options.preferredMode || getTopicSummaryViewMode(normalizedTopicId) ); applyTopicSummaryViewMode(container, buttonGroup, normalizedTopicId, preferredMode, { historyList }); } function showTopicQuestionPanel(container, buttonGroup, topicId, options = {}) { const normalizedTopicId = normalizeTopicId4(topicId); if (!container || !buttonGroup || !normalizedTopicId) return null; if (typeof openListQuestionPanel !== "function") return null; const panel = openListQuestionPanel({ topicId: normalizedTopicId, container, buttonGroup, focus: options.focus !== false, onClose: () => collapseTopicSummaryView(normalizedTopicId, { clearTracking: true }) }); applyTopicSummaryViewMode( container, buttonGroup, normalizedTopicId, TOPIC_SUMMARY_VIEW_MODE.QUESTION ); return panel; } function showTopicSummaryLoading(container, buttonGroup, topicId, message = "正在生成总结,请稍候...") { const normalizedTopicId = normalizeTopicId4(topicId); if (!container || !buttonGroup || !normalizedTopicId) return false; const { contentWrapper } = ensureTopicSummaryContentElements(container, buttonGroup); if (!contentWrapper) return false; clearSummaryRenderPayload2(contentWrapper); setListSummaryHtml( contentWrapper, `回答内容为空。
"; return g.parse(text); } function renderQuestionHistory(panel) { if (!panel) return; const topicId = normalizeTopicId4(panel.dataset.topicId); const historyEl = panel.querySelector(".topic-question-history"); if (!historyEl || !topicId) return; const history = typeof getQuestionHistory === "function" ? getQuestionHistory(topicId) : []; if (!Array.isArray(history) || history.length === 0) { updateHtml(historyEl, '暂无问答记录。
', { preserveSelection: true }); return; } const html = history.map((record) => { const presetLabel = record?.presetName ? `${escapeHtml(record.presetName)}` : ""; const timestamp = record?.timestamp ? new Date(record.timestamp).toLocaleString() : ""; const meta = [ timestamp ? escapeHtml(timestamp) : "", record?.model ? escapeHtml(record.model) : "" ].filter(Boolean).join(" · "); return `暂无历史记录。
", { preserveSelection: true }); counter.textContent = "0 / 0"; return; } const record = currentHistory[currentHistoryIndex]; if (!record || typeof record !== "object") { applyHtml(historyContentElement, "暂无历史记录。
", { preserveSelection: true }); counter.textContent = "0 / 0"; return; } if (typeof renderSidebarHistoryRecord2 === "function") { renderSidebarHistoryRecord2(historyContentElement, record, { preserveSelection: true }); } counter.textContent = `${currentHistoryIndex + 1} / ${currentHistory.length}`; updateHistoryButtons(); } function updateHistoryButtons() { prevButton.disabled = currentHistoryIndex === 0; nextButton.disabled = currentHistoryIndex >= currentHistory.length - 1; } historyDiv.loadHistory = loadHistory; } function toElement(node) { if (!node) return null; if (node.nodeType === 1) return node; return node.parentElement || null; } function getSummaryScopeHost(node) { const element = toElement(node); if (!element) return null; return element.closest(SUMMARY_SELECTION_SCOPE_SELECTOR); } function getActiveSummarySelectionScope() { const selection = typeof window.getSelection === "function" ? window.getSelection() : null; if (!selection || selection.rangeCount === 0 || selection.isCollapsed) { return null; } for (let index = 0; index < selection.rangeCount; index += 1) { const range = selection.getRangeAt(index); const startHost = getSummaryScopeHost(range.startContainer); const endHost = getSummaryScopeHost(range.endContainer); if (startHost && endHost) { if (startHost === endHost || startHost.contains(endHost)) { return { host: startHost, range }; } if (endHost.contains(startHost)) { return { host: endHost, range }; } return { host: startHost, range }; } } return null; } function isSummaryControlTarget(node) { const element = toElement(node); if (!element) return false; return Boolean(element.closest(SUMMARY_CONTROL_SELECTOR)); } function clearSummarySelectionSnapshot() { summarySelectionPointerActive = false; summarySelectionRestoring = false; summarySelectionRestoreScheduled = false; summarySelectionSnapshotRange = null; summarySelectionSnapshotHost = null; } function rememberSummarySelection(scope) { if (!scope || !scope.range || !scope.host) return false; try { summarySelectionSnapshotRange = scope.range.cloneRange(); summarySelectionSnapshotHost = scope.host; return true; } catch (_2) { clearSummarySelectionSnapshot(); return false; } } function captureSummarySelectionSnapshot() { const scope = getActiveSummarySelectionScope(); if (!scope) return false; return rememberSummarySelection(scope); } function isSummarySelectionLocked2() { if (!summarySelectionSnapshotRange || !summarySelectionSnapshotHost) { return false; } if (!summarySelectionSnapshotHost.isConnected) { clearSummarySelectionSnapshot(); return false; } const startNode = summarySelectionSnapshotRange.startContainer; if (startNode && typeof startNode.isConnected === "boolean" && !startNode.isConnected) { clearSummarySelectionSnapshot(); return false; } return true; } function isEditableTarget(node) { const element = toElement(node); if (!element) return false; const tagName = String(element.tagName || "").toLowerCase(); if (tagName === "input" || tagName === "textarea" || tagName === "select") return true; if (element.isContentEditable) return true; return Boolean(element.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]')); } function isSelectionInsideSummaryElement(element) { const target = toElement(element); if (!target) return false; const activeScope = getActiveSummarySelectionScope(); if (activeScope && activeScope.host) { if (target === activeScope.host) return true; if (target.contains(activeScope.host) || activeScope.host.contains(target)) return true; } if (!isSummarySelectionLocked2()) return false; if (target === summarySelectionSnapshotHost) return true; if (target.contains(summarySelectionSnapshotHost)) return true; if (summarySelectionSnapshotHost.contains(target)) return true; return false; } function setSummaryElementHtmlWithSelection(element, html, options = {}) { const target = toElement(element); if (!target) return false; const nextHtml = html === null || html === void 0 ? "" : String(html); if (target.innerHTML === nextHtml) return false; const preserveSelection = options.preserveSelection !== false; if (preserveSelection && isSummarySelectionLocked2() && isSelectionInsideSummaryElement(target)) { return false; } target.innerHTML = nextHtml; return true; } function restoreSummarySelectionFromSnapshot() { if (!isSummarySelectionLocked2()) return false; const activeElement = document.activeElement; if (isEditableTarget(activeElement) && !getSummaryScopeHost(activeElement)) { clearSummarySelectionSnapshot(); return false; } const selection = typeof window.getSelection === "function" ? window.getSelection() : null; if (!selection) return false; try { const nextRange = summarySelectionSnapshotRange.cloneRange(); summarySelectionRestoring = true; selection.removeAllRanges(); selection.addRange(nextRange); summarySelectionSnapshotRange = nextRange.cloneRange(); summarySelectionSnapshotHost = getSummaryScopeHost(nextRange.startContainer) || summarySelectionSnapshotHost; return true; } catch (_2) { clearSummarySelectionSnapshot(); return false; } finally { setTimeout(() => { summarySelectionRestoring = false; }, 0); } } function scheduleSummarySelectionRestore() { if (summarySelectionRestoreScheduled) return; if (summarySelectionPointerActive || summarySelectionRestoring) return; if (!isSummarySelectionLocked2()) return; summarySelectionRestoreScheduled = true; requestAnimationFrame(() => { summarySelectionRestoreScheduled = false; if (summarySelectionPointerActive || summarySelectionRestoring) return; const activeScope = getActiveSummarySelectionScope(); if (activeScope) { rememberSummarySelection(activeScope); return; } restoreSummarySelectionFromSnapshot(); }); } function bindSummarySelectionGuards2() { if (summarySelectionGuardsBound) return; summarySelectionGuardsBound = true; const pointerDownHandler = (event) => { const targetHost = getSummaryScopeHost(event.target); if (targetHost && !isSummaryControlTarget(event.target)) { summarySelectionPointerActive = true; if (!captureSummarySelectionSnapshot()) { summarySelectionSnapshotHost = targetHost; } return; } clearSummarySelectionSnapshot(); }; const pointerUpHandler = () => { if (!summarySelectionPointerActive) return; summarySelectionPointerActive = false; const captured = captureSummarySelectionSnapshot(); if (!captured) { clearSummarySelectionSnapshot(); } }; const selectionChangeHandler = () => { if (summarySelectionRestoring) return; const activeScope = getActiveSummarySelectionScope(); if (activeScope) { rememberSummarySelection(activeScope); return; } scheduleSummarySelectionRestore(); }; const keyDownHandler = (event) => { if (event.key === "Escape") { clearSummarySelectionSnapshot(); } }; window.addEventListener("pointerdown", pointerDownHandler, true); window.addEventListener("mousedown", pointerDownHandler, true); window.addEventListener("pointerup", pointerUpHandler, true); window.addEventListener("mouseup", pointerUpHandler, true); window.addEventListener("keydown", keyDownHandler, true); document.addEventListener("selectionchange", selectionChangeHandler, true); } return { createSidebar: createSidebar2, createHistoryNavigation, bindSummarySelectionGuards: bindSummarySelectionGuards2, setSummaryElementHtml: setSummaryElementHtmlWithSelection, isSummarySelectionLocked: isSummarySelectionLocked2 }; } // src/features/settings/index.js function createSettingsController(deps = {}) { const { state: state2, GM_getValue: GM_getValue2, GM_setValue: GM_setValue2, GM_registerMenuCommand: GM_registerMenuCommand2, defaultSummaryPrompt: defaultSummaryPrompt2, defaultHTMLPrompt: defaultHTMLPrompt2, defaultSummaryOutputFilters: defaultSummaryOutputFilters2, DEFAULT_SUMMARY_WIDTH_OFFSET: DEFAULT_SUMMARY_WIDTH_OFFSET2, MIN_SUMMARY_PANEL_WIDTH: MIN_SUMMARY_PANEL_WIDTH2, createDefaultApiConfiguration: createDefaultApiConfiguration2, initializeImportExportFeature: initializeImportExportFeature2, resolveImportedSidebarSettings: resolveImportedSidebarSettings2, normalizeApiConfiguration: normalizeApiConfiguration2, normalizeApiConfigurations: normalizeApiConfigurations2, normalizeAutoRetryCount: normalizeAutoRetryCount2, normalizeAutoRetryInterval: normalizeAutoRetryInterval2, normalizeCurrentApiIndex: normalizeCurrentApiIndex2, normalizeDeArrowApiIndex: normalizeDeArrowApiIndex2, normalizeDeArrowPrompt: normalizeDeArrowPrompt2, normalizeDeArrowScopeRules: normalizeDeArrowScopeRules2, defaultDeArrowSettings: defaultDeArrowSettings2, validateDeArrowScopeRules: validateDeArrowScopeRules2, normalizeDeArrowTopicStates: normalizeDeArrowTopicStates2, normalizeSummaryOutputFilters: normalizeSummaryOutputFilters2, normalizeSummaryWidthOffset: normalizeSummaryWidthOffset2, sanitizeSummaryTopicIds: sanitizeSummaryTopicIds2, normalizeQuestionPromptPresets: normalizeQuestionPromptPresets2, getCurrentApiConfiguration: getCurrentApiConfiguration2, syncAutoRetrySettingsFromCurrentApiConfiguration: syncAutoRetrySettingsFromCurrentApiConfiguration2, persistApiConfigurations: persistApiConfigurations2, persistDriveSummarySettings: persistDriveSummarySettings2, persistSummaryTopicIds: persistSummaryTopicIds2, syncDriveSummarySettingsUI: syncDriveSummarySettingsUI2, createToast: createToast2, createSettingsToast: createSettingsToast2, getSummaryHistoryMap, setSummaryHistoryMap, getTopicQuestionHistoryMap, setTopicQuestionHistoryMap, getDeArrowTopicStates, setDeArrowTopicStates, syncSummaryTopicIdsFromSources: syncSummaryTopicIdsFromSources2, replaceSummaryTopicIdsFromHistoryMap: replaceSummaryTopicIdsFromHistoryMap2, markDriveSummaryTopicsDirty: markDriveSummaryTopicsDirty2, markDriveDeArrowDirty: markDriveDeArrowDirty2, scheduleDriveSummarySync: scheduleDriveSummarySync2, updateAllSummaryButtonsAndContainers, refreshListSummaryForCurrentPage: refreshListSummaryForCurrentPage2, clearListSummaryBootstrapWatcher: clearListSummaryBootstrapWatcher2, removeTopicListSummaryButtons: removeTopicListSummaryButtons2, addTopicListSummaryButtons, restoreExpandedSummaryRows, updateListSummaryStyles, refreshDeArrowForCurrentPage: refreshDeArrowForCurrentPage2, cancelDeArrowAutoRewrites: cancelDeArrowAutoRewrites2, updateSidebarSubmitButtonState: updateSidebarSubmitButtonState2, uploadSummaryHistoryToDrive: uploadSummaryHistoryToDrive2, rebuildSummaryTopicIdsFromDrive: rebuildSummaryTopicIdsFromDrive2, getDriveSummarySettings, extractTopicId: extractTopicId2, attemptAutoSummarize: attemptAutoSummarize2, isSidebarWidthScriptActive: isSidebarWidthScriptActive2, isListSummaryPageUrl: isListSummaryPageUrl2, registerPublicApiHandlers: registerPublicApiHandlers2 } = deps; let persistListSummarySettingsHandler = null; let importExportFeatureController = null; let updatePromptSelect = () => { }; let updateQuestionPresetSelect = () => { }; let updateApiSelect = () => { }; let updateDeArrowSettingsInputs = () => { }; let updateSummaryWidthOffset = () => { }; let updateAdjustmentPrompts2 = () => { }; let updateSidebarPreview = () => { const sidebar = document.getElementById("summary-sidebar"); if (!sidebar) return; const sidebarWidthSlider = document.getElementById("sidebar-width-slider"); const sidebarTopSlider = document.getElementById("sidebar-top-slider"); const sidebarBottomSlider = document.getElementById("sidebar-bottom-slider"); const sidebarWidthValue = document.getElementById("sidebar-width-value"); const sidebarTopValue = document.getElementById("sidebar-top-value"); const sidebarBottomValue = document.getElementById("sidebar-bottom-value"); const offsetInput = document.getElementById("summary-width-offset"); if (!sidebarWidthSlider || !sidebarTopSlider || !sidebarBottomSlider || !sidebarWidthValue || !sidebarTopValue || !sidebarBottomValue || !offsetInput) { return; } const widthPercent = sidebarWidthSlider.value; const top = `${sidebarTopSlider.value}%`; const bottom = `${sidebarBottomSlider.value}%`; const widthOffset = parseInt(offsetInput.value, 10) || 0; let previewWidth; if (isSidebarWidthScriptActive2()) { const mainSidebarWidthStr = localStorage.getItem("discourseSidebarWidth") || "250px"; const mainSidebarWidth = parseInt(mainSidebarWidthStr.replace("px", ""), 10) || 250; const rawWidth = mainSidebarWidth + widthOffset; const clampedWidth = Math.max(MIN_SUMMARY_PANEL_WIDTH2, rawWidth); previewWidth = `${clampedWidth}px`; } else { previewWidth = `${widthPercent}%`; } sidebar.style.width = previewWidth; sidebar.style.top = top; sidebar.style.height = `calc(100vh - ${top} - ${bottom})`; sidebarWidthValue.textContent = `${widthPercent}%`; sidebarTopValue.textContent = top; sidebarBottomValue.textContent = bottom; }; let applyTabsCollapsedState = () => { }; function lockBodyScroll() { const docEl = document.documentElement; const body = document.body; if (docEl) docEl.classList.add("settings-modal-open"); if (body) body.classList.add("settings-modal-open"); } function unlockBodyScroll() { const docEl = document.documentElement; const body = document.body; if (docEl) docEl.classList.remove("settings-modal-open"); if (body) body.classList.remove("settings-modal-open"); } function applySummaryWidthSettings2() { let cssValue; if (state2.summaryWidthType === "percent") { cssValue = `${state2.summaryWidthValue}%`; } else { cssValue = `${state2.summaryWidthValue}px`; } document.documentElement.style.setProperty("--summary-width-type", state2.summaryWidthType); document.documentElement.style.setProperty("--summary-width-value", cssValue); let styleElement = document.getElementById("summary-width-style"); if (!styleElement) { styleElement = document.createElement("style"); styleElement.id = "summary-width-style"; document.head.appendChild(styleElement); } styleElement.textContent = ` .topic-summary-container { width: ${cssValue} !important; max-width: 100% !important; margin-left: 0 !important; margin-right: auto !important; box-sizing: border-box !important; } @media (max-width: ${state2.summaryWidthType === "pixel" ? parseInt(state2.summaryWidthValue, 10) + 40 + "px" : "768px"}) { .topic-summary-container { width: 100% !important; } } `; } function saveAndApplySidebarSettings() { const widthSlider = document.getElementById("sidebar-width-slider"); const topSlider = document.getElementById("sidebar-top-slider"); const bottomSlider = document.getElementById("sidebar-bottom-slider"); const positionSwitch = document.getElementById("sidebar-position-switch"); const offsetInput = document.getElementById("summary-width-offset"); const width = widthSlider ? `${widthSlider.value}%` : "15%"; const top = topSlider ? `${topSlider.value}%` : "5%"; const bottom = bottomSlider ? `${bottomSlider.value}%` : "5%"; const position = positionSwitch && positionSwitch.checked ? "right" : "left"; const clampedOffset = normalizeSummaryWidthOffset2( offsetInput ? offsetInput.value : state2.summaryWidthOffset, state2.summaryWidthOffset ); if (offsetInput) { offsetInput.value = clampedOffset; } state2.summaryWidthOffset = clampedOffset; GM_setValue2("sidebarWidth", width); GM_setValue2("sidebarTopDistance", top); GM_setValue2("sidebarBottomDistance", bottom); GM_setValue2("sidebarPosition", position); GM_setValue2("summaryWidthOffset", state2.summaryWidthOffset); applySidebarSettings2(); } function syncUIWithStoredSettings2() { const sidebarPositionSwitch = document.getElementById("sidebar-position-switch"); const sidebarWidthSlider = document.getElementById("sidebar-width-slider"); const sidebarWidthValue = document.getElementById("sidebar-width-value"); const sidebarTopSlider = document.getElementById("sidebar-top-slider"); const sidebarTopValue = document.getElementById("sidebar-top-value"); const sidebarBottomSlider = document.getElementById("sidebar-bottom-slider"); const sidebarBottomValue = document.getElementById("sidebar-bottom-value"); const defaultOpenSidebarSwitch = document.getElementById("default-open-sidebar-switch"); const sidebarAutoSummarizeSwitch = document.getElementById("sidebar-auto-summarize-switch"); const summaryWidthOffsetInput = document.getElementById("summary-width-offset"); const summaryFilterEnabled = document.getElementById("summary-filter-enabled"); const summaryFilterPrefixes = document.getElementById("summary-filter-prefixes"); const summaryFilterSuffixes = document.getElementById("summary-filter-suffixes"); if (sidebarPositionSwitch) { const storedPosition = GM_getValue2("sidebarPosition", "left"); sidebarPositionSwitch.checked = storedPosition === "right"; } if (sidebarWidthSlider && sidebarWidthValue) { const storedWidth = GM_getValue2("sidebarWidth", "15%"); sidebarWidthSlider.value = parseInt(storedWidth, 10); sidebarWidthValue.textContent = storedWidth; } if (sidebarTopSlider && sidebarTopValue) { const storedTopDistance = GM_getValue2("sidebarTopDistance", "5%"); sidebarTopSlider.value = parseInt(storedTopDistance, 10); sidebarTopValue.textContent = storedTopDistance; } if (sidebarBottomSlider && sidebarBottomValue) { const storedBottomDistance = GM_getValue2("sidebarBottomDistance", "5%"); sidebarBottomSlider.value = parseInt(storedBottomDistance, 10); sidebarBottomValue.textContent = storedBottomDistance; } if (defaultOpenSidebarSwitch) { defaultOpenSidebarSwitch.checked = state2.defaultOpenSidebar; } if (sidebarAutoSummarizeSwitch) { sidebarAutoSummarizeSwitch.checked = state2.newTopicAutoSummarize; } if (summaryWidthOffsetInput) { summaryWidthOffsetInput.value = state2.summaryWidthOffset; } if (summaryFilterEnabled || summaryFilterPrefixes || summaryFilterSuffixes) { const filterConfig = normalizeSummaryOutputFilters2(state2.summaryOutputFilters); if (summaryFilterEnabled) summaryFilterEnabled.checked = filterConfig.enabled; if (summaryFilterPrefixes) summaryFilterPrefixes.value = filterConfig.leadingTokens.join("\n"); if (summaryFilterSuffixes) summaryFilterSuffixes.value = filterConfig.trailingTokens.join("\n"); } } function parseSummaryFilterLines(value) { if (!value) return []; return value.split(/\r?\n/).map((line) => line.trim()).filter(Boolean); } function updateSummaryFilterInputs() { const summaryFilterEnabled = document.getElementById("summary-filter-enabled"); const summaryFilterPrefixes = document.getElementById("summary-filter-prefixes"); const summaryFilterSuffixes = document.getElementById("summary-filter-suffixes"); if (!summaryFilterEnabled && !summaryFilterPrefixes && !summaryFilterSuffixes) return; const filterConfig = normalizeSummaryOutputFilters2(state2.summaryOutputFilters); if (summaryFilterEnabled) summaryFilterEnabled.checked = filterConfig.enabled; if (summaryFilterPrefixes) summaryFilterPrefixes.value = filterConfig.leadingTokens.join("\n"); if (summaryFilterSuffixes) summaryFilterSuffixes.value = filterConfig.trailingTokens.join("\n"); } function saveSummaryFilterSettings({ showToast = true } = {}) { const summaryFilterEnabled = document.getElementById("summary-filter-enabled"); const summaryFilterPrefixes = document.getElementById("summary-filter-prefixes"); const summaryFilterSuffixes = document.getElementById("summary-filter-suffixes"); if (!summaryFilterEnabled || !summaryFilterPrefixes || !summaryFilterSuffixes) return; state2.summaryOutputFilters = normalizeSummaryOutputFilters2({ enabled: summaryFilterEnabled.checked, leadingTokens: parseSummaryFilterLines(summaryFilterPrefixes.value), trailingTokens: parseSummaryFilterLines(summaryFilterSuffixes.value) }); GM_setValue2("summaryOutputFilters", state2.summaryOutputFilters); if (showToast) { createSettingsToast2("输出过滤设置已保存!", "success", 2400); } } function resetSummaryFilterSettings() { state2.summaryOutputFilters = normalizeSummaryOutputFilters2(defaultSummaryOutputFilters2); GM_setValue2("summaryOutputFilters", state2.summaryOutputFilters); updateSummaryFilterInputs(); createSettingsToast2("输出过滤已恢复默认!", "info", 2400); } function applySidebarSettings2() { const sidebar = document.getElementById("summary-sidebar"); if (!sidebar) return; const toggleBar = document.getElementById("toggle-bar"); const position = GM_getValue2("sidebarPosition", "left"); const topDistance = GM_getValue2("sidebarTopDistance", "5%"); const bottomDistance = GM_getValue2("sidebarBottomDistance", "5%"); const isOpen = sidebar.classList.contains("open"); const mainSidebarWidthStr = localStorage.getItem("discourseSidebarWidth") || "250px"; const mainSidebarWidth = parseInt(mainSidebarWidthStr.replace("px", ""), 10) || 250; const rawWidth = mainSidebarWidth + state2.summaryWidthOffset; const summaryPanelWidthPx = Math.max(MIN_SUMMARY_PANEL_WIDTH2, rawWidth); const summaryPanelWidth = `${summaryPanelWidthPx}px`; sidebar.className = `${position} ${isOpen ? "open" : ""}`; sidebar.style.width = summaryPanelWidth; sidebar.style.top = topDistance; sidebar.style.height = `calc(100vh - ${topDistance} - ${bottomDistance})`; if (isOpen) { sidebar.style[position] = "0"; } else { sidebar.style[position] = `-${summaryPanelWidth}`; } if (toggleBar) { if (position === "left") { toggleBar.style.right = "-20px"; toggleBar.style.left = "auto"; toggleBar.style.borderRadius = "0 5px 5px 0"; } else { toggleBar.style.left = "-20px"; toggleBar.style.right = "auto"; toggleBar.style.borderRadius = "5px 0 0 5px"; } } syncUIWithStoredSettings2(); } function toggleSummaryPanel2() { const currentUrl = window.location.href; const isTopicPage = /^https:\/\/linux\.do\/t\/topic\/\d+/.test(currentUrl); const sidebar = document.getElementById("summary-sidebar"); if (!sidebar) return; sidebar.style.display = isTopicPage ? "flex" : "none"; } function openSettingsModal() { const settingsModal = document.getElementById("settings-modal"); if (settingsModal) { settingsModal.style.display = "block"; lockBodyScroll(); } const imageSettingsPanel = document.getElementById("api-image-settings"); const imageSettingsToggle = document.getElementById("toggle-api-image-settings"); if (imageSettingsPanel) imageSettingsPanel.classList.add("is-collapsed"); if (imageSettingsToggle) { imageSettingsToggle.setAttribute("aria-expanded", "false"); imageSettingsToggle.setAttribute("title", "展开图片设置"); imageSettingsToggle.setAttribute("aria-label", "展开图片设置"); } updatePromptSelect(); updateQuestionPresetSelect(); updateSummaryFilterInputs(); updateApiSelect(); updateDeArrowSettingsInputs(); updateSummaryWidthOffset(); updateAdjustmentPrompts2(); applyTabsCollapsedState(state2.settingsTabsCollapsed); requestAnimationFrame(() => { syncUIWithStoredSettings2(); updateAdjustmentPrompts2(); updateSidebarPreview(); }); } function initializeSettingsModal2() { const settingsModal = document.getElementById("settings-modal"); const closeSettings = document.getElementById("close-settings"); const toggleTabsButton = document.getElementById("toggle-tabs-button"); const modalContentElement = settingsModal ? settingsModal.querySelector(".modal-content") : null; const tabButtons = document.querySelectorAll(".tab-button"); const tabContents = document.querySelectorAll(".tab-content"); const mobileTabSelect = document.getElementById("mobile-tab-select"); const mobileTabSelectWrapper = settingsModal ? settingsModal.querySelector(".mobile-tab-select-wrapper") : null; const settingsButton = document.getElementById("settings-button"); const refreshButton = document.getElementById("refresh-button"); const sidebarWidthSlider = document.getElementById("sidebar-width-slider"); const sidebarWidthValue = document.getElementById("sidebar-width-value"); const sidebarTopSlider = document.getElementById("sidebar-top-slider"); const sidebarTopValue = document.getElementById("sidebar-top-value"); const sidebarBottomSlider = document.getElementById("sidebar-bottom-slider"); const sidebarBottomValue = document.getElementById("sidebar-bottom-value"); const saveSidebarSettings = document.getElementById("save-sidebar-settings"); const promptSelect = document.getElementById("prompt-select"); const promptName = document.getElementById("prompt-name"); const promptSummaryMethod = document.getElementById("prompt-summary-method"); const promptOutputFormat = document.getElementById("prompt-output-format"); const questionPresetSelect = document.getElementById("question-preset-select"); const questionPresetName = document.getElementById("question-preset-name"); const questionPresetPrompt = document.getElementById("question-preset-prompt"); const saveQuestionPreset = document.getElementById("save-question-preset"); const deleteQuestionPreset = document.getElementById("delete-question-preset"); const addQuestionPreset = document.getElementById("add-question-preset"); const saveSummaryFilters = document.getElementById("save-summary-filters"); const resetSummaryFilters = document.getElementById("reset-summary-filters"); const savePrompt = document.getElementById("save-prompt"); const deletePrompt = document.getElementById("delete-prompt"); const addPrompt = document.getElementById("add-prompt"); const apiSelect = document.getElementById("api-select"); const apiName = document.getElementById("api-name"); const apiUrl = document.getElementById("api-url"); const apiKey = document.getElementById("api-key"); const apiModel = document.getElementById("api-model"); const apiImageInputEnabled = document.getElementById("api-image-input-enabled"); const apiImageOptions = document.getElementById("api-image-options"); const apiImageDetail = document.getElementById("api-image-detail"); const apiMaxImages = document.getElementById("api-max-images"); const apiMaxImageMb = document.getElementById("api-max-image-mb"); const apiMaxTotalImageMb = document.getElementById("api-max-total-image-mb"); const apiKeyWrap = apiKey && apiKey.closest(".ld-secret-wrap"); if (apiKeyWrap && apiKey) { const adjustApiKeyTextarea = (revealed) => { const lineHeight = parseInt(getComputedStyle(apiKey).lineHeight, 10) || 18; const minHeight = Math.max(lineHeight, 22); if (revealed) { apiKey.style.overflowY = "hidden"; apiKey.style.height = "auto"; const maxLines = 3; const lines = (apiKey.value.match(/\n/g) || []).length + 1; if (lines <= maxLines) { apiKey.style.height = `${Math.max(apiKey.scrollHeight, minHeight)}px`; apiKey.style.overflowY = "hidden"; } else { apiKey.style.height = `${lineHeight * maxLines}px`; apiKey.style.overflowY = "auto"; } } else { apiKey.style.overflowY = "hidden"; apiKey.style.height = `${minHeight}px`; } }; bindSecretField(apiKeyWrap, { onRevealChange: (revealed) => adjustApiKeyTextarea(revealed) }); apiKey.addEventListener("input", () => { if (apiKeyWrap.classList.contains("is-revealed")) adjustApiKeyTextarea(true); }); } const saveApi = document.getElementById("save-api"); const copyApi = document.getElementById("copy-api"); const deleteApi = document.getElementById("delete-api"); const addApi = document.getElementById("add-api"); const apiImageSettings = document.getElementById("api-image-settings"); const toggleApiImageSettings = document.getElementById("toggle-api-image-settings"); const setApiImageSettingsCollapsed = (collapsed) => { if (apiImageSettings) { apiImageSettings.classList.toggle("is-collapsed", collapsed); } if (toggleApiImageSettings) { toggleApiImageSettings.setAttribute("aria-expanded", collapsed ? "false" : "true"); toggleApiImageSettings.setAttribute("title", collapsed ? "展开图片设置" : "折叠图片设置"); toggleApiImageSettings.setAttribute("aria-label", collapsed ? "展开图片设置" : "折叠图片设置"); } }; const uniqueApiCopyName = (baseName) => { const names = new Set( (state2.apiConfigurations || []).map((config) => String(config?.name || "").trim()).filter(Boolean) ); const stem = String(baseName || "新API配置").trim().replace(/\s*副本(?:\s+\d+)?$/, "").trim() || "新API配置"; const first = `${stem} 副本`; if (!names.has(first)) return first; let index = 2; while (names.has(`${stem} 副本 ${index}`)) index += 1; return `${stem} 副本 ${index}`; }; const populateMobileTabSelect = () => { if (!mobileTabSelect || !tabButtons.length) return; mobileTabSelect.innerHTML = ""; tabButtons.forEach((button) => { const tabId = button.getAttribute("data-tab"); if (!tabId) return; const option = document.createElement("option"); const label = button.querySelector(".tab-label")?.textContent?.trim() || button.textContent.trim(); option.value = tabId; option.textContent = label; mobileTabSelect.appendChild(option); }); }; const syncMobileTabSelectValue = () => { if (!mobileTabSelect) return; const activeButton = document.querySelector(".tab-button.active"); const activeTabId = activeButton?.getAttribute("data-tab"); if (activeTabId && mobileTabSelect.value !== activeTabId) { mobileTabSelect.value = activeTabId; } }; populateMobileTabSelect(); syncMobileTabSelectValue(); const isElementActuallyVisible = (element) => { if (!element) return false; const styles = window.getComputedStyle(element); if (styles.display === "none" || styles.visibility === "hidden" || parseFloat(styles.opacity || "1") === 0) { return false; } if ((element.offsetWidth ?? 0) <= 0 && (element.offsetHeight ?? 0) <= 0) { return false; } return true; }; const updateTabsToggleVisibility = () => { if (!toggleTabsButton) return; const shouldHide = isElementActuallyVisible(mobileTabSelectWrapper); toggleTabsButton.classList.toggle("mobile-tabs-hidden", shouldHide); if (shouldHide) { toggleTabsButton.setAttribute("aria-hidden", "true"); toggleTabsButton.setAttribute("tabindex", "-1"); } else { toggleTabsButton.removeAttribute("aria-hidden"); toggleTabsButton.removeAttribute("tabindex"); } }; applyTabsCollapsedState = (collapsed) => { if (modalContentElement) { modalContentElement.classList.toggle("tabs-collapsed", collapsed); } if (toggleTabsButton) { toggleTabsButton.classList.toggle("active", collapsed); toggleTabsButton.setAttribute("aria-pressed", collapsed ? "true" : "false"); toggleTabsButton.setAttribute("title", collapsed ? "展开按钮栏" : "折叠按钮栏"); toggleTabsButton.setAttribute("aria-label", collapsed ? "展开左侧按钮栏" : "折叠左侧按钮栏"); } updateTabsToggleVisibility(); }; if (toggleTabsButton) { applyTabsCollapsedState(state2.settingsTabsCollapsed); toggleTabsButton.addEventListener("click", () => { state2.settingsTabsCollapsed = !state2.settingsTabsCollapsed; GM_setValue2("settingsTabsCollapsed", state2.settingsTabsCollapsed); applyTabsCollapsedState(state2.settingsTabsCollapsed); syncMobileTabSelectValue(); }); } updateTabsToggleVisibility(); window.addEventListener("resize", updateTabsToggleVisibility); if (mobileTabSelect) { mobileTabSelect.addEventListener("change", () => { const targetTabId = mobileTabSelect.value; if (!targetTabId) return; const targetButton = document.querySelector(`.tab-button[data-tab="${targetTabId}"]`); if (targetButton) { targetButton.click(); } }); } const defaultOpenSidebarSwitch = document.getElementById("default-open-sidebar-switch"); const sidebarAutoSummarizeSwitch = document.getElementById("sidebar-auto-summarize-switch"); const importSettingsButton = document.getElementById("import-settings-button"); const exportSettingsButton = document.getElementById("export-settings-button"); const importSettingsFile = document.getElementById("import-settings-file"); const newTopicAutoSummarizeCheckbox = document.getElementById("new-topic-auto-summarize"); const autoRetryCountInput = document.getElementById("auto-retry-count"); const autoRetryIntervalInput = document.getElementById("auto-retry-interval"); const listSummaryEnabledSwitch = document.getElementById("list-summary-enabled-switch"); const autoShowSummarySwitch = document.getElementById("auto-show-summary-switch"); const listSummaryMaxLinesInput = document.getElementById("list-summary-max-lines"); const dearrowEnabledSwitch = document.getElementById("dearrow-enabled-switch"); const dearrowAutoRewriteSwitch = document.getElementById("dearrow-auto-rewrite-switch"); const dearrowJudgmentPromptInput = document.getElementById("dearrow-judgment-prompt"); const dearrowRewritePromptInput = document.getElementById("dearrow-rewrite-prompt"); const dearrowJudgmentApiSelect = document.getElementById("dearrow-judgment-api-select"); const dearrowRewriteApiSelect = document.getElementById("dearrow-rewrite-api-select"); const dearrowScopeRulesInput = document.getElementById("dearrow-scope-rules"); const dearrowScopeError = document.getElementById("dearrow-scope-error"); const saveDeArrowSettingsButtons = document.querySelectorAll("#dearrow-settings .save-dearrow-settings"); const getDefaultDeArrowPrompt = (key) => String(defaultDeArrowSettings2?.[key] || "").trim(); const normalizePromptValue = (value, fallback = "") => typeof normalizeDeArrowPrompt2 === "function" ? normalizeDeArrowPrompt2(value, fallback) : String(value ?? "").trim() || String(fallback || "").trim(); const syncAutoSummarizeSwitches = () => { if (newTopicAutoSummarizeCheckbox) { newTopicAutoSummarizeCheckbox.checked = state2.newTopicAutoSummarize; } if (sidebarAutoSummarizeSwitch) { sidebarAutoSummarizeSwitch.checked = state2.newTopicAutoSummarize; } }; if (settingsButton) { settingsButton.addEventListener("click", () => { openSettingsModal(); syncAutoSummarizeSwitches(); }); } if (refreshButton) { refreshButton.addEventListener("click", () => { location.reload(); }); } if (closeSettings) { closeSettings.addEventListener("click", () => { if (settingsModal) settingsModal.style.display = "none"; unlockBodyScroll(); }); } if (tabButtons && tabContents) { tabButtons.forEach((button) => { button.addEventListener("click", () => { if (button.classList.contains("active")) return; const tabId = button.getAttribute("data-tab"); tabButtons.forEach((btn) => btn.classList.remove("active")); tabContents.forEach((content) => content.classList.remove("active")); button.classList.add("active"); const targetContent = document.getElementById(tabId); if (targetContent) targetContent.classList.add("active"); syncMobileTabSelectValue(); }); }); } const sidebarSubTabButtons = document.querySelectorAll("#sidebar-settings .sidebar-sub-tab-button"); const sidebarSubTabContents = document.querySelectorAll("#sidebar-settings .sidebar-sub-tab-content"); if (sidebarSubTabButtons.length && sidebarSubTabContents.length) { sidebarSubTabButtons.forEach((button) => { button.addEventListener("click", () => { if (button.classList.contains("active")) return; const targetId = button.getAttribute("data-sidebar-tab"); sidebarSubTabButtons.forEach((btn) => btn.classList.remove("active")); sidebarSubTabContents.forEach((content) => content.classList.remove("active")); button.classList.add("active"); const targetContent = document.getElementById(targetId); if (targetContent) targetContent.classList.add("active"); if (targetId === "sidebar-settings-dimensions") { requestAnimationFrame(() => { syncUIWithStoredSettings2(); updateAdjustmentPrompts2(); updateSidebarPreview(); }); } }); }); } const promptSubTabButtons = document.querySelectorAll("#prompt-settings .prompt-sub-tab-button"); const promptSubTabContents = document.querySelectorAll("#prompt-settings .prompt-sub-tab-content"); if (promptSubTabButtons.length && promptSubTabContents.length) { promptSubTabButtons.forEach((button) => { button.addEventListener("click", () => { if (button.classList.contains("active")) return; const targetId = button.getAttribute("data-prompt-tab"); promptSubTabButtons.forEach((btn) => btn.classList.remove("active")); promptSubTabContents.forEach((content) => content.classList.remove("active")); button.classList.add("active"); const targetContent = document.getElementById(targetId); if (targetContent) targetContent.classList.add("active"); }); }); } const apiSubTabButtons = document.querySelectorAll("#api-settings .api-sub-tab-button"); const apiSubTabContents = document.querySelectorAll("#api-settings .api-sub-tab-content"); if (apiSubTabButtons.length && apiSubTabContents.length) { apiSubTabButtons.forEach((button) => { button.addEventListener("click", () => { if (button.classList.contains("active")) return; const targetId = button.getAttribute("data-api-tab"); apiSubTabButtons.forEach((btn) => btn.classList.remove("active")); apiSubTabContents.forEach((content) => content.classList.remove("active")); button.classList.add("active"); const targetContent = document.getElementById(targetId); if (targetContent) targetContent.classList.add("active"); }); }); } const listSummarySubTabButtons = document.querySelectorAll("#list-summary-settings .list-summary-sub-tab-button"); const listSummarySubTabContents = document.querySelectorAll("#list-summary-settings .list-summary-sub-tab-content"); if (listSummarySubTabButtons.length && listSummarySubTabContents.length) { listSummarySubTabButtons.forEach((button) => { button.addEventListener("click", () => { if (button.classList.contains("active")) return; const targetId = button.getAttribute("data-list-summary-tab"); listSummarySubTabButtons.forEach((btn) => btn.classList.remove("active")); listSummarySubTabContents.forEach((content) => content.classList.remove("active")); button.classList.add("active"); const targetContent = document.getElementById(targetId); if (targetContent) targetContent.classList.add("active"); }); }); } const dearrowSubTabButtons = document.querySelectorAll("#dearrow-settings .dearrow-sub-tab-button"); const dearrowSubTabContents = document.querySelectorAll("#dearrow-settings .dearrow-sub-tab-content"); if (dearrowSubTabButtons.length && dearrowSubTabContents.length) { dearrowSubTabButtons.forEach((button) => { button.addEventListener("click", () => { if (button.classList.contains("active")) return; const targetId = button.getAttribute("data-dearrow-tab"); dearrowSubTabButtons.forEach((btn) => btn.classList.remove("active")); dearrowSubTabContents.forEach((content) => content.classList.remove("active")); button.classList.add("active"); const targetContent = document.getElementById(targetId); if (targetContent) targetContent.classList.add("active"); }); }); } if (sidebarWidthSlider && sidebarWidthValue) { sidebarWidthSlider.addEventListener("input", () => { sidebarWidthValue.textContent = `${sidebarWidthSlider.value}%`; }); } if (sidebarTopSlider && sidebarTopValue) { sidebarTopSlider.addEventListener("input", () => { sidebarTopValue.textContent = `${sidebarTopSlider.value}%`; }); } if (sidebarBottomSlider && sidebarBottomValue) { sidebarBottomSlider.addEventListener("input", () => { sidebarBottomValue.textContent = `${sidebarBottomSlider.value}%`; }); } if (saveSidebarSettings) { saveSidebarSettings.addEventListener("click", () => { saveAndApplySidebarSettings(); createSettingsToast2("侧边栏设置已保存并应用!", "success", 3e3); }); } const sidebarPositionSwitch = document.getElementById("sidebar-position-switch"); if (sidebarPositionSwitch) { sidebarPositionSwitch.addEventListener("change", function() { const newPosition = this.checked ? "right" : "left"; GM_setValue2("sidebarPosition", newPosition); saveAndApplySidebarSettings(); }); } ["sidebar-width-slider", "sidebar-top-slider", "sidebar-bottom-slider"].forEach((sliderId) => { const slider = document.getElementById(sliderId); if (slider) { slider.addEventListener("input", () => { updateSidebarPreview(); }); slider.addEventListener("change", () => { saveAndApplySidebarSettings(); }); } }); if (listSummaryEnabledSwitch && autoShowSummarySwitch && listSummaryMaxLinesInput) { listSummaryEnabledSwitch.checked = state2.listPageSummaryEnabled; autoShowSummarySwitch.checked = state2.autoShowSummaryInList; listSummaryMaxLinesInput.value = state2.listPageSummaryMaxLines; const autoSaveListSummarySettings = ({ showToast = true } = {}) => { const previousEnabled = state2.listPageSummaryEnabled; state2.listPageSummaryEnabled = listSummaryEnabledSwitch.checked; state2.autoShowSummaryInList = autoShowSummarySwitch.checked; let parsedMaxLines = parseInt(listSummaryMaxLinesInput.value, 10); if (Number.isNaN(parsedMaxLines)) parsedMaxLines = 6; parsedMaxLines = Math.min(20, Math.max(1, parsedMaxLines)); if (String(parsedMaxLines) !== listSummaryMaxLinesInput.value) { listSummaryMaxLinesInput.value = parsedMaxLines; } state2.listPageSummaryMaxLines = parsedMaxLines; if (state2.summaryWidthType === "percent") { const percentInput = document.getElementById("summary-percent-value"); let percentValue = parseInt(percentInput ? percentInput.value : state2.summaryWidthValue, 10); if (Number.isNaN(percentValue)) percentValue = 100; percentValue = Math.min(100, Math.max(10, percentValue)); state2.summaryWidthValue = percentValue; if (percentInput && percentInput.value !== String(percentValue)) { percentInput.value = percentValue; } const percentRange = document.getElementById("percent-range"); if (percentRange && percentRange.value !== String(percentValue)) { percentRange.value = percentValue; } } else { const pixelInput = document.getElementById("summary-pixel-value"); let pixelValue = parseInt(pixelInput ? pixelInput.value : state2.summaryWidthValue, 10); if (Number.isNaN(pixelValue)) pixelValue = 500; pixelValue = Math.min(2e3, Math.max(100, pixelValue)); state2.summaryWidthValue = pixelValue; if (pixelInput && pixelInput.value !== String(pixelValue)) { pixelInput.value = pixelValue; } const pixelRange = document.getElementById("pixel-range"); if (pixelRange && pixelRange.value !== String(pixelValue)) { pixelRange.value = pixelValue; } } GM_setValue2("listPageSummaryEnabled", state2.listPageSummaryEnabled); GM_setValue2("autoShowSummaryInList", state2.autoShowSummaryInList); GM_setValue2("listPageSummaryMaxLines", state2.listPageSummaryMaxLines); GM_setValue2("summaryWidthType", state2.summaryWidthType); GM_setValue2("summaryWidthValue", state2.summaryWidthValue); updateListSummaryStyles(); applySummaryWidthSettings2(); const onListSummaryPage = isListSummaryPageUrl2(state2.currentPageUrl); if (!state2.listPageSummaryEnabled) { clearListSummaryBootstrapWatcher2?.(); removeTopicListSummaryButtons2?.({ preserveExpanded: true }); if (window.topicListObserver) window.topicListObserver.disconnect(); } else if (onListSummaryPage) { if (typeof refreshListSummaryForCurrentPage2 === "function") { refreshListSummaryForCurrentPage2({ forceRebuild: state2.listPageSummaryEnabled !== previousEnabled, delay: 0 }); } else { addTopicListSummaryButtons?.(); } restoreExpandedSummaryRows?.(); } else { clearListSummaryBootstrapWatcher2?.(); } if (showToast) { createSettingsToast2("列表页总结设置已自动保存!", "success", 2200); } }; persistListSummarySettingsHandler = autoSaveListSummarySettings; listSummaryEnabledSwitch.addEventListener("change", () => autoSaveListSummarySettings()); autoShowSummarySwitch.addEventListener("change", () => autoSaveListSummarySettings()); listSummaryMaxLinesInput.addEventListener("change", () => autoSaveListSummarySettings()); } const renderDeArrowScopeError = (messages = []) => { if (!dearrowScopeError) return; const normalizedMessages = Array.isArray(messages) ? messages.map((message) => String(message || "").trim()).filter(Boolean) : []; dearrowScopeError.textContent = normalizedMessages.join("\n"); dearrowScopeError.classList.toggle("visible", normalizedMessages.length > 0); }; updateDeArrowSettingsInputs = () => { if (dearrowEnabledSwitch) { dearrowEnabledSwitch.checked = state2.dearrowEnabled === true; } if (dearrowAutoRewriteSwitch) { dearrowAutoRewriteSwitch.checked = state2.dearrowAutoRewrite === true; } if (dearrowJudgmentPromptInput) { dearrowJudgmentPromptInput.value = normalizePromptValue( state2.dearrowJudgmentPrompt, getDefaultDeArrowPrompt("dearrowJudgmentPrompt") ); } if (dearrowRewritePromptInput) { dearrowRewritePromptInput.value = normalizePromptValue( state2.dearrowRewritePrompt, getDefaultDeArrowPrompt("dearrowRewritePrompt") ); } const apiList = Array.isArray(state2.apiConfigurations) ? state2.apiConfigurations : []; const populateDeArrowApiSelect = (select, stateKey) => { if (!select) return; const normalizedIndex = typeof normalizeDeArrowApiIndex2 === "function" ? normalizeDeArrowApiIndex2(state2[stateKey], apiList) : Math.max(0, Math.min(Math.max(0, apiList.length - 1), parseInt(state2[stateKey], 10) || 0)); state2[stateKey] = normalizedIndex; select.innerHTML = ""; apiList.forEach((config, index) => { const option = document.createElement("option"); option.value = String(index); const name = String(config?.name || "").trim(); const model = String(config?.model || "").trim(); option.textContent = name && model && name !== model ? `${name}(${model})` : name || model || `API ${index + 1}`; select.appendChild(option); }); select.value = String(normalizedIndex); select.disabled = apiList.length === 0; }; populateDeArrowApiSelect(dearrowJudgmentApiSelect, "dearrowJudgmentApiIndex"); populateDeArrowApiSelect(dearrowRewriteApiSelect, "dearrowRewriteApiIndex"); if (dearrowScopeRulesInput) { const rules = typeof normalizeDeArrowScopeRules2 === "function" ? normalizeDeArrowScopeRules2(state2.dearrowScopeRules) : Array.isArray(state2.dearrowScopeRules) ? state2.dearrowScopeRules : []; dearrowScopeRulesInput.value = rules.join("\n"); } renderDeArrowScopeError([]); }; let dearrowSettingsRefreshTimer = null; let dearrowPendingRefreshOptions = null; const scheduleDeArrowSettingsRefresh = (options) => { dearrowPendingRefreshOptions = { forceRebuild: dearrowPendingRefreshOptions?.forceRebuild === true || options?.forceRebuild === true, pullDrive: false, judge: dearrowPendingRefreshOptions?.judge === true || options?.judge === true }; if (dearrowSettingsRefreshTimer !== null) { clearTimeout(dearrowSettingsRefreshTimer); } dearrowSettingsRefreshTimer = setTimeout(() => { dearrowSettingsRefreshTimer = null; const refreshOptions = dearrowPendingRefreshOptions; dearrowPendingRefreshOptions = null; Promise.resolve(refreshDeArrowForCurrentPage2?.(refreshOptions)).catch((error) => console.warn("[DeArrow] 应用设置失败:", error)); }, 120); }; const saveDeArrowSettings = ({ showToast = true } = {}) => { if (!dearrowEnabledSwitch || !dearrowJudgmentApiSelect || !dearrowRewriteApiSelect || !dearrowScopeRulesInput) return false; const rawScopeRules = dearrowScopeRulesInput.value; const validation = typeof validateDeArrowScopeRules2 === "function" ? validateDeArrowScopeRules2(rawScopeRules) : { valid: rawScopeRules.split(/\r?\n/).some((line) => line.trim()), rules: rawScopeRules.split(/\r?\n/).map((line) => line.trim()).filter(Boolean), errors: [] }; if (!validation.valid) { const messages = (validation.errors || []).map((error) => error?.message || String(error)); renderDeArrowScopeError(messages.length ? messages : ["作用范围配置无效"]); if (showToast) { createSettingsToast2("DeArrow 作用范围配置无效,请检查后重试。", "error", 3200); } return false; } const previous = { dearrowEnabled: state2.dearrowEnabled === true, dearrowAutoRewrite: state2.dearrowAutoRewrite === true, dearrowJudgmentPrompt: state2.dearrowJudgmentPrompt, dearrowRewritePrompt: state2.dearrowRewritePrompt, dearrowJudgmentApiIndex: state2.dearrowJudgmentApiIndex, dearrowRewriteApiIndex: state2.dearrowRewriteApiIndex, dearrowScopeRules: Array.isArray(state2.dearrowScopeRules) ? [...state2.dearrowScopeRules] : [] }; const apiList = Array.isArray(state2.apiConfigurations) ? state2.apiConfigurations : []; state2.dearrowEnabled = dearrowEnabledSwitch.checked === true; state2.dearrowAutoRewrite = dearrowAutoRewriteSwitch?.checked === true; if (dearrowJudgmentPromptInput) { state2.dearrowJudgmentPrompt = normalizePromptValue( dearrowJudgmentPromptInput.value, getDefaultDeArrowPrompt("dearrowJudgmentPrompt") ); } if (dearrowRewritePromptInput) { state2.dearrowRewritePrompt = normalizePromptValue( dearrowRewritePromptInput.value, getDefaultDeArrowPrompt("dearrowRewritePrompt") ); } state2.dearrowJudgmentApiIndex = typeof normalizeDeArrowApiIndex2 === "function" ? normalizeDeArrowApiIndex2(dearrowJudgmentApiSelect.value, apiList) : Math.max(0, parseInt(dearrowJudgmentApiSelect.value, 10) || 0); state2.dearrowRewriteApiIndex = typeof normalizeDeArrowApiIndex2 === "function" ? normalizeDeArrowApiIndex2(dearrowRewriteApiSelect.value, apiList) : Math.max(0, parseInt(dearrowRewriteApiSelect.value, 10) || 0); state2.dearrowScopeRules = validation.rules; if (previous.dearrowEnabled !== state2.dearrowEnabled) { GM_setValue2("dearrowEnabled", state2.dearrowEnabled); } if (previous.dearrowAutoRewrite !== state2.dearrowAutoRewrite) { GM_setValue2("dearrowAutoRewrite", state2.dearrowAutoRewrite); } if (previous.dearrowJudgmentPrompt !== state2.dearrowJudgmentPrompt && state2.dearrowJudgmentPrompt !== void 0) { GM_setValue2("dearrowJudgmentPrompt", state2.dearrowJudgmentPrompt); } if (previous.dearrowRewritePrompt !== state2.dearrowRewritePrompt && state2.dearrowRewritePrompt !== void 0) { GM_setValue2("dearrowRewritePrompt", state2.dearrowRewritePrompt); } if (previous.dearrowJudgmentApiIndex !== state2.dearrowJudgmentApiIndex) { GM_setValue2("dearrowJudgmentApiIndex", state2.dearrowJudgmentApiIndex); } if (previous.dearrowRewriteApiIndex !== state2.dearrowRewriteApiIndex) { GM_setValue2("dearrowRewriteApiIndex", state2.dearrowRewriteApiIndex); } const scopeChanged = previous.dearrowScopeRules.join("\n") !== state2.dearrowScopeRules.join("\n"); if (scopeChanged) { GM_setValue2("dearrowScopeRules", state2.dearrowScopeRules); } renderDeArrowScopeError([]); const activationChanged = previous.dearrowEnabled !== state2.dearrowEnabled; if (previous.dearrowAutoRewrite !== state2.dearrowAutoRewrite) { cancelDeArrowAutoRewrites2?.(); } const autoRewriteEnabled = !previous.dearrowAutoRewrite && state2.dearrowAutoRewrite; if (activationChanged || scopeChanged || autoRewriteEnabled) { scheduleDeArrowSettingsRefresh({ forceRebuild: activationChanged || scopeChanged, pullDrive: false, judge: activationChanged || scopeChanged }); } if (showToast) { createSettingsToast2("DeArrow 设置已保存并应用!", "success", 2400); } return true; }; if (dearrowEnabledSwitch) { dearrowEnabledSwitch.addEventListener("change", () => saveDeArrowSettings({ showToast: false })); } dearrowAutoRewriteSwitch?.addEventListener("change", () => saveDeArrowSettings({ showToast: false })); dearrowJudgmentApiSelect?.addEventListener("change", () => saveDeArrowSettings({ showToast: false })); dearrowRewriteApiSelect?.addEventListener("change", () => saveDeArrowSettings({ showToast: false })); saveDeArrowSettingsButtons.forEach((button) => { button.addEventListener("click", () => saveDeArrowSettings()); }); updateDeArrowSettingsInputs(); function updatePromptConfigInputs() { if (!promptName || !promptSummaryMethod || !promptOutputFormat) return; const currentConfig = state2.promptConfigurations[state2.currentPromptIndex]; if (!currentConfig) return; promptName.value = currentConfig.name; promptSummaryMethod.value = currentConfig.summaryMethod; promptOutputFormat.value = currentConfig.outputFormat; } updatePromptSelect = () => { if (!promptSelect) return; promptSelect.innerHTML = ""; state2.promptConfigurations.forEach((config, index) => { const option = document.createElement("option"); option.value = index; option.textContent = config.name; promptSelect.appendChild(option); }); promptSelect.value = state2.currentPromptIndex; updatePromptConfigInputs(); }; if (promptSelect) { promptSelect.addEventListener("change", (e) => { state2.currentPromptIndex = parseInt(e.target.value, 10); GM_setValue2("currentPromptIndex", state2.currentPromptIndex); updatePromptConfigInputs(); }); } if (savePrompt) { savePrompt.addEventListener("click", () => { if (!promptName || !promptSummaryMethod || !promptOutputFormat) return; if (!promptName.value.trim()) { createSettingsToast2("请填写提示词配置的名称!", "warning", 3e3); return; } state2.promptConfigurations[state2.currentPromptIndex] = { name: promptName.value.trim(), summaryMethod: promptSummaryMethod.value.trim(), outputFormat: promptOutputFormat.value.trim() }; GM_setValue2("promptConfigurations", state2.promptConfigurations); updatePromptSelect(); createSettingsToast2("提示词配置已保存!", "success", 3e3); }); } if (deletePrompt) { deletePrompt.addEventListener("click", () => { if (state2.promptConfigurations.length > 1) { if (confirm("确定要删除当前提示词配置吗?")) { state2.promptConfigurations.splice(state2.currentPromptIndex, 1); state2.currentPromptIndex = 0; GM_setValue2("promptConfigurations", state2.promptConfigurations); GM_setValue2("currentPromptIndex", state2.currentPromptIndex); updatePromptSelect(); createSettingsToast2("提示词配置已删除!", "success", 3e3); } } else { createSettingsToast2("至少需要保留一个提示词配置!", "warning", 3e3); } }); } if (addPrompt) { addPrompt.addEventListener("click", () => { const newPrompt = { name: "新 总结 + 输出 配置", summaryMethod: defaultSummaryPrompt2, outputFormat: defaultHTMLPrompt2 }; state2.promptConfigurations.push(newPrompt); state2.currentPromptIndex = state2.promptConfigurations.length - 1; GM_setValue2("promptConfigurations", state2.promptConfigurations); GM_setValue2("currentPromptIndex", state2.currentPromptIndex); updatePromptSelect(); createSettingsToast2("新提示词配置已添加!", "info", 3e3); }); } function getNormalizedQuestionPresets() { const normalizer = typeof normalizeQuestionPromptPresets2 === "function" ? normalizeQuestionPromptPresets2 : (value) => Array.isArray(value) ? value : []; state2.customQuestionPresets = normalizer(state2.customQuestionPresets); return state2.customQuestionPresets; } function updateQuestionPresetInputs() { if (!questionPresetName || !questionPresetPrompt) return; const presets = getNormalizedQuestionPresets(); const selectedIndex = questionPresetSelect ? parseInt(questionPresetSelect.value, 10) : 0; const preset = presets[selectedIndex]; if (!preset) { questionPresetName.value = ""; questionPresetPrompt.value = ""; return; } questionPresetName.value = preset.name; questionPresetPrompt.value = preset.prompt; } updateQuestionPresetSelect = () => { if (!questionPresetSelect) return; const presets = getNormalizedQuestionPresets(); questionPresetSelect.innerHTML = ""; if (presets.length === 0) { const option = document.createElement("option"); option.value = "0"; option.textContent = "暂无自定义预设"; questionPresetSelect.appendChild(option); questionPresetSelect.disabled = true; } else { questionPresetSelect.disabled = false; presets.forEach((preset, index) => { const option = document.createElement("option"); option.value = index; option.textContent = preset.name; questionPresetSelect.appendChild(option); }); const currentValue = parseInt(questionPresetSelect.dataset.currentIndex || "0", 10); questionPresetSelect.value = Math.min(Math.max(0, currentValue), presets.length - 1); } updateQuestionPresetInputs(); }; if (questionPresetSelect) { questionPresetSelect.addEventListener("change", () => { questionPresetSelect.dataset.currentIndex = questionPresetSelect.value; updateQuestionPresetInputs(); }); } if (addQuestionPreset) { addQuestionPreset.addEventListener("click", () => { const presets = getNormalizedQuestionPresets(); const newPreset = { id: `custom-${Date.now()}`, name: "新提问预设", prompt: "请基于当前话题回答:" }; state2.customQuestionPresets = [...presets, newPreset]; GM_setValue2("customQuestionPresets", state2.customQuestionPresets); if (questionPresetSelect) { questionPresetSelect.dataset.currentIndex = String(state2.customQuestionPresets.length - 1); } updateQuestionPresetSelect(); createSettingsToast2("新提问预设已添加!", "info", 2600); }); } if (saveQuestionPreset) { saveQuestionPreset.addEventListener("click", () => { if (!questionPresetName || !questionPresetPrompt) return; const presets = getNormalizedQuestionPresets(); const selectedIndex = questionPresetSelect ? parseInt(questionPresetSelect.value, 10) : 0; if (!presets[selectedIndex]) { createSettingsToast2("请先添加一个自定义提问预设!", "warning", 2800); return; } const name = questionPresetName.value.trim(); const prompt = questionPresetPrompt.value.trim(); if (!name || !prompt) { createSettingsToast2("请填写预设名称和预设问题!", "warning", 2800); return; } const nextPresets = presets.slice(); nextPresets[selectedIndex] = { ...nextPresets[selectedIndex], name, prompt }; state2.customQuestionPresets = typeof normalizeQuestionPromptPresets2 === "function" ? normalizeQuestionPromptPresets2(nextPresets) : nextPresets; GM_setValue2("customQuestionPresets", state2.customQuestionPresets); if (questionPresetSelect) { questionPresetSelect.dataset.currentIndex = String(selectedIndex); } updateQuestionPresetSelect(); createSettingsToast2("提问预设已保存!", "success", 2600); }); } if (deleteQuestionPreset) { deleteQuestionPreset.addEventListener("click", () => { const presets = getNormalizedQuestionPresets(); const selectedIndex = questionPresetSelect ? parseInt(questionPresetSelect.value, 10) : 0; if (!presets[selectedIndex]) { createSettingsToast2("暂无可删除的自定义预设!", "warning", 2600); return; } if (!confirm("确定要删除当前提问预设吗?")) return; const nextPresets = presets.filter((_2, index) => index !== selectedIndex); state2.customQuestionPresets = typeof normalizeQuestionPromptPresets2 === "function" ? normalizeQuestionPromptPresets2(nextPresets) : nextPresets; GM_setValue2("customQuestionPresets", state2.customQuestionPresets); if (questionPresetSelect) { questionPresetSelect.dataset.currentIndex = String(Math.max(0, selectedIndex - 1)); } updateQuestionPresetSelect(); createSettingsToast2("提问预设已删除!", "success", 2600); }); } if (saveSummaryFilters) { saveSummaryFilters.addEventListener("click", () => { saveSummaryFilterSettings(); }); } if (resetSummaryFilters) { resetSummaryFilters.addEventListener("click", () => { resetSummaryFilterSettings(); }); } const bytesToMbInputValue = (bytes, fallbackBytes) => { const numeric = Number(bytes); const fallback = Number(fallbackBytes); const normalized = Number.isFinite(numeric) && numeric > 0 ? numeric : Number.isFinite(fallback) && fallback > 0 ? fallback : 4 * 1024 * 1024; const mb = normalized / (1024 * 1024); return Number.isInteger(mb) ? String(mb) : String(Number(mb.toFixed(2))); }; const mbInputToBytes = (value, fallbackBytes) => { const parsed = Number(value); if (!Number.isFinite(parsed) || parsed <= 0) return fallbackBytes; return Math.round(parsed * 1024 * 1024); }; function syncApiImageOptionsState() { const enabled = apiImageInputEnabled?.checked === true; if (apiImageOptions) { apiImageOptions.style.display = enabled ? "" : "none"; apiImageOptions.querySelectorAll("input, select").forEach((input) => { input.disabled = !enabled; }); } } function updateApiConfigInputs() { if (!apiName || !apiUrl || !apiKey || !apiModel || !newTopicAutoSummarizeCheckbox || !autoRetryCountInput || !autoRetryIntervalInput) return; const currentConfig = getCurrentApiConfiguration2(); if (!currentConfig) return; syncAutoRetrySettingsFromCurrentApiConfiguration2?.(); apiName.value = currentConfig.name; apiUrl.value = currentConfig.url; apiKey.value = currentConfig.key; apiModel.value = currentConfig.model; newTopicAutoSummarizeCheckbox.checked = state2.newTopicAutoSummarize; if (sidebarAutoSummarizeSwitch) { sidebarAutoSummarizeSwitch.checked = state2.newTopicAutoSummarize; } autoRetryCountInput.value = normalizeAutoRetryCount2(currentConfig.retryCount, state2.autoRetryCount); autoRetryIntervalInput.value = normalizeAutoRetryInterval2(currentConfig.retryInterval, state2.autoRetryInterval); if (apiImageInputEnabled) { apiImageInputEnabled.checked = currentConfig.imageInputEnabled === true; } if (apiImageDetail) { apiImageDetail.value = currentConfig.imageDetail || "auto"; } if (apiMaxImages) { apiMaxImages.value = currentConfig.maxImagesPerRequest || 6; } if (apiMaxImageMb) { apiMaxImageMb.value = bytesToMbInputValue(currentConfig.maxImageBytes, 4 * 1024 * 1024); } if (apiMaxTotalImageMb) { apiMaxTotalImageMb.value = bytesToMbInputValue(currentConfig.maxTotalImageBytes, 12 * 1024 * 1024); } syncApiImageOptionsState(); } updateApiSelect = () => { if (!apiSelect) return; state2.currentApiIndex = normalizeCurrentApiIndex2(state2.currentApiIndex, state2.apiConfigurations); apiSelect.innerHTML = ""; state2.apiConfigurations.forEach((config, index) => { const option = document.createElement("option"); option.value = index; option.textContent = config.name; apiSelect.appendChild(option); }); apiSelect.value = String(state2.currentApiIndex); updateApiConfigInputs(); updateDeArrowSettingsInputs(); }; if (apiSelect) { apiSelect.addEventListener("change", (e) => { state2.currentApiIndex = normalizeCurrentApiIndex2(e.target.value, state2.apiConfigurations); GM_setValue2("currentApiIndex", state2.currentApiIndex); syncAutoRetrySettingsFromCurrentApiConfiguration2?.(); updateApiConfigInputs(); }); } if (apiImageInputEnabled) { apiImageInputEnabled.addEventListener("change", () => { syncApiImageOptionsState(); }); } if (toggleApiImageSettings) { const toggleImageSettingsFold = () => { const collapsed = !(apiImageSettings?.classList.contains("is-collapsed")); setApiImageSettingsCollapsed(collapsed); }; toggleApiImageSettings.addEventListener("click", (event) => { event.preventDefault(); toggleImageSettingsFold(); }); const apiImageHeading = apiImageSettings?.querySelector(".api-image-settings-heading"); if (apiImageHeading) { apiImageHeading.addEventListener("click", (event) => { if (event.target.closest("#toggle-api-image-settings")) return; toggleImageSettingsFold(); }); } } if (saveApi) { saveApi.addEventListener("click", () => { if (!apiName || !apiUrl || !apiKey || !apiModel || !newTopicAutoSummarizeCheckbox || !autoRetryCountInput || !autoRetryIntervalInput) return; if (!apiName.value.trim() || !apiUrl.value.trim() || !apiKey.value.trim() || !apiModel.value.trim()) { createToast2("请填写所有API配置项!", "warning", 3e3); return; } const currentConfig = getCurrentApiConfiguration2(); const nextRetryCount = parseInt(autoRetryCountInput.value, 10); const nextRetryInterval = parseInt(autoRetryIntervalInput.value, 10); state2.newTopicAutoSummarize = newTopicAutoSummarizeCheckbox.checked; if (Number.isNaN(nextRetryCount) || nextRetryCount < 1 || nextRetryCount > 10) { createToast2("重试次数必须在1到10之间!", "warning", 3e3); autoRetryCountInput.value = currentConfig && currentConfig.retryCount ? currentConfig.retryCount : state2.autoRetryCount; return; } if (Number.isNaN(nextRetryInterval) || nextRetryInterval < 1 || nextRetryInterval > 600) { createToast2("重试间隔时间必须在1到600秒之间!", "warning", 3e3); autoRetryIntervalInput.value = currentConfig && currentConfig.retryInterval ? currentConfig.retryInterval : state2.autoRetryInterval; return; } state2.apiConfigurations[state2.currentApiIndex] = normalizeApiConfiguration2({ name: apiName.value.trim(), url: apiUrl.value.trim(), key: apiKey.value.trim(), model: apiModel.value.trim(), retryCount: nextRetryCount, retryInterval: nextRetryInterval, imageInputEnabled: apiImageInputEnabled?.checked === true, imageDetail: apiImageDetail?.value || currentConfig?.imageDetail || "auto", maxImagesPerRequest: apiMaxImages?.value || currentConfig?.maxImagesPerRequest || 6, maxImageBytes: mbInputToBytes(apiMaxImageMb?.value, currentConfig?.maxImageBytes || 4 * 1024 * 1024), maxTotalImageBytes: mbInputToBytes(apiMaxTotalImageMb?.value, currentConfig?.maxTotalImageBytes || 12 * 1024 * 1024) }, currentConfig || {}); state2.autoRetryCount = nextRetryCount; state2.autoRetryInterval = nextRetryInterval; persistApiConfigurations2?.(); GM_setValue2("newTopicAutoSummarize", state2.newTopicAutoSummarize); updateApiSelect(); createSettingsToast2("API配置已保存!", "success", 3e3); }); } if (deleteApi) { deleteApi.addEventListener("click", () => { if (state2.apiConfigurations.length > 1) { if (confirm("确定要删除当前API配置吗?")) { state2.apiConfigurations.splice(state2.currentApiIndex, 1); state2.currentApiIndex = normalizeCurrentApiIndex2(state2.currentApiIndex, state2.apiConfigurations); persistApiConfigurations2?.(); updateApiSelect(); createSettingsToast2("API配置已删除!", "success", 3e3); } } else { createToast2("至少需要保留一个API配置!", "warning", 3e3); } }); } if (addApi) { addApi.addEventListener("click", () => { const currentConfig = getCurrentApiConfiguration2(); const retryFallback = { retryCount: currentConfig && currentConfig.retryCount, retryInterval: currentConfig && currentConfig.retryInterval }; const newApi = createDefaultApiConfiguration2({}, retryFallback); state2.apiConfigurations.push(newApi); state2.currentApiIndex = state2.apiConfigurations.length - 1; persistApiConfigurations2?.(); updateApiSelect(); createSettingsToast2("新API配置已添加!", "info", 3e3); }); } if (copyApi) { copyApi.addEventListener("click", () => { const currentConfig = getCurrentApiConfiguration2() || {}; const sourceName = apiName?.value.trim() || currentConfig.name || "新API配置"; const copied = normalizeApiConfiguration2({ name: uniqueApiCopyName(sourceName), url: apiUrl?.value.trim() || currentConfig.url, key: apiKey?.value.trim() || currentConfig.key, model: apiModel?.value.trim() || currentConfig.model, retryCount: currentConfig.retryCount, retryInterval: currentConfig.retryInterval, imageInputEnabled: apiImageInputEnabled?.checked === true, imageDetail: apiImageDetail?.value || currentConfig.imageDetail || "auto", maxImagesPerRequest: apiMaxImages?.value || currentConfig.maxImagesPerRequest || 6, maxImageBytes: mbInputToBytes(apiMaxImageMb?.value, currentConfig.maxImageBytes || 4 * 1024 * 1024), maxTotalImageBytes: mbInputToBytes(apiMaxTotalImageMb?.value, currentConfig.maxTotalImageBytes || 12 * 1024 * 1024) }, currentConfig); state2.apiConfigurations.push(copied); state2.currentApiIndex = state2.apiConfigurations.length - 1; persistApiConfigurations2?.(); updateApiSelect(); createSettingsToast2(`已复制为「${copied.name}」`, "success", 3e3); }); } if (defaultOpenSidebarSwitch) { defaultOpenSidebarSwitch.checked = state2.defaultOpenSidebar; defaultOpenSidebarSwitch.addEventListener("change", function() { state2.defaultOpenSidebar = this.checked; GM_setValue2("defaultOpenSidebar", state2.defaultOpenSidebar); }); } if (sidebarAutoSummarizeSwitch) { sidebarAutoSummarizeSwitch.checked = state2.newTopicAutoSummarize; sidebarAutoSummarizeSwitch.addEventListener("change", () => { state2.newTopicAutoSummarize = sidebarAutoSummarizeSwitch.checked; GM_setValue2("newTopicAutoSummarize", state2.newTopicAutoSummarize); if (newTopicAutoSummarizeCheckbox) { newTopicAutoSummarizeCheckbox.checked = state2.newTopicAutoSummarize; } if (state2.newTopicAutoSummarize) { const topicId = document.getElementById("building")?.value || extractTopicId2?.(); if (topicId && /^https:\/\/linux\.do\/t\/topic\/\d+/.test(window.location.href)) { attemptAutoSummarize2?.(topicId); } } }); } updateSummaryWidthOffset = () => { const offsetInput2 = document.getElementById("summary-width-offset"); if (!offsetInput2) return; state2.summaryWidthOffset = normalizeSummaryWidthOffset2( offsetInput2.value, DEFAULT_SUMMARY_WIDTH_OFFSET2 ); offsetInput2.value = state2.summaryWidthOffset; GM_setValue2("summaryWidthOffset", state2.summaryWidthOffset); applySidebarSettings2(); }; const offsetInput = document.getElementById("summary-width-offset"); if (offsetInput) { offsetInput.addEventListener("change", () => { updateSummaryWidthOffset(); }); } updatePromptSelect(); updateSummaryFilterInputs(); updateApiSelect(); updateSummaryWidthOffset(); function exportSettings(returnObjOnly = false) { try { const settings = { promptConfigurations: state2.promptConfigurations, currentPromptIndex: state2.currentPromptIndex, customQuestionPresets: state2.customQuestionPresets, apiConfigurations: state2.apiConfigurations, currentApiIndex: state2.currentApiIndex, defaultOpenSidebar: state2.defaultOpenSidebar, settingsTabsCollapsed: state2.settingsTabsCollapsed, summaryWidthOffset: state2.summaryWidthOffset, summaryOutputFilters: state2.summaryOutputFilters, newTopicAutoSummarize: state2.newTopicAutoSummarize, listPageSummaryEnabled: state2.listPageSummaryEnabled, autoShowSummaryInList: state2.autoShowSummaryInList, listPageSummaryMaxLines: state2.listPageSummaryMaxLines, dearrowEnabled: state2.dearrowEnabled === true, dearrowAutoRewrite: state2.dearrowAutoRewrite === true, dearrowJudgmentPrompt: normalizePromptValue( state2.dearrowJudgmentPrompt, getDefaultDeArrowPrompt("dearrowJudgmentPrompt") ), dearrowRewritePrompt: normalizePromptValue( state2.dearrowRewritePrompt, getDefaultDeArrowPrompt("dearrowRewritePrompt") ), dearrowJudgmentApiIndex: state2.dearrowJudgmentApiIndex, dearrowRewriteApiIndex: state2.dearrowRewriteApiIndex, dearrowScopeRules: state2.dearrowScopeRules, toastEnabled: state2.toastEnabled, toastSettings: state2.toastSettings, toastClickAutoOpenSidebar: state2.toastClickAutoOpenSidebar, summaryTopicIds: Array.from(state2.summaryTopicIds), summaryWidthType: state2.summaryWidthType, summaryWidthValue: state2.summaryWidthValue, driveSummarySettings: state2.driveSummarySettings, sidebarWidth: GM_getValue2("sidebarWidth", "15%"), sidebarPosition: GM_getValue2("sidebarPosition", "left"), sidebarTopDistance: GM_getValue2("sidebarTopDistance", "5%"), sidebarBottomDistance: GM_getValue2("sidebarBottomDistance", "5%") }; if (returnObjOnly) { return settings; } const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(settings, null, 2))}`; const downloadAnchorNode = document.createElement("a"); downloadAnchorNode.setAttribute("href", dataStr); const currentDate = /* @__PURE__ */ new Date(); const formattedDate = currentDate.toISOString().split("T")[0]; downloadAnchorNode.setAttribute("download", `脚本配置 - [LINUX DO] 🌟 主题 & 回复 总结_${formattedDate}.json`); document.body.appendChild(downloadAnchorNode); downloadAnchorNode.click(); downloadAnchorNode.remove(); createSettingsToast2("设置已导出!", "success", 3e3); } catch (error) { createSettingsToast2("导出设置时出错!", "error"); console.error("Export error:", error); if (returnObjOnly) { return null; } } } function importSettings(importedSettings) { if (!importedSettings || typeof importedSettings !== "object" || !Array.isArray(importedSettings.promptConfigurations)) { createSettingsToast2("导入失败:设置数据无效或格式错误!", "error"); return false; } const importedDeArrowScopeValidation = importedSettings.dearrowScopeRules !== void 0 ? typeof validateDeArrowScopeRules2 === "function" ? validateDeArrowScopeRules2(importedSettings.dearrowScopeRules) : { valid: true, rules: importedSettings.dearrowScopeRules, errors: [] } : null; if (importedDeArrowScopeValidation && !importedDeArrowScopeValidation.valid) { const firstError = importedDeArrowScopeValidation.errors?.[0]?.message || "DeArrow 作用范围无效"; createSettingsToast2(`导入失败:${firstError}`, "error", 3200); return false; } try { state2.promptConfigurations = importedSettings.promptConfigurations ?? state2.promptConfigurations; state2.currentPromptIndex = importedSettings.currentPromptIndex >= 0 && importedSettings.currentPromptIndex < state2.promptConfigurations.length ? importedSettings.currentPromptIndex : 0; state2.customQuestionPresets = typeof normalizeQuestionPromptPresets2 === "function" ? normalizeQuestionPromptPresets2(importedSettings.customQuestionPresets ?? state2.customQuestionPresets) : Array.isArray(importedSettings.customQuestionPresets) ? importedSettings.customQuestionPresets : state2.customQuestionPresets; const importedApiRetryFallback = { retryCount: normalizeAutoRetryCount2(importedSettings.autoRetryCount, state2.autoRetryCount), retryInterval: normalizeAutoRetryInterval2(importedSettings.autoRetryInterval, state2.autoRetryInterval) }; state2.apiConfigurations = importedSettings.apiConfigurations ? normalizeApiConfigurations2(importedSettings.apiConfigurations, importedApiRetryFallback) : state2.apiConfigurations; state2.currentApiIndex = normalizeCurrentApiIndex2(importedSettings.currentApiIndex, state2.apiConfigurations); state2.defaultOpenSidebar = importedSettings.defaultOpenSidebar !== void 0 ? importedSettings.defaultOpenSidebar : state2.defaultOpenSidebar; state2.settingsTabsCollapsed = importedSettings.settingsTabsCollapsed !== void 0 ? importedSettings.settingsTabsCollapsed : state2.settingsTabsCollapsed; state2.summaryWidthOffset = normalizeSummaryWidthOffset2(importedSettings.summaryWidthOffset, state2.summaryWidthOffset); state2.summaryOutputFilters = normalizeSummaryOutputFilters2(importedSettings.summaryOutputFilters ?? state2.summaryOutputFilters); state2.newTopicAutoSummarize = importedSettings.newTopicAutoSummarize !== void 0 ? importedSettings.newTopicAutoSummarize : state2.newTopicAutoSummarize; state2.listPageSummaryEnabled = importedSettings.listPageSummaryEnabled !== void 0 ? importedSettings.listPageSummaryEnabled : state2.listPageSummaryEnabled; state2.autoShowSummaryInList = importedSettings.autoShowSummaryInList !== void 0 ? importedSettings.autoShowSummaryInList : state2.autoShowSummaryInList; state2.listPageSummaryMaxLines = importedSettings.listPageSummaryMaxLines ?? state2.listPageSummaryMaxLines; state2.dearrowEnabled = importedSettings.dearrowEnabled !== void 0 ? importedSettings.dearrowEnabled === true : state2.dearrowEnabled; state2.dearrowAutoRewrite = importedSettings.dearrowAutoRewrite !== void 0 ? importedSettings.dearrowAutoRewrite === true : state2.dearrowAutoRewrite === true; if (importedSettings.dearrowJudgmentPrompt !== void 0) { state2.dearrowJudgmentPrompt = normalizePromptValue( importedSettings.dearrowJudgmentPrompt, getDefaultDeArrowPrompt("dearrowJudgmentPrompt") ); } if (importedSettings.dearrowRewritePrompt !== void 0) { state2.dearrowRewritePrompt = normalizePromptValue( importedSettings.dearrowRewritePrompt, getDefaultDeArrowPrompt("dearrowRewritePrompt") ); } const importedLegacyDeArrowApiIndex = importedSettings.dearrowApiIndex; const importedJudgmentApiIndex = importedSettings.dearrowJudgmentApiIndex ?? importedLegacyDeArrowApiIndex ?? state2.dearrowJudgmentApiIndex; const importedRewriteApiIndex = importedSettings.dearrowRewriteApiIndex ?? importedLegacyDeArrowApiIndex ?? state2.dearrowRewriteApiIndex; state2.dearrowJudgmentApiIndex = typeof normalizeDeArrowApiIndex2 === "function" ? normalizeDeArrowApiIndex2( importedJudgmentApiIndex, state2.apiConfigurations ) : Math.max(0, parseInt(importedJudgmentApiIndex, 10) || 0); state2.dearrowRewriteApiIndex = typeof normalizeDeArrowApiIndex2 === "function" ? normalizeDeArrowApiIndex2( importedRewriteApiIndex, state2.apiConfigurations ) : Math.max(0, parseInt(importedRewriteApiIndex, 10) || 0); if (importedDeArrowScopeValidation) { state2.dearrowScopeRules = importedDeArrowScopeValidation.rules; } state2.toastEnabled = importedSettings.toastEnabled !== void 0 ? importedSettings.toastEnabled : state2.toastEnabled; state2.toastSettings = importedSettings.toastSettings ?? state2.toastSettings; state2.toastClickAutoOpenSidebar = importedSettings.toastClickAutoOpenSidebar !== void 0 ? importedSettings.toastClickAutoOpenSidebar : state2.toastClickAutoOpenSidebar; state2.summaryWidthType = importedSettings.summaryWidthType ?? state2.summaryWidthType; state2.summaryWidthValue = importedSettings.summaryWidthValue ?? state2.summaryWidthValue; if (importedSettings.driveSummarySettings) { state2.driveSummarySettings = persistDriveSummarySettings2(importedSettings.driveSummarySettings); } if (Array.isArray(importedSettings.summaryTopicIds)) { state2.summaryTopicIds = new Set(sanitizeSummaryTopicIds2(importedSettings.summaryTopicIds)); persistSummaryTopicIds2?.(); } const resolvedSidebarSettings = resolveImportedSidebarSettings2(importedSettings, { sidebarWidth: GM_getValue2("sidebarWidth", "15%"), sidebarPosition: GM_getValue2("sidebarPosition", "left"), sidebarTopDistance: GM_getValue2("sidebarTopDistance", "5%"), sidebarBottomDistance: GM_getValue2("sidebarBottomDistance", "5%") }); GM_setValue2("promptConfigurations", state2.promptConfigurations); GM_setValue2("currentPromptIndex", state2.currentPromptIndex); GM_setValue2("customQuestionPresets", state2.customQuestionPresets); persistApiConfigurations2?.({ retryFallback: importedApiRetryFallback }); GM_setValue2("defaultOpenSidebar", state2.defaultOpenSidebar); GM_setValue2("settingsTabsCollapsed", state2.settingsTabsCollapsed); GM_setValue2("summaryWidthOffset", state2.summaryWidthOffset); GM_setValue2("summaryOutputFilters", state2.summaryOutputFilters); GM_setValue2("newTopicAutoSummarize", state2.newTopicAutoSummarize); GM_setValue2("listPageSummaryEnabled", state2.listPageSummaryEnabled); GM_setValue2("autoShowSummaryInList", state2.autoShowSummaryInList); GM_setValue2("listPageSummaryMaxLines", state2.listPageSummaryMaxLines); GM_setValue2("dearrowEnabled", state2.dearrowEnabled); GM_setValue2("dearrowAutoRewrite", state2.dearrowAutoRewrite); if (state2.dearrowJudgmentPrompt !== void 0) { GM_setValue2("dearrowJudgmentPrompt", state2.dearrowJudgmentPrompt); } if (state2.dearrowRewritePrompt !== void 0) { GM_setValue2("dearrowRewritePrompt", state2.dearrowRewritePrompt); } GM_setValue2("dearrowJudgmentApiIndex", state2.dearrowJudgmentApiIndex); GM_setValue2("dearrowRewriteApiIndex", state2.dearrowRewriteApiIndex); GM_setValue2("dearrowScopeRules", state2.dearrowScopeRules); GM_setValue2("toastEnabled", state2.toastEnabled); GM_setValue2("toastSettings", state2.toastSettings); GM_setValue2("toastClickAutoOpenSidebar", state2.toastClickAutoOpenSidebar); GM_setValue2("summaryWidthType", state2.summaryWidthType); GM_setValue2("summaryWidthValue", state2.summaryWidthValue); GM_setValue2("sidebarWidth", resolvedSidebarSettings.sidebarWidth); GM_setValue2("sidebarPosition", resolvedSidebarSettings.sidebarPosition); GM_setValue2("sidebarTopDistance", resolvedSidebarSettings.sidebarTopDistance); GM_setValue2("sidebarBottomDistance", resolvedSidebarSettings.sidebarBottomDistance); const listSummaryEnabledSwitchEl = document.getElementById("list-summary-enabled-switch"); const autoShowSummarySwitchEl = document.getElementById("auto-show-summary-switch"); const listSummaryMaxLinesInputEl = document.getElementById("list-summary-max-lines"); const summaryWidthOffsetInput = document.getElementById("summary-width-offset"); const newTopicAutoSummarizeCheckboxEl = document.getElementById("new-topic-auto-summarize"); const sidebarAutoSummarizeSwitchEl = document.getElementById("sidebar-auto-summarize-switch"); const toastClickAutoOpenSidebarSwitchEl = document.getElementById("toast-click-auto-open-sidebar-switch"); const autoRetryCountInputEl = document.getElementById("auto-retry-count"); const autoRetryIntervalInputEl = document.getElementById("auto-retry-interval"); if (listSummaryEnabledSwitchEl) listSummaryEnabledSwitchEl.checked = state2.listPageSummaryEnabled; if (autoShowSummarySwitchEl) autoShowSummarySwitchEl.checked = state2.autoShowSummaryInList; if (listSummaryMaxLinesInputEl) listSummaryMaxLinesInputEl.value = state2.listPageSummaryMaxLines; updatePromptSelect(); updateQuestionPresetSelect(); updateSummaryFilterInputs(); updateApiSelect(); applySidebarSettings2(); if (summaryWidthOffsetInput) summaryWidthOffsetInput.value = state2.summaryWidthOffset; if (newTopicAutoSummarizeCheckboxEl) newTopicAutoSummarizeCheckboxEl.checked = state2.newTopicAutoSummarize; if (sidebarAutoSummarizeSwitchEl) sidebarAutoSummarizeSwitchEl.checked = state2.newTopicAutoSummarize; if (toastClickAutoOpenSidebarSwitchEl) toastClickAutoOpenSidebarSwitchEl.checked = state2.toastClickAutoOpenSidebar; if (autoRetryCountInputEl) autoRetryCountInputEl.value = state2.autoRetryCount; if (autoRetryIntervalInputEl) autoRetryIntervalInputEl.value = state2.autoRetryInterval; updateDeArrowSettingsInputs(); try { addToastSettingsToModal2(); updateAdjustmentPrompts2(); updateListSummaryStyles?.(); applySummaryWidthSettings2(); enhanceSummaryWidthSettings2(); syncDriveSummarySettingsUI2?.(); const onListSummaryPage = isListSummaryPageUrl2(state2.currentPageUrl); if (state2.listPageSummaryEnabled && onListSummaryPage) { if (typeof refreshListSummaryForCurrentPage2 === "function") { refreshListSummaryForCurrentPage2({ forceRebuild: true, delay: 0 }); } else { removeTopicListSummaryButtons2?.({ preserveExpanded: true }); addTopicListSummaryButtons?.(); restoreExpandedSummaryRows?.(); } } else { clearListSummaryBootstrapWatcher2?.(); removeTopicListSummaryButtons2?.({ preserveExpanded: true }); if (window.topicListObserver) window.topicListObserver.disconnect(); } refreshDeArrowForCurrentPage2?.({ forceRebuild: true, pullDrive: true }); updateAllSummaryButtonsAndContainers?.(); const currentTopicId = document.getElementById("building")?.value || extractTopicId2?.(); if (currentTopicId) { updateSidebarSubmitButtonState2?.(currentTopicId); } applyTabsCollapsedState(state2.settingsTabsCollapsed); } catch (uiErr) { console.warn("UI refresh after import failed:", uiErr); } createSettingsToast2("设置已成功导入并应用!", "success", 3e3); return true; } catch (error) { createSettingsToast2("应用导入的设置时出错!", "error"); console.error("Error applying imported settings:", error); return false; } } if (exportSettingsButton && exportSettingsButton.dataset.bound !== "true") { exportSettingsButton.dataset.bound = "true"; exportSettingsButton.addEventListener("click", (event) => { event.preventDefault(); exportSettings(false); }); } if (importSettingsButton && importSettingsFile && importSettingsButton.dataset.bound !== "true") { importSettingsButton.dataset.bound = "true"; importSettingsButton.addEventListener("click", (event) => { event.preventDefault(); importSettingsFile.click(); }); } if (importSettingsFile && importSettingsFile.dataset.bound !== "true") { importSettingsFile.dataset.bound = "true"; importSettingsFile.addEventListener("change", (event) => { const file = event.target.files?.[0]; if (!file) return; if (typeof FileReader !== "function") { createSettingsToast2("导入失败:当前浏览器不支持读取文件", "error", 3e3); importSettingsFile.value = ""; return; } const reader = new FileReader(); reader.onload = (loadEvent) => { try { importSettings(JSON.parse(loadEvent.target.result)); } catch (error) { createSettingsToast2("导入失败:格式有误", "error", 3e3); console.error("Import settings parse error:", error); } finally { importSettingsFile.value = ""; } }; reader.onerror = () => { createSettingsToast2("导入失败:无法读取文件", "error", 3e3); importSettingsFile.value = ""; }; reader.readAsText(file); }); } registerPublicApiHandlers2?.({ exportSettings, importSettings }); if (!importExportFeatureController) { importExportFeatureController = initializeImportExportFeature2({ createToast: createToast2, createSettingsToast: createSettingsToast2, exportSettingsObject: () => exportSettings(true), importSettings, getSummaryHistoryMap: () => getSummaryHistoryMap(), setSummaryHistoryMap: (summaryHistory) => setSummaryHistoryMap(summaryHistory), getTopicQuestionHistoryMap: () => getTopicQuestionHistoryMap?.() || {}, setTopicQuestionHistoryMap: (questionHistory) => setTopicQuestionHistoryMap?.(questionHistory), getDeArrowTopicStates: () => getDeArrowTopicStates?.() || {}, setDeArrowTopicStates: (topicStates) => setDeArrowTopicStates?.(topicStates), normalizeDeArrowTopicStates: normalizeDeArrowTopicStates2, syncSummaryTopicIdsFromSources: syncSummaryTopicIdsFromSources2, replaceSummaryTopicIdsFromHistoryMap: replaceSummaryTopicIdsFromHistoryMap2, markDriveSummaryTopicsDirty: markDriveSummaryTopicsDirty2, markDriveDeArrowDirty: markDriveDeArrowDirty2, scheduleDriveSummarySync: scheduleDriveSummarySync2, updateAllSummaryButtonsAndContainers, syncDriveSummarySettingsUI: syncDriveSummarySettingsUI2, persistDriveSummarySettings: persistDriveSummarySettings2, getDriveSummarySettings, uploadSummaryHistoryToDrive: uploadSummaryHistoryToDrive2, rebuildSummaryTopicIdsFromDrive: rebuildSummaryTopicIdsFromDrive2 }); } importExportFeatureController?.mountPanels?.(); registerPublicApiHandlers2?.({ exportSummaryContent: importExportFeatureController?.exportSummaryContent, exportAllData: importExportFeatureController?.exportAllData, importAllData: importExportFeatureController?.importAllData }); updateAdjustmentPrompts2 = () => { const sidebarWidthScriptActive = isSidebarWidthScriptActive2(); const widthMsg = document.getElementById("width-adjustment-message"); const offsetMsg = document.getElementById("offset-adjustment-message"); const widthSlider = document.getElementById("sidebar-width-slider"); const offsetInput2 = document.getElementById("summary-width-offset"); if (!widthMsg || !offsetMsg || !widthSlider || !offsetInput2) { return; } if (sidebarWidthScriptActive) { widthMsg.textContent = "已锁定🔒!(宽度已由侧边栏宽度控制脚本接管!)"; widthMsg.classList.remove("inactive"); widthSlider.disabled = true; offsetMsg.textContent = "已解锁🔓!(宽度偏差值可正负调整,负值会收窄面板)"; offsetMsg.classList.remove("inactive"); offsetInput2.disabled = false; } else { widthMsg.textContent = "已解锁🔓!(未检测到侧边栏宽度控制脚本,宽度不受接管!)"; widthMsg.classList.add("inactive"); widthSlider.disabled = false; offsetMsg.textContent = "已锁定🔒!(未检测到侧边栏宽度控制脚本,偏差值不可用)"; offsetMsg.classList.add("inactive"); offsetInput2.disabled = true; } }; } function enhanceSummaryWidthSettings2() { const listSummarySettingsTab = document.getElementById("list-summary-settings"); if (!listSummarySettingsTab) return; const widthSettings = listSummarySettingsTab.querySelector(".width-settings"); if (!widthSettings) return; widthSettings.innerHTML = ""; const widthTypeWrapper = document.createElement("div"); widthTypeWrapper.className = "width-type-options"; const widthTypeTitle = document.createElement("label"); widthTypeTitle.className = "width-type-title"; widthTypeTitle.textContent = "选择宽度类型:"; widthTypeWrapper.appendChild(widthTypeTitle); const widthTypeOptions = [ { value: "percent", label: "相对宽度 (百分比)" }, { value: "pixel", label: "绝对宽度 (像素)" } ]; const widthTypeSelect = document.createElement("details"); widthTypeSelect.id = "summary-width-type"; widthTypeSelect.className = "select-kit single-select combobox combo-box has-selection width-type-select"; const selectHeader = document.createElement("summary"); selectHeader.id = "summary-width-type-header"; selectHeader.className = "select-kit-header single-select-header combo-box-header"; selectHeader.setAttribute("role", "listbox"); selectHeader.setAttribute("tabindex", "0"); const headerWrapper = document.createElement("div"); headerWrapper.className = "select-kit-header-wrapper"; const selectedName = document.createElement("div"); selectedName.className = "select-kit-selected-name selected-name choice"; const selectedNameText = document.createElement("span"); selectedNameText.className = "name"; selectedName.appendChild(selectedNameText); const caretIcon = document.createElementNS("http://www.w3.org/2000/svg", "svg"); caretIcon.setAttribute("class", "fa d-icon d-icon-caret-down svg-icon fa-width-auto caret-icon svg-string"); caretIcon.setAttribute("aria-hidden", "true"); caretIcon.setAttribute("xmlns", "http://www.w3.org/2000/svg"); const caretUse = document.createElementNS("http://www.w3.org/2000/svg", "use"); caretUse.setAttribute("href", "#caret-down"); caretIcon.appendChild(caretUse); headerWrapper.appendChild(selectedName); headerWrapper.appendChild(caretIcon); selectHeader.appendChild(headerWrapper); widthTypeSelect.appendChild(selectHeader); const selectBody = document.createElement("div"); selectBody.id = "summary-width-type-body"; selectBody.className = "select-kit-body"; const selectCollection = document.createElement("div"); selectCollection.className = "select-kit-collection"; selectBody.appendChild(selectCollection); widthTypeSelect.appendChild(selectBody); const widthTypeRows = []; function normalizeWidthType(value) { return widthTypeOptions.some((option) => option.value === value) ? value : widthTypeOptions[0].value; } function updateWidthTypeSelect() { state2.summaryWidthType = normalizeWidthType(state2.summaryWidthType); const activeOption = widthTypeOptions.find((option) => option.value === state2.summaryWidthType) || widthTypeOptions[0]; const label = activeOption.label; selectedNameText.textContent = label; selectedName.title = label; selectedName.dataset.value = activeOption.value; selectedName.dataset.name = label; selectHeader.dataset.value = activeOption.value; selectHeader.dataset.name = label; selectHeader.setAttribute("name", label); selectHeader.setAttribute("aria-label", `选择宽度类型:${label}`); widthTypeRows.forEach(({ row, option }) => { const isSelected = option.value === activeOption.value; row.classList.toggle("is-selected", isSelected); row.setAttribute("aria-selected", isSelected ? "true" : "false"); }); } widthTypeOptions.forEach((option) => { const row = document.createElement("div"); row.className = "select-kit-row"; row.dataset.value = option.value; row.dataset.name = option.label; row.setAttribute("role", "option"); row.setAttribute("tabindex", "0"); const rowLabel = document.createElement("span"); rowLabel.className = "name"; rowLabel.textContent = option.label; row.appendChild(rowLabel); const selectOption = () => { if (state2.summaryWidthType === option.value) { widthTypeSelect.open = false; return; } state2.summaryWidthType = option.value; toggleWidthContainers(state2.summaryWidthType); updatePreview(); updateWidthTypeSelect(); widthTypeSelect.open = false; if (typeof persistListSummarySettingsHandler === "function") { persistListSummarySettingsHandler({ showToast: false }); } }; row.addEventListener("click", selectOption); row.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); selectOption(); } }); widthTypeRows.push({ row, option }); selectCollection.appendChild(row); }); widthTypeWrapper.appendChild(widthTypeSelect); widthSettings.appendChild(widthTypeWrapper); function createWidthInputSection(config) { const { id, title, min, max, unit, defaultValue, rangeId, inputId } = config; const container = document.createElement("div"); container.id = id; container.className = "width-input-container"; const titleSpan = document.createElement("span"); titleSpan.className = "width-input-title"; const titleMatch = title.match(/^(.*?)(\s*\(.*\))$/); if (titleMatch) { const mainTitle = document.createElement("span"); mainTitle.className = "width-input-title-main"; mainTitle.textContent = titleMatch[1]; const metaTitle = document.createElement("span"); metaTitle.className = "width-input-title-meta"; metaTitle.textContent = titleMatch[2]; titleSpan.appendChild(mainTitle); titleSpan.appendChild(metaTitle); } else { titleSpan.textContent = title; } const headerRow = document.createElement("div"); headerRow.className = "width-input-header"; const inlineGroup = document.createElement("div"); inlineGroup.className = "width-input-inline"; const range = document.createElement("input"); range.type = "range"; range.id = rangeId; range.className = "width-range"; range.min = String(min); range.max = String(max); range.value = String(defaultValue); const numberWrap = document.createElement("div"); numberWrap.className = "width-number-wrap"; const numberInput = document.createElement("input"); numberInput.type = "number"; numberInput.id = inputId; numberInput.className = "number-input summary-width-value-input"; numberInput.min = String(min); numberInput.max = String(max); numberInput.value = String(defaultValue); const unitSpan = document.createElement("span"); unitSpan.className = "unit-label"; unitSpan.textContent = unit; numberWrap.appendChild(numberInput); numberWrap.appendChild(unitSpan); headerRow.appendChild(titleSpan); headerRow.appendChild(numberWrap); inlineGroup.appendChild(range); container.appendChild(headerRow); container.appendChild(inlineGroup); return { container, range, numberInput }; } const percentDefaults = state2.summaryWidthType === "percent" ? state2.summaryWidthValue : 100; const pixelDefaults = state2.summaryWidthType === "pixel" ? state2.summaryWidthValue : 500; const percentSection = createWidthInputSection({ id: "percent-width-container", title: "宽度值 (10-100%)", min: 10, max: 100, unit: "%", defaultValue: percentDefaults, rangeId: "percent-range", inputId: "summary-percent-value" }); const pixelSection = createWidthInputSection({ id: "pixel-width-container", title: "宽度值 (100-2000px)", min: 100, max: 2e3, unit: "px", defaultValue: pixelDefaults, rangeId: "pixel-range", inputId: "summary-pixel-value" }); widthSettings.appendChild(percentSection.container); widthSettings.appendChild(pixelSection.container); const widthPreview = document.createElement("div"); widthPreview.className = "width-preview"; const previewHeader = document.createElement("div"); previewHeader.className = "width-preview-header"; const previewLabel = document.createElement("span"); previewLabel.textContent = "当前预览宽度:"; const previewValue = document.createElement("span"); previewValue.id = "current-width-display"; previewValue.textContent = state2.summaryWidthType === "percent" ? `${percentDefaults}%` : `${pixelDefaults}px`; previewHeader.appendChild(previewLabel); previewHeader.appendChild(previewValue); const previewBarWrapper = document.createElement("div"); previewBarWrapper.className = "width-preview-bar-wrapper"; const previewBar = document.createElement("div"); previewBar.id = "width-preview-box"; previewBarWrapper.appendChild(previewBar); widthPreview.appendChild(previewHeader); widthPreview.appendChild(previewBarWrapper); widthSettings.appendChild(widthPreview); const percentContainer = percentSection.container; const pixelContainer = pixelSection.container; const percentRange = percentSection.range; const percentValue = percentSection.numberInput; const pixelRange = pixelSection.range; const pixelValue = pixelSection.numberInput; const previewBox = previewBar; const currentWidthDisplay = previewValue; function clampPercent(value) { let val = parseInt(value, 10); if (Number.isNaN(val)) val = 10; return Math.max(10, Math.min(100, val)); } function clampPixel(value) { let val = parseInt(value, 10); if (Number.isNaN(val)) val = 100; return Math.max(100, Math.min(2e3, val)); } function toggleWidthContainers(activeType) { if (activeType === "percent") { percentContainer.style.display = ""; pixelContainer.style.display = "none"; } else { percentContainer.style.display = "none"; pixelContainer.style.display = ""; } } function getPercentValue() { const raw = percentValue ? percentValue.value : percentDefaults; const clamped = clampPercent(raw); if (percentValue) percentValue.value = clamped; if (percentRange) percentRange.value = clamped; return clamped; } function getPixelValue() { const raw = pixelValue ? pixelValue.value : pixelDefaults; const clamped = clampPixel(raw); if (pixelValue) pixelValue.value = clamped; if (pixelRange) pixelRange.value = clamped; return clamped; } function updatePreview() { if (!previewBox || !currentWidthDisplay) return; if (state2.summaryWidthType === "percent") { const percent = getPercentValue(); previewBox.style.width = `${percent}%`; currentWidthDisplay.textContent = `${percent}%`; } else { const px = getPixelValue(); const percent = Math.min(100, Math.max(0, Math.round(px / 2e3 * 100))); previewBox.style.width = `${percent}%`; currentWidthDisplay.textContent = `${px}px`; } } if (percentRange && percentValue) { const applyPercentFromRange = () => { const clamped = clampPercent(percentRange.value); percentRange.value = clamped; percentValue.value = clamped; if (state2.summaryWidthType === "percent") updatePreview(); }; const applyPercentFromInput = () => { const clamped = clampPercent(percentValue.value); percentValue.value = clamped; percentRange.value = clamped; if (state2.summaryWidthType === "percent") updatePreview(); }; percentRange.addEventListener("input", applyPercentFromRange); percentValue.addEventListener("input", applyPercentFromInput); percentRange.addEventListener("change", () => { applyPercentFromRange(); if (typeof persistListSummarySettingsHandler === "function") { persistListSummarySettingsHandler({ showToast: false }); } }); percentValue.addEventListener("change", () => { applyPercentFromInput(); if (typeof persistListSummarySettingsHandler === "function") { persistListSummarySettingsHandler({ showToast: false }); } }); } if (pixelRange && pixelValue) { const applyPixelFromRange = () => { const clamped = clampPixel(pixelRange.value); pixelRange.value = clamped; pixelValue.value = clamped; if (state2.summaryWidthType === "pixel") updatePreview(); }; const applyPixelFromInput = () => { const clamped = clampPixel(pixelValue.value); pixelValue.value = clamped; pixelRange.value = clamped; if (state2.summaryWidthType === "pixel") updatePreview(); }; pixelRange.addEventListener("input", applyPixelFromRange); pixelValue.addEventListener("input", applyPixelFromInput); pixelRange.addEventListener("change", () => { applyPixelFromRange(); if (typeof persistListSummarySettingsHandler === "function") { persistListSummarySettingsHandler({ showToast: false }); } }); pixelValue.addEventListener("change", () => { applyPixelFromInput(); if (typeof persistListSummarySettingsHandler === "function") { persistListSummarySettingsHandler({ showToast: false }); } }); } updateWidthTypeSelect(); toggleWidthContainers(state2.summaryWidthType); updatePreview(); } function addToastSettingsToModal2() { const toastSettingsTab = document.getElementById("toast-settings"); if (!toastSettingsTab) return; toastSettingsTab.innerHTML = ""; const subTabs = document.createElement("div"); subTabs.className = "toast-sub-tabs"; subTabs.innerHTML = ` `; toastSettingsTab.appendChild(subTabs); const subTabPanels = document.createElement("div"); subTabPanels.className = "toast-sub-tab-panels"; toastSettingsTab.appendChild(subTabPanels); const basicContent = document.createElement("div"); basicContent.className = "toast-sub-tab-content settings-card active"; basicContent.id = "toast-settings-basic"; subTabPanels.appendChild(basicContent); const basicSwitchDiv = document.createElement("div"); basicSwitchDiv.className = "switch-container"; basicSwitchDiv.innerHTML = ` 1. Toast通知总开关(关/开) 是否显示操作结果的Toast通知? `; basicContent.appendChild(basicSwitchDiv); const autoExpandSwitchDiv = document.createElement("div"); autoExpandSwitchDiv.className = "switch-container"; autoExpandSwitchDiv.innerHTML = ` 2. Toast点击自动展开总结(关/开) 启用后,点击总结完成Toast会自动展开对应总结。 `; basicContent.appendChild(autoExpandSwitchDiv); const clickAutoOpenSidebarSwitchDiv = document.createElement("div"); clickAutoOpenSidebarSwitchDiv.className = "switch-container"; clickAutoOpenSidebarSwitchDiv.innerHTML = ` 3. 点击 Toast 自动展开侧边栏(关/开) 启用后,在话题页点击当前话题Toast会自动展开折叠的侧边栏。 `; basicContent.appendChild(clickAutoOpenSidebarSwitchDiv); const toastAutoExpandSwitch = document.getElementById("toast-auto-expand-switch"); if (toastAutoExpandSwitch) { toastAutoExpandSwitch.addEventListener("change", () => { state2.toastAutoExpand = toastAutoExpandSwitch.checked; GM_setValue2("toastAutoExpand", state2.toastAutoExpand); }); } const toastClickAutoOpenSidebarSwitch = document.getElementById("toast-click-auto-open-sidebar-switch"); if (toastClickAutoOpenSidebarSwitch) { toastClickAutoOpenSidebarSwitch.addEventListener("change", () => { state2.toastClickAutoOpenSidebar = toastClickAutoOpenSidebarSwitch.checked; GM_setValue2("toastClickAutoOpenSidebar", state2.toastClickAutoOpenSidebar); }); } const delayContent = document.createElement("div"); delayContent.className = "toast-sub-tab-content settings-card"; delayContent.id = "toast-settings-delay"; subTabPanels.appendChild(delayContent); const typeSettingsHeader = document.createElement("div"); typeSettingsHeader.className = "toast-settings-header"; typeSettingsHeader.innerHTML = `🕒 时间:${timestamp}
🤖 模型:${model}
`, { preserveSelection: true } ); resultDiv.appendChild(contentWrapper); resultDiv.appendChild(infoContainer); resultDiv.style.display = "flex"; } function displayError(message) { const resultDiv = document.getElementById("summary-result"); if (!resultDiv) return; resultDiv.innerHTML = ""; const contentWrapper = document.createElement("div"); contentWrapper.className = "summary-content-wrapper"; const errorDiv = document.createElement("div"); errorDiv.style.color = "var(--toast-bg-error)"; errorDiv.style.padding = "10px"; errorDiv.style.backgroundColor = "rgba(231, 76, 60, 0.1)"; errorDiv.style.border = "1px solid var(--toast-bg-error)"; errorDiv.style.borderRadius = "5px"; errorDiv.style.marginTop = "10px"; errorDiv.textContent = message; contentWrapper.appendChild(errorDiv); resultDiv.appendChild(contentWrapper); resultDiv.style.display = "flex"; } function createTopicContentAccumulator() { return { dialogues: [], images: [], skippedImages: [], seenImageUrls: /* @__PURE__ */ new Set(), nextImageId: 1 }; } function appendPostImagesToAccumulator(post, cooked, accumulator, fallbackFloor) { const username = post?.username || "未知用户"; const floor = post?.post_number || fallbackFloor || ""; const extracted = extractImagesFromCooked(cooked, { baseUrl: TOPIC_IMAGE_BASE_URL }); const postImages = []; extracted.images.forEach((image) => { const urlKey = image.url; if (!urlKey) { accumulator.skippedImages.push({ ...image, username, floor, reason: "missing-url" }); return; } if (accumulator.seenImageUrls.has(urlKey)) { accumulator.skippedImages.push({ ...image, username, floor, reason: "duplicate-image" }); return; } accumulator.seenImageUrls.add(urlKey); const normalizedImage = { ...image, id: accumulator.nextImageId, username, floor }; accumulator.nextImageId += 1; accumulator.images.push(normalizedImage); postImages.push(normalizedImage); }); extracted.skippedImages.forEach((image) => { accumulator.skippedImages.push({ ...image, username, floor }); }); return postImages; } function formatDialogues(json, accumulator = createTopicContentAccumulator()) { if (!json?.post_stream?.posts) return []; return json.post_stream.posts.map((post, index) => { const cooked = post.cooked || ""; const username = post.username || "未知用户"; const replyToUsername = post.reply_to_user?.username; const postImages = appendPostImagesToAccumulator( post, cooked, accumulator, accumulator.dialogues.length + index + 1 ); const imageText = postImages.length > 0 ? ` ${postImages.map(formatImagePlaceholder).join("\n")}` : ""; return replyToUsername ? `${username}回复${replyToUsername}说:${cooked}${imageText}` : `${username}说:${cooked}${imageText}`; }); } async function fetchTopicPostIds(topicId, currentApi = null) { if (!topicId) throw new Error("Missing topicId"); const postIdsUrl = `https://linux.do/t/${topicId}/post_ids.json`; const idResponse = await fetchLinuxDoTopicContent(postIdsUrl, getFetchOptions2(), { topicId: normalizeTopicId4(topicId), requestKind: "post_ids", currentApi }); if (!idResponse.ok) { throw new Error(`HTTP error ${idResponse.status} fetching post IDs`); } const idJson = await idResponse.json(); if (!Array.isArray(idJson.post_ids)) { throw new Error("Invalid post_ids format received"); } return idJson.post_ids; } function getFullFloorRangeFromPostIds(postIds, maxEnd = DEFAULT_FULL_FLOOR_END) { const totalPosts = Array.isArray(postIds) ? postIds.length : 0; const endFloor = Math.min(totalPosts, Math.max(1, maxEnd)); return { startFloor: 1, endFloor }; } async function getFullFloorRangeForTopic(topicId, maxEnd = DEFAULT_FULL_FLOOR_END, currentApi = null) { const postIds = await fetchTopicPostIds(topicId, currentApi); if (!postIds || postIds.length === 0) { throw new Error("No post_ids returned"); } return getFullFloorRangeFromPostIds(postIds, maxEnd); } async function buildTopicContentContext(building, startFloor, endFloor, currentApi = null) { const urls = await postid_to_url(building, startFloor, endFloor, currentApi); if (!urls || urls.length === 0) { return { dialogues: [], contentText: "", images: [], skippedImages: [] }; } const accumulator = createTopicContentAccumulator(); const fetchOptions = getFetchOptions2(); for (const url of urls) { const response = await fetchLinuxDoTopicContent(url, fetchOptions, { topicId: normalizeTopicId4(building), requestKind: "posts", currentApi }); if (!response.ok) { throw new Error(`HTTP error ${response.status} fetching posts`); } const json = await response.json(); const dialogues = formatDialogues(json, accumulator); accumulator.dialogues = accumulator.dialogues.concat(dialogues); } return { dialogues: accumulator.dialogues, contentText: accumulator.dialogues.join("\n\n"), images: accumulator.images, skippedImages: accumulator.skippedImages }; } async function prepareTopicImagesForCurrentApi(topicContent, operationApi = null) { const currentApi = operationApi || getCurrentApiConfiguration2?.() || {}; return prepareImageInputsForApi(topicContent?.images || [], { apiConfig: currentApi, requestImpl: imageRequest, fetchImpl: typeof fetch === "function" ? fetch : void 0, baseUrl: TOPIC_IMAGE_BASE_URL }); } function safeSlice(arr, start, end) { if (!Array.isArray(arr)) return []; start = Math.max(start, 0); end = end === void 0 || end > arr.length ? arr.length : end; return arr.slice(start, end); } async function postid_to_url(building, startFloor, endFloor, currentApi = null) { const fetchOptions = getFetchOptions2(); const allPostIds = await fetchTopicPostIds(building, currentApi); let targetPostIds = []; if (startFloor === 1 && endFloor >= allPostIds.length) { targetPostIds = allPostIds; } else { targetPostIds = safeSlice(allPostIds, startFloor - 1, endFloor); if (startFloor === 1) { const topicUrl = `https://linux.do/t/${building}.json`; const topicResponse = await fetchLinuxDoTopicContent(topicUrl, fetchOptions, { topicId: normalizeTopicId4(building), requestKind: "topic", currentApi }); if (topicResponse.ok) { const topicJson = await topicResponse.json(); const firstPostId = topicJson?.post_stream?.posts?.[0]?.id; if (firstPostId && (!targetPostIds.length || targetPostIds[0] !== firstPostId)) { targetPostIds.unshift(firstPostId); if (targetPostIds.length > 1 && targetPostIds[1] === firstPostId) { targetPostIds.splice(1, 1); } } if (topicJson?.title) { setTopicTitle2?.(building, topicJson.title); } } } } if (targetPostIds.length === 0) { return []; } const chunkSize = 100; const urls = []; for (let index = 0; index < targetPostIds.length; index += chunkSize) { const chunk = targetPostIds.slice(index, index + chunkSize); const postIdsParam = chunk.map((id) => `post_ids[]=${id}`).join("&"); urls.push(`https://linux.do/t/${building}/posts.json?${postIdsParam}&include_suggested=false`); } return urls; } async function main(building, startFloor, endFloor, retryAttempt = 0, operationApi = null, operationContext = null) { const currentApi = operationApi || { ...typeof getCurrentApiConfiguration2 === "function" ? getCurrentApiConfiguration2() : {} }; const stopNow = getSummaryStopDecision(building, operationContext); if (stopNow) throw stopNow; try { const topicTitle = typeof ensureTopicTitle2 === "function" ? await ensureTopicTitle2(building) : getTopicTitle2?.(building); const afterTitleStop = getSummaryStopDecision(building, operationContext); if (afterTitleStop) throw afterTitleStop; const topicContent = await buildTopicContentContext( building, startFloor, endFloor, currentApi ); const afterContentStop = getSummaryStopDecision(building, operationContext); if (afterContentStop) throw afterContentStop; if (!topicContent?.contentText) { throw new Error("未能获取到帖子内容"); } const imageContext = await prepareTopicImagesForCurrentApi(topicContent, currentApi); const imageInstruction = imageContext.imageInputs?.length ? `本次请求附带了 ${imageContext.imageInputs.length} 张话题图片,请结合图片视觉内容和正文中的 [图片#] 占位符理解。` : ""; const prompt = [ "请基于以上要求,对下面的话题及其讨论回复进行总结。", topicTitle ? `话题标题:${topicTitle}` : `话题ID:${building}`, imageInstruction, "原文如下:", topicContent.contentText ].filter(Boolean).join("\n"); const summary = await summarizeSomething2(prompt, { currentApi, imageInputs: imageContext.imageInputs, images: topicContent.images, skippedImages: [ ...topicContent.skippedImages || [], ...imageContext.skippedImages || [] ], signal: operationContext?.controller?.signal || null }); const afterSummaryStop = getSummaryStopDecision(building, operationContext); if (afterSummaryStop) throw afterSummaryStop; if (!summary) { throw new Error("API返回了空的总结内容"); } if (retryAttempt > 0) { setTopicRetryVisualState(building, false); } return summary; } catch (error) { if (error?.name === "AbortError") { throw createSummaryStopError("SUMMARY_CANCELLED", "总结已取消"); } if (isSummaryStopError(error) || isNonRetryableSummaryError(error)) { throw error; } const currentApiConfig = currentApi; const retryCount = normalizeAutoRetryCount2(currentApiConfig && currentApiConfig.retryCount, state2.autoRetryCount); const retryInterval = normalizeAutoRetryInterval2(currentApiConfig && currentApiConfig.retryInterval, state2.autoRetryInterval); state2.autoRetryCount = retryCount; state2.autoRetryInterval = retryInterval; if (retryAttempt < retryCount) { const beforeRetryStop = getSummaryStopDecision(building, operationContext); if (beforeRetryStop) throw beforeRetryStop; const operation = getActiveSummaryOperation(building); if (operation?.aborted || operation?.dismissed) { throw createSummaryStopError("SUMMARY_CANCELLED", "总结已取消"); } setTopicRetryVisualState(building, true); const retryMessage = `总结失败,正在尝试第 ${retryAttempt + 2}/${retryCount + 1} 次重试...`; const toast = operationContext?.toast || operation?.toast; if (!operation?.dismissed) { if (toast && typeof toast.changeType === "function") { toast.changeType("warning", 0); toast.update(retryMessage); } else { createToast2(retryMessage, "warning", 0, building); } } await new Promise((resolve) => { const timer = setTimeout(resolve, retryInterval * 1e3); const signal = operationContext?.controller?.signal || operation?.controller?.signal; if (!signal) return; if (signal.aborted) { clearTimeout(timer); resolve(); return; } signal.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true }); }); const afterWaitStop = getSummaryStopDecision(building, operationContext); if (afterWaitStop) throw afterWaitStop; return main(building, startFloor, endFloor, retryAttempt + 1, currentApi, operationContext); } setTopicRetryVisualState(building, false); const finalError = new Error(`总结失败,已达到最大重试次数 (${retryCount + 1})。错误: ${error.message}`); finalError.cause = error; throw finalError; } } async function buildTopicQuestionContext(topicId, operationApi = null) { const normalizedTopicId = normalizeTopicId4(topicId); if (!normalizedTopicId) { throw new Error("Missing topicId"); } const currentApi = operationApi || { ...typeof getCurrentApiConfiguration2 === "function" ? getCurrentApiConfiguration2() : {} }; const topicTitle = typeof ensureTopicTitle2 === "function" ? await ensureTopicTitle2(normalizedTopicId) : getTopicTitle2?.(normalizedTopicId); const { startFloor, endFloor } = await getFullFloorRangeForTopic( normalizedTopicId, DEFAULT_FULL_FLOOR_END, currentApi ); const topicContent = await buildTopicContentContext( normalizedTopicId, startFloor, endFloor, currentApi ); if (!topicContent?.contentText) { throw new Error("未能获取到帖子内容"); } const imageContext = await prepareTopicImagesForCurrentApi(topicContent, currentApi); return { topicId: normalizedTopicId, title: topicTitle || getTopicTitle2?.(normalizedTopicId) || "", contentText: topicContent.contentText, images: topicContent.images, skippedImages: [ ...topicContent.skippedImages || [], ...imageContext.skippedImages || [] ], imageInputs: imageContext.imageInputs }; } async function handleFormSubmit2(event) { if (event && typeof event.preventDefault === "function") { event.preventDefault(); } const resultDiv = document.getElementById("summary-result"); const historyDiv = document.getElementById("summary-history"); const submitButton = document.getElementById("submit-button"); const topicIdInput = document.getElementById("building"); if (!resultDiv || !historyDiv || !submitButton || !topicIdInput) { console.error("Sidebar form elements not found!"); return; } const topicId = normalizeTopicId4(topicIdInput.value); if (!topicId) { createToast2("无法获取当前主题ID!", "error"); return; } if (state2.summarizingTopics.has(topicId)) { createToast2("该话题正在总结中,请稍候...", "info", null, topicId); showSummarizingInterface(resultDiv, topicId); historyDiv.style.display = "none"; updateSidebarSubmitButtonState2(topicId); return; } const safeGetTopicHistory = () => { try { const history = getSummaryHistory2(topicId); return Array.isArray(history) ? history : []; } catch (error) { console.warn(`Failed to read local history for topic ${topicId}:`, error); return []; } }; let localHistory = safeGetTopicHistory(); const hasSummaryState = localHistory.length > 0 || isTopicMarkedSummarized2(topicId); const drivePullAllowed = state2.driveSummarySettings?.enabled && (typeof hasDriveSummaryCredentials2 !== "function" || hasDriveSummaryCredentials2()); const hasManualFallbackArmed = pendingManualAfterDriveFailTopics2.has(topicId); if (!localHistory.length && hasSummaryState && drivePullAllowed && !hasManualFallbackArmed) { const pullResult = await ensureSidebarTopicHistoryFromDrive(topicId, { force: true, probeOnly: false }); localHistory = safeGetTopicHistory(); if (pullResult?.ok && localHistory.length > 0) { pendingManualAfterDriveFailTopics2.delete(topicId); if (typeof historyDiv.loadHistory === "function") { historyDiv.loadHistory(topicId); } autoShowHistoryIfExists2(topicId); updateSidebarSubmitButtonState2(topicId); return; } if (pullResult?.skipped && pullResult?.reason === "pull-in-flight") { updateSidebarSubmitButtonState2(topicId); return; } updateSidebarSubmitButtonState2(topicId); } if (hasManualFallbackArmed) { pendingManualAfterDriveFailTopics2.delete(topicId); } const summarizingToastEarly = createSummarizingToast2(topicId); const started = beginSummaryOperation(topicId, { mode: "manual", toast: summarizingToastEarly }); if (started.skipped) { summarizingToastEarly.clear?.(); createToast2("该话题正在总结中,请稍候...", "info", null, topicId); showSummarizingInterface(resultDiv, topicId); historyDiv.style.display = "none"; updateSidebarSubmitButtonState2(topicId); return; } resultDiv.innerHTML = ""; const contentWrapper = document.createElement("div"); contentWrapper.className = "summary-content-wrapper"; contentWrapper.style.width = "100%"; contentWrapper.style.position = "relative"; const loadingIndicator = document.createElement("div"); loadingIndicator.className = "loading-indicator"; loadingIndicator.textContent = "正在生成总结,请稍候..."; contentWrapper.appendChild(loadingIndicator); resultDiv.appendChild(contentWrapper); resultDiv.style.display = "flex"; historyDiv.style.display = "none"; const historyButton = document.getElementById("history-button"); if (historyButton) historyButton.classList.remove("active"); const summarizingToast = summarizingToastEarly; const requestContext = captureCurrentSummaryRequestContext2(); const operationApi = { ...typeof getCurrentApiConfiguration2 === "function" ? getCurrentApiConfiguration2() : {} }; try { let startFloor; let endFloor; const postIds = await fetchTopicPostIds(topicId, operationApi); if (!postIds || postIds.length === 0) { throw new Error("未能获取楼层信息"); } ({ startFloor, endFloor } = getFullFloorRangeFromPostIds(postIds)); if (Number.isNaN(startFloor) || Number.isNaN(endFloor)) { throw new Error("无法获取有效的楼层范围!"); } if (endFloor < startFloor) { throw new Error("结束楼层不得小于起始楼层!"); } const maxFloorRange = 1e4; if (endFloor - startFloor + 1 > maxFloorRange) { throw new Error(`楼层范围不能超过${maxFloorRange}楼!`); } const summary = await main(topicId, startFloor, endFloor, 0, operationApi, { generation: started.generation, mode: "manual", toast: summarizingToast, controller: started.controller }); if (!summary) { throw new Error("生成总结失败 (空响应)"); } displayResult(summary, requestContext); saveSummaryHistory2(topicId, summary, requestContext.model, requestContext); loadHistoryForCurrentTopic2(); autoShowHistoryIfExists2(topicId); loadHistoryForCurrentTopic2(); summarizingToast.changeType("success"); summarizingToast.update("总结生成成功!"); if (submitButton) { submitButton.classList.remove("summarizing"); submitButton.classList.add("summarized"); submitButton.textContent = "✅ 已总结"; setTimeout(() => { updateSidebarSubmitButtonState2(topicId); }, 3e3); } } catch (error) { if (isSummaryStopError(error)) { if (error.code === "SUMMARY_HAS_EXISTING") { summarizingToast.changeType("success", 2400); summarizingToast.update("已有总结,已停止重试"); loadHistoryForCurrentTopic2(); autoShowHistoryIfExists2(topicId); } else { summarizingToast.clear?.(); } } else { console.error("Summary failed:", error); const message = error?.message || String(error || "未知错误"); displayError(`发生错误: ${message}`); summarizingToast.changeType("error"); summarizingToast.update(`总结失败: ${message}`); } } finally { finishSummaryOperation(topicId, started.generation); if (submitButton && !submitButton.classList.contains("summarized")) { updateSidebarSubmitButtonState2(topicId); } } } async function attemptAutoSummarize2(topicId) { if (!state2.newTopicAutoSummarize) return; const normalizedTopicId = normalizeTopicId4(topicId); if (!normalizedTopicId) return; if (!isCurrentPageTopic(normalizedTopicId)) return; let { hasLocalHistory, hasSummaryState } = getTopicSummaryState(normalizedTopicId); if (hasLocalHistory) { return; } if (hasSummaryState && canAttemptDrivePull()) { try { await ensureSidebarTopicHistoryFromDrive(normalizedTopicId, { force: true, probeOnly: false }); } catch (_error) { } if (getTopicSummaryState(normalizedTopicId).hasLocalHistory) { autoShowHistoryIfExists2(normalizedTopicId); updateSidebarSubmitButtonState2(normalizedTopicId); updateTopicSummaryButtons?.(normalizedTopicId); return; } } if (!isCurrentPageTopic(normalizedTopicId)) return; if (getTopicSummaryState(normalizedTopicId).hasLocalHistory) return; if (state2.summarizingTopics.has(normalizedTopicId)) { return; } getTopicTitle2?.(normalizedTopicId); const summarizingToast = createSummarizingToast2(normalizedTopicId); const requestContext = captureCurrentSummaryRequestContext2(); const operationApi = { ...typeof getCurrentApiConfiguration2 === "function" ? getCurrentApiConfiguration2() : {} }; const started = beginSummaryOperation(normalizedTopicId, { mode: "auto", toast: summarizingToast }); if (started.skipped) { summarizingToast.clear?.(); return; } if (getSummaryStopDecision(normalizedTopicId, { generation: started.generation, mode: "auto", stopIfExistingHistory: true })) { summarizingToast.clear?.(); finishSummaryOperation(normalizedTopicId, started.generation); return; } try { const { startFloor, endFloor } = await getFullFloorRangeForTopic( normalizedTopicId, DEFAULT_FULL_FLOOR_END, operationApi ); const summary = await main(normalizedTopicId, startFloor, endFloor, 0, operationApi, { generation: started.generation, mode: "auto", toast: summarizingToast, controller: started.controller, stopIfExistingHistory: true }); summarizingToast.changeType("success"); summarizingToast.update("话题自动总结完成!"); saveSummaryHistory2(normalizedTopicId, summary, requestContext.model, requestContext); pendingManualAfterDriveFailTopics2.delete(normalizedTopicId); loadHistoryForCurrentTopic2(); autoShowHistoryIfExists2(normalizedTopicId); if (document.getElementById("building")?.value === normalizedTopicId) { loadHistoryForCurrentTopic2(); } } catch (error) { if (isSummaryStopError(error)) { if (error.code === "SUMMARY_HAS_EXISTING") { summarizingToast.changeType("success", 2400); summarizingToast.update("已有总结,已停止重试"); loadHistoryForCurrentTopic2(); autoShowHistoryIfExists2(normalizedTopicId); updateTopicSummaryButtons?.(normalizedTopicId); } else { summarizingToast.clear?.(); } } else { console.error(`Auto summarize error for topic ${normalizedTopicId}:`, error); summarizingToast.changeType("error"); summarizingToast.update(`自动总结失败: ${error.message}`); if (document.getElementById("building")?.value === normalizedTopicId) { displayError(`自动总结失败: ${error.message}`); } } } finally { finishSummaryOperation(normalizedTopicId, started.generation); } } async function ensureSidebarTopicHistoryFromDrive(topicId, { force = false, probeOnly = false } = {}) { const normalizedTopicId = normalizeTopicId4(topicId); if (!normalizedTopicId) return { ok: false, skipped: true, reason: "invalid-topic-id" }; if (typeof pullTopicHistoryFromDrive2 !== "function") { return { ok: false, skipped: true, reason: "drive-api-unavailable" }; } if (!canAttemptDrivePull()) { return { ok: false, skipped: true, reason: state2.driveSummarySettings?.enabled ? "drive-credentials-missing" : "drive-disabled" }; } const localHistory = getSummaryHistory2(normalizedTopicId); const hasLocalHistory = localHistory.length > 0; if (hasLocalHistory && !force) { return { ok: true, skipped: true, reason: "local-history-exists" }; } if (probeOnly) { if (!state2.driveSummarySettings?.enabled) { return { ok: false, skipped: true, reason: "drive-disabled" }; } if (typeof hasDriveSummaryCredentials2 === "function" && !hasDriveSummaryCredentials2()) { return { ok: false, skipped: true, reason: "drive-credentials-missing" }; } } if (sidebarDriveHistoryPullingTopics.has(normalizedTopicId)) { return { ok: false, skipped: true, reason: "pull-in-flight" }; } sidebarDriveHistoryPullingTopics.add(normalizedTopicId); const resultDiv = document.getElementById("summary-result"); const historyDiv = document.getElementById("summary-history"); const historyButton = document.getElementById("history-button"); const submitButton = document.getElementById("submit-button"); const shouldShowPullUi = !probeOnly && !hasLocalHistory; const shouldToastPullResult = !probeOnly && !hasLocalHistory; if (shouldShowPullUi && resultDiv && historyDiv) { const loadingHtml = '