// ==UserScript== // @name 知到智慧树掌握度答题-AI自动答题脚本(Zhihuishu AI Auto-Answering) // @namespace https://github.com/Cooanyh/zhihuishu-zhangwodu // @homepageURL https://github.com/Cooanyh/zhihuishu-zhangwodu // @supportURL https://github.com/Cooanyh/zhihuishu-zhangwodu/issues // @version 2.3.0 // @description 全自动完成智慧树掌握度练习。兼容智慧树全子域掌握度页面,中性极简UI,支持硅基流动等多AI服务商与动态获取模型、多源联网搜索(默认免费)、OCS冲突检测与排除引导、后台续跑及中断弹窗提醒。 // @author Coren // @match https://*.zhihuishu.com/* // @exclude https://passport.zhihuishu.com/* // @exclude https://login.zhihuishu.com/* // @connect api.coren.xin // @connect open.bigmodel.cn // @connect api.deepseek.com // @connect api.siliconflow.cn // @connect api.openai.com // @connect api.anthropic.com // @connect generativelanguage.googleapis.com // @connect gist.githubusercontent.com // @connect cn.bing.com // @connect m.so.com // @connect baike.baidu.com // @connect api.bochaai.com // @connect api.tavily.com // @connect google.serper.dev // @connect * // @grant GM_addStyle // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @grant GM_notification // @grant unsafeWindow // @license CC BY-NC-SA 4.0 // @license https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh // ==/UserScript== (function () { 'use strict'; // --- 0. 单例防重复注入 --- if (window.__ZHS_AI_HELPER_LOADED__) return; window.__ZHS_AI_HELPER_LOADED__ = true; // --- 1. 安全存储与通用工具 --- const MAX_LOG_ENTRIES = 150; const MAX_CACHE_ENTRIES = 200; const SEARCH_KEY_PROVIDERS = new Set(['bocha', 'tavily', 'serper']); let originalTitle = document.title; function getStoredJson(key, fallback) { try { const raw = GM_getValue(key, ''); if (!raw) return fallback; const parsed = JSON.parse(raw); return parsed && typeof parsed === 'object' ? parsed : fallback; } catch (e) { return fallback; } } function saveStoredJson(key, value) { try { GM_setValue(key, JSON.stringify(value)); } catch (e) { console.warn('[AI脚本] 保存配置失败:', e); } } function normalizeOpenAiChatUrl(inputUrl, defaultUrl) { const raw = String(inputUrl || '').trim(); if (!raw) return defaultUrl; const clean = raw.replace(/\/+$/, ''); if (/\/chat\/completions$/i.test(clean)) return clean; if (/\/v\d+$/i.test(clean)) return `${clean}/chat/completions`; return clean; } function deriveModelsEndpoint(chatOrBaseUrl, defaultChatUrl) { const raw = String(chatOrBaseUrl || defaultChatUrl || '').trim().replace(/\/+$/, ''); if (/\/chat\/completions$/i.test(raw)) { return raw.replace(/\/chat\/completions$/i, '/models'); } if (/\/models$/i.test(raw)) return raw; return `${raw}/models`; } function normalizeAnthropicMessagesUrl(inputUrl, defaultUrl) { const raw = String(inputUrl || '').trim(); if (!raw) return defaultUrl; const clean = raw.replace(/\/+$/, ''); if (/\/messages$/i.test(clean)) return clean; if (/\/v\d+$/i.test(clean)) return `${clean}/messages`; return `${clean}/v1/messages`; } function deriveAnthropicModelsUrl(messagesOrBaseUrl, defaultUrl) { const raw = String(messagesOrBaseUrl || defaultUrl || '').trim().replace(/\/+$/, ''); if (/\/messages$/i.test(raw)) return raw.replace(/\/messages$/i, '/models'); if (/\/models$/i.test(raw)) return raw; if (/\/v\d+$/i.test(raw)) return `${raw}/models`; return `${raw}/v1/models`; } // --- 2. AI 服务商配置中心(不预填模型,支持按 Key 拉取) --- const API_PROVIDERS = { deepseek: { name: 'DeepSeek', defaultUrl: 'https://api.deepseek.com/v1/chat/completions', supportsNativeSearch: true, supportsModelFetch: true, buildUrl: (baseUrl) => normalizeOpenAiChatUrl(baseUrl, 'https://api.deepseek.com/v1/chat/completions'), buildModelsUrl: (baseUrl) => deriveModelsEndpoint(baseUrl, 'https://api.deepseek.com/v1/chat/completions'), buildHeaders: (key) => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${key}` }), buildPayload: (messages, model) => { const payload = { model, messages, max_tokens: 256, temperature: 0 }; if (/(?:v4|flash|reasoner)/i.test(model)) payload.thinking = { type: 'disabled' }; return payload; }, parseResponse: (data) => { const msg = data?.choices?.[0]?.message; return msg?.content || msg?.reasoning_content || null; } }, siliconflow: { name: '硅基流动 (SiliconFlow)', defaultUrl: 'https://api.siliconflow.cn/v1/chat/completions', supportsNativeSearch: false, supportsModelFetch: true, buildUrl: (baseUrl) => normalizeOpenAiChatUrl(baseUrl, 'https://api.siliconflow.cn/v1/chat/completions'), buildModelsUrl: (baseUrl) => deriveModelsEndpoint(baseUrl, 'https://api.siliconflow.cn/v1/chat/completions'), buildHeaders: (key) => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${key}` }), buildPayload: (messages, model) => { const payload = { model, messages, max_tokens: 256, temperature: 0 }; if (/(?:qwen3|thinking)/i.test(model)) payload.enable_thinking = false; return payload; }, parseResponse: (data) => { const msg = data?.choices?.[0]?.message; return msg?.content || msg?.reasoning_content || null; } }, zhipu: { name: '智谱 GLM (Zhipu)', defaultUrl: 'https://open.bigmodel.cn/api/paas/v4/chat/completions', supportsNativeSearch: true, supportsModelFetch: true, buildUrl: (baseUrl) => normalizeOpenAiChatUrl(baseUrl, 'https://open.bigmodel.cn/api/paas/v4/chat/completions'), buildModelsUrl: (baseUrl) => deriveModelsEndpoint(baseUrl, 'https://open.bigmodel.cn/api/paas/v4/chat/completions'), buildHeaders: (key) => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${key}` }), buildPayload: (messages, model, opts = {}) => { const payload = { model, messages, max_tokens: 256, temperature: 0 }; if (/(?:4\.5|flash|glm-z|thinking)/i.test(model)) { payload.thinking = { type: 'disabled' }; } if (opts.nativeSearch) { payload.tools = [{ type: 'web_search', web_search: { enable: true, search_result: true } }]; } return payload; }, parseResponse: (data) => { const msg = data?.choices?.[0]?.message; return msg?.content || msg?.reasoning_content || null; } }, openai: { name: 'OpenAI 兼容 (OpenAI / 中转站)', defaultUrl: 'https://api.openai.com/v1/chat/completions', supportsNativeSearch: false, supportsModelFetch: true, buildUrl: (baseUrl) => normalizeOpenAiChatUrl(baseUrl, 'https://api.openai.com/v1/chat/completions'), buildModelsUrl: (baseUrl) => deriveModelsEndpoint(baseUrl, 'https://api.openai.com/v1/chat/completions'), buildHeaders: (key) => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${key}` }), buildPayload: (messages, model) => ({ model, messages, max_tokens: 256, temperature: 0 }), parseResponse: (data) => { const msg = data?.choices?.[0]?.message; return msg?.content || msg?.reasoning_content || null; } }, anthropic: { name: 'Anthropic 兼容 (Claude / 中转站)', defaultUrl: 'https://api.anthropic.com/v1/messages', supportsNativeSearch: false, supportsModelFetch: true, buildUrl: (baseUrl) => normalizeAnthropicMessagesUrl(baseUrl, 'https://api.anthropic.com/v1/messages'), buildModelsUrl: (baseUrl) => deriveAnthropicModelsUrl(baseUrl, 'https://api.anthropic.com/v1/messages'), buildHeaders: (key) => ({ 'Content-Type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' }), buildPayload: (messages, model) => { const sysMsgs = messages.filter(m => m.role === 'system').map(m => m.content).join('\n'); const nonSys = messages.filter(m => m.role !== 'system').map(m => ({ role: m.role === 'assistant' ? 'assistant' : 'user', content: m.content })); const payload = { model, max_tokens: 256, temperature: 0, messages: nonSys }; if (sysMsgs) payload.system = sysMsgs; return payload; }, parseResponse: (data) => { const blocks = Array.isArray(data?.content) ? data.content : []; return blocks.filter(b => b?.type === 'text' && b.text).map(b => b.text).join('\n') || null; } }, gemini: { name: 'Google (Gemini)', defaultUrl: 'https://generativelanguage.googleapis.com/v1beta', supportsNativeSearch: true, supportsModelFetch: true, buildUrl: (baseUrl, model) => { const base = String(baseUrl || 'https://generativelanguage.googleapis.com/v1beta').trim().replace(/\/+$/, ''); return `${base}/models/${encodeURIComponent(model)}:generateContent`; }, buildModelsUrl: (baseUrl) => { const base = String(baseUrl || 'https://generativelanguage.googleapis.com/v1beta').trim().replace(/\/+$/, ''); return `${base}/models`; }, // Key 放在请求头,不拼在 URL 查询串 buildHeaders: (key) => ({ 'Content-Type': 'application/json', 'x-goog-api-key': key }), buildPayload: (messages, model, opts = {}) => { const sysText = messages.filter(m => m.role === 'system').map(m => m.content).join('\n'); const chatMsgs = messages.filter(m => m.role !== 'system'); const payload = { contents: chatMsgs.map(msg => ({ role: msg.role === 'assistant' ? 'model' : 'user', parts: [{ text: msg.content }] })), generationConfig: { maxOutputTokens: 256, temperature: 0 } }; if (/gemini-2\.5-flash/i.test(model)) { payload.generationConfig.thinkingConfig = { thinkingBudget: 0 }; } else if (/(?:gemini-2\.5-pro|thinking)/i.test(model)) { payload.generationConfig.maxOutputTokens = Math.max(payload.generationConfig.maxOutputTokens, 1024); } if (sysText) { payload.systemInstruction = { parts: [{ text: sysText }] }; } if (opts.nativeSearch) { payload.tools = [{ google_search: {} }]; } return payload; }, parseResponse: (data) => { const parts = Array.isArray(data?.candidates?.[0]?.content?.parts) ? data.candidates[0].content.parts : []; const textParts = parts.filter(p => !p?.thought && typeof p?.text === 'string' && p.text.length > 0).map(p => p.text); if (textParts.length > 0) return textParts.join('\n'); const fallbackParts = parts.filter(p => typeof p?.text === 'string' && p.text.length > 0).map(p => p.text); return fallbackParts.length > 0 ? fallbackParts.join('\n') : null; } } }; const SEARCH_HINTS = { local: '无需任何 Key,自动用 Bing / 360 / 百度百科查资料再交给 AI 判断。', native: '直接开启当前 AI 服务商自带联网(仅 DeepSeek / 智谱 / Gemini 支持,其余自动转免费搜题)。', bocha: '使用博查搜索接口,需填博查 Key,中文课程题检索准确度高。', tavily: '使用 Tavily 搜索接口,需填 Tavily Key,适合英文与综合检索。', serper: '使用 Serper (Google) 接口,需填 Serper Key。', off: '不进行任何联网搜索,完全依靠 AI 自身知识作答,响应最快。' }; const OCS_HINTS = { yield: '检测到 OCS 处于活跃状态时自动暂停提醒;由于脚本沙箱隔离无法关闭 OCS 后台搜题,推荐点下方按钮复制排除规则,在脚本管理器中对 OCS 排除掌握度页面。', off: '不做检测(已在脚本管理器中排除 OCS 或未安装时可选)。' }; const OCS_EXCLUDE_RULES = [ 'https://*.zhihuishu.com/study/mastery*', 'https://*.zhihuishu.com/study/analysis*', 'https://*.zhihuishu.com/exam*', 'https://*.zhihuishu.com/pointOfMastery*' ].join('\n'); const STOP_HINTS = { gray: '只刷尚未掌握的「遗漏点」,跳过「薄弱点」「一般」「较好」「免考」。', 'non-red': '同时刷「遗漏点」与「薄弱点」,已掌握的知识点自动跳过。' }; // --- 3. 中性大厂风 Shadow DOM UI(零蓝紫色) --- const hostEl = document.createElement('div'); hostEl.id = 'zhs-ai-helper-host'; document.body.appendChild(hostEl); const shadow = hostEl.attachShadow({ mode: 'open' }); const styleSheet = ` :host { all: initial; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Microsoft YaHei', sans-serif; color: #18181b; } * { box-sizing: border-box; } #panel-toggle { position: fixed; height: 38px; padding: 0 14px; border-radius: 999px; border: 1px solid #d4d4d8; background: rgba(255, 255, 255, 0.96); backdrop-filter: blur(10px); color: #18181b; font-size: 13px; font-weight: 600; cursor: grab; z-index: 2147483000; display: inline-flex; align-items: center; gap: 7px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12); user-select: none; touch-action: none; transition: box-shadow 0.15s ease, border-color 0.15s ease; } #panel-toggle.dragging, #ai-panel.dragging { transition: none !important; backdrop-filter: none !important; will-change: transform; cursor: grabbing !important; } #panel-toggle:hover { box-shadow: 0 6px 20px rgba(0, 0, 0, 0.16); } #panel-toggle.glow-on { animation: zhs-halo-pulse 2.4s ease-in-out infinite; } #panel-toggle.glow-on.dragging { animation: none; } #panel-toggle.running { border-color: #10b981; color: #065f46; } #panel-toggle.running.glow-on { animation: zhs-halo-pulse-running 1.9s ease-in-out infinite; } @keyframes zhs-halo-pulse { 0%, 100% { box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12), 0 0 0 0 rgba(16, 185, 129, 0.36); } 50% { box-shadow: 0 6px 20px rgba(0, 0, 0, 0.14), 0 0 14px 6px rgba(16, 185, 129, 0.28), 0 0 0 9px rgba(16, 185, 129, 0); } } @keyframes zhs-halo-pulse-running { 0%, 100% { box-shadow: 0 4px 14px rgba(16, 185, 129, 0.18), 0 0 0 0 rgba(16, 185, 129, 0.5); } 50% { box-shadow: 0 6px 22px rgba(16, 185, 129, 0.25), 0 0 18px 8px rgba(16, 185, 129, 0.35), 0 0 0 11px rgba(16, 185, 129, 0); } } .toggle-dot { width: 8px; height: 8px; border-radius: 50%; background: #71717a; flex-shrink: 0; } #panel-toggle.running .toggle-dot { background: #10b981; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.22); } #ai-panel { position: fixed; width: 356px; height: min(520px, calc(100vh - 32px)); background: rgba(255, 255, 255, 0.98); backdrop-filter: blur(14px); border: 1px solid #e4e4e7; border-radius: 12px; box-shadow: 0 18px 44px rgba(0, 0, 0, 0.14); z-index: 2147482999; display: flex; flex-direction: column; overflow: hidden; opacity: 0; pointer-events: none; transform: translateY(-6px) scale(0.98); transition: opacity 0.16s ease, transform 0.16s ease; } #ai-panel.show { opacity: 1; pointer-events: auto; transform: translateY(0) scale(1); } #panel-header { padding: 11px 14px; background: #ffffff; border-bottom: 1px solid #f4f4f5; display: flex; align-items: center; justify-content: space-between; cursor: grab; user-select: none; touch-action: none; flex-shrink: 0; } #panel-header:active { cursor: grabbing; } .header-left { display: flex; align-items: center; gap: 8px; } .brand-badge { width: 24px; height: 24px; border-radius: 6px; background: #18181b; color: #ffffff; font-size: 11px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; } #panel-title { font-size: 13.5px; font-weight: 700; color: #18181b; } #panel-version { font-size: 10.5px; color: #52525b; background: #f4f4f5; padding: 1px 7px; border-radius: 999px; font-weight: 600; } #panel-close { background: #f4f4f5; border: none; color: #52525b; width: 26px; height: 26px; border-radius: 6px; cursor: pointer; font-size: 16px; line-height: 26px; text-align: center; padding: 0; } #panel-close:hover { background: #e4e4e7; color: #18181b; } .tab-nav { display: flex; padding: 0 12px; gap: 4px; background: #ffffff; border-bottom: 1px solid #f4f4f5; flex-shrink: 0; } .tab-btn { flex: 1; padding: 8px 0; border: none; background: transparent; color: #71717a; font-size: 12.5px; font-weight: 600; cursor: pointer; border-bottom: 2px solid transparent; transition: color 0.15s ease, border-color 0.15s ease; } .tab-btn.active { color: #18181b; border-bottom-color: #18181b; } .tab-panel { padding: 12px 14px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; flex: 1; background: #fafafa; } .status-card { padding: 9px 11px; background: #ffffff; border: 1px solid #e4e4e7; border-radius: 9px; display: flex; flex-direction: column; gap: 6px; } .status-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; } .status-pill { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: 999px; background: #f4f4f5; color: #52525b; font-size: 11px; font-weight: 600; } .status-pill::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: currentColor; } .status-pill.running { background: #d1fae5; color: #065f46; } .status-meta { display: flex; align-items: center; justify-content: space-between; font-size: 11px; color: #71717a; } .seg-control { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; padding: 3px; background: #e4e4e7; border-radius: 8px; } .seg-btn { border: none; background: transparent; color: #52525b; font-size: 12px; font-weight: 600; padding: 6px 4px; border-radius: 6px; cursor: pointer; } .seg-btn.active { background: #ffffff; color: #18181b; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); } .config-tip { display: flex; align-items: center; justify-content: space-between; padding: 7px 10px; background: #fef3c7; color: #92400e; border: 1px solid #fde68a; border-radius: 8px; font-size: 11.5px; } .link-btn { background: none; border: none; color: #18181b; font-weight: 700; font-size: 11.5px; cursor: pointer; padding: 0; text-decoration: underline; } .toggle-row { display: flex; align-items: center; justify-content: space-between; padding: 8px 10px; background: #ffffff; border: 1px solid #e4e4e7; border-radius: 8px; cursor: pointer; font-size: 12.5px; color: #27272a; font-weight: 500; } .switch { position: relative; display: inline-block; width: 34px; height: 19px; flex-shrink: 0; } .switch input { opacity: 0; width: 0; height: 0; position: absolute; } .slider { position: absolute; inset: 0; background: #d4d4d8; border-radius: 999px; transition: background 0.18s ease; } .slider::before { content: ''; position: absolute; width: 15px; height: 15px; left: 2px; top: 2px; background: #ffffff; border-radius: 50%; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.18); transition: transform 0.18s ease; } .switch input:checked + .slider { background: #18181b; } .switch input:checked + .slider::before { transform: translateX(15px); } .section-card { padding: 10px 11px; border: 1px solid #e4e4e7; border-radius: 9px; background: #ffffff; display: flex; flex-direction: column; gap: 8px; } .section-title { font-size: 12px; font-weight: 700; color: #18181b; display: flex; align-items: center; justify-content: space-between; } .input-group { display: flex; flex-direction: column; gap: 4px; } .input-group label { font-size: 11.5px; color: #52525b; font-weight: 600; } .input-row { display: flex; gap: 6px; align-items: center; } .input-group input[type="text"], .input-group input[type="password"], .input-group select { width: 100%; padding: 7px 9px; border: 1px solid #e4e4e7; border-radius: 7px; font-size: 12px; color: #18181b; background: #f4f4f5; outline: none; } .input-group input:focus, .input-group select:focus { background: #ffffff; border-color: #18181b; } .btn-row { display: flex; gap: 7px; } .btn { padding: 8px 11px; border: none; border-radius: 8px; cursor: pointer; font-size: 12.5px; font-weight: 600; color: #ffffff; transition: opacity 0.15s ease; } .btn:hover { opacity: 0.92; } .btn:disabled { opacity: 0.55; cursor: not-allowed; } .btn-dark { background: #18181b; } .btn-success { background: #10b981; } .btn-danger { background: #dc2626; } .btn-soft { background: #e4e4e7; color: #27272a; } .btn-xs { padding: 4px 9px; font-size: 11px; border-radius: 6px; background: #f4f4f5; color: #18181b; border: 1px solid #e4e4e7; cursor: pointer; font-weight: 600; white-space: nowrap; } .btn-xs:hover { background: #e4e4e7; } .tab-panel::-webkit-scrollbar, #status-log::-webkit-scrollbar { width: 5px; } .tab-panel::-webkit-scrollbar-thumb, #status-log::-webkit-scrollbar-thumb { background: #d4d4d8; border-radius: 999px; } .log-box-wrap { display: flex; flex-direction: column; gap: 5px; flex: 1; min-height: 92px; } .log-header { display: flex; justify-content: space-between; align-items: center; font-size: 11px; color: #71717a; font-weight: 600; } #clear-log-btn { background: none; border: none; color: #52525b; cursor: pointer; font-size: 11px; padding: 0; } #clear-log-btn:hover { color: #18181b; } #status-log { padding: 8px 9px; background: #ffffff; border: 1px solid #e4e4e7; border-radius: 8px; flex: 1; min-height: 80px; overflow-y: auto; font-size: 11px; line-height: 1.5; color: #3f3f46; word-break: break-all; } .help-list { margin: 0; padding-left: 16px; font-size: 11.5px; line-height: 1.55; color: #3f3f46; } .help-list li { margin-bottom: 4px; } .help-link { color: #18181b; font-weight: 600; text-decoration: underline; font-size: 11.5px; } .hint-line { font-size: 11px; color: #71717a; line-height: 1.4; } #interrupt-banner { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 2147483001; max-width: 440px; width: calc(100vw - 32px); background: #fffbeb; border: 1px solid #f59e0b; border-left: 4px solid #d97706; border-radius: 10px; padding: 11px 13px; box-shadow: 0 12px 28px rgba(0, 0, 0, 0.16); display: flex; flex-direction: column; gap: 8px; color: #78350f; font-size: 12px; } .banner-title { font-weight: 700; font-size: 13px; color: #92400e; } .banner-actions { display: flex; gap: 8px; justify-content: flex-end; } .inline-feedback { padding: 6px 8px; border-radius: 6px; font-size: 11px; line-height: 1.4; word-break: break-word; } .inline-feedback.ok { background: #ecfdf5; color: #065f46; border: 1px solid #a7f3d0; } .inline-feedback.err { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; } .inline-feedback.info { background: #f4f4f5; color: #3f3f46; border: 1px solid #e4e4e7; } .hidden { display: none !important; } `; shadow.innerHTML = `
AI 掌握度助手 v2.3.0
待机中 OCS: 正常
免费 AI · 免费搜题增强 本轮已试: 0
运行日志
`; // --- 4. DOM 引用 & 状态初始化 --- const $ = (id) => shadow.getElementById(id); const panel = $('ai-panel'); const panelHeader = $('panel-header'); const toggleButton = $('panel-toggle'); const closeButton = $('panel-close'); const interruptBanner = $('interrupt-banner'); const interruptBannerMsg = $('interrupt-banner-msg'); const bannerOpenBtn = $('banner-open-btn'); const bannerCloseBtn = $('banner-close-btn'); const tabButtons = Array.from(shadow.querySelectorAll('.tab-btn')); const tabHome = $('tab-home'); const tabSettings = $('tab-settings'); const tabHelp = $('tab-help'); const modeSegButtons = Array.from(shadow.querySelectorAll('#mode-seg .seg-btn')); const configTip = $('config-tip'); const configTipText = $('config-tip-text'); const gotoSettingsBtn = $('goto-settings-btn'); const statusPill = $('status-pill'); const statusSummaryEl = $('status-summary'); const statusAttemptedEl = $('status-attempted'); const statusOcsEl = $('status-ocs'); const startButton = $('start-button'); const modeSelect = $('mode-select'); const searchModeSelect = $('search-mode'); const searchModeHintEl = $('search-mode-hint'); const searchKeyGroup = $('search-key-group'); const searchKeyLabel = $('search-key-label'); const searchApiKeyInput = $('search-api-key'); const ocsConflictSelect = $('ocs-conflict-mode'); const ocsModeHintEl = $('ocs-mode-hint'); const copyOcsExcludeBtn = $('copy-ocs-exclude-btn'); const ocsCopyResultEl = $('ocs-copy-result'); const stopConditionSelect = $('stop-condition'); const stopConditionHintEl = $('stop-condition-hint'); const capsuleGlowCheckbox = $('capsule-glow'); const providerSelect = $('provider-select'); const apiKeyInput = $('api-key'); const apiKeyLabel = $('api-key-label'); const apiUrlGroup = $('api-url-group'); const apiUrlInput = $('api-url'); const apiModelGroup = $('api-model-group'); const apiModelInput = $('api-model'); const fetchModelsBtn = $('fetch-models-btn'); const modelSelectList = $('model-select-list'); const statusLog = $('status-log'); const clearLogBtn = $('clear-log-btn'); const quizbankUrlInput = $('quizbank-url'); const fallbackAiCheckbox = $('fallback-ai'); const refreshQuizbankButton = $('refresh-quizbank'); const autoSubmitCheckbox = $('auto-submit'); const resetAttemptedButton = $('reset-attempted-button'); const testAiBtn = $('test-ai-btn'); const testSearchBtn = $('test-search-btn'); const aiTestResultEl = $('ai-test-result'); const searchTestResultEl = $('search-test-result'); const quizbankTestResultEl = $('quizbank-test-result'); function setInlineFeedback(el, type, text) { if (!el) return; if (!text) { el.className = 'inline-feedback hidden'; el.textContent = ''; return; } el.className = `inline-feedback ${type || 'info'}`; el.textContent = text; } let isPanelVisible = false; let currentCourseRunId = new URLSearchParams(window.location.search).get('recruitAndCourseId') || window.location.pathname; let hasExplicitCourseId = Boolean(new URLSearchParams(window.location.search).get('recruitAndCourseId')); const getAutoModeStorageKey = (runId = currentCourseRunId) => `zhihuishu_zhangwodu_auto_mode:${runId}`; const getAttemptedItemsStorageKey = (runId = currentCourseRunId) => `zhihuishu_zhangwodu_attempted_items:${runId}`; const getActiveItemStorageKey = (runId = currentCourseRunId) => `zhihuishu_zhangwodu_active_item:${runId}`; let autoMode = readSessionStorage(getAutoModeStorageKey()) === '1'; let attemptedMasteryItems = new Set(readSessionArray(getAttemptedItemsStorageKey()).filter(isCurrentMasteryItemKey)); let mainLoopTimer = null; let mainLoopRunning = false; let mainLoopPending = false; let runEpoch = 0; let quizBank = []; let quizBankExactMap = new Map(); const searchCache = new Map(); const answerCache = new Map(); // 仅按页面前台有效时间计时 let hiddenSince = document.hidden ? performance.now() : null; let accumulatedHiddenTime = 0; function setCacheWithLimit(cache, key, val) { if (cache.has(key)) cache.delete(key); cache.set(key, val); if (cache.size > MAX_CACHE_ENTRIES) { cache.delete(cache.keys().next().value); } } // --- 后台防冻结保活 + Web Worker 定时器(切后台不暂停) --- let bgAudioCtx = null; let bgTimerWorker = null; let bgWorkerDisabled = false; let bgTimerSeq = 1; const bgTimerCallbacks = new Map(); function fallbackBgTimersToNative() { const pending = Array.from(bgTimerCallbacks.values()); bgTimerCallbacks.clear(); const now = performance.now(); for (const entry of pending) { const remaining = Math.max(0, entry.fireAt - now); setTimeout(() => entry.callback(), remaining); } } function initBgTimerWorker() { if (bgWorkerDisabled) return null; if (bgTimerWorker) return bgTimerWorker; try { if (typeof Worker === 'function' && typeof Blob === 'function' && typeof URL?.createObjectURL === 'function') { const workerSrc = 'self.onmessage=function(e){var id=e.data.id;if(e.data.type==="set"){setTimeout(function(){self.postMessage(id);},e.data.delay);}};'; const blob = new Blob([workerSrc], { type: 'application/javascript' }); const worker = new Worker(URL.createObjectURL(blob)); worker.onmessage = (ev) => { const entry = bgTimerCallbacks.get(ev.data); if (entry) { bgTimerCallbacks.delete(ev.data); entry.callback(); } }; worker.onerror = () => { bgWorkerDisabled = true; bgTimerWorker = null; try { worker.terminate(); } catch (e) { /* ignore */ } fallbackBgTimersToNative(); }; bgTimerWorker = worker; } } catch (e) { bgWorkerDisabled = true; } return bgTimerWorker; } function startBackgroundKeepalive() { try { const Ctx = window.AudioContext || window.webkitAudioContext; if (!Ctx) return; if (!bgAudioCtx) { bgAudioCtx = new Ctx(); const osc = bgAudioCtx.createOscillator(); const gain = bgAudioCtx.createGain(); gain.gain.value = 0; osc.connect(gain); gain.connect(bgAudioCtx.destination); osc.start(); } if (bgAudioCtx.state === 'suspended') { bgAudioCtx.resume().catch(() => {}); } } catch (e) { /* ignore */ } } function stopBackgroundKeepalive() { try { if (bgAudioCtx && bgAudioCtx.state === 'running') { bgAudioCtx.suspend().catch(() => {}); } } catch (e) { /* ignore */ } } function getActiveTime() { return performance.now(); } function scheduleActiveTimeout(callback, delay) { const delayMs = Math.max(0, Number(delay) || 0); let cancelled = false; const worker = initBgTimerWorker(); if (worker) { const id = bgTimerSeq++; bgTimerCallbacks.set(id, { fireAt: performance.now() + delayMs, callback: () => { if (!cancelled) callback(); } }); try { worker.postMessage({ type: 'set', id, delay: delayMs }); return () => { cancelled = true; bgTimerCallbacks.delete(id); }; } catch (e) { bgTimerCallbacks.delete(id); bgWorkerDisabled = true; bgTimerWorker = null; try { worker.terminate(); } catch (err) { /* ignore */ } fallbackBgTimersToNative(); } } const tid = setTimeout(() => { if (!cancelled) callback(); }, delayMs); return () => { cancelled = true; clearTimeout(tid); }; } function waitForActiveTime(delay) { return new Promise(resolve => scheduleActiveTimeout(resolve, delay)); } document.addEventListener('visibilitychange', () => { if (document.hidden) { if (autoMode) log('页面已切至后台,防休眠保活运行中,继续自动答题...'); return; } if (document.title.startsWith('【需处理】')) { document.title = originalTitle; } if (autoMode) { startBackgroundKeepalive(); if (!mainLoopRunning && !mainLoopTimer) requestMainLoop(0); } }); // --- 5. 页面识别与胶囊显隐 --- function detectPageKind(urlStr = window.location.href, doc = document) { const url = String(urlStr || ''); if (/\/exam\b/i.test(url)) return 'exam'; if (/pointOfMastery|masteryResult|examResult/i.test(url)) return 'result'; if (/\/study\/(?:mastery|analysis)|\/mastery\b|knowledgeMastery|\/ability\b/i.test(url)) return 'mastery'; try { if (doc.querySelector('.answer-card .list .item') && doc.querySelector('.exam-item')) return 'exam'; if (doc.querySelector('.charts-label-rate') || doc.querySelector('.line1-count-total')) return 'result'; if (doc.querySelector('.item-box.gray, .item-box.pink, .mastery-box-custom-popover')) return 'mastery'; } catch (e) { /* ignore */ } return 'unsupported'; } function refreshHostVisibility() { const kind = detectPageKind(); const visible = kind !== 'unsupported' || autoMode; hostEl.style.display = visible ? '' : 'none'; return kind; } // --- 6. 胶囊/面板拖拽、Tab 与提醒弹窗 --- function clampBoxPosition(left, top, width, height) { const maxLeft = Math.max(8, window.innerWidth - width - 8); const maxTop = Math.max(8, window.innerHeight - height - 8); return { left: Math.min(Math.max(8, left), maxLeft), top: Math.min(Math.max(8, top), maxTop) }; } function makeDraggable(handleEl, targetEl, storageKey, defaultLeft, defaultTop, estWidth, estHeight, onDragEnd) { const saved = getStoredJson(storageKey, null); const init = saved && Number.isFinite(saved.left) && Number.isFinite(saved.top) ? clampBoxPosition(saved.left, saved.top, estWidth, estHeight) : clampBoxPosition(defaultLeft, defaultTop, estWidth, estHeight); targetEl.style.left = `${init.left}px`; targetEl.style.top = `${init.top}px`; let moved = false; handleEl.addEventListener('pointerdown', (e) => { if (e.button !== 0 && e.pointerType === 'mouse') return; if (e.target.closest('button') && handleEl !== e.target && handleEl === panelHeader) return; e.preventDefault(); const startX = e.clientX; const startY = e.clientY; const startLeft = parseFloat(targetEl.style.left) || 0; const startTop = parseFloat(targetEl.style.top) || 0; const rect = targetEl.getBoundingClientRect(); const width = rect.width || estWidth; const height = rect.height || estHeight; const maxLeft = Math.max(8, window.innerWidth - width - 8); const maxTop = Math.max(8, window.innerHeight - height - 8); moved = false; let rafId = null; let curDx = 0; let curDy = 0; handleEl.setPointerCapture(e.pointerId); const applyFrame = () => { rafId = null; targetEl.style.transform = `translate3d(${curDx}px, ${curDy}px, 0)`; }; const onMove = (ev) => { const rawDx = ev.clientX - startX; const rawDy = ev.clientY - startY; if (!moved && Math.hypot(rawDx, rawDy) > 4) { moved = true; targetEl.classList.add('dragging'); } if (moved) { const nextLeft = Math.min(Math.max(8, startLeft + rawDx), maxLeft); const nextTop = Math.min(Math.max(8, startTop + rawDy), maxTop); curDx = nextLeft - startLeft; curDy = nextTop - startTop; if (rafId === null) rafId = requestAnimationFrame(applyFrame); } }; const finishDrag = () => { handleEl.removeEventListener('pointermove', onMove); handleEl.removeEventListener('pointerup', finishDrag); handleEl.removeEventListener('pointercancel', finishDrag); if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; } if (moved) { const finalLeft = Math.round(startLeft + curDx); const finalTop = Math.round(startTop + curDy); targetEl.style.left = `${finalLeft}px`; targetEl.style.top = `${finalTop}px`; targetEl.style.transform = ''; void targetEl.offsetWidth; saveStoredJson(storageKey, { left: finalLeft, top: finalTop }); } targetEl.classList.remove('dragging'); if (onDragEnd) onDragEnd(moved); }; handleEl.addEventListener('pointermove', onMove); handleEl.addEventListener('pointerup', finishDrag); handleEl.addEventListener('pointercancel', finishDrag); }); window.addEventListener('resize', () => { const curLeft = parseFloat(targetEl.style.left) || defaultLeft; const curTop = parseFloat(targetEl.style.top) || defaultTop; const clamped = clampBoxPosition(curLeft, curTop, estWidth, estHeight); targetEl.style.left = `${clamped.left}px`; targetEl.style.top = `${clamped.top}px`; }); } let toggleDragMoved = false; makeDraggable(toggleButton, toggleButton, 'panel_pos', window.innerWidth - 112, window.innerHeight - 64, 96, 40, (moved) => { toggleDragMoved = moved; }); const defaultPanelHeight = Math.min(520, Math.max(300, window.innerHeight - 32)); makeDraggable(panelHeader, panel, 'panel_box_pos', window.innerWidth - 376, window.innerHeight - defaultPanelHeight - 20, 356, defaultPanelHeight); function setPanelVisible(visible) { isPanelVisible = Boolean(visible); panel.classList.toggle('show', isPanelVisible); toggleButton.classList.toggle('hidden', isPanelVisible); } function switchTab(tabName) { tabButtons.forEach(btn => btn.classList.toggle('active', btn.dataset.tab === tabName)); tabHome.classList.toggle('hidden', tabName !== 'home'); tabSettings.classList.toggle('hidden', tabName !== 'settings'); tabHelp.classList.toggle('hidden', tabName !== 'help'); } tabButtons.forEach(btn => btn.addEventListener('click', () => switchTab(btn.dataset.tab))); gotoSettingsBtn.addEventListener('click', () => switchTab('settings')); toggleButton.addEventListener('click', () => { if (toggleDragMoved) { toggleDragMoved = false; return; } setPanelVisible(true); }); closeButton.addEventListener('click', () => setPanelVisible(false)); bannerOpenBtn.addEventListener('click', () => { interruptBanner.classList.add('hidden'); setPanelVisible(true); }); bannerCloseBtn.addEventListener('click', () => interruptBanner.classList.add('hidden')); function notifyInterruption(reason) { if (!reason) return; interruptBannerMsg.textContent = reason; interruptBanner.classList.remove('hidden'); if (document.hidden && !document.title.startsWith('【需处理】')) { document.title = `【需处理】${originalTitle}`; } try { if (typeof GM_notification === 'function') { GM_notification({ title: '智慧树掌握度助手已暂停', text: reason, timeout: 8000, onclick: () => { window.focus(); setPanelVisible(true); } }); } } catch (e) { /* ignore */ } } // --- 7. 配置加载与动态模型拉取 --- modeSelect.value = GM_getValue('answer_mode', 'free'); searchModeSelect.value = GM_getValue('search_mode', 'local'); let savedOcsMode = GM_getValue('ocs_conflict_mode', 'yield'); if (savedOcsMode !== 'yield' && savedOcsMode !== 'off') { savedOcsMode = 'yield'; GM_setValue('ocs_conflict_mode', savedOcsMode); } ocsConflictSelect.value = savedOcsMode; capsuleGlowCheckbox.checked = GM_getValue('capsule_glow', true); toggleButton.classList.toggle('glow-on', capsuleGlowCheckbox.checked); let savedProvider = GM_getValue('api_provider', 'deepseek'); if (!API_PROVIDERS[savedProvider]) { savedProvider = 'deepseek'; GM_setValue('api_provider', savedProvider); } providerSelect.value = savedProvider; function loadProviderInputs(providerKey) { const provider = API_PROVIDERS[providerKey]; const allKeys = getStoredJson('api_keys_storage', {}); const allModels = getStoredJson('api_models_storage', {}); const allUrls = getStoredJson('api_urls_storage', {}); apiKeyInput.value = allKeys[providerKey] || ''; // 不预填默认模型,仅回填用户曾保存的模型 apiModelInput.value = allModels[providerKey] || ''; modelSelectList.classList.add('hidden'); modelSelectList.innerHTML = ''; apiUrlInput.value = allUrls[providerKey] ?? provider.defaultUrl; apiUrlInput.placeholder = provider.defaultUrl; } function loadSearchKeyInput(searchMode) { const searchKeys = getStoredJson('search_keys_storage', {}); searchApiKeyInput.value = searchKeys[searchMode] || ''; } loadProviderInputs(savedProvider); loadSearchKeyInput(searchModeSelect.value); quizbankUrlInput.value = GM_getValue('quizbank_url', ''); fallbackAiCheckbox.checked = GM_getValue('fallback_ai', false); stopConditionSelect.value = GM_getValue('stop_condition', 'gray'); autoSubmitCheckbox.checked = GM_getValue('auto_submit', false); function updateUIVisibility() { const mode = modeSelect.value; const providerKey = providerSelect.value; const provider = API_PROVIDERS[providerKey]; const searchMode = searchModeSelect.value; modeSegButtons.forEach(btn => btn.classList.toggle('active', btn.dataset.mode === mode)); if (provider) { apiKeyLabel.textContent = `${provider.name} Key`; apiModelGroup.classList.remove('hidden'); fetchModelsBtn.classList.toggle('hidden', !provider.supportsModelFetch); apiUrlGroup.classList.remove('hidden'); } if (SEARCH_KEY_PROVIDERS.has(searchMode)) { searchKeyGroup.classList.remove('hidden'); const labelMap = { bocha: '博查 API Key', tavily: 'Tavily API Key', serper: 'Serper API Key' }; searchKeyLabel.textContent = labelMap[searchMode] || '搜索 API Key'; } else { searchKeyGroup.classList.add('hidden'); } searchModeHintEl.textContent = SEARCH_HINTS[searchMode] || ''; ocsModeHintEl.textContent = OCS_HINTS[ocsConflictSelect.value] || ''; stopConditionHintEl.textContent = STOP_HINTS[stopConditionSelect.value] || ''; const searchLabelMap = { local: '免费搜题增强', native: 'AI 自带联网', bocha: '博查联网', tavily: 'Tavily', serper: 'Serper', off: '不联网' }; const modeLabel = mode === 'free' ? '免费 AI' : (mode === 'quizbank' ? '题库模式' : (provider?.name?.split(' ')[0] || '自定义 AI')); statusSummaryEl.textContent = `${modeLabel} · ${searchLabelMap[searchMode] || searchMode}`; let tip = ''; if (mode === 'custom') { if (!apiKeyInput.value.trim()) tip = `未填写 ${provider?.name || 'AI'} Key`; else if (!apiModelInput.value.trim()) tip = '未选择模型(点获取模型)'; } else if (mode === 'quizbank' && !quizbankUrlInput.value.trim()) { tip = '未填写题库 JSON 地址'; } configTip.classList.toggle('hidden', !tip); if (tip) configTipText.textContent = tip; } let modelFetchSeq = 0; async function fetchAvailableModels() { const providerKey = providerSelect.value; const provider = API_PROVIDERS[providerKey]; const apiKey = apiKeyInput.value.trim(); if (!provider?.supportsModelFetch) return; if (!apiKey) { const msg = '请先填写 API Key,再点击「获取模型」。'; setInlineFeedback(aiTestResultEl, 'err', msg); log(msg); return; } const reqSeq = ++modelFetchSeq; const customUrl = apiUrlInput.value.trim() || provider.defaultUrl; const modelsUrl = provider.buildModelsUrl(customUrl); fetchModelsBtn.disabled = true; fetchModelsBtn.textContent = '获取中...'; setInlineFeedback(aiTestResultEl, 'info', '正在获取可用模型列表...'); try { let headers; if (providerKey === 'gemini') headers = { 'x-goog-api-key': apiKey }; else if (providerKey === 'anthropic') headers = { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' }; else headers = { 'Authorization': `Bearer ${apiKey}` }; const res = await gmRequest({ url: modelsUrl, headers, timeout: 10000 }); if (reqSeq !== modelFetchSeq || providerSelect.value !== providerKey) return; if (!res.ok || !res.text) { const msg = `获取模型失败 (${res.status || res.statusText}),请检查 Key 或接口地址。`; setInlineFeedback(aiTestResultEl, 'err', msg); log(msg); return; } const json = JSON.parse(res.text); let models = []; if (providerKey === 'gemini') { models = (Array.isArray(json.models) ? json.models : []) .filter(m => !Array.isArray(m.supportedGenerationMethods) || m.supportedGenerationMethods.includes('generateContent')) .map(m => String(m.name || '').replace(/^models\//, '')) .filter(Boolean); } else { models = (Array.isArray(json.data) ? json.data : []) .map(m => String(m.id || '').trim()) .filter(Boolean); } models = [...new Set(models)].sort(); if (models.length === 0) { const msg = '接口返回成功,但模型列表为空,请手动输入模型名。'; setInlineFeedback(aiTestResultEl, 'err', msg); log(msg); return; } const frag = document.createDocumentFragment(); const placeholderOpt = document.createElement('option'); placeholderOpt.value = ''; placeholderOpt.textContent = '-- 请选择获取到的模型 --'; frag.appendChild(placeholderOpt); for (const id of models) { const opt = document.createElement('option'); opt.value = id; opt.textContent = id; frag.appendChild(opt); } modelSelectList.textContent = ''; modelSelectList.appendChild(frag); modelSelectList.classList.remove('hidden'); if (!apiModelInput.value.trim()) { apiModelInput.value = models[0]; modelSelectList.value = models[0]; const allModels = getStoredJson('api_models_storage', {}); allModels[providerKey] = models[0]; saveStoredJson('api_models_storage', allModels); updateUIVisibility(); } const okMsg = `已获取 ${models.length} 个模型,当前选用: ${apiModelInput.value}`; setInlineFeedback(aiTestResultEl, 'ok', okMsg); log(okMsg); } catch (e) { if (reqSeq !== modelFetchSeq || providerSelect.value !== providerKey) return; const msg = `解析模型列表失败: ${e.message}`; setInlineFeedback(aiTestResultEl, 'err', msg); log(msg); } finally { if (reqSeq === modelFetchSeq) { fetchModelsBtn.disabled = false; fetchModelsBtn.textContent = '获取模型'; } } } fetchModelsBtn.addEventListener('click', fetchAvailableModels); modelSelectList.addEventListener('change', () => { if (!modelSelectList.value) return; const k = providerSelect.value; apiModelInput.value = modelSelectList.value; const allModels = getStoredJson('api_models_storage', {}); allModels[k] = apiModelInput.value; saveStoredJson('api_models_storage', allModels); updateUIVisibility(); }); modeSegButtons.forEach(btn => { btn.addEventListener('click', () => { modeSelect.value = btn.dataset.mode; GM_setValue('answer_mode', modeSelect.value); updateUIVisibility(); }); }); modeSelect.addEventListener('change', () => { GM_setValue('answer_mode', modeSelect.value); updateUIVisibility(); }); searchModeSelect.addEventListener('change', () => { const val = searchModeSelect.value; GM_setValue('search_mode', val); loadSearchKeyInput(val); updateUIVisibility(); }); searchApiKeyInput.addEventListener('input', () => { const sMode = searchModeSelect.value; if (!SEARCH_KEY_PROVIDERS.has(sMode)) return; const searchKeys = getStoredJson('search_keys_storage', {}); searchKeys[sMode] = searchApiKeyInput.value; saveStoredJson('search_keys_storage', searchKeys); }); ocsConflictSelect.addEventListener('change', () => { GM_setValue('ocs_conflict_mode', ocsConflictSelect.value); updateUIVisibility(); refreshOcsPolicyStatus(); }); copyOcsExcludeBtn.addEventListener('click', async () => { let copied = false; try { if (navigator?.clipboard?.writeText) { await navigator.clipboard.writeText(OCS_EXCLUDE_RULES); copied = true; } } catch (e) { /* fallback below */ } if (!copied) { try { const ta = document.createElement('textarea'); ta.value = OCS_EXCLUDE_RULES; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); copied = document.execCommand('copy'); ta.remove(); } catch (e) { /* ignore */ } } if (copied) { setInlineFeedback(ocsCopyResultEl, 'ok', '已复制 4 条排除规则!打开 ScriptCat / Tampermonkey → OCS 设置 →「用户排除」粘贴保存即可(不影响正常看课)。'); log('已复制 OCS 掌握度页面排除规则到剪贴板。'); } else { setInlineFeedback(ocsCopyResultEl, 'err', '自动复制受限,请参考帮助文档手动复制排除规则。'); } }); capsuleGlowCheckbox.addEventListener('change', () => { GM_setValue('capsule_glow', capsuleGlowCheckbox.checked); toggleButton.classList.toggle('glow-on', capsuleGlowCheckbox.checked); }); function handleProviderChange() { modelFetchSeq++; fetchModelsBtn.disabled = false; fetchModelsBtn.textContent = '获取模型'; setInlineFeedback(aiTestResultEl, '', ''); const newProvider = providerSelect.value; GM_setValue('api_provider', newProvider); loadProviderInputs(newProvider); updateUIVisibility(); } providerSelect.addEventListener('change', handleProviderChange); apiKeyInput.addEventListener('input', () => { const k = providerSelect.value; const allKeys = getStoredJson('api_keys_storage', {}); allKeys[k] = apiKeyInput.value; saveStoredJson('api_keys_storage', allKeys); updateUIVisibility(); }); apiModelInput.addEventListener('input', () => { const k = providerSelect.value; const allModels = getStoredJson('api_models_storage', {}); allModels[k] = apiModelInput.value; saveStoredJson('api_models_storage', allModels); updateUIVisibility(); }); apiUrlInput.addEventListener('input', () => { const k = providerSelect.value; const allUrls = getStoredJson('api_urls_storage', {}); allUrls[k] = apiUrlInput.value; saveStoredJson('api_urls_storage', allUrls); }); quizbankUrlInput.addEventListener('input', () => { GM_setValue('quizbank_url', quizbankUrlInput.value); updateUIVisibility(); }); fallbackAiCheckbox.addEventListener('change', () => GM_setValue('fallback_ai', fallbackAiCheckbox.checked)); stopConditionSelect.addEventListener('change', () => { GM_setValue('stop_condition', stopConditionSelect.value); updateUIVisibility(); }); autoSubmitCheckbox.addEventListener('change', () => { GM_setValue('auto_submit', autoSubmitCheckbox.checked); log(autoSubmitCheckbox.checked ? '已开启自动提交:题目处理完成后不再弹窗,直接提交本次练习。' : '已关闭自动提交:题目处理完成后会弹窗等待人工确认。'); }); refreshQuizbankButton.addEventListener('click', fetchQuizBank); startButton.addEventListener('click', () => toggleAutoMode(!autoMode)); clearLogBtn.addEventListener('click', () => { statusLog.innerHTML = ''; }); resetAttemptedButton.addEventListener('click', () => { if (!window.confirm('清除当前课程、本浏览器标签页中的已尝试知识点记录?')) return; attemptedMasteryItems.clear(); writeSessionStorage(getAttemptedItemsStorageKey(), '[]'); removeSessionStorage(getActiveItemStorageKey()); updateStatusBar(); log('已清除本页尝试记录。'); }); testAiBtn.addEventListener('click', async () => { testAiBtn.disabled = true; const providerName = API_PROVIDERS[providerSelect.value]?.name || providerSelect.value; const startedAt = Date.now(); setInlineFeedback(aiTestResultEl, 'info', `正在测试 ${providerName} 连接...`); try { log(`正在测试 AI 连接(${providerName})...`); const ans = await callAiApi('1+1等于几?', ['1', '2', '3', '4'], '单选题', 'custom', { skipSearch: true }); const elapsed = ((Date.now() - startedAt) / 1000).toFixed(1); if (ans) { const msg = `连接成功 (${elapsed}s),测试题回答: ${ans}`; setInlineFeedback(aiTestResultEl, 'ok', msg); log(`AI 连接测试成功,返回结果: ${ans}`); } else { const msg = '连接未返回有效答案,请检查 Key、模型名称或接口地址(详情见主页日志)。'; setInlineFeedback(aiTestResultEl, 'err', msg); } } finally { testAiBtn.disabled = false; } }); testSearchBtn.addEventListener('click', async () => { testSearchBtn.disabled = true; const sMode = searchModeSelect.value; try { log(`正在测试联网搜索(模式: ${sMode})...`); if (sMode === 'off') { const msg = '当前已选择「不联网」,无需测试。'; setInlineFeedback(searchTestResultEl, 'info', msg); log(msg); return; } setInlineFeedback(searchTestResultEl, 'info', '正在执行搜索测试...'); const res = await runWebSearch('马克思主义哲学的基本特征', modeSelect.value === 'custom' ? 'custom' : 'free'); if (res.results.length > 0) { const msg = `搜索成功 [${res.source}],命中 ${res.results.length} 条,首条: ${res.results[0].title}`; setInlineFeedback(searchTestResultEl, 'ok', msg); log(msg); } else if (res.useNativeInChat) { const msg = `${API_PROVIDERS[providerSelect.value].name} 将在答题对话中直接开启自带联网。`; setInlineFeedback(searchTestResultEl, 'ok', msg); log(msg); } else { const msg = '未获取到搜索结果,可能网络受限或搜索 Key 无效。'; setInlineFeedback(searchTestResultEl, 'err', msg); log(msg); } } finally { testSearchBtn.disabled = false; } }); updateUIVisibility(); updateAutoModeButton(); updateStatusBar(); // --- 8. 日志与状态栏 --- function log(message) { console.log(`[AI脚本] ${message}`); const timestamp = new Date().toLocaleTimeString(); const entry = document.createElement('div'); entry.textContent = `${timestamp}: ${message}`; statusLog.appendChild(entry); while (statusLog.childElementCount > MAX_LOG_ENTRIES) { statusLog.removeChild(statusLog.firstElementChild); } statusLog.scrollTop = statusLog.scrollHeight; } function updateStatusBar(ocsStateText = null) { statusAttemptedEl.textContent = `本轮已试: ${attemptedMasteryItems.size}`; if (autoMode) { statusPill.textContent = '运行中'; statusPill.className = 'status-pill running'; toggleButton.classList.add('running'); } else { statusPill.textContent = '待机中'; statusPill.className = 'status-pill'; toggleButton.classList.remove('running'); } if (ocsStateText) { statusOcsEl.textContent = ocsStateText; } } // --- 9. OCS 等答题脚本冲突检测与治理 --- const OCS_SELECTORS = [ '#ocs-panel', '.ocs-container', '[id^="ocs-"]', '[class*="ocs-panel"]', '[class*="ocs-container"]', '[class*="ocs-message"]', 'container-element', 'message-element', 'modal-element', 'script-panel-element', 'ocs-panel', 'ocs-root' ]; const OCS_SHADOW_INNER_SELECTOR = 'container-element, message-element, modal-element, script-panel-element, .ocs-container, [class*="ocs-"]'; function findOcsShadowHosts() { const hosts = []; const candidates = [ ...(document.body?.children ? Array.from(document.body.children) : []), ...(document.documentElement?.children ? Array.from(document.documentElement.children) : []) ]; const seen = new Set(); for (const el of candidates) { if (!el || seen.has(el) || el.id === 'zhs-ai-helper-host') continue; seen.add(el); try { if (el.shadowRoot && el.shadowRoot.querySelector(OCS_SHADOW_INNER_SELECTOR)) { hosts.push(el); } } catch (e) { /* ignore */ } } return hosts; } function detectOcsPresence() { for (const selector of OCS_SELECTORS) { try { const el = document.querySelector(selector); if (el && el.id !== 'zhs-ai-helper-host') { const style = window.getComputedStyle(el); const visible = style.display !== 'none' && style.visibility !== 'hidden'; return { detected: true, visible, selector }; } } catch (e) { /* ignore */ } } for (const host of findOcsShadowHosts()) { try { const style = window.getComputedStyle(host); const visible = style.display !== 'none' && style.visibility !== 'hidden'; return { detected: true, visible, selector: `${host.tagName?.toLowerCase() || 'shadow'}#shadow` }; } catch (e) { return { detected: true, visible: true, selector: 'ocs-shadow-host' }; } } try { if (typeof unsafeWindow !== 'undefined' && (unsafeWindow.OCS || unsafeWindow.$ocs)) { return { detected: true, visible: true, selector: 'window.OCS' }; } } catch (e) { /* ignore */ } return { detected: false, visible: false, selector: '' }; } function refreshOcsPolicyStatus() { const pageKind = detectPageKind(); if (pageKind === 'unsupported' && !autoMode) { updateStatusBar('OCS: 待机'); return { shouldYield: false }; } const mode = ocsConflictSelect.value; if (mode === 'off') { updateStatusBar('OCS: 已忽略'); return { shouldYield: false }; } const info = detectOcsPresence(); if (info.detected && info.visible) { updateStatusBar('OCS: 已避让'); return { shouldYield: true, reason: `检测到其他答题脚本 (${info.selector}) 处于活跃状态;请在脚本管理器中为 OCS 添加掌握度页面排除规则` }; } updateStatusBar('OCS: 正常'); return { shouldYield: false }; } refreshOcsPolicyStatus(); // --- 10. 存储与卡片标识辅助 --- function readSessionStorage(key) { try { return sessionStorage.getItem(key); } catch (e) { return null; } } function writeSessionStorage(key, value) { try { sessionStorage.setItem(key, value); return true; } catch (e) { log(`无法保存本页运行状态: ${e.message}`); return false; } } function removeSessionStorage(key) { try { sessionStorage.removeItem(key); } catch (e) { log(`无法清理本页运行状态: ${e.message}`); } } function readSessionArray(key) { try { const value = JSON.parse(sessionStorage.getItem(key) || '[]'); return Array.isArray(value) ? value.filter(item => typeof item === 'string') : []; } catch (e) { return []; } } function isCurrentMasteryItemKey(key) { try { const value = JSON.parse(key); return Array.isArray(value) && value.length === 5 && value[1] === 'tile-v2' && Number.isInteger(value[2]); } catch (e) { return false; } } function getMasteryItemKey(item) { const courseId = new URLSearchParams(window.location.search).get('recruitAndCourseId') || ''; const itemIndex = Array.from(document.querySelectorAll('.item-box')).indexOf(item); if (itemIndex < 0) throw new Error('知识点卡片已脱离当前页面,无法生成唯一标识。'); const sectionName = item.closest('.chunk-list')?.parentElement?.querySelector('.mastery-name')?.textContent?.trim() || ''; const itemName = item.querySelector('.item-box-name_text, .item-box-name')?.textContent?.trim() || item.textContent.trim(); return JSON.stringify([courseId, 'tile-v2', itemIndex, sectionName, itemName]); } function getMasteryPopoverForItem(item) { const items = Array.from(document.querySelectorAll('.item-box')); const itemIndex = items.indexOf(item); const popovers = Array.from(document.querySelectorAll('.mastery-box-custom-popover')); if (itemIndex < 0 || popovers.length !== items.length) return null; const popover = popovers[itemIndex]; const itemName = item.querySelector('.item-box-name_text, .item-box-name')?.textContent?.trim() || ''; const popoverName = popover?.querySelector('.name, strong')?.textContent?.trim() || ''; const normalize = value => value.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ''); if (!itemName || !popoverName || normalize(itemName) !== normalize(popoverName)) return null; return { itemIndex, popover, popoverName }; } function markActiveMasteryItemAttempted(resultSummary = null) { const activeKey = getActiveItemStorageKey(); const activeItemKey = readSessionStorage(activeKey); if (!activeItemKey) return; if (!isCurrentMasteryItemKey(activeItemKey)) { removeSessionStorage(activeKey); toggleAutoMode(false, '检测到旧版知识点标识,已暂停以避免把结果记到错误卡片;请返回掌握度页面后重新开始。'); return; } attemptedMasteryItems.add(activeItemKey); writeSessionStorage(getAttemptedItemsStorageKey(), JSON.stringify([...attemptedMasteryItems])); removeSessionStorage(activeKey); updateStatusBar(); if (resultSummary) { const fullScore = resultSummary.score >= 100 && resultSummary.correct === resultSummary.total; const resultLabel = `掌握度 ${resultSummary.score}%,答对 ${resultSummary.correct}/${resultSummary.total} 题`; log(`已记录本知识点本轮尝试(${resultLabel}${fullScore ? ',本次满分' : ',本次未满分'});是否掌握仍以列表状态为准。`); if (!fullScore) log('本次结果未满分,该知识点可能仍为遗漏/薄弱状态;为避免重复提交,本轮不会自动重做。'); } else { log('已记录本知识点本轮尝试,但未能读取结算结果;这不代表平台已确认掌握度更新,本轮不会自动重复提交。'); } } function isAutoSubmitEnabled() { return autoSubmitCheckbox.checked; } function reliableClick(element) { if (!element) { log('警告: 尝试点击一个不存在的元素。'); return; } if (typeof element.click === 'function') { element.click(); return; } const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true, view: unsafeWindow }); element.dispatchEvent(clickEvent); } // --- 11. 题库搜索(预索引 + 剪枝一维 Levenshtein) --- function normalizeQuestionText(text) { return String(text || '').replace(/^\d+[.、\s]*/, '').replace(/\s+/g, ' ').trim(); } function getLevenshteinDistance(a, b) { if (a === b) return 0; if (a.length === 0) return b.length; if (b.length === 0) return a.length; if (a.length > b.length) [a, b] = [b, a]; const m = a.length; const n = b.length; let prev = new Array(m + 1); let curr = new Array(m + 1); for (let i = 0; i <= m; i++) prev[i] = i; for (let j = 1; j <= n; j++) { curr[0] = j; const bj = b.charCodeAt(j - 1); for (let i = 1; i <= m; i++) { const cost = a.charCodeAt(i - 1) === bj ? 0 : 1; curr[i] = Math.min(curr[i - 1] + 1, prev[i] + 1, prev[i - 1] + cost); } [prev, curr] = [curr, prev]; } return prev[m]; } function findInQuizBank(question) { if (quizBank.length === 0) { log('题库为空,跳过搜索。'); return null; } const processedQuestion = normalizeQuestionText(question); const exactAnswer = quizBankExactMap.get(processedQuestion); if (exactAnswer) { log(`题库精确命中: ${exactAnswer}`); return exactAnswer; } let bestMatch = null; let highestSimilarity = 0; const qLen = processedQuestion.length; for (const item of quizBank) { const maxLen = Math.max(qLen, item._normQ.length, 1); if (Math.abs(qLen - item._normQ.length) / maxLen > 0.1) continue; const distance = getLevenshteinDistance(processedQuestion, item._normQ); const similarity = 1 - (distance / maxLen); if (similarity > highestSimilarity) { highestSimilarity = similarity; bestMatch = item; } } if (highestSimilarity >= 0.9 && bestMatch) { log(`题库模糊命中 (相似度 ${(highestSimilarity * 100).toFixed(1)}%): ${bestMatch.a}`); return bestMatch.a; } log(`题库未命中,最高相似度: ${(highestSimilarity * 100).toFixed(1)}% (未达 90%)`); return null; } async function fetchQuizBank() { const url = quizbankUrlInput.value.trim(); if (!url) { const msg = '错误: 题库 URL 为空。'; setInlineFeedback(quizbankTestResultEl, 'err', msg); log(msg); return false; } setInlineFeedback(quizbankTestResultEl, 'info', '正在加载题库...'); log('正在从 Gist/URL 加载题库...'); quizBank = []; quizBankExactMap = new Map(); answerCache.clear(); const response = await gmRequest({ method: 'GET', url, timeout: 15000 }); if (response.status === 200) { try { const data = JSON.parse(response.text); if (Array.isArray(data)) { quizBank = data .filter(item => item && item.q && item.a) .map(item => ({ ...item, _normQ: normalizeQuestionText(item.q) })); for (const item of quizBank) { if (!quizBankExactMap.has(item._normQ)) quizBankExactMap.set(item._normQ, item.a); } answerCache.clear(); const okMsg = `题库加载成功!共 ${quizBank.length} 条有效记录。`; setInlineFeedback(quizbankTestResultEl, 'ok', okMsg); log(okMsg); return true; } const msg = '错误: 题库格式不是 JSON 数组。'; setInlineFeedback(quizbankTestResultEl, 'err', msg); log(msg); return false; } catch (e) { const msg = `题库 JSON 解析失败: ${e.message}`; setInlineFeedback(quizbankTestResultEl, 'err', msg); log(msg); return false; } } const msg = response.timeout ? '题库请求超时。' : (response.networkError ? `题库请求错误: ${response.statusText || 'Network Error'}` : `题库加载失败: ${response.status} ${response.statusText}`); setInlineFeedback(quizbankTestResultEl, 'err', msg); log(msg); return false; } // --- 12. 联网搜索模块 --- function cleanSearchQuery(raw) { return String(raw || '') .replace(/^\d+[.、\s]*/, '') .replace(/[((]\s*(?:单选题|多选题|判断题|填空题|简答题|论述题|必答|\d+(?:\.\d+)?分)\s*[))]/g, '') .replace(/\s+/g, ' ') .trim() .slice(0, 80); } function gmRequest(options) { return new Promise((resolve) => { GM_xmlhttpRequest({ method: options.method || 'GET', url: options.url, headers: options.headers || {}, data: options.data, timeout: options.timeout || 8000, onload: (res) => resolve({ ok: res.status >= 200 && res.status < 300, status: res.status, text: res.responseText || '', statusText: res.statusText || '' }), onerror: (err) => resolve({ ok: false, status: 0, text: '', statusText: err?.statusText || 'Network Error', networkError: true }), ontimeout: () => resolve({ ok: false, status: 0, text: '', statusText: 'Timeout', timeout: true }) }); }); } async function searchLocalWeb(query) { const cleaned = cleanSearchQuery(query); if (!cleaned) return { results: [], source: 'local' }; const encoded = encodeURIComponent(cleaned); const parser = new DOMParser(); const bingRes = await gmRequest({ url: `https://cn.bing.com/search?q=${encoded}&mkt=zh-CN`, headers: { 'Accept-Language': 'zh-CN,zh;q=0.9' }, timeout: 7000 }); if (bingRes.ok && bingRes.text) { try { const doc = parser.parseFromString(bingRes.text, 'text/html'); const items = []; for (const li of doc.querySelectorAll('#b_results li.b_algo')) { const title = li.querySelector('h2 a, h2')?.textContent?.trim() || ''; const snippet = li.querySelector('.b_caption p, .b_algoSlug, p')?.textContent?.trim() || ''; if (title || snippet) items.push({ title, snippet: snippet.slice(0, 180) }); if (items.length >= 3) break; } if (items.length > 0) return { results: items, source: 'Bing' }; } catch (e) { /* fallback */ } } const soRes = await gmRequest({ url: `https://m.so.com/s?q=${encoded}`, headers: { 'Accept-Language': 'zh-CN,zh;q=0.9' }, timeout: 7000 }); if (soRes.ok && soRes.text) { try { const doc = parser.parseFromString(soRes.text, 'text/html'); const items = []; for (const card of doc.querySelectorAll('.res-list .g-card, .res-list')) { const title = card.querySelector('h3, a.res-title')?.textContent?.trim() || ''; if (!title || title.includes('猜您关注') || title.includes('相关搜索')) continue; const snippet = card.querySelector('.res-desc, p, .summary')?.textContent?.trim() || ''; if (title || snippet) items.push({ title, snippet: snippet.slice(0, 180) }); if (items.length >= 3) break; } if (items.length > 0) return { results: items, source: '360搜索' }; } catch (e) { /* fallback */ } } const baikeKey = cleaned.split(/[\s,,。??!!::]+/).find(Boolean) || cleaned; const baikeRes = await gmRequest({ url: `https://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=${encodeURIComponent(baikeKey)}`, timeout: 6000 }); if (baikeRes.ok && baikeRes.text) { try { const obj = JSON.parse(baikeRes.text); const title = String(obj?.title || '').trim(); const abs = String(obj?.abstract || '').trim(); if (title || abs) return { results: [{ title, snippet: abs.slice(0, 200) }], source: '百度百科' }; } catch (e) { /* ignore */ } } return { results: [], source: 'local' }; } const deepseekToolsUnsupportedRoots = new Set(); async function searchDeepSeekTools(baseUrl, apiKey, query) { const cleaned = cleanSearchQuery(query); if (!cleaned || !apiKey) return { results: [], source: 'DeepSeek' }; const root = String(baseUrl || 'https://api.deepseek.com/v1').trim().replace(/\/chat\/completions\/?$/i, '').replace(/\/+$/, ''); if (deepseekToolsUnsupportedRoots.has(root)) { return { results: [], source: 'DeepSeek', unsupported: true }; } const res = await gmRequest({ method: 'POST', url: `${root}/tools/search`, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, data: JSON.stringify({ query: cleaned, count: 5, need_content: false }), timeout: 8000 }); if (res.status === 404 || res.status === 405) { deepseekToolsUnsupportedRoots.add(root); return { results: [], source: 'DeepSeek', unsupported: true }; } if (!res.ok || !res.text) return { results: [], source: 'DeepSeek' }; try { const json = JSON.parse(res.text); const list = Array.isArray(json.results) ? json.results : []; const results = list.slice(0, 3).map(it => ({ title: String(it.title || '').trim(), snippet: String(it.summary || it.snippet || '').trim().slice(0, 200) })).filter(it => it.title || it.snippet); return { results, source: 'DeepSeek搜索' }; } catch (e) { return { results: [], source: 'DeepSeek' }; } } async function searchThirdPartyApi(searchMode, apiKey, query) { const cleaned = cleanSearchQuery(query); if (!cleaned || !apiKey) return { results: [], source: searchMode }; if (searchMode === 'bocha') { const res = await gmRequest({ method: 'POST', url: 'https://api.bochaai.com/v1/web-search', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, data: JSON.stringify({ query: cleaned, count: 3, summary: true }), timeout: 8000 }); if (res.ok && res.text) { try { const data = JSON.parse(res.text); const pages = data?.data?.webPages?.value || data?.webPages?.value || []; return { results: pages.slice(0, 3).map(p => ({ title: p.name || '', snippet: (p.summary || p.snippet || '').slice(0, 200) })), source: '博查' }; } catch (e) { /* ignore */ } } } else if (searchMode === 'tavily') { const res = await gmRequest({ method: 'POST', url: 'https://api.tavily.com/search', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ api_key: apiKey, query: cleaned, max_results: 3, search_depth: 'basic' }), timeout: 8000 }); if (res.ok && res.text) { try { const data = JSON.parse(res.text); const list = Array.isArray(data?.results) ? data.results : []; return { results: list.slice(0, 3).map(p => ({ title: p.title || '', snippet: (p.content || '').slice(0, 200) })), source: 'Tavily' }; } catch (e) { /* ignore */ } } } else if (searchMode === 'serper') { const res = await gmRequest({ method: 'POST', url: 'https://google.serper.dev/search', headers: { 'Content-Type': 'application/json', 'X-API-KEY': apiKey }, data: JSON.stringify({ q: cleaned, gl: 'cn', hl: 'zh-cn', num: 3 }), timeout: 8000 }); if (res.ok && res.text) { try { const data = JSON.parse(res.text); const list = Array.isArray(data?.organic) ? data.organic : []; return { results: list.slice(0, 3).map(p => ({ title: p.title || '', snippet: (p.snippet || '').slice(0, 200) })), source: 'Serper' }; } catch (e) { /* ignore */ } } } return { results: [], source: searchMode }; } async function runWebSearch(question, aiMode) { const sMode = searchModeSelect.value; if (sMode === 'off') return { results: [], source: 'off', useNativeInChat: false }; const providerKey = providerSelect.value; if (sMode === 'native') { if (aiMode === 'custom') { if (providerKey === 'zhipu' || providerKey === 'gemini') { return { results: [], source: `${API_PROVIDERS[providerKey].name}原生联网`, useNativeInChat: true }; } if (providerKey === 'deepseek') { const key = apiKeyInput.value.trim(); const url = apiUrlInput.value.trim() || API_PROVIDERS.deepseek.defaultUrl; const dsCacheKey = `deepseek:${cleanSearchQuery(question)}`; if (searchCache.has(dsCacheKey)) return searchCache.get(dsCacheKey); const dsRes = await searchDeepSeekTools(url, key, question); if (dsRes.results.length > 0) { const out = { ...dsRes, useNativeInChat: false }; setCacheWithLimit(searchCache, dsCacheKey, out); return out; } log(dsRes.unsupported ? '当前 DeepSeek 接口不支持 /tools/search,已熔断并降级为免费搜题增强...' : 'DeepSeek 原生搜索无结果,自动降级为免费搜题增强...'); } else { log(`${API_PROVIDERS[providerKey]?.name || providerKey} 无原生联网接口,自动转为免费搜题增强...`); } } else { log('免费模式自动使用免费搜题增强...'); } } if (SEARCH_KEY_PROVIDERS.has(sMode)) { const searchKeys = getStoredJson('search_keys_storage', {}); const sKey = (searchKeys[sMode] || searchApiKeyInput.value || '').trim(); if (!sKey) { log(`未填写 ${sMode} 搜索 Key,自动转为免费搜题增强...`); } else { const cacheKey = `${sMode}:${cleanSearchQuery(question)}`; if (searchCache.has(cacheKey)) return searchCache.get(cacheKey); const tpRes = await searchThirdPartyApi(sMode, sKey, question); if (tpRes.results.length > 0) { const out = { ...tpRes, useNativeInChat: false }; setCacheWithLimit(searchCache, cacheKey, out); return out; } log(`${sMode} 搜索无结果,降级为免费搜题增强...`); } } const localCacheKey = `local:${cleanSearchQuery(question)}`; if (searchCache.has(localCacheKey)) return searchCache.get(localCacheKey); const localRes = await searchLocalWeb(question); const out = { ...localRes, useNativeInChat: false }; if (out.results.length > 0) setCacheWithLimit(searchCache, localCacheKey, out); return out; } // --- 13. AI 答案提取与重试容错 --- function extractAnswerLetters(rawContent, optionsText = [], questionType = '单选题') { if (rawContent === null || rawContent === undefined) return null; let text = String(rawContent) .replace(/[\s\S]*?<\/think>/gi, ' ') .replace(/```[a-z]*\s*/gi, ' ') .replace(/```/g, ' ') .trim(); if (!text) return null; const optionCount = Array.isArray(optionsText) && optionsText.length > 0 ? optionsText.length : 26; const maxLetterCode = 65 + Math.min(optionCount, 26) - 1; const isValidLetter = (ch) => { const code = ch.charCodeAt(0); return code >= 65 && code <= maxLetterCode; }; const filterLetters = (str) => { const unique = []; for (const ch of String(str || '').toUpperCase()) { if (isValidLetter(ch) && !unique.includes(ch)) unique.push(ch); } return unique.join(''); }; // 1. 判断题正负语义优先映射 if (questionType === '判断题') { const positive = /^(?:对|正确|是|T|TRUE|YES|√)$/i.test(text); const negative = /^(?:错|错误|否|F|FALSE|NO|×)$/i.test(text); if (positive || negative) { const idx = optionsText.findIndex(opt => { const t = String(opt || '').trim(); return positive ? /^(?:对|正确|是|√)/.test(t) : /^(?:错|错误|否|×)/.test(t); }); if (idx >= 0) return String.fromCharCode(65 + idx); return positive ? 'A' : 'B'; } } const isSingleChoice = questionType === '单选题' || questionType === '判断题'; // 2. 仅当全部由合法选项字母及分隔符组成,且符合题型长度时才直接提取(避免误判英文句子或选项文本) if (/^[A-Za-z\s,,、/.;;]+$/.test(text)) { const compact = text.replace(/[\s,,、/.;;]+/g, '').toUpperCase(); const allValid = compact.length > 0 && [...compact].every(isValidLetter); if (allValid && (isSingleChoice ? compact.length === 1 : compact.length <= optionCount)) { const direct = filterLetters(compact); if (direct) return direct; } } // 3. 显式结论句(取最后一个匹配) const conclusionRegex = /(?:正确答案|最终答案|答案|应选|选择|选|Option|Answer)(?:\s*is\b)?\s*[::为是]?\s*([A-Z](?:[\s,,、/与和]*[A-Z])*)/gi; let lastConclusion = null; let m; while ((m = conclusionRegex.exec(text)) !== null) { const candidate = filterLetters(m[1]); if (candidate) lastConclusion = candidate; } if (lastConclusion) { return isSingleChoice ? lastConclusion[0] : lastConclusion; } // 4. 独立边界字母(避免把 "Option" 中的 O/P/T/I/N 误当答案) const standaloneMatches = text.match(/(?:^|[^A-Za-z])([A-Z])(?=$|[^A-Za-z])/g); if (standaloneMatches) { const combined = filterLetters(standaloneMatches.map(s => s.replace(/[^A-Z]/g, '')).join('')); if (combined) return isSingleChoice ? combined[0] : combined; } // 5. 兜底:若 AI 回复了选项原文文本,反推对应字母(大小写不敏感) if (Array.isArray(optionsText) && optionsText.length > 0) { const cleanText = text.replace(/\s+/g, '').toLowerCase(); const matchedIndices = []; optionsText.forEach((opt, idx) => { const cleanOpt = String(opt || '').replace(/\s+/g, '').toLowerCase(); const subMatch = cleanText.length >= 2 && cleanText.length >= Math.ceil(cleanOpt.length * 0.5) && cleanOpt.includes(cleanText); if (cleanOpt.length >= 2 && (cleanText === cleanOpt || cleanText.includes(cleanOpt) || subMatch)) { matchedIndices.push(String.fromCharCode(65 + idx)); } }); if (matchedIndices.length > 0) { return isSingleChoice ? matchedIndices[0] : matchedIndices.join(''); } } return null; } async function callAiApiOnce(question, options, type, aiMode, searchContext) { const refText = searchContext?.results?.length ? `\n---联网参考摘要 (${searchContext.source}):\n${searchContext.results.map((r, i) => `${i + 1}. ${r.title}: ${r.snippet}`).join('\n')}` : ''; const sysPrompt = '你是一个严格按格式输出的答题引擎。禁止输出任何思考过程、分析、解释或标点。只输出正确选项的大写字母(单选/判断如 A,多选如 AC)。'; const userPrompt = `题型:${type}\n题目:${question}\n选项:\n${options.map((opt, index) => `${String.fromCharCode(65 + index)}. ${opt}`).join('\n')}${refText}\n请直接输出答案字母:`; const messages = [ { role: 'system', content: sysPrompt }, { role: 'user', content: userPrompt } ]; let url, headers, data, providerConfig; const effectiveProviderKey = aiMode === 'free' ? 'zhipu' : providerSelect.value; if (aiMode === 'free') { url = 'https://api.coren.xin/zhipu-free-proxy'; headers = { 'Content-Type': 'application/json' }; data = JSON.stringify({ messages, temperature: 0, max_tokens: 128, thinking: { type: 'disabled' } }); providerConfig = API_PROVIDERS.zhipu; } else { const apiKey = apiKeyInput.value.trim(); providerConfig = API_PROVIDERS[effectiveProviderKey]; if (!apiKey) { log('错误: 自定义 AI 模式下必须提供 API Key'); return { answer: null, retryable: false }; } if (!providerConfig) { log(`错误: 未知的服务商: ${effectiveProviderKey}`); return { answer: null, retryable: false }; } const customUrl = apiUrlInput.value.trim(); const customModel = apiModelInput.value.trim(); if (!customModel) { log('错误: 请先在「配置」中点击「获取模型」或输入模型名称。'); return { answer: null, retryable: false }; } url = providerConfig.buildUrl(customUrl, customModel); headers = providerConfig.buildHeaders(apiKey); data = JSON.stringify(providerConfig.buildPayload(messages, customModel, { nativeSearch: Boolean(searchContext?.useNativeInChat) })); } const res = await gmRequest({ method: 'POST', url, headers, data, timeout: 22000 }); if (!res.ok) { const retryable = Boolean(res.networkError || res.timeout || res.status === 429 || res.status >= 500); log(`API 请求失败 (${res.status || res.statusText})。`); return { answer: null, retryable }; } try { const responseData = JSON.parse(res.text); const rawContent = providerConfig.parseResponse(responseData); const answer = extractAnswerLetters(rawContent, options, type); if (!answer) { const snippet = String(rawContent || responseData?.message || '空内容').replace(/\s+/g, ' ').slice(0, 80); log(`AI 返回未能提取有效选项(原始片段: ${snippet})`); return { answer: null, retryable: true }; } return { answer, retryable: false }; } catch (e) { log(`解析 API 响应失败: ${e.message}`); return { answer: null, retryable: true }; } } async function callAiApi(question, options, type, aiMode, opts = {}) { let searchContext = { results: [], source: 'off', useNativeInChat: false }; if (!opts.skipSearch) { searchContext = await runWebSearch(question, aiMode); if (searchContext.results.length > 0) { log(`联网搜索 [${searchContext.source}] 命中 ${searchContext.results.length} 条参考。`); } } log('正在请求 AI 回答...'); const retryDelays = [1500, 3000, 5000]; let result = await callAiApiOnce(question, options, type, aiMode, searchContext); for (let i = 0; i < retryDelays.length && !result.answer && result.retryable; i++) { const waitMs = retryDelays[i]; log(`第 ${i + 1} 次退避重试(${waitMs / 1000} 秒后)...`); await waitForActiveTime(waitMs); const ctx = i >= 1 ? { results: [], source: 'off', useNativeInChat: false } : searchContext; result = await callAiApiOnce(question, options, type, aiMode, ctx); } if (!result.answer && aiMode === 'free') { log('提示:免费代理节点可能出现临时 502/拥堵,建议在「配置」中填写自有 AI Key 以获得稳定极速体验。'); } if (result.answer) log(`AI 回答: ${result.answer}`); return result.answer; } async function runWithConcurrency(items, concurrency, worker, shouldAbort = null) { const results = new Array(items.length); let cursor = 0; async function runner() { while (cursor < items.length) { if (shouldAbort && shouldAbort()) break; const idx = cursor++; results[idx] = await worker(items[idx], idx); } } const workers = Array.from({ length: Math.min(concurrency, Math.max(1, items.length)) }, () => runner()); await Promise.all(workers); return results; } function parseBatchAiResponse(rawContent, batchItems) { const resultMap = new Map(); if (!rawContent) return resultMap; const cleaned = String(rawContent) .replace(/[\s\S]*?<\/think>/gi, ' ') .replace(/```(?:json)?\s*([\s\S]*?)```/gi, '$1') .trim(); const byIndex = new Map(batchItems.map(it => [String(it.questionNumber), it])); const recordAnswer = (key, rawAns) => { const target = byIndex.get(String(key || '')); if (!target) return; const letters = extractAnswerLetters(rawAns, target.optionsText, target.questionType); if (letters) resultMap.set(String(target.questionNumber), letters); }; // 1. 尝试完整 JSON 数组或 JSON 对象 const jsonMatch = cleaned.match(/(\[[\s\S]*\]|\{[\s\S]*\})/); if (jsonMatch) { try { const parsed = JSON.parse(jsonMatch[0]); if (Array.isArray(parsed)) { for (const entry of parsed) recordAnswer(entry?.index, entry?.answer); } else if (parsed && typeof parsed === 'object') { for (const [k, v] of Object.entries(parsed)) recordAnswer(k, v); } if (resultMap.size > 0) return resultMap; } catch (e) { /* 尝试截断抢救与紧凑格式 */ } } // 2. 抢救被截断的 JSON 数组片段 const partialJsonRegex = /\{\s*"index"\s*:\s*"?(\d+)"?\s*,\s*"answer"\s*:\s*"([^"]*)"/g; let pm; while ((pm = partialJsonRegex.exec(cleaned)) !== null) { recordAnswer(pm[1], pm[2]); } if (resultMap.size > 0) return resultMap; // 3. 紧凑格式与行式格式(如 "1:A 2:BC"、"1: A, B 2: C"、"1. A、B、D\n2. 正确"、"第1题:A/B/C") const compactRegex = /(?:第\s*)?(\d+)\s*(?:题)?\s*[::.、\-]\s*(对|错|正确|错误|[A-Za-z](?:[ \t,,、/与和]*[A-Za-z])*)(?=\s*(?:(?:第\s*)?\d+\s*(?:题)?\s*[::.、\-]|[\r\n.;;,,]|$))/g; let cm; while ((cm = compactRegex.exec(cleaned)) !== null) { recordAnswer(cm[1], cm[2]); } return resultMap; } async function callAiApiBatch(batchItems, aiMode, shouldAbort = null) { const effectiveProviderKey = aiMode === 'free' ? 'zhipu' : providerSelect.value; const blocks = batchItems.map(item => { const lines = [`【第${item.questionNumber}题】(${item.questionType})`, `题干:${item.questionTitle}`]; lines.push(`选项:\n${item.optionsText.map((opt, idx) => `${String.fromCharCode(65 + idx)}. ${opt}`).join('\n')}`); if (item.searchContext?.results?.length) { lines.push(`联网参考:\n${item.searchContext.results.map((r, i) => `${i + 1}. ${r.title}: ${r.snippet}`).join('\n')}`); } return lines.join('\n'); }).join('\n\n'); const sysPrompt = '你是一个严格按格式输出的答题引擎。禁止输出任何思考过程、分析、解释或开场白。严格按「题号:大写字母」输出并用空格分隔,例如:1:A 2:BC 3:A。单选/判断只输出1个对应所给选项顺序的大写字母,多选输出字母拼接。'; const userPrompt = `请一次性作答以下 ${batchItems.length} 道题:\n\n${blocks}\n\n严格按 1:A 2:BC 格式直接输出结果:`; const messages = [ { role: 'system', content: sysPrompt }, { role: 'user', content: userPrompt } ]; let url, headers, data, providerConfig; const batchMaxTokens = Math.max(512, batchItems.length * 120); if (aiMode === 'free') { url = 'https://api.coren.xin/zhipu-free-proxy'; headers = { 'Content-Type': 'application/json' }; data = JSON.stringify({ messages, temperature: 0, max_tokens: batchMaxTokens, thinking: { type: 'disabled' } }); providerConfig = API_PROVIDERS.zhipu; } else { const apiKey = apiKeyInput.value.trim(); const customUrl = apiUrlInput.value.trim(); const customModel = apiModelInput.value.trim(); providerConfig = API_PROVIDERS[effectiveProviderKey]; if (!apiKey || !providerConfig || !customModel) return new Map(); url = providerConfig.buildUrl(customUrl, customModel); headers = providerConfig.buildHeaders(apiKey); const payload = providerConfig.buildPayload(messages, customModel, { nativeSearch: batchItems.some(it => it.searchContext?.useNativeInChat) }); if (payload.max_tokens) payload.max_tokens = batchMaxTokens; if (payload.generationConfig) payload.generationConfig.maxOutputTokens = Math.max(payload.generationConfig.maxOutputTokens || 0, batchMaxTokens); data = JSON.stringify(payload); } const retryDelays = [1500, 3000, 5000]; let parseRetryCount = 0; for (let attempt = 0; attempt <= retryDelays.length; attempt++) { if (shouldAbort && shouldAbort()) return new Map(); const res = await gmRequest({ method: 'POST', url, headers, data, timeout: 30000 }); if (shouldAbort && shouldAbort()) return new Map(); if (res.ok && res.text) { let snippet = ''; try { const responseData = JSON.parse(res.text); const rawContent = providerConfig.parseResponse(responseData); snippet = String(rawContent || responseData?.message || '空内容').replace(/\s+/g, ' ').slice(0, 80); const parsedMap = parseBatchAiResponse(rawContent, batchItems); if (parsedMap.size > 0) return parsedMap; } catch (e) { snippet = res.text.replace(/\s+/g, ' ').slice(0, 80); } log(`批量 AI 返回无法解析 (HTTP 200),原始片段: ${snippet || '空'}`); if (parseRetryCount >= 1) break; parseRetryCount++; await waitForActiveTime(1500); if (shouldAbort && shouldAbort()) return new Map(); continue; } if (attempt < retryDelays.length) { const retryable = res.networkError || res.timeout || res.status === 429 || res.status >= 500; if (!retryable) break; log(`批量 AI 请求波动 (${res.status || res.statusText}),${retryDelays[attempt] / 1000} 秒后重试...`); await waitForActiveTime(retryDelays[attempt]); if (shouldAbort && shouldAbort()) return new Map(); } } return new Map(); } function normalizeDomText(el) { return String(el?.textContent || '').replace(/\s+/g, ' ').trim(); } function extractQuestionData(qContainer) { const questionType = normalizeDomText(qContainer?.querySelector('.quest-type')) || '单选题'; const questionTitle = normalizeDomText(qContainer?.querySelector('.quest-title .option-name')); const optionsElements = qContainer ? Array.from(qContainer.querySelectorAll('.el-radio, .el-checkbox')) : []; const optionsText = optionsElements.map(el => normalizeDomText(el.querySelector('.preStyle'))); return { questionType, questionTitle, optionsElements, optionsText }; } function collectBatchQuestionsFromDom(questionItems) { const examItems = Array.from(document.querySelectorAll('.exam-item')); if (examItems.length !== questionItems.length) return null; const collected = []; for (let i = 0; i < questionItems.length; i++) { const qEl = questionItems[i]; if (qEl.classList.contains('violet')) continue; const questionNumber = qEl.textContent.trim(); const qContainer = examItems[i]?.querySelector('.question-item'); const { questionType, questionTitle, optionsElements, optionsText } = extractQuestionData(qContainer); if (!questionTitle || optionsElements.length === 0 || optionsText.some(o => !o)) return null; collected.push({ questionNumber, questionType, questionTitle, optionsText }); } return collected; } function buildAnswerCacheKey(question, options, type) { const mode = modeSelect.value; const providerKey = providerSelect.value; const modelName = apiModelInput.value.trim(); const norm = (s) => String(s || '').replace(/\s+/g, ' ').trim(); return `${mode}|${providerKey}|${modelName}|${searchModeSelect.value}|${norm(type)}|${norm(question)}|${options.map(norm).join('||')}`; } async function getAnswer(question, options, type) { const mode = modeSelect.value; const providerKey = providerSelect.value; const modelName = apiModelInput.value.trim(); const cacheKey = buildAnswerCacheKey(question, options, type); if (answerCache.has(cacheKey)) { const cached = answerCache.get(cacheKey); log(`命中本页会话缓存答案: ${cached}`); return cached; } let answer = null; if (mode === 'quizbank') { const bankAnswer = findInQuizBank(question); if (bankAnswer) { log(`答案来自题库: ${bankAnswer}`); answer = bankAnswer; } else if (fallbackAiCheckbox.checked) { log('题库未命中,执行 AI Fallback...'); const customKey = apiKeyInput.value.trim(); const aiModeToUse = (customKey && API_PROVIDERS[providerKey] && modelName) ? 'custom' : 'free'; log(`Fallback AI 模式: ${aiModeToUse}`); answer = await callAiApi(question, options, type, aiModeToUse); } else { log('题库未命中,且未开启 AI Fallback。'); } } else { answer = await callAiApi(question, options, type, mode); } if (answer) setCacheWithLimit(answerCache, cacheKey, answer); return answer; } // --- 14. 答题页、结算页与列表页核心逻辑 --- async function processTestPage(epoch = runEpoch) { const isStale = () => !autoMode || epoch !== runEpoch; log('进入答题页面,开始处理...'); let firstQuestionReady = false; for (let attempt = 1; attempt <= 2 && !isStale(); attempt++) { try { await waitForQuestionChange('1', attempt === 1 ? 10000 : 5000, isStale); firstQuestionReady = true; break; } catch (e) { log(`第 1 题加载等待第 ${attempt} 次失败: ${e.message}`); } } if (isStale()) return; if (!firstQuestionReady) { toggleAutoMode(false, '连续等待第 1 题超时,请检查页面加载后再继续。'); return; } const questionItems = document.querySelectorAll('.answer-card .list .item'); log(`共 ${questionItems.length} 道题。`); if (questionItems.length === 0) { toggleAutoMode(false, '未识别到答题卡题目,已暂停以免误提交。'); return; } // 尝试一次性批量采集全部未答题并合并发给 AI,大幅提速 let usedBatchPrefetch = false; const batchCandidates = collectBatchQuestionsFromDom(questionItems); if (batchCandidates && batchCandidates.length >= 2) { const mode = modeSelect.value; const providerKey = providerSelect.value; const modelName = apiModelInput.value.trim(); const customKey = apiKeyInput.value.trim(); const needAiList = []; for (const item of batchCandidates) { const cKey = buildAnswerCacheKey(item.questionTitle, item.optionsText, item.questionType); if (answerCache.has(cKey)) continue; if (mode === 'quizbank') { const bankAns = findInQuizBank(item.questionTitle); if (bankAns) { setCacheWithLimit(answerCache, cKey, bankAns); continue; } if (!fallbackAiCheckbox.checked) continue; } needAiList.push({ ...item, cacheKey: cKey }); } if (needAiList.length >= 2) { const aiModeToUse = mode === 'quizbank' ? ((customKey && API_PROVIDERS[providerKey] && modelName) ? 'custom' : 'free') : mode; if (aiModeToUse) { log(`已一次性采集 ${needAiList.length} 道未答题,正在并发联网并批量请求 AI...`); await runWithConcurrency(needAiList, 3, async (it) => { if (isStale()) return; it.searchContext = await runWebSearch(it.questionTitle, aiModeToUse); }, isStale); if (isStale()) return; const batchResultMap = await callAiApiBatch(needAiList, aiModeToUse, isStale); if (isStale()) return; if (batchResultMap.size > 0) { usedBatchPrefetch = true; for (const it of needAiList) { const ans = batchResultMap.get(it.questionNumber); if (ans) setCacheWithLimit(answerCache, it.cacheKey, ans); } log(`批量预答完成:一次性成功获取 ${batchResultMap.size}/${needAiList.length} 题答案,开始快速作答...`); } else { log('批量预答未成功解析,自动回退逐题作答模式...'); } } } } const unansweredQuestionNumbers = new Set(); for (const questionEl of questionItems) { if (isStale()) { log('自动答题已停止或页面已切换。'); return; } const ocsCheck = refreshOcsPolicyStatus(); if (ocsCheck.shouldYield) { toggleAutoMode(false, `${ocsCheck.reason},已自动避让暂停。`); return; } if (questionEl.classList.contains('violet')) { log(`第 ${questionEl.textContent.trim()} 题已完成,跳过。`); continue; } const questionNumber = questionEl.textContent.trim(); log(`开始处理第 ${questionNumber} 题...`); if (!questionEl.classList.contains('active')) reliableClick(questionEl); try { await waitForQuestionChange(questionNumber, 7000, isStale); if (isStale()) return; await waitForActiveTime(300); if (isStale()) return; const visibleExamItem = Array.from(document.querySelectorAll('.exam-item')).find(el => el.offsetHeight > 0); const questionContainer = visibleExamItem?.querySelector('.question-item') || document.querySelector('.exam-item:not([style*="display: none"]) .question-item'); const { questionType, questionTitle, optionsElements, optionsText } = extractQuestionData(questionContainer); if (!questionTitle || optionsElements.length === 0 || optionsText.some(option => !option)) { log('错误: 无法解析题目或选项,标记为未完成并跳过。'); unansweredQuestionNumbers.add(questionNumber); continue; } log(`题目 (${questionType}): ${questionTitle}`); const answer = await getAnswer(questionTitle, optionsText, questionType); if (isStale()) return; const answerText = String(answer || '').trim().toUpperCase(); const answerLetters = answerText.replace(/[^A-Z]/g, ''); const requestedIndices = [...new Set([...answerLetters].map(char => char.charCodeAt(0) - 65))]; const answerIsValid = answerLetters.length > 0 && answerLetters.length === answerText.length && requestedIndices.length === answerLetters.length && requestedIndices.every(index => index >= 0 && index < optionsElements.length) && ((questionType !== '单选题' && questionType !== '判断题') || requestedIndices.length === 1); if (!answerIsValid) { log('未获得有效答案,跳过此题;本轮不会自动提交。'); unansweredQuestionNumbers.add(questionNumber); } else { log(`尝试选择答案: ${answerLetters}`); const requestedIndexSet = new Set(requestedIndices); const isOptionSelected = (el) => { const input = el.querySelector('.el-radio__original, .el-checkbox__original'); return Boolean(input?.checked) || el.classList.contains('is-checked'); }; const applySelection = async () => { const selectedBefore = new Set(optionsElements .map((el, index) => isOptionSelected(el) ? index : -1) .filter(index => index >= 0)); for (const optionIndex of selectedBefore) { if (requestedIndexSet.has(optionIndex)) continue; const inputElement = optionsElements[optionIndex].querySelector('.el-radio__original, .el-checkbox__original'); if (inputElement) reliableClick(inputElement); } for (const optionIndex of requestedIndices) { if (selectedBefore.has(optionIndex)) continue; const inputElement = optionsElements[optionIndex].querySelector('.el-radio__original, .el-checkbox__original'); if (inputElement) reliableClick(inputElement); else { log(`错误:找不到选项 ${String.fromCharCode(65 + optionIndex)} 的内部 input 元素。`); unansweredQuestionNumbers.add(questionNumber); } await waitForActiveTime(180); } }; await applySelection(); let selectedAfter = new Set(optionsElements .map((el, index) => isOptionSelected(el) ? index : -1) .filter(index => index >= 0)); let selectionMatches = selectedAfter.size === requestedIndexSet.size && [...requestedIndexSet].every(index => selectedAfter.has(index)); if (!selectionMatches) { log(`答案选择未通过页面状态校验(预期 ${requestedIndices.map(index => String.fromCharCode(65 + index)).join('、')},页面实际选择 ${[...selectedAfter].map(index => String.fromCharCode(65 + index)).join('、') || '无'})。`); unansweredQuestionNumbers.add(questionNumber); } } if (!usedBatchPrefetch && (modeSelect.value === 'free' || (modeSelect.value === 'quizbank' && fallbackAiCheckbox.checked))) { log('避免 API 速率限制,等待 2 秒...'); await waitForActiveTime(2000); if (isStale()) return; } } catch (err) { if (isStale()) return; log(`处理第 ${questionNumber} 题时出错: ${err.message}, 标记为未完成并跳过。`); unansweredQuestionNumbers.add(questionNumber); } } if (isStale()) return; if (unansweredQuestionNumbers.size > 0) { const numbers = [...unansweredQuestionNumbers].join('、'); toggleAutoMode(false, `第 ${numbers} 题未答或未通过选择校验,已暂停;请人工检查后再提交。`); return; } const submitButton = document.querySelector('.submit'); if (!submitButton || submitButton.disabled) { toggleAutoMode(false, '未找到可用的提交按钮,请人工检查页面。'); return; } if (isAutoSubmitEnabled()) { log('自动提交已开启:题目全部完成且校验通过,直接提交,不弹确认框。'); } else { log('所有题目均已选择并通过页面状态校验,等待人工确认提交...'); if (!window.confirm('题目已处理完成。请确认答案后,是否提交本次练习?')) { toggleAutoMode(false, '提交未获人工确认,练习保持未提交状态。'); return; } log('已按人工确认准备提交。'); } reliableClick(submitButton); log('已触发提交,等待结算页面...'); } function waitForQuestionChange(qNum, timeout = 7000, shouldAbort = null) { log(`正在等待第 ${qNum} 题加载...`); return new Promise((resolve, reject) => { const intervalTime = 200; const startedAt = getActiveTime(); let cancelNextPoll = null; const poll = () => { if (shouldAbort && shouldAbort()) { if (cancelNextPoll) cancelNextPoll(); resolve(); return; } if (getActiveTime() - startedAt >= timeout) { if (cancelNextPoll) cancelNextPoll(); reject(new Error(`等待第 ${qNum} 题超时`)); return; } const answerCardItem = Array.from(document.querySelectorAll('.answer-card .list .item')).find(item => item.textContent.trim() === qNum); if (answerCardItem && answerCardItem.classList.contains('active')) { const visibleExamItem = Array.from(document.querySelectorAll('.exam-item')).find(el => el.offsetHeight > 0); const questionContainer = visibleExamItem?.querySelector('.question-item'); const titleElement = questionContainer?.querySelector('.quest-title .option-index'); const displayedQuestionNumber = titleElement?.textContent?.trim().match(/^\d+/)?.[0]; if (displayedQuestionNumber === String(qNum)) { log(`第 ${qNum} 题加载成功!`); resolve(); return; } } cancelNextPoll = scheduleActiveTimeout(poll, intervalTime); }; poll(); }); } function readExerciseResultSummary() { const scoreText = document.querySelector('.charts-label-rate')?.textContent?.trim() || ''; const scoreMatch = scoreText.match(/(\d+(?:\.\d+)?)\s*%/); const score = scoreMatch ? Number(scoreMatch[1]) : null; const counts = new Map(); for (const counter of document.querySelectorAll('.line1-count-total')) { const label = counter.querySelector('.line1-count-total-title')?.textContent?.trim(); const valueText = counter.querySelector('.line1-count-total-num')?.textContent?.trim() || ''; const valueMatch = valueText.match(/\d+/); if (label && valueMatch) counts.set(label, Number(valueMatch[0])); } const total = counts.get('总题数'); const correct = counts.get('已答对'); if (!Number.isFinite(score) || !Number.isFinite(total) || !Number.isFinite(correct)) return null; return { score, total, correct }; } async function processResultsPage(epoch = runEpoch) { const isStale = () => !autoMode || epoch !== runEpoch; if (isStale()) return; log('进入结算页面,等待读取掌握度和答题统计...'); const settleStartedAt = getActiveTime(); let resultSummary = null; while (!isStale() && getActiveTime() - settleStartedAt < 10000) { resultSummary = readExerciseResultSummary(); if (resultSummary) break; await waitForActiveTime(250); } if (isStale()) return; if (resultSummary) { log(`结算结果已读取:掌握度 ${resultSummary.score}%,答对 ${resultSummary.correct}/${resultSummary.total} 题。`); } else { log('等待 10 秒仍未识别结算统计;只记录为本轮已尝试,不推断为提交成功或已掌握。'); } markActiveMasteryItemAttempted(resultSummary); log('结算检查完成,继续返回掌握度页面。'); const backButtonStartedAt = getActiveTime(); let backButton = null; while (!isStale() && getActiveTime() - backButtonStartedAt < 10000) { backButton = document.querySelector('.backup-icon'); if (backButton) break; await waitForActiveTime(250); } if (isStale()) return; if (backButton) { reliableClick(backButton); log('已返回掌握度页面,等待状态刷新...'); } else { toggleAutoMode(false, '结算页 10 秒内未出现返回按钮,请人工检查提交结果。'); } } function findMatchingPopoverButton(targetItemName) { const targetClean = targetItemName.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ''); const targetSuffix = targetClean.slice(-20); const allButtons = document.querySelectorAll('.el-popover .el-button, .mastery-box-custom-popover .el-button, .custom-content .el-button, .el-popper .el-button'); for (const btn of allButtons) { if (!btn.textContent.includes('提升掌握度') && !btn.textContent.includes('去提升')) continue; const popover = btn.closest('.el-popover, .el-popper, .mastery-box-custom-popover'); const popoverNameEl = popover?.querySelector('.name') || popover?.querySelector('strong.name') || popover?.querySelector('strong'); const popoverName = popoverNameEl?.textContent?.trim() || ''; const popoverClean = popoverName.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ''); if (targetSuffix && !popoverClean.includes(targetSuffix)) continue; return { btn, popoverName }; } return null; } async function findAndScrollToIncompleteItem(epoch = runEpoch) { const isStale = () => !autoMode || epoch !== runEpoch; await waitForActiveTime(1000); if (isStale()) return; const stopCondition = stopConditionSelect.value; const eligibleSelector = stopCondition === 'gray' ? '.item-box.gray' : '.item-box.gray, .item-box.pink'; const eligibleItems = Array.from(document.querySelectorAll(eligibleSelector)); const pendingItems = eligibleItems.filter(item => !attemptedMasteryItems.has(getMasteryItemKey(item))); const targetItem = pendingItems[0] || null; const logMessage = stopCondition === 'gray' ? '遗漏点' : '遗漏/薄弱点'; log(`待处理${logMessage} ${pendingItems.length} 个;本页已提交过 ${attemptedMasteryItems.size} 个知识点。`); if (!targetItem) { if (eligibleItems.length > 0) { toggleAutoMode(false, `剩余 ${eligibleItems.length} 个${logMessage}本轮均已尝试但仍未达标,已停止自动重复;请先核对各点结算结果。`); } else { log(`未找到${logMessage},任务已完成。`); toggleAutoMode(false); } return; } const targetItemKey = getMasteryItemKey(targetItem); const itemName = targetItem.querySelector('.item-box-name_text, .item-box-name')?.textContent?.trim() || '未知'; log(`选中项目: "${itemName}"`); targetItem.scrollIntoView({ behavior: 'smooth', block: 'center' }); await waitForActiveTime(500); document.body.click(); await waitForActiveTime(100); document.querySelectorAll('.el-popover, .el-popper, .mastery-box-custom-popover').forEach(p => { p.style.display = 'none'; p.setAttribute('aria-hidden', 'true'); }); await waitForActiveTime(200); const triggerElement = targetItem.querySelector('.el-tooltip__trigger') || targetItem; const isMasteryPage = window.location.href.includes('/study/mastery'); let popoverButton = null; if (isMasteryPage) { log('Mastery 模式: 按卡片顺序匹配对应弹窗...'); const match = getMasteryPopoverForItem(targetItem); if (!match) { toggleAutoMode(false, '无法将所选卡片与唯一弹窗可靠对应,已暂停以避免练错知识点。'); return; } const { itemIndex, popover, popoverName } = match; const btn = popover.querySelector('.el-button'); if (!btn || (!btn.textContent.includes('提升掌握度') && !btn.textContent.includes('去提升'))) { toggleAutoMode(false, `第 ${itemIndex + 1} 张卡片未找到可用练习入口,已暂停。`); return; } popoverButton = btn; popover.style.display = 'block'; popover.style.visibility = 'visible'; popover.style.opacity = '1'; popover.setAttribute('aria-hidden', 'false'); log(`卡片序号 ${itemIndex + 1} 与弹窗标题“${popoverName}”一一匹配。`); } else { reliableClick(triggerElement); } const maxWaitTime = 2000; const checkInterval = 100; if (!popoverButton) { await waitForActiveTime(500); if (isStale()) return; const firstWaitStartedAt = getActiveTime(); while (!isStale() && getActiveTime() - firstWaitStartedAt < maxWaitTime) { await waitForActiveTime(checkInterval); if (isStale()) return; const found = findMatchingPopoverButton(itemName); if (found) { popoverButton = found.btn; log(`弹窗匹配成功: "${found.popoverName.substring(0, 25)}"`); break; } } } if (!popoverButton) { if (isStale()) return; log('首次点击未触发匹配弹窗,再次尝试...'); await waitForActiveTime(300); if (isStale()) return; reliableClick(triggerElement); await waitForActiveTime(500); if (isStale()) return; const retryWaitStartedAt = getActiveTime(); while (!isStale() && getActiveTime() - retryWaitStartedAt < maxWaitTime) { await waitForActiveTime(checkInterval); if (isStale()) return; const found = findMatchingPopoverButton(itemName); if (found) { popoverButton = found.btn; log(`重试弹窗匹配成功: "${found.popoverName.substring(0, 25)}"`); break; } } } if (isStale()) return; if (popoverButton) { log('已找到【提升掌握度/去提升】按钮,正在点击...'); await waitForActiveTime(300); if (isStale()) return; writeSessionStorage(getActiveItemStorageKey(), targetItemKey); reliableClick(popoverButton); log('已点击进入练习页面!'); } else { toggleAutoMode(false, '未能打开该知识点的练习入口,请人工检查页面后继续。'); } } function requestMainLoop(delay = 0) { if (!autoMode) return; if (mainLoopRunning) { mainLoopPending = true; return; } if (mainLoopTimer) mainLoopTimer(); mainLoopTimer = scheduleActiveTimeout(() => { mainLoopTimer = null; mainLoop(); }, delay); } async function mainLoop() { if (!autoMode) return; if (mainLoopRunning) { mainLoopPending = true; return; } const ocsCheck = refreshOcsPolicyStatus(); if (ocsCheck.shouldYield) { toggleAutoMode(false, `${ocsCheck.reason},已自动避让暂停。`); return; } mainLoopRunning = true; const epoch = runEpoch; try { const pageKind = detectPageKind(); if (pageKind === 'mastery') { await findAndScrollToIncompleteItem(epoch); } else if (pageKind === 'exam') { await processTestPage(epoch); } else if (pageKind === 'result') { await processResultsPage(epoch); } else { toggleAutoMode(false, '当前页面不在掌握度支持范围内,已暂停。'); } } catch (error) { if (epoch === runEpoch) { toggleAutoMode(false, `主流程异常:${error.message}`); } } finally { mainLoopRunning = false; if (mainLoopPending && autoMode) { mainLoopPending = false; requestMainLoop(500); } } } function updateAutoModeButton() { startButton.textContent = autoMode ? '停止自动答题' : '开始自动答题'; startButton.className = `btn ${autoMode ? 'btn-danger' : 'btn-dark'}`; updateStatusBar(); } function toggleAutoMode(start, reason = '') { runEpoch++; autoMode = Boolean(start); writeSessionStorage(getAutoModeStorageKey(), autoMode ? '1' : '0'); refreshHostVisibility(); updateAutoModeButton(); refreshOcsPolicyStatus(); if (autoMode) { interruptBanner.classList.add('hidden'); startBackgroundKeepalive(); log('自动答题已开始(后台防冻结保活已启动)!'); requestMainLoop(0); } else { stopBackgroundKeepalive(); if (mainLoopTimer) { mainLoopTimer(); mainLoopTimer = null; } mainLoopPending = false; log(reason ? `自动答题已暂停:${reason}` : '自动答题已停止。'); if (reason) notifyInterruption(reason); } } // --- 15. 路由变化监听(History Hook + 按需显隐) --- function syncCourseContext() { const queryCourseId = new URLSearchParams(window.location.search).get('recruitAndCourseId'); const pageKind = detectPageKind(); let nextRunId = currentCourseRunId; if (queryCourseId) { nextRunId = queryCourseId; hasExplicitCourseId = true; } else if (!hasExplicitCourseId && pageKind === 'mastery') { nextRunId = window.location.pathname; } if (nextRunId === currentCourseRunId) return; currentCourseRunId = nextRunId; attemptedMasteryItems = new Set(readSessionArray(getAttemptedItemsStorageKey()).filter(isCurrentMasteryItemKey)); if (autoMode) { writeSessionStorage(getAutoModeStorageKey(), '1'); } else { autoMode = readSessionStorage(getAutoModeStorageKey()) === '1'; } updateAutoModeButton(); } let lastUrl = location.href; function handleRouteChange() { const url = location.href; if (url === lastUrl) return; lastUrl = url; runEpoch++; if (!document.title.startsWith('【需处理】')) { originalTitle = document.title; } syncCourseContext(); log(`页面路由已变化: ${location.pathname}`); refreshHostVisibility(); refreshOcsPolicyStatus(); if (autoMode) requestMainLoop(1200); } ['pushState', 'replaceState'].forEach((methodName) => { const original = history[methodName]; if (typeof original === 'function') { history[methodName] = function (...args) { const ret = original.apply(this, args); setTimeout(handleRouteChange, 0); return ret; }; } }); window.addEventListener('popstate', handleRouteChange); window.addEventListener('hashchange', handleRouteChange); setInterval(() => { if (location.href !== lastUrl) handleRouteChange(); else refreshHostVisibility(); }, 1500); // 仅供自动化测试导入纯函数 if (window.__ZHS_TEST_MODE__ === true && typeof GM_info === 'undefined') { window.__ZHS_TEST_EXPORTS__ = { extractAnswerLetters, detectPageKind, parseBatchAiResponse, API_PROVIDERS, syncCourseContext, refreshOcsPolicyStatus, fetchQuizBank, scheduleActiveTimeout, fetchAvailableModels, runWithConcurrency, callAiApiBatch, runWebSearch, waitForQuestionChange, triggerProviderChange: (provider) => { providerSelect.value = provider; handleProviderChange(); }, getCurrentCourseRunId: () => currentCourseRunId, getAttemptedCount: () => attemptedMasteryItems.size, getQuizBankLength: () => quizBank.length, getApiModelValue: () => apiModelInput.value, setProviderAndModel: (provider, url, key, model) => { providerSelect.value = provider; apiUrlInput.value = url; apiKeyInput.value = key; apiModelInput.value = model; }, setSearchMode: (mode) => { searchModeSelect.value = mode; }, setOcsConflictMode: (mode) => { ocsConflictSelect.value = mode; }, getOcsConflictMode: () => ocsConflictSelect.value, OCS_EXCLUDE_RULES, setQuizBankUrl: (url) => { quizbankUrlInput.value = url; }, getModelSelectList: () => modelSelectList }; } async function onPageReady() { refreshHostVisibility(); log('AI 答题脚本 v2.3.0 已加载。'); refreshOcsPolicyStatus(); if (GM_getValue('answer_mode', 'free') === 'quizbank' && GM_getValue('quizbank_url', '')) { await fetchQuizBank(); } if (autoMode) { log('检测到本标签页上次运行状态,正在恢复任务...'); requestMainLoop(1200); } } if (document.readyState === 'complete') setTimeout(onPageReady, 0); else window.addEventListener('load', onPageReady, { once: true }); })();