window-warmup 0.1.0: a page that sends a short message after a quota window resets, daily or every few hours (#661)
Adds packages/window-warmup (@magpie-community/page-window-warmup 0.1.0), by YangHonghang: a page plugin whose host part runs a service on 127.0.0.1:3492 and, on a schedule (after a quota window resets, daily at a set time, or every N hours), sends "hi" with max_tokens 16 through magpie's gateway to a provider/account/model the user picks. The registry entry moves from the author's own npm package magpie-window-warmup to this one. The package README opens with the zh/en warning that sends spend real quota and that some vendors (Claude subscriptions especially) may treat scheduled requests as unusual use. Reviewed at 07a0b217adb2a111f839c984cbc955c5bb45b68d: - Outside packages/window-warmup only README.md and registry.json change; no workflow and no other package. - The service binds 127.0.0.1, checks Host (DNS rebinding) and Origin (null or itself), needs a per-process 32-byte token on /api/*, and serves the index with a nonce CSP. - It reaches only MAGPIE_ADDR (default 127.0.0.1:3425). providers.json is read for sha256 key fingerprints only; no spawn, eval or outside hosts. - A window task sends at most once per resetsAt (or once per hour when idle); daily/every tasks catch up only the latest missed point, once. Run on mote (bun 1.4.2): - HOME=$(mktemp -d) bun test at the repo root: 5142 pass, 15 skip, 0 fail. - scripts/check.mjs ok. - packages/window-warmup bun test: 242 pass (dist.test rebuilds dist byte for byte). - browser.test.ts with Playwright 1.62.0: chromium and webkit pass. Bun ignores NODE_PATH, so it needs node_modules/playwright linked and PLAYWRIGHT_BROWSERS_PATH set under a temp HOME; without them it skips. Not tried: a real send through a live magpie gateway, and tsc --noEmit (no typescript on mote).
This commit is contained in:
@@ -124,6 +124,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
|
||||
| [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
|
||||
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
|
||||
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
|
||||
| [window-warmup](packages/window-warmup) | Window warmup: send one fixed short message ("hi", max_tokens 16) to a provider, account and model you pick, right after its quota window resets, daily at set times or every few hours, so the next subscription window opens early, by [YangHonghang](https://github.com/YangHonghang). Has a host part: a local service on 127.0.0.1 the page goes to | none (its service calls magpie's gateway) |
|
||||
| [agent-console](packages/agent-console) | Drive the Agent CLIs on this computer (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh) with a timeline, Git changes, files and a terminal, by [qingnian108](https://github.com/qingnian108). Has a host part: a gate and a daemon on 127.0.0.1, started when the page opens | none (its daemon runs the Agent CLIs you pick, in the projects you open) |
|
||||
|
||||
```sh
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# AGENTS.md
|
||||
|
||||
本包是 magpie 社区插件「窗口预热(Window Warmup)」:在 magpie 宿主进程里按计划向指定供应商 / 账号 / 模型发一条 `hi`(`max_tokens: 16`),提前开启订阅额度窗口。源码位于社区仓库 magpie-community/plugins 的 `packages/window-warmup/`,作者 YangHonghang。用户可见行为、触发规则、去重与费用说明以 `README.md` 为准,改行为时同步更新 README。
|
||||
|
||||
## 命令
|
||||
|
||||
运行时、包管理器、构建与测试都用 Bun(`engines.bun >= 1.4.2`),不引入其他构建工具。
|
||||
|
||||
```sh
|
||||
bun install # 仓库根目录:安装所有 workspace 的依赖(含 playwright)
|
||||
bun run build # packages/window-warmup 内:scripts/build.ts → dist/plugin.js、dist/ui/…
|
||||
bun run typecheck # packages/window-warmup 内:tsc --noEmit,覆盖 src、scripts、tests、web
|
||||
bun test # 仓库根目录:跑所有包的测试;包内跑本包测试
|
||||
bun test tests/rules.test.ts # 单个文件
|
||||
bun test tests/scheduler.test.ts -t "关键字" # 按用例名过滤
|
||||
```
|
||||
|
||||
- **`dist/` 入库**,宿主直接加载 `dist/plugin.js`(`package.json` 的 `main`),服务从 `dist/ui` 提供静态页。改了 `src/` 或 `web/` 必须 `bun run build` 并一并提交 `dist/`。
|
||||
- `tests/server.test.ts` 的 `beforeAll` 会调用 `buildAll()` 重建 `dist/`。
|
||||
- `tests/fake-gateway.ts` 是假的 magpie 网关,网关 / 调度相关测试都靠它,不打真实网关。
|
||||
- `tests/browser.test.ts` 用真实 Chromium 与 WebKit 走一遍页面冒烟。Playwright 是**可选依赖**:仓库不安装、CI 也不安装,评审机通过 `NODE_PATH` 提供;本机没装时整组自动跳过。要本地跑:自备 playwright(如 `bunx playwright install chromium webkit`),并在真实 HOME 下运行或设 `PLAYWRIGHT_BROWSERS_PATH`。
|
||||
- `tests/dist.test.ts` 构建到临时目录,与入库的 `dist/` 逐字节比对;测试本身不写工作区,改源码后必须 `bun run build` 并提交 `dist/`。
|
||||
- `tests/discoverability.test.ts` 校验 `registry.json` 条目、搜索词与包契约,改包名或简介时一起看。
|
||||
|
||||
## 发布
|
||||
|
||||
- **合并 PR 即发包**:社区仓库的 `.github/workflows/publish.yml` 由 `packages/window-warmup/package.json` 的版本变化触发,先跑全仓测试与 `scripts/check.mjs`,再把新版本打包进 `dist` 分支(magpie 在没有 npm 版本时从那里安装),最后把 npm 上还没有的版本发布出去。
|
||||
- **版本号必须和改动在同一个 PR**:只改代码不改 `version`,合并后不会发版,用户也拿不到。发新版就加版本号(0.1.1、0.1.2…)。
|
||||
- 新包在 npm 的第一个版本无法用 Trusted Publishing 创建,需要社区 owner 手动发布一次;在那之前 magpie 从 `dist` 分支安装。`README` 因此不写 `npm i`。
|
||||
- 已安装用户由 magpie 自动更新(社区包一小时内),无需用户操作。
|
||||
- 本仓库的 `registry.json` 条目(`kind: "page"`、`community: true`)只在名称、图标或中英文简介变化时才需要改;包名、图标 URL 由 `tests/discoverability.test.ts` 守卫。
|
||||
|
||||
## 架构
|
||||
|
||||
两层入口 + 一个带路页:
|
||||
|
||||
- **`page/index.html` + `page/boot.js`(带路页)**:magpie 页面框架里加载的页面。CSP 为 `connect-src 'none'`,脚本不能联网探测,只能整页跳转到本地服务;跳转时带上 magpie bridge 给的主题、语言、设计令牌,`magpie web` 场景优先跳 `window.magpie.service` 转发地址。
|
||||
- **`src/plugin.ts`(宿主入口)**:`server()` 先探测端口上是否已有本插件(所有响应带 `x-window-warmup: 1`),有就复用;没有才迁移旧数据并 `startService`。**模块不要导出额外函数**——宿主会把导出的每个函数都当插件函数调用。
|
||||
- **`src/server.ts`**:只监听 `127.0.0.1` 的 Bun 服务。每进程随机 token 注入首页,`/api/*` 必须带 `x-window-warmup-token`;校验 Host / Origin(防 DNS 重绑定)、CSP。store 损坏 → fatal(只展示原因、不调度、拒绝写);锁被他人持有 → 只读。
|
||||
- **`web/app.ts`(页面 UI)**:DOM 一律 `createElement` + `textContent`,不拼 HTML。导出的纯函数供测试复用,被 import 时不碰 DOM(文件尾部守卫)。编辑区由 `buildEditor` 按区块拼装(`sendToParts` / `triggerSeg` / `triggerFields` / `nextPreview` / `editorActions` / `runsSection`)。i18n 在 `web/i18n.ts`(`app.ts` 原样转出,测试从 app 取用),键即中文原文,en / zh-TW / ja 三张表键集合必须一致(`tests/i18n.test.ts` 守卫)。
|
||||
|
||||
核心模块分工:
|
||||
|
||||
- **`src/rules.ts`**:纯时间计算(每天定时含时区 / 夏令时、固定间隔、窗口到期 = `resetsAt` + 30s、补发回看 48 小时)、任务校验与探活消息常量。**页面直接打包本模块**(编辑区预览与调度器用同一个 `upcoming`),所以它只能依赖 `types.ts`,不得引入 `node:*` 或网关模块(`tests/rules.test.ts` 有守卫)。`types.ts` 同理,另放各层共用的 `errText`。
|
||||
- **`src/scheduler.ts`**:所有改状态入口(tick / upsert / remove / runNow)走同一操作队列串行;发送本体在队列外但登记在 inflight,保证同任务不重叠、删除后异步完成不会把记录写回。单定时器,最长睡 10 分钟后重算。窗口任务发送前后让 magpie 单卡重读额度(`readAt` 早于上次发送的空闲读数不信)。判断逻辑集中在几个私有函数:`pendingFixedDue`(定时/间隔该不该补发)、`currentWindowDue` + `windowReady`(窗口到期且本轮未尝试,纯计算);`lastReset` 只在 `recordResets` 里写(额度刷新后与 `rearm` 时),不要再把写盘塞回查询路径。
|
||||
- **`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`。
|
||||
- **`src/store.ts`**:`state.json` 临时文件 + rename 落盘,损坏时拒绝启动且绝不改动原文件;`service.lock` 原子排他创建 + pid 活性判断(活性不明不抢占,pid 存活但端口无本插件应答视为陈旧锁接管);一次性从旧包 `scheduled-messages` 迁移 `state.json`。
|
||||
|
||||
## 供应商 → 账号 → 模型级联(无官方接口的绕行路径)
|
||||
|
||||
Magpie 不提供「供应商 / 账号 / 每账号可用模型」的列表接口,目录是拼出来的。用户视角的完整说明见 README「供应商 → 账号 → 模型」一节,改规则时两处同步。
|
||||
|
||||
**数据链路**:`fetchCatalog`(`src/gateway.ts`)并发读取 `/v1/models` 与额度卡(`fetchQuotas`:平时 `?kept=1` 只读缓存,缓存空时兜底读完整接口,至少间隔 5 分钟),再经 `readDefaultKeyDirectory` / `readDefaultModelCache` 读 `providers.json` 和 `<缓存目录>/models/<pid>.json`,逐个供应商调用 `accountsOf` 生成 `/api/catalog`。页面(`web/app.ts` 的 `accountOptions` / `modelOptions` / `windowOptions` / `accountModelView`)只消费目录、不做推算,每 60 秒刷新。调度器 `resolveSend`(`src/scheduler.ts`)发送前重新读同样的数据,再调用同一组函数(`modelsForAccount`、`pickAutoModel`、`pinFor`、`windowsForAccount`)。
|
||||
|
||||
**关键绕行点**(都在 `src/accounts.ts` 与 `src/magpie-files.ts`):
|
||||
|
||||
- **供应商**:模型按 `owned_by`、否则按 id 首段归属(`modelProvider`),跳过 `group/`;额度卡的 provider 也算,`<p>/~keys` 归一为 `<p>` 并标记 `viaKey`(`parseQuotas`)。
|
||||
- **key 账号**:`providers.json` 的 `key` + 未停用的 `keys[]`,取 `sha256(key)` 前 5 字节 hex 作为指纹,与 Magpie `internal/provider/keys.go` 的 keyID 同一算法。这个指纹是连接三方的唯一桥梁:模型缓存的 `Keys`、`accountModels` 的键、发送头 `<P>#<指纹>`。改算法会让三处同时失配。
|
||||
- **订阅账号**:非 key 卡的额度卡 `user`。
|
||||
- **key 账号的窗口**:用指纹反查 key 名,匹配 `<p>/~keys` 卡的 `user`(不分大小写相等,或以 `名字 · ` 开头);无名 key 接受无窗口。
|
||||
- **模型三层过滤**(`modelsForAccount`):
|
||||
1. 缓存 `Keys` 可见性(仅缓存存在且账号是指纹时);
|
||||
2. `accountModels[指纹或小写账号名]`,比对不带供应商前缀的 id;
|
||||
3. 必须仍在 `/v1/models` 里。
|
||||
|
||||
无缓存时退化为 `/v1/models` 全量(`perAccount: false`),两者皆无时返回 `list: null`。
|
||||
- **发送头**(`pinFor`):订阅账号原样发;key 指纹在启用 key 不少于 2 把(目录读不出时按 2 把处理)时发 `<P>#<指纹>`,只有 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 与便携版。
|
||||
|
||||
## 约定
|
||||
|
||||
- 默认端口 3492 同时出现在 `package.json`(`magpie.options` / `magpie.page.service`)、`src/plugin.ts` 的 `DEFAULT_PORT`、`page/boot.js`,改动需三处一致。
|
||||
- 插件页的搜索文本来自 `registry.json` 这一条的 `name` + 包名 + 当前语言 `summary`(小写子串匹配、不分词),`tests/discoverability.test.ts` 逐个搜索词守卫;`package.json` 的 `keywords` 只服务 npm 自身搜索。
|
||||
- 除本地 magpie 网关外不得引入任何对外连接;预热消息内容固定,不提供自定义。
|
||||
- Commit 格式:`[type] 中文简述`(`feat` / `fix` / `doc` / `refactor` / `test` / `chore`),参见 `git log`。
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Yang
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,180 @@
|
||||
# 窗口预热(Window Warmup)
|
||||
|
||||
> **注意**:定时自动发送会真实消耗所选账号的订阅额度;部分厂商(尤其 Claude 订阅)可能把定时自动请求视为异常用量。是否使用、何时使用由用户自行判断并承担风险。
|
||||
>
|
||||
> **Note**: Scheduled sends really spend the chosen account's subscription quota. Some vendors (Claude subscriptions especially) may treat scheduled automated requests as unusual use. Whether and when to use it is the user's own call and risk.
|
||||
|
||||
Window Warmup is a page plugin for [magpie](https://usemagpie.ai) that sends a short keep-alive message to a provider, account and model of your choice — right after a quota window resets, at a fixed time of day, or every few hours — so the next subscription usage window opens early. It runs inside the Magpie host process; a local page manages tasks and shows run history.
|
||||
|
||||
在 magpie 窗口里按计划给指定供应商、账号和模型发一条短消息,用来提前开启下一轮额度(订阅)窗口。消息内容固定为 `hi`、`max_tokens: 16`,只当探活用,不可自定义;**每条消息都会真实发给所选模型并计费**。
|
||||
|
||||
本插件是 magpie 社区插件,源码在 [magpie-community/plugins 的 packages/window-warmup](https://github.com/magpie-community/plugins/tree/main/packages/window-warmup),作者 [YangHonghang](https://github.com/YangHonghang)。
|
||||
|
||||
## 安装
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/page-window-warmup
|
||||
```
|
||||
|
||||
也可以在 magpie 插件页的搜索框里搜 `warmup` 或「窗口预热」找到它。装好后在侧边栏 Plugins 下出现 **Window Warmup**(窗口预热)标签页。页面界面的语言跟随 Magpie 本身(zh / zh-TW / en / ja),不单独设置。
|
||||
|
||||
新包在 npm 上还没有第一个版本时,magpie 从社区仓库的 `dist` 分支安装并在之后自动更新,功能不受影响;npm 上有版本之后按常规方式安装即可。
|
||||
|
||||
## 三种触发
|
||||
|
||||
| 触发 | 到期点 | 去重 |
|
||||
|---|---|---|
|
||||
| 窗口重置后 | 账号额度窗口的 `resetsAt` 加 30 秒宽限(确保 magpie 侧已完成重置);窗口空闲(重置点已过或没有)则立即到期 | 同一 `resetKey` 最多尝试一次,成功、失败、未知都算;有重置点时 key 就是重置点本身,同一轮重置只发一次;没有重置点的空闲窗口按快照所在小时计 key |
|
||||
| 每天定时 | 指定 IANA 时区的 `HH:MM`;夏令时跳过的时刻顺延到跳变后第一个有效时刻,重复时刻取较早一次 | 按到期点记 |
|
||||
| 固定间隔 | 起点 anchor 之后每 1–168 小时一个点 | 按到期点记 |
|
||||
|
||||
所有任务都必须选定账号(预热发给具体账号或 key;交给网关自动选,就没有稳定的去重与窗口归属)。调度器只保留一个定时器,最长睡 10 分钟就醒来重算,系统睡眠、改系统时间都能自愈。额度快照约每 10 分钟及每次发送后刷新。magpie 的额度缓存只在它路由请求那一刻读卡(没有托盘的 `magpie web` 平时不读),所以窗口任务快到期要发送时,以及发送满 1 分钟后,插件会让 magpie 重读这一张订阅卡(`POST /v1/magpie/quotas/refresh`,同用量页单卡「刷新」,只查余额);卡片读取时刻(`readAt`)早于上次发送的空闲读数一律不信,宁可晚发也不重发。
|
||||
|
||||
## 模型与思考档位
|
||||
|
||||
模型选「自动」时,任务里不存选中值,每次发送前按统一账号规则现选(目录与调度器同一份实现):
|
||||
|
||||
- 可选模型以 Magpie 的模型缓存为基础,按账号收窄:key 账号只留该 key 能看到的模型(缓存里的 Keys 指纹),providers.json 的 accountModels 给账号配了清单就只留清单内的;
|
||||
- 没有模型缓存的供应商(插件型订阅供应商本来就不写缓存)退而用 `/v1/models` 里的全部模型,此时不按账号区分;连 `/v1/models` 都没有该供应商的模型 → 本次失败「供应商 X 还没有模型列表,无法自动选模型」;
|
||||
- 收窄后按模型 id 最后一段的规格词排序 `flash < lite < mini < nano < small < turbo`(整词匹配、不分大小写,"minimax" 不算 mini),都不含的排最后;同档按 id 数字感知降序(新版本优先),取第一个;
|
||||
- 收窄后一个模型都不剩 → 本次失败「账号 X 没有可用模型」。
|
||||
|
||||
插件页的目录会直接显示每个账号「自动」当前会选中谁。
|
||||
|
||||
思考档位同样不保存在任务里,每次发送前从当次 `/v1/models` 取该模型自己的档位列表现算,模型配置变了下次发送自动跟随:
|
||||
|
||||
- 模型不支持思考或档位列表为空 → 不带 `reasoning_effort`;
|
||||
- 档位里有 `none`(`disabled`/`off` 视同)→ `reasoning_effort: "none"`,能关就关;
|
||||
- 否则取该模型列表里最低一档(已知名按 `minimal < low < medium < high < xhigh < max` 排,纯数字思考预算低于所有命名档;全部是不知名的取列表第一档)。
|
||||
|
||||
每次执行记录都会写下当次实际用的模型与档位。
|
||||
|
||||
## 失败与补发
|
||||
|
||||
- **失败不暂停**:失败、超时(30 秒内没有结果,记 `unknown`,「可能已发送」)只写进执行记录,原因原样显示在页面上,任务保持启用,下一个时刻照常;不自动重发本次。
|
||||
- **同一任务不重叠**:上一次发送还没结束,本次记「跳过」。
|
||||
- **Magpie 关闭期间不执行**:调度跑在 magpie 宿主进程里,magpie 没开就没有发送。重新打开(或从睡眠恢复)后,每个任务最多补发一次:每天定时/固定间隔任务补发最近错过的应到点(须晚于任务最后一次编辑;每天定时只回看最近 48 小时),多个错过的点只补一个;窗口任务由 `resetKey` 去重兜着,同一轮重置不会发第二次。
|
||||
- 找不到账号或窗口时记失败原因,不发送;额度快照取不到(刷新一直失败)时静默等下一轮刷新,不写执行记录。
|
||||
- magpie 刚启动、额度缓存还是空的时候,插件会兜底读一次完整额度接口(只读余额,不发模型请求,15 秒超时);两次兜底读取至少间隔 5 分钟。
|
||||
|
||||
## 供应商 → 账号 → 模型:级联选择是怎么拼出来的
|
||||
|
||||
Magpie 没有给插件提供「列出供应商、每个供应商有哪些账号、每个账号能用哪些模型」的接口:`/v1/models` 只有一张不分账号的模型清单,`/v1/magpie/quotas` 只有额度卡,账号与 key 的对应关系只存在于 Magpie 自己的配置和缓存文件里。插件把下面四处现成数据拼成一份目录:
|
||||
|
||||
| 来源 | 取用内容 | 用在哪一级 |
|
||||
|---|---|---|
|
||||
| 网关 `GET /v1/models` | 全部模型 id、`owned_by`、思考档位 | 供应商归属、模型的最终白名单、思考档位 |
|
||||
| 网关 `GET /v1/magpie/quotas?kept=1` | 额度卡:`provider`、`user`、`windows`、`readAt` | 订阅账号、窗口;补充只有额度卡的供应商 |
|
||||
| 文件 `<配置目录>/providers.json` | 每个供应商启用的 key(只算指纹)、key 名、`accountModels` | key 账号;模型第 2 层过滤 |
|
||||
| 文件 `<缓存目录>/models/<供应商id>.json` | Magpie 上次「获取模型」的结果:每个模型的 `ID` 与 `Keys`(能看到它的 key 指纹) | 模型第 1 层过滤(按 key 可见性) |
|
||||
|
||||
服务端 `/api/catalog`(`src/gateway.ts` 的 `fetchCatalog`)一次算好整份目录,页面打开时拉取、之后每 60 秒刷新一次;调度器每次发送前用**同一份规则**(`src/accounts.ts`)重新计算,所以页面上显示的账号、模型和「自动」选中项,与实际发送时一致。
|
||||
|
||||
### 1. 供应商
|
||||
|
||||
- `/v1/models` 里的每个模型按 `owned_by`(真正接住请求的一方)归到供应商,没有 `owned_by` 时取 id 的第一段;`group/` 路由组不列出,归不到供应商的模型丢弃(任务必须有供应商)。
|
||||
- 额度卡上出现的供应商也列出,即使它暂时没有模型;远程 key 卡的 `<p>/~keys` 归一成 `<p>`。
|
||||
|
||||
### 2. 账号
|
||||
|
||||
Magpie 内部用「候选 ID」区分同一供应商下的多把 key 和多个订阅登录,但没有接口把它们列出来。插件从两处还原:
|
||||
|
||||
- **key 账号**:读 `providers.json`,取该供应商的第一把 `key` 与 `keys[]` 中未停用(`off` 不为 `true`)的 key,对 key 原文做 sha256 并取前 5 字节的小写 hex 作为指纹。这与 Magpie `internal/provider/keys.go` 的 keyID 算法一致,因此能同时对上模型缓存里的 `Keys` 和发送时的候选 ID。账号 id 是指纹,显示名是 key 名(没起名则显示指纹),按指纹去重。**key 原文算完指纹即丢。**
|
||||
- **订阅账号**:该供应商名下、非 key 卡的额度卡的 `user`,去重后原样作为账号 id 与显示名。
|
||||
|
||||
窗口挂到账号上的方式:
|
||||
|
||||
- 订阅账号按 `user` 精确匹配额度卡。
|
||||
- key 账号先用指纹反查 key 名,再找 `<p>/~keys` 卡里 `user` 与 key 名相同(不分大小写),或以「名字 · 」开头(同名多把 key 时的打码形态)的那张。远程 Magpie 会给每把网关 key 单独发这样一张限额卡。
|
||||
- 没起名的 key 无法匹配:卡名是打码后的样子,插件算不出来,这类账号没有窗口。
|
||||
- `unlimited: true` 的「不限额」占位不算窗口。没有窗口的账号不提供「窗口重置后」触发。
|
||||
|
||||
账号下拉没有「自动」项,所有任务都必须选账号。旧任务里存的账号值原样保留并标注「不在当前账号列表」;存的是 key 名的照样按名字发送,兼容升级。
|
||||
|
||||
### 3. 模型(三层过滤)
|
||||
|
||||
对选定的账号,候选模型依次经过:
|
||||
|
||||
1. **按 key 可见性**:仅当该供应商有模型缓存且账号是 key 指纹时,只留 `Keys` 为空(所有 key 可见)或包含这把指纹的模型。
|
||||
2. **按 `accountModels`**:`providers.json` 给这个账号(键为 key 指纹,或小写的订阅账号名)配了模型清单时,只留清单内的(比对不带供应商前缀的 id)。
|
||||
3. **按当前存在**:只留此刻仍在 `/v1/models` 里的。
|
||||
|
||||
没有模型缓存的供应商(插件型订阅供应商本来就不写缓存)退而用 `/v1/models` 里该供应商的全部模型,跳过第 1 层,所有账号共用同一份清单。缓存和 `/v1/models` 都没有该供应商的模型时,模型下拉禁用,并提示到 Magpie 里「获取模型」。
|
||||
|
||||
下拉首项「自动」按「模型与思考档位」一节的规则,从过滤后的列表里现选,并在旁边附注当前会选中哪个模型。
|
||||
|
||||
### 4. 发送时怎么指定到这个账号
|
||||
|
||||
预热消息发往 `/v1/chat/completions`,用 `X-Magpie-Account` 头钉住账号:
|
||||
|
||||
- **订阅账号**:头值是账号名原文;含非 ASCII 字符时按 UTF-8 字节写入头部。
|
||||
- **key 账号**:该供应商启用的 key 不少于 2 把时,头值是 `<供应商>#<指纹>`;只有 1 把时不带这个头。此时候选 ID 就是供应商 id,带了反而选不中。
|
||||
- **旧任务存的 key 名**:原样作为头值发送。
|
||||
|
||||
同时带 `X-Magpie-Session: window-warmup/<任务id>`,方便在 Magpie 日志里识别来源。
|
||||
|
||||
### 文件位置怎么推断
|
||||
|
||||
插件装在 `<配置目录>/plugins/node_modules/magpie-window-warmup/dist` 时,从这个路径往上 4 级就是 Magpie 的配置目录:
|
||||
|
||||
- 它等于安装版配置目录(`$XDG_CONFIG_HOME`,或 `~/.config` 下的 `magpie`)时,缓存目录取安装版位置(`$XDG_CACHE_HOME`,或 `~/.cache` 下的 `magpie`)。
|
||||
- 否则视为便携版,缓存目录是 `<配置目录>/cache`。
|
||||
|
||||
路径对不上(源码态开发等)时,按安装版目录读取。两种文件的读取结果在进程内缓存 5 秒;读不出时按「没有」处理,目录照常返回,不会整体报错。
|
||||
|
||||
## 插件只读的 Magpie 数据
|
||||
|
||||
除本地网关外插件没有任何对外连接;上节表格里的两份文件和两个网关读接口(地址取 `MAGPIE_ADDR`,默认 `http://127.0.0.1:3425`)全部只读不写,另外只调用 `/v1/chat/completions` 发预热消息,以及 `/v1/magpie/quotas/refresh` 让 Magpie 重读单张额度卡。
|
||||
|
||||
- **providers.json 红线**:key 原文只在「读文件 → 算指纹」这一步存在,不保存、不写日志、不进错误信息、不外传;配置文件损坏时报固定文案,绝不把文件内容带出来。
|
||||
- **模型缓存**只读每个模型的 `ID` 与 `Keys`(key 指纹),不含 key 原文与 key 名。
|
||||
|
||||
模型下拉被禁用并提示「还没有这个供应商的模型列表。请到 Magpie『供应商』里打开它,点『获取模型』。」时,就是第 2、3 样都拿不到该供应商的模型。
|
||||
|
||||
## 已知限制:插件拿不到的信息
|
||||
|
||||
插件的判断都来自 magpie 暴露的额度卡、模型列表与本地配置。下面这些情况它无法确认或纠正,任务可能失败、没有按预期开窗,或仍然产生费用。
|
||||
|
||||
**计费与窗口**
|
||||
|
||||
- **发送成功不等于窗口已开始**:有的供应商要累计到一定用量才开窗,或只在特定模型、端点上计入订阅用量;插件只能记录「已发送」,无法验证窗口是否真的开了。
|
||||
- **免费额度、赠送额度优先**:`hi` 可能只消耗赠送额度,订阅窗口不会开始;额度卡也未必能区分扣的是哪一档。
|
||||
- **固定周期的订阅**:自然月或固定重置日的订阅不随首次使用提前开窗,预热对它们没有效果。
|
||||
- **失败也可能计费**:上游在返回错误前已经受理的请求,插件只能按 HTTP 结果记「失败」或「结果未知」,无法知道是否扣了额度。
|
||||
- **空闲窗口按小时重试**:窗口一直不开时(例如上面几种),空闲窗口每小时尝试一次,每次都会真实发送,可能持续产生费用。
|
||||
|
||||
**额度与账号信息**
|
||||
|
||||
- **供应商没有额度卡**(常见于插件型订阅供应商):看不到窗口,只能用每天定时或固定间隔。
|
||||
- **没有起名的远程 key**:额度卡上的名字是打码形态,插件算不出对应关系,窗口任务会一直报「账号的额度里没有这个窗口」。
|
||||
- **额度卡瞬断或 Magpie 没在运行**:插件静默等下一轮刷新,可能错过一次重置;Magpie 关闭期间不执行,重开后每个任务最多补发一次。
|
||||
- **额度读数的时效**:依赖 Magpie 的缓存与单卡重读限频(30 秒),拿不到新读数时按快照时刻判断,发送可能提前或推迟。
|
||||
- **改过名的订阅供应商**:额度卡的供应商 id 是 agent 名,改名后目录里的账号与模型可能匹配不上。
|
||||
|
||||
**模型与账号权限**
|
||||
|
||||
- **没有模型缓存的供应商**(如插件型订阅供应商):不按账号区分模型,所有账号共用 `/v1/models` 的完整清单;自动选出的模型该账号可能无权使用,发送时才失败。
|
||||
- **模型清单是旧快照**:来自 Magpie 上次「获取模型」的结果,过期后可能选中已下线或账号不可见的模型;账号和模型对不上时去 Magpie 重新「获取模型」再刷新本页。
|
||||
- **思考档位只是建议**:按模型列表推导出的 `reasoning_effort`,上游不认识时不保证生效。
|
||||
- **自动选模型只看名字**:按 flash / lite / mini 等规格词挑最省的,不检查账号权限、最低 token 要求或区域限制;`max_tokens: 16` 被上游拒绝时本次失败。
|
||||
|
||||
## 数据在哪
|
||||
|
||||
- 数据目录:`WINDOW_WARMUP_DIR` 优先,否则 `${XDG_CONFIG_HOME:-~/.config}/magpie/window-warmup/`。`XDG_CONFIG_HOME` 只认绝对路径,留空或相对路径都按未设置处理(与 Magpie 自己的规则一致,插件数据目录与 Magpie 配置目录因此总在同一个根下)。
|
||||
- `state.json` 存任务、执行记录与去重标记,每任务保留最近 50 条记录;写入用临时文件加 rename。
|
||||
- 已知边界:落盘没有 fsync,断电极端情况可能留下损坏文件。程序会拒绝启动并显示原因,**原文件一个字节不动**,需要你确认后手动删除或修复。
|
||||
- 单实例锁 `service.lock` 写入持有者 pid;锁内容读不出或解析不了时按「活性不明」处理,页面提示另一个实例可能正在运行并只读展示,不会抢占。持有者 pid 活着但端口上没有本插件在应答(典型:Docker 容器重建后 pid 被无关进程复用,持久卷上的旧锁成了假阳性),视为陈旧锁自动接管、正常读写。
|
||||
|
||||
## 安全与端口
|
||||
|
||||
本地服务只监听 `127.0.0.1`(默认端口 3492,可在插件设置里改)。每次启动生成随机口令,经首页注入,`/api/*` 全部要求带 `x-window-warmup-token` 头;服务同时校验 `Host` 与 `Origin`(防 DNS 重绑定),响应按沙箱框架给 CORS 与 CSP,别的页面读不到接口。所有响应都带 `x-window-warmup: 1` 自标记:启动前插件先探测端口,已有本插件的服务在跑就直接复用,不重开数据目录。除 magpie 本地网关(发消息、读额度、读模型)外没有任何对外连接。
|
||||
|
||||
## 费用
|
||||
|
||||
每条消息都会真实发给所选模型并计费(内容固定 `hi`、`max_tokens: 16`,只当探活)。窗口触发以 magpie 额度快照为准,同一轮窗口只发一次;额度缓存长时间不更新时,空闲窗口按小时计 key,同一小时内最多尝试一次;读数早于上次发送的空闲不算数。
|
||||
|
||||
## 发布与维护
|
||||
|
||||
仓库在 [magpie-community/plugins](https://github.com/magpie-community/plugins) 的 `packages/window-warmup/`,插件页的条目登记在同一仓库的 `registry.json`(`kind: "page"`、`community: true`)。改代码走 PR:改版本号(`packages/window-warmup/package.json`)与改动放在同一个 PR,合并后仓库 CI 自动跑测试、把新版本打进 `dist` 分支,并把 npm 上没有的版本发布出去。`dist/` 入库,宿主直接加载它,发布流程不构建,改源码后要 `bun run build` 并一并提交。
|
||||
|
||||
已安装的用户由 magpie 自动更新(社区包一小时内),无需手动操作。`registry.json` 里这一条的名称、图标或中英文简介变化时,才需要单独提 PR 同步。
|
||||
+2186
File diff suppressed because it is too large
Load Diff
+1899
File diff suppressed because it is too large
Load Diff
+24
@@ -0,0 +1,24 @@
|
||||
<!doctype html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>窗口预热</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="app">
|
||||
<div class="wrap">
|
||||
<div class="bar">
|
||||
<span class="sum" id="sum"></span>
|
||||
<span class="sp"></span>
|
||||
<button class="qm" id="info" aria-label="说明">?<span class="tip">消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。<br>Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。<br>失败不会暂停任务,下一次照常执行。</span></button>
|
||||
<button class="btn" id="new">新建任务</button>
|
||||
</div>
|
||||
<div id="bars"></div>
|
||||
<div class="list" id="list"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="app.js" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
/* 窗口预热界面:逐值照已确认原型 v10 的样式实现(颜色变量、深色变量、控件尺寸、间距、字号)。
|
||||
深浅色经 body.dark 切换(启动页带 ?theme=),magpie 设计令牌由脚本写入 :root,同名变量即被覆盖。 */
|
||||
:root {
|
||||
--bg:#f4f4f6; --card:#fff; --card-2:#f9f9fb; --pill:#f1f1f4; --pill-hover:#e9e9ee;
|
||||
--line:#e3e3e8; --line-2:#ececf0; --fg:#1c1c21; --fg-2:#4b4b53; --muted:#85858d; --faint:#b9b9c2; --ctl-fg:#63636b;
|
||||
--accent:#4f46e5; --accent-soft:#eeedfd; --sel:#ecebfb;
|
||||
--green:#189a58; --green-soft:#e4f6ec; --red:#d64545; --red-soft:#fbe9e9; --amber:#b45309; --amber-soft:#fbf0df;
|
||||
--font:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI","PingFang SC","Microsoft YaHei",system-ui,sans-serif;
|
||||
--code:ui-monospace,"SF Mono",Menlo,Consolas,monospace;
|
||||
}
|
||||
body.dark {
|
||||
--bg:#1a1a1e; --card:#232327; --card-2:#1f1f23; --pill:#2d2d33; --pill-hover:#36363d;
|
||||
--line:#333339; --line-2:#2c2c32; --fg:#ededf1; --fg-2:#b9b9c1; --muted:#8b8b94; --faint:#56565f; --ctl-fg:#a1a1aa;
|
||||
--accent:#a5b4fc; --accent-soft:#2b2c47; --sel:#33345a;
|
||||
--green:#4ade80; --green-soft:#1d3327; --red:#f87171; --red-soft:#3a2224; --amber:#fbbf24; --amber-soft:#3a2f1c;
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
html,body { margin:0; height:100%; }
|
||||
body { font:13px/1.45 var(--font); color:var(--fg); background:var(--bg); }
|
||||
button,input,select,textarea { font:inherit; color:inherit; }
|
||||
button { background:none; border:0; cursor:default; }
|
||||
:focus-visible { outline:2px solid var(--accent); outline-offset:1px; }
|
||||
|
||||
/* 页面主体是唯一滚动容器:宿主给多高就占多高,插件内部只滚这一处 */
|
||||
.app { height:100%; overflow:auto; padding:14px 18px 24px; }
|
||||
.wrap { max-width:860px; margin:0 auto; }
|
||||
.bar { display:flex; align-items:center; gap:8px; margin-bottom:10px; }
|
||||
.bar .sum { color:var(--muted); font-size:12px; }
|
||||
.bar .sum b { font-weight:500; color:var(--fg-2); font-variant-numeric:tabular-nums; }
|
||||
.bar .sp { flex:1; }
|
||||
.qm { width:20px; height:20px; border-radius:50%; color:var(--faint); font-size:11px; font-weight:600; position:relative; box-shadow:inset 0 0 0 1px var(--line); }
|
||||
.qm:hover { color:var(--fg-2); }
|
||||
.qm .tip { display:none; position:absolute; right:0; top:26px; width:320px; z-index:5; text-align:left; font-weight:400; font-size:12px; color:var(--fg-2); background:var(--card); border-radius:10px; padding:10px 12px; line-height:1.6; box-shadow:0 16px 44px rgba(20,22,30,.16),0 0 0 .5px rgba(20,22,30,.1); }
|
||||
.qm:hover .tip, .qm:focus .tip { display:block; }
|
||||
/* 按钮:照 Magpie 的 .text.action / .text.primary / .text.danger */
|
||||
.btn { height:27px; padding:0 10px; border-radius:6px; font-size:12px; border:1px solid var(--line); background:var(--card); color:var(--fg-2); box-shadow:0 1px 1px rgba(0,0,0,.04); }
|
||||
.btn:hover { border-color:var(--muted); background:var(--card-2); color:var(--fg); }
|
||||
.btn.primary { border-color:transparent; background:var(--accent); color:#fff; font-weight:500; }
|
||||
body.dark .btn.primary { color:#14142a; }
|
||||
.btn.primary:hover { filter:brightness(1.08); background:var(--accent); }
|
||||
.btn.danger { border:0; box-shadow:none; background:none; color:var(--ctl-fg); padding:0 7px; }
|
||||
.btn.danger:hover { color:var(--red); background:var(--red-soft); }
|
||||
.btn[disabled] { opacity:.5; }
|
||||
|
||||
/* 全局提示条(断连 / 致命 / 单实例锁 / 保存失败 / 目录错误):原型之外的必要补充,配色取自同一套变量 */
|
||||
.notice { margin-top:8px; border-radius:8px; padding:7px 12px; font-size:12px; }
|
||||
.notice.warn { background:var(--amber-soft); color:var(--amber); }
|
||||
.notice.bad { background:var(--red-soft); color:var(--red); }
|
||||
|
||||
.list { background:var(--card); border:1px solid var(--line); border-radius:12px; overflow:hidden; }
|
||||
.row { display:flex; align-items:center; gap:12px; min-height:48px; padding:7px 12px 7px 14px; }
|
||||
.row + .row, .editor + .row, .row + .editor { border-top:1px solid var(--line-2); }
|
||||
.row:hover { background:var(--card-2); }
|
||||
.who { flex:1; min-width:0; }
|
||||
.who .name { font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.who .sub { font-size:11.5px; color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:1px; }
|
||||
.row.dim .name { color:var(--muted); }
|
||||
.when { text-align:right; flex:none; font-size:11.5px; color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.when .t { color:var(--fg-2); font-size:12px; }
|
||||
.when .s.bad { color:var(--red); }
|
||||
.when .s.unk { color:var(--amber); }
|
||||
/* 开关:Magpie 的 lib-switch,开是前景色(黑),不是绿 */
|
||||
.sw { width:28px; height:16px; border-radius:10px; background:var(--line); position:relative; flex:none; transition:background .2s; }
|
||||
.sw::after { content:""; position:absolute; top:2px; left:2px; width:12px; height:12px; border-radius:50%; background:#fff; box-shadow:0 1px 2px rgba(0,0,0,.25); transition:transform .22s; }
|
||||
.sw.on { background:var(--fg); }
|
||||
.sw.on::after { transform:translateX(12px); background:var(--card); }
|
||||
body.dark .sw.on::after { background:var(--bg); }
|
||||
.chev { color:var(--faint); width:12px; flex:none; transition:transform .15s; font-size:14px; }
|
||||
.row.open .chev { transform:rotate(90deg); color:var(--muted); }
|
||||
|
||||
/* 展开编辑区:Magpie 的 .editor —— 标签右对齐、白底细边输入框 */
|
||||
.editor { background:var(--card-2); padding:16px 18px 14px; display:grid; grid-template-columns:fit-content(132px) minmax(0,1fr); gap:10px 14px; align-items:start; }
|
||||
.editor > label { font-size:12px; color:var(--fg-2); text-align:right; padding-top:5px; }
|
||||
.editor > .v { min-width:0; }
|
||||
.editor > .full { grid-column:1 / -1; }
|
||||
.note { font-size:12px; color:var(--red); }
|
||||
.note span { color:var(--fg-2); }
|
||||
.stale { font-size:12px; color:var(--amber); }
|
||||
/* 下拉:逐值照 Magpie 主窗口的 .field:
|
||||
高 25、左 8 右 5 内边距、间距 5、整体 12.5px;key 11.5px 浅灰;值 12.5px 字重 500 超长省略;箭头 11px。
|
||||
不用原生 select:原生控件自带边距和基线,key 与值对不齐 */
|
||||
.field { display:inline-flex; align-items:center; gap:5px; height:25px; padding:0 5px 0 8px; border-radius:6px; background:var(--pill); font-size:12.5px; line-height:18px; max-width:100%; min-width:0; transition:background .12s, box-shadow .12s; }
|
||||
.field:hover { background:var(--pill-hover); }
|
||||
.field.open { background:var(--pill-hover); box-shadow:inset 0 0 0 1px var(--accent); }
|
||||
/* 禁用的下拉(如该账号没有任何模型列表)只展示当前值:去 hover 反馈但保留 title 提示 */
|
||||
.field[disabled] { opacity:.5; }
|
||||
.field[disabled]:hover { background:var(--pill); box-shadow:none; }
|
||||
/* 字号不同(11.5 / 12.5)、中英文回退字体不同,按中线居中会让文字底边错开;人眼看的是基线,所以这里按基线对齐 */
|
||||
.field .kv { display:flex; align-items:baseline; gap:5px; min-width:0; flex:1 1 auto; overflow:hidden; }
|
||||
.field .k { color:var(--faint); font-size:11.5px; flex:none; }
|
||||
.field .v { min-width:0; flex:0 1 auto; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; font-weight:500; font-variant-numeric:tabular-nums; }
|
||||
.field .aux { flex:none; color:var(--faint); font-size:11.5px; font-variant-numeric:tabular-nums; }
|
||||
.field .chev { flex:none; color:var(--faint); display:inline-flex; margin-left:auto; padding-left:1px; }
|
||||
.field:hover .chev, .field.open .chev { color:var(--muted); }
|
||||
.field input[type=time], .field input[type=datetime-local] { border:0; background:none; outline:none; padding:0; font:inherit; font-weight:500; line-height:18px; height:20px; color:var(--fg); }
|
||||
/* 同 Magpie 主窗口:下拉排成固定列、撑满各自的列,箭头上下对齐;值再长也只在自己的列里省略 */
|
||||
.fields { display:grid; gap:5px; }
|
||||
.fields.c3 { grid-template-columns:repeat(auto-fit, minmax(180px, 1fr)); }
|
||||
.fields.c2 { grid-template-columns:minmax(0,1fr) minmax(0,1fr); max-width:420px; }
|
||||
.fields.c1 { grid-template-columns:minmax(0,1fr); }
|
||||
.fields > .field { justify-self:stretch; }
|
||||
.pop { position:fixed; z-index:30; min-width:180px; max-width:min(440px, calc(100vw - 24px)); max-height:300px; overflow:auto; padding:5px; border-radius:11px; background:var(--card); box-shadow:0 16px 44px rgba(20,22,30,.16),0 2px 8px rgba(20,22,30,.06),0 0 0 .5px rgba(20,22,30,.1); }
|
||||
.pop .it { display:flex; align-items:center; gap:8px; width:100%; min-height:28px; padding:4px 8px; border-radius:7px; font-size:12.5px; text-align:left; color:var(--fg); }
|
||||
.pop .it:hover, .pop .it:focus { background:var(--pill); outline:none; }
|
||||
.pop .it .tx { flex:1; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.pop .it .tick { width:12px; flex:none; color:var(--fg); font-size:11px; }
|
||||
.pop .it .aux { flex:none; color:var(--muted); font-size:11.5px; font-variant-numeric:tabular-nums; }
|
||||
input.text, textarea.text { width:100%; height:27px; padding:0 9px; border-radius:7px; border:1px solid var(--line); background:var(--card); font-size:12.5px; outline:none; }
|
||||
textarea.text { height:auto; min-height:27px; padding:4px 9px; resize:vertical; }
|
||||
input.text:focus, textarea.text:focus { border-color:var(--accent); box-shadow:0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
|
||||
input.text::placeholder { color:var(--faint); }
|
||||
.hint { margin-top:4px; font-size:11px; color:var(--fg-2); }
|
||||
.hint.mute { color:var(--muted); }
|
||||
.hint.warn { color:var(--amber); }
|
||||
.seg { display:inline-flex; padding:2px; border-radius:8px; background:var(--pill); }
|
||||
.seg button { height:22px; padding:0 11px; border-radius:6px; font-size:12px; color:var(--ctl-fg); }
|
||||
.seg button.on { background:var(--card); color:var(--fg); box-shadow:0 1px 2px rgba(0,0,0,.14),0 0 0 .5px rgba(0,0,0,.08); }
|
||||
.next { margin-top:6px; font-size:11px; color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.next b { font-weight:500; color:var(--fg-2); }
|
||||
.actions { display:flex; gap:8px; align-items:center; padding-top:12px; border-top:1px solid var(--line-2); }
|
||||
.actions .sp { flex:1; }
|
||||
.dirty-tip { font-size:11.5px; color:var(--muted); }
|
||||
|
||||
.runs-h { display:flex; align-items:baseline; gap:8px; margin-top:4px; }
|
||||
.runs-h b { font-weight:500; font-size:12px; color:var(--fg-2); }
|
||||
.runs-h span { font-size:11px; color:var(--muted); }
|
||||
.runs-h .sp { flex:1; }
|
||||
.link { font-size:12px; color:var(--ctl-fg); padding:3px 7px; border-radius:6px; }
|
||||
.link:hover { color:var(--fg); background:var(--pill); }
|
||||
.link:disabled { color:var(--faint); background:none; }
|
||||
.runs { background:var(--card); border:1px solid var(--line); border-radius:10px; overflow:hidden; margin-top:6px; }
|
||||
.run { display:grid; grid-template-columns:84px 40px minmax(0,1fr); gap:10px; padding:6px 11px; font-size:12px; align-items:baseline; }
|
||||
.run + .run { border-top:1px solid var(--line-2); }
|
||||
.run .t { color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.run .r { color:var(--muted); }
|
||||
.run .r.bad { color:var(--red); }
|
||||
.run .r.unk { color:var(--amber); }
|
||||
.run .why { color:var(--fg-2); overflow-wrap:anywhere; }
|
||||
.more { display:block; width:100%; padding:6px; font-size:11px; color:var(--muted); border-top:1px solid var(--line-2); }
|
||||
.more:hover { color:var(--fg); }
|
||||
.empty { padding:36px 20px; text-align:center; color:var(--muted); }
|
||||
.empty b { display:block; color:var(--fg); font-weight:500; margin-bottom:4px; }
|
||||
@media (prefers-reduced-motion:reduce) { * { transition:none !important; } }
|
||||
@media (max-width:640px) {
|
||||
.editor { grid-template-columns:1fr; }
|
||||
.editor > label { text-align:left; padding-top:0; }
|
||||
.qm .tip { width:min(320px, 86vw); }
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"name": "@magpie-community/page-window-warmup",
|
||||
"version": "0.1.0",
|
||||
"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",
|
||||
"license": "MIT",
|
||||
"main": "dist/plugin.js",
|
||||
"files": [
|
||||
"dist",
|
||||
"page",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"engines": {
|
||||
"magpie": ">=0.1.1340",
|
||||
"bun": ">=1.4.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "bun scripts/build.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test"
|
||||
},
|
||||
"magpie": {
|
||||
"page": {
|
||||
"title": "Window Warmup",
|
||||
"titles": {
|
||||
"zh": "窗口预热",
|
||||
"zh-TW": "窗口預熱",
|
||||
"ja": "ウィンドウ予熱"
|
||||
},
|
||||
"file": "page/index.html",
|
||||
"service": {
|
||||
"port": 3492,
|
||||
"option": "port"
|
||||
},
|
||||
"icon": "page/icon.svg"
|
||||
},
|
||||
"options": {
|
||||
"port": 3492
|
||||
},
|
||||
"permissions": [],
|
||||
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjODU4NThkIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj4KICA8cmVjdCB4PSIzIiB5PSIzIiB3aWR0aD0iMTgiIGhlaWdodD0iMTgiIHJ4PSI0Ii8+CiAgPHBhdGggZD0iTTMgOGgxOCIvPgogIDxjaXJjbGUgY3g9IjYuMiIgY3k9IjUuNSIgcj0iLjkiIGZpbGw9IiM4NTg1OGQiIHN0cm9rZT0ibm9uZSIvPgogIDxjaXJjbGUgY3g9IjkiIGN5PSI1LjUiIHI9Ii45IiBmaWxsPSIjODU4NThkIiBzdHJva2U9Im5vbmUiLz4KICA8cGF0aCBkPSJNOC4zIDE4LjJjLTEuMi0xIDEuMi0xLjYgMC0yLjZzMS4yLTEuNiAwLTIuNiIvPgogIDxwYXRoIGQ9Ik0xMiAxOC4zYy0xLjMtMS4yIDEuMy0yIDAtMy4yczEuMy0yIDAtMy4yIi8+CiAgPHBhdGggZD0iTTE1LjcgMTguMmMtMS4yLTEgMS4yLTEuNiAwLTIuNnMxLjItMS42IDAtMi42Ii8+Cjwvc3ZnPgo="
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "5.9.3",
|
||||
"@types/bun": "1.4.4"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/window-warmup"
|
||||
},
|
||||
"homepage": "https://github.com/magpie-community/plugins/tree/main/packages/window-warmup",
|
||||
"bugs": "https://github.com/magpie-community/plugins/issues",
|
||||
"keywords": [
|
||||
"magpie",
|
||||
"magpie-page",
|
||||
"magpie-plugin",
|
||||
"llm",
|
||||
"window-warmup",
|
||||
"cron",
|
||||
"quota",
|
||||
"warmup",
|
||||
"keep-alive",
|
||||
"schedule",
|
||||
"rate-limit"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// 带路页:把它自己(也就是 magpie 页面那个框架)导航到插件的服务。
|
||||
//
|
||||
// 这里必须"直接跳",不能先探测:
|
||||
// 页面的 CSP 是 connect-src 'none',一切脚本级联网动作都被禁止 ——
|
||||
// 「先探一下服务在不在」这条路走不通,只能整页跳转。
|
||||
//
|
||||
// 端口用插件选项里的 port(默认 3492),服务端(src/server.ts 经 src/plugin.ts)读同一个值。
|
||||
//
|
||||
// 跳到哪:magpie 把页面给浏览器时(`magpie web`,可能在另一台电脑上打开),
|
||||
// 127.0.0.1 是看页面那台电脑自己,不是跑服务的机器。这时 bridge 会给出
|
||||
// magpie.service:magpie web 在它自己的地址上替本服务转发的路径(package.json
|
||||
// 的 magpie.page.service 声明了它)。有就跳那里;没有(桌面窗口,或旧版
|
||||
// magpie)就照旧跳 127.0.0.1。
|
||||
//
|
||||
// 顺手把窗口的主题、界面语言和设计令牌一起带上(magpie 的 bridge 已经把它们算好了),
|
||||
// 这样窗口预热页的配色跟窗口完全一致,连用户的自定义主题也算在内;语言跟随 magpie 本身,
|
||||
// 页面不再有自己的语言设置。
|
||||
(async () => {
|
||||
const DEFAULT_PORT = 3492;
|
||||
let port = DEFAULT_PORT;
|
||||
let theme = "";
|
||||
let tokens = null;
|
||||
let service = "";
|
||||
let lang = "";
|
||||
|
||||
try {
|
||||
const t = await window.magpie?.ready; // { dark, lang, tokens }
|
||||
if (t) {
|
||||
if (typeof t.dark === "boolean") theme = t.dark ? "dark" : "light";
|
||||
if (t.tokens && typeof t.tokens === "object") tokens = t.tokens;
|
||||
if (typeof t.lang === "string" && t.lang) lang = t.lang;
|
||||
}
|
||||
} catch { /* 没有 bridge 就退回默认主题 */ }
|
||||
try {
|
||||
// 带路页自己的提示语也跟着 magpie 的语言走(认不出就保持中文默认)
|
||||
const said = document.getElementById("said");
|
||||
if (said) {
|
||||
const l = lang.toLowerCase();
|
||||
if (l.startsWith("en")) said.textContent = "Connecting to the local Window Warmup service…";
|
||||
else if (l === "zh-tw" || l === "zh-hk" || l === "zh-hant") said.textContent = "正在連線到本機視窗預熱服務…";
|
||||
else if (l.startsWith("ja")) said.textContent = "ローカルのウィンドウ予熱サービスに接続しています…";
|
||||
}
|
||||
} catch { /* 保持中文默认 */ }
|
||||
try {
|
||||
const s = window.magpie?.service;
|
||||
if (typeof s === "string" && /^https?:\/\//.test(s)) service = s;
|
||||
} catch { /* 旧版 magpie 没有 service */ }
|
||||
try {
|
||||
const o = await window.magpie?.options?.get?.();
|
||||
if (o && Number.isFinite(Number(o.port)) && Number(o.port) > 0) port = Number(o.port);
|
||||
} catch { /* 没有 options 就用默认端口 */ }
|
||||
|
||||
const q = new URLSearchParams();
|
||||
if (theme) q.set("theme", theme);
|
||||
if (lang) q.set("lang", lang);
|
||||
{
|
||||
// 只留非空的令牌,压成一个短串;令牌本身就是 magpie 自己的 CSS 变量值。
|
||||
const slim = {};
|
||||
for (const [k, v] of Object.entries(tokens || {})) {
|
||||
const s = String(v ?? "").trim();
|
||||
if (s) slim[k] = s;
|
||||
}
|
||||
if (Object.keys(slim).length) {
|
||||
try { q.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim))))); } catch { /* 编码不了就只带主题 */ }
|
||||
}
|
||||
}
|
||||
|
||||
// magpie 给了 service 就走它:这是 magpie web 在自己地址上的转发,远程也能用。
|
||||
if (service) {
|
||||
location.replace(service + "?" + q.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const target = "http://127.0.0.1:" + port + "/?" + q.toString();
|
||||
|
||||
// 服务只听本机的 127.0.0.1,跳过去的是「打开这个页面的浏览器」所在的机器。
|
||||
// magpie web 部署在服务器上、从别的电脑打开时,那台电脑的 127.0.0.1 上没有服务,
|
||||
// 直接跳只会得到「127.0.0.1 拒绝连接」。旧版 magpie 不给 service 时,先说明原因,
|
||||
// 给出 SSH 端口转发的做法,转好了再点「继续」。
|
||||
if (!isLoopback(location.hostname)) {
|
||||
showRemote(port, target);
|
||||
return;
|
||||
}
|
||||
location.replace(target);
|
||||
})();
|
||||
|
||||
function isLoopback(host) {
|
||||
const h = String(host || "").toLowerCase().replace(/^\[|\]$/g, "");
|
||||
return h === "" || h === "localhost" || h.endsWith(".localhost") || h === "::1" || /^127\./.test(h);
|
||||
}
|
||||
|
||||
function showRemote(port, target) {
|
||||
const said = document.getElementById("said");
|
||||
if (!said) return;
|
||||
const host = location.hostname.replace(/^\[|\]$/g, "");
|
||||
said.textContent = "";
|
||||
const p = (text) => {
|
||||
const el = document.createElement("p");
|
||||
el.textContent = text;
|
||||
said.appendChild(el);
|
||||
return el;
|
||||
};
|
||||
p("窗口预热页的服务只在运行 magpie 的那台机器上监听 127.0.0.1:" + port + ",从这台电脑的浏览器连不到它。");
|
||||
p("在这台电脑上开一个 SSH 端口转发,然后点「继续」:");
|
||||
const code = p("ssh -N -L " + port + ":127.0.0.1:" + port + " <用户名>@" + host);
|
||||
code.style.fontFamily = "ui-monospace, Menlo, Consolas, monospace";
|
||||
code.style.userSelect = "all";
|
||||
const go = document.createElement("button");
|
||||
go.type = "button";
|
||||
go.textContent = "继续";
|
||||
go.addEventListener("click", () => location.replace(target));
|
||||
said.appendChild(go);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#85858d" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="4"/>
|
||||
<path d="M3 8h18"/>
|
||||
<circle cx="6.2" cy="5.5" r=".9" fill="#85858d" stroke="none"/>
|
||||
<circle cx="9" cy="5.5" r=".9" fill="#85858d" stroke="none"/>
|
||||
<path d="M8.3 18.2c-1.2-1 1.2-1.6 0-2.6s1.2-1.6 0-2.6"/>
|
||||
<path d="M12 18.3c-1.3-1.2 1.3-2 0-3.2s1.3-2 0-3.2"/>
|
||||
<path d="M15.7 18.2c-1.2-1 1.2-1.6 0-2.6s1.2-1.6 0-2.6"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 542 B |
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>窗口预热</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
html, body { margin: 0; height: 100%; }
|
||||
body {
|
||||
display: grid; place-items: center;
|
||||
font: 13px/1.5 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif);
|
||||
background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText);
|
||||
}
|
||||
.box { text-align: center; color: var(--magpie-muted, GrayText); max-width: 520px; padding: 0 16px; }
|
||||
.box p { margin: 6px 0; }
|
||||
.box button { margin-top: 8px; font: inherit; padding: 4px 14px; }
|
||||
.box b { display: block; color: var(--magpie-fg, CanvasText); font-size: 14px; margin-bottom: 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="box"><b>窗口预热</b><div id="said">正在连接到本地窗口预热服务…</div></div>
|
||||
<script src="_magpie/bridge.js"></script>
|
||||
<script src="boot.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
// 构建脚本:Bun.build 两次 + 复制静态页。
|
||||
// - src/plugin.ts → dist/plugin.js(target bun,宿主加载入口)
|
||||
// - web/app.ts → dist/ui/app.js(target browser,界面逻辑)
|
||||
// - web/index.html、web/style.css → dist/ui/(服务从 dist/ui 提供静态资源)
|
||||
import { cp, mkdir, rm } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
/** 从包根构建全部产物;默认写回 dist/,测试用 outDir 构建到临时目录做一致性比对 */
|
||||
export async function buildAll(
|
||||
root: string = resolve(import.meta.dir, ".."),
|
||||
outDir: string = resolve(root, "dist"),
|
||||
): Promise<void> {
|
||||
const dist = resolve(outDir);
|
||||
await rm(dist, { recursive: true, force: true });
|
||||
await mkdir(resolve(dist, "ui"), { recursive: true });
|
||||
// Bun 产物里的源文件注释相对当前工作目录:固定以包根为 cwd,从仓库根或别处调用都得到同一份输出
|
||||
const prev = process.cwd();
|
||||
process.chdir(resolve(root));
|
||||
try {
|
||||
await Bun.build({
|
||||
entrypoints: [resolve(root, "src/plugin.ts")],
|
||||
outdir: dist,
|
||||
target: "bun",
|
||||
});
|
||||
await Bun.build({
|
||||
entrypoints: [resolve(root, "web/app.ts")],
|
||||
outdir: resolve(dist, "ui"),
|
||||
target: "browser",
|
||||
});
|
||||
} finally {
|
||||
process.chdir(prev);
|
||||
}
|
||||
await cp(resolve(root, "web/index.html"), resolve(dist, "ui/index.html"));
|
||||
await cp(resolve(root, "web/style.css"), resolve(dist, "ui/style.css"));
|
||||
}
|
||||
|
||||
if (import.meta.main) await buildAll();
|
||||
@@ -0,0 +1,280 @@
|
||||
// 统一账号规则:/api/catalog(fetchCatalog)与调度器共用同一份实现,禁止两处各写一套。
|
||||
// 数据来源:providers.json 的 key 目录(指纹、key 名、accountModels)、额度卡(窗口)、
|
||||
// 模型缓存(按账号的可见性)。自动选模型也归这里(pickAutoModel),目录与调度器才能算得一致。
|
||||
import type { CachedModel, KeyDirectoryEntry } from "./magpie-files";
|
||||
import type { CatalogAccount, QuotaEntry, QuotaWindow } from "./types";
|
||||
|
||||
/** key 指纹的形态:10 位小写 hex(sha256 前 5 字节),见 magpie internal/provider/keys.go keyID */
|
||||
const FINGERPRINT_RE = /^[0-9a-f]{10}$/;
|
||||
|
||||
/** key 卡 user 里「名字 · 打码」的分隔(remote_key_limits.go:同名多把是「名字 · 打码」) */
|
||||
const MASKED_SEP = " · ";
|
||||
|
||||
export const isFingerprint = (v: string): boolean => FINGERPRINT_RE.test(v);
|
||||
|
||||
// ---------- 自动选模型(自 gateway.ts 迁入,gateway 原样转出保持公开 API) ----------
|
||||
|
||||
/**
|
||||
* 自动选模型的规格词与优先序:越小越省额度(flash 最小),模型都不含的排最后。
|
||||
* 与 pickEffort 一样每次发送前现算,不落进任务。
|
||||
*/
|
||||
const AUTO_SPEC_WORDS = ["flash", "lite", "mini", "nano", "small", "turbo"] as const;
|
||||
const AUTO_SPEC_RES = AUTO_SPEC_WORDS.map((w) => new RegExp(`\\b${w}\\b`, "i"));
|
||||
|
||||
/** id 最后一段命中了哪个规格档;单词匹配,"minimax" 不算 mini;都没命中返回词表长度 */
|
||||
function specTier(id: string): number {
|
||||
const seg = id.slice(id.lastIndexOf("/") + 1);
|
||||
let best: number = AUTO_SPEC_WORDS.length;
|
||||
for (let i = 0; i < AUTO_SPEC_RES.length; i++) {
|
||||
if (i < best && AUTO_SPEC_RES[i].test(seg)) best = i;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* id 的数字感知比较(降序,新版本在前):数字段按数值(10 > 9)、文本段按字典序,
|
||||
* 一方是另一方的前缀时更长(更具体/更新)的在前。
|
||||
*/
|
||||
function cmpNewerDesc(a: string, b: string): number {
|
||||
const ta = a.toLowerCase().match(/\d+|\D+/g) ?? [];
|
||||
const tb = b.toLowerCase().match(/\d+|\D+/g) ?? [];
|
||||
for (let i = 0; i < Math.max(ta.length, tb.length); i++) {
|
||||
const x = ta[i];
|
||||
const y = tb[i];
|
||||
if (x === undefined) return 1;
|
||||
if (y === undefined) return -1;
|
||||
const nx = /^\d+$/.test(x);
|
||||
const ny = /^\d+$/.test(y);
|
||||
if (nx && ny) {
|
||||
// 数字相等(如 "5" 与 "5.2" 的前段)不算分出胜负,继续比后面的 token
|
||||
const d = Number(y) - Number(x);
|
||||
if (d !== 0) return d;
|
||||
} else if (nx !== ny) {
|
||||
return nx ? -1 : 1;
|
||||
} else if (x !== y) {
|
||||
return y < x ? 1 : -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动选模型:在(调用方已按供应商筛好的)候选里,按 id 最后一段的规格词
|
||||
* flash < lite < mini < nano < small < turbo 排序取第一个,都没有的排最后;
|
||||
* 同档按 id 数字感知降序(新版本优先)。选不到(空列表)返回 null。
|
||||
*/
|
||||
export function pickAutoModel<T extends { id: string }>(models: T[]): T | null {
|
||||
if (models.length === 0) return null;
|
||||
const decorated = models.map((m, i) => ({ m, tier: specTier(m.id), i }));
|
||||
decorated.sort((a, b) => a.tier - b.tier || cmpNewerDesc(a.m.id, b.m.id) || a.i - b.i);
|
||||
return decorated[0].m;
|
||||
}
|
||||
|
||||
// ---------- 内部工具 ----------
|
||||
|
||||
const byId = (a: { id: string }, b: { id: string }): number => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
||||
|
||||
/** 「不限额」占位(unlimited: true)不是窗口,进入账号前剔除 */
|
||||
function keepWindows(windows: QuotaWindow[]): QuotaWindow[] {
|
||||
return windows.filter(
|
||||
(w) => (w as { unlimited?: unknown }).unlimited !== true,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号窗口归属:优先精确匹配订阅卡(user 原样),否则按 key 名匹配 key 卡
|
||||
* (user 与 key 名不分大小写相等,或以「名字 · 」开头——同名多把卡是打码形态)。
|
||||
* key 名来自指纹反查 keyDir;没起名的 key(卡名是打码的样子,插件算不出来)接受无窗口。
|
||||
* 返回 null = 账号不存在(既无订阅卡、指纹也解析不出 key 名)。
|
||||
*/
|
||||
export function windowsForAccount(
|
||||
provider: string,
|
||||
account: string,
|
||||
quotas: QuotaEntry[],
|
||||
keyDir: Map<string, KeyDirectoryEntry> | null,
|
||||
): QuotaWindow[] | null {
|
||||
const login = quotas.find(
|
||||
(q) => q.provider === provider && !q.viaKey && q.account === account,
|
||||
);
|
||||
if (login) return keepWindows(login.windows);
|
||||
// key:先解析 key 名(旧任务里存的名字原样用;指纹经 keyDir 反查),再按卡名匹配
|
||||
const name = isFingerprint(account)
|
||||
? keyDir?.get(provider)?.keys.find((k) => k.fingerprint === account)?.name ?? null
|
||||
: account;
|
||||
if (name === null) return null;
|
||||
if (name === "") return []; // 没起名的 key:接受无窗口
|
||||
const low = name.toLowerCase();
|
||||
const card = quotas.find(
|
||||
(q) =>
|
||||
q.provider === provider &&
|
||||
q.viaKey &&
|
||||
(q.account.toLowerCase() === low || q.account.startsWith(`${name}${MASKED_SEP}`)),
|
||||
);
|
||||
return card ? keepWindows(card.windows) : [];
|
||||
}
|
||||
|
||||
// ---------- 可选模型(三层规则) ----------
|
||||
|
||||
export interface ModelsInput {
|
||||
/** /v1/models 中归属该供应商的完整模型 id */
|
||||
models: string[];
|
||||
keyDir: Map<string, KeyDirectoryEntry> | null;
|
||||
/** 该供应商的模型缓存;null = 缓存文件不存在或读不出 */
|
||||
cache: CachedModel[] | null;
|
||||
}
|
||||
|
||||
/** 候选统一成 {full, bare}:bare 是不带供应商前缀的形态(accountModels 里的模型 id 形态) */
|
||||
interface Candidate {
|
||||
full: string;
|
||||
bare: string;
|
||||
/** 只有缓存候选才有(key 指纹列表);退化候选没有按账号的可见性 */
|
||||
keys: string[] | null;
|
||||
}
|
||||
|
||||
function candidatesOf(provider: string, models: string[], cache: CachedModel[] | null): Candidate[] {
|
||||
if (cache) {
|
||||
return cache.map((c) => ({ full: `${provider}/${c.id}`, bare: c.id, keys: c.keys }));
|
||||
}
|
||||
// 退化:没有模型缓存(插件型订阅供应商不写这个文件)——直接用 /v1/models 的 id
|
||||
const prefix = `${provider}/`;
|
||||
return models.map((m) => ({
|
||||
full: m,
|
||||
bare: m.startsWith(prefix) ? m.slice(prefix.length) : m,
|
||||
keys: null,
|
||||
}));
|
||||
}
|
||||
|
||||
export interface AccountModels {
|
||||
/** null = 该供应商既无缓存、/v1/models 里也没有它的模型(提示 B;自动模型失败) */
|
||||
list: string[] | null;
|
||||
/** false = 没有模型缓存,列出的是全部模型(未按账号区分) */
|
||||
perAccount: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号的可选模型(三层规则的共用实现,accountsOf 与调度器都走这里):
|
||||
* 第 1 层按 Keys 过滤(仅缓存模式、仅 key 账号);第 2 层 accountModels[账号键];
|
||||
* 第 3 层只留 /v1/models 里存在的。缓存缺失且有 /v1/models 模型时退化为全部模型。
|
||||
*/
|
||||
export function modelsForAccount(
|
||||
provider: string,
|
||||
account: string,
|
||||
input: ModelsInput,
|
||||
): AccountModels {
|
||||
const hasCache = input.cache !== null;
|
||||
if (!hasCache && input.models.length === 0) return { list: null, perAccount: false };
|
||||
let cands = candidatesOf(provider, input.models, input.cache);
|
||||
if (hasCache && isFingerprint(account)) {
|
||||
// 第 1 层:Keys 为空 = 所有 key 可见,否则只留包含这把指纹的
|
||||
cands = cands.filter((c) => !c.keys || c.keys.length === 0 || c.keys.includes(account));
|
||||
}
|
||||
const filterKey = isFingerprint(account) ? account : account.toLowerCase();
|
||||
const allowed = input.keyDir?.get(provider)?.accountModels[filterKey];
|
||||
if (allowed && allowed.length > 0) {
|
||||
// 第 2 层:配置了账号的模型清单就只留列出的
|
||||
const set = new Set(allowed);
|
||||
cands = cands.filter((c) => set.has(c.bare));
|
||||
}
|
||||
const present = new Set(input.models);
|
||||
const list = cands
|
||||
.map((c) => c.full)
|
||||
.filter((id) => present.has(id))
|
||||
.sort();
|
||||
return { list, perAccount: hasCache };
|
||||
}
|
||||
|
||||
// ---------- 账号列表与发送头 ----------
|
||||
|
||||
export interface AccountsInput extends ModelsInput {
|
||||
/** 归一后的额度条目(key 卡 viaKey=true、provider 已归一为 <p>) */
|
||||
quotas: QuotaEntry[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商 P 的账号列表与「自动选账号」的可选模型:
|
||||
* - key 账号来自 providers.json 的启用 key(指纹去重),id = 指纹,label = key 名(无名用指纹);
|
||||
* - 订阅账号来自额度卡(provider === P 且非 key 卡)的 user,去重,id = label = user;
|
||||
* - 所有窗口剔除 unlimited 占位;模型列表与自动模型按三层规则现算。
|
||||
*/
|
||||
export function accountsOf(
|
||||
provider: string,
|
||||
input: AccountsInput,
|
||||
): { accounts: CatalogAccount[]; autoAccountModels: string[] | null } {
|
||||
const entry = input.keyDir?.get(provider) ?? null;
|
||||
const accounts: CatalogAccount[] = [];
|
||||
const seenFingerprints = new Set<string>();
|
||||
for (const k of entry?.keys ?? []) {
|
||||
if (seenFingerprints.has(k.fingerprint)) continue;
|
||||
seenFingerprints.add(k.fingerprint);
|
||||
accounts.push({
|
||||
id: k.fingerprint,
|
||||
label: k.name || k.fingerprint,
|
||||
kind: "key",
|
||||
windows: windowsForAccount(provider, k.fingerprint, input.quotas, input.keyDir) ?? [],
|
||||
...pickModels(provider, k.fingerprint, input),
|
||||
});
|
||||
}
|
||||
const seenUsers = new Set<string>();
|
||||
for (const q of input.quotas) {
|
||||
if (q.provider !== provider || q.viaKey) continue;
|
||||
if (seenUsers.has(q.account)) continue;
|
||||
seenUsers.add(q.account);
|
||||
accounts.push({
|
||||
id: q.account,
|
||||
label: q.account,
|
||||
kind: "login",
|
||||
windows: windowsForAccount(provider, q.account, input.quotas, input.keyDir) ?? [],
|
||||
...pickModels(provider, q.account, input),
|
||||
});
|
||||
}
|
||||
accounts.sort(byId);
|
||||
return { accounts, autoAccountModels: autoAccountModelsOf(provider, input) };
|
||||
}
|
||||
|
||||
function pickModels(
|
||||
provider: string,
|
||||
account: string,
|
||||
input: AccountsInput,
|
||||
): { models: string[] | null; perAccount: boolean; autoModel: string | null } {
|
||||
const pick = modelsForAccount(provider, account, input);
|
||||
return {
|
||||
models: pick.list,
|
||||
perAccount: pick.perAccount,
|
||||
autoModel: pick.list ? (pickAutoModel(pick.list.map((id) => ({ id })))?.id ?? null) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** 「自动选账号」的可选模型:不做第 1、2 层(不按账号区分),只做第 3 层归属校验 */
|
||||
function autoAccountModelsOf(provider: string, input: AccountsInput): string[] | null {
|
||||
if (input.cache === null && input.models.length === 0) return null;
|
||||
const present = new Set(input.models);
|
||||
return candidatesOf(provider, input.models, input.cache)
|
||||
.map((c) => c.full)
|
||||
.filter((id) => present.has(id))
|
||||
.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送时的账号头值(X-Magpie-Account):
|
||||
* - "" → null(不带头,网关自动选);
|
||||
* - 先查账号归属:额度卡里有这个 user 的订阅账号 → 原样发名字(哪怕恰好形似指纹);
|
||||
* 是 P 的 key 指纹 → 启用 key ≥2 把(读不出目录时按 ≥2)发 `<P>#指纹`,只有 1 把不带头
|
||||
* (此时候选 ID 就是供应商 id);
|
||||
* - 查不到且形如 10 位小写 hex → 按指纹规则;其余(订阅名、旧任务存的 key 名)→ 原样。
|
||||
*/
|
||||
export function pinFor(
|
||||
provider: string,
|
||||
account: string,
|
||||
keyDir: Map<string, KeyDirectoryEntry> | null,
|
||||
quotas: QuotaEntry[] = [],
|
||||
): string | null {
|
||||
if (!account) return null;
|
||||
const isLogin = quotas.some((q) => q.provider === provider && !q.viaKey && q.account === account);
|
||||
if (isLogin) return account;
|
||||
if (isFingerprint(account)) {
|
||||
// 指纹形态(目录读不出时也按 ≥2 处理):启用 key ≥2 把才有 <P>#指纹 这个候选 ID
|
||||
const enabled = keyDir?.get(provider)?.keys.length ?? 2;
|
||||
return enabled >= 2 ? `${provider}#${account}` : null;
|
||||
}
|
||||
return account;
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
// 和 Magpie 网关说话的客户端:列模型、读额度、发预热消息。
|
||||
// 一切请求只打本地网关(base 由 gatewayBase 从 MAGPIE_ADDR 推出),超时都偏短:
|
||||
// 网关不可达时调度层要把失败写进执行记录,而不是被挂住的请求拖死。
|
||||
|
||||
import { accountsOf, pickAutoModel } from "./accounts";
|
||||
import { readDefaultKeyDirectory, readDefaultModelCache } from "./magpie-files";
|
||||
import { WARMUP_MESSAGE } from "./rules";
|
||||
import {
|
||||
errText,
|
||||
type Catalog,
|
||||
type CatalogProvider,
|
||||
type EffortPick,
|
||||
type QuotaEntry,
|
||||
type QuotaWindow,
|
||||
type RawModel,
|
||||
type SendResult,
|
||||
type Task,
|
||||
} from "./types";
|
||||
|
||||
// 自动选模型的规则在 accounts.ts、探活消息在 rules.ts;这里转出保持既有公开 API 不变
|
||||
export { pickAutoModel, WARMUP_MESSAGE };
|
||||
|
||||
/** MAGPIE_ADDR 缺省时的老端口 */
|
||||
const DEFAULT_GATEWAY = "http://127.0.0.1:3425";
|
||||
/** 单次发送的 token 上限:预热消息只是探活,不追求完整回答 */
|
||||
const SEND_MAX_TOKENS = 16;
|
||||
/** 发送超时;超了只能记 unknown(请求可能已送达上游) */
|
||||
const SEND_TIMEOUT_MS = 30_000;
|
||||
/** 目录/额度的读取超时:页面加载与调度刷新都不该被挂死的网关拖住 */
|
||||
const READ_TIMEOUT_MS = 10_000;
|
||||
/**
|
||||
* 完整额度读取(不带 kept)的超时。这一路会问上游要最新余额,magpie 侧自身限 12 秒
|
||||
* (internal/gateway/gateway.go quotas 的 ctx timeout),放宽到 15 秒兜住网络往返。
|
||||
*/
|
||||
const FULL_QUOTAS_TIMEOUT_MS = 15_000;
|
||||
/** 单卡刷新的超时:magpie 侧给这次上游读取 30 秒(gateway.go quotaCardsRefresh),再放宽兜住往返 */
|
||||
const CARD_REFRESH_TIMEOUT_MS = 35_000;
|
||||
/** 两次完整额度读取的最小间隔:kept 缓存空窗期(magpie 刚启动)内的兜底读取不许每次都打 */
|
||||
const MIN_FULL_GAP_MS = 5 * 60_000;
|
||||
/** 上游错误原因截断长度,避免个别上游把整页 HTML 塞进 error.message */
|
||||
const REASON_MAX = 200;
|
||||
|
||||
/** 超时属于「结果未知」:请求可能已被网关受理,不能当失败自动重发。文案带实际时长,测试注入短超时时不会谎报 30 秒 */
|
||||
function timeoutReason(timeoutMs: number): string {
|
||||
const duration = timeoutMs % 1000 === 0 ? `${timeoutMs / 1000} 秒` : `${timeoutMs} 毫秒`;
|
||||
return `${duration}内没有结果,可能已发送`;
|
||||
}
|
||||
|
||||
export function gatewayBase(env: Record<string, string | undefined> = process.env): string {
|
||||
const addr = env.MAGPIE_ADDR?.trim().replace(/\/+$/, "");
|
||||
if (!addr) return DEFAULT_GATEWAY;
|
||||
// 容忍直接给完整地址(含 https:// 的远程网关)
|
||||
if (/^https?:\/\//.test(addr)) return addr;
|
||||
return `http://${addr}`;
|
||||
}
|
||||
|
||||
/** 已知名档的优先序;纯数字档(思考预算)低于所有命名档,未知名排在已知名之后 */
|
||||
const KNOWN_EFFORT_RANK: Record<string, number> = {
|
||||
minimal: 0,
|
||||
low: 1,
|
||||
medium: 2,
|
||||
high: 3,
|
||||
xhigh: 4,
|
||||
max: 5,
|
||||
};
|
||||
|
||||
/** "disabled"/"off" 是「支持关闭」的写法,归一成 none 才能参与档位比较;发送值保留模型原样 */
|
||||
function normalizeLevel(s: string): string {
|
||||
const t = s.trim();
|
||||
const low = t.toLowerCase();
|
||||
if (low === "disabled" || low === "off") return "none";
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取模型的档位列表:reasoning_levels 优先,否则 supported_reasoning_levels[].effort
|
||||
* (字段形状随模型而变,这里运行时校验)。字段存在却提不出任何档位视为数据损坏。
|
||||
*/
|
||||
function levelList(model: RawModel): string[] | { error: string } {
|
||||
const raw = model.reasoning_levels;
|
||||
if (raw !== undefined && raw !== null) {
|
||||
// 宁可报错也不能把坏数据误判成「模型不思考」——那会漏发 reasoning_effort
|
||||
if (!Array.isArray(raw)) return { error: "模型的思考档位数据无法识别" };
|
||||
const list = raw.filter((s): s is string => typeof s === "string");
|
||||
if (raw.length > 0 && list.length === 0) return { error: "模型的思考档位数据无法识别" };
|
||||
return list;
|
||||
}
|
||||
const supported = model.supported_reasoning_levels;
|
||||
if (supported !== undefined && supported !== null) {
|
||||
if (!Array.isArray(supported)) return { error: "模型的思考档位数据无法识别" };
|
||||
const list = supported
|
||||
.map((x) => (typeof x === "object" && x !== null ? (x as { effort?: unknown }).effort : null))
|
||||
.filter((s): s is string => typeof s === "string");
|
||||
if (supported.length > 0 && list.length === 0) return { error: "模型的思考档位数据无法识别" };
|
||||
return list;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 每次发送前从当次模型列表现算思考档位(任务不存档位,模型配置变了自动跟随):
|
||||
* - reasoning 为假或列表为空 → 模型不思考,不带 reasoning_effort
|
||||
* - 含 none → 能关就关
|
||||
* - 否则取该模型自己的最低一档(必须思考就开最低)
|
||||
*/
|
||||
export function pickEffort(model: RawModel): EffortPick {
|
||||
const levels = levelList(model);
|
||||
if ("error" in levels) return levels;
|
||||
if (!model.reasoning || levels.length === 0) {
|
||||
return { send: null, label: "不适用" };
|
||||
}
|
||||
const normalized = levels.map(normalizeLevel).filter((s) => s !== "");
|
||||
if (normalized.length === 0) return { send: null, label: "不适用" };
|
||||
if (normalized.some((s) => s.toLowerCase() === "none")) {
|
||||
return { send: "none", label: "关闭(模型支持关闭)" };
|
||||
}
|
||||
// 稳定排序键:组别 → 组内次序 → 列表原序(未知名保持模型给出的顺序)
|
||||
const decorated = normalized.map((s, i) => {
|
||||
if (/^\d+$/.test(s)) return { s, group: 0, rank: Number(s), i };
|
||||
const known = KNOWN_EFFORT_RANK[s.toLowerCase()];
|
||||
return { s, group: known === undefined ? 2 : 1, rank: known ?? i, i };
|
||||
});
|
||||
decorated.sort((a, b) => a.group - b.group || a.rank - b.rank || a.i - b.i);
|
||||
const lowest = decorated[0].s;
|
||||
const allUnknown = decorated.every((d) => d.group === 2);
|
||||
return {
|
||||
send: lowest,
|
||||
label: allUnknown ? `${lowest}(按模型列表第一档)` : `${lowest}(模型必须思考,已用最低档)`,
|
||||
};
|
||||
}
|
||||
|
||||
/** 提取上游错误说明;不是 JSON 就原样截断 */
|
||||
function errorReason(text: string): string {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as { error?: { message?: unknown } };
|
||||
const msg = parsed?.error?.message;
|
||||
if (typeof msg === "string" && msg.trim()) return msg.trim().slice(0, REASON_MAX);
|
||||
} catch {
|
||||
/* 非 JSON 响应体 */
|
||||
}
|
||||
return text.trim().slice(0, REASON_MAX) || "上游未返回错误说明";
|
||||
}
|
||||
|
||||
async function requestJSON(
|
||||
base: string,
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
timeoutMs: number = READ_TIMEOUT_MS,
|
||||
method: "GET" | "POST" = "GET",
|
||||
): Promise<unknown> {
|
||||
// 外部 signal(发送被停用/删除)与读超时一并生效,取元数据阶段也能被立即中止。
|
||||
// 连接失败不包装:底层原始错误如实抛给上层显示
|
||||
const timeout = AbortSignal.timeout(timeoutMs);
|
||||
const res = await fetch(base + path, {
|
||||
method,
|
||||
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
||||
});
|
||||
const text = await res.text().catch(() => "");
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}:${errorReason(text)}`);
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
throw new Error(`Magpie 返回的不是 JSON(${path})`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 兼容裸数组与 {data:[...]} 两种包法 */
|
||||
function dataArray(data: unknown): unknown[] {
|
||||
if (Array.isArray(data)) return data;
|
||||
if (typeof data === "object" && data !== null && Array.isArray((data as { data?: unknown }).data)) {
|
||||
return (data as { data: unknown[] }).data;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function coerceWindows(list: unknown): QuotaWindow[] {
|
||||
const out: QuotaWindow[] = [];
|
||||
for (const w of Array.isArray(list) ? list : []) {
|
||||
const raw = typeof w === "object" && w !== null ? (w as Record<string, unknown>) : {};
|
||||
// unlimited: true 是「不限额」占位,不是窗口(magpie 额度卡用来补齐总余额),剔除
|
||||
if (raw.unlimited === true) continue;
|
||||
out.push({
|
||||
name: typeof raw.name === "string" ? raw.name : "",
|
||||
used: typeof raw.used === "number" ? raw.used : null,
|
||||
resetsAt: typeof raw.resetsAt === "string" ? raw.resetsAt : null,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 远程 magpie 给每把网关 key 单独发一张限额卡,provider 记作 "<p>/~keys"、user 是 key 名
|
||||
* 或打码形态(magpie internal/provider/remote_key_limits.go 的 remoteKeyCard)。条目保留
|
||||
* 这层来历:viaKey 标记 + provider 归一成 <p>——key 卡只能挂到 providers.json 里对应的那把
|
||||
* key 上(账号统一规则在 accounts.ts),不能再像 0.1 那样直接变成供应商账号。
|
||||
*/
|
||||
function parseQuotas(data: unknown): QuotaEntry[] {
|
||||
const entries: QuotaEntry[] = [];
|
||||
for (const item of dataArray(data)) {
|
||||
if (typeof item !== "object" || item === null) continue;
|
||||
const q = item as Record<string, unknown>;
|
||||
const rawProvider = typeof q.provider === "string" ? q.provider : "";
|
||||
const viaKey = rawProvider.endsWith("/~keys");
|
||||
const provider = viaKey ? rawProvider.slice(0, -"/~keys".length) : rawProvider;
|
||||
const user = typeof q.user === "string" ? q.user : "";
|
||||
if (!provider || !user) continue;
|
||||
const readAt = typeof q.readAt === "string" && q.readAt ? q.readAt : null;
|
||||
entries.push({
|
||||
provider,
|
||||
account: user,
|
||||
label: typeof q.name === "string" && q.name ? q.name : user,
|
||||
windows: coerceWindows(q.windows),
|
||||
viaKey,
|
||||
...(readAt ? { readAt } : {}),
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
export type QuotasFn = (base: string) => Promise<{ at: Date; entries: QuotaEntry[] }>;
|
||||
|
||||
/**
|
||||
* 额度读取:平时 ?kept=1 只读缓存(绝不触发上游探测)。magpie 刚启动时缓存为空,
|
||||
* 这时兜底读一次不带 kept 的完整接口(只读余额,不发模型请求,15 秒超时)。
|
||||
* 完整读取按「尝试时刻」节流:任何一次尝试(成功或失败)之后 5 分钟内不再发起新的尝试,
|
||||
* 期间直接用上次成功结果,没有就当空——否则 magpie 不可达时,页面 60 秒的目录轮询
|
||||
* 与调度器刷新会反复重打上游,还要各自等满 15 秒超时。失败同样吃节流,但发起那次
|
||||
* 的错误如实抛给调用方(页面目录兜成空账号,调度器保留旧快照)。
|
||||
* 并发的兜底读取合并成同一次尝试,保证「至少间隔 5 分钟」在并发下同样成立。
|
||||
* 目录(fetchCatalog)与调度器的窗口评估都走这里,共用同一份缓存。
|
||||
*/
|
||||
export function createQuotaReader(opts: { now?: () => Date } = {}): QuotasFn {
|
||||
const nowFn = opts.now ?? (() => new Date());
|
||||
/** base → 上次成功读到的额度:节流窗口内的兜底结果 */
|
||||
const lastGood = new Map<string, { at: Date; entries: QuotaEntry[] }>();
|
||||
/** base → 上次完整读取的尝试时刻(成功失败都记):节流按尝试计,不看成败 */
|
||||
const lastAttempt = new Map<string, number>();
|
||||
const inflight = new Map<string, Promise<{ at: Date; entries: QuotaEntry[] }>>();
|
||||
return async (base) => {
|
||||
const kept = parseQuotas(await requestJSON(base, "/v1/magpie/quotas?kept=1"));
|
||||
if (kept.length > 0) return { at: nowFn(), entries: kept };
|
||||
// 正在进行的那次尝试不算新请求:先并入它,节流判断只管要不要「另起一次」
|
||||
let pending = inflight.get(base);
|
||||
if (!pending) {
|
||||
const now = nowFn().getTime();
|
||||
const attempted = lastAttempt.get(base);
|
||||
if (attempted !== undefined && now - attempted < MIN_FULL_GAP_MS) {
|
||||
return lastGood.get(base) ?? { at: nowFn(), entries: [] };
|
||||
}
|
||||
// 尝试时刻先记账再发请求:失败也吃节流,不许立刻重试
|
||||
lastAttempt.set(base, now);
|
||||
pending = requestJSON(base, "/v1/magpie/quotas", undefined, FULL_QUOTAS_TIMEOUT_MS)
|
||||
.then((data) => {
|
||||
const fresh = { at: nowFn(), entries: parseQuotas(data) };
|
||||
lastGood.set(base, fresh);
|
||||
return fresh;
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(base);
|
||||
});
|
||||
inflight.set(base, pending);
|
||||
}
|
||||
return pending;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 让 magpie 去上游重读一张订阅卡(用量页单卡「刷新」按钮的同一路径),重读结果进 kept 缓存,
|
||||
* 下一次 ?kept=1 即可读到。magpie 按卡限频 30 秒,限频内不报错只是不重读——调用方靠
|
||||
* 卡片的 readAt 判断是否真拿到了新读数。响应体是另一种卡片形态,这里不解析。
|
||||
*/
|
||||
export async function refreshQuotaCard(base: string, provider: string, user: string): Promise<void> {
|
||||
const q = new URLSearchParams({ provider, user });
|
||||
await requestJSON(base, `/v1/magpie/quotas/refresh?${q}`, undefined, CARD_REFRESH_TIMEOUT_MS, "POST");
|
||||
}
|
||||
|
||||
/** 默认读取器:进程内唯一,目录与调度器(未注入 quotasFn 时)共用同一份完整读取缓存 */
|
||||
export const fetchQuotas: QuotasFn = createQuotaReader();
|
||||
|
||||
/**
|
||||
* 拉取原始模型列表(不做目录归并):调度器每次发送前用它现算该模型的思考档位,
|
||||
* 模型配置变了下一次发送自动跟着变。路由组 group/ 一律不接受。
|
||||
* signal:调度器在停用/删除任务时传入,中止进行中的取元数据请求。
|
||||
*/
|
||||
export async function fetchModels(base: string, signal?: AbortSignal): Promise<RawModel[]> {
|
||||
const data = await requestJSON(base, "/v1/models", signal);
|
||||
const out: RawModel[] = [];
|
||||
for (const item of dataArray(data)) {
|
||||
if (typeof item !== "object" || item === null) continue;
|
||||
const m = item as RawModel;
|
||||
if (typeof m.id !== "string" || !m.id || m.id.startsWith("group/")) continue;
|
||||
out.push(m);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 模型归属的供应商 id:owned_by 优先(真正接住请求的一方),否则取 id 首段 */
|
||||
export function modelProvider(m: RawModel): string {
|
||||
const owner = typeof m.owned_by === "string" ? m.owned_by.trim() : "";
|
||||
return owner || (m.id.includes("/") ? m.id.slice(0, m.id.indexOf("/")) : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 模型目录:模型按 owned_by(真正接住请求的一方)或 id 前缀归供应商,路由组 group/ 一律不列出。
|
||||
* 账号、窗口与每账号可选模型走统一账号规则(accounts.ts):key 账号来自 providers.json 的
|
||||
* 指纹,订阅账号来自额度卡,key 卡只用来给 key 账号挂窗口。providers.json 读不出 → key
|
||||
* 账号为空,目录照常返回;额度接口挂了不连累模型目录(照搬 fingerprint 的取舍)。
|
||||
* autoModel 用与调度器同一套规则在服务端算好,页面直接显示。
|
||||
*/
|
||||
export async function fetchCatalog(base: string): Promise<Catalog> {
|
||||
const [models, quotas] = await Promise.all([
|
||||
fetchModels(base),
|
||||
fetchQuotas(base).catch(() => ({ at: new Date(), entries: [] as QuotaEntry[] })),
|
||||
]);
|
||||
const providers = new Map<string, CatalogProvider>();
|
||||
const rawModels = new Map<string, RawModel[]>();
|
||||
const ensure = (id: string): CatalogProvider => {
|
||||
let p = providers.get(id);
|
||||
if (!p) {
|
||||
p = { id, accounts: [], models: [], autoAccountModels: null, autoModel: null };
|
||||
providers.set(id, p);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
for (const m of models) {
|
||||
const pid = modelProvider(m);
|
||||
// 归不到供应商的模型建不了任务(provider 必填),列出来只会是死选项
|
||||
if (!pid) continue;
|
||||
ensure(pid);
|
||||
const raws = rawModels.get(pid);
|
||||
if (raws) raws.push(m);
|
||||
else rawModels.set(pid, [m]);
|
||||
}
|
||||
for (const q of quotas.entries) ensure(q.provider);
|
||||
// providers.json 与各供应商的模型缓存现读(调度器发送前读的是同一份);读不出按「没有」处理,不让整个目录 502
|
||||
const keyDir = await readDefaultKeyDirectory();
|
||||
const list = [...providers.values()];
|
||||
for (const p of list) {
|
||||
const raws = rawModels.get(p.id) ?? [];
|
||||
p.models = raws
|
||||
.map((m) => ({ id: m.id, effort: pickEffort(m) }))
|
||||
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||
const built = accountsOf(p.id, {
|
||||
models: raws.map((m) => m.id),
|
||||
quotas: quotas.entries,
|
||||
keyDir,
|
||||
cache: await readDefaultModelCache(p.id),
|
||||
});
|
||||
p.accounts = built.accounts;
|
||||
p.autoAccountModels = built.autoAccountModels;
|
||||
p.autoModel = built.autoAccountModels
|
||||
? (pickAutoModel(built.autoAccountModels.map((id) => ({ id })))?.id ?? null)
|
||||
: null;
|
||||
}
|
||||
list.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||
return { providers: list };
|
||||
}
|
||||
|
||||
/** 2xx 的 chat 响应体必须是 JSON 对象;Bun 在流中断时 text() 可能不抛错而返回占位内容,形状校验兜住 */
|
||||
function usableChatBody(text: string): boolean {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as unknown;
|
||||
return typeof parsed === "object" && parsed !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发一次预热消息。pin 是调度器按统一账号规则算好的账号头值(null = 不带头,网关自动选)。
|
||||
* 只有一次请求,成败都如实上报:
|
||||
* - 2xx 且响应体是 JSON 对象 → ok
|
||||
* - HTTP 错误 → failed(原因 = 状态码 + 上游 error.message)
|
||||
* - 连不上 → failed(原因是底层原始错误)
|
||||
* - 超时 / 外部取消 / 2xx 但响应体读不出来 → unknown(请求可能已送达,不允许上层据此自动重发)
|
||||
*/
|
||||
export async function send(
|
||||
base: string,
|
||||
task: Pick<Task, "id" | "model">,
|
||||
pin: string | null,
|
||||
effort: string | null,
|
||||
signal: AbortSignal,
|
||||
timeoutMs: number = SEND_TIMEOUT_MS,
|
||||
): Promise<SendResult> {
|
||||
const startedAt = Date.now();
|
||||
const elapsed = () => Date.now() - startedAt;
|
||||
const timer = AbortSignal.timeout(timeoutMs);
|
||||
const combined = AbortSignal.any([signal, timer]);
|
||||
const headers: Record<string, string> = {
|
||||
"content-type": "application/json",
|
||||
"x-magpie-session": `window-warmup/${task.id}`,
|
||||
};
|
||||
if (pin) {
|
||||
// 头值只能按 latin-1 写上线路:含非 ASCII(如中文账号名)时改存 UTF-8 字节,
|
||||
// 网关侧按字节收到原文(HTTP 头按字节透传)
|
||||
headers["x-magpie-account"] = /[^\x00-\x7F]/.test(pin)
|
||||
? Buffer.from(pin, "utf8").toString("latin1")
|
||||
: pin;
|
||||
}
|
||||
const body: Record<string, unknown> = {
|
||||
model: task.model,
|
||||
messages: [{ role: "user", content: WARMUP_MESSAGE }],
|
||||
max_tokens: SEND_MAX_TOKENS,
|
||||
stream: false,
|
||||
};
|
||||
if (effort) body.reasoning_effort = effort;
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${base}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
signal: combined,
|
||||
});
|
||||
} catch (e) {
|
||||
// 外部取消优先于超时上报;连接被重置说明请求多半已送达、响应丢了,
|
||||
// 属「结果未知」而不是「连不上」;都未触发才是连接层失败(原始错误如实上报)
|
||||
if (signal.aborted) return { outcome: "unknown", reason: "发送被取消", ms: elapsed() };
|
||||
if (timer.aborted) return { outcome: "unknown", reason: timeoutReason(timeoutMs), ms: elapsed() };
|
||||
const code = (e as NodeJS.ErrnoException).code;
|
||||
if (code === "ECONNRESET" || code === "EPIPE") {
|
||||
return { outcome: "unknown", reason: "连接中断,结果未知(可能已发送)", ms: elapsed() };
|
||||
}
|
||||
return { outcome: "failed", reason: errText(e), ms: elapsed() };
|
||||
}
|
||||
let text = "";
|
||||
let bodyBroken = false;
|
||||
try {
|
||||
text = await res.text();
|
||||
} catch {
|
||||
bodyBroken = true;
|
||||
if (signal.aborted) return { outcome: "unknown", reason: "发送被取消", ms: elapsed() };
|
||||
if (timer.aborted) return { outcome: "unknown", reason: timeoutReason(timeoutMs), ms: elapsed() };
|
||||
}
|
||||
if (res.ok) {
|
||||
// 状态码到了但响应体没读出来/不完整:大概率已发送,但无法确认,不能记 ok
|
||||
return !bodyBroken && usableChatBody(text)
|
||||
? { outcome: "ok", reason: "", ms: elapsed() }
|
||||
: { outcome: "unknown", reason: `HTTP ${res.status},响应体读取失败,结果未知`, ms: elapsed() };
|
||||
}
|
||||
return { outcome: "failed", reason: `HTTP ${res.status}:${errorReason(text)}`, ms: elapsed() };
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// 读 Magpie 自己的配置与缓存文件:providers.json(key 指纹与账号模型)与模型缓存。
|
||||
// 红线:providers.json 里的 key 原文只允许在 readKeyDirectory 内「读文件 → 算指纹」这一步存在,
|
||||
// 算完即丢——绝不进入返回值、错误信息或缓存(JSON.parse 的报错会夹带文件片段,必须换成固定文案)。
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import path, { join, resolve } from "node:path";
|
||||
|
||||
/**
|
||||
* 本插件在 Magpie 配置目录里的安装位置特征(moduleDir 的末尾几段):
|
||||
* 现在的作用域包名装成 node_modules/@magpie-community/page-window-warmup/dist;
|
||||
* 旧独立包名(≤0.3.7)还可能留在 node_modules/magpie-window-warmup/dist。
|
||||
*/
|
||||
const PLUGIN_DIR_TAILS = [
|
||||
["plugins", "node_modules", "@magpie-community", "page-window-warmup", "dist"],
|
||||
["plugins", "node_modules", "magpie-window-warmup", "dist"],
|
||||
];
|
||||
/** providers.json 解析失败的固定文案:原异常信息可能夹带文件内容(含 key 原文),不能透传 */
|
||||
export const BROKEN_PROVIDERS_MESSAGE = "Magpie 的供应商配置文件读不出来";
|
||||
|
||||
/** 读取结果进程内缓存的时长:页面目录轮询与调度器发送都会反复读盘,5 秒内共用一次读取 */
|
||||
const READ_CACHE_MS = 5_000;
|
||||
|
||||
export interface KeyDirectoryEntry {
|
||||
/** 启用的 key(按指纹去重);只有指纹与名字,绝无 key 原文 */
|
||||
keys: { fingerprint: string; name: string }[];
|
||||
/** <小写账号名或 key 指纹> → 模型 id 列表(不带供应商前缀) */
|
||||
accountModels: Record<string, string[]>;
|
||||
}
|
||||
|
||||
/** 模型缓存里的一个模型:id 不带供应商前缀,keys 是能看到它的 key 指纹(空 = 所有 key) */
|
||||
export interface CachedModel {
|
||||
id: string;
|
||||
keys: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Magpie 的配置与缓存目录。插件装在 <配置目录>/plugins/node_modules/<包名>/dist
|
||||
* 时(按 PLUGIN_DIR_TAILS 判定,兼容 Windows 反斜杠),配置目录就是上溯到 plugins 的上一级;
|
||||
* 它与安装版配置目录相同 → 缓存用安装版缓存目录,否则是便携版 data 目录,缓存跟配置走
|
||||
* (<data>/cache)。位置对不上(源码态开发、别的宿主)时用安装版两个目录。
|
||||
* XDG 变量只在是绝对路径时才算数(对齐 magpie internal/appdir/env.go 的 rooted),
|
||||
* home 取 os.homedir()。
|
||||
*/
|
||||
export function magpieDirs(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
moduleDir: string = import.meta.dir,
|
||||
p: typeof path = path,
|
||||
): { config: string; cache: string } {
|
||||
const installConfig = p.resolve(xdgConfigHome(env, p), "magpie");
|
||||
const installCache = p.resolve(rooted(env.XDG_CACHE_HOME, p) ?? p.join(homedir(), ".cache"), "magpie");
|
||||
const segments = moduleDir.split(p.sep === "\\" ? /[\\/]/ : p.sep).filter((s) => s !== "");
|
||||
const tail = PLUGIN_DIR_TAILS.find((t) => {
|
||||
if (segments.length < t.length) return false;
|
||||
const got = segments.slice(-t.length);
|
||||
return t.every((seg, i) => got[i] === seg);
|
||||
});
|
||||
if (!tail) return { config: installConfig, cache: installCache };
|
||||
const config = p.resolve(moduleDir, ...tail.map(() => ".."));
|
||||
return {
|
||||
config,
|
||||
cache: p.resolve(config) === installConfig ? installCache : p.join(config, "cache"),
|
||||
};
|
||||
}
|
||||
|
||||
/** XDG 变量留白或相对路径都视为没设(magpie 的 rooted 语义) */
|
||||
function rooted(v: string | undefined, p: typeof path): string | null {
|
||||
const t = v?.trim();
|
||||
return t && p.isAbsolute(t) ? t : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* XDG 配置根目录(不含 magpie 段):插件数据目录、旧包迁移来源与 Magpie 配置目录
|
||||
* 都从这里推,三者必须用同一语义,否则相对路径的 XDG_CONFIG_HOME 会让它们各指一处。
|
||||
*/
|
||||
export function xdgConfigHome(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
p: typeof path = path,
|
||||
): string {
|
||||
return rooted(env.XDG_CONFIG_HOME, p) ?? p.join(homedir(), ".config");
|
||||
}
|
||||
|
||||
// 目录(/api/catalog)与调度器都经下面两个入口按默认位置读 Magpie 文件。
|
||||
// 位置每次现推(纯字符串运算):环境变量在进程内可能被改(测试即如此),不做缓存。
|
||||
|
||||
/** 按默认位置读 providers.json;读不出(损坏/权限)按 null 处理,调用方当「没有 key 目录」 */
|
||||
export function readDefaultKeyDirectory(): Promise<Map<string, KeyDirectoryEntry> | null> {
|
||||
return readKeyDirectory(magpieDirs().config).catch(() => null);
|
||||
}
|
||||
|
||||
/** 按默认位置读某供应商的模型缓存;没有缓存为 null */
|
||||
export function readDefaultModelCache(providerId: string): Promise<CachedModel[] | null> {
|
||||
return readModelCache(magpieDirs().cache, providerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* providers.json 的 key 指纹,与 magpie internal/provider/keys.go keyID 同一算法:
|
||||
* sha256(key 原文 UTF-8) 前 5 字节的小写 hex(10 字符)。
|
||||
*/
|
||||
function keyFingerprint(key: string): string {
|
||||
return createHash("sha256").update(key, "utf8").digest("hex").slice(0, 10);
|
||||
}
|
||||
|
||||
function asStringArray(v: unknown): string[] | null {
|
||||
return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : null;
|
||||
}
|
||||
|
||||
/** 单个 provider 的目录条目;key 原文只在入参处短暂存在,离开本函数前只剩指纹 */
|
||||
function entryOf(raw: unknown): KeyDirectoryEntry | null {
|
||||
if (typeof raw !== "object" || raw === null) return null;
|
||||
const pr = raw as Record<string, unknown>;
|
||||
if (typeof pr.id !== "string" || !pr.id) return null;
|
||||
const keys: KeyDirectoryEntry["keys"] = [];
|
||||
const seen = new Set<string>();
|
||||
const push = (key: unknown, name: unknown): void => {
|
||||
if (typeof key !== "string" || !key) return;
|
||||
const fingerprint = keyFingerprint(key); // 到这里为止 key 原文已用完
|
||||
if (seen.has(fingerprint)) return;
|
||||
seen.add(fingerprint);
|
||||
keys.push({ fingerprint, name: typeof name === "string" ? name : "" });
|
||||
};
|
||||
push(pr.key, pr.keyName);
|
||||
if (Array.isArray(pr.keys)) {
|
||||
for (const k of pr.keys) {
|
||||
if (typeof k !== "object" || k === null) continue;
|
||||
const rec = k as Record<string, unknown>;
|
||||
if (rec.off === true) continue; // 停用的 key 不列
|
||||
push(rec.key, rec.name);
|
||||
}
|
||||
}
|
||||
const accountModels: Record<string, string[]> = {};
|
||||
if (typeof pr.accountModels === "object" && pr.accountModels !== null) {
|
||||
for (const [k, v] of Object.entries(pr.accountModels)) {
|
||||
const list = asStringArray(v);
|
||||
if (list) accountModels[k] = list;
|
||||
}
|
||||
}
|
||||
return { keys, accountModels };
|
||||
}
|
||||
|
||||
// 读取缓存:只存解析成功且非空的结果(键是文件路径),损坏/缺失每次现读,便于夹具与排错
|
||||
const readCache = new Map<string, { at: number; value: unknown }>();
|
||||
|
||||
function cached<T>(key: string, load: () => Promise<T>, worth: (v: T) => boolean): Promise<T> {
|
||||
const hit = readCache.get(key);
|
||||
if (hit && Date.now() - hit.at < READ_CACHE_MS && worth(hit.value as T)) {
|
||||
return Promise.resolve(hit.value as T);
|
||||
}
|
||||
return load().then((value) => {
|
||||
if (worth(value)) readCache.set(key, { at: Date.now(), value });
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 读 providers.json → 供应商 id → key 目录(指纹、key 名、accountModels)。
|
||||
* 文件不存在 → 空 Map;解析失败 → 固定文案(原异常可能夹带 key 原文,绝不透传)。
|
||||
*/
|
||||
export function readKeyDirectory(configDir: string): Promise<Map<string, KeyDirectoryEntry>> {
|
||||
const file = resolve(join(configDir, "providers.json"));
|
||||
return cached(
|
||||
file,
|
||||
async () => {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(file, "utf8");
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === "ENOENT") return new Map();
|
||||
throw new Error(BROKEN_PROVIDERS_MESSAGE);
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new Error(BROKEN_PROVIDERS_MESSAGE);
|
||||
}
|
||||
const map = new Map<string, KeyDirectoryEntry>();
|
||||
const providers = (parsed as { providers?: unknown } | null)?.providers;
|
||||
if (Array.isArray(providers)) {
|
||||
for (const item of providers) {
|
||||
const entry = entryOf(item);
|
||||
if (entry) {
|
||||
const id = (item as { id: string }).id;
|
||||
const prev = map.get(id);
|
||||
// 同 id 出现两次时合并 key(按指纹去重),accountModels 后者胜
|
||||
if (prev) {
|
||||
for (const k of entry.keys) {
|
||||
if (!prev.keys.some((x) => x.fingerprint === k.fingerprint)) prev.keys.push(k);
|
||||
}
|
||||
Object.assign(prev.accountModels, entry.accountModels);
|
||||
} else {
|
||||
map.set(id, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
},
|
||||
(v) => v.size > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读某供应商的模型缓存 <缓存目录>/models/<供应商id>.json。
|
||||
* 不存在 / 解析失败 / 形状不对 → null;providerId 含路径分隔符或 .. → null(防路径穿越)。
|
||||
*/
|
||||
export function readModelCache(
|
||||
cacheDir: string,
|
||||
providerId: string,
|
||||
): Promise<CachedModel[] | null> {
|
||||
if (
|
||||
!providerId ||
|
||||
providerId.includes("/") ||
|
||||
providerId.includes("\\") ||
|
||||
providerId.includes("..")
|
||||
) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const file = resolve(join(cacheDir, "models", `${providerId}.json`));
|
||||
return cached(
|
||||
file,
|
||||
async () => {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(file, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const models = (parsed as { models?: unknown } | null)?.models;
|
||||
if (!Array.isArray(models)) return null;
|
||||
const out: CachedModel[] = [];
|
||||
for (const item of models) {
|
||||
if (typeof item !== "object" || item === null) return null;
|
||||
const rec = item as Record<string, unknown>;
|
||||
if (typeof rec.ID !== "string" || !rec.ID) return null;
|
||||
const keys = rec.Keys === undefined || rec.Keys === null ? [] : asStringArray(rec.Keys);
|
||||
if (!keys) return null;
|
||||
out.push({ id: rec.ID, keys });
|
||||
}
|
||||
return out;
|
||||
},
|
||||
(v) => v !== null,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// 宿主入口:magpie 加载本包并调用 server() 时启动本地服务(每个端口只起一次)。
|
||||
// 单纯 import 不占端口、不读写磁盘;启动失败清掉对应单例,宿主下次调用可重试。
|
||||
// 启动前先探测端口:响应带本插件的自标记头(server.ts 所有响应都带 x-window-warmup: 1)
|
||||
// → 已有本服务在跑,直接返回 {}(不重开数据目录、不迁移、不报错);没探测到才真正启动,
|
||||
// 端口被别的程序占用时 Bun.serve 仍抛原错误。
|
||||
import { join } from "node:path";
|
||||
import { gatewayBase } from "./gateway";
|
||||
import { xdgConfigHome } from "./magpie-files";
|
||||
import { alreadyServing, startService, type ServiceHandle } from "./server";
|
||||
import { migrateLegacyState } from "./store";
|
||||
|
||||
/** 默认服务端口,与 package.json 的 magpie.options 和带路页(page/boot.js)一致 */
|
||||
export const DEFAULT_PORT = 3492;
|
||||
|
||||
/** 数据目录:WINDOW_WARMUP_DIR 优先,否则 XDG 配置目录下的 magpie/window-warmup。
|
||||
* 不导出:宿主会把模块导出的每个函数都当插件函数调(scripts/check.mjs 的约定) */
|
||||
function defaultDir(env: Record<string, string | undefined> = process.env): string {
|
||||
const custom = env.WINDOW_WARMUP_DIR?.trim();
|
||||
if (custom) return custom;
|
||||
return join(xdgConfigHome(env), "magpie", "window-warmup");
|
||||
}
|
||||
|
||||
/** 端口 → 启动中的服务;按端口分键,端口改了旧实例也不串 */
|
||||
const instances = new Map<number, Promise<ServiceHandle>>();
|
||||
|
||||
export default {
|
||||
id: "magpie-window-warmup",
|
||||
/** magpie 宿主入口;options.port 来自 package.json 的 magpie.options */
|
||||
server: async (_input: unknown, opts: { port?: number } = {}) => {
|
||||
const port = Number(opts?.port);
|
||||
const listen = Number.isFinite(port) && port > 0 ? port : DEFAULT_PORT;
|
||||
if (await alreadyServing(listen)) return {};
|
||||
let instance = instances.get(listen);
|
||||
if (!instance) {
|
||||
instance = (async () => {
|
||||
const dir = defaultDir();
|
||||
// 首次启动(新目录还没有 state.json)时把旧包的数据接过来;迁移在打开 store 之前完成
|
||||
await migrateLegacyState(dir);
|
||||
return startService({
|
||||
port: listen,
|
||||
dir,
|
||||
base: gatewayBase(),
|
||||
});
|
||||
})().catch((e: unknown) => {
|
||||
instances.delete(listen);
|
||||
throw e;
|
||||
});
|
||||
instances.set(listen, instance);
|
||||
}
|
||||
await instance;
|
||||
return {};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,330 @@
|
||||
// 纯规则:时间推算、窗口到期与任务校验。页面(web/app.ts)也直接打包本模块,
|
||||
// 因此这里只许依赖 types,不能引入任何 node:* 或网关模块。
|
||||
import type { QuotaWindow, Task, Trigger } from "./types";
|
||||
|
||||
const MINUTE_MS = 60_000;
|
||||
const HOUR_MS = 3_600_000;
|
||||
/** 额度重置宽限:到期点取 resetsAt + 30s,确保 Magpie 侧已完成重置 */
|
||||
export const RESET_GRACE_MS = 30_000;
|
||||
/** 预热消息固定为 hi:探活用,不可配置(页面与校验都不再收自定义消息) */
|
||||
export const WARMUP_MESSAGE = "hi";
|
||||
/** 补发判断向前回看 48 小时:跨夏令时的日间隔最多 25 小时,足以覆盖最近一个应到点 */
|
||||
const LAST_DUE_LOOKBACK_MS = 48 * HOUR_MS;
|
||||
/** 名称的长度上限按 Unicode 码点计,页面校验共用同一个值 */
|
||||
export const NAME_MAX = 40;
|
||||
|
||||
interface Wall {
|
||||
year: number;
|
||||
month: number;
|
||||
day: number;
|
||||
hour: number;
|
||||
minute: number;
|
||||
}
|
||||
|
||||
const formatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
function formatter(timeZone: string): Intl.DateTimeFormat {
|
||||
let f = formatters.get(timeZone);
|
||||
if (!f) {
|
||||
// h23 避免 "24:xx" 式午夜;en-US 保证 formatToParts 字段稳定
|
||||
f = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
hourCycle: "h23",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
formatters.set(timeZone, f);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
function wallOf(t: Date, timeZone: string): Wall {
|
||||
const p: Record<string, number> = {};
|
||||
for (const part of formatter(timeZone).formatToParts(t)) {
|
||||
if (part.type !== "literal") p[part.type] = Number(part.value);
|
||||
}
|
||||
return { year: p.year, month: p.month, day: p.day, hour: p.hour, minute: p.minute };
|
||||
}
|
||||
|
||||
/** 时区偏移(毫秒,东正西负)。秒级截断,避免子秒噪声 */
|
||||
export function offsetMs(t: Date, timeZone: string): number {
|
||||
const sec = Math.floor(t.getTime() / 1000) * 1000;
|
||||
const w = wallOf(new Date(sec), timeZone);
|
||||
return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, sec / 1000 % 60) - sec;
|
||||
}
|
||||
|
||||
function sameWall(w: Wall, y: number, mo: number, d: number, hh: number, mm: number): boolean {
|
||||
return w.year === y && w.month === mo && w.day === d && w.hour === hh && w.minute === mm;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把某日期的墙上时刻(y-mo-d hh:mm)换算为 UTC 瞬间:
|
||||
* - 正常:唯一实例(回拨日取较早一次)
|
||||
* - 春令时被跳过:返回偏移跳变后的第一个有效时刻
|
||||
*/
|
||||
function resolveWallTime(y: number, mo: number, d: number, hh: number, mm: number, timeZone: string): Date {
|
||||
const guess = Date.UTC(y, mo - 1, d, hh, mm);
|
||||
// 先按 guess 点的偏移猜 UTC,再用猜测点的偏移修正一次; 高偏移时区(如 UTC+13/14)会落到相邻日期,按日差平移
|
||||
let t = guess - offsetMs(new Date(guess), timeZone);
|
||||
t = guess - offsetMs(new Date(t), timeZone);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const w = wallOf(new Date(t), timeZone);
|
||||
if (sameWall(w, y, mo, d, hh, mm)) {
|
||||
return earliestInstanceOf(guess, t, y, mo, d, hh, mm, timeZone);
|
||||
}
|
||||
if (w.hour === hh && w.minute === mm) {
|
||||
t += Date.UTC(y, mo - 1, d) - Date.UTC(w.year, w.month - 1, w.day);
|
||||
continue;
|
||||
}
|
||||
// 墙上时刻不存在:在两个探测点之间二分找偏移跳变,跳变瞬间即跳变后第一个有效时刻
|
||||
const probe = guess - offsetMs(new Date(t), timeZone);
|
||||
let lo = Math.min(t, probe);
|
||||
const loOffset = offsetMs(new Date(lo), timeZone);
|
||||
let hi = Math.max(t, probe);
|
||||
if (offsetMs(new Date(hi), timeZone) === loOffset) return new Date(t);
|
||||
// 二分到 1ms:到期点必须精确落在跳变边界上,提前停会留下 ≤999ms 的漂移
|
||||
while (hi - lo > 1) {
|
||||
const mid = lo + Math.floor((hi - lo) / 2);
|
||||
if (offsetMs(new Date(mid), timeZone) === loOffset) lo = mid;
|
||||
else hi = mid;
|
||||
}
|
||||
return new Date(hi);
|
||||
}
|
||||
return new Date(t);
|
||||
}
|
||||
|
||||
/** 命中的实例若紧跟在回拨之后,可能是较晚的重复实例:向前探测偏移下降,换回较早一次 */
|
||||
function earliestInstanceOf(
|
||||
guess: number, t: number, y: number, mo: number, d: number,
|
||||
hh: number, mm: number, timeZone: string,
|
||||
): Date {
|
||||
const at = new Date(t);
|
||||
const oAt = offsetMs(at, timeZone);
|
||||
const back = t - 3 * HOUR_MS - MINUTE_MS;
|
||||
if (offsetMs(new Date(back), timeZone) === oAt) return at;
|
||||
let lo = back;
|
||||
let hi = t;
|
||||
while (hi - lo > 1) {
|
||||
const mid = lo + Math.floor((hi - lo) / 2);
|
||||
if (offsetMs(new Date(mid), timeZone) === oAt) hi = mid;
|
||||
else lo = mid;
|
||||
}
|
||||
const oBefore = offsetMs(new Date(lo), timeZone);
|
||||
if (oBefore <= oAt) return at;
|
||||
const earlier = guess - oBefore;
|
||||
return sameWall(wallOf(new Date(earlier), timeZone), y, mo, d, hh, mm) ? new Date(earlier) : at;
|
||||
}
|
||||
|
||||
/**
|
||||
* 该日期内目标墙上时刻的全部出现(升序):被跳过时是 [跳变后首个有效时刻],
|
||||
* 回拨日落在重复区间时是 [较早实例, 较晚实例]。
|
||||
*/
|
||||
function occurrencesOnDay(
|
||||
y: number, mo: number, d: number, hh: number, mm: number, timeZone: string,
|
||||
): Date[] {
|
||||
const first = resolveWallTime(y, mo, d, hh, mm, timeZone);
|
||||
const out = [first];
|
||||
const guess = Date.UTC(y, mo - 1, d, hh, mm);
|
||||
const oAt = offsetMs(first, timeZone);
|
||||
const probeEnd = first.getTime() + 3 * HOUR_MS + MINUTE_MS;
|
||||
if (offsetMs(new Date(probeEnd), timeZone) === oAt) return out;
|
||||
let lo = first.getTime();
|
||||
let hi = probeEnd;
|
||||
while (hi - lo > 1) {
|
||||
const mid = lo + Math.floor((hi - lo) / 2);
|
||||
if (offsetMs(new Date(mid), timeZone) === oAt) lo = mid;
|
||||
else hi = mid;
|
||||
}
|
||||
const oAfter = offsetMs(new Date(hi), timeZone);
|
||||
if (oAfter >= oAt) return out;
|
||||
const second = guess - oAfter;
|
||||
if (second > first.getTime() && sameWall(wallOf(new Date(second), timeZone), y, mo, d, hh, mm)) {
|
||||
out.push(new Date(second));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function nextCalDay(y: number, mo: number, d: number): [number, number, number] {
|
||||
const t = new Date(Date.UTC(y, mo - 1, d + 1));
|
||||
return [t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate()];
|
||||
}
|
||||
|
||||
export function nextDaily(t: { time: string; timeZone: string }, after: Date): Date {
|
||||
const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(t.time);
|
||||
if (!m) throw new Error("时间需为 24 小时制的 HH:MM");
|
||||
const hh = Number(m[1]);
|
||||
const mm = Number(m[2]);
|
||||
const start = wallOf(after, t.timeZone);
|
||||
let y = start.year;
|
||||
let mo = start.month;
|
||||
let d = start.day;
|
||||
for (let i = 0; i < 400; i++) {
|
||||
for (const occ of occurrencesOnDay(y, mo, d, hh, mm, t.timeZone)) {
|
||||
if (occ.getTime() > after.getTime()) return occ;
|
||||
}
|
||||
[y, mo, d] = nextCalDay(y, mo, d);
|
||||
}
|
||||
throw new Error("无法计算下一次执行时间");
|
||||
}
|
||||
|
||||
export function nextEvery(t: { hours: number; anchor: string }, after: Date): Date {
|
||||
const anchor = new Date(t.anchor).getTime();
|
||||
if (Number.isNaN(anchor)) throw new Error("起点时间无法识别");
|
||||
// step 要做除数:hours<=0 会算出 Infinity/NaN 点,未校验来源一律拒绝
|
||||
if (!Number.isFinite(t.hours) || t.hours <= 0) throw new Error("间隔小时数必须为正数");
|
||||
if (after.getTime() < anchor) return new Date(anchor);
|
||||
const step = t.hours * HOUR_MS;
|
||||
// 到期点为 anchor + k·step(k 从 0 起),取第一个严格晚于 after 的点
|
||||
const k = Math.floor((after.getTime() - anchor) / step) + 1;
|
||||
return new Date(anchor + k * step);
|
||||
}
|
||||
|
||||
export function lastDue(trigger: Trigger, before: Date): Date | null {
|
||||
if (trigger.kind === "window") return null;
|
||||
if (trigger.kind === "every") {
|
||||
const anchor = new Date(trigger.anchor).getTime();
|
||||
if (Number.isNaN(anchor) || before.getTime() < anchor) return null;
|
||||
if (!Number.isFinite(trigger.hours) || trigger.hours <= 0) return null;
|
||||
const step = trigger.hours * HOUR_MS;
|
||||
const k = Math.floor((before.getTime() - anchor) / step);
|
||||
return new Date(anchor + k * step);
|
||||
}
|
||||
// daily:从 48 小时前起顺序推进,收集 (before-48h, before] 内最后一个应到点
|
||||
let best: Date | null = null;
|
||||
let cursor = nextDaily(trigger, new Date(before.getTime() - LAST_DUE_LOOKBACK_MS));
|
||||
for (let i = 0; i < 6 && cursor.getTime() <= before.getTime(); i++) {
|
||||
best = cursor;
|
||||
cursor = nextDaily(trigger, cursor);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** 快照时刻按小时取整的 ISO 形态:窗口 idle key 与调度器的 missing key 共用同一粒度 */
|
||||
export function hourFloorISO(at: Date): string {
|
||||
return new Date(Math.floor(at.getTime() / HOUR_MS) * HOUR_MS).toISOString();
|
||||
}
|
||||
|
||||
export function windowDue(
|
||||
win: QuotaWindow | undefined,
|
||||
snapshotAt: Date,
|
||||
): { at: Date; resetKey: string } | { error: string } {
|
||||
if (!win) return { error: "账号的额度里没有这个窗口" };
|
||||
if (win.resetsAt) {
|
||||
const resetsAt = new Date(win.resetsAt);
|
||||
if (!Number.isNaN(resetsAt.getTime()) && resetsAt.getTime() > snapshotAt.getTime()) {
|
||||
return { at: new Date(resetsAt.getTime() + RESET_GRACE_MS), resetKey: win.resetsAt };
|
||||
}
|
||||
}
|
||||
// 空闲窗口立即到期;resetKey 按快照所在小时取整,保证同一小时内不会反复尝试
|
||||
return { at: new Date(snapshotAt.getTime()), resetKey: `idle:${hourFloorISO(snapshotAt)}` };
|
||||
}
|
||||
|
||||
export function upcoming(trigger: Trigger, now: Date, n: number): Date[] {
|
||||
// 窗口触发的到期点依赖额度快照(resetsAt),调度层单独计算,几何推算不适用
|
||||
if (trigger.kind === "window") return [];
|
||||
const out: Date[] = [];
|
||||
let cursor = new Date(now.getTime());
|
||||
for (let i = 0; i < n; i++) {
|
||||
cursor = trigger.kind === "daily" ? nextDaily(trigger, cursor) : nextEvery(trigger, cursor);
|
||||
out.push(cursor);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isValidTimeZone(tz: string): boolean {
|
||||
if (!tz) return false;
|
||||
try {
|
||||
new Intl.DateTimeFormat("en-US", { timeZone: tz });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateTask(
|
||||
input: unknown,
|
||||
now: Date,
|
||||
): { task: Omit<Task, "id" | "createdAt" | "updatedAt"> } | { error: string; field: string } {
|
||||
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
||||
return { error: "请求体必须是 JSON 对象", field: "body" };
|
||||
}
|
||||
const raw = input as Record<string, unknown>;
|
||||
|
||||
const name = typeof raw.name === "string" ? raw.name.trim() : "";
|
||||
if (!name) return { error: "给任务起个名字", field: "name" };
|
||||
if ([...name].length > NAME_MAX) return { error: `名称不能超过 ${NAME_MAX} 字`, field: "name" };
|
||||
|
||||
const provider = typeof raw.provider === "string" ? raw.provider.trim() : "";
|
||||
if (!provider) return { error: "必须选择供应商", field: "provider" };
|
||||
|
||||
// "" 表示自动选模型:每次发送前由调度器按 pickAutoModel 现算,这里只拦路由组
|
||||
const model = typeof raw.model === "string" ? raw.model.trim() : "";
|
||||
if (model.startsWith("group/")) return { error: "不支持路由组模型", field: "model" };
|
||||
|
||||
// 消息固定 hi(探活):入参里的 message 忽略,字段只为旧数据兼容保留
|
||||
const message = WARMUP_MESSAGE;
|
||||
|
||||
let enabled = true;
|
||||
if (raw.enabled !== undefined && raw.enabled !== null) {
|
||||
if (typeof raw.enabled !== "boolean") return { error: "启用状态必须是布尔值", field: "enabled" };
|
||||
enabled = raw.enabled;
|
||||
}
|
||||
|
||||
let account = "";
|
||||
if (raw.account !== undefined && raw.account !== null) {
|
||||
if (typeof raw.account !== "string") return { error: "账号标识必须是文本", field: "account" };
|
||||
account = raw.account.trim();
|
||||
}
|
||||
// 账号必选:预热是发给具体账号/key 的,交给网关自动选就没有稳定的去重与窗口归属
|
||||
if (!account) return { error: "必须选择账号", field: "account" };
|
||||
|
||||
const trig = raw.trigger;
|
||||
if (typeof trig !== "object" || trig === null || Array.isArray(trig)) {
|
||||
return { error: "缺少触发方式", field: "trigger" };
|
||||
}
|
||||
const tv = trig as Record<string, unknown>;
|
||||
let trigger: Trigger;
|
||||
switch (tv.kind) {
|
||||
case "window": {
|
||||
const win = typeof tv.window === "string" ? tv.window.trim() : "";
|
||||
if (!win) return { error: "必须填写额度窗口名", field: "window" };
|
||||
trigger = { kind: "window", window: win };
|
||||
break;
|
||||
}
|
||||
case "daily": {
|
||||
const time = typeof tv.time === "string" ? tv.time : "";
|
||||
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(time)) {
|
||||
return { error: "时间需为 24 小时制的 HH:MM", field: "time" };
|
||||
}
|
||||
const timeZone = typeof tv.timeZone === "string" ? tv.timeZone : "";
|
||||
if (!isValidTimeZone(timeZone)) return { error: "无法识别的时区", field: "timeZone" };
|
||||
trigger = { kind: "daily", time, timeZone };
|
||||
break;
|
||||
}
|
||||
case "every": {
|
||||
const hours = tv.hours;
|
||||
if (typeof hours !== "number" || !Number.isFinite(hours) || hours < 1 || hours > 168) {
|
||||
return { error: "间隔需为 1–168 小时", field: "hours" };
|
||||
}
|
||||
let anchor: string;
|
||||
if (tv.anchor === undefined || tv.anchor === null || tv.anchor === "") {
|
||||
anchor = new Date(Math.floor(now.getTime() / MINUTE_MS) * MINUTE_MS).toISOString();
|
||||
} else {
|
||||
if (typeof tv.anchor !== "string") return { error: "起点时间无法识别", field: "anchor" };
|
||||
const a = new Date(tv.anchor);
|
||||
if (Number.isNaN(a.getTime())) return { error: "起点时间无法识别", field: "anchor" };
|
||||
anchor = a.toISOString();
|
||||
}
|
||||
trigger = { kind: "every", hours, anchor };
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return { error: "触发方式必须是 window、daily 或 every", field: "trigger" };
|
||||
}
|
||||
|
||||
return { task: { name, enabled, provider, account, model, message, trigger } };
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
// 调度器:任务的时间计算交给 rules,网关交互交给 gateway(可注入假件)。
|
||||
// 并发模型:所有会改状态的入口(tick/upsert/remove/runNow)都过同一操作队列串行执行,
|
||||
// 发送本体游离在队列外但登记在 inflight 里 —— 同一任务不重叠、删除/停用能等到收尾,
|
||||
// 收尾写回前再查任务是否存在,杜绝「删除后异步完成把记录加回来」。
|
||||
// 单个定时器,延迟 = min(最近到期 − now, 10 分钟),每次醒来重算(抵御睡眠与改系统时间)。
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { modelsForAccount, pinFor, pickAutoModel, windowsForAccount } from "./accounts";
|
||||
import { fetchModels, fetchQuotas, modelProvider, pickEffort, refreshQuotaCard, send } from "./gateway";
|
||||
import {
|
||||
readDefaultKeyDirectory,
|
||||
readDefaultModelCache,
|
||||
type CachedModel,
|
||||
type KeyDirectoryEntry,
|
||||
} from "./magpie-files";
|
||||
import { hourFloorISO, lastDue, nextDaily, nextEvery, upcoming, windowDue } from "./rules";
|
||||
import type { Store, TaskMarks } from "./store";
|
||||
import {
|
||||
errText,
|
||||
type QuotaEntry,
|
||||
type QuotaWindow,
|
||||
type RawModel,
|
||||
type Run,
|
||||
type SendResult,
|
||||
type Task,
|
||||
} from "./types";
|
||||
|
||||
/** 单个定时器的最长睡眠:醒来重算,弥补系统睡眠/时钟跳变 */
|
||||
const TIMER_CAP_MS = 600_000;
|
||||
/** 窗口额度快照的刷新节奏:每 10 分钟及每次到期后 */
|
||||
const QUOTA_REFRESH_MS = 600_000;
|
||||
/**
|
||||
* 发送后多久的读数才算「开窗后」:厂商记账有延迟,刚发完立刻读可能仍是空闲。
|
||||
* 早于「上次发送 + 这段」的空闲读数不可信(见 staleIdle),发送后也按这个点去重读卡
|
||||
*/
|
||||
const POST_SEND_SETTLE_MS = 60_000;
|
||||
/** 窗口到期要发送时,卡片读数超过这个年龄就先让 magpie 重读一次 */
|
||||
const CARD_FRESH_MS = 60_000;
|
||||
/** 同一张卡两次重读请求的最小间隔(magpie 侧另有 30 秒限频) */
|
||||
const CARD_REFRESH_GAP_MS = 60_000;
|
||||
const HOUR_MS = 3_600_000;
|
||||
/** snapshot 时间轴只画未来 24 小时 */
|
||||
const DAY_MS = 24 * HOUR_MS;
|
||||
|
||||
const INTERRUPTED_REASON = "Magpie 在发送中途退出,结果未知";
|
||||
const OVERLAP_REASON = "上一次发送还没结束,本次跳过";
|
||||
const DISABLED_REASON = "任务已停用,发送被取消";
|
||||
const DELETED_REASON = "任务已删除,发送被取消";
|
||||
/** HTTP 409:立即发送撞上正在进行的发送 */
|
||||
export const CONFLICT_MESSAGE = "上一次发送还没结束,请稍后再试";
|
||||
/** HTTP 404:任务不存在或已删除 */
|
||||
export const NOT_FOUND_MESSAGE = "任务不存在";
|
||||
|
||||
export type SendFn = typeof send;
|
||||
export type QuotasFn = typeof fetchQuotas;
|
||||
export type RefreshCardFn = typeof refreshQuotaCard;
|
||||
/** 取模型元数据;signal 在停用/删除时传入,中止进行中的请求(测试假件可不实现) */
|
||||
export type ModelsFn = (base: string, signal?: AbortSignal) => Promise<RawModel[]>;
|
||||
/** 读 providers.json 的 key 目录;null = 读不出(指纹账号按「≥2 把 key」处理) */
|
||||
export type KeyDirFn = () => Promise<Map<string, KeyDirectoryEntry> | null>;
|
||||
/** 读某供应商的模型缓存;null = 没有缓存文件 */
|
||||
export type ModelCacheFn = (providerId: string) => Promise<CachedModel[] | null>;
|
||||
/** 注册定时器,返回取消函数;测试注入假时钟时用它截取回调 */
|
||||
export type TimerSetter = (fn: () => void, ms: number) => () => void;
|
||||
|
||||
/** 新建/全量更新的任务输入;id 缺省表示新建,档位永不入参(发送时现算) */
|
||||
export type TaskInput = Omit<Task, "id" | "createdAt" | "updatedAt"> & { id?: string };
|
||||
|
||||
export interface SchedulerDeps {
|
||||
store: Store;
|
||||
/** Magpie 网关地址(gatewayBase 的产物) */
|
||||
base: string;
|
||||
now?: () => Date;
|
||||
setTimer?: TimerSetter;
|
||||
sendFn?: SendFn;
|
||||
quotasFn?: QuotasFn;
|
||||
refreshCardFn?: RefreshCardFn;
|
||||
modelsFn?: ModelsFn;
|
||||
/** key 目录与模型缓存的读取器;缺省与 /api/catalog 一样按默认位置读(readDefault*) */
|
||||
keyDirFn?: KeyDirFn;
|
||||
modelCacheFn?: ModelCacheFn;
|
||||
}
|
||||
|
||||
export interface TimelinePoint {
|
||||
taskId: string;
|
||||
at: string;
|
||||
}
|
||||
|
||||
/** snapshot() 的返回:页面状态的总览;window 任务的 next 依赖最新额度快照 */
|
||||
export interface StateView {
|
||||
tasks: Task[];
|
||||
runs: Run[];
|
||||
/** taskId → 下一个执行点 ISO;停用任务为 null */
|
||||
next: Record<string, string | null>;
|
||||
/** 未来 24 小时内的计划点,按时间升序 */
|
||||
timeline: TimelinePoint[];
|
||||
/** 最近一次落盘失败的中文原因;成功保存后清除。非 null 时页面应提示「数据可能没保存」 */
|
||||
saveError: string | null;
|
||||
}
|
||||
|
||||
type QuotaSnapshot = { at: Date; entries: QuotaEntry[] };
|
||||
/** 窗口任务按当前快照算出的到期点与去重键 */
|
||||
type WindowDue = { at: Date; resetKey: string };
|
||||
|
||||
interface Inflight {
|
||||
abort: AbortController;
|
||||
/** 停用/删除请求的取消标记;置位后收尾把记录改判 unknown */
|
||||
cancel: "disabled" | "deleted" | null;
|
||||
done: Promise<void>;
|
||||
}
|
||||
|
||||
/** 白名单挑任务内容字段:档位等运行时字段永远进不了任务文件 */
|
||||
function taskContent(input: TaskInput): Omit<Task, "id" | "createdAt" | "updatedAt"> {
|
||||
return {
|
||||
name: input.name,
|
||||
enabled: input.enabled,
|
||||
provider: input.provider,
|
||||
account: input.account,
|
||||
model: input.model,
|
||||
message: input.message,
|
||||
trigger: input.trigger,
|
||||
};
|
||||
}
|
||||
|
||||
/** 一条刚开始的执行记录(running);直接失败的记录在此基础上覆盖结果字段 */
|
||||
function newRun(
|
||||
task: Task,
|
||||
at: Date,
|
||||
due: Date | null,
|
||||
source: Run["source"],
|
||||
resetKey: string | null,
|
||||
): Run {
|
||||
return {
|
||||
id: randomUUID(),
|
||||
taskId: task.id,
|
||||
source,
|
||||
due: due?.toISOString() ?? null,
|
||||
startedAt: at.toISOString(),
|
||||
endedAt: null,
|
||||
outcome: "running",
|
||||
reason: "",
|
||||
effort: null,
|
||||
model: null,
|
||||
ms: null,
|
||||
resetKey,
|
||||
};
|
||||
}
|
||||
|
||||
export class Scheduler {
|
||||
private readonly store: Store;
|
||||
private readonly base: string;
|
||||
private readonly nowFn: () => Date;
|
||||
private readonly setTimerFn: TimerSetter;
|
||||
private readonly sendFn: SendFn;
|
||||
private readonly quotasFn: QuotasFn;
|
||||
private readonly refreshCardFn: RefreshCardFn;
|
||||
private readonly modelsFn: ModelsFn;
|
||||
private readonly keyDirFn: KeyDirFn;
|
||||
private readonly modelCacheFn: ModelCacheFn;
|
||||
|
||||
private started = false;
|
||||
/** 操作队列:串行执行所有改状态入口,前一个失败不阻塞后一个 */
|
||||
private chain: Promise<unknown> = Promise.resolve();
|
||||
/** 游离的发送收尾,flush() 等它们 */
|
||||
private background: Promise<unknown>[] = [];
|
||||
private lastWrite: Promise<void> = Promise.resolve();
|
||||
private cancelTimer: (() => void) | null = null;
|
||||
/** 当前定时器为每个 daily/every 任务排的到期点;唤醒时与之比对区分 schedule/catchup */
|
||||
private armedFor = new Map<string, Date>();
|
||||
private inflight = new Map<string, Inflight>();
|
||||
private quota: QuotaSnapshot | null = null;
|
||||
/** key 目录的最近一次读取:窗口任务的账号→窗口映射(同步路径)要用 */
|
||||
private keyDirMap: Map<string, KeyDirectoryEntry> | null = null;
|
||||
/** 发送改变额度状态,或上次刷新失败 → 下一轮先刷新快照再判断 */
|
||||
private quotaStale = false;
|
||||
private quotaTried = false;
|
||||
/** 最近一次落盘失败的原始原因;成功保存后清除。snapshot().saveError 组合展示文案 */
|
||||
private saveError: string | null = null;
|
||||
/** 评估抛错的去重:taskId → 「小时|原因」,同一小时同一原因只记一条 */
|
||||
private lastErrKey = new Map<string, string>();
|
||||
/** 「供应商|账号」→ 上次请求重读该卡的时刻 */
|
||||
private lastCardRefresh = new Map<string, number>();
|
||||
|
||||
constructor(deps: SchedulerDeps) {
|
||||
this.store = deps.store;
|
||||
this.base = deps.base;
|
||||
this.nowFn = deps.now ?? (() => new Date());
|
||||
this.setTimerFn =
|
||||
deps.setTimer ??
|
||||
((fn, ms) => {
|
||||
const t = setTimeout(fn, ms);
|
||||
return () => clearTimeout(t);
|
||||
});
|
||||
this.sendFn = deps.sendFn ?? send;
|
||||
this.quotasFn = deps.quotasFn ?? fetchQuotas;
|
||||
this.refreshCardFn = deps.refreshCardFn ?? refreshQuotaCard;
|
||||
this.modelsFn = deps.modelsFn ?? fetchModels;
|
||||
// 缺省与 /api/catalog 读同一份 Magpie 文件;providers.json 损坏按「读不出」处理(null)
|
||||
this.keyDirFn = deps.keyDirFn ?? readDefaultKeyDirectory;
|
||||
this.modelCacheFn = deps.modelCacheFn ?? readDefaultModelCache;
|
||||
}
|
||||
|
||||
/** 启动:把遗留的 running 记录改判 unknown,再排定时器。可重复调用 */
|
||||
start(): void {
|
||||
this.started = true;
|
||||
const now = this.nowFn();
|
||||
let dirty = false;
|
||||
for (const r of this.store.data.runs) {
|
||||
if (r.outcome === "running") {
|
||||
r.outcome = "unknown";
|
||||
r.reason = INTERRUPTED_REASON;
|
||||
r.endedAt = now.toISOString();
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
if (dirty) void this.trackSave();
|
||||
this.rearm();
|
||||
}
|
||||
|
||||
/** 停止排程(进行中的发送照常收尾记录) */
|
||||
stop(): void {
|
||||
this.started = false;
|
||||
if (this.cancelTimer) {
|
||||
this.cancelTimer();
|
||||
this.cancelTimer = null;
|
||||
}
|
||||
this.armedFor = new Map();
|
||||
}
|
||||
|
||||
/** 新建或全量更新任务;进行中的发送遇 enabled→false 会被中止并改判 unknown */
|
||||
upsert(input: TaskInput): Promise<Task> {
|
||||
return this.queueOp(async () => {
|
||||
const now = this.nowFn();
|
||||
if (input.id) {
|
||||
const idx = this.store.data.tasks.findIndex((t) => t.id === input.id);
|
||||
if (idx < 0) throw new Error(NOT_FOUND_MESSAGE);
|
||||
const prev = this.store.data.tasks[idx];
|
||||
const next: Task = {
|
||||
id: prev.id,
|
||||
...taskContent(input),
|
||||
createdAt: prev.createdAt,
|
||||
updatedAt: now.toISOString(),
|
||||
};
|
||||
this.store.data.tasks[idx] = next;
|
||||
const flight = this.inflight.get(next.id);
|
||||
if (prev.enabled && !next.enabled && flight && !flight.cancel) {
|
||||
flight.cancel = "disabled";
|
||||
flight.abort.abort();
|
||||
await flight.done;
|
||||
}
|
||||
await this.store.save();
|
||||
this.rearm();
|
||||
return next;
|
||||
}
|
||||
const task: Task = {
|
||||
id: randomUUID(),
|
||||
...taskContent(input),
|
||||
createdAt: now.toISOString(),
|
||||
updatedAt: now.toISOString(),
|
||||
};
|
||||
this.store.data.tasks.push(task);
|
||||
this.store.data.marks[task.id] = { lastDue: null, resetKeys: [] };
|
||||
await this.store.save();
|
||||
this.rearm();
|
||||
return task;
|
||||
});
|
||||
}
|
||||
|
||||
/** 删除任务、执行记录与 marks;进行中的发送先中止并等收尾 */
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.queueOp(async () => {
|
||||
const exists = this.store.data.tasks.some((t) => t.id === id);
|
||||
const flight = this.inflight.get(id);
|
||||
if (!exists && !flight) throw new Error(NOT_FOUND_MESSAGE);
|
||||
if (flight) {
|
||||
flight.cancel = "deleted";
|
||||
flight.abort.abort();
|
||||
await flight.done;
|
||||
}
|
||||
this.store.data.tasks = this.store.data.tasks.filter((t) => t.id !== id);
|
||||
this.store.data.runs = this.store.data.runs.filter((r) => r.taskId !== id);
|
||||
delete this.store.data.marks[id];
|
||||
this.lastErrKey.delete(id);
|
||||
await this.store.save();
|
||||
this.rearm();
|
||||
});
|
||||
}
|
||||
|
||||
/** 立即发送一次(source=manual),不动计划与 resetKey;正在发送时视为冲突抛错 */
|
||||
runNow(id: string): Promise<Run> {
|
||||
return this.queueOp(async () => {
|
||||
const task = this.store.data.tasks.find((t) => t.id === id);
|
||||
if (!task) throw new Error(NOT_FOUND_MESSAGE);
|
||||
if (this.inflight.has(id)) throw new Error(CONFLICT_MESSAGE);
|
||||
return this.fire(task, null, "manual", null);
|
||||
});
|
||||
}
|
||||
|
||||
/** 页面状态总览(同步读,不发请求);window 任务的 next 依赖已缓存的额度快照 */
|
||||
snapshot(): StateView {
|
||||
const now = this.nowFn();
|
||||
const next: Record<string, string | null> = {};
|
||||
const timeline: TimelinePoint[] = [];
|
||||
for (const task of this.store.data.tasks) {
|
||||
if (!task.enabled) {
|
||||
next[task.id] = null;
|
||||
continue;
|
||||
}
|
||||
// 与 tick/rearm 同策略:单个坏任务(如时区库变更后 state.json 里的旧时区失效)
|
||||
// 不能拖垮整页状态——否则 GET /api/state 500,用户连删除它的入口都没有。
|
||||
// 它的下次执行点置空、不进时间轴,失败本身由 tick 的评估记录
|
||||
const points: TimelinePoint[] = [];
|
||||
try {
|
||||
this.snapshotTask(task, now, next, points);
|
||||
} catch {
|
||||
next[task.id] = null;
|
||||
continue;
|
||||
}
|
||||
timeline.push(...points);
|
||||
}
|
||||
timeline.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
|
||||
return {
|
||||
tasks: [...this.store.data.tasks],
|
||||
runs: [...this.store.data.runs],
|
||||
next,
|
||||
timeline,
|
||||
saveError: this.saveError === null ? null : `状态文件写不进去:${this.saveError}`,
|
||||
};
|
||||
}
|
||||
|
||||
/** 单任务的下次执行点与 24 小时时间轴点;时区/规则抛错时由调用方兜成「无计划」 */
|
||||
private snapshotTask(
|
||||
task: Task,
|
||||
now: Date,
|
||||
next: Record<string, string | null>,
|
||||
points: TimelinePoint[],
|
||||
): void {
|
||||
if (task.trigger.kind === "window") {
|
||||
const due = this.currentWindowDue(task, now);
|
||||
let at: Date | null = null;
|
||||
if (due && !this.tried(task, due)) {
|
||||
// 空闲窗口且本轮没发过:快照新鲜就立即发(调度器会在到点前先刷新快照),
|
||||
// 快照过期/缺失才按刷新节奏等下一轮——保存即符合条件不该再等 10 分钟
|
||||
if (due.at.getTime() > now.getTime()) at = due.at;
|
||||
else at = this.snapshotFresh(now) ? now : new Date(now.getTime() + QUOTA_REFRESH_MS);
|
||||
}
|
||||
next[task.id] = at ? at.toISOString() : null;
|
||||
if (at && at.getTime() > now.getTime() && at.getTime() <= now.getTime() + DAY_MS) {
|
||||
points.push({ taskId: task.id, at: at.toISOString() });
|
||||
}
|
||||
} else {
|
||||
const base = this.pendingFixedDue(task, now) ?? now;
|
||||
const at =
|
||||
task.trigger.kind === "daily" ? nextDaily(task.trigger, base) : nextEvery(task.trigger, base);
|
||||
next[task.id] = at.toISOString();
|
||||
for (const p of upcoming(task.trigger, now, 25)) {
|
||||
if (p.getTime() > now.getTime() + DAY_MS) break;
|
||||
points.push({ taskId: task.id, at: p.toISOString() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 等待排队中的操作与发送收尾全部落盘(测试与优雅退出用) */
|
||||
async flush(): Promise<void> {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const bg = [...this.background];
|
||||
if (bg.length > 0) {
|
||||
// 有的发送(假件或极端网络)可能永不返回:等不动就先走
|
||||
await Promise.race([Promise.allSettled(bg), new Promise((r) => setTimeout(r, 0))]);
|
||||
}
|
||||
await this.chain.catch(() => {});
|
||||
await this.lastWrite;
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
if (this.background.length === 0) {
|
||||
await this.chain.catch(() => {});
|
||||
await this.lastWrite;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private queueOp<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const run = this.chain.then(fn, fn);
|
||||
this.chain = run.then(
|
||||
() => {},
|
||||
() => {},
|
||||
);
|
||||
return run;
|
||||
}
|
||||
|
||||
private track(p: Promise<unknown>): void {
|
||||
const wrapped = p.catch(() => {}).finally(() => {
|
||||
this.background = this.background.filter((x) => x !== wrapped);
|
||||
});
|
||||
this.background.push(wrapped);
|
||||
}
|
||||
|
||||
/**
|
||||
* 落盘并如实上报本次成败(false = 失败):调度内部不能吞掉保存错误——
|
||||
* 「发送前持久化成功」是发请求的前提,错误同时记入 saveError 供 snapshot 暴露。
|
||||
*/
|
||||
private trackSave(): Promise<boolean> {
|
||||
const p = this.store.save().then(
|
||||
() => {
|
||||
this.saveError = null;
|
||||
return true;
|
||||
},
|
||||
(e) => {
|
||||
this.saveError = errText(e);
|
||||
return false;
|
||||
},
|
||||
);
|
||||
this.lastWrite = p.then(() => {});
|
||||
return p;
|
||||
}
|
||||
|
||||
private marksOf(id: string): TaskMarks {
|
||||
let m = this.store.data.marks[id];
|
||||
if (!m) {
|
||||
m = { lastDue: null, resetKeys: [] };
|
||||
this.store.data.marks[id] = m;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
private async tick(): Promise<void> {
|
||||
if (!this.started) return;
|
||||
const now = this.nowFn();
|
||||
const tasks = this.store.data.tasks;
|
||||
const hasWindow = tasks.some((t) => t.enabled && t.trigger.kind === "window");
|
||||
// 评估前先把快照刷到最新(refreshQuotas 对新鲜快照是空操作):
|
||||
// 拿过期快照评估会在睡眠醒来、手动发送刚开窗之后,按旧的空闲窗口再发一次
|
||||
if (hasWindow) {
|
||||
await this.refreshQuotas();
|
||||
if (await this.readCards(now)) {
|
||||
this.quotaStale = true;
|
||||
await this.refreshQuotas();
|
||||
}
|
||||
}
|
||||
for (const task of [...tasks]) {
|
||||
if (!task.enabled) continue;
|
||||
try {
|
||||
if (task.trigger.kind === "window") await this.evaluateWindow(task, now);
|
||||
else await this.evaluateFixed(task, now);
|
||||
} catch (e) {
|
||||
// 单个任务评估出错不拖垮其他任务;同一小时同一原因只记一条,别每个 tick 刷屏
|
||||
const reason = `调度出错:${errText(e)}`;
|
||||
const key = `${hourFloorISO(now)}|${reason}`;
|
||||
if (this.lastErrKey.get(task.id) !== key) {
|
||||
this.lastErrKey.set(task.id, key);
|
||||
this.appendFailure(task, now, null, reason, null, "schedule");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasWindow) await this.refreshQuotas(); // 到期后/每 10 分钟刷新,供下轮判断
|
||||
this.rearm();
|
||||
}
|
||||
|
||||
/**
|
||||
* daily/every 任务已消费到哪一刻:上次执行的到期点与最后一次编辑取较晚者。
|
||||
* 只有严格晚于它的应到点才有效——编辑之前错过的点不补,已执行的点不重发。
|
||||
*/
|
||||
private fixedConsumedUntil(task: Task): number {
|
||||
const last = this.store.data.marks[task.id]?.lastDue;
|
||||
const updated = new Date(task.updatedAt).getTime();
|
||||
return last ? Math.max(new Date(last).getTime(), updated) : updated;
|
||||
}
|
||||
|
||||
/** daily/every 任务待补发的最近应到点(还没消费过);没有为 null */
|
||||
private pendingFixedDue(task: Task, now: Date): Date | null {
|
||||
const recent = lastDue(task.trigger, now);
|
||||
return recent && recent.getTime() > this.fixedConsumedUntil(task) ? recent : null;
|
||||
}
|
||||
|
||||
/** 评估 daily/every 任务:最近应到点若晚于上次执行且晚于 updatedAt,就发一次 */
|
||||
private async evaluateFixed(task: Task, now: Date): Promise<void> {
|
||||
const due = this.pendingFixedDue(task, now);
|
||||
if (!due) return;
|
||||
const armed = this.armedFor.get(task.id) ?? null;
|
||||
const source: Run["source"] =
|
||||
armed !== null && armed.getTime() === due.getTime() ? "schedule" : "catchup";
|
||||
await this.fire(task, due, source, null);
|
||||
}
|
||||
|
||||
private async evaluateWindow(task: Task, now: Date): Promise<void> {
|
||||
// 拿不到窗口不记失败:额度卡时有时无(插件供应商的用量读取会瞬断、刚刷新时缓存
|
||||
// 短暂缺卡),按失败上报只会刷一屏红字。等下一轮刷新,页面上的账号/窗口下拉会
|
||||
// 显示当前实际有哪些;账号或窗口被永久删掉时,编辑区能看出来
|
||||
const due = this.currentWindowDue(task, now);
|
||||
if (!due || !this.windowReady(task, due, now)) return;
|
||||
const marks = this.marksOf(task.id);
|
||||
marks.resetKeys.push(due.resetKey);
|
||||
// 同一实际重置只花一次额度:把本次到期所在小时的 idle key 一并消费,
|
||||
// 免得缓存随后丢掉 resetsAt 时,同一小时里又被当成新的空闲事件发一次
|
||||
const companion = `idle:${hourFloorISO(due.at)}`;
|
||||
if (companion !== due.resetKey) marks.resetKeys.push(companion);
|
||||
this.quotaStale = true; // 发送改变额度状态,下一轮先刷新快照再判断
|
||||
await this.fire(task, due.at, "schedule", due.resetKey);
|
||||
}
|
||||
|
||||
/** 这个 resetKey 已经尝试过(同一 resetKey 最多尝试一次,成功失败未知都算) */
|
||||
private tried(task: Task, due: WindowDue): boolean {
|
||||
return this.marksOf(task.id).resetKeys.includes(due.resetKey);
|
||||
}
|
||||
|
||||
/** 已过 resetsAt+30s(或空闲立即到期)且本轮还没尝试过:该发了 */
|
||||
private windowReady(task: Task, due: WindowDue, now: Date): boolean {
|
||||
return due.at.getTime() <= now.getTime() && !this.tried(task, due);
|
||||
}
|
||||
|
||||
/** 任务所选窗口在当前快照里的样子;无快照、没账号、额度里找不到账号/窗口都是 undefined */
|
||||
private quotaWindow(task: Task): QuotaWindow | undefined {
|
||||
if (task.trigger.kind !== "window" || !this.quota || !task.account) return undefined;
|
||||
const name = task.trigger.window;
|
||||
// 账号 → 窗口走统一账号列表:key 账号用指纹反查 key 名再匹配 ~keys 卡(accounts.ts 共用实现)
|
||||
const windows = windowsForAccount(task.provider, task.account, this.quota.entries, this.keyDirMap);
|
||||
return windows?.find((w) => w.name === name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记下各窗口任务最近见到的重置时间(变了才落盘):额度卡瞬断丢了 resetsAt 时,
|
||||
* currentWindowDue 靠它分辨真假空闲。额度快照或 key 目录一更新就要补记,新建/编辑任务后也要。
|
||||
*/
|
||||
private recordResets(): void {
|
||||
let dirty = false;
|
||||
for (const task of this.store.data.tasks) {
|
||||
if (!task.enabled) continue;
|
||||
const raw = this.quotaWindow(task)?.resetsAt;
|
||||
if (!raw || Number.isNaN(new Date(raw).getTime())) continue;
|
||||
const mark = this.marksOf(task.id);
|
||||
if (mark.lastReset !== raw) {
|
||||
mark.lastReset = raw;
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
if (dirty) void this.trackSave();
|
||||
}
|
||||
|
||||
/**
|
||||
* 用当前快照判断窗口任务的到期点与去重键;null 表示这一轮当没数据,等下一轮刷新
|
||||
* (无快照、找不到账号或窗口、读数不可信)。纯计算,不改任何状态。
|
||||
*/
|
||||
private currentWindowDue(task: Task, now: Date): WindowDue | null {
|
||||
const win = this.quotaWindow(task);
|
||||
if (!win || !this.quota) return null;
|
||||
const due = windowDue(win, this.quota.at);
|
||||
if ("error" in due) return null;
|
||||
// 空闲读数早于上次发送:那是发送前读的(magpie 只在路由请求那一刻读卡),当没数据,
|
||||
// 等 readCards 拿到发送后的读数再判断——否则跨整点 idle key 一变就会再发一次
|
||||
if (due.resetKey.startsWith("idle:") && this.staleIdle(task)) return null;
|
||||
const raw = win.resetsAt;
|
||||
if (raw && !Number.isNaN(new Date(raw).getTime())) {
|
||||
// 只要窗口带着可解析的 resetsAt,key 就用 resetsAt 本身:与重置发送同 key,消费过
|
||||
// 就绝不再发(刷新/跨小时/重启都一样),出现新 resetsAt 才是新事件;
|
||||
// truthy 但解析不了的 resetsAt 当缺失处理,保留按小时限频。
|
||||
return { at: due.at, resetKey: raw };
|
||||
}
|
||||
// resetsAt 缺失或解析不了——两种可能:真空闲(没开始/上一轮已过),或卡瞬断。
|
||||
// 之前见过且还没到的重置时间说明窗口其实在计时,这轮当没数据,静默等下一轮刷新;
|
||||
// 已消费过的未来 resetsAt 同理(重启后 lastReset 还没补上时兜一道)。
|
||||
// idle: 等非时间形态的 key 解析出 NaN,比较恒为假,不用单独排除
|
||||
const mark = this.marksOf(task.id);
|
||||
const isFuture = (iso: string | null | undefined): boolean =>
|
||||
!!iso && new Date(iso).getTime() > now.getTime();
|
||||
if (isFuture(mark.lastReset) || mark.resetKeys.some(isFuture)) return null;
|
||||
return due;
|
||||
}
|
||||
|
||||
/** 任务账号的订阅卡(本机可重读的那种);key 卡来自远程 magpie,返回 null */
|
||||
private loginCard(task: Task): QuotaEntry | null {
|
||||
return (
|
||||
this.quota?.entries.find(
|
||||
(q) => q.provider === task.provider && !q.viaKey && q.account === task.account,
|
||||
) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/** 窗口任务上次真正发出的收尾时刻(毫秒);没有为 NaN */
|
||||
private lastSentMs(task: Task): number {
|
||||
const v = this.store.data.marks[task.id]?.lastSent;
|
||||
return v ? new Date(v).getTime() : NaN;
|
||||
}
|
||||
|
||||
/** 卡片读数早于「上次发送 + 记账余量」;拿不到 readAt(旧版 magpie)时不设门槛 */
|
||||
private staleIdle(task: Task): boolean {
|
||||
const readAt = new Date(this.loginCard(task)?.readAt ?? "").getTime();
|
||||
const sent = this.lastSentMs(task);
|
||||
return Number.isFinite(readAt) && Number.isFinite(sent) && readAt < sent + POST_SEND_SETTLE_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 该重读的订阅卡让 magpie 现读一次,返回是否发起过。kept 缓存只在 magpie 路由请求那一刻
|
||||
* 更新(无托盘的 magpie web 平时不读卡),两种时机需要新读数:
|
||||
* - 窗口按当前快照到期、马上要发:读数超过 1 分钟就先重读,别按旧空闲白发;
|
||||
* - 发送已满记账余量、读数还早于那时:拿开窗后的 resetsAt,定时器才能精确排到重置点。
|
||||
* 重读失败不记失败:staleIdle 门槛兜着,下一轮再试
|
||||
*/
|
||||
private async readCards(now: Date): Promise<boolean> {
|
||||
let asked = false;
|
||||
for (const task of this.store.data.tasks) {
|
||||
if (!task.enabled || task.trigger.kind !== "window") continue;
|
||||
const card = this.loginCard(task);
|
||||
if (!card) continue;
|
||||
const readAt = new Date(card.readAt ?? "").getTime();
|
||||
const settled = this.lastSentMs(task) + POST_SEND_SETTLE_MS;
|
||||
const afterSend = now.getTime() >= settled && readAt < settled;
|
||||
const due = this.currentWindowDue(task, now);
|
||||
// readAt 缺失时是 NaN,「足够新」比较为假,照样算需要重读
|
||||
const readFresh = now.getTime() - readAt <= CARD_FRESH_MS;
|
||||
const dueNow = due !== null && this.windowReady(task, due, now) && !readFresh;
|
||||
if (!afterSend && !dueNow) continue;
|
||||
const key = `${card.provider}|${card.account}`;
|
||||
const last = this.lastCardRefresh.get(key);
|
||||
if (last !== undefined && now.getTime() - last < CARD_REFRESH_GAP_MS) continue;
|
||||
this.lastCardRefresh.set(key, now.getTime());
|
||||
asked = true;
|
||||
await this.refreshCardFn(this.base, card.provider, card.account).catch(() => {});
|
||||
}
|
||||
return asked;
|
||||
}
|
||||
|
||||
/** 额度快照是否新鲜:没过期且不是上次发送刚弄脏的 */
|
||||
private snapshotFresh(now: Date): boolean {
|
||||
return (
|
||||
this.quota !== null &&
|
||||
!this.quotaStale &&
|
||||
now.getTime() - this.quota.at.getTime() < QUOTA_REFRESH_MS
|
||||
);
|
||||
}
|
||||
|
||||
private async refreshQuotas(): Promise<void> {
|
||||
const now = this.nowFn();
|
||||
const quotaFresh = this.snapshotFresh(now);
|
||||
// 快照还新鲜但 key 目录没读到(上轮失败):也要再补读,指纹账号的窗口映射等着它
|
||||
if (quotaFresh && this.keyDirMap !== null) return;
|
||||
this.quotaTried = true;
|
||||
// key 目录与额度快照一起等完再返回:currentWindowDue 是同步路径,只等额度的话,
|
||||
// key 目录(真实文件 I/O)后到会让指纹账号在首轮误报「额度里没有账号」。
|
||||
// key 目录读失败保留旧值(可能仍是 null),不拿失败结果盖掉上一次的好数据
|
||||
const [keyDir, snap] = await Promise.all([
|
||||
this.keyDirFn().then(
|
||||
(m) => m,
|
||||
() => this.keyDirMap,
|
||||
),
|
||||
quotaFresh
|
||||
? Promise.resolve(this.quota)
|
||||
: this.quotasFn(this.base).catch(() => null),
|
||||
]);
|
||||
this.keyDirMap = keyDir;
|
||||
if (snap) {
|
||||
this.quota = snap;
|
||||
this.quotaStale = false;
|
||||
} else if (!quotaFresh) {
|
||||
// 刷新失败保留旧快照,下个周期再试;额度读不到不值得记一条失败记录
|
||||
this.quotaStale = true;
|
||||
}
|
||||
this.recordResets();
|
||||
}
|
||||
|
||||
/** 发送一次:先落盘 running 与 lastDue,再解析档位、调用 sendFn;收尾游离,返回 running 记录 */
|
||||
private async fire(
|
||||
task: Task,
|
||||
due: Date | null,
|
||||
source: Run["source"],
|
||||
resetKey: string | null,
|
||||
): Promise<Run> {
|
||||
const now = this.nowFn();
|
||||
if (this.inflight.has(task.id)) {
|
||||
// 同一任务不重叠:本次到期点作废,但仍算已消费,避免反复记「跳过」
|
||||
if (due && task.trigger.kind !== "window") this.marksOf(task.id).lastDue = due.toISOString();
|
||||
return this.appendFailure(task, now, due, OVERLAP_REASON, resetKey, source);
|
||||
}
|
||||
if (due && task.trigger.kind !== "window") this.marksOf(task.id).lastDue = due.toISOString();
|
||||
const run = newRun(task, now, due, source, resetKey);
|
||||
this.store.data.runs.push(run);
|
||||
const abort = new AbortController();
|
||||
const entry: Inflight = { abort, cancel: null, done: Promise.resolve() };
|
||||
this.inflight.set(task.id, entry);
|
||||
const savedRunning = this.trackSave(); // 本次落盘的成败决定能不能发(见 sendAndFinalize)
|
||||
entry.done = this.sendAndFinalize(task, run, entry, savedRunning);
|
||||
this.track(entry.done);
|
||||
await savedRunning;
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送前解析当次的账号头与模型(每次发送现取 /v1/models、key 目录与该供应商的模型缓存,
|
||||
* 配置变了下一次发送自动跟随)。固定模型只校验仍在 /v1/models,不校验账号权限(交给服务器);
|
||||
* 自动模型按统一账号规则取该账号(或「自动选账号」)的可选模型列表现选。
|
||||
*/
|
||||
private async resolveSend(
|
||||
task: Task,
|
||||
models: RawModel[],
|
||||
): Promise<{ id: string; model: RawModel; pin: string | null } | { error: string }> {
|
||||
const [keyDir, cache] = await Promise.all([
|
||||
this.keyDirFn().catch(() => null),
|
||||
this.modelCacheFn(task.provider).catch(() => null),
|
||||
]);
|
||||
const pin = pinFor(task.provider, task.account, keyDir, this.quota?.entries ?? []);
|
||||
if (task.model) {
|
||||
const model = models.find((m) => m.id === task.model);
|
||||
return model
|
||||
? { id: task.model, model, pin }
|
||||
: { error: `模型 ${task.model} 已不在 Magpie 的模型列表里` };
|
||||
}
|
||||
const ids = models.filter((m) => modelProvider(m) === task.provider).map((m) => m.id);
|
||||
const list = modelsForAccount(task.provider, task.account, { models: ids, keyDir, cache }).list;
|
||||
if (list === null) {
|
||||
return { error: `供应商 ${task.provider} 还没有模型列表,无法自动选模型` };
|
||||
}
|
||||
if (list.length === 0) return { error: `账号 ${task.account || "自动"} 没有可用模型` };
|
||||
const chosen = pickAutoModel(list.map((id) => ({ id })));
|
||||
if (!chosen) return { error: `账号 ${task.account || "自动"} 没有可用模型` };
|
||||
const model = models.find((m) => m.id === chosen.id);
|
||||
// list 由第 3 层过滤过,一定还在 /v1/models 里;兜底防夹具不一致
|
||||
if (!model) return { error: `模型 ${chosen.id} 已不在 Magpie 的模型列表里` };
|
||||
return { id: chosen.id, model, pin };
|
||||
}
|
||||
|
||||
private async sendAndFinalize(
|
||||
task: Task,
|
||||
run: Run,
|
||||
entry: Inflight,
|
||||
savedRunning: Promise<boolean>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
// 持久化是发送的前提:running 记录与已消费的 marks 没落盘就不发请求——
|
||||
// 否则进程一旦退出,磁盘上的到期点还没消费,重启会对同一点再发一次
|
||||
const persisted = await savedRunning;
|
||||
let effort: string | null = null;
|
||||
let result: SendResult;
|
||||
let sent = false;
|
||||
if (!persisted) {
|
||||
result = {
|
||||
outcome: "failed",
|
||||
reason: `状态文件写不进去,本次不发送:${this.saveError ?? "未知原因"}`,
|
||||
ms: 0,
|
||||
};
|
||||
} else {
|
||||
try {
|
||||
const models = await this.modelsFn(this.base, entry.abort.signal);
|
||||
const resolved = await this.resolveSend(task, models);
|
||||
if ("error" in resolved) {
|
||||
result = { outcome: "failed", reason: resolved.error, ms: 0 };
|
||||
} else {
|
||||
const pick = pickEffort(resolved.model);
|
||||
if ("error" in pick) {
|
||||
result = { outcome: "failed", reason: pick.error, ms: 0 };
|
||||
} else {
|
||||
effort = pick.send;
|
||||
run.model = resolved.id;
|
||||
sent = true;
|
||||
result = await this.sendFn(
|
||||
this.base,
|
||||
{ id: task.id, model: resolved.id },
|
||||
resolved.pin,
|
||||
effort,
|
||||
entry.abort.signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
result = { outcome: "failed", reason: errText(e), ms: 0 };
|
||||
}
|
||||
}
|
||||
run.effort = effort;
|
||||
|
||||
if (entry.cancel === "disabled") {
|
||||
run.outcome = "unknown";
|
||||
run.reason = DISABLED_REASON;
|
||||
} else if (entry.cancel === "deleted") {
|
||||
run.outcome = "unknown";
|
||||
run.reason = DELETED_REASON; // remove 随后会清掉它,进程若在这里崩掉也能对上账
|
||||
} else {
|
||||
run.outcome = result.outcome;
|
||||
run.reason = result.reason;
|
||||
}
|
||||
run.ms = result.ms;
|
||||
run.endedAt = this.nowFn().toISOString();
|
||||
// 收尾与删除竞态的最后一道闸:任务已不在就什么都不写
|
||||
if (!this.store.data.tasks.some((t) => t.id === task.id)) return;
|
||||
// 真正发出去(含结果未知)就算开过窗:此前的空闲读数作废,并排一次发送后的重读
|
||||
const opened = sent && !entry.cancel && result.outcome !== "failed" && task.trigger.kind === "window";
|
||||
if (opened) this.marksOf(task.id).lastSent = run.endedAt;
|
||||
await this.trackSave();
|
||||
if (opened) this.rearm();
|
||||
} finally {
|
||||
this.inflight.delete(task.id);
|
||||
}
|
||||
}
|
||||
|
||||
private appendFailure(
|
||||
task: Task,
|
||||
at: Date,
|
||||
due: Date | null,
|
||||
reason: string,
|
||||
resetKey: string | null,
|
||||
source: Run["source"],
|
||||
): Run {
|
||||
const run: Run = {
|
||||
...newRun(task, at, due, source, resetKey),
|
||||
endedAt: at.toISOString(),
|
||||
outcome: "failed",
|
||||
reason,
|
||||
ms: 0,
|
||||
};
|
||||
this.store.data.runs.push(run);
|
||||
this.trackSave();
|
||||
return run;
|
||||
}
|
||||
|
||||
/** 重排唯一定时器:延迟 = min(各任务最近到期 − now, 10 分钟);窗口任务没算得出到期点时按刷新节奏回头 */
|
||||
private rearm(): void {
|
||||
if (this.cancelTimer) {
|
||||
this.cancelTimer();
|
||||
this.cancelTimer = null;
|
||||
}
|
||||
this.armedFor = new Map();
|
||||
if (!this.started) return;
|
||||
this.recordResets(); // 新建/编辑的窗口任务要赶在下一次额度刷新前记下当前重置点
|
||||
const now = this.nowFn();
|
||||
let minDelay = Infinity;
|
||||
for (const task of this.store.data.tasks) {
|
||||
if (!task.enabled) continue;
|
||||
if (task.trigger.kind === "window") {
|
||||
const settled = this.lastSentMs(task) + POST_SEND_SETTLE_MS;
|
||||
if (settled > now.getTime()) minDelay = Math.min(minDelay, settled - now.getTime());
|
||||
const due = this.currentWindowDue(task, now);
|
||||
if (due && due.at.getTime() > now.getTime()) {
|
||||
minDelay = Math.min(minDelay, due.at.getTime() - now.getTime());
|
||||
} else if (due && this.windowReady(task, due, now) && this.snapshotFresh(now)) {
|
||||
// 空闲窗口、本轮没发过、快照新鲜:立即唤醒去发(每小时最多一次,evaluateWindow 去重)。
|
||||
// 快照过期时不走这条——先等一轮刷新,拿新数据再决定,免得按旧快照白发
|
||||
minDelay = Math.min(minDelay, 0);
|
||||
} else {
|
||||
// 拿不到到期点(无快照/出错/刚发过):按刷新节奏回头再看(从未取到过快照时尽快取一次)
|
||||
minDelay = Math.min(minDelay, this.quotaTried ? QUOTA_REFRESH_MS : 0);
|
||||
}
|
||||
} else {
|
||||
// 已执行点之后、编辑点之后的第一个到期点才有效,否则会围着作废点空转
|
||||
const base = new Date(this.fixedConsumedUntil(task));
|
||||
let due: Date;
|
||||
try {
|
||||
due =
|
||||
task.trigger.kind === "daily" ? nextDaily(task.trigger, base) : nextEvery(task.trigger, base);
|
||||
} catch {
|
||||
// 单个坏任务(如时区库变更)不能打断重排——整个定时器排不出来等于调度停摆;
|
||||
// 它的失败已由 tick 的评估记录,这里跳过即可
|
||||
continue;
|
||||
}
|
||||
if (due.getTime() > now.getTime()) {
|
||||
this.armedFor.set(task.id, due);
|
||||
minDelay = Math.min(minDelay, due.getTime() - now.getTime());
|
||||
} else {
|
||||
// 已过期的应到点(服务中断/睡眠):立即唤醒去补发评估
|
||||
minDelay = Math.min(minDelay, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Number.isFinite(minDelay)) {
|
||||
const delay = Math.min(Math.max(minDelay, 0), TIMER_CAP_MS);
|
||||
this.cancelTimer = this.setTimerFn(() => {
|
||||
void this.queueOp(() => this.tick()).catch(() => {});
|
||||
}, delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
// 本地页面服务:只监听 127.0.0.1,照搬 chat 的防护模型。
|
||||
// - 每进程随机 32 字节 token,经首页 HTML 的 boot 数据块注入,/api/* 全部要求带它;
|
||||
// Origin 只认缺失、"null"(sandbox 框架)或自身,Host 只认本服务实际绑定的端口
|
||||
// (防 DNS 重绑定)。首页响应带 CSP,页面数据一律 textContent 渲染。
|
||||
// - store 损坏 → fatal:服务照起让页面显示原因,但绝不启动调度、拒绝一切写操作。
|
||||
// - 单实例锁被别人持有 → lockedBy:页面只读展示,同样不启动调度。
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path, { basename, extname, join, resolve } from "node:path";
|
||||
import { fetchCatalog } from "./gateway";
|
||||
import { validateTask } from "./rules";
|
||||
import { Scheduler, CONFLICT_MESSAGE, NOT_FOUND_MESSAGE, type TaskInput } from "./scheduler";
|
||||
import { acquireLock, openStore, StoreError, type Store } from "./store";
|
||||
import { errText } from "./types";
|
||||
|
||||
/** 页面请求 /api/* 用的口令头 */
|
||||
export const TOKEN_HEADER = "x-window-warmup-token";
|
||||
/** 本插件服务的自标记响应头:所有响应都带,识别「这是窗口预热的服务」 */
|
||||
export const MARKER_HEADER = "x-window-warmup";
|
||||
/** 启动前探测已有实例的超时:挂着不响应的服务按「不是本插件」处理 */
|
||||
const PROBE_TIMEOUT_MS = 2_000;
|
||||
/** JSON 请求体上限:任务字段都很小,超限必然不是页面发的 */
|
||||
const BODY_LIMIT = 64 * 1024;
|
||||
|
||||
/**
|
||||
* 探测端口上有没有本插件的服务在应答(所有响应都带 MARKER_HEADER)。
|
||||
* plugin.ts 启动前用它识别「已经在跑」;锁冲突时用它确认持有者是否真在服务。
|
||||
*/
|
||||
export async function alreadyServing(port: number): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${port}/`, {
|
||||
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
|
||||
});
|
||||
return res.headers.get(MARKER_HEADER) === "1";
|
||||
} catch {
|
||||
return false; // 没人听或探测不通:按未运行处理
|
||||
}
|
||||
}
|
||||
|
||||
export interface ServiceOptions {
|
||||
/** 监听端口;0 = 让系统挑空闲端口(测试用) */
|
||||
port: number;
|
||||
/** 数据目录(state.json 与 service.lock 所在) */
|
||||
dir: string;
|
||||
/** Magpie 网关地址 */
|
||||
base: string;
|
||||
/** 界面静态文件目录;缺省按运行位置解析(源码态 ../dist/ui,构建产物态 ./ui) */
|
||||
uiDir?: string;
|
||||
/** 锁冲突时的持有者确认,仅测试注入;缺省探测本服务端口上有无本插件在应答 */
|
||||
confirmLockAlive?: (pid: number) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface ServiceHandle {
|
||||
/** 实际绑定端口(port 0 时由系统分配) */
|
||||
port: number;
|
||||
/** 停止:先停排程、等发送收尾,再释放单实例锁,最后关 HTTP */
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
function json(data: unknown, status = 200, headers: Record<string, string> = {}): Response {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status,
|
||||
headers: { "content-type": "application/json; charset=utf-8", ...headers },
|
||||
});
|
||||
}
|
||||
|
||||
const MIME: Record<string, string> = {
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".html": "text/html; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".woff2": "font/woff2",
|
||||
};
|
||||
|
||||
async function readBody(req: Request): Promise<unknown> {
|
||||
// 边读边计数:超限立即取消读取,不先把整个请求体收进内存
|
||||
let text = "";
|
||||
if (req.body) {
|
||||
const decoder = new TextDecoder();
|
||||
const reader = req.body.getReader();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
text += decoder.decode(value, { stream: true });
|
||||
if (text.length > BODY_LIMIT) {
|
||||
await reader.cancel().catch(() => {});
|
||||
throw new Error("请求体太大");
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error("请求不是合法的 JSON");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* file 是否落在 root 目录之内(不含 root 自身)。
|
||||
* 不能拼 `${root}/` 比前缀:Windows 上 resolve 出来是反斜杠,所有静态文件都会被误判越界而 404。
|
||||
*/
|
||||
export function insideDir(root: string, file: string, p: typeof path = path): boolean {
|
||||
const rel = p.relative(root, file);
|
||||
return rel !== "" && !rel.startsWith("..") && !p.isAbsolute(rel);
|
||||
}
|
||||
|
||||
export async function startService(opts: ServiceOptions): Promise<ServiceHandle> {
|
||||
const uiDir =
|
||||
opts.uiDir ??
|
||||
resolve(import.meta.dir, basename(import.meta.dir) === "src" ? "../dist/ui" : "ui");
|
||||
|
||||
// 打开状态文件:损坏不抛给宿主,而是进 fatal 态(页面显示原因,调度与写接口全关)
|
||||
let fatal: string | null = null;
|
||||
let store: Store | undefined;
|
||||
try {
|
||||
store = await openStore(opts.dir);
|
||||
} catch (e) {
|
||||
if (e instanceof StoreError) fatal = e.message;
|
||||
else throw e;
|
||||
}
|
||||
|
||||
let scheduler: Scheduler | null = null;
|
||||
let lockRelease: (() => Promise<void>) | null = null;
|
||||
let lockedBy: number | null = null;
|
||||
if (!fatal && store) {
|
||||
const lock = await acquireLock(opts.dir, {
|
||||
// pid 活 ≠ 持有者真在跑:容器/整机重启后 pid 常被无关进程复用(比如 magpie 自己),
|
||||
// 持久卷上的旧锁就成了假阳性,服务会错误进入只读、调度停摆。持有者必须
|
||||
// 真的在应答本插件的标记头才认,否则按陈旧锁接管。
|
||||
confirmAlive: opts.confirmLockAlive ?? (() => alreadyServing(opts.port)),
|
||||
});
|
||||
if (lock.ok) lockRelease = lock.release;
|
||||
else lockedBy = lock.pid; // pid 0 = 持有者身份无法判断
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("hex");
|
||||
let stopped = false;
|
||||
|
||||
let server: ReturnType<typeof Bun.serve>;
|
||||
try {
|
||||
server = Bun.serve({
|
||||
hostname: "127.0.0.1",
|
||||
port: opts.port,
|
||||
async fetch(req: Request): Promise<Response> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await handle(req);
|
||||
} catch (e) {
|
||||
// 兜底错误也要带 CORS:否则沙箱页只看到 Failed to fetch,读不到原因
|
||||
res = json({ error: errText(e) }, 500, corsHeaders(req.headers.get("origin")));
|
||||
}
|
||||
// 所有响应都带自标记:plugin.ts 启动前探测它,识别「本插件已在运行」
|
||||
res.headers.set(MARKER_HEADER, "1");
|
||||
return res;
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
await lockRelease?.(); // 端口被占等绑定失败:把刚抢到的锁还回去
|
||||
throw e;
|
||||
}
|
||||
|
||||
// HTTP 起好才启动调度;锁不是自己的就不调度
|
||||
if (!fatal && store && lockedBy === null) {
|
||||
scheduler = new Scheduler({ store, base: opts.base });
|
||||
scheduler.start();
|
||||
}
|
||||
|
||||
const ownOrigins = (): string[] => [
|
||||
`http://127.0.0.1:${server.port}`,
|
||||
`http://localhost:${server.port}`,
|
||||
];
|
||||
|
||||
function tokenOK(got: string | null): boolean {
|
||||
const a = Buffer.from(got ?? "");
|
||||
const b = Buffer.from(token);
|
||||
return a.length === b.length && timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
// 响应侧 CORS(照 chat):magpie 的插件页跑在 sandbox="allow-scripts" 框架里,
|
||||
// origin 是 opaque,对 http://127.0.0.1:port 的取回全是跨源请求——API 与非 index
|
||||
// 静态资源的响应没有 ACAO,浏览器直接拦掉 body,页面什么都读不到。
|
||||
// Origin 缺失或 "null" 时给 "null",自身来源则原样反射。
|
||||
function corsHeaders(origin: string | null): Record<string, string> {
|
||||
const allow = origin && ownOrigins().includes(origin) ? origin : "null";
|
||||
return {
|
||||
"access-control-allow-origin": allow,
|
||||
"access-control-allow-headers": `content-type, ${TOKEN_HEADER}`,
|
||||
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
|
||||
vary: "Origin",
|
||||
"cache-control": "no-store",
|
||||
};
|
||||
}
|
||||
|
||||
function guardedState(): unknown {
|
||||
if (fatal !== null) {
|
||||
return { fatal, tasks: [], runs: [], next: {}, timeline: [], saveError: null };
|
||||
}
|
||||
if (lockedBy !== null) {
|
||||
return { lockedBy, tasks: [], runs: [], next: {}, timeline: [], saveError: null };
|
||||
}
|
||||
return scheduler!.snapshot();
|
||||
}
|
||||
|
||||
/** 调度器抛错 → HTTP 状态码;未知错误一律 400 带原因 */
|
||||
function opError(e: unknown, cors: Record<string, string>): Response {
|
||||
const msg = errText(e);
|
||||
if (msg === NOT_FOUND_MESSAGE) return json({ error: msg }, 404, cors);
|
||||
if (msg === CONFLICT_MESSAGE) return json({ error: msg }, 409, cors);
|
||||
return json({ error: msg }, 400, cors);
|
||||
}
|
||||
|
||||
/** 请求体读不出来是客户端的事:太大/不是 JSON 记 400,不落到外层兜底 500 */
|
||||
async function readBodyChecked(
|
||||
req: Request,
|
||||
cors: Record<string, string>,
|
||||
): Promise<{ value: unknown } | { error: Response }> {
|
||||
try {
|
||||
return { value: await readBody(req) };
|
||||
} catch (e) {
|
||||
return { error: json({ error: errText(e) }, 400, cors) };
|
||||
}
|
||||
}
|
||||
|
||||
function readonlyBlock(cors: Record<string, string>): Response | null {
|
||||
if (fatal !== null) {
|
||||
return json({ error: `服务处于故障状态,先修复数据文件:${fatal}` }, 503, cors);
|
||||
}
|
||||
if (lockedBy !== null) {
|
||||
const who = lockedBy > 0 ? `(进程 ${lockedBy})` : "";
|
||||
return json({ error: `另一个实例正在运行${who},本页只读` }, 503, cors);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 新建(id 缺省)或全量更新任务:读请求体 → 校验 → 交给调度器 */
|
||||
async function saveTask(
|
||||
req: Request,
|
||||
cors: Record<string, string>,
|
||||
id: string | undefined,
|
||||
): Promise<Response> {
|
||||
const input = await readBodyChecked(req, cors);
|
||||
if ("error" in input) return input.error;
|
||||
const checked = validateTask(input.value, new Date());
|
||||
if ("error" in checked) return json({ error: checked.error, field: checked.field }, 400, cors);
|
||||
const task: TaskInput = id === undefined ? checked.task : { ...checked.task, id };
|
||||
try {
|
||||
return json(await scheduler!.upsert(task), 200, cors);
|
||||
} catch (e) {
|
||||
return opError(e, cors);
|
||||
}
|
||||
}
|
||||
|
||||
async function api(req: Request, url: URL, origin: string | null): Promise<Response> {
|
||||
// 每个 API 响应(含错误)都必须带 CORS:magpie 的插件页跑在 sandbox 框架里,
|
||||
// origin 是 opaque,浏览器发来的 Origin 是字面量 "null",对 http://127.0.0.1:port
|
||||
// 的 fetch 全是跨源请求——响应没有 ACAO,页面连错误信息都读不到。
|
||||
const cors = corsHeaders(origin);
|
||||
const path = url.pathname;
|
||||
if (req.method === "GET" && path === "/api/state") return json(guardedState(), 200, cors);
|
||||
if (req.method === "GET" && path === "/api/catalog") {
|
||||
try {
|
||||
return json(await fetchCatalog(opts.base), 200, cors);
|
||||
} catch (e) {
|
||||
return json({ error: errText(e) }, 502, cors);
|
||||
}
|
||||
}
|
||||
const blocked = readonlyBlock(cors);
|
||||
if (blocked) return blocked;
|
||||
const runMatch = /^\/api\/tasks\/([^/]+)\/run$/.exec(path);
|
||||
const idMatch = /^\/api\/tasks\/([^/]+)$/.exec(path);
|
||||
if (path === "/api/tasks" && req.method === "POST") return saveTask(req, cors, undefined);
|
||||
if (idMatch && req.method === "PUT") return saveTask(req, cors, decodeURIComponent(idMatch[1]));
|
||||
if (idMatch && req.method === "DELETE") {
|
||||
try {
|
||||
await scheduler!.remove(decodeURIComponent(idMatch[1]));
|
||||
} catch (e) {
|
||||
return opError(e, cors);
|
||||
}
|
||||
return json({ ok: true }, 200, cors);
|
||||
}
|
||||
if (runMatch && req.method === "POST") {
|
||||
try {
|
||||
return json(await scheduler!.runNow(decodeURIComponent(runMatch[1])), 200, cors);
|
||||
} catch (e) {
|
||||
return opError(e, cors);
|
||||
}
|
||||
}
|
||||
return json({ error: `没有这个接口:${path}` }, 404, cors);
|
||||
}
|
||||
|
||||
async function serveIndex(req: Request, url: URL): Promise<Response> {
|
||||
const nonce = randomBytes(16).toString("base64");
|
||||
// token 与主题一起进 boot 数据块;JSON 里的 < 转义掉,杜绝提前闭合脚本标签。
|
||||
// lang 透传给页面跟随 magpie 的界面语言;只放行字母与连字符(BCP-47 标签的形态),
|
||||
// 其余字符一律不带,异常值交给页面回退中文。
|
||||
const bootData: Record<string, string> = {
|
||||
token,
|
||||
theme: url.searchParams.get("theme") ?? "",
|
||||
tokens: url.searchParams.get("tokens") ?? "",
|
||||
};
|
||||
const lang = url.searchParams.get("lang") ?? "";
|
||||
if (/^[a-zA-Z-]{2,10}$/.test(lang)) bootData.lang = lang;
|
||||
const boot = JSON.stringify(bootData).replaceAll("<", "\\u003c");
|
||||
let html: string;
|
||||
try {
|
||||
html = await readFile(join(uiDir, "index.html"), "utf8");
|
||||
} catch {
|
||||
html =
|
||||
"<!doctype html><title>窗口预热</title><p>界面还没构建:先在包目录运行 bun run build。</p>";
|
||||
}
|
||||
html = html.replace(
|
||||
"</head>",
|
||||
`<script type="application/json" id="boot" nonce="${nonce}">${boot}</script>\n</head>`,
|
||||
);
|
||||
// connect-src 不能只写 'self':页面在 sandbox 框架里是 opaque origin,WebKit(iOS / macOS
|
||||
// Safari、经 magpie web 打开的 PWA)的 'self' 什么都匹配不上,/api/* 全被 CSP 拦掉;
|
||||
// Chromium 按 URL 匹配所以没事。经 magpie web 转发时 Host 已被改成 127.0.0.1,服务端
|
||||
// 也无从得知页面的真实地址,只能放宽到 http/https。脚本仍只认 nonce 与本服务自身,
|
||||
// 渲染一律 textContent,放宽 connect-src 不额外打开注入口。
|
||||
const headers = {
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
"referrer-policy": "no-referrer",
|
||||
"x-content-type-options": "nosniff",
|
||||
"content-security-policy":
|
||||
`default-src 'self'; script-src 'self' 'nonce-${nonce}'; ` +
|
||||
"connect-src 'self' http: https:; frame-ancestors *",
|
||||
};
|
||||
// HEAD 只给头不带体(安全头与 GET 一致),语义上不把整页带上
|
||||
return new Response(req.method === "HEAD" ? null : html, { headers });
|
||||
}
|
||||
|
||||
async function serveStatic(req: Request, url: URL, origin: string | null): Promise<Response> {
|
||||
// 非 index 的静态资源照 chat 带 CORS:页面是 opaque origin 时,
|
||||
// type="module" 的脚本固定以 CORS 模式获取,没有 ACAO 连 app.js 都加载不了。
|
||||
const cors = corsHeaders(origin);
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
return json({ error: "方法不支持" }, 405, cors);
|
||||
}
|
||||
// index 里带着口令,绝不能带 CORS——别的页面读不到它
|
||||
if (url.pathname === "/" || url.pathname === "/index.html") return serveIndex(req, url);
|
||||
const decoded = decodeURIComponent(url.pathname);
|
||||
const root = resolve(uiDir);
|
||||
const file = resolve(root, `.${decoded}`);
|
||||
if (!insideDir(root, file) || decoded.includes("..")) {
|
||||
return new Response("没有这个文件", { status: 404, headers: cors });
|
||||
}
|
||||
const asset = Bun.file(file);
|
||||
if (!(await asset.exists())) return new Response("没有这个文件", { status: 404, headers: cors });
|
||||
return new Response(asset, {
|
||||
headers: {
|
||||
"content-type": MIME[extname(file)] ?? "application/octet-stream",
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
...cors,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function handle(req: Request): Promise<Response> {
|
||||
const url = new URL(req.url);
|
||||
const own = `127.0.0.1:${server.port}`;
|
||||
const host = (req.headers.get("host") ?? "").toLowerCase();
|
||||
// 端口 0 时必须用实际绑定端口校验,Host 头张冠李戴直接拒绝(DNS 重绑定防护)
|
||||
if (host !== own && host !== `localhost:${server.port}`) {
|
||||
return new Response("只服务于本机页面", { status: 403 });
|
||||
}
|
||||
const origin = req.headers.get("origin");
|
||||
// magpie 页面跑在 sandbox 框架里,Origin 是字面量 "null";直接打开时是本服务自己
|
||||
if (origin && origin !== "null" && !ownOrigins().includes(origin)) {
|
||||
return json({ error: "只服务于 magpie 窗口里的页面" }, 403, corsHeaders(origin));
|
||||
}
|
||||
if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(origin) });
|
||||
if (url.pathname.startsWith("/api/")) {
|
||||
if (!tokenOK(req.headers.get(TOKEN_HEADER))) {
|
||||
return json({ error: "口令不对:请重新打开窗口预热页" }, 401, corsHeaders(origin));
|
||||
}
|
||||
return api(req, url, origin);
|
||||
}
|
||||
return serveStatic(req, url, origin);
|
||||
}
|
||||
|
||||
return {
|
||||
port: server.port ?? 0,
|
||||
async stop(): Promise<void> {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
scheduler?.stop();
|
||||
await scheduler?.flush();
|
||||
await lockRelease?.();
|
||||
server.stop(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
// 状态持久化与单实例锁。
|
||||
// - state.json 用「临时文件 + rename」原子落盘;打开时校验 JSON/version/结构,损坏即拒绝启动且绝不覆盖原文件。
|
||||
// - service.lock 用原子排他创建(link)+ pid 活性判断:持有者存活则不启动,确认已死才接管;
|
||||
// 活性不明(内容读不出/解析不了)一律不抢占。
|
||||
import { link, mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { xdgConfigHome } from "./magpie-files";
|
||||
import { errText, type Run, type Task } from "./types";
|
||||
|
||||
/** 每个任务保留的执行记录上限(超出丢最旧的) */
|
||||
const RUNS_PER_TASK = 50;
|
||||
/** 每个任务记住的 resetKey 上限(窗口去重用,超出丢最旧的) */
|
||||
const RESET_KEYS_PER_TASK = 20;
|
||||
const STATE_FILE = "state.json";
|
||||
const LOCK_FILE = "service.lock";
|
||||
/** 旧包(定时消息)的数据目录名;包改名为窗口预热后做一次性数据迁移 */
|
||||
const LEGACY_DIR_NAME = "scheduled-messages";
|
||||
|
||||
export class StoreError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "StoreError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface TaskMarks {
|
||||
/** 最近一次计划执行的到期点(ISO);窗口任务不用它 */
|
||||
lastDue: string | null;
|
||||
/** 已尝试过的窗口 resetKey(成功/失败/未知都算),最多留最近 20 个 */
|
||||
resetKeys: string[];
|
||||
/** 这个任务的窗口最近一次见到的重置时间(ISO):额度卡瞬断丢了 resetsAt 时,
|
||||
* 用它区分「窗口其实在计时」和「真空闲」;旧数据没有这个字段照常加载 */
|
||||
lastReset?: string | null;
|
||||
/** 窗口任务最近一次真正把消息发出去的收尾时刻(ISO):此前读到的空闲是发送前的旧读数,不可信 */
|
||||
lastSent?: string | null;
|
||||
}
|
||||
|
||||
export interface StateFile {
|
||||
version: 1;
|
||||
tasks: Task[];
|
||||
runs: Run[];
|
||||
marks: Record<string, TaskMarks>;
|
||||
}
|
||||
|
||||
export interface Store {
|
||||
readonly data: StateFile;
|
||||
/** 全量原子写入;并发调用在内部串行化,总是把最新内存状态写进文件 */
|
||||
save(): Promise<void>;
|
||||
}
|
||||
|
||||
function isStr(x: unknown): x is string {
|
||||
return typeof x === "string";
|
||||
}
|
||||
|
||||
function isStrOrNull(x: unknown): x is string | null {
|
||||
return x === null || typeof x === "string";
|
||||
}
|
||||
|
||||
function checkTask(t: unknown, at: string): string | null {
|
||||
if (typeof t !== "object" || t === null || Array.isArray(t)) {
|
||||
return `状态文件结构不对:${at} 必须是对象`;
|
||||
}
|
||||
const o = t as Record<string, unknown>;
|
||||
for (const k of ["id", "name", "provider", "account", "model", "message", "createdAt", "updatedAt"]) {
|
||||
if (!isStr(o[k])) return `状态文件结构不对:${at}.${k} 必须是字符串`;
|
||||
}
|
||||
if (typeof o.enabled !== "boolean") return `状态文件结构不对:${at}.enabled 必须是布尔值`;
|
||||
const trig = o.trigger;
|
||||
if (typeof trig !== "object" || trig === null || Array.isArray(trig)) {
|
||||
return `状态文件结构不对:${at}.trigger 必须是对象`;
|
||||
}
|
||||
const tv = trig as Record<string, unknown>;
|
||||
switch (tv.kind) {
|
||||
case "window":
|
||||
if (!isStr(tv.window)) return `状态文件结构不对:${at}.trigger.window 必须是字符串`;
|
||||
break;
|
||||
case "daily":
|
||||
if (!isStr(tv.time) || !/^([01]\d|2[0-3]):([0-5]\d)$/.test(tv.time)) {
|
||||
return `状态文件结构不对:${at}.trigger.time 需为 24 小时制 HH:MM`;
|
||||
}
|
||||
if (!isStr(tv.timeZone) || !tv.timeZone) {
|
||||
return `状态文件结构不对:${at}.trigger.timeZone 必须是字符串`;
|
||||
}
|
||||
break;
|
||||
case "every":
|
||||
if (typeof tv.hours !== "number" || !Number.isFinite(tv.hours) || tv.hours <= 0) {
|
||||
return `状态文件结构不对:${at}.trigger.hours 必须是正数`;
|
||||
}
|
||||
if (!isStr(tv.anchor) || Number.isNaN(new Date(tv.anchor).getTime())) {
|
||||
return `状态文件结构不对:${at}.trigger.anchor 必须是可识别的时间`;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return `状态文件结构不对:${at}.trigger.kind 必须是 window、daily 或 every`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkRun(r: unknown, at: string): string | null {
|
||||
if (typeof r !== "object" || r === null || Array.isArray(r)) {
|
||||
return `状态文件结构不对:${at} 必须是对象`;
|
||||
}
|
||||
const o = r as Record<string, unknown>;
|
||||
for (const k of ["id", "taskId", "startedAt"]) {
|
||||
if (!isStr(o[k])) return `状态文件结构不对:${at}.${k} 必须是字符串`;
|
||||
}
|
||||
if (o.source !== "schedule" && o.source !== "catchup" && o.source !== "manual") {
|
||||
return `状态文件结构不对:${at}.source 无法识别`;
|
||||
}
|
||||
if (o.outcome !== "ok" && o.outcome !== "failed" && o.outcome !== "unknown" && o.outcome !== "running") {
|
||||
return `状态文件结构不对:${at}.outcome 无法识别`;
|
||||
}
|
||||
if (!isStr(o.reason)) return `状态文件结构不对:${at}.reason 必须是字符串`;
|
||||
for (const k of ["due", "endedAt", "effort", "resetKey"]) {
|
||||
if (!isStrOrNull(o[k])) return `状态文件结构不对:${at}.${k} 必须是字符串或 null`;
|
||||
}
|
||||
// model 是改版新增字段:旧 state.json 的记录没有它,缺省按 null 加载,不得拒绝启动
|
||||
if (o.model !== undefined && !isStrOrNull(o.model)) {
|
||||
return `状态文件结构不对:${at}.model 必须是字符串或 null`;
|
||||
}
|
||||
if (o.ms !== null && typeof o.ms !== "number") {
|
||||
return `状态文件结构不对:${at}.ms 必须是数字或 null`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 返回错误描述(中文、带位置);null 表示结构完好 */
|
||||
function validateState(v: unknown): string | null {
|
||||
if (typeof v !== "object" || v === null || Array.isArray(v)) {
|
||||
return "状态文件结构不对:顶层必须是 JSON 对象";
|
||||
}
|
||||
const o = v as Record<string, unknown>;
|
||||
if (o.version !== 1) {
|
||||
return `状态文件版本不认识:${JSON.stringify(o.version) ?? "缺失"}(本程序只支持版本 1)`;
|
||||
}
|
||||
if (!Array.isArray(o.tasks)) return "状态文件结构不对:tasks 必须是数组";
|
||||
for (let i = 0; i < o.tasks.length; i++) {
|
||||
const problem = checkTask(o.tasks[i], `tasks[${i}]`);
|
||||
if (problem) return problem;
|
||||
}
|
||||
if (!Array.isArray(o.runs)) return "状态文件结构不对:runs 必须是数组";
|
||||
for (let i = 0; i < o.runs.length; i++) {
|
||||
const problem = checkRun(o.runs[i], `runs[${i}]`);
|
||||
if (problem) return problem;
|
||||
}
|
||||
const marks = o.marks;
|
||||
if (typeof marks !== "object" || marks === null || Array.isArray(marks)) {
|
||||
return "状态文件结构不对:marks 必须是对象";
|
||||
}
|
||||
for (const [id, value] of Object.entries(marks)) {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||
return `状态文件结构不对:marks.${id} 必须是对象`;
|
||||
}
|
||||
const m = value as Record<string, unknown>;
|
||||
if (!isStrOrNull(m.lastDue)) return `状态文件结构不对:marks.${id}.lastDue 必须是字符串或 null`;
|
||||
if (!Array.isArray(m.resetKeys) || m.resetKeys.some((k) => !isStr(k))) {
|
||||
return `状态文件结构不对:marks.${id}.resetKeys 必须是字符串数组`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 截断到上限:每任务最近 50 条 run、最近 20 个 resetKey,保持原有先后顺序 */
|
||||
function truncateState(data: StateFile): void {
|
||||
const counts = new Map<string, number>();
|
||||
const kept: Run[] = [];
|
||||
for (let i = data.runs.length - 1; i >= 0; i--) {
|
||||
const r = data.runs[i];
|
||||
const n = (counts.get(r.taskId) ?? 0) + 1;
|
||||
counts.set(r.taskId, n);
|
||||
if (n <= RUNS_PER_TASK) kept.push(r);
|
||||
}
|
||||
data.runs = kept.reverse();
|
||||
for (const m of Object.values(data.marks)) {
|
||||
if (m.resetKeys.length > RESET_KEYS_PER_TASK) m.resetKeys = m.resetKeys.slice(-RESET_KEYS_PER_TASK);
|
||||
}
|
||||
}
|
||||
|
||||
class StoreImpl implements Store {
|
||||
private writing: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(
|
||||
readonly data: StateFile,
|
||||
private readonly path: string,
|
||||
) {}
|
||||
|
||||
save(): Promise<void> {
|
||||
// 写入串行化,且 JSON.stringify 放进队列里执行:并发保存不会交错临时文件,
|
||||
// 后一次总是带走前一次已落进内存的改动(防写入丢失);顺带截断,常驻进程内存不无界增长。
|
||||
// 注意没有 fsync:进程崩溃靠 rename 的原子性兜底,断电极端情况可能留下空/半截文件,
|
||||
// openStore 会拒绝启动并保留原样,由用户手动处理(已知边界,见包 README「数据在哪」)。
|
||||
const next = this.writing.then(async () => {
|
||||
truncateState(this.data);
|
||||
const tmp = `${this.path}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(this.data), { mode: 0o600 });
|
||||
await rename(tmp, this.path);
|
||||
});
|
||||
this.writing = next.then(() => {}, () => {});
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开数据目录里的 state.json:没有就给全新状态;
|
||||
* JSON/version/结构任一损坏 → StoreError(含中文原因),原文件一个字节都不动。
|
||||
*/
|
||||
export async function openStore(dir: string): Promise<Store> {
|
||||
await mkdir(dir, { recursive: true, mode: 0o700 });
|
||||
const path = join(dir, STATE_FILE);
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(path, "utf8");
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return new StoreImpl({ version: 1, tasks: [], runs: [], marks: {} }, path);
|
||||
}
|
||||
throw new StoreError(`状态文件读不出来:${errText(e)}`);
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch (e) {
|
||||
throw new StoreError(`状态文件不是合法的 JSON:${errText(e)}`);
|
||||
}
|
||||
const problem = validateState(parsed);
|
||||
if (problem) throw new StoreError(problem);
|
||||
const data = parsed as StateFile;
|
||||
for (const r of data.runs) {
|
||||
if (r.model === undefined) r.model = null;
|
||||
}
|
||||
truncateState(data);
|
||||
return new StoreImpl(data, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧包(定时消息)的一次性数据迁移:新目录还没有 state.json 而旧目录有 → 把这一个文件
|
||||
* 复制过来(service.lock 属于旧目录的进程语义,绝不跟过来)。复制而非移动:旧文件保持
|
||||
* 原样,用户回退旧版也不丢数据;新目录已有 state.json 就什么都不做(哪怕它是坏的——
|
||||
* 坏文件该由 openStore 报给用户,不能被迁移悄悄盖掉)。条件本身保证了只做一次。
|
||||
*/
|
||||
export async function migrateLegacyState(
|
||||
dir: string,
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): Promise<void> {
|
||||
const statePath = join(dir, STATE_FILE);
|
||||
try {
|
||||
await readFile(statePath);
|
||||
return; // 新目录已有状态(含读不出权限问题的情形):一律不动
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") return;
|
||||
}
|
||||
const legacy = join(xdgConfigHome(env), "magpie", LEGACY_DIR_NAME, STATE_FILE);
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(legacy, "utf8");
|
||||
} catch {
|
||||
return; // 没有旧数据:无事发生
|
||||
}
|
||||
await mkdir(dir, { recursive: true, mode: 0o700 });
|
||||
// 复制失败不挡启动:旧数据仍在原处,下次启动(state.json 仍缺)还有机会
|
||||
await writeFile(statePath, raw, { mode: 0o600 }).catch(() => {});
|
||||
}
|
||||
|
||||
function parsePid(raw: string): number | null {
|
||||
const t = raw.trim();
|
||||
if (/^\d+$/.test(t)) return Number(t);
|
||||
try {
|
||||
const j = JSON.parse(t) as unknown;
|
||||
if (typeof j === "object" && j !== null && typeof (j as { pid?: unknown }).pid === "number") {
|
||||
return (j as { pid: number }).pid;
|
||||
}
|
||||
} catch {
|
||||
/* 不是 JSON 也正常,锁内容就是裸 pid 文本 */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pidAlive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (e) {
|
||||
// EPERM 说明进程存在但属于别人,同样算活着
|
||||
return (e as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
}
|
||||
|
||||
/** 只在自己仍是持有者时删除锁文件;锁已被别人接管/换内容时不动它 */
|
||||
async function releaseLock(path: string): Promise<void> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(path, "utf8");
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (parsePid(raw) === process.pid) await unlink(path).catch(() => {});
|
||||
}
|
||||
|
||||
export type LockResult = { ok: true; release: () => Promise<void> } | { ok: false; pid: number };
|
||||
|
||||
export interface AcquireLockOptions {
|
||||
/**
|
||||
* 锁冲突且 pid 存活时的二次确认:持有者是否真的在服务。
|
||||
* 容器/整机重启后 pid 会被无关进程复用,持久卷上的旧锁就成了假阳性——
|
||||
* 只有确认不过的才当陈旧锁接管;不传则维持原行为(pid 活着就算被占)。
|
||||
*/
|
||||
confirmAlive?: (pid: number) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 原子排他创建 service.lock(写入本进程 pid):
|
||||
* - 已存在且持有者确认在服务 → {ok:false, pid}
|
||||
* - 已存在且 pid 确认不存在,或 pid 被复用但确认不过(持有者并未在服务)→ 接管(删旧文件重抢)
|
||||
* - 已存在但内容读不出/解析不了(活性不明)→ 不抢占,{ok:false, pid:0}
|
||||
*/
|
||||
export async function acquireLock(dir: string, opts: AcquireLockOptions = {}): Promise<LockResult> {
|
||||
await mkdir(dir, { recursive: true, mode: 0o700 });
|
||||
const path = join(dir, LOCK_FILE);
|
||||
// 上一次持有者在 writeFile 与 link 之间崩溃会留下 *.tmp 残骸,永不自清;入口顺带扫掉
|
||||
const leftovers = await readdir(dir).catch(() => [] as string[]);
|
||||
for (const name of leftovers) {
|
||||
if (/^service\.lock\.\d+\.[0-9a-f-]+\.tmp$/.test(name)) {
|
||||
await unlink(join(dir, name)).catch(() => {});
|
||||
}
|
||||
}
|
||||
for (let round = 0; round < 3; round++) {
|
||||
const tmp = join(dir, `${LOCK_FILE}.${process.pid}.${randomUUID()}.tmp`);
|
||||
await writeFile(tmp, String(process.pid), { mode: 0o600 });
|
||||
try {
|
||||
await link(tmp, path);
|
||||
await unlink(tmp).catch(() => {});
|
||||
return { ok: true, release: () => releaseLock(path) };
|
||||
} catch (e) {
|
||||
await unlink(tmp).catch(() => {});
|
||||
if ((e as NodeJS.ErrnoException).code !== "EEXIST") {
|
||||
throw new Error(`无法创建单实例锁:${errText(e)}`);
|
||||
}
|
||||
}
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(path, "utf8");
|
||||
} catch (e) {
|
||||
// 上一持有者刚好 release、锁文件已消失:回循环顶重抢,而不是误报「另一实例运行中」
|
||||
if ((e as NodeJS.ErrnoException).code === "ENOENT") continue;
|
||||
return { ok: false, pid: 0 };
|
||||
}
|
||||
const pid = parsePid(raw);
|
||||
if (pid === null) return { ok: false, pid: 0 };
|
||||
if (pidAlive(pid)) {
|
||||
const confirmed = opts.confirmAlive ? await opts.confirmAlive(pid) : true;
|
||||
if (confirmed) return { ok: false, pid };
|
||||
// pid 被复用而持有者并未在服务:不认这把锁,落到下面的接管路径
|
||||
}
|
||||
try {
|
||||
await unlink(path);
|
||||
} catch {
|
||||
/* 可能刚被别人接管,下一轮重试 */
|
||||
}
|
||||
}
|
||||
throw new Error("单实例锁被占用且无法接管");
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// 窗口预热插件的共享数据类型,外加各层(含浏览器端页面)都要用的极少量无依赖小工具。
|
||||
|
||||
/** 异常转人话原因:Error 取 message,其余原样转字符串 */
|
||||
export function errText(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
export type Trigger =
|
||||
| { kind: "window"; window: string } // 额度窗口名,如 "5h"
|
||||
| { kind: "daily"; time: string; timeZone: string } // "HH:MM" + IANA 时区
|
||||
| { kind: "every"; hours: number; anchor: string }; // 1–168 小时,anchor 为 ISO 起点
|
||||
|
||||
export interface Task {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
provider: string;
|
||||
/** key 指纹或订阅账号名,新建/编辑时必填;"" 只会出现在旧版本存下的任务里(发送时不带账号头) */
|
||||
account: string;
|
||||
/** "" 表示自动选模型:每次发送前按 pickAutoModel 现算,任务里不存选中值 */
|
||||
model: string;
|
||||
/** 恒为 "hi"(探活消息固定,字段只为旧数据保留) */
|
||||
message: string;
|
||||
trigger: Trigger;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type Outcome = "ok" | "failed" | "unknown";
|
||||
|
||||
export interface Run {
|
||||
id: string;
|
||||
taskId: string;
|
||||
source: "schedule" | "catchup" | "manual";
|
||||
due: string | null;
|
||||
startedAt: string;
|
||||
endedAt: string | null;
|
||||
/** "running" 只存在于发送中途的落盘记录 */
|
||||
outcome: Outcome | "running";
|
||||
/** 失败/未知时必须是人能看懂的中文原因 */
|
||||
reason: string;
|
||||
/** 当次实际使用的思考档位;模型不思考或不适用时为 null */
|
||||
effort: string | null;
|
||||
/** 当次实际使用的模型 id;固定模型即任务所配,自动选择即当次选中,解析不出来为 null */
|
||||
model: string | null;
|
||||
ms: number | null;
|
||||
resetKey: string | null;
|
||||
}
|
||||
|
||||
export type EffortPick = { send: string | null; label: string } | { error: string };
|
||||
|
||||
/** send() 的结果;失败/未知时 reason 必须是人能看懂的中文 */
|
||||
export interface SendResult {
|
||||
outcome: Outcome;
|
||||
reason: string;
|
||||
ms: number;
|
||||
}
|
||||
|
||||
export interface QuotaWindow {
|
||||
name: string;
|
||||
used: number | null;
|
||||
resetsAt: string | null;
|
||||
}
|
||||
|
||||
export interface QuotaEntry {
|
||||
provider: string;
|
||||
account: string;
|
||||
label: string;
|
||||
windows: QuotaWindow[];
|
||||
/** true = 远程 Magpie 给单把 key 发的限额卡(原 provider 形如 "<p>/~keys",user 是 key 名或打码) */
|
||||
viaKey: boolean;
|
||||
/** magpie 上次向上游读这张卡的时刻(ISO);旧版 magpie 不给 */
|
||||
readAt?: string;
|
||||
}
|
||||
|
||||
/** /v1/models 的单条原始对象;档位字段形状随模型而变,使用前需运行时校验 */
|
||||
export interface RawModel {
|
||||
id: string;
|
||||
owned_by?: string;
|
||||
reasoning?: boolean | string | null;
|
||||
reasoning_levels?: string[];
|
||||
supported_reasoning_levels?: { effort: string }[];
|
||||
}
|
||||
|
||||
export interface CatalogAccount {
|
||||
/** key 账号:key 指纹;订阅账号:额度卡 user */
|
||||
id: string;
|
||||
/** key 名(没起名用指纹)或账号名 */
|
||||
label: string;
|
||||
kind: "key" | "login";
|
||||
windows: QuotaWindow[];
|
||||
/** 该账号可选的模型(/v1/models 的完整 id,升序);null = 该供应商既无模型缓存、/v1/models 里也没有它的模型 */
|
||||
models: string[] | null;
|
||||
/** false = 没有模型缓存,models 是该供应商的全部模型(未按账号区分) */
|
||||
perAccount: boolean;
|
||||
/** 该账号的自动选模型;models 为 null 或空时为 null */
|
||||
autoModel: string | null;
|
||||
}
|
||||
|
||||
export interface CatalogModel {
|
||||
id: string;
|
||||
effort: EffortPick;
|
||||
}
|
||||
|
||||
export interface CatalogProvider {
|
||||
id: string;
|
||||
accounts: CatalogAccount[];
|
||||
models: CatalogModel[];
|
||||
/** 「自动选账号」的可选模型(完整 id,升序);null = 既无模型缓存也无 /v1/models 模型 */
|
||||
autoAccountModels: string[] | null;
|
||||
/** 「自动选账号」时的自动选模型 */
|
||||
autoModel: string | null;
|
||||
}
|
||||
|
||||
/** GET /api/catalog 的响应体 */
|
||||
export interface Catalog {
|
||||
providers: CatalogProvider[];
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
// 页面纯函数的测试:不碰 DOM、不发请求。
|
||||
// statusOf / trigText / 下拉选项构造 / 执行记录文案等由 web/app.ts 导出,界面渲染直接复用。
|
||||
import { expect, test } from "bun:test";
|
||||
import {
|
||||
accountHasWindows,
|
||||
accountModelView,
|
||||
accountOptions,
|
||||
contentOf,
|
||||
deleteArmed,
|
||||
DELETE_CONFIRM_MS,
|
||||
effortLabel,
|
||||
forceWindowAccount,
|
||||
modelDisplay,
|
||||
modelHint,
|
||||
modelOptions,
|
||||
nextLabel,
|
||||
nextPointsAfter,
|
||||
rowSub,
|
||||
runOutcome,
|
||||
runReason,
|
||||
runTimeLabel,
|
||||
shortModel,
|
||||
statusOf,
|
||||
shouldCloseOnScroll,
|
||||
sumView,
|
||||
syncDraftOnPoll,
|
||||
trigText,
|
||||
validateDraft,
|
||||
windowOptions,
|
||||
} from "../web/app";
|
||||
import type { CatalogAccount, CatalogProvider, Run, Task, Trigger } from "../src/types";
|
||||
|
||||
const T0 = new Date("2026-10-31T12:00:00+08:00"); // 周六 12:00,本地(nextLabel 看本地时间)
|
||||
|
||||
/** 假想的 key 指纹(10 位小写 hex),页面的 key 账号 id 都长这样 */
|
||||
const FP1 = "1a2b3c4d5e";
|
||||
const FP2 = "f0e1d2c3b4";
|
||||
|
||||
const p2 = (n: number): string => String(n).padStart(2, "0");
|
||||
|
||||
function mkTask(over: Partial<Task> = {}): Task {
|
||||
return {
|
||||
id: "t1",
|
||||
name: "早报",
|
||||
enabled: true,
|
||||
provider: "openai",
|
||||
account: "",
|
||||
model: "",
|
||||
message: "hi",
|
||||
trigger: { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" },
|
||||
createdAt: "2026-10-30T08:00:00+08:00",
|
||||
updatedAt: "2026-10-30T08:00:00+08:00",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function mkRun(over: Partial<Run> = {}): Run {
|
||||
return {
|
||||
id: "r1",
|
||||
taskId: "t1",
|
||||
source: "schedule",
|
||||
due: null,
|
||||
startedAt: "2026-10-31T06:00:00+08:00",
|
||||
endedAt: "2026-10-31T06:00:01+08:00",
|
||||
outcome: "ok",
|
||||
reason: "",
|
||||
effort: null,
|
||||
model: null,
|
||||
ms: 900,
|
||||
resetKey: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function mkProvider(over: Partial<CatalogProvider> = {}): CatalogProvider {
|
||||
return {
|
||||
id: "remote-magpie",
|
||||
accounts: [],
|
||||
models: [],
|
||||
autoAccountModels: null,
|
||||
autoModel: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function mkAccount(over: Partial<CatalogAccount> = {}): CatalogAccount {
|
||||
return {
|
||||
id: "a1",
|
||||
label: "a1",
|
||||
kind: "login",
|
||||
windows: [],
|
||||
models: null,
|
||||
perAccount: false,
|
||||
autoModel: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
test("statusOf:正常不显示文字 / 上次失败 / 上次结果未知 / 发送中 / 已停用", () => {
|
||||
expect(statusOf(mkTask(), [])).toEqual({ tone: "", text: "" });
|
||||
expect(statusOf(mkTask(), [mkRun({ outcome: "ok" })])).toEqual({ tone: "", text: "" });
|
||||
expect(statusOf(mkTask(), [mkRun({ outcome: "failed", reason: "HTTP 429" })])).toEqual({
|
||||
tone: "bad",
|
||||
text: "上次失败",
|
||||
});
|
||||
expect(statusOf(mkTask(), [mkRun({ outcome: "unknown", reason: "30 秒内没有结果" })])).toEqual({
|
||||
tone: "unk",
|
||||
text: "上次结果未知",
|
||||
});
|
||||
expect(statusOf(mkTask(), [mkRun({ outcome: "running", endedAt: null })])).toEqual({
|
||||
tone: "ok",
|
||||
text: "发送中",
|
||||
});
|
||||
expect(statusOf(mkTask({ enabled: false }), [mkRun()])).toEqual({ tone: "", text: "已停用" });
|
||||
// 只看该任务自己的记录
|
||||
expect(statusOf(mkTask(), [mkRun({ taskId: "other", outcome: "failed" })])).toEqual({
|
||||
tone: "",
|
||||
text: "",
|
||||
});
|
||||
// 记录按时间取最新:旧失败被新成功盖过
|
||||
expect(
|
||||
statusOf(mkTask(), [
|
||||
mkRun({ id: "r0", startedAt: "2026-10-31T05:00:00+08:00", outcome: "failed" }),
|
||||
mkRun({ outcome: "ok", startedAt: "2026-10-31T06:00:00+08:00" }),
|
||||
]),
|
||||
).toEqual({ tone: "", text: "" });
|
||||
});
|
||||
|
||||
test("失败不暂停:状态是上次失败,下次时间仍在", () => {
|
||||
const task = mkTask();
|
||||
const status = statusOf(task, [mkRun({ outcome: "failed", reason: "连不上 Magpie" })]);
|
||||
expect(status).toEqual({ tone: "bad", text: "上次失败" });
|
||||
expect(nextLabel("2026-11-01T06:00:00+08:00", T0)).not.toBe("—");
|
||||
expect(nextLabel(null, T0)).toBe("—");
|
||||
});
|
||||
|
||||
test("trigText:窗口 / 每天 / 固定间隔", () => {
|
||||
expect(trigText({ kind: "window", window: "5h" })).toBe("窗口 5h 重置后");
|
||||
expect(trigText({ kind: "daily", time: "06:00", timeZone: "UTC" })).toBe("每天 06:00");
|
||||
expect(trigText({ kind: "every", hours: 6, anchor: "2026-10-30T00:00:00Z" })).toBe("每 6 小时");
|
||||
});
|
||||
|
||||
test("shortModel / modelDisplay:取末段、剥供应商前缀", () => {
|
||||
expect(shortModel("remote-magpie/group/glm-5.3-flash")).toBe("glm-5.3-flash");
|
||||
expect(shortModel("gpt-5.2")).toBe("gpt-5.2");
|
||||
expect(modelDisplay("openai/gpt-5.2", "openai")).toBe("gpt-5.2");
|
||||
expect(modelDisplay("deepseek/deepseek-v4", "openai")).toBe("deepseek/deepseek-v4");
|
||||
expect(modelDisplay("gpt-5.2", "openai")).toBe("gpt-5.2");
|
||||
});
|
||||
|
||||
test("rowSub:账号显示目录里的 label,找不到(旧值/目录暂缺)用原值", () => {
|
||||
const providers = [
|
||||
mkProvider({ id: "openai", accounts: [mkAccount({ id: FP1, label: "主 Key", kind: "key" })] }),
|
||||
];
|
||||
expect(rowSub(mkTask({ provider: "openai", account: FP1, model: "openai/gpt-5.2-chat" }), providers)).toBe(
|
||||
"每天 06:00 · 主 Key · gpt-5.2-chat",
|
||||
);
|
||||
// 旧任务存的 key 名不在目录:原样显示,不改写
|
||||
expect(rowSub(mkTask({ provider: "openai", account: "sk-legacy" }), providers)).toBe(
|
||||
"每天 06:00 · sk-legacy · 自动选模型",
|
||||
);
|
||||
expect(rowSub(mkTask({ provider: "openai", account: "" }), providers)).toBe(
|
||||
"每天 06:00 · 自动选账号 · 自动选模型",
|
||||
);
|
||||
expect(rowSub(mkTask({ trigger: { kind: "window", window: "week" } }), providers)).toBe(
|
||||
"窗口 week 重置后 · 自动选账号 · 自动选模型",
|
||||
);
|
||||
// 目录整体暂缺:退回原值
|
||||
expect(rowSub(mkTask({ account: FP1 }), [])).toBe(`每天 06:00 · ${FP1} · 自动选模型`);
|
||||
});
|
||||
|
||||
test("runOutcome:成功灰、失败红、未知琥珀、发送中灰", () => {
|
||||
expect(runOutcome("ok")).toEqual({ text: "成功", tone: "" });
|
||||
expect(runOutcome("failed")).toEqual({ text: "失败", tone: "bad" });
|
||||
expect(runOutcome("unknown")).toEqual({ text: "未知", tone: "unk" });
|
||||
expect(runOutcome("running")).toEqual({ text: "发送中", tone: "" });
|
||||
});
|
||||
|
||||
test("runReason:成功拼模型/思考/耗时/来源,失败直接用原因", () => {
|
||||
expect(
|
||||
runReason(
|
||||
mkRun({
|
||||
outcome: "ok",
|
||||
model: "remote-magpie/group/glm-5.3-flash",
|
||||
effort: "low",
|
||||
ms: 1200,
|
||||
source: "schedule",
|
||||
}),
|
||||
),
|
||||
).toBe("已发送 · glm-5.3-flash · 思考 low · 1.2 秒 · 按计划");
|
||||
// 旧记录没有 model/effort/ms 时不留空段
|
||||
expect(runReason(mkRun({ outcome: "ok", source: "manual", ms: null }))).toBe("已发送 · 手动");
|
||||
expect(runReason(mkRun({ outcome: "ok", source: "catchup", ms: null, effort: null, model: null }))).toBe(
|
||||
"已发送 · 补发",
|
||||
);
|
||||
expect(runReason(mkRun({ outcome: "failed", reason: "HTTP 429:额度已用完" }))).toBe(
|
||||
"HTTP 429:额度已用完",
|
||||
);
|
||||
expect(runReason(mkRun({ outcome: "unknown", reason: "30 秒内没有结果" }))).toBe(
|
||||
"30 秒内没有结果",
|
||||
);
|
||||
});
|
||||
|
||||
test("runTimeLabel:今天 / 昨天 / 更早给 M/D", () => {
|
||||
const today = new Date("2026-10-31T13:36:00Z");
|
||||
expect(runTimeLabel("2026-10-31T13:36:00Z", T0)).toMatch(/^今天 \d{2}:\d{2}$/);
|
||||
expect(runTimeLabel("2026-10-30T13:36:00Z", T0)).toMatch(/^昨天 \d{2}:\d{2}$/);
|
||||
const older = new Date("2026-10-28T13:36:00Z");
|
||||
expect(runTimeLabel("2026-10-28T13:36:00Z", T0)).toBe(
|
||||
`${older.getMonth() + 1}/${older.getDate()} ${p2(older.getHours())}:${p2(older.getMinutes())}`,
|
||||
);
|
||||
expect(runTimeLabel("不是时间", T0)).toBe("—");
|
||||
});
|
||||
|
||||
test("nextLabel:今天 HH:MM / 明天 / M/D(取 UTC 与 +08 同日期的时刻,断言与测试机时区无关)", () => {
|
||||
expect(nextLabel("2026-10-31T06:00:00Z", T0)).toMatch(/^\d{2}:\d{2}$/);
|
||||
expect(nextLabel("2026-11-01T06:00:00Z", T0)).toMatch(/^明天 \d{2}:\d{2}$/);
|
||||
expect(nextLabel("2026-11-05T06:00:00Z", T0)).toMatch(/^11\/5 \d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
test("accountOptions:账号必选(无自动项);key 账号 label + 指纹附注;旧账号保留并标注", () => {
|
||||
const providers = [
|
||||
mkProvider({
|
||||
id: "remote-magpie",
|
||||
accounts: [
|
||||
mkAccount({ id: "acct-team", label: "acct-team" }),
|
||||
mkAccount({ id: FP1, label: "主 Key", kind: "key" }),
|
||||
mkAccount({ id: FP2, label: FP2, kind: "key" }), // 没起名的 key:label 就是指纹
|
||||
],
|
||||
}),
|
||||
];
|
||||
const opts = accountOptions("remote-magpie", "", providers);
|
||||
// 账号必选:空账号只给「请选择账号」占位,不再有自动项
|
||||
expect(opts[0]).toEqual({ value: "", text: "请选择账号" });
|
||||
expect(opts[1]).toEqual({ value: "acct-team", text: "acct-team" });
|
||||
expect(opts[2]).toEqual({ value: FP1, text: "主 Key", aux: FP1 });
|
||||
expect(opts[3]).toEqual({ value: FP2, text: FP2 });
|
||||
expect(opts.some((o) => o.text.includes("自动"))).toBe(false);
|
||||
|
||||
// 旧任务里的账号(key 名或已删除的账号)不在目录:保留原值不自动改写,标注「不在当前账号列表」
|
||||
const stale = accountOptions("remote-magpie", "sk-legacy", providers);
|
||||
expect(stale[0]).toEqual({ value: "sk-legacy", text: "sk-legacy(不在当前账号列表)" });
|
||||
});
|
||||
|
||||
test("accountModelView:指定账号用其列表;自动与目录暂缺的账号退回供应商全集", () => {
|
||||
const provider = mkProvider({
|
||||
id: "p",
|
||||
accounts: [
|
||||
mkAccount({ id: FP1, label: "主 Key", kind: "key", models: ["p/a"], autoModel: "p/a", perAccount: true }),
|
||||
mkAccount({ id: "acct-z", label: "acct-z", models: null, perAccount: false, autoModel: null }),
|
||||
],
|
||||
autoAccountModels: ["p/a", "p/b"],
|
||||
autoModel: "p/b",
|
||||
});
|
||||
expect(accountModelView(provider, FP1)).toEqual({ models: ["p/a"], autoModel: "p/a", perAccount: true });
|
||||
expect(accountModelView(provider, "acct-z")).toEqual({ models: null, autoModel: null, perAccount: false });
|
||||
expect(accountModelView(provider, "")).toEqual({ models: ["p/a", "p/b"], autoModel: "p/b", perAccount: null });
|
||||
// 目录暂缺的账号(旧任务存的名字):退回全集不禁用,此时无从判断是否按账号区分
|
||||
expect(accountModelView(provider, "sk-legacy")).toEqual({ models: ["p/a", "p/b"], autoModel: "p/b", perAccount: null });
|
||||
expect(accountModelView(undefined, "")).toEqual({ models: null, autoModel: null, perAccount: null });
|
||||
});
|
||||
|
||||
test("modelOptions:首项自动附注当前账号的自动模型;列表来自所选账号;旧值保留", () => {
|
||||
const providers = [
|
||||
mkProvider({
|
||||
id: "remote-magpie",
|
||||
accounts: [
|
||||
mkAccount({
|
||||
id: FP1,
|
||||
label: "主 Key",
|
||||
kind: "key",
|
||||
models: ["remote-magpie/glm-4.7"],
|
||||
autoModel: "remote-magpie/glm-4.7",
|
||||
perAccount: true,
|
||||
}),
|
||||
mkAccount({ id: "acct-z", label: "acct-z", models: null, perAccount: false, autoModel: null }),
|
||||
],
|
||||
autoAccountModels: [
|
||||
"remote-magpie/glm-4.7",
|
||||
"remote-magpie/glm-5.3",
|
||||
"remote-magpie/glm-5.3-flash",
|
||||
],
|
||||
autoModel: "remote-magpie/glm-5.3-flash",
|
||||
}),
|
||||
];
|
||||
const byAccount = modelOptions("remote-magpie", FP1, "", providers);
|
||||
expect(byAccount[0]).toEqual({ value: "", text: "自动", aux: "glm-4.7" });
|
||||
expect(byAccount.slice(1).map((o) => o.text)).toEqual(["glm-4.7"]);
|
||||
|
||||
// 自动账号用供应商全集,附注是供应商级的自动模型
|
||||
const autoAcct = modelOptions("remote-magpie", "", "", providers);
|
||||
expect(autoAcct[0].aux).toBe("glm-5.3-flash");
|
||||
expect(autoAcct.slice(1).map((o) => o.value)).toEqual([
|
||||
"remote-magpie/glm-4.7",
|
||||
"remote-magpie/glm-5.3",
|
||||
"remote-magpie/glm-5.3-flash",
|
||||
]);
|
||||
|
||||
// 已存模型不在当前账号列表:保留原值不自动改写(打开旧任务不重置,重置只发生在主动切换时)
|
||||
const stale = modelOptions("remote-magpie", FP1, "remote-magpie/gone", providers);
|
||||
expect(stale[1]).toEqual({ value: "remote-magpie/gone", text: "remote-magpie/gone" });
|
||||
|
||||
// 列表为 null:只有自动 + 旧值,渲染层据此禁用下拉并显示提示 B
|
||||
const none = modelOptions("remote-magpie", "acct-z", "remote-magpie/gone", providers);
|
||||
expect(none).toEqual([
|
||||
{ value: "", text: "自动" },
|
||||
{ value: "remote-magpie/gone", text: "remote-magpie/gone" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("windowOptions:账号的窗口带已用与重置附注;无账号 / 无窗口给占位", () => {
|
||||
const resetAt = new Date("2026-10-31T18:36:00+08:00");
|
||||
const providers = [
|
||||
mkProvider({
|
||||
id: "p",
|
||||
accounts: [
|
||||
mkAccount({
|
||||
id: "a1",
|
||||
label: "",
|
||||
windows: [
|
||||
{ name: "5h", used: 62, resetsAt: "2026-10-31T18:36:00+08:00" },
|
||||
{ name: "week", used: 30, resetsAt: null },
|
||||
{ name: "long", used: null, resetsAt: null },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
];
|
||||
const opts = windowOptions("p", "a1", "5h", providers);
|
||||
expect(opts[0]).toEqual({
|
||||
value: "5h",
|
||||
text: "5h",
|
||||
aux: `已用 62% · ${p2(resetAt.getHours())}:${p2(resetAt.getMinutes())} 重置`,
|
||||
});
|
||||
expect(opts[1].aux).toBe("已用 30% · 空闲");
|
||||
expect(opts[2].aux).toBe("空闲");
|
||||
expect(windowOptions("p", "", "", providers)).toEqual([{ value: "", text: "先选定账号" }]);
|
||||
expect(windowOptions("p", "a2", "", providers)).toEqual([{ value: "", text: "该账号没有窗口信息" }]);
|
||||
});
|
||||
|
||||
test("forceWindowAccount:窗口触发缺账号时取该供应商第一个账号", () => {
|
||||
const providers = [
|
||||
mkProvider({ id: "p1", accounts: [mkAccount({ id: "a1", label: "" })] }),
|
||||
mkProvider({ id: "p2", accounts: [] }),
|
||||
];
|
||||
expect(forceWindowAccount("p1", providers)).toBe("a1");
|
||||
expect(forceWindowAccount("p2", providers)).toBe("");
|
||||
expect(forceWindowAccount("nope", providers)).toBe("");
|
||||
});
|
||||
|
||||
test("modelHint:固定模型只给思考;自动按所选账号给自动选中;没有可用模型给提示", () => {
|
||||
const provider = mkProvider({
|
||||
id: "p",
|
||||
accounts: [
|
||||
mkAccount({ id: "acct-a", label: "acct-a", models: ["p/small"], autoModel: "p/small" }),
|
||||
],
|
||||
autoModel: "p/glm-5.3-flash",
|
||||
models: [
|
||||
{ id: "p/glm-5.3-flash", effort: { send: null, label: "不适用" } },
|
||||
{ id: "p/big", effort: { send: "low", label: "low(模型必须思考,已用最低档)" } },
|
||||
],
|
||||
});
|
||||
const fixed = modelHint("p/big", provider, "acct-a");
|
||||
expect(fixed.main).toBe("思考:low(模型必须思考,已用最低档)");
|
||||
expect(fixed.sub).toBe("思考档位按这个模型的配置自动决定:能关就关,不能关用最低档。");
|
||||
|
||||
const auto = modelHint("", provider, "");
|
||||
expect(auto.main).toBe("自动选中 glm-5.3-flash · 思考:不适用");
|
||||
expect(auto.sub).toBe(
|
||||
"名字带 flash / lite / mini 的小模型优先,每次发送前重新选;思考能关就关,不能关用最低档。",
|
||||
);
|
||||
// 指定账号的自动模型与供应商级不同,按账号的来
|
||||
const byAccount = modelHint("", provider, "acct-a");
|
||||
expect(byAccount.main).toBe("自动选中 small · 思考:目录里暂时没有这个模型");
|
||||
|
||||
const none = modelHint("", mkProvider({ id: "p2", autoModel: null }), "");
|
||||
expect(none.main).toBe("该供应商没有可用模型");
|
||||
// 指定了账号却选不出模型:归因到账号,不能写成整个供应商没有
|
||||
const emptyAccount = modelHint(
|
||||
"",
|
||||
mkProvider({
|
||||
id: "p3",
|
||||
accounts: [mkAccount({ id: "acct-b", label: "acct-b", models: [], autoModel: null })],
|
||||
autoModel: "p3/any",
|
||||
}),
|
||||
"acct-b",
|
||||
);
|
||||
expect(emptyAccount.main).toBe("这个账号没有可用模型");
|
||||
const missing = modelHint("p/gone", provider, "");
|
||||
expect(missing.main).toBe("思考:目录里暂时没有这个模型");
|
||||
});
|
||||
|
||||
test("effortLabel:三种结论 + 出错提示", () => {
|
||||
expect(effortLabel({ send: null, label: "不适用" })).toBe("思考:不适用");
|
||||
expect(effortLabel({ send: "none", label: "关闭(模型支持关闭)" })).toBe(
|
||||
"思考:关闭(模型支持关闭)",
|
||||
);
|
||||
expect(effortLabel({ error: "模型的思考档位数据无法识别" })).toContain("无法识别");
|
||||
});
|
||||
|
||||
test("sumView:启用数与最近一次执行点", () => {
|
||||
const tasks = [
|
||||
mkTask({ id: "a" }),
|
||||
mkTask({ id: "b", enabled: false }),
|
||||
mkTask({ id: "c", trigger: { kind: "daily", time: "23:00", timeZone: "UTC" } }),
|
||||
];
|
||||
const next = { a: "2026-11-01T06:00:00+08:00", b: "2026-10-31T13:00:00+08:00", c: "2026-10-31T12:30:00+08:00" };
|
||||
const view = sumView(tasks, next);
|
||||
expect(view.enabled).toBe(2);
|
||||
expect(view.next).toEqual({ at: "2026-10-31T12:30:00+08:00", name: "早报" });
|
||||
expect(sumView([], {}).next).toBeNull();
|
||||
expect(sumView([mkTask({ enabled: false })], {}).next).toBeNull();
|
||||
});
|
||||
|
||||
test("nextPointsAfter:daily 沿时区推算;every 沿锚点;窗口不外推", () => {
|
||||
const daily: Trigger = { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" };
|
||||
expect(nextPointsAfter(daily, T0, 3).map((d) => d.toISOString())).toEqual([
|
||||
"2026-10-31T22:00:00.000Z",
|
||||
"2026-11-01T22:00:00.000Z",
|
||||
"2026-11-02T22:00:00.000Z",
|
||||
]);
|
||||
const every: Trigger = { kind: "every", hours: 5, anchor: "2026-10-30T08:00:00Z" };
|
||||
expect(nextPointsAfter(every, T0, 2).map((d) => d.toISOString())).toEqual([
|
||||
"2026-10-31T09:00:00.000Z",
|
||||
"2026-10-31T14:00:00.000Z",
|
||||
]);
|
||||
expect(nextPointsAfter({ kind: "window", window: "5h" }, T0, 3)).toEqual([]);
|
||||
});
|
||||
|
||||
test("deleteArmed:3 秒内处于确认态,未进入确认(0)永远不算", () => {
|
||||
expect(deleteArmed(1000, 2000)).toBe(true);
|
||||
expect(deleteArmed(1000, 1000 + DELETE_CONFIRM_MS)).toBe(true);
|
||||
expect(deleteArmed(1000, 1000 + DELETE_CONFIRM_MS + 1)).toBe(false);
|
||||
expect(deleteArmed(0, 1000)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldCloseOnScroll:菜单内滚动不关(长列表可滚),菜单外滚动关,无菜单不关", () => {
|
||||
const pop = { contains: (x: unknown) => x === "menu-inner" };
|
||||
expect(shouldCloseOnScroll("menu-inner", pop)).toBe(false);
|
||||
expect(shouldCloseOnScroll(pop, pop)).toBe(false); // 菜单本体就是滚动元素
|
||||
expect(shouldCloseOnScroll("page-body", pop)).toBe(true);
|
||||
expect(shouldCloseOnScroll(null, pop)).toBe(true); // 读不到目标(如 window 滚动)按外关
|
||||
expect(shouldCloseOnScroll("page-body", null)).toBe(false); // 没开菜单就无所谓
|
||||
});
|
||||
|
||||
test("syncDraftOnPoll:未保存编辑优先;外部更新提示;任务删除收起", () => {
|
||||
const saved = mkTask({ updatedAt: "2026-10-31T08:00:00+08:00" });
|
||||
expect(syncDraftOnPoll(null, "x", true)).toBe("gone");
|
||||
expect(syncDraftOnPoll(saved, "2026-10-31T08:00:00+08:00", false)).toBe("adopt");
|
||||
expect(syncDraftOnPoll(saved, "2026-10-31T08:00:00+08:00", true)).toBe("keep");
|
||||
expect(syncDraftOnPoll(saved, "2026-10-30T08:00:00+08:00", true)).toBe("stale");
|
||||
});
|
||||
|
||||
test("contentOf:保存内容只含六个字段,不再带 message(探活消息固定 hi,由服务端填)", () => {
|
||||
const keys = Object.keys(contentOf(mkTask({ message: "hi" }))).sort();
|
||||
expect(keys).toEqual(["account", "enabled", "model", "name", "provider", "trigger"]);
|
||||
});
|
||||
|
||||
test("validateDraft:名称 / 供应商 / 窗口账号与窗口名必填", () => {
|
||||
expect(validateDraft(mkTask({ name: " " }))).toEqual({ error: "给任务起个名字", field: "name" });
|
||||
expect(validateDraft(mkTask({ provider: " " }))).toEqual({
|
||||
error: "必须选择供应商",
|
||||
field: "provider",
|
||||
});
|
||||
// 账号必选,不分触发方式
|
||||
expect(validateDraft(mkTask({ account: "" }))).toEqual({ error: "必须选择账号", field: "account" });
|
||||
expect(
|
||||
validateDraft(mkTask({ trigger: { kind: "window", window: "5h" }, account: "" })),
|
||||
).toEqual({ error: "必须选择账号", field: "account" });
|
||||
expect(
|
||||
validateDraft(mkTask({ trigger: { kind: "window", window: "" }, account: "a" })),
|
||||
).toEqual({ error: "必须填写额度窗口名", field: "window" });
|
||||
expect(
|
||||
validateDraft(mkTask({ account: "a", trigger: { kind: "daily", time: "", timeZone: "UTC" } })),
|
||||
).toEqual({
|
||||
error: "时间需为 24 小时制的 HH:MM",
|
||||
field: "time",
|
||||
});
|
||||
expect(validateDraft(mkTask({ account: "a" }))).toBeNull();
|
||||
});
|
||||
|
||||
test("accountHasWindows:没账号、不在目录、没有窗口都算没有——此时不提供「窗口重置后」", () => {
|
||||
const provider = mkProvider({
|
||||
id: "p",
|
||||
accounts: [
|
||||
mkAccount({ id: "with-win", windows: [{ name: "5h", used: 10, resetsAt: T0.toISOString() }] }),
|
||||
mkAccount({ id: "no-win", windows: [] }),
|
||||
],
|
||||
});
|
||||
expect(accountHasWindows("p", "with-win", [provider])).toBe(true);
|
||||
expect(accountHasWindows("p", "no-win", [provider])).toBe(false);
|
||||
// 空账号(自动)永远不能跟窗口
|
||||
expect(accountHasWindows("p", "", [provider])).toBe(false);
|
||||
// 旧任务里存着、目录里已经没有的账号
|
||||
expect(accountHasWindows("p", "gone", [provider])).toBe(false);
|
||||
expect(accountHasWindows("nope", "with-win", [provider])).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
// 带路页 boot.js 的失败测试(抄 fingerprint tests/boot.test.ts 的做法):
|
||||
// 在新上下文里执行脚本,断言跳转目标;并确保脚本没有任何联网调用
|
||||
// (magpie 页面 CSP connect-src 'none',只能整页跳转)。
|
||||
import { expect, test } from "bun:test";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { runInNewContext } from "node:vm";
|
||||
|
||||
const source = await readFile(new URL("../page/boot.js", import.meta.url), "utf8");
|
||||
|
||||
test("脚本中不出现 fetch / XMLHttpRequest / WebSocket", () => {
|
||||
expect(source).not.toMatch(/fetch|XMLHttpRequest|WebSocket/);
|
||||
});
|
||||
|
||||
interface BootResult {
|
||||
destination?: URL;
|
||||
said: { texts: string[] };
|
||||
}
|
||||
|
||||
async function boot(opts: {
|
||||
dark?: boolean;
|
||||
tokens?: Record<string, string>;
|
||||
service?: string;
|
||||
port?: number;
|
||||
remote?: boolean;
|
||||
} = {}): Promise<BootResult> {
|
||||
const said = { texts: [] as string[] };
|
||||
const el = () => {
|
||||
const kids: { textContent: string; style: Record<string, string>; appendChild: (x: unknown) => void }[] = [];
|
||||
return {
|
||||
textContent: "",
|
||||
style: {} as Record<string, string>,
|
||||
addEventListener: (_t: string, _fn: () => void) => {},
|
||||
appendChild(child: { textContent?: string }) {
|
||||
kids.push(child as never);
|
||||
said.texts.push(String(child?.textContent ?? ""));
|
||||
},
|
||||
};
|
||||
};
|
||||
let destination: URL | undefined;
|
||||
const document = {
|
||||
getElementById: (_id: string) => el(),
|
||||
createElement: (_tag: string) => el(),
|
||||
};
|
||||
await runInNewContext(source, {
|
||||
URL,
|
||||
URLSearchParams,
|
||||
btoa,
|
||||
atob,
|
||||
document,
|
||||
window: {
|
||||
magpie: {
|
||||
ready: Promise.resolve({ dark: opts.dark ?? true, tokens: opts.tokens }),
|
||||
service: opts.service ?? "",
|
||||
options: { get: async () => ({ port: opts.port }) },
|
||||
},
|
||||
},
|
||||
location: {
|
||||
hostname: opts.remote ? "magpie.example" : "127.0.0.1",
|
||||
href: opts.remote ? "http://magpie.example/boot/index.html" : "http://127.0.0.1/boot/index.html",
|
||||
replace: (url: string) => {
|
||||
destination = new URL(url);
|
||||
},
|
||||
},
|
||||
});
|
||||
// 带路页内部有多个 await(ready、options.get),等一个宏任务让它们全部走完
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
return { destination, said };
|
||||
}
|
||||
|
||||
test("有 magpie.service → 跳 service,并带上主题与令牌", async () => {
|
||||
const r = await boot({
|
||||
service: "http://magpie.example:8080/plugins/scheduled-messages/",
|
||||
tokens: { "--magpie-bg": "#101217" },
|
||||
});
|
||||
expect(r.destination?.origin).toBe("http://magpie.example:8080");
|
||||
expect(r.destination?.pathname).toBe("/plugins/scheduled-messages/");
|
||||
expect(r.destination?.searchParams.get("theme")).toBe("dark");
|
||||
const tokens = r.destination?.searchParams.get("tokens") ?? "";
|
||||
const decoded = JSON.parse(
|
||||
new TextDecoder().decode(Uint8Array.from(atob(tokens), (c) => c.charCodeAt(0))),
|
||||
) as Record<string, string>;
|
||||
expect(decoded["--magpie-bg"]).toBe("#101217");
|
||||
});
|
||||
|
||||
test("无 service → 跳 127.0.0.1 的插件端口", async () => {
|
||||
const r = await boot();
|
||||
expect(r.destination?.hostname).toBe("127.0.0.1");
|
||||
expect(r.destination?.port).toBe("3492"); // 默认端口与 package.json 的 magpie.options 一致
|
||||
expect(r.destination?.searchParams.get("theme")).toBe("dark");
|
||||
});
|
||||
|
||||
test("插件选项 port 覆盖默认端口", async () => {
|
||||
const r = await boot({ port: 4567 });
|
||||
expect(r.destination?.port).toBe("4567");
|
||||
});
|
||||
|
||||
test("无效端口退回默认 3492", async () => {
|
||||
const r = await boot({ port: -1 });
|
||||
expect(r.destination?.port).toBe("3492");
|
||||
});
|
||||
|
||||
test("浅色主题跟随宿主", async () => {
|
||||
const r = await boot({ dark: false });
|
||||
expect(r.destination?.searchParams.get("theme")).toBe("light");
|
||||
});
|
||||
|
||||
test("远程打开且无 service → 原地不动,给出 SSH 端口转发提示", async () => {
|
||||
const r = await boot({ remote: true, port: 3492 });
|
||||
expect(r.destination).toBeUndefined();
|
||||
expect(r.said.texts.join("\n")).toContain("SSH");
|
||||
expect(r.said.texts.join("\n")).toContain("3492");
|
||||
});
|
||||
|
||||
test("页面资源与 API 全走相对路径:任意服务前缀下都落回转发内,本地直达不受影响", async () => {
|
||||
// magpie web 把服务转发在自己的前缀路径下,根绝对引用会解析到宿主根而 404
|
||||
const html = await readFile(new URL("../web/index.html", import.meta.url), "utf8");
|
||||
expect(html).not.toContain('href="/');
|
||||
expect(html).not.toContain('src="/');
|
||||
const app = await readFile(new URL("../web/app.ts", import.meta.url), "utf8");
|
||||
expect(app).not.toMatch(/["'`]\/api\//);
|
||||
expect(app).not.toContain('src="/');
|
||||
// 相对引用的解析语义:转发前缀下落回前缀内,本地根路径下等价于根绝对
|
||||
const base = "http://magpie.example:8080/plugins/scheduled-messages/";
|
||||
expect(new URL("app.js", base).pathname).toBe("/plugins/scheduled-messages/app.js");
|
||||
expect(new URL("style.css", base).pathname).toBe("/plugins/scheduled-messages/style.css");
|
||||
expect(new URL("api/state", base).pathname).toBe("/plugins/scheduled-messages/api/state");
|
||||
expect(new URL("api/state", "http://127.0.0.1:3492/").pathname).toBe("/api/state");
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
// 页面端到端冒烟:真实浏览器(Chromium 与 WebKit)打开本地服务页面,走一遍新建任务并保存。
|
||||
// Playwright 是可选依赖:仓库不安装它,评审机通过 NODE_PATH 提供(1.62.0,Chromium + WebKit)。
|
||||
// 导入失败或浏览器启动失败时整组跳过,仓库根目录的 bun test 不受影响。
|
||||
import { afterAll, beforeAll, expect, test } from "bun:test";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { startService, type ServiceHandle } from "../src/server";
|
||||
import { fakeGateway, type FakeGateway } from "./fake-gateway";
|
||||
|
||||
// Playwright 的最小类型面:不依赖它的类型声明,没装也能通过 tsc
|
||||
interface Locator {
|
||||
click(): Promise<void>;
|
||||
fill(v: string): Promise<void>;
|
||||
first(): Locator;
|
||||
waitFor(o?: { timeout?: number }): Promise<void>;
|
||||
}
|
||||
interface Page {
|
||||
goto(url: string): Promise<unknown>;
|
||||
on(ev: "pageerror", cb: (e: unknown) => void): void;
|
||||
getByRole(role: string, o?: { name?: string; exact?: boolean }): Locator;
|
||||
getByPlaceholder(t: string): Locator;
|
||||
getByText(t: string): Locator;
|
||||
}
|
||||
interface Browser {
|
||||
newPage(): Promise<Page>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
interface Engine {
|
||||
launch(): Promise<Browser>;
|
||||
}
|
||||
interface Playwright {
|
||||
chromium: Engine;
|
||||
webkit: Engine;
|
||||
}
|
||||
|
||||
const pw = await (async (): Promise<Playwright | null> => {
|
||||
try {
|
||||
const name = "playwright"; // 非字面量:未安装时也不要求模块声明
|
||||
return (await import(name)) as unknown as Playwright;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
const ENGINES: Array<[string, Engine]> = pw ? [["chromium", pw.chromium], ["webkit", pw.webkit]] : [];
|
||||
|
||||
// 浏览器缺失时跳过整组(test.skipIf 在定义时求值):探针各启动一次并立即关闭
|
||||
const browsersReady = await (async () => {
|
||||
for (const [, engine] of ENGINES) {
|
||||
try {
|
||||
const b = await engine.launch();
|
||||
await b.close();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return ENGINES.length > 0;
|
||||
})();
|
||||
const testBrowser = test.skipIf(!browsersReady);
|
||||
|
||||
if (!browsersReady) test.skip("浏览器冒烟:本机没有可用的 Playwright/Chromium/WebKit,已跳过", () => {});
|
||||
|
||||
let svc: ServiceHandle;
|
||||
let gw: FakeGateway;
|
||||
let dir: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!browsersReady) return; // 没浏览器就不起服务
|
||||
dir = await mkdtemp(join(tmpdir(), "ww-browser-"));
|
||||
gw = fakeGateway({
|
||||
models: [
|
||||
{ id: "acme/acme-pro-2", owned_by: "acme", reasoning: true, reasoning_levels: ["low", "high"] },
|
||||
{ id: "acme/acme-mini-3", owned_by: "acme" },
|
||||
],
|
||||
quotas: [
|
||||
{
|
||||
provider: "acme",
|
||||
user: "me@x.com",
|
||||
windows: [{ name: "5h", used: 40, resetsAt: new Date(Date.now() + 2 * 3600_000).toISOString() }],
|
||||
},
|
||||
],
|
||||
chat: { status: 200, body: { id: "x", choices: [] } },
|
||||
});
|
||||
svc = await startService({ port: 0, dir, base: gw.base, uiDir: join(import.meta.dir, "..", "dist", "ui") });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await svc?.stop();
|
||||
gw?.stop();
|
||||
if (dir) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
for (const [name, engine] of ENGINES) {
|
||||
testBrowser(
|
||||
`${name}:新建任务、切换触发方式并保存`,
|
||||
async () => {
|
||||
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:${svc.port}/?lang=zh`);
|
||||
// 目录加载完成前按钮就存在;等账号下拉渲染出目录里的账号再操作
|
||||
await page.getByRole("button", { name: "新建任务" }).click();
|
||||
await page.getByRole("button", { name: "账号 me@x.com", exact: true }).waitFor({ timeout: 15_000 });
|
||||
await page.getByPlaceholder("给任务起个名字").fill("浏览器冒烟");
|
||||
await page.getByRole("button", { name: "每天定时", exact: true }).click();
|
||||
await page.getByRole("button", { name: "保存", exact: true }).click();
|
||||
await page.getByText("浏览器冒烟").first().waitFor({ timeout: 15_000 });
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
},
|
||||
90_000,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
// 收录与可发现性回归。依据(magpie 源码):
|
||||
// - 社区插件靠 magpie-community/plugins 的 registry.json 收录,magpie 自己从 npm 取最新版
|
||||
// (internal/plugin/market.go),发版无需同步清单;只有名称、图标、简介变化才改这条。
|
||||
// - 插件页搜索框把 [名称, 包名, 当前语言 summary, providers, npm 发布者] 拼成一串做小写子串匹配
|
||||
// (internal/gui/assets/plugins.js 的 match,不分词):所以 summary 必须带上用户会搜的词。
|
||||
// - 带 community: true 的 page 条目才会出现在不搜索时的「Pages」分区。
|
||||
|
||||
type Pkg = {
|
||||
name: string;
|
||||
description: string;
|
||||
main?: string;
|
||||
files: string[];
|
||||
keywords: string[];
|
||||
author?: string;
|
||||
repository: { url: string; directory?: string };
|
||||
};
|
||||
|
||||
type Entry = {
|
||||
package: string;
|
||||
name: string;
|
||||
kind?: string;
|
||||
community?: boolean;
|
||||
icon?: string;
|
||||
summary: Record<string, string>;
|
||||
};
|
||||
|
||||
const pkgDir = join(import.meta.dir, "..");
|
||||
const repoRoot = join(pkgDir, "..", "..");
|
||||
const pkg: Pkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")) as Pkg;
|
||||
const registry = JSON.parse(readFileSync(join(repoRoot, "registry.json"), "utf8")) as { plugins: Entry[] };
|
||||
const entry = registry.plugins.find((p) => p.package === pkg.name);
|
||||
const readme = readFileSync(join(pkgDir, "README.md"), "utf8");
|
||||
|
||||
// 与 plugins.js 的 match 同一公式:当前语言的搜索串(zh 用户看 summary.zh,其余语言回退 en)
|
||||
const searchable = (lang: "zh" | "en"): string =>
|
||||
[entry?.name ?? "", pkg.name, entry?.summary?.[lang] ?? entry?.summary?.en ?? ""].join(" ").toLowerCase();
|
||||
|
||||
// 插件页只匹配「当前语言」的 summary:中文词查 zh,英文词查 en;名称与包名两边都在
|
||||
const ZH_WORDS = ["窗口预热", "预热", "窗口", "额度", "配额", "定时", "定时消息", "保活", "重置", "订阅", "每周"];
|
||||
const EN_WORDS = [
|
||||
"warm up", "keep-alive", "keep alive", "quota", "usage window",
|
||||
"rate limit", "scheduled messages", "schedule", "daily", "reset",
|
||||
];
|
||||
const NAME_WORDS = ["window warmup", "warmup"];
|
||||
|
||||
describe("registry.json 收录", () => {
|
||||
test("这一条存在,字段与包一致", () => {
|
||||
expect(entry, `registry.json 里没有 ${pkg.name}`).toBeDefined();
|
||||
expect(entry?.kind).toBe("page");
|
||||
expect(entry?.community).toBe(true);
|
||||
expect(entry?.summary.zh).toBeTruthy();
|
||||
expect(entry?.summary.en).toBeTruthy();
|
||||
});
|
||||
|
||||
test("图标指向本仓库包内文件,不用个人仓库的 raw 地址", () => {
|
||||
expect(entry?.icon).toBe(
|
||||
"https://raw.githubusercontent.com/magpie-community/plugins/main/packages/window-warmup/page/icon.svg",
|
||||
);
|
||||
expect(existsSync(join(pkgDir, "page", "icon.svg"))).toBe(true);
|
||||
});
|
||||
|
||||
test("每个搜索词按界面语言命中对应搜索串", () => {
|
||||
for (const w of NAME_WORDS) {
|
||||
expect(searchable("zh"), `「${w}」未命中中文搜索串`).toContain(w);
|
||||
expect(searchable("en"), `「${w}」未命中英文搜索串`).toContain(w);
|
||||
}
|
||||
for (const w of ZH_WORDS) expect(searchable("zh"), `「${w}」未命中中文搜索串`).toContain(w);
|
||||
for (const w of EN_WORDS) expect(searchable("en"), `「${w}」未命中英文搜索串`).toContain(w);
|
||||
});
|
||||
|
||||
test("README 提到作者与源码位置", () => {
|
||||
expect(readme).toContain("YangHonghang");
|
||||
expect(readme).toContain("magpie-community/plugins");
|
||||
});
|
||||
});
|
||||
|
||||
describe("包契约(magpie 宿主与社区仓库约定)", () => {
|
||||
test("包名、入口、仓库目录", () => {
|
||||
expect(pkg.name).toBe("@magpie-community/page-window-warmup");
|
||||
expect(pkg.repository.directory).toBe("packages/window-warmup");
|
||||
expect(pkg.main === undefined || existsSync(join(pkgDir, pkg.main))).toBe(true);
|
||||
});
|
||||
|
||||
test("files 只列发布必需的文件,且包含 dist 与 page", () => {
|
||||
expect(pkg.files).toContain("dist");
|
||||
expect(pkg.files).toContain("page");
|
||||
for (const f of pkg.files) expect(["dist", "page", "README.md", "LICENSE"]).toContain(f);
|
||||
});
|
||||
|
||||
test("keywords 保留插件发现契约词", () => {
|
||||
for (const w of ["magpie", "magpie-page", "magpie-plugin"]) {
|
||||
expect(pkg.keywords, `keywords 缺「${w}」`).toContain(w);
|
||||
}
|
||||
});
|
||||
|
||||
test("author 是作者本人", () => {
|
||||
expect(pkg.author ?? "").toContain("YangHonghang");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
// 入库的 dist/ 必须等于源码构建结果:宿主直接加载它,发布流程也不构建。
|
||||
// 测试只读已提交的 dist/,构建产物写到临时目录,跑测试不会改写工作区。
|
||||
import { expect, test } from "bun:test";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { buildAll } from "../scripts/build";
|
||||
|
||||
const ROOT = join(import.meta.dir, "..");
|
||||
const FILES = ["plugin.js", "ui/app.js", "ui/index.html", "ui/style.css"];
|
||||
|
||||
test(
|
||||
"dist/ 与源码构建结果逐字节一致(不一致就先 bun run build 再提交)",
|
||||
async () => {
|
||||
const out = await mkdtemp(join(tmpdir(), "ww-dist-"));
|
||||
try {
|
||||
await buildAll(ROOT, out);
|
||||
for (const rel of FILES) {
|
||||
const [built, committed] = await Promise.all([
|
||||
readFile(join(out, rel)),
|
||||
readFile(join(ROOT, "dist", rel)),
|
||||
]);
|
||||
expect(built.equals(committed), `dist/${rel} 与构建结果不一致`).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
await rm(out, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
@@ -0,0 +1,181 @@
|
||||
// 测试与 --serve 演示共用的假 Magpie 网关:只在本机回环上应答,不发任何真实请求。
|
||||
// 请求全部按到达顺序记进 requests,供断言请求体与请求头。
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
// 测试进程绝不读真实用户的 Magpie 配置:把目录推导用的 XDG 钉到临时位置
|
||||
// (fetchCatalog 与调度器的兜底读取会走 magpieDirs 的默认路径)
|
||||
process.env.XDG_CONFIG_HOME = join(tmpdir(), "window-warmup-test-magpie-config");
|
||||
process.env.XDG_CACHE_HOME = join(tmpdir(), "window-warmup-test-magpie-cache");
|
||||
|
||||
export interface FakeChatReply {
|
||||
status?: number;
|
||||
body?: unknown;
|
||||
/** 延迟应答毫秒数,用于模拟超时与外部取消 */
|
||||
delayMs?: number;
|
||||
/** 模拟 2xx 响应体不完整:truncate=半截 JSON;reset=流中途断开(客户端收到 ECONNRESET) */
|
||||
breakBody?: "truncate" | "reset";
|
||||
}
|
||||
|
||||
export interface FakeRequest {
|
||||
method: string;
|
||||
path: string;
|
||||
/** 查询串原样(如 "?kept=1"),用于区分额度缓存读取与完整读取 */
|
||||
search: string;
|
||||
headers: Record<string, string>;
|
||||
/** /v1/chat/completions 的 JSON 请求体;其余请求为 null */
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
export interface FakeGatewayOpts {
|
||||
models?: unknown[];
|
||||
/** 额度完整读取(不带 kept)的应答;kept=1 缺省也用它(缓存里就是最新读数) */
|
||||
quotas?: unknown[];
|
||||
/** ?kept=1 的独立应答,模拟「缓存为空」触发兜底完整读取 */
|
||||
keptQuotas?: unknown[];
|
||||
/** /v1/models 的状态码,模拟模型目录接口故障 */
|
||||
modelsStatus?: number;
|
||||
/** 额度缓存读取(kept=1)的状态码,模拟额度接口故障 */
|
||||
quotasStatus?: number;
|
||||
/** 完整读取(不带 kept)的状态码;缺省跟随 quotasStatus(额度接口挂了两种读法都挂) */
|
||||
fullQuotasStatus?: number;
|
||||
/** 单卡刷新(POST /v1/magpie/quotas/refresh)的状态码 */
|
||||
refreshStatus?: number;
|
||||
/** 完整读取(不带 kept)的延迟毫秒数,用于并发合并测试 */
|
||||
fullQuotasDelayMs?: number;
|
||||
/** chat 端点的固定应答,或按请求体动态应答 */
|
||||
chat?: FakeChatReply | ((body: unknown, req: Request) => FakeChatReply | Promise<FakeChatReply>);
|
||||
}
|
||||
|
||||
export interface FakeGateway {
|
||||
base: string;
|
||||
requests: FakeRequest[];
|
||||
stop: () => void;
|
||||
}
|
||||
|
||||
function reply(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const DEFAULT_CHAT_BODY = {
|
||||
id: "chatcmpl-fake",
|
||||
object: "chat.completion",
|
||||
choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }],
|
||||
};
|
||||
|
||||
export function fakeGateway(opts: FakeGatewayOpts = {}): FakeGateway {
|
||||
const requests: FakeRequest[] = [];
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
const entry: FakeRequest = {
|
||||
method: req.method,
|
||||
path: url.pathname,
|
||||
search: url.search,
|
||||
headers: Object.fromEntries(req.headers.entries()),
|
||||
body: null,
|
||||
};
|
||||
requests.push(entry);
|
||||
if (url.pathname === "/v1/models") {
|
||||
return reply(opts.modelsStatus ?? 200, { data: opts.models ?? [] });
|
||||
}
|
||||
if (url.pathname === "/v1/magpie/quotas/refresh" && req.method === "POST") {
|
||||
return reply(opts.refreshStatus ?? 200, { data: [] });
|
||||
}
|
||||
if (url.pathname === "/v1/magpie/quotas") {
|
||||
const kept = url.searchParams.get("kept") === "1";
|
||||
const status = kept
|
||||
? opts.quotasStatus ?? 200
|
||||
: opts.fullQuotasStatus ?? opts.quotasStatus ?? 200;
|
||||
if (!kept && opts.fullQuotasDelayMs) await Bun.sleep(opts.fullQuotasDelayMs);
|
||||
return reply(status, { data: kept ? opts.keptQuotas ?? opts.quotas ?? [] : opts.quotas ?? [] });
|
||||
}
|
||||
if (url.pathname === "/v1/chat/completions") {
|
||||
const raw = await req.text();
|
||||
try {
|
||||
entry.body = JSON.parse(raw);
|
||||
} catch {
|
||||
entry.body = raw;
|
||||
}
|
||||
const conf =
|
||||
typeof opts.chat === "function" ? await opts.chat(entry.body, req) : (opts.chat ?? {});
|
||||
if (conf.delayMs) await Bun.sleep(conf.delayMs);
|
||||
if (conf.breakBody) {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('{"id":"chatcmpl-fake"'));
|
||||
if (conf.breakBody === "reset") controller.error(new Error("连接中断"));
|
||||
else controller.close();
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
status: conf.status ?? 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
return reply(conf.status ?? 200, conf.body ?? DEFAULT_CHAT_BODY);
|
||||
}
|
||||
return reply(404, { error: { message: `假网关没有 ${url.pathname}` } });
|
||||
},
|
||||
});
|
||||
return {
|
||||
base: `http://127.0.0.1:${server.port}`,
|
||||
requests,
|
||||
stop: () => server.stop(true),
|
||||
};
|
||||
}
|
||||
|
||||
// bun tests/fake-gateway.ts --serve:以示例数据常驻并打印地址,供页面联调与截图(长驻,勿在测试里跑)
|
||||
if (import.meta.main && process.argv.includes("--serve")) {
|
||||
const in2h = new Date(Date.now() + 2 * 3_600_000).toISOString();
|
||||
const gw = fakeGateway({
|
||||
models: [
|
||||
{
|
||||
id: "openai/gpt-5.2",
|
||||
owned_by: "openai",
|
||||
reasoning: true,
|
||||
reasoning_levels: ["minimal", "low", "medium", "high"],
|
||||
},
|
||||
{ id: "openai/gpt-5.2-chat", owned_by: "openai", reasoning: false },
|
||||
{
|
||||
id: "anthropic/claude-opus-4",
|
||||
owned_by: "anthropic",
|
||||
reasoning: true,
|
||||
reasoning_levels: ["disabled", "low", "high", "max"],
|
||||
},
|
||||
{
|
||||
id: "google/gemini-3-pro",
|
||||
owned_by: "google",
|
||||
reasoning: true,
|
||||
supported_reasoning_levels: [{ effort: "low" }, { effort: "high" }],
|
||||
},
|
||||
{ id: "deepseek/deepseek-v4", owned_by: "deepseek", reasoning: true, reasoning_levels: ["8192", "2048"] },
|
||||
{ id: "group/auto", owned_by: "openai", reasoning: false },
|
||||
],
|
||||
quotas: [
|
||||
{
|
||||
provider: "openai",
|
||||
user: "acct-yang",
|
||||
name: "Yang 主账号",
|
||||
kind: "subscription",
|
||||
windows: [
|
||||
{ name: "5h", used: 2, resetsAt: in2h },
|
||||
{ name: "week", used: 31, resetsAt: null },
|
||||
],
|
||||
},
|
||||
{
|
||||
provider: "anthropic",
|
||||
user: "acct-team",
|
||||
name: "Team 席位",
|
||||
kind: "subscription",
|
||||
windows: [{ name: "5h", used: 0, resetsAt: null }],
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(`fake gateway: ${gw.base}`);
|
||||
}
|
||||
@@ -0,0 +1,898 @@
|
||||
import { afterEach, describe, 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 { accountsOf, pinFor } from "../src/accounts";
|
||||
import {
|
||||
createQuotaReader,
|
||||
fetchCatalog,
|
||||
fetchQuotas,
|
||||
gatewayBase,
|
||||
modelProvider,
|
||||
pickAutoModel,
|
||||
pickEffort,
|
||||
refreshQuotaCard,
|
||||
send,
|
||||
WARMUP_MESSAGE,
|
||||
} from "../src/gateway";
|
||||
import type { CachedModel, KeyDirectoryEntry } from "../src/magpie-files";
|
||||
import type { CatalogAccount, EffortPick, QuotaEntry, QuotaWindow, RawModel, Task } from "../src/types";
|
||||
import { fakeGateway, type FakeGateway, type FakeGatewayOpts } from "./fake-gateway";
|
||||
|
||||
const started: FakeGateway[] = [];
|
||||
const cleanupDirs: string[] = [];
|
||||
function start(opts: FakeGatewayOpts = {}): FakeGateway {
|
||||
const gw = fakeGateway(opts);
|
||||
started.push(gw);
|
||||
return gw;
|
||||
}
|
||||
afterEach(async () => {
|
||||
for (const gw of started.splice(0)) gw.stop();
|
||||
while (cleanupDirs.length) await rm(cleanupDirs.pop()!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function mkTask(over: Partial<Task> = {}): Task {
|
||||
return {
|
||||
id: "t1",
|
||||
name: "早报",
|
||||
enabled: true,
|
||||
provider: "openai",
|
||||
account: "",
|
||||
model: "openai/gpt-5",
|
||||
message: "hi",
|
||||
trigger: { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" },
|
||||
createdAt: "",
|
||||
updatedAt: "",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
const chatReqs = (gw: FakeGateway) => gw.requests.filter((r) => r.path === "/v1/chat/completions");
|
||||
const bodyOf = (r: FakeGateway["requests"][number]) => r.body as Record<string, unknown>;
|
||||
|
||||
function okPick(pick: EffortPick): { send: string | null; label: string } {
|
||||
if ("error" in pick) throw new Error(`意外的 error 结果:${pick.error}`);
|
||||
return pick;
|
||||
}
|
||||
|
||||
const FUTURE = new Date(Date.now() + 2 * 3_600_000).toISOString();
|
||||
|
||||
describe("gatewayBase", () => {
|
||||
test("MAGPIE_ADDR host:port → 拼 http://", () => {
|
||||
expect(gatewayBase({ MAGPIE_ADDR: "127.0.0.1:9" })).toBe("http://127.0.0.1:9");
|
||||
});
|
||||
|
||||
test("缺省 127.0.0.1:3425", () => {
|
||||
expect(gatewayBase({})).toBe("http://127.0.0.1:3425");
|
||||
});
|
||||
|
||||
test("已是完整地址 → 原样保留并去掉尾部斜杠", () => {
|
||||
expect(gatewayBase({ MAGPIE_ADDR: "http://127.0.0.1:9/" })).toBe("http://127.0.0.1:9");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickEffort", () => {
|
||||
const m = (over: Partial<RawModel>): RawModel => ({ id: "m", ...over });
|
||||
|
||||
test("档位列表为空 → 不适用", () => {
|
||||
expect(pickEffort(m({ reasoning: true, reasoning_levels: [] }))).toEqual({
|
||||
send: null,
|
||||
label: "不适用",
|
||||
});
|
||||
});
|
||||
|
||||
test("reasoning 为假 → 不适用(即使列表里有 none)", () => {
|
||||
expect(pickEffort(m({ reasoning: false, reasoning_levels: ["none", "high"] }))).toEqual({
|
||||
send: null,
|
||||
label: "不适用",
|
||||
});
|
||||
});
|
||||
|
||||
test("reasoning 缺失 → 视为不思考,不适用", () => {
|
||||
expect(pickEffort(m({ reasoning_levels: ["low", "high"] }))).toEqual({
|
||||
send: null,
|
||||
label: "不适用",
|
||||
});
|
||||
});
|
||||
|
||||
test("disabled 归一为 none → 关闭", () => {
|
||||
expect(pickEffort(m({ reasoning: true, reasoning_levels: ["disabled", "high"] }))).toEqual({
|
||||
send: "none",
|
||||
label: "关闭(模型支持关闭)",
|
||||
});
|
||||
});
|
||||
|
||||
test("off 同样归一为 none", () => {
|
||||
expect(okPick(pickEffort(m({ reasoning: true, reasoning_levels: ["off", "high"] }))).send).toBe(
|
||||
"none",
|
||||
);
|
||||
});
|
||||
|
||||
test("minimal < low", () => {
|
||||
expect(okPick(pickEffort(m({ reasoning: true, reasoning_levels: ["minimal", "low"] }))).send).toBe(
|
||||
"minimal",
|
||||
);
|
||||
});
|
||||
|
||||
test("乱序 → low", () => {
|
||||
expect(okPick(pickEffort(m({ reasoning: true, reasoning_levels: ["high", "low"] }))).send).toBe(
|
||||
"low",
|
||||
);
|
||||
});
|
||||
|
||||
test("low/high → low,标签注明已用最低档", () => {
|
||||
expect(pickEffort(m({ reasoning: true, reasoning_levels: ["low", "high"] }))).toEqual({
|
||||
send: "low",
|
||||
label: "low(模型必须思考,已用最低档)",
|
||||
});
|
||||
});
|
||||
|
||||
test("纯数字档低于命名档 → 2048", () => {
|
||||
expect(okPick(pickEffort(m({ reasoning: true, reasoning_levels: ["2048", "low"] }))).send).toBe(
|
||||
"2048",
|
||||
);
|
||||
});
|
||||
|
||||
test("数字档按数值取最小", () => {
|
||||
expect(
|
||||
okPick(pickEffort(m({ reasoning: true, reasoning_levels: ["8192", "2048", "low"] }))).send,
|
||||
).toBe("2048");
|
||||
});
|
||||
|
||||
test("已知名低于未知名 → high", () => {
|
||||
expect(okPick(pickEffort(m({ reasoning: true, reasoning_levels: ["high", "turbo"] }))).send).toBe(
|
||||
"high",
|
||||
);
|
||||
});
|
||||
|
||||
test("只有未知名 → 列表第一档,标签注明", () => {
|
||||
const pick = pickEffort(m({ reasoning: true, reasoning_levels: ["turbo", "fast"] }));
|
||||
expect("error" in pick).toBe(false);
|
||||
if (!("error" in pick)) {
|
||||
expect(pick.send).toBe("turbo");
|
||||
expect(pick.label.includes("按模型列表第一档")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("supported_reasoning_levels[].effort 同样识别", () => {
|
||||
const pick = pickEffort(m({ reasoning: true, supported_reasoning_levels: [{ effort: "medium" }] }));
|
||||
expect(okPick(pick).send).toBe("medium");
|
||||
});
|
||||
|
||||
test("档位字段损坏(提不出任何档位)→ error", () => {
|
||||
const levels = [42] as unknown as string[];
|
||||
expect("error" in pickEffort(m({ reasoning: true, reasoning_levels: levels }))).toBe(true);
|
||||
});
|
||||
|
||||
test("档位字段存在但不是数组 → error(宁可报错也不误判成模型不思考)", () => {
|
||||
const levels = "low,high" as unknown as string[];
|
||||
expect("error" in pickEffort(m({ reasoning: true, reasoning_levels: levels }))).toBe(true);
|
||||
const supported = "low" as unknown as { effort: string }[];
|
||||
expect("error" in pickEffort(m({ reasoning: true, supported_reasoning_levels: supported }))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("send", () => {
|
||||
test("请求体与会话头:max_tokens 16、stream false、消息恒为 hi、无 pin 则无账号头", async () => {
|
||||
const gw = start();
|
||||
const r = await send(gw.base, mkTask(), null, null, new AbortController().signal);
|
||||
expect(r.outcome).toBe("ok");
|
||||
expect(r.reason).toBe("");
|
||||
expect(typeof r.ms).toBe("number");
|
||||
const [req] = chatReqs(gw);
|
||||
expect(req.method).toBe("POST");
|
||||
expect(bodyOf(req)).toEqual({
|
||||
model: "openai/gpt-5",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
max_tokens: 16,
|
||||
stream: false,
|
||||
});
|
||||
expect(req.headers["x-magpie-session"]).toBe("window-warmup/t1");
|
||||
expect(req.headers["x-magpie-account"]).toBeUndefined();
|
||||
expect(WARMUP_MESSAGE).toBe("hi");
|
||||
});
|
||||
|
||||
test("带 effort 与 pin → reasoning_effort 与 X-Magpie-Account", async () => {
|
||||
const gw = start();
|
||||
await send(gw.base, mkTask(), "acc-1", "low", new AbortController().signal);
|
||||
const [req] = chatReqs(gw);
|
||||
expect(bodyOf(req).reasoning_effort).toBe("low");
|
||||
expect(req.headers["x-magpie-account"]).toBe("acc-1");
|
||||
});
|
||||
|
||||
test("中文 pin 按原始字节到线路上仍是 UTF-8(假网关读原始字节)", async () => {
|
||||
// 真 socket 假网关:直接读请求字节,绕开 Headers 的解码差异
|
||||
let got: string | null = null;
|
||||
const server = Bun.listen({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
socket: {
|
||||
data(socket, data) {
|
||||
const head = data.toString("latin1");
|
||||
const m = /^x-magpie-account:\s*(.*)\r?$/im.exec(head.slice(0, head.indexOf("\r\n\r\n")));
|
||||
if (m && got === null) got = m[1];
|
||||
socket.end();
|
||||
},
|
||||
error() {},
|
||||
},
|
||||
});
|
||||
try {
|
||||
await send(`http://127.0.0.1:${server.port}`, mkTask(), "免费flash", null, new AbortController().signal);
|
||||
expect(got).not.toBeNull();
|
||||
// 线路上的字节(latin1 逐字节还原)就是 UTF-8 的原文
|
||||
expect(Buffer.from(got!, "latin1").toString("utf8")).toBe("免费flash");
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("429 + 上游 message → failed,原因含状态码与原文", async () => {
|
||||
const gw = start({ chat: { status: 429, body: { error: { message: "余额不足" } } } });
|
||||
const r = await send(gw.base, mkTask(), null, null, new AbortController().signal);
|
||||
expect(r.outcome).toBe("failed");
|
||||
expect(r.reason.includes("429")).toBe(true);
|
||||
expect(r.reason.includes("余额不足")).toBe(true);
|
||||
});
|
||||
|
||||
test("固定账号 403 → 只请求一次,不改用其他账号", async () => {
|
||||
const gw = start({ chat: { status: 403, body: { error: { message: "该账号无权使用此模型" } } } });
|
||||
const r = await send(gw.base, mkTask(), "acc-1", null, new AbortController().signal);
|
||||
expect(r.outcome).toBe("failed");
|
||||
expect(chatReqs(gw)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("网关不可达 → failed,原因是底层原始错误(不再写死「连不上 Magpie」)", async () => {
|
||||
const gw = start();
|
||||
const base = gw.base;
|
||||
gw.stop();
|
||||
// 同一地址直接 fetch 拿到的原始错误信息,就是 send 应上报的
|
||||
let raw = "";
|
||||
try {
|
||||
await fetch(`${base}/v1/models`);
|
||||
} catch (e) {
|
||||
raw = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
expect(raw).not.toBe("");
|
||||
const r = await send(base, mkTask(), null, null, new AbortController().signal);
|
||||
expect(r.outcome).toBe("failed");
|
||||
expect(r.reason).toBe(raw);
|
||||
expect(r.reason.includes("连不上 Magpie")).toBe(false);
|
||||
});
|
||||
|
||||
test("超过注入的超时 → unknown,原因按实际超时时长生成(不硬写 30 秒)", async () => {
|
||||
const gw = start({ chat: { delayMs: 500 } });
|
||||
const r = await send(gw.base, mkTask(), null, null, new AbortController().signal, 50);
|
||||
expect(r.outcome).toBe("unknown");
|
||||
expect(r.reason).toBe("50 毫秒内没有结果,可能已发送");
|
||||
|
||||
const gw2 = start({ chat: { delayMs: 2500 } });
|
||||
const r2 = await send(gw2.base, mkTask(), null, null, new AbortController().signal, 2000);
|
||||
expect(r2.outcome).toBe("unknown");
|
||||
expect(r2.reason).toBe("2 秒内没有结果,可能已发送");
|
||||
});
|
||||
|
||||
test("HTTP 200 但响应体不完整 → unknown(不能判 ok)", async () => {
|
||||
const gw = start({ chat: { breakBody: "truncate" } });
|
||||
const r = await send(gw.base, mkTask(), null, null, new AbortController().signal);
|
||||
expect(r.outcome).toBe("unknown");
|
||||
expect(r.reason).toContain("响应");
|
||||
});
|
||||
|
||||
test("响应中途连接重置 → unknown(可能已发送,不是连不上)", async () => {
|
||||
const gw = start({ chat: { breakBody: "reset" } });
|
||||
const r = await send(gw.base, mkTask(), null, null, new AbortController().signal);
|
||||
expect(r.outcome).toBe("unknown");
|
||||
expect(r.reason).toContain("可能已发送");
|
||||
});
|
||||
|
||||
test("外部 signal 中止 → unknown 发送被取消", async () => {
|
||||
const gw = start({ chat: { delayMs: 500 } });
|
||||
const ac = new AbortController();
|
||||
setTimeout(() => ac.abort(), 30);
|
||||
const r = await send(gw.base, mkTask(), null, null, ac.signal, 10_000);
|
||||
expect(r.outcome).toBe("unknown");
|
||||
expect(r.reason).toBe("发送被取消");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchCatalog", () => {
|
||||
test("归供应商、排除 group/、带上账号与窗口", async () => {
|
||||
const gw = start({
|
||||
models: [
|
||||
{ id: "openai/gpt-5", owned_by: "openai", reasoning: true, reasoning_levels: ["low", "high"] },
|
||||
{
|
||||
id: "openai/gpt-5-mini",
|
||||
owned_by: "openai",
|
||||
reasoning: true,
|
||||
reasoning_levels: ["disabled", "high"],
|
||||
},
|
||||
{
|
||||
id: "vertex/gemini-3-pro",
|
||||
owned_by: "google",
|
||||
reasoning: true,
|
||||
reasoning_levels: ["minimal", "low", "medium"],
|
||||
},
|
||||
{ id: "group/auto", owned_by: "openai", reasoning: false },
|
||||
],
|
||||
quotas: [
|
||||
{
|
||||
provider: "openai",
|
||||
user: "acct-1",
|
||||
name: "Yang",
|
||||
kind: "subscription",
|
||||
windows: [{ name: "5h", used: 2, resetsAt: FUTURE }],
|
||||
},
|
||||
{ provider: "moonshot", user: "acct-9", name: "", windows: [] },
|
||||
],
|
||||
});
|
||||
const catalog = await fetchCatalog(gw.base);
|
||||
expect(catalog.providers.map((p) => p.id)).toEqual(["google", "moonshot", "openai"]);
|
||||
|
||||
const openai = catalog.providers.find((p) => p.id === "openai");
|
||||
if (!openai) throw new Error("缺 openai 供应商");
|
||||
expect(openai.models.map((x) => x.id)).toEqual(["openai/gpt-5", "openai/gpt-5-mini"]);
|
||||
expect(okPick(openai.models[0].effort).send).toBe("low");
|
||||
expect(okPick(openai.models[1].effort).send).toBe("none");
|
||||
// 订阅账号来自额度卡;没有模型缓存但 /v1/models 有模型 → 退化为全部模型、未按账号区分
|
||||
expect(openai.accounts).toEqual([
|
||||
{
|
||||
id: "acct-1", label: "acct-1", kind: "login",
|
||||
windows: [{ name: "5h", used: 2, resetsAt: FUTURE }],
|
||||
models: ["openai/gpt-5", "openai/gpt-5-mini"], perAccount: false,
|
||||
autoModel: "openai/gpt-5-mini",
|
||||
},
|
||||
]);
|
||||
expect(openai.autoAccountModels).toEqual(["openai/gpt-5", "openai/gpt-5-mini"]);
|
||||
expect(openai.autoModel).toBe("openai/gpt-5-mini");
|
||||
|
||||
const google = catalog.providers.find((p) => p.id === "google");
|
||||
if (!google) throw new Error("缺 google 供应商");
|
||||
// 供应商归属优先看 owned_by(真正接住请求的一方),id 前缀只做回退
|
||||
expect(google.models.map((x) => x.id)).toEqual(["vertex/gemini-3-pro"]);
|
||||
|
||||
const moonshot = catalog.providers.find((p) => p.id === "moonshot");
|
||||
if (!moonshot) throw new Error("缺 moonshot 供应商");
|
||||
expect(moonshot.models).toEqual([]);
|
||||
expect(moonshot.accounts[0].id).toBe("acct-9");
|
||||
});
|
||||
|
||||
test("quotas 挂了 → 目录仍可用(账号为空)", async () => {
|
||||
const gw = start({
|
||||
models: [{ id: "openai/gpt-5", owned_by: "openai", reasoning: false }],
|
||||
quotasStatus: 500,
|
||||
});
|
||||
const catalog = await fetchCatalog(gw.base);
|
||||
expect(catalog.providers).toHaveLength(1);
|
||||
expect(catalog.providers[0].accounts).toEqual([]);
|
||||
});
|
||||
|
||||
test("key 限额卡只给 key 账号挂窗口用,自己不再是账号", async () => {
|
||||
const gw = start({
|
||||
models: [{ id: "office/gpt-5", owned_by: "office", reasoning: false }],
|
||||
quotas: [
|
||||
{ provider: "office/~keys", user: "key-a", name: "Key A", windows: [] },
|
||||
{ provider: "office/~keys", user: "key-b", name: "", windows: [] },
|
||||
],
|
||||
});
|
||||
const catalog = await fetchCatalog(gw.base);
|
||||
expect(catalog.providers.map((p) => p.id)).toEqual(["office"]);
|
||||
// 临时 HOME 没有 providers.json:key 卡找不到对应的 key,不产生账号
|
||||
expect(catalog.providers[0].accounts).toEqual([]);
|
||||
});
|
||||
|
||||
test("有模型缓存 → autoAccountModels 与 autoModel 按缓存算;无缓存的退化用全部模型", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "ww-catalog-"));
|
||||
cleanupDirs.push(root);
|
||||
await mkdir(join(root, "cfg", "magpie"), { recursive: true });
|
||||
await mkdir(join(root, "cache", "magpie", "models"), { recursive: true });
|
||||
await writeFile(
|
||||
join(root, "cache", "magpie", "models", "openai.json"),
|
||||
JSON.stringify({
|
||||
fetched: "2026-11-01T00:00:00Z",
|
||||
base: "https://x.test",
|
||||
models: [{ ID: "gpt-5.2" }, { ID: "gpt-5.2-mini" }, { ID: "gpt-5.2-turbo" }],
|
||||
}),
|
||||
);
|
||||
const savedConfig = process.env.XDG_CONFIG_HOME;
|
||||
const savedCache = process.env.XDG_CACHE_HOME;
|
||||
process.env.XDG_CONFIG_HOME = join(root, "cfg");
|
||||
process.env.XDG_CACHE_HOME = join(root, "cache");
|
||||
try {
|
||||
const gw = start({
|
||||
models: [
|
||||
{ id: "openai/gpt-5.2", owned_by: "openai", reasoning: false },
|
||||
{ id: "openai/gpt-5.2-mini", owned_by: "openai", reasoning: false },
|
||||
{ id: "openai/gpt-5.2-turbo", owned_by: "openai", reasoning: false },
|
||||
{ id: "moonshot/kimi", owned_by: "moonshot", reasoning: false },
|
||||
],
|
||||
quotas: [{ provider: "moonshot", user: "acct-9", name: "", windows: [] }],
|
||||
});
|
||||
const catalog = await fetchCatalog(gw.base);
|
||||
const openai = catalog.providers.find((p) => p.id === "openai");
|
||||
const moonshot = catalog.providers.find((p) => p.id === "moonshot");
|
||||
if (!openai || !moonshot) throw new Error("缺供应商");
|
||||
expect(openai.autoAccountModels).toEqual([
|
||||
"openai/gpt-5.2",
|
||||
"openai/gpt-5.2-mini",
|
||||
"openai/gpt-5.2-turbo",
|
||||
]);
|
||||
expect(openai.autoModel).toBe("openai/gpt-5.2-mini");
|
||||
// moonshot 没有缓存文件:退化为全部模型(/v1/models 里就是全部),autoModel 照常
|
||||
expect(moonshot.autoAccountModels).toEqual(["moonshot/kimi"]);
|
||||
expect(moonshot.autoModel).toBe("moonshot/kimi");
|
||||
} finally {
|
||||
if (savedConfig === undefined) delete process.env.XDG_CONFIG_HOME;
|
||||
else process.env.XDG_CONFIG_HOME = savedConfig;
|
||||
if (savedCache === undefined) delete process.env.XDG_CACHE_HOME;
|
||||
else process.env.XDG_CACHE_HOME = savedCache;
|
||||
}
|
||||
});
|
||||
|
||||
test("网关不可达 → 抛底层原始错误", async () => {
|
||||
const gw = start();
|
||||
const base = gw.base;
|
||||
gw.stop();
|
||||
let raw = "";
|
||||
try {
|
||||
await fetch(`${base}/v1/models`);
|
||||
} catch (e) {
|
||||
raw = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
await expect(fetchCatalog(base)).rejects.toThrow(raw);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchQuotas", () => {
|
||||
test("返回快照时间与归一化条目", async () => {
|
||||
const gw = start({
|
||||
quotas: [
|
||||
{
|
||||
provider: "openai",
|
||||
user: "acct-1",
|
||||
name: "Yang",
|
||||
windows: [{ name: "5h", used: 2, resetsAt: FUTURE }],
|
||||
},
|
||||
],
|
||||
});
|
||||
const snap = await fetchQuotas(gw.base);
|
||||
expect(snap.at).toBeInstanceOf(Date);
|
||||
expect(snap.entries).toEqual([
|
||||
{
|
||||
provider: "openai",
|
||||
account: "acct-1",
|
||||
label: "Yang",
|
||||
windows: [{ name: "5h", used: 2, resetsAt: FUTURE }],
|
||||
viaKey: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("远程 key 限额卡:viaKey 标记 + provider 归一成 <p>,user 原样保留", async () => {
|
||||
const gw = start({
|
||||
quotas: [
|
||||
{
|
||||
provider: "office/~keys",
|
||||
user: "key-yang",
|
||||
name: "office @ yang",
|
||||
windows: [{ name: "5h", used: 1, resetsAt: FUTURE }],
|
||||
},
|
||||
{ provider: "openai", user: "acct-1", name: "Yang", windows: [] },
|
||||
],
|
||||
});
|
||||
const snap = await fetchQuotas(gw.base);
|
||||
expect(snap.entries).toEqual([
|
||||
{
|
||||
provider: "office",
|
||||
account: "key-yang",
|
||||
label: "office @ yang",
|
||||
windows: [{ name: "5h", used: 1, resetsAt: FUTURE }],
|
||||
viaKey: true,
|
||||
},
|
||||
{ provider: "openai", account: "acct-1", label: "Yang", windows: [], viaKey: false },
|
||||
]);
|
||||
});
|
||||
|
||||
test("unlimited: true 的「不限额」占位不是窗口,读取时剔除", async () => {
|
||||
const gw = start({
|
||||
quotas: [
|
||||
{
|
||||
provider: "openai",
|
||||
user: "acct-1",
|
||||
name: "Yang",
|
||||
windows: [
|
||||
{ name: "5h", used: 2, resetsAt: FUTURE },
|
||||
{ name: "total", unlimited: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const snap = await fetchQuotas(gw.base);
|
||||
expect(snap.entries[0].windows).toEqual([{ name: "5h", used: 2, resetsAt: FUTURE }]);
|
||||
});
|
||||
|
||||
test("卡片的读取时刻 readAt 原样带出(纳秒精度的串也能解析)", async () => {
|
||||
const readAt = "2026-11-02T09:44:34.222418286+08:00";
|
||||
const gw = start({
|
||||
quotas: [{ provider: "zcode", user: "a@b.c", name: "Z", readAt, windows: [] }],
|
||||
});
|
||||
const snap = await fetchQuotas(gw.base);
|
||||
expect(snap.entries[0].readAt).toBe(readAt);
|
||||
expect(new Date(snap.entries[0].readAt!).toISOString()).toBe("2026-11-02T01:44:34.222Z");
|
||||
});
|
||||
});
|
||||
|
||||
describe("refreshQuotaCard", () => {
|
||||
test("POST 单卡刷新接口,供应商与账号按查询参数编码", async () => {
|
||||
const gw = start();
|
||||
await refreshQuotaCard(gw.base, "zcode", "ho****ng@qq.com");
|
||||
const req = gw.requests.find((r) => r.path === "/v1/magpie/quotas/refresh");
|
||||
expect(req?.method).toBe("POST");
|
||||
const q = new URLSearchParams(req!.search);
|
||||
expect(q.get("provider")).toBe("zcode");
|
||||
expect(q.get("user")).toBe("ho****ng@qq.com");
|
||||
});
|
||||
|
||||
test("接口报错如实抛出", async () => {
|
||||
const gw = start({ refreshStatus: 403 });
|
||||
await expect(refreshQuotaCard(gw.base, "zcode", "a")).rejects.toThrow("HTTP 403");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickAutoModel", () => {
|
||||
const m = (id: string): RawModel => ({ id, owned_by: "p", reasoning: false });
|
||||
|
||||
test("规格词排序 flash < lite < mini < nano < small < turbo", () => {
|
||||
const picked = pickAutoModel([
|
||||
m("p/turbo"),
|
||||
m("p/small"),
|
||||
m("p/nano"),
|
||||
m("p/mini"),
|
||||
m("p/lite"),
|
||||
m("p/flash"),
|
||||
]);
|
||||
expect(picked?.id).toBe("p/flash");
|
||||
});
|
||||
|
||||
test("按单词匹配且不区分大小写:Mini 命中、minimax 不算 mini", () => {
|
||||
expect(pickAutoModel([m("p/gpt-5-Mini"), m("p/gpt-5")])?.id).toBe("p/gpt-5-Mini");
|
||||
// 两个都不含规格词 → 都排最后,比较落到数字感知降序
|
||||
expect(pickAutoModel([m("p/minimax"), m("p/gpt-6"), m("p/gpt-5")])?.id).toBe("p/gpt-6");
|
||||
});
|
||||
|
||||
test("都不含规格词的排最后;同档按 id 数字感知降序(新版本优先)", () => {
|
||||
expect(pickAutoModel([m("p/gpt-5"), m("p/gpt-5.2"), m("p/gpt-4")])?.id).toBe("p/gpt-5.2");
|
||||
expect(pickAutoModel([m("p/model-9"), m("p/model-10")])?.id).toBe("p/model-10");
|
||||
});
|
||||
|
||||
test("规格词只看 id 的最后一段", () => {
|
||||
expect(pickAutoModel([m("turbo/flash"), m("p/turbo")])?.id).toBe("turbo/flash");
|
||||
expect(pickAutoModel([m("flash/turbo"), m("p/flash-lite")])?.id).toBe("p/flash-lite");
|
||||
});
|
||||
|
||||
test("空列表 → null", () => {
|
||||
expect(pickAutoModel([])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("modelProvider", () => {
|
||||
test("owned_by 优先(真正接住请求的一方),其次 id 首段,都没有则空", () => {
|
||||
expect(modelProvider({ id: "a/b", owned_by: "x" })).toBe("x");
|
||||
expect(modelProvider({ id: "a/b" })).toBe("a");
|
||||
expect(modelProvider({ id: "bare" })).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("额度兜底读取(kept 为空时读完整接口)", () => {
|
||||
const ENTRY = { provider: "openai", user: "acct-1", name: "A", windows: [] };
|
||||
function fakeClock(): { now: () => Date; tick: (ms: number) => void } {
|
||||
let t = 1_700_000_000_000;
|
||||
return { now: () => new Date(t), tick: (ms: number) => { t += ms; } };
|
||||
}
|
||||
const fulls = (gw: FakeGateway) =>
|
||||
gw.requests.filter((r) => r.path === "/v1/magpie/quotas" && r.search === "");
|
||||
const kepts = (gw: FakeGateway) =>
|
||||
gw.requests.filter((r) => r.path === "/v1/magpie/quotas" && r.search === "?kept=1");
|
||||
|
||||
test("kept 有数据 → 只读缓存,不触发完整读取", async () => {
|
||||
const gw = start({ keptQuotas: [ENTRY] });
|
||||
const read = createQuotaReader(fakeClock());
|
||||
const snap = await read(gw.base);
|
||||
expect(snap.entries).toHaveLength(1);
|
||||
expect(fulls(gw)).toHaveLength(0);
|
||||
expect(kepts(gw)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("kept 为空 → 完整读取一次;5 分钟内再读不重复;跨过 5 分钟才再读", async () => {
|
||||
const clock = fakeClock();
|
||||
const gw = start({ keptQuotas: [], quotas: [ENTRY] });
|
||||
const read = createQuotaReader({ now: clock.now });
|
||||
|
||||
const first = await read(gw.base);
|
||||
expect(first.entries).toEqual([
|
||||
{ provider: "openai", account: "acct-1", label: "A", windows: [], viaKey: false },
|
||||
]);
|
||||
expect(fulls(gw)).toHaveLength(1);
|
||||
|
||||
const second = await read(gw.base);
|
||||
expect(second.entries).toHaveLength(1);
|
||||
expect(fulls(gw)).toHaveLength(1); // 仍在 5 分钟内:复用完整读取结果
|
||||
expect(kepts(gw)).toHaveLength(2); // kept 是便宜读,每次照常
|
||||
expect(second.at.getTime()).toBe(first.at.getTime()); // 缓存快照保留原读取时刻
|
||||
|
||||
clock.tick(5 * 60_000 + 1);
|
||||
await read(gw.base);
|
||||
expect(fulls(gw)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("完整读取失败 → 5 分钟内不再发起尝试(没有上次成功就当空),跨过 5 分钟才重试", async () => {
|
||||
const clock = fakeClock();
|
||||
const opts: FakeGatewayOpts = { keptQuotas: [], quotas: [ENTRY] };
|
||||
const gw = start(opts);
|
||||
const read = createQuotaReader({ now: clock.now });
|
||||
|
||||
opts.fullQuotasStatus = 500;
|
||||
await expect(read(gw.base)).rejects.toThrow(/500/); // 首次尝试如实报错
|
||||
const second = await read(gw.base); // 窗口内:不重试,也没有上次成功 → 空条目
|
||||
expect(second.entries).toEqual([]);
|
||||
expect(fulls(gw)).toHaveLength(1);
|
||||
|
||||
opts.fullQuotasStatus = 200;
|
||||
const third = await read(gw.base); // 仍在窗口内:上游已恢复也不会立刻被打
|
||||
expect(third.entries).toEqual([]);
|
||||
expect(fulls(gw)).toHaveLength(1);
|
||||
|
||||
clock.tick(5 * 60_000 + 1);
|
||||
const fourth = await read(gw.base); // 跨过 5 分钟:重试并拿到数据
|
||||
expect(fourth.entries).toHaveLength(1);
|
||||
expect(fulls(gw)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("完整读取失败 → 5 分钟内复用上一次成功结果", async () => {
|
||||
const clock = fakeClock();
|
||||
const opts: FakeGatewayOpts = { keptQuotas: [], quotas: [ENTRY] };
|
||||
const gw = start(opts);
|
||||
const read = createQuotaReader({ now: clock.now });
|
||||
|
||||
const good = await read(gw.base); // 成功一次
|
||||
expect(good.entries).toHaveLength(1);
|
||||
|
||||
opts.quotas = []; // 上游真坏了:即便重试也拿不到数据
|
||||
opts.fullQuotasStatus = 500;
|
||||
clock.tick(5 * 60_000 + 1);
|
||||
await expect(read(gw.base)).rejects.toThrow(/500/); // 窗口外重试失败
|
||||
const fallback = await read(gw.base); // 窗口内:用上次成功,不再打上游
|
||||
expect(fallback.entries).toHaveLength(1);
|
||||
expect(fallback.at.getTime()).toBe(good.at.getTime());
|
||||
expect(fulls(gw)).toHaveLength(2); // 失败后的窗口内没有第三次尝试
|
||||
});
|
||||
|
||||
test("kept 为空时并发兜底读取合并为一次完整读取", async () => {
|
||||
const gw = start({ keptQuotas: [], quotas: [ENTRY], fullQuotasDelayMs: 50 });
|
||||
const read = createQuotaReader(fakeClock());
|
||||
const [a, b, c] = await Promise.all([read(gw.base), read(gw.base), read(gw.base)]);
|
||||
expect(fulls(gw)).toHaveLength(1);
|
||||
expect(a.entries).toEqual(b.entries);
|
||||
expect(b.entries).toEqual(c.entries);
|
||||
expect(a.entries).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------- 统一账号规则(src/accounts.ts,目录与调度器共用) ----------
|
||||
|
||||
describe("accountsOf", () => {
|
||||
const fp = (key: string): string =>
|
||||
createHash("sha256").update(key, "utf8").digest("hex").slice(0, 10);
|
||||
// 夹具假 key
|
||||
const K_GLM = "sk-test-AAAA11";
|
||||
const K_FREE = "sk-test-BBBB22";
|
||||
const K_OTHER = "sk-test-CCCC33";
|
||||
const FP = { glm: fp(K_GLM), free: fp(K_FREE), other: fp(K_OTHER) };
|
||||
const P = "remote-magpie";
|
||||
const M_FLASH = "remote-magpie/group/glm-5.3-flash";
|
||||
const M_GLM = "remote-magpie/group/glm-5.3";
|
||||
const M_QWEN = "remote-magpie/qwen-token-plan/qwen3.8-flash";
|
||||
|
||||
const keyDir = (): Map<string, KeyDirectoryEntry> =>
|
||||
new Map([
|
||||
[
|
||||
P,
|
||||
{
|
||||
keys: [
|
||||
{ fingerprint: FP.free, name: "免费flash" },
|
||||
{ fingerprint: FP.glm, name: "GLM" },
|
||||
{ fingerprint: FP.other, name: "除GLM外其他" },
|
||||
],
|
||||
accountModels: { [FP.glm]: ["group/glm-5.3"], yang: ["group/glm-5.3"] },
|
||||
},
|
||||
],
|
||||
]);
|
||||
const cache = (): CachedModel[] => [
|
||||
{ id: "group/glm-5.3-flash", keys: [FP.free, FP.glm] },
|
||||
{ id: "group/glm-5.3", keys: [FP.glm] },
|
||||
{ id: "qwen-token-plan/qwen3.8-flash", keys: [FP.other] },
|
||||
];
|
||||
const models = (): string[] => [M_FLASH, M_GLM, M_QWEN];
|
||||
const quotas = (): QuotaEntry[] => [
|
||||
{
|
||||
provider: P, account: "免费flash", label: "免费flash", viaKey: true,
|
||||
windows: [{ name: "5h", used: 1, resetsAt: null }],
|
||||
},
|
||||
{
|
||||
provider: P, account: "GLM", label: "GLM", viaKey: true,
|
||||
windows: [
|
||||
{ name: "5h", used: 2, resetsAt: FUTURE },
|
||||
// unlimited 是「不限额」占位,不是窗口:cast 塞进去验证账号侧同样剔除
|
||||
{ name: "week", used: 0, resetsAt: null, unlimited: true } as unknown as QuotaWindow,
|
||||
],
|
||||
},
|
||||
{
|
||||
provider: P, account: "除GLM外其他 · sk-…ab", label: "除GLM外其他 · sk-…ab", viaKey: true,
|
||||
windows: [{ name: "5h", used: 4, resetsAt: null }],
|
||||
},
|
||||
{
|
||||
provider: P, account: "Yang", label: "Yang 主账号", viaKey: false,
|
||||
windows: [{ name: "5h", used: 3, resetsAt: FUTURE }],
|
||||
},
|
||||
];
|
||||
|
||||
const accountOf = (accounts: CatalogAccount[], id: string): CatalogAccount => {
|
||||
const a = accounts.find((x) => x.id === id);
|
||||
if (!a) throw new Error(`缺账号 ${id}`);
|
||||
return a;
|
||||
};
|
||||
|
||||
test("本机实况夹具:三个 key 账号各自的可选模型、窗口与自动模型", () => {
|
||||
const { accounts, autoAccountModels } = accountsOf(P, {
|
||||
models: models(), quotas: quotas(), keyDir: keyDir(), cache: cache(),
|
||||
});
|
||||
expect(accounts.map((a) => a.id).sort()).toEqual([FP.free, FP.glm, FP.other, "Yang"].sort());
|
||||
|
||||
const free = accountOf(accounts, FP.free);
|
||||
expect(free).toEqual({
|
||||
id: FP.free, label: "免费flash", kind: "key",
|
||||
windows: [{ name: "5h", used: 1, resetsAt: null }],
|
||||
models: [M_FLASH], perAccount: true, autoModel: M_FLASH,
|
||||
});
|
||||
// GLM:accountModels 限定 glm-5.3;~keys 卡的 unlimited 窗口被剔除
|
||||
expect(accountOf(accounts, FP.glm)).toEqual({
|
||||
id: FP.glm, label: "GLM", kind: "key",
|
||||
windows: [{ name: "5h", used: 2, resetsAt: FUTURE }],
|
||||
models: [M_GLM], perAccount: true, autoModel: M_GLM,
|
||||
});
|
||||
// 除GLM外其他:卡名是「名字 · 打码」形态,仍按前缀挂上
|
||||
expect(accountOf(accounts, FP.other)).toEqual({
|
||||
id: FP.other, label: "除GLM外其他", kind: "key",
|
||||
windows: [{ name: "5h", used: 4, resetsAt: null }],
|
||||
models: [M_QWEN], perAccount: true, autoModel: M_QWEN,
|
||||
});
|
||||
// 订阅账号:accountModels 按小写名过滤(键 yang,账号 Yang)
|
||||
expect(accountOf(accounts, "Yang")).toEqual({
|
||||
id: "Yang", label: "Yang", kind: "login",
|
||||
windows: [{ name: "5h", used: 3, resetsAt: FUTURE }],
|
||||
models: [M_GLM], perAccount: true, autoModel: M_GLM,
|
||||
});
|
||||
expect(autoAccountModels).toEqual([M_FLASH, M_GLM, M_QWEN].sort());
|
||||
});
|
||||
|
||||
test("没有额度卡对应的 key 不产生账号;key 卡本身不变成登录账号", () => {
|
||||
const { accounts } = accountsOf(P, {
|
||||
models: models(),
|
||||
quotas: [
|
||||
{ provider: P, account: "ghost-key", label: "ghost", viaKey: true, windows: [] },
|
||||
{ provider: P, account: "ghost-acct", label: "ghost", viaKey: false, windows: [] },
|
||||
],
|
||||
keyDir: keyDir(),
|
||||
cache: cache(),
|
||||
});
|
||||
expect(accounts.map((a) => a.id).sort()).toEqual([FP.free, FP.glm, FP.other, "ghost-acct"].sort());
|
||||
});
|
||||
|
||||
test("缓存缺失退化:/v1/models 有模型 → 全部模型不按账号区分(第 1 层跳过),perAccount false", () => {
|
||||
const { accounts, autoAccountModels } = accountsOf(P, {
|
||||
models: models(), quotas: quotas(), keyDir: keyDir(), cache: null,
|
||||
});
|
||||
for (const id of [FP.free, FP.glm, FP.other, "Yang"]) {
|
||||
const a = accountOf(accounts, id);
|
||||
// 第 2 层(accountModels)仍然生效:GLM 与 Yang 仍被限定
|
||||
if (id === FP.glm || id === "Yang") {
|
||||
expect(a.models).toEqual([M_GLM]);
|
||||
} else {
|
||||
expect(a.models).toEqual([M_FLASH, M_GLM, M_QWEN].sort());
|
||||
}
|
||||
expect(a.perAccount).toBe(false);
|
||||
expect(a.autoModel).toBe(a.models!.length === 1 ? M_GLM : "remote-magpie/group/glm-5.3-flash");
|
||||
}
|
||||
expect(autoAccountModels).toEqual([M_FLASH, M_GLM, M_QWEN].sort());
|
||||
});
|
||||
|
||||
test("缓存与 /v1/models 模型都没有 → models null(提示 B、自动模型失败)", () => {
|
||||
const { accounts, autoAccountModels } = accountsOf(P, {
|
||||
models: [], quotas: quotas(), keyDir: keyDir(), cache: null,
|
||||
});
|
||||
for (const a of accounts) {
|
||||
expect(a.models).toBeNull();
|
||||
expect(a.perAccount).toBe(false);
|
||||
expect(a.autoModel).toBeNull();
|
||||
}
|
||||
expect(autoAccountModels).toBeNull();
|
||||
});
|
||||
|
||||
test("窗口匹配:未命名 key 接受无窗口;同名两把 key 都挂「名字 · 打码」卡", () => {
|
||||
const fpA = fp("sk-test-AAAA11");
|
||||
const fpB = fp("sk-test-BBBB22");
|
||||
const fpC = fp("sk-test-CCCC33");
|
||||
const win = [{ name: "5h", used: 7, resetsAt: null }];
|
||||
const { accounts } = accountsOf(P, {
|
||||
models: models(),
|
||||
quotas: [
|
||||
{ provider: P, account: "GLM · sk-…9f", label: "GLM · sk-…9f", viaKey: true, windows: win },
|
||||
{ provider: P, account: "sk-…cd", label: "sk-…cd", viaKey: true, windows: win },
|
||||
],
|
||||
keyDir: new Map([
|
||||
[P, {
|
||||
keys: [
|
||||
{ fingerprint: fpA, name: "" },
|
||||
{ fingerprint: fpB, name: "GLM" },
|
||||
{ fingerprint: fpC, name: "GLM" },
|
||||
],
|
||||
accountModels: {},
|
||||
}],
|
||||
]),
|
||||
cache: cache(),
|
||||
});
|
||||
// 没起名:卡名是打码后的样子,插件算不出来 → 无窗口
|
||||
expect(accountOf(accounts, fpA).windows).toEqual([]);
|
||||
// 同名两把:都挂到「GLM · 打码」那张卡
|
||||
expect(accountOf(accounts, fpB).windows).toEqual(win);
|
||||
expect(accountOf(accounts, fpC).windows).toEqual(win);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pinFor", () => {
|
||||
const fp = (key: string): string =>
|
||||
createHash("sha256").update(key, "utf8").digest("hex").slice(0, 10);
|
||||
const P = "remote-magpie";
|
||||
const keyDir = (names: string[]): Map<string, KeyDirectoryEntry> =>
|
||||
new Map([
|
||||
[P, {
|
||||
keys: names.map((name, i) => ({ fingerprint: fp(`sk-test-${i}-key`), name })),
|
||||
accountModels: {},
|
||||
}],
|
||||
]);
|
||||
|
||||
test("空账号 → null", () => {
|
||||
expect(pinFor(P, "", keyDir(["a", "b"]), [])).toBeNull();
|
||||
});
|
||||
|
||||
test("启用 key ≥2 把 → P#指纹;只有 1 把 → null(候选 ID 就是供应商 id)", () => {
|
||||
const fp0 = fp("sk-test-0-key");
|
||||
expect(pinFor(P, fp0, keyDir(["a", "b"]), [])).toBe(`${P}#${fp0}`);
|
||||
expect(pinFor(P, fp0, keyDir(["a"]), [])).toBeNull();
|
||||
});
|
||||
|
||||
test("订阅账号名原样;形如 10 位 hex 的订阅名也在账号列表里 → 仍原样", () => {
|
||||
const quotas: QuotaEntry[] = [
|
||||
{ provider: P, account: "Yang", label: "Y", viaKey: false, windows: [] },
|
||||
{ provider: P, account: "abc1234567", label: "h", viaKey: false, windows: [] },
|
||||
];
|
||||
expect(pinFor(P, "Yang", keyDir(["a", "b"]), quotas)).toBe("Yang");
|
||||
expect(pinFor(P, "abc1234567", keyDir(["a", "b"]), quotas)).toBe("abc1234567");
|
||||
});
|
||||
|
||||
test("目录读不出且账号是 10 位小写 hex → 按 ≥2 处理,发 P#账号", () => {
|
||||
expect(pinFor(P, "abc1234567", null, [])).toBe(`${P}#abc1234567`);
|
||||
expect(pinFor(P, "ABC1234567", null, [])).toBe("ABC1234567"); // 大写不是指纹形态,原样
|
||||
});
|
||||
|
||||
test("供应商在目录里但认不出这把 key:按该供应商的启用 key 数走指纹规则", () => {
|
||||
expect(pinFor(P, "abc1234567", keyDir(["a", "b"]), [])).toBe(`${P}#abc1234567`);
|
||||
expect(pinFor(P, "abc1234567", keyDir(["a"]), [])).toBeNull();
|
||||
});
|
||||
|
||||
test("旧任务里存的 key 名 → 原样发头", () => {
|
||||
expect(pinFor(P, "免费flash", keyDir(["免费flash"]), [])).toBe("免费flash");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// i18n 的测试:语言归一、三张译文的键集合一致、t 的查表与回退。不碰 DOM、不发请求。
|
||||
import { expect, test } from "bun:test";
|
||||
import { I18N, normalizeLang, setLang, t, type I18NTable, type Lang } from "../web/app";
|
||||
|
||||
test("normalizeLang:归一到 Magpie 的四种语言,识别不了回退 zh", () => {
|
||||
const table: [string | null | undefined, Lang][] = [
|
||||
["zh", "zh"],
|
||||
["zh-CN", "zh"],
|
||||
["zh-TW", "zh-TW"],
|
||||
["zh-Hant-TW", "zh-TW"],
|
||||
["en", "en"],
|
||||
["en-US", "en"],
|
||||
["ja", "ja"],
|
||||
["ja-JP", "ja"],
|
||||
["fr", "zh"],
|
||||
["", "zh"],
|
||||
[null, "zh"],
|
||||
];
|
||||
for (const [raw, want] of table) expect(normalizeLang(raw)).toBe(want);
|
||||
});
|
||||
|
||||
test("en / zh-TW / ja 三张译文的键集合完全一致,漏译即暴露", () => {
|
||||
const keys = (l: Lang): string[] => Object.keys((I18N[l] ?? {}) as I18NTable).sort();
|
||||
expect(keys("en")).toEqual(keys("zh-TW"));
|
||||
expect(keys("en")).toEqual(keys("ja"));
|
||||
// 译文一律非空:空串会退化成回退键,等于没译
|
||||
for (const l of ["en", "zh-TW", "ja"] as const) {
|
||||
for (const [k, v] of Object.entries(I18N[l] ?? {})) expect(v.trim().length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
test("t:zh 恒等返回键,其他语言命中译文,未知键在任何语言都回退键本身", () => {
|
||||
const KEY = "必须选择账号";
|
||||
const UNKNOWN = "不存在的键";
|
||||
expect(t(KEY)).toBe(KEY); // 默认 zh:键即中文,逐字恒等
|
||||
expect(t(UNKNOWN)).toBe(UNKNOWN);
|
||||
for (const l of ["en", "zh-TW", "ja"] as const) {
|
||||
setLang(l);
|
||||
expect(t(KEY)).toBe(I18N[l]![KEY]);
|
||||
expect(t(UNKNOWN)).toBe(UNKNOWN);
|
||||
}
|
||||
setLang("zh");
|
||||
expect(t(KEY)).toBe(KEY);
|
||||
});
|
||||
|
||||
test("调用点键 ⊆ 三张译表:app.ts 里每个 t(\"…\") 字面量在各语言都有词条", async () => {
|
||||
const src = await Bun.file(new URL("../web/app.ts", import.meta.url)).text();
|
||||
const keys = new Set<string>();
|
||||
for (const m of src.matchAll(/\bt\("((?:[^"\\]|\\.)*)"\)/g)) keys.add(m[1]);
|
||||
expect(keys.size).toBeGreaterThan(50); // 防止正则失配让测试空转
|
||||
for (const langName of ["en", "zh-TW", "ja"] as const) {
|
||||
const table = I18N[langName]!;
|
||||
const missing = [...keys].filter((k) => !(k in table));
|
||||
expect(missing).toEqual([]);
|
||||
if (missing.length) console.error(`${langName} 缺词条:`, missing);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
// 图标字段与 magpie 的读取规则对齐(internal/plugin/market.go ownIcon、internal/plugin/page.go):
|
||||
// 市场与插件行读 package.json 的 magpie.icon(只收 https:// 或 data:image/,上限 3<<19 字节);
|
||||
// 侧边栏页面图标读 magpie.page.icon(必须落在页面文件所在目录 page/ 内)。
|
||||
import { stat } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { expect, test } from "bun:test";
|
||||
|
||||
const pkg = (await Bun.file(new URL("../package.json", import.meta.url)).json()) as {
|
||||
magpie?: { icon?: string; page?: { icon?: string; file?: string } };
|
||||
};
|
||||
|
||||
test("magpie.icon:data:image URI,且不超过 magpie ownIcon 的 1.5MB 上限", () => {
|
||||
const icon = pkg.magpie?.icon ?? "";
|
||||
expect(icon.startsWith("data:image/")).toBe(true);
|
||||
expect(icon.length).toBeLessThanOrEqual(3 << 19);
|
||||
});
|
||||
|
||||
test("magpie.icon 与 page/icon.svg 是同一张图:插件页卡片与侧边栏图标不能只改一份", async () => {
|
||||
const icon = pkg.magpie?.icon ?? "";
|
||||
const b64 = icon.slice(icon.indexOf(",") + 1);
|
||||
const svg = await Bun.file(new URL("../page/icon.svg", import.meta.url)).text();
|
||||
expect(Buffer.from(b64, "base64").toString("utf8")).toBe(svg);
|
||||
});
|
||||
|
||||
test("magpie.page.icon:文件存在,且在页面文件(page/)所在目录内", async () => {
|
||||
const pageIcon = pkg.magpie?.page?.icon ?? "";
|
||||
const pageFile = pkg.magpie?.page?.file ?? "";
|
||||
expect(pageFile.startsWith("page/")).toBe(true);
|
||||
expect(pageIcon.startsWith("page/")).toBe(true);
|
||||
// 与 magpie page.go 一致:图标相对页面目录解析后不得越出
|
||||
const rel = pageIcon.slice("page/".length);
|
||||
expect(rel).not.toContain("..");
|
||||
expect(rel).not.toMatch(/[/\\]/); // 就放在 page/ 一层,最简单也最稳
|
||||
await expect(stat(resolve(import.meta.dir, "..", pageIcon))).resolves.toBeTruthy();
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
// magpie-files 的单元测试:目录推导、providers.json 读目录(key 指纹)、模型缓存读取。
|
||||
// 夹具一律放临时目录,绝不读真实用户的 Magpie 配置;夹具里的 key 都是假的(sk-test-…),
|
||||
// 并断言它们不出现在任何返回值与错误信息里。
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import path, { join, posix, win32 } from "node:path";
|
||||
import { magpieDirs, readKeyDirectory, readModelCache, xdgConfigHome } from "../src/magpie-files";
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterEach(async () => {
|
||||
while (dirs.length) await rm(dirs.pop()!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function fixtureDir(): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "ww-files-test-"));
|
||||
dirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** 与 magpie internal/provider/keys.go keyID 同一算法:sha256(原文 UTF-8) 前 5 字节的小写 hex */
|
||||
const fp = (key: string): string =>
|
||||
createHash("sha256").update(key, "utf8").digest("hex").slice(0, 10);
|
||||
|
||||
// 夹具专用假 key:只存在于测试里,断言它们绝不外泄
|
||||
const K_GLM = "sk-test-AAAA11";
|
||||
const K_FREE = "sk-test-BBBB22";
|
||||
const K_OTHER = "sk-test-CCCC33";
|
||||
const K_BROKEN = "sk-test-EEEE55";
|
||||
const ALL_FAKE_KEYS = [K_GLM, K_FREE, K_OTHER, K_BROKEN];
|
||||
|
||||
describe("magpieDirs", () => {
|
||||
test("安装版(作用域包名):按安装路径上溯到配置目录,缓存用安装版缓存目录", () => {
|
||||
const d = magpieDirs(
|
||||
{ XDG_CONFIG_HOME: "/tmp/ww-cfg", XDG_CACHE_HOME: "/tmp/ww-cache" },
|
||||
"/tmp/ww-cfg/magpie/plugins/node_modules/@magpie-community/page-window-warmup/dist",
|
||||
posix,
|
||||
);
|
||||
expect(d).toEqual({ config: "/tmp/ww-cfg/magpie", cache: "/tmp/ww-cache/magpie" });
|
||||
});
|
||||
|
||||
test("安装版(XDG 为空):回退 ~/.config/magpie 与 ~/.cache/magpie", () => {
|
||||
const home = homedir();
|
||||
const d = magpieDirs(
|
||||
{},
|
||||
posix.join(home, ".config", "magpie", "plugins", "node_modules", "@magpie-community", "page-window-warmup", "dist"),
|
||||
posix,
|
||||
);
|
||||
expect(d).toEqual({
|
||||
config: posix.join(home, ".config", "magpie"),
|
||||
cache: posix.join(home, ".cache", "magpie"),
|
||||
});
|
||||
});
|
||||
|
||||
test("便携版:配置 = data 目录,缓存 = <data>/cache(XDG 不参与)", () => {
|
||||
const d = magpieDirs(
|
||||
{ XDG_CONFIG_HOME: "/tmp/ww-cfg", XDG_CACHE_HOME: "/tmp/ww-cache" },
|
||||
"/data/magpie-portable/plugins/node_modules/@magpie-community/page-window-warmup/dist",
|
||||
posix,
|
||||
);
|
||||
expect(d).toEqual({ config: "/data/magpie-portable", cache: "/data/magpie-portable/cache" });
|
||||
});
|
||||
|
||||
test("安装版(win32):反斜杠与正斜杠混用都能识别", () => {
|
||||
const env = { XDG_CONFIG_HOME: "C:\\Users\\me\\cfg", XDG_CACHE_HOME: "C:\\Users\\me\\cache" };
|
||||
const back = magpieDirs(
|
||||
env,
|
||||
"C:\\Users\\me\\cfg\\magpie\\plugins\\node_modules\\@magpie-community\\page-window-warmup\\dist",
|
||||
win32,
|
||||
);
|
||||
expect(back).toEqual({ config: "C:\\Users\\me\\cfg\\magpie", cache: "C:\\Users\\me\\cache\\magpie" });
|
||||
const mixed = magpieDirs(
|
||||
env,
|
||||
"C:/Users/me/cfg/magpie/plugins\\node_modules\\@magpie-community\\page-window-warmup/dist",
|
||||
win32,
|
||||
);
|
||||
expect(mixed).toEqual(back);
|
||||
});
|
||||
|
||||
test("便携版(win32):缓存跟 data 目录走", () => {
|
||||
const d = magpieDirs(
|
||||
{ XDG_CONFIG_HOME: "C:\\Users\\me\\cfg" },
|
||||
"D:\\portable\\plugins\\node_modules\\@magpie-community\\page-window-warmup\\dist",
|
||||
win32,
|
||||
);
|
||||
expect(d).toEqual({ config: "D:\\portable", cache: "D:\\portable\\cache" });
|
||||
});
|
||||
|
||||
test("旧独立包名(≤0.3.7)的安装路径同样识别,升级后不会读错目录", () => {
|
||||
const d = magpieDirs(
|
||||
{ XDG_CONFIG_HOME: "/tmp/ww-cfg", XDG_CACHE_HOME: "/tmp/ww-cache" },
|
||||
"/tmp/ww-cfg/magpie/plugins/node_modules/magpie-window-warmup/dist",
|
||||
posix,
|
||||
);
|
||||
expect(d).toEqual({ config: "/tmp/ww-cfg/magpie", cache: "/tmp/ww-cache/magpie" });
|
||||
});
|
||||
|
||||
test("非插件目录:用安装版两个目录", () => {
|
||||
const d = magpieDirs(
|
||||
{ XDG_CONFIG_HOME: "/tmp/ww-cfg", XDG_CACHE_HOME: "/tmp/ww-cache" },
|
||||
"/opt/somewhere/else",
|
||||
posix,
|
||||
);
|
||||
expect(d).toEqual({ config: "/tmp/ww-cfg/magpie", cache: "/tmp/ww-cache/magpie" });
|
||||
});
|
||||
|
||||
test("xdgConfigHome:插件数据目录与旧包迁移共用,相对路径同样不算数", () => {
|
||||
expect(xdgConfigHome({ XDG_CONFIG_HOME: " /tmp/ww-cfg " }, posix)).toBe("/tmp/ww-cfg");
|
||||
expect(xdgConfigHome({ XDG_CONFIG_HOME: "relative/cfg" }, posix)).toBe(posix.join(homedir(), ".config"));
|
||||
expect(xdgConfigHome({}, posix)).toBe(posix.join(homedir(), ".config"));
|
||||
});
|
||||
|
||||
test("XDG 变量是相对路径时不算数(对齐 magpie 的 rooted)", () => {
|
||||
const home = homedir();
|
||||
const d = magpieDirs(
|
||||
{ XDG_CONFIG_HOME: "relative/cfg", XDG_CACHE_HOME: "relative/cache" },
|
||||
"/opt/somewhere/else",
|
||||
posix,
|
||||
);
|
||||
expect(d).toEqual({
|
||||
config: posix.join(home, ".config", "magpie"),
|
||||
cache: posix.join(home, ".cache", "magpie"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("readKeyDirectory", () => {
|
||||
test("列启用的 key(指纹去重),off 的不列,accountModels 原样带出", async () => {
|
||||
const dir = await fixtureDir();
|
||||
await writeFile(
|
||||
join(dir, "providers.json"),
|
||||
JSON.stringify({
|
||||
providers: [
|
||||
{
|
||||
id: "remote-magpie",
|
||||
key: K_GLM,
|
||||
keyName: "GLM",
|
||||
keys: [
|
||||
{ name: "免费flash", key: K_FREE, off: true },
|
||||
{ name: "除GLM外其他", key: K_OTHER },
|
||||
{ name: "重复", key: K_GLM },
|
||||
],
|
||||
accountModels: { [fp(K_GLM)]: ["group/glm-5.3"], yang: ["group/glm-5.3"] },
|
||||
},
|
||||
{ id: "no-keys", key: "", keyName: "", keys: [] },
|
||||
],
|
||||
}),
|
||||
);
|
||||
const map = await readKeyDirectory(dir);
|
||||
expect([...map.keys()].sort()).toEqual(["no-keys", "remote-magpie"]);
|
||||
const entry = map.get("remote-magpie")!;
|
||||
// 第一把 key + keys[] 里启用的;off 的免费flash 不列;与第一把重复的按指纹合并
|
||||
expect(entry.keys).toEqual([
|
||||
{ fingerprint: fp(K_GLM), name: "GLM" },
|
||||
{ fingerprint: fp(K_OTHER), name: "除GLM外其他" },
|
||||
]);
|
||||
expect(entry.accountModels).toEqual({ [fp(K_GLM)]: ["group/glm-5.3"], yang: ["group/glm-5.3"] });
|
||||
expect(map.get("no-keys")).toEqual({ keys: [], accountModels: {} });
|
||||
|
||||
// 红线:key 原文不出现在任何返回值里
|
||||
const serialized = JSON.stringify([...map.entries()]);
|
||||
for (const key of ALL_FAKE_KEYS) expect(serialized).not.toContain(key);
|
||||
});
|
||||
|
||||
test("文件不存在 → 空 Map", async () => {
|
||||
const dir = await fixtureDir();
|
||||
const map = await readKeyDirectory(dir);
|
||||
expect(map.size).toBe(0);
|
||||
});
|
||||
|
||||
test("损坏文件 → 抛固定文案,错误信息不含 key 原文", async () => {
|
||||
const dir = await fixtureDir();
|
||||
await writeFile(
|
||||
join(dir, "providers.json"),
|
||||
`{"providers":[{"id":"p","key":"${K_BROKEN}","keyNa`,
|
||||
);
|
||||
let message = "";
|
||||
try {
|
||||
await readKeyDirectory(dir);
|
||||
} catch (e) {
|
||||
message = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
expect(message).toBe("Magpie 的供应商配置文件读不出来");
|
||||
for (const key of ALL_FAKE_KEYS) expect(message).not.toContain(key);
|
||||
});
|
||||
});
|
||||
|
||||
describe("readModelCache", () => {
|
||||
test("正常读取:ID 与 Keys(缺省为空)", async () => {
|
||||
const dir = await fixtureDir();
|
||||
await mkdir(join(dir, "models"), { recursive: true });
|
||||
await writeFile(
|
||||
join(dir, "models", "remote-magpie.json"),
|
||||
JSON.stringify({
|
||||
fetched: "2026-11-01T00:00:00Z",
|
||||
base: "https://x.test",
|
||||
models: [
|
||||
{ ID: "group/glm-5.3", Keys: [fp(K_GLM)] },
|
||||
{ ID: "qwen-token-plan/qwen3.8-flash" },
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(await readModelCache(dir, "remote-magpie")).toEqual([
|
||||
{ id: "group/glm-5.3", keys: [fp(K_GLM)] },
|
||||
{ id: "qwen-token-plan/qwen3.8-flash", keys: [] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("文件缺失 / 坏 JSON / 形状不对 → null", async () => {
|
||||
const dir = await fixtureDir();
|
||||
await mkdir(join(dir, "models"), { recursive: true });
|
||||
expect(await readModelCache(dir, "absent")).toBeNull();
|
||||
await writeFile(join(dir, "models", "broken.json"), "{oops");
|
||||
expect(await readModelCache(dir, "broken")).toBeNull();
|
||||
await writeFile(join(dir, "models", "shape1.json"), JSON.stringify({ models: "x" }));
|
||||
expect(await readModelCache(dir, "shape1")).toBeNull();
|
||||
await writeFile(join(dir, "models", "shape2.json"), JSON.stringify({ models: [{ id: "x" }] }));
|
||||
expect(await readModelCache(dir, "shape2")).toBeNull();
|
||||
await writeFile(
|
||||
join(dir, "models", "shape3.json"),
|
||||
JSON.stringify({ models: [{ ID: "x", Keys: "y" }] }),
|
||||
);
|
||||
expect(await readModelCache(dir, "shape3")).toBeNull();
|
||||
});
|
||||
|
||||
test("路径穿越 id → null,不读盘", async () => {
|
||||
const dir = await fixtureDir();
|
||||
await mkdir(join(dir, "models"), { recursive: true });
|
||||
await writeFile(join(dir, "models", "evil.json"), JSON.stringify({ models: [] }));
|
||||
for (const bad of ["a/b", "..", "a\\b", "a/../b", ""]) {
|
||||
expect(await readModelCache(dir, bad)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { lastDue, nextDaily, nextEvery, upcoming, validateTask, windowDue } from "../src/rules";
|
||||
import type { Trigger } from "../src/types";
|
||||
|
||||
test("rules 只依赖 types:页面直接打包它,引入 node:* 或网关模块会让浏览器端构建失效", () => {
|
||||
for (const file of ["rules.ts", "types.ts"]) {
|
||||
const src = readFileSync(join(import.meta.dir, "..", "src", file), "utf8");
|
||||
const imports = [...src.matchAll(/^import[^;]*?from\s+"([^"]+)"/gms)].map((m) => m[1]);
|
||||
expect(imports.filter((s) => s !== "./types")).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
const SH = "Asia/Shanghai";
|
||||
const NY = "America/New_York";
|
||||
|
||||
const ms = (iso: string) => new Date(iso).getTime();
|
||||
|
||||
describe("nextDaily", () => {
|
||||
test("上海:05:00 之后下一次 06:00 是当天", () => {
|
||||
expect(nextDaily({ time: "06:00", timeZone: SH }, new Date("2026-10-31T05:00:00+08:00")).getTime())
|
||||
.toBe(ms("2026-10-31T06:00:00+08:00"));
|
||||
});
|
||||
|
||||
test("after 恰为 06:00 → 次日 06:00", () => {
|
||||
expect(nextDaily({ time: "06:00", timeZone: SH }, new Date("2026-10-31T06:00:00+08:00")).getTime())
|
||||
.toBe(ms("2026-11-01T06:00:00+08:00"));
|
||||
});
|
||||
|
||||
test("纽约春令时:02:30 不存在 → 跳变后第一个有效时刻 03:00(EDT)", () => {
|
||||
expect(nextDaily({ time: "02:30", timeZone: NY }, new Date("2026-03-08T00:00:00-05:00")).getTime())
|
||||
.toBe(ms("2026-03-08T03:00:00-04:00"));
|
||||
});
|
||||
|
||||
test("纽约秋令时:01:30 出现两次 → 取较早的 EDT 实例", () => {
|
||||
expect(nextDaily({ time: "01:30", timeZone: NY }, new Date("2026-11-01T00:00:00-04:00")).getTime())
|
||||
.toBe(ms("2026-11-01T01:30:00-04:00"));
|
||||
});
|
||||
|
||||
test("纽约秋令时:EDT 实例已过 → 同日较晚的 EST 实例", () => {
|
||||
expect(nextDaily({ time: "01:30", timeZone: NY }, new Date("2026-11-01T01:45:00-04:00")).getTime())
|
||||
.toBe(ms("2026-11-01T01:30:00-05:00"));
|
||||
});
|
||||
|
||||
test("纽约秋令时:02:30 当天不受跳变影响(EST)", () => {
|
||||
expect(nextDaily({ time: "02:30", timeZone: NY }, new Date("2026-11-01T00:00:00-04:00")).getTime())
|
||||
.toBe(ms("2026-11-01T02:30:00-05:00"));
|
||||
});
|
||||
|
||||
test("春令时跳变:结果毫秒精确到跳变边界(二分提前停止会带 ≤999ms 误差)", () => {
|
||||
// 跳变瞬间是 07:00:00Z;02:01 与 02:04 的二分区间奇偶不同,修复前分别落在 .234Z / .058Z
|
||||
expect(nextDaily({ time: "02:01", timeZone: NY }, new Date("2026-03-08T00:00:00-05:00")).getTime())
|
||||
.toBe(ms("2026-03-08T03:00:00-04:00"));
|
||||
expect(nextDaily({ time: "02:04", timeZone: NY }, new Date("2026-03-08T00:00:00-05:00")).getTime())
|
||||
.toBe(ms("2026-03-08T03:00:00-04:00"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextEvery", () => {
|
||||
const t = { hours: 5, anchor: "2026-10-31T09:30:00+08:00" };
|
||||
|
||||
test("anchor 09:30 起每 5 小时:14:29 → 14:30", () => {
|
||||
expect(nextEvery(t, new Date("2026-10-31T14:29:00+08:00")).getTime())
|
||||
.toBe(ms("2026-10-31T14:30:00+08:00"));
|
||||
});
|
||||
|
||||
test("after 早于 anchor → anchor", () => {
|
||||
expect(nextEvery(t, new Date("2026-10-31T08:00:00+08:00")).getTime())
|
||||
.toBe(ms("2026-10-31T09:30:00+08:00"));
|
||||
});
|
||||
|
||||
test("after 恰为到期点 → 下一个点(严格晚于)", () => {
|
||||
expect(nextEvery(t, new Date("2026-10-31T14:30:00+08:00")).getTime())
|
||||
.toBe(ms("2026-10-31T19:30:00+08:00"));
|
||||
});
|
||||
|
||||
test("hours <= 0 → 抛错(正常路径有校验,这里防未校验来源除零)", () => {
|
||||
expect(() => nextEvery({ hours: 0, anchor: t.anchor }, new Date("2026-10-31T14:29:00+08:00")))
|
||||
.toThrow(/间隔/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lastDue", () => {
|
||||
const daily: Trigger = { kind: "daily", time: "06:00", timeZone: SH };
|
||||
const every: Trigger = { kind: "every", hours: 5, anchor: "2026-10-31T09:30:00+08:00" };
|
||||
|
||||
test("daily:07:00 之前最近的应到点是当天 06:00", () => {
|
||||
expect(lastDue(daily, new Date("2026-10-31T07:00:00+08:00"))?.getTime())
|
||||
.toBe(ms("2026-10-31T06:00:00+08:00"));
|
||||
});
|
||||
|
||||
test("daily:05:00 之前最近的应到点是前一天 06:00", () => {
|
||||
expect(lastDue(daily, new Date("2026-10-31T05:00:00+08:00"))?.getTime())
|
||||
.toBe(ms("2026-10-30T06:00:00+08:00"));
|
||||
});
|
||||
|
||||
test("every:14:29 之前最近的应到点是 anchor", () => {
|
||||
expect(lastDue(every, new Date("2026-10-31T14:29:00+08:00"))?.getTime())
|
||||
.toBe(ms("2026-10-31T09:30:00+08:00"));
|
||||
});
|
||||
|
||||
test("every:19:00 之前最近的应到点是 14:30", () => {
|
||||
expect(lastDue(every, new Date("2026-10-31T19:00:00+08:00"))?.getTime())
|
||||
.toBe(ms("2026-10-31T14:30:00+08:00"));
|
||||
});
|
||||
|
||||
test("every:before 早于 anchor → null", () => {
|
||||
expect(lastDue(every, new Date("2026-10-31T08:00:00+08:00"))).toBeNull();
|
||||
});
|
||||
|
||||
test("window 触发没有几何上的应到点 → null", () => {
|
||||
expect(lastDue({ kind: "window", window: "5h" }, new Date())).toBeNull();
|
||||
});
|
||||
|
||||
test("every:hours <= 0 → null(不产生几何点)", () => {
|
||||
expect(lastDue({ kind: "every", hours: 0, anchor: "2026-10-31T09:30:00+08:00" }, new Date()))
|
||||
.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("windowDue", () => {
|
||||
test("resetsAt 在未来 → at = resetsAt + 30s,resetKey = resetsAt", () => {
|
||||
const r = windowDue(
|
||||
{ name: "5h", used: 3, resetsAt: "2026-10-31T14:32:00+08:00" },
|
||||
new Date("2026-10-31T10:00:00+08:00"),
|
||||
);
|
||||
expect("error" in r).toBe(false);
|
||||
if (!("error" in r)) {
|
||||
expect(r.at.getTime()).toBe(ms("2026-10-31T14:32:30+08:00"));
|
||||
expect(r.resetKey).toBe("2026-10-31T14:32:00+08:00");
|
||||
}
|
||||
});
|
||||
|
||||
test("resetsAt 为 null(窗口空闲):同一小时的两个快照共享 idle resetKey", () => {
|
||||
const a = windowDue({ name: "5h", used: 0, resetsAt: null }, new Date("2026-10-31T10:05:00+08:00"));
|
||||
const b = windowDue({ name: "5h", used: 0, resetsAt: null }, new Date("2026-10-31T10:55:00+08:00"));
|
||||
expect("error" in a).toBe(false);
|
||||
expect("error" in b).toBe(false);
|
||||
if (!("error" in a) && !("error" in b)) {
|
||||
expect(a.resetKey).toBe(b.resetKey);
|
||||
expect(a.resetKey.startsWith("idle:")).toBe(true);
|
||||
expect(a.at.getTime()).toBe(ms("2026-10-31T10:05:00+08:00"));
|
||||
expect(b.at.getTime()).toBe(ms("2026-10-31T10:55:00+08:00"));
|
||||
}
|
||||
});
|
||||
|
||||
test("resetsAt 已过 → 视为空闲,立即到期", () => {
|
||||
const r = windowDue(
|
||||
{ name: "5h", used: 0, resetsAt: "2026-10-31T09:00:00+08:00" },
|
||||
new Date("2026-10-31T10:05:00+08:00"),
|
||||
);
|
||||
expect("error" in r).toBe(false);
|
||||
if (!("error" in r)) {
|
||||
expect(r.at.getTime()).toBe(ms("2026-10-31T10:05:00+08:00"));
|
||||
expect(r.resetKey.startsWith("idle:")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("账号的额度里没有这个窗口 → error", () => {
|
||||
const r = windowDue(undefined, new Date("2026-10-31T10:00:00+08:00"));
|
||||
expect("error" in r && r.error === "账号的额度里没有这个窗口").toBe(true);
|
||||
});
|
||||
|
||||
test("resetsAt 无法解析(truthy 但非时间)→ 按空闲每小时限频", () => {
|
||||
const r = windowDue(
|
||||
{ name: "5h", used: 0, resetsAt: "not-a-date" },
|
||||
new Date("2026-10-31T10:05:00+08:00"),
|
||||
);
|
||||
expect("error" in r).toBe(false);
|
||||
if (!("error" in r)) {
|
||||
expect(r.resetKey.startsWith("idle:")).toBe(true);
|
||||
expect(r.at.getTime()).toBe(ms("2026-10-31T10:05:00+08:00"));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("upcoming", () => {
|
||||
test("daily:给出未来 3 个点", () => {
|
||||
const pts = upcoming({ kind: "daily", time: "06:00", timeZone: SH }, new Date("2026-10-31T07:00:00+08:00"), 3);
|
||||
expect(pts.map((p) => p.getTime())).toEqual([
|
||||
ms("2026-11-01T06:00:00+08:00"),
|
||||
ms("2026-11-02T06:00:00+08:00"),
|
||||
ms("2026-11-03T06:00:00+08:00"),
|
||||
]);
|
||||
});
|
||||
|
||||
test("every:给出未来 2 个点", () => {
|
||||
const pts = upcoming(
|
||||
{ kind: "every", hours: 5, anchor: "2026-10-31T09:30:00+08:00" },
|
||||
new Date("2026-10-31T14:29:00+08:00"), 2,
|
||||
);
|
||||
expect(pts.map((p) => p.getTime())).toEqual([
|
||||
ms("2026-10-31T14:30:00+08:00"),
|
||||
ms("2026-10-31T19:30:00+08:00"),
|
||||
]);
|
||||
});
|
||||
|
||||
test("window 触发依赖额度快照,由调度层单独计算 → 空数组", () => {
|
||||
expect(upcoming({ kind: "window", window: "5h" }, new Date(), 3)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateTask", () => {
|
||||
const now = new Date("2026-10-31T09:00:00+08:00");
|
||||
const base = {
|
||||
name: "早报",
|
||||
provider: "openai",
|
||||
account: "acc-1",
|
||||
model: "gpt-5",
|
||||
trigger: { kind: "daily", time: "06:00", timeZone: SH },
|
||||
};
|
||||
|
||||
test("合法 daily 任务:缺省 message=hi、enabled=true", () => {
|
||||
const r = validateTask(base, now);
|
||||
expect("task" in r).toBe(true);
|
||||
if ("task" in r) {
|
||||
expect(r.task.message).toBe("hi");
|
||||
expect(r.task.enabled).toBe(true);
|
||||
expect(r.task.trigger).toEqual({ kind: "daily", time: "06:00", timeZone: SH });
|
||||
}
|
||||
});
|
||||
|
||||
test("account 为空(账号必选,不分触发)→ field account", () => {
|
||||
const r = validateTask({ ...base, account: "" }, now);
|
||||
expect("error" in r && r.field === "account").toBe(true);
|
||||
});
|
||||
|
||||
test("名称为空 → field name", () => {
|
||||
const checked = validateTask({ ...base, name: " " }, now);
|
||||
expect("error" in checked && checked.field === "name").toBe(true);
|
||||
});
|
||||
|
||||
test("名称超过 40 字 → field name;恰好 40 字 → 通过", () => {
|
||||
const long = validateTask({ ...base, name: "字".repeat(41) }, now);
|
||||
expect("error" in long && long.field === "name").toBe(true);
|
||||
const edge = validateTask({ ...base, name: "字".repeat(40) }, now);
|
||||
expect("task" in edge).toBe(true);
|
||||
});
|
||||
|
||||
test("路由组模型(group/ 开头)不接受 → field model", () => {
|
||||
const r = validateTask({ ...base, model: "group/auto" }, now);
|
||||
expect("error" in r && r.field === "model").toBe(true);
|
||||
});
|
||||
|
||||
test("model 为空串 → 通过,表示由供应商自动选模型", () => {
|
||||
const r = validateTask({ ...base, model: "" }, now);
|
||||
expect("task" in r).toBe(true);
|
||||
if ("task" in r) expect(r.task.model).toBe("");
|
||||
// 纯空白同样归一成自动
|
||||
const blank = validateTask({ ...base, model: " " }, now);
|
||||
expect("task" in blank && blank.task.model === "").toBe(true);
|
||||
});
|
||||
|
||||
test("非法时区 → field timeZone", () => {
|
||||
const r = validateTask({ ...base, trigger: { kind: "daily", time: "06:00", timeZone: "Mars/Olympus" } }, now);
|
||||
expect("error" in r && r.field === "timeZone").toBe(true);
|
||||
});
|
||||
|
||||
test("time 非 HH:MM → field time", () => {
|
||||
for (const time of ["6:00", "25:00", "06:60"]) {
|
||||
const r = validateTask({ ...base, trigger: { kind: "daily", time, timeZone: SH } }, now);
|
||||
expect("error" in r && r.field === "time").toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("hours 越界(0 与 200)→ field hours", () => {
|
||||
for (const hours of [0, 200]) {
|
||||
const r = validateTask({ ...base, trigger: { kind: "every", hours } }, now);
|
||||
expect("error" in r && r.field === "hours").toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("every 缺省 anchor → 取创建时刻并取整到分钟", () => {
|
||||
const at = new Date("2026-10-31T09:30:47+08:00");
|
||||
const r = validateTask({ ...base, trigger: { kind: "every", hours: 5 } }, at);
|
||||
expect("task" in r).toBe(true);
|
||||
if ("task" in r) {
|
||||
expect(r.task.trigger).toEqual({ kind: "every", hours: 5, anchor: "2026-10-31T01:30:00.000Z" });
|
||||
}
|
||||
});
|
||||
|
||||
test("every 提供非法 anchor → field anchor", () => {
|
||||
const r = validateTask({ ...base, trigger: { kind: "every", hours: 5, anchor: "not-a-date" } }, now);
|
||||
expect("error" in r && r.field === "anchor").toBe(true);
|
||||
});
|
||||
|
||||
test("message 字段忽略,一律存 hi(旧长度校验不再存在)", () => {
|
||||
const long = validateTask({ ...base, message: "字".repeat(201) }, now);
|
||||
expect("task" in long).toBe(true);
|
||||
if ("task" in long) expect(long.task.message).toBe("hi");
|
||||
// 类型不对的字段同样忽略
|
||||
const weird = validateTask({ ...base, message: 42 }, now);
|
||||
expect("task" in weird).toBe(true);
|
||||
if ("task" in weird) expect(weird.task.message).toBe("hi");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,509 @@
|
||||
// 本地服务的失败测试:端口 0、假网关、临时目录,不发任何真实请求。
|
||||
// 覆盖:静态首页注入 boot JSON、鉴权(token/Host/Origin)、CRUD 与立即发送往返、
|
||||
// 状态文件损坏(fatal)、单实例锁被占(lockedBy)。
|
||||
import { afterAll, beforeAll, expect, test } from "bun:test";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, posix, win32 } from "node:path";
|
||||
import plugin from "../src/plugin";
|
||||
import { alreadyServing, insideDir, startService, type ServiceHandle } from "../src/server";
|
||||
import { fakeGateway, type FakeGateway } from "./fake-gateway";
|
||||
|
||||
const services: ServiceHandle[] = [];
|
||||
const gateways: FakeGateway[] = [];
|
||||
const dirs: string[] = [];
|
||||
afterAll(async () => {
|
||||
while (services.length) await services.pop()!.stop();
|
||||
for (const gw of gateways.splice(0)) gw.stop();
|
||||
while (dirs.length) await rm(dirs.pop()!, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const MODELS = [{ id: "p1/m1", owned_by: "p1", reasoning: false }];
|
||||
|
||||
interface Harness {
|
||||
svc: ServiceHandle;
|
||||
token: string;
|
||||
boot: Record<string, unknown>;
|
||||
dir: string;
|
||||
gw: FakeGateway;
|
||||
api: (path: string, init?: RequestInit) => Promise<Response>;
|
||||
}
|
||||
|
||||
async function harness(
|
||||
opts: {
|
||||
state?: string;
|
||||
lockPid?: number;
|
||||
confirmLockAlive?: (pid: number) => Promise<boolean>;
|
||||
} = {},
|
||||
): Promise<Harness> {
|
||||
const gw = fakeGateway({ models: MODELS });
|
||||
gateways.push(gw);
|
||||
const dir = await mkdtemp(join(tmpdir(), "sm-server-test-"));
|
||||
dirs.push(dir);
|
||||
if (opts.state !== undefined) await writeFile(join(dir, "state.json"), opts.state);
|
||||
if (opts.lockPid !== undefined) await writeFile(join(dir, "service.lock"), String(opts.lockPid));
|
||||
const svc = await startService({
|
||||
port: 0,
|
||||
dir,
|
||||
base: gw.base,
|
||||
confirmLockAlive: opts.confirmLockAlive,
|
||||
});
|
||||
services.push(svc);
|
||||
const base = `http://127.0.0.1:${svc.port}`;
|
||||
const html = await (await fetch(base)).text();
|
||||
const m = /<script type="application\/json" id="boot"[^>]*>([\s\S]*?)<\/script>/.exec(html);
|
||||
if (!m) throw new Error(`首页缺少 boot 数据块:${html.slice(0, 200)}`);
|
||||
const boot = JSON.parse(m[1]) as Record<string, unknown>;
|
||||
const token = String(boot.token ?? "");
|
||||
const api = (path: string, init: RequestInit = {}) =>
|
||||
fetch(base + path, {
|
||||
...init,
|
||||
headers: {
|
||||
"x-window-warmup-token": token,
|
||||
"content-type": "application/json",
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
return { svc, token, boot, dir, gw, api };
|
||||
}
|
||||
|
||||
const DAILY = {
|
||||
name: "早报",
|
||||
provider: "p1",
|
||||
account: "acct-1",
|
||||
model: "p1/m1",
|
||||
message: "hi",
|
||||
trigger: { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" },
|
||||
};
|
||||
|
||||
test("首页注入 nonce boot JSON(含 token)并带 CSP", async () => {
|
||||
const { svc, token } = await harness();
|
||||
const res = await fetch(`http://127.0.0.1:${svc.port}/?theme=dark`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("text/html");
|
||||
const html = await res.text();
|
||||
const nonce = /id="boot"[^>]*\bnonce="([^"]+)"/.exec(html)?.[1];
|
||||
expect(nonce).toBeTruthy();
|
||||
const bootData = JSON.parse(
|
||||
/<script type="application\/json" id="boot"[^>]*>([\s\S]*?)<\/script>/.exec(html)![1],
|
||||
) as { theme?: string };
|
||||
expect(bootData.theme).toBe("dark");
|
||||
const csp = res.headers.get("content-security-policy") ?? "";
|
||||
expect(csp).toContain("default-src 'self'");
|
||||
expect(csp).toContain("script-src 'self'");
|
||||
// sandbox 框架里 WebKit 的 'self' 匹配不上 opaque origin,必须另带 scheme 源,否则 Safari 下 /api/* 全被拦
|
||||
expect(csp).toContain("connect-src 'self' http: https:");
|
||||
expect(csp).toContain("frame-ancestors *");
|
||||
expect(csp).toContain(`nonce-${nonce}`);
|
||||
expect(token).toMatch(/^[0-9a-f]{64}$/); // 32 字节 hex
|
||||
expect(token).not.toContain("<");
|
||||
// 本插件服务的自标记:plugin.ts 启动前探测它,识别「已经在跑」
|
||||
expect(res.headers.get("x-window-warmup")).toBe("1");
|
||||
// 首页带着口令,绝不能带 CORS——别的页面读不到它
|
||||
expect(res.headers.get("access-control-allow-origin")).toBeNull();
|
||||
});
|
||||
|
||||
test("CORS:沙箱页(Origin null)能读到 API、错误与模块脚本,自身来源原样反射", async () => {
|
||||
const { svc, api } = await harness();
|
||||
const base = `http://127.0.0.1:${svc.port}`;
|
||||
// API 200:null 反射
|
||||
const ok = await api("/api/state", { headers: { origin: "null" } });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.headers.get("access-control-allow-origin")).toBe("null");
|
||||
expect(ok.headers.get("access-control-allow-headers")).toContain("x-window-warmup-token");
|
||||
// 无 Origin(同源 GET、带 token)也放行并给 ACAO null
|
||||
const noOrigin = await api("/api/state");
|
||||
expect(noOrigin.status).toBe(200);
|
||||
expect(noOrigin.headers.get("access-control-allow-origin")).toBe("null");
|
||||
// 错误响应(401/400)同样带 ACAO,否则沙箱页只看到 Failed to fetch
|
||||
const unauth = await fetch(`${base}/api/state`);
|
||||
expect(unauth.status).toBe(401);
|
||||
expect(unauth.headers.get("access-control-allow-origin")).toBe("null");
|
||||
const invalid = await api("/api/tasks", { method: "POST", body: "{}", headers: { origin: "null" } });
|
||||
expect(invalid.status).toBe(400);
|
||||
expect(invalid.headers.get("access-control-allow-origin")).toBe("null");
|
||||
// 自身 Origin 原样反射
|
||||
const own = await api("/api/state", { headers: { origin: `http://127.0.0.1:${svc.port}` } });
|
||||
expect(own.headers.get("access-control-allow-origin")).toBe(`http://127.0.0.1:${svc.port}`);
|
||||
// 非法 Origin 仍在入口被拒
|
||||
expect((await api("/api/state", { headers: { origin: "https://evil.test" } })).status).toBe(403);
|
||||
// 非法 Origin 的 403 也不外泄该来源(ACAO 落到 null,浏览器照样拦)
|
||||
const rejected = await api("/api/state", { headers: { origin: "https://evil.test" } });
|
||||
expect(rejected.headers.get("access-control-allow-origin")).toBe("null");
|
||||
// 模块脚本固定以 CORS 模式获取:opaque origin 下没有 ACAO 连 app.js 都加载不了
|
||||
const js = await fetch(`${base}/app.js`, { headers: { origin: "null" } });
|
||||
expect(js.status).toBe(200);
|
||||
expect(js.headers.get("access-control-allow-origin")).toBe("null");
|
||||
const css = await fetch(`${base}/style.css`, { headers: { origin: "null" } });
|
||||
expect(css.headers.get("access-control-allow-origin")).toBe("null");
|
||||
// OPTIONS 预检保持可用
|
||||
const pre = await fetch(`${base}/api/state`, { method: "OPTIONS", headers: { origin: "null" } });
|
||||
expect(pre.status).toBe(204);
|
||||
expect(pre.headers.get("access-control-allow-origin")).toBe("null");
|
||||
});
|
||||
|
||||
test("/api/state 鉴权:缺 token → 401,带 token → 200 空状态", async () => {
|
||||
const { svc } = await harness();
|
||||
const base = `http://127.0.0.1:${svc.port}`;
|
||||
expect((await fetch(`${base}/api/state`)).status).toBe(401);
|
||||
expect(
|
||||
(await fetch(`${base}/api/state`, { headers: { "x-window-warmup-token": "bad" } })).status,
|
||||
).toBe(401);
|
||||
const ok = await fetch(base + "/api/state", {
|
||||
headers: { "x-window-warmup-token": "x".repeat(64) },
|
||||
});
|
||||
// 错 token 也是 401;正确 token 才 200 —— 用 harness 的 api 再验一次
|
||||
expect(ok.status).toBe(401);
|
||||
const h = await harness();
|
||||
const state = (await (await h.api("/api/state")).json()) as Record<string, unknown>;
|
||||
expect(state.tasks).toEqual([]);
|
||||
expect(state.runs).toEqual([]);
|
||||
expect(state.saveError).toBeNull();
|
||||
expect(state.fatal ?? null).toBeNull();
|
||||
});
|
||||
|
||||
test("Host 与 Origin 校验:错 Host 403、外站 Origin 403、Origin null 放行", async () => {
|
||||
const { svc, api } = await harness();
|
||||
const base = `http://127.0.0.1:${svc.port}`;
|
||||
const evil = (await fetch(base + "/api/state", {
|
||||
headers: { host: `evil.test:${svc.port}`, "x-window-warmup-token": "x".repeat(64) },
|
||||
})).status;
|
||||
expect(evil).toBe(403);
|
||||
expect(
|
||||
(await api("/api/state", { headers: { origin: "https://evil.test" } })).status,
|
||||
).toBe(403);
|
||||
expect((await api("/api/state", { headers: { origin: "null" } })).status).toBe(200);
|
||||
expect((await api("/api/state", { headers: { host: `localhost:${svc.port}` } })).status).toBe(200);
|
||||
});
|
||||
|
||||
test("POST /api/tasks 非法 → 400 且带 field", async () => {
|
||||
const { api } = await harness();
|
||||
const r1 = (await (await api("/api/tasks", { method: "POST", body: "{}" })).json()) as {
|
||||
error: string;
|
||||
field?: string;
|
||||
};
|
||||
expect(r1.field).toBe("name");
|
||||
const res3 = await api("/api/tasks", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ...DAILY, trigger: { kind: "alien" } }),
|
||||
});
|
||||
expect(res3.status).toBe(400);
|
||||
});
|
||||
|
||||
test("model 为空串(自动选模型)可通过 API 保存", async () => {
|
||||
const { api } = await harness();
|
||||
const res = await api("/api/tasks", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ...DAILY, model: "" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(((await res.json()) as { model: string }).model).toBe("");
|
||||
});
|
||||
|
||||
test("完整 CRUD 与立即发送往返", async () => {
|
||||
const { api } = await harness();
|
||||
// 新建
|
||||
const created = await api("/api/tasks", { method: "POST", body: JSON.stringify(DAILY) });
|
||||
expect(created.status).toBe(200);
|
||||
const task = (await created.json()) as { id: string; createdAt: string; updatedAt: string };
|
||||
expect(task.id).toBeTruthy();
|
||||
// 列表可见
|
||||
interface StateShape {
|
||||
tasks: { id: string }[];
|
||||
runs: { taskId: string; outcome: string; reason: string; source: string }[];
|
||||
next: Record<string, string | null>;
|
||||
timeline: { taskId: string }[];
|
||||
}
|
||||
let state = (await (await api("/api/state")).json()) as StateShape;
|
||||
expect(state.tasks.map((t) => t.id)).toEqual([task.id]);
|
||||
expect(state.next[task.id]).toBeTruthy();
|
||||
expect(state.timeline.some((p) => p.taskId === task.id)).toBe(true);
|
||||
// 更新
|
||||
const renamed = await api(`/api/tasks/${task.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...DAILY, name: "晚报" }),
|
||||
});
|
||||
expect(renamed.status).toBe(200);
|
||||
const afterRename = (await renamed.json()) as { name: string; updatedAt: string };
|
||||
expect(afterRename.name).toBe("晚报");
|
||||
expect(afterRename.updatedAt >= task.updatedAt).toBe(true);
|
||||
// 停用:next 为 null,不进时间轴
|
||||
await api(`/api/tasks/${task.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...DAILY, name: "晚报", enabled: false }),
|
||||
});
|
||||
state = (await (await api("/api/state")).json()) as StateShape;
|
||||
expect(state.next[task.id]).toBeNull();
|
||||
expect(state.timeline.some((p) => p.taskId === task.id)).toBe(false);
|
||||
await api(`/api/tasks/${task.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...DAILY, name: "晚报", enabled: true }),
|
||||
});
|
||||
// 立即发送:先返回 running 记录,随后落为 ok
|
||||
const run = await api(`/api/tasks/${task.id}/run`, { method: "POST" });
|
||||
expect(run.status).toBe(200);
|
||||
expect(((await run.json()) as { outcome: string }).outcome).toBe("running");
|
||||
let finished: { outcome: string; reason: string; source: string } | undefined;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const s = (await (await api("/api/state")).json()) as {
|
||||
runs: { taskId: string; outcome: string; reason: string; source: string }[];
|
||||
};
|
||||
const mine = s.runs.find((r) => r.taskId === task.id);
|
||||
if (mine && mine.outcome !== "running") {
|
||||
finished = mine;
|
||||
break;
|
||||
}
|
||||
await Bun.sleep(30);
|
||||
}
|
||||
expect(finished?.outcome).toBe("ok");
|
||||
expect(finished?.reason).toBe("");
|
||||
expect(finished?.source).toBe("manual");
|
||||
// 发送中再点一次 → 409(换个长延迟任务验证)
|
||||
// 删除
|
||||
expect((await api(`/api/tasks/${task.id}`, { method: "DELETE" })).status).toBe(200);
|
||||
state = (await (await api("/api/state")).json()) as StateShape;
|
||||
expect(state.tasks).toEqual([]);
|
||||
expect(state.runs).toEqual([]);
|
||||
expect((await api(`/api/tasks/${task.id}`, { method: "DELETE" })).status).toBe(404);
|
||||
});
|
||||
|
||||
test("发送进行中重复 run → 409", async () => {
|
||||
const gw = fakeGateway({
|
||||
models: MODELS,
|
||||
chat: { delayMs: 400 },
|
||||
});
|
||||
gateways.push(gw);
|
||||
const dir = await mkdtemp(join(tmpdir(), "sm-server-test-"));
|
||||
dirs.push(dir);
|
||||
const svc = await startService({ port: 0, dir, base: gw.base });
|
||||
services.push(svc);
|
||||
const bootHtml = await (await fetch(`http://127.0.0.1:${svc.port}/`)).text();
|
||||
const token = String(
|
||||
JSON.parse(
|
||||
/<script type="application\/json" id="boot"[^>]*>([\s\S]*?)<\/script>/.exec(bootHtml)![1],
|
||||
).token,
|
||||
);
|
||||
const api = (path: string, init: RequestInit = {}) =>
|
||||
fetch(`http://127.0.0.1:${svc.port}${path}`, {
|
||||
...init,
|
||||
headers: { "x-window-warmup-token": token, ...init.headers },
|
||||
});
|
||||
const created = await api("/api/tasks", { method: "POST", body: JSON.stringify(DAILY) });
|
||||
const task = (await created.json()) as { id: string };
|
||||
const first = await api(`/api/tasks/${task.id}/run`, { method: "POST" });
|
||||
expect(first.status).toBe(200);
|
||||
const second = await api(`/api/tasks/${task.id}/run`, { method: "POST" });
|
||||
expect(second.status).toBe(409);
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const s = (await (await api("/api/state")).json()) as {
|
||||
runs: { outcome: string }[];
|
||||
};
|
||||
if (s.runs.every((r) => r.outcome !== "running")) break;
|
||||
await Bun.sleep(30);
|
||||
}
|
||||
});
|
||||
|
||||
test("状态文件损坏 → /api/state 返回 fatal,不启动调度,原文件不动", async () => {
|
||||
const broken = '{"version":1,"tasks":';
|
||||
const { api, dir } = await harness({ state: broken });
|
||||
const state = (await (await api("/api/state")).json()) as {
|
||||
fatal?: string;
|
||||
tasks: unknown[];
|
||||
};
|
||||
expect(typeof state.fatal).toBe("string");
|
||||
expect(state.fatal).toBeTruthy();
|
||||
expect(state.tasks).toEqual([]);
|
||||
expect((await api("/api/tasks", { method: "POST", body: JSON.stringify(DAILY) })).status).toBe(
|
||||
503,
|
||||
);
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(broken);
|
||||
});
|
||||
|
||||
test("不认识的版本号同样 fatal", async () => {
|
||||
const { api } = await harness({ state: '{"version":2,"tasks":[],"runs":[],"marks":{}}' });
|
||||
const state = (await (await api("/api/state")).json()) as { fatal?: string };
|
||||
expect(state.fatal).toContain("版本");
|
||||
});
|
||||
|
||||
test("锁被占(持有者确认在服务)→ /api/state 返回 lockedBy,不启动调度", async () => {
|
||||
const { api } = await harness({ lockPid: process.pid, confirmLockAlive: async () => true });
|
||||
const state = (await (await api("/api/state")).json()) as {
|
||||
lockedBy?: number;
|
||||
fatal?: string;
|
||||
tasks: unknown[];
|
||||
};
|
||||
expect(state.lockedBy).toBe(process.pid);
|
||||
expect(state.fatal ?? null).toBeNull();
|
||||
expect(state.tasks).toEqual([]);
|
||||
expect((await api("/api/tasks", { method: "POST", body: JSON.stringify(DAILY) })).status).toBe(
|
||||
503,
|
||||
);
|
||||
});
|
||||
|
||||
test("锁被占但持有者并未在服务(pid 被复用)→ 接管陈旧锁,正常读写", async () => {
|
||||
// Docker 上容器重建后 pid 会被无关进程(比如 magpie 自己)复用,卷上的旧锁是假阳性;
|
||||
// 缺省确认走端口探测,port 0 必然无人应答 → 必须接管而不是只读
|
||||
const h = await harness({ lockPid: process.pid });
|
||||
const state = (await (await h.api("/api/state")).json()) as { lockedBy?: number };
|
||||
expect(state.lockedBy ?? null).toBeNull();
|
||||
const res = await h.api("/api/tasks", { method: "POST", body: JSON.stringify(DAILY) });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
test("alreadyServing 只认带本插件标记头的响应", async () => {
|
||||
const marker = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => new Response("x", { headers: { "x-window-warmup": "1" } }),
|
||||
});
|
||||
const plain = Bun.serve({ port: 0, fetch: () => new Response("x") });
|
||||
try {
|
||||
expect(await alreadyServing(marker.port ?? 0)).toBe(true);
|
||||
expect(await alreadyServing(plain.port ?? 0)).toBe(false);
|
||||
} finally {
|
||||
marker.stop(true);
|
||||
plain.stop(true);
|
||||
}
|
||||
expect(await alreadyServing(0)).toBe(false); // 没人听:按未运行处理
|
||||
});
|
||||
|
||||
test("GET /api/catalog 走网关并透传目录", async () => {
|
||||
const { api } = await harness();
|
||||
const catalog = (await (await api("/api/catalog")).json()) as {
|
||||
providers: { id: string; models: { id: string }[]; autoModel: string | null }[];
|
||||
};
|
||||
expect(catalog.providers.map((p) => p.id)).toEqual(["p1"]);
|
||||
expect(catalog.providers[0].models.map((m) => m.id)).toEqual(["p1/m1"]);
|
||||
expect(catalog.providers[0].autoModel).toBe("p1/m1");
|
||||
});
|
||||
|
||||
test("GET / 提供 app.js 与 style.css", async () => {
|
||||
const { svc } = await harness();
|
||||
const base = `http://127.0.0.1:${svc.port}`;
|
||||
const js = await fetch(`${base}/app.js`);
|
||||
expect(js.status).toBe(200);
|
||||
expect(js.headers.get("content-type")).toContain("javascript");
|
||||
expect(await js.text()).toContain("statusOf");
|
||||
const css = await fetch(`${base}/style.css`);
|
||||
expect(css.status).toBe(200);
|
||||
expect(css.headers.get("content-type")).toContain("css");
|
||||
expect((await fetch(`${base}/../etc/passwd`)).status).toBe(404);
|
||||
});
|
||||
|
||||
test("超大请求体:边读边计数,超限 → 400(不是兜底 500)", async () => {
|
||||
const { api } = await harness();
|
||||
const res = await api("/api/tasks", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ pad: "x".repeat(70_000) }),
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(((await res.json()) as { error: string }).error).toContain("请求体太大");
|
||||
});
|
||||
|
||||
test("HEAD / 与 GET 同状态同安全头,不带响应体", async () => {
|
||||
const { svc } = await harness();
|
||||
const res = await fetch(`http://127.0.0.1:${svc.port}/`, { method: "HEAD" });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-security-policy")).toContain("default-src 'self'");
|
||||
expect(await res.text()).toBe("");
|
||||
});
|
||||
|
||||
test("坏时区任务不拖垮页面:/api/state 200,坏任务可从页面删除", async () => {
|
||||
// 手工编辑 state.json 塞入坏时区任务(store 校验只查非空字符串,挡不住)
|
||||
const bad = {
|
||||
id: "t-bad", name: "坏时区", enabled: true, provider: "p1", account: "", model: "p1/m1",
|
||||
message: "hi",
|
||||
trigger: { kind: "daily", time: "06:00", timeZone: "Mars/Olympus" },
|
||||
createdAt: "2026-10-30T00:00:00.000Z", updatedAt: "2026-10-30T00:00:00.000Z",
|
||||
};
|
||||
const state = JSON.stringify({
|
||||
version: 1, tasks: [bad], runs: [],
|
||||
marks: { "t-bad": { lastDue: null, resetKeys: [] } },
|
||||
});
|
||||
const { api } = await harness({ state });
|
||||
const res = await api("/api/state");
|
||||
expect(res.status).toBe(200); // 修复前:snapshot 抛 invalid time zone → 500,页面不可用
|
||||
const view = (await res.json()) as {
|
||||
fatal?: string;
|
||||
tasks: { id: string }[];
|
||||
next: Record<string, string | null>;
|
||||
timeline: { taskId: string }[];
|
||||
};
|
||||
expect(view.fatal ?? null).toBeNull();
|
||||
expect(view.tasks.map((t) => t.id)).toEqual(["t-bad"]);
|
||||
expect(view.next["t-bad"]).toBeNull();
|
||||
expect(view.timeline.some((p) => p.taskId === "t-bad")).toBe(false);
|
||||
// 页面删得掉坏任务,删完状态恢复
|
||||
expect((await api("/api/tasks/t-bad", { method: "DELETE" })).status).toBe(200);
|
||||
const after = (await (await api("/api/state")).json()) as { tasks: { id: string }[] };
|
||||
expect(after.tasks).toEqual([]);
|
||||
});
|
||||
|
||||
test("静态文件目录判定按平台分隔符:Windows 下 ui 目录内文件可读,越界仍拒绝", () => {
|
||||
const winRoot = "C:\\Users\\me\\scheduled-messages\\dist\\ui";
|
||||
expect(insideDir(winRoot, win32.resolve(winRoot, "./style.css"), win32)).toBe(true);
|
||||
expect(insideDir(winRoot, win32.resolve(winRoot, "./app.js"), win32)).toBe(true);
|
||||
expect(insideDir(winRoot, win32.resolve(winRoot, "../plugin.js"), win32)).toBe(false);
|
||||
expect(insideDir(winRoot, "C:\\Users\\me\\scheduled-messages\\dist\\ui-evil\\x.js", win32)).toBe(false);
|
||||
expect(insideDir(winRoot, winRoot, win32)).toBe(false);
|
||||
expect(insideDir("/srv/ui", "/srv/ui/app.js", posix)).toBe(true);
|
||||
expect(insideDir("/srv/ui", "/srv/ui-evil/app.js", posix)).toBe(false);
|
||||
});
|
||||
|
||||
// ---------- 端口探测(plugin.ts):已有实例不重开,被占不静默 ----------
|
||||
|
||||
/** 在测试期间把数据目录指到指定路径 */
|
||||
function withDir(dir: string): () => void {
|
||||
const saved = process.env.WINDOW_WARMUP_DIR;
|
||||
process.env.WINDOW_WARMUP_DIR = dir;
|
||||
return () => {
|
||||
if (saved === undefined) delete process.env.WINDOW_WARMUP_DIR;
|
||||
else process.env.WINDOW_WARMUP_DIR = saved;
|
||||
};
|
||||
}
|
||||
|
||||
test("端口探测:已有本插件的服务(带标记头)→ 直接返回,不重开数据目录", async () => {
|
||||
const marker = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
fetch: () => new Response("{}", { headers: { "x-window-warmup": "1" } }),
|
||||
});
|
||||
// 故意用不存在的目录:startService 一旦被调就会 mkdir 出来
|
||||
const dir = join(tmpdir(), `ww-plugin-absent-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
||||
const restore = withDir(dir);
|
||||
try {
|
||||
expect(await plugin.server(null, { port: marker.port })).toEqual({});
|
||||
} finally {
|
||||
restore();
|
||||
marker.stop(true);
|
||||
}
|
||||
expect(await stat(dir).then(() => true, () => false)).toBe(false);
|
||||
});
|
||||
|
||||
test("端口探测:端口空闲 → 照常启动,响应带标记头", async () => {
|
||||
const probe = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("x") });
|
||||
const port = probe.port;
|
||||
probe.stop(true);
|
||||
const dir = await mkdtemp(join(tmpdir(), "ww-plugin-run-"));
|
||||
dirs.push(dir);
|
||||
const restore = withDir(dir);
|
||||
try {
|
||||
expect(await plugin.server(null, { port })).toEqual({});
|
||||
const res = await fetch(`http://127.0.0.1:${port}/`);
|
||||
expect(res.headers.get("x-window-warmup")).toBe("1");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("端口探测:被别的服务(无标记头)占用 → 抛原错误,不静默成功", async () => {
|
||||
const other = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("not ours") });
|
||||
const dir = await mkdtemp(join(tmpdir(), "ww-plugin-clash-"));
|
||||
dirs.push(dir);
|
||||
const restore = withDir(dir);
|
||||
try {
|
||||
await expect(plugin.server(null, { port: other.port })).rejects.toThrow();
|
||||
} finally {
|
||||
restore();
|
||||
other.stop(true);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,304 @@
|
||||
// store 与单实例锁的失败测试:损坏拒启动且不覆盖原文件、原子写入、按任务截断、锁的活性判断。
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { acquireLock, migrateLegacyState, openStore, StoreError, type TaskMarks } from "../src/store";
|
||||
import type { Run, Task } from "../src/types";
|
||||
|
||||
const t1: Task = {
|
||||
id: "t1", name: "早报", enabled: true, provider: "openai", account: "",
|
||||
model: "m1", message: "hi",
|
||||
trigger: { kind: "daily", time: "06:00", timeZone: "Asia/Shanghai" },
|
||||
createdAt: "2026-10-30T00:00:00.000Z", updatedAt: "2026-10-30T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function runFixture(over: Partial<Run> = {}): Run {
|
||||
return {
|
||||
id: "r1", taskId: "t1", source: "schedule", due: null,
|
||||
startedAt: "2026-10-30T06:00:00.000Z", endedAt: "2026-10-30T06:00:05.000Z",
|
||||
outcome: "ok", reason: "", effort: null, model: null, ms: 5, resetKey: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function stateJson(tasks: Task[], runs: Run[], marks: Record<string, TaskMarks>): string {
|
||||
return JSON.stringify({ version: 1, tasks, runs, marks });
|
||||
}
|
||||
|
||||
let dirs: string[] = [];
|
||||
async function newDir(): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "sched-store-"));
|
||||
dirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe("openStore", () => {
|
||||
test("空目录得到全新状态;保存后重开内容一致", async () => {
|
||||
const dir = await newDir();
|
||||
const s = await openStore(dir);
|
||||
expect(s.data).toEqual({ version: 1, tasks: [], runs: [], marks: {} });
|
||||
|
||||
const run = runFixture();
|
||||
s.data.tasks.push(t1);
|
||||
s.data.runs.push(run);
|
||||
s.data.marks["t1"] = { lastDue: "2026-10-30T06:00:00.000Z", resetKeys: ["k1"] };
|
||||
await s.save();
|
||||
|
||||
const s2 = await openStore(dir);
|
||||
expect(s2.data).toEqual({ version: 1, tasks: [t1], runs: [run], marks: { t1: { lastDue: "2026-10-30T06:00:00.000Z", resetKeys: ["k1"] } } });
|
||||
});
|
||||
|
||||
test("只留 .tmp(模拟 rename 前崩溃)→ 原文件完整可用,且下次保存覆盖 tmp", async () => {
|
||||
const dir = await newDir();
|
||||
const good = stateJson([t1], [runFixture()], {});
|
||||
await mkdir(dir, { recursive: true });
|
||||
await writeFile(join(dir, "state.json"), good);
|
||||
await writeFile(join(dir, "state.json.tmp"), "{坏了");
|
||||
|
||||
const s = await openStore(dir);
|
||||
expect(s.data.tasks.map((t) => t.id)).toEqual(["t1"]);
|
||||
s.data.tasks.push({ ...t1, id: "t2" });
|
||||
await s.save();
|
||||
|
||||
const s2 = await openStore(dir);
|
||||
expect(s2.data.tasks.map((t) => t.id)).toEqual(["t1", "t2"]);
|
||||
});
|
||||
|
||||
test("非法 JSON → StoreError 且原文件字节不变", async () => {
|
||||
const dir = await newDir();
|
||||
const broken = '{"version":1,"tasks":[';
|
||||
await writeFile(join(dir, "state.json"), broken);
|
||||
|
||||
await expect(openStore(dir)).rejects.toThrow(StoreError);
|
||||
await expect(openStore(dir)).rejects.toThrow(/JSON/);
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(broken);
|
||||
});
|
||||
|
||||
test("version:2 → StoreError 且原文件不变", async () => {
|
||||
const dir = await newDir();
|
||||
const future = JSON.stringify({ version: 2, tasks: [], runs: [], marks: {} });
|
||||
await writeFile(join(dir, "state.json"), future);
|
||||
|
||||
await expect(openStore(dir)).rejects.toThrow(StoreError);
|
||||
await expect(openStore(dir)).rejects.toThrow(/版本/);
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(future);
|
||||
});
|
||||
|
||||
test("结构损坏 → StoreError(tasks 非数组 / 任务缺字段 / marks 形状错 / run 字段坏)", async () => {
|
||||
const cases: unknown[] = [
|
||||
{ version: 1, tasks: "nope", runs: [], marks: {} },
|
||||
{ version: 1, tasks: [{ ...t1, id: 5 }], runs: [], marks: {} },
|
||||
{ version: 1, tasks: [t1], runs: [runFixture({ outcome: "bogus" as never })], marks: {} },
|
||||
{ version: 1, tasks: [t1], runs: [], marks: { t1: { lastDue: 7, resetKeys: [] } } },
|
||||
{ version: 1, tasks: [t1], runs: [], marks: { t1: { lastDue: null, resetKeys: "k" } } },
|
||||
[1, 2, 3],
|
||||
];
|
||||
for (const bad of cases) {
|
||||
const dir = await newDir();
|
||||
const raw = JSON.stringify(bad);
|
||||
await writeFile(join(dir, "state.json"), raw);
|
||||
await expect(openStore(dir)).rejects.toThrow(StoreError);
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(raw);
|
||||
}
|
||||
});
|
||||
|
||||
test("runs 超过 50 条按任务截断(保留最近的尾部)", async () => {
|
||||
const dir = await newDir();
|
||||
const many: Run[] = Array.from({ length: 55 }, (_, i) => runFixture({ id: `r${i}` }));
|
||||
const t2 = { ...t1, id: "t2" };
|
||||
const raw = stateJson(
|
||||
[t1, t2],
|
||||
[...many, runFixture({ id: "x1", taskId: "t2" }), runFixture({ id: "x2", taskId: "t2" })],
|
||||
{},
|
||||
);
|
||||
await writeFile(join(dir, "state.json"), raw);
|
||||
|
||||
const s = await openStore(dir);
|
||||
const mine = s.data.runs.filter((r) => r.taskId === "t1");
|
||||
expect(mine).toHaveLength(50);
|
||||
expect(mine[0].id).toBe("r5");
|
||||
expect(mine[49].id).toBe("r54");
|
||||
expect(s.data.runs.filter((r) => r.taskId === "t2")).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("每任务 resetKey 超过 20 个截断", async () => {
|
||||
const dir = await newDir();
|
||||
const keys = Array.from({ length: 25 }, (_, i) => `k${i}`);
|
||||
await writeFile(join(dir, "state.json"), stateJson([t1], [], { t1: { lastDue: null, resetKeys: keys } }));
|
||||
|
||||
const s = await openStore(dir);
|
||||
expect(s.data.marks["t1"].resetKeys).toHaveLength(20);
|
||||
expect(s.data.marks["t1"].resetKeys[0]).toBe("k5");
|
||||
expect(s.data.marks["t1"].resetKeys[19]).toBe("k24");
|
||||
});
|
||||
|
||||
test("旧 state 的 run 没有 model 字段 → 照常加载为 null,保存后字段补齐", async () => {
|
||||
const dir = await newDir();
|
||||
const legacyRun = {
|
||||
id: "r1", taskId: "t1", source: "schedule", due: null,
|
||||
startedAt: "2026-10-30T06:00:00.000Z", endedAt: "2026-10-30T06:00:05.000Z",
|
||||
outcome: "ok", reason: "", effort: null, ms: 5, resetKey: null,
|
||||
};
|
||||
await writeFile(join(dir, "state.json"), JSON.stringify({ version: 1, tasks: [t1], runs: [legacyRun], marks: {} }));
|
||||
|
||||
const s = await openStore(dir);
|
||||
expect(s.data.runs[0].model).toBeNull();
|
||||
await s.save();
|
||||
const s2 = await openStore(dir);
|
||||
expect(s2.data.runs[0]).toEqual(runFixture());
|
||||
});
|
||||
|
||||
test("run.model 类型坏 → StoreError", async () => {
|
||||
const dir = await newDir();
|
||||
const raw = stateJson([t1], [runFixture({ model: 5 as never })], {});
|
||||
await writeFile(join(dir, "state.json"), raw);
|
||||
await expect(openStore(dir)).rejects.toThrow(StoreError);
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(raw);
|
||||
});
|
||||
});
|
||||
|
||||
describe("migrateLegacyState", () => {
|
||||
function legacyEnv(xdg: string): Record<string, string | undefined> {
|
||||
return { XDG_CONFIG_HOME: xdg };
|
||||
}
|
||||
|
||||
test("旧目录有 state.json 且新目录没有 → 复制过来;旧文件与锁都不动", async () => {
|
||||
const xdg = await newDir();
|
||||
const legacyDir = join(xdg, "magpie", "scheduled-messages");
|
||||
await mkdir(legacyDir, { recursive: true });
|
||||
const legacyState = stateJson([t1], [runFixture()], {});
|
||||
await writeFile(join(legacyDir, "state.json"), legacyState);
|
||||
await writeFile(join(legacyDir, "service.lock"), "999");
|
||||
const dir = await newDir();
|
||||
|
||||
await migrateLegacyState(dir, legacyEnv(xdg));
|
||||
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(legacyState);
|
||||
expect(await readFile(join(legacyDir, "state.json"), "utf8")).toBe(legacyState); // 复制而非移动
|
||||
expect(await readdir(dir)).toEqual(["state.json"]); // 锁属于旧目录的进程语义,不跟过来
|
||||
});
|
||||
|
||||
test("新目录已有 state.json → 不覆盖(哪怕是坏的,坏文件由 openStore 报给用户)", async () => {
|
||||
const xdg = await newDir();
|
||||
const legacyDir = join(xdg, "magpie", "scheduled-messages");
|
||||
await mkdir(legacyDir, { recursive: true });
|
||||
await writeFile(join(legacyDir, "state.json"), stateJson([t1], [], {}));
|
||||
const dir = await newDir();
|
||||
const own = "自己已有的内容";
|
||||
await writeFile(join(dir, "state.json"), own);
|
||||
|
||||
await migrateLegacyState(dir, legacyEnv(xdg));
|
||||
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe(own);
|
||||
});
|
||||
|
||||
test("旧目录没有 state.json → 新目录保持空,不报错", async () => {
|
||||
const xdg = await newDir();
|
||||
const dir = await newDir();
|
||||
await migrateLegacyState(dir, legacyEnv(xdg));
|
||||
expect(await readdir(dir)).toEqual([]);
|
||||
});
|
||||
|
||||
test("旧文件损坏也照搬(迁移只看存在性,结构校验交给 openStore)", async () => {
|
||||
const xdg = await newDir();
|
||||
const legacyDir = join(xdg, "magpie", "scheduled-messages");
|
||||
await mkdir(legacyDir, { recursive: true });
|
||||
await writeFile(join(legacyDir, "state.json"), "{坏了");
|
||||
const dir = await newDir();
|
||||
|
||||
await migrateLegacyState(dir, legacyEnv(xdg));
|
||||
|
||||
expect(await readFile(join(dir, "state.json"), "utf8")).toBe("{坏了");
|
||||
});
|
||||
});
|
||||
|
||||
describe("acquireLock", () => {
|
||||
test("无锁 → 原子拿到并写入自身 pid;release 后文件消失", async () => {
|
||||
const dir = await newDir();
|
||||
const lock = await acquireLock(dir);
|
||||
if (!lock.ok) throw new Error("应当拿到锁");
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe(String(process.pid));
|
||||
await lock.release();
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8").catch(() => "gone")).toBe("gone");
|
||||
});
|
||||
|
||||
test("锁里是存活 pid → ok:false 且不覆盖文件", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock"), String(process.pid));
|
||||
const lock = await acquireLock(dir);
|
||||
expect(lock.ok).toBe(false);
|
||||
if (!lock.ok) expect(lock.pid).toBe(process.pid);
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe(String(process.pid));
|
||||
});
|
||||
|
||||
test("锁里是存活 pid 但确认不过(持有者并未在服务)→ 视为陈旧锁接管", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock"), String(process.pid));
|
||||
const lock = await acquireLock(dir, { confirmAlive: () => false });
|
||||
expect(lock.ok).toBe(true);
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe(String(process.pid));
|
||||
if (lock.ok) await lock.release();
|
||||
});
|
||||
|
||||
test("锁里是存活 pid 且确认在服务 → ok:false 不覆盖文件", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock"), String(process.pid));
|
||||
const lock = await acquireLock(dir, { confirmAlive: () => true });
|
||||
expect(lock.ok).toBe(false);
|
||||
if (!lock.ok) expect(lock.pid).toBe(process.pid);
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe(String(process.pid));
|
||||
});
|
||||
|
||||
test("pid 已死时不调用确认直接接管", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock"), String(2 ** 22 + 1));
|
||||
let calls = 0;
|
||||
const lock = await acquireLock(dir, {
|
||||
confirmAlive: () => {
|
||||
calls += 1;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
expect(lock.ok).toBe(true);
|
||||
expect(calls).toBe(0);
|
||||
if (lock.ok) await lock.release();
|
||||
});
|
||||
|
||||
test("锁里是不存在的 pid → 接管并写入自身 pid", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock"), String(2 ** 22 + 1));
|
||||
const lock = await acquireLock(dir);
|
||||
expect(lock.ok).toBe(true);
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe(String(process.pid));
|
||||
if (lock.ok) await lock.release();
|
||||
});
|
||||
|
||||
test("release 只释放自己持有的锁", async () => {
|
||||
const dir = await newDir();
|
||||
const lock = await acquireLock(dir);
|
||||
if (!lock.ok) throw new Error("应当拿到锁");
|
||||
await writeFile(join(dir, "service.lock"), "999999");
|
||||
await lock.release();
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe("999999");
|
||||
});
|
||||
|
||||
test("锁内容无法解析(活性不明)→ 不抢占", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock"), "看不懂的内容");
|
||||
const lock = await acquireLock(dir);
|
||||
expect(lock.ok).toBe(false);
|
||||
if (!lock.ok) expect(lock.pid).toBe(0);
|
||||
expect(await readFile(join(dir, "service.lock"), "utf8")).toBe("看不懂的内容");
|
||||
});
|
||||
|
||||
test("入口顺带清理崩溃残留的锁 tmp 文件", async () => {
|
||||
const dir = await newDir();
|
||||
await writeFile(join(dir, "service.lock.999.3f2b4c5d-6e7f-8a9b-0a1b-2c3d4e5f6a7b.tmp"), "999");
|
||||
const lock = await acquireLock(dir);
|
||||
expect(lock.ok).toBe(true);
|
||||
const leftovers = (await readdir(dir)).filter((f) => f.endsWith(".tmp"));
|
||||
expect(leftovers).toHaveLength(0);
|
||||
if (lock.ok) await lock.release();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["bun"],
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"]
|
||||
},
|
||||
"include": ["src", "scripts", "tests", "web"]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,417 @@
|
||||
// 页面 i18n:界面语言跟随 magpie 本身(zh / zh-TW / en / ja),不单独设置。
|
||||
// 译文表的键即中文原文;app.ts 原样转出这里的导出,测试与渲染都从 app 取用。
|
||||
|
||||
/** magpie 支持的四种界面语言;zh 是源语言(键本身),其余语言查表 */
|
||||
export type Lang = "zh" | "zh-TW" | "en" | "ja";
|
||||
|
||||
/** 单语言译文表:键一律是中文原文 */
|
||||
export type I18NTable = Record<string, string>;
|
||||
|
||||
/**
|
||||
* 译文表。键即中文原文,查不到就回退键本身——zh 因此不需要条目,
|
||||
* 也保证默认语言下所有文案逐字不变(现有测试依赖这一恒等)。
|
||||
* 三张表的键集合必须完全一致,tests/i18n.test.ts 有完整性守卫。
|
||||
*/
|
||||
export const I18N: Partial<Record<Lang, I18NTable>> = {
|
||||
en: {
|
||||
"模型列表来自 Magpie 上次获取的结果。账号和模型对不上时,到 Magpie「供应商」里打开这个供应商,点「获取模型」,再回来刷新本页。":
|
||||
"The model list comes from Magpie's last fetch. If accounts and models don't match, open this provider under Magpie's Providers page, click Fetch models, then refresh this page.",
|
||||
"还没有这个供应商的模型列表。请到 Magpie「供应商」里打开它,点「获取模型」。":
|
||||
"No model list for this provider yet. Open it under Magpie's Providers page and click Fetch models.",
|
||||
"窗口重置后": "After window reset",
|
||||
"每天定时": "Daily",
|
||||
"固定间隔": "Every N hours",
|
||||
"已停用": "Disabled",
|
||||
"发送中": "Sending",
|
||||
"上次失败": "Last failed",
|
||||
"上次结果未知": "Last result unknown",
|
||||
"明天": "Tomorrow",
|
||||
"今天": "Today",
|
||||
"昨天": "Yesterday",
|
||||
"自动选账号": "auto account",
|
||||
"自动选模型": "auto model",
|
||||
"窗口": "Window",
|
||||
"重置后": "after reset",
|
||||
"每天": "Daily",
|
||||
"每": "Every",
|
||||
"小时": "hours",
|
||||
"思考档位无法识别:": "Cannot read the reasoning effort: ",
|
||||
"思考:": "Reasoning: ",
|
||||
"成功": "Success",
|
||||
"失败": "Failed",
|
||||
"未知": "Unknown",
|
||||
"手动": "manual",
|
||||
"补发": "catch-up",
|
||||
"按计划": "scheduled",
|
||||
"已发送": "Sent",
|
||||
"思考": "reasoning",
|
||||
"秒": "s",
|
||||
"(不在当前账号列表)": " (not in the current account list)",
|
||||
"请选择账号": "Pick an account",
|
||||
"该供应商没有账号": "This provider has no accounts",
|
||||
"自动": "Auto",
|
||||
"已用": "Used",
|
||||
"重置": "reset",
|
||||
"空闲": "Idle",
|
||||
"该账号没有窗口信息": "No window info for this account",
|
||||
"先选定账号": "Pick an account first",
|
||||
"名字带 flash / lite / mini 的小模型优先,每次发送前重新选;思考能关就关,不能关用最低档。":
|
||||
"Smaller models with flash / lite / mini in the name are preferred and re-picked before each send; reasoning is turned off when possible, else the lowest effort is used.",
|
||||
"思考档位按这个模型的配置自动决定:能关就关,不能关用最低档。":
|
||||
"The reasoning effort follows this model's own configuration: off when possible, else the lowest effort.",
|
||||
"思考:目录里暂时没有这个模型": "Reasoning: this model is not in the catalog yet",
|
||||
"这个账号没有可用模型": "This account has no usable models",
|
||||
"该供应商没有可用模型": "This provider has no usable models",
|
||||
"自动选中": "Auto picks",
|
||||
"给任务起个名字": "Name the task",
|
||||
"名称不能超过": "The name can be at most",
|
||||
"字": "characters",
|
||||
"必须选择供应商": "Pick a provider",
|
||||
"必须选择账号": "Pick an account",
|
||||
"必须填写额度窗口名": "Enter the quota window name",
|
||||
"时间需为 24 小时制的 HH:MM": "Time must be HH:MM in 24-hour format",
|
||||
"任务没有暂停,下一次照常发送。": "The task is not paused; the next send proceeds as usual.",
|
||||
"名称": "Name",
|
||||
"选择供应商": "Pick a provider",
|
||||
"供应商": "Provider",
|
||||
"账号": "Account",
|
||||
"模型": "Model",
|
||||
"这个供应商没有按账号区分的模型列表,列出的是全部模型":
|
||||
"This provider has no per-account model list; every model is listed.",
|
||||
"跟随窗口重置时必须指定账号,每个账号的窗口各自计时。":
|
||||
"Following a window reset requires an account; each account's windows run on their own clocks.",
|
||||
"发送到": "Send to",
|
||||
"时区": "Time zone",
|
||||
"时间": "Time",
|
||||
"从": "From",
|
||||
"接下来": "Next",
|
||||
",之后跟随每次重置": ", then after every reset",
|
||||
"等下一次额度刷新,之后跟随每次重置": "Waiting for the next quota refresh, then after every reset",
|
||||
"这个账号没有可跟随的窗口,已改为每天定时,保存后生效。":
|
||||
"This account has no window to follow; switched to Daily. Takes effect after saving.",
|
||||
"触发": "Trigger",
|
||||
"确认删除": "Confirm delete",
|
||||
"删除": "Delete",
|
||||
"放弃": "Discard",
|
||||
"有未保存的修改": "Unsaved changes",
|
||||
"取消": "Cancel",
|
||||
"保存": "Save",
|
||||
"执行记录": "Run history",
|
||||
"最近 50 次": "Last 50",
|
||||
"立即发送一次": "Send once now",
|
||||
"先保存任务": "Save the task first",
|
||||
"按已保存的设置发送,不含未保存的修改": "Sends with the saved settings; unsaved changes are not included",
|
||||
"马上按当前设置发一条,不影响计划":
|
||||
"Sends one message with the current settings right away, without affecting the schedule",
|
||||
"还没有执行过。": "No runs yet.",
|
||||
"显示更多": "Show more",
|
||||
"未命名任务": "Untitled task",
|
||||
"启用": "Enabled",
|
||||
"当前无法编辑任务。": "Tasks cannot be edited right now.",
|
||||
"还没有任务": "No tasks yet",
|
||||
"点「新建任务」,选好账号和触发方式即可。": "Click New task, pick an account and a trigger, and you are set.",
|
||||
"没有启用的任务": "No enabled tasks",
|
||||
"个任务启用": "task(s) enabled",
|
||||
"下一次": "Next",
|
||||
"页面与服务断开了:": "The page lost contact with the service: ",
|
||||
"(服务可能已退出,重新打开页面试试)": " (the service may have exited; try reopening the page)",
|
||||
"重试": "Retry",
|
||||
"与服务断开了,正在自动重连…": "Disconnected from the service; reconnecting automatically…",
|
||||
"服务处于故障状态,任务没有在运行:": "The service is in a failed state; tasks are not running: ",
|
||||
"另一个实例正在运行(进程 ": "Another instance is running (process ",
|
||||
"),本页只读。": "); this page is read-only.",
|
||||
"另一个实例可能正在运行(无法确认持有者进程),本页只读。":
|
||||
"Another instance may be running (its process could not be confirmed); this page is read-only.",
|
||||
"数据可能没保存:": "Data may not have been saved: ",
|
||||
"模型目录读取失败:": "Failed to read the model catalog: ",
|
||||
"(稍后自动重试)": " (retrying automatically)",
|
||||
"这个任务刚在别处被更新。下面保留的是你未保存的修改,直接保存会覆盖新版本。":
|
||||
"This task was just updated elsewhere. Your unsaved changes are kept below; saving now would overwrite the new version.",
|
||||
"页面缺少访问口令,请从 Magpie 的插件页重新打开。":
|
||||
"The page is missing its access token; please reopen it from Magpie's plugin page.",
|
||||
"窗口预热": "Window Warmup",
|
||||
"新建任务": "New task",
|
||||
"说明": "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.",
|
||||
"失败不会暂停任务,下一次照常执行。": "A failure does not pause the task; the next run proceeds as usual.",
|
||||
},
|
||||
"zh-TW": {
|
||||
"模型列表来自 Magpie 上次获取的结果。账号和模型对不上时,到 Magpie「供应商」里打开这个供应商,点「获取模型」,再回来刷新本页。":
|
||||
"模型清單來自 Magpie 上次取得的結果。帳號和模型對不上時,到 Magpie「供應商」裡開啟這個供應商,點「取得模型」,再回來重新整理本頁。",
|
||||
"还没有这个供应商的模型列表。请到 Magpie「供应商」里打开它,点「获取模型」。":
|
||||
"還沒有這個供應商的模型清單。請到 Magpie「供應商」裡開啟它,點「取得模型」。",
|
||||
"窗口重置后": "窗口重置後",
|
||||
"每天定时": "每天定時",
|
||||
"固定间隔": "固定間隔",
|
||||
"已停用": "已停用",
|
||||
"发送中": "傳送中",
|
||||
"上次失败": "上次失敗",
|
||||
"上次结果未知": "上次結果未知",
|
||||
"明天": "明天",
|
||||
"今天": "今天",
|
||||
"昨天": "昨天",
|
||||
"自动选账号": "自動選帳號",
|
||||
"自动选模型": "自動選模型",
|
||||
"窗口": "窗口",
|
||||
"重置后": "重置後",
|
||||
"每天": "每天",
|
||||
"每": "每",
|
||||
"小时": "小時",
|
||||
"思考档位无法识别:": "思考檔位無法識別:",
|
||||
"思考:": "思考:",
|
||||
"成功": "成功",
|
||||
"失败": "失敗",
|
||||
"未知": "未知",
|
||||
"手动": "手動",
|
||||
"补发": "補發",
|
||||
"按计划": "按計畫",
|
||||
"已发送": "已傳送",
|
||||
"思考": "思考",
|
||||
"秒": "秒",
|
||||
"(不在当前账号列表)": "(不在目前帳號清單)",
|
||||
"请选择账号": "請選擇帳號",
|
||||
"该供应商没有账号": "這個供應商沒有帳號",
|
||||
"自动": "自動",
|
||||
"已用": "已用",
|
||||
"重置": "重置",
|
||||
"空闲": "空閒",
|
||||
"该账号没有窗口信息": "這個帳號沒有窗口資訊",
|
||||
"先选定账号": "先選定帳號",
|
||||
"名字带 flash / lite / mini 的小模型优先,每次发送前重新选;思考能关就关,不能关用最低档。":
|
||||
"名字帶 flash / lite / mini 的小模型優先,每次傳送前重新選;思考能關就關,不能關用最低檔。",
|
||||
"思考档位按这个模型的配置自动决定:能关就关,不能关用最低档。":
|
||||
"思考檔位按這個模型的設定自動決定:能關就關,不能關用最低檔。",
|
||||
"思考:目录里暂时没有这个模型": "思考:目錄裡暫時沒有這個模型",
|
||||
"这个账号没有可用模型": "這個帳號沒有可用模型",
|
||||
"该供应商没有可用模型": "這個供應商沒有可用模型",
|
||||
"自动选中": "自動選中",
|
||||
"给任务起个名字": "給任務取個名字",
|
||||
"名称不能超过": "名稱不能超過",
|
||||
"字": "字",
|
||||
"必须选择供应商": "必須選擇供應商",
|
||||
"必须选择账号": "必須選擇帳號",
|
||||
"必须填写额度窗口名": "必須填寫額度窗口名",
|
||||
"时间需为 24 小时制的 HH:MM": "時間需為 24 小時制的 HH:MM",
|
||||
"任务没有暂停,下一次照常发送。": "任務沒有暫停,下一次照常傳送。",
|
||||
"名称": "名稱",
|
||||
"选择供应商": "選擇供應商",
|
||||
"供应商": "供應商",
|
||||
"账号": "帳號",
|
||||
"模型": "模型",
|
||||
"这个供应商没有按账号区分的模型列表,列出的是全部模型":
|
||||
"這個供應商沒有按帳號區分的模型清單,列出的是全部模型",
|
||||
"跟随窗口重置时必须指定账号,每个账号的窗口各自计时。":
|
||||
"跟隨窗口重置時必須指定帳號,每個帳號的窗口各自計時。",
|
||||
"发送到": "傳送到",
|
||||
"时区": "時區",
|
||||
"时间": "時間",
|
||||
"从": "從",
|
||||
"接下来": "接下來",
|
||||
",之后跟随每次重置": ",之後跟隨每次重置",
|
||||
"等下一次额度刷新,之后跟随每次重置": "等下一次額度刷新,之後跟隨每次重置",
|
||||
"这个账号没有可跟随的窗口,已改为每天定时,保存后生效。":
|
||||
"這個帳號沒有可跟隨的窗口,已改為每天定時,儲存後生效。",
|
||||
"触发": "觸發",
|
||||
"确认删除": "確認刪除",
|
||||
"删除": "刪除",
|
||||
"放弃": "放棄",
|
||||
"有未保存的修改": "有未儲存的修改",
|
||||
"取消": "取消",
|
||||
"保存": "儲存",
|
||||
"执行记录": "執行記錄",
|
||||
"最近 50 次": "最近 50 次",
|
||||
"立即发送一次": "立即傳送一次",
|
||||
"先保存任务": "先儲存任務",
|
||||
"按已保存的设置发送,不含未保存的修改": "按已儲存的設定傳送,不含未儲存的修改",
|
||||
"马上按当前设置发一条,不影响计划": "馬上按目前設定發一條,不影響計畫",
|
||||
"还没有执行过。": "還沒有執行過。",
|
||||
"显示更多": "顯示更多",
|
||||
"未命名任务": "未命名任務",
|
||||
"启用": "啟用",
|
||||
"当前无法编辑任务。": "目前無法編輯任務。",
|
||||
"还没有任务": "還沒有任務",
|
||||
"点「新建任务」,选好账号和触发方式即可。": "點「新增任務」,選好帳號和觸發方式即可。",
|
||||
"没有启用的任务": "沒有啟用的任務",
|
||||
"个任务启用": "個任務啟用",
|
||||
"下一次": "下一次",
|
||||
"页面与服务断开了:": "頁面與服務的連線中斷:",
|
||||
"(服务可能已退出,重新打开页面试试)": "(服務可能已結束,重新開啟頁面試試)",
|
||||
"重试": "重試",
|
||||
"与服务断开了,正在自动重连…": "與服務的連線中斷,正在自動重新連線…",
|
||||
"服务处于故障状态,任务没有在运行:": "服務處於故障狀態,任務沒有在執行:",
|
||||
"另一个实例正在运行(进程 ": "另一個執行個體正在執行(處理程序 ",
|
||||
"),本页只读。": "),本頁唯讀。",
|
||||
"另一个实例可能正在运行(无法确认持有者进程),本页只读。":
|
||||
"另一個執行個體可能在執行(無法確認持有者處理程序),本頁唯讀。",
|
||||
"数据可能没保存:": "資料可能沒儲存:",
|
||||
"模型目录读取失败:": "模型目錄讀取失敗:",
|
||||
"(稍后自动重试)": "(稍後自動重試)",
|
||||
"这个任务刚在别处被更新。下面保留的是你未保存的修改,直接保存会覆盖新版本。":
|
||||
"這個任務剛在別處被更新。下面保留的是你未儲存的修改,直接儲存會覆蓋新版本。",
|
||||
"页面缺少访问口令,请从 Magpie 的插件页重新打开。":
|
||||
"頁面缺少存取權杖,請從 Magpie 的外掛頁重新開啟。",
|
||||
"窗口预热": "窗口預熱",
|
||||
"新建任务": "新增任務",
|
||||
"说明": "說明",
|
||||
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。":
|
||||
"訊息按供應商自己的額度規則計費,可能用到贈送額度或 API 餘額;傳送成功不代表窗口一定已開始計時。",
|
||||
"Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。":
|
||||
"Magpie 關閉期間不會執行,重新開啟後每個任務最多補發一次。",
|
||||
"失败不会暂停任务,下一次照常执行。": "失敗不會暫停任務,下一次照常執行。",
|
||||
},
|
||||
ja: {
|
||||
"模型列表来自 Magpie 上次获取的结果。账号和模型对不上时,到 Magpie「供应商」里打开这个供应商,点「获取模型」,再回来刷新本页。":
|
||||
"モデル一覧は Magpie が最後に取得した結果のものです。アカウントとモデルが合わないときは、Magpie の「プロバイダー」でこのプロバイダーを開き、「モデルを取得」をクリックしてから、このページを再読み込みしてください。",
|
||||
"还没有这个供应商的模型列表。请到 Magpie「供应商」里打开它,点「获取模型」。":
|
||||
"このプロバイダーのモデル一覧はまだありません。Magpie の「プロバイダー」で開き、「モデルを取得」をクリックしてください。",
|
||||
"窗口重置后": "ウィンドウリセット後",
|
||||
"每天定时": "毎日定時",
|
||||
"固定间隔": "固定間隔",
|
||||
"已停用": "停止中",
|
||||
"发送中": "送信中",
|
||||
"上次失败": "前回失敗",
|
||||
"上次结果未知": "前回結果不明",
|
||||
"明天": "明日",
|
||||
"今天": "今日",
|
||||
"昨天": "昨日",
|
||||
"自动选账号": "アカウント自動選択",
|
||||
"自动选模型": "モデル自動選択",
|
||||
"窗口": "ウィンドウ",
|
||||
"重置后": "リセット後",
|
||||
"每天": "毎日",
|
||||
"每": "毎",
|
||||
"小时": "時間",
|
||||
"思考档位无法识别:": "思考レベルを判別できません:",
|
||||
"思考:": "思考:",
|
||||
"成功": "成功",
|
||||
"失败": "失敗",
|
||||
"未知": "不明",
|
||||
"手动": "手動",
|
||||
"补发": "キャッチアップ",
|
||||
"按计划": "予定どおり",
|
||||
"已发送": "送信済み",
|
||||
"思考": "思考",
|
||||
"秒": "秒",
|
||||
"(不在当前账号列表)": "(現在のアカウント一覧にありません)",
|
||||
"请选择账号": "アカウントを選択してください",
|
||||
"该供应商没有账号": "このプロバイダーにはアカウントがありません",
|
||||
"自动": "自動",
|
||||
"已用": "使用済み",
|
||||
"重置": "リセット",
|
||||
"空闲": "アイドル",
|
||||
"该账号没有窗口信息": "このアカウントにはウィンドウ情報がありません",
|
||||
"先选定账号": "先にアカウントを選択してください",
|
||||
"名字带 flash / lite / mini 的小模型优先,每次发送前重新选;思考能关就关,不能关用最低档。":
|
||||
"名前に flash / lite / mini が付く小さめのモデルを優先し、送信のたびに選び直します。思考はオフにできるときはオフ、できないときは最低レベルを使います。",
|
||||
"思考档位按这个模型的配置自动决定:能关就关,不能关用最低档。":
|
||||
"思考レベルはこのモデルの設定に従って自動的に決まります。オフにできるときはオフ、できないときは最低レベルです。",
|
||||
"思考:目录里暂时没有这个模型": "思考:このモデルはまだ一覧にありません",
|
||||
"这个账号没有可用模型": "このアカウントには使えるモデルがありません",
|
||||
"该供应商没有可用模型": "このプロバイダーには使えるモデルがありません",
|
||||
"自动选中": "自動選択",
|
||||
"给任务起个名字": "タスクに名前を付けてください",
|
||||
"名称不能超过": "名前は",
|
||||
"字": "文字まで",
|
||||
"必须选择供应商": "プロバイダーを選択してください",
|
||||
"必须选择账号": "アカウントを選択してください",
|
||||
"必须填写额度窗口名": "クォータウィンドウ名を入力してください",
|
||||
"时间需为 24 小时制的 HH:MM": "時刻は 24 時間制の HH:MM で入力してください",
|
||||
"任务没有暂停,下一次照常发送。": "タスクは停止せず、次回も通常どおり送信します。",
|
||||
"名称": "名前",
|
||||
"选择供应商": "プロバイダーを選択",
|
||||
"供应商": "プロバイダー",
|
||||
"账号": "アカウント",
|
||||
"模型": "モデル",
|
||||
"这个供应商没有按账号区分的模型列表,列出的是全部模型":
|
||||
"このプロバイダーにはアカウント別のモデル一覧がなく、すべてのモデルが表示されます。",
|
||||
"跟随窗口重置时必须指定账号,每个账号的窗口各自计时。":
|
||||
"ウィンドウのリセットに追従するにはアカウントの指定が必要です。各アカウントのウィンドウはそれぞれ別に計時されます。",
|
||||
"发送到": "送信先",
|
||||
"时区": "タイムゾーン",
|
||||
"时间": "時刻",
|
||||
"从": "起点",
|
||||
"接下来": "次回",
|
||||
",之后跟随每次重置": "、その後はリセットのたびに送信",
|
||||
"等下一次额度刷新,之后跟随每次重置": "次のクォータ更新を待って、その後はリセットのたびに送信",
|
||||
"这个账号没有可跟随的窗口,已改为每天定时,保存后生效。":
|
||||
"このアカウントには追従できるウィンドウがないため、毎日定時に変更しました。保存後に有効になります。",
|
||||
"触发": "トリガー",
|
||||
"确认删除": "削除する",
|
||||
"删除": "削除",
|
||||
"放弃": "破棄",
|
||||
"有未保存的修改": "未保存の変更があります",
|
||||
"取消": "キャンセル",
|
||||
"保存": "保存",
|
||||
"执行记录": "実行履歴",
|
||||
"最近 50 次": "直近 50 件",
|
||||
"立即发送一次": "今すぐ 1 回送信",
|
||||
"先保存任务": "先にタスクを保存してください",
|
||||
"按已保存的设置发送,不含未保存的修改": "保存済みの設定で送信します。未保存の変更は含まれません",
|
||||
"马上按当前设置发一条,不影响计划": "現在の設定で 1 通すぐ送信します。予定には影響しません",
|
||||
"还没有执行过。": "まだ実行されていません。",
|
||||
"显示更多": "もっと表示",
|
||||
"未命名任务": "無題のタスク",
|
||||
"启用": "有効",
|
||||
"当前无法编辑任务。": "現在タスクを編集できません。",
|
||||
"还没有任务": "まだタスクがありません",
|
||||
"点「新建任务」,选好账号和触发方式即可。": "「新規タスク」から、アカウントとトリガーを選ぶだけで始められます。",
|
||||
"没有启用的任务": "有効なタスクはありません",
|
||||
"个任务启用": "件のタスクが有効",
|
||||
"下一次": "次回",
|
||||
"页面与服务断开了:": "ページとサービスの接続が切れました:",
|
||||
"(服务可能已退出,重新打开页面试试)": "(サービスが終了した可能性があります。ページを開き直してみてください)",
|
||||
"重试": "再試行",
|
||||
"与服务断开了,正在自动重连…": "サービスと切断されました。自動的に再接続しています…",
|
||||
"服务处于故障状态,任务没有在运行:": "サービスは故障状態にあり、タスクは実行されていません:",
|
||||
"另一个实例正在运行(进程 ": "別のインスタンスが実行中(プロセス ",
|
||||
"),本页只读。": ")。このページは閲覧のみです。",
|
||||
"另一个实例可能正在运行(无法确认持有者进程),本页只读。":
|
||||
"別のインスタンスが実行中の可能性があります(保持しているプロセスを確認できません)。このページは閲覧のみです。",
|
||||
"数据可能没保存:": "データが保存されていない可能性があります:",
|
||||
"模型目录读取失败:": "モデルカタログの読み取りに失敗しました:",
|
||||
"(稍后自动重试)": "(後で自動的に再試行します)",
|
||||
"这个任务刚在别处被更新。下面保留的是你未保存的修改,直接保存会覆盖新版本。":
|
||||
"このタスクは別の場所で更新されました。下には未保存の変更が残っています。このまま保存すると新しいバージョンが上書きされます。",
|
||||
"页面缺少访问口令,请从 Magpie 的插件页重新打开。":
|
||||
"ページにアクセストークンがありません。Magpie のプラグインページから開き直してください。",
|
||||
"窗口预热": "ウィンドウ予熱",
|
||||
"新建任务": "新規タスク",
|
||||
"说明": "ヘルプ",
|
||||
"消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。":
|
||||
"メッセージはプロバイダー独自のクォータ規則で課金され、ボーナス額度や API 残高を使うことがあります。送信が成功してもウィンドウの計時が始まったとは限りません。",
|
||||
"Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。":
|
||||
"Magpie が閉じている間は実行されません。再オープン後、各タスクは最大 1 回キャッチアップ送信されます。",
|
||||
"失败不会暂停任务,下一次照常执行。": "失敗してもタスクは停止せず、次回も通常どおり実行します。",
|
||||
},
|
||||
};
|
||||
|
||||
/** 把 BCP-47 风格的语言标签归一到四种支持语言;识别不了回退 zh */
|
||||
export function normalizeLang(raw: string | null | undefined): Lang {
|
||||
const s = String(raw ?? "").trim().toLowerCase();
|
||||
// 繁体区先于 zh* 兜底判断:zh-hant-* / zh-tw / zh-hk 都算繁体,其余 zh 系归简体
|
||||
if (s.startsWith("zh-hant") || s === "zh-tw" || s === "zh-hk") return "zh-TW";
|
||||
if (s.startsWith("zh")) return "zh";
|
||||
if (s.startsWith("ja")) return "ja";
|
||||
if (s.startsWith("en")) return "en";
|
||||
return "zh";
|
||||
}
|
||||
|
||||
let lang: Lang = "zh";
|
||||
|
||||
/** 设置界面语言(magpie 主题消息与测试都走这里);值先归一,未传即回 zh */
|
||||
export function setLang(raw: string | null | undefined): void {
|
||||
lang = normalizeLang(raw);
|
||||
}
|
||||
|
||||
/** 当前界面语言(渲染签名与 <html lang> 用) */
|
||||
export function currentLang(): Lang {
|
||||
return lang;
|
||||
}
|
||||
|
||||
/** 取当前语言的文案:键是中文原文,zh(含表里查不到的键)原样返回 */
|
||||
export function t(s: string): string {
|
||||
return I18N[lang]?.[s] ?? s;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<!doctype html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>窗口预热</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="app">
|
||||
<div class="wrap">
|
||||
<div class="bar">
|
||||
<span class="sum" id="sum"></span>
|
||||
<span class="sp"></span>
|
||||
<button class="qm" id="info" aria-label="说明">?<span class="tip">消息按供应商自己的额度规则计费,可能用到赠送额度或 API 余额;发送成功不代表窗口一定已开始计时。<br>Magpie 关闭期间不会执行,重新打开后每个任务最多补发一次。<br>失败不会暂停任务,下一次照常执行。</span></button>
|
||||
<button class="btn" id="new">新建任务</button>
|
||||
</div>
|
||||
<div id="bars"></div>
|
||||
<div class="list" id="list"></div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="app.js" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,148 @@
|
||||
/* 窗口预热界面:逐值照已确认原型 v10 的样式实现(颜色变量、深色变量、控件尺寸、间距、字号)。
|
||||
深浅色经 body.dark 切换(启动页带 ?theme=),magpie 设计令牌由脚本写入 :root,同名变量即被覆盖。 */
|
||||
:root {
|
||||
--bg:#f4f4f6; --card:#fff; --card-2:#f9f9fb; --pill:#f1f1f4; --pill-hover:#e9e9ee;
|
||||
--line:#e3e3e8; --line-2:#ececf0; --fg:#1c1c21; --fg-2:#4b4b53; --muted:#85858d; --faint:#b9b9c2; --ctl-fg:#63636b;
|
||||
--accent:#4f46e5; --accent-soft:#eeedfd; --sel:#ecebfb;
|
||||
--green:#189a58; --green-soft:#e4f6ec; --red:#d64545; --red-soft:#fbe9e9; --amber:#b45309; --amber-soft:#fbf0df;
|
||||
--font:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI","PingFang SC","Microsoft YaHei",system-ui,sans-serif;
|
||||
--code:ui-monospace,"SF Mono",Menlo,Consolas,monospace;
|
||||
}
|
||||
body.dark {
|
||||
--bg:#1a1a1e; --card:#232327; --card-2:#1f1f23; --pill:#2d2d33; --pill-hover:#36363d;
|
||||
--line:#333339; --line-2:#2c2c32; --fg:#ededf1; --fg-2:#b9b9c1; --muted:#8b8b94; --faint:#56565f; --ctl-fg:#a1a1aa;
|
||||
--accent:#a5b4fc; --accent-soft:#2b2c47; --sel:#33345a;
|
||||
--green:#4ade80; --green-soft:#1d3327; --red:#f87171; --red-soft:#3a2224; --amber:#fbbf24; --amber-soft:#3a2f1c;
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
html,body { margin:0; height:100%; }
|
||||
body { font:13px/1.45 var(--font); color:var(--fg); background:var(--bg); }
|
||||
button,input,select,textarea { font:inherit; color:inherit; }
|
||||
button { background:none; border:0; cursor:default; }
|
||||
:focus-visible { outline:2px solid var(--accent); outline-offset:1px; }
|
||||
|
||||
/* 页面主体是唯一滚动容器:宿主给多高就占多高,插件内部只滚这一处 */
|
||||
.app { height:100%; overflow:auto; padding:14px 18px 24px; }
|
||||
.wrap { max-width:860px; margin:0 auto; }
|
||||
.bar { display:flex; align-items:center; gap:8px; margin-bottom:10px; }
|
||||
.bar .sum { color:var(--muted); font-size:12px; }
|
||||
.bar .sum b { font-weight:500; color:var(--fg-2); font-variant-numeric:tabular-nums; }
|
||||
.bar .sp { flex:1; }
|
||||
.qm { width:20px; height:20px; border-radius:50%; color:var(--faint); font-size:11px; font-weight:600; position:relative; box-shadow:inset 0 0 0 1px var(--line); }
|
||||
.qm:hover { color:var(--fg-2); }
|
||||
.qm .tip { display:none; position:absolute; right:0; top:26px; width:320px; z-index:5; text-align:left; font-weight:400; font-size:12px; color:var(--fg-2); background:var(--card); border-radius:10px; padding:10px 12px; line-height:1.6; box-shadow:0 16px 44px rgba(20,22,30,.16),0 0 0 .5px rgba(20,22,30,.1); }
|
||||
.qm:hover .tip, .qm:focus .tip { display:block; }
|
||||
/* 按钮:照 Magpie 的 .text.action / .text.primary / .text.danger */
|
||||
.btn { height:27px; padding:0 10px; border-radius:6px; font-size:12px; border:1px solid var(--line); background:var(--card); color:var(--fg-2); box-shadow:0 1px 1px rgba(0,0,0,.04); }
|
||||
.btn:hover { border-color:var(--muted); background:var(--card-2); color:var(--fg); }
|
||||
.btn.primary { border-color:transparent; background:var(--accent); color:#fff; font-weight:500; }
|
||||
body.dark .btn.primary { color:#14142a; }
|
||||
.btn.primary:hover { filter:brightness(1.08); background:var(--accent); }
|
||||
.btn.danger { border:0; box-shadow:none; background:none; color:var(--ctl-fg); padding:0 7px; }
|
||||
.btn.danger:hover { color:var(--red); background:var(--red-soft); }
|
||||
.btn[disabled] { opacity:.5; }
|
||||
|
||||
/* 全局提示条(断连 / 致命 / 单实例锁 / 保存失败 / 目录错误):原型之外的必要补充,配色取自同一套变量 */
|
||||
.notice { margin-top:8px; border-radius:8px; padding:7px 12px; font-size:12px; }
|
||||
.notice.warn { background:var(--amber-soft); color:var(--amber); }
|
||||
.notice.bad { background:var(--red-soft); color:var(--red); }
|
||||
|
||||
.list { background:var(--card); border:1px solid var(--line); border-radius:12px; overflow:hidden; }
|
||||
.row { display:flex; align-items:center; gap:12px; min-height:48px; padding:7px 12px 7px 14px; }
|
||||
.row + .row, .editor + .row, .row + .editor { border-top:1px solid var(--line-2); }
|
||||
.row:hover { background:var(--card-2); }
|
||||
.who { flex:1; min-width:0; }
|
||||
.who .name { font-weight:500; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.who .sub { font-size:11.5px; color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-top:1px; }
|
||||
.row.dim .name { color:var(--muted); }
|
||||
.when { text-align:right; flex:none; font-size:11.5px; color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.when .t { color:var(--fg-2); font-size:12px; }
|
||||
.when .s.bad { color:var(--red); }
|
||||
.when .s.unk { color:var(--amber); }
|
||||
/* 开关:Magpie 的 lib-switch,开是前景色(黑),不是绿 */
|
||||
.sw { width:28px; height:16px; border-radius:10px; background:var(--line); position:relative; flex:none; transition:background .2s; }
|
||||
.sw::after { content:""; position:absolute; top:2px; left:2px; width:12px; height:12px; border-radius:50%; background:#fff; box-shadow:0 1px 2px rgba(0,0,0,.25); transition:transform .22s; }
|
||||
.sw.on { background:var(--fg); }
|
||||
.sw.on::after { transform:translateX(12px); background:var(--card); }
|
||||
body.dark .sw.on::after { background:var(--bg); }
|
||||
.chev { color:var(--faint); width:12px; flex:none; transition:transform .15s; font-size:14px; }
|
||||
.row.open .chev { transform:rotate(90deg); color:var(--muted); }
|
||||
|
||||
/* 展开编辑区:Magpie 的 .editor —— 标签右对齐、白底细边输入框 */
|
||||
.editor { background:var(--card-2); padding:16px 18px 14px; display:grid; grid-template-columns:fit-content(132px) minmax(0,1fr); gap:10px 14px; align-items:start; }
|
||||
.editor > label { font-size:12px; color:var(--fg-2); text-align:right; padding-top:5px; }
|
||||
.editor > .v { min-width:0; }
|
||||
.editor > .full { grid-column:1 / -1; }
|
||||
.note { font-size:12px; color:var(--red); }
|
||||
.note span { color:var(--fg-2); }
|
||||
.stale { font-size:12px; color:var(--amber); }
|
||||
/* 下拉:逐值照 Magpie 主窗口的 .field:
|
||||
高 25、左 8 右 5 内边距、间距 5、整体 12.5px;key 11.5px 浅灰;值 12.5px 字重 500 超长省略;箭头 11px。
|
||||
不用原生 select:原生控件自带边距和基线,key 与值对不齐 */
|
||||
.field { display:inline-flex; align-items:center; gap:5px; height:25px; padding:0 5px 0 8px; border-radius:6px; background:var(--pill); font-size:12.5px; line-height:18px; max-width:100%; min-width:0; transition:background .12s, box-shadow .12s; }
|
||||
.field:hover { background:var(--pill-hover); }
|
||||
.field.open { background:var(--pill-hover); box-shadow:inset 0 0 0 1px var(--accent); }
|
||||
/* 禁用的下拉(如该账号没有任何模型列表)只展示当前值:去 hover 反馈但保留 title 提示 */
|
||||
.field[disabled] { opacity:.5; }
|
||||
.field[disabled]:hover { background:var(--pill); box-shadow:none; }
|
||||
/* 字号不同(11.5 / 12.5)、中英文回退字体不同,按中线居中会让文字底边错开;人眼看的是基线,所以这里按基线对齐 */
|
||||
.field .kv { display:flex; align-items:baseline; gap:5px; min-width:0; flex:1 1 auto; overflow:hidden; }
|
||||
.field .k { color:var(--faint); font-size:11.5px; flex:none; }
|
||||
.field .v { min-width:0; flex:0 1 auto; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; font-weight:500; font-variant-numeric:tabular-nums; }
|
||||
.field .aux { flex:none; color:var(--faint); font-size:11.5px; font-variant-numeric:tabular-nums; }
|
||||
.field .chev { flex:none; color:var(--faint); display:inline-flex; margin-left:auto; padding-left:1px; }
|
||||
.field:hover .chev, .field.open .chev { color:var(--muted); }
|
||||
.field input[type=time], .field input[type=datetime-local] { border:0; background:none; outline:none; padding:0; font:inherit; font-weight:500; line-height:18px; height:20px; color:var(--fg); }
|
||||
/* 同 Magpie 主窗口:下拉排成固定列、撑满各自的列,箭头上下对齐;值再长也只在自己的列里省略 */
|
||||
.fields { display:grid; gap:5px; }
|
||||
.fields.c3 { grid-template-columns:repeat(auto-fit, minmax(180px, 1fr)); }
|
||||
.fields.c2 { grid-template-columns:minmax(0,1fr) minmax(0,1fr); max-width:420px; }
|
||||
.fields.c1 { grid-template-columns:minmax(0,1fr); }
|
||||
.fields > .field { justify-self:stretch; }
|
||||
.pop { position:fixed; z-index:30; min-width:180px; max-width:min(440px, calc(100vw - 24px)); max-height:300px; overflow:auto; padding:5px; border-radius:11px; background:var(--card); box-shadow:0 16px 44px rgba(20,22,30,.16),0 2px 8px rgba(20,22,30,.06),0 0 0 .5px rgba(20,22,30,.1); }
|
||||
.pop .it { display:flex; align-items:center; gap:8px; width:100%; min-height:28px; padding:4px 8px; border-radius:7px; font-size:12.5px; text-align:left; color:var(--fg); }
|
||||
.pop .it:hover, .pop .it:focus { background:var(--pill); outline:none; }
|
||||
.pop .it .tx { flex:1; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.pop .it .tick { width:12px; flex:none; color:var(--fg); font-size:11px; }
|
||||
.pop .it .aux { flex:none; color:var(--muted); font-size:11.5px; font-variant-numeric:tabular-nums; }
|
||||
input.text, textarea.text { width:100%; height:27px; padding:0 9px; border-radius:7px; border:1px solid var(--line); background:var(--card); font-size:12.5px; outline:none; }
|
||||
textarea.text { height:auto; min-height:27px; padding:4px 9px; resize:vertical; }
|
||||
input.text:focus, textarea.text:focus { border-color:var(--accent); box-shadow:0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
|
||||
input.text::placeholder { color:var(--faint); }
|
||||
.hint { margin-top:4px; font-size:11px; color:var(--fg-2); }
|
||||
.hint.mute { color:var(--muted); }
|
||||
.hint.warn { color:var(--amber); }
|
||||
.seg { display:inline-flex; padding:2px; border-radius:8px; background:var(--pill); }
|
||||
.seg button { height:22px; padding:0 11px; border-radius:6px; font-size:12px; color:var(--ctl-fg); }
|
||||
.seg button.on { background:var(--card); color:var(--fg); box-shadow:0 1px 2px rgba(0,0,0,.14),0 0 0 .5px rgba(0,0,0,.08); }
|
||||
.next { margin-top:6px; font-size:11px; color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.next b { font-weight:500; color:var(--fg-2); }
|
||||
.actions { display:flex; gap:8px; align-items:center; padding-top:12px; border-top:1px solid var(--line-2); }
|
||||
.actions .sp { flex:1; }
|
||||
.dirty-tip { font-size:11.5px; color:var(--muted); }
|
||||
|
||||
.runs-h { display:flex; align-items:baseline; gap:8px; margin-top:4px; }
|
||||
.runs-h b { font-weight:500; font-size:12px; color:var(--fg-2); }
|
||||
.runs-h span { font-size:11px; color:var(--muted); }
|
||||
.runs-h .sp { flex:1; }
|
||||
.link { font-size:12px; color:var(--ctl-fg); padding:3px 7px; border-radius:6px; }
|
||||
.link:hover { color:var(--fg); background:var(--pill); }
|
||||
.link:disabled { color:var(--faint); background:none; }
|
||||
.runs { background:var(--card); border:1px solid var(--line); border-radius:10px; overflow:hidden; margin-top:6px; }
|
||||
.run { display:grid; grid-template-columns:84px 40px minmax(0,1fr); gap:10px; padding:6px 11px; font-size:12px; align-items:baseline; }
|
||||
.run + .run { border-top:1px solid var(--line-2); }
|
||||
.run .t { color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.run .r { color:var(--muted); }
|
||||
.run .r.bad { color:var(--red); }
|
||||
.run .r.unk { color:var(--amber); }
|
||||
.run .why { color:var(--fg-2); overflow-wrap:anywhere; }
|
||||
.more { display:block; width:100%; padding:6px; font-size:11px; color:var(--muted); border-top:1px solid var(--line-2); }
|
||||
.more:hover { color:var(--fg); }
|
||||
.empty { padding:36px 20px; text-align:center; color:var(--muted); }
|
||||
.empty b { display:block; color:var(--fg); font-weight:500; margin-bottom:4px; }
|
||||
@media (prefers-reduced-motion:reduce) { * { transition:none !important; } }
|
||||
@media (max-width:640px) {
|
||||
.editor { grid-template-columns:1fr; }
|
||||
.editor > label { text-align:left; padding-top:0; }
|
||||
.qm .tip { width:min(320px, 86vw); }
|
||||
}
|
||||
+3
-2
@@ -182,10 +182,11 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "magpie-window-warmup",
|
||||
"package": "@magpie-community/page-window-warmup",
|
||||
"name": "Window Warmup",
|
||||
"kind": "page",
|
||||
"icon": "https://raw.githubusercontent.com/YangHonghang/magpie-window-warmup/main/page/icon.svg",
|
||||
"community": true,
|
||||
"icon": "https://raw.githubusercontent.com/magpie-community/plugins/main/packages/window-warmup/page/icon.svg",
|
||||
"summary": {
|
||||
"en": "Window warmup (formerly Scheduled Messages): warm up a subscription's 5-hour or weekly quota / usage window ahead of time with a keep-alive (keep alive) message. It sends one fixed short message (\"hi\", max_tokens 16) to a provider, account and model you pick, on a schedule: right after its rate limit window resets, daily at set times or every few hours. Each send uses that provider's quota. Runs a local service on 127.0.0.1 that only calls magpie's own gateway; only its own page gets the token.",
|
||||
"zh": "窗口预热(原「定时消息」):提前开启订阅的 5 小时或每周额度窗口,给额度保活。给指定的供应商、账号和模型发一条固定短消息(\"hi\",max_tokens 16),可在窗口重置后、每天定时或每隔几小时发送。每次发送都会消耗该供应商的额度(配额)。在本机 127.0.0.1 跑一个本地服务,只调用 magpie 自己的网关;令牌只交给自己的页面。"
|
||||
|
||||
Reference in New Issue
Block a user