@dorokuma/magpie-gemini-web 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  本文件按版本倒序记录 `magpie-gemini-web`(0.15.0 起为 `@dorokuma/magpie-gemini-web`)的全部已发布与待发变更,依据本仓 `git log` 与 tag 事实编写。
4
4
 
5
+ ## 0.23.0 - 2026-11-25
6
+
7
+ ### 新增
8
+ - Gemini Web 后端 pin 升级至 **`dorokuma/gemini-web2api-go` `v6.7.0`** 官方预编译二进制:Cookie JSON / Playwright `storageState` / cURL 导入与 `POST /admin/api/cookies/sync` 扩展自动同步、`accounts.auto_disabled` 自动/手动停用区分、内存环形系统日志 `/admin/api/logs` 与面板「系统日志」页。
9
+ - 合入上游高价值提交(`BUKOWSKIREAL/magpie-gemini-web`):容器僵尸进程探活与锁自愈(`lib/proc.mjs` 统一 `kill(pid,0)` + `/proc/<pid>/stat` 状态检查,`processAlive`/`processExists`/`zombie`/`setProcRoot`;接入 `cleanup.mjs`、`native.mjs`、`studio-native.mjs`、`studio-updates.mjs`)、Windows 短暂可执行文件锁重试删除(`forceRemoveBackendPath`/`forceRemovePath` 改异步重试:win32 最多 25×100ms,非 win32 最多 3 次)、容器环境代理防呆提示(`isContainerEnv`/`isLoopbackProxy`/`dockerProxyHint`;`index.mjs` 登录向导 proxyPrompt 与 submit 失败提示接入)、AI Studio 自动更新双次空闲复检(`idleActivity` 拆出,冷启动 `GET /api/update` 超时放宽至 30s 并捕获 `TimeoutError`/`AbortError` 推迟至下一轮,慢查询后二次复检防在途请求被打断)、AI Studio 用量卡片四连增强(账号状态窗口 `accountStateWindow`、本地今日 Token 与 API 标价估算 `dailyUsageWindows`、`capabilities.modelCost===1` 映射 `estimated_cost` 分段费率 `studioModelCost`、区分冷却不可读与空列表 `hasCooldownsData`;`ready` 显示为「账号就绪」)。
10
+
11
+ ### 修复
12
+ - `test/studio-user-backend.test.mjs`:合入上游 `endChild` 加固(unref 子进程 `ref()` + 5s 超时兜底 + `disconnect()`/`SIGKILL` 防御)与 `fixture` 目录删除重试(`maxRetries: 10, retryDelay: 100`),消除在 `umask 0022` 下因子进程未退出导致的 `cancelledByParent` 级联取消。
13
+
5
14
  ## 0.22.0 - 2026-11-24
6
15
 
7
16
  ### 新增
package/README.en.md CHANGED
@@ -99,6 +99,9 @@ Need multiple accounts, usage-card refresh details or the full image-generation
99
99
  - **Usage reporting:**
100
100
  - `gemini-web`: Available only with the one-click local backend. Usage is read from Google again whenever Magpie asks for it (at most once every 30 seconds per account), so pressing refresh shows the current allowance, including usage from the Gemini app, the website or other devices. On its own, Magpie asks about once a minute while the Usage page or the menu bar's allowances panel is open, whenever it updates allowances shown in the menu bar (every 3 minutes by default), and at most once a minute while it routes requests among accounts; otherwise it doesn't ask. A failed read isn't retried on its own for 10 minutes; pressing refresh in that time retries it at once (press it again if the first press doesn't).
101
101
  - `ai-studio`: AI Studio does not report remaining total quota; cards display models currently on cooldown and their recovery times, or prompt when re-authentication is needed.
102
+ Cards also show today's tokens and estimated USD at API list prices from the local backend's request ledger, filtered to that account or imported group. Today starts at midnight in the Magpie host's timezone. These are estimates for traffic through this backend, not actual charges or remaining credits. The backend handles model pricing, cached input and long-context tiers; unpriced models are marked as missing or partial pricing. If the backend cannot provide this report, the daily row is omitted.
103
+
104
+ When the backend's `/v1/models` supplies `estimated_cost`, the plugin passes the same input, output, cached-input and context-tier rates to Magpie. Magpie hosts advertising `magpie.capabilities.modelCost: 1` use those backend rates on the Usage page, with user-set prices taking precedence. Older Magpie hosts, OpenCode, and backends without that field keep their existing catalog pricing. Account cards cover the backend's traffic; Usage covers requests recorded by Magpie, so token costs can be compared for the same requests.
102
105
 
103
106
  ## Image Generation (AI Studio)
104
107
 
package/README.md CHANGED
@@ -99,6 +99,9 @@ flowchart LR
99
99
  - **用量刷新说明**:
100
100
  - `gemini-web`:仅一键配置的本地后端可读取用量。Magpie 每次来查都会向 Google 重新读取(同一账号 30 秒内只读一次),点刷新即显示最新额度,包括在 Gemini 官方 App、网页或其他设备上的用量。Magpie 自己来查的频率:用量页或菜单栏的额度面板开着时约每分钟一次;菜单栏显示任何一家额度时随菜单栏更新(默认每 3 分钟);经 Magpie 转发请求时最多每分钟一次;都没有时不查。读取失败后 10 分钟内不自动重试,这期间点刷新会立即重试,若未生效再点一次。
101
101
  - `ai-studio`:AI Studio 不提供剩余总额度,卡片会展示当前账号正在冷却的模型、恢复时间或重新登录提示。
102
+ 同时按账号或导入的账号组展示本地后端账本中的今日 tokens 与 API 标价估算美元费用,以 Magpie 所在机器时区的午夜为起点。仅统计经过该后端的请求,不是实际扣款或剩余 credits。模型价格、缓存输入和长上下文分档由后端计算;无价格的模型会标明未计价或部分未计价。后端不支持或读取失败时不展示该行。
103
+
104
+ 后端 `/v1/models` 提供 `estimated_cost` 时,插件把同一份输入、输出、缓存与长上下文单价传给 Magpie 的模型计价。声明 `magpie.capabilities.modelCost: 1` 的 Magpie 会按后端单价估算用量页费用,用户手动设置的价格优先;旧版 Magpie、OpenCode 或未提供该字段的后端继续使用原有目录计价。账号卡统计整个后端的流量,用量页统计 Magpie 收录的请求,相同请求的 token 费用可对照。
102
105
 
103
106
  ## 图片生成(AI Studio)
104
107
 
package/index.mjs CHANGED
@@ -4,6 +4,7 @@ import { registerMagpieCleanup, isPluginRemovedInActiveMagpie } from './lib/clea
4
4
  import { importCookie, removeAccount, ensureProxy, validateProxyURL, requireLoginBackend } from './lib/setup.mjs';
5
5
  import { usage, poolChoices, poolAccounts, accountEmail } from './lib/usage.mjs';
6
6
  import { startWebConnect } from './lib/web-connect.mjs';
7
+ import { isContainerEnv, dockerProxyHint } from './lib/proc.mjs';
7
8
 
8
9
  const ID = 'gemini-web';
9
10
 
@@ -85,11 +86,14 @@ export const GeminiWebPlugin = async (_input, options = {}) => {
85
86
  const { studio: _studio, ...webOptions } = options;
86
87
  const opts = settings(webOptions);
87
88
  registerMagpieCleanup(_input);
89
+ const inContainer = isContainerEnv();
88
90
  const proxyPrompt = {
89
91
  type: 'text',
90
92
  key: 'proxy',
91
- message: '访问 Google 的代理地址(无需代理或已在代理池配置可留空)',
92
- placeholder: opts.proxy || 'http://127.0.0.1:7890',
93
+ message: inContainer
94
+ ? '访问 Google 的代理地址(容器 bridge 网络勿填 127.0.0.1,请填 http://host.docker.internal:<端口> 或宿主机局域网 IP;无需代理或已在代理池配置可留空)'
95
+ : '访问 Google 的代理地址(无需代理或已在代理池配置可留空)',
96
+ placeholder: opts.proxy || (inContainer ? 'http://host.docker.internal:7890' : 'http://127.0.0.1:7890'),
93
97
  validate: value => {
94
98
  try {
95
99
  validateProxyURL(value);
@@ -161,19 +165,36 @@ export const GeminiWebPlugin = async (_input, options = {}) => {
161
165
  const session = await startWebConnect({
162
166
  proxy,
163
167
  async submit({ cookie, authuser, proxy: formProxy, isEnded }) {
168
+ const bind = formProxy !== undefined ? formProxy : initialProxy;
169
+ // A loopback proxy inside a container is the classic misconfiguration behind a
170
+ // failed wait/import, so the docker hint rides on the error — but never on a
171
+ // cancellation message, and never twice. The page renders errors through
172
+ // textContent, so the hint joins as a new sentence rather than a folded '\n'.
173
+ const withProxyHint = err => {
174
+ if (isEnded?.()) return err;
175
+ const hint = dockerProxyHint(bind);
176
+ const msg = err.message;
177
+ if (!hint || msg.includes(hint)) return err;
178
+ const sep = /[。.!?!?]$/.test(msg) ? ' ' : '。';
179
+ return new Error(`${msg}${sep}${hint}`, { cause: err });
180
+ };
164
181
  if (readyFailed || (formProxy !== undefined && formProxy !== initialProxy)) {
165
182
  startReady(formProxy !== undefined ? formProxy : initialProxy);
166
183
  }
167
- const local = await ready;
168
- // The user may have cancelled or the session timed out while the backend was
169
- // starting; importing into it now would keep an account nobody signs in to.
170
- if (isEnded?.()) throw new Error('登录已结束,未导入 Cookie。');
171
- const bind = formProxy !== undefined ? formProxy : initialProxy;
172
- const added = await importCookie(local, cookie, {
173
- authuser,
174
- isEnded,
175
- ...(bind ? { proxy: bind } : {})
176
- });
184
+ let local, added;
185
+ try {
186
+ local = await ready;
187
+ // The user may have cancelled or the session timed out while the backend was
188
+ // starting; importing into it now would keep an account nobody signs in to.
189
+ if (isEnded?.()) throw new Error('登录已结束,未导入 Cookie。');
190
+ added = await importCookie(local, cookie, {
191
+ authuser,
192
+ isEnded,
193
+ ...(bind ? { proxy: bind } : {})
194
+ });
195
+ } catch (err) {
196
+ throw withProxyHint(err);
197
+ }
177
198
  // importCookie's own rollback ends when it returns. A session that ends during
178
199
  // poolAccounts or signInFor (accountEmail waits on Gemini, up to its 15s
179
200
  // timeout) still leaves the account it created, so this submit keeps removing
@@ -1,31 +1,31 @@
1
1
  {
2
- "version": "6.6.0",
2
+ "version": "6.7.0",
3
3
  "repository": "dorokuma/gemini-web2api-go",
4
- "tag": "v6.6.0",
4
+ "tag": "v6.7.0",
5
5
  "binaries": {
6
6
  "darwin-x64": {
7
- "asset": "gemini-web2api-go_v6.6.0_darwin_amd64",
8
- "sha256": "a0814b79daa2aef445fd8e8d25cda86060a921e454f1c6072acb8fc0bd231d66"
7
+ "asset": "gemini-web2api-go_v6.7.0_darwin_amd64",
8
+ "sha256": "40817736b1ec73bfe0136a61fb26bdf4bc48f8726a587a22d0bcd4d42f1492b3"
9
9
  },
10
10
  "darwin-arm64": {
11
- "asset": "gemini-web2api-go_v6.6.0_darwin_arm64",
12
- "sha256": "fc1d12e3014347ed01dba97a485487188de4108c8259509bdd1d21629c5d61a8"
11
+ "asset": "gemini-web2api-go_v6.7.0_darwin_arm64",
12
+ "sha256": "58f4f4e8aff8154033d3d0c1bb23d642f0275173bc7c0ce7cb0c5ad091cd7cba"
13
13
  },
14
14
  "linux-x64": {
15
- "asset": "gemini-web2api-go_v6.6.0_linux_amd64",
16
- "sha256": "911e83daca3e2519129c98e6dc890e1d2e775d67337cb15702057f21e9e00d46"
15
+ "asset": "gemini-web2api-go_v6.7.0_linux_amd64",
16
+ "sha256": "48cc0e140110bb36f3ade4ab9aff86f324a3b4759915084613e2f47e485ee391"
17
17
  },
18
18
  "linux-arm64": {
19
- "asset": "gemini-web2api-go_v6.6.0_linux_arm64",
20
- "sha256": "4da97d0cff36e171c747669afc737c413c8acf91f618db73a7a222d326410bc1"
19
+ "asset": "gemini-web2api-go_v6.7.0_linux_arm64",
20
+ "sha256": "364bb723ae57fbbba6fb7b4b78e4e1fb42d633df8723e26ee7494e7fae8a2e71"
21
21
  },
22
22
  "win32-x64": {
23
- "asset": "gemini-web2api-go_v6.6.0_windows_amd64.exe",
24
- "sha256": "378915e9cb16dbee6729abaf950df3d42da684e1b88ad20078a77533c8898656"
23
+ "asset": "gemini-web2api-go_v6.7.0_windows_amd64.exe",
24
+ "sha256": "f13ee86a20aa363bda2766b141e4ed0b9ac15b27edb014b96715441d5f6652a5"
25
25
  },
26
26
  "win32-arm64": {
27
- "asset": "gemini-web2api-go_v6.6.0_windows_arm64.exe",
28
- "sha256": "f5b090a38a7509a125cf3310280dc09d5ad34506ffc04d4c8dc48fe0f892080f"
27
+ "asset": "gemini-web2api-go_v6.7.0_windows_arm64.exe",
28
+ "sha256": "4b4304ceec6567d8f38d7a88baa0aa13922328bee39ef9ec6f5433e1a6cb68da"
29
29
  }
30
30
  }
31
31
  }
package/lib/cleanup.mjs CHANGED
@@ -4,6 +4,7 @@ import os from 'node:os';
4
4
  import crypto from 'node:crypto';
5
5
  import { spawn, execFileSync } from 'node:child_process';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import { processAlive } from './proc.mjs';
7
8
  import {
8
9
  studioDataDir,
9
10
  cleanStudio,
@@ -157,15 +158,7 @@ function watcherPidFilePath(magpieDir) {
157
158
  return path.join(os.tmpdir(), `magpie-gemini-web-cleanup-${key}.pid`);
158
159
  }
159
160
 
160
- function isProcessAlive(pid) {
161
- if (!Number.isInteger(pid) || pid <= 0) return false;
162
- try {
163
- process.kill(pid, 0);
164
- return true;
165
- } catch (err) {
166
- return err.code === 'EPERM';
167
- }
168
- }
161
+ const isProcessAlive = processAlive;
169
162
 
170
163
  // The pidfile graduated from a bare PID line to JSON { pid, pluginRoot, version } so a
171
164
  // watcher from an older plugin build can be replaced instead of silently reused.
package/lib/native.mjs CHANGED
@@ -5,6 +5,7 @@ import crypto from 'node:crypto';
5
5
  import { spawn, execFile, execFileSync } from 'node:child_process';
6
6
  import { validateProxyURL } from './setup.mjs';
7
7
  import { verifyProcessIdentity, studioProcessPids, studioListenerPids } from './studio-native.mjs';
8
+ import { processAlive } from './proc.mjs';
8
9
  import { hasProxyCredentials, normalizeCurlProxy, redactProxyCredentials } from './studio-upstream.mjs';
9
10
  import release from './backend-release.json' with { type: 'json' };
10
11
 
@@ -819,11 +820,6 @@ export function setBackendAssetHook(fn) {
819
820
  onBackendAssetInstalled = typeof fn === 'function' ? fn : null;
820
821
  }
821
822
 
822
- function processAlive(pid) {
823
- if (!Number.isInteger(pid) || pid <= 0) return false;
824
- try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
825
- }
826
-
827
823
  function recordedBackendPid(dataDir) {
828
824
  try { return Number(fs.readFileSync(path.join(dataDir, 'backend.pid'), 'utf8').trim()); } catch { return NaN; }
829
825
  }
@@ -846,20 +842,25 @@ export function hasBackendAssets(dataDir = getDataDir(), platform = process.plat
846
842
  return false;
847
843
  }
848
844
 
849
- function forceRemoveBackendPath(target, platform) {
845
+ async function forceRemoveBackendPath(target, platform) {
850
846
  if (!fs.existsSync(target)) return false;
851
- try {
852
- if (platform !== 'win32') {
853
- const st = fs.lstatSync(target);
854
- if (st.isDirectory()) {
855
- try { fs.chmodSync(target, (st.mode & 0o777) | 0o700); } catch {}
847
+ const maxAttempts = platform === 'win32' ? 25 : 3;
848
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
849
+ try {
850
+ if (platform !== 'win32') {
851
+ const st = fs.lstatSync(target);
852
+ if (st.isDirectory()) {
853
+ try { fs.chmodSync(target, (st.mode & 0o777) | 0o700); } catch {}
854
+ }
856
855
  }
856
+ fs.rmSync(target, { recursive: true, force: true });
857
+ if (!fs.existsSync(target)) return true;
858
+ } catch {}
859
+ if (attempt < maxAttempts) {
860
+ await new Promise(resolve => setTimeout(resolve, 100));
857
861
  }
858
- fs.rmSync(target, { recursive: true, force: true });
859
- return !fs.existsSync(target);
860
- } catch {
861
- return false;
862
862
  }
863
+ return !fs.existsSync(target);
863
864
  }
864
865
 
865
866
  export async function stopBackend(options = {}) {
@@ -1005,7 +1006,7 @@ export async function cleanBackend(options = {}) {
1005
1006
 
1006
1007
  const removed = [];
1007
1008
  for (const name of ['bin', 'backend.pid', 'backend-channel.json', 'argon-build.json']) {
1008
- if (forceRemoveBackendPath(path.join(dataDir, name), platform)) {
1009
+ if (await forceRemoveBackendPath(path.join(dataDir, name), platform)) {
1009
1010
  removed.push(name);
1010
1011
  }
1011
1012
  }
package/lib/proc.mjs ADDED
@@ -0,0 +1,86 @@
1
+ import fs from 'node:fs';
2
+
3
+ // Where /proc is read. Tests point it at a fake tree.
4
+ let procRoot = '/proc';
5
+
6
+ export function setProcRoot(root) {
7
+ procRoot = root || '/proc';
8
+ }
9
+
10
+ // zombie: /proc says the PID has exited and waits only to be reaped (Z), or is
11
+ // being torn down (X). A process whose parent ended is adopted by PID 1, and in
12
+ // a container without an init (magpie itself as PID 1) nothing may ever reap
13
+ // it, while kill(pid, 0) still succeeds on it. Off Linux there is no /proc and
14
+ // an unreadable entry is not evidence of exit: both answer false.
15
+ export function zombie(pid) {
16
+ let stat;
17
+ try { stat = fs.readFileSync(`${procRoot}/${pid}/stat`, 'utf8'); } catch { return false; }
18
+ // The command name, in parentheses, can hold spaces and ')'; the state follows the last ')'.
19
+ const state = stat.slice(stat.lastIndexOf(')') + 1).trim()[0];
20
+ return state === 'Z' || state === 'X';
21
+ }
22
+
23
+ // processAlive: a PID that can still run. EPERM means it exists under another
24
+ // user; a zombie has exited.
25
+ export function processAlive(pid) {
26
+ if (!Number.isInteger(pid) || pid <= 0) return false;
27
+ try { process.kill(pid, 0); } catch (err) { if (err.code !== 'EPERM') return false; }
28
+ return !zombie(pid);
29
+ }
30
+
31
+ // processExists: as processAlive, but a failed probe other than ESRCH counts as
32
+ // alive, for callers that must not reclaim what they cannot inspect.
33
+ export function processExists(pid) {
34
+ if (!Number.isInteger(pid) || pid <= 0) return false;
35
+ try { process.kill(pid, 0); } catch (err) { if (err.code === 'ESRCH') return false; }
36
+ return !zombie(pid);
37
+ }
38
+
39
+ /**
40
+ * Returns whether the current process appears to be running inside a container.
41
+ */
42
+ export function isContainerEnv({
43
+ env = process.env,
44
+ platform = process.platform,
45
+ existsSync = fs.existsSync,
46
+ readFileSync = fs.readFileSync,
47
+ } = {}) {
48
+ const override = String(env?.DOCKER_CONTAINER || '').trim().toLowerCase();
49
+ if (override === '1' || override === 'true') return true;
50
+ if (override === '0' || override === 'false') return false;
51
+ if (String(env?.container || '').trim()) return true;
52
+ if (String(env?.KUBERNETES_SERVICE_HOST || '').trim()) return true;
53
+ if (platform !== 'linux') return false;
54
+ try {
55
+ if (existsSync('/.dockerenv') || existsSync('/run/.containerenv')) return true;
56
+ } catch {}
57
+ try {
58
+ const cgroup = readFileSync('/proc/1/cgroup', 'utf8');
59
+ if (/(?:docker|containerd|kubepods|podman|lxc)/i.test(cgroup)) return true;
60
+ } catch {}
61
+ return false;
62
+ }
63
+
64
+ /**
65
+ * Returns whether a proxy URL points to loopback (127.0.0.1, localhost, or ::1).
66
+ */
67
+ export function isLoopbackProxy(proxy) {
68
+ const raw = String(proxy || '').trim();
69
+ if (!raw) return false;
70
+ try {
71
+ const { hostname } = new URL(raw);
72
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
73
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1';
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Returns a Docker-specific hint when a loopback proxy URL is used inside a container.
81
+ */
82
+ export function dockerProxyHint(proxy, opts = {}) {
83
+ const inContainer = opts.container ?? isContainerEnv(opts);
84
+ if (!inContainer || !isLoopbackProxy(proxy)) return '';
85
+ return '检测到当前运行在容器环境中,容器内的 127.0.0.1/localhost 指向容器自身而非宿主机代理;若代理在宿主机上,请改用 http://host.docker.internal:<端口>(Linux Docker 需添加 --add-host=host.docker.internal:host-gateway)、宿主机局域网 IP,或使用 --network host。';
86
+ }
@@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url';
9
9
  import { spawn, execFile, execFileSync } from 'node:child_process';
10
10
  import { promisify } from 'node:util';
11
11
  import { resolveStudioRelease, hasProxyCredentials, normalizeCurlProxy, redactProxyCredentials } from './studio-upstream.mjs';
12
+ import { processAlive, processExists, zombie } from './proc.mjs';
12
13
 
13
14
  // execFileAsync is execFile awaited: unpacking a download this way leaves the plugin host free to answer
14
15
  // meanwhile, a sign-in's progress page among others.
@@ -1345,6 +1346,7 @@ function hasStudioAuthArg(pid, dataDir, platform) {
1345
1346
  try {
1346
1347
  if (platform === 'linux') {
1347
1348
  const args = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0');
1349
+ if (!args[0]) return processAlive(pid) ? null : false;
1348
1350
  return args.includes(arg) ? true : args.some(a => /^--?auth(?:=|$)/.test(a)) ? false : undefined;
1349
1351
  }
1350
1352
  const command = platform === 'win32'
@@ -1370,11 +1372,6 @@ function belongsToStudio(pid, dataDir, platform) {
1370
1372
  return scope === null && recordedInstance(pid, dataDir, platform) ? true : scope;
1371
1373
  }
1372
1374
 
1373
- function processAlive(pid) {
1374
- if (!Number.isInteger(pid) || pid <= 0) return false;
1375
- try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
1376
- }
1377
-
1378
1375
  function recordedPid(dataDir) {
1379
1376
  try { return Number(fs.readFileSync(path.join(dataDir, 'backend.pid'), 'utf8').trim()); } catch { return NaN; }
1380
1377
  }
@@ -1401,7 +1398,7 @@ export function studioProcessPids(bin, platform = process.platform, run = execFi
1401
1398
  return fs.readdirSync('/proc').filter(n => /^\d+$/.test(n)).flatMap(n => {
1402
1399
  try {
1403
1400
  const command = fs.readFileSync(`/proc/${n}/cmdline`, 'utf8').split('\0')[0];
1404
- return path.isAbsolute(command) && path.resolve(command) === path.resolve(bin) ? [Number(n)] : [];
1401
+ return path.isAbsolute(command) && path.resolve(command) === path.resolve(bin) && !zombie(n) ? [Number(n)] : [];
1405
1402
  } catch { return []; }
1406
1403
  });
1407
1404
  }
@@ -1428,7 +1425,8 @@ export function studioProcessPids(bin, platform = process.platform, run = execFi
1428
1425
  const match = line.trim().match(/^(\d+)\s+(.+)$/);
1429
1426
  if (match && launchedFrom(match[2], bin)) pids.add(Number(match[1]));
1430
1427
  }
1431
- return [...pids];
1428
+ // An exited process nobody has reaped yet (a zombie) is gone.
1429
+ return [...pids].filter(pid => !zombie(pid));
1432
1430
  }
1433
1431
 
1434
1432
  export function studioListenerPids(port, platform = process.platform, run = execFileSync) {
@@ -1512,10 +1510,7 @@ async function withLock(dataDir, fn, timeoutMs = 600000) {
1512
1510
  const content = fs.readFileSync(lockPath, 'utf8');
1513
1511
  const lines = content.split('\n');
1514
1512
  ownerPid = parseInt(lines[0], 10);
1515
- if (Number.isInteger(ownerPid) && ownerPid > 0) {
1516
- process.kill(ownerPid, 0);
1517
- ownerAlive = true;
1518
- }
1513
+ ownerAlive = processExists(ownerPid);
1519
1514
  } catch {
1520
1515
  ownerAlive = false;
1521
1516
  }
@@ -2217,13 +2212,11 @@ export async function stopStudio(options = {}) {
2217
2212
 
2218
2213
  const deadline = Date.now() + 5000;
2219
2214
  while (Date.now() < deadline) {
2220
- try {
2221
- process.kill(pid, 0);
2222
- await sleep(150);
2223
- } catch {
2215
+ if (!processAlive(pid)) {
2224
2216
  alive = false;
2225
2217
  break;
2226
2218
  }
2219
+ await sleep(150);
2227
2220
  }
2228
2221
 
2229
2222
  if (alive) {
@@ -2417,15 +2410,20 @@ function unlockDirectoriesRecursive(target, platform) {
2417
2410
  } catch {}
2418
2411
  }
2419
2412
 
2420
- function forceRemovePath(target, platform) {
2413
+ async function forceRemovePath(target, platform) {
2421
2414
  if (!fs.existsSync(target)) return false;
2422
- try {
2423
- unlockDirectoriesRecursive(target, platform);
2424
- fs.rmSync(target, { recursive: true, force: true });
2425
- return !fs.existsSync(target);
2426
- } catch {
2427
- return false;
2415
+ const maxAttempts = platform === 'win32' ? 25 : 3;
2416
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2417
+ try {
2418
+ unlockDirectoriesRecursive(target, platform);
2419
+ fs.rmSync(target, { recursive: true, force: true });
2420
+ if (!fs.existsSync(target)) return true;
2421
+ } catch {}
2422
+ if (attempt < maxAttempts) {
2423
+ await sleep(100);
2424
+ }
2428
2425
  }
2426
+ return !fs.existsSync(target);
2429
2427
  }
2430
2428
 
2431
2429
  async function terminateVerifiedPids(pids, bin, platform, termWaitMs = 3000, owns = () => true) {
@@ -2505,7 +2503,7 @@ export async function cleanStudio(options = {}) {
2505
2503
 
2506
2504
  const removed = [];
2507
2505
  for (const name of ['package', 'install-manifest.json', 'backend.pid', LAUNCH_RECORD, ...(platform === 'win32' ? ['aistudio2api.exe'] : [])]) {
2508
- if (forceRemovePath(path.join(dataDir, name), platform)) {
2506
+ if (await forceRemovePath(path.join(dataDir, name), platform)) {
2509
2507
  removed.push(name);
2510
2508
  }
2511
2509
  }
@@ -2514,7 +2512,7 @@ export async function cleanStudio(options = {}) {
2514
2512
  try { rootEntries = fs.readdirSync(dataDir); } catch {}
2515
2513
  for (const name of rootEntries) {
2516
2514
  if (isStudioStagingEntry(name)) {
2517
- if (forceRemovePath(path.join(dataDir, name), platform)) {
2515
+ if (await forceRemovePath(path.join(dataDir, name), platform)) {
2518
2516
  removed.push(name);
2519
2517
  }
2520
2518
  }
@@ -2526,7 +2524,7 @@ export async function cleanStudio(options = {}) {
2526
2524
  try { runtimeEntries = fs.readdirSync(runtimeDir); } catch {}
2527
2525
  for (const name of runtimeEntries) {
2528
2526
  if (isCamoufoxRuntimeEntry(name)) {
2529
- if (forceRemovePath(path.join(runtimeDir, name), platform)) {
2527
+ if (await forceRemovePath(path.join(runtimeDir, name), platform)) {
2530
2528
  removed.push(path.join('runtime', name));
2531
2529
  }
2532
2530
  }
@@ -3,6 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
5
  import { setTimeout as sleep } from 'node:timers/promises';
6
+ import { processExists } from './proc.mjs';
6
7
  import {
7
8
  studioDataDir, studioAutoUpdates, studioProcessStarted, withStudioUpdate,
8
9
  localStudio, checkStudioHealth, studioAdmin, installStudio, computeFileHash, downloadProxy
@@ -25,7 +26,7 @@ function record() {
25
26
 
26
27
  function live(record) {
27
28
  if (!record || !Number.isInteger(record.pid) || record.pid <= 0) return true;
28
- try { process.kill(record.pid, 0); } catch (err) { return err.code !== 'ESRCH'; }
29
+ if (!processExists(record.pid)) return false;
29
30
  if (!record.started) return true;
30
31
  const start = record.pid === process.pid ? ownStart : studioProcessStarted(record.pid);
31
32
  return !start || record.started === start;
@@ -164,6 +165,25 @@ export function newerStudioRelease(latest, installed) {
164
165
 
165
166
  async function idleStatus(local, options) {
166
167
  const fetchFn = options.fetchFn || globalThis.fetch;
168
+ if (!await idleActivity(local, fetchFn)) return null;
169
+ // A cold GET /api/update also checks GitHub in the official backend. Give it
170
+ // a network-sized budget; an inconclusive timeout defers replacement until
171
+ // the next watcher tick, without treating it as a rejected release.
172
+ let update;
173
+ try {
174
+ update = await studioAdmin(local, 'GET', '/api/update', null, { fetchFn, timeoutMs: 30000 });
175
+ } catch (err) {
176
+ // Fetch may report body-read timeouts as AbortError after headers arrive.
177
+ if ([err.name, err.cause?.name].some(name => name === 'TimeoutError' || name === 'AbortError')) return null;
178
+ throw err;
179
+ }
180
+ if (typeof update?.updating !== 'boolean' || update.updating) return null;
181
+ // Read activity after the potentially slow release lookup, so a request or
182
+ // sign-in that started during that lookup still prevents replacement.
183
+ return idleActivity(local, fetchFn);
184
+ }
185
+
186
+ async function idleActivity(local, fetchFn) {
167
187
  const health = await checkStudioHealth(local, fetchFn);
168
188
  if (health.state !== 'up') return null;
169
189
  const s = health.status;
@@ -176,8 +196,6 @@ async function idleStatus(local, options) {
176
196
  !['RUNNING', 'STOPPED'].includes(s.state) || (s.accounts.busy ?? 0) > 0) return null;
177
197
  const tasks = await studioAdmin(local, 'GET', '/api/accounts/tasks', null, { fetchFn, timeoutMs: 3000 });
178
198
  if (!Array.isArray(tasks?.tasks) || tasks.tasks.some(t => !['done', 'failed', 'cancelled', 'canceled'].includes(t?.state))) return null;
179
- const update = await studioAdmin(local, 'GET', '/api/update', null, { fetchFn, timeoutMs: 5000 });
180
- if (typeof update?.updating !== 'boolean' || update.updating) return null;
181
199
  return s;
182
200
  }
183
201
 
package/lib/studio.mjs CHANGED
@@ -57,7 +57,7 @@ const PAGE_LINE = '下载和登录的进度显示在刚打开的浏览器页面
57
57
  const PAGE_LINGER_MS = 2 * 60 * 1000;
58
58
  // AdminAccount.state as the account list shows it
59
59
  const ACCOUNT_STATES = {
60
- ready: '可用',
60
+ ready: '账号就绪',
61
61
  busy: '使用中',
62
62
  cooldown: '冷却中',
63
63
  auth_required: '需要重新登录',
@@ -225,7 +225,22 @@ export function studioSettings(options = {}) {
225
225
  };
226
226
  }
227
227
 
228
- export async function listStudioModels(c, opts) {
228
+ // Use the backend's usage-page rates, including cached input and whole-request context tiers.
229
+ // Missing or malformed prices stay unknown; the model list remains usable on older backends.
230
+ function studioModelCost(value) {
231
+ const valid = v => typeof v === 'number' && Number.isFinite(v) && v >= 0;
232
+ const rate = p => p && ['input', 'output', 'cache_read'].every(k => valid(p[k]));
233
+ if (!rate(value)) return undefined;
234
+ const tiers = value.tiers ?? [];
235
+ if (!Array.isArray(tiers) || tiers.some((p, i) => !rate(p) || !Number.isSafeInteger(p.above) || p.above <= (i ? tiers[i - 1].above : 0))) return undefined;
236
+ return {
237
+ preferred: true, input: value.input, output: value.output,
238
+ cache: { read: value.cache_read, write: 0 },
239
+ ...(tiers.length ? { tiers: tiers.map(p => ({ above: p.above, input: p.input, output: p.output, cache_read: p.cache_read, cache_write: 0 })) } : {})
240
+ };
241
+ }
242
+
243
+ export async function listStudioModels(c, opts, modelCost = false) {
229
244
  const url = `${c.baseURL}/models`;
230
245
  let res;
231
246
  try {
@@ -362,14 +377,7 @@ export async function listStudioModels(c, opts) {
362
377
  image: draws
363
378
  }
364
379
  },
365
- cost: {
366
- input: 0,
367
- output: 0,
368
- cache: {
369
- read: 0,
370
- write: 0
371
- }
372
- },
380
+ cost: (modelCost ? studioModelCost(item.estimated_cost) : undefined) ?? { input: 0, output: 0, cache: { read: 0, write: 0 } },
373
381
  options: {},
374
382
  headers: {},
375
383
  variants,
@@ -481,6 +489,11 @@ function accountSignIn(local, account) {
481
489
  const SERVING_STATES = new Set(['ready', 'busy', 'cooldown']);
482
490
  const labelOf = a => String(a.label || a.id);
483
491
 
492
+ // Keep identity and state visible in compact cards too; no used value, since this is not quota.
493
+ function accountStateWindow(account) {
494
+ return { name: labelOf(account), display: ACCOUNT_STATES[account.state] || account.state || '暂时不可用' };
495
+ }
496
+
484
497
  // Magpie deduplicates cards by key + email. The sorted ID set keeps a batch stable across
485
498
  // retries/order changes and distinguishes groups with the same first label and count.
486
499
  export function accountGroupEmail(accounts) {
@@ -578,7 +591,7 @@ export function accountUsage(account, cooldowns, now = Date.now()) {
578
591
  display: reason && reason.length <= 40 ? `冷却中:${reason}` : '冷却中'
579
592
  });
580
593
  }
581
- return { user, windows: windows.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt)) };
594
+ return { user, windows: [accountStateWindow(account), ...windows.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt))] };
582
595
  }
583
596
 
584
597
  // poolUsage is the usage card of the local service's accounts: they go by their labels (Google
@@ -610,7 +623,36 @@ export function poolUsage(accounts, cooldowns, now = Date.now(), options = {}) {
610
623
  : '本地 AI Studio 的 Google 账号暂时都不可用';
611
624
  return { user, error, windows: [] };
612
625
  }
613
- return { user, windows: cooldownWindows(cooldowns, ordered, now, options) };
626
+ return { user, windows: [...ordered.map(accountStateWindow), ...cooldownWindows(cooldowns, ordered, now, options)] };
627
+ }
628
+
629
+ // The backend prices its own request ledger per model (including cached input and long-context
630
+ // tiers). This is API-price equivalent usage, not a Google bill or remaining subscription quota.
631
+ // Today follows the Magpie host's local midnight, as the admin page follows its viewer's day.
632
+ export async function dailyUsageWindows(local, accounts, now = new Date()) {
633
+ const labels = [...new Set(accounts.map(labelOf))];
634
+ // The ledger filters labels, with commas as separators. Never fall back to an unscoped read.
635
+ if (!labels.length || labels.some(label => !label.trim() || label.includes(','))) return [];
636
+ const from = new Date(now);
637
+ from.setHours(0, 0, 0, 0);
638
+ if (from >= now) return [];
639
+ const query = new URLSearchParams({
640
+ from: from.toISOString(), to: now.toISOString(), account: labels.join(','), bucket: 'auto', pairs: '0'
641
+ });
642
+ try {
643
+ const report = await studioAdmin(local, 'GET', `/api/usage?${query}`, null, { timeoutMs: 3000 });
644
+ const tokens = report?.totals?.total_tokens, cost = report?.cost;
645
+ if (!Number.isSafeInteger(tokens) || tokens < 0 || !Number.isFinite(cost) || cost < 0 || !Array.isArray(report?.unpriced_models)) return [];
646
+ const partial = report.unpriced_models.length > 0;
647
+ const dollars = cost > 0 && cost < 0.01 ? '<$0.01' : `$${cost.toFixed(2)}`;
648
+ const estimate = partial && cost === 0 ? '费用未计价'
649
+ : `API 标价估算 ${dollars}${partial ? '(部分模型未计价)' : ''}`;
650
+ const count = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 2 }).format(tokens);
651
+ return [{ name: '今日用量(本地)', display: `${count} tokens · ${estimate}` }];
652
+ } catch {
653
+ // Older backends and failed reads leave the account/cooldown card intact, never a fake zero.
654
+ return [];
655
+ }
614
656
  }
615
657
 
616
658
  // proxyLine says which proxy the local service goes out through, where that comes from, a saved
@@ -809,6 +851,8 @@ async function ensureStudio(options) {
809
851
 
810
852
  export const AIStudioPlugin = async (_input, options = {}) => {
811
853
  const opts = studioSettings(options);
854
+ // Older hosts consume only base rates, silently underpricing long-context requests.
855
+ const modelCost = _input?.magpie?.capabilities?.modelCost === 1;
812
856
  registerMagpieCleanup(_input);
813
857
 
814
858
  if (localStudio(opts)) {
@@ -1100,8 +1144,12 @@ export const AIStudioPlugin = async (_input, options = {}) => {
1100
1144
  }
1101
1145
  return { error: `无法读取本地 AI Studio 状态: ${err.message}`, windows: [], signIn: 'kept' };
1102
1146
  }
1103
- const enabled = (Array.isArray(accounts?.accounts) ? accounts.accounts : []).filter(a => a && a.enabled !== false);
1104
- const cooling = Array.isArray(cooldowns?.cooldowns) ? cooldowns.cooldowns : [];
1147
+ if (!Array.isArray(accounts?.accounts)) {
1148
+ return { error: '无法读取本地 AI Studio 账号列表,请刷新重试', windows: [], signIn: 'kept' };
1149
+ }
1150
+ const enabled = accounts.accounts.filter(a => a && a.enabled !== false);
1151
+ const hasCooldownsData = Array.isArray(cooldowns?.cooldowns);
1152
+ const cooling = hasCooldownsData ? cooldowns.cooldowns : [];
1105
1153
  const id = auth.metadata.account;
1106
1154
  let env = {};
1107
1155
  try {
@@ -1113,20 +1161,26 @@ export const AIStudioPlugin = async (_input, options = {}) => {
1113
1161
  modelAccounts: env.MODEL_ACCOUNTS || opts.modelAccounts || ''
1114
1162
  };
1115
1163
  const service = serviceWindows(local, proxy, routing);
1116
- let card;
1164
+ let card, selected;
1117
1165
  if (typeof id !== 'string' || !id) {
1118
1166
  const ids = auth.metadata.accounts;
1119
1167
  const group = Array.isArray(ids) && ids.length ? enabled.filter(a => ids.includes(a.id)) : enabled;
1168
+ selected = group;
1120
1169
  card = group.length || !Array.isArray(ids)
1121
1170
  ? poolUsage(group, cooling, Date.now(), routing)
1122
1171
  : { error: '本次导入的 AI Studio 账号均已停用或移除,请重新登录', windows: [] };
1123
1172
  } else {
1124
1173
  const account = enabled.find(a => a.id === id);
1174
+ selected = account ? [account] : [];
1125
1175
  card = account
1126
1176
  ? accountUsage(account, cooling)
1127
1177
  : { error: `本地 AI Studio 里已经没有这个账号(${auth.metadata.email || id}),可能被停用或删除了`, windows: [] };
1128
1178
  }
1129
- return { ...card, windows: [...card.windows, ...service], signIn: 'kept' };
1179
+ if (!card.error && !hasCooldownsData) {
1180
+ card.windows.push({ name: '模型冷却', display: '未能读取冷却状态,请刷新重试' });
1181
+ }
1182
+ const daily = await dailyUsageWindows(local, selected);
1183
+ return { ...card, windows: [...card.windows, ...daily, ...service], signIn: 'kept' };
1130
1184
  }
1131
1185
  },
1132
1186
  provider: {
@@ -1139,11 +1193,11 @@ export const AIStudioPlugin = async (_input, options = {}) => {
1139
1193
  if (!sameBackend(c, local)) throw managedMismatch();
1140
1194
  }
1141
1195
  try {
1142
- return await listStudioModels(c, opts);
1196
+ return await listStudioModels(c, opts, modelCost);
1143
1197
  } catch (err) {
1144
1198
  if (!err.unreachable || !auth.metadata?.managed) throw err;
1145
1199
  await ensureStudio({ ...opts, proxy: opts.proxy });
1146
- return listStudioModels(c, opts);
1200
+ return listStudioModels(c, opts, modelCost);
1147
1201
  }
1148
1202
  }
1149
1203
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dorokuma/magpie-gemini-web",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Google AI Studio and Gemini Web provider for Magpie (Gemini 4 Neon / Carbon / Hydrogen in Chat & Task modes, Nano Banana image generation, Deep Research), backed by AIStudio2API and gemini-web2api-go",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",