From 0bd00f0c72f828bfb540db033c62fc09ebdd9173 Mon Sep 17 00:00:00 2001
From: YangHonghang <60209620+YangHonghang@users.noreply.github.com>
Date: Wed, 4 Nov 2026 22:20:07 +0800
Subject: [PATCH] window-warmup 0.1.2: effort-variant caches keep their public
models, and Report a problem carries anonymized diagnostics (YangHonghang,
#726)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
window-warmup 0.1.2 (@magpie-community/page-window-warmup).
- Candidates are now the model cache, /v1/models and the chosen list together
(deduplicated by full id), so a cache that stores effort variants
(antigravity's gemini-3.8-flash-high/-low/-tiered) no longer leaves an
account with no models; layer 3 still keeps only public ids.
- A "Report a problem" link at the foot of the page: GET /api/diagnostics
(read-only, no model request, works for fatal and read-only instances)
builds an anonymized report (accounts and keys as acct-N / key-N, task and
card names left out, free text scrubbed of emails, key-shaped strings,
Bearer tokens, URL secrets and home user names, saveError included), and a
two-step copy puts an issue link and the report on the clipboard inside
magpie's sandboxed frame.
Reviewed at head bf66c2b7302c66395833bb3e93054a55901d77c1, with main 9bba5fed
merged in locally, on a Mac mini (macOS, Bun 1.4.2):
- bun test in packages/window-warmup: 259 pass, 1 skip (browser smoke without
Playwright), 0 fail; the diagnostics file runs in milliseconds now, with no
wait on a connect timeout.
- tests/browser.test.ts with Playwright 1.62.0: 4 pass in Chromium and
WebKit, the sandboxed two-step copy included.
- tsc --noEmit ok; dist/ rebuilt with scripts/build.ts is byte-identical to
the committed one; bun scripts/check.mjs ok for every package.
- Broken by hand, one at a time: exporting saveError without scrub turns the
new EACCES /home/alice case red; baseView passing every host turns the
baseView test red; an unsettled /v1/models fetch turns the unreachable
gateway test red; dropping the home-directory rule turns both privacy
tests red.
- Left as is: the header comment in src/diagnostics.ts still says 几十 KB,
and the unreachable-gateway test connects to a port it has just freed,
which another listener could take in between.
---
packages/window-warmup/AGENTS.md | 3 +-
packages/window-warmup/README.md | 24 +-
packages/window-warmup/dist/plugin.js | 241 ++++++++++++++-
packages/window-warmup/dist/ui/app.js | 188 ++++++++++++
packages/window-warmup/dist/ui/index.html | 2 +
packages/window-warmup/dist/ui/style.css | 9 +
packages/window-warmup/package.json | 2 +-
packages/window-warmup/src/accounts.ts | 13 +-
packages/window-warmup/src/diagnostics.ts | 287 ++++++++++++++++++
packages/window-warmup/src/scheduler.ts | 42 +++
packages/window-warmup/src/server.ts | 15 +
packages/window-warmup/tests/app.test.ts | 32 ++
packages/window-warmup/tests/browser.test.ts | 46 +++
.../window-warmup/tests/diagnostics.test.ts | 258 ++++++++++++++++
packages/window-warmup/tests/gateway.test.ts | 22 ++
.../window-warmup/tests/scheduler.test.ts | 40 +++
packages/window-warmup/tests/server.test.ts | 15 +
packages/window-warmup/web/app.ts | 123 ++++++++
packages/window-warmup/web/i18n.ts | 57 ++++
packages/window-warmup/web/index.html | 2 +
packages/window-warmup/web/style.css | 9 +
21 files changed, 1412 insertions(+), 18 deletions(-)
create mode 100644 packages/window-warmup/src/diagnostics.ts
create mode 100644 packages/window-warmup/tests/diagnostics.test.ts
diff --git a/packages/window-warmup/AGENTS.md b/packages/window-warmup/AGENTS.md
index 32f189f..a712e91 100644
--- a/packages/window-warmup/AGENTS.md
+++ b/packages/window-warmup/AGENTS.md
@@ -46,6 +46,7 @@ bun test tests/scheduler.test.ts -t "关键字" # 按用例名过滤
- **`src/gateway.ts`**:与本地 magpie 网关(`MAGPIE_ADDR`,默认 `127.0.0.1:3425`)通信:`/v1/models`、`/v1/magpie/quotas`(含单卡 refresh)、`/v1/chat/completions`;思考档位 `pickEffort` 每次发送前现算。
- **`src/accounts.ts`**:**统一账号规则的唯一实现**——`/api/catalog` 与调度器共用(账号合并、key 卡挂回、按账号收窄模型、`pickAutoModel`)。禁止在别处另写一套,否则页面显示与实际发送会不一致。
- **`src/magpie-files.ts`**:只读 magpie 的 `providers.json` 与模型缓存。`readDefaultKeyDirectory` / `readDefaultModelCache` 是目录与调度器共用的默认读取入口;`xdgConfigHome` 是插件数据目录、旧包迁移与 Magpie 配置目录共用的 XDG 解析(只认绝对路径)。**红线**:key 原文只允许在 `readKeyDirectory` 内「读 → 算指纹(sha256 前 5 字节 hex)」后即丢,不得进入返回值、日志、错误信息或缓存;JSON 解析失败一律换成固定文案 `BROKEN_PROVIDERS_MESSAGE`。除 key 指纹与 `accountModels` 外还取每供应商的 `models`(chosen 启用清单):模型被路由组 `unlists` 藏出 `/v1/models` 时它是唯一的存在性来源。
+- **`src/diagnostics.ts`**:`GET /api/diagnostics` 的诊断导出(页面底部「反馈问题」把它拼进 issue 正文,`web/app.ts` 的 `issueURL` / `issueBody`;插件框架只有 `allow-scripts`,下载、弹窗、Clipboard API 都被拦,复制只能用 `execCommand("copy")`),只读、不发模型请求;在只读拦截之前,fatal / 只读实例也能导出。内容是排错现场:各供应商的原始输入(`/v1/models`、chosen、模型缓存、额度卡)与 `/api/catalog` 计算结果并列,外加任务、最近执行记录、marks 与 `Scheduler.previewSend`(按 `resolveSend` 现算此刻会怎么发)。**红线**:账号名、key 指纹、key 名、任务名、额度卡显示名不得原样出现——账号与 key 统一经 `Aliases` 换成 `acct-N` / `key-N`(全份导出一一对应),自由文本一律过 `scrubber`;新增导出字段时先想清楚它是否可能夹带这些原文。列表与文本有上限(`LIST_MAX` / `RUNS_PER_TASK` / `TEXT_MAX`),截断记入 `truncated`。`tests/diagnostics.test.ts` 逐项断言隐私原文不出现。
- **`src/store.ts`**:`state.json` 临时文件 + rename 落盘,损坏时拒绝启动且绝不改动原文件;`service.lock` 原子排他创建 + pid 活性判断(活性不明不抢占,pid 存活但端口无本插件应答视为陈旧锁接管);一次性从旧包 `scheduled-messages` 迁移 `state.json`。
## 供应商 → 账号 → 模型级联(无官方接口的绕行路径)
@@ -65,7 +66,7 @@ Magpie 不提供「供应商 / 账号 / 每账号可用模型」的列表接口
2. `accountModels[指纹或小写账号名]`,比对不带供应商前缀的 id;
3. 仍在 `/v1/models` 里,或仍在 chosen 启用清单(`providers.json` 的 `models`)里——后者接住被路由组 `unlists` 藏出 `/v1/models` 的模型。
- 无缓存时候选退化为 `/v1/models` ∪ chosen(按完整 id 去重,`perAccount: false`),两者皆无时返回 `list: null`。
+ 候选 = 缓存 ∪ `/v1/models` ∪ chosen(按完整 id 去重)。缓存 id 不一定是对外 id(antigravity 缓存存分档变体 `gemini-3.8-flash-high`,对外只有 `gemini-3.8-flash`),只用缓存会整列表为空;缓存外的候选没有 `Keys`,第 1 层视为所有 key 可见。无缓存时 `perAccount: false`,三者皆无时返回 `list: null`。
- **发送头**(`pinFor`):订阅账号原样发;key 指纹在启用 key 不少于 2 把(目录读不出时按 2 把处理)时发 `
#<指纹>`,只有 1 把时不带头,因为此时候选 ID 就是供应商 id;其余值(旧任务存的 key 名)原样发。非 ASCII 头值按 UTF-8 字节写入(`send`)。
- **文件位置**(`magpieDirs`):从安装路径 `<配置目录>/plugins/node_modules/@magpie-community/page-window-warmup/dist` 上溯得到配置目录;旧独立包名 `node_modules/magpie-window-warmup/dist` 也识别(升级用户的旧路径)。再据此区分安装版和便携版的缓存目录。`tests/magpie-files.test.ts` 覆盖了新作用域路径、旧路径、Windows 与便携版。
diff --git a/packages/window-warmup/README.md b/packages/window-warmup/README.md
index 6cb0b09..0c130e6 100644
--- a/packages/window-warmup/README.md
+++ b/packages/window-warmup/README.md
@@ -58,6 +58,26 @@ magpie plugin add @magpie-community/page-window-warmup
- 找不到账号或窗口时记失败原因,不发送;额度快照取不到(刷新一直失败)时静默等下一轮刷新,不写执行记录。
- magpie 刚启动、额度缓存还是空的时候,插件会兜底读一次完整额度接口(只读余额,不发模型请求,15 秒超时);两次兜底读取至少间隔 5 分钟。
+## 反馈问题(自动附上诊断日志)
+
+遇到选不到账号/模型、窗口没触发、发送失败等问题,点页面底部的「反馈问题」:
+
+1. 点「① 复制 issue 链接」,在浏览器地址栏粘贴打开。链接指向社区仓库的新建 issue 页,标题已预填 `window-warmup: `。
+2. 回到本页点「② 复制问题内容」,粘贴到 issue 正文。内容是问题模板(描述、复现步骤、环境),后面折叠附着脱敏后的诊断日志。
+
+之所以要复制两次:Magpie 把插件页放在 `sandbox="allow-scripts"` 的框架里,插件页不能打开新窗口、不能下载文件,也不能用剪贴板 API,只能整段复制文本。诊断日志有十几 KB,超出 GitHub 预填链接能带的长度,所以要单独粘贴。直接用浏览器打开本插件服务的页面时,「在 GitHub 新建 issue」链接可以直接点开。
+
+收集诊断只读,不发模型请求,也不改任何任务或状态。诊断日志里有:
+
+- 插件版本、运行时、网关与各数据文件能否读到;
+- 每个供应商的原始数据(`/v1/models` 的模型与思考档位、`providers.json` 的启用清单与 `accountModels`、Magpie 模型缓存、额度卡窗口),以及页面目录据此算出的账号与可选模型——两边并列,能直接看出是哪一步对不上;
+- 每个任务的配置、调度标记、下次执行点,以及「此刻会发给哪个账号、用哪个模型和档位」的预演结果(只算不发);
+- 每个任务最近 20 条执行记录。
+
+隐私:账号名(邮箱等)、key 原文、key 指纹、key 名、任务名、额度卡显示名都不会导出。账号和 key 换成 `acct-1`、`key-1` 这样的别名,同一份文件里同一个账号始终是同一个别名;执行记录原因、上游报错等自由文本会抹掉邮箱、key 形态串、`Bearer` 口令、URL 里的口令参数和家目录用户名(含状态文件写入失败时报错里的路径)。已知账号名少于 4 个字符时(如 `bob`),不会从自由文本里替换,免得误伤 `GLM-5.3` 这类模型 id;这类短名字若出现在上游报错里会原样保留。供应商 id、模型 id、窗口名会原样保留,这些是排错所需。提交前可以在 GitHub 的预览里自己检查一遍。
+
+体积:每个列表最多 200 条、每段文本最多 400 字,超出部分在 `truncated` 里注明,常见规模在十几 KB。整段正文超过 GitHub 的字数上限时改用紧凑 JSON,仍然超出就截断并注明。
+
## 供应商 → 账号 → 模型:级联选择是怎么拼出来的
Magpie 没有给插件提供「列出供应商、每个供应商有哪些账号、每个账号能用哪些模型」的接口:`/v1/models` 只有一张不分账号的模型清单,`/v1/magpie/quotas` 只有额度卡,账号与 key 的对应关系只存在于 Magpie 自己的配置和缓存文件里。插件把下面四处现成数据拼成一份目录,每一级的做法与它可能对不上的情况都在下面说明;拼不上的后果统一收在[「已知限制」](#已知限制插件拿不到的信息)的数据缺口表里。
@@ -104,7 +124,7 @@ Magpie 内部用「候选 ID」区分同一供应商下的多把 key 和多个
没有模型缓存的供应商退化为 `/v1/models` ∪ 启用清单的全部模型(去重),所有账号共用同一份清单,跳过第 1 层——模型缓存文件只有 key 型供应商才写,插件型订阅供应商(zcode、各类 OpenCode 登录插件)没有按账号的模型可见性,自动选出的模型该账号可能无权使用,发送时才发现。缓存、`/v1/models` 与启用清单三者都拿不到该供应商的模型时,模型下拉禁用,并提示到 Magpie 里「获取模型」。
-**可能对不上**:模型缓存是 Magpie 上次「获取模型」的快照,里面的模型 id 形态可能和 `/v1/models` 漂移(例如缓存里是 `gemini-3.8-flash-high` 等档位形态,清单里是 `gemini-3.8-flash`),全部对不上时该供应商的模型列表为空;去 Magpie 重新「获取模型」刷新缓存即可恢复。
+**可能对不上**:模型缓存里的 id 不一定是对外 id。例如 antigravity 的缓存存的是分档变体(`gemini-3.8-flash-high` / `-low` / `-tiered`),`/v1/models` 与启用清单里只有合并后的 `gemini-3.8-flash`,重新「获取模型」也不会变。所以候选模型取缓存 ∪ `/v1/models` ∪ 启用清单(0.1.2 起),再经第 3 层只留对外 id;缓存外的模型没有 `Keys`,第 1 层按所有 key 可见处理。
下拉首项「自动」按「模型与思考档位」一节的规则,从过滤后的列表里现选,并在旁边附注当前会选中哪个模型。
@@ -149,7 +169,7 @@ Magpie 内部用「候选 ID」区分同一供应商下的多把 key 和多个
| 账号与模型目录接口 | 从 `/v1/models`、额度卡、`providers.json`、模型缓存四份数据拼目录 | 下面各行的一切错配场景 |
| `/v1/models` 里被路由组隐藏的模型(`unlists: true`,清单不显示但发送仍接受) | 用 `providers.json` 的启用清单兜底判定存在(0.1.1 起) | 旧版本表现为模型下拉禁用、任务报「已不在模型列表」;启用清单也过期时(模型真下线但没重新获取)会照发并收到上游报错 |
| 插件型订阅供应商的按账号模型可见性(缓存文件只有 key 型供应商写) | 不按账号区分,列出全部模型 | 自动选出的模型该账号可能无权使用,发送时才失败 |
-| 缓存模型 id 与清单 id 的统一 | 直接比对 id | 形态漂移时该供应商模型列表为空,去 Magpie 重新「获取模型」可恢复 |
+| 缓存模型 id 与清单 id 的统一 | 候选取缓存 ∪ `/v1/models` ∪ 启用清单,按对外 id 收窄(0.1.2 起) | 旧版本表现为该供应商「这个账号没有可用模型」;缓存外的模型拿不到按 key 的可见性,key 账号可能选中自己无权使用的模型,发送时才失败 |
| key 与账号对应关系的接口 | sha256 指纹三方对齐(key 目录、缓存 `Keys`、发送头) | Magpie 更改 keyID 算法时三处同时失配,key 账号集体失效 |
| 起名 key 之外的额度卡匹配方式 | 指纹反查 key 名再按卡名匹配 | 没起名的 key 匹配不上(卡名是打码形态),账号没有窗口,窗口任务会一直报「账号的额度里没有这个窗口」 |
| 订阅供应商的稳定 id | 额度卡上的供应商名按订阅 agent 名对 | 在 Magpie 里改过名的供应商,目录里的账号与模型可能匹配不上 |
diff --git a/packages/window-warmup/dist/plugin.js b/packages/window-warmup/dist/plugin.js
index 89ab399..082a6be 100644
--- a/packages/window-warmup/dist/plugin.js
+++ b/packages/window-warmup/dist/plugin.js
@@ -66,12 +66,9 @@ function windowsForAccount(provider, account, quotas, keyDir) {
return card ? keepWindows(card.windows) : [];
}
function candidatesOf(provider, models, cache, chosen) {
- if (cache) {
- return cache.map((c) => ({ full: `${provider}/${c.id}`, bare: c.id, keys: c.keys }));
- }
const prefix = `${provider}/`;
- const seen = new Set;
- const out = [];
+ const out = (cache ?? []).map((c) => ({ full: `${prefix}${c.id}`, bare: c.id, keys: c.keys }));
+ const seen = new Set(out.map((c) => c.full));
for (const m of models) {
if (seen.has(m))
continue;
@@ -965,6 +962,197 @@ async function send(base, task, pin, effort, signal, timeoutMs = SEND_TIMEOUT_MS
import { randomBytes, timingSafeEqual } from "crypto";
import { readFile as readFile3 } from "fs/promises";
import path2, { basename, extname, join as join3, resolve as resolve2 } from "path";
+// package.json
+var version = "0.1.2";
+
+// src/diagnostics.ts
+var DIAGNOSTICS_SCHEMA = "window-warmup-diagnostics/1";
+var LIST_MAX = 200;
+var RUNS_PER_TASK = 20;
+var TEXT_MAX = 400;
+var SCRUB_MIN_LEN = 4;
+var MASKED_SEP2 = " \xB7 ";
+
+class Aliases {
+ byRaw = new Map;
+ acctN = 0;
+ keyN = 0;
+ key(fingerprint, name) {
+ let alias = this.byRaw.get(fingerprint);
+ if (!alias) {
+ alias = `key-${++this.keyN}`;
+ this.byRaw.set(fingerprint, alias);
+ }
+ if (name && !this.byRaw.has(`name:${name.toLowerCase()}`))
+ this.byRaw.set(`name:${name.toLowerCase()}`, alias);
+ return alias;
+ }
+ account(raw) {
+ if (!raw)
+ return "";
+ const hit = this.byRaw.get(raw) ?? this.byRaw.get(`login:${raw.toLowerCase()}`);
+ if (hit)
+ return hit;
+ const alias = `acct-${++this.acctN}`;
+ this.byRaw.set(`login:${raw.toLowerCase()}`, alias);
+ return alias;
+ }
+ keyCard(user) {
+ const name = user.includes(MASKED_SEP2) ? user.slice(0, user.indexOf(MASKED_SEP2)) : user;
+ return this.byRaw.get(`name:${name.toLowerCase()}`) ?? this.account(user);
+ }
+ accountKey(k) {
+ return this.byRaw.get(k) ?? this.account(k);
+ }
+ raws() {
+ return [...this.byRaw].map(([k, v]) => [k.replace(/^(login|name):/, ""), v]).filter(([k]) => k.length >= SCRUB_MIN_LEN).sort((a, b) => b[0].length - a[0].length);
+ }
+}
+var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+function scrubber(aliases) {
+ const known = aliases.raws().map(([raw, alias]) => [new RegExp(escapeRe(raw), "gi"), alias]);
+ return (s) => {
+ let out = s;
+ for (const [re, alias] of known)
+ out = out.replace(re, alias);
+ out = out.replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, "").replace(/\bBearer\s+\S+/gi, "Bearer ").replace(/\b(sk|pk|rk|ak|key)-[\w-]{8,}/gi, "").replace(/([?&](?:key|api_?key|token|access_token|auth|sig|signature|cookie)=)[^&\s"']+/gi, "$1").replace(/[A-Za-z0-9_-]{32,}/g, "").replace(/(\/home|\/Users)\/[^/\s"']+/g, "$1/").replace(/([A-Za-z]:\\Users\\)[^\\\s"']+/gi, "$1");
+ return out.length > TEXT_MAX ? `${out.slice(0, TEXT_MAX)}\u2026\uFF08\u622A\u65AD\uFF0C\u539F\u957F ${out.length}\uFF09` : out;
+ };
+}
+function baseView(base) {
+ try {
+ const u = new URL(base);
+ return ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname) ? `${u.protocol}//${u.host}` : "<\u975E\u672C\u673A\u5730\u5740>";
+ } catch {
+ return "<\u65E0\u6CD5\u89E3\u6790>";
+ }
+}
+async function buildDiagnostics(input) {
+ const now = input.now ?? new Date;
+ const truncated = [];
+ const cap = (list, path, max = LIST_MAX) => {
+ if (list.length <= max)
+ return list;
+ truncated.push(`${path}\uFF1A\u5171 ${list.length} \u6761\uFF0C\u53EA\u5BFC\u51FA\u524D ${max} \u6761`);
+ return list.slice(0, max);
+ };
+ const settle = (p) => p.then((ok) => ({ ok }), (e) => ({ error: errText(e) }));
+ const dirs = magpieDirs();
+ const [models, quotas, keyDir, catalog] = await Promise.all([
+ settle(fetchModels(input.base)),
+ settle(fetchQuotas(input.base)),
+ settle(readKeyDirectory(dirs.config)),
+ settle(fetchCatalog(input.base))
+ ]);
+ const dir = "ok" in keyDir ? keyDir.ok : null;
+ const quotaEntries = "ok" in quotas ? quotas.ok.entries : [];
+ const rawModels = "ok" in models ? models.ok : [];
+ const aliases = new Aliases;
+ for (const entry of dir?.values() ?? [])
+ for (const k of entry.keys)
+ aliases.key(k.fingerprint, k.name);
+ const cardAlias = (q) => q.viaKey ? aliases.keyCard(q.account) : aliases.account(q.account);
+ for (const q of quotaEntries)
+ cardAlias(q);
+ for (const t of input.tasks)
+ aliases.account(t.account);
+ for (const q of input.scheduler?.quotaEntries() ?? [])
+ cardAlias(q);
+ const scrub = scrubber(aliases);
+ const pids = new Set([
+ ...rawModels.map(modelProvider).filter(Boolean),
+ ...quotaEntries.map((q) => q.provider),
+ ...dir?.keys() ?? [],
+ ...input.tasks.map((t) => t.provider)
+ ]);
+ const catalogById = new Map(("ok" in catalog ? catalog.ok.providers : []).map((p) => [p.id, p]));
+ const providers = await Promise.all([...pids].sort().map(async (pid) => {
+ const entry = dir?.get(pid);
+ const v1 = rawModels.filter((m) => modelProvider(m) === pid);
+ const cache = await readDefaultModelCache(pid).catch(() => null);
+ const cat = catalogById.get(pid);
+ const path = `providers.${pid}`;
+ return {
+ id: pid,
+ v1Models: cap(v1.map((m) => ({
+ id: m.id,
+ owned_by: m.owned_by,
+ reasoning: m.reasoning,
+ reasoning_levels: m.reasoning_levels,
+ supported_reasoning_levels: m.supported_reasoning_levels?.map((l) => l.effort)
+ })), `${path}.v1Models`),
+ providersJson: entry ? {
+ chosen: cap(entry.models, `${path}.chosen`),
+ keys: entry.keys.map((k) => ({ alias: aliases.key(k.fingerprint, k.name), named: k.name !== "" })),
+ accountModels: Object.fromEntries(Object.entries(entry.accountModels).map(([k, v]) => [aliases.accountKey(k), v]))
+ } : null,
+ modelCache: cache ? cap(cache.map((c) => ({ id: c.id, keys: c.keys.map((fp) => aliases.accountKey(fp)) })), `${path}.modelCache`) : null,
+ quotaCards: quotaEntries.filter((q) => q.provider === pid).map((q) => ({ account: cardAlias(q), viaKey: q.viaKey, readAt: q.readAt ?? null, windows: q.windows })),
+ catalog: cat ? {
+ accounts: cat.accounts.map((a) => ({
+ id: a.kind === "key" ? aliases.accountKey(a.id) : aliases.account(a.id),
+ kind: a.kind,
+ windows: a.windows.map((w) => w.name),
+ models: a.models === null ? null : cap(a.models, `${path}.catalog.accounts.models`),
+ perAccount: a.perAccount,
+ autoModel: a.autoModel
+ })),
+ autoAccountModels: cat.autoAccountModels === null ? null : cap(cat.autoAccountModels, `${path}.catalog.autoAccountModels`),
+ autoModel: cat.autoModel
+ } : null
+ };
+ }));
+ const scheduler = input.scheduler;
+ const next = scheduler?.snapshot().next ?? {};
+ const tasks = await Promise.all(input.tasks.map(async (t) => {
+ const preview = scheduler ? await scheduler.previewSend(t) : { error: "\u8C03\u5EA6\u5668\u672A\u8FD0\u884C" };
+ const marks = input.marks[t.id];
+ return {
+ id: t.id,
+ enabled: t.enabled,
+ provider: t.provider,
+ account: aliases.account(t.account),
+ accountKind: /^[0-9a-f]{10}$/.test(t.account) ? "key" : t.account ? "login" : "",
+ model: t.model || "<\u81EA\u52A8>",
+ trigger: t.trigger,
+ createdAt: t.createdAt,
+ updatedAt: t.updatedAt,
+ next: next[t.id] ?? null,
+ marks: marks ? { ...marks, resetKeys: marks.resetKeys.slice(-5).map(scrub) } : null,
+ sendPreview: "error" in preview ? { error: scrub(preview.error) } : { ...preview, pin: preview.pin === null ? null : scrub(preview.pin) }
+ };
+ }));
+ const runs = input.tasks.flatMap((t) => input.runs.filter((r) => r.taskId === t.id).slice(-RUNS_PER_TASK).map((r) => ({ ...r, reason: scrub(r.reason) })));
+ return {
+ schema: DIAGNOSTICS_SCHEMA,
+ note: "\u8D26\u53F7\u4E0E key \u5DF2\u6362\u6210\u522B\u540D\uFF08acct-N / key-N\uFF09\uFF0C\u4EFB\u52A1\u540D\u4E0E\u989D\u5EA6\u5361\u663E\u793A\u540D\u672A\u5BFC\u51FA\uFF0C\u81EA\u7531\u6587\u672C\u5DF2\u8131\u654F",
+ generatedAt: now.toISOString(),
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ plugin: { version, bun: Bun.version, platform: `${process.platform}-${process.arch}` },
+ gateway: {
+ base: baseView(input.base),
+ models: "ok" in models ? `ok\uFF08${models.ok.length} \u4E2A\uFF09` : scrub(models.error),
+ quotas: "ok" in quotas ? `ok\uFF08${quotas.ok.entries.length} \u5F20\u5361\uFF09` : scrub(quotas.error),
+ catalog: "ok" in catalog ? "ok" : scrub(catalog.error)
+ },
+ files: {
+ configDir: scrub(dirs.config),
+ cacheDir: scrub(dirs.cache),
+ dataDir: scrub(input.dir),
+ providersJson: "ok" in keyDir ? keyDir.ok.size > 0 ? `ok\uFF08${keyDir.ok.size} \u4E2A\u4F9B\u5E94\u5546\uFF09` : "\u6CA1\u6709\u6587\u4EF6\u6216\u4E3A\u7A7A" : keyDir.error
+ },
+ service: {
+ fatal: input.fatal === null ? null : scrub(input.fatal),
+ lockedBy: input.lockedBy,
+ saveError: scrub(scheduler?.snapshot().saveError ?? "") || null,
+ scheduler: scheduler?.debugView() ?? null
+ },
+ tasks,
+ runs,
+ providers,
+ truncated
+ };
+}
// src/scheduler.ts
import { randomUUID } from "crypto";
@@ -1167,6 +1355,32 @@ class Scheduler {
saveError: this.saveError === null ? null : `\u72B6\u6001\u6587\u4EF6\u5199\u4E0D\u8FDB\u53BB\uFF1A${this.saveError}`
};
}
+ debugView() {
+ return {
+ quotaAt: this.quota?.at.toISOString() ?? null,
+ quotaStale: this.quotaStale,
+ quotaTried: this.quotaTried,
+ keyDirLoaded: this.keyDirMap !== null,
+ inflight: [...this.inflight.keys()],
+ armedFor: Object.fromEntries([...this.armedFor].map(([id, at]) => [id, at.toISOString()]))
+ };
+ }
+ quotaEntries() {
+ return this.quota?.entries ?? null;
+ }
+ async previewSend(task) {
+ try {
+ const resolved = await this.resolveSend(task, await this.modelsFn(this.base));
+ if ("error" in resolved)
+ return resolved;
+ const pick = pickEffort(resolved.model);
+ if ("error" in pick)
+ return pick;
+ return { model: resolved.id, pin: resolved.pin, effort: pick.send };
+ } catch (e) {
+ return { error: errText(e) };
+ }
+ }
snapshotTask(task, now, next, points) {
if (task.trigger.kind === "window") {
const due = this.currentWindowDue(task, now);
@@ -1589,7 +1803,7 @@ class Scheduler {
import { link, mkdir, readdir, readFile as readFile2, rename, unlink, writeFile } from "fs/promises";
import { join as join2 } from "path";
import { randomUUID as randomUUID2 } from "crypto";
-var RUNS_PER_TASK = 50;
+var RUNS_PER_TASK2 = 50;
var RESET_KEYS_PER_TASK = 20;
var STATE_FILE = "state.json";
var LOCK_FILE = "service.lock";
@@ -1724,7 +1938,7 @@ function truncateState(data) {
const r = data.runs[i];
const n = (counts.get(r.taskId) ?? 0) + 1;
counts.set(r.taskId, n);
- if (n <= RUNS_PER_TASK)
+ if (n <= RUNS_PER_TASK2)
kept.push(r);
}
data.runs = kept.reverse();
@@ -2060,6 +2274,19 @@ async function startService(opts) {
return json({ error: errText(e) }, 502, cors);
}
}
+ if (req.method === "GET" && path === "/api/diagnostics") {
+ const data = await buildDiagnostics({
+ base: opts.base,
+ dir: opts.dir,
+ tasks: store?.data.tasks ?? [],
+ runs: store?.data.runs ?? [],
+ marks: store?.data.marks ?? {},
+ scheduler,
+ fatal,
+ lockedBy
+ });
+ return json(data, 200, cors);
+ }
const blocked = readonlyBlock(cors);
if (blocked)
return blocked;
diff --git a/packages/window-warmup/dist/ui/app.js b/packages/window-warmup/dist/ui/app.js
index 77aa74a..c891f0a 100644
--- a/packages/window-warmup/dist/ui/app.js
+++ b/packages/window-warmup/dist/ui/app.js
@@ -271,6 +271,25 @@ var I18N = {
"页面缺少访问口令,请从 Magpie 的插件页重新打开。": "The page is missing its access token; please reopen it from Magpie's plugin page.",
"窗口预热": "Window Warmup",
"新建任务": "New task",
+ "反馈问题": "Report a problem",
+ "(把「复制问题内容」复制的内容粘贴到这里,替换这一行)": "(Paste what “Copy the report” copied here, replacing this line)",
+ "问题描述": "What happened",
+ "(发生了什么,期望是什么)": "(What happened, and what you expected)",
+ "复现步骤": "Steps to reproduce",
+ "环境": "Environment",
+ "诊断日志(已脱敏)": "Diagnostics (anonymized)",
+ "(诊断日志过长,已截断)": "(diagnostics too long, truncated)",
+ "问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。": "The report includes an anonymized diagnostics log (accounts, keys and task names are replaced); you can preview it on GitHub before submitting.",
+ "① 复制 issue 链接": "① Copy the issue link",
+ "在 GitHub 新建 issue": "New issue on GitHub",
+ "到浏览器地址栏粘贴打开": "paste it into your browser's address bar",
+ "② 复制问题内容": "② Copy the report",
+ "正在收集诊断…": "Collecting diagnostics…",
+ "粘贴到 issue 正文": "paste it into the issue body",
+ "诊断收集失败:": "Collecting diagnostics failed: ",
+ "链接已复制。": "Link copied.",
+ "问题内容已复制。": "Report copied.",
+ "复制失败:浏览器不允许这个页面写剪贴板。": "Copy failed: the browser doesn't let this page write to the clipboard.",
"说明": "Help",
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。": "Each message is billed under the provider's own quota rules and may draw on bonus quota or API balance; a successful send does not guarantee the window has started counting.",
"Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。": "Nothing runs while Magpie is closed; after it reopens, each task catches up at most once.",
@@ -383,6 +402,25 @@ var I18N = {
"页面缺少访问口令,请从 Magpie 的插件页重新打开。": "頁面缺少存取權杖,請從 Magpie 的外掛頁重新開啟。",
"窗口预热": "窗口預熱",
"新建任务": "新增任務",
+ "反馈问题": "回報問題",
+ "(把「复制问题内容」复制的内容粘贴到这里,替换这一行)": "(把「複製問題內容」複製的內容貼到這裡,取代這一行)",
+ "问题描述": "問題描述",
+ "(发生了什么,期望是什么)": "(發生了什麼,期望是什麼)",
+ "复现步骤": "重現步驟",
+ "环境": "環境",
+ "诊断日志(已脱敏)": "診斷日誌(已去識別化)",
+ "(诊断日志过长,已截断)": "(診斷日誌過長,已截斷)",
+ "问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。": "問題內容會附上去識別化的診斷日誌(帳號、key、任務名都已替換),送出前可以在 GitHub 上先預覽。",
+ "① 复制 issue 链接": "① 複製 issue 連結",
+ "在 GitHub 新建 issue": "在 GitHub 新增 issue",
+ "到浏览器地址栏粘贴打开": "到瀏覽器網址列貼上開啟",
+ "② 复制问题内容": "② 複製問題內容",
+ "正在收集诊断…": "正在收集診斷…",
+ "粘贴到 issue 正文": "貼到 issue 內文",
+ "诊断收集失败:": "診斷收集失敗:",
+ "链接已复制。": "連結已複製。",
+ "问题内容已复制。": "問題內容已複製。",
+ "复制失败:浏览器不允许这个页面写剪贴板。": "複製失敗:瀏覽器不允許這個頁面寫入剪貼簿。",
"说明": "說明",
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。": "訊息按供應商自己的額度規則計費,可能用到贈送額度或 API 餘額;傳送成功不代表窗口一定已開始計時。",
"Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。": "Magpie 關閉期間不會執行,重新開啟後每個任務最多補發一次。",
@@ -495,6 +533,25 @@ var I18N = {
"页面缺少访问口令,请从 Magpie 的插件页重新打开。": "ページにアクセストークンがありません。Magpie のプラグインページから開き直してください。",
"窗口预热": "ウィンドウ予熱",
"新建任务": "新規タスク",
+ "反馈问题": "問題を報告",
+ "(把「复制问题内容」复制的内容粘贴到这里,替换这一行)": "(「報告内容をコピー」でコピーした内容をここに貼り付け、この行と置き換えてください)",
+ "问题描述": "問題の内容",
+ "(发生了什么,期望是什么)": "(何が起きたか、どうなるはずだったか)",
+ "复现步骤": "再現手順",
+ "环境": "環境",
+ "诊断日志(已脱敏)": "診断ログ(匿名化済み)",
+ "(诊断日志过长,已截断)": "(診断ログが長すぎるため切り詰めました)",
+ "问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。": "報告には匿名化した診断ログが付きます(アカウント・key・タスク名は置き換え済み)。送信前に GitHub でプレビューできます。",
+ "① 复制 issue 链接": "① issue のリンクをコピー",
+ "在 GitHub 新建 issue": "GitHub で issue を作成",
+ "到浏览器地址栏粘贴打开": "ブラウザのアドレスバーに貼り付けて開く",
+ "② 复制问题内容": "② 報告内容をコピー",
+ "正在收集诊断…": "診断を収集中…",
+ "粘贴到 issue 正文": "issue の本文に貼り付け",
+ "诊断收集失败:": "診断の収集に失敗しました:",
+ "链接已复制。": "リンクをコピーしました。",
+ "问题内容已复制。": "報告内容をコピーしました。",
+ "复制失败:浏览器不允许这个页面写剪贴板。": "コピーに失敗しました:このページはクリップボードへの書き込みを許可されていません。",
"说明": "ヘルプ",
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。": "メッセージはプロバイダー独自のクォータ規則で課金され、ボーナス額度や API 残高を使うことがあります。送信が成功してもウィンドウの計時が始まったとは限りません。",
"Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。": "Magpie が閉じている間は実行されません。再オープン後、各タスクは最大 1 回キャッチアップ送信されます。",
@@ -536,6 +593,50 @@ var CATALOG_POLL_MS = 60000;
var RUNS_PREVIEW = 5;
var RUNS_MAX = 50;
var DELETE_CONFIRM_MS = 3000;
+var ISSUE_NEW_URL = "https://github.com/magpie-community/plugins/issues/new";
+var ISSUE_BODY_MAX = 60000;
+function issueURL() {
+ const q = new URLSearchParams({
+ title: "window-warmup: ",
+ body: t("(把「复制问题内容」复制的内容粘贴到这里,替换这一行)")
+ });
+ return `${ISSUE_NEW_URL}?${q}`;
+}
+function issueBody(diag) {
+ const info = diag?.plugin ?? {};
+ const head = [
+ `### ${t("问题描述")}`,
+ "",
+ t("(发生了什么,期望是什么)"),
+ "",
+ `### ${t("复现步骤")}`,
+ "",
+ "1. ",
+ "",
+ `### ${t("环境")}`,
+ "",
+ `- window-warmup ${info.version ?? "?"},Bun ${info.bun ?? "?"},${info.platform ?? "?"}`,
+ "",
+ `${t("诊断日志(已脱敏)")}
`,
+ "",
+ "```json"
+ ].join(`
+`);
+ const tail = `
+\`\`\`
+
+
+`;
+ let json = JSON.stringify(diag, null, 1);
+ if (head.length + json.length + tail.length > ISSUE_BODY_MAX)
+ json = JSON.stringify(diag);
+ const room = ISSUE_BODY_MAX - head.length - tail.length;
+ if (json.length > room)
+ json = `${json.slice(0, room - 40)}
+…${t("(诊断日志过长,已截断)")}`;
+ return `${head}
+${json}${tail}`;
+}
var MODEL_SOURCE_HINT = "模型列表来自 Magpie 上次获取的结果。账号和模型对不上时,到 Magpie「供应商」里打开这个供应商,点「获取模型」,再回来刷新本页。";
var NO_MODELS_HINT = "还没有这个供应商的模型列表。请到 Magpie「供应商」里打开它,点「获取模型」。";
var TRIGGERS = [
@@ -1701,6 +1802,7 @@ function render() {
renderBars();
renderSum();
renderList();
+ renderFeedback();
const newBtn = document.getElementById("new");
if (newBtn)
newBtn.disabled = isReadonly();
@@ -1760,6 +1862,86 @@ async function refreshCatalog() {
}
render();
}
+var feedback = null;
+function copyText(text) {
+ const ta = el("textarea");
+ ta.value = text;
+ ta.setAttribute("readonly", "");
+ ta.style.position = "fixed";
+ ta.style.opacity = "0";
+ document.body.append(ta);
+ ta.select();
+ let ok = false;
+ try {
+ ok = document.execCommand("copy");
+ } catch {
+ ok = false;
+ }
+ ta.remove();
+ return ok;
+}
+async function openFeedback() {
+ if (feedback) {
+ feedback = null;
+ renderFeedback();
+ return;
+ }
+ feedback = { body: null, error: "", copied: "" };
+ renderFeedback();
+ try {
+ const diag = await apiJSON("api/diagnostics");
+ if (feedback)
+ feedback.body = issueBody(diag);
+ } catch (e) {
+ if (feedback)
+ feedback.error = errText(e);
+ }
+ renderFeedback();
+}
+function renderFeedback() {
+ const box = document.getElementById("feedback-panel");
+ if (!box)
+ return;
+ const fb = feedback;
+ if (!fb) {
+ box.replaceChildren();
+ return;
+ }
+ const panel = el("div", "fb");
+ panel.append(el("div", "hint", t("问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。")));
+ const url = issueURL();
+ const step1 = el("div", "fb-row");
+ const copyLink = el("button", "btn", t("① 复制 issue 链接"));
+ copyLink.addEventListener("click", () => {
+ fb.copied = copyText(url) ? "link" : "fail";
+ renderFeedback();
+ });
+ const a = el("a", "fb-link", t("在 GitHub 新建 issue"));
+ a.href = url;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer";
+ step1.append(copyLink, a, el("span", "hint mute", t("到浏览器地址栏粘贴打开")));
+ const step2 = el("div", "fb-row");
+ const copyBody = el("button", "btn", t("② 复制问题内容"));
+ copyBody.disabled = fb.body === null;
+ copyBody.addEventListener("click", () => {
+ if (fb.body === null)
+ return;
+ fb.copied = copyText(fb.body) ? "body" : "fail";
+ renderFeedback();
+ });
+ step2.append(copyBody, el("span", "hint mute", fb.body === null && !fb.error ? t("正在收集诊断…") : t("粘贴到 issue 正文")));
+ panel.append(step1, step2);
+ if (fb.error)
+ panel.append(el("div", "hint warn", `${t("诊断收集失败:")}${fb.error}`));
+ if (fb.copied === "link")
+ panel.append(el("div", "hint", t("链接已复制。")));
+ if (fb.copied === "body")
+ panel.append(el("div", "hint", t("问题内容已复制。")));
+ if (fb.copied === "fail")
+ panel.append(el("div", "hint warn", t("复制失败:浏览器不允许这个页面写剪贴板。")));
+ box.replaceChildren(panel);
+}
function applyLook(dark, vars) {
if (dark === true)
document.body.classList.add("dark");
@@ -1793,6 +1975,9 @@ function applyStaticTexts() {
const newBtn = document.getElementById("new");
if (newBtn)
newBtn.textContent = t("新建任务");
+ const fbBtn = document.getElementById("feedback");
+ if (fbBtn)
+ fbBtn.textContent = t("反馈问题");
const info = document.getElementById("info");
if (info) {
info.setAttribute("aria-label", t("说明"));
@@ -1836,6 +2021,7 @@ function init() {
if (!isReadonly() && !isNew)
openNew();
});
+ document.getElementById("feedback")?.addEventListener("click", () => void openFeedback());
document.addEventListener("mousedown", (e) => {
if (popEl && e.target instanceof Node && !popEl.contains(e.target) && !popEl.btn.contains(e.target))
closePop();
@@ -1876,6 +2062,8 @@ export {
deleteArmed,
effortLabel,
forceWindowAccount,
+ issueBody,
+ issueURL,
modelDisplay,
modelHint,
modelOptions,
diff --git a/packages/window-warmup/dist/ui/index.html b/packages/window-warmup/dist/ui/index.html
index 343fca0..4556998 100644
--- a/packages/window-warmup/dist/ui/index.html
+++ b/packages/window-warmup/dist/ui/index.html
@@ -17,6 +17,8 @@
+
+
diff --git a/packages/window-warmup/dist/ui/style.css b/packages/window-warmup/dist/ui/style.css
index b40564c..0b6885d 100644
--- a/packages/window-warmup/dist/ui/style.css
+++ b/packages/window-warmup/dist/ui/style.css
@@ -146,3 +146,12 @@ input.text::placeholder { color:var(--faint); }
.editor > label { text-align:left; padding-top:0; }
.qm .tip { width:min(320px, 86vw); }
}
+
+/* 反馈问题:页脚的低调文字入口 + 两步复制面板(沙箱里打不开外链,只能复制) */
+.foot { display:flex; justify-content:flex-end; margin-top:10px; }
+.link { color:var(--faint); font-size:11.5px; padding:2px 4px; }
+.link:hover { color:var(--fg-2); text-decoration:underline; }
+.fb { margin-top:6px; background:var(--card); border:1px solid var(--line); border-radius:10px; padding:10px 12px; display:flex; flex-direction:column; gap:8px; }
+.fb .hint { margin-top:0; }
+.fb-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
+.fb-link { font-size:12px; color:var(--accent); }
diff --git a/packages/window-warmup/package.json b/packages/window-warmup/package.json
index 76e79c1..61a254c 100644
--- a/packages/window-warmup/package.json
+++ b/packages/window-warmup/package.json
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-window-warmup",
- "version": "0.1.1",
+ "version": "0.1.2",
"description": "窗口预热 Window Warmup:定时消息插件,定时给指定供应商/账号/模型发一条短消息,在额度窗口重置后、每天定时或每隔几小时自动预热保活,提前开启5小时/每周订阅额度(配额)窗口,适用 Codex、Claude、GLM 智谱、ZCode 等。Scheduled keep-alive message to warm up quota / usage / rate limit windows after reset (cron-like).",
"author": "YangHonghang (https://github.com/YangHonghang)",
"type": "module",
diff --git a/packages/window-warmup/src/accounts.ts b/packages/window-warmup/src/accounts.ts
index e26d45c..44c8a33 100644
--- a/packages/window-warmup/src/accounts.ts
+++ b/packages/window-warmup/src/accounts.ts
@@ -135,14 +135,13 @@ interface Candidate {
}
function candidatesOf(provider: string, models: string[], cache: CachedModel[] | null, chosen: string[]): Candidate[] {
- if (cache) {
- return cache.map((c) => ({ full: `${provider}/${c.id}`, bare: c.id, keys: c.keys }));
- }
- // 退化:没有模型缓存(插件型订阅供应商不写这个文件)——/v1/models 的 id,
- // 再并上 chosen(用户明确启用的清单,可能被路由组藏出 /v1/models),按 full 去重
+ // 缓存 id 不一定是对外 id:antigravity 缓存存分档变体(gemini-3.8-flash-high/-low/-tiered),
+ // /v1/models 与 chosen 里只有合并后的 gemini-3.8-flash。所以缓存之外,再并上
+ // /v1/models 的 id 与 chosen(用户明确启用的清单,可能被路由组藏出 /v1/models),按 full 去重;
+ // 缓存外的候选没有按 key 的可见性(keys: null)。没有缓存(插件型订阅供应商不写这个文件)时只有后两者
const prefix = `${provider}/`;
- const seen = new Set();
- const out: Candidate[] = [];
+ const out: Candidate[] = (cache ?? []).map((c) => ({ full: `${prefix}${c.id}`, bare: c.id, keys: c.keys }));
+ const seen = new Set(out.map((c) => c.full));
for (const m of models) {
if (seen.has(m)) continue;
seen.add(m);
diff --git a/packages/window-warmup/src/diagnostics.ts b/packages/window-warmup/src/diagnostics.ts
new file mode 100644
index 0000000..fc52516
--- /dev/null
+++ b/packages/window-warmup/src/diagnostics.ts
@@ -0,0 +1,287 @@
+// 诊断导出(GET /api/diagnostics):把排查「选不到账号/模型、窗口不触发、发送失败」要用的现场
+// 打成一个 JSON,用户可直接附在 issue 里。导出是只读的:不发模型请求、不写状态。
+//
+// 隐私:账号名、key 指纹、key 名、任务名、额度卡显示名一律不出现。账号换成 acct-N、key 换成 key-N,
+// 同一份导出内一一对应(同一个邮箱在两个供应商下是同一个别名,能看出串号);自由文本(执行记录
+// 原因、上游报错、路径)先替换已知账号与指纹,再按规则抹掉邮箱、key 形态串、口令参数与家目录。
+// 体积:列表与文本都有上限,截掉的部分记在 truncated 里,常见规模在几十 KB。
+import { version } from "../package.json";
+import { fetchCatalog, fetchModels, fetchQuotas, modelProvider } from "./gateway";
+import {
+ magpieDirs,
+ readDefaultModelCache,
+ readKeyDirectory,
+ type KeyDirectoryEntry,
+} from "./magpie-files";
+import type { Scheduler } from "./scheduler";
+import type { TaskMarks } from "./store";
+import { errText, type QuotaEntry, type RawModel, type Run, type Task } from "./types";
+
+export const DIAGNOSTICS_SCHEMA = "window-warmup-diagnostics/1";
+/** 单个列表(某供应商的模型、某任务的执行记录等)最多导出的条数 */
+const LIST_MAX = 200;
+/** 每个任务导出的最近执行记录条数(store 每任务留 50 条,排错看最近的就够) */
+const RUNS_PER_TASK = 20;
+/** 自由文本(原因、报错)的字数上限 */
+const TEXT_MAX = 400;
+/** 已知账号原文短于这个长度时不在自由文本里替换:太短的名字会误伤模型 id(如 key 名 GLM) */
+const SCRUB_MIN_LEN = 4;
+/** magpie 额度卡里同名多把 key 的「名字 · 打码」分隔 */
+const MASKED_SEP = " · ";
+
+export interface DiagnosticsInput {
+ base: string;
+ /** 插件数据目录(state.json 所在),只导出脱敏后的路径 */
+ dir: string;
+ tasks: Task[];
+ runs: Run[];
+ marks: Record;
+ /** fatal / 只读实例时为 null */
+ scheduler: Scheduler | null;
+ fatal: string | null;
+ lockedBy: number | null;
+ now?: Date;
+}
+
+/** 账号与 key 的别名表:原文 → 别名,全份导出共用 */
+class Aliases {
+ private readonly byRaw = new Map();
+ private acctN = 0;
+ private keyN = 0;
+
+ key(fingerprint: string, name: string): string {
+ let alias = this.byRaw.get(fingerprint);
+ if (!alias) {
+ alias = `key-${++this.keyN}`;
+ this.byRaw.set(fingerprint, alias);
+ }
+ // key 名也指向同一别名:~keys 额度卡的 user 就是 key 名
+ if (name && !this.byRaw.has(`name:${name.toLowerCase()}`)) this.byRaw.set(`name:${name.toLowerCase()}`, alias);
+ return alias;
+ }
+
+ /** 订阅账号或任务里存的账号值;指纹形态先查 key 表 */
+ account(raw: string): string {
+ if (!raw) return "";
+ const hit = this.byRaw.get(raw) ?? this.byRaw.get(`login:${raw.toLowerCase()}`);
+ if (hit) return hit;
+ const alias = `acct-${++this.acctN}`;
+ this.byRaw.set(`login:${raw.toLowerCase()}`, alias);
+ return alias;
+ }
+
+ /** ~keys 卡的 user:key 名,或同名多把时的「名字 · 打码」;打码部分是 key 的片段,不导出 */
+ keyCard(user: string): string {
+ const name = user.includes(MASKED_SEP) ? user.slice(0, user.indexOf(MASKED_SEP)) : user;
+ return this.byRaw.get(`name:${name.toLowerCase()}`) ?? this.account(user);
+ }
+
+ /** accountModels 的键:key 指纹或小写账号名 */
+ accountKey(k: string): string {
+ return this.byRaw.get(k) ?? this.account(k);
+ }
+
+ /** 自由文本里要替换的原文(长的先换,免得子串先被换掉) */
+ raws(): [string, string][] {
+ return [...this.byRaw]
+ .map(([k, v]): [string, string] => [k.replace(/^(login|name):/, ""), v])
+ .filter(([k]) => k.length >= SCRUB_MIN_LEN)
+ .sort((a, b) => b[0].length - a[0].length);
+ }
+}
+
+const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+/** 自由文本脱敏:已知账号/指纹换别名,再抹通用的敏感形态,最后截断 */
+function scrubber(aliases: Aliases): (s: string) => string {
+ const known = aliases.raws().map(([raw, alias]) => [new RegExp(escapeRe(raw), "gi"), alias] as const);
+ return (s) => {
+ let out = s;
+ for (const [re, alias] of known) out = out.replace(re, alias);
+ out = out
+ .replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, "")
+ .replace(/\bBearer\s+\S+/gi, "Bearer ")
+ .replace(/\b(sk|pk|rk|ak|key)-[\w-]{8,}/gi, "")
+ .replace(/([?&](?:key|api_?key|token|access_token|auth|sig|signature|cookie)=)[^&\s"']+/gi, "$1")
+ // 长串不透明口令(cookie、JWT 段等);模型 id 带点和斜杠,不会被整段吞掉
+ .replace(/[A-Za-z0-9_-]{32,}/g, "")
+ .replace(/(\/home|\/Users)\/[^/\s"']+/g, "$1/")
+ .replace(/([A-Za-z]:\\Users\\)[^\\\s"']+/gi, "$1");
+ return out.length > TEXT_MAX ? `${out.slice(0, TEXT_MAX)}…(截断,原长 ${out.length})` : out;
+ };
+}
+
+/** 网关地址只在是本机回环时原样导出(端口有用),否则只说明是远程 */
+export function baseView(base: string): string {
+ try {
+ const u = new URL(base);
+ return ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname) ? `${u.protocol}//${u.host}` : "<非本机地址>";
+ } catch {
+ return "<无法解析>";
+ }
+}
+
+export async function buildDiagnostics(input: DiagnosticsInput): Promise> {
+ const now = input.now ?? new Date();
+ const truncated: string[] = [];
+ const cap = (list: T[], path: string, max = LIST_MAX): T[] => {
+ if (list.length <= max) return list;
+ truncated.push(`${path}:共 ${list.length} 条,只导出前 ${max} 条`);
+ return list.slice(0, max);
+ };
+ const settle = (p: Promise): Promise<{ ok: T } | { error: string }> =>
+ p.then((ok) => ({ ok }), (e: unknown) => ({ error: errText(e) }));
+
+ const dirs = magpieDirs();
+ const [models, quotas, keyDir, catalog] = await Promise.all([
+ settle(fetchModels(input.base)),
+ settle(fetchQuotas(input.base)),
+ // 直接调 readKeyDirectory 区分「没有文件」与「读不出」;报错是固定文案,不夹带文件内容
+ settle(readKeyDirectory(dirs.config)),
+ settle(fetchCatalog(input.base)),
+ ]);
+ const dir: Map | null = "ok" in keyDir ? keyDir.ok : null;
+ const quotaEntries: QuotaEntry[] = "ok" in quotas ? quotas.ok.entries : [];
+ const rawModels: RawModel[] = "ok" in models ? models.ok : [];
+
+ // 先登记所有 key,再登记订阅账号:任务与卡片里的指纹/key 名才能落到同一个 key 别名上
+ const aliases = new Aliases();
+ for (const entry of dir?.values() ?? []) for (const k of entry.keys) aliases.key(k.fingerprint, k.name);
+ const cardAlias = (q: QuotaEntry): string => (q.viaKey ? aliases.keyCard(q.account) : aliases.account(q.account));
+ for (const q of quotaEntries) cardAlias(q);
+ for (const t of input.tasks) aliases.account(t.account);
+ for (const q of input.scheduler?.quotaEntries() ?? []) cardAlias(q);
+ const scrub = scrubber(aliases);
+
+ const pids = new Set([
+ ...rawModels.map(modelProvider).filter(Boolean),
+ ...quotaEntries.map((q) => q.provider),
+ ...(dir?.keys() ?? []),
+ ...input.tasks.map((t) => t.provider),
+ ]);
+ const catalogById = new Map(("ok" in catalog ? catalog.ok.providers : []).map((p) => [p.id, p]));
+ const providers = await Promise.all(
+ [...pids].sort().map(async (pid) => {
+ const entry = dir?.get(pid);
+ const v1 = rawModels.filter((m) => modelProvider(m) === pid);
+ const cache = await readDefaultModelCache(pid).catch(() => null);
+ const cat = catalogById.get(pid);
+ const path = `providers.${pid}`;
+ return {
+ id: pid,
+ v1Models: cap(
+ v1.map((m) => ({
+ id: m.id,
+ owned_by: m.owned_by,
+ reasoning: m.reasoning,
+ reasoning_levels: m.reasoning_levels,
+ supported_reasoning_levels: m.supported_reasoning_levels?.map((l) => l.effort),
+ })),
+ `${path}.v1Models`,
+ ),
+ // providers.json 里的启用清单(chosen)与 key 概况;null = providers.json 没有这个供应商
+ providersJson: entry
+ ? {
+ chosen: cap(entry.models, `${path}.chosen`),
+ keys: entry.keys.map((k) => ({ alias: aliases.key(k.fingerprint, k.name), named: k.name !== "" })),
+ accountModels: Object.fromEntries(
+ Object.entries(entry.accountModels).map(([k, v]) => [aliases.accountKey(k), v]),
+ ),
+ }
+ : null,
+ // Magpie 模型缓存文件;null = 没有缓存文件(插件型订阅供应商本来就不写)
+ modelCache: cache
+ ? cap(
+ cache.map((c) => ({ id: c.id, keys: c.keys.map((fp) => aliases.accountKey(fp)) })),
+ `${path}.modelCache`,
+ )
+ : null,
+ quotaCards: quotaEntries
+ .filter((q) => q.provider === pid)
+ .map((q) => ({ account: cardAlias(q), viaKey: q.viaKey, readAt: q.readAt ?? null, windows: q.windows })),
+ // 页面 /api/catalog 此刻给出的结果(与下拉框所见一致);null = 目录里没有这个供应商
+ catalog: cat
+ ? {
+ accounts: cat.accounts.map((a) => ({
+ id: a.kind === "key" ? aliases.accountKey(a.id) : aliases.account(a.id),
+ kind: a.kind,
+ windows: a.windows.map((w) => w.name),
+ models: a.models === null ? null : cap(a.models, `${path}.catalog.accounts.models`),
+ perAccount: a.perAccount,
+ autoModel: a.autoModel,
+ })),
+ autoAccountModels:
+ cat.autoAccountModels === null ? null : cap(cat.autoAccountModels, `${path}.catalog.autoAccountModels`),
+ autoModel: cat.autoModel,
+ }
+ : null,
+ };
+ }),
+ );
+
+ const scheduler = input.scheduler;
+ const next = scheduler?.snapshot().next ?? {};
+ const tasks = await Promise.all(
+ input.tasks.map(async (t) => {
+ const preview = scheduler ? await scheduler.previewSend(t) : { error: "调度器未运行" };
+ const marks = input.marks[t.id];
+ return {
+ id: t.id,
+ enabled: t.enabled,
+ provider: t.provider,
+ account: aliases.account(t.account),
+ accountKind: /^[0-9a-f]{10}$/.test(t.account) ? "key" : t.account ? "login" : "",
+ model: t.model || "<自动>",
+ trigger: t.trigger,
+ createdAt: t.createdAt,
+ updatedAt: t.updatedAt,
+ next: next[t.id] ?? null,
+ marks: marks
+ ? { ...marks, resetKeys: marks.resetKeys.slice(-5).map(scrub) }
+ : null,
+ // 按发送前同一套规则此刻会怎么发(不真的发)
+ sendPreview:
+ "error" in preview
+ ? { error: scrub(preview.error) }
+ : { ...preview, pin: preview.pin === null ? null : scrub(preview.pin) },
+ };
+ }),
+ );
+
+ const runs = input.tasks.flatMap((t) =>
+ input.runs
+ .filter((r) => r.taskId === t.id)
+ .slice(-RUNS_PER_TASK)
+ .map((r) => ({ ...r, reason: scrub(r.reason) })),
+ );
+
+ return {
+ schema: DIAGNOSTICS_SCHEMA,
+ note: "账号与 key 已换成别名(acct-N / key-N),任务名与额度卡显示名未导出,自由文本已脱敏",
+ generatedAt: now.toISOString(),
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ plugin: { version, bun: Bun.version, platform: `${process.platform}-${process.arch}` },
+ gateway: {
+ base: baseView(input.base),
+ models: "ok" in models ? `ok(${models.ok.length} 个)` : scrub(models.error),
+ quotas: "ok" in quotas ? `ok(${quotas.ok.entries.length} 张卡)` : scrub(quotas.error),
+ catalog: "ok" in catalog ? "ok" : scrub(catalog.error),
+ },
+ files: {
+ configDir: scrub(dirs.config),
+ cacheDir: scrub(dirs.cache),
+ dataDir: scrub(input.dir),
+ providersJson: "ok" in keyDir ? (keyDir.ok.size > 0 ? `ok(${keyDir.ok.size} 个供应商)` : "没有文件或为空") : keyDir.error,
+ },
+ service: {
+ fatal: input.fatal === null ? null : scrub(input.fatal),
+ lockedBy: input.lockedBy,
+ saveError: scrub(scheduler?.snapshot().saveError ?? "") || null,
+ scheduler: scheduler?.debugView() ?? null,
+ },
+ tasks,
+ runs,
+ providers,
+ truncated,
+ };
+}
diff --git a/packages/window-warmup/src/scheduler.ts b/packages/window-warmup/src/scheduler.ts
index 3779765..bb18ff8 100644
--- a/packages/window-warmup/src/scheduler.ts
+++ b/packages/window-warmup/src/scheduler.ts
@@ -327,6 +327,48 @@ export class Scheduler {
};
}
+ /** 诊断用的内部视角(只读):额度快照时刻与新鲜度、进行中的发送、定时器为固定任务排的到期点 */
+ debugView(): {
+ quotaAt: string | null;
+ quotaStale: boolean;
+ quotaTried: boolean;
+ keyDirLoaded: boolean;
+ inflight: string[];
+ armedFor: Record;
+ } {
+ return {
+ quotaAt: this.quota?.at.toISOString() ?? null,
+ quotaStale: this.quotaStale,
+ quotaTried: this.quotaTried,
+ keyDirLoaded: this.keyDirMap !== null,
+ inflight: [...this.inflight.keys()],
+ armedFor: Object.fromEntries([...this.armedFor].map(([id, at]) => [id, at.toISOString()])),
+ };
+ }
+
+ /** 额度快照(调度器判窗口时用的那一份);还没取到为 null */
+ quotaEntries(): QuotaEntry[] | null {
+ return this.quota?.entries ?? null;
+ }
+
+ /**
+ * 诊断用:按发送前同一套规则(resolveSend + pickEffort)现算这个任务此刻会用哪个模型、
+ * 账号头与档位。不发请求、不写状态;取 /v1/models 失败也作为结果返回,不让导出整体失败
+ */
+ async previewSend(
+ task: Task,
+ ): Promise<{ model: string; pin: string | null; effort: string | null } | { error: string }> {
+ try {
+ const resolved = await this.resolveSend(task, await this.modelsFn(this.base));
+ if ("error" in resolved) return resolved;
+ const pick = pickEffort(resolved.model);
+ if ("error" in pick) return pick;
+ return { model: resolved.id, pin: resolved.pin, effort: pick.send };
+ } catch (e) {
+ return { error: errText(e) };
+ }
+ }
+
/** 单任务的下次执行点与 24 小时时间轴点;时区/规则抛错时由调用方兜成「无计划」 */
private snapshotTask(
task: Task,
diff --git a/packages/window-warmup/src/server.ts b/packages/window-warmup/src/server.ts
index 88436bf..9308b80 100644
--- a/packages/window-warmup/src/server.ts
+++ b/packages/window-warmup/src/server.ts
@@ -7,6 +7,7 @@
import { randomBytes, timingSafeEqual } from "node:crypto";
import { readFile } from "node:fs/promises";
import path, { basename, extname, join, resolve } from "node:path";
+import { buildDiagnostics } from "./diagnostics";
import { fetchCatalog } from "./gateway";
import { validateTask } from "./rules";
import { Scheduler, CONFLICT_MESSAGE, NOT_FOUND_MESSAGE, type TaskInput } from "./scheduler";
@@ -265,6 +266,20 @@ export async function startService(opts: ServiceOptions): Promise
return json({ error: errText(e) }, 502, cors);
}
}
+ // 诊断导出不改状态:故障/只读时最需要它,放在只读拦截之前
+ if (req.method === "GET" && path === "/api/diagnostics") {
+ const data = await buildDiagnostics({
+ base: opts.base,
+ dir: opts.dir,
+ tasks: store?.data.tasks ?? [],
+ runs: store?.data.runs ?? [],
+ marks: store?.data.marks ?? {},
+ scheduler,
+ fatal,
+ lockedBy,
+ });
+ return json(data, 200, cors);
+ }
const blocked = readonlyBlock(cors);
if (blocked) return blocked;
const runMatch = /^\/api\/tasks\/([^/]+)\/run$/.exec(path);
diff --git a/packages/window-warmup/tests/app.test.ts b/packages/window-warmup/tests/app.test.ts
index 2f1b0c9..9d95f10 100644
--- a/packages/window-warmup/tests/app.test.ts
+++ b/packages/window-warmup/tests/app.test.ts
@@ -2,6 +2,9 @@
// statusOf / trigText / 下拉选项构造 / 执行记录文案等由 web/app.ts 导出,界面渲染直接复用。
import { expect, test } from "bun:test";
import {
+ issueBody,
+ issueURL,
+ setLang,
accountHasWindows,
accountModelView,
accountOptions,
@@ -495,3 +498,32 @@ test("accountHasWindows:没账号、不在目录、没有窗口都算没有—
expect(accountHasWindows("p", "gone", [provider])).toBe(false);
expect(accountHasWindows("nope", "with-win", [provider])).toBe(false);
});
+
+test("反馈问题:链接预填标题前缀与粘贴提示;正文含模板、环境与折叠的诊断 JSON", () => {
+ setLang("zh");
+ const u = new URL(issueURL());
+ expect(u.origin + u.pathname).toBe("https://github.com/magpie-community/plugins/issues/new");
+ expect(u.searchParams.get("title")).toBe("window-warmup: ");
+ expect(u.searchParams.get("body")).toContain("复制问题内容");
+ expect(issueURL().length).toBeLessThan(1000);
+
+ const diag = { schema: "window-warmup-diagnostics/1", plugin: { version: "0.1.2", bun: "1.4.4", platform: "linux-x64" } };
+ const body = issueBody(diag);
+ expect(body).toContain("### 问题描述");
+ expect(body).toContain("window-warmup 0.1.2,Bun 1.4.4,linux-x64");
+ const json = /```json\n([\s\S]*)\n```/.exec(body)![1];
+ expect(JSON.parse(json)).toEqual(diag);
+});
+
+test("反馈问题:诊断过大时改用紧凑 JSON,仍超 GitHub 上限就截断并注明", () => {
+ setLang("zh");
+ const mid = { plugin: {}, rows: Array.from({ length: 3000 }, (_, i) => ({ i, a: "x" })) };
+ expect(JSON.stringify(mid, null, 1).length).toBeGreaterThan(60_000);
+ const compact = issueBody(mid);
+ expect(compact.length).toBeLessThanOrEqual(60_000);
+ expect(JSON.parse(/```json\n([\s\S]*)\n```/.exec(compact)![1])).toEqual(mid);
+ const huge = issueBody({ plugin: {}, blob: "y".repeat(100_000) });
+ expect(huge.length).toBeLessThanOrEqual(60_000);
+ expect(huge).toContain("诊断日志过长,已截断");
+ expect(huge.endsWith("\n")).toBe(true);
+});
diff --git a/packages/window-warmup/tests/browser.test.ts b/packages/window-warmup/tests/browser.test.ts
index 06736eb..d9a586f 100644
--- a/packages/window-warmup/tests/browser.test.ts
+++ b/packages/window-warmup/tests/browser.test.ts
@@ -22,6 +22,15 @@ interface Page {
getByPlaceholder(t: string): Locator;
getByText(t: string): Locator;
}
+/** 插件页在 magpie 里跑在 iframe 中:框架内的定位器 */
+interface FrameLocator {
+ getByRole(role: string, o?: { name?: string; exact?: boolean }): Locator;
+ getByText(t: string): Locator;
+ locator(selector: string): Locator;
+}
+interface Page {
+ frameLocator(selector: string): FrameLocator;
+}
interface Browser {
newPage(): Promise;
close(): Promise;
@@ -116,3 +125,40 @@ for (const [name, engine] of ENGINES) {
90_000,
);
}
+
+for (const [name, engine] of ENGINES) {
+ testBrowser(
+ `${name}:magpie 同款沙箱框架里「反馈问题」能收集诊断并复制两段内容`,
+ async () => {
+ // 与 magpie 宿主一致:sandbox="allow-scripts" + allow="",下载/弹窗/Clipboard API 全被拦
+ const host = Bun.serve({
+ port: 0,
+ hostname: "127.0.0.1",
+ fetch: () =>
+ new Response(
+ ``,
+ { headers: { "content-type": "text/html" } },
+ ),
+ });
+ const browser = await engine.launch();
+ try {
+ const page = await browser.newPage();
+ const errors: string[] = [];
+ page.on("pageerror", (e) => errors.push(String(e)));
+ await page.goto(`http://127.0.0.1:${host.port}/`);
+ const f = page.frameLocator("#f");
+ await f.getByRole("button", { name: "反馈问题" }).click();
+ await f.getByRole("button", { name: "① 复制 issue 链接" }).click();
+ await f.getByText("链接已复制。").waitFor({ timeout: 15_000 });
+ await f.locator("button:has-text('② 复制问题内容'):not([disabled])").waitFor({ timeout: 15_000 });
+ await f.getByRole("button", { name: "② 复制问题内容" }).click();
+ await f.getByText("问题内容已复制。").waitFor({ timeout: 15_000 });
+ expect(errors).toEqual([]);
+ } finally {
+ await browser.close();
+ host.stop(true);
+ }
+ },
+ 90_000,
+ );
+}
diff --git a/packages/window-warmup/tests/diagnostics.test.ts b/packages/window-warmup/tests/diagnostics.test.ts
new file mode 100644
index 0000000..bb2a63f
--- /dev/null
+++ b/packages/window-warmup/tests/diagnostics.test.ts
@@ -0,0 +1,258 @@
+// 诊断导出:端到端起服务(假网关 + 临时 Magpie 配置/缓存目录),断言导出能还原排错现场,
+// 且账号、key、任务名等隐私原文一个字节都不出现。
+import { afterAll, beforeAll, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { baseView, buildDiagnostics } from "../src/diagnostics";
+import { Scheduler } from "../src/scheduler";
+import { startService, type ServiceHandle } from "../src/server";
+import type { Run, Task } from "../src/types";
+import { fakeGateway, type FakeGateway } from "./fake-gateway";
+
+const KEY_RAW = "sk-test-SECRET-9f8e7d6c5b";
+const FP = createHash("sha256").update(KEY_RAW, "utf8").digest("hex").slice(0, 10);
+const EMAIL = "someone.private@example.com";
+const KEY_NAME = "我的私钥名字";
+const TASK_NAME = "私人任务名";
+const CARD_LABEL = "Private Display Name";
+const LEAK = "Bearer abcdefghijklmnopqrstuvwxyz0123456789 at /home/alice/.config";
+
+let root = "";
+let saved: Record = {};
+let gw: FakeGateway;
+let svc: ServiceHandle;
+let api: (path: string, init?: RequestInit) => Promise;
+
+beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), "ww-diag-"));
+ saved = { XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME, XDG_CACHE_HOME: process.env.XDG_CACHE_HOME };
+ process.env.XDG_CONFIG_HOME = join(root, "config");
+ process.env.XDG_CACHE_HOME = join(root, "cache");
+ await mkdir(join(root, "config", "magpie"), { recursive: true });
+ await mkdir(join(root, "cache", "magpie", "models"), { recursive: true });
+ await writeFile(
+ join(root, "config", "magpie", "providers.json"),
+ JSON.stringify({
+ providers: [
+ { id: "antigravity", key: "ag-raw-key-should-not-leak", models: ["gemini-3.8-flash"] },
+ { id: "remote", key: KEY_RAW, keyName: KEY_NAME, accountModels: { [FP]: ["m1"], [EMAIL]: ["m1"] } },
+ ],
+ }),
+ );
+ // antigravity 的缓存只有分档变体(真实形态),remote 的缓存按 key 指纹区分可见性
+ await writeFile(
+ join(root, "cache", "magpie", "models", "antigravity.json"),
+ JSON.stringify({ models: [{ ID: "gemini-3.8-flash-high" }, { ID: "gemini-3.8-flash-low" }] }),
+ );
+ await writeFile(
+ join(root, "cache", "magpie", "models", "remote.json"),
+ JSON.stringify({ models: [{ ID: "m1", Keys: [FP] }] }),
+ );
+ gw = fakeGateway({
+ models: [
+ { id: "antigravity/gemini-3.8-flash", owned_by: "antigravity", reasoning: true, reasoning_levels: ["low", "high"] },
+ { id: "remote/m1", owned_by: "remote", reasoning: false },
+ ],
+ quotas: [
+ { provider: "antigravity", user: EMAIL, name: CARD_LABEL, windows: [{ name: "5h", used: 0, resetsAt: null }] },
+ { provider: "remote/~keys", user: KEY_NAME, windows: [{ name: "5h", used: 10, resetsAt: null }] },
+ ],
+ chat: { status: 400, body: { error: { message: `upstream rejected ${EMAIL}: ${LEAK}` } } },
+ });
+ const dir = join(root, "data");
+ svc = await startService({ port: 0, dir, base: gw.base });
+ const base = `http://127.0.0.1:${svc.port}`;
+ const html = await (await fetch(base)).text();
+ const token = String(JSON.parse(/id="boot"[^>]*>([\s\S]*?)<\/script>/.exec(html)![1]).token);
+ api = (path, init = {}) =>
+ fetch(base + path, {
+ ...init,
+ headers: { "x-window-warmup-token": token, "content-type": "application/json", ...init.headers },
+ });
+});
+
+afterAll(async () => {
+ await svc?.stop();
+ gw?.stop();
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ await rm(root, { recursive: true, force: true });
+});
+
+const daily = { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" };
+
+test("导出还原排错现场,且不含账号、key、任务名等隐私原文", async () => {
+ const created = (await (
+ await api("/api/tasks", {
+ method: "POST",
+ body: JSON.stringify({
+ name: TASK_NAME, enabled: true, provider: "antigravity", account: EMAIL, model: "", message: "hi", trigger: daily,
+ }),
+ })
+ ).json()) as { id: string };
+ await api("/api/tasks", {
+ method: "POST",
+ body: JSON.stringify({
+ name: TASK_NAME, enabled: true, provider: "remote", account: FP, model: "", message: "hi", trigger: daily,
+ }),
+ });
+ // 立即发送一次拿到一条失败记录:上游报错里夹着邮箱、Bearer 口令与家目录
+ await api(`/api/tasks/${created.id}/run`, { method: "POST" });
+ for (let i = 0; i < 50; i++) {
+ const st = (await (await api("/api/state")).json()) as { runs: { outcome: string }[] };
+ if (st.runs.length && st.runs[0].outcome !== "running") break;
+ await Bun.sleep(20);
+ }
+
+ expect(await (await fetch(`http://127.0.0.1:${svc.port}/api/diagnostics`)).status).toBe(401);
+ const res = await api("/api/diagnostics");
+ expect(res.status).toBe(200);
+ const text = await res.text();
+ for (const secret of [KEY_RAW, "ag-raw-key", FP, EMAIL, KEY_NAME, TASK_NAME, CARD_LABEL, "abcdefghijklmnop", "alice"]) {
+ expect(text).not.toContain(secret);
+ }
+ const d = JSON.parse(text) as {
+ schema: string;
+ tasks: { provider: string; account: string; accountKind: string; sendPreview: Record }[];
+ runs: { reason: string; outcome: string }[];
+ providers: {
+ id: string;
+ modelCache: { id: string; keys: string[] }[] | null;
+ providersJson: { chosen: string[]; keys: { alias: string }[]; accountModels: Record } | null;
+ quotaCards: { account: string; viaKey: boolean }[];
+ catalog: { accounts: { id: string; kind: string; models: string[] | null }[] } | null;
+ }[];
+ };
+ expect(d.schema).toBe("window-warmup-diagnostics/1");
+
+ const ag = d.providers.find((p) => p.id === "antigravity")!;
+ const remote = d.providers.find((p) => p.id === "remote")!;
+ const agTask = d.tasks.find((t) => t.provider === "antigravity")!;
+ const remoteTask = d.tasks.find((t) => t.provider === "remote")!;
+ // 同一个账号/同一把 key 在任务、额度卡、目录、accountModels、缓存可见性里是同一个别名
+ expect(agTask.account).toMatch(/^acct-\d+$/);
+ expect(agTask.accountKind).toBe("login");
+ expect(ag.quotaCards[0].account).toBe(agTask.account);
+ const agLogin = ag.catalog!.accounts.find((a) => a.kind === "login")!;
+ expect(agLogin.id).toBe(agTask.account);
+ const keyAlias = remote.providersJson!.keys[0].alias;
+ expect(keyAlias).toMatch(/^key-\d+$/);
+ expect(remoteTask.account).toBe(keyAlias);
+ expect(remote.quotaCards[0]).toMatchObject({ account: keyAlias, viaKey: true });
+ expect(remote.modelCache![0].keys).toEqual([keyAlias]);
+ expect(Object.keys(remote.providersJson!.accountModels).sort()).toEqual([agTask.account, keyAlias].sort());
+ // 原始输入与计算结果都在:缓存是分档变体、启用清单是合并名、目录与发送预演选中合并名
+ expect(ag.modelCache!.map((m) => m.id)).toEqual(["gemini-3.8-flash-high", "gemini-3.8-flash-low"]);
+ expect(ag.providersJson!.chosen).toEqual(["gemini-3.8-flash"]);
+ expect(agLogin.models).toEqual(["antigravity/gemini-3.8-flash"]);
+ expect(agTask.sendPreview).toMatchObject({ model: "antigravity/gemini-3.8-flash", pin: agTask.account, effort: "low" });
+ // 执行记录原因保留可读的报错,敏感片段被抹掉
+ expect(d.runs[0].outcome).toBe("failed");
+ expect(d.runs[0].reason).toContain("upstream rejected");
+ expect(d.runs[0].reason).toContain(agTask.account);
+ expect(d.runs[0].reason).toContain("Bearer ");
+ expect(d.runs[0].reason).toContain("/home/");
+});
+
+const task = (over: Partial = {}): Task => ({
+ id: "t1", name: TASK_NAME, enabled: true, provider: "antigravity", account: EMAIL, model: "", message: "hi",
+ trigger: { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" },
+ createdAt: "2026-11-01T00:00:00.000Z", updatedAt: "2026-11-01T00:00:00.000Z", ...over,
+});
+const run = (i: number, reason: string): Run => ({
+ id: `r${i}`, taskId: "t1", source: "manual", due: null, startedAt: new Date(Date.UTC(2026, 10, 1, 0, i)).toISOString(),
+ endedAt: null, outcome: "failed", reason, effort: null, model: null, ms: 0, resetKey: null,
+});
+
+test("自由文本脱敏:邮箱、key 形态串、URL 口令参数、长口令、Windows 家目录都被抹掉;超长截断并注明原长", async () => {
+ const reasons = [
+ "mail other.person@corp.example.org failed",
+ "key sk-live-0123456789abcdef rejected",
+ "GET https://x.test/v1?api_key=SEKRIT123&model=m1 401",
+ "cookie eyJhbGciOiJIUzI1NiJ9eyJzdWIiOiIxMjM0NTY3ODkwIn0abcdef",
+ "open C:\\Users\\bob\\AppData failed",
+ `long ${"z ".repeat(400)}`,
+ ];
+ const d = (await buildDiagnostics({
+ base: gw.base, dir: join(root, "data"), tasks: [task()], runs: reasons.map((r, i) => run(i, r)),
+ marks: {}, scheduler: null, fatal: null, lockedBy: null,
+ })) as { runs: { reason: string }[]; tasks: { sendPreview: unknown }[] };
+ const text = JSON.stringify(d);
+ for (const secret of ["other.person", "sk-live-0123", "SEKRIT123", "eyJhbGciOiJIUzI1NiJ9", "bob", EMAIL, TASK_NAME]) {
+ expect(text).not.toContain(secret);
+ }
+ const got = d.runs.map((r) => r.reason);
+ expect(got[0]).toContain("");
+ expect(got[1]).toContain("");
+ expect(got[2]).toContain("api_key=&model=m1");
+ expect(got[3]).toContain("");
+ expect(got[4]).toContain("C:\\Users\\");
+ expect(got[5]).toContain("(截断,原长");
+ expect(got[5].length).toBeLessThan(450);
+ // 没有调度器(fatal/只读实例)时预演如实说明,不让导出失败
+ expect(d.tasks[0].sendPreview).toEqual({ error: "调度器未运行" });
+});
+
+test("体积上限:每任务只留最近 20 条执行记录;单个列表超 200 条截断并记入 truncated", async () => {
+ const many = fakeGateway({
+ models: Array.from({ length: 250 }, (_, i) => ({ id: `bulk/m${i}`, owned_by: "bulk", reasoning: false })),
+ });
+ try {
+ const d = (await buildDiagnostics({
+ base: many.base, dir: join(root, "data"), tasks: [task()], runs: Array.from({ length: 30 }, (_, i) => run(i, `r${i}`)),
+ marks: {}, scheduler: null, fatal: null, lockedBy: null,
+ })) as { runs: { id: string }[]; providers: { id: string; v1Models: unknown[] }[]; truncated: string[] };
+ expect(d.runs.map((r) => r.id)).toEqual(Array.from({ length: 20 }, (_, i) => `r${i + 10}`));
+ expect(d.providers.find((p) => p.id === "bulk")!.v1Models).toHaveLength(200);
+ expect(d.truncated.some((t) => t.startsWith("providers.bulk.v1Models:共 250 条"))).toBe(true);
+ } finally {
+ many.stop();
+ }
+});
+
+test("网关地址:本机回环原样导出,其余只标注「非本机地址」(纯函数,不建连接)", () => {
+ expect(baseView("http://127.0.0.1:3425")).toBe("http://127.0.0.1:3425");
+ expect(baseView("http://localhost:3425/")).toBe("http://localhost:3425");
+ expect(baseView("http://[::1]:3425")).toBe("http://[::1]:3425");
+ expect(baseView("http://127.0.0.2:3425")).toBe("<非本机地址>");
+ expect(baseView("https://magpie.example.com")).toBe("<非本机地址>");
+ expect(baseView("not a url")).toBe("<无法解析>");
+});
+
+test("网关连不上不让导出失败,原因记在 gateway 里", async () => {
+ // 刚释放的 127.0.0.1 端口:各系统都立即拒绝连接,不会等读超时(127.0.0.2 在 macOS 上不在 lo0,会挂到超时)
+ const probe = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response() });
+ const port = probe.port;
+ probe.stop(true);
+ const d = (await buildDiagnostics({
+ base: `http://127.0.0.1:${port}`, dir: join(root, "data"), tasks: [], runs: [], marks: {},
+ scheduler: null, fatal: null, lockedBy: null,
+ })) as { gateway: { base: string; models: string; catalog: string } };
+ expect(d.gateway.base).toBe(`http://127.0.0.1:${port}`);
+ expect(d.gateway.models).not.toMatch(/^ok/);
+ expect(d.gateway.catalog).not.toBe("ok");
+});
+
+test("落盘失败的原因(Bun 报错带 state.json 完整路径)同样脱敏,家目录用户名不出现", async () => {
+ const t = task();
+ const store = {
+ data: { version: 1 as const, tasks: [t], runs: [] as Run[], marks: {} },
+ save: async () => {
+ throw new Error("EACCES: permission denied, open '/home/alice/.config/magpie/window-warmup/state.json.tmp'");
+ },
+ };
+ const scheduler = new Scheduler({ store, base: gw.base });
+ await scheduler.runNow(t.id);
+ await scheduler.flush();
+ expect(scheduler.snapshot().saveError).toContain("/home/alice/");
+ const d = (await buildDiagnostics({
+ base: gw.base, dir: join(root, "data"), tasks: store.data.tasks, runs: store.data.runs, marks: {},
+ scheduler, fatal: null, lockedBy: null,
+ })) as { service: { saveError: string | null } };
+ expect(d.service.saveError).toContain("/home//.config");
+ expect(JSON.stringify(d)).not.toContain("alice");
+});
diff --git a/packages/window-warmup/tests/gateway.test.ts b/packages/window-warmup/tests/gateway.test.ts
index c2e220c..f63c860 100644
--- a/packages/window-warmup/tests/gateway.test.ts
+++ b/packages/window-warmup/tests/gateway.test.ts
@@ -851,6 +851,28 @@ describe("accountsOf", () => {
for (const a of accounts) expect(a.perAccount).toBe(false);
});
+ test("缓存 id 是分档变体、对外 id 是合并名(antigravity 实况)→ 并上 v1 与 chosen,不再整列表为空", () => {
+ const A = "antigravity";
+ const { accounts, autoAccountModels } = accountsOf(A, {
+ models: ["antigravity/gemini-3.8-flash"],
+ quotas: [{ provider: A, account: "me@example.com", label: "me@example.com", viaKey: false, windows: [] }],
+ keyDir: new Map([[A, { keys: [], accountModels: {}, models: ["gemini-3.8-flash"] }]]),
+ // 缓存里没有 gemini-3.8-flash 本身,只有分档变体;变体不在 v1 也不在 chosen,第 3 层剔除
+ cache: [
+ { id: "gemini-3.8-flash-high", keys: [] },
+ { id: "gemini-3.8-flash-low", keys: [] },
+ { id: "gemini-3.8-flash-tiered", keys: [] },
+ ],
+ chosen: ["gemini-3.8-flash"],
+ });
+ expect(autoAccountModels).toEqual(["antigravity/gemini-3.8-flash"]);
+ expect(accountOf(accounts, "me@example.com")).toMatchObject({
+ models: ["antigravity/gemini-3.8-flash"],
+ perAccount: true,
+ autoModel: "antigravity/gemini-3.8-flash",
+ });
+ });
+
test("窗口匹配:未命名 key 接受无窗口;同名两把 key 都挂「名字 · 打码」卡", () => {
const fpA = fp("sk-test-AAAA11");
const fpB = fp("sk-test-BBBB22");
diff --git a/packages/window-warmup/tests/scheduler.test.ts b/packages/window-warmup/tests/scheduler.test.ts
index 89fa463..0d793a1 100644
--- a/packages/window-warmup/tests/scheduler.test.ts
+++ b/packages/window-warmup/tests/scheduler.test.ts
@@ -534,6 +534,23 @@ test("自动模型:/v1/models 全空但 chosen 有清单 → 从 chosen 现选
expect(h.store.data.runs[0].model).toBe("openai/m1-flash");
});
+test("自动模型:缓存只有分档变体、v1 是合并名 → 选 v1 的合并名照发,不报「没有可用模型」", async () => {
+ const h = await harness({
+ models: [{ id: "openai/m1-flash", owned_by: "openai", reasoning: false }],
+ keyDir: new Map([["openai", { keys: [], accountModels: {}, models: ["m1-flash"] }]]),
+ modelCache: () => [
+ { id: "m1-flash-high", keys: [] },
+ { id: "m1-flash-low", keys: [] },
+ ],
+ });
+ await h.scheduler.upsert(dailyTask({ model: "" }));
+ await firedDaily(h);
+
+ expect(h.sendCalls).toHaveLength(1);
+ expect(h.sendCalls[0].task.model).toBe("openai/m1-flash");
+ expect(h.store.data.runs[0].outcome).toBe("ok");
+});
+
test("模型真不在 chosen 里(重新获取后已剔除)→ 仍报「已不在模型列表」", async () => {
const h = await harness({
keyDir: new Map([["openai", { keys: [], accountModels: {}, models: ["other"] }]]),
@@ -1117,3 +1134,26 @@ test("window:发送 60 秒后单卡刷新拿到新 resetsAt 精确排程;到
await h.flush();
expect(h.sendCalls).toHaveLength(2);
});
+
+test("previewSend:按发送前同一套规则现算模型/账号头/档位,不发请求、不写执行记录", async () => {
+ const h = await harness();
+ const task = await h.scheduler.upsert(dailyTask());
+ const before = h.store.data.runs.length;
+ expect(await h.scheduler.previewSend(task)).toEqual({ model: "m1", pin: null, effort: null });
+ h.models.length = 0;
+ expect(await h.scheduler.previewSend(task)).toEqual({ error: "模型 m1 已不在 Magpie 的模型列表里" });
+ expect(h.sendCalls).toHaveLength(0);
+ expect(h.store.data.runs.length).toBe(before);
+});
+
+test("debugView:暴露定时器为固定任务排的到期点与进行中的发送,只读", async () => {
+ const h = await harness();
+ const id = (await h.scheduler.upsert(dailyTask())).id;
+ expect(h.scheduler.debugView()).toMatchObject({ quotaAt: null, inflight: [], armedFor: {} });
+ h.scheduler.start();
+ const view = h.scheduler.debugView();
+ expect(view.inflight).toEqual([]);
+ expect(Object.keys(view.armedFor)).toEqual([id]);
+ expect(new Date(view.armedFor[id]).toISOString()).toBe(new Date("2026-10-31T06:00:00+08:00").toISOString());
+ expect(h.scheduler.quotaEntries()).toBeNull();
+});
diff --git a/packages/window-warmup/tests/server.test.ts b/packages/window-warmup/tests/server.test.ts
index a546e6e..2b3d3bf 100644
--- a/packages/window-warmup/tests/server.test.ts
+++ b/packages/window-warmup/tests/server.test.ts
@@ -319,6 +319,21 @@ test("状态文件损坏 → /api/state 返回 fatal,不启动调度,原文
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(broken);
});
+test("状态文件损坏或锁被占时 /api/diagnostics 仍可导出(排错最需要的时候),且同样要口令", async () => {
+ const broken = await harness({ state: '{"version":1,"tasks":' });
+ expect((await fetch(`http://127.0.0.1:${broken.svc.port}/api/diagnostics`)).status).toBe(401);
+ const res = await broken.api("/api/diagnostics");
+ expect(res.status).toBe(200);
+ const d = (await res.json()) as { service: { fatal: string | null; scheduler: unknown }; tasks: unknown[] };
+ expect(d.service.fatal).toBeTruthy();
+ expect(d.service.scheduler).toBeNull();
+ expect(d.tasks).toEqual([]);
+
+ const locked = await harness({ lockPid: process.pid, confirmLockAlive: async () => true });
+ const l = (await (await locked.api("/api/diagnostics")).json()) as { service: { lockedBy: number | null } };
+ expect(l.service.lockedBy).toBe(process.pid);
+});
+
test("不认识的版本号同样 fatal", async () => {
const { api } = await harness({ state: '{"version":2,"tasks":[],"runs":[],"marks":{}}' });
const state = (await (await api("/api/state")).json()) as { fatal?: string };
diff --git a/packages/window-warmup/web/app.ts b/packages/window-warmup/web/app.ts
index cf231a3..0d47c7c 100644
--- a/packages/window-warmup/web/app.ts
+++ b/packages/window-warmup/web/app.ts
@@ -50,6 +50,41 @@ const RUNS_MAX = 50;
/** 删除的两步确认窗口 */
export const DELETE_CONFIRM_MS = 3000;
+/** 反馈问题:社区仓库的新建 issue 入口(同 package.json 的 bugs) */
+const ISSUE_NEW_URL = "https://github.com/magpie-community/plugins/issues/new";
+/** GitHub issue 正文的字数上限是 65536,留出模板的余量 */
+const ISSUE_BODY_MAX = 60_000;
+
+/**
+ * 反馈问题的 issue 链接:标题预填包名前缀,正文只放一句粘贴提示。
+ * 诊断日志不进链接——十几 KB 的 JSON 编码后远超 GitHub 预填链接能带的长度(约 8 KB)
+ */
+export function issueURL(): string {
+ const q = new URLSearchParams({
+ title: "window-warmup: ",
+ body: t("(把「复制问题内容」复制的内容粘贴到这里,替换这一行)"),
+ });
+ return `${ISSUE_NEW_URL}?${q}`;
+}
+
+/** 反馈问题的正文:问题模板 + 折叠的诊断日志;超出 GitHub 上限时改用紧凑 JSON,仍超就截断并注明 */
+export function issueBody(diag: unknown): string {
+ const info = (diag as { plugin?: { version?: string; bun?: string; platform?: string } } | null)?.plugin ?? {};
+ const head = [
+ `### ${t("问题描述")}`, "", t("(发生了什么,期望是什么)"), "",
+ `### ${t("复现步骤")}`, "", "1. ", "",
+ `### ${t("环境")}`, "",
+ `- window-warmup ${info.version ?? "?"},Bun ${info.bun ?? "?"},${info.platform ?? "?"}`, "",
+ `${t("诊断日志(已脱敏)")}
`, "", "```json",
+ ].join("\n");
+ const tail = "\n```\n\n \n";
+ let json = JSON.stringify(diag, null, 1);
+ if (head.length + json.length + tail.length > ISSUE_BODY_MAX) json = JSON.stringify(diag);
+ const room = ISSUE_BODY_MAX - head.length - tail.length;
+ if (json.length > room) json = `${json.slice(0, room - 40)}\n…${t("(诊断日志过长,已截断)")}`;
+ return `${head}\n${json}${tail}`;
+}
+
/** 提示 A(常驻灰字):模型列表的来源与账号对不上时的解法;值是 i18n 键,取用时要过 t() */
const MODEL_SOURCE_HINT =
"模型列表来自 Magpie 上次获取的结果。账号和模型对不上时,到 Magpie「供应商」里打开这个供应商,点「获取模型」,再回来刷新本页。";
@@ -1411,6 +1446,7 @@ function render(): void {
renderBars();
renderSum();
renderList();
+ renderFeedback();
const newBtn = document.getElementById("new") as HTMLButtonElement | null;
if (newBtn) newBtn.disabled = isReadonly();
}
@@ -1480,6 +1516,90 @@ async function refreshCatalog(): Promise {
render();
}
+// ---------- 反馈问题 ----------
+// magpie 的插件框架是 sandbox="allow-scripts" + allow="":下载、window.open / target=_blank、
+// navigator.clipboard 全被拦,只有 document.execCommand("copy") 可用(Chromium 实测)。
+// 所以面板分两步:复制 issue 链接到浏览器打开,再复制正文(含脱敏诊断)粘贴进去。
+
+/** 面板状态:null = 收起;body 为 null 时诊断还在取 */
+let feedback: { body: string | null; error: string; copied: "" | "link" | "body" | "fail" } | null = null;
+
+/** 沙箱里唯一可用的复制方式:临时 textarea + execCommand,须在点击事件里同步调用 */
+function copyText(text: string): boolean {
+ const ta = el("textarea");
+ ta.value = text;
+ ta.setAttribute("readonly", "");
+ ta.style.position = "fixed";
+ ta.style.opacity = "0";
+ document.body.append(ta);
+ ta.select();
+ let ok = false;
+ try {
+ ok = document.execCommand("copy");
+ } catch {
+ ok = false;
+ }
+ ta.remove();
+ return ok;
+}
+
+async function openFeedback(): Promise {
+ if (feedback) {
+ feedback = null;
+ renderFeedback();
+ return;
+ }
+ feedback = { body: null, error: "", copied: "" };
+ renderFeedback();
+ try {
+ const diag = await apiJSON("api/diagnostics");
+ if (feedback) feedback.body = issueBody(diag);
+ } catch (e) {
+ if (feedback) feedback.error = errText(e);
+ }
+ renderFeedback();
+}
+
+function renderFeedback(): void {
+ const box = document.getElementById("feedback-panel");
+ if (!box) return;
+ const fb = feedback;
+ if (!fb) {
+ box.replaceChildren();
+ return;
+ }
+ const panel = el("div", "fb");
+ panel.append(el("div", "hint", t("问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。")));
+ const url = issueURL();
+ const step1 = el("div", "fb-row");
+ const copyLink = el("button", "btn", t("① 复制 issue 链接"));
+ copyLink.addEventListener("click", () => {
+ fb.copied = copyText(url) ? "link" : "fail";
+ renderFeedback();
+ });
+ // 直接打开本服务页面(不在 magpie 框架里)时这个链接能点开;框架里会被沙箱拦下,只能复制
+ const a = el("a", "fb-link", t("在 GitHub 新建 issue"));
+ a.href = url;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer";
+ step1.append(copyLink, a, el("span", "hint mute", t("到浏览器地址栏粘贴打开")));
+ const step2 = el("div", "fb-row");
+ const copyBody = el("button", "btn", t("② 复制问题内容"));
+ copyBody.disabled = fb.body === null;
+ copyBody.addEventListener("click", () => {
+ if (fb.body === null) return;
+ fb.copied = copyText(fb.body) ? "body" : "fail";
+ renderFeedback();
+ });
+ step2.append(copyBody, el("span", "hint mute", fb.body === null && !fb.error ? t("正在收集诊断…") : t("粘贴到 issue 正文")));
+ panel.append(step1, step2);
+ if (fb.error) panel.append(el("div", "hint warn", `${t("诊断收集失败:")}${fb.error}`));
+ if (fb.copied === "link") panel.append(el("div", "hint", t("链接已复制。")));
+ if (fb.copied === "body") panel.append(el("div", "hint", t("问题内容已复制。")));
+ if (fb.copied === "fail") panel.append(el("div", "hint warn", t("复制失败:浏览器不允许这个页面写剪贴板。")));
+ box.replaceChildren(panel);
+}
+
// ---------- 启动 ----------
/** 把 magpie 的深浅主题与设计令牌落到文档上;boot 数据块与主题消息两个来源共用 */
@@ -1517,6 +1637,8 @@ function applyStaticTexts(): void {
document.documentElement.lang = currentLang();
const newBtn = document.getElementById("new");
if (newBtn) newBtn.textContent = t("新建任务");
+ const fbBtn = document.getElementById("feedback");
+ if (fbBtn) fbBtn.textContent = t("反馈问题");
const info = document.getElementById("info");
if (info) {
info.setAttribute("aria-label", t("说明"));
@@ -1567,6 +1689,7 @@ function init(): void {
document.getElementById("new")?.addEventListener("click", () => {
if (!isReadonly() && !isNew) openNew();
});
+ document.getElementById("feedback")?.addEventListener("click", () => void openFeedback());
document.addEventListener("mousedown", (e) => {
if (popEl && e.target instanceof Node && !popEl.contains(e.target) && !popEl.btn.contains(e.target)) closePop();
});
diff --git a/packages/window-warmup/web/i18n.ts b/packages/window-warmup/web/i18n.ts
index 02203d5..34100ce 100644
--- a/packages/window-warmup/web/i18n.ts
+++ b/packages/window-warmup/web/i18n.ts
@@ -131,6 +131,25 @@ export const I18N: Partial> = {
"The page is missing its access token; please reopen it from Magpie's plugin page.",
"窗口预热": "Window Warmup",
"新建任务": "New task",
+ "反馈问题": "Report a problem",
+ "(把「复制问题内容」复制的内容粘贴到这里,替换这一行)": "(Paste what “Copy the report” copied here, replacing this line)",
+ "问题描述": "What happened",
+ "(发生了什么,期望是什么)": "(What happened, and what you expected)",
+ "复现步骤": "Steps to reproduce",
+ "环境": "Environment",
+ "诊断日志(已脱敏)": "Diagnostics (anonymized)",
+ "(诊断日志过长,已截断)": "(diagnostics too long, truncated)",
+ "问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。": "The report includes an anonymized diagnostics log (accounts, keys and task names are replaced); you can preview it on GitHub before submitting.",
+ "① 复制 issue 链接": "① Copy the issue link",
+ "在 GitHub 新建 issue": "New issue on GitHub",
+ "到浏览器地址栏粘贴打开": "paste it into your browser's address bar",
+ "② 复制问题内容": "② Copy the report",
+ "正在收集诊断…": "Collecting diagnostics…",
+ "粘贴到 issue 正文": "paste it into the issue body",
+ "诊断收集失败:": "Collecting diagnostics failed: ",
+ "链接已复制。": "Link copied.",
+ "问题内容已复制。": "Report copied.",
+ "复制失败:浏览器不允许这个页面写剪贴板。": "Copy failed: the browser doesn't let this page write to the clipboard.",
"说明": "Help",
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。":
"Each message is billed under the provider's own quota rules and may draw on bonus quota or API balance; a successful send does not guarantee the window has started counting.",
@@ -255,6 +274,25 @@ export const I18N: Partial> = {
"頁面缺少存取權杖,請從 Magpie 的外掛頁重新開啟。",
"窗口预热": "窗口預熱",
"新建任务": "新增任務",
+ "反馈问题": "回報問題",
+ "(把「复制问题内容」复制的内容粘贴到这里,替换这一行)": "(把「複製問題內容」複製的內容貼到這裡,取代這一行)",
+ "问题描述": "問題描述",
+ "(发生了什么,期望是什么)": "(發生了什麼,期望是什麼)",
+ "复现步骤": "重現步驟",
+ "环境": "環境",
+ "诊断日志(已脱敏)": "診斷日誌(已去識別化)",
+ "(诊断日志过长,已截断)": "(診斷日誌過長,已截斷)",
+ "问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。": "問題內容會附上去識別化的診斷日誌(帳號、key、任務名都已替換),送出前可以在 GitHub 上先預覽。",
+ "① 复制 issue 链接": "① 複製 issue 連結",
+ "在 GitHub 新建 issue": "在 GitHub 新增 issue",
+ "到浏览器地址栏粘贴打开": "到瀏覽器網址列貼上開啟",
+ "② 复制问题内容": "② 複製問題內容",
+ "正在收集诊断…": "正在收集診斷…",
+ "粘贴到 issue 正文": "貼到 issue 內文",
+ "诊断收集失败:": "診斷收集失敗:",
+ "链接已复制。": "連結已複製。",
+ "问题内容已复制。": "問題內容已複製。",
+ "复制失败:浏览器不允许这个页面写剪贴板。": "複製失敗:瀏覽器不允許這個頁面寫入剪貼簿。",
"说明": "說明",
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。":
"訊息按供應商自己的額度規則計費,可能用到贈送額度或 API 餘額;傳送成功不代表窗口一定已開始計時。",
@@ -379,6 +417,25 @@ export const I18N: Partial> = {
"ページにアクセストークンがありません。Magpie のプラグインページから開き直してください。",
"窗口预热": "ウィンドウ予熱",
"新建任务": "新規タスク",
+ "反馈问题": "問題を報告",
+ "(把「复制问题内容」复制的内容粘贴到这里,替换这一行)": "(「報告内容をコピー」でコピーした内容をここに貼り付け、この行と置き換えてください)",
+ "问题描述": "問題の内容",
+ "(发生了什么,期望是什么)": "(何が起きたか、どうなるはずだったか)",
+ "复现步骤": "再現手順",
+ "环境": "環境",
+ "诊断日志(已脱敏)": "診断ログ(匿名化済み)",
+ "(诊断日志过长,已截断)": "(診断ログが長すぎるため切り詰めました)",
+ "问题内容会附上脱敏后的诊断日志(账号、key、任务名都已替换),提交前可以在 GitHub 上先预览。": "報告には匿名化した診断ログが付きます(アカウント・key・タスク名は置き換え済み)。送信前に GitHub でプレビューできます。",
+ "① 复制 issue 链接": "① issue のリンクをコピー",
+ "在 GitHub 新建 issue": "GitHub で issue を作成",
+ "到浏览器地址栏粘贴打开": "ブラウザのアドレスバーに貼り付けて開く",
+ "② 复制问题内容": "② 報告内容をコピー",
+ "正在收集诊断…": "診断を収集中…",
+ "粘贴到 issue 正文": "issue の本文に貼り付け",
+ "诊断收集失败:": "診断の収集に失敗しました:",
+ "链接已复制。": "リンクをコピーしました。",
+ "问题内容已复制。": "報告内容をコピーしました。",
+ "复制失败:浏览器不允许这个页面写剪贴板。": "コピーに失敗しました:このページはクリップボードへの書き込みを許可されていません。",
"说明": "ヘルプ",
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。":
"メッセージはプロバイダー独自のクォータ規則で課金され、ボーナス額度や API 残高を使うことがあります。送信が成功してもウィンドウの計時が始まったとは限りません。",
diff --git a/packages/window-warmup/web/index.html b/packages/window-warmup/web/index.html
index 343fca0..4556998 100644
--- a/packages/window-warmup/web/index.html
+++ b/packages/window-warmup/web/index.html
@@ -17,6 +17,8 @@
+
+
diff --git a/packages/window-warmup/web/style.css b/packages/window-warmup/web/style.css
index b40564c..0b6885d 100644
--- a/packages/window-warmup/web/style.css
+++ b/packages/window-warmup/web/style.css
@@ -146,3 +146,12 @@ input.text::placeholder { color:var(--faint); }
.editor > label { text-align:left; padding-top:0; }
.qm .tip { width:min(320px, 86vw); }
}
+
+/* 反馈问题:页脚的低调文字入口 + 两步复制面板(沙箱里打不开外链,只能复制) */
+.foot { display:flex; justify-content:flex-end; margin-top:10px; }
+.link { color:var(--faint); font-size:11.5px; padding:2px 4px; }
+.link:hover { color:var(--fg-2); text-decoration:underline; }
+.fb { margin-top:6px; background:var(--card); border:1px solid var(--line); border-radius:10px; padding:10px 12px; display:flex; flex-direction:column; gap:8px; }
+.fb .hint { margin-top:0; }
+.fb-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
+.fb-link { font-size:12px; color:var(--accent); }