diff --git a/PRIVACY.md b/PRIVACY.md index 95d14b4d..1b1ce89b 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -3,7 +3,7 @@ MoonDigest 的隐私政策。适用于 Chrome 应用商店版和 GitHub 发布的 zip 包。 - 设置、分拣结果、备注和对话都存在浏览器本地。API Key 也存在本地,不会出现在任何导出文件里。 -- 插件只连这些地方:B站和 YouTube、你配置的 AI 平台、你本机的 Obsidian。允许读取网页以后,侧边栏开着时会在本机读它跟随的每个网页的正文;只有你提问或点 AI 总结时,正文才发给你选的 AI 平台。没有作者的服务器,没有统计。 +- 插件只连这些地方:B站和 YouTube、你配置的 AI 平台、你本机的 Obsidian。允许读取网页以后,侧边栏开着时会在本机读它跟随的每个网页的正文;只有你提问或点 AI 总结时,正文才发给你选的 AI 平台。分拣台的收藏夹打开「联网核实」时,字幕细看由 DeepSeek 的服务器去搜索网页,插件自己不访问别的网站。没有作者的服务器,没有统计。 - B站 和 YouTube 视频页上的网页脚本(包括你用的 AI agent)可以向插件要这个视频的信息、字幕、章节和热门评论,这些都是网站本来就给这个页面的数据。 - 设置 → MCP 的「允许 Agent 使用我的 B站和 YouTube 账号」默认关闭。打开后,插件会连本机 `127.0.0.1:47823` 上的 MCP 服务(`mcp/`),你在本机运行的 AI 工具就能通过它用你的登录读和改下面这些。见 README 的「给 AI agent 用」。 - 能读:B站 和 YouTube 的视频搜索结果;视频的信息、字幕、章节、热门评论和画面;你 B站 的收藏夹和里面的视频、稍后再看、关注和分组、观看历史,连同分拣台的标签、备注、AI 判断和判断标准;你 YouTube 的稍后观看、赞过的视频、订阅、历史记录和 YouTube 播放列表。 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f5378425..5e495b26 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -23,7 +23,8 @@ B站 页面上的颜色是 `tokens.css` 的第三份拷贝:`content.css` 里 - 内置播放框下的标签行只有一种写法:`TriageUi.viewerLine`,行名用第 3/4 行的 `labeledRow`。收藏夹的「视频标签」行在 `fav-tags.js`,「UP 标签」行在 `follow.js`,收藏夹每次画完自己那行就通过 `MoonTriage.setViewerHook` 让关注重画 UP 那行;B站 自动连播换了视频时(`fav-page.js` 的 `showViewing`),关注也在这个 hook 里把 `F.viewing` / `F.viewingMid` 换成新视频。 - 后台(`background.js` 的 service worker)也加载 `tag-core.js` 和 `shared.js`,日期、时长、标签名清洗和关注分组名的上限与检查(`GROUP_NAME_MAX`、`groupNameError`)直接用 `TriageUi`,不在 `triage-bg.js`、`follow-bg.js` 里另写。弹窗也加载 `shared.js`,时长用 `TriageUi.fmtDuration`。笔记、弹窗和视频页共用的去句尾标点只在 `sites.js`(`trimReason`)。视频上下文的字段(标题、地址、站点和视频 id、分 P、选中的字幕)怎么整理也只在这里:`MdgSites.contextRef`,后台写笔记、读上下文和侧边栏存对话、画占位上下文都用它;它的网址(去掉专注模式和跟踪参数、带分 P)只由 `MdgSites.videoUrl` 拼,笔记、后台和视频页都用它。标签名最长几个字只有 `MdgTagCore.TAG_NAME_MAX`,各个标签名输入框都读它。B站 页面的标记开关默认值读 `MdgSettings.DEFAULTS`。加载顺序以 `background.js` 的 `importScripts` 为准,后台的 selftest 照它读;侧边栏、摘读记录页和视频页的 selftest 同样照 `sidepanel.html`、`history/history.html` 和 manifest 里 `content.js` 那一项读,不手写脚本清单。 - 「✦ AI 打标签」的后台只有一份:`triage-bg.js` 的 `triageAiCommand`(指令检查、新建上限按 `numSetting("newTagMax")` 取值、解析)。关注只把 UP 主整理成条目,带上自己的 unit 调它。摘读记录页自己把记录整理成条目(`history.js` 的 `aiItem`:标题、视频还是网页、现有标签和对话的问答,按 `TriageUi.READING_AI_CHARS` 截;没有对话的带分拣台的 AI 总结和备注),发 `triage-reading-ai-tag`,后台带 `READING_AI_UNIT` 调它;条目按 `id`(`MdgNote.readingKey`)认,没有 `id` 的按 `bvid`(`triageItemId`)。摘读记录的批次也走 `runs.js`(`history.html` 加载它,页面自己一个实例,没有胶囊,倒计时写在弹窗和状态文字里),用同一个 `MdgRuns.aiJudge`:限流倒计时重发、超时重发一次、设置类错误停下给「去设置」或「授权」。它的设置存在 sync 的 `KEYS.readingAiSettings`,读法和关注的 `follow_ai_settings` 同一个(`FollowCore.followAiSettings`:第一次用时照搬 `triage-settings-get` 的收藏夹值并存下,之后只读自己的),所以 `history.html` 也加载 `follow-core.js`;建议和「AI 刚打的」存在 local 的 `readingAiProposal` / `readingAiRecent`,U 的步骤只在页面内存里(`tag-store.js` 自己的栈,最多 `TRIAGE_UNDO_STEPS` 步)。设置行的样式(`.set-row` 等)在 `tags.css`,三个设置弹窗共用。 -- 选哪个 AI 平台只有一处记:侧边栏顶部的选择存在扩展页面的 `localStorage`(`MdgLimits.KEYS.aiSelectedProvider`)。分拣台的每个请求由 `fav-base.js` 的 `sendRaw` 带上它(`aiProviderId`),后台的 `triageChat`(`triageProvider`)用它,没选或已停用就用第一个启用的平台,和侧边栏一样。收藏夹设置的「开启思考」显示不显示也跟着它:每次打开收藏夹设置都重新问一次 `triage-settings-get`,侧边栏换了平台不用重开分拣台。 +- AI 平台在选项里怎么写只有一处:`MdgSettings.aiProviderLabel`(备注名 `note`,没有就「平台 · 模型」),侧边栏的下拉框和分拣台都用它。平台配置的字段由后台 `normalizeAiProvider` 整理,设置页 `collectAiProviders` 收,`note` 和别的字段一样随设置文件导出导入。 +- 选哪个 AI 平台只有一处记:侧边栏顶部的选择存在扩展页面的 `localStorage`(`MdgLimits.KEYS.aiSelectedProvider`)。分拣台的每个请求由 `fav-base.js` 的 `sendRaw` 带上它(`aiProviderId`),后台的 `triageChat`(`triageProvider`)用它,没选或已停用就用第一个启用的平台,和侧边栏一样。打开具体收藏夹时,存过判断标准弹窗的收藏夹用自己的记录:`fav-base.js` 的 `K.folderAi`(`triage_folder_ai`,local,`{ [mediaId]: { providerId, thinking, search } }`,和 `folderCriteria` 一样经 `storeEdit` 读改写),`aiReq` 把 `aiProviderId` 和 `thinking` 放进粗看、细看、AI 打标签的请求,`sendRaw` 不再拿侧边栏的覆盖它。「所有收藏夹」是这两份记录里的一个 id(`ALL`):在它里面 `aiReq` 和 `searchWanted` 一律取它自己的记录(`aiFolder`),不取视频所在收藏夹的;判断标准取它自己的,空着才取视频所在收藏夹的(`critOf`),粗看、细看的请求和 `staleCoarse` / `staleFine` 都走这一处。后台 `triageAiSettings` 只在平台能开关思考时用页面给的 `thinking`,没带时用旧的全局 `triageThinking`(它的开关已去掉,只剩这个回落用途)。平台能做什么只由后台 `background.js` 的 `aiCaps`(`{ thinking, search }`)判断:`triage-settings-get` 回 `aiPlatforms`(启用的平台和各自的 `caps`),页面照着画、按同样的回落规则选中(`folderAiOf`),设置里的平台列表变了就重问一次。联网核实只在细看:`triage-analyze` 带 `search`,后台 `triageChat` 只在 `aiCaps(provider).search` 时加 `tools: [{ type: "deepseek_web_search" }]` 和提示词里那一句(`TRIAGE_SEARCH_PROMPT`),超时用思考那一档;结果记 `search: true`,页面的 `staleFine` 据此把收藏夹开着联网时没联网做的细看算作旧结果。`finish_reason` 为 `content_filter` 时报「AI 平台的内容审核拦下了这次回复」。 - 分拣台的长任务只有一个循环:`extension/triage/runs.js`(`MdgRuns.create`),每种模式一个实例(`fav-base.js` 和 `follow.js` 的 `runs`)。粗看、细看、AI 打标签(两种模式和摘读记录,`MdgTagStore` 的 `runAi`)、逐个视频笔记、「已出分拣范围」的核对、两边改 B站 的批量写和关注「视频投稿」的限流等待都是它的 `run` 或 `wait`:一个任务名同一时间只跑一个(第二个被拒并报出在跑的名字)、请求之间留间隔、限流时倒计时再重发同一个请求、暂停 / 停止 / 切换收藏夹在间隔和倒计时里立即生效、做完的个数由它数。每个回答怎么算由任务的 `judge` 定:AI 的超时和限流怎么数只有 `MdgRuns.aiJudge`(每次跑各数各的),粗看、细看、AI 打标签和摘读记录的 AI 打标签共用;等不等按这次运行实例的 `hold`(分拣台是 `THROTTLES`,细看遇到 B站 限流也等)。例外:「所有收藏夹」的加载(`runLoadAll`)两条队列会轮换、暂停后能接着跑,留着自己的循环,只用 `runs.wait` 等限流。 - 进度胶囊只从它画:`runs.pill(顺序)` 取第一个在跑、在等或有行的任务,都没有再取跑完留下的绿色结果行;等限流时一律在进度后面接「· B站限流卡住,m:ss 后重试」。别处来的状态(关注的后台刷新和它的「B站限流变慢」、观看进度、刷新中、标签建议待确认、「所有收藏夹」的加载)用 `runs.put` 放一行进去。收藏夹的顺序是 `fav-base.js` 的 `PILL`,按钮是 `PILL_BTN`;关注的在 `follow.js` 的 `renderSync` 旁边。第 3 行的「暂停粗看 N/M」也读 `runs.get`。 - 限流等多久只有 `hold`:收藏夹是 `fav-base.js` 的 `THROTTLES`(`MoonTriage.hold`),关注的 B站限流是 90 秒的 `TriageUi.BILI_HOLD_MS`。后台的队列暂停(`follow_jobs.hold`、`follow_hold`)和观看进度的 30 分钟来自后台存储,不走它。`runs.selftest.js` 在 node 里用假时钟测它。 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 73e7e066..ad09b347 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -68,6 +68,8 @@ | 存储用量里各收藏夹视频列表那一行 | 收藏夹快照 | 收藏夹列表缓存 | 2026-10-23:存的是每个收藏夹的视频快照,不是收藏夹列表 | | 设置页「B站页面上显示什么」里管没单列的页面那一行 | 首页、搜索和其他页面(热门、分区、番剧等都归它) | 首页、搜索(单写) | 2026-10-23:单写让人以为别的页面不受这一行管 | | 关注设置、摘读记录设置里隔开 AI 打标签每批的秒数 | AI 打标签每批间隔(收藏夹设置里同一个数还隔开 B站 请求,叫「请求间隔」) | 请求间隔(关注、摘读记录) | 2026-10-23:关注的刷新不按它隔开 | +| 字幕细看时让 AI 平台上网查内容是否过时或有误 | 联网核实(判断标准弹窗里的开关;只有 DeepSeek 的 deepseek-flash 支持) | 联网搜索、联网(作开关名时) | 说的是用途:核实内容,不是让 AI 随便搜 | +| AI 平台配置上自己起的名字 | 备注名(设置页「AI 平台」每行一格,可选;侧边栏和分拣台的平台选项写它,不填时写「平台 · 模型」,模型空着时只写平台) | 别名、昵称 | 同一个平台配两个 Key 时分得开 | | 侧边栏和摘读记录写成单独一篇 AI 笔记时结果后面的说明 | (单独的 AI 笔记) | (视频已失效,只写了对话) | 视频失效时也是同一种文件,里面还有 AI 总结和备注 | 下面的时间格式管的是分拣台。 @@ -185,7 +187,9 @@ AI 打标签的建议在应用或放弃前一直存着,刷新或重开分拣 - 选中的都被筛选隐藏时,选中栏照样列出这一页的按钮,灰掉并写「选中的都被筛选隐藏了」,按钮上的个数是选中的个数(「保留选中的 2 个」,不写 0),两种模式一样;选中的都不能做这一步时(都已处理过、都已取消关注、都还关注着)也写选中的个数,灰掉写原因(「选中的都已经处理过了」「选中的都已取消关注」);只隐藏了一部分时写看得见的个数,也就是点了会处理的那些。选中栏开头同样:只隐藏了一部分时写「已选中 N 个」(看得见的)、后面灰字「另有 M 个被筛选隐藏」;都被隐藏时写「已选中 M 个」(全部)、后面灰字「都被筛选隐藏」,不写「已选中 0 个」。只要有选中(看不看得见都算),所有按钮都对着选中:第 3 行不出「取消收藏(AI:可清理)N 个」这类按 AI 判断的批量按钮,「标题粗看选中的 N 个」「清理选中的 N 个」这类写选中的个数并灰掉写同一句,不改成对着列出的视频。为什么:按钮突然消失会让人以为选中没了;有选中时动了没选的,会让人以为动的是选中的。 - 改 B站 的批量在跑时,每个改 B站 的按钮都灰掉(批量的、卡片上的 ★、重新关注、取消关注),原因写出在跑的是什么:「取消关注还在跑,等它完成」「批量取消收藏还在跑,等它完成」,不做成能点、点了才提示,两种模式一样。「清理」只删 MoonDigest 的记录、不碰 B站,但删的正是这些批量要写的取消收藏和取关记录,所以也灰掉(第 3 行的和卡片上的)。只改本地标签的(选中栏的「标签…」、T、卡片上的「+ 标签」)不受影响。 - 关注的「已出分拣范围」照收藏夹的做:左栏最下面、分隔线下,0 个时隐藏(开着时照样显示),悬停说明是什么;标题「已出分拣范围 · N」,信息行先写各有几个(「8 个已注销 · 31 个投稿已清空」)再写「不在关注分拣里了,标签都还留着,清理前可先从「导出」菜单备份」,不显示「在 B站打开」;已取消关注的 UP 主卡片上的标签和收藏夹「已出分拣范围」的视频一样,点一下去掉、按 U 放回(标签存在取关记录里);排序是它自己的,多一个「离开时间」并默认按它(新的在前,还关注着的没有离开时间,排在后面);进出它时清空选中、页签和筛选,刷新页面后不停在这里,回到「全部」;第 2 行页签是离开的原因:全部 / 已取消关注 / 已注销 / 投稿已清空,换页签清空选中;第 3 行是全部、在哪取消关注(全部和已取消关注页签才有)、未打标签 已打标签,第 4 行标签照常。卡片多一行写分组和离开原因(「原在「数码」 10月5日 在 B站取消关注」「在「默认分组」 账号已注销」「投稿已清空:…播放过 N 次」);已取消关注的卡片有「重新关注」和红色「清理」,还关注着的有红色「取消关注」。第 3 行右边是「清理这 N 个 / 清理选中的 N 个」,选中栏是「重新关注选中的」「取消关注选中的」。取消关注和清理是两层,照收藏夹的取消收藏和清理:取消关注只改 B站,记录和标签都留着;清理只删 MoonDigest 的记录(连标签),不碰 B站,先确认,不能撤销,所以只对已取消关注的人;还关注着的清理按钮灰掉,写「还关注着的先取消关注,再清理」,取消关注的确认框也写「不想留记录的也在那里清理」。为什么:只清理不取关,下次刷新人又回来了;合成一个按钮,以后有了关注记录页又得拆开。取关时记下当时的分组(取关记录里),重新关注时放回还在的分组,放不回时说出原因(人在默认分组,按 U 撤销会取消关注、记录照原样放回);这之前取关的人没有分组记录。已注销 = 关注列表里名字是「账号已注销」,或查投稿时 B站 说用户不存在;投稿已清空 = 投稿一个都没有、但视频播放量大于 0(被封、被下架或自己删光,B站 不说是哪种)。这两种还关注着,但不在「全部」、各分组和它们的计数里;以后又有投稿或恢复了,下次刷新自动回去;投稿已清空的人又有了视频叫「UP 回归」,刷新结果写「UP 回归 +N」,展开是「UP 回归:原本投稿已清空、现在又能看到视频」。没投过稿(播放量也是 0)的照常留在列表里。为什么:清理停更 UP 时这些人没什么可分的,混在里面还会让批量改分组撞上注销账号。 -- 「所有收藏夹」里也能标题粗看、字幕细看、「按新标准重新粗看 / 细看」和重试失败的。每个视频按它所在收藏夹的判断标准判断,重复收藏的视频按收藏夹列表里排最前的那个(左栏顺序)。第 3 行没有「判断标准」按钮;点这几个按钮先弹出和按钮同名的弹窗(重试的写「全部重试」「重试选中的 N 个」这类),列出这次涉及的每个收藏夹、视频数和它的判断标准(可改,存法和「判断标准」弹窗一样),按钮写「开始粗看 N 个」,取消什么都不做。粗看一批只发同一个收藏夹的视频。 +- 「所有收藏夹」里也能标题粗看、字幕细看、「按新标准重新粗看 / 细看」和重试失败的。它当作一个收藏夹,有自己的一份设置:第 3 行有「判断标准」按钮,弹窗标题写「判断标准 ·「所有收藏夹」」,判断标准、AI 平台、开启思考、联网核实都存在它自己名下。AI 平台、开启思考、联网核实在这里一律用它自己的(没保存过就和没保存过的收藏夹一样),不跟视频所在的收藏夹。它自己写了判断标准时,这里每个视频都按这一份判断,点粗看、细看直接开始;「按新标准重新粗看 / 细看」也按这一份和它自己的联网核实算。结果按视频存、不按视图存:在这里按它的判断标准做过的视频,回到所在收藏夹会算作按旧标准做的,反过来也一样。2026-11-15 用户定:「所有收藏夹的视图,本身就是一个收藏夹的概念」。它自己没写判断标准时(弹窗写「不写时,每个视频按它所在收藏夹的判断标准判断。」,按钮上没有橙点),每个视频按它所在收藏夹的判断标准判断,重复收藏的视频按收藏夹列表里排最前的那个(左栏顺序);这时点这几个按钮先弹出和按钮同名的弹窗(重试的写「全部重试」「重试选中的 N 个」这类),列出这次涉及的每个收藏夹、视频数和它的判断标准(可改,存法和「判断标准」弹窗一样),按钮写「开始粗看 N 个」,取消什么都不做。粗看一批只发同一个收藏夹的视频。 +- 判断标准弹窗左边是判断标准,右边是这个收藏夹的「AI 平台」(单选,每个启用的平台一行,有备注名时备注名在上、小字「平台 · 模型」在下)、「开启思考」和「联网核实」。三项只对这个收藏夹生效:点「保存」就记成这个收藏夹自己的,此后和侧边栏无关;没保存过的收藏夹用侧边栏选中的平台(没有就用第一个启用的)和以前的思考设置、不联网。记下的平台被删或停用时用第一个启用的,弹窗在平台列表上方写明原来选的已删除或停用。平台不支持某一项时那个开关灰掉,说明换成「‹选项文字›不支持开关思考」「‹选项文字›不支持联网」;已开着的保留,开关画成斜纹,说明后面加「已开启的设置保留,换回支持的平台后生效」,请求里不发。平台列表最多显示约 5 行,多了在列表里滚动,两个开关一直看得见;有两个以上平台时每行后面写「思考」「联网」支不支持(指着开关时对应那一列加深),只有一个平台时不画这两列;没配平台时写「没有启用的 AI 平台」和「去设置」。换平台或开关思考不算改了判断标准,不问要不要重新粗看。「所有收藏夹」里的粗看、细看和 AI 打标签用「所有收藏夹」自己的这三项。2026-11-15 用户定。 +- 联网核实只作用于字幕细看,标题粗看和 AI 打标签不联网。收藏夹开着联网核实、平台也支持时,没联网做的细看结果算旧结果,和判断标准改了一样能「按新标准重新细看」;保存弹窗时因此多出旧结果,就问「联网核实打开了」。关掉联网核实不算。2026-11-15 用户定。 - 「✦ AI 打标签」在「所有收藏夹」里按收藏夹分开打:每个收藏夹用自己的标签和新建名额,重复收藏的视频在每个收藏夹各打一次;进度写「「想学的技能」第 2/3 批」。可用标签同名的合成一个片,点掉就是这个名字在每个收藏夹都不给 AI 用。新标签建在提出它的收藏夹,确认页在后面写「建在「X」」,两个收藏夹的同名新标签分开勾选。整次一个建议、一次应用、一步撤销。「标签管理」和选中栏的「标签…」仍只在具体收藏夹里。 - 关注会记住左栏选的是哪一项。 @@ -246,7 +250,7 @@ AI 打标签的建议在应用或放弃前一直存着,刷新或重开分拣 - 「待查」一直显示,0 时变淡。为什么:以前它一消失,后面的片就跟着挪位。 - 「全选」放在右边按钮组最前面,是三态勾选。为什么:条件片出现或消失时它不动。 - 多选不用开关:点卡片就是选中,点标题才是播放。为什么:分拣时选比看多,第一次选不用去找藏着的勾选框。 -- 「所有收藏夹」的 AI 判断按每个视频排在最前的收藏夹的判断标准,AI 打标签按收藏夹分开打。为什么:一次请求只带一份判断标准、一个收藏夹的标签;同一个视频在两个收藏夹里各有一套标签。 +- 「所有收藏夹」自己没写判断标准时,AI 判断按每个视频排在最前的收藏夹的判断标准;AI 打标签按收藏夹分开打。为什么:一次请求只带一份判断标准、一个收藏夹的标签;同一个视频在两个收藏夹里各有一套标签。 - 打标签面板是一种样子,收藏夹、关注和摘读记录共用:筛选框在上,标签等宽三列在下,放不下的名字截断,悬停看全名;没有「完成」和说明文字,按 Esc 或点外面就保存。从任何卡片和播放框的「+ 标签」打开时都贴着按钮弹出,不写标题;从选中栏的「标签…」打开时是居中弹窗,写标题,部分有的写「N 个有」。B站 页面的「+ UP 标签」面板是同一种样子和键盘,只差两处:点一下马上写入,不等关闭(B站 页面可能随时跳转);底部多一行「在分拣台「关注」里打开这个 UP 主 ↗」和「只存在 MoonDigest 里,不改 B站」。标签满了时写明原因。2026-10-30 用户定。标签颜色在每个地方都一样:圆点是标签色,勾选后圆点留色、✓ 画在里面,底色和边框按标签色淡化。为什么:标签名短,一行放一个浪费地方;等宽对齐才能预判方向键落在哪。2026-10-30 用户定 - 打标签面板的键盘:筛选框为空时,1–9 和 0 勾选前 10 个(0 是第 10 个,键盘上 0 在 9 后面),方向键在三列里走;开始筛选后没有编号,数字是文字,↑↓ 走结果,回车勾选或新建。名字以数字开头时先按空格,编号消失,空格不进名字。10 个以内顺序固定,超过 10 个常用的排前面,顺序在打开时定住,勾选不挪位置,新建的排最后。2026-10-30 用户定 - 「标签管理」和「✦ AI 打标签」是两个弹窗、两个按钮,放在标签行右边;两种模式用同一份组件。为什么:一个按钮只做一件事;收藏夹的标签按收藏夹分,放左栏会被当成全局的。 diff --git a/docs/FAQ.md b/docs/FAQ.md index 7b8ef2d8..38f6ad01 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -28,4 +28,4 @@ YouTube 短时间内收到太多请求时会暂时拒绝。插件会稍等重试 在 Obsidian 社区插件里装好 **Local REST API with MCP**,打开 **Enable Non-encrypted (HTTP) Server**(地址一般是 `http://127.0.0.1:27123`),复制 API Key,填进设置页「Obsidian」一节,打开「启用写入 Obsidian」,点「测试连接」。 **侧边栏的回答有没有用「思考」?** -用 DeepSeek、智谱和 Kimi 时,侧边栏对话和测试连接会关闭思考。分拣台是否思考由设置里的「开启思考」开关决定。 +用 DeepSeek、智谱和 Kimi 时,侧边栏对话和测试连接会关闭思考。分拣台是否思考由每个收藏夹判断标准里的「开启思考」决定。 diff --git a/docs/TRIAGE.md b/docs/TRIAGE.md index 735602a3..2178db85 100644 --- a/docs/TRIAGE.md +++ b/docs/TRIAGE.md @@ -12,7 +12,7 @@ └─ 标签 ───▶ 入门 进阶 办公 ``` -- **判断标准**:「✎ 判断标准」按钮,没写时带一个小点。不写时,AI 从收藏夹名和简介推测用途。改了标准以后,按旧标准做的结果可以「按新标准重新粗看 / 细看」。 +- **判断标准**:「✎ 判断标准」按钮,没写时带一个小点。不写时,AI 从收藏夹名和简介推测用途。改了标准以后,按旧标准做的结果可以「按新标准重新粗看 / 细看」。同一个弹窗里还能给这个收藏夹选 AI 平台、开关思考和联网核实(字幕细看时让 DeepSeek 上网查内容是否过时或有误,只有 deepseek-flash 支持;打开后,没联网做的细看可以「按新标准重新细看」):保存后只对这个收藏夹生效;没保存过的收藏夹用侧边栏选中的平台。换平台或开关思考不算改了判断标准。 - **标签**属于各自的收藏夹,每个收藏夹默认最多 10 个(收藏夹设置里可改,1–50),一个视频可以打多个。标签那一行的「标签管理」里改名、写说明、删除,**✦ AI 打标签** 用一句话让 AI 给一批视频打标签(每次默认最多新建 5 个,收藏夹设置里可改),你检查后再应用。改标签和应用都能按 U 撤销,你之后又改过的视频不动。 - 两层互不影响:打标签不算处理,AI 判断也不改你的标签。 @@ -35,7 +35,7 @@ - 细看时视频没有字幕,AI 按简介和热门评论判断,卡片上标灰色的「无字幕」(没登录 B站时是「未登录无字幕」,字幕下载失败是「字幕抓取失败」,悬停看原因)。第 3 行的「无字幕」筛选能把它们挑出来。 - 粗看、细看、批量取消收藏和移动在切换收藏夹后继续跑,进度显示在进度胶囊里。关掉分拣台页面就暂停。 - 标题粗看和字幕细看有选中时只跑选中的(最多一批);选中的都不能跑时按钮灰掉,不改跑下一批。AI 回复出错的视频标「分析失败」排在最后,可以逐个或整批重试;Key、余额、连不上这类 AI 平台的问题会停下并提示去设置。 -- 收藏夹设置里能调请求间隔、两步的每批数量和输出上限。分拣台用的是 DeepSeek、智谱或 Kimi 时还有「开启思考」开关:关着快、省;开着判断更细,但慢得多、token 多几倍。 +- 收藏夹设置里能调请求间隔、两步的每批数量和输出上限。「开启思考」在每个收藏夹的判断标准里,只有 DeepSeek、智谱和 Kimi 能开关:关着快、省;开着判断更细,但慢得多、token 多几倍。 ## 选中和批量操作 @@ -53,7 +53,7 @@ ## 其他视图 -- **所有收藏夹**:把勾选的收藏夹合在一起看和搜索。第一次要逐个加载,之后只核对有变化的。AI 粗看、细看和 AI 打标签也能在这里做:每个视频按它排在最前的收藏夹的判断标准判断,标签按收藏夹分开打。批量保留和批量取消收藏也能在这里做,取消收藏时勾选从哪些收藏夹取消。 +- **所有收藏夹**:把勾选的收藏夹合在一起看和搜索。第一次要逐个加载,之后只核对有变化的。AI 粗看、细看和 AI 打标签也能在这里做:它有自己的判断标准、AI 平台、开启思考和联网核实;判断标准没写时,每个视频按它排在最前的收藏夹的判断标准判断。标签按收藏夹分开打。批量保留和批量取消收藏也能在这里做,取消收藏时勾选从哪些收藏夹取消。 - **稍后再看**:和收藏夹一样分拣,卡片上标出在 B站看到了哪里。 - **已出分拣范围**:视频离开了你勾选的所有收藏夹(在 B站取消收藏、移到没勾选的收藏夹、收藏夹被删、或你取消勾选),它的 AI 判断、AI 总结、备注和标签先放这里,不会悄悄丢掉。打开时逐个问 B站这个视频还在哪些收藏夹里(和 B站收藏按钮弹出的是同一份信息,不读没勾选收藏夹的内容),上方页签分「全部」「已取消收藏」「在未勾选收藏夹」「已失效」。也可以按 AI 判断、标签、看完了筛选,选中后收藏到任意收藏夹,或导出后清理。「全部」和「已取消收藏」下面有「最近取消收藏」:每个勾选收藏夹最近取消收藏的视频,点「重新收藏」放回原来的收藏夹,整批取消收藏的可以「这批全部重新收藏」。 - **从 B站刷新**:打开收藏夹时核对 B站的变化,只补有差别的部分。点「刷新」重新读取整个收藏夹。刷新结果列出新增、来自其他收藏夹、已移除和已失效的视频。 diff --git a/extension/background.js b/extension/background.js index 059a40fe..5a680de8 100644 --- a/extension/background.js +++ b/extension/background.js @@ -856,7 +856,8 @@ async function saveSettings(settings) { } // Every setting (收藏夹 and 关注 included) lives in sync, except the 分拣台's folder choice (收藏夹设置) and each folder's -// 判断标准, kept in local beside the data; the file carries those as `local`. The sort is a quick toggle, not a setting. Keys and data stay out of the file. The key filter only guards +// 判断标准, kept in local beside the data; the file carries those as `local`. Each folder's AI platform, 开启思考 and +// 联网核实 (triageFolderAi) are local too and stay out of the file. The sort is a quick toggle, not a setting. Keys and data stay out of the file. The key filter only guards // against a copy left in sync by an older version. const SETTINGS_FILE_VERSION = 1; const { triageIncludedFolders: FOLDERS_KEY, triageFolderCriteria: CRITERIA_KEY } = MdgLimits.KEYS; @@ -935,6 +936,7 @@ function normalizeAiProvider(item) { id, presetId: String(item.presetId || "custom"), name: String(item.name || "").trim() || MdgErrors.LABEL.customAi, + note: String(item.note || "").trim(), baseUrl: MdgSettings.trimBaseUrl(item.baseUrl), model: String(item.model || "").trim(), temperature: typeof item.temperature === "number" ? item.temperature : 0.7, @@ -1171,6 +1173,13 @@ function supportsThinkingToggle(baseUrl) { return /^https?:\/\/(api\.deepseek\.com|open\.bigmodel\.cn|api\.z\.ai|api\.moonshot\.(cn|ai))(\/|:|$)/i.test(String(baseUrl || "")); } +// What a platform can do in 分拣台's requests, said only here (the page draws it from triage-settings-get): 开启思考 where +// it takes the thinking switch; 联网核实 only on DeepSeek's deepseek-flash, the one model its web search tool serves. +function aiCaps(provider) { + const baseUrl = String(provider?.baseUrl || ""); + return { thinking: supportsThinkingToggle(baseUrl), search: /^https:\/\/api\.deepseek\.com(\/|$)/i.test(baseUrl) && provider?.model === "deepseek-flash" }; +} + // The one OpenAI-compatible request every AI call sends (the side panel's streamChat, 测试连接, 分拣台's triageChat): POST // to chat/completions with the key as Bearer (a key pasted with its 「Bearer 」, saved before that was dropped, too). // Thinking is off unless asked, on the platforms that think by default. diff --git a/extension/background.selftest.js b/extension/background.selftest.js index beea086c..6ad98f9d 100644 --- a/extension/background.selftest.js +++ b/extension/background.selftest.js @@ -175,6 +175,7 @@ process.on("exit", (code) => { const src = ["background.js", "triage/triage-bg.js"].map((f) => fs.readFileSync(path.join(__dirname, f), "utf8")).join("\n"); assert.strictEqual(src.match(/await hostPermissionError\(/g).length, 1, "hostPermissionError is asked only in aiFetchError"); assert.strictEqual(ctx.normalizeAiProvider({ id: "x", baseUrl: " https://ai.test/v1// " }).baseUrl, "https://ai.test/v1", "a saved platform's address is trimmed"); + assert.deepStrictEqual([ctx.normalizeAiProvider({ id: "x", note: " 自己的 " }).note, ctx.normalizeAiProvider({ id: "x" }).note], ["自己的", ""], "a saved platform keeps its 备注名"); const timeout = async () => { throw Object.assign(new Error("timeout"), { name: "TimeoutError" }); }; @@ -1064,11 +1065,11 @@ process.on("exit", (code) => { assert.deepStrictEqual(syncLeft, { triageCriteria: "全局" }); // Settings file: everything in sync (收藏夹 and 关注 included), never a key, even one an older version left in sync. - const exportSync = { noteFolder: "X", triageFineBatchSize: 20, follow_ai_settings: { batchSize: 7 }, aiProviders: [{ id: "p", apiKey: "sk-old" }], obsidianApiKey: "leak" }; + const exportSync = { noteFolder: "X", triageFineBatchSize: 20, follow_ai_settings: { batchSize: 7 }, aiProviders: [{ id: "p", note: "自己的", apiKey: "sk-old" }], obsidianApiKey: "leak" }; ctx.chrome = { runtime: { getManifest: () => ({ version: "9" }) }, storage: { sync: area(exportSync), local: area({ obsidianApiKey: "k", aiProviderKeys: { p: "sk" }, triage_included_folders: ["11", "toview"], triage_folder_criteria: { 11: "只留菜谱" }, triage_sort: { 11: "pub" }, triage_tags: [] }) } }; const file = JSON.parse(JSON.stringify(await ctx.exportSettings())); assert.deepStrictEqual([file.kind, file.extensionVersion, file.settings.triageFineBatchSize, file.settings.follow_ai_settings], ["settings", "9", 20, { batchSize: 7 }]); - assert.deepStrictEqual(file.settings.aiProviders, [{ id: "p" }]); + assert.deepStrictEqual(file.settings.aiProviders, [{ id: "p", note: "自己的" }], "a platform's 备注名 goes with it"); assert.ok(!/sk|leak|"k"/.test(JSON.stringify(file)), "no keys in the file"); assert.deepStrictEqual(file.local, { triage_included_folders: ["11", "toview"], triage_folder_criteria: { 11: "只留菜谱" } }, "the 分拣台's folder choice and 判断标准; no sort, no data"); @@ -1080,6 +1081,9 @@ process.on("exit", (code) => { const old = { ...file, settings: { ...file.settings, aiInitialQuickPrompts: ["旧"], obsidianApiKey: "x", aiProviders: [{ id: "p", apiKey: "sk-file" }] } }; await ctx.importSettings(old); assert.ok(!JSON.stringify(importSync).includes("sk-file") && importSync.aiProviders?.[0]?.id === "p", "a provider's key in the file stays out of sync"); + await ctx.importSettings(file); + assert.strictEqual(ctx.normalizeAiProvider(importSync.aiProviders[0]).note, "自己的", "the 备注名 comes back with an imported file"); + await ctx.importSettings(old); assert.deepStrictEqual([importSync.noteFolder, importSync.triageFineBatchSize, importSync.follow_ai_settings], ["X", 20, { batchSize: 7 }]); assert.ok(!("stray" in importSync) && !("aiInitialQuickPrompts" in importSync) && !("obsidianApiKey" in importSync)); assert.ok(importSync.aiPresetPrompts.includes("旧")); diff --git a/extension/limits.js b/extension/limits.js index 7ec7073a..da1ac5b4 100644 --- a/extension/limits.js +++ b/extension/limits.js @@ -84,6 +84,8 @@ // The 分拣台's folder choice and 判断标准: settings kept in local, carried by the settings file. triageIncludedFolders: "triage_included_folders", triageFolderCriteria: "triage_folder_criteria", + // Each folder's AI platform, 开启思考 and 联网核实 (判断标准's 保存). In local, and on purpose not in the settings file. + triageFolderAi: "triage_folder_ai", // 关注 (follow-bg.js writes most of them; the 分拣台, the B站 page's UP tags and the 分拣台 backup read them): follow_ // for list, people, last, last_wip, content, tags, tag_map, unfollowed, jobs, hold, stats, groups, ai_recent, ai_proposal, // ai_history, view (local) and ai_settings (sync). Code names them by the short name; followGet / followFull / diff --git a/extension/limits.selftest.js b/extension/limits.selftest.js index fdaa8cc5..4324d67b 100644 --- a/extension/limits.selftest.js +++ b/extension/limits.selftest.js @@ -80,7 +80,7 @@ const names = Object.values(L.KEYS).filter((v) => typeof v === "string"); // Renaming one loses the data stored under it. assert.deepStrictEqual([...names].sort(), [ "aiProviderKeys", "aiProviders", "follow_", "mdg_ai_conversations_v1", "mdg_ai_selected_provider", "mdg_obsidian_note_paths_v1", "mdg_player_ai_quick_action_v1", "mdg_reading_ai_history_v1", "mdg_reading_ai_proposal_v1", "mdg_reading_ai_recent_v1", "mdg_reading_ai_settings_v1", "mdg_reading_marks_v1", "mdg_subtitle_cache_", - "seen_", "triage_agent_log", "triage_analysis_", "triage_basket", "triage_decisions_", "triage_folder_criteria", "triage_folder_list", "triage_included_folders", "triage_kept", "triage_left", "triage_notes", "triage_removed", + "seen_", "triage_agent_log", "triage_analysis_", "triage_basket", "triage_decisions_", "triage_folder_ai", "triage_folder_criteria", "triage_folder_list", "triage_included_folders", "triage_kept", "triage_left", "triage_notes", "triage_removed", "triage_seen_meta", "triage_snapshot_", "triage_tags", "triage_title_", "triage_video_tags", "triage_zones" ]); assert.strictEqual(L.KEYS.triageDecisions(7), "triage_decisions_7"); diff --git a/extension/messages.js b/extension/messages.js index ae4a6ac0..7479ecc0 100644 --- a/extension/messages.js +++ b/extension/messages.js @@ -91,11 +91,11 @@ "triage-transfer": { from: ["triage/fav-writes.js"], to: TRIAGE_BG, request: ["from", "to", "aids", "move"], response: data }, "triage-title-get": { from: ["triage/fav-folders.js"], to: TRIAGE_BG, request: ["bvids"], response: data }, "triage-analysis-get": { from: ["triage/fav-folders.js"], to: TRIAGE_BG, request: ["bvids"], response: data }, - "triage-classify-titles": { from: ["triage/fav-ai.js"], to: TRIAGE_BG, request: ["items", "criteria", "folder", "aiProviderId"], response: data }, - "triage-analyze": { from: ["triage/fav-ai.js"], to: TRIAGE_BG, request: ["bvid", "force", "criteria", "folder", "aiProviderId"], response: data }, - "triage-ai-command": { from: ["triage/fav-ai.js"], to: TRIAGE_BG, request: ["instruction", "items", "tags", "maxNewTags", "allowRemove", "aiProviderId"], response: data }, + "triage-classify-titles": { from: ["triage/fav-ai.js"], to: TRIAGE_BG, request: ["items", "criteria", "folder", "aiProviderId", "thinking"], response: data }, + "triage-analyze": { from: ["triage/fav-ai.js"], to: TRIAGE_BG, request: ["bvid", "force", "criteria", "folder", "aiProviderId", "thinking", "search"], response: data }, + "triage-ai-command": { from: ["triage/fav-ai.js"], to: TRIAGE_BG, request: ["instruction", "items", "tags", "maxNewTags", "allowRemove", "aiProviderId", "thinking"], response: data }, "triage-reading-ai-tag": { from: ["history/history.js"], to: TRIAGE_BG, request: ["instruction", "items", "tags", "maxNewTags", "allowRemove", "aiProviderId"], response: data }, - "triage-settings-get": { from: ["history/history.js", "triage/fav-page.js", ...FOLLOW], to: TRIAGE_BG, request: ["aiProviderId"], response: data }, + "triage-settings-get": { from: ["history/history.js", "triage/fav-page.js", ...FOLLOW], to: TRIAGE_BG, request: [], response: data }, "triage-settings-save": { from: ["triage/fav-ai.js", "triage/fav-page.js"], to: TRIAGE_BG, request: [], open: "any key of triage-bg.js's TRIAGE_SETTINGS_DEFAULTS", response: data }, "triage-seen-sync": { from: ["badges.js", "triage/fav-folders.js"], to: TRIAGE_BG, request: ["force"], response: data }, "triage-seen-done": { from: [TRIAGE_BG], to: "triage/fav-page.js", request: ["error"], response: [] }, diff --git a/extension/options.css b/extension/options.css index af285be8..f479ce63 100644 --- a/extension/options.css +++ b/extension/options.css @@ -664,7 +664,7 @@ details.adv[open] > summary::before { .ai-provider-row { display: grid; - grid-template-columns: 136px minmax(150px, 1fr) 150px 150px 96px minmax(30px, max-content); + grid-template-columns: 124px 112px minmax(130px, 1fr) 140px 140px 96px minmax(30px, max-content); gap: 8px; align-items: center; } @@ -713,6 +713,10 @@ details.adv[open] > summary::before { font-size: var(--fs-sm); } +.prov > .hint { + margin: 0 0 10px; +} + .ai-later { margin: 6px 0 14px; color: var(--muted); diff --git a/extension/options.html b/extension/options.html index 5a9b6b39..cae0675a 100644 --- a/extension/options.html +++ b/extension/options.html @@ -186,9 +186,10 @@

AI 平台

+

备注名显示在侧边栏和分拣台的平台选项里。不填时显示「平台 · 模型」。

加好平台后,这里会出现系统提示词、AI 总结要求、播放器上的 ✦ AI 总结按钮和快捷追问。

diff --git a/extension/options.js b/extension/options.js index 7210097c..a68e8c4e 100644 --- a/extension/options.js +++ b/extension/options.js @@ -1218,6 +1218,7 @@ function renderAiProviders(items) { function updateAiProvidersEmptyState() { const hasRows = elements.aiProvidersList.children.length > 0; elements.aiProvidersHead.hidden = !hasRows; + elements.aiNoteHint.hidden = !hasRows; // The prompt settings do nothing without a platform, so they wait until a row is added. elements.aiPromptRows.hidden = !hasRows; elements.aiPromptsLater.hidden = hasRows; @@ -1270,6 +1271,7 @@ function addAiProviderRow(item = {}) { +
@@ -1458,6 +1460,7 @@ function collectAiProviders() { id: row.dataset.providerId || generateAiProviderId(), presetId: preset.id, name: preset.name, + note: row.querySelector(".ai-provider-note").value.trim(), baseUrl, model: row.querySelector(".ai-provider-model").value.trim(), temperature: 0.7, diff --git a/extension/options.selftest.js b/extension/options.selftest.js index 45c3d25a..f17dd704 100644 --- a/extension/options.selftest.js +++ b/extension/options.selftest.js @@ -253,6 +253,8 @@ assert.ok(!/seenThreshold\.value = String\((readFormPayload\(\)|payload)\.seenTh const type = (sel, v) => ((parts[sel].value = v), parts[sel].L.input.forEach((f) => f())); type(".ai-provider-baseurl", "https://api.deepseek.com/v2"); assert.strictEqual(page.collectAiProviders()[0].hasSavedKey, true, "another path on the same host keeps the Key"); + parts[".ai-provider-note"].value = " 自己的 "; + assert.strictEqual(page.collectAiProviders()[0].note, "自己的", "the row's 备注名 is saved with it"); // A5: pointed at another host, the saved Key is not counted (save asks for one) and 测试连接 does not use it. parts[".ai-provider-preset"].value = "custom"; diff --git a/extension/settings.js b/extension/settings.js index f1477202..890aef25 100644 --- a/extension/settings.js +++ b/extension/settings.js @@ -166,6 +166,8 @@ return ""; } }; + // An AI platform as its option reads (the side panel's select, 分拣台's 判断标准): its 备注名, else 「平台 · 模型」. + const aiProviderLabel = (p) => text(p?.note) || [text(p?.name), text(p?.model)].filter(Boolean).join(" · "); const normalizeDownloadFormat = (value) => (value === "txt" ? "txt" : "srt"); const normalizePlayerAiQuickPrompt = (value) => text(value); // 快捷追问: trimmed, no blanks or repeats, at most MAX_PRESET_PROMPTS. @@ -301,6 +303,7 @@ normalizeApiKey, trimBaseUrl, urlOrigin, + aiProviderLabel, normalizeFrontmatterField, normalizeDownloadFormat, normalizePlayerAiQuickPrompt, diff --git a/extension/settings.selftest.js b/extension/settings.selftest.js index 0c1e19c2..4c1c3f6c 100644 --- a/extension/settings.selftest.js +++ b/extension/settings.selftest.js @@ -159,4 +159,10 @@ for (const name of ["normalizeAiPresetPrompts", "normalizeApiKey", "normalizeDow for (const file of sources) assert.ok(!new RegExp(`function ${name}\\(`).test(read(file)), `${file} defines ${name} again`); } +// An AI platform's option text, the side panel's and 分拣台's: its 备注名, else 「平台 · 模型」, else the platform alone. +assert.deepStrictEqual( + [{ note: " 自己的 ", name: "DeepSeek", model: "deepseek-flash" }, { note: " ", name: "DeepSeek", model: "deepseek-flash" }, { name: "Ollama (本地)", model: "" }].map(S.aiProviderLabel), + ["自己的", "DeepSeek · deepseek-flash", "Ollama (本地)"] +); + console.log("settings selftest ok"); diff --git a/extension/sidepanel.js b/extension/sidepanel.js index 681ab2b1..74f91ddd 100644 --- a/extension/sidepanel.js +++ b/extension/sidepanel.js @@ -472,8 +472,7 @@ function renderModelSelect(preferredProviderId = "") { els.modelSelect.innerHTML = providers .map((p) => { - const label = String(p.model || p.name || "").trim(); - return ``; + return ``; }) .join(""); @@ -484,7 +483,7 @@ function renderModelSelect(preferredProviderId = "") { syncModelSelectTitle(); } -// The select is narrow, so the full model name lives in its tooltip. +// The select is narrow, so the full option text lives in its tooltip. function syncModelSelectTitle() { els.modelSelect.title = els.modelSelect.selectedOptions[0]?.textContent || ""; } diff --git a/extension/sidepanel.selftest.js b/extension/sidepanel.selftest.js index 9fa3fd3c..2ce8e6ab 100644 --- a/extension/sidepanel.selftest.js +++ b/extension/sidepanel.selftest.js @@ -1139,6 +1139,13 @@ const tick = () => new Promise((r) => setImmediate(r)); ctx.chrome.runtime.sendMessage = async (m) => (m.type === "ai-providers-list" ? { ok: true, providers: [] } : settings); await ctx.loadProvidersAndPrefs(); assert.strictEqual(els.modelSelect.title, "没有启用的 AI 平台"); + // Each option reads as its 备注名, else 「平台 · 模型」 (MdgSettings.aiProviderLabel). + const two = [{ id: "a", name: "DeepSeek", model: "deepseek-flash", note: "自己的", enabled: true }, { id: "b", name: "智谱 GLM", model: "glm", enabled: true }]; + ctx.chrome.runtime.sendMessage = async (m) => (m.type === "ai-providers-list" ? { ok: true, providers: two } : settings); + ctx.localStorage = { getItem: () => "" }; + await ctx.loadProvidersAndPrefs(); + delete ctx.localStorage; + assert.deepStrictEqual([...els.modelSelect.innerHTML.matchAll(/]*>([^<]*) m[1]), ["自己的", "智谱 GLM · glm"]); ctx.chrome.runtime.sendMessage = realSend; vm.runInContext("providers = [{}]; settingsReadFailed = false", ctx); } diff --git a/extension/triage/dev/mock-chrome.js b/extension/triage/dev/mock-chrome.js index 623c077f..8cfe08db 100644 --- a/extension/triage/dev/mock-chrome.js +++ b/extension/triage/dev/mock-chrome.js @@ -323,7 +323,13 @@ }, "triage-settings-get": () => ({ ok: true, - data: { thinkingToggle: true, triageIntervalSec: 1, triageThinking: false, triageTitleMaxTokens: 0, triageAnalyzeMaxTokens: 0, ...store.__settings } + data: { + aiPlatforms: [ + { id: "ds", name: "DeepSeek", model: "deepseek-flash", note: "自己的", caps: { thinking: true, search: true } }, + { id: "zp", name: "智谱 GLM", model: "glm-4.7-flash", note: "", caps: { thinking: true, search: false } }, + { id: "oa", name: "OpenAI 兼容", model: "gpt-6-luna", note: "", caps: { thinking: false, search: false } } + ], + triageIntervalSec: 1, triageThinking: false, triageTitleMaxTokens: 0, triageAnalyzeMaxTokens: 0, ...store.__settings } }), "triage-settings-save": ({ type, ...patch }) => { store.__settings = { ...store.__settings, ...patch }; diff --git a/extension/triage/fav-ai.js b/extension/triage/fav-ai.js index 5db46fcb..b6a51fa1 100644 --- a/extension/triage/fav-ai.js +++ b/extension/triage/fav-ai.js @@ -48,14 +48,14 @@ async function runStage1(list = stage1Pending(), redo = false) { // One request carries one 判断标准: in 所有收藏夹 a batch is the first pending video's folder only. const left = pending(); if (!left.length) return null; - const { home, crit, ctx } = judge.get(left[0].bvid); + const { home, crit, ctx, ai } = judge.get(left[0].bvid); const batch = left.filter((it) => judge.get(it.bvid).home === home).slice(0, TITLES_PER_REQUEST); - return { batch, crit, ctx, n: batch.length }; + return { batch, crit, ctx, ai, n: batch.length }; }, - async act({ batch, crit, ctx }) { + async act({ batch, crit, ctx, ai }) { for (const it of batch) S.analyzing.add(it.bvid); render(); - const r = await send({ type: "triage-classify-titles", items: batch.map(aiItem), criteria: crit, folder: ctx }); + const r = await send({ type: "triage-classify-titles", items: batch.map(aiItem), criteria: crit, folder: ctx, aiProviderId: ai.aiProviderId, thinking: ai.thinking }); for (const it of batch) S.analyzing.delete(it.bvid); return r; }, @@ -117,10 +117,10 @@ function startGroup(bvids, redo = false, name = "") { const groupPending = (group, b) => (group.redo ? group.redo.has(b) : needsAnalysis(b, group)); -async function analyzeOne(bvid, force, { crit, ctx }) { +async function analyzeOne(bvid, force, { crit, ctx, ai }) { S.analyzing.add(bvid); render(); - const r = await send({ type: "triage-analyze", bvid, force, criteria: crit, folder: ctx }); + const r = await send({ type: "triage-analyze", bvid, force, criteria: crit, folder: ctx, aiProviderId: ai.aiProviderId, thinking: ai.thinking, search: ai.search }); S.analyzing.delete(bvid); render(); return r; @@ -366,6 +366,7 @@ async function runAiCommand({ instruction, scope, allowRemove }) { // In 所有收藏夹 a video in no chosen folder has no part: nothing may be left to send. if (!from) return; addAiHistory(instruction); + const ai = aiReq(folder); const partOf = (i) => { const part = parts.findLast((x) => x.from <= i); return [part, i - part.from]; @@ -379,7 +380,7 @@ async function runAiCommand({ instruction, scope, allowRemove }) { request: (i, p) => { const [part, j] = partOf(i); const maxNewTags = Math.max(0, part.opts.maxNewTags - p.newTags.filter((t) => t.folder === part.opts.newTagFolder).length); - return { type: "triage-ai-command", instruction, items: part.payload.slice(j * size, (j + 1) * size), tags: part.tags, maxNewTags, allowRemove }; + return { type: "triage-ai-command", instruction, items: part.payload.slice(j * size, (j + 1) * size), tags: part.tags, maxNewTags, allowRemove, aiProviderId: ai.aiProviderId, thinking: ai.thinking }; }, // not tagIdsOf: the open folder may have changed since the run started merge: (p, data, i) => { diff --git a/extension/triage/fav-base.js b/extension/triage/fav-base.js index 5a2fbf43..9f63ada9 100644 --- a/extension/triage/fav-base.js +++ b/extension/triage/fav-base.js @@ -28,7 +28,8 @@ const K = { lastFolder: "triage_last_folder", folderList: KEYS.triageFolderList, // the page opens from it before it reads B站's list again tags: KEYS.triageTags, // [{ id, name, color, folder, rule? }]: folder is the mediaId the tag belongs to; rule is the one line the AI follows - folderCriteria: KEYS.triageFolderCriteria, // { [mediaId]: 判断标准 } + folderCriteria: KEYS.triageFolderCriteria, // { [mediaId]: 判断标准 }; 所有收藏夹 has its own under ALL + folderAi: KEYS.triageFolderAi, // { [mediaId]: { providerId, thinking, search } }, 所有收藏夹's under ALL: written by 判断标准's 保存; none = the side panel's pick videoTags: KEYS.triageVideoTags, basket: KEYS.triageBasket, zones: KEYS.triageZones, @@ -108,6 +109,7 @@ const S = { loadAll: null, // 所有收藏夹 only: { lists: { [mediaId]: { items, at } }, check, checkTotal, queue, phase (LOAD_ALL_STEPS), error, partial } tags: [], folderCriteria: {}, + folderAi: {}, videoTags: {}, basket: [], notes: {}, @@ -129,7 +131,7 @@ const S = { ...Object.fromEntries(NUM_FIELDS.map(([key, kind]) => [key, TriageUi.numSetting(kind)])), triageThinking: false, triageAiRemoveTags: false, // 批量打 may also take tags off - thinkingToggle: false + aiPlatforms: [] // the enabled AI platforms, { id, name, model, note, caps: { thinking, search } } (the background's aiCaps) }, tab: "none", classFilter: { none: "all", coarse: "all", fine: "all", read: "all" }, // each tab's one pick of 已保留 / 待决定 / an AI verdict; a folder switch resets them @@ -205,21 +207,55 @@ const writeRunning = () => Boolean(runs.get("write")); const criteriaFor = (id) => S.folderCriteria[id] || ""; const criteria = () => criteriaFor(S.mediaId); +// The 判断标准 a video of this home folder is judged under: in 所有收藏夹 its own when written, else the home folder's. +const critOf = (home) => (S.mediaId === ALL && criteriaFor(ALL)) || criteriaFor(home); +// The folder whose AI record (folderAi) a request about folder id runs on: 所有收藏夹 runs on its own, whatever folder a +// video is in. +const aiFolder = (id) => (S.mediaId === ALL ? ALL : id); // The folder a video is judged under: the open one, or in 所有收藏夹 the first chosen folder (list order) it is in. const homeOf = (it) => (S.mediaId === ALL ? S.folders.map((f) => String(f.id)).find((id) => it?.folders?.includes(id)) : String(S.mediaId)); // What the AI is told about a folder; its 判断标准 is relative to this. const folderContext = (id = S.mediaId) => ({ title: folderName(id), intro: S.folderIntro[id] || "" }); +// The fields a request about a folder carries: its own platform, 开启思考 and 联网核实 (folderAi; only 字幕细看 sends search). +// None without a record: the background then takes the side panel's pick (sendRaw), 开启思考's old global value and no +// search. +const aiReq = (id) => { + const r = S.folderAi[aiFolder(id)]; + return r ? { aiProviderId: r.providerId, thinking: r.thinking, search: r.search } : {}; +}; +// A folder's AI as its requests run, the background's fallbacks included: the platform (its own, else the side panel's +// pick, else the first enabled), gone when its own was deleted or disabled; thinking, the switch as stored, and thinkingOn, +// what the request gets (a folder's own only where the platform takes it). +function folderAiOf(id) { + const list = S.settings.aiPlatforms; + const r = S.folderAi[id]; + const want = r ? r.providerId : aiProviderId(); + const provider = list.find((p) => p.id === want) || list[0] || null; + const thinking = r ? r.thinking : Boolean(S.settings.triageThinking); + return { own: Boolean(r), provider, gone: Boolean(r && provider && provider.id !== r.providerId), thinking, thinkingOn: r ? thinking && Boolean(provider?.caps.thinking) : thinking, search: Boolean(r?.search) }; +} // Everything a 粗看 or 细看 request about this video carries, taken when its run starts. const judgeOf = (it) => { const home = homeOf(it); - return { home, crit: criteriaFor(home), ctx: folderContext(home) }; + return { home, crit: critOf(home), ctx: folderContext(home), ai: aiReq(home) }; }; // A 粗看 or 细看 result remembers the 判断标准 it was made under (loadResults stamps older ones with the folder's // current one), so after the criteria change the old results can be redone. const isStale = (r, crit = criteria()) => Boolean(r) && (r.criteria ?? crit) !== crit; const judged = () => S.mediaId && S.mediaId !== REMOVED; -const staleCoarse = () => (judged() ? S.items.filter((it) => !it.invalid && inStage(it, "coarse") && isStale(S.titleRes[it.bvid], criteriaFor(homeOf(it)))) : []); -const staleFine = () => (judged() ? S.items.filter((it) => !it.invalid && inStage(it, "fine") && isStale(S.analyses[it.bvid], criteriaFor(homeOf(it)))) : []); +const staleCoarse = () => (judged() ? S.items.filter((it) => !it.invalid && inStage(it, "coarse") && isStale(S.titleRes[it.bvid], critOf(homeOf(it)))) : []); +// 联网核实 on for the folder (in 所有收藏夹, for 所有收藏夹) and possible on its platform: a 细看 made without it is old +// too, redone like one made under another 判断标准. Turning it off makes none old. +const searchWanted = (id) => { + const a = folderAiOf(aiFolder(id)); + return a.search && Boolean(a.provider?.caps.search); +}; +const staleFineOf = (it) => { + const a = S.analyses[it.bvid]; + const home = homeOf(it); + return isStale(a, critOf(home)) || (Boolean(a) && !a.search && searchWanted(home)); +}; +const staleFine = () => (judged() ? S.items.filter((it) => !it.invalid && inStage(it, "fine") && staleFineOf(it)) : []); const $ = (id) => document.getElementById(id); @@ -244,11 +280,11 @@ const el = {}; "folderSelect", "folderList", "folderHead", "settingsHeading", "settingsFoldersHeading", "settingsAi", "settingsFirstRunHint", "searchInput", "searchCount", "refreshBtn", "activity", "settingsBtn", "helpBtn", "banner", "bannerText", "bannerBtn", "bannerClose", "syncNotice", "syncText", "syncViewBtn", "syncCloseBtn", "syncDetail", "tabs", "stagebar", "sortBox", "classFilter", "tagFilter", "aiTagSlot", "listHeader", "favSel", "list", "basket", "basketToggle", "basketCount", - "basketList", "basketClearBtn", "settingsDialog", "folderToggles", "thinkingRow", "intervalInput", - "coarseBatchInput", "fineBatchInput", "aiBatchInput", "tagLimitInput", "aiNewTagMaxInput", "aiRemoveTagsInput", "openOptionsBtn", "thinkingInput", "titleMaxInput", + "basketList", "basketClearBtn", "settingsDialog", "folderToggles", "intervalInput", + "coarseBatchInput", "fineBatchInput", "aiBatchInput", "tagLimitInput", "aiNewTagMaxInput", "aiRemoveTagsInput", "openOptionsBtn", "titleMaxInput", "titleMaxHint", "analyzeMaxInput", "analyzeMaxHint", "csvBtn", "confirmDialog", "confirmTitle", "confirmBody", "confirmOk", - "criteriaDialog", "criteriaTitle", "criteriaInput", "helpDialog", + "criteriaDialog", "criteriaTitle", "criteriaInput", "criteriaHint", "critAiNote", "critAiList", "critAiNone", "critAiOptions", "critThinking", "critThinkingHint", "critSearch", "critSearchHint", "helpDialog", "biliBtn", "main", "viewer", "viewerCloseBtn", "viewerFrame", "viewerTags", "tools", "writeBtn", "writeDialog", "writeScope", "writeFormat", "writeScopeCount", "writeOverwriteRow", "writeOverwrite", "writeProgress", "writeFailed", "writeStopBtn", "writeSettingsBtn", "writeCopyBtn", "writeRunBtn", "writeMdBtn" ].forEach((id) => (el[id] = $(id))); @@ -266,7 +302,8 @@ function send(msg) { const openOptions = () => send({ type: "open-options" }).then((r) => r.ok || toast(`${MdgErrors.TEXT.settingsOpenFailed}:${MdgErrors.text(r)}`, true)); const showLogin = () => showBanner(MdgErrors.TEXT.biliLogin, "去登录", () => openTab("https://passport.bilibili.com/login"), "login"); // The AI platform picked at the top of the side panel: sidepanel.js keeps it in this extension's localStorage under -// this key (SELECTED_PROVIDER_KEY there). Every request carries it; the background's AI calls use it (triageChat). +// this key (SELECTED_PROVIDER_KEY there). Every request carries it; the background's AI calls use it (triageChat) unless +// the folder has its own (aiReq). const AI_PROVIDER_KEY = KEYS.aiSelectedProvider; // Before the first read: 3.5 and older kept it under the old key prefix. Either page may open first after the update. try { @@ -281,7 +318,8 @@ function aiProviderId() { } const NO_REPLY = "后台无响应"; function sendRaw(msg) { - const id = aiProviderId(); + // A folder's own platform (aiReq) wins over the side panel's pick. + const id = msg.aiProviderId || aiProviderId(); return new Promise((resolve) => { try { chrome.runtime.sendMessage(id ? { ...msg, aiProviderId: id } : msg, (resp) => { @@ -451,11 +489,14 @@ function handleAiError(error, code = "", limit = "粗看") { } else if (aiSettingsCode(code)) { showBanner(text, MdgErrors.LABEL.toSettings, openOptions, "ai"); } else if (code === "AI_TRUNCATED") { - showBanner(`${text}。建议调大${limit}输出上限${hasThinkingToggle() ? "或关闭思考" : ""}`, `打开${SETTINGS_NAME}`, () => openSettings(true), "ai"); + showBanner(`${text}。建议调大${limit}输出上限${canThinkLess() ? "或在判断标准里关闭思考" : ""}`, `打开${SETTINGS_NAME}`, () => openSettings(true), "ai"); } else toast(text, true); } -// Only platforms with the 开启思考 switch in 收藏夹设置 can turn thinking off. -const hasThinkingToggle = () => Boolean(S.settings.thinkingToggle); +// The open folder thinks, on a platform whose thinking can be switched off (判断标准's 开启思考). +const canThinkLess = () => { + const a = folderAiOf(String(S.mediaId)); + return a.thinkingOn && Boolean(a.provider?.caps.thinking); +}; const clearAiBanner = () => { if (el.banner.dataset.kind === "ai") el.banner.hidden = true; }; diff --git a/extension/triage/fav-folders.js b/extension/triage/fav-folders.js index 2b911d43..6825e9fc 100644 --- a/extension/triage/fav-folders.js +++ b/extension/triage/fav-folders.js @@ -80,8 +80,8 @@ function coverHtml(it) { } async function loadTagsAndCriteria() { - const got = await chrome.storage.local.get([K.tags, K.videoTags, K.folderCriteria]); - return { tags: got[K.tags] || [], videoTags: got[K.videoTags] || {}, folderCriteria: got[K.folderCriteria] || {} }; + const got = await chrome.storage.local.get([K.tags, K.videoTags, K.folderCriteria, K.folderAi]); + return { tags: got[K.tags] || [], videoTags: got[K.videoTags] || {}, folderCriteria: got[K.folderCriteria] || {}, folderAi: got[K.folderAi] || {} }; } // The chosen folders other than exceptId, the ones whose cached lists keep a video out of 已出分拣范围. 稍后再看 missing diff --git a/extension/triage/fav-page.js b/extension/triage/fav-page.js index 3ed13c85..d5721ab0 100644 --- a/extension/triage/fav-page.js +++ b/extension/triage/fav-page.js @@ -41,7 +41,7 @@ async function start() { bindEvents(); // Read up front: sidePanel.open must run inside the click's user gesture, before any await. chrome.tabs.getCurrent().then((tab) => (ownTabId = tab?.id)); - const [{ tags, videoTags, folderCriteria }, kept, basket, notes, settingsResp, aiHistory, aiRecent, sortBy, readAt, aiProposals, agentLog, zones] = await Promise.all([ + const [{ tags, videoTags, folderCriteria, folderAi }, kept, basket, notes, settingsResp, aiHistory, aiRecent, sortBy, readAt, aiProposals, agentLog, zones] = await Promise.all([ loadTagsAndCriteria(), storeGet(K.kept, {}), storeGet(K.basket, []), @@ -55,7 +55,7 @@ async function start() { storeGet(K.agentLog, []), storeGet(K.zones, {}) ]); - Object.assign(S, { tags, videoTags, folderCriteria, kept, notes, aiHistory, aiRecent, sortBy, readAt, zones }); + Object.assign(S, { tags, videoTags, folderCriteria, folderAi, kept, notes, aiHistory, aiRecent, sortBy, readAt, zones }); followAgentLog(agentLog, false); S.ai.proposals = aiProposals; pruneAiProposals(); @@ -97,13 +97,15 @@ async function start() { // 收藏夹设置's stored keys. A write from elsewhere (导入设置 on the options page, AI 打标签's switch) is read again here, as // 关注 and 摘读记录 read theirs, so this page runs with it and a later save does not put the old values back. -const SETTING_KEYS = [...NUM_FIELDS.map(([key]) => key), "triageThinking", "triageAiRemoveTags"]; +// The platform list too: 判断标准 draws each one's name and what it can do. +const SETTING_KEYS = [...NUM_FIELDS.map(([key]) => key), "triageThinking", "triageAiRemoveTags", KEYS.aiProviderList]; function followSettings(changes) { if (!SETTING_KEYS.some((k) => changes[k])) return; return send({ type: "triage-settings-get" }).then((r) => { if (!r.ok) return; Object.assign(S.settings, r.data); renderTagLimit(); + if (critAi && el.criteriaDialog.open) renderCritAi(); render(); }); } @@ -127,7 +129,7 @@ function followIncluded(changes) { // Another triage tab wrote one of the lists every page writes whole: take its value, so the next // write here does not put back what it removed. This page's own writes come back as events too and are skipped: an // older one arriving after a newer edit would undo that edit. -const SHARED = { kept: {}, videoTags: {}, tags: [], basket: [], folderCriteria: {}, aiRecent: {} }; +const SHARED = { kept: {}, videoTags: {}, tags: [], basket: [], folderCriteria: {}, folderAi: {}, aiRecent: {} }; function followShared(changes) { let changed = false; for (const [name, empty] of Object.entries(SHARED)) { @@ -556,9 +558,6 @@ function bindEvents() { ); el.settingsBtn.addEventListener("click", () => openSettings()); - for (const input of [el.thinkingInput, el.titleMaxInput, el.analyzeMaxInput]) { - input.addEventListener("input", renderTokenHints); - } el.settingsDialog.addEventListener("click", (e) => { const all = e.target.closest("[data-folders-all]"); if (!all && !e.target.closest("[data-folders-none]")) return; @@ -651,6 +650,17 @@ function bindEvents() { e.preventDefault(); el.criteriaDialog.close("save"); }); + el.critAiList.addEventListener("change", (e) => { + Object.assign(critAi, { providerId: e.target.value, gone: false }); + renderCritAi(); + }); + el.critAiOptions.addEventListener("click", openOptions); + for (const [kind, box] of [["thinking", el.critThinking], ["search", el.critSearch]]) { + box.addEventListener("change", () => { + critAi[kind] = box.checked; + renderCritAi(); + }); + } el.criteriaDialog.addEventListener("close", () => { if (el.criteriaDialog.returnValue === "save") saveCriteria(); }); @@ -680,8 +690,9 @@ function renderTagLimit() { for (const node of document.querySelectorAll("[data-ai-new-tag-max]")) node.textContent = S.settings.triageAiNewTagMax; } +// The automatic caps as the open folder's requests get them (判断标准's 开启思考). function renderTokenHints() { - const on = el.thinkingInput.checked; + const on = folderAiOf(String(S.mediaId)).thinkingOn; // ✦ AI 打标签 takes a number set here; left empty it has its own 自动 per batch (autoMaxTokens "command"). el.titleMaxHint.textContent = `留空 = 自动(${UI.autoMaxTokens("title", TITLES_PER_REQUEST, on)};✦ AI 打标签按每批数量另算),被截断时再调大。填了数时 ✦ AI 打标签也用它。`; el.analyzeMaxHint.textContent = `留空 = 自动(${UI.autoMaxTokens("analyze", 1, on)})`; @@ -690,7 +701,6 @@ function renderTokenHints() { // 收藏夹设置's fields as the values they store; settingsShown is what they held when the dialog opened. const settingsFields = () => ({ ...Object.fromEntries(NUM_FIELDS.map(([key, kind, input]) => [key, UI.numSetting(kind, el[input].value)])), - triageThinking: el.thinkingInput.checked, triageAiRemoveTags: el.aiRemoveTagsInput.checked }); let settingsShown = {}; @@ -705,18 +715,10 @@ function openSettings(scrollToLimits = false, firstRun = false) { el.folderToggles.innerHTML = S.allFolders .map((f) => ``) .join("") || `

${esc(S.foldersRead == null ? "收藏夹列表还没加载" : S.foldersRead ? `读取收藏夹失败:${S.foldersRead}` : NO_FOLDERS)}

`; - el.thinkingRow.hidden = !hasThinkingToggle(); - // The side panel may have switched platform since this page loaded: ask again which one the requests go to. - send({ type: "triage-settings-get" }).then((r) => { - if (!r.ok) return; - S.settings.thinkingToggle = r.data.thinkingToggle; - el.thinkingRow.hidden = !hasThinkingToggle(); - }); el.intervalInput.value = S.settings.triageIntervalSec; el.coarseBatchInput.value = coarseBatchSize(); el.fineBatchInput.value = fineBatchSize(); el.aiBatchInput.value = aiBatchSize(); - el.thinkingInput.checked = Boolean(S.settings.triageThinking); el.titleMaxInput.value = S.settings.triageTitleMaxTokens || ""; el.analyzeMaxInput.value = S.settings.triageAnalyzeMaxTokens || ""; el.tagLimitInput.value = tagLimit(); diff --git a/extension/triage/fav-render.js b/extension/triage/fav-render.js index cc162f00..342b1558 100644 --- a/extension/triage/fav-render.js +++ b/extension/triage/fav-render.js @@ -163,11 +163,13 @@ const favBusyReason = () => UI.busyText(fav.state().busy); // The folder's 判断标准, before the 粗看/细看 button it is for. Written: the text in the tooltip. Not written: the warn -// dot (the AI then guesses from the folder name; the editor's placeholder says so). +// dot (the AI then guesses from the folder name; the editor's hint says so), none in 所有收藏夹, where each video then +// goes by its folder's. function criteriaBtn() { const text = criteria(); + const all = S.mediaId === ALL; const pen = ''; - return ``; + return ``; } // Whether anything in row 3 is on (全部 is pressed when not). @@ -281,7 +283,8 @@ function renderListHeader(list) { // like the step's own button. all: how many the folder has, so the button stays (disabled) while filters hide them. const redoBtn = (act, step, all) => { const { label, why, verb } = redoOf(step); - return all ? headBtn(act, label, "", why, "", `这些视频是按旧的判断标准${verb}的`, false, true) : ""; + const unsearched = step === "fine" && searchWanted(String(S.mediaId)) ? ",或细看时没有联网核实" : ""; + return all ? headBtn(act, label, "", why, "", `这些视频是按旧的判断标准${verb}的${unsearched}`, false, true) : ""; }; const sel = selectedIn(list).length; // A selection, listed or not, decides alone: no AI-verdict batches beside it (all hidden: its buttons say why). @@ -290,8 +293,7 @@ function renderListHeader(list) { // html is what this step does (全部 mixes 粗看 guesses with 细看 conclusions: no class-wide batch, only the selection); // the selection's buttons go to its floating bar (selActs). let html = ""; - // 所有收藏夹 has no one 判断标准 to show: its runs ask for each folder's first (askAllCriteria). - const critBtn = all ? "" : criteriaBtn(); + const critBtn = criteriaBtn(); if (t === "none") { // The criteria the AI reads sits just before the button that sends it. html = critBtn; diff --git a/extension/triage/fav-tags.js b/extension/triage/fav-tags.js index a4b3adb1..11134c25 100644 --- a/extension/triage/fav-tags.js +++ b/extension/triage/fav-tags.js @@ -125,14 +125,63 @@ function renderViewerTags() { const tagPlaying = () => S.viewer?.folders?.length && openPicker(S.viewing, "#viewerTags .tag-plus", S.viewer); // ---------- 判断标准 ---------- +// The dialog's AI side: the folder's platform, 开启思考 and 联网核实 as drafted while it is open ({ providerId, thinking, +// search, gone }); 保存 writes them as the folder's own record (folderAi), whatever they were before. +let critAi = null; +const CAP_TEXT = { + thinking: { hint: "判断更细,但慢得多、token 多几倍。", no: "不支持开关思考" }, + search: { hint: "字幕细看时查内容是否过时或有误,按搜索次数另外计费、更慢。标题粗看不联网。", no: "不支持联网" } +}; +// 所有收藏夹 without a 判断标准 of its own (the dialog's hint and its button's tooltip). +const ALL_CRIT_NONE = "不写时,每个视频按它所在收藏夹的判断标准判断。"; +const KEPT_ON = "已开启的设置保留,换回支持的平台后生效"; + function openCriteria() { el.criteriaTitle.textContent = `判断标准 ·「${folderName(S.mediaId)}」`; el.criteriaInput.value = criteria(); + el.criteriaHint.textContent = S.mediaId === ALL ? ALL_CRIT_NONE : "不写时,AI 按收藏夹名和简介推测。"; + const a = folderAiOf(String(S.mediaId)); + critAi = { providerId: a.provider?.id || "", thinking: a.thinking, search: a.search, gone: a.gone }; + renderCritAi(); el.criteriaDialog.returnValue = ""; el.criteriaDialog.showModal(); el.criteriaInput.focus(); } +// The platform list (one radio per enabled platform; 思考 and 联网 columns only when there is a choice; none: 去设置), the note when +// the folder's own platform is gone, and each switch: off with the reason where the picked platform cannot do it, a +// stored on kept and shown on. +function renderCritAi() { + const list = S.settings.aiPlatforms; + // The drafted platform went away while the dialog was open (deleted on the settings page): the background's fallback. + if (list.length && !list.some((p) => p.id === critAi.providerId)) Object.assign(critAi, { providerId: list[0].id, gone: true }); + const pick = list.find((p) => p.id === critAi.providerId) || null; + const label = (p) => MdgSettings.aiProviderLabel(p); + el.critAiNote.hidden = !critAi.gone; + el.critAiNote.textContent = critAi.gone && pick ? `原来选的 AI 平台已删除或停用,现在用「${label(pick)}」。` : ""; + const cols = list.length > 1; + const cap = (on, cls) => `${on ? "支持" : "—"}`; + el.critAiList.classList.toggle("one", !cols); + el.critAiNone.hidden = list.length > 0; + el.critAiList.innerHTML = + (cols ? '' : "") + + list + .map((p) => { + const sub = p.note ? `${esc([p.name, p.model].filter(Boolean).join(" · "))}` : ""; + const caps = cols ? cap(p.caps.thinking, "t") + cap(p.caps.search, "n") : ""; + const says = `${p.caps.thinking ? "支持" : "不支持"}开关思考,${p.caps.search ? "支持" : "不支持"}联网`; + return ``; + }) + .join(""); + for (const [kind, box, hint] of [["thinking", el.critThinking, el.critThinkingHint], ["search", el.critSearch, el.critSearchHint]]) { + const why = !pick ? MdgErrors.TEXT.aiNone : pick.caps[kind] ? "" : `${label(pick)}${CAP_TEXT[kind].no}`; + box.checked = critAi[kind]; + MdgErrors.setReason(box, why); + hint.textContent = why ? `${why}${pick && critAi[kind] ? `。${KEPT_ON}` : ""}` : CAP_TEXT[kind].hint; + hint.classList.toggle("warn", Boolean(why)); + } +} + // These folders' 判断标准 ([[id, text]]; an empty text removes it), on the page's copy at once and on the stored map by // read-modify-write, so a 判断标准 another tab wrote for its folder stays; the page then takes what was written. function setCriteria(pairs) { @@ -149,15 +198,27 @@ function setCriteria(pairs) { }); } +// One folder's AI record set, on the page's copy at once and on the stored map by read-modify-write, as setCriteria. +function setFolderAi(id, rec) { + const apply = (m) => ((m[id] = rec), m); + apply(S.folderAi); + return storeEdit(K.folderAi, {}, apply).then((m) => { + if (m) S.folderAi = m; + }); +} + async function saveCriteria() { const changed = el.criteriaInput.value.trim() !== criteria(); - await setCriteria([[S.mediaId, el.criteriaInput.value]]); + const searchWas = searchWanted(String(S.mediaId)); + // No platform to pick: nothing to record, the folder keeps following the side panel. + const ai = critAi?.providerId && { providerId: critAi.providerId, thinking: critAi.thinking, search: critAi.search }; + await Promise.all([setCriteria([[S.mediaId, el.criteriaInput.value]]), ai && setFolderAi(String(S.mediaId), ai)]); render(); // Asked whenever 粗看完成 has stale ones, filters or not. Its button is row 3's 按新标准重新粗看 (listed ones, the // selection first, one batch), disabled with the same why when that has none. While an AI step runs it could not // start, so a toast says what to do once it ends instead of a dialog that can only be cancelled. const stale = staleCoarse().length; - if (!changed || !stale) return; + if (!changed || !stale) return askSearchRedo(searchWas); if (aiBusyStep()) return toast(`有 ${stale} 个视频是按旧标准粗看的,等${aiBusyStep()}跑完,点「按新标准重新粗看」就能更新`); const open = redoCoarseOpen(); const { batch, label, why } = redoOf("coarse"); @@ -168,11 +229,24 @@ async function saveCriteria() { label, { reason: why } ); - if (ok) runStage1(batch, true); + if (ok) startJudging(label, "重新粗看", batch, () => runStage1(batch, true)); +} + +// 联网核实 just turned on (and possible on the folder's platform) leaves the 细看 made without it old: asked as a changed +// 判断标准 asks for 粗看, with 细看完成's own redo button. +async function askSearchRedo(searchWas) { + const stale = staleFine().length; + if (searchWas || !searchWanted(String(S.mediaId)) || !stale) return; + if (aiBusyStep()) return toast(`有 ${stale} 个视频细看时没有联网核实,等${aiBusyStep()}跑完,点「按新标准重新细看」就能更新`); + const open = redoFineListed(); + const { batch, label, why } = redoOf("fine"); + const shown = open.length < stale ? `(当前筛选下列出 ${open.length} 个)` : ""; + const ok = await askConfirm("联网核实打开了", `

「细看完成」里有 ${stale} 个视频细看时没有联网核实${shown},要按新标准重新细看吗?

`, label, { reason: why }); + if (ok) startJudging(label, "重新细看", batch, () => startGroup(batch.map((it) => it.bvid), true)); } -// 所有收藏夹 has no one 判断标准: before a 粗看 or 细看 run it lists each folder the run touches, with its videos and its -// 判断标准 to edit (saved as in the 判断标准 dialog). false on 取消. +// 所有收藏夹 without a 判断标准 of its own judges each video under its folder's: before a 粗看 or 细看 run it lists each +// folder the run touches, with its videos and its 判断标准 to edit (saved as in the 判断标准 dialog). false on 取消. async function askAllCriteria(title, verb, items) { const n = new Map(); for (const it of items) n.set(homeOf(it), (n.get(homeOf(it)) || 0) + 1); @@ -187,9 +261,9 @@ async function askAllCriteria(title, verb, items) { render(); return true; } -// A 粗看 / 细看 button: in 所有收藏夹 after askAllCriteria, elsewhere at once. +// A 粗看 / 细看 button: in 所有收藏夹 without its own 判断标准 after askAllCriteria, elsewhere at once. async function startJudging(title, verb, items, start) { - if (S.mediaId === ALL && !(await askAllCriteria(title, verb, items))) return; + if (S.mediaId === ALL && !criteria() && !(await askAllCriteria(title, verb, items))) return; start(); } diff --git a/extension/triage/triage-bg.js b/extension/triage/triage-bg.js index b2f53141..1f5d055a 100644 --- a/extension/triage/triage-bg.js +++ b/extension/triage/triage-bg.js @@ -176,6 +176,10 @@ const TRIAGE_TITLE_PROMPT = [ '[{"i": 序号, "verdict": "keep|drop|unsure", "reason": "≤20字", "confidence": "high|low"}]' ].join("\n"); +// 联网核实: the line triageChat adds to the system prompt when it sends the search tool. +const TRIAGE_SEARCH_PROMPT = "你可以联网搜索。只在需要核实视频内容是否过时或有误时搜索,次数尽量少;回复格式不变。"; +const TRIAGE_FILTERED = "AI 平台的内容审核拦下了这次回复"; + // folder 是 { title, intro },criteria 是这个收藏夹的判断标准;都可以为空 function triageWithCriteria(system, criteria, folder) { const text = String(criteria ?? "").trim(); @@ -653,16 +657,18 @@ function triageMaxTokens(kind, itemCount, { triageThinking, triageTitleMaxTokens return TriageUi.autoMaxTokens(kind, itemCount, triageThinking); } -async function triageAiSettings() { +// thinking: the open folder's own 开启思考 (folderAi), kept only where its platform takes the switch (aiCaps). A folder +// without a record sends none: the global triageThinking, whose switch is gone, is that fallback and nothing else. +async function triageAiSettings({ aiProviderId, thinking } = {}) { const s = await chrome.storage.sync.get({ triageThinking: false, triageTitleMaxTokens: null, triageAnalyzeMaxTokens: null }); return { - triageThinking: s.triageThinking === true, + triageThinking: typeof thinking === "boolean" ? thinking && aiCaps(await triageProvider(aiProviderId)).thinking : s.triageThinking === true, triageTitleMaxTokens: TriageUi.numSetting("maxTokens", s.triageTitleMaxTokens), triageAnalyzeMaxTokens: TriageUi.numSetting("maxTokens", s.triageAnalyzeMaxTokens) }; } -async function triageAnalyze({ bvid, force, criteria, folder, aiProviderId }) { +async function triageAnalyze({ bvid, force, criteria, folder, aiProviderId, thinking, search }) { if (!bvid) throw triageError("缺少 bvid"); const cacheKey = MdgLimits.KEYS.triageAnalysis(bvid); if (!force) { @@ -686,8 +692,9 @@ async function triageAnalyze({ bvid, force, criteria, folder, aiProviderId }) { } const comments = subtitle ? "" : (await site.fetchComments(ref, m, TRIAGE_BILI_IO, TriageUi.DEEP_COMMENTS).catch(() => [])).map((c, i) => `${i + 1}. ${c.message}`).join("\n"); - const ai = await triageAiSettings(); - const { content, model } = await triageChat(triageBuildMessages({ ...meta, subtitleNeedLogin: got.needLogin, subtitleFailure: got.failure }, subtitle, comments, criteria, folder), triageMaxTokens("analyze", 1, ai), ai.triageThinking, aiProviderId); + const ai = await triageAiSettings({ aiProviderId, thinking }); + const chat = await triageChat(triageBuildMessages({ ...meta, subtitleNeedLogin: got.needLogin, subtitleFailure: got.failure }, subtitle, comments, criteria, folder), triageMaxTokens("analyze", 1, ai), ai.triageThinking, aiProviderId, search === true); + const { content, model } = chat; const analysis = { bvid, status: "done", @@ -699,7 +706,9 @@ async function triageAnalyze({ bvid, force, criteria, folder, aiProviderId }) { ...triageParseLlm(content), model, analyzedAt: Date.now(), - criteria: String(criteria ?? "").trim() + criteria: String(criteria ?? "").trim(), + // Made with 联网核实: a folder that has it on redoes the 细看 made without it (fav-base.js staleFine). + ...(chat.search ? { search: true } : {}) }; await chrome.storage.local.set({ [cacheKey]: analysis }); return analysis; @@ -761,29 +770,33 @@ function aiProviderProblem(provider, apiKey) { return null; } -// The platform 分拣台's AI requests go to: the side panel's pick (aiProviderId), else the first enabled one. 开启思考 -// (triage-settings-get) asks the same, so the switch shows exactly when the requests would carry it. +// The platform 分拣台's AI requests go to (aiProviderId: the folder's own from folderAi, else the side panel's pick), else +// the first enabled one. The page falls back the same way to draw 判断标准 (fav-base.js folderAiOf). async function triageProvider(providerId = "") { const enabled = (await loadAiProviders()).filter((p) => p.enabled !== false); return enabled.find((p) => p.id === providerId) || enabled[0] || null; } -// 单次 AI 请求的超时(毫秒)。思考模式慢得多;两档都要短于 MV3 单个消息事件约 5 分钟的上限 +// 单次 AI 请求的超时(毫秒)。思考和联网核实慢得多;两档都要短于 MV3 单个消息事件约 5 分钟的上限 const TRIAGE_AI_TIMEOUT_MS = { normal: 120000, thinking: 240000 }; // 非流式 chat/completions,只取 message.content(忽略 reasoning_content) -// providerId: the platform picked at the top of the side panel, which the pages send as aiProviderId (收藏夹's sendRaw, fav-*.js); +// providerId: the folder's platform or the side panel's pick, as the pages send aiProviderId (收藏夹's sendRaw, fav-*.js); // unset or no longer enabled, the first enabled one, as in the side panel. -async function triageChat(messages, maxTokens, thinking = false, providerId = "") { +// search: 联网核实 (字幕细看 only), sent only where the platform has it (aiCaps): DeepSeek's server searches within this one +// request and answers in the same format. Resolves { content, model, search } (search: whether it was sent). +async function triageChat(messages, maxTokens, thinking = false, providerId = "", search = false) { const provider = await triageProvider(providerId); if (!provider) throw triageError(MdgErrors.TEXT.aiNone, MdgErrors.CODE.AI_SETUP); const apiKey = (await loadAiProviderKeys())[provider.id]; const problem = aiProviderProblem(provider, apiKey); if (problem) throw triageError(problem.text, problem.code); const { baseUrl } = provider; // normalized by loadAiProviders - const body = { model: provider.model, stream: false, temperature: 0.3, max_tokens: maxTokens, messages }; + const web = search && aiCaps(provider).search; + const said = web ? [{ ...messages[0], content: `${messages[0].content}\n\n${TRIAGE_SEARCH_PROMPT}` }, ...messages.slice(1)] : messages; + const body = { model: provider.model, stream: false, temperature: 0.3, max_tokens: maxTokens, messages: said, ...(web && { tools: [{ type: "deepseek_web_search" }] }) }; - const ms = TRIAGE_AI_TIMEOUT_MS[thinking ? "thinking" : "normal"]; + const ms = TRIAGE_AI_TIMEOUT_MS[thinking || web ? "thinking" : "normal"]; return triageRace(ms, () => triageError(MdgErrors.aiTimeout(ms), "AI_TIMEOUT"), async (signal) => { // 思考 token 计入 max_tokens;默认关(DeepSeek 实测 30 标题 3s/815 token,开则约 19s/4579 token) const res = await postChat({ baseUrl, apiKey, signal, thinking }, body).catch(async () => { @@ -795,14 +808,16 @@ async function triageChat(messages, maxTokens, thinking = false, providerId = "" const choice = json.choices?.[0]; // Cut at the output limit, with or without a partial answer: the page offers 调大输出上限. if (choice?.finish_reason === "length") throw triageError(MdgErrors.TEXT.aiTruncated, "AI_TRUNCATED"); - return { content: choice?.message?.content, model: provider.model }; + // The platform's moderation stopped the answer (content is then empty): this video's failure, said as that. + if (choice?.finish_reason === "content_filter") throw triageError(TRIAGE_FILTERED); + return { content: choice?.message?.content, model: provider.model, search: Boolean(web) }; }); } -async function triageClassifyTitles({ items, criteria, folder, aiProviderId }) { +async function triageClassifyTitles({ items, criteria, folder, aiProviderId, thinking }) { const list = (Array.isArray(items) ? items : []).filter((it) => it && it.bvid); if (!list.length) throw triageError("缺少 items"); - const ai = await triageAiSettings(); + const ai = await triageAiSettings({ aiProviderId, thinking }); const system = triageWithCriteria(TRIAGE_TITLE_PROMPT, criteria, folder); const user = list.map((it, idx) => triageTitleLine(it, idx + 1)).join("\n"); const { content, model } = await triageChat( @@ -828,14 +843,14 @@ async function triageClassifyTitles({ items, criteria, folder, aiProviderId }) { } // 协作打标签:只返回提案,不缓存。提示里让 AI 新建至多 maxNewTags 个(收藏夹剩余名额与分拣设置里 AI 新建上限取小),多出的照样返回 -// 关注 (follow-bg.js) calls it too, with UP 主 as items (mid in bvid) and its own unit, and so does 摘读记录. 开启思考 and -// 粗看输出上限 are 收藏夹设置's: 关注设置 and 摘读记录设置 have neither, so their runs think off with the automatic cap. -async function triageAiCommand({ instruction, items, tags, maxNewTags, allowRemove = false, aiProviderId }, unit = TRIAGE_AI_UNIT) { +// 关注 (follow-bg.js) calls it too, with UP 主 as items (mid in bvid) and its own unit, and so does 摘读记录. 开启思考 is +// 判断标准's and 粗看输出上限 is 收藏夹设置's: 关注 and 摘读记录 have neither, so their runs think off with the automatic cap. +async function triageAiCommand({ instruction, items, tags, maxNewTags, allowRemove = false, aiProviderId, thinking }, unit = TRIAGE_AI_UNIT) { const text = String(instruction ?? "").trim(); if (!text) throw triageError("缺少指令"); const list = (Array.isArray(items) ? items : []).filter(triageItemId); if (!list.length) throw triageError("缺少 items"); - const ai = unit === TRIAGE_AI_UNIT ? await triageAiSettings() : { triageThinking: false, triageTitleMaxTokens: null }; + const ai = unit === TRIAGE_AI_UNIT ? await triageAiSettings({ aiProviderId, thinking }) : { triageThinking: false, triageTitleMaxTokens: null }; const opts = { maxNewTags: TriageUi.numSetting("newTagMax", maxNewTags), allowRemove: allowRemove === true }; const { content } = await triageChat( triageBuildCommandMessages({ instruction: text, tags, items: list, ...opts, unit }), @@ -1212,9 +1227,9 @@ const TRIAGE_HANDLERS = { return { id: data.id, title: data.title || name }; }, - "triage-settings-get": async ({ aiProviderId } = {}) => { + "triage-settings-get": async () => { const s = await chrome.storage.sync.get(TRIAGE_SETTINGS_DEFAULTS); - const provider = typeof loadAiProviders === "function" ? await triageProvider(aiProviderId).catch(() => null) : null; + const providers = typeof loadAiProviders === "function" ? await loadAiProviders().catch(() => []) : []; return { triageIntervalSec: TriageUi.numSetting("interval", s.triageIntervalSec), triageFineBatchSize: TriageUi.numSetting("fineBatch", s.triageFineBatchSize), @@ -1226,9 +1241,8 @@ const TRIAGE_HANDLERS = { triageAiNewTagMax: TriageUi.numSetting("newTagMax", s.triageAiNewTagMax), triageAiRemoveTags: s.triageAiRemoveTags === true, triageAiBatchSize: TriageUi.numSetting("aiBatch", s.triageAiBatchSize), - // 开启思考 only reaches these platforms (triageChat), so the page shows the switch only when the platform the - // requests go to (triageProvider) is one of them. - thinkingToggle: supportsThinkingToggle(provider?.baseUrl) + // The enabled platforms 判断标准 offers, with what each can do (aiCaps): the page draws them, it does not judge. + aiPlatforms: providers.filter((p) => p.enabled !== false).map((p) => ({ id: p.id, name: p.name, model: p.model, note: p.note, caps: aiCaps(p) })) }; }, diff --git a/extension/triage/triage-bg.selftest.js b/extension/triage/triage-bg.selftest.js index 81b20d15..87b1bc4b 100644 --- a/extension/triage/triage-bg.selftest.js +++ b/extension/triage/triage-bg.selftest.js @@ -10,8 +10,8 @@ const ctx = vm.createContext({ TextEncoder, URL, URLSearchParams, console, setTi const bg = fs.readFileSync(path.join(__dirname, "../background.js"), "utf8"); const order = [...bg.matchAll(/importScripts\(([^)]*)\)/g)].flatMap((m) => m[1].match(/"[^"]+"/g).map((f) => JSON.parse(f))); for (const file of order.slice(0, order.indexOf("triage/triage-bg.js") + 1)) vm.runInContext(fs.readFileSync(path.join(__dirname, "..", file), "utf8"), ctx); -// background.js owns supportsThinkingToggle and postChat; lift just those. -for (const name of ["supportsThinkingToggle", "postChat"]) { +// background.js owns supportsThinkingToggle, aiCaps and postChat; lift just those. +for (const name of ["supportsThinkingToggle", "aiCaps", "postChat"]) { const at = bg.indexOf(`function ${name}(`); vm.runInContext(bg.slice(at, bg.indexOf("\n}\n", at) + 2), ctx); } @@ -294,8 +294,13 @@ assert.throws(() => t.triageParseCommand('{"new_tags":[', cmdItems, cmdTags, {}) await t.triageChat([], 100, false); assert.deepStrictEqual(sent.thinking, on ? { type: "disabled" } : undefined, url); t.chrome = { storage: { sync: { get: async (d) => d } } }; - assert.strictEqual((await vm.runInContext("TRIAGE_HANDLERS", ctx)["triage-settings-get"]()).thinkingToggle, on, url); + assert.strictEqual((await vm.runInContext("TRIAGE_HANDLERS", ctx)["triage-settings-get"]()).aiPlatforms[0].caps.thinking, on, url); } + // 联网核实: only DeepSeek's deepseek-flash, the one model its web search serves. + assert.deepStrictEqual( + [["https://api.deepseek.com/v1", "deepseek-flash"], ["https://api.deepseek.com", "deepseek-flash"], ["https://api.deepseek.com/v1", "deepseek-chat"], ["https://open.bigmodel.cn/api/paas/v4", "deepseek-flash"], ["https://api.deepseek.com.evil.test/v1", "deepseek-flash"]].map(([baseUrl, model]) => t.aiCaps({ baseUrl, model }).search), + [true, true, false, false, false] + ); // The platform picked in the side panel (aiProviderId from the page) answers; a missing or disabled pick falls back to the // first enabled one, as the side panel does. { @@ -307,10 +312,35 @@ assert.throws(() => t.triageParseCommand('{"new_tags":[', cmdItems, cmdTags, {}) t.fetch = async (url) => ({ ok: true, json: async () => ({ choices: [{ message: { content: url } }] }) }); const host = async (id) => (await t.triageChat([], 100, false, id)).content.split("/")[2]; assert.deepStrictEqual([await host("b"), await host(""), await host("gone"), await host("off")], ["b.test", "a.test", "a.test", "a.test"]); - // C6: 开启思考 shows by the platform the requests go to, not by the first one. - t.loadAiProviders = async () => [{ id: "a", baseUrl: "https://api.openai.com/v1" }, { id: "b", baseUrl: "https://api.deepseek.com/v1" }]; - const toggle = async (msg) => (await vm.runInContext("TRIAGE_HANDLERS", ctx)["triage-settings-get"](msg)).thinkingToggle; - assert.deepStrictEqual([await toggle({ aiProviderId: "b" }), await toggle({}), await toggle({ aiProviderId: "gone" })], [true, false, false]); + // 判断标准 lists every enabled platform with what it can do; the page draws that and judges nothing itself. + t.loadAiProviders = async () => [ + { id: "a", name: "OpenAI 兼容", model: "gpt", note: "", baseUrl: "https://api.openai.com/v1" }, + { id: "off", baseUrl: "https://api.deepseek.com/v1", model: "deepseek-flash", enabled: false }, + { id: "b", name: "DeepSeek", model: "deepseek-flash", note: "自己的", baseUrl: "https://api.deepseek.com/v1" } + ]; + assert.deepStrictEqual(plain((await vm.runInContext("TRIAGE_HANDLERS", ctx)["triage-settings-get"]()).aiPlatforms), [ + { id: "a", name: "OpenAI 兼容", model: "gpt", note: "", caps: { thinking: false, search: false } }, + { id: "b", name: "DeepSeek", model: "deepseek-flash", note: "自己的", caps: { thinking: true, search: true } } + ]); + // 开启思考: a folder's own (thinking sent) only where its platform takes it; without one, the old global value as is. + const thinks = async (msg, stored) => { + t.chrome = { storage: { sync: { get: async (d) => ({ ...d, triageThinking: stored }) } } }; + return (await t.triageAiSettings(msg)).triageThinking; + }; + assert.deepStrictEqual( + [await thinks({ aiProviderId: "b", thinking: true }, false), await thinks({ aiProviderId: "b", thinking: false }, true), await thinks({ aiProviderId: "a", thinking: true }, false), await thinks({ aiProviderId: "a" }, true), await thinks({}, false)], + [true, false, false, true, false] + ); + // End to end: a 粗看 with the folder's record goes to its platform with thinking on; without one, as before. + { + const bodies = []; + t.fetch = async (url, init) => (bodies.push([url.split("/")[2], JSON.parse(init.body).thinking]), { ok: true, json: async () => ({ choices: [{ message: { content: "[]" } }] }) }); + t.chrome = { storage: { sync: { get: async (d) => d }, local: { set: async () => {} } } }; + const H = vm.runInContext("TRIAGE_HANDLERS", ctx); + await H["triage-classify-titles"]({ items: [{ bvid: "BV1", title: "t" }], aiProviderId: "b", thinking: true }).catch(() => {}); + await H["triage-classify-titles"]({ items: [{ bvid: "BV1", title: "t" }], aiProviderId: "a" }).catch(() => {}); + assert.deepStrictEqual(plain(bodies), [["api.deepseek.com", { type: "enabled" }], ["api.openai.com", null]]); + } } t.loadAiProviders = async () => [{ id: "p", baseUrl: "https://ai.test", model: "m" }]; @@ -336,6 +366,53 @@ assert.throws(() => t.triageParseCommand('{"new_tags":[', cmdItems, cmdTags, {}) await assert.rejects(t.triageChat([], 100, true), (e) => e.code === "AI_TIMEOUT"); assert.ok(Date.now() - started >= 55, "thinking uses the longer timeout"); + // 联网核实: the search tool and its line in the prompt go only with 细看's search on a platform that has it; the other + // combinations, and 标题粗看 and AI 打标签 whatever they carry, send neither. It waits as long as thinking does. + { + t.loadAiProviders = async () => [ + { id: "ds", baseUrl: "https://api.deepseek.com/v1", model: "deepseek-flash" }, + { id: "zp", baseUrl: "https://open.bigmodel.cn/api/paas/v4", model: "glm" } + ]; + t.loadAiProviderKeys = async () => ({ ds: "k", zp: "k" }); + let body; + t.fetch = async (_, init) => ((body = JSON.parse(init.body)), { ok: true, json: async () => ({ choices: [{ message: { content: "[]" } }] }) }); + const sends = async (search, id) => { + const r = await t.triageChat([{ role: "system", content: "S" }, { role: "user", content: "U" }], 100, false, id, search); + return [Boolean(body.tools), body.messages[0].content.includes("联网"), r.search]; + }; + assert.deepStrictEqual(plain([await sends(true, "ds"), await sends(true, "zp"), await sends(false, "ds"), await sends(false, "zp")]), [[true, true, true], [false, false, false], [false, false, false], [false, false, false]]); + assert.deepStrictEqual(plain(body.messages[1]), { role: "user", content: "U" }); + await sends(true, "ds"); + assert.deepStrictEqual(plain(body.tools), [{ type: "deepseek_web_search" }]); + assert.ok(!("response_format" in body), "the search tool takes no response_format"); + const H = vm.runInContext("TRIAGE_HANDLERS", ctx); + t.chrome = { storage: { sync: { get: async (d) => d }, local: { set: async () => {} } } }; + await H["triage-classify-titles"]({ items: [{ bvid: "BV1", title: "t" }], aiProviderId: "ds", search: true }).catch(() => {}); + assert.ok(!body.tools, "标题粗看 never searches"); + t.fetch = async (_, init) => ((body = JSON.parse(init.body)), { ok: true, json: async () => ({ choices: [{ message: { content: '{"new_tags":[],"items":[]}' } }] }) }); + await H["triage-ai-command"]({ instruction: "x", items: [{ bvid: "BV1", title: "t" }], tags: [], aiProviderId: "ds", search: true }); + assert.ok(!body.tools, "AI 打标签 never searches"); + // A searching request has the thinking timeout. + t.fetch = (url, { signal }) => new Promise((_, reject) => signal.addEventListener("abort", () => reject(new Error("aborted")))); + const began = Date.now(); + await assert.rejects(t.triageChat([{ role: "system", content: "S" }], 100, false, "ds", true), (e) => e.code === "AI_TIMEOUT"); + assert.ok(Date.now() - began >= 55, "联网核实 waits as long as thinking"); + // Moderation stopped the answer: a sentence of its own, not a format error. + t.fetch = async () => ({ ok: true, json: async () => ({ choices: [{ message: { content: "" }, finish_reason: "content_filter" }] }) }); + await assert.rejects(t.triageChat([{ role: "system", content: "S" }], 100, false, "ds", true), (e) => e.message === "AI 平台的内容审核拦下了这次回复" && e.code === undefined); + // 细看 records whether it searched. + const was = t.MdgSites; + t.MdgSites = { ...was, SITES: { bilibili: { fetchMeta: async () => ({ title: "T", description: "", author: "A", duration: 60, uploadDate: "", tname: "", tags: [] }), fetchComments: async () => [] } }, loadSubtitle: async () => ({ body: [] }) }; + const stored = {}; + t.chrome = { storage: { sync: { get: async (d) => d }, local: { get: async () => ({}), set: async (o) => Object.assign(stored, o) } } }; + t.fetch = async (_, init) => ((body = JSON.parse(init.body)), { ok: true, json: async () => ({ choices: [{ message: { content: '{"one_liner":"x","points":["a","b","c"],"verdict":"keep","reason":"r"}' } }] }) }); + const analyzed = async (msg) => plain(await H["triage-analyze"]({ bvid: "BV9", force: true, ...msg })); + assert.deepStrictEqual([(await analyzed({ aiProviderId: "ds", search: true })).search, (await analyzed({ aiProviderId: "zp", search: true })).search, (await analyzed({ aiProviderId: "ds" })).search], [true, undefined, undefined]); + t.MdgSites = was; + t.loadAiProviders = async () => [{ id: "p", baseUrl: "https://ai.test", model: "m" }]; + t.loadAiProviderKeys = async () => ({ p: "k", a: "k", b: "k" }); + } + // Interval 0 is a valid user choice; only invalid values fall back to the default. const settingsWith = async (stored) => { t.chrome = { storage: { sync: { get: async (d) => ({ ...d, ...stored }) } } }; diff --git a/extension/triage/triage.css b/extension/triage/triage.css index 231ee359..a837194b 100644 --- a/extension/triage/triage.css +++ b/extension/triage/triage.css @@ -606,6 +606,36 @@ button.icon { width: 26px; height: 24px; padding: 0; } .form-error { margin: 4px 0 0; color: var(--danger); font-size: var(--fs-xs); } .confirm-body ul { margin: 0; padding-left: 18px; } +/* 判断标准: the criteria on the left, as tall as the column; the folder's AI platform and its two switches on the right. The + list stops at about five rows and scrolls inside, so the switches stay in view. */ +dialog.crit-dialog { width: min(780px, calc(100% - 32px)); } +.crit-cols { display: grid; gap: 16px 20px; } +@media (min-width: 640px) { .crit-cols { grid-template-columns: minmax(0, 1fr) 300px; } } +.crit-left, .crit-right { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.crit-left textarea { flex: 1; min-height: 200px; } +dialog .crit-head { font-size: var(--fs-sm); font-weight: 600; color: var(--text); } +.crit-list { display: grid; gap: 2px; max-height: 236px; margin: 0 -8px; overflow-y: auto; } +.crit-opt { display: grid; grid-template-columns: 16px minmax(0, 1fr) 34px 34px; align-items: center; gap: 8px; padding: 6px 8px; border-radius: var(--radius-sm); } +.crit-list.one .crit-opt { grid-template-columns: 16px minmax(0, 1fr); } +dialog label.crit-opt { font-size: var(--fs-sm); color: var(--text); cursor: pointer; } +label.crit-opt:has(input:checked) { background: var(--action-bg); box-shadow: inset 0 0 0 1px var(--action-border); } +.crit-opt input { margin: 0; } +.crit-opt .nm { min-width: 0; line-height: 1.35; overflow-wrap: anywhere; } +.crit-opt small { display: block; overflow: hidden; color: var(--muted); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; } +.crit-opt .cap { color: var(--text-2); font-size: var(--fs-xs); text-align: center; transition: color 0.12s, opacity 0.12s; } +.crit-opt .cap.x { color: var(--faint); } +.crit-th { position: sticky; top: 0; z-index: 1; padding-top: 0; padding-bottom: 0; background: var(--surface); color: var(--faint); font-size: var(--fs-xs); } +/* Pointing at a switch brings out its column in the list. */ +.crit-right:has([data-cap="thinking"]:hover) .cap.t:not(.x), .crit-right:has([data-cap="search"]:hover) .cap.n:not(.x) { color: var(--text); font-weight: 600; } +.crit-right:has([data-cap="thinking"]:hover) .cap.n, .crit-right:has([data-cap="search"]:hover) .cap.t { opacity: 0.35; } +.crit-switch { display: flex; align-items: center; gap: 12px; margin-top: 6px; padding-top: 10px; border-top: 1px solid var(--border); } +.crit-switch > div { flex: 1; min-width: 0; } +dialog .crit-switch .name { color: var(--text); font-size: var(--fs-sm); font-weight: 600; } +.crit-switch .dialog-meta.warn { color: var(--warn); } +/* The platform cannot do it: greyed out; one left on stays visibly on, striped, for when a platform that can comes back. */ +.crit-switch input.switch:disabled { background: var(--border); cursor: not-allowed; } +.crit-switch input.switch:disabled:checked { background: repeating-linear-gradient(135deg, var(--border-strong) 0 3px, var(--border) 3px 6px); } + /* 所有收藏夹's runs: each folder's 判断标准 under its name. */ .crit-row { display: grid; gap: 4px; margin-top: 8px; } .help-cols { display: grid; gap: 24px 32px; } diff --git a/extension/triage/triage.html b/extension/triage/triage.html index f5d02c8a..7beff5d5 100644 --- a/extension/triage/triage.html +++ b/extension/triage/triage.html @@ -124,7 +124,6 @@

请求和 AI 参数

-

判断更细,但慢得多、token 多几倍。

点一次「标题粗看」跑几个。默认 ,最多 。

点一次「字幕细看」跑几个。默认 ,最多 。

@@ -260,12 +259,32 @@

- +

判断标准

- -

只对这个收藏夹生效 · 回车保存,Shift+回车换行

+
+
+ + +

+
+
+
AI 平台
+ +
+ +
+

+ +
+
+

+ +
+
+
+ 只对这个收藏夹生效 · 回车保存,Shift+回车换行 diff --git a/extension/triage/triage.selftest.js b/extension/triage/triage.selftest.js index faee3f53..3ea2561f 100644 --- a/extension/triage/triage.selftest.js +++ b/extension/triage/triage.selftest.js @@ -1353,6 +1353,139 @@ const unfavOnlyOf = (d) => Object.fromEntries(Object.entries(d).filter(([, v]) = assert.deepStrictEqual([t.S.titleRes.BV500.reason, t.S.titleRes.BV500.criteria], ["新理由", "新标准"], "the new result replaces it"); Object.assign(t.S, { titleRes: {}, folderCriteria: {} }); + // 判断标准's AI side (L2): the platform is the folder's own, the fallback (side panel's pick), a gone one, or none; each + // switch on or off, on a platform that can or cannot do it. + { + const ds = { id: "ds", name: "DeepSeek", model: "deepseek-flash", note: "自己的", caps: { thinking: true, search: true } }; + const zp = { id: "zp", name: "智谱 GLM", model: "glm", caps: { thinking: true, search: false } }; + const oa = { id: "oa", name: "OpenAI 兼容", model: "gpt", caps: { thinking: false, search: false } }; + const was = { providers: t.S.settings.aiPlatforms, thinking: t.S.settings.triageThinking }; + Object.assign(t.S.settings, { aiPlatforms: [ds, zp, oa], triageThinking: true }); + ctx.localStorage = { getItem: (k) => (k === "mdg_ai_selected_provider" ? "zp" : null) }; + const draft = () => plain(vm.runInContext("critAi", ctx)); + const open = (rec) => { + t.S.folderAi = rec ? { J: rec } : {}; + t.el.criteriaInput = { value: "", focus() {} }; + t.openCriteria(); + return draft(); + }; + const sw = (box, hint) => [t.el[box].checked, t.el[box].disabled, t.el[hint].textContent]; + const KEPT = "已开启的设置保留,换回支持的平台后生效"; + // No record: the side panel's pick and 开启思考's old global value, no 联网核实; 智谱 cannot search, so that one is off. + assert.deepStrictEqual(open(null), { providerId: "zp", thinking: true, search: false, gone: false }); + assert.match(t.el.critAiList.innerHTML, /思考<\/span>联网<\/span>/); + assert.match(t.el.critAiList.innerHTML, /value="zp" checked/); + assert.ok(t.el.critAiList.innerHTML.includes('自己的DeepSeek · deepseek-flash') && t.el.critAiList.innerHTML.includes(">智谱 GLM · glm<"), "备注名 on top, 「平台 · 模型」 under it; without one, the option text alone"); + assert.deepStrictEqual(sw("critThinking", "critThinkingHint"), [true, false, "判断更细,但慢得多、token 多几倍。"]); + assert.deepStrictEqual(sw("critSearch", "critSearchHint"), [false, true, "智谱 GLM · glm不支持联网"]); + assert.strictEqual(t.el.critSearch.title, "智谱 GLM · glm不支持联网", "the reason is on the switch too"); + assert.strictEqual(t.el.critAiNote.hidden, true); + // Its own record on a platform that can do neither: both off, both kept on, and said so. + assert.deepStrictEqual(open({ providerId: "oa", thinking: true, search: true }), { providerId: "oa", thinking: true, search: true, gone: false }); + assert.deepStrictEqual(sw("critThinking", "critThinkingHint"), [true, true, `OpenAI 兼容 · gpt不支持开关思考。${KEPT}`]); + assert.deepStrictEqual(sw("critSearch", "critSearchHint"), [true, true, `OpenAI 兼容 · gpt不支持联网。${KEPT}`]); + // On one that can: both on and free. + open({ providerId: "ds", thinking: false, search: true }); + assert.deepStrictEqual([sw("critThinking", "critThinkingHint").slice(0, 2), sw("critSearch", "critSearchHint")[1]], [[false, false], false]); + // Its own platform deleted or disabled: the first enabled one, as the background falls back, with a note. + assert.deepStrictEqual(open({ providerId: "gone", thinking: true, search: false }), { providerId: "ds", thinking: true, search: false, gone: true }); + assert.deepStrictEqual([t.el.critAiNote.hidden, t.el.critAiNote.textContent], [false, "原来选的 AI 平台已删除或停用,现在用「自己的」。"]); + // The drafted platform deleted on the settings page while the dialog is open: the same fallback, said the same way. + open({ providerId: "ds", thinking: true, search: false }); + t.S.settings.aiPlatforms = [zp, oa]; + vm.runInContext("renderCritAi()", ctx); + assert.deepStrictEqual([draft().providerId, draft().gone, t.el.critAiNote.hidden], ["zp", true, false]); + // One platform: no columns to compare. + t.S.settings.aiPlatforms = [zp]; + open(null); + assert.ok(!t.el.critAiList.innerHTML.includes("crit-th") && !t.el.critAiList.innerHTML.includes('class="cap'), t.el.critAiList.innerHTML); + // None: the list says so with 去设置, the switches are off with that reason, and 保存 records no platform. + t.S.settings.aiPlatforms = []; + assert.strictEqual(open(null).providerId, ""); + assert.deepStrictEqual([t.el.critAiList.innerHTML, t.el.critAiNone.hidden], ["", false], "the list says 没有启用的 AI 平台 with 去设置"); + assert.deepStrictEqual([t.el.critThinking.disabled, t.el.critSearch.disabled, t.el.critSearch.title], [true, true, "没有启用的 AI 平台"]); + assert.strictEqual(t.el.critThinkingHint.textContent, "没有启用的 AI 平台", "nothing to switch back to: no 「换回支持的平台后生效」"); + await t.saveCriteria(); + assert.deepStrictEqual(plain(store[t.K.folderAi] || {}), {}); + // 保存 writes the dialog's three as this folder's record by read-modify-write: another tab's folder stays. + t.S.settings.aiPlatforms = [ds, zp, oa]; + open(null); + vm.runInContext('Object.assign(critAi, { providerId: "ds", search: true })', ctx); + store[t.K.folderAi] = { K: { providerId: "zp", thinking: false, search: false } }; + await t.saveCriteria(); + assert.deepStrictEqual(plain(store[t.K.folderAi]), { K: { providerId: "zp", thinking: false, search: false }, J: { providerId: "ds", thinking: true, search: true } }); + // A changed platform or switch is not a changed 判断标准: no 重新粗看 is offered. + t.S.titleRes.BV500 = { verdict: "keep", criteria: "" }; + const asked = []; + const realAsk = t.askConfirm; + t.askConfirm = async (title) => (asked.push(title), false); + open({ providerId: "ds", thinking: true, search: true }); + vm.runInContext('Object.assign(critAi, { providerId: "zp", thinking: false })', ctx); + await t.saveCriteria(); + assert.deepStrictEqual(asked, []); + t.askConfirm = realAsk; + // Requests: the folder's own platform and 开启思考; without a record exactly what they were (the side panel's pick only). + handlers["triage-classify-titles"] = () => ({ ok: true, data: { results: {} } }); + t.S.folderAi = { J: { providerId: "ds", thinking: false, search: true } }; + t.S.titleRes = {}; + await t.runStage1(); + assert.deepStrictEqual([sent.at(-1).aiProviderId, sent.at(-1).thinking, sent.at(-1).search], ["ds", false, undefined], "标题粗看 never asks for 联网核实"); + t.S.folderAi = {}; + t.S.coarseFailed.clear(); + await t.runStage1(); + assert.deepStrictEqual(Object.keys(plain(sent.at(-1))).sort(), ["aiProviderId", "criteria", "folder", "items", "type"]); + assert.strictEqual(sent.at(-1).aiProviderId, "zp"); + // 所有收藏夹 runs on its own record, never on a video's folder's: none of its own, none sent. + t.S.folderAi = { J: { providerId: "ds", thinking: true, search: false } }; + t.S.mediaId = "all"; + assert.deepStrictEqual(plain(vm.runInContext('aiReq("J")', ctx)), {}); + t.S.folderAi.all = { providerId: "zp", thinking: false, search: true }; + assert.deepStrictEqual(plain(vm.runInContext('aiReq("J")', ctx)), { aiProviderId: "zp", thinking: false, search: true }); + assert.deepStrictEqual(plain(vm.runInContext('[folderAiOf("all").own, folderAiOf("all").provider.id]', ctx)), [true, "zp"]); + t.S.mediaId = "J"; + assert.deepStrictEqual(plain(vm.runInContext('aiReq("J")', ctx)), { aiProviderId: "ds", thinking: true, search: false }); + // 联网核实 on, on a platform that has it: a 细看 made without it is old (按新标准重新细看); one made with it, a folder + // with it off, or a platform without it, is not. The 细看 request carries it. + { + const done = (extra) => ({ status: "done", verdict: "keep", criteria: "", ...extra }); + t.S.analyses = { BV500: done({}) }; + const staleWith = (rec) => ((t.S.folderAi = rec ? { J: rec } : {}), plain(t.staleFine().map((it) => it.bvid))); + assert.deepStrictEqual( + [staleWith({ providerId: "ds", thinking: false, search: true }), staleWith({ providerId: "ds", thinking: false, search: false }), staleWith({ providerId: "zp", thinking: false, search: true }), staleWith(null)], + [["BV500"], [], [], []] + ); + t.S.analyses.BV500 = done({ search: true }); + assert.deepStrictEqual(staleWith({ providerId: "ds", thinking: false, search: true }), []); + t.S.analyses = {}; + handlers["triage-analyze"] = () => ({ ok: true, data: done({ search: true }) }); + await vm.runInContext("analyzeOne", ctx)("BV500", true, vm.runInContext("judgeOf", ctx)(t.S.itemMap.get("BV500"))); + assert.deepStrictEqual([sent.at(-1).type, sent.at(-1).search, sent.at(-1).aiProviderId], ["triage-analyze", true, "ds"]); + // Saving with 联网核实 just turned on asks to redo the 细看 made without it; turning it off, or saving it on again, does not. + const asked = []; + const realAsk = t.askConfirm; + t.askConfirm = async (title) => (asked.push(title), false); + t.S.analyses = { BV500: done({}) }; + t.S.folderCriteria = {}; + const save = async (rec, next) => { + open(rec); + vm.runInContext(`Object.assign(critAi, ${JSON.stringify(next)})`, ctx); + await t.saveCriteria(); + }; + await save({ providerId: "ds", thinking: false, search: false }, { search: true }); + await save({ providerId: "ds", thinking: false, search: true }, { search: true }); + await save({ providerId: "ds", thinking: false, search: true }, { search: false }); + assert.deepStrictEqual(asked, ["联网核实打开了"]); + t.askConfirm = realAsk; + delete handlers["triage-analyze"]; + t.S.analyses = {}; + } + delete ctx.localStorage; + t.S.coarseFailed.clear(); + Object.assign(t.S, { titleRes: {}, folderCriteria: {}, folderAi: {} }); + Object.assign(t.S.settings, { aiPlatforms: was.providers, triageThinking: was.thinking }); + delete handlers["triage-classify-titles"]; + } + // 移动/复制 is offered for a selection in any tab, 未分析 too. openFake("Z", [item(700)]); t.S.tab = "none"; @@ -2852,7 +2985,8 @@ const unfavOnlyOf = (d) => Object.fromEntries(Object.entries(d).filter(([, v]) = t.el.banner.hidden = true; } - // 所有收藏夹: each video is judged under its first chosen folder's 判断标准 and context; a 粗看 batch holds one folder. + // 所有收藏夹 without a 判断标准 of its own: each video is judged under its first chosen folder's 判断标准 and context; a + // 粗看 batch holds one folder. { const vids = [{ ...item(850), folders: ["K"] }, { ...item(851), folders: ["L", "K"] }, { ...item(852), folders: ["L"] }, { ...item(853), folders: ["K"] }]; openFake("all", vids); @@ -2861,9 +2995,10 @@ const unfavOnlyOf = (d) => Object.fromEntries(Object.entries(d).filter(([, v]) = store[t.K.folderCriteria] = structuredClone(t.S.folderCriteria); Object.assign(t.S.settings, { triageIntervalSec: 0 }); assert.deepStrictEqual(vids.map((it) => vm.runInContext("homeOf", ctx)(it)), ["K", "K", "L", "K"], "the first chosen folder it is in"); - // The step bar offers the run (no single 判断标准 button); the run asks first, listing each folder's count and 判断标准. + // The step bar offers the run and 所有收藏夹's own 判断标准 button (not written: what happens then, no warn dot); the + // run asks first, listing each folder's count and 判断标准. t.renderListHeader(t.visibleItems()); - assert.ok((t.el.listHeader.innerHTML + t.el.favSel.innerHTML).includes("标题粗看下一批 4 个") && !(t.el.listHeader.innerHTML + t.el.favSel.innerHTML).includes('data-head="criteria"'), (t.el.listHeader.innerHTML + t.el.favSel.innerHTML)); + assert.ok((t.el.listHeader.innerHTML + t.el.favSel.innerHTML).includes("标题粗看下一批 4 个") && (t.el.listHeader.innerHTML + t.el.favSel.innerHTML).includes('data-head="criteria" title="不写时,每个视频按它所在收藏夹的判断标准判断。" aria-label="判断标准">'), (t.el.listHeader.innerHTML + t.el.favSel.innerHTML)); const batches = []; handlers["triage-classify-titles"] = ({ items, criteria, folder }) => { batches.push([items.map((x) => x.bvid), criteria, folder.title, folder.intro]); @@ -2896,20 +3031,83 @@ const unfavOnlyOf = (d) => Object.fromEntries(Object.entries(d).filter(([, v]) = let started = false; await vm.runInContext("startJudging", ctx)("细看", "细看", [vids[0]], () => (started = true)); assert.ok(!started); + // 所有收藏夹's own 判断标准 and AI: the dialog opens on it and 保存 writes both under its id. + const platforms = t.S.settings.aiPlatforms; + t.S.settings.aiPlatforms = [{ id: "ds", name: "DeepSeek", model: "m", caps: { thinking: true, search: true } }, { id: "zp", name: "智谱", model: "g", caps: { thinking: true, search: false } }]; + t.S.folderAi = { K: { providerId: "ds", thinking: true, search: true } }; + store[t.K.folderAi] = structuredClone(t.S.folderAi); + t.el.criteriaInput = { value: "", focus() {} }; + t.openCriteria(); + assert.deepStrictEqual([t.el.criteriaTitle.textContent, t.el.criteriaHint.textContent], ["判断标准 ·「所有收藏夹」", "不写时,每个视频按它所在收藏夹的判断标准判断。"]); + vm.runInContext('Object.assign(critAi, { providerId: "zp", thinking: false, search: false })', ctx); + t.el.criteriaInput = { value: "总标准" }; + await t.saveCriteria(); + assert.strictEqual(store[t.K.folderCriteria].all, "总标准"); + assert.deepStrictEqual(plain(store[t.K.folderAi]), { K: { providerId: "ds", thinking: true, search: true }, all: { providerId: "zp", thinking: false, search: false } }); + // Written, it is the one every video is judged under, and staleness goes by it: 夹K's and 夹L's no longer count. + assert.deepStrictEqual(plain([t.staleCoarse().map((it) => it.bvid), t.staleFine().map((it) => it.bvid)]), [["BV850", "BV853"], ["BV851", "BV852"]]); + // Its runs start at once (no per-folder dialog), each video still told its own folder, on 所有收藏夹's platform. + asked = null; + t.askConfirm = async (...a) => ((asked = a), true); + batches.length = fine.length = 0; + const ran = []; + const coarse = handlers["triage-classify-titles"]; + handlers["triage-classify-titles"] = (m) => (ran.push([m.aiProviderId, m.thinking]), coarse(m)); + handlers["triage-analyze"] = ({ bvid, criteria, folder, aiProviderId, thinking, search }) => (fine.push([bvid, criteria, folder.title, aiProviderId, thinking, search]), { ok: true, data: { bvid, status: "done", verdict: "keep", ...(search && { search }) } }); + await vm.runInContext("startJudging", ctx)("重新粗看", "重新粗看", [vids[0], vids[3]], () => t.runStage1([vids[0], vids[3]], true)); + while (vm.runInContext("runs", ctx).get("stage1")) await new Promise((r) => setTimeout(r, 0)); + await vm.runInContext("startJudging", ctx)("重新细看", "重新细看", [vids[2]], () => t.startGroup(["BV852"], true)); + for (let i = 0; i < 20 && t.S.group; i++) await new Promise((r) => setImmediate(r)); + assert.deepStrictEqual([asked, batches, ran, fine], [null, [[["BV850", "BV853"], "总标准", "夹K", ""]], [["zp", false]], [["BV852", "总标准", "夹L", "zp", false, false]]]); + assert.deepStrictEqual(plain([t.staleCoarse().map((it) => it.bvid), t.staleFine().map((it) => it.bvid)]), [[], ["BV851"]]); + // Its 判断标准 emptied and saved: the redo that save offers runs under each folder's again, so it lists the folders first. + { + const calls = []; + t.askConfirm = async (...args) => (calls.push(args), calls.length === 1); + t.el.criteriaInput = { value: "" }; + await t.saveCriteria(); + assert.deepStrictEqual([calls.length, calls[0][0]], [2, "判断标准改了"]); + assert.ok(calls[1][1].includes("每个视频按它所在收藏夹的判断标准判断"), calls[1][1]); + t.askConfirm = async () => false; + t.el.criteriaInput = { value: "总标准" }; + await t.saveCriteria(); + t.askConfirm = async (...args) => ((asked = args), true); + } + // 联网核实 follows 所有收藏夹's record: 夹K's being on makes nothing old, its own on does, and its 细看 then searches. + t.S.analyses.BV851.criteria = "总标准"; + assert.deepStrictEqual(plain(t.staleFine().map((it) => it.bvid)), []); + t.S.folderAi = { K: { providerId: "zp", thinking: false, search: false }, all: { providerId: "ds", thinking: true, search: true } }; + assert.deepStrictEqual(plain(t.staleFine().map((it) => it.bvid)), ["BV851", "BV852"]); + t.startGroup(["BV851"], true); + for (let i = 0; i < 20 && t.S.group; i++) await new Promise((r) => setImmediate(r)); + assert.deepStrictEqual([fine.at(-1), plain(t.staleFine().map((it) => it.bvid))], [["BV851", "总标准", "夹K", "ds", true, true], ["BV852"]]); + // Emptied again, each video goes back to its folder's 判断标准. + delete t.S.folderCriteria.all; + assert.deepStrictEqual(plain(t.staleCoarse().map((it) => it.bvid)), ["BV850", "BV853"]); + assert.strictEqual(vm.runInContext("judgeOf", ctx)(vids[2]).crit, "L 新标准"); + t.S.settings.aiPlatforms = platforms; + delete store[t.K.folderAi]; Object.assign(t, { askConfirm: async () => true }); - Object.assign(t.S, { titleRes: {}, analyses: {}, folderCriteria: {}, folderIntro: {}, loadAll: null }); + Object.assign(t.S, { titleRes: {}, analyses: {}, folderCriteria: {}, folderAi: {}, folderIntro: {}, loadAll: null }); } - for (const thinkingToggle of [false, true]) { - t.S.settings.thinkingToggle = thinkingToggle; - t.handleAiError("模型输出被截断", "AI_TRUNCATED"); - assert.strictEqual(t.el.bannerText.textContent.endsWith("关闭思考"), thinkingToggle, "only a platform with the thinking switch is told to turn it off"); + // Turning thinking off is offered only when the open folder thinks on a platform that can switch it (判断标准). + { + const was = { mediaId: t.S.mediaId, folderAi: t.S.folderAi, providers: t.S.settings.aiPlatforms }; + t.S.mediaId = "TF"; + t.S.settings.aiPlatforms = [{ id: "ds", name: "DeepSeek", model: "m", caps: { thinking: true, search: false } }, { id: "oa", name: "OpenAI", model: "g", caps: { thinking: false, search: false } }]; + for (const [rec, want] of [[null, false], [{ providerId: "ds", thinking: true }, true], [{ providerId: "ds", thinking: false }, false], [{ providerId: "oa", thinking: true }, false]]) { + t.S.folderAi = rec ? { TF: { ...rec, search: false } } : {}; + t.handleAiError("模型输出被截断", "AI_TRUNCATED"); + assert.strictEqual(t.el.bannerText.textContent.endsWith("关闭思考"), want, JSON.stringify(rec)); + } + Object.assign(t.S, { mediaId: was.mediaId, folderAi: was.folderAi }); + t.S.settings.aiPlatforms = was.providers; } - t.S.settings.thinkingToggle = false; // C553: a cut 细看 answer names 细看's own limit; 粗看 and AI 打标签 share 粗看's. assert.ok(t.el.bannerText.textContent.includes("调大粗看输出上限"), t.el.bannerText.textContent); t.el.banner.hidden = true; openFake("all", []); - assert.strictEqual(t.activityState().text, "字幕细看完成 2 个", "back in its folder, the newest finished line shows (细看 ran after 粗看)"); + assert.strictEqual(t.activityState().text, "按新标准重新细看完成 1 个", "back in its folder, the newest finished line shows (细看 ran after 粗看)"); for (const job of ["stage1", "group"]) await vm.runInContext("runs", ctx).run(job, { line: () => "", next: () => null }); // drops their finished lines // Back on the tab: the id check alone when nothing changed, no full load. @@ -4110,14 +4308,6 @@ const unfavOnlyOf = (d) => Object.fromEntries(Object.entries(d).filter(([, v]) = await wait(); assert.deepStrictEqual(texts(), { BV1: "中文字", BV2: "侧边栏的", BV3: "视频记录的" }); t.render = realRender; - // 开启思考 follows the platform the side panel picks now: opening 收藏夹设置 asks the background again. - handlers["triage-settings-get"] = () => ({ ok: true, data: { thinkingToggle: true } }); - t.S.settings.thinkingToggle = false; - t.openSettings(); - await wait(); - assert.deepStrictEqual([t.S.settings.thinkingToggle, t.el.thinkingRow.hidden], [true, false], "the switch follows the platform in use"); - delete handlers["triage-settings-get"]; - t.el.settingsDialog.close?.(); // a background re-render waits while a note is composing, and runs on compositionend. t.S.items = []; t.document.activeElement = { closest: (s) => (s.split(", ").includes("[data-note]") ? note : null) }; diff --git a/extension/wording.selftest.js b/extension/wording.selftest.js index 46ebd65d..b1018901 100644 --- a/extension/wording.selftest.js +++ b/extension/wording.selftest.js @@ -226,6 +226,7 @@ const DUPLICATES = [ ["整篇覆盖会替换全部内容:", "content.js download.js", "例外:同上,「该笔记已存在」确认框的两份"], ["账号已注销", "triage/follow-bg.js triage/follow.js", "例外:follow-bg.js 里的是 B站 给注销账号的占位名(接口数据,按它认人),follow.js 显示的状态名恰好同字"], ["UP 标签", "bili-surfaces.js triage/follow.js triage/shared.js", "待修:C55"], + ["AI 平台", "options.html triage/triage.html", "例外:设置页那一节的名字,分拣台判断标准弹窗里选平台的那一栏用同一个词指同一个东西,各是静态 html 的标题"], ]; { const where = new Map(); // text → [file:line]