Merge pull request #43 from yuhuan-dev/release/v1.5.5

feat(panel): Windows multi-account vault, incremental SQLite ledger, image generation pricing, and unified chart motion (v1.5.5)
This commit is contained in:
fish
2026-11-25 14:20:45 +09:00
committed by GitHub
125 changed files with 67799 additions and 6460 deletions
+5 -2
View File
@@ -1,11 +1,14 @@
.data/
node_modules/
plan/
dist/
/dist/
usage-monitor.zip
*.log
*.dpapi
.account-test-*
.DS_Store
Thumbs.db
docs/
docs/
.agents/
host-i18n/README.md
host-i18n/.tmp-*.json
+39
View File
@@ -0,0 +1,39 @@
# Changelog
All notable changes to **Antigravity Usage & Speed Monitor** are documented in this file.
## [1.5.4] - Unreleased
### Added
- **Local CloudCode Proxy & Dual Context-Window Controls**: Added `cloudcode-proxy.mjs` loopback reverse proxy (`SetCloudCodeURL`) to synchronize custom per-model context window limits to non-`self` subagents and Swarm workers alongside independent `contextWindowMainEnabled` / `contextWindowSwarmEnabled` toggles.
- **Experimental Quota Lease Reservation Estimator**: Added `quota-reservation.mjs` 5h/weekly dual-bucket in-flight quota lease tracking, FIFO settlement, delayed refund confirmation, outlier-filtered rolling median rate calibration, violet bar indicator, and `GET /api/quota-reservation/log`.
- **Native Multi-Sheet `.xlsx` & Markdown Exports**: Added zero-dependency OOXML workbook builder (`xlsxBuilder.js`) and localized multi-sheet Excel / Markdown report exports with local `~/Downloads` save and one-click file manager reveal toast.
- **Step Diagnostic Drawer & Live Filtering**: Added click-to-inspect `StepDiagnosticDrawer` (timing waterfall, token/cost breakdown, 9-kind V4 `anomaly.events` list, Markdown copy), live multi-term step search, and danger-tier diagnostic filter chips.
- **Workspace Cost Attribution & Session Migration**: Added **Projects (Workspaces)** cost ranking tab, session project tags, portable JSON settings backup/import, and opt-in cross-client session migration/cloning (`CLI ↔ Desktop/IDE` and `Legacy IDE`) with isolated UUID rewriting.
- **CLI `statusLine` Gauge Styles & JSON Output**: Added `--style pill|bar|compact`, `--preset compact|balanced|full`, and single-line `--json` snapshot output for external prompt/bar integrations.
### Changed & Optimized
- **Hot-Path Performance (P1)**: Made `trajectoryCache` lazy via `createTrajectoryCacheStore` and added tail-row (`LIMIT 16`) SQLite reads for `cli-statusline.mjs` (`~419ms → <60ms`); skipped redundant per-poll WAL `statSync` on unchanged `IDLE` sessions; switched `cloudcode-proxy` Windows system proxy lookup to async `execFile` with TTL caching; deferred overlay `App()` instantiation until first popover open; coalesced host `MutationObserver` via `requestAnimationFrame`; shared `adoptedStyleSheets` across overlay portals and cached chart `DOMRect` on hover.
- **Shared Primitives & Modular Architecture (P2–P3)**: Extracted `fs-atomic.mjs`, `trajectory-cache-store.mjs`, `workspace-uri.mjs`, `prompt-clean.mjs`, `windows-shortcut-provision.ps1`, `ToggleSwitch.js` (cutting `SettingsView` `ResizeObserver` count by ~59%), `SearchInput.js`, `StepDiagnosticDrawer.js`, `ConsumptionBreakdownRows.js`, `stepChartMath.js`, and `overlayHostAnchors.js`; upgraded `build-bundle.mjs` regex-after-condition-paren lexer and inner-IIFE `import/export { a as b }` alias support.
### Fixed
- **Telemetry & Inspector Accuracy (P0)**: Unified step selection keys so clicking any step reliably opens the diagnostic drawer; preserved V4 `nativeStreamSec`, `thinkingDurationSec`, and `hasToolCalls` across step projections; fixed `reportExporter.js` and `stepInspector.js` duration/waterfall fields and `anomaly.events` rendering; computed merged model average speed from exact `speedSummary.{tokens, seconds}` harmonic totals; honored `ANTIGRAVITY_GEMINI_DIR` override and cleaned up `multiRunningWidget` on overlay disposal.
## [1.5.3] - 2026-04
### Added & Changed
- Graduated borderless **Modern UI** to default, defaulted language to host/system (`auto`), and unified token breakdown ordering and flat tooltip cards.
- Added SSH Remote multi-window isolation (`endpoint-registry.mjs`) with per-endpoint trajectory/quota caches and RPC routing.
- Added support for Opus 5.5 Orchestrator (`Neon` variants) and prevented unknown future variants from misrouting to Carbon pools.
- Fixed 5-hour quota cycle boundary accounting and macOS host relaunch ancestor process matching.
## [1.5.2] - 2026-03
### Added & Changed
- Added runtime-only whitelist Release ZIP packager (`pack-release-zip.mjs`), Native Swarm mode worker telemetry, 9-category step anomaly diagnostics, virtualized large step tables (`>80` rows), and pruned `scope=consumption` / `scope=conversation` fast paths.
- Hardened Desktop `2.33.0+` launcher auto-provisioning and out-of-job 1-click host relaunch across Windows (UIPI-safe user relaunch + on-demand UAC), macOS, and Linux (`.desktop` / AppImage).
## [1.5.1] - 2026-03
### Added & Changed
- Added hybrid SQLite + WAL direct reader, `384k` context window preset, time-phased promotional model pricing, scalable `--fs-*` typography tokens, and isolated `sidecar-worker.mjs` hot-reloadable runtime.
+1
View File
@@ -34,6 +34,7 @@ English · [简体中文](README.zh-CN.md)
- **Live Metrics & Customizable Layout**: Tracks output speed (`tok/s`), time-to-first-token (`TTFT`), session average speed, step/session USD cost, cache hit rate, tightest remaining quota, and session tokens. You can choose and reorder the overview metric cards (4 shown by default out of 9 options) and section blocks.
- **10-Category Context Breakdown**: Shows the token breakdown of the latest request across assistant replies, tool results, user messages, subagent notifications, checkpoints, system prompts, system tools, MCP tools, skills, and user rules, with a switcher between the main agent and spawned subagents.
- **Quota Pool Tracking, Lease Reservation & Burn-Rate Reference**: Reads 5-hour and weekly quotas, reset timers, and cycle consumption across `Gemini`, `Gemini 4 Argon`, `Gemini 4 Carbon`, and `Claude & GPT` pools (plus Ultra `5x / 20x` tier badges), renders an in-flight lease reservation segment with an account-isolated per-model burn-rate & equivalent full-pool cost popover (`?`), and preserves cached quota data with a stale notice when upstream is temporarily unavailable.
- **Account Sign-in and Switching on Windows**: Choose Sign in with Google under Preferences → Account. Browser authorization automatically adds the account and loads its quota. Existing refresh tokens and OAuth JSON can also be imported. Switch and restart closes and reopens the App and newer IDE sharing its sign-in. Save your work before switching.
- **Main Agent, Subagents, Swarm & SSH Isolation**: Merges main agent, subagent, and Native Swarm worker steps in chronological order (or filters by individual agent), renders optional turn rails, expands running tasks inline, and isolates per-window caches and quotas across multiple SSH Remote windows (`endpointId`).
- **Call Details, Timing Tooltips & Anomaly Chips**: Includes **By Step** and **By Model** tabs (with multi-model LOESS throughput/TTFT fit charts), clickable column sorting, hover TTFT/duration stage breakdowns, accent-highlighted compaction rows with diagnostic tooltips, and an optional live search & 9-category anomaly/compaction/low-cache/slow-TTFT filter toolbar. Supports 2–14 configurable columns and custom token DSL strings such as `context:in:cache`.
- **Historical Usage, Project Attribution & Heatmap**: Summarizes tokens, uncached input vs. cache-read savings, thinking/output split, smooth hourly/daily trend curves (switching automatically to a GitHub-style daily calendar heatmap over `>90` days), **Model / Project (Workspace) / Session** rankings, client attribution (`Desktop App` / `IDE` / `CLI`), and monthly bar charts with pointer-following breakdown popovers across `Today`, `1d`, `7d`, `14d`, `30d`, `All`, or custom date/time ranges.
+1
View File
@@ -34,6 +34,7 @@ Google Antigravity 2.0、Antigravity IDE 与 Antigravity CLI 的本地用量、
- **实时指标与版面编排**:统计单步输出速度(`tok/s`)、首字延迟(`TTFT`)、会话平均速度、单步/累计费用、缓存命中率、最紧缺配额与已用 Token;可在设置中从 9 项指标中自由勾选并拖拽排序(默认展示 4 项),并调整实时监控各模块顺序。
- **10 类上下文窗口构成**:展示最近一次请求的上下文占比,按占用列出模型回复、工具结果、用户消息、子代理通知、压缩摘要、系统提示词、系统工具、MCP 工具、Skill 与用户规则,支持在主代理与任意子代理之间切换查看。
- **配额池监控、预占估算及速率参考**:追踪 `Gemini`、`Gemini 4 Argon`、`Gemini 4 Carbon` 及 `Claude & GPT` 配额池的 5 小时及每周用量、重置倒计时、周期累计消耗及 Ultra `5x / 20x` 倍率标识;内置租约预占斜纹指示段及按账号隔离的模型消耗速率/等效满池费用悬浮卡(`?`),上游暂未返回新数据时保留缓存状态及提示。
- **账号登录及切换(Windows)**:在「偏好设置 → 账号」点击「使用 Google 登录」,通过浏览器授权后自动保存账号并查询额度;也支持导入已有刷新令牌或 OAuth JSON。「切换并重启」关闭并重开 App 和共享登录的新版 IDE,以载入选定凭证,切换前请保存工作。
- **主/子代理、Swarm 蜂群及 SSH 多远端隔离**:按时间归并展示主代理、子代理及原生 Swarm Worker 调用步骤(也可按单一代理过滤),支持轮次分组导轨及运行中任务原地展开,并对多个 SSH Remote 远端窗口按端点独立隔离轨迹缓存及配额状态。
- **调用明细、耗时拆解及异常筛选**:包含「按步查看」及「按模型汇总」(含多模型 LOESS 吞吐/TTFT 拟合曲线);支持表头点击排序、首字延迟/总耗时分阶段悬停拆解、压缩行强调色高亮及悬停诊断、可选实时搜索及 9 类异常/慢首字/低缓存快捷诊断筛选条;支持定制 2–14 列及 `context:in:cache` 等自定义 Token 语法。
- **历史用量、项目工作区归因及日历热力图**:按今天、1 天、7 天、14 天、30 天、全部或自定义时间窗统计总 Token、缓存节省金额、输出/思考拆分、平滑小时/日趋势折线(跨度 `>90` 天自动切换为每日日历热力图)、**模型 / 项目工作区 / 会话**三合一排行、客户端来源(App / IDE / CLI)及月度堆叠柱状图,均配备跟手悬浮明细卡。
+26
View File
@@ -0,0 +1,26 @@
{
"schemaVersion": 1,
"packs": [
{
"locale": "zh-CN",
"name": "Chinese (Simplified)",
"nativeName": "简体中文",
"version": "2.1.1",
"file": "packs/zh-CN.json",
"sha256": "75ce150cc8952b65fe04493f2d9e16ae1370140474072e2458277f065e83d384",
"bytes": 568779,
"depths": [
"light",
"deep"
],
"stats": {
"baseExact": 4174,
"lightExact": 1113,
"deepExact": 1113,
"basePatterns": 767,
"lightPatterns": 147,
"deepPatterns": 147
}
}
]
}
File diff suppressed because one or more lines are too long
+483
View File
@@ -0,0 +1,483 @@
#!/usr/bin/env node
/**
* @fileoverview Zero-dependency Antigravity Host I18n coverage auditor & live CDP drift scanner.
*
* Compares the latest extracted host UI strings (from Desktop `language_server.exe` JS + embedded
* feature-flag JSONC and Antigravity IDE `jetskiAgent/main.js`) against a compiled locale pack
* (`host-i18n/dist/packs/<locale>.json`), optionally also scanning live open Antigravity windows
* over read-only CDP to catch server-pushed runtime strings (e.g., model tags like `Leaving Soon`).
*
* Usage:
* node host-i18n/scripts/audit-host-i18n.mjs --locale zh-CN
* node host-i18n/scripts/audit-host-i18n.mjs --locale zh-CN --extract --live-cdp --emit-missing tmp/missing.json
* node host-i18n/scripts/audit-host-i18n.mjs --locale zh-CN --no-extract --strict
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
DEFAULT_CATALOG_OUT,
discoverLocalAntigravitySources,
runHostStringExtraction,
} from './extract-host-strings.mjs';
import { compileHostI18nRuntimePayload } from '../../sidecars/panel/backend/host-i18n/pack-manager.mjs';
import { createHostI18nCollectExpression } from '../../sidecars/panel/backend/host-i18n/runtime-translator.mjs';
import { resolveDevToolsPortCandidates } from '../../sidecars/panel/backend/window-bridge.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
export const HOST_I18N_ROOT = resolve(__dirname, '..');
export const DEFAULT_IGNORE_PATH = join(HOST_I18N_ROOT, 'sources', 'ignore.json');
export function loadIgnoreLists(ignorePath = DEFAULT_IGNORE_PATH) {
if (!existsSync(ignorePath)) {
return { exact: new Set(), templates: new Set() };
}
const raw = JSON.parse(readFileSync(ignorePath, 'utf8'));
return {
exact: new Set(Array.isArray(raw?.exact) ? raw.exact : []),
templates: new Set(Array.isArray(raw?.templates) ? raw.templates : []),
};
}
function buildRuntimeMatcher(payload) {
const exactMap = new Map(Object.entries(payload.exact || {}));
const exactLowerMap = new Map();
for (const [k, v] of exactMap.entries()) {
if (k.length <= 80) {
const lk = k.toLowerCase();
if (!exactLowerMap.has(lk)) exactLowerMap.set(lk, v);
}
}
const patterns = [];
for (const rule of payload.patterns || []) {
try {
patterns.push({
source: rule.source,
re: new RegExp(rule.source, rule.flags || ''),
replace: rule.replace,
hintLower: String(rule.hint || '').toLowerCase(),
});
} catch {
// invalid regex caught separately
}
}
return {
match(text) {
const t = String(text || '').trim();
if (!t) return null;
if (exactMap.has(t)) return { kind: 'exact', value: exactMap.get(t) };
if (t.length <= 80) {
const lv = exactLowerMap.get(t.toLowerCase());
if (lv !== undefined) return { kind: 'exact-ci', value: lv };
}
if (t.length <= 360 && !t.includes('\n')) {
const lower = t.toLowerCase();
for (const p of patterns) {
if (p.hintLower && !lower.includes(p.hintLower)) continue;
if (p.re.test(t)) {
const next = t.replace(p.re, p.replace);
if (next && next !== t) return { kind: 'pattern', value: next, source: p.source };
}
}
}
return null;
},
};
}
function countCaptureGroups(source) {
let count = 0;
let inCharClass = false;
for (let i = 0; i < source.length; i += 1) {
const ch = source[i];
if (ch === '\\') {
i += 1;
continue;
}
if (ch === '[') {
inCharClass = true;
continue;
}
if (ch === ']') {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(' && source[i + 1] !== '?') {
count += 1;
}
}
return count;
}
/**
* Pure coverage & integrity audit comparing a catalog against a compiled pack JSON.
*/
export function auditCatalogAgainstPack(catalog, packObj, ignoreLists = { exact: new Set(), templates: new Set() }) {
const lightPayload = compileHostI18nRuntimePayload(packObj, 'light');
const deepPayload = compileHostI18nRuntimePayload(packObj, 'deep');
const lightMatcher = buildRuntimeMatcher(lightPayload);
const deepMatcher = buildRuntimeMatcher(deepPayload);
const packPatternSources = new Set([
...(packObj?.base?.patterns || []).map((r) => r.source),
...(packObj?.modes?.light?.patterns || []).map((r) => r.source),
...(packObj?.modes?.deep?.patterns || []).map((r) => r.source),
]);
const missingExact = [];
const coveredExactByPattern = [];
let ignoredExactCount = 0;
for (const str of catalog.exact || []) {
if (ignoreLists.exact.has(str)) {
ignoredExactCount += 1;
continue;
}
const deepHit = deepMatcher.match(str);
const lightHit = lightMatcher.match(str);
if (!deepHit && !lightHit) {
missingExact.push(str);
} else if (deepHit?.kind === 'pattern' && !deepPayload.exact[str]) {
coveredExactByPattern.push({ text: str, translated: deepHit.value, by: deepHit.source });
}
}
const missingTemplates = [];
let ignoredTemplateCount = 0;
for (const tpl of catalog.templates || []) {
if (ignoreLists.templates.has(tpl.source)) {
ignoredTemplateCount += 1;
continue;
}
if (!packPatternSources.has(tpl.source)) {
// Also check if a slightly tightened boundary variant of this template already exists
// (e.g. `^Continue(.+?)$` tightened to `^Continue(\s+\(.+?\))$`).
const tightenedVariant = tpl.source.replace(/\(\.\+\?\)\$$/, '(\\s+\\(.+?\\))$');
if (packPatternSources.has(tightenedVariant)) continue;
missingTemplates.push(tpl);
}
}
// Audit pattern backreference integrity & redundant light===deep rules
const brokenPatterns = [];
const redundantModeExact = [];
for (const tierName of ['base', 'light', 'deep']) {
const list =
tierName === 'base'
? packObj?.base?.patterns || []
: packObj?.modes?.[tierName]?.patterns || [];
for (const rule of list) {
const capCount = countCaptureGroups(rule.source);
const refs = Array.from(String(rule.replace || '').matchAll(/\$(\d+)/g)).map((m) => Number(m[1]));
const badRef = refs.find((n) => n < 1 || n > capCount);
if (badRef !== undefined) {
brokenPatterns.push({ tier: tierName, source: rule.source, replace: rule.replace, badRef, capCount });
}
}
}
const lightExact = packObj?.modes?.light?.exact || {};
const deepExact = packObj?.modes?.deep?.exact || {};
for (const [k, v] of Object.entries(lightExact)) {
if (Object.prototype.hasOwnProperty.call(deepExact, k) && deepExact[k] === v) {
redundantModeExact.push(k);
}
}
return {
locale: packObj.locale,
version: packObj.version,
catalogCounts: {
exact: (catalog.exact || []).length,
templates: (catalog.templates || []).length,
},
packCounts: {
baseExact: Object.keys(packObj?.base?.exact || {}).length,
lightExact: Object.keys(lightExact).length,
deepExact: Object.keys(deepExact).length,
basePatterns: (packObj?.base?.patterns || []).length,
lightPatterns: (packObj?.modes?.light?.patterns || []).length,
deepPatterns: (packObj?.modes?.deep?.patterns || []).length,
},
ignoredExactCount,
ignoredTemplateCount,
missingExact,
missingTemplates,
coveredExactByPatternCount: coveredExactByPattern.length,
brokenPatterns,
redundantModeExact,
};
}
function discoverDevToolsPorts(explicitPorts = []) {
const candidates = resolveDevToolsPortCandidates({
platform: process.platform,
env: process.env,
homeDir: homedir(),
});
const ports = new Set(explicitPorts.filter((p) => Number.isInteger(p) && p > 0 && p < 65536));
const envPort = Number(process.env.USAGE_MONITOR_CDP_PORT || 0);
if (Number.isInteger(envPort) && envPort > 0 && envPort < 65536) ports.add(envPort);
for (const file of candidates) {
if (!existsSync(file)) continue;
try {
const firstLine = readFileSync(file, 'utf8').split(/\r?\n/)[0]?.trim();
const port = Number(firstLine);
if (Number.isInteger(port) && port > 0 && port < 65536) ports.add(port);
} catch {
// ignore unreadable port file
}
}
return Array.from(ports);
}
async function evalCdpOnce(wsUrl, expression, timeoutMs = 4000) {
const WS = globalThis.WebSocket;
if (typeof WS !== 'function') {
throw new Error('Global WebSocket unavailable in this Node runtime');
}
return new Promise((resolvePromise, rejectPromise) => {
const ws = new WS(wsUrl);
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try { ws.close(); } catch {}
rejectPromise(new Error(`CDP evaluate timeout (${timeoutMs}ms)`));
}, timeoutMs);
const finish = (err, val) => {
if (settled) return;
settled = true;
clearTimeout(timer);
try { ws.close(); } catch {}
if (err) rejectPromise(err);
else resolvePromise(val);
};
ws.addEventListener('open', () => {
ws.send(
JSON.stringify({
id: 1,
method: 'Runtime.evaluate',
params: { expression, returnByValue: true, awaitPromise: false },
})
);
});
ws.addEventListener('message', (ev) => {
try {
const msg = JSON.parse(String(ev.data || ''));
if (msg.id === 1) {
finish(null, msg?.result?.result?.value ?? null);
}
} catch (err) {
finish(err);
}
});
ws.addEventListener('error', () => finish(new Error('CDP WebSocket error')));
});
}
/**
* Connects read-only to running Antigravity CDP targets and collects any visible untranslated UI strings.
*/
export async function scanLiveCdpUntranslated({ ignoreLists = { exact: new Set() }, explicitPorts = [] } = {}) {
const ports = discoverDevToolsPorts(explicitPorts);
const merged = new Map();
let scannedTargets = 0;
for (const port of ports) {
let targets = [];
try {
const res = await fetch(`http://127.0.0.1:${port}/json/list`, {
signal: AbortSignal.timeout(2000),
});
if (!res.ok) continue;
targets = await res.json();
} catch {
continue;
}
const collectExpr = createHostI18nCollectExpression();
for (const t of Array.isArray(targets) ? targets : []) {
const url = String(t?.url || '');
const wsUrl = String(t?.webSocketDebuggerUrl || '');
if (!wsUrl) continue;
if (url.startsWith('vscode-file://') || url.includes('workbench.html') || url.startsWith('devtools://')) {
continue;
}
if (t.type !== 'page' && !(t.type === 'iframe' && url.includes('extensionView=true'))) {
continue;
}
try {
const res = await evalCdpOnce(wsUrl, collectExpr, 4000);
scannedTargets += 1;
for (const item of res?.items || []) {
const text = String(item?.text || '').trim();
if (!text || ignoreLists.exact.has(text)) continue;
const prev = merged.get(text);
merged.set(text, {
text,
kind: prev?.kind || item.kind || 'text',
count: (prev?.count || 0) + (Number(item.count) || 1),
});
}
} catch {
// Target closed or unavailable
}
}
}
return {
ports,
scannedTargets,
items: Array.from(merged.values()).sort((a, b) => b.count - a.count || (a.text < b.text ? -1 : 1)),
};
}
function parseCliArgs(argv) {
const opts = {
locale: 'zh-CN',
extract: false,
noExtract: false,
liveCdp: false,
cdpPorts: [],
strict: false,
emitMissing: '',
catalogPath: DEFAULT_CATALOG_OUT,
ignorePath: DEFAULT_IGNORE_PATH,
lsPaths: [],
jsPaths: [],
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--locale' && argv[i + 1]) opts.locale = argv[++i];
else if (arg === '--extract') opts.extract = true;
else if (arg === '--no-extract') opts.noExtract = true;
else if (arg === '--live-cdp') opts.liveCdp = true;
else if (arg === '--cdp-port' && argv[i + 1]) opts.cdpPorts.push(Number(argv[++i]));
else if (arg === '--strict') opts.strict = true;
else if (arg === '--emit-missing' && argv[i + 1]) opts.emitMissing = resolve(argv[++i]);
else if (arg === '--catalog' && argv[i + 1]) opts.catalogPath = resolve(argv[++i]);
else if (arg === '--ignore' && argv[i + 1]) opts.ignorePath = resolve(argv[++i]);
else if (arg === '--ls' && argv[i + 1]) opts.lsPaths.push(resolve(argv[++i]));
else if (arg === '--js' && argv[i + 1]) opts.jsPaths.push(resolve(argv[++i]));
}
return opts;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const cli = parseCliArgs(process.argv.slice(2));
let catalog;
const shouldExtract = cli.extract || (!cli.noExtract && !existsSync(cli.catalogPath));
if (shouldExtract) {
const lsPaths = [...cli.lsPaths];
const jsPaths = [...cli.jsPaths];
if (lsPaths.length === 0 && jsPaths.length === 0) {
const discovered = discoverLocalAntigravitySources();
lsPaths.push(...discovered.lsBinaries);
jsPaths.push(...discovered.jsFiles);
}
if (lsPaths.length === 0 && jsPaths.length === 0) {
console.error('[audit-host-i18n] No local Antigravity installation found. Pass --ls/--js or --no-extract.');
process.exit(1);
}
catalog = runHostStringExtraction({ lsPaths, jsPaths, outPath: cli.catalogPath });
} else {
catalog = JSON.parse(readFileSync(cli.catalogPath, 'utf8'));
}
const packPath = join(HOST_I18N_ROOT, 'dist', 'packs', `${cli.locale}.json`);
if (!existsSync(packPath)) {
console.error(`[audit-host-i18n] Compiled pack not found: ${packPath}. Run build-packs.mjs first.`);
process.exit(1);
}
const packObj = JSON.parse(readFileSync(packPath, 'utf8'));
const ignoreLists = loadIgnoreLists(cli.ignorePath);
const report = auditCatalogAgainstPack(catalog, packObj, ignoreLists);
let liveCdp = null;
if (cli.liveCdp) {
liveCdp = await scanLiveCdpUntranslated({ ignoreLists, explicitPorts: cli.cdpPorts });
}
console.log(
`[audit-host-i18n] Locale ${report.locale}@${report.version} vs catalog (${report.catalogCounts.exact} exact, ${report.catalogCounts.templates} templates)`
);
console.log(
` Pack size: base=${report.packCounts.baseExact}, light=${report.packCounts.lightExact}, deep=${report.packCounts.deepExact}, patterns=${report.packCounts.basePatterns}+${report.packCounts.lightPatterns}/${report.packCounts.deepPatterns}`
);
console.log(
` Ignored allowlist: ${report.ignoredExactCount} exact, ${report.ignoredTemplateCount} templates`
);
console.log(
` Missing static: ${report.missingExact.length} exact, ${report.missingTemplates.length} templates (covered via pattern: ${report.coveredExactByPatternCount})`
);
console.log(
` Integrity: ${report.brokenPatterns.length} broken pattern(s), ${report.redundantModeExact.length} redundant identical light/deep key(s)`
);
if (report.missingExact.length > 0) {
console.log(' Sample missing exact (first 25):');
for (const s of report.missingExact.slice(0, 25)) {
console.log(` - ${JSON.stringify(s)}`);
}
}
if (report.missingTemplates.length > 0) {
console.log(' Sample missing templates (first 15):');
for (const t of report.missingTemplates.slice(0, 15)) {
console.log(` - ${JSON.stringify(t.key)} (${t.source})`);
}
}
if (report.brokenPatterns.length > 0) {
console.log(' Broken pattern backreferences:');
for (const b of report.brokenPatterns) {
console.log(` - [${b.tier}] ${b.source} -> ${b.replace} ($${b.badRef} > ${b.capCount})`);
}
}
if (liveCdp) {
console.log(
` Live CDP scan: ports=[${liveCdp.ports.join(',')}], targets=${liveCdp.scannedTargets}, untranslated=${liveCdp.items.length}`
);
for (const item of liveCdp.items.slice(0, 25)) {
console.log(` - [${item.kind} x${item.count}] ${JSON.stringify(item.text)}`);
}
}
if (cli.emitMissing) {
mkdirSync(dirname(cli.emitMissing), { recursive: true });
writeFileSync(
cli.emitMissing,
JSON.stringify(
{
generatedAt: new Date().toISOString(),
locale: report.locale,
version: report.version,
missingExact: report.missingExact,
missingTemplates: report.missingTemplates,
liveCdpUntranslated: liveCdp ? liveCdp.items : [],
brokenPatterns: report.brokenPatterns,
redundantModeExact: report.redundantModeExact,
},
null,
2
) + '\n',
'utf8'
);
console.log(`[audit-host-i18n] Emitted missing report -> ${cli.emitMissing}`);
}
const hasGap =
report.missingExact.length > 0 ||
report.missingTemplates.length > 0 ||
report.brokenPatterns.length > 0 ||
(liveCdp && liveCdp.items.length > 0);
if (hasGap && cli.strict) {
process.exit(2);
}
}
+396
View File
@@ -0,0 +1,396 @@
#!/usr/bin/env node
/**
* @fileoverview Zero-dependency builder and validator for Antigravity Host I18n packs.
*
* Reads modular source dictionaries under `host-i18n/sources/<locale>/`, validates
* key conflicts, regex anchoring/safety, and schema integrity, and emits deterministic
* compressed packs under `host-i18n/dist/packs/<locale>.json` alongside
* `host-i18n/dist/manifest.json` with SHA-256 digests.
*
* Usage:
* node host-i18n/scripts/build-packs.mjs
* node host-i18n/scripts/build-packs.mjs --check
*/
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
export const DEFAULT_HOST_I18N_ROOT = resolve(__dirname, '..');
export const PACK_SCHEMA_VERSION = 1;
export const SUPPORTED_DEPTHS = Object.freeze(['light', 'deep']);
const LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/;
const ALLOWED_REGEX_FLAGS_RE = /^[i]?$/;
const UNSAFE_NESTED_QUANTIFIER_RE = /\([^)]*[+*][^)]*\)[+*{]/;
function isPlainObject(val) {
return Boolean(val && typeof val === 'object' && !Array.isArray(val));
}
function sha256Hex(text) {
return createHash('sha256').update(String(text), 'utf8').digest('hex');
}
function sortRecordKeys(record) {
const out = {};
for (const key of Object.keys(record).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
out[key] = record[key];
}
return out;
}
/**
* Validates a single anchored regex pattern rule for safety and determinism.
*
* @param {object} rule
* @param {string} contextLabel
* @returns {{ source: string, flags: string, replace: string, hint?: string }}
*/
export function validatePatternRule(rule, contextLabel = 'pattern') {
if (!isPlainObject(rule)) {
throw new Error(`${contextLabel}: pattern entry must be an object`);
}
const source = typeof rule.source === 'string' ? rule.source : '';
const flags = typeof rule.flags === 'string' ? rule.flags : '';
const replace = typeof rule.replace === 'string' ? rule.replace : '';
const hint = typeof rule.hint === 'string' ? rule.hint.trim() : '';
if (!source || source.length > 360) {
throw new Error(`${contextLabel}: pattern source must be 1..360 chars`);
}
if (!source.startsWith('^') || !source.endsWith('$')) {
throw new Error(`${contextLabel}: pattern "${source}" must be strictly anchored with ^ and $`);
}
if (!ALLOWED_REGEX_FLAGS_RE.test(flags)) {
throw new Error(`${contextLabel}: unsupported regex flags "${flags}" (only "" or "i" allowed)`);
}
if (UNSAFE_NESTED_QUANTIFIER_RE.test(source)) {
throw new Error(`${contextLabel}: potentially catastrophic nested quantifier in "${source}"`);
}
if (!replace) {
throw new Error(`${contextLabel}: replacement string cannot be empty`);
}
try {
// Compile to ensure valid JS RegExp syntax.
// eslint-disable-next-line no-new
new RegExp(source, flags);
} catch (err) {
throw new Error(`${contextLabel}: invalid RegExp "${source}": ${err.message}`);
}
return hint ? { source, flags, replace, hint } : { source, flags, replace };
}
function mergeExactBucket(target, bucket, fileLabel, bucketName) {
if (bucket === undefined) return;
if (!isPlainObject(bucket)) {
throw new Error(`${fileLabel}: "${bucketName}" must be a plain object`);
}
for (const [rawKey, rawVal] of Object.entries(bucket)) {
const key = String(rawKey).trim();
const val = typeof rawVal === 'string' ? rawVal.trim() : '';
if (!key) {
throw new Error(`${fileLabel}: empty key in "${bucketName}"`);
}
if (!val) {
throw new Error(`${fileLabel}: empty translation for "${key}" in "${bucketName}"`);
}
if (Object.prototype.hasOwnProperty.call(target, key)) {
throw new Error(`${fileLabel}: duplicate key "${key}" in "${bucketName}"`);
}
target[key] = val;
}
}
function patternLiteralSpecificity(source) {
const s = String(source || '');
let literalChars = 0;
let parenDepth = 0;
let inCharClass = false;
for (let i = 0; i < s.length; i += 1) {
const ch = s[i];
if (ch === '\\' && i + 1 < s.length) {
const next = s[i + 1];
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
literalChars += 1;
}
i += 1;
continue;
}
if (ch === '[' && !inCharClass) {
inCharClass = true;
continue;
}
if (ch === ']' && inCharClass) {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(') {
parenDepth += 1;
continue;
}
if (ch === ')') {
if (parenDepth > 0) parenDepth -= 1;
continue;
}
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
literalChars += 1;
}
}
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
const typedCaptures = (s.match(/\\d\+/g) || []).length;
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
}
function sortPatternsBySpecificity(list) {
return [...list].sort((a, b) => {
const specDiff = patternLiteralSpecificity(b.source) - patternLiteralSpecificity(a.source);
if (specDiff !== 0) return specDiff;
const lenDiff = b.source.length - a.source.length;
if (lenDiff !== 0) return lenDiff;
return a.source < b.source ? -1 : a.source > b.source ? 1 : 0;
});
}
function mergePatternBucket(target, list, fileLabel, bucketName) {
if (list === undefined) return;
if (!Array.isArray(list)) {
throw new Error(`${fileLabel}: "${bucketName}" patterns must be an array`);
}
const seen = new Set(target.map((p) => `${p.flags}:${p.source}`));
for (let i = 0; i < list.length; i += 1) {
const rule = validatePatternRule(list[i], `${fileLabel}[${bucketName}#${i}]`);
const sig = `${rule.flags}:${rule.source}`;
if (seen.has(sig)) continue;
seen.add(sig);
target.push(rule);
}
}
/**
* Compiles one locale folder under `sources/<locale>/` into a validated pack object.
*
* @param {string} localeDir
* @param {string} folderLocale
*/
export function compileLocaleSourceDir(localeDir, folderLocale) {
if (!LOCALE_RE.test(folderLocale)) {
throw new Error(`Invalid locale folder name: "${folderLocale}"`);
}
const metaPath = join(localeDir, 'meta.json');
if (!existsSync(metaPath)) {
throw new Error(`Missing meta.json in ${localeDir}`);
}
const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
if (!isPlainObject(meta)) {
throw new Error(`${metaPath}: meta.json must be a JSON object`);
}
const locale = String(meta.locale || '').trim();
if (locale !== folderLocale) {
throw new Error(`${metaPath}: meta.locale "${locale}" must match folder "${folderLocale}"`);
}
const name = String(meta.name || '').trim();
const nativeName = String(meta.nativeName || '').trim();
const version = String(meta.version || '').trim();
if (!name || !nativeName || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(version)) {
throw new Error(`${metaPath}: name, nativeName, and SemVer version are required`);
}
const baseExact = {};
const lightExact = {};
const deepExact = {};
const basePatterns = [];
const lightPatterns = [];
const deepPatterns = [];
const fileNames = readdirSync(localeDir)
.filter((f) => f.endsWith('.json') && f !== 'meta.json')
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
if (fileNames.length === 0) {
throw new Error(`${localeDir}: at least one dictionary JSON file is required`);
}
for (const fileName of fileNames) {
const absPath = join(localeDir, fileName);
const parsed = JSON.parse(readFileSync(absPath, 'utf8'));
if (!isPlainObject(parsed)) {
throw new Error(`${absPath}: dictionary file must be a JSON object`);
}
const label = `${folderLocale}/${fileName}`;
if (fileName === 'patterns.json' || Array.isArray(parsed.base) || Array.isArray(parsed.light) || Array.isArray(parsed.deep)) {
mergePatternBucket(basePatterns, parsed.base, label, 'base');
mergePatternBucket(lightPatterns, parsed.light, label, 'light');
mergePatternBucket(deepPatterns, parsed.deep, label, 'deep');
} else {
mergeExactBucket(baseExact, parsed.base, label, 'base');
mergeExactBucket(lightExact, parsed.light, label, 'light');
mergeExactBucket(deepExact, parsed.deep, label, 'deep');
}
}
// Ensure light/deep overlays do not silently shadow base keys unless intentional:
// disallow exact key duplication between base and light/deep so layering stays unambiguous.
for (const key of Object.keys(lightExact)) {
if (Object.prototype.hasOwnProperty.call(baseExact, key)) {
throw new Error(`${folderLocale}: key "${key}" exists in both "base" and "light"`);
}
}
for (const key of Object.keys(deepExact)) {
if (Object.prototype.hasOwnProperty.call(baseExact, key)) {
throw new Error(`${folderLocale}: key "${key}" exists in both "base" and "deep"`);
}
}
const sortedBaseExact = sortRecordKeys(baseExact);
const sortedLightExact = sortRecordKeys(lightExact);
const sortedDeepExact = sortRecordKeys(deepExact);
const sortedBasePatterns = sortPatternsBySpecificity(basePatterns);
const sortedLightPatterns = sortPatternsBySpecificity(lightPatterns);
const sortedDeepPatterns = sortPatternsBySpecificity(deepPatterns);
const packObj = {
schemaVersion: PACK_SCHEMA_VERSION,
locale,
name,
nativeName,
version,
depths: [...SUPPORTED_DEPTHS],
base: {
exact: sortedBaseExact,
patterns: sortedBasePatterns,
},
modes: {
light: {
exact: sortedLightExact,
patterns: sortedLightPatterns,
},
deep: {
exact: sortedDeepExact,
patterns: sortedDeepPatterns,
},
},
};
const jsonText = JSON.stringify(packObj) + '\n';
const sha256 = sha256Hex(jsonText);
const bytes = Buffer.byteLength(jsonText, 'utf8');
return {
locale,
meta: {
locale,
name,
nativeName,
version,
file: `packs/${locale}.json`,
sha256,
bytes,
depths: [...SUPPORTED_DEPTHS],
stats: {
baseExact: Object.keys(sortedBaseExact).length,
lightExact: Object.keys(sortedLightExact).length,
deepExact: Object.keys(sortedDeepExact).length,
basePatterns: basePatterns.length,
lightPatterns: lightPatterns.length,
deepPatterns: deepPatterns.length,
},
},
packObj,
jsonText,
};
}
/**
* Builds or validates (`checkOnly: true`) all packs under `rootDir/sources` into `rootDir/dist`.
*
* @param {{ rootDir?: string, checkOnly?: boolean }} [options]
*/
export function buildAllHostI18nPacks({
rootDir = DEFAULT_HOST_I18N_ROOT,
checkOnly = false,
} = {}) {
const sourcesDir = join(rootDir, 'sources');
const distDir = join(rootDir, 'dist');
const packsOutDir = join(distDir, 'packs');
if (!existsSync(sourcesDir)) {
throw new Error(`Missing host-i18n sources directory: ${sourcesDir}`);
}
const localeFolders = readdirSync(sourcesDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
.map((entry) => entry.name)
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
if (localeFolders.length === 0) {
throw new Error(`No locale directories found in ${sourcesDir}`);
}
const compiled = localeFolders.map((folder) =>
compileLocaleSourceDir(join(sourcesDir, folder), folder)
);
const manifestObj = {
schemaVersion: PACK_SCHEMA_VERSION,
packs: compiled.map((item) => item.meta),
};
const manifestText = JSON.stringify(manifestObj, null, 2) + '\n';
if (checkOnly) {
const manifestPath = join(distDir, 'manifest.json');
if (!existsSync(manifestPath)) {
throw new Error(`Check failed: missing ${manifestPath}`);
}
const diskManifest = readFileSync(manifestPath, 'utf8').replace(/\r\n/g, '\n');
if (diskManifest !== manifestText) {
throw new Error('Check failed: host-i18n/dist/manifest.json is out of date with sources');
}
for (const item of compiled) {
const packPath = join(packsOutDir, `${item.locale}.json`);
if (!existsSync(packPath)) {
throw new Error(`Check failed: missing ${packPath}`);
}
const diskPack = readFileSync(packPath, 'utf8').replace(/\r\n/g, '\n');
if (diskPack !== item.jsonText) {
throw new Error(`Check failed: ${packPath} is out of date with sources`);
}
if (sha256Hex(diskPack) !== item.meta.sha256) {
throw new Error(`Check failed: SHA-256 mismatch for ${packPath}`);
}
}
return { checked: true, manifest: manifestObj, packs: compiled };
}
mkdirSync(packsOutDir, { recursive: true });
const expectedFiles = new Set(compiled.map((item) => `${item.locale}.json`));
for (const existing of readdirSync(packsOutDir)) {
if (existing.endsWith('.json') && !expectedFiles.has(existing)) {
rmSync(join(packsOutDir, existing), { force: true });
}
}
for (const item of compiled) {
writeFileSync(join(packsOutDir, `${item.locale}.json`), item.jsonText, 'utf8');
}
writeFileSync(join(distDir, 'manifest.json'), manifestText, 'utf8');
return { checked: false, manifest: manifestObj, packs: compiled };
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const checkOnly = process.argv.includes('--check');
const res = buildAllHostI18nPacks({ checkOnly });
const summary = res.manifest.packs
.map(
(p) =>
`${p.locale}@${p.version} (base=${p.stats.baseExact}, light=${p.stats.lightExact}, deep=${p.stats.deepExact}, patterns=${p.stats.basePatterns + p.stats.lightPatterns + p.stats.deepPatterns}, ${(p.bytes / 1024).toFixed(1)} KB)`
)
.join(', ');
console.log(
checkOnly
? `[host-i18n] Check passed: ${summary}`
: `[host-i18n] Built ${res.manifest.packs.length} pack(s): ${summary}`
);
}
File diff suppressed because it is too large Load Diff
+290
View File
@@ -0,0 +1,290 @@
#!/usr/bin/env node
/**
* @fileoverview Conflict-free incremental merger for Antigravity Host I18n source dictionaries.
*
* Accepts a translation batch JSON (`exact`, `patterns`, `ignore`), routes entries into the right
* modular files under `host-i18n/sources/<locale>/` without duplicating keys across files or
* between `base` and `light`/`deep`, updates `host-i18n/sources/ignore.json`, optionally bumps
* `meta.json` SemVer, and rebuilds + verifies `host-i18n/dist/`.
*
* Input JSON format:
* {
* "exact": {
* "Light Theme": "浅色主题",
* "Queue": { "light": "Queue", "deep": "排队" }
* },
* "patterns": [
* { "source": "^Settings for conversations outside of (.+?)\\.$", "flags": "", "hint": "outside of", "light": "...", "deep": "..." }
* ],
* "ignore": {
* "exact": ["..."],
* "templates": ["^...$"]
* }
* }
*
* Usage:
* node host-i18n/scripts/merge-translations.mjs --locale zh-CN --in patch.json [--bump patch|minor]
*/
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildAllHostI18nPacks } from './build-packs.mjs';
import { DEFAULT_IGNORE_PATH, HOST_I18N_ROOT } from './audit-host-i18n.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
function sortKeys(obj) {
const out = {};
for (const k of Object.keys(obj).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
out[k] = obj[k];
}
return out;
}
function readJson(filePath, fallback) {
if (!existsSync(filePath)) return fallback;
return JSON.parse(readFileSync(filePath, 'utf8'));
}
function writeJson(filePath, data) {
writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');
}
function bumpSemver(version, kind) {
const m = String(version || '').match(/^(\d+)\.(\d+)\.(\d+)(.*)$/);
if (!m) return version;
let [, major, minor, patch] = m;
major = Number(major);
minor = Number(minor);
patch = Number(patch);
if (kind === 'major') return `${major + 1}.0.0`;
if (kind === 'minor') return `${major}.${minor + 1}.0`;
if (kind === 'patch') return `${major}.${minor}.${patch + 1}`;
return version;
}
function pickShardFileName(key) {
const first = String(key || '').trim().charAt(0).toLowerCase();
if (first >= 'a' && first <= 'm') return 'ui-a-m.json';
return 'ui-n-z.json';
}
export function mergeHostI18nTranslations({
locale,
patch,
rootDir = HOST_I18N_ROOT,
ignorePath = DEFAULT_IGNORE_PATH,
bump = '',
rebuild = true,
} = {}) {
const localeDir = join(rootDir, 'sources', locale);
if (!existsSync(join(localeDir, 'meta.json'))) {
throw new Error(`Locale source directory not initialized: ${localeDir}`);
}
// Load all existing exact dictionary files and build key -> fileName index
const dictFileNames = readdirSync(localeDir)
.filter((f) => f.endsWith('.json') && f !== 'meta.json' && f !== 'patterns.json')
.sort();
const dictFiles = new Map();
const keyToFile = new Map();
for (const f of dictFileNames) {
const obj = readJson(join(localeDir, f), { base: {}, light: {}, deep: {} });
obj.base = obj.base || {};
obj.light = obj.light || {};
obj.deep = obj.deep || {};
dictFiles.set(f, obj);
for (const bucket of ['base', 'light', 'deep']) {
for (const k of Object.keys(obj[bucket])) {
keyToFile.set(k, f);
}
}
}
const ensureShard = (fileName) => {
if (!dictFiles.has(fileName)) {
dictFiles.set(fileName, { base: {}, light: {}, deep: {} });
}
return dictFiles.get(fileName);
};
let exactAdded = 0;
let exactUpdated = 0;
const dirtyFiles = new Set();
for (const [rawKey, rawVal] of Object.entries(patch?.exact || {})) {
const key = String(rawKey || '').trim();
if (!key) continue;
let lightVal = '';
let deepVal = '';
if (typeof rawVal === 'string') {
lightVal = rawVal.trim();
deepVal = rawVal.trim();
} else if (rawVal && typeof rawVal === 'object') {
lightVal = String(rawVal.light ?? rawVal.base ?? '').trim();
deepVal = String(rawVal.deep ?? rawVal.base ?? lightVal).trim();
}
if (!lightVal || !deepVal) continue;
const existingFile = keyToFile.get(key);
const targetFileName = existingFile || pickShardFileName(key);
const targetObj = ensureShard(targetFileName);
const existed =
Object.prototype.hasOwnProperty.call(targetObj.base, key) ||
Object.prototype.hasOwnProperty.call(targetObj.light, key) ||
Object.prototype.hasOwnProperty.call(targetObj.deep, key);
// Clear all three buckets for this key before writing to guarantee zero base/mode collisions
delete targetObj.base[key];
delete targetObj.light[key];
delete targetObj.deep[key];
if (lightVal === deepVal) {
targetObj.base[key] = lightVal;
} else {
targetObj.light[key] = lightVal;
targetObj.deep[key] = deepVal;
}
keyToFile.set(key, targetFileName);
dirtyFiles.add(targetFileName);
if (existed) exactUpdated += 1;
else exactAdded += 1;
}
for (const fileName of dirtyFiles) {
const obj = dictFiles.get(fileName);
const out = {};
if (Object.keys(obj.base).length > 0) out.base = sortKeys(obj.base);
if (Object.keys(obj.light).length > 0) out.light = sortKeys(obj.light);
if (Object.keys(obj.deep).length > 0) out.deep = sortKeys(obj.deep);
writeJson(join(localeDir, fileName), out);
}
// Merge patterns cleanly
let patternsAdded = 0;
let patternsUpdated = 0;
const rawPatterns = Array.isArray(patch?.patterns) ? patch.patterns : [];
if (rawPatterns.length > 0) {
const patPath = join(localeDir, 'patterns.json');
const patObj = readJson(patPath, { base: [], light: [], deep: [] });
patObj.base = Array.isArray(patObj.base) ? patObj.base : [];
patObj.light = Array.isArray(patObj.light) ? patObj.light : [];
patObj.deep = Array.isArray(patObj.deep) ? patObj.deep : [];
const sigOf = (r) => `${r.flags || ''}:${r.source}`;
const removeBySig = (sig) => {
let removed = false;
for (const tier of ['base', 'light', 'deep']) {
const before = patObj[tier].length;
patObj[tier] = patObj[tier].filter((r) => sigOf(r) !== sig);
if (patObj[tier].length !== before) removed = true;
}
return removed;
};
for (const item of rawPatterns) {
if (!item || typeof item.source !== 'string') continue;
const source = item.source.trim();
const flags = typeof item.flags === 'string' ? item.flags : '';
const hint = typeof item.hint === 'string' ? item.hint.trim() : '';
const lightRep = String(item.light ?? item.replace ?? '').trim();
const deepRep = String(item.deep ?? item.replace ?? lightRep).trim();
if (!source || !lightRep || !deepRep) continue;
const sig = `${flags}:${source}`;
const existed = removeBySig(sig);
const makeRule = (replace) => (hint ? { source, flags, replace, hint } : { source, flags, replace });
if (lightRep === deepRep) {
patObj.base.push(makeRule(lightRep));
} else {
patObj.light.push(makeRule(lightRep));
patObj.deep.push(makeRule(deepRep));
}
if (existed) patternsUpdated += 1;
else patternsAdded += 1;
}
writeJson(patPath, patObj);
}
// Merge verified ignore entries
let ignoreAdded = 0;
const ignoreExact = Array.isArray(patch?.ignore?.exact) ? patch.ignore.exact : [];
const ignoreTemplates = Array.isArray(patch?.ignore?.templates) ? patch.ignore.templates : [];
if (ignoreExact.length > 0 || ignoreTemplates.length > 0) {
const curIgnore = readJson(ignorePath, {
description: 'Verified non-UI code literals, vendor noise, and intentionally untranslated brand/model tokens excluded from missing-translation audits.',
exact: [],
templates: [],
});
const exSet = new Set(Array.isArray(curIgnore.exact) ? curIgnore.exact : []);
const tpSet = new Set(Array.isArray(curIgnore.templates) ? curIgnore.templates : []);
const before = exSet.size + tpSet.size;
for (const s of ignoreExact) if (typeof s === 'string' && s.trim()) exSet.add(s.trim());
for (const s of ignoreTemplates) if (typeof s === 'string' && s.trim()) tpSet.add(s.trim());
ignoreAdded = exSet.size + tpSet.size - before;
curIgnore.exact = Array.from(exSet).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
curIgnore.templates = Array.from(tpSet).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
writeJson(ignorePath, curIgnore);
}
let version = '';
const metaPath = join(localeDir, 'meta.json');
const meta = readJson(metaPath, {});
if (bump) {
meta.version = bumpSemver(meta.version, bump);
writeJson(metaPath, meta);
}
version = meta.version;
let buildResult = null;
if (rebuild) {
buildResult = buildAllHostI18nPacks({ rootDir, checkOnly: false });
buildAllHostI18nPacks({ rootDir, checkOnly: true });
}
return {
locale,
version,
exactAdded,
exactUpdated,
patternsAdded,
patternsUpdated,
ignoreAdded,
buildResult,
};
}
function parseCliArgs(argv) {
const opts = { locale: 'zh-CN', inPath: '', bump: '', noBuild: false };
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--locale' && argv[i + 1]) opts.locale = argv[++i];
else if (arg === '--in' && argv[i + 1]) opts.inPath = resolve(argv[++i]);
else if (arg === '--bump' && argv[i + 1]) opts.bump = argv[++i];
else if (arg === '--no-build') opts.noBuild = true;
}
return opts;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const cli = parseCliArgs(process.argv.slice(2));
if (!cli.inPath || !existsSync(cli.inPath)) {
console.error('[merge-translations] Required --in <patch.json> file not found.');
process.exit(1);
}
const patch = JSON.parse(readFileSync(cli.inPath, 'utf8'));
const res = mergeHostI18nTranslations({
locale: cli.locale,
patch,
bump: cli.bump,
rebuild: !cli.noBuild,
});
console.log(
`[merge-translations] Merged into ${res.locale}@${res.version}: exact +${res.exactAdded}/~${res.exactUpdated}, patterns +${res.patternsAdded}/~${res.patternsUpdated}, ignore +${res.ignoreAdded}`
);
}
File diff suppressed because it is too large Load Diff
+144
View File
@@ -0,0 +1,144 @@
{
"description": "Verified non-UI code literals, vendor noise, and intentionally untranslated proper nouns/commands excluded from missing-translation audits.",
"exact": [
"(ADC)",
"/abns/…",
"== != in",
"A similar",
"ADEX",
"Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown",
"Alt+ArrowUp Alt+ArrowDown",
"Alternation",
"Android (main)",
"Antigravity Dev",
"Base UI",
"BigInt",
"BoN",
"Buganizer",
"CSP",
"Cloud Bang",
"Cog (GoB)",
"Command Shift A",
"Ctrl",
"Deprecated use `method` instead",
"Edge `",
"Edge already in inter-graph edge list!",
"Edge already in source and/or target incidency list!",
"Edge is null!",
"Edge owner graph or owner graph manager is null!",
"Edge source and/or target is null!",
"ElementNode.splice: Ephemeral nodes can not mutate their children (key %s type %s)",
"ElementNode.splice: start + deleteCount > oldSize (%s + %s > %s)",
"ElementNode: node %s is both slotted into host %s and a child of parent %s; __slotHost and __parent are mutually exclusive",
"Elements should not switch from uncontrolled to controlled (or vice versa).",
"Encountered Promise during synchronous parse. Use .parseAsync() instead.",
"Expected node %s to have a first child.",
"Fig",
"Flash",
"Flash Lite",
"Flask",
"Font style must be 'italic', 'bold', 'underline' or 'strikethrough' or a combination. The empty string unsets all styles.",
"GUID",
"Gemini 2.5 Flash Image",
"Gemini 3 Pro Image",
"Gemini 3.1 Flash Image",
"Gemini Enterprise",
"Gemini Flash Next",
"Google Chat",
"Google Chrome",
"Google Sans",
"Google3",
"H_CENTER V_CENTER",
"Ide",
"Iframe",
"Inter",
"Invalid \\arraystretch:",
"Invalid delimiter '",
"Invalid delimiter type '",
"Jetski",
"Jetski Chat",
"KSUID",
"Knut Sveidqvist",
"LexicalComposerContext.useLexicalComposerContext: cannot find a LexicalComposerContext",
"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",
"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",
"Minified React error #",
"Mismatch: \\begin{",
"Multiple \\tag",
"NaN",
"Peter Pan",
"Piper",
"Piper (g4)",
"Pro",
"Project 4K",
"Promise",
"Shift",
"Style for enums.",
"Style for types.",
"Tab",
"ULID",
"WSL:",
"X-Frame-Options",
"XID",
"\\angl",
"\\fbox",
"a2a (ttv2)",
"agent-marketplace.corp.google.com",
"bash",
"cuid",
"cuid2",
"data(label)",
"description.contains(\"fix\")",
"eu",
"gcert",
"gh auth login",
"googleplex-android/platform/superproject/main",
"http://localhost:8080",
"https://open-vsx.org/vscode/gallery",
"https://open-vsx.org/vscode/item",
"https://policies.google.com/privacy",
"nanoid",
"o+rx",
"priority in [\"P0\", \"P1\"]",
"rev27",
"root",
"sudo",
"you@company.com",
"~/.env",
"~/.gemini/antigravity-browser-profile",
"~/.ssh/config"
],
"templates": [
"^(.+?) observers:$",
"^(.+?) state: (.+?)$",
"^(.+?) value: (.+?)$",
"^(.+?) and (.+?)$",
"^(.+?) svg$",
"^Bar (.+?)$",
"^Bearer (.+?)$",
"^Error (.+?)$",
"^From (.+?)$",
"^HTTP (.+?)$",
"^Invariant failed: (.+?)$",
"^McpAppTabIcon\\((.+?)\\)$",
"^Move (.+?) (.+?)$",
"^Moved (.+?) (.+?)$",
"^NET::(.+?)$",
"^PERMISSIONED_GITHUB__GH_TOKEN=(.+?)$",
"^ReflectList \\((.+?)\\)$",
"^ReflectMap \\((.+?), (.+?)\\)$",
"^ReflectMessage \\((.+?)\\)$",
"^Running(.+?)$",
"^Side Question: (.+?)\n\n(.+?)$",
"^SidecarTabIcon\\((.+?)\\)$",
"^Top-level \"\\|\\|\" cannot be indexed up front because branch \"(.+?)\" does not positively constrain an indexed anchor; every branch of \"\\|\\|\" must constrain (.+?), or combine with an anchor using \"&&\"$",
"^Using (.+?)$",
"^View (.+?) (.+?)$",
"^View (.+?) help(.+?)$",
"^Waiting for your input(.+?)$",
"^When (.+?)$",
"^\\+(.+?) more options via locator\\('#(.+?) option'\\)$",
"^no message for (\\d+(?:\\.\\d+)?) ms$",
"^this (.+?)$"
]
}
File diff suppressed because it is too large Load Diff
+335
View File
@@ -0,0 +1,335 @@
{
"base": {
". Change it in the model menu.": "。请在模型菜单中更改。",
". For non-corp passwords or SSH passphrases, allow the next prompt and re-run your command.": "。对于非公司密码或 SSH 密钥口令,请允许下一次提示并重新运行您的命令。",
"Add Custom Model": "添加自定义模型",
"Add Model": "添加模型",
"Add a message...": "添加消息...",
"Add an optional message, ⏎ to submit comments": "添加可选消息,按 ⏎ 提交评论",
"Add attachment": "添加附件",
"Attach": "附件",
"Attach Antigravity server logs": "附加 Antigravity 服务器日志",
"Attach a screenshot (optional)": "附加截图(可选)",
"Attach file": "添加附件",
"Attach files": "添加附件",
"Attach image": "添加图片",
"Attach the trajectory ID to the feedback form": "将轨迹 ID 附加到反馈表单",
"Audio attachment": "音频附件",
"Automatically pin conversations when you send a message. Unpin as needed to keep your Pinned list focused.": "发送消息时自动固定对话。您可以按需取消固定,以保持“已固定”列表简洁聚焦。",
"Available CEL field tokens and helpers": "可用的 CEL 字段标记和辅助函数",
"Available dictation languages": "可用的听写语言",
"Best of N Models": "多路择优模型",
"CSV spreadsheet attachment": "CSV 电子表格附件",
"Cancel Sending Message": "取消发送消息",
"Cannot revert this message": "无法回退此消息",
"Carries out the plan: searches, edits, builds, and tests. Pick a faster, cheaper model.": "执行计划:搜索、编辑、构建并测试。请选择更快速、更经济的模型。",
"Change model": "更改模型",
"Chief of Staff voice message failed": "幕僚长语音消息发送失败",
"Chief of Staff voice mode is active": "幕僚长语音模式已激活",
"Chief of Staff voice mode stopped": "幕僚长语音模式已停止",
"Choose model": "选择模型",
"Choose which key sends a message in the chat composer.": "选择在聊天输入框中用于发送消息的按键。",
"Click on \"Send feedback\"": "点击“发送反馈”",
"Close message": "关闭消息",
"Collapse queued messages": "折叠排队中的消息",
"Command prompt": "命令提示符",
"Compact": "压缩",
"Compacting": "正在压缩",
"Compacting conversation...": "正在压缩对话...",
"Configure external tools via Model Context Protocol.": "通过 Model Context Protocol 配置外部工具。",
"Constrain voice dictation to selected languages in priority order. Leave empty to auto-detect.": "将语音听写限制为按优先级排序的所选语言。留空则自动检测。",
"Context Menus": "上下文菜单",
"Copy Message": "复制消息",
"Copy message": "复制消息",
"Could not determine the GitHub username for this token.": "无法确定此令牌对应的 GitHub 用户名。",
"Could not reach GitHub to validate the token. Check your connection.": "无法连接到 GitHub 以验证令牌。请检查您的网络连接。",
"Couldn't edit queued message": "无法编辑排队中的消息",
"Couldn't load message": "无法加载消息",
"Couldn't start voice. Try again.": "无法启动语音功能。请重试。",
"Couldn’t send. Try again.": "无法发送。请重试。",
"Create a token": "创建令牌",
"Custom Context Menus": "自定义上下文菜单",
"Custom context menus": "自定义上下文菜单",
"Custom models are only supported on Linux machines.": "仅 Linux 机器支持自定义模型。",
"Default Model": "默认模型",
"Dictation language options": "听写语言选项",
"Dictation languages": "听写语言",
"Display and preserve intermediate thinking steps.": "显示并保留中间思考步骤。",
"Document attachment": "文档附件",
"Drop to attach": "拖放以添加附件",
"Edit Custom Model": "编辑自定义模型",
"Edit Model": "编辑模型",
"Edit message": "编辑消息",
"Effort": "思考强度",
"Empty message": "空消息",
"End Voice mode": "结束语音模式",
"End voice": "结束语音",
"Enter to send": "按 Enter 发送",
"Error Loading Models": "加载模型出错",
"Executor Model": "执行器模型",
"Expand message": "展开消息",
"Expand queued messages": "展开排队中的消息",
"Failed to attach file": "附加文件失败",
"Failed to load token from ~/.env": "从 ~/.env 加载令牌失败",
"Failed to save token to ~/.env": "将令牌保存到 ~/.env 失败",
"Failed to send": "发送失败",
"Failed to send command input": "发送命令输入失败",
"Failed to send queued message": "发送排队消息失败",
"Failed to send side question": "发送侧边提问失败",
"Failed to validate the saved GitHub token.": "验证已保存的 GitHub 令牌失败。",
"File attachment": "文件附件",
"Fires before the model is called.": "在调用模型前触发。",
"GitHub Personal Access Token": "GitHub 个人访问令牌",
"Hide token": "隐藏令牌",
"Host supports receiving content messages (ui/message) from the view.": "宿主支持接收来自视图的内容消息(ui/message)。",
"How loud Antigravity's voice is.": "Antigravity 的语音音量。",
"How loud Jetski's voice is.": "Jetski 的语音音量。",
"Image attachment": "图像附件",
"Input device for voice mode and dictation.": "用于语音模式和听写的输入设备。",
"Invalid GitHub token. Please check the token and try again.": "GitHub 令牌无效。请检查令牌后重试。",
"Invalid auth token": "身份验证令牌无效",
"Invalid token after macro prefix": "宏前缀后的标记无效",
"It was already sent or couldn't be removed from the queue.": "该消息已发送或无法从队列中移除。",
"JSON attachment": "JSON 附件",
"Loading models...": "正在加载模型...",
"Markdown attachment": "Markdown 附件",
"Message Antigravity...": "给 Antigravity 发消息...",
"Message Board": "消息板",
"Message input": "消息输入框",
"Message this chat": "在此对话中发送消息",
"Messages now send immediately. Configure in": "消息现已改为立即发送。配置位置:",
"Model": "模型",
"Model Credits": "模型额度",
"Model Label": "模型标签",
"Model Summarization Failed": "模型摘要生成失败",
"Model URL": "模型 URL",
"Model URL info": "模型 URL 信息",
"Model must be available on the Gemini API and use the gemini-api scheme.": "模型必须在 Gemini API 上可用并使用 gemini-api 协议方案。",
"Model selection": "模型选择",
"Model selector loading": "正在加载模型选择器",
"Models": "模型",
"Models & Usage": "模型与用量",
"Models Tab": "模型标签页",
"Mute Voice Mic": "静音语音麦克风",
"Mute Voice Speaker": "静音语音扬声器",
"New models have been enabled for you!": "已为您启用新模型!",
"Next voice": "下一个语音",
"No Model Selected": "未选择模型",
"No Models Available": "无可用模型",
"No message text": "无消息文本",
"No model specified for Battle Mode, falling back to use current selected model": "未为对战模式指定模型,将回退使用当前所选模型",
"No models available": "无可用模型",
"No rate card for this model; showing comparable rates.": "此模型暂无费率表,当前显示同类参考费率。",
"One live model talks and hands real lookups to Jetski.": "由一个实时模型进行对话,并将实际查询任务交给 Jetski。",
"Orchestrator Model": "编排器模型",
"Orchestrator model selection": "编排器模型选择",
"PDF attachment": "PDF 附件",
"Password Prompt Blocked": "已阻止密码提示",
"Password prompt blocked to prevent a Chrome Password Alert reset.": "已阻止密码提示,以防止触发 Chrome 密码警报重置。",
"Pick a model to change it.": "选择一个模型以进行更改。",
"Plans the work, makes design decisions, and reviews the result. Pick a top-tier model. You can also pick one per conversation from the Orchestrator row in the model menu.": "规划任务、制定设计决策并审核结果。请选择顶级模型。你也可以在模型菜单中的“编排器”行内为每个对话单独选择。",
"Press Ctrl+Enter to send, Enter for a new line.": "按 Ctrl+Enter 发送,按 Enter 换行。",
"Press Enter to send, Shift+Enter for a new line.": "按 Enter 发送,按 Shift+Enter 换行。",
"Previous voice": "上一个语音",
"Queue Message": "加入发送队列",
"Queue message": "排队发送消息",
"Queue until after the current turn.": "排队等待当前轮次结束后发送。",
"Queued": "排队中",
"Queued Messages": "排队中的消息",
"Queued message deleted": "已删除排队中的消息",
"Queued message loaded into editor": "已将排队中的消息加载到编辑器",
"Queued message sent": "已发送排队中的消息",
"Queued messages": "排队中的消息",
"Reasoning": "推理",
"Reasoning Effort": "推理强度",
"Record voice memo": "录制语音备忘",
"Reply": "回复",
"Reply to /help": "回复 /help",
"Reply to /help... (Esc to minimize)": "回复 /help... (按 Esc 最小化)",
"Run Jetski Live on the ELMO composite voice actor.": "在 ELMO 复合语音角色上运行 Jetski Live。",
"Select Model": "选择模型",
"Select Model to Send Message": "选择模型以发送消息",
"Select a model in the model selector": "在模型选择器中选择一个模型",
"Select a model using the model selector in the input box": "使用输入框中的模型选择器选择一个模型",
"Select another model": "选择其他模型",
"Select model": "选择模型",
"Selected dictation languages": "已选听写语言",
"Selected model does not support this media type": "所选模型不支持此媒体类型",
"Send": "发送",
"Send Feedback": "发送反馈",
"Send Immediately": "立即发送",
"Send Message": "发送消息",
"Send Now": "立即发送",
"Send a message in the main conversation first to start a side question": "请先在主对话中发送一条消息,然后再发起侧边提问",
"Send command input?": "是否发送命令输入?",
"Send diagnostics": "发送诊断数据",
"Send feedback as": "发送反馈身份:",
"Send message": "发送消息",
"Send messages with the keyboard's Enter key instead of starting a new line.": "按键盘上的 Enter 键发送消息,而不是换行。",
"Send reply": "发送回复",
"Sending transcribed message...": "正在发送转录消息...",
"Sent Message": "已发送消息",
"Show token": "显示令牌",
"Some sites block embedding (via X-Frame-Options or CSP) and will show a fallback message. Blocked-page detection is best-effort (based on a load timeout), so it may occasionally be wrong. Use \"Open in new tab\" if a page doesn't load.": "部分站点会禁止嵌入(通过 X-Frame-Options 或 CSP),此时将显示回退提示。被拦截页面的检测为尽力而为(基于加载超时判断),因此偶尔可能出现误判。如果页面无法加载,请使用“在新标签页中打开”。",
"Speech recognition service is failing, and the current model doesn't support direct audio file input.": "语音识别服务出现故障,且当前模型不支持直接输入音频文件。",
"Start Voice Recording": "开始语音录制",
"Start Voice mode": "开启语音模式",
"Start voice": "开启语音",
"Stop Recording and Send": "停止录制并发送",
"Stop Voice Recording": "停止语音录制",
"Switch model": "切换模型",
"System Message": "系统消息",
"Text attachment": "文本附件",
"Thanks for helping make Gemini better! This is a critical part of evaluating and improving our models.": "感谢您帮助改进 Gemini!这是评估和提升我们模型质量的关键环节。",
"The other model hallucinated": "另一个模型出现了幻觉",
"The voice Jetski speaks with.": "Jetski 使用的语音。",
"The voice used in Voice mode. Powered by Gemini Live.": "语音模式中使用的声音。由 Gemini Live 提供支持。",
"Thinking": "思考",
"Thinking effort": "思考深度",
"Thinking...": "正在思考...",
"Thinking…": "正在思考…",
"This error is likely temporary. You can prompt the model to try again after some time.": "此错误可能是暂时的。您可以让模型稍后再试。",
"Thought Process": "思考过程",
"To continue using this model now, enable AI Credit overages.": "要立即继续使用此模型,请启用 AI 额度超额使用。",
"Toggle Model Selector": "切换模型选择器",
"Toggle Voice Recording": "切换语音录制",
"Token rejected": "令牌被拒绝",
"True if the host rejected or failed to deliver the message.": "如果宿主拒绝或未能传递该消息,则为 true。",
"Type a message...": "输入消息...",
"Type a voice variant name, such as rev27.": "输入语音变体名称,例如 rev27。",
"Type any voice server address.": "输入任意语音服务器地址。",
"User message": "用户消息",
"Video attachment": "视频附件",
"Voice": "语音",
"Voice Mode": "语音模式",
"Voice Speed": "语速",
"Voice dictation unavailable": "语音听写不可用",
"Voice disconnected.": "语音连接已断开。",
"Voice engine": "语音引擎",
"Voice engine address": "语音引擎地址",
"Voice input": "语音输入",
"Voice mode": "语音模式",
"Voice mode in progress": "语音模式进行中",
"Voice on": "语音已开启",
"Voice recording is unavailable while the Chief of Staff mic is on": "Chief of Staff 麦克风开启时无法录制语音",
"Voice speed": "语速",
"Voice transcript": "语音转写",
"Voice volume": "语音音量",
"Wait for the user's first request. Don't read files or run tools, and don't write a reply; the app already shows a welcome.": "等待用户的首个请求。不要读取文件或运行工具,也不要撰写回复;应用已显示欢迎信息。",
"Whatever the voice-engine-addr flag serves you.": "由 voice-engine-addr 参数提供的任意内容。",
"Whether to use AI credits for model requests": "是否为模型请求使用 AI 额度",
"Write a message": "输入消息",
"You can prompt the model to try again or start a new conversation if the error persists.": "如果错误持续存在,您可以提示模型重试或开始新对话。",
"Zip attachment": "Zip 附件",
"e.g. \"My Custom Gemini Model\"": "例如 \"我的自定义 Gemini 模型\"",
"e.g. \"gemini-api:/models/gemini-v3-byom\"": "例如 \"gemini-api:/models/gemini-v3-byom\""
},
"light": {
"/ 1M tokens": "/ 1M Token",
"Add Context": "添加 Context",
"Add context": "添加 Context",
"Allow Next Non-Corp Prompt": "允许下一个非企业 Prompt",
"Auto-compact": "自动 Compact",
"Choose the models Orchestrator uses. A larger, smarter orchestrator model with a faster, cheaper executor gives high quality for fewer tokens.": "选择 Orchestrator 使用的模型。更大、更智能的编排模型搭配更快、更经济的执行模型,能以更少的 Token 提供高质量的结果。",
"Code Context Items": "代码 Context 项",
"Combined Auth State and Context": "组合身份验证状态与 Context",
"Compact Context": "压缩 Context",
"Context": "Context",
"Context Providers": "Context 提供程序",
"Context Window": "Context 窗口",
"Context usage": "Context 使用量",
"Context window": "Context 窗口",
"Create a new workspace from your first message.": "根据您的第一条消息创建新的 Workspace。",
"Create with Prompt": "通过 Prompt 创建",
"Customization token budget exceeded. Large customizations are excluded from context.": "自定义配置的 Token 预算已超出。较大的自定义项将从 Context 中排除。",
"Failed to Generate Commit Message": "生成 Commit 信息失败",
"Failed to resolve context URI": "解析 Context URI 失败",
"For Unix shells, an allow list entry matches a command if its space-separated tokens form a prefix of the command's tokens. For PowerShell, the entry tokens may match any contiguous subsequence of the command tokens.": "对于 Unix Shell,如果 Allowlist 条目中以空格分隔的 Token 构成命令 Token 的前缀,则该条目匹配该命令。对于 PowerShell,条目 Token 可以匹配命令 Token 的任意连续子序列。",
"Forgot context": "已忘记 Context",
"Generate a commit message for the following file changes, which are likely relevant to this conversation.": "为以下可能与当前对话相关的文件更改生成 Commit 信息。",
"Generating commit message...": "正在生成 Commit 信息...",
"Git-on-Borg repository used when creating a new Cog workspace from your initial prompt (e.g., chromium/chromium/src or android/platform/superproject).": "根据初始 Prompt 创建新 Cog Workspace 时使用的 Git-on-Borg 仓库(例如 chromium/chromium/src 或 android/platform/superproject)。",
"Git-on-Borg repository used when creating a new Cog workspace from your initial prompt (e.g., chromium/src or android/platform/superproject).": "根据初始 Prompt 创建新 Cog Workspace 时使用的 Git-on-Borg 仓库(例如 chromium/src 或 android/platform/superproject)。",
"Help me understand the current context.": "帮我理解当前 Context。",
"Jump to Next Prompt": "跳转到下一条 Prompt",
"Jump to Previous Prompt": "跳转到上一条 Prompt",
"Last Prompt": "上一条 Prompt",
"Loading token usage...": "正在加载 Token 用量...",
"No token data available.": "暂无可用的 Token 数据。",
"Offloads routine steps to a faster executor. Same quality, fewer tokens used.": "将常规步骤交由更快的执行器处理。质量不变,消耗更少 Token。",
"Pay only for the tokens you use, billed through Gemini platform.": "仅按实际使用的 Token 付费,通过 Gemini 平台计费。",
"Prompt": "Prompt",
"Prompt to run when triggered...": "触发时运行的 Prompt...",
"Prompt too simple": "Prompt 过于简单",
"Select workspace to send message": "选择要发送消息的 Workspace",
"Submit Prompt (Alternate to Enter)": "提交 Prompt(Enter 的替代键)",
"System Prompt": "System Prompt",
"The conversation was compacted to fit within the context window.": "对话已压缩以适应 Context 窗口。",
"This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.": "这用于标记跳过的 Token 模式,表示由其识别的每个 Token 都将被消耗并直接丢弃,例如可用于完全忽略空白字符。",
"This prompt is straightforward and does not need alternative comparisons.": "此 Prompt 足够明确,无需进行备选方案对比。",
"Timed out waiting for commit message generation": "等待生成 Commit 信息超时",
"Token Usage": "Token 用量",
"Tokens": "Tokens",
"Trigger multiple response variants from the same prompt.": "基于同一 Prompt 触发多个回复变体。",
"Used context well": "合理利用了 Context",
"VCS used when creating a new workspace, including workspaces generated based off your initial prompt.": "创建新 Workspace(包括根据您的初始 Prompt 生成的 Workspace)时使用的 VCS。",
"does not collect any of your prompts, content, or model responses but will still collect general usage patterns (e.g., feature adoption, active user counts).": "不会收集您的任何 Prompt、内容或模型回复,但仍会收集常规使用模式(例如功能采用情况、活跃用户数)。",
"tokens": "Token",
"tokens (": "Token(",
"tokens)": "Token)"
},
"deep": {
"/ 1M tokens": "/ 1M 词元",
"Add Context": "添加上下文",
"Add context": "添加上下文",
"Allow Next Non-Corp Prompt": "允许下一个非企业提示词",
"Auto-compact": "自动压缩上下文",
"Choose the models Orchestrator uses. A larger, smarter orchestrator model with a faster, cheaper executor gives high quality for fewer tokens.": "选择 Orchestrator 使用的模型。更大、更智能的编排模型搭配更快、更经济的执行模型,能以更少的词元提供高质量的结果。",
"Code Context Items": "代码上下文项",
"Combined Auth State and Context": "组合身份验证状态与上下文",
"Compact Context": "压缩上下文",
"Context": "上下文",
"Context Providers": "上下文提供程序",
"Context Window": "上下文窗口",
"Context usage": "上下文使用量",
"Context window": "上下文窗口",
"Create a new workspace from your first message.": "根据您的第一条消息创建新的工作区。",
"Create with Prompt": "通过提示词创建",
"Customization token budget exceeded. Large customizations are excluded from context.": "自定义配置的词元预算已超出。较大的自定义项将从上下文中排除。",
"Failed to Generate Commit Message": "生成提交信息失败",
"Failed to resolve context URI": "解析上下文 URI 失败",
"For Unix shells, an allow list entry matches a command if its space-separated tokens form a prefix of the command's tokens. For PowerShell, the entry tokens may match any contiguous subsequence of the command tokens.": "对于 Unix Shell,如果允许名单条目中以空格分隔的词元构成命令词元的前缀,则该条目匹配该命令。对于 PowerShell,条目词元可以匹配命令词元的任意连续子序列。",
"Forgot context": "已忘记上下文",
"Generate a commit message for the following file changes, which are likely relevant to this conversation.": "为以下可能与当前对话相关的文件更改生成提交信息。",
"Generating commit message...": "正在生成提交信息...",
"Git-on-Borg repository used when creating a new Cog workspace from your initial prompt (e.g., chromium/chromium/src or android/platform/superproject).": "根据初始提示词创建新 Cog 工作区时使用的 Git-on-Borg 仓库(例如 chromium/chromium/src 或 android/platform/superproject)。",
"Git-on-Borg repository used when creating a new Cog workspace from your initial prompt (e.g., chromium/src or android/platform/superproject).": "根据初始提示词创建新 Cog 工作区时使用的 Git-on-Borg 仓库(例如 chromium/src 或 android/platform/superproject)。",
"Help me understand the current context.": "帮我理解当前上下文。",
"Jump to Next Prompt": "跳转到下一条提示词",
"Jump to Previous Prompt": "跳转到上一条提示词",
"Last Prompt": "上一条提示词",
"Loading token usage...": "正在加载词元用量...",
"No token data available.": "暂无可用的词元数据。",
"Offloads routine steps to a faster executor. Same quality, fewer tokens used.": "将常规步骤交由更快的执行器处理。质量不变,消耗更少词元。",
"Pay only for the tokens you use, billed through Gemini platform.": "仅按实际使用的词元付费,通过 Gemini 平台计费。",
"Prompt": "提示词",
"Prompt to run when triggered...": "触发时运行的提示词...",
"Prompt too simple": "提示词过于简单",
"Select workspace to send message": "选择要发送消息的工作区",
"Submit Prompt (Alternate to Enter)": "提交提示词(Enter 的替代键)",
"System Prompt": "系统提示词",
"The conversation was compacted to fit within the context window.": "对话已压缩以适应上下文窗口。",
"This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.": "这用于标记跳过的词元模式,表示由其识别的每个词元都将被消耗并直接丢弃,例如可用于完全忽略空白字符。",
"This prompt is straightforward and does not need alternative comparisons.": "此提示词足够明确,无需进行备选方案对比。",
"Timed out waiting for commit message generation": "等待生成提交信息超时",
"Token Usage": "词元用量",
"Tokens": "词元",
"Trigger multiple response variants from the same prompt.": "基于同一提示词触发多个回复变体。",
"Used context well": "合理利用了上下文",
"VCS used when creating a new workspace, including workspaces generated based off your initial prompt.": "创建新工作区(包括根据您的初始提示词生成的工作区)时使用的 VCS。",
"does not collect any of your prompts, content, or model responses but will still collect general usage patterns (e.g., feature adoption, active user counts).": "不会收集您的任何提示词、内容或模型回复,但仍会收集常规使用模式(例如功能采用情况、活跃用户数)。",
"tokens": "词元",
"tokens (": "词元(",
"tokens)": "词元)"
}
}
+307
View File
@@ -0,0 +1,307 @@
{
"base": {
"? This action cannot be undone.": "?此操作无法撤销。",
"A primitive argument cannot be optional": "基本类型参数不能为可选",
"Accept": "接受",
"Accept All": "全部接受",
"Accept Step": "接受步骤",
"Accept all": "全部接受",
"Add them to allow future interactions": "添加它们以允许后续交互",
"Allow": "允许",
"Allow Always": "始终允许",
"Allow Google to collect and use your Interactions data, subject to the": "允许 Google 收集和使用您的交互数据,需遵守",
"Allow Once": "仅允许一次",
"Allow always": "始终允许",
"Allow command execution?": "允许执行此命令吗?",
"Allow creating issues and grant access to specific issues.": "允许创建议题并授予对特定议题的访问权限。",
"Allow for this session": "在本次会话中允许",
"Allow once": "仅允许一次",
"Always Allow": "始终允许",
"Always allow this command": "始终允许此命令",
"Amend and Upload Failed": "修订并上传失败",
"An error occurred while checking the port. Please try again.": "检查端口时出错,请重试。",
"An error occurred while submitting your feedback. Please try again.": "提交反馈时出错,请重试。",
"An error was thrown.": "抛出了一个错误。",
"An unexpected error occurred during creation": "创建过程中发生意外错误",
"Any error messages": "任何错误信息",
"Any error messages seen when trying to log in": "尝试登录时看到的任何错误信息",
"Approve": "批准",
"Approve and continue": "批准并继续",
"Are you sure you want to delete": "确定要删除",
"Are you sure you want to delete the": "确定要删除",
"Are you sure you want to delete this handler?": "确定要删除此处理程序吗?",
"Are you sure you want to delete this side question? This action cannot be undone.": "确定要删除此支线提问吗?此操作无法撤销。",
"Authentication expired": "身份验证已过期",
"Authentication failed": "身份验证失败",
"Auto-approve": "自动批准",
"BlockIdExtension: generateId returned %s ids in a row that were invalid or already in use": "BlockIdExtension: generateId 连续返回了 %s 个无效或已被占用的 ID",
"Cancel": "取消",
"Cancel (Ctrl+D)": "取消 (Ctrl+D)",
"Cancel All Tasks": "取消所有任务",
"Cancel Generation": "取消生成",
"Cancel Render Page Failed": "取消页面渲染失败",
"Cancel Render Thumbnail Failed": "取消缩略图渲染失败",
"Cancel Step": "取消步骤",
"Cancel Task": "取消任务",
"Cancel download": "取消下载",
"Cancel questionnaire": "取消问卷",
"Cancel recording": "取消录制",
"Cancel step": "取消步骤",
"Cancel task": "取消任务",
"Cannot add elements to a Range": "无法向 Range 添加元素",
"Cannot handle MDX estrees without `createEvaluater`": "缺少 `createEvaluater` 时无法处理 MDX estree",
"Cannot parse `style` attribute": "无法解析 `style` 属性",
"Cannot remove elements from a Range": "无法从 Range 移除元素",
"Cannot set elements in a Range": "无法在 Range 中设置元素",
"Cannot start best-of-N mode: background tasks are still running.": "无法启动多路择优模式:后台任务仍在运行中。",
"Command failed": "命令执行失败",
"Confirm": "确认",
"Confirm & Save": "确认并保存",
"Confirm Selection": "确认选择",
"Confirm Undo": "确认撤销",
"Confirm before running": "运行前确认",
"Copied error": "已复制错误",
"Copied error to clipboard": "已将错误复制到剪贴板",
"Copy error": "复制错误",
"Copy error messages": "复制错误消息",
"Copy error to clipboard": "复制错误到剪贴板",
"Could not clear site data for": "无法清除以下网站的站点数据:",
"Could not create canvas of type": "无法创建以下类型的画布:",
"Could not find match for route:": "找不到路由匹配项:",
"Could not load": "无法加载",
"Could not load the app view:": "无法加载应用视图:",
"Could not start.": "无法启动。",
"Couldn't delete cookies for": "无法删除以下网站的 Cookie:",
"Couldn't delete your data. Try again.": "无法删除您的数据。请重试。",
"Couldn't load older messages — retry": "无法加载更早的消息 — 重试",
"Couldn't load older messages, retry": "无法加载更早的消息,重试",
"DecoratorPastePlugin: resolve timeout": "DecoratorPastePlugin:解析超时",
"Delete": "删除",
"Delete All Data": "删除所有数据",
"Delete Group": "删除分组",
"Delete Handler": "删除处理程序",
"Delete Permanently": "永久删除",
"Delete Side Question": "删除侧边提问",
"Delete Task": "删除任务",
"Delete all": "全部删除",
"Delete all recordings?": "删除所有录制内容?",
"Delete command": "删除命令",
"Delete comment": "删除评论",
"Delete permanently": "永久删除",
"Delete server": "删除服务器",
"Delete side question": "删除侧边提问",
"Deny": "拒绝",
"Discard": "放弃",
"Discard Changes": "放弃更改",
"Discard changes": "放弃更改",
"Discard comment draft": "放弃评论草稿",
"Discard unstaged changes": "放弃未暂存的更改",
"Disconnect": "断开连接",
"Dismiss error": "关闭错误提示",
"Dismiss microphone warning": "关闭麦克风警告",
"Encountered an error": "遇到错误",
"Error": "错误",
"Error Details:": "错误详情:",
"Error ID:": "错误 ID:",
"Error during tool execution": "执行工具时出错",
"Error editing notebook": "编辑 Notebook 出错",
"Error generating stack:": "生成堆栈时出错:",
"Error occurred during import.": "导入期间发生错误。",
"Error parsing key-value for \\htmlData": "解析 \\\\htmlData 的键值对时出错",
"Error preloading route! ☝️": "预加载路由出错!☝️",
"Error reading notebook": "读取 Notebook 出错",
"Error rendering playback": "渲染回放出错",
"Error starting sign-in: this host can't start it": "启动登录出错: 此主机无法启动登录",
"Error while analyzing directory": "分析目录时出错",
"Error while editing": "编辑时出错",
"Error while editing notebook": "编辑 Notebook 时出错",
"Error while reading notebook": "读取 Notebook 时出错",
"Error while running command": "运行命令时出错",
"Error while searching": "搜索时出错",
"Error while searching filesystem": "搜索文件系统时出错",
"Error while searching the web": "搜索网页时出错",
"Error while semantic searching": "语义搜索时出错",
"Error while viewing": "查看时出错",
"Error:": "错误:",
"Every command requires approval.": "每条命令都需要批准。",
"Expected a notFound error": "预期为 notFound 错误",
"Expected a redirect error": "预期为重定向错误",
"Expired · Action not taken": "已过期 · 未执行操作",
"Failed": "失败",
"Failed target:": "失败目标:",
"Failed to Amend": "修订失败",
"Failed to Push": "推送失败",
"Failed to add bundle.": "添加捆绑包失败。",
"Failed to add bundle. Please try again.": "添加捆绑包失败,请重试。",
"Failed to capture screenshot": "截图失败",
"Failed to continue": "继续失败",
"Failed to delete side question": "删除侧边提问失败",
"Failed to edit": "编辑失败",
"Failed to establish connection.": "建立连接失败。",
"Failed to get all annotations": "获取所有批注失败",
"Failed to get annotations": "获取批注失败",
"Failed to load bundle. Please try again.": "加载捆绑包失败,请重试。",
"Failed to load image": "加载图片失败",
"Failed to load media": "加载媒体失败",
"Failed to load resources": "加载资源失败",
"Failed to load your customizations. Please try again.": "加载自定义配置失败,请重试。",
"Failed to parse trailer frame:": "解析尾部帧失败:",
"Failed to proceed": "继续操作失败",
"Failed to process image": "处理图片失败",
"Failed to read": "读取失败",
"Failed to refresh credentials": "刷新凭据失败",
"Failed to render diagram": "渲染图表失败",
"Failed to render math": "渲染数学公式失败",
"Failed to save changes.": "保存更改失败。",
"Failed to start Best of N mode": "启动 Best of N 模式失败",
"Failed to start side question": "发起侧边提问失败",
"Failed to submit comment. Please try again.": "提交评论失败,请重试。",
"Fork warning": "派生警告",
"Full Error": "完整错误",
"GoB Repository path cannot be empty": "GoB 仓库路径不能为空",
"Hide Error": "隐藏错误",
"Highlight After Accept": "采纳后高亮显示",
"ICE/DTLS failed": "ICE/DTLS 失败",
"Idle Guard Warning": "空闲保护警告",
"Internal Error:": "内部错误:",
"Internal error": "内部错误",
"Intersection results could not be merged": "无法合并交集结果",
"Invalid Base64 string": "无效的 Base64 字符串",
"Invalid CEL": "无效的 CEL",
"Invalid Media": "无效的媒体",
"Invalid argument number \"": "无效的参数编号 \"",
"Invalid base-": "无效的进制-",
"Invalid color: '": "无效的颜色:'",
"Invalid date": "无效的日期",
"Invalid embed:": "无效的嵌入项:",
"Invalid environment name": "无效的环境名称",
"Invalid function arguments": "无效的函数参数",
"Invalid function return type": "无效的函数返回类型",
"Invalid input": "无效输入",
"Invalid key: '": "无效的键:'",
"Invalid loopback URL": "无效的环回 URL",
"Invalid notebook JSON.": "无效的 Notebook JSON。",
"Invalid number of arguments:": "无效的参数数量:",
"Invalid parent node!": "无效的父节点!",
"Invalid separator type:": "无效的分隔符类型:",
"Invalid size: '": "无效的大小:'",
"Invalid tool call": "无效的工具调用",
"Invalid unit: '": "无效的单位:'",
"Invariant failed": "不变量检查失败",
"Lexical error on line": "词法错误,位于第",
"Manage and delete your data anytime": "随时管理和删除您的数据",
"Manager Error": "管理器错误",
"Manager Error:": "管理器错误:",
"Maximum total timeout exceeded": "已超过最大总超时时间",
"Media upload failed after 3 attempts.": "媒体上传在尝试 3 次后失败。",
"Microphone blocked. Allow mic access.": "麦克风已被阻止。请允许麦克风访问权限。",
"Microphone capture failed.": "麦克风采集失败。",
"NAVIGATION_BLOCKED: Opaque-origin subframe cannot be pierced without a verified parent origin": "NAVIGATION_BLOCKED: 未经验证父源的情况下无法穿透不透明源子框架",
"Needs Approval": "等待审批",
"Needs approval": "等待审批",
"Needs reconnect": "需要重新连接",
"Needs your approval": "需要您的批准",
"Offline": "离线",
"Optional reason for the cancellation (e.g., \"user action\", \"timeout\").": "可选的取消原因(例如 \"user action\"、\"timeout\")。",
"Owner graph is invalid!": "所有者图无效!",
"Owner graph manager is invalid!": "所有者图管理器无效!",
"PageAgent batch call failed": "PageAgent 批量调用失败",
"Parse error on line": "解析错误,位于第",
"Permanently delete": "永久删除",
"Preview unavailable due to a notebook parsing error.": "由于 Notebook 解析错误,无法预览。",
"Process Error": "进程错误",
"Process Error:": "进程错误:",
"Process exited with an error": "进程因错误退出",
"ProducerConsumer: cannot produce after final value has been set": "ProducerConsumer: 设置最终值后无法继续生成",
"Reconciliation: could not find DOM element for node key %s": "协调失败:找不到节点键 %s 对应的 DOM 元素",
"Reconnect": "重新连接",
"Redo": "重做",
"Reject": "拒绝",
"Reject All": "全部拒绝",
"Reject Step": "拒绝此步骤",
"Reject all": "全部拒绝",
"Remove": "移除",
"Remove All": "全部移除",
"Remove From Split": "从分栏中移除",
"Remove audio": "移除音频",
"Remove bundle": "移除扩展包",
"Remove from Group": "从分组中移除",
"Remove from Recent": "从最近列表中移除",
"Remove from Split": "从分栏中移除",
"Remove from list": "从列表中移除",
"Remove resource": "移除资源",
"Remove trigger": "移除触发器",
"Render failed": "渲染失败",
"Repository name cannot start with a dash": "仓库名称不能以短横线开头",
"Request failed": "请求失败",
"Retry": "重试",
"Revert": "回退",
"Revert and redo turn, best of N:": "撤销并重做本轮对话,取 N 次最佳结果:",
"Running processes are killed. This cannot be undone.": "正在运行的进程将被终止。此操作无法撤销。",
"Server returned an invalid API key or name": "服务器返回了无效的 API 密钥或名称",
"Setup script failed.": "初始化脚本运行失败。",
"Show Error": "显示错误",
"Sign-in failed:": "登录失败:",
"Source and/or target owner is invalid!": "源节点和/或目标节点的所有者无效!",
"Stream error": "流错误",
"Stream transport error": "流传输错误",
"Sync and Upload Failed": "同步并上传失败",
"Syntax error in text": "文本中存在语法错误",
"The certificate has expired or is not yet valid.": "证书已过期或尚未生效。",
"The color used for the problems error icon.": "问题错误图标使用的颜色。",
"The color used for the problems warning icon.": "问题警告图标使用的颜色。",
"The reader object cannot be used outside its compute function!": "reader 对象无法在其 compute 函数之外使用!",
"There was an error with your authentication. To log in, click": "您的身份验证出错。要登录,请点击",
"This action cannot be undone.": "此操作无法撤销。",
"This cannot be undone.": "此操作无法撤销。",
"This site cannot provide a secure connection.": "此网站无法提供安全连接。",
"This undo action will not make any code changes.": "此撤销操作不会更改任何代码。",
"This will permanently delete": "这将永久删除",
"Timeout must be a positive non-zero integer.": "超时时间必须为非零正整数。",
"Timeout:": "超时时间:",
"Toggle this on to allow creating new issues.": "开启此项以允许创建新议题。",
"True if the download failed (e.g., user cancelled or host denied).": "如果下载失败(例如用户取消或宿主拒绝),则为 true。",
"Unable to load PDF:": "无法加载 PDF:",
"Unable to resolve PDF source URL": "无法解析 PDF 源 URL",
"Unable to resolve audio source URL": "无法解析音频源 URL",
"Undo": "撤销",
"Undo to Here": "撤销到此处",
"Unknown error": "未知错误",
"Unknown error.": "未知错误。",
"Unknown execution error": "未知执行错误",
"Upload Chain Failed": "上传调用链失败",
"Using this option will attempt to revert all changes in this turn and redo the turn using N parallel trajectories. This will discard any changes made in this turn in order to redo it.": "使用此选项将尝试撤销本轮的所有更改,并使用 N 条并行路径重新执行本轮。为重新执行,本轮所做的任何更改都将被丢弃。",
"Validation failed. Please verify requirements and try again.": "验证失败。请核实要求后重试。",
"View could not be opened": "无法打开视图",
"Waiting for approval": "等待批准",
"Waiting for approval to grant administrator access": "正在等待批准授予管理员权限",
"Waiting for your approval": "正在等待您的批准",
"Warning": "警告",
"WebSocket RPC error": "WebSocket RPC 错误",
"Yes, allow": "是,允许",
"Yes, allow downloads from": "是,允许下载来自",
"Yes, allow for this task": "是,在此任务中允许",
"Yes, allow this download": "是,允许此下载",
"Yes, allow this time": "是,仅本次允许",
"Yes, always allow": "是,始终允许",
"Yes, always allow downloads from": "是,始终允许下载来自",
"Yes, and always allow": "是,且始终允许",
"Yes, and always allow '": "是,且始终允许 '",
"Your session has expired. Please log back in to continue.": "您的会话已过期。请重新登录以继续。",
"lint error": "Lint 错误",
"⚠️ Failed to render LaTeX:": "⚠️ 渲染 LaTeX 失败:",
"⚠️ Failed to render Mermaid diagram:": "⚠️ 渲染 Mermaid 图表失败:"
},
"light": {
"Allow opening pull requests and grant access to specific PRs.": "允许发起 Pull Request 并授予对特定 PR 的访问权限。",
"Allow reading workflow runs (list, view, watch) across the whole repository.": "允许在整个仓库中读取 Workflow 运行记录(列出、查看、监视)。",
"Allow sandboxed commands to make network requests.": "允许 Sandbox 中的命令发出网络请求。",
"Toggle this on to allow creating new pull requests.": "开启此项以允许创建新的 Pull Request。"
},
"deep": {
"Allow opening pull requests and grant access to specific PRs.": "允许发起拉取请求并授予对特定拉取请求的访问权限。",
"Allow reading workflow runs (list, view, watch) across the whole repository.": "允许在整个仓库中读取工作流运行记录(列出、查看、监视)。",
"Allow sandboxed commands to make network requests.": "允许沙箱中的命令发出网络请求。",
"Toggle this on to allow creating new pull requests.": "开启此项以允许创建新的拉取请求。"
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"locale": "zh-CN",
"name": "Chinese (Simplified)",
"nativeName": "简体中文",
"version": "2.1.1"
}
+999
View File
@@ -0,0 +1,999 @@
{
"base": {
"), use an external SSH session": "),请使用外部 SSH 会话",
". Reload the window if a change does not take effect.": "。如果更改未生效,请重新加载窗口。",
"A Google Cloud project is required to use Antigravity.": "需要一个 Google Cloud 项目才能使用 Antigravity。",
"A folder in this project could not be loaded because its location is invalid.": "无法加载此项目中的一个文件夹,因为其位置无效。",
"A license or project selection is required to use Antigravity.": "需要许可证或选择项目才能使用 Antigravity。",
"A permanent Chief of Staff conversation in the sidebar that manages your other conversations: delegate tasks, check status, and read results from one place.": "侧边栏中常驻的“参谋长”(Chief of Staff)对话,用于统一管理您的其他对话:在一处委派任务、查看状态并读取结果。",
"A project with this name already exists.": "已存在同名项目。",
"Accounts tab": "账号标签页",
"Active Tasks & Conversations:": "当前任务与对话:",
"Add Folder": "添加文件夹",
"Add files": "添加文件",
"Add filter": "添加筛选器",
"Add screenshot to conversation": "将截图添加到对话",
"Advanced File Access": "高级文件访问权限",
"All Conversations": "全部对话",
"All conversations": "所有对话",
"Allow Tab to view and edit the files in .gitignore. Use with caution if your .gitignore lists files containing credentials, secrets, or other sensitive information.": "允许 Tab 查看和编辑 .gitignore 中的文件。如果您的 .gitignore 列出了包含凭据、密钥或其他敏感信息的文件,请谨慎使用。",
"Allowed in this conversation": "在此对话中已允许",
"Always allowed in this project": "在此项目中始终允许",
"Archive": "归档",
"Archive / Restore": "归档 / 恢复",
"Archive Conversation": "归档对话",
"Archive This Conversation": "归档此对话",
"Archive conversation": "归档对话",
"Archive project": "归档项目",
"Archived": "已归档",
"Archived Conversations": "已归档对话",
"Archived Only": "仅限已归档",
"Are you sure you want to delete this conversation? This action cannot be undone.": "确定要删除此对话吗?此操作无法撤销。",
"Ask a quick question without interrupting the main conversation.": "在不打断主对话的情况下快速提问。",
"Ask a side question without interrupting the main conversation": "在不打断主对话的情况下提出支线问题",
"Audio File": "音频文件",
"Audio file size exceeds 20MB limit": "音频文件大小超过 20MB 限制",
"Auto Pin": "自动固定",
"Auto-Open Edited Files": "自动打开已编辑的文件",
"Auto-dismissed due to conversation switching": "因切换对话而自动关闭",
"Binary file not shown": "未显示二进制文件",
"Browsing history": "浏览历史记录",
"Cannot continue as a new conversation during Battle Mode — end the battle first": "对战模式下无法继续作为新对话——请先结束对战",
"Cannot continue as a new conversation while side question is running": "旁路提问运行期间无法继续作为新对话",
"Cannot parse folder URI.": "无法解析文件夹 URI。",
"Cannot revert messages with file comments": "无法回退包含文件评论的消息",
"Check CLs that require my attention and fix them in their respective conversations.": "检查需要我关注的 CL,并在各自的对话中进行修复。",
"Check pending conversations in the last 3 days that require action from me.": "检查最近 3 天内需要我处理的待处理对话。",
"Chief of Staff is listening — open the Chief of Staff conversation": "幕僚长正在聆听 — 打开幕僚长对话",
"Choose File…": "选择文件…",
"Choose between the Default and Project 4K experience.": "在默认体验和 Project 4K 体验之间进行选择。",
"Choose how much detail is shown during a conversation.": "选择在对话过程中显示的详细程度。",
"Chrome on the machine you are controlling is not accepting remote debugging. Complete these steps on that machine, not in this tab:": "您正在控制的机器上的 Chrome 未开启远程调试。请在该机器上(而非此标签页中)完成以下步骤:",
"Clear Search": "清除搜索",
"Clear file filter": "清除文件筛选条件",
"Clear filter": "清除筛选条件",
"Clear row filter": "清除行筛选条件",
"Clear search": "清除搜索",
"Clone from Remote": "从远程克隆",
"Close Other Tabs": "关闭其他标签页",
"Close Sidebar": "关闭侧边栏",
"Close Tab": "关闭标签页",
"Close Tabs to the Left": "关闭左侧标签页",
"Close Tabs to the Right": "关闭右侧标签页",
"Close sidebar": "收起侧边栏",
"Close split view and go to forked conversation": "关闭分屏视图并前往派生对话",
"Cloud Conversation": "云端对话",
"Cloud conversation": "云端对话",
"Code Search": "代码搜索",
"Code search": "代码搜索",
"Collapse All Folders": "折叠所有文件夹",
"Combined filter clauses share no compatible event type": "组合的筛选子句没有兼容的事件类型",
"Configure allowed and denied paths for file reads and writes.": "配置允许和禁止读写文件的路径。",
"Configure tab completion, suggestions, and navigation behavior.": "配置 Tab 补全、建议和导航行为。",
"Configure the maximum width of the conversation panel.": "配置对话面板的最大宽度。",
"Confirm Window Reload": "确认重新加载窗口",
"Connect to SSH Host": "连接到 SSH 主机",
"Connect to SSH Host…": "连接到 SSH 主机…",
"Contact your administrator to set up Gemini Enterprise for this project": "请联系管理员为此项目设置 Gemini Enterprise",
"Continue \"Explain and Fix\" actions in the current conversation instead of starting a new one.": "在当前对话中继续执行“解释并修复”操作,而不是开启新对话。",
"Continue as a New Conversation": "作为新对话继续",
"Continue as a new conversation": "作为新对话继续",
"Continue your work from another device with Remote Control. Scan the QR code or open the link below.": "使用远程控制在另一台设备上继续工作。请扫描二维码或打开下方链接。",
"Conversation": "对话",
"Conversation 1": "对话 1",
"Conversation 2": "对话 2",
"Conversation 3": "对话 3",
"Conversation Archived": "对话已归档",
"Conversation History": "对话历史记录",
"Conversation ID": "对话 ID",
"Conversation Log": "对话日志",
"Conversation Name": "对话名称",
"Conversation Unarchived": "对话已取消归档",
"Conversation Width": "对话宽度",
"Conversation compacted": "对话已压缩",
"Conversation copied as Markdown to clipboard": "已将对话以 Markdown 格式复制到剪贴板",
"Conversation is not open in this Hub window": "对话未在此 Hub 窗口中打开",
"Conversation limit reached": "已达到对话上限",
"Conversation link": "对话链接",
"Conversation name": "对话名称",
"Conversation resolved": "对话已解决",
"Conversation steps": "对话步骤",
"Conversation turns": "对话轮次",
"Conversation unavailable": "对话不可用",
"Conversation width": "对话宽度",
"Conversations": "对话",
"Copy Config File Path": "复制配置文件路径",
"Copy Conversation ID": "复制对话 ID",
"Copy Conversation Markdown": "复制对话 Markdown",
"Copy File Name": "复制文件名",
"Copy File Path": "复制文件路径",
"Copy the folder elsewhere first if you might want it back.": "如果以后可能还需要,请先将该文件夹复制到其他位置。",
"Could not create project": "无法创建项目",
"Couldn't fetch the Google Drive file's title. The link was kept as-is.": "无法获取 Google Drive 文件的标题。已保留原链接。",
"Couldn't load your SSH hosts": "无法加载您的 SSH 主机",
"Couldn't load your SSH hosts. You can still type one.": "无法加载您的 SSH 主机。您仍可手动输入。",
"Couldn't mark conversations as read": "无法将对话标记为已读",
"Couldn't search files": "无法搜索文件",
"Create New Project": "新建项目",
"Create Project": "创建项目",
"Create a Project": "创建项目",
"Create a new project from one or more folders.": "从一个或多个文件夹创建新项目。",
"Create a project first.": "请先创建一个项目。",
"Create a project on a machine you reach over SSH. It opens in that host's own window.": "在通过 SSH 连接的机器上创建项目。它将在该主机的独立窗口中打开。",
"Create a project on this computer or remotely.": "在本机或远程创建项目。",
"Create a project whose conversations run remotely.": "创建一个对话在远程运行的项目。",
"Create project from scratch": "从头创建项目",
"Creating Cloud Project": "正在创建云端项目",
"Creating projects for your conversations": "正在为您的对话创建项目",
"Creating the forked conversation...": "正在创建派生对话...",
"Customize Sidebar": "自定义侧边栏",
"Daily conversation limit reached": "已达到每日对话上限",
"Delete Conversation": "删除对话",
"Delete conversation": "删除对话",
"Deprecated: go/projects-jetski": "已弃用:go/projects-jetski",
"Describe your Remote Control issue...": "请描述你的远程控制问题...",
"Diagnose why it failed. If a dependency it needs (for example node/npx, uv/uvx, python) is missing, check what is installed and tell me how to install it for my OS. If the server config is wrong, propose the fix. When it is fixed, tell me to restart the server from the Customizations tab.": "诊断失败原因。如果缺少所需的依赖项(例如 node/npx、uv/uvx、python),请检查当前已安装的内容并告诉我如何针对我的操作系统进行安装。如果服务配置有误,请提出修复方案。修复后,请提示我从“自定义配置”标签页重启服务。",
"Discard changes (revert file to last committed state)": "放弃更改(将文件恢复到上次提交的状态)",
"Disk is full. Search will no longer match in conversation bodies until you clear up space and restart.": "磁盘已满。在清理空间并重启之前,搜索将不再匹配对话正文内容。",
"Dismiss conversation open elsewhere warning": "关闭对话已在别处打开的警告",
"Docs, Sheets, Slides, and folders": "文档、表格、幻灯片和文件夹",
"Document file size exceeds 10MB limit": "文档文件大小超出 10MB 限制",
"Download File": "下载文件",
"Download files": "下载文件",
"Edit Conversation Title": "编辑对话标题",
"Edits the conversation title": "编辑对话标题",
"Enable Remote Control": "启用远程控制",
"Enter Google Cloud Project Details": "输入 Google Cloud 项目详情",
"Enter [user@]host[:port], or pick a host from your SSH config.": "输入 [user@]host[:port],或从你的 SSH 配置中选择主机。",
"Enter command (e.g., git, blaze)...": "输入命令(例如 git、blaze)...",
"Enter file or directory path...": "输入文件或目录路径...",
"Enter project name...": "输入项目名称...",
"Error editing file": "编辑文件出错",
"Error viewing file": "查看文件出错",
"Expand All Folders": "展开所有文件夹",
"Explain and Fix in Current Conversation": "在当前对话中解释并修复",
"Failed to clone project locally": "本地克隆项目失败",
"Failed to create folder. Please try again.": "创建文件夹失败,请重试。",
"Failed to create remote project": "创建远程项目失败",
"Failed to delete conversation": "删除对话失败",
"Failed to fork conversation": "分叉对话失败",
"Failed to inspect license for this project": "检查此项目的许可证失败",
"Failed to load shared conversation": "加载共享对话失败",
"Failed to read file": "读取文件失败",
"Failed to read file content": "读取文件内容失败",
"Failed to rename conversation": "重命名对话失败",
"Failed to revert conversation": "回退对话失败",
"Failed to save project": "保存项目失败",
"Failed to start conversation": "启动对话失败",
"Failed to stop conversation": "停止对话失败",
"Failed to unarchive local project": "取消归档本地项目失败",
"Failed to unarchive project: project management feature not available": "取消归档项目失败: 项目管理功能不可用",
"File": "文件",
"File Access": "文件访问",
"File Comments": "文件评论",
"File Explorer": "文件资源管理器",
"File Picker": "文件选择器",
"File Reads": "文件读取",
"File Tree Component is not loaded.": "文件树组件未加载。",
"File Viewer": "文件查看器",
"File Writes": "文件写入",
"File created": "已创建文件",
"File deleted": "已删除文件",
"File edited": "已编辑文件",
"File exceeds 512 KB table preview limit.": "文件大小超过 512 KB 表格预览限制。",
"File explorer": "文件资源管理器",
"File not found": "未找到文件",
"File path breadcrumbs": "文件路径面包屑导航",
"File reads": "文件读取",
"File size exceeds 20MB limit": "文件大小超过 20MB 限制",
"File system provider not available": "文件系统提供程序不可用",
"File writes": "文件写入",
"Files": "文件",
"Files Changed": "已更改文件",
"Files changed": "已变更文件",
"Files to edit:": "要编辑的文件:",
"Filter": "筛选",
"Filter files": "筛选文件",
"Filter files...": "筛选文件...",
"Filter log lines...": "筛选日志行...",
"Filter resources...": "筛选资源...",
"Filter rows": "筛选行",
"Filter rows...": "筛选行...",
"Filter topics...": "筛选主题...",
"Find all your Jetski conversations here.": "在此处查找您的所有 Jetski 对话。",
"Find in Conversation": "在对话中查找",
"Find in files": "在文件中查找",
"Folder": "文件夹",
"Folder count": "文件夹数量",
"Folder doesn't exist": "文件夹不存在",
"Folders": "文件夹",
"Fork Conversation": "派生对话",
"Fork conversation in this folder": "在此文件夹中派生对话",
"Forked conversation": "已派生的对话",
"GCP Project ID for enterprise features.": "用于企业功能的 GCP 项目 ID。",
"Get started with Remote Control": "开始使用远程控制",
"Go to File": "转到文件",
"Google Cloud Project ID": "Google Cloud 项目 ID",
"Google Search": "Google 搜索",
"Google3 projects are deprecated": "Google3 项目已弃用",
"Google3 projects are deprecated. Learn more": "Google3 项目已弃用。了解更多",
"Group By Project": "按项目分组",
"Help me self-troubleshoot an issue, configure Jetski, or file a bug or feature request about Jetski.": "帮我自助排查问题、配置 Jetski,或提交关于 Jetski 的 Bug 报告或功能请求。",
"Help me self-troubleshoot an issue, configure Jetski, or file a bug or feature request from this conversation.": "帮我根据此对话自助排查问题、配置 Jetski,或提交 Bug 报告或功能请求。",
"Here's how uploaded files, attachments, and connected resources work in your cloud environment": "以下是已上传的文件、附件和关联资源在您的云环境中的工作方式",
"Hide Thumbnail Sidebar": "隐藏缩略图侧边栏",
"Highlight newly inserted text after accepting a Tab completion.": "采纳 Tab 补全后高亮显示新插入的文本。",
"History": "历史记录",
"Host supports file downloads via ui/download-file.": "宿主支持通过 ui/download-file 下载文件。",
"Import AI Studio Project": "导入 AI Studio 项目",
"Importing shared conversation...": "正在导入共享对话...",
"Inbox": "收件箱",
"Inbox Mode": "收件箱模式",
"Insert into main conversation": "插入到主对话",
"Internal search": "内部搜索",
"Keep running conversations in a separate Working section instead of in the Inbox.": "将正在进行的对话保留在单独的“进行中”区域,而不是放在“收件箱”中。",
"Keep the app accessible from the menu bar and running in the background when all windows are closed.": "关闭所有窗口后,仍可从菜单栏访问应用并保持其在后台运行。",
"Keeps working in this folder. Nothing is copied.": "继续在此文件夹中工作。不会复制任何内容。",
"Launch Jetski in its installed Isolated Web App window:": "在已安装的独立 Web 应用窗口中启动 Jetski:",
"LexicalBuilder.fromEditor: The given editor was created with LexicalBuilder %s but this version is %s. A project should have exactly one copy of LexicalBuilder": "LexicalBuilder.fromEditor:传入的编辑器由 LexicalBuilder %s 创建,但当前版本为 %s。一个项目中应只包含一份 LexicalBuilder",
"LexicalBuilder.fromEditor: There are multiple copies of the same version of LexicalBuilder in your project, and this editor was created with another one. Your project, or one of its dependencies, has its package.json and/or bundler configured incorrectly.": "LexicalBuilder.fromEditor:您的项目中存在多个相同版本的 LexicalBuilder 副本,且此编辑器是由另一个副本创建的。您的项目或其某个依赖项的 package.json 和/或打包器配置有误。",
"Loading conversations...": "正在加载对话...",
"Local Windows environment": "本地 Windows 环境",
"Lost connection to the remote instance. Please wait a minute or refresh the page.": "与远程实例的连接已断开。请稍候片刻或刷新页面。",
"Manage your conversations from the companion website.": "在配套网站上管理您的对话。",
"Many external websites (such as Google Search, GitHub, or Wikipedia) restrict iframe embedding via": "许多外部网站(如 Google 搜索、GitHub 或维基百科)会限制 iframe 嵌入,使用",
"Mark This Conversation as Read": "将此对话标为已读",
"Mark This Conversation as Unread": "将此对话标为未读",
"Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.": "类 Markdown 语法,用于生成流程图、思维导图、时序图、类图、甘特图、Git 图表等。",
"Marked 1 conversation as read": "已将 1 个对话标为已读",
"Match when any modified file path starts with the given depot prefix.": "当任意已修改文件路径以指定的 depot 前缀开头时匹配。",
"Missing Folders": "缺少文件夹",
"Modified Files": "已修改文件",
"Modified files:": "已修改文件:",
"Move Conversation": "移动对话",
"Move Conversation Down": "下移对话",
"Move Conversation Up": "上移对话",
"Move idle Inbox conversations to Resolved automatically after the selected time.": "在所选时间后,自动将闲置的收件箱对话移至“已解决”。",
"Multi-conversation view is not available": "多对话视图不可用",
"New Conversation": "新建对话",
"New Conversation Button": "新建对话按钮",
"New Conversation in Project": "在项目中新建对话",
"New Editor Window": "新建编辑器窗口",
"New Folder": "新建文件夹",
"New Project": "新建项目",
"New Remote Project": "新建远程项目",
"New Tab": "新建标签页",
"New Window": "新建窗口",
"New conversation": "新对话",
"New conversation button": "新对话按钮",
"New tab": "新建标签页",
"Next Aux Pane Tab": "下一个辅助窗格标签页",
"Next Pane Tab": "下一个窗格标签页",
"Next Side Panel Tab": "下一个侧边栏标签页",
"No Project": "无项目",
"No archived conversations": "无已归档对话",
"No build files are updated.": "没有构建文件被更新。",
"No conversation": "无对话",
"No conversations found": "未找到对话",
"No conversations yet": "暂无对话",
"No custom flag matches your search.": "没有与您的搜索匹配的自定义标志。",
"No customizations match your search.": "没有与您的搜索匹配的自定义项。",
"No file changes": "无文件更改",
"No files or folders found": "未找到文件或文件夹",
"No folder selected": "未选择文件夹",
"No folders added yet.": "暂未添加文件夹。",
"No hosts in ~/.ssh/config yet": "~/.ssh/config 中暂无主机",
"No license available for this project and location": "此项目和位置无可用许可证",
"No matching conversations": "无匹配的对话",
"No matching files": "无匹配的文件",
"No matching project folders. Apply to use the custom URI.": "无匹配的项目文件夹。点击应用以使用自定义 URI。",
"No pinned conversations": "无已置顶对话",
"No project selected": "未选择项目",
"No project selected or project management not available.": "未选择项目或项目管理不可用。",
"No projects created": "尚未创建项目",
"No remote configured": "未配置远程仓库",
"Not in Project": "不在项目中",
"Only Archived": "仅已归档",
"Open Blame in Code Search": "在 Code Search 中打开 Blame",
"Open Conversation": "打开对话",
"Open Conversation History": "打开对话历史",
"Open Conversation Picker": "打开对话选择器",
"Open Conversation in New Tab": "在新标签页中打开对话",
"Open File": "打开文件",
"Open File Search": "打开文件搜索",
"Open Folder": "打开文件夹",
"Open Folder (Interactive)": "打开文件夹(交互式)",
"Open Image in New Tab": "在新标签页中打开图片",
"Open Link in New Tab": "在新标签页中打开链接",
"Open Project Picker": "打开项目选择器",
"Open Remote Control": "打开远程控制",
"Open SSH Host": "打开 SSH 主机",
"Open Search": "打开搜索",
"Open Sidebar": "展开侧边栏",
"Open Tabs": "已打开的标签页",
"Open folder": "打开文件夹",
"Open in Code Search": "在 Code Search 中打开",
"Open in New Tab": "在新标签页中打开",
"Open in New Window": "在新窗口中打开",
"Open in Preview Tab": "在预览标签页中打开",
"Open in Remote": "在远程环境中打开",
"Open in Remote Control": "在远程控制中打开",
"Open in Tab": "在标签页中打开",
"Open in full conversation": "在完整对话中打开",
"Open in new tab": "在新标签页中打开",
"Open in tab": "在标签页中打开",
"Open sidebar": "展开侧边栏",
"Optional boolean filter": "可选布尔筛选器",
"Other Conversations": "其他对话",
"Other Projects": "其他项目",
"Other conversation": "其他对话",
"Outside of Project": "项目外部",
"PDF file size exceeds 10MB limit": "PDF 文件大小超过 10MB 限制",
"Parent Conversation": "父对话",
"Pin": "固定",
"Pin / Unpin Conversation": "固定 / 取消固定对话",
"Pin Tab": "固定标签页",
"Pin This Conversation": "固定此对话",
"Pin conversation": "固定对话",
"Pinned": "已固定",
"Pinned Actions": "已固定的操作",
"Pinned Conversations": "已固定的对话",
"Please sign in using the Antigravity sidebar panel to view this page.": "请使用 Antigravity 侧边栏面板登录以查看此页面。",
"Port number for Chrome DevTools Protocol remote debugging. Leave empty for default (9222).": "Chrome DevTools Protocol 远程调试的端口号。留空则使用默认值 (9222)。",
"Predict the location of your next edit and navigate you there with a tab keypress.": "预测您下次编辑的位置,并通过按 Tab 键跳转至该处。",
"Preview is not available for this file type.": "此文件类型不支持预览。",
"Previous Aux Pane Tab": "上一个辅助窗格标签页",
"Previous Pane Tab": "上一个窗格标签页",
"Previous Side Panel Tab": "上一个侧边栏标签页",
"Previous chats live under a deprecated Google3 Project": "之前的对话位于已弃用的 Google3 项目下",
"Project": "项目",
"Project 4K interface without developer tooling.": "不含开发者工具的 Project 4K 界面。",
"Project Folders": "项目文件夹",
"Project General": "项目常规",
"Project ID:": "项目 ID:",
"Project Name": "项目名称",
"Project Required": "需要项目",
"Project already exists": "项目已存在",
"Project location": "项目位置",
"Project options": "项目选项",
"Project required": "需要项目",
"Projects": "项目",
"Provide Google Cloud Project": "提供 Google Cloud 项目",
"Read Files": "读取文件",
"Read file": "读取文件",
"Read files": "读取文件",
"Recent Conversations": "最近对话",
"Recent Files": "最近文件",
"Recent Projects": "最近项目",
"Recent conversations": "最近对话",
"Recent files": "最近文件",
"Reload Window": "重新加载窗口",
"Reload this window.": "重新加载此窗口。",
"Reload window": "重新加载窗口",
"Remote": "远程",
"Remote Control": "远程控制",
"Remote Control Instances": "远程控制实例",
"Remote Control Issue": "远程控制问题",
"Remote Control channel closed": "远程控制通道已关闭",
"Remote Control isn't active on this instance. Enable it in": "此实例未启用远程控制。请前往",
"Remote Control link": "远程控制链接",
"Remote Debugging Required": "需要远程调试",
"Remote only": "仅远程",
"Remove from history": "从历史记录中移除",
"Remove from history (Shift+Delete)": "从历史记录中移除 (Shift+Delete)",
"Rename Conversation": "重命名对话",
"Rename This Conversation": "重命名此对话",
"Rename conversation": "重命名对话",
"Reopen Closed Tab": "重新打开关闭的标签页",
"Resolve conversation": "解决对话",
"Restore Conversation": "恢复对话",
"Resume it to load this file.": "恢复后即可加载此文件。",
"Return to Inbox": "返回收件箱",
"Returned conversation to Inbox": "已将对话移回收件箱",
"Revert file changes": "还原文件更改",
"Review pending conversations": "审阅待处理对话",
"Rewinds the conversation only. Files in this folder stay as they are now.": "仅回退对话记录。此文件夹中的文件将保持当前状态。",
"SSH Config": "SSH 配置",
"SSH Host": "SSH 主机",
"SSH Host…": "SSH 主机…",
"SSH config:": "SSH 配置:",
"SSH host": "SSH 主机",
"Same Project": "同一项目",
"Scan the code to open this device in Remote Control, or": "扫码在远程控制中打开此设备,或",
"Search": "搜索",
"Search Conversations": "搜索对话",
"Search GoB repositories...": "搜索 GoB 仓库...",
"Search Google Drive": "搜索 Google Drive",
"Search Hosts…": "搜索主机…",
"Search Projects": "搜索项目",
"Search Projects…": "搜索项目…",
"Search Remote…": "搜索远程…",
"Search Repositories…": "搜索仓库…",
"Search by name or username": "按名称或用户名搜索",
"Search catalog...": "搜索目录...",
"Search conversations": "搜索对话",
"Search conversations with": "搜索以下对象的对话",
"Search conversations, commands, and code...": "搜索对话、命令和代码...",
"Search conversations...": "搜索对话...",
"Search customizations...": "搜索自定义项...",
"Search file contents...": "搜索文件内容...",
"Search files...": "搜索文件...",
"Search filters…": "搜索筛选条件…",
"Search flags": "搜索标志",
"Search for commands...": "搜索命令...",
"Search for content to open": "搜索要打开的内容",
"Search for conversations...": "搜索对话...",
"Search for files in the project...": "在项目中搜索文件...",
"Search identities": "搜索身份",
"Search in document...": "在文档中搜索...",
"Search or enter a URL": "搜索或输入 URL",
"Search projects...": "搜索项目...",
"Search results": "搜索结果",
"Search sites": "搜索站点",
"Search sites...": "搜索站点...",
"Search tabs, files and more": "搜索标签页、文件及更多内容",
"Search tasks...": "搜索任务...",
"Search triggers…": "搜索触发器…",
"Search...": "搜索...",
"Searched files": "已搜索文件",
"Searched for files": "已搜索文件",
"Select Folder(s)": "选择文件夹",
"Select Google Drive files or folders": "选择 Google Drive 文件或文件夹",
"Select Next Conversation": "选择下一个对话",
"Select Previous Conversation": "选择上一个对话",
"Select Project": "选择项目",
"Select Sidebar Item 1": "选择侧边栏第 1 项",
"Select Sidebar Item 2": "选择侧边栏第 2 项",
"Select Sidebar Item 3": "选择侧边栏第 3 项",
"Select Sidebar Item 4": "选择侧边栏第 4 项",
"Select Sidebar Item 5": "选择侧边栏第 5 项",
"Select Sidebar Item 6": "选择侧边栏第 6 项",
"Select Sidebar Item 7": "选择侧边栏第 7 项",
"Select Sidebar Item 8": "选择侧边栏第 8 项",
"Select Sidebar Item 9": "选择侧边栏第 9 项",
"Select a folder.": "请选择一个文件夹。",
"Select category to search...": "选择要搜索的类别...",
"Selected event types conflict with event_type in CEL filter": "所选事件类型与 CEL 过滤器中的 event_type 冲突",
"Set Project Name": "设置项目名称",
"Set at least one scope filter": "请至少设置一个范围过滤器",
"Set the speed of tab suggestions": "设置 Tab 建议的速度",
"Share Conversation (Preview)": "分享对话(预览版)",
"Shared conversations live in your x20 user directory, so readers need": "共享的对话保存在你的 x20 用户目录中,因此阅读者需要",
"Sharing is a preview feature. It exports this conversation's history to your": "分享是一项预览功能。它会将此对话的历史记录导出到你的",
"Show Remote Control QR code": "显示远程控制二维码",
"Show Thumbnail Sidebar": "显示缩略图侧边栏",
"Show in Sidebar": "在侧边栏中显示",
"Show in folder": "在文件夹中显示",
"Sidebar": "侧边栏",
"Sidebar grouped by project": "侧边栏按项目分组",
"Sort Conversations": "排序对话",
"Sort Projects": "排序项目",
"Sort and filter conversations": "排序和筛选对话",
"Split Conversation Horizontally": "水平拆分对话",
"Split Conversation Vertically": "垂直拆分对话",
"Stage and commit all changes": "暂存并提交所有更改",
"Star": "星标",
"Starred": "已星标",
"Starred Conversations": "星标对话",
"Starting the conversation…": "正在开始对话…",
"Stop SSH Server…": "停止 SSH 服务器…",
"Successfully imported project:": "成功导入项目:",
"Tab Gitignore Access": "Tab Gitignore 访问权限",
"Tab Speed": "Tab 速度",
"Tab to Import": "按 Tab 导入",
"Tab to Jump": "按 Tab 跳转",
"Tabs": "标签页",
"Text color of the current search match.": "当前搜索匹配项的文本颜色。",
"Text file size exceeds 1MB limit": "文本文件大小超过 1MB 限制",
"The Google3 project is deprecated": "该 Google3 项目已弃用",
"The app is currently connected to a WSL distro. Reopening locally relaunches it directly on Windows.": "应用当前已连接到 WSL 发行版。在本地重新打开将直接在 Windows 上重新启动应用。",
"The conversation could not be loaded because its data was not found.": "找不到对话数据,无法加载该对话。",
"The conversation was compacted while generating this response.": "生成此回复时对话已压缩。",
"The main conversation's input isn't available right now.": "主对话的输入框当前不可用。",
"The remote shared a link for this push.": "远程仓库为此推送分享了一个链接。",
"Then create the project in its window.": "然后在其窗口中创建项目。",
"This chat is archived.": "此对话已归档。",
"This conversation grew too large, so the history before this point may be missing or incomplete.": "此对话过长,因此在此之前的历史记录可能缺失或不完整。",
"This conversation is also open in another app. Sending messages from both may cause conflicts.": "此对话也已在另一个应用中打开。同时从两端发送消息可能会导致冲突。",
"This conversation is not on disk. Delete it to remove it from your sidebar.": "此对话不在磁盘上。删除后即可将其从侧边栏中移除。",
"This page is taking longer than expected to load, or it may be blocking embedded views (via X-Frame-Options or CSP). We'll keep waiting, or you can open it directly in a new tab.": "此页面加载时间超出预期,或者可能禁止了嵌入式视图(通过 X-Frame-Options 或 CSP)。我们将继续等待,您也可以直接在新标签页中打开。",
"This project was created for": "此项目的创建目标为",
"This side question isn't available in this conversation.": "此支线问题在此对话中不可用。",
"Timed out fetching the Google Drive file's title. The link was kept as-is.": "获取 Google Drive 文件标题超时。链接已按原样保留。",
"Toggle File Viewer": "切换文件查看器",
"Toggle Google Cloud projects": "切换 Google Cloud 项目",
"Toggle Project Selector": "切换项目选择器",
"Toggle Sidebar": "切换侧边栏",
"Toggle Sidebar, conversations need attention": "切换侧边栏,有对话需要关注",
"Toggle if a confirmation is shown when using the \"Reload Window\" button.": "切换使用“重新加载窗口”按钮时是否显示确认提示。",
"Toggle sidebar": "切换侧边栏",
"Top-level \"||\" cannot mix different indexed dimensions across branches; every branch of \"||\" must constrain principal roles or the same resource dimension, or combine them with \"&&\"": "顶层 \"||\" 不能跨分支混用不同的索引维度;\"||\" 的每个分支必须约束主体角色或同一资源维度,或者使用 \"&&\" 进行组合",
"Trusted Folders": "受信任文件夹",
"Type absolute path or navigate folders...": "输入绝对路径或浏览文件夹...",
"Type to search file contents": "输入以搜索文件内容",
"Unarchive the main conversation to insert": "取消归档主对话以插入",
"Unknown Project": "未知项目",
"Unknown file edit": "未知文件编辑",
"Unpin Tab": "取消固定标签页",
"Unpin This Conversation": "取消固定此对话",
"Unpin conversation": "取消固定对话",
"Unsupported core-js use. Try https://npms.io/search?q=ponyfill.": "不支持的 core-js 用法。请尝试 https://npms.io/search?q=ponyfill。",
"Unsupported file format": "不支持的文件格式",
"Untitled Conversation": "无标题对话",
"Untitled project": "无标题项目",
"Updated sidebar grouping": "已更新侧边栏分组",
"Upload Files": "上传文件",
"Upload file": "上传文件",
"Uploaded files and connected resources are mounted in your cloud environment.": "已上传的文件和已连接的资源将挂载到您的云端环境中。",
"Use Google Cloud project instead": "改用 Google Cloud 项目",
"Use full Git clones for Best of N": "为 Best of N 使用完整 Git 克隆",
"Uses your local files and tools. Schedules only.": "使用您的本地文件和工具。仅限定时任务。",
"View File": "查看文件",
"View archived in the sidebar": "在侧边栏中查看已归档项",
"View archived in the sidebar (![filter](icon://filter_list) menu).": "在侧边栏中查看已归档项(![filter](icon://filter_list) 菜单)。",
"View archived in the sidebar (![tune](icon://tune) Customize Sidebar).": "在侧边栏中查看已归档项(![tune](icon://tune) 自定义侧边栏)。",
"View archived in the sidebar (Customize Sidebar).": "在侧边栏中查看已归档项(自定义侧边栏)。",
"View archived in the sidebar (Display options menu).": "在侧边栏中查看已归档项(显示选项菜单)。",
"Virtual File": "虚拟文件",
"Virtual File Viewer": "虚拟文件查看器",
"We'll keep waiting, or you can open it directly in a new tab.": "我们会继续等待,您也可以直接在新标签页中打开。",
"Web (desktop, remote control)": "Web(桌面端,远程控制)",
"Web (desktop, remote control, PWA)": "Web(桌面端,远程控制,PWA)",
"Web (mobile, remote control)": "Web(移动端,远程控制)",
"Web (mobile, remote control, PWA)": "Web(移动端,远程控制,PWA)",
"Web search prioritized results from": "网页搜索优先检索来自",
"When debug mode is on, you can see additional information about each steps in the conversation.": "开启调试模式后,您可以查看对话中每一步的更多详细信息。",
"When enabled, 'Explain and Fix' actions will continue in the current conversation instead of starting a new one.": "启用后,“解释并修复”操作将在当前对话中继续,而不会开启新对话。",
"Window": "窗口",
"Window X position": "窗口 X 坐标",
"Window Y position": "窗口 Y 坐标",
"Window height": "窗口高度",
"Window mode (0=Maximized, 1=Normal, 2=Fullscreen)": "窗口模式(0=最大化,1=正常,2=全屏)",
"Window width": "窗口宽度",
"Windows Subsystem for Linux": "适用于 Linux 的 Windows 子系统",
"Write Files": "写入文件",
"Write file": "写入文件",
"Write files": "写入文件",
"Yes, allow in this conversation": "是,在此对话中允许",
"Yes, always allow in this project": "是,在此项目中始终允许",
"Yes, and always allow in this conversation": "是,且在此对话中始终允许",
"You cannot sign out from Remote Control. Please sign out on your local application.": "无法从远程控制中退出登录。请在本地应用程序中退出登录。",
"You don't have access to this Google Drive file, so its title couldn't be added. The link was kept as-is.": "您无权访问此 Google 云端硬盘文件,因此无法添加其标题。链接已按原样保留。",
"You don't have any projects created. Please create a project first.": "您尚未创建任何项目。请先创建一个项目。",
"You have a conversation in progress. Updating will cancel it and you'll need to manually restart it.": "您当前有一个正在进行的对话。更新将会取消该对话,之后您需要手动重新开始。",
"You're viewing a local or shared file": "您正在查看本地文件或共享文件",
"Your Antigravity use will be associated with provided project.": "您的 Antigravity 使用记录将与所提供的项目关联。",
"Your existing conversations in CitC are grouped under a": "您在 CitC 中的现有对话已归入一个",
"Zip file size exceeds 20MB limit": "Zip 文件大小超出 20MB 限制",
"[Dev Mode] View full search results": "[开发模式] 查看完整搜索结果",
"[Dev] GCP Project ID": "[开发] GCP 项目 ID",
"combination of folders": "文件夹组合",
"cumulative total for the conversation up to this point": "截至当前对话的累计总量",
"drag it back in from the small window.": "从小窗口将其拖回。",
"e.g., /path/to/file": "例如:/path/to/file",
"files": "文件",
"filter": "筛选",
"folder": "文件夹",
"on for this conversation": "在此对话中开启",
"project": "项目",
"projects": "项目",
"search": "搜索",
"to any content or files that you upload, including content of minors. Don't generate content that infringes on others' rights, including content that deceives, harasses, or harms. When using Antigravity, you must comply with Google's": ",涵盖您上传的任何内容或文件(包括涉及未成年人的内容)。请勿生成侵犯他人权利的内容,包括欺骗、骚扰或伤害他人的内容。使用 Antigravity 时,您必须遵守 Google 的",
"view full search results": "查看完整搜索结果",
"~/.ssh/config (default)": "~/.ssh/config (默认)"
},
"light": {
". Active workspace URI:": "。当前 Workspace URI:",
". Applying or clearing reloads the window. Suggestions come from your recent workspaces and the folders of your existing projects and their environments": "。应用或清除会重新加载窗口。建议来自您最近的 Workspace 以及现有项目及其环境的文件夹",
"A full copy of this workspace, uncommitted changes included.": "此 Workspace 的完整副本,包含未提交的更改。",
"ABFS Workspace (Alpha)": "ABFS Workspace (Alpha)",
"ABFS branch name": "ABFS Branch 名称",
"ABFS is required to create ABFS workspaces. Please visit": "创建 ABFS Workspace 需要先安装 ABFS。请访问",
"ABFS workspace creation feature is not available.": "ABFS Workspace 创建功能不可用。",
"ABFS workspace creation is not available in this environment.": "在此环境中无法创建 ABFS Workspace。",
"ABFS workspace name": "ABFS Workspace 名称",
"Add Workspace": "添加 Workspace",
"All Workspaces": "所有 Workspace",
"All changes since the branch point": "自 Branch 分叉点以来的所有更改",
"Archive Workspace": "归档 Workspace",
"Are you sure you want to delete the workspace": "确定要删除该 Workspace",
"Automated safeguards help to protect your conversations from insecure or unsafe content. That being said, users should be aware of potential agentic risks, including data exfiltration.": "自动化安全防护有助于保护您的对话免受不安全或有害内容的影响。但尽管如此,用户仍需留意潜在的 Agent 相关风险,包括数据泄露。",
"Available workspaces": "可用的 Workspace",
"Branch": "Branch",
"Branch / Ref": "Branch / Ref",
"Branch Changes": "Branch 更改",
"Branch actions": "Branch 操作",
"Branch name cannot start with a dash": "Branch 名称不能以连字符开头",
"Branch names": "Branch 名称",
"CitC Workspace": "CitC Workspace",
"CitC Workspace Type": "CitC Workspace 类型",
"CitC workspace paths are world-readable and permanently snapshotted. Choose a local folder outside CitC.": "CitC Workspace 路径对所有人可读且会永久快照。请选择 CitC 之外的本地文件夹。",
"CitC workspace type": "CitC Workspace 类型",
"Citc workspace name": "CitC Workspace 名称",
"Clone current workspace into a new independent workspace": "将当前 Workspace 克隆为新的独立 Workspace",
"Cog Workspace": "Cog Workspace",
"Cog workspace creation failed.": "Cog Workspace 创建失败。",
"Cog workspace creation is not available in this environment.": "Cog Workspace 创建在此环境中不可用。",
"Cog workspace feature provider not found": "未找到 Cog Workspace 功能提供程序",
"Collapse Diffs": "折叠 Diff",
"Commit": "Commit",
"Commit Changes": "Commit 变更",
"Commit staged changes": "Commit 已暂存的更改",
"Commit succeeded": "Commit 成功",
"Configure Branches": "配置 Branch",
"Continue in Current Workspace": "在当前 Workspace 中继续",
"Continue in New Workspace": "在新 Workspace 中继续",
"Continue in Shared Workspace": "在共享 Workspace 中继续",
"Could not create Cog workspace": "无法创建 Cog Workspace",
"Couldn't load branches": "无法加载 Branch",
"Create ABFS Workspace (Alpha)": "创建 ABFS Workspace (Alpha)",
"Create Branch": "创建 Branch",
"Create CitC Workspace": "创建 CitC Workspace",
"Create Cog Workspace": "创建 Cog Workspace",
"Create Commit": "创建 Commit",
"Create Pull Request": "创建 Pull Request",
"Create a Fig shared workspace": "创建 Fig 共享 Workspace",
"Create a new project using normal folders and/or citc workspaces.": "使用普通文件夹和/或 CitC Workspace 创建新项目。",
"Created a new branch on GitHub.": "已在 GitHub 上创建新 Branch。",
"Created a new branch on Origin.": "已在 Origin 上创建新 Branch。",
"Creating commit...": "正在创建 Commit...",
"Creating workspace for the forked conversation...": "正在为派生对话创建 Workspace...",
"Current Workspace": "当前 Workspace",
"Current workspace": "当前 Workspace",
"Default Cog Branch / Ref": "默认 Cog Branch / Ref",
"Default Cog branch / ref": "默认 Cog Branch / Ref",
"Default Workspace VCS": "默认 Workspace VCS",
"Default workspace VCS": "默认 Workspace VCS",
"Delete ABFS Workspace": "删除 ABFS Workspace",
"Delete workspace": "删除 Workspace",
"DevTools port is still closed. Please make sure Chrome is running with remote debugging enabled.": "DevTools 端口仍处于关闭状态。请确保 Chrome 正在运行并已启用远程调试。",
"Diff contents are no longer available.": "Diff 内容已不再可用。",
"Diff overview ruler foreground for inserted content.": "已插入内容的 Diff 概览标尺前景色。",
"Diff overview ruler foreground for removed content.": "已删除内容的 Diff 概览标尺前景色。",
"Enter workspace name (e.g., my-cog-feature)": "输入 Workspace 名称(例如 my-cog-feature)",
"Enter workspace name (e.g., my-feature)": "输入 Workspace 名称(例如 my-feature)",
"Expand Diffs": "展开 Diff",
"Failed to Commit": "Commit 失败",
"Failed to create CitC clone workspace": "创建 CitC 克隆 Workspace 失败",
"Failed to create new workspace": "创建新 Workspace 失败",
"Failed to create workspace.": "创建 Workspace 失败。",
"Failed to fetch diffs": "获取 Diff 失败",
"Failed to load diff contents.": "加载 Diff 内容失败。",
"Failed to load diff.": "加载 Diff 失败。",
"Failed to load some diffs": "加载部分 Diff 失败",
"Failed to open created workspace": "打开已创建的 Workspace 失败",
"File Diff Comments": "文件 Diff 评论",
"Files and resources in cloud workspaces": "云端 Workspace 中的文件和资源",
"Fork in Current Workspace": "在当前 Workspace 中派生",
"Fork in New Workspace": "在新 Workspace 中派生",
"Fork in Shared Workspace": "在共享 Workspace 中派生",
"Found in This Workspace": "在此 Workspace 中找到",
"Git Branch": "Git Branch",
"Git commit": "Git Commit",
"Give each Best of N fork a full clone of your workspace, including its local commit history. Choosing a winner then gives your workspace that fork's state, so the commits it made are kept. Forks take longer to create than the default CitC clone. See go/jetski-best-of-n.": "为每个 Best of N 派生副本提供 Workspace 的完整克隆(包括本地 Commit 历史记录)。选定胜出者后,您的 Workspace 将应用该派生副本的状态,因此其产生的 Commit 会被保留。创建派生副本比默认的 CitC 克隆耗时更长。请参阅 go/jetski-best-of-n。",
"Give each Best of N fork its own clone of your Git repository instead of a copy-on-write overlay. Each fork is then a real repository, so commits it makes are kept when you choose it as the winner. Forks take longer to create, and the wait grows with the size of your repository. See go/jetski-best-of-n.": "为每个 Best of N 派生副本提供 Git 仓库的独立克隆,而非写时复制叠加层。这样每个派生副本都是一个真实的仓库,当您将其选为胜出者时,它产生的 Commit 会被保留。派生副本创建耗时更长,且等待时间随仓库大小增长。请参阅 go/jetski-best-of-n。",
"Google3 chats will be regrouped into their workspaces in the sidebar.": "Google3 对话将在侧边栏中重新归组到各自的 Workspace 下。",
"Google3 projects are being deprecated. Select a CitC workspace instead.": "Google3 项目即将弃用,请改用 CitC Workspace。",
"Grant read access to workflow runs and allow dispatching workflows on specific files and refs.": "授予 Workflow 运行的读取权限,并允许在特定文件和引用上调度 Workflow。",
"Grant the selected actions on the listed branch names — a comma-separated list like main, dev, prod (glob patterns like fix-* allowed), or * for all.": "对列出的 Branch 名称授予所选操作——以逗号分隔的列表,例如 main、dev、prod(允许使用 fix-* 等 glob 模式),或使用 * 表示全部。",
"Grant the selected actions on the listed pull request numbers — a comma-separated list like 1, 2, 3, or * for all.": "对列出的 Pull Request 编号授予所选操作——以逗号分隔的列表,例如 1、2、3,或使用 * 表示全部。",
"Group By Workspace": "按 Workspace 分组",
"Hide Diff": "隐藏 Diff",
"Inspected commit": "已检查的 Commit",
"Invalid branch or ref format": "无效的 Branch 或引用格式",
"Keeps working in this workspace. Nothing is copied.": "继续在此 Workspace 中工作。不会复制任何内容。",
"Last Workspace": "上一个 Workspace",
"Loading branches…": "正在加载 Branch…",
"Loading workspace customizations...": "正在加载 Workspace 自定义项...",
"Name workspace...": "命名 Workspace...",
"New Fig Workspace": "新建 Fig Workspace",
"New Workspace": "新建 Workspace",
"New chats will be grouped by workspace.": "新对话将按 Workspace 分组。",
"New conversations in CitC will be grouped by distinct workspace.": "CitC 中的新对话将按不同的 Workspace 分组。",
"No branches": "无 Branch",
"No branches found": "未找到任何 Branch",
"No commit to amend": "没有可修订的 Commit",
"No commits to push": "没有可推送的 Commit",
"No workspace window available": "没有可用的 Workspace 窗口",
"No workspaces found": "未找到 Workspace",
"No workspaces open.": "未打开任何 Workspace。",
"Not on a branch": "当前不在任何 Branch 上",
"Open Commit Graph": "打开 Commit 图谱",
"Open Diff": "打开 Diff",
"Open Pull Request": "打开 Pull Request",
"Open Workspace": "打开 Workspace",
"Open Workspace Selector": "打开 Workspace 选择器",
"Open a pull request": "打开 Pull Request",
"Optional branch or ref used when creating a new Cog workspace (defaults to main if unset).": "创建新 Cog Workspace 时使用的可选 Branch 或引用(未设置时默认为 main)。",
"Parent workspace not found for this battle.": "未找到此对战的父 Workspace。",
"Pull request actions": "Pull Request 操作",
"Pull request creation": "创建 Pull Request",
"Pull request numbers": "Pull Request 编号",
"Push Branch": "推送 Branch",
"Read access to code, refs, commits, and other repository contents.": "对代码、引用、Commit 及其他仓库内容的读取权限。",
"Remote SSH": "Remote SSH",
"Remote branch": "远程 Branch",
"Remote branches": "远程 Branch",
"Remount workspace": "重新挂载 Workspace",
"Reuse your last workspace.": "复用上次使用的 Workspace。",
"Review Diff": "查看 Diff",
"Run in a new jj workspace or Fig share": "在新的 jj Workspace 或 Fig share 中运行",
"Run in your current workspace": "在当前 Workspace 中运行",
"Search Recent Workspaces": "搜索最近的 Workspace",
"Search Workspaces…": "搜索 Workspace…",
"Search branches": "搜索 Branch",
"Search past workspaces...": "搜索历史 Workspace...",
"Search workspace files": "搜索 Workspace 文件",
"Search workspace folders": "搜索 Workspace 文件夹",
"Search workspaces...": "搜索 Workspace...",
"Select ABFS Workspace (Alpha)": "选择 ABFS Workspace (Alpha)",
"Select CitC Workspace": "选择 CitC Workspace",
"Select CitC workspace": "选择 CitC Workspace",
"Select Cog Workspace": "选择 Cog Workspace",
"Select Default Branch": "选择默认 Branch",
"Select branch": "选择 Branch",
"Select or enter a workspace URI": "选择或输入 Workspace URI",
"Select the workspace type that will be used for new conversations started with the New Workspace option.": "选择使用“新建 Workspace”选项启动新对话时所用的 Workspace 类型。",
"Select workspace": "选择 Workspace",
"Sets the `workspaceUri` URL parameter and reloads, repointing the active workspace. Pick a folder from an existing project or enter a custom URI (e.g. file:///path/to/workspace).": "设置 `workspaceUri` URL 参数并重新加载,以重新指向当前活动的 Workspace。请从现有项目中选择一个文件夹,或输入自定义 URI(例如 file:///path/to/workspace)。",
"Show Diff": "显示 Diff",
"Show temporary and forked workspaces": "显示临时和复刻的 Workspace",
"Sidebar grouped by workspace": "侧边栏按 Workspace 分组",
"Stage and amend all changes into the current commit": "暂存所有更改并修补到当前 Commit",
"Start without a workspace, for general questions.": "不使用 Workspace 直接开始,适用于一般性问题。",
"Switch IDE Workspace": "切换 IDE Workspace",
"Switch Workspace": "切换 Workspace",
"Switch branch": "切换 Branch",
"The branch was pushed to GitLab.": "已将该 Branch 推送到 GitLab。",
"The remote workspace is not running": "远程 Workspace 未运行",
"This conversation is in a different workspace.": "此对话位于另一个 Workspace 中。",
"This is a CitC workspace (Fig share)": "这是一个 CitC Workspace(Fig 共享)",
"This project is associated with a different workspace.": "此项目关联了另一个 Workspace。",
"Toggle file diff": "切换文件 Diff",
"True changes vs the parent workspace": "相对于父 Workspace 的真实变更",
"Try selecting a different workspace.": "请尝试选择其他 Workspace。",
"Undo restores your entire workspace to its state at this point.": "撤销会将整个 Workspace 恢复到此时刻的状态。",
"Unmount workspace": "卸载 Workspace",
"View Branches": "查看 Branch",
"View Diff": "查看 Diff",
"View Split Diff": "查看并排 Diff",
"View Stacked Diff": "查看堆叠 Diff",
"Viewing Diff": "正在查看 Diff",
"Want to re-group your old conversations by workspace? They can be": "想要按 Workspace 重新分组旧对话吗?它们可以",
"Work in Google3. Create conversations in new and existing workspaces.": "在 Google3 中工作。在新建和现有的 Workspace 中创建对话。",
"Work in a CitC workspace.": "在 CitC Workspace 中工作。",
"Work in a Cog workspace.": "在 Cog Workspace 中工作。",
"Work in an ABFS workspace.": "在 ABFS Workspace 中工作。",
"Workflow files": "Workflow 文件",
"Workspace": "Workspace",
"Workspace > Restore to Snapshot": "Workspace > 恢复到快照",
"Workspace Command Access": "Workspace 命令访问权限",
"Workspace Creation": "Workspace 创建",
"Workspace File Access": "Workspace 文件访问权限",
"Workspace File Explorer": "Workspace 文件资源管理器",
"Workspace Name": "Workspace 名称",
"Workspace URI Switcher": "Workspace URI 切换器",
"Workspace URI not found": "未找到 Workspace URI",
"Workspace URI query parameter": "Workspace URI 查询参数",
"Workspace URI to switch to": "要切换到的 Workspace URI",
"Workspace Web Access": "Workspace Web 访问",
"Workspace folder suggestions": "Workspace 文件夹建议",
"Workspace mismatch actions": "Workspace 不匹配操作",
"Workspace name can only contain letters, numbers, underscores, and dashes": "Workspace 名称只能包含字母、数字、下划线和连字符",
"Workspace name cannot be empty": "Workspace 名称不能为空",
"Workspace name cannot start with a dash": "Workspace 名称不能以连字符开头",
"Workspace setup warning": "Workspace 设置警告",
"Workspaces": "Workspaces",
"Yes, and always allow in this workspace": "是,且在此 Workspace 中始终允许",
"cogfsd and cidermux are required to create Cog workspaces. Please visit": "创建 Cog Workspace 需要 cogfsd 和 cidermux。请访问",
"the current workspace": "当前 Workspace",
"workspace.": "Workspace。"
},
"deep": {
". Active workspace URI:": "。当前工作区 URI:",
". Applying or clearing reloads the window. Suggestions come from your recent workspaces and the folders of your existing projects and their environments": "。应用或清除会重新加载窗口。建议来自您最近的工作区以及现有项目及其环境的文件夹",
"A full copy of this workspace, uncommitted changes included.": "此工作区的完整副本,包含未提交的更改。",
"ABFS Workspace (Alpha)": "ABFS 工作区 (Alpha)",
"ABFS branch name": "ABFS 分支名称",
"ABFS is required to create ABFS workspaces. Please visit": "创建 ABFS 工作区需要先安装 ABFS。请访问",
"ABFS workspace creation feature is not available.": "ABFS 工作区创建功能不可用。",
"ABFS workspace creation is not available in this environment.": "在此环境中无法创建 ABFS 工作区。",
"ABFS workspace name": "ABFS 工作区名称",
"Add Workspace": "添加工作区",
"All Workspaces": "所有工作区",
"All changes since the branch point": "自分支分叉点以来的所有更改",
"Archive Workspace": "归档工作区",
"Are you sure you want to delete the workspace": "确定要删除该工作区",
"Automated safeguards help to protect your conversations from insecure or unsafe content. That being said, users should be aware of potential agentic risks, including data exfiltration.": "自动化安全防护有助于保护您的对话免受不安全或有害内容的影响。但尽管如此,用户仍需留意潜在的智能体风险,包括数据泄露。",
"Available workspaces": "可用的工作区",
"Branch": "分支",
"Branch / Ref": "分支 / 引用",
"Branch Changes": "分支更改",
"Branch actions": "分支操作",
"Branch name cannot start with a dash": "分支名称不能以连字符开头",
"Branch names": "分支名称",
"CitC Workspace": "CitC 工作区",
"CitC Workspace Type": "CitC 工作区类型",
"CitC workspace paths are world-readable and permanently snapshotted. Choose a local folder outside CitC.": "CitC 工作区路径对所有人可读且会永久快照。请选择 CitC 之外的本地文件夹。",
"CitC workspace type": "CitC 工作区类型",
"Citc workspace name": "CitC 工作区名称",
"Clone current workspace into a new independent workspace": "将当前工作区克隆为新的独立工作区",
"Cog Workspace": "Cog 工作区",
"Cog workspace creation failed.": "Cog 工作区创建失败。",
"Cog workspace creation is not available in this environment.": "Cog 工作区创建在此环境中不可用。",
"Cog workspace feature provider not found": "未找到 Cog 工作区功能提供程序",
"Collapse Diffs": "折叠变更对比",
"Commit": "提交",
"Commit Changes": "提交变更",
"Commit staged changes": "提交已暂存的更改",
"Commit succeeded": "提交成功",
"Configure Branches": "配置分支",
"Continue in Current Workspace": "在当前工作区中继续",
"Continue in New Workspace": "在新工作区中继续",
"Continue in Shared Workspace": "在共享工作区中继续",
"Could not create Cog workspace": "无法创建 Cog 工作区",
"Couldn't load branches": "无法加载分支",
"Create ABFS Workspace (Alpha)": "创建 ABFS 工作区 (Alpha)",
"Create Branch": "创建分支",
"Create CitC Workspace": "创建 CitC 工作区",
"Create Cog Workspace": "创建 Cog 工作区",
"Create Commit": "创建提交",
"Create Pull Request": "创建拉取请求",
"Create a Fig shared workspace": "创建 Fig 共享工作区",
"Create a new project using normal folders and/or citc workspaces.": "使用普通文件夹和/或 CitC 工作区创建新项目。",
"Created a new branch on GitHub.": "已在 GitHub 上创建新分支。",
"Created a new branch on Origin.": "已在 Origin 上创建新分支。",
"Creating commit...": "正在创建提交...",
"Creating workspace for the forked conversation...": "正在为派生对话创建工作区...",
"Current Workspace": "当前工作区",
"Current workspace": "当前工作区",
"Default Cog Branch / Ref": "默认 Cog 分支 / 引用",
"Default Cog branch / ref": "默认 Cog 分支 / 引用",
"Default Workspace VCS": "默认工作区 VCS",
"Default workspace VCS": "默认工作区 VCS",
"Delete ABFS Workspace": "删除 ABFS 工作区",
"Delete workspace": "删除工作区",
"DevTools port is still closed. Please make sure Chrome is running with remote debugging enabled.": "开发者工具端口仍处于关闭状态。请确保 Chrome 正在运行并已启用远程调试。",
"Diff contents are no longer available.": "变更对比内容已不再可用。",
"Diff overview ruler foreground for inserted content.": "已插入内容的变更对比概览标尺前景色。",
"Diff overview ruler foreground for removed content.": "已删除内容的变更对比概览标尺前景色。",
"Enter workspace name (e.g., my-cog-feature)": "输入工作区名称(例如 my-cog-feature)",
"Enter workspace name (e.g., my-feature)": "输入工作区名称(例如 my-feature)",
"Expand Diffs": "展开变更对比",
"Failed to Commit": "提交失败",
"Failed to create CitC clone workspace": "创建 CitC 克隆工作区失败",
"Failed to create new workspace": "创建新工作区失败",
"Failed to create workspace.": "创建工作区失败。",
"Failed to fetch diffs": "获取变更对比失败",
"Failed to load diff contents.": "加载变更对比内容失败。",
"Failed to load diff.": "加载变更对比失败。",
"Failed to load some diffs": "加载部分变更对比失败",
"Failed to open created workspace": "打开已创建的工作区失败",
"File Diff Comments": "文件变更对比评论",
"Files and resources in cloud workspaces": "云端工作区中的文件和资源",
"Fork in Current Workspace": "在当前工作区中派生",
"Fork in New Workspace": "在新工作区中派生",
"Fork in Shared Workspace": "在共享工作区中派生",
"Found in This Workspace": "在此工作区中找到",
"Git Branch": "Git 分支",
"Git commit": "Git 提交",
"Give each Best of N fork a full clone of your workspace, including its local commit history. Choosing a winner then gives your workspace that fork's state, so the commits it made are kept. Forks take longer to create than the default CitC clone. See go/jetski-best-of-n.": "为每个 Best of N 派生副本提供工作区的完整克隆(包括本地提交历史记录)。选定胜出者后,您的工作区将应用该派生副本的状态,因此其产生的提交会被保留。创建派生副本比默认的 CitC 克隆耗时更长。请参阅 go/jetski-best-of-n。",
"Give each Best of N fork its own clone of your Git repository instead of a copy-on-write overlay. Each fork is then a real repository, so commits it makes are kept when you choose it as the winner. Forks take longer to create, and the wait grows with the size of your repository. See go/jetski-best-of-n.": "为每个 Best of N 派生副本提供 Git 仓库的独立克隆,而非写时复制叠加层。这样每个派生副本都是一个真实的仓库,当您将其选为胜出者时,它产生的提交会被保留。派生副本创建耗时更长,且等待时间随仓库大小增长。请参阅 go/jetski-best-of-n。",
"Google3 chats will be regrouped into their workspaces in the sidebar.": "Google3 对话将在侧边栏中重新归组到各自的工作区下。",
"Google3 projects are being deprecated. Select a CitC workspace instead.": "Google3 项目即将弃用,请改用 CitC 工作区。",
"Grant read access to workflow runs and allow dispatching workflows on specific files and refs.": "授予工作流运行的读取权限,并允许在特定文件和引用上调度工作流。",
"Grant the selected actions on the listed branch names — a comma-separated list like main, dev, prod (glob patterns like fix-* allowed), or * for all.": "对列出的分支名称授予所选操作——以逗号分隔的列表,例如 main、dev、prod(允许使用 fix-* 等 glob 模式),或使用 * 表示全部。",
"Grant the selected actions on the listed pull request numbers — a comma-separated list like 1, 2, 3, or * for all.": "对列出的拉取请求编号授予所选操作——以逗号分隔的列表,例如 1、2、3,或使用 * 表示全部。",
"Group By Workspace": "按工作区分组",
"Hide Diff": "隐藏变更对比",
"Inspected commit": "已检查的提交",
"Invalid branch or ref format": "无效的分支或引用格式",
"Keeps working in this workspace. Nothing is copied.": "继续在此工作区中工作。不会复制任何内容。",
"Last Workspace": "上一个工作区",
"Loading branches…": "正在加载分支…",
"Loading workspace customizations...": "正在加载工作区自定义项...",
"Name workspace...": "命名工作区...",
"New Fig Workspace": "新建 Fig 工作区",
"New Workspace": "新建工作区",
"New chats will be grouped by workspace.": "新对话将按工作区分组。",
"New conversations in CitC will be grouped by distinct workspace.": "CitC 中的新对话将按不同的工作区分组。",
"No branches": "无分支",
"No branches found": "未找到任何分支",
"No commit to amend": "没有可修订的提交",
"No commits to push": "没有可推送的提交",
"No workspace window available": "没有可用的工作区窗口",
"No workspaces found": "未找到工作区",
"No workspaces open.": "未打开任何工作区。",
"Not on a branch": "当前不在任何分支上",
"Open Commit Graph": "打开提交图谱",
"Open Diff": "打开变更对比",
"Open Pull Request": "打开拉取请求",
"Open Workspace": "打开工作区",
"Open Workspace Selector": "打开工作区选择器",
"Open a pull request": "打开拉取请求",
"Optional branch or ref used when creating a new Cog workspace (defaults to main if unset).": "创建新 Cog 工作区时使用的可选分支或引用(未设置时默认为 main)。",
"Parent workspace not found for this battle.": "未找到此对战的父工作区。",
"Pull request actions": "拉取请求操作",
"Pull request creation": "创建拉取请求",
"Pull request numbers": "拉取请求编号",
"Push Branch": "推送分支",
"Read access to code, refs, commits, and other repository contents.": "对代码、引用、提交及其他仓库内容的读取权限。",
"Remote SSH": "SSH 远程连接",
"Remote branch": "远程分支",
"Remote branches": "远程分支",
"Remount workspace": "重新挂载工作区",
"Reuse your last workspace.": "复用上次使用的工作区。",
"Review Diff": "查看变更对比",
"Run in a new jj workspace or Fig share": "在新的 jj 工作区或 Fig share 中运行",
"Run in your current workspace": "在当前工作区中运行",
"Search Recent Workspaces": "搜索最近的工作区",
"Search Workspaces…": "搜索工作区…",
"Search branches": "搜索分支",
"Search past workspaces...": "搜索历史工作区...",
"Search workspace files": "搜索工作区文件",
"Search workspace folders": "搜索工作区文件夹",
"Search workspaces...": "搜索工作区...",
"Select ABFS Workspace (Alpha)": "选择 ABFS 工作区 (Alpha)",
"Select CitC Workspace": "选择 CitC 工作区",
"Select CitC workspace": "选择 CitC 工作区",
"Select Cog Workspace": "选择 Cog 工作区",
"Select Default Branch": "选择默认分支",
"Select branch": "选择分支",
"Select or enter a workspace URI": "选择或输入工作区 URI",
"Select the workspace type that will be used for new conversations started with the New Workspace option.": "选择使用“新建工作区”选项启动新对话时所用的工作区类型。",
"Select workspace": "选择工作区",
"Sets the `workspaceUri` URL parameter and reloads, repointing the active workspace. Pick a folder from an existing project or enter a custom URI (e.g. file:///path/to/workspace).": "设置 `workspaceUri` URL 参数并重新加载,以重新指向当前活动的工作区。请从现有项目中选择一个文件夹,或输入自定义 URI(例如 file:///path/to/workspace)。",
"Show Diff": "显示变更对比",
"Show temporary and forked workspaces": "显示临时和复刻的工作区",
"Sidebar grouped by workspace": "侧边栏按工作区分组",
"Stage and amend all changes into the current commit": "暂存所有更改并修补到当前提交",
"Start without a workspace, for general questions.": "不使用工作区直接开始,适用于一般性问题。",
"Switch IDE Workspace": "切换 IDE 工作区",
"Switch Workspace": "切换工作区",
"Switch branch": "切换分支",
"The branch was pushed to GitLab.": "已将该分支推送到 GitLab。",
"The remote workspace is not running": "远程工作区未运行",
"This conversation is in a different workspace.": "此对话位于另一个工作区中。",
"This is a CitC workspace (Fig share)": "这是一个 CitC 工作区(Fig 共享)",
"This project is associated with a different workspace.": "此项目关联了另一个工作区。",
"Toggle file diff": "切换文件变更对比",
"True changes vs the parent workspace": "相对于父工作区的真实变更",
"Try selecting a different workspace.": "请尝试选择其他工作区。",
"Undo restores your entire workspace to its state at this point.": "撤销会将整个工作区恢复到此时刻的状态。",
"Unmount workspace": "卸载工作区",
"View Branches": "查看分支",
"View Diff": "查看变更对比",
"View Split Diff": "查看并排变更对比",
"View Stacked Diff": "查看堆叠变更对比",
"Viewing Diff": "正在查看变更对比",
"Want to re-group your old conversations by workspace? They can be": "想要按工作区重新分组旧对话吗?它们可以",
"Work in Google3. Create conversations in new and existing workspaces.": "在 Google3 中工作。在新建和现有的工作区中创建对话。",
"Work in a CitC workspace.": "在 CitC 工作区中工作。",
"Work in a Cog workspace.": "在 Cog 工作区中工作。",
"Work in an ABFS workspace.": "在 ABFS 工作区中工作。",
"Workflow files": "工作流文件",
"Workspace": "工作区",
"Workspace > Restore to Snapshot": "工作区 > 恢复到快照",
"Workspace Command Access": "工作区命令访问权限",
"Workspace Creation": "工作区创建",
"Workspace File Access": "工作区文件访问权限",
"Workspace File Explorer": "工作区文件资源管理器",
"Workspace Name": "工作区名称",
"Workspace URI Switcher": "工作区 URI 切换器",
"Workspace URI not found": "未找到工作区 URI",
"Workspace URI query parameter": "工作区 URI 查询参数",
"Workspace URI to switch to": "要切换到的工作区 URI",
"Workspace Web Access": "工作区 Web 访问",
"Workspace folder suggestions": "工作区文件夹建议",
"Workspace mismatch actions": "工作区不匹配操作",
"Workspace name can only contain letters, numbers, underscores, and dashes": "工作区名称只能包含字母、数字、下划线和连字符",
"Workspace name cannot be empty": "工作区名称不能为空",
"Workspace name cannot start with a dash": "工作区名称不能以连字符开头",
"Workspace setup warning": "工作区设置警告",
"Workspaces": "工作区",
"Yes, and always allow in this workspace": "是,且在此工作区中始终允许",
"cogfsd and cidermux are required to create Cog workspaces. Please visit": "创建 Cog 工作区需要 cogfsd 和 cidermux。请访问",
"the current workspace": "当前工作区",
"workspace.": "工作区。"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,517 @@
{
"base": {
"? This will remove it from your MCP configuration.": "?这会将其从您的 MCP 配置中移除。",
"A Cytoscape container has style position:static and so can not use UI extensions properly": "Cytoscape 容器的样式为 position:static,因此无法正常使用 UI 扩展",
"Add MCP": "添加 MCP",
"Browse Connectors": "浏览连接器",
"Browse MCP resources": "浏览 MCP 资源",
"CSS variable keys available to MCP apps for theming.": "可供 MCP 应用用于主题定制的 CSS 变量键。",
"Connectors": "连接器",
"Could not determine MCP config file path": "无法确定 MCP 配置文件路径",
"Could not determine MCP config file path. Please check your home directory settings.": "无法确定 MCP 配置文件路径。请检查您的主目录设置。",
"Could not read MCP config file": "无法读取 MCP 配置文件",
"Error while running MCP tool": "运行 MCP 工具时出错",
"Extension": "扩展",
"Extension %s used as a dependency before build": "扩展 %s 在构建前被用作依赖项",
"Extension (Antigravity IDE)": "扩展 (Antigravity IDE)",
"Extension (Cider)": "扩展 (Cider)",
"Extension (Eclipse)": "扩展 (Eclipse)",
"Extension (VS Code)": "扩展 (VS Code)",
"Extension (Visual Studio)": "扩展 (Visual Studio)",
"Extension Is Loading": "正在加载扩展",
"Extensions": "扩展",
"Failed to load hooks.json:": "加载 hooks.json 失败:",
"Failed to open MCP config file": "打开 MCP 配置文件失败",
"Failed to save hooks.json:": "保存 hooks.json 失败:",
"HTML extension is disabled on strict mode": "严格模式下已禁用 HTML 扩展",
"Invalid extension access syntax": "无效的扩展访问语法",
"LexicalBuilder: A registered extension with name %s exists but does not match the given extension": "LexicalBuilder:已存在名为 %s 的已注册扩展,但与给定扩展不匹配",
"Loading connectors…": "正在加载连接器…",
"MCP": "MCP",
"MCP App": "MCP 应用",
"MCP Authentication Error:": "MCP 身份验证错误:",
"MCP Config": "MCP 配置",
"MCP Configuration Error:": "MCP 配置错误:",
"MCP Install Error:": "MCP 安装错误:",
"MCP Restart Error:": "MCP 重启错误:",
"MCP Tools": "MCP 工具",
"MCP error": "MCP 错误",
"MCP tools": "MCP 工具",
"Manage MCP": "管理 MCP",
"No OAuth token (user not logged in)": "无 OAuth 令牌(用户未登录)",
"No connectors available in this project": "此项目中无可用连接器",
"No extensions available": "无可用扩展",
"No method available to open MCP config file": "没有可用于打开 MCP 配置文件的方法",
"OAuth token information": "OAuth 令牌信息",
"Open MCP Config": "打开 MCP 配置",
"Search connectors": "搜索连接器",
"Simulate a different host (Electron, desktop or mobile Web, Extension, remote control, or installed PWA).": "模拟不同的宿主环境(Electron、桌面或移动 Web、扩展程序、远程控制或已安装的 PWA)。",
"Start Extension": "启动扩展",
"There is already an extension with this id": "已存在具有此 ID 的扩展",
"This extension has no declared permissions requiring user input.": "此扩展未声明需要用户输入信息的权限。",
"This extension is currently stopped. Events and stdout streams will appear here once started.": "此扩展当前已停止。启动后,事件和 stdout 流将显示在此处。",
"UI Extensions": "UI 扩展",
"UI extensions": "UI 扩展",
"Use Add MCP to browse the store, or add a custom server via the MCP config.": "使用“添加 MCP”浏览商店,或通过 MCP 配置添加自定义服务器。",
"Use Add MCP to browse the store.": "使用“添加 MCP”浏览商店。",
"Used MCP tool": "已使用 MCP 工具"
},
"light": {
"+ Add Hook": "+ 添加 Hook",
". Learn more about skills at": "。了解有关 Skill 的更多信息,请访问",
"Active Skills": "已启用的 Skill",
"Add Hook Card": "添加 Hook 卡片",
"Add MCP Server": "添加 MCP Server",
"Add MCP Servers": "添加 MCP Server",
"Add Plugin": "添加 Plugin",
"Add Skill": "添加 Skill",
"Agent Hooks Configuration": "Agent Hook 配置",
"Agent Marketplace": "Agent Marketplace",
"Are you sure you want to delete this hook card?": "确定要删除此 Hook 卡片吗?",
"Base UI calls `render` as a plain function, which can break the Rules of Hooks during reconciliation.": "Base UI 将 `render` 作为普通函数调用,这可能会在协调过程中违反 Rules of Hooks。",
"Browse Plugins": "浏览 Plugins",
"Browse Skills": "浏览 Skills",
"Browse and enable plugins from the Build With Google catalog.": "浏览并启用 Build With Google 目录中的 Plugin。",
"Browse the Marketplace": "浏览 Marketplace",
"Build With Google Plugins": "Build With Google Plugin",
"Build With Google plugins": "Build With Google Plugin",
"Changes plugins can make without asking.": "Plugin 无需询问即可进行的更改。",
"Close Sidecar": "关闭 Sidecar",
"Close skills panel": "关闭 Skill 面板",
"Configure MCP Server": "配置 MCP Server",
"Configure default behaviors, skills, and MCP servers.": "配置默认行为、Skill 和 MCP Server。",
"Configure hooks that run on agent lifecycle events.": "配置在 Agent 生命周期事件上运行的 Hook。",
"Could not determine plugin config file path": "无法确定 Plugin 配置文件路径",
"Couldn't load the suggested plugin.": "无法加载推荐的 Plugin。",
"Create Plugin": "创建 Plugin",
"Create Skill": "创建 Skill",
"Create a Plugin with the Agent": "使用 Agent 创建 Plugin",
"Create plugin": "创建 Plugin",
"Creating Sidecar": "正在创建 Sidecar",
"Curated sets of plugins for common workflows and roles.": "针对常见 Workflow 和角色的精选 Plugin 集合。",
"Customizations & Skills": "自定义配置与 Skill",
"Customize Global Skills": "自定义全局 Skill",
"Customize your experience across the agent, plugins, and product from the settings and marketplace. We won’t show you ads or let advertisers influence what": "在设置和 Marketplace 中自定义你在 Agent、Plugin 和产品中的体验。我们不会向你展示广告,也不会让广告商影响",
"Delete Hook": "删除 Hook",
"Delete MCP Server": "删除 MCP Server",
"Delete Skill": "删除 Skill",
"Delete plugin": "删除 Plugin",
"Disabled. Open the plugin page to finish setup.": "已禁用。打开 Plugin 页面以完成设置。",
"Discover helpful skills & plugins": "发现实用的 Skill 和 Plugin",
"Each plugin can be managed on its own.": "每个 Plugin 都可以单独管理。",
"Enable Recommended Skills": "启用推荐的 Skill",
"Enable recommended skills": "启用推荐的 Skill",
"Enable the plugin to sign in.": "启用该 Plugin 以登录。",
"Enable this plugin to manage its accounts.": "启用此 Plugin 以管理其账号。",
"Encountered an error while running the plugin.": "运行 Plugin 时遇到错误。",
"Enter the configuration values this MCP server needs. Saving restarts the server with them.": "输入此 MCP Server 所需的配置值。保存后将使用这些配置重启服务。",
"Enter the required configuration values to install this MCP server.": "输入安装此 MCP Server 所需的配置值。",
"Error fetching MCP prompt": "获取 MCP Prompt 出错",
"Explore other marketplace customizations": "探索其他 Marketplace 自定义项",
"Explore the plugin marketplace": "探索 Plugin Marketplace",
"Failed to add plugin.": "添加 Plugin 失败。",
"Failed to add plugin. Please try again.": "添加 Plugin 失败,请重试。",
"Failed to delete plugin.": "删除 Plugin 失败。",
"Failed to delete plugin. Please try again.": "删除 Plugin 失败,请重试。",
"Failed to delete skill.": "删除 Skill 失败。",
"Failed to delete skill. Please try again.": "删除 Skill 失败,请重试。",
"Failed to determine plugin ID": "确定 Plugin ID 失败",
"Failed to determine plugin install directory": "确定 Plugin 安装目录失败",
"Failed to download Firebase skill.": "下载 Firebase Skill 失败。",
"Failed to load MCP servers": "加载 MCP Server 失败",
"Failed to load marketplace bundles. Please try again.": "加载 Marketplace 捆绑包失败,请重试。",
"Failed to load more plugins. Please try again.": "加载更多 Plugin 失败,请重试。",
"Failed to load plugin. Please try again.": "加载 Plugin 失败,请重试。",
"Failed to load plugins": "加载 Plugin 失败",
"Failed to load plugins. Please try again.": "加载 Plugin 失败,请重试。",
"Failed to load skills paths:": "加载 Skill 路径失败:",
"Failed to load skills:": "加载 Skill 失败:",
"Failed to open plugin config file": "打开 Plugin 配置文件失败",
"Failed to scan skills config file:": "扫描 Skill 配置文件失败:",
"Failed to toggle plugin. Please try again.": "切换 Plugin 状态失败,请重试。",
"Filter plugins": "筛选 Plugin",
"Find plugins - bundles of skills, agents, MCP servers, UI extensions and more, and install them in one click.": "查找 Plugin——包含 Skill、Agent、MCP Server、UI 扩展等的组合包,并一键安装。",
"Find skills, agents, and more in the Marketplace.": "在 Marketplace 中查找 Skill、Agent 及更多内容。",
"Hook will only trigger if the tool name matches run_command or view_file.": "仅当工具名称匹配 run_command 或 view_file 时,Hook 才会触发。",
"Hook will only trigger if the tool name matches run_command.": "仅当工具名称匹配 run_command 时,Hook 才会触发。",
"Hook will only trigger if the tool name starts with browser_.": "仅当工具名称以 browser_ 开头时,Hook 才会触发。",
"Hook will trigger if any tool is executed.": "执行任意工具时都会触发 Hook。",
"Hook with this name already exists": "已存在同名 Hook",
"Hooks": "Hook",
"Host can proxy resource reads to the MCP server.": "宿主可将资源读取代理转发至 MCP Server。",
"Host can proxy tool calls to the MCP server.": "宿主可将工具调用代理转发至 MCP Server。",
"If you add multiple accounts, MCP servers use the one marked Default.": "如果您添加了多个账号,MCP Server 将使用标记为“默认”的账号。",
"Include default customizations, such as default skills.": "包含默认自定义项,例如默认 Skill。",
"Included with plugin": "随 Plugin 附带",
"Install or enable the Google Drive plugin in Customizations to search files with @drive: or paste Drive links": "在自定义设置中安装或启用 Google Drive Plugin,即可使用 @drive: 搜索文件或粘贴云端硬盘链接",
"Install this plugin to see the commands it adds, along with its skills, agents and MCP servers.": "安装此 Plugin 以查看其新增的命令,以及包含的 Skill、Agent 和 MCP Server。",
"Installed MCP Servers": "已安装的 MCP Server",
"Installed Plugins": "已安装的 Plugins",
"Installed Skills": "已安装的 Skill",
"LexicalBuilder: @lexical/react legacy text plugins conflict with the %s extension. Remove the legacy <RichTextPlugin/> or <PlainTextPlugin/> component.": "LexicalBuilder:@lexical/react 旧版文本 Plugin 与 %s 扩展冲突。请移除旧版 <RichTextPlugin/> 或 <PlainTextPlugin/> 组件。",
"Loading MCP servers...": "正在加载 MCP Server...",
"Loading available plugins...": "正在加载可用 Plugin...",
"Loading hooks...": "正在加载 Hook...",
"Loading installed plugins...": "正在加载已安装 Plugin...",
"Loading plugins...": "正在加载 Plugin...",
"Loading skills...": "正在加载 Skill...",
"Loading skills…": "正在加载 Skill…",
"MCP Server": "MCP Server",
"MCP Servers": "MCP Server",
"MCP Servers Disabled": "已禁用 MCP Server",
"MCP server": "MCP Server",
"MCP server error": "MCP Server 错误",
"MCP servers": "MCP Server",
"Manage Hooks": "管理 Hook",
"Manage MCP Servers": "管理 MCP Servers",
"Manage Plugins": "管理 Plugins",
"Manage Skills": "管理 Skill",
"Manage hooks": "管理 Hook",
"Managed by plugin": "由 Plugin 管理",
"Marketplace": "Marketplace",
"Marketplace Gallery URL": "Marketplace 库 URL",
"Marketplace Item URL": "Marketplace 项目 URL",
"Marketplace notice": "Marketplace 须知",
"More Plugins": "更多 Plugin",
"New hook name": "新 Hook 名称",
"No Custom Agents or Plugins": "无自定义 Agent 或 Plugin",
"No MCP servers found for \"": "未找到对应的 MCP Server:\"",
"No MCP servers installed": "未安装任何 MCP Server",
"No MCP servers yet. Use Add to browse the store.": "暂无 MCP Server。请点击“添加”浏览商店。",
"No Plugins Available": "无可用 Plugin",
"No apps connected yet. Connect one from Marketplace.": "暂未连接任何应用。请从 Marketplace 连接。",
"No matching plugins found.": "未找到匹配的 Plugin。",
"No plugin loads from this folder.": "此文件夹中未加载任何 Plugin。",
"No plugins available": "无可用 Plugin",
"No plugins available in the marketplace.": "Marketplace 中暂无可用 Plugin。",
"No plugins available.": "无可用 Plugin。",
"No plugins match your search.": "没有与您的搜索匹配的 Plugin。",
"No recommended skills found in workspace": "在 Workspace 中未找到推荐的 Skill",
"No skills available": "没有可用的 Skill",
"No skills loaded.": "未加载任何 Skill。",
"No skills or rules match this filter.": "没有 Skill 或 Rule 符合此筛选条件。",
"Nothing is always allowed. You'll be asked before this plugin makes changes.": "目前没有任何始终允许的操作。此 Plugin 进行更改前都会先征询您的同意。",
"Open plugin page": "打开 Plugin 页面",
"Open skill page": "打开 Skill 页面",
"Organization MCP Allowlist (Read-Only)": "组织 MCP Allowlist(只读)",
"Permanently delete your remote conversations, projects, scheduled tasks, connected plugins and settings. Data in the desktop app and your Google account are not affected.": "永久删除你的远程对话、项目、定时任务、已连接的 Plugin 和设置。桌面应用和你的 Google 账号中的数据不受影响。",
"Plugin": "Plugin",
"Plugin Accounts": "Plugin 账号",
"Plugin Operation Error:": "Plugin 操作错误:",
"Plugin Settings": "Plugin 设置",
"Plugin details": "Plugin 详情",
"Plugin disabled": "Plugin 已禁用",
"Plugin metadata": "Plugin 元数据",
"Plugin operations are not supported in this environment.": "当前环境不支持 Plugin 操作。",
"Plugin permissions": "Plugin 权限",
"Plugin update required": "需要更新 Plugin",
"Plugin:": "Plugin:",
"Plugins": "Plugins",
"Plugins Manager": "Plugins 管理器",
"Plugins Options": "Plugin 选项",
"Plugins are packaged collections of skills and MCPs to help the Agent": "Plugin 是打包的 Skill 和 MCP 集合,用于帮助 Agent",
"Plugins are packaged collections of skills and MCPs to help the Agent in": "Plugin 是打包的 Skill 和 MCP 集合,用于帮助 Agent 处理",
"Plugins, skills and MCP servers installed here. They run locally.": "此处安装的 Plugin、Skill 和 MCP Server。它们在本地运行。",
"Recommended Skills": "推荐的 Skill",
"Refresh MCP servers": "刷新 MCP Server",
"Refresh Skills": "刷新 Skill",
"Refresh skills": "刷新 Skill",
"Refresh skills paths": "刷新 Skill 路径",
"Removed from the marketplace. Stays installed until you uninstall it.": "已从 Marketplace 移除。在您卸载前仍会保持安装状态。",
"Removing the bundle removes all of its plugins.": "移除该扩展包将同时移除其中的所有 Plugin。",
"Replacing removes the currently installed plugin and installs the new one in its place.": "替换操作会移除当前已安装的 Plugin,并在原位置安装新版本。",
"Scanning skills config file...": "正在扫描 Skill 配置文件...",
"Search MCP servers by name": "按名称搜索 MCP Server",
"Search all skills on Agent Market…": "在 Agent Market 中搜索所有 Skill…",
"Search for MCP servers to add to your configuration": "搜索要添加到配置中的 MCP Server",
"Search plugins...": "搜索 Plugins...",
"Search skills...": "搜索 Skills...",
"Search skills…": "搜索 Skill…",
"Search tabs, files, extensions, subagents, artifacts, tasks...": "搜索标签页、文件、扩展、Subagent、Artifact、任务...",
"See less in Plugins": "在 Plugin 中显示更少",
"See more in Plugins": "在 Plugin 中查看更多",
"Services this plugin connects to on your behalf.": "此 Plugin 将代您连接的服务。",
"Services this plugin connects to on your behalf. Credentials stay on this machine and are only sent to the domains listed.": "此 Plugin 将代您连接的服务。凭据将保留在本机,仅发送至列出的域名。",
"Show Plugins": "显示 Plugin",
"Show or Hide Plugins": "显示或隐藏 Plugin",
"Sidecar": "Sidecar",
"Sidecar View": "Sidecar 视图",
"Sidecar disabled": "Sidecar 已禁用",
"Sidecar error": "Sidecar 出错",
"Sidecar feature is not available.": "Sidecar 功能不可用。",
"Sidecars": "Sidecars",
"Sign in to finish setting up this plugin.": "登录以完成此 Plugin 的设置。",
"Skill": "Skill",
"Skill Custom Paths": "Skill 自定义路径",
"Skill deletion is not available.": "无法删除 Skill。",
"Skills": "Skills",
"Skills & Rules": "Skill 与 Rule",
"Skills Configuration Error:": "Skill 配置错误:",
"Skills and Customizations": "Skill 与自定义项",
"Skills are instructions that extend what Agent can do.": "Skill 是用于扩展 Agent 能力的指令。",
"Start Plugin": "启动 Plugin",
"Suggested plugin:": "推荐的 Plugin:",
"TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.": "TRUSTED_TYPES_POLICY 配置选项必须提供 \"createHTML\" Hook。",
"TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.": "TRUSTED_TYPES_POLICY 配置选项必须提供 \"createScriptURL\" Hook。",
"The agent will wait for you to install the browser extension.": "Agent 将等待您安装浏览器扩展程序。",
"The breakdown below shows token usage from customizations like rules, skills, and MCP. If a budget is exceeded, large rules are demoted to path pointers and large customizations are excluded automatically.": "下方明细显示了来自 Rule、Skill 和 MCP 等自定义配置的 Token 用量。如果超出预算,大型 Rule 将降级为路径指针,大型自定义配置将自动排除。",
"The suggested plugin isn't in the marketplace.": "建议的 Plugin 不在 Marketplace 中。",
"These MCP allowlist rules are enforced by your organization's administrator.": "这些 MCP Allowlist Rule 由您所在组织的管理员强制执行。",
"These come with the plugin and can't be revoked.": "这些权限随 Plugin 附带,无法撤销。",
"This bundle has no plugins yet.": "此套件尚无 Plugin。",
"This permanently deletes all of your Remote Agents conversations, projects, scheduled tasks, connected plugins and settings, and stops any running remote agents. It can't be undone. Data in the desktop app and your Google account are not affected, and you can keep using Remote Agents afterwards.": "此操作将永久删除您所有的 Remote Agents 对话、项目、定时任务、已连接的 Plugin 和设置,并停止所有正在运行的远程 Agent,且无法撤销。桌面应用中的数据和您的 Google 账户不会受到影响,之后您仍可继续使用 Remote Agents。",
"This plugin is currently stopped. Events and stdout streams will appear here once started.": "此 Plugin 当前已停止。启动后,事件和 stdout 流将显示在此处。",
"This plugin requires authentication before the agent can use its tools.": "此 Plugin 需要先进行身份验证,Agent 才能使用其工具。",
"This plugin was force disabled.": "此 Plugin 已被强制禁用。",
"This project uses Firebase. Do you want to download the Firebase skill?": "此项目使用了 Firebase。是否要下载 Firebase Skill?",
"This sidecar failed to start.": "此 Sidecar 启动失败。",
"This sidecar runs from a path that is not officially supported. Make sure your code is in a trusted location in google3.": "此 Sidecar 运行于不受官方支持的路径。请确保您的代码位于 google3 中的受信任位置。",
"This skill came from the marketplace, so you can add it again whenever you need it.": "此 Skill 来自 Marketplace,因此你可以随时重新添加。",
"This skill is installed in your workspace": "此 Skill 已安装在你的 Workspace 中",
"UI Plugins": "UI Plugin",
"UI plugins": "UI Plugin",
"Unnamed MCP Server": "未命名的 MCP Server",
"Untrusted sidecar": "不受信任的 Sidecar",
"Use my conversation history to tell me which skills and plugins would be helpful for me.": "根据我的对话历史,告诉我哪些 Skill 和 Plugin 对我有帮助。",
"View MCP servers": "查看 MCP Server",
"When enabled, the agent will include default customizations, including default skills.": "启用后,Agent 将包含默认自定义配置,包括默认 Skill。",
"When running commands, the agent will try to use this address, and fall back to the \"connector.host.featureDefault\" host if not defined.\n\nNote: hosts set here with auto-run enabled will have internet access restricted soon.": "运行命令时,Agent 将尝试使用此地址;若未定义,则回退到 \"connector.host.featureDefault\" 主机。\n\n注意:此处设置了自动运行的主机不久后将受到互联网访问限制。",
"You can also add or remove each plugin below.": "您也可以在下方添加或移除各个 Plugin。",
"You don't have any custom agents or plugins configured. Create agent scripts in the agents/ directory or add plugins to the plugins/ directory inside your Gemini configuration folder.": "您尚未配置任何自定义 Agent 或 Plugin。请在 Gemini 配置文件夹内的 agents/ 目录中创建 Agent 脚本,或将 Plugin 添加到 plugins/ 目录中。",
"Your administrator has disabled MCP servers for this workspace.": "您的管理员已为此 Workspace 禁用 MCP Server。",
"plugin": "Plugin",
"plugins": "Plugin",
"plugins available.": "个可用的 Plugin。",
"— the skills config path does not exist in this workspace.": "— 此 Workspace 中不存在 Skill 配置路径。",
"💡 Discover and install more skills at": "💡 发现并安装更多 Skill,请访问"
},
"deep": {
"+ Add Hook": "+ 添加钩子",
". Learn more about skills at": "。了解有关技能的更多信息,请访问",
"Active Skills": "已启用的技能",
"Add Hook Card": "添加钩子卡片",
"Add MCP Server": "添加 MCP 服务",
"Add MCP Servers": "添加 MCP 服务",
"Add Plugin": "添加插件",
"Add Skill": "添加技能",
"Agent Hooks Configuration": "智能体钩子配置",
"Agent Marketplace": "智能体插件市场",
"Are you sure you want to delete this hook card?": "确定要删除此钩子卡片吗?",
"Base UI calls `render` as a plain function, which can break the Rules of Hooks during reconciliation.": "Base UI 将 `render` 作为普通函数调用,这可能会在协调过程中违反 Hook 规则。",
"Browse Plugins": "浏览插件",
"Browse Skills": "浏览技能",
"Browse and enable plugins from the Build With Google catalog.": "浏览并启用 Build With Google 目录中的插件。",
"Browse the Marketplace": "浏览插件市场",
"Build With Google Plugins": "Build With Google 插件",
"Build With Google plugins": "Build With Google 插件",
"Changes plugins can make without asking.": "插件无需询问即可进行的更改。",
"Close Sidecar": "关闭辅助侧栏",
"Close skills panel": "关闭技能面板",
"Configure MCP Server": "配置 MCP 服务",
"Configure default behaviors, skills, and MCP servers.": "配置默认行为、技能和 MCP 服务。",
"Configure hooks that run on agent lifecycle events.": "配置在智能体生命周期事件上运行的钩子。",
"Could not determine plugin config file path": "无法确定插件配置文件路径",
"Couldn't load the suggested plugin.": "无法加载推荐的插件。",
"Create Plugin": "创建插件",
"Create Skill": "创建技能",
"Create a Plugin with the Agent": "使用智能体创建插件",
"Create plugin": "创建插件",
"Creating Sidecar": "正在创建辅助侧栏",
"Curated sets of plugins for common workflows and roles.": "针对常见工作流和角色的精选插件集合。",
"Customizations & Skills": "自定义配置与技能",
"Customize Global Skills": "自定义全局技能",
"Customize your experience across the agent, plugins, and product from the settings and marketplace. We won’t show you ads or let advertisers influence what": "在设置和插件市场中自定义你在智能体、插件和产品中的体验。我们不会向你展示广告,也不会让广告商影响",
"Delete Hook": "删除钩子",
"Delete MCP Server": "删除 MCP 服务",
"Delete Skill": "删除技能",
"Delete plugin": "删除插件",
"Disabled. Open the plugin page to finish setup.": "已禁用。打开插件页面以完成设置。",
"Discover helpful skills & plugins": "发现实用的技能和插件",
"Each plugin can be managed on its own.": "每个插件都可以单独管理。",
"Enable Recommended Skills": "启用推荐的技能",
"Enable recommended skills": "启用推荐的技能",
"Enable the plugin to sign in.": "启用该插件以登录。",
"Enable this plugin to manage its accounts.": "启用此插件以管理其账号。",
"Encountered an error while running the plugin.": "运行插件时遇到错误。",
"Enter the configuration values this MCP server needs. Saving restarts the server with them.": "输入此 MCP 服务所需的配置值。保存后将使用这些配置重启服务。",
"Enter the required configuration values to install this MCP server.": "输入安装此 MCP 服务所需的配置值。",
"Error fetching MCP prompt": "获取 MCP 提示词出错",
"Explore other marketplace customizations": "探索其他插件市场自定义项",
"Explore the plugin marketplace": "探索插件市场",
"Failed to add plugin.": "添加插件失败。",
"Failed to add plugin. Please try again.": "添加插件失败,请重试。",
"Failed to delete plugin.": "删除插件失败。",
"Failed to delete plugin. Please try again.": "删除插件失败,请重试。",
"Failed to delete skill.": "删除技能失败。",
"Failed to delete skill. Please try again.": "删除技能失败,请重试。",
"Failed to determine plugin ID": "确定插件 ID 失败",
"Failed to determine plugin install directory": "确定插件安装目录失败",
"Failed to download Firebase skill.": "下载 Firebase 技能失败。",
"Failed to load MCP servers": "加载 MCP 服务失败",
"Failed to load marketplace bundles. Please try again.": "加载插件市场捆绑包失败,请重试。",
"Failed to load more plugins. Please try again.": "加载更多插件失败,请重试。",
"Failed to load plugin. Please try again.": "加载插件失败,请重试。",
"Failed to load plugins": "加载插件失败",
"Failed to load plugins. Please try again.": "加载插件失败,请重试。",
"Failed to load skills paths:": "加载技能路径失败:",
"Failed to load skills:": "加载技能失败:",
"Failed to open plugin config file": "打开插件配置文件失败",
"Failed to scan skills config file:": "扫描技能配置文件失败:",
"Failed to toggle plugin. Please try again.": "切换插件状态失败,请重试。",
"Filter plugins": "筛选插件",
"Find plugins - bundles of skills, agents, MCP servers, UI extensions and more, and install them in one click.": "查找插件——包含技能、智能体、MCP 服务、UI 扩展等的组合包,并一键安装。",
"Find skills, agents, and more in the Marketplace.": "在插件市场中查找技能、智能体及更多内容。",
"Hook will only trigger if the tool name matches run_command or view_file.": "仅当工具名称匹配 run_command 或 view_file 时,钩子才会触发。",
"Hook will only trigger if the tool name matches run_command.": "仅当工具名称匹配 run_command 时,钩子才会触发。",
"Hook will only trigger if the tool name starts with browser_.": "仅当工具名称以 browser_ 开头时,钩子才会触发。",
"Hook will trigger if any tool is executed.": "执行任意工具时都会触发钩子。",
"Hook with this name already exists": "已存在同名钩子",
"Hooks": "钩子",
"Host can proxy resource reads to the MCP server.": "宿主可将资源读取代理转发至 MCP 服务。",
"Host can proxy tool calls to the MCP server.": "宿主可将工具调用代理转发至 MCP 服务。",
"If you add multiple accounts, MCP servers use the one marked Default.": "如果您添加了多个账号,MCP 服务将使用标记为“默认”的账号。",
"Include default customizations, such as default skills.": "包含默认自定义项,例如默认技能。",
"Included with plugin": "随插件附带",
"Install or enable the Google Drive plugin in Customizations to search files with @drive: or paste Drive links": "在自定义设置中安装或启用 Google Drive 插件,即可使用 @drive: 搜索文件或粘贴云端硬盘链接",
"Install this plugin to see the commands it adds, along with its skills, agents and MCP servers.": "安装此插件以查看其新增的命令,以及包含的技能、智能体和 MCP 服务。",
"Installed MCP Servers": "已安装的 MCP 服务",
"Installed Plugins": "已安装插件",
"Installed Skills": "已安装的技能",
"LexicalBuilder: @lexical/react legacy text plugins conflict with the %s extension. Remove the legacy <RichTextPlugin/> or <PlainTextPlugin/> component.": "LexicalBuilder:@lexical/react 旧版文本插件与 %s 扩展冲突。请移除旧版 <RichTextPlugin/> 或 <PlainTextPlugin/> 组件。",
"Loading MCP servers...": "正在加载 MCP 服务...",
"Loading available plugins...": "正在加载可用插件...",
"Loading hooks...": "正在加载钩子...",
"Loading installed plugins...": "正在加载已安装插件...",
"Loading plugins...": "正在加载插件...",
"Loading skills...": "正在加载技能...",
"Loading skills…": "正在加载技能…",
"MCP Server": "MCP 服务",
"MCP Servers": "MCP 服务",
"MCP Servers Disabled": "已禁用 MCP 服务",
"MCP server": "MCP 服务",
"MCP server error": "MCP 服务错误",
"MCP servers": "MCP 服务",
"Manage Hooks": "管理钩子",
"Manage MCP Servers": "管理 MCP 服务",
"Manage Plugins": "管理插件",
"Manage Skills": "管理技能",
"Manage hooks": "管理钩子",
"Managed by plugin": "由插件管理",
"Marketplace": "插件市场",
"Marketplace Gallery URL": "插件市场库 URL",
"Marketplace Item URL": "插件市场项目 URL",
"Marketplace notice": "插件市场须知",
"More Plugins": "更多插件",
"New hook name": "新钩子名称",
"No Custom Agents or Plugins": "无自定义智能体或插件",
"No MCP servers found for \"": "未找到对应的 MCP 服务:\"",
"No MCP servers installed": "未安装任何 MCP 服务",
"No MCP servers yet. Use Add to browse the store.": "暂无 MCP 服务。请点击“添加”浏览商店。",
"No Plugins Available": "无可用插件",
"No apps connected yet. Connect one from Marketplace.": "暂未连接任何应用。请从插件市场连接。",
"No matching plugins found.": "未找到匹配的插件。",
"No plugin loads from this folder.": "此文件夹中未加载任何插件。",
"No plugins available": "无可用插件",
"No plugins available in the marketplace.": "插件市场中暂无可用插件。",
"No plugins available.": "无可用插件。",
"No plugins match your search.": "没有与您的搜索匹配的插件。",
"No recommended skills found in workspace": "在工作区中未找到推荐的技能",
"No skills available": "没有可用的技能",
"No skills loaded.": "未加载任何技能。",
"No skills or rules match this filter.": "没有技能或规则符合此筛选条件。",
"Nothing is always allowed. You'll be asked before this plugin makes changes.": "目前没有任何始终允许的操作。此插件进行更改前都会先征询您的同意。",
"Open plugin page": "打开插件页面",
"Open skill page": "打开技能页面",
"Organization MCP Allowlist (Read-Only)": "组织 MCP 允许名单(只读)",
"Permanently delete your remote conversations, projects, scheduled tasks, connected plugins and settings. Data in the desktop app and your Google account are not affected.": "永久删除你的远程对话、项目、定时任务、已连接的插件和设置。桌面应用和你的 Google 账号中的数据不受影响。",
"Plugin": "插件",
"Plugin Accounts": "插件账号",
"Plugin Operation Error:": "插件操作错误:",
"Plugin Settings": "插件设置",
"Plugin details": "插件详情",
"Plugin disabled": "插件已禁用",
"Plugin metadata": "插件元数据",
"Plugin operations are not supported in this environment.": "当前环境不支持插件操作。",
"Plugin permissions": "插件权限",
"Plugin update required": "需要更新插件",
"Plugin:": "插件:",
"Plugins": "插件",
"Plugins Manager": "插件管理器",
"Plugins Options": "插件选项",
"Plugins are packaged collections of skills and MCPs to help the Agent": "插件是打包的技能和 MCP 集合,用于帮助智能体",
"Plugins are packaged collections of skills and MCPs to help the Agent in": "插件是打包的技能和 MCP 集合,用于帮助智能体处理",
"Plugins, skills and MCP servers installed here. They run locally.": "此处安装的插件、技能和 MCP 服务。它们在本地运行。",
"Recommended Skills": "推荐的技能",
"Refresh MCP servers": "刷新 MCP 服务",
"Refresh Skills": "刷新技能",
"Refresh skills": "刷新技能",
"Refresh skills paths": "刷新技能路径",
"Removed from the marketplace. Stays installed until you uninstall it.": "已从插件市场移除。在您卸载前仍会保持安装状态。",
"Removing the bundle removes all of its plugins.": "移除该扩展包将同时移除其中的所有插件。",
"Replacing removes the currently installed plugin and installs the new one in its place.": "替换操作会移除当前已安装的插件,并在原位置安装新版本。",
"Scanning skills config file...": "正在扫描技能配置文件...",
"Search MCP servers by name": "按名称搜索 MCP 服务",
"Search all skills on Agent Market…": "在智能体市场中搜索所有技能…",
"Search for MCP servers to add to your configuration": "搜索要添加到配置中的 MCP 服务",
"Search plugins...": "搜索插件...",
"Search skills...": "搜索技能...",
"Search skills…": "搜索技能…",
"Search tabs, files, extensions, subagents, artifacts, tasks...": "搜索标签页、文件、扩展、子代理、产物、任务...",
"See less in Plugins": "在插件中显示更少",
"See more in Plugins": "在插件中查看更多",
"Services this plugin connects to on your behalf.": "此插件将代您连接的服务。",
"Services this plugin connects to on your behalf. Credentials stay on this machine and are only sent to the domains listed.": "此插件将代您连接的服务。凭据将保留在本机,仅发送至列出的域名。",
"Show Plugins": "显示插件",
"Show or Hide Plugins": "显示或隐藏插件",
"Sidecar": "辅助侧栏",
"Sidecar View": "辅助侧栏视图",
"Sidecar disabled": "辅助侧栏已禁用",
"Sidecar error": "辅助侧栏出错",
"Sidecar feature is not available.": "辅助侧栏功能不可用。",
"Sidecars": "辅助侧栏",
"Sign in to finish setting up this plugin.": "登录以完成此插件的设置。",
"Skill": "技能",
"Skill Custom Paths": "技能自定义路径",
"Skill deletion is not available.": "无法删除技能。",
"Skills": "技能",
"Skills & Rules": "技能与规则",
"Skills Configuration Error:": "技能配置错误:",
"Skills and Customizations": "技能与自定义项",
"Skills are instructions that extend what Agent can do.": "技能是用于扩展智能体能力的指令。",
"Start Plugin": "启动插件",
"Suggested plugin:": "推荐的插件:",
"TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.": "TRUSTED_TYPES_POLICY 配置选项必须提供 \"createHTML\" 钩子。",
"TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.": "TRUSTED_TYPES_POLICY 配置选项必须提供 \"createScriptURL\" 钩子。",
"The agent will wait for you to install the browser extension.": "智能体将等待您安装浏览器扩展程序。",
"The breakdown below shows token usage from customizations like rules, skills, and MCP. If a budget is exceeded, large rules are demoted to path pointers and large customizations are excluded automatically.": "下方明细显示了来自规则、技能和 MCP 等自定义配置的词元用量。如果超出预算,大型规则将降级为路径指针,大型自定义配置将自动排除。",
"The suggested plugin isn't in the marketplace.": "建议的插件不在插件市场中。",
"These MCP allowlist rules are enforced by your organization's administrator.": "这些 MCP 允许名单规则由您所在组织的管理员强制执行。",
"These come with the plugin and can't be revoked.": "这些权限随插件附带,无法撤销。",
"This bundle has no plugins yet.": "此套件尚无插件。",
"This permanently deletes all of your Remote Agents conversations, projects, scheduled tasks, connected plugins and settings, and stops any running remote agents. It can't be undone. Data in the desktop app and your Google account are not affected, and you can keep using Remote Agents afterwards.": "此操作将永久删除您所有的远程智能体对话、项目、定时任务、已连接的插件和设置,并停止所有正在运行的远程智能体,且无法撤销。桌面应用中的数据和您的 Google 账户不会受到影响,之后您仍可继续使用远程智能体。",
"This plugin is currently stopped. Events and stdout streams will appear here once started.": "此插件当前已停止。启动后,事件和 stdout 流将显示在此处。",
"This plugin requires authentication before the agent can use its tools.": "此插件需要先进行身份验证,智能体才能使用其工具。",
"This plugin was force disabled.": "此插件已被强制禁用。",
"This project uses Firebase. Do you want to download the Firebase skill?": "此项目使用了 Firebase。是否要下载 Firebase 技能?",
"This sidecar failed to start.": "此辅助侧栏启动失败。",
"This sidecar runs from a path that is not officially supported. Make sure your code is in a trusted location in google3.": "此辅助侧栏运行于不受官方支持的路径。请确保您的代码位于 google3 中的受信任位置。",
"This skill came from the marketplace, so you can add it again whenever you need it.": "此技能来自插件市场,因此你可以随时重新添加。",
"This skill is installed in your workspace": "此技能已安装在你的工作区中",
"UI Plugins": "UI 插件",
"UI plugins": "UI 插件",
"Unnamed MCP Server": "未命名的 MCP 服务",
"Untrusted sidecar": "不受信任的辅助侧栏",
"Use my conversation history to tell me which skills and plugins would be helpful for me.": "根据我的对话历史,告诉我哪些技能和插件对我有帮助。",
"View MCP servers": "查看 MCP 服务",
"When enabled, the agent will include default customizations, including default skills.": "启用后,智能体将包含默认自定义配置,包括默认技能。",
"When running commands, the agent will try to use this address, and fall back to the \"connector.host.featureDefault\" host if not defined.\n\nNote: hosts set here with auto-run enabled will have internet access restricted soon.": "运行命令时,智能体将尝试使用此地址;若未定义,则回退到 \"connector.host.featureDefault\" 主机。\n\n注意:此处设置了自动运行的主机不久后将受到互联网访问限制。",
"You can also add or remove each plugin below.": "您也可以在下方添加或移除各个插件。",
"You don't have any custom agents or plugins configured. Create agent scripts in the agents/ directory or add plugins to the plugins/ directory inside your Gemini configuration folder.": "您尚未配置任何自定义智能体或插件。请在 Gemini 配置文件夹内的 agents/ 目录中创建智能体脚本,或将插件添加到 plugins/ 目录中。",
"Your administrator has disabled MCP servers for this workspace.": "您的管理员已为此工作区禁用 MCP 服务。",
"plugin": "插件",
"plugins": "插件",
"plugins available.": "个可用的插件。",
"— the skills config path does not exist in this workspace.": "— 此工作区中不存在技能配置路径。",
"💡 Discover and install more skills at": "💡 发现并安装更多技能,请访问"
}
}
+346
View File
@@ -0,0 +1,346 @@
{
"base": {
"+ Add Organization policy": "+ 添加组织策略",
"+ Add Repository policy": "+ 添加仓库策略",
"+ Add issue policy": "+ 添加议题策略",
". I understand I can choose to opt out later whenever I want via my settings.": "。我了解我可以随时在设置中选择退出。",
". If it isn't in the list, drag it in from the small window next to System Settings.": "。如果它不在列表中,请从系统设置旁的小窗口将其拖入。",
". To add another account, go to the": "。要添加其他账号,请前往",
". To use another account, add it in the": "。要使用其他账号,请将其添加到",
". You can control this from your settings at any point.": "。您可以随时在设置中控制此项。",
"A few things to know, and a couple settings to review.": "有几项注意事项需要了解,还有几个设置需要确认。",
"AI Credits are used when you've exceeded your model quota. Keep track of your current AI Credits in the": "当您超出模型配额时将消耗 AI 额度。查看当前 AI 额度,请前往",
"Access rules": "访问规则",
"Account": "账号",
"Account & Billing": "账号与计费",
"Account connected.": "账号已连接。",
"Account connection was not completed.": "账号连接未完成。",
"Add Account": "添加账号",
"Add Shortcut": "添加快捷键",
"Add account": "添加账号",
"Advanced Settings": "高级设置",
"All active Antigravity shortcuts and user keybinding overrides are managed directly by VS Code.": "所有已启用的 Antigravity 快捷键和用户键位绑定覆盖均直接由 VS Code 管理。",
"App Settings": "应用设置",
"App update required": "需要更新应用",
"Appearance": "外观",
"Approval Policy": "审批策略",
"Apps connected to your account": "已连接到您账号的应用",
"Auth and Billing": "身份验证与账单",
"Auto-update": "自动更新",
"Automatic Check for Updates": "自动检查更新",
"Automatic check for updates": "自动检查更新",
"Automatically prompt you to restart the app when a new update is available. When disabled, you can check for updates manually from the app menu.": "有新更新可用时自动提示您重启应用。禁用后,您可以从应用菜单中手动检查更新。",
"Baseline model quota reached": "已达到基础模型配额",
"Billing": "计费",
"Billing model": "计费模式",
"Blocked by organization policy": "已被组织策略阻止",
"Business Account Sign In": "企业账号登录",
"Cached setting value": "缓存的设置值",
"Change Theme": "切换主题",
"Change VCS in General settings, under Advanced": "请在“通用”设置中的“高级”下更改 VCS",
"Chat Settings": "聊天设置",
"Check for Updates": "检查更新",
"Check for updates": "检查更新",
"Checking for updates...": "正在检查更新...",
"Choose a Subscription": "选择订阅方案",
"Close Settings": "关闭设置",
"Cloud Permissions": "云端权限",
"Color Theme": "颜色主题",
"Color theme preference for the host environment.": "宿主环境的颜色主题偏好设置。",
"Configure GitHub access policies.": "配置 GitHub 访问策略。",
"Configure editor-specific behaviors and shortcuts.": "配置编辑器特定行为和快捷键。",
"Configure global allowed and denied resource permissions.": "配置全局允许和禁止的资源权限。",
"Connect your account to browse": "连接您的账号以浏览",
"Connection security information is not available for this page": "此页面的连接安全信息不可用",
"Continue with different account": "使用其他账号继续",
"Controls how much time and quota the model spends reasoning before responding. Higher effort improves accuracy on hard problems, at the cost of slower responses and higher quota use.": "控制模型在回复前用于推理的时间和配额。提高推理力度可提升复杂问题的准确度,但会导致回复变慢并消耗更多配额。",
"Controls permissions for remote conversations.": "控制远程对话的权限。",
"Customize Shortcuts": "自定义快捷键",
"Data & Privacy": "数据与隐私",
"Default uses server-managed routing and Orchestrator quota. Custom pins specific models for orchestration and execution.": "默认使用服务端托管路由和 Orchestrator 配额。自定义模式会为编排和执行固定特定模型。",
"Delete organization policy": "删除组织策略",
"Delete repository policy": "删除仓库策略",
"Describe your auth or billing issue...": "请描述你的身份验证或计费问题...",
"Developer-only tools. These settings do not affect other users.": "仅限开发者使用的工具。这些设置不会影响其他用户。",
"Disabled by organization policy": "已被组织策略禁用",
"Disconnect account": "断开账号连接",
"Downloading Update": "正在下载更新",
"Edit Shortcut": "编辑快捷键",
"Edit permission target": "编辑权限目标",
"Editor Settings": "编辑器设置",
"Enable macOS Permissions": "启用 macOS 权限",
"Enter always submits. This adds a second shortcut.": "Enter 键始终会提交。这会添加第二个快捷键。",
"Enterprise FetchAdminControlsResponse proto (overrides user settings)": "企业版 FetchAdminControlsResponse proto(覆盖用户设置)",
"Execute JavaScript Policy": "执行 JavaScript 策略",
"Failed to parse settings. Fix and restart.": "解析设置失败。请修复后重启。",
"Failed to push update": "推送更新失败",
"Failed to resolve permissions. Please try again.": "处理权限失败,请重试。",
"Failed to update permissions. Please try again.": "更新权限失败,请重试。",
"Failed to update the bundle.": "更新捆绑包失败。",
"Failed to update the bundle. Please try again.": "更新捆绑包失败,请重试。",
"File Permissions": "文件权限",
"Font Family": "字体",
"Font Size": "字号",
"GitHub Permissions": "GitHub 权限",
"GitHub Policies": "GitHub 策略",
"Global Permissions": "全局权限",
"Global Settings": "全局设置",
"Go to global settings": "前往全局设置",
"Go to the machine you are controlling and quit Antigravity. It installs pending updates the next time it starts.": "前往您正在控制的机器并退出 Antigravity。它将在下次启动时安装待处理的更新。",
"Google Privacy Policy": "Google 隐私政策",
"Hidden by policy": "已根据策略隐藏",
"Hidden by the preview policy.": "已根据预览策略隐藏。",
"In System Settings, click": "在“系统设置”中,点击",
"In System Settings, turn on": "在“系统设置”中,开启",
"Install Update": "安装更新",
"Installing Update": "正在安装更新",
"Keybinding Scheme": "快捷键方案",
"Keyboard Shortcuts": "快捷键",
"Keyboard shortcuts": "键盘快捷键",
"Keyboard shortcuts for quick navigation and control.": "用于快速导航和控制的键盘快捷键。",
"Lexical node does not exist in active editor state (key %s, type %s). The reference was probably kept from another read or update, for example in a closure, event handler or component state, and the node has since been removed or is not part of this editor state. Before using a node reference that may be stale, check node.isAttached() or look the node up again with $getNodeByKey(node.getKey()), inside the read or update where it is used.": "当前活动编辑器状态中不存在 Lexical 节点(key %s,type %s)。该引用可能是从之前的读取或更新(例如闭包、事件处理程序或组件状态)中保留下来的,而该节点此后已被移除或不属于当前编辑器状态。在使用可能已过期的节点引用之前,请先检查 node.isAttached(),或在使用的读取/更新逻辑内通过 $getNodeByKey(node.getKey()) 重新查找该节点。",
"Link Settings": "链接设置",
"Local Permissions": "本地权限",
"Manage Account": "管理账号",
"Manage Permissions": "管理权限",
"Manage fine-grained permissions for GitHub.": "管理 GitHub 的细粒度权限。",
"Manage permissions": "管理权限",
"Manage your keybinding scheme and customize shortcuts in VS Code.": "在 VS Code 中管理快捷键方案并自定义快捷键。",
"Manage your model quota and credits.": "管理您的模型配额与额度。",
"Manage your notification preferences.": "管理您的通知偏好设置。",
"Manage your plan, credentials, and general preferences.": "管理您的方案、凭据和常规偏好设置。",
"Microphone access is blocked by your operating system. Grant microphone permission in System Settings and try again.": "操作系统已阻止麦克风访问权限。请在系统设置中授予麦克风权限后重试。",
"Model Quota": "模型配额",
"Model quota reached": "已达到模型配额上限",
"Network Access Rules": "网络访问规则",
"Network Permissions": "网络权限",
"Network access rules": "网络访问规则",
"Next: Review Permissions": "下一步:检查权限",
"No keyboard shortcuts found matching your filter.": "未找到与过滤条件匹配的键盘快捷键。",
"No models are available for your current project or account. Please check your project settings and IAM permissions.": "您当前的项目或账号无可用模型。请检查您的项目设置和 IAM 权限。",
"No quota information available.": "暂无配额信息。",
"Notification Preferences": "通知偏好设置",
"Notification Settings": "通知设置",
"Notification settings": "通知设置",
"Open Appearance": "打开外观设置",
"Open Editor Settings": "打开编辑器设置",
"Open Keyboard Shortcuts": "打开键盘快捷方式",
"Open Preferences": "打开偏好设置",
"Open Settings": "打开设置",
"Open System Preferences": "打开系统偏好设置",
"Open project settings": "打开项目设置",
"Open settings menu": "打开设置菜单",
"Orchestrator Settings": "编排器设置",
"Outside of folders file access policy": "文件夹外的文件访问策略",
"Permission": "权限",
"Permission Details": "权限详情",
"Permission Preset": "权限预设",
"Permission Required": "需要权限",
"Permission Settings": "权限设置",
"Permission decision": "权限决定",
"Permission preset": "权限预设",
"Permission required": "需要权限",
"Permissions": "权限",
"Permissions granted by the host (camera, microphone, geolocation).": "宿主授予的权限(摄像头、麦克风、地理位置)。",
"Pick one of these themes under Preset in Settings > Appearance.": "在“设置 > 外观”下的“预设”中选择其中一种主题。",
"Plan Review Policy": "计划审核策略",
"Please describe your auth or billing issue. More details will help our support team resolve your issue quicker. Some helpful information includes:": "请描述您的身份验证或账单问题。更多详细信息将有助于我们的支持团队更快解决您的问题。以下信息可能会有所帮助:",
"Please verify your account to continue using": "请验证您的账号以继续使用",
"Please verify your account, then sign in again to continue. Learn more by visiting our": "请验证您的账号,然后重新登录以继续。如需了解更多信息,请访问我们的",
"Preferences": "偏好设置",
"Privacy": "隐私",
"Privacy Notice": "隐私声明",
"Prohibited Use Policy": "禁止使用政策",
"Project Settings": "项目设置",
"Proxy": "代理",
"Proxy Settings": "代理设置",
"Push Update": "推送更新",
"Quickly add and update imports with a tab keypress.": "通过按 Tab 键快速添加和更新导入。",
"Quota": "配额",
"Raw theme data for copying to tests": "用于复制到测试的原始主题数据",
"Reconnect Account": "重新连接账号",
"Reconnect account": "重新连接账号",
"Refresh quota and credits data": "刷新配额与额度数据",
"Remove Shortcut": "移除快捷键",
"Remove individual uploaded files or connected resources in Project Settings, or delete a project or conversation to remove its stored files.": "可在项目设置中移除单个已上传文件或已连接资源,或通过删除项目或对话来移除其存储的文件。",
"Remove policy": "移除策略",
"Request camera access.\n\nMaps to Permission Policy `camera` feature.": "请求摄像头访问权限。\\n\\n对应权限策略(Permission Policy)中的 `camera` 功能。",
"Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.": "请求剪贴板写入权限。\\n\\n对应权限策略(Permission Policy)中的 `clipboard-write` 功能。",
"Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature.": "请求地理位置访问权限。\\n\\n对应权限策略(Permission Policy)中的 `geolocation` 功能。",
"Request microphone access.\n\nMaps to Permission Policy `microphone` feature.": "请求麦克风访问权限。\\n\\n对应权限策略(Permission Policy)中的 `microphone` 功能。",
"Reset all shortcuts to defaults": "将所有快捷键恢复为默认",
"Resolving permissions...": "正在解析权限...",
"Restart to Update": "重启以更新",
"Restart to update": "重启以完成更新",
"Review Policy": "审阅策略",
"Review permissions": "审阅权限",
"Search shortcuts": "搜索快捷键",
"Search shortcuts...": "搜索快捷键...",
"Security": "安全",
"Security Notice & Data Use": "安全声明与数据使用",
"Security Preset": "安全预设",
"Security preset": "安全预设",
"Select Billing Model": "选择计费模式",
"Select Theme": "选择主题",
"Setting a `style` bypass at element creation should be done only when absolutely necessary. Try to use the stylesheet instead.": "仅在绝对必要时才应在创建元素时绕过样式表直接设置 `style`。请尽量改用样式表。",
"Settings": "设置",
"Settings -": "设置 -",
"Settings Unavailable": "设置不可用",
"Settings ↗": "设置 ↗",
"Shortcuts": "快捷键",
"Show a floating notification card when background conversations need your input. Answer questions, approve commands, and grant permissions without leaving your current conversation. Share feedback at go/inline-actions-feedback.": "当后台对话需要你的输入时显示悬浮通知卡片。无需离开当前对话即可回答问题、批准命令并授予权限。欢迎通过 go/inline-actions-feedback 分享反馈。",
"Show settings anyway": "仍然显示设置",
"Sidebar Updates": "侧边栏更新",
"Sign in with a different account": "使用其他账号登录",
"Slightly modify your UI to ensure more consistent demos. This is only recommended for demo purposes. In most cases, you can run \"Antigravity: Start Demo Mode\" and \"Antigravity: Stop Demo Mode\" to control this switch and update your ~/.gemini/antigravity data directory.": "微调界面以确保演示效果更加一致。仅建议在演示时使用。在大多数情况下,你可以运行“Antigravity: Start Demo Mode”和“Antigravity: Stop Demo Mode”来控制此开关并更新你的 ~/.gemini/antigravity 数据目录。",
"Sorry, this account is ineligible to use": "抱歉,此账号无法使用",
"Subscription": "订阅",
"Terms and Privacy:": "条款与隐私:",
"Theme": "主题",
"There was an unexpected issue setting up your account.": "设置您的账户时发生意外问题。",
"These settings can only be changed on the computer running the app, not from a remote session.": "这些设置只能在运行应用的计算机上更改,无法从远程会话更改。",
"This Google Cloud project is not supported. Input a different project, or sign in with another account.": "不支持此 Google Cloud 项目。请输入其他项目,或使用其他账户登录。",
"This migration may mess up your settings, chats, and sidebar.": "此迁移可能会弄乱您的设置、对话和侧边栏。",
"To modify editor settings, open Settings within the editor window.": "要修改编辑器设置,请在编辑器窗口中打开设置。",
"To modify notification settings, open your operating system's system preferences.": "要修改通知设置,请打开操作系统的系统偏好设置。",
"To update:": "更新方法:",
"Too many expansions: infinite loop or need to increase maxExpand setting": "展开次数过多:可能存在无限循环或需要调大 maxExpand 设置",
"Tool Permissions": "工具权限",
"Tool permissions": "工具权限",
"True if the host failed to open the URL (e.g., due to security policy).": "如果宿主未能打开该 URL(例如由于安全策略),则为 true。",
"Unnamed Theme": "未命名主题",
"Update": "更新",
"Update Anyway": "仍然更新",
"Update Available": "有可用更新",
"Update available": "有可用更新",
"Updates": "更新",
"Updates to your sidebar": "侧边栏更新",
"Uploads logs, settings, and conversation summaries to your Drive.": "将日志、设置和对话摘要上传到您的 Drive。",
"Usage & Quota": "用量与配额",
"Use Antigravity through your Gemini subscription.": "通过您的 Gemini 订阅使用 Antigravity。",
"Use Business Account": "使用企业账号",
"Use Global Settings": "使用全局设置",
"Use theme to be imported with settings": "使用随设置导入的主题",
"User Settings": "用户设置",
"VS Code keyboard shortcuts": "VS Code 键盘快捷键",
"Verify that these licenses were provided by your administrator and that you trust the project ID before proceeding. Account activity and data may be logged by your organization.": "在继续之前,请确认这些许可证由您的管理员提供,并且您信任该项目 ID。您的组织可能会记录账号活动和数据。",
"Waiting for tool permission approval — click Open in full conversation (↗) to approve": "正在等待工具权限批准 — 点击“在完整对话中打开 (↗)”进行批准",
"What functionality you expect your account tier to have available that is missing": "您期望当前账号等级应具备但缺失的功能",
"What quota or feature is being incorrectly limited": "哪个配额或功能被错误限制",
"Yes, I'd like to receive product updates, tips, and promotions from Google": "是的,我希望接收来自 Google 的产品更新、使用技巧和促销信息",
"You have a conversation in progress. Updating will interrupt it, and it will automatically resume once the update completes.": "您当前有一个正在进行的对话。更新将会中断该对话,更新完成后将自动恢复。",
"Your Antigravity use will be associated with provided project. Make sure you trust the project ID before proceeding. Account activity and data may be logged by your organization.": "您的 Antigravity 使用记录将与所提供的项目关联。继续前请确保您信任该项目 ID。您的账号活动和数据可能会被所属组织记录。",
"Your This Computer setting": "您的“此计算机”设置",
"Your quota for this model is running low.": "您在此模型上的配额即将耗尽。",
"macOS Permissions Ready": "macOS 权限已就绪",
"migrated in settings": "已在设置中迁移",
"on it. This makes the directory listable by any Googler; the files inside keep their own permissions.": "。这会使目录可被任何 Googler 列出;其中的文件仍保留各自权限。",
"settings": "设置",
"settings page.": "设置页面。",
"with its own permissions, which you can change anytime in the": "拥有各自独立的权限,你可以随时在",
"work with Google developer products. You can always change your choices in Settings.": "配合 Google 开发者产品使用。你可以随时在设置中更改你的选择。",
"✓ macOS permissions granted": "✓ 已授予 macOS 权限"
},
"light": {
"+ Add branch policy": "+ 添加 Branch 策略",
"+ Add pull request policy": "+ 添加 Pull Request 策略",
"+ Add workflow run policy": "+ 添加 Workflow 运行策略",
"Add to allowlist": "添加到 Allowlist",
"Added to allowlist": "已添加到 Allowlist",
"Allowlist": "Allowlist",
"Browse rules": "浏览 Rule",
"Configure workspace-specific permissions, resources, and customizations.": "配置特定于 Workspace 的权限、资源和自定义设置。",
"Console Telemetry": "控制台 Telemetry",
"Context and quota indicator": "Context 与配额指示器",
"Conversation Telemetry": "对话 Telemetry",
"Create a new Cog (GoB) workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始 Prompt 创建新的 Cog (GoB) Workspace。可在“通用设置”的“高级”中自定义。",
"Create a new Fig workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始 Prompt 创建新的 Fig Workspace。可在“通用设置”的“高级”中自定义。",
"Create a new JJ workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始 Prompt 创建新的 JJ Workspace。可在“通用设置”的“高级”中自定义。",
"Create a new Piper (g4) workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始 Prompt 创建新的 Piper (g4) Workspace。可在“通用设置”的“高级”中自定义。",
"Denylist": "Denylist",
"Enable Telemetry": "启用 Telemetry",
"Enable telemetry": "启用 Telemetry",
"Enable telemetry in Settings before changing per-conversation telemetry.": "请先在“设置”中启用 Telemetry,然后再更改单个对话的 Telemetry。",
"File Access Rules": "文件访问 Rule",
"File access rules": "文件访问 Rule",
"Generate personalized rules": "生成个性化 Rule",
"Global Rules": "全局 Rules",
"Grant create, update, or delete access to specific branches.": "授予特定 Branch 的创建、更新或删除权限。",
"Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.": "宿主接受 Context 更新(ui/update-model-context),以便在后续轮次中纳入模型的 Context。",
"Learn from my conversation history to write a personalized set of rules for future agentic interactions.": "从我的对话历史中学习,为未来的 Agent 交互编写一套个性化 Rule。",
"Manage Rules": "管理 Rules",
"Open allowlist": "打开 Allowlist",
"Print telemetry to the console": "将 Telemetry 打印到控制台",
"Rules": "Rule",
"Rules token budget exceeded. Large rules are demoted to path pointers.": "已超出 Rule 的 Token 预算。较大的 Rule 已降级为路径指针。",
"Set the rules, define the boundaries.": "制定 Rule,划定边界。",
"Show how full the context window is next to the send button. Click it for a breakdown and to see your model quota.": "在发送按钮旁显示 Context 窗口的占用情况。点击可查看详细构成和模型配额。",
"Site Allowlist": "站点 Allowlist",
"Telemetry": "Telemetry",
"Telemetry is disabled in Settings": "已在设置中禁用 Telemetry",
"Telemetry is turned off for your account.": "您的账号已关闭 Telemetry。",
"Telemetry will be disabled for this conversation; click to enable.": "本次对话将禁用 Telemetry;点击以启用。",
"The deny list follows the same matching rules as the allow list and takes precedence over the allow list.": "Denylist 遵循与 Allowlist 相同的匹配 Rule,且优先级高于 Allowlist。",
"The settings here only apply to conversations that are under Google3 Projects, which are deprecated. Any new conversations should be grouped by workspace and apply global settings.": "此处的设置仅适用于已弃用的 Google3 项目下的对话。任何新对话都应按 Workspace 分组并应用全局设置。",
"The window title matches a privacy rule.": "窗口标题匹配隐私 Rule。",
"These allowed domain rules are set by your organization's administrator and cannot be removed.": "这些允许的域名 Rule 由您所在组织的管理员设置,无法移除。",
"Unnamed rule": "未命名的 Rule",
"User Rules": "User Rules",
"Which workspace the New Conversation button and keyboard shortcut start you in.": "点击“新建对话”按钮或使用快捷键时默认进入的 Workspace。",
"Workspace Rules": "Workspace Rules",
"Workspace Settings": "Workspace 设置",
"Yes, save rule for '": "是,保存此 Rule:'",
"does not collect any of your prompts, content, or model responses but does collect general usage patterns such as feature adoption and active user counts (“product analytics”). Telemetry data will be handled in accordance with the Google Privacy Policy.": "不会收集您的任何 Prompt、内容或模型回复,但会收集常规使用模式,例如功能采用情况和活跃用户数(“产品分析”)。Telemetry 数据将按照《Google 隐私权政策》进行处理。"
},
"deep": {
"+ Add branch policy": "+ 添加分支策略",
"+ Add pull request policy": "+ 添加拉取请求策略",
"+ Add workflow run policy": "+ 添加工作流运行策略",
"Add to allowlist": "添加到允许名单",
"Added to allowlist": "已添加到允许名单",
"Allowlist": "允许名单",
"Browse rules": "浏览规则",
"Configure workspace-specific permissions, resources, and customizations.": "配置特定于工作区的权限、资源和自定义设置。",
"Console Telemetry": "控制台遥测数据",
"Context and quota indicator": "上下文与配额指示器",
"Conversation Telemetry": "对话遥测数据",
"Create a new Cog (GoB) workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始提示词创建新的 Cog (GoB) 工作区。可在“通用设置”的“高级”中自定义。",
"Create a new Fig workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始提示词创建新的 Fig 工作区。可在“通用设置”的“高级”中自定义。",
"Create a new JJ workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始提示词创建新的 JJ 工作区。可在“通用设置”的“高级”中自定义。",
"Create a new Piper (g4) workspace from your initial prompt. Customize in General Settings, under Advanced.": "根据您的初始提示词创建新的 Piper (g4) 工作区。可在“通用设置”的“高级”中自定义。",
"Denylist": "禁止名单",
"Enable Telemetry": "启用遥测数据",
"Enable telemetry": "启用遥测数据",
"Enable telemetry in Settings before changing per-conversation telemetry.": "请先在“设置”中启用遥测数据,然后再更改单个对话的遥测数据。",
"File Access Rules": "文件访问规则",
"File access rules": "文件访问规则",
"Generate personalized rules": "生成个性化规则",
"Global Rules": "全局规则",
"Grant create, update, or delete access to specific branches.": "授予特定分支的创建、更新或删除权限。",
"Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.": "宿主接受上下文更新(ui/update-model-context),以便在后续轮次中纳入模型的上下文。",
"Learn from my conversation history to write a personalized set of rules for future agentic interactions.": "从我的对话历史中学习,为未来的智能体交互编写一套个性化规则。",
"Manage Rules": "管理规则",
"Open allowlist": "打开允许名单",
"Print telemetry to the console": "将遥测数据打印到控制台",
"Rules": "规则",
"Rules token budget exceeded. Large rules are demoted to path pointers.": "已超出规则的词元预算。较大的规则已降级为路径指针。",
"Set the rules, define the boundaries.": "制定规则,划定边界。",
"Show how full the context window is next to the send button. Click it for a breakdown and to see your model quota.": "在发送按钮旁显示上下文窗口的占用情况。点击可查看详细构成和模型配额。",
"Site Allowlist": "站点允许名单",
"Telemetry": "遥测数据",
"Telemetry is disabled in Settings": "已在设置中禁用遥测数据",
"Telemetry is turned off for your account.": "您的账号已关闭遥测数据。",
"Telemetry will be disabled for this conversation; click to enable.": "本次对话将禁用遥测数据;点击以启用。",
"The deny list follows the same matching rules as the allow list and takes precedence over the allow list.": "禁止名单遵循与允许名单相同的匹配规则,且优先级高于允许名单。",
"The settings here only apply to conversations that are under Google3 Projects, which are deprecated. Any new conversations should be grouped by workspace and apply global settings.": "此处的设置仅适用于已弃用的 Google3 项目下的对话。任何新对话都应按工作区分组并应用全局设置。",
"The window title matches a privacy rule.": "窗口标题匹配隐私规则。",
"These allowed domain rules are set by your organization's administrator and cannot be removed.": "这些允许的域名规则由您所在组织的管理员设置,无法移除。",
"Unnamed rule": "未命名的规则",
"User Rules": "用户规则",
"Which workspace the New Conversation button and keyboard shortcut start you in.": "点击“新建对话”按钮或使用快捷键时默认进入的工作区。",
"Workspace Rules": "工作区规则",
"Workspace Settings": "工作区设置",
"Yes, save rule for '": "是,保存此规则:'",
"does not collect any of your prompts, content, or model responses but does collect general usage patterns such as feature adoption and active user counts (“product analytics”). Telemetry data will be handled in accordance with the Google Privacy Policy.": "不会收集您的任何提示词、内容或模型回复,但会收集常规使用模式,例如功能采用情况和活跃用户数(“产品分析”)。遥测数据将按照《Google 隐私权政策》进行处理。"
}
}
File diff suppressed because it is too large Load Diff
+663
View File
@@ -0,0 +1,663 @@
{
"base": {
"(Optional) Tell us more or type your reason...": "(可选)告诉我们更多信息或输入您的原因...",
"(Optional, defaults to main)": "(可选,默认为 main)",
"(Specific to this client's truncation and pagination)": "(特定于此客户端的截断与分页设置)",
"(excluding product analytics data)": "(不包括产品分析数据)",
"(for example, passwords, messages, or credit cards).": "(例如密码、消息或信用卡)。",
", always on.": ",始终开启。",
", then reopen this dialog.": ",然后重新打开此对话框。",
", then turn it on.": ",然后将其开启。",
". If a page fails to load, use the": "。如果页面加载失败,请使用",
". Try again.": "。请重试。",
". Would you like to continue using it or make a new one?": "。您想继续使用它还是创建一个新的?",
". Your use is subject to the": "。您的使用需遵守",
"...and": "...以及",
"0 is a reserved stream ID.": "0 是保留的流 ID。",
"1. Accessibility": "1. 辅助功能",
"2. Screen Recording": "2. 屏幕录制",
"? This removes it from your config directory.": "?这会将其从您的配置目录中移除。",
"A bash script run in your cloud environment after cloning repositories (or configure interactively in chat with /env-setup).": "克隆仓库后在您的云环境中运行的 bash 脚本(或在对话中使用 /env-setup 进行交互式配置)。",
"A chunk is a section of the page. Long pages are chunked so that only the sections that are relevant to your query are read.": "分块(Chunk)是页面中的一个片段。较长的页面会被分段,以便仅读取与您的查询相关的部分。",
"A comma-separated list like org-a, org-b, or * for all.": "逗号分隔的列表,例如 org-a, org-b,或使用 * 表示全部。",
"A comma-separated list like repo-a, repo-b, or * for all.": "逗号分隔的列表,例如 repo-a, repo-b,或使用 * 表示全部。",
"A customization failed to load": "某个自定义扩展加载失败",
"A fast Talker acks; Jetski answers; a Narrator reads it out.": "由快速的 Talker 应答,Jetski 解答,Narrator 朗读。",
"A group with this name already exists.": "已存在同名分组。",
"A host can't contain spaces.": "主机名不能包含空格。",
"A label for this computer when you connect from another device. Changing it reconnects.": "从其他设备连接时用于标识此计算机的标签。更改后将会重新连接。",
"A new version is available": "有新版本可用",
"A new version is available.": "有新版本可用。",
"A nickname for identifying this application in the companion website. Changing this will restart the connection.": "用于在配套网站中标识此应用的昵称。更改此项将重启连接。",
"A password or secure field is on screen.": "屏幕上存在密码或安全输入字段。",
"A selector must be created from a string; found": "选择器必须从字符串创建;实际得到",
"A snapshot was saved before running. To restore your previous output:": "运行前已保存快照。要恢复之前的输出:",
"A subtler version of list hover background.": "列表悬停背景色的更柔和版本。",
"AI Credits Used to Generate Response": "用于生成回复的 AI 额度",
"APIs, services, and tools to build, test, secure, and run your apps.": "用于构建、测试、加固和运行应用的 API、服务与工具。",
"Abandoned": "已放弃",
"Aborted due to condition callback returning false.": "由于条件回调返回 false,已中止。",
"Absolute path to the Chrome/Chromium executable": "Chrome/Chromium 可执行文件的绝对路径",
"Accent": "强调色",
"Accented Unicode text character \"": "带重音符号的 Unicode 文本字符 \"",
"Access": "访问权限",
"Active environment: os=": "当前环境:os=",
"Adding...": "正在添加...",
"Address CLs needing attention": "处理需要关注的 CL",
"Address bar suggestions": "地址栏建议",
"Advanced Command Access": "高级命令访问权限",
"Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)": "文档允许的基准 URI。\n\n- 映射到 CSP `base-uri` 指令\n- 为空或省略 → 仅允许同源(`base-uri 'self'`)",
"Alpha": "内测版",
"Amending...": "正在修订...",
"An element must be of type `nodes` or `edges`; you specified `": "元素类型必须为 `nodes` 或 `edges`;您指定的是 `",
"An element must have a core reference and parameters set": "元素必须设置核心引用和参数",
"An embedded page on this page says": "此页面中的内嵌页面提示",
"An extra border around active elements to separate them from others for greater contrast.": "活动元素周围的额外边框,用于将其与其他元素分隔开以提高对比度。",
"An extra border around elements to separate them from others for greater contrast.": "元素周围的额外边框,用于将其与其他元素分隔开以提高对比度。",
"An unexpected bug occurred.": "发生了意外错误。",
"Analyze user trends and retention cohorts": "分析用户趋势与留存队列",
"Analyzing Task Log": "正在分析任务日志",
"Answered": "已回答",
"Antigravity (AGY) Style": "Antigravity (AGY) 风格",
"Antigravity Interactive HTML": "Antigravity 交互式 HTML",
"Antigravity can draft docs, analyze files, and organize your work.": "Antigravity 可以起草文档、分析文件并整理你的工作。",
"Antigravity can query tables, clean spreadsheets, and chart trends.": "Antigravity 可以查询数据表、清洗电子表格并绘制趋势图。",
"Antigravity can review code, trace errors, and ship across your stack.": "Antigravity 可以审查代码、追踪错误并完成全栈交付。",
"Antigravity can turn notes and docs into plans, decks, and action items.": "Antigravity 可以将笔记和文档转化为计划、演示文稿与待办事项。",
"Antigravity can turn your designs into live code, briefs, and assets.": "Antigravity 可以将你的设计转化为可运行的代码、设计简报和素材。",
"Any relevant information": "任何相关信息",
"Any resource": "任意资源",
"Apostrophe": "单引号",
"App": "应用",
"Appears larger on mobile": "在移动设备上会显示得更大",
"Applying...": "应用中...",
"Approved": "已批准",
"Approved · Code-Review +2": "已批准 · Code-Review +2",
"Approved · ready to submit": "已批准 · 可提交",
"Approximate; may start a few minutes later": "大约时间;可能会晚几分钟开始",
"Ask": "询问",
"Ask Antigravity...": "向 Antigravity 提问...",
"Ask about your code or any topic, get clear answers.": "询问关于代码或任何话题的问题,获取清晰解答。",
"Ask anything, @ to mention": "任意提问,输入 @ 可提及",
"Ask anything, @ to mention, / for commands": "输入任何问题,@ 引用内容,/ 调用命令",
"Ask anything...": "输入任何问题...",
"Ask before sensitive operations.": "执行敏感操作前先询问。",
"Ask questions, report issues, and discuss features": "提问、报告问题并讨论功能",
"Async validation not supported": "不支持异步验证",
"At least 2 nodes are required for Karger-Stein algorithm": "Karger-Stein 算法至少需要 2 个节点",
"Attaching logs requires an email address": "附加日志需要提供邮箱地址",
"Attackers might be able to see the images you're looking at on this site and trick you by modifying them.": "攻击者可能会看到您在此网站上查看的图片,并通过修改图片来欺骗您。",
"Attackers might be trying to steal your information from": "攻击者可能正试图从以下网站窃取您的信息:",
"Audio streaming transcription not available": "流式音频转录不可用",
"AudioContext closed before fallback capture could start": "在回退音频采集开始前 AudioContext 已关闭",
"AudioWorklet and ScriptProcessorNode are unavailable": "AudioWorklet 和 ScriptProcessorNode 均不可用",
"Authenticated via Enterprise Gateway": "已通过企业网关认证",
"Authenticating...": "正在进行身份验证...",
"Authentication Required": "需要身份验证",
"Authentication required": "需要身份验证",
"Authorization code sign-in is unavailable in this version.": "此版本不支持授权码登录。",
"Authorization code was rejected. Paste a fresh code and try again.": "授权码被拒绝。请粘贴新的授权码并重试。",
"Auto-Expand Changes Overview": "自动展开更改概览",
"Auto-assignment not configured": "未配置自动分配",
"Automatically decide if commands run.": "自动决定是否运行命令。",
"Automatically reproduce bugs, trace causes, test fixes.": "自动复现 Bug、追踪原因并测试修复方案。",
"Available AI credits (undefined means not loaded yet)": "可用 AI 额度(undefined 表示尚未加载)",
"Available CEL helper functions": "可用的 CEL 辅助函数",
"Axis color for the chart.": "图表的坐标轴颜色。",
"Background": "背景色",
"Backquote": "反引号",
"Backslash": "反斜杠",
"Best of N mode is not available": "多路择优模式不可用",
"Beta": "测试版",
"Better instruction following": "指令遵循更准确",
"Binary file": "二进制文件",
"Bold": "粗体",
"Bookmarked": "已收藏",
"Bookmarking": "正在收藏",
"Boolean AND, OR, and negation": "布尔与(AND)、或(OR)与非(NOT)",
"Bot name must be between 3 and 24 characters": "机器人名称长度必须为 3 到 24 个字符",
"Both owners must be this graph!": "两个所有者都必须是此图!",
"Brief me on my meetings every morning": "每天早上为我汇总会议简报",
"Bring over my setup from other Agentic Developer Tools": "从其他智能体开发工具迁移我的配置",
"Build Cleaner completed for": "Build Cleaner 已完成:",
"Build Cleaner is running on": "Build Cleaner 正在运行于",
"Build a dashboard from my sheet": "根据我的表格构建仪表板",
"Build a page from my Figma design": "根据我的 Figma 设计构建页面",
"Build me a web app": "帮我构建一个 Web 应用",
"Build on Google's developer platforms, including Android, Chrome, Gemini, and Google Cloud.": "基于 Google 开发者平台(包括 Android、Chrome、Gemini 和 Google Cloud)进行构建。",
"Build with Google": "与 Google 共建",
"Building": "正在构建",
"Built": "已构建",
"Built to help, not hurt": "旨在提供帮助,而非造成伤害",
"Business": "商业与办公",
"By using this app, you agree to its": "使用本应用即表示您同意其",
"CEL Expression Reference": "CEL 表达式参考",
"CSP domains approved by the host.": "主机批准的 CSP 域名。",
"CSS blocks that apps can inject.": "应用可注入的 CSS 块。",
"CSS variables for theming the app.": "用于定制应用主题的 CSS 变量。",
"Cache": "缓存",
"Calling 'cancelAndSet' on a disposed IntervalTimer": "在已释放的 IntervalTimer 上调用了 'cancelAndSet'",
"Calling 'cancelAndSet' on a disposed TimeoutTimer": "在已释放的 TimeoutTimer 上调用了 'cancelAndSet'",
"Calling 'setIfNotSet' on a disposed TimeoutTimer": "在已释放的 TimeoutTimer 上调用了 'setIfNotSet'",
"Can not get id list for null key": "无法获取空键的 ID 列表",
"Can't open the Drive link?": "无法打开 Drive 链接?",
"Canceled": "已取消",
"Canceled bookmark of": "已取消收藏:",
"Canceled creation of": "已取消创建:",
"Canceled deletion of": "已取消删除:",
"Canceled edit to": "已取消编辑:",
"Canceled removal of bookmark": "已取消移除收藏",
"Canceling": "正在取消",
"Cannot revert messages before or at the point where Best of N mode was triggered": "无法撤销在 Best of N 模式触发时或之前的消息",
"Cannot revert to a message that was cleared to save space": "无法回退到已为节省空间而清理的消息",
"Canvas page · display only": "Canvas 页面 · 仅作展示",
"Canvas · written by your Chief of Staff · display only": "Canvas · 由您的幕僚长撰写 · 仅作展示",
"Caps Lock": "大写锁定",
"Caret": "插入符",
"Catch up on my recent meeting notes": "快速回顾我最近的会议纪要",
"Certificate is not valid": "证书无效",
"Certificate is valid": "证书有效",
"Change details unavailable": "变更详情不可用",
"Check a BigQuery table for anomalies": "检查 BigQuery 数据表中的异常情况",
"Check that the microphone is unmuted and the right input device is selected.": "请检查麦克风是否已取消静音,并确保已选择正确的输入设备。",
"Checking access...": "正在检查访问权限...",
"Checking command status": "正在检查命令状态",
"Checking...": "正在检查...",
"Checks": "检查项",
"Chief of Staff Dashboard": "幕僚长仪表板",
"Children of root nodes must be elements or decorators": "根节点的子节点必须是元素或装饰器",
"Choose between non-colliding VS Code defaults or standalone Antigravity chords.": "在无冲突的 VS Code 默认快捷键或独立的 Antigravity 组合键之间进行选择。",
"Choose the experience that fits how you work.": "选择适合您工作方式的体验。",
"Choose where links open by default when clicked.": "选择点击链接时的默认打开位置。",
"Choose…": "选择…",
"Circle": "圆形",
"Clear cookies and site data": "清除 Cookie 和网站数据",
"Clear visited URLs and autocomplete suggestions from side panel preview.": "清除侧边栏预览中已访问的 URL 和自动补全建议。",
"Clearing cookies and site data for": "正在清除 Cookie 和网站数据:",
"Click items to multi-select · Drag or ‹/› pills to reorder": "点击项目以多选 · 拖动或点击 ‹/› 标签重新排序",
"Click to copy full command": "点击复制完整命令",
"Click to disable tool": "点击禁用工具",
"Click to enable tool": "点击启用工具",
"Click to learn more about sources": "点击了解有关来源的更多信息",
"Click to load": "点击加载",
"Click to view or edit comment": "点击查看或编辑评论",
"Clicked": "已点击",
"Clicking": "正在点击",
"Clone from This Computer": "从此计算机克隆",
"Closed": "已关闭",
"Cloud Hosting & Deployment": "云托管与部署",
"Cmd+click to open": "按住 Cmd 并点击打开",
"Code Preview": "代码预览",
"Collapse IWA installation steps": "折叠 IWA 安装步骤",
"Collapse command": "收起命令",
"Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations.": "与所选内容相同区域的颜色。颜色不能为不透明,以免遮挡底层装饰。",
"Color for text separators.": "文本分隔符的颜色。",
"Color of active links.": "活动链接的颜色。",
"Color of focused breadcrumb items.": "获得焦点的面包屑导航项的颜色。",
"Color of selected breadcrumb items.": "已选中的面包屑导航项的颜色。",
"Combined event_type clauses share no compatible event type": "组合的 event_type 子句没有兼容的事件类型",
"Coming Soon": "即将推出",
"Comma": "逗号",
"Comments unavailable at this screen size": "当前屏幕尺寸下无法显示评论",
"Common ancestor content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.": "内联合并冲突中共同祖先内容的背景色。颜色不能为不透明,以免遮挡底层装饰。",
"Common ancestor header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.": "内联合并冲突中共同祖先标题的背景色。颜色不能为不透明,以免遮挡底层装饰。",
"Common ancestor overview ruler foreground for inline merge-conflicts.": "内联合并冲突中共同祖先概览标尺的前景色。",
"Communication": "沟通协作",
"Complete Onboarding Step": "完成引导步骤",
"Complete tool call arguments as key-value pairs.": "以键值对形式补全工具调用参数。",
"Configuration saved successfully!": "配置已成功保存!",
"Configure a chat bot so you can use Jetski directly from Google Chat.": "配置聊天机器人,以便直接从 Google Chat 使用 Jetski。",
"Configure allowed and denied URLs for reading.": "配置允许和禁止读取的 URL。",
"Configure when follow-up messages are sent.": "配置后续消息的发送时机。",
"Confirmation required to execute this step": "执行此步骤需要确认",
"Confirming this undo action will make the following changes:": "确认此撤销操作将进行以下更改:",
"Connected Google Drive and GitHub resources": "已连接的 Google Drive 和 GitHub 资源",
"Connected account": "已连接账号",
"Connecting to language server...": "正在连接到语言服务器...",
"Connecting...": "连接中...",
"Connection has closed.": "连接已关闭。",
"Continue with Google Cloud": "使用 Google Cloud 继续",
"Contrast": "对比度",
"Cookies and other site data": "Cookie 及其他网站数据",
"Copied sign-in link to clipboard": "已将登录链接复制到剪贴板",
"Copied version details": "已复制版本详情",
"Copy full URL to clipboard": "复制完整 URL 到剪贴板",
"Copy gh auth login command": "复制 gh auth login 命令",
"Core AI Systems is hiring!": "Core AI Systems 正在招聘!",
"Correctness": "正确性",
"Couldn't clear browsing data. Try again.": "无法清除浏览数据。请重试。",
"Couldn't connect": "无法连接",
"Couldn't load Google Drive link title": "无法加载 Google Drive 链接标题",
"Couldn't load cookies.": "无法加载 Cookie。",
"Couldn't load harnesses.": "无法加载运行框架。",
"Couldn't load older messages · Retry": "无法加载更早的消息 · 重试",
"Couldn't load older messages. Try again.": "无法加载更早的消息。请重试。",
"Couldn't switch accounts:": "无法切换账号:",
"Created": "已创建",
"Creating": "正在创建",
"Creating Fork...": "正在创建 Fork...",
"Creating environment...": "正在创建环境...",
"Creating...": "正在创建...",
"Credentials are only sent to the domains listed.": "凭据仅会发送到列出的域名。",
"Credentials stay on this machine and are only sent to the domains listed.": "凭据仅保留在本机,且只会发送到列出的域名。",
"Cron expression e.g. 0 */6 * * *": "Cron 表达式,例如 0 */6 * * *",
"Current content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.": "行内合并冲突中当前内容的背景色。该颜色不能为不透明,以免遮挡底层修饰。",
"Current header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.": "行内合并冲突中当前标题栏的背景色。该颜色不能为不透明,以免遮挡底层修饰。",
"Current overview ruler foreground for inline merge-conflicts.": "行内合并冲突中当前概览标尺的前景色。",
"Cyclic deriveds are not supported yet!": "暂不支持循环派生值!",
"Daily environment time used": "每日环境已用时长",
"Dark Theme": "深色主题",
"Data & Analytics": "数据与分析",
"Data serializer was not provided.": "未提供数据序列化器。",
"Debug (Enabled)": "调试(已启用)",
"DecoratorNode: node %s is both slotted into host %s and a child of parent %s; __slotHost and __parent are mutually exclusive": "DecoratorNode:节点 %s 同时插入了宿主 %s 且为父节点 %s 的子节点;__slotHost 与 __parent 互斥",
"Default harness": "默认执行框架",
"Deleting": "正在删除",
"Deleting Recording methods": "正在删除录制方法",
"Deleting...": "正在删除...",
"Deploy and host your apps, sites, and their backends.": "部署并托管你的应用、网站及其后端服务。",
"Describe the bug you encountered...": "请描述你遇到的 Bug...",
"Describe the feature you would like to see...": "请描述你希望看到的功能...",
"Describe your changes, or leave empty to auto-generate": "描述你的更改,或留空以自动生成",
"Design": "设计",
"Design, Creative & Media": "设计、创意与媒体",
"Design, creative, and media tools.": "设计、创意与媒体工具。",
"Dev": "开发版",
"Dev mode: Localhost server automatically detected": "开发模式:已自动检测到 localhost 服务器",
"Developer Tools": "开发者工具",
"Developer: Reset Onboarding": "开发者:重置新手引导",
"Did not receive status from server endpoint.": "未从服务端点收到状态。",
"Did restarting the desktop app help?": "重启桌面应用是否有效?",
"Direct access storage": "直接访问存储",
"Directories": "目录",
"Directory": "目录",
"Disabled. Open Details to finish setup or enable.": "已禁用。打开“详情”以完成设置或启用。",
"Disables all safety barriers for maximal iteration velocity.": "禁用所有安全防护以实现最高迭代速度。",
"Disabling or removing this bundle doesn't affect it.": "禁用或移除此捆绑包不会影响它。",
"Disk storage": "磁盘存储",
"Dismiss IWA installation banner": "关闭 IWA 安装横幅",
"Dismiss service announcement": "关闭服务公告",
"Dismiss text selection notice": "关闭文本选择提示",
"Display mode for UI presentation.": "用于界面呈现的显示模式。",
"Divided process shape": "分段流程图形",
"Do not use for PII/NTK data.": "请勿用于 PII/NTK 敏感数据。",
"Don't enter corp passwords": "请勿输入公司密码",
"Don't show this for 2 days": "2 天内不再显示",
"Done.": "完成。",
"Down": "向下",
"Download Jetski IWA (jetski-shell.swbn)": "下载 Jetski IWA (jetski-shell.swbn)",
"Download the bundle manually and share it instead:": "改为手动下载捆绑包并分享:",
"Download the signed bundle, open": "下载已签名的捆绑包,打开",
"Downloading...": "正在下载...",
"Draft": "草稿",
"Draft documents, emails, and notes that sound like you.": "起草符合你风格的文档、电子邮件和笔记。",
"Draft · not yet sent for review": "草稿 · 尚未发送审核",
"Drag to resize, double-click to reset": "拖动以调整大小,双击重置",
"Drag to select a region to comment": "拖动以选择要评论的区域",
"Draws from your organization's pooled Gemini Enterprise usage.": "从贵组织的 Gemini Enterprise 共享用量池中扣除。",
"E.g. locations/global/workforcePools...": "例如 locations/global/workforcePools...",
"Empty \"in []\" list literal is not allowed": "不允许使用空的 \"in []\" 列表字面量",
"Empty script.": "空脚本。",
"Enable AI Credit Overages": "启用 AI 额度超额使用",
"Enable AI credit overages": "启用 AI 额度超额使用",
"Enable Chrome IWA flags and relaunch Chrome:": "启用 Chrome IWA 标志并重启 Chrome:",
"Enable Demo Mode (Beta)": "启用演示模式 (Beta)",
"Enable Shell Integration": "启用 Shell 集成",
"Enabling...": "正在启用...",
"Encountered errors while disposing of store": "释放状态存储时遇到错误",
"End of Life": "即将停止支持",
"Enter URL pattern...": "输入 URL 模式...",
"Enter a URL (e.g. http://localhost:8080)": "输入 URL(例如 http://localhost:8080)",
"Enter a side question after /btw": "在 /btw 后输入附加问题",
"Enter authorization code...": "输入授权码...",
"Enter avatar URL (optional)": "输入头像 URL(可选)",
"Enter bot name (optional)": "输入机器人名称(可选)",
"Enter command...": "输入命令...",
"Enter device name...": "输入设备名称...",
"Enter directory path...": "输入目录路径...",
"Enter target...": "输入目标...",
"Enter tool name or server...": "输入工具名称或服务器...",
"Enter your feedback here...": "在此输入你的反馈...",
"Enterprise Gateway": "企业网关",
"Environment name should contain only text characters and spaces": "环境名称只能包含文本字符和空格",
"Equal": "等号",
"Equality and list membership (e.g.": "相等性与列表成员关系(例如",
"Errored": "已出错",
"Event type": "事件类型",
"Events and stdout streams will appear here as they occur.": "事件和 stdout 输出流将在发生时显示在这里。",
"Exit inspect element mode (Esc)": "退出检查元素模式 (Esc)",
"Expand IWA installation steps": "展开 IWA 安装步骤",
"Expected TextNode createDOM to always return a HTMLElement": "预期 TextNode createDOM 始终返回 HTMLElement",
"Expected \\\\ or \\cr or \\end": "预期为 \\\\\\\\、\\\\cr 或 \\\\end",
"Expected a control sequence": "预期为控制序列",
"Expected a macro definition": "预期为宏定义",
"Expected ancestor to be a block ElementNode": "预期祖先节点为块级 ElementNode",
"Expected node %s to have a parent.": "预期节点 %s 具有父节点。",
"Expected node %s to have a top parent element.": "预期节点 %s 具有顶层父元素。",
"Expected node %s to have closest block element node.": "预期节点 %s 具有最近的块级元素节点。",
"Expected node with key %s to exist but it's not in the nodeMap.": "预期键为 %s 的节点存在,但它不在 nodeMap 中。",
"Expected parentElement of Text not to be null": "预期 Text 的 parentElement 不为 null",
"Expected valid LexicalSelection": "预期为有效的 LexicalSelection",
"Experimental features (structure TBD).": "实验性功能(结构待定)。",
"Explore the proteins behind our 24-hour body clock.": "探索控制人体 24 小时生物钟的蛋白质。",
"Explore the synthesis of aspirin.": "探索阿司匹林的合成过程。",
"Explored": "已探索",
"Exploring": "正在探索",
"Extra": "额外",
"Extracting DOM elements": "正在提取 DOM 元素",
"Extraction process": "提取流程",
"Failed to build": "构建失败",
"Feature Environment Override": "功能环境覆盖",
"Fetched network request": "已获取网络请求",
"Fetched network request for page.": "已获取页面网络请求。",
"Fetched network requests": "已获取网络请求",
"Fetched network requests for page.": "已获取页面网络请求。",
"Fetching network request": "正在获取网络请求",
"Fetching network requests": "正在获取网络请求",
"Fill": "填充",
"Finalizing transcription...": "正在完成转录...",
"Finalizing...": "正在完成...",
"Find in page...": "在页面中查找...",
"Fires after a tool step completes.": "在工具步骤完成后触发。",
"Fires after tool calls finish.": "在工具调用结束后触发。",
"Fires before a tool step executes.": "在工具步骤执行前触发。",
"Fires when the execution loop terminates.": "在执行循环终止时触发。",
"Follow up...": "继续追问...",
"Font": "字体",
"Footnotes": "脚注",
"For Antigravity Business consumption options, see": "有关 Antigravity Business 的用量选项,请参阅",
"For a full list of available locations and deployment endpoints, please refer to the": "有关可用位置和部署端点的完整列表,请参阅",
"For any feedback that does not fit into the above categories.": "适用于不属于上述任何类别的反馈。",
"For corp passwords (such as": "对于公司密码(例如",
"For example: Morning bug summary": "例如:早间 Bug 汇总",
"For example: every morning, summarize new bugs assigned to me and anything that changed overnight.": "例如:每天早上汇总分配给我的新 Bug 以及夜间发生的所有变更。",
"Foreground": "前景色",
"Fork Environment Notice": "派生环境提示",
"Frames must be associated with a stream.": "帧必须与流关联。",
"Generated image preview": "生成的图片预览",
"Generating...": "生成中...",
"Generic": "通用",
"Getting scripts...": "正在获取脚本...",
"Getting started with Google Antigravity": "Google Antigravity 入门指南",
"Good to see you. What's next?": "很高兴见到您。接下来要做什么?",
"Google Antigravity - Experience liftoff": "Google Antigravity - 体验启航",
"Google Antigravity Terms of Service": "Google Antigravity 服务条款",
"Google Workspace": "Google Workspace",
"Google does not control the availability or functionality of third party developer tools. Your data from third party developer tools connected to your Antigravity instance may be shared with Google. Google will protect any such data in accordance with the Google Privacy Policy, found here:": "Google 无法控制第三方开发者工具的可用性或功能。连接到你 Antigravity 实例的第三方开发者工具中的数据可能会与 Google 共享。Google 将按照此处提供的《Google 隐私权政策》保护此类数据:",
"Got group of unknown type: '": "获取到未知类型的分组:'",
"Grand Total": "总计",
"Grant administrator access for": "为以下对象授予管理员权限",
"Grant repository access": "授予仓库访问权限",
"Grant the selected actions on the listed issue numbers — a comma-separated list like 1, 2, 3, or * for all.": "对列出的 Issue 编号授予所选操作——以逗号分隔的列表,例如 1、2、3,或使用 * 表示全部。",
"Graph already in this graph mgr!": "图已在此图管理器中!",
"Graph contains a negative weight cycle for Bellman-Ford": "图中包含 Bellman-Ford 算法的负权环",
"Graph has no graph mgr!": "图没有图管理器!",
"Graph not in this graph mgr": "图不在此图管理器中",
"Green": "绿色",
"Guide line for the chart.": "图表的参考线。",
"Hand off a feature and come back to working code.": "交接一个功能需求,回来即可看到可用的代码。",
"Harnesses are unavailable from this language server.": "此语言服务器暂不支持运行框架。",
"Having trouble signing in?": "登录遇到问题?",
"Headers must be received before any other frames.": "必须在任何其他帧之前接收标头。",
"Headers must be sent before any other frames.": "必须在任何其他帧之前发送标头。",
"Hey there, what should we build today?": "你好,今天我们打算构建什么?",
"Hide Whitespace Changes": "隐藏空白字符变更",
"Highlight": "高亮",
"Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations.": "在显示悬停提示的单词下方高亮显示。颜色不能为不透明,以免遮挡底层装饰。",
"Host accepts log messages.": "宿主接受日志消息。",
"Host supports audio content blocks.": "宿主支持音频内容块。",
"Host supports image content blocks.": "宿主支持图像内容块。",
"Host supports opening external URLs.": "宿主支持打开外部 URL。",
"Host supports resource content blocks.": "宿主支持资源内容块。",
"Host supports resource link content blocks.": "宿主支持资源链接内容块。",
"Host supports resources/list_changed notifications.": "宿主支持 resources/list_changed 通知。",
"Host supports structured content.": "宿主支持结构化内容。",
"Host supports text content blocks.": "宿主支持文本内容块。",
"Host supports tool use via `tools` and `toolChoice` parameters.": "宿主支持通过 `tools` 和 `toolChoice` 参数使用工具。",
"Host supports tools/list_changed notifications.": "宿主支持 tools/list_changed 通知。",
"How this feature would help you and other users": "此功能将如何为您和其他用户提供帮助",
"I prefer an immediate single response to prioritize productivity right now.": "我现在更希望立即获得单次响应,以优先提高效率。",
"If set, color of double underlines for errors in the editor.": "如果设置,表示编辑器中错误双下划线的颜色。",
"If set, color of double underlines for hints in the editor.": "如果设置,表示编辑器中提示双下划线的颜色。",
"If set, color of double underlines for infos in the editor.": "如果设置,表示编辑器中信息双下划线的颜色。",
"If set, color of double underlines for warnings in the editor.": "如果设置,表示编辑器中警告双下划线的颜色。",
"If that machine is a cloudtop, reach it via": "如果该机器是 cloudtop,请通过以下方式访问",
"If this is an intentional render callback, rename it to start with a lowercase letter.": "如果这是有意为之的渲染回调,请将其重命名为以小写字母开头。",
"Ignore events emitted by automated review or robot accounts (groupagent-*).": "忽略由自动审查或机器人账号(groupagent-*)发出的事件。",
"Image preview not available": "无法预览图像",
"Image rendering blocked (strict mode enabled)": "图像渲染已阻止(已启用严格模式)",
"Important": "重要",
"In LaTeX, \\\\ or \\newline does nothing in display mode": "在 LaTeX 中,\\\\ 或 \\newline 在展示模式下不起作用",
"In review · waiting on reviewers": "评审中 · 等待审阅人",
"Include Jetski Default Customizations": "包含 Jetski 默认自定义项",
"Include Jetski default customizations": "包含 Jetski 默认自定义项",
"Include at least one positive": "至少包含一个正向项",
"Include unstaged changes": "包含未暂存的更改",
"Incoming content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.": "行内合并冲突中传入内容的背景色。该颜色不能为不透明,以免遮挡底层装饰。",
"Incoming header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.": "行内合并冲突中传入标题的背景色。该颜色不能为不透明,以免遮挡底层装饰。",
"Incoming overview ruler foreground for inline merge-conflicts.": "行内合并冲突中传入内容的概览标尺前景色。",
"Incompatible event type": "不兼容的事件类型",
"Incomplete operator at end of expression": "表达式末尾存在不完整的运算符",
"Incomplete placeholder at end of macro body": "宏主体末尾存在未完成的占位符",
"Incorrect edge source and/or target": "边的源节点和/或目标节点不正确",
"Indent value must be non-negative.": "缩进值必须为非负数。",
"Indexed CEL helper functions": "已建立索引的 CEL 辅助函数",
"Initializing...": "正在初始化...",
"Ink": "墨水",
"Inline PDF preview is not available in this environment.": "当前环境不支持行内 PDF 预览。",
"Input": "输入",
"Insert": "插入",
"Inspect element to comment": "检查元素以添加评论",
"Inspect live bindings or record custom key chords filtered to": "查看实时键位绑定或录制自定义组合键,筛选范围:",
"Inspecting documentation, config, or issues...": "正在检查文档、配置或问题...",
"Install → Signed Bundle → Install": "安装 → 签名捆绑包 → 安装",
"Installing...": "正在安装...",
"Insufficient AI Credits": "AI 额度不足",
"Integers must be within the safe integer range.": "整数必须在安全整数范围内。",
"Intended primarily for previewing local development servers (e.g.,": "主要用于预览本地开发服务器(例如,",
"Internal storage": "内部存储",
"Interrupted": "已中断",
"Invalid": "无效",
"Invalid indent value.": "缩进值无效。",
"Italic": "斜体",
"JavaScript execution disabled in strict mode": "严格模式下已禁用 JavaScript 执行",
"Jetski Chat configuration is not available in the current environment.": "当前环境中无法使用 Jetski Chat 配置。",
"Jetski and Cider are now more closely integrated:": "Jetski 与 Cider 现已实现更紧密的集成:",
"Join the Google Chat space": "加入 Google Chat 聊天室",
"Junction point": "连接点",
"Karger-Stein must be run on a connected (sub)graph": "Karger-Stein 算法必须在连通(子)图上运行",
"Keeps your checkout untouched": "保持当前检出目录不受影响",
"Knowledge Work": "知识工作",
"Language Server Client Infos": "语言服务器客户端信息",
"Language Server Client Machine Infos": "语言服务器客户端机器信息",
"Last": "最后",
"Latin-1/Unicode text character \"": "Latin-1/Unicode 文本字符 \"",
"Laziness": "惰性",
"Learn more by visiting our": "了解更多请访问我们的",
"Learn more.": "了解更多。",
"Leaving Soon": "即将下线",
"Leaving soon": "即将下线",
"Left": "左",
"Legacy": "旧版",
"Legacy Light": "经典浅色",
"Let's tailor the experience for you. What best describes your work?": "让我们为您量身定制使用体验。哪项最符合您的工作?",
"LexicalBuilder.fromEditor: The given editor was not created with LexicalBuilder": "LexicalBuilder.fromEditor:传入的编辑器不是由 LexicalBuilder 创建的",
"LexicalNode.isBefore: exhaustiveness check": "LexicalNode.isBefore:穷举性检查",
"Light Theme": "浅色主题",
"Limit controls must follow a math operator": "极限控件必须跟在数学运算符之后",
"Limited": "限量",
"Line color for the chart.": "图表的线条颜色。",
"Lined document": "横线文档",
"Link": "链接",
"Link copied to clipboard.": "链接已复制到剪贴板。",
"Listening. Ask anything.": "正在聆听,请随时提问。",
"Live preview unavailable": "实时预览不可用",
"Loading Notebook View...": "正在加载 Notebook 视图...",
"Loading apps...": "正在加载应用...",
"Loading bundles...": "正在加载资源包...",
"Loading customizations...": "正在加载自定义项...",
"Loading events...": "正在加载事件...",
"Loading instances...": "正在加载实例...",
"Loading licenses...": "正在加载许可证...",
"Loading logs...": "正在加载日志...",
"Loading media...": "正在加载媒体...",
"Loading messages": "正在加载消息",
"Loading newer messages": "正在加载更新的消息",
"Loading newer messages…": "正在加载更新的消息…",
"Loading older messages…": "正在加载更早的消息…",
"Loading resources...": "正在加载资源...",
"Loading trajectory...": "正在加载轨迹...",
"Loading...": "正在加载...",
"Locked while grouped by Status": "按状态分组时已锁定",
"Long pages like this one will be broken down into outlines and read as needed. Read more at our": "像这样的长页面将被拆分为大纲,并按需读取。了解更多请访问我们的",
"Loop limit step": "循环上限步骤",
"Make sure the ref is set before accessing the element. Maybe wrong initialization order?": "访问元素前请确保已设置 ref。可能是初始化顺序有误?",
"Manage project folders and settings.": "管理项目文件夹与设置。",
"Manage project resources and settings.": "管理项目资源与设置。",
"Managed by Enterprise Gateway": "由企业网关托管",
"Managed by application menu": "由应用程序菜单管理",
"Manager": "管理器",
"Manual file operation": "手动文件操作",
"Manual input step": "手动输入步骤",
"Manually Rejected": "已手动拒绝",
"Manually customize individual settings.": "手动自定义各项设置。",
"Match when push_def equals or is a child of the given PushDef prefix.": "当 push_def 等于指定的 PushDef 前缀或为其子项时匹配。",
"Match when the issue component equals or is under the given Buganizer component ID.": "当问题组件等于指定 Buganizer 组件 ID 或位于其下级时匹配。",
"Match when the principal belongs to the specified MDB group.": "当主体属于指定的 MDB 组时匹配。",
"Match when the principal equals any listed username or belongs to any listed mdb/ group.": "当主体等于任意所列用户名或属于任意所列 mdb/ 组时匹配。",
"Maximize Width": "最大化宽度",
"Maximum number of attachments reached": "已达到附件数量上限",
"Memo": "备忘录",
"Merged": "已合并",
"Message": "消息",
"Message queued.": "消息已加入队列。",
"Microphone capture ended unexpectedly.": "麦克风采集意外结束。",
"Microphone capture is not supported in this environment.": "当前环境不支持麦克风采集。",
"Microphone is already in use by another recording session.": "麦克风正被另一个录音会话占用。",
"Microphone open timed out": "打开麦克风超时",
"Minimized": "已最小化",
"Minus": "减号",
"Missing": "缺失",
"Missing Folder": "文件夹不存在",
"Missing a repository? Configure on GitHub": "找不到仓库?前往 GitHub 配置",
"Modes": "模式",
"Module": "模块",
"Most popular first": "最受欢迎优先",
"Most popular matches first": "最受欢迎匹配优先",
"Moved to Resolved.": "已移至“已解决”。",
"Movie": "影片",
"Multiple documents": "多份文档",
"Multiple processes": "多个流程",
"already exists for this": "已存在于当前",
"already exists.": "已存在。",
"and add it again.": "并重新添加。",
"and make it the default.": "并将其设为默认。",
"and sign in again.": "并重新登录。",
"antigravity.": "Antigravity。",
"button in the status bar to report any issues.": "按钮(位于状态栏中)以报告任何问题。",
"by allowing Google to collect and use my Interactions data, subject to the": "允许 Google 收集和使用我的交互数据,但需遵守",
"chunks were collapsed into one. Chunks included in this read:": "个区块已合并为一个。本次读取包含的区块:",
"commands.": "命令。",
"directly in the side pane.": "直接在侧边窗格中。",
"do not exist.": "不存在。",
"does not exist.": "不存在。",
"drawing rectangle preview": "矩形绘制预览",
"e.g. Release helper": "例如 Release helper",
"e.g. ci.yml,deploy.yml or *": "例如 ci.yml,deploy.yml 或 *",
"e.g. google or *": "例如 google 或 *",
"e.g. in_mdb(author, \"mdb/my-team\") && !is_watching_user(actor)": "例如 in_mdb(author, \"mdb/my-team\") && !is_watching_user(actor)",
"e.g. jetski or *": "例如 jetski 或 *",
"e.g. main,dev or *": "例如 main,dev 或 *",
"e.g. work": "例如 work",
"e.g., chromium/chromium/src": "例如:chromium/chromium/src",
"e.g., chromium/src": "例如:chromium/src",
"e.g., curl": "例如:curl",
"e.g., example.com": "例如:example.com",
"e.g., https://example.com": "例如:https://example.com",
"e.g., main or refs/heads/main": "例如:main 或 refs/heads/main",
"e.g., npm test": "例如:npm test",
"e.g., refs/heads/main or main": "例如:refs/heads/main 或 main",
"e.g., ~/my-feature": "例如:~/my-feature",
"example:\nnpm ci && npm run build": "示例:\nnpm ci && npm run build",
"example:\nsource ~/.jetski_shell_setup": "示例:\nsource ~/.jetski_shell_setup",
"for debugging.": "以便调试。",
"for more help.": "以获取更多帮助。",
"icon in the URL bar.": "URL 栏中的图标。",
"in the top left.": "在左上角。",
"in the top menu.": "在顶部菜单中。",
"later.": "稍后。",
"main (or e.g., sc-dev, sc-release)": "main(或例如 sc-dev、sc-release)",
"managed by your organization": "由您的组织管理",
"may sign you out of this site.": "可能会使您退出此网站。",
"more...": "更多...",
"— narrow matched events by status, priority, or event details": "— 按状态、优先级或事件详情缩小匹配事件范围",
"— specify at least one user, team, component, or resource (joined with": "— 至少指定一个用户、团队、组件或资源(连接方式为",
"” already exists.": "”已存在。"
},
"light": {
"A copy of the workspace snapshot recorded at this step.": "此步骤记录的 Workspace 快照副本。",
"Agent settings and permissions for conversations outside of projects.": "非项目对话的 Agent 设置与权限。",
"Agent settings and permissions for conversations outside of workspaces.": "Workspace 外对话的 Agent 设置与权限。",
"Agent skills, databases, and interactive viewers for scientific research.": "面向科学研究的 Agent Skill、数据库和交互式查看器。",
"Amend staged changes into the current commit": "将暂存更改追加修订到当前 Commit",
"Antigravity can synthesize scientific literature, build interactive visualizations, and run workflows across biology, chemistry, and more.": "Antigravity 可以综合科学文献、构建交互式可视化,并在生物、化学等领域运行 Workflow。",
"Back to all agents": "返回全部 Agent",
"Both staged and unstaged changes are being committed.": "将同时 Commit 暂存和未暂存的更改。",
"CL details unavailable": "CL 详情不可用",
"Cannot revert a message sent while the agent was running": "无法撤销在 Agent 运行期间发送的消息",
"Cannot revert messages with artifact comments": "无法撤销带有 Artifact 评论的消息",
"Cannot revert messages with file diff comments": "无法撤销带有文件 Diff 评论的消息",
"Cleared built-in browser data": "已清除内置 Browser 数据",
"Clicking in Browser": "正在 Browser 中点击",
"Commits": "Commits",
"Committing...": "正在 Commit...",
"Configuration parameters are required before this server can be started": "启动此 Server 前需要填写配置参数",
"Couldn't create the agent. Try again.": "无法创建 Agent,请重试。",
"Dragging in Browser": "正在 Browser 中拖拽",
"From a plugin": "来自 Plugin",
"Full interface for coding, developer tools, and managing agents.": "用于编写代码、使用开发者工具及管理 Agent 的完整界面。",
"Hook": "Hook",
"Manage project folders, agent settings, and permissions.": "管理项目文件夹、Agent 设置和权限。",
"Manage project resources, agent settings, and permissions.": "管理项目资源、Agent 设置和权限。",
"Manage workspace folders and settings.": "管理 Workspace 文件夹与设置。",
"Manage workspace folders, agent settings, and permissions.": "管理 Workspace 文件夹、Agent 设置和权限。",
"Manage workspace resources and settings.": "管理 Workspace 资源与设置。",
"Model cannot be changed while the agent is running": "Agent 运行期间无法切换模型",
"Modify permissions for file, terminal, and MCP tools.": "修改文件、Terminal 与 MCP 工具的权限。",
"Moving Mouse in Browser": "正在 Browser 中移动鼠标",
"from a plugin": "来自 Plugin"
},
"deep": {
"A copy of the workspace snapshot recorded at this step.": "此步骤记录的工作区快照副本。",
"Agent settings and permissions for conversations outside of projects.": "非项目对话的智能体设置与权限。",
"Agent settings and permissions for conversations outside of workspaces.": "工作区外对话的智能体设置与权限。",
"Agent skills, databases, and interactive viewers for scientific research.": "面向科学研究的智能体技能、数据库和交互式查看器。",
"Amend staged changes into the current commit": "将暂存更改追加修订到当前提交",
"Antigravity can synthesize scientific literature, build interactive visualizations, and run workflows across biology, chemistry, and more.": "Antigravity 可以综合科学文献、构建交互式可视化,并在生物、化学等领域运行工作流。",
"Back to all agents": "返回全部智能体",
"Both staged and unstaged changes are being committed.": "将同时提交暂存和未暂存的更改。",
"CL details unavailable": "变更列表详情不可用",
"Cannot revert a message sent while the agent was running": "无法撤销在智能体运行期间发送的消息",
"Cannot revert messages with artifact comments": "无法撤销带有产物评论的消息",
"Cannot revert messages with file diff comments": "无法撤销带有文件差异评论的消息",
"Cleared built-in browser data": "已清除内置浏览器数据",
"Clicking in Browser": "正在浏览器中点击",
"Commits": "提交记录",
"Committing...": "正在提交...",
"Configuration parameters are required before this server can be started": "启动此服务前需要填写配置参数",
"Couldn't create the agent. Try again.": "无法创建智能体,请重试。",
"Dragging in Browser": "正在浏览器中拖拽",
"From a plugin": "来自插件",
"Full interface for coding, developer tools, and managing agents.": "用于编写代码、使用开发者工具及管理智能体的完整界面。",
"Hook": "钩子",
"Manage project folders, agent settings, and permissions.": "管理项目文件夹、智能体设置和权限。",
"Manage project resources, agent settings, and permissions.": "管理项目资源、智能体设置和权限。",
"Manage workspace folders and settings.": "管理工作区文件夹与设置。",
"Manage workspace folders, agent settings, and permissions.": "管理工作区文件夹、智能体设置和权限。",
"Manage workspace resources and settings.": "管理工作区资源与设置。",
"Model cannot be changed while the agent is running": "智能体运行期间无法切换模型",
"Modify permissions for file, terminal, and MCP tools.": "修改文件、终端与 MCP 工具的权限。",
"Moving Mouse in Browser": "正在浏览器中移动鼠标",
"from a plugin": "来自插件"
}
}
+568
View File
@@ -0,0 +1,568 @@
{
"base": {
"1 active conversation": "1 个活跃对话",
"1 archived conversation": "1 个已归档对话",
"1 audio attachment": "1 个音频附件",
"1 background task": "1 个后台任务",
"1 image attachment": "1 个图片附件",
"1 tool": "1 个工具",
"1 video attachment": "1 个视频附件",
"Narrow": "窄",
"Need help? Reach out in the": "需要帮助?请前往",
"New height in pixels.": "新高度(像素)。",
"New width in pixels.": "新宽度(像素)。",
"No Javascript Result Output": "无 JavaScript 结果输出",
"No TM Grammar registered for this language.": "未为此语言注册 TM 语法。",
"No answer provided": "未提供回答",
"No apps available.": "没有可用的应用。",
"No bundles available.": "无可用捆绑包。",
"No character metrics for '": "没有以下字符的度量信息:'",
"No compatible devices found.": "未找到兼容设备。",
"No content available for this resource": "此资源无可用内容",
"No description available.": "暂无描述。",
"No events recorded.": "未记录任何事件。",
"No function handler for": "未找到对应的函数处理程序:",
"No handlers configured for": "未配置对应的处理程序:",
"No instances yet.": "暂无实例。",
"No instructions.": "无说明。",
"No logs available.": "暂无可用日志。",
"No matching customizations found.": "未找到匹配的自定义项。",
"No matching hosts": "没有匹配的主机",
"No matching repositories": "无匹配的仓库",
"No matching resources found.": "未找到匹配的资源。",
"No microphone was found on this machine. Connect or enable an input device and try again.": "此设备上未找到麦克风。请连接或启用输入设备后重试。",
"No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router.": "未找到 notFoundComponent。请在路由上设置 notFoundComponent 或向路由器提供 defaultNotFoundComponent。",
"No notebook cells were found.": "未找到任何 Notebook 单元格。",
"No recordings": "暂无录制",
"No repositories found. Type to enter a custom path.": "未找到仓库。输入内容以填写自定义路径。",
"No resources added yet.": "暂未添加资源。",
"No shared path provided": "未提供共享路径",
"No sign-in required. This app is ready to use.": "无需登录。此应用已准备就绪。",
"No trajectory found in response": "响应中未找到轨迹",
"No upcoming run.": "暂无即将进行的运行。",
"Node class %s with type %s not registered in editor": "类型为 %s 的节点类 %s 未在编辑器中注册",
"Node is not incident with this edge": "节点不与此边相连",
"Node not in owner node list!": "节点不在所属节点列表中!",
"Node with key %s changed from ElementNode to !ElementNode": "键为 %s 的节点已从 ElementNode 变为 !ElementNode",
"None (clear inherited style)": "无(清除继承样式)",
"Not a valid argument number": "无效的参数编号",
"Not an inter-graph edge!": "不是跨图边!",
"Not in owner graph manager's edge list!": "不在所属图管理器的边列表中!",
"Not in owner's edge list!": "不在所属边列表中!",
"Not referenced by any feature (": "未被任何功能引用 (",
"Not shared automatically—share with": "不会自动共享——共享给",
"Not suitable for Best-of-N": "不适用于 Best-of-N",
"Not supported.": "不支持。",
"Notebook": "笔记本",
"Notebook execution not implemented": "Notebook 执行尚未实现",
"Nothing is running right now": "当前没有正在运行的任务",
"Notice": "提示",
"Notification": "通知",
"Null argument, please report this as a bug": "参数为空,请将此问题报告为 Bug",
"Number of columns should be a positive integer": "列数应为正整数",
"Observable is not supported": "不支持 Observable",
"Odd shape": "异形",
"Offscreen": "屏幕外",
"One last thing before getting started…": "开始前的最后一步…",
"One or more, comma-separated": "一个或多个,用逗号分隔",
"Only staged changes are being committed.": "仅正在提交已暂存的更改。",
"Only stored on your machine.": "仅存储在您的计算机上。",
"Only the conversation will be rewound; your files will be left as-is.": "仅会回退对话;你的文件将保持原样。",
"Only this conversation uses this preset.": "仅当前对话使用此预设。",
"Only works when Auto-execution policy is set to \"Request Review\" on a go/limited-internet host.": "仅在受限网络主机上将自动执行策略设为“请求审查”时生效。",
"Open Google Chrome on the machine running Antigravity.": "在运行 Antigravity 的计算机上打开 Google Chrome。",
"Open Mermaid diagram preview": "打开 Mermaid 图表预览",
"Open Trajectory Debug View": "打开轨迹调试视图",
"Open extracted DOM in editor": "在编辑器中打开提取的 DOM",
"Open in Antigravity IDE": "在 Antigravity IDE 中打开",
"Open preview in embedded pane": "在嵌入式窗格中打开预览",
"Opens in the in-app preview pane. Some sites don't support iframe embedding and may not load.": "在应用内预览窗格中打开。部分网站不支持 iframe 嵌入,可能无法加载。",
"Organization Allowed Domains (Read-Only)": "组织允许的域名(只读)",
"Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)": "嵌套 iframe 的源。\\n\\n- 映射到 CSP `frame-src` 指令\\n- 为空或省略 → 不允许嵌套 iframe(`frame-src 'none'`)",
"Origins for network requests (fetch/XHR/WebSocket).\n\n- Maps to CSP `connect-src` directive\n- Empty or omitted → no network connections (secure default)": "网络请求(fetch/XHR/WebSocket)的源。\\n\\n- 映射到 CSP `connect-src` 指令\\n- 为空或省略 → 不允许网络连接(安全默认设置)",
"Other (write your answer)": "其他(填写你的回答)",
"Outline color for text that got removed.": "已移除文本的轮廓颜色。",
"Outline color for the text that got inserted.": "已插入文本的轮廓颜色。",
"Overall foreground for disabled elements. This color is only used if not overridden by a component.": "禁用元素的全局前景色。仅在未被组件覆盖时使用此颜色。",
"Override feature environment": "覆盖功能环境",
"Page render committed to visible buffer": "页面渲染已提交至可见缓冲区",
"Page was short enough to be read as a single document.": "页面较短,已作为单个文档读取。",
"Pairs (arm order may be shuffled)": "配对(分组顺序可能会打乱)",
"Paper tape": "纸带",
"Partial tool call arguments (incomplete, may change).": "部分工具调用参数(尚未完整,可能会变化)。",
"Paste authorization code": "粘贴授权码",
"Paste the code shown after you sign in.": "粘贴登录后显示的授权码。",
"Path to the Chrome/Chromium executable. Leave empty for auto-detection.": "Chrome/Chromium 可执行文件的路径。留空则自动检测。",
"Paused.": "已暂停。",
"Pending · WIP or no reviewers assigned": "待处理 · 进行中或尚未指定审阅者",
"Period": "句号",
"Pick a suggestion below to get started, or ask me anything.": "从下方选择一条建议即可开始,或随时向我提问。",
"Pick order sets the harness for each response; the rest run control.": "选择顺序决定了每次响应所使用的测试框架;其余则作为对照组运行。",
"Plan work, track issues, sign documents, and manage your notes and files.": "规划工作、跟踪问题、签署文档并管理你的笔记与文件。",
"Please describe the feature you'd like to see. The more detailed the requirements, the easier it will be for our team to incorporate your ideas. Some helpful information includes:": "请描述您希望看到的功能。需求越详细,我们的团队就越容易采纳您的想法。以下信息可能会有所帮助:",
"Please describe the issue in detail. The more actionable your feedback, the quicker our team can address your request. Some helpful information includes:": "请详细描述该问题。您的反馈越具可操作性,我们的团队就能越快处理您的请求。以下信息可能会有所帮助:",
"Please fill out all required argument values before continuing.": "请填写所有必填参数值后再继续。",
"Please fill out all required values to continue.": "请填写所有必填项以继续。",
"Please list the steps to reproduce the issue": "请列出重现该问题的步骤",
"Please provide a more detailed description (at least 10 characters).": "请提供更详细的描述(至少 10 个字符)。",
"Please provide more detailed steps to reproduce (at least 5 characters).": "请提供更详细的重现步骤(至少 5 个字符)。",
"Point.getNode: node not found": "Point.getNode: 未找到节点",
"Polygon": "多边形",
"Popup": "弹窗",
"Portal": "门户",
"Post": "发布",
"Post-onboarding completed steps": "引导后已完成步骤",
"Posting...": "正在发布...",
"Powered by Gemini Live ·": "由 Gemini Live 提供支持 ·",
"Predict the functional impact of a genomic variant": "预测基因组变异的功能影响",
"Preset": "预设",
"Press Cmd+Enter to send, Enter for a new line.": "按 Cmd+Enter 发送,按 Enter 换行。",
"Press keys...": "请按键...",
"Pressed": "已按下",
"Pressing": "正在按下",
"Prevent the computer from sleeping while the app is running.": "在应用运行期间防止计算机休眠。",
"Preview disabled (experiment off)": "预览已禁用(实验性功能已关闭)",
"Previous Match (Shift+Enter)": "上一个匹配项 (Shift+Enter)",
"Pricing is based on public API pricing": "定价基于公开 API 定价",
"Priority is not optional for beforeRender": "beforeRender 的优先级不可省略",
"Proceed with implementation plan": "按实施计划继续执行",
"Productivity & Project Management": "效率与项目管理",
"Profiler": "性能分析器",
"Prototype": "原型",
"Pushing...": "正在推送...",
"Quality": "质量",
"Query research databases for recent papers on a topic": "查询科研数据库以获取某主题的最新论文",
"Queue": "排队",
"Radar": "雷达图",
"Ran": "已运行",
"Received frame with identifier that does not match this stream.": "收到与当前流不匹配的标识符帧。",
"Red": "红色",
"Redact": "脱敏",
"Redefinition of subject in selector `": "选择器中重复定义了主体 `",
"Redundant input, expecting EOF but found:": "多余的输入,预期为 EOF 但发现:",
"Refresh all credentials": "刷新所有凭据",
"Refresh gcert Credentials": "刷新 gcert 凭据",
"Refreshing credentials...": "正在刷新凭据...",
"Refreshing...": "正在刷新...",
"Regular": "常规",
"Rejected": "已拒绝",
"Remote Permissions": "远程权限",
"Removed bookmark": "已移除收藏",
"Removing bookmark": "正在移除收藏",
"Removing the message from the queue…": "正在将消息移出队列…",
"Removing...": "正在移除...",
"Renderer does not implement `renderer.": "渲染器未实现 `renderer.",
"Replacing...": "正在替换...",
"Repo default": "仓库默认",
"Repository access required": "需要仓库访问权限",
"Repository name can only contain letters, numbers, underscores, dashes, dots, and slashes": "仓库名称只能包含字母、数字、下划线、短横线、点号和斜杠",
"Represents a display": "表示显示器",
"Requesting a one-time administrator (UAC) elevation": "正在请求一次性管理员 (UAC) 提权",
"Requires manual confirmation.": "需要手动确认。",
"Research, writing, and everyday tasks, without code.": "研究、写作和日常任务,不涉及代码。",
"Reset to preset": "重置为预设",
"Resize side question panel": "调整侧边提问面板大小",
"Resolve conflicts first": "请先解决冲突",
"Resolving...": "正在解析...",
"Response (incl. tool calls)": "响应(含工具调用)",
"Restart Main Language Server": "重启主语言服务器",
"Retiring Soon": "即将停用",
"Retrieving findings for": "正在获取分析结果:",
"Review bundle before adding": "添加前审阅配置包",
"Right": "右",
"Root": "根目录",
"Root not in this graph mgr!": "根节点不在此图管理器中!",
"Run all commands without restrictions.": "无限制运行所有命令。",
"Run command step not found": "未找到运行命令步骤",
"Run the app against a Linux environment. Connecting relaunches the app into the selected WSL distro.": "在 Linux 环境中运行应用。连接后将重启应用并进入所选 WSL 发行版。",
"Running...": "运行中...",
"Runs in a cloud environment": "在云端环境中运行",
"SafeStyleSheet does not support @keyframes": "SafeStyleSheet 不支持 @keyframes",
"Saving...": "正在保存...",
"Science": "科学研究",
"Scratchpad": "草稿区",
"Screen": "屏幕",
"Screenshot must be under 10 MB": "截图大小必须小于 10 MB",
"Scrollbar shadow to indicate that the view is scrolled.": "用于指示视图已滚动的滚动条阴影。",
"Searching Moma for": "正在 Moma 中搜索:",
"Searching older messages": "正在搜索更早的消息",
"Searching older messages…": "正在搜索更早的消息…",
"Searching...": "正在搜索...",
"Sections": "分区",
"Secure mode enabled state (user toggle)": "安全模式启用状态(用户开关)",
"See more...": "查看更多...",
"Select an option...": "选择一个选项...",
"Select or enter GoB repository...": "选择或输入 GoB 仓库...",
"Select text in the PDF and click + Add to start commenting.": "在 PDF 中选择文本,然后点击“+ 添加”开始添加批注。",
"Select the latest snapshot from the": "从中选择最新快照:",
"Select...": "选择...",
"Selected element preview": "已选元素预览",
"Self-watch target presets": "自监控目标预设",
"Semantic searching": "正在语义搜索",
"Semicolon": "分号",
"Sends after background work finishes.": "后台任务完成后发送。",
"Server errored internally": "服务器发生内部错误",
"Settings for conversations outside of projects.": "非项目对话设置。",
"Setup Chat RPC is not available.": "Setup Chat RPC 不可用。",
"Setup may take over 5 minutes. Please keep this screen open during setup.": "设置可能需要 5 分钟以上。设置期间请保持此页面打开。",
"Setup script ran successfully.": "初始化脚本运行成功。",
"Share your referral link with friends": "与好友分享你的推荐链接",
"Shares this repository, with a working copy of its own. Uncommitted changes stay behind.": "共享此仓库并拥有独立的工作副本。未提交的更改将保留在原处。",
"Show \"Edit\" and \"Chat\" buttons when selecting text in the editor.": "在编辑器中选中文本时显示“编辑”和“对话”按钮。",
"Show Whitespace Changes": "显示空白字符更改",
"Show suggestions when typing in the editor": "在编辑器中输入时显示建议",
"Side Panel Preview": "侧面板预览",
"Side Question Selection": "侧边提问选区",
"Side question answered.": "侧边提问已回答。",
"Sign in required.": "需要登录。",
"Sign out of this server?": "确定要退出登录此服务器吗?",
"Sign up for newsletters, tips and tricks, and other notifications about": "订阅新闻简报、实用技巧及其他通知,了解",
"Sign-in didn't finish. Try again.": "登录未完成,请重试。",
"Signed in": "已登录",
"Signing Out...": "正在退出登录...",
"Simplified interface for research, writing, and everyday tasks.": "面向研究、写作和日常任务的精简界面。",
"Simulate a different user cohort (Google, External, Enterprise).": "模拟不同的用户群体(Google、外部用户、企业用户)。",
"Simulate running as a different binary (Hub or the IDE/editor).": "模拟以不同的二进制程序运行(Hub 或 IDE/编辑器)。",
"Simulate running on a different OS.": "模拟在不同的操作系统上运行。",
"Size": "大小",
"Skipping...": "正在跳过...",
"Slash": "斜杠",
"Slow": "较慢",
"Socket closed.": "Socket 连接已关闭。",
"Software Engineering": "软件工程",
"Some non-image binary content was truncated.": "部分非图像二进制内容已被截断。",
"Something else (optional)": "其他原因(可选)",
"Something went wrong.": "出错了。",
"Source and/or target doesn't know this edge!": "源节点和/或目标节点不包含此边!",
"Source and/or target is null!": "源节点和/或目标节点为空!",
"Source not in this graph mgr!": "源节点不在此图管理器中!",
"Source or target not in graph!": "源节点或目标节点不在图中!",
"Square": "方形",
"Squiggly": "波浪线",
"Stable": "稳定版",
"Staged": "已暂存",
"Staged index changes and working tree changes": "已暂存的索引更改和工作树更改",
"Stamp": "图章",
"Standard process shape": "标准流程图形",
"Start Live Chat": "发起实时对话",
"Start in a new Fig share (go/fig-shares)": "在新的 Fig 共享中启动 (go/fig-shares)",
"Start it again.": "重新启动。",
"Started during": "启动于",
"Starting...": "正在启动...",
"Stay up to date.": "保持最新状态。",
"Steps to reproduce the issue": "问题复现步骤",
"Stopping...": "正在停止...",
"Stored and mounted in your cloud environment": "存储并挂载在您的云端环境中",
"Stored data": "已存储数据",
"Stream closed before receiving OK trailer": "流在收到 OK 尾部标记前已关闭",
"Strong": "强",
"Style for all symbol declarations.": "所有符号声明的样式。",
"Style for decorators & annotations.": "装饰器与注解的样式。",
"Style for events.": "事件的样式。",
"Style for labels.": "标签的样式。",
"Style to use for references in documentation.": "文档中引用的样式。",
"Style to use for symbols that are abstract.": "抽象符号的样式。",
"Style to use for symbols that are async.": "异步符号的样式。",
"Style to use for symbols that are deprecated.": "已弃用符号的样式。",
"Style to use for symbols that are read-only.": "只读符号的样式。",
"Style to use for symbols that are static.": "静态符号的样式。",
"Style to use for write accesses.": "写入访问的样式。",
"Submitted": "已提交",
"Submitting...": "正在提交...",
"Substring or list check (e.g.": "子字符串或列表检查 (例如",
"Summarize a spreadsheet": "总结电子表格内容",
"Sun Mon Tue Wed Thu Fri Sat": "周日 周一 周二 周三 周四 周五 周六",
"Sunday Monday Tuesday Wednesday Thursday Friday Saturday": "星期日 星期一 星期二 星期三 星期四 星期五 星期六",
"Sunset": "即将停用",
"Switch to RTL text direction": "切换为 RTL 文本方向",
"Switch to This Computer": "切换到此计算机",
"Switch to default text direction": "切换为默认文本方向",
"Switched to authorization code sign-in": "已切换为授权码登录",
"Sync encountered merge conflicts. Please resolve the conflicts and run \"hg rebase --continue\" manually.": "同步时遇到合并冲突。请解决冲突并手动运行 \"hg rebase --continue\"。",
"Sync encountered merge conflicts. Please resolve the conflicts and run `hg rebase --continue` manually.": "同步时遇到合并冲突。请解决冲突并手动运行 `hg rebase --continue`。",
"Syncing...": "正在同步...",
"TabNode does not support setDetail": "TabNode 不支持 setDetail",
"TabNode does not support setMode": "TabNode 不支持 setMode",
"TabNode does not support spliceText": "TabNode 不支持 spliceText",
"Table exceeds 100 columns.": "表格超过 100 列。",
"Tagged document": "带标签文档",
"Tagged process": "带标签流程",
"Taking Screenshot": "正在截图",
"Taking longer than usual to load": "加载时间比平时长",
"Talker + Narrator (relay)": "对话者 + 旁白(中继)",
"Target not in this graph mgr!": "目标不在此图管理器中!",
"Target text in PDF...": "PDF 中的目标文本...",
"Telemetry is off for all conversations.": "所有对话均已关闭遥测。",
"Telemetry is off for this conversation.": "当前对话已关闭遥测。",
"Telemetry will be enabled for this conversation; click to disable.": "当前对话将启用遥测;点击可关闭。",
"Tell us anything else here (optional)": "请在此告诉我们其他信息(可选)",
"Terms of Service & Data Use": "服务条款与数据使用",
"Tested": "已测试",
"Testing": "正在测试",
"Text": "文本",
"Thank you! Your feedback has been submitted successfully.": "谢谢!您的反馈已成功提交。",
"Thanks for your feedback!": "感谢您的反馈!",
"The Hub sent an unexpected response.": "Hub 返回了意外响应。",
"The Orchestrator's own planner": "编排器自带的规划器",
"The `cutrectangle` node shape can not be used at small sizes so `rectangle` is used instead": "较小尺寸下无法使用 `cutrectangle` 节点形状,因此改用 `rectangle`",
"The certificate has been revoked.": "证书已被吊销。",
"The certificate is not issued by a trusted authority.": "证书并非由受信任的机构颁发。",
"The certificate is not valid for this site.": "证书对此网站无效。",
"The change was pushed to Gerrit.": "更改已推送到 Gerrit。",
"The color used for the lightbulb AI icon.": "灯泡 AI 图标使用的颜色。",
"The color used for the lightbulb actions icon.": "灯泡操作图标使用的颜色。",
"The color used for the lightbulb auto fix actions icon.": "灯泡自动修复操作图标使用的颜色。",
"The color used for the problems info icon.": "问题信息图标使用的颜色。",
"The current trigger rate is too high.": "当前触发频率过高。",
"The default color for icons in the workbench.": "工作台中图标的默认颜色。",
"The fetch API does not support streaming request bodies": "Fetch API 不支持流式请求体",
"The full developer experience with code and tooling.": "包含代码和工具的完整开发者体验。",
"The full developer experience.": "完整的开发者体验。",
"The length of delimiters doesn't match the number of args!": "分隔符的长度与参数数量不匹配!",
"The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.\nMore info: https://fb.me/react-controlled-components": "状态性质在首次渲染时确定。如果值不为 `undefined`,则视为受控状态。\\n详细信息:https://fb.me/react-controlled-components",
"The unique identifier for the corresponding tool call.": "对应工具调用的唯一标识符。",
"There are currently no Build with": "当前没有使用",
"There are no customizations enabled.": "尚未启用任何自定义配置。",
"This Conversation": "当前对话",
"This Object indicates the Parser is during Recording Phase": "此对象表示解析器正处于录制阶段",
"This app is not allowed in previews.": "不允许在预览中使用此应用。",
"This chat's environment is paused": "此对话的环境已暂停",
"This client was started with no custom flags.": "此客户端启动时未使用自定义标志。",
"This color must be transparent or it will obscure content": "此颜色必须透明,否则会遮挡内容",
"This link wants to open an app on your device.": "此链接请求在您的设备上打开应用。",
"This may take a few minutes": "这可能需要几分钟时间",
"This model is leaving soon.": "此模型即将下线。",
"This notebook has no renderable cells.": "此笔记本没有可渲染的单元格。",
"This page is going away soon": "此页面即将下线",
"This page is not allowed in previews.": "不允许在预览中打开此页面。",
"This page is taking longer than expected to load, or it may be blocking embedded views (via X-Frame-Options or CSP).": "此页面加载时间超出预期,或者可能禁止了嵌入式视图(通过 X-Frame-Options 或 CSP)。",
"This page isn’t working": "此页面无法正常工作",
"This request is not well-suited for parallel Best-of-N generation.": "此请求不太适合并行 Best-of-N 生成。",
"This setting is turned off for your account.": "此设置已在你的账号下关闭。",
"This sign-in option is only available to invited teams.": "此登录选项仅对受邀团队开放。",
"This site can’t be reached": "无法访问此网站",
"This site uses an unsupported TLS protocol or cipher suite.": "此网站使用了不受支持的 TLS 协议或加密套件。",
"This usually means a React component was passed directly as `render={Component}`.": "这通常意味着某个 React 组件被直接作为 `render={Component}` 传入。",
"This will cause issues between the Toggle Group and Toggle values.": "这会导致切换组(Toggle Group)和切换值之间出现问题。",
"Thread": "会话串",
"Tilde": "波浪号",
"Tip: Complex tasks get better results with multiple responses.": "提示:对于复杂任务,生成多个回复往往能获得更好的效果。",
"To switch accounts, sign out in the": "要切换账号,请在",
"Toggle Between Light/Dark Themes": "在浅色/深色主题间切换",
"Toggle Environment Selector": "切换环境选择器",
"Toggle Maximize Auxiliary Pane": "切换最大化辅助窗格",
"Toggle Maximize Side Panel": "切换最大化侧边面板",
"Toggle checkerboard background": "切换棋盘格背景",
"Toggle this on to enable read access on contents.": "开启此项以启用内容读取权限。",
"Too many environments running": "正在运行的环境过多",
"Too many math in a row:": "连续数学模式过多:",
"Too many math in a row: expected": "连续数学模式过多:预期",
"Too many requests, please try again in a bit!": "请求过于频繁,请稍后再试!",
"Too much output to announce, navigate to rows manually to read": "输出内容过多无法播报,请手动导航至各行阅读",
"Toolbar background when holding the mouse over actions": "鼠标悬停在操作上时的工具栏背景",
"Toolbar background when hovering over actions using the mouse": "使用鼠标悬停在操作上时的工具栏背景",
"Toolbar outline when hovering over actions using the mouse": "使用鼠标悬停在操作上时的工具栏轮廓",
"Transaction already finished!": "事务已结束!",
"Trouble signing in? Enter authorization code": "登录遇到问题?请输入授权码",
"Try out early-stage features before they ship. These may be changed or removed at any time. These features are experimental, and we make no guarantees about performance or functionality.": "在正式发布前抢先体验早期功能。这些功能随时可能更改或移除,属于实验性功能,我们不对其性能或功能作任何保证。",
"Turn a doc into a slide deck": "将文档转换为演示文稿",
"Turn a screenshot into a web page": "将截图转化为网页",
"Turn on a flag you don't have": "开启你尚未拥有的功能开关",
"Turned off by your admin": "已由管理员关闭",
"Typing your corp password here may trigger a Password Alert reset.": "在此输入公司密码可能会触发 Password Alert 重置。",
"UI Extension (AuxPane)": "UI 扩展(辅助窗格)",
"UI view does not exist.": "UI 视图不存在。",
"Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug": "命名空间销毁不平衡:尝试弹出全局命名空间;请将此问题报告为 Bug",
"Unbalanced parentheses or brackets": "圆括号或方括号不匹配",
"Unclosed string literal": "未闭合的字符串字面量",
"Uncommitted changes in working directory": "工作目录中存在未提交的更改",
"Undefined control sequence:": "未定义的控制序列:",
"Underline": "下划线",
"Undo to this point": "撤销到此处",
"Unexpected character: '": "意外字符:'",
"Unexpected end of input in a macro argument, expected '": "宏参数输入意外结束,预期为 '",
"Unexpected leading binary operator": "表达式开头出现意外的二元运算符",
"Unicode text character \"": "Unicode 文本字符 \"",
"Unidentified": "未识别",
"Uninstalling...": "正在卸载...",
"Unknown column alignment:": "未知列对齐方式:",
"Unknown type of space \"": "未知间距类型 \"",
"Unmute mic": "取消麦克风静音",
"Unnamed": "未命名",
"Unrecognized Unicode character \"": "无法识别的 Unicode 字符 \"",
"Updating will restart the server and apply the latest changes.": "更新将会重启服务器并应用最新更改。",
"Updating...": "更新中...",
"Uploaded to Google Drive": "已上传到 Google Drive",
"Uploading chain...": "正在上传调用链...",
"Uploading to Google Drive…": "正在上传到 Google Drive…",
"Use \"&&\", \"||\", and \"!\" instead of \"and\", \"or\", or \"not\"": "请使用 \"&&\"、\"||\" 和 \"!\" 代替 \"and\"、\"or\" 或 \"not\"",
"Use \"==\" for equality comparison instead of \"=\"": "请使用 \"==\" 进行相等比较,而不是 \"=\"",
"Use Advanced SSO Config": "使用高级 SSO 配置",
"Use Regular Expression (.*)": "使用正则表达式 (.*)",
"Use full VCS clones for Best of N": "为 Best of N 使用完整 VCS 克隆",
"Use of the macro doesn't match its definition": "宏的用法与其定义不匹配",
"Use the default color.": "使用默认颜色。",
"Use this if your admin gave you a WIF config. Paste it below to sign in.": "如果管理员向您提供了 WIF 配置,请使用此选项。在下方粘贴即可登录。",
"User": "用户",
"User status information": "用户状态信息",
"Using system default microphone": "正在使用系统默认麦克风",
"Validated with GitHub and stored in": "已通过 GitHub 验证并存储在",
"Validating setup script…": "正在验证初始化脚本…",
"Validation timed out.": "验证超时。",
"Verbose": "详细",
"Video": "视频",
"Videos must be at least 1 second long": "视频时长必须至少为 1 秒",
"Visited URLs and autocomplete suggestions.": "已访问的 URL 和自动补全建议。",
"Waiting for confirmation": "等待确认",
"Waiting for response... (Esc to minimize)": "正在等待响应...(按 Esc 最小化)",
"Waiting for you to finish signing in…": "正在等待您完成登录…",
"Watermark": "水印",
"We apologize for the inconvenience. Please try again later.": "由此带来不便,深表歉意。请稍后重试。",
"We opened a popup for you to authorize adding the bot to your chat. Please copy the code from it and paste it below:": "我们已为您打开弹窗,用于授权将机器人添加到您的聊天中。请从弹窗复制代码并粘贴到下方:",
"We recommend attaching logs. Attaching logs will help the Antigravity team act on and prioritize your feedback.": "建议附上日志。附上日志有助于 Antigravity 团队处理并优先跟进您的反馈。",
"We'll tailor the experience to you.": "我们将为您量身定制使用体验。",
"Web": "网页",
"WebSocket connection closed unexpectedly": "WebSocket 连接意外关闭",
"Welcome back. Where should we pick up?": "欢迎回来。我们从哪里继续?",
"Welcome to Cider with Jetski": "欢迎使用 Cider with Jetski",
"Welcome to your Chief of Staff": "欢迎使用您的 Chief of Staff",
"What best describes you?": "以下哪项最符合您的身份?",
"What counts as a document": "什么算作文档",
"What did you like about this response?": "您喜欢这条回复的哪些方面?",
"What did you like? Select any that apply (optional).": "您喜欢哪些方面?可多选(可选)。",
"What was off? Select any that apply (optional).": "有哪些地方不对?可多选(可选)。",
"When enabled, the values below replace the auto-detected OS, host, and user type used for feature gating.": "启用后,下方的值将覆盖自动检测的操作系统、主机和用户类型,用于功能开关控制。",
"When enabled, the values below replace the auto-detected OS, host, binary, and user type used for feature gating.": "启用后,下方的值将覆盖自动检测的操作系统、主机、二进制文件和用户类型,用于功能开关控制。",
"Whether it never connects or is intermittent/flaky": "是完全无法连接,还是断断续续/不稳定",
"Why are you opting out of auto-triggered Best-of-N?": "为什么选择退出自动触发的 Best-of-N?",
"Why did you choose this response?": "为什么选择这条回复?",
"Wide": "宽",
"Widget": "小组件",
"Worked": "已处理",
"Working...": "正在处理...",
"Write": "写入",
"Write a comment...": "撰写评论...",
"Write a design brief from my research": "根据我的调研撰写设计简报",
"Yellow": "黄色",
"Yes, I agree to help improve": "是的,我同意帮助改进",
"Yes, allow for this conversation": "是,仅在当前对话中允许",
"You are logged in using environment credentials and cannot sign out from the application.": "你当前正通过环境变量凭据登录,无法从应用内退出登录。",
"You can now switch seamlessly between Jetski Web and Cider using the icons above.": "您现在可以使用上方的图标在 Jetski Web 和 Cider 之间无缝切换。",
"You can opt-out temporarily using": "您可以临时选择退出,只需使用",
"You should not enter any sensitive information on this site (for example, passwords or credit cards), because it could be stolen by attackers.": "您不应在此网站上输入任何敏感信息(例如密码或信用卡),因为这些信息可能会被攻击者窃取。",
"You're viewing a blank page": "您正在查看空白页",
"You've reached the maximum number of turns for this battle. End battle mode to continue.": "您已达到本次对战的最大轮次。请结束对战模式以继续。",
"Your AI credits balance is too low to continue.": "您的 AI 积分余额过低,无法继续。",
"Your Remote setting": "你的远程设置",
"Your changes were not saved. Please try again.": "您的更改未保存。请重试。",
"Your connection is not private": "您的连接不是私密连接",
"Your connection to this site is not fully secure": "您与此网站的连接并非完全安全",
"Your connection to this site is not secure": "您与此网站的连接不安全",
"Your feedback directly improves Gemini. See": "您的反馈有助于直接改进 Gemini。请参阅",
"Your information (for example, passwords or credit card numbers) is private when it is sent to this site.": "您发送至此网站的信息(例如密码或信用卡号)为私密信息。",
"needs a few details from you before it can run.": "需要您提供一些详细信息才能运行。",
"on this computer.": "在此计算机上。",
"on your cloudtop server": "在您的 Cloudtop 服务器上",
"projectManagementFeature is not available": "projectManagementFeature 不可用",
"projectManagementService is not available": "projectManagementService 不可用",
"run_command or view_file": "run_command 或 view_file",
"says.": "所说。",
"script return value is not JSON-serializable": "脚本返回值无法序列化为 JSON",
"script source must not be empty": "脚本源不能为空",
"that runs Jetski Web.": ",用于运行 Jetski Web。",
"this time, the website sent back unusual and incorrect credentials.": "时,该网站发回了异常且不正确的凭据。",
"to ask for content changes for legal reasons.": "以出于法律原因请求更改内容。",
"to back up your data and run the migration.": "以备份您的数据并运行迁移。",
"to be installed.": "完成安装。",
"to set up ABFS.": "以设置 ABFS。",
"to set up Cog.": "以设置 Cog。",
"user directory, and any Googler with the link can load and view it. Storage will move to Google Drive in a future version.": "用户目录,任何拥有链接的 Googler 都可以加载并查看。存储将在未来版本中迁移至 Google Drive。",
"via email.": "通过电子邮件。",
"with this name already exists on this computer. Run it remotely, or go back and rename it.": "在此计算机上已存在同名项。请远程运行,或返回并重命名。",
"with this name already exists.": "已存在同名项。",
"within it.": "在其中。",
"yet. Type one above.": "还没有。请在上方输入。"
},
"light": {
"1 MCP server failed to start": "1 个 MCP Server 启动失败",
"1 browser step": "1 个 Browser 步骤",
"1 subagent": "1 个 Subagent",
"No MCP servers available.": "没有可用的 MCP Server。",
"No active terminals. Click + to create one.": "无活跃的 Terminal。点击 + 创建一个。",
"No commits yet": "暂无 Commit",
"No skills or rules yet.": "暂无 Skill 或 Rule。",
"Opening URL in Browser": "正在 Browser 中打开 URL",
"PR details unavailable": "PR 详情不可用",
"Payments, CRM, accounting, data, identity, customer support, marketing, and workflow automation.": "支付、CRM、会计、数据、身份认证、客户支持、营销及 Workflow 自动化。",
"Permissions cannot be changed while the agent is running": "Agent 运行期间无法修改权限",
"Reading Browser Page in Browser": "正在 Browser 中读取网页",
"Refreshing Browser page": "正在刷新 Browser 页面",
"Resizing Browser window": "正在调整 Browser 窗口大小",
"Retrieving Browser Pages": "正在获取 Browser 页面列表",
"Retrieving Console Logs from Browser": "正在从 Browser 获取控制台日志",
"Review plans and walkthroughs": "审阅计划与 Walkthrough",
"Rewinds the conversation only. Files in this workspace stay as they are now.": "仅回退对话。此 Workspace 中的文件保持当前状态不变。",
"Rule": "Rule",
"Rules and customization token budgets exceeded. Large rules are demoted to path pointers and large customizations are excluded from context.": "Rule 与自定义扩展已超出 Token 预算。较大的 Rule 已降级为路径指针,较大的自定义扩展已从 Context 中排除。",
"Scrolling down in Browser": "正在 Browser 中向下滚动",
"Scrolling in Browser": "正在 Browser 中滚动",
"Scrolling up in Browser": "正在 Browser 中向上滚动",
"Selecting Option in Browser": "正在 Browser 中选择选项",
"Settings for conversations outside of workspaces.": "Workspace 外对话设置。",
"Simulating Key Press in Browser": "正在 Browser 中模拟按键",
"Sort Workspaces": "排序 Workspaces",
"The files below were changed by the agent and will be reverted, but other files may also be affected if your workspace changed for other reasons (e.g. a sync) in the meantime.": "以下由 Agent 修改的文件将被回退;但如果此期间你的 Workspace 因其他原因(如同步)发生变动,其他文件也可能受到影响。",
"This subagent was killed and can no longer be messaged.": "此 Subagent 已终止,无法再向其发送消息。",
"Typing into Browser": "正在 Browser 中输入",
"UI Plugin (SidePanel)": "UI Plugin(侧面板)",
"What is missing in your workflow": "您的 Workflow 中缺少什么",
"What you would like to see to address this gap in your workflow": "您希望如何解决 Workflow 中的这一缺口",
"When enabled, sandboxed commands are allowed to make network requests.": "启用后,允许 Sandbox 中的命令发起网络请求。",
"Workspaces are not available for this project": "此项目不支持 Workspaces",
"Worktrees are available for Git repositories": "Git 仓库支持 Worktree",
"Yes, save rule globally": "是,全局保存 Rule",
"Yes, save rule in this conversation": "是,在当前对话中保存 Rule",
"Yes, save rule in this workspace": "是,在当前 Workspace 中保存 Rule"
},
"deep": {
"1 MCP server failed to start": "1 个 MCP 服务启动失败",
"1 browser step": "1 个浏览器步骤",
"1 subagent": "1 个子代理",
"No MCP servers available.": "没有可用的 MCP 服务。",
"No active terminals. Click + to create one.": "无活跃的终端。点击 + 创建一个。",
"No commits yet": "暂无提交记录",
"No skills or rules yet.": "暂无技能或规则。",
"Opening URL in Browser": "正在浏览器中打开链接",
"PR details unavailable": "拉取请求详情不可用",
"Payments, CRM, accounting, data, identity, customer support, marketing, and workflow automation.": "支付、客户关系管理、会计、数据、身份认证、客户支持、营销及工作流自动化。",
"Permissions cannot be changed while the agent is running": "智能体运行期间无法修改权限",
"Reading Browser Page in Browser": "正在浏览器中读取网页",
"Refreshing Browser page": "正在刷新浏览器页面",
"Resizing Browser window": "正在调整浏览器窗口大小",
"Retrieving Browser Pages": "正在获取浏览器页面列表",
"Retrieving Console Logs from Browser": "正在从浏览器获取控制台日志",
"Review plans and walkthroughs": "审阅计划与变更说明",
"Rewinds the conversation only. Files in this workspace stay as they are now.": "仅回退对话。此工作区中的文件保持当前状态不变。",
"Rule": "规则",
"Rules and customization token budgets exceeded. Large rules are demoted to path pointers and large customizations are excluded from context.": "规则与自定义扩展已超出词元预算。较大的规则已降级为路径指针,较大的自定义扩展已从上下文中排除。",
"Scrolling down in Browser": "正在浏览器中向下滚动",
"Scrolling in Browser": "正在浏览器中滚动",
"Scrolling up in Browser": "正在浏览器中向上滚动",
"Selecting Option in Browser": "正在浏览器中选择选项",
"Settings for conversations outside of workspaces.": "工作区外对话设置。",
"Simulating Key Press in Browser": "正在浏览器中模拟按键",
"Sort Workspaces": "排序工作区",
"The files below were changed by the agent and will be reverted, but other files may also be affected if your workspace changed for other reasons (e.g. a sync) in the meantime.": "以下由智能体修改的文件将被回退;但如果此期间你的工作区因其他原因(如同步)发生变动,其他文件也可能受到影响。",
"This subagent was killed and can no longer be messaged.": "此子代理已终止,无法再向其发送消息。",
"Typing into Browser": "正在浏览器中输入",
"UI Plugin (SidePanel)": "UI 插件(侧面板)",
"What is missing in your workflow": "您的工作流中缺少什么",
"What you would like to see to address this gap in your workflow": "您希望如何解决工作流中的这一缺口",
"When enabled, sandboxed commands are allowed to make network requests.": "启用后,允许沙箱中的命令发起网络请求。",
"Workspaces are not available for this project": "此项目不支持工作区",
"Worktrees are available for Git repositories": "Git 仓库支持工作树",
"Yes, save rule globally": "是,全局保存规则",
"Yes, save rule in this conversation": "是,在当前对话中保存规则",
"Yes, save rule in this workspace": "是,在当前工作区中保存规则"
}
}
+11 -4
View File
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"catalogVersion": "2026.11.21.3",
"updatedAt": "2026-11-21T14:35:00+09:00",
"catalogVersion": "2026.11.24.1",
"updatedAt": "2026-11-24T11:35:00+09:00",
"latestPluginVersion": "1.5.4",
"releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest",
"downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
@@ -102,12 +102,16 @@
"gemini-3.1-flash-lite-preview": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" },
"gemini-3.1-flash-lite": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" },
"gemini-for-google-3.1-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1", "family": "Gemini" },
"gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1-img", "family": "Gemini" },
"gemini-3.1-flash-image-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "imageOutput": 60.0, "short": "flash-3.1-img", "family": "Gemini" },
"gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "imageOutput": 60.0, "short": "flash-3.1-img", "family": "Gemini" },
"gemini-3-flash-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" },
"gemini-3-flash-c": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" },
"gemini-3-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" },
"gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3-img", "family": "Gemini" },
"gemini-3-pro-image-preview": { "input": 2.00, "cache": 0.20, "output": 12.0, "imageOutput": 120.0, "short": "pro-3-img", "family": "Gemini" },
"gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "imageOutput": 120.0, "short": "pro-3-img", "family": "Gemini" },
"gemini-2.5-pro": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "pro-2.5", "family": "Gemini" },
"gemini-2.5-flash-image-preview": { "input": 0.30, "cache": 0.03, "output": 2.50, "imageOutput": 30.0, "short": "flash-2.5-img", "family": "Gemini" },
"gemini-2.5-flash-image": { "input": 0.30, "cache": 0.03, "output": 2.50, "imageOutput": 30.0, "short": "flash-2.5-img", "family": "Gemini" },
"gemini-2.5-flash": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-2.5", "family": "Gemini" },
"gemini-2.5-flash-lite": { "input": 0.10, "cache": 0.01, "output": 0.40, "short": "flash-2.5-lite", "family": "Gemini" },
"claude-fable-5-2-max": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2-max", "family": "Claude" },
@@ -212,10 +216,13 @@
"MODEL_PLACEHOLDER_M50": { "modelId": "gemini-3.1-flash-lite", "label": "Gemini 3.1 Flash Lite" },
"MODEL_PLACEHOLDER_M59": { "modelId": "gemini-for-google-3.1-flash", "label": "Gemini for Google 3.1 Flash" },
"MODEL_PLACEHOLDER_M21": { "modelId": "gemini-3.1-flash-image", "label": "Gemini 3.1 Flash Image" },
"MODEL_GOOGLE_GEMINI_3_1_FLASH_IMAGE_PREVIEW": { "modelId": "gemini-3.1-flash-image-preview", "label": "Gemini 3.1 Flash Image" },
"MODEL_PLACEHOLDER_M47": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" },
"MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" },
"MODEL_PLACEHOLDER_M9": { "modelId": "gemini-3-pro-image", "label": "Gemini 3 Pro Image" },
"MODEL_GOOGLE_GEMINI_3_PRO_IMAGE_PREVIEW": { "modelId": "gemini-3-pro-image-preview", "label": "Gemini 3 Pro Image" },
"MODEL_GOOGLE_GEMINI_2_5_PRO": { "modelId": "gemini-2.5-pro", "label": "Gemini 2.5 Pro" },
"MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW": { "modelId": "gemini-2.5-flash-image-preview", "label": "Gemini 2.5 Flash Image" },
"MODEL_GOOGLE_GEMINI_2_5_FLASH": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash" },
"MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash (Thinking)" },
"MODEL_PLACEHOLDER_M330": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" },
+9060 -1811
View File
File diff suppressed because it is too large Load Diff
+304 -33
View File
@@ -1,7 +1,11 @@
param([string]$JobPath = '')
$ErrorActionPreference = 'Stop'
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$utf8 = [Console]::OutputEncoding
$script:clientsToRestart = @()
$script:clientsStopped = $false
function Test-AccountFile($path) {
if (-not (Test-Path -LiteralPath $path)) { return $false }
@@ -26,11 +30,168 @@ function Write-AccountFile($path, [byte[]]$bytes) {
}
}
function Ensure-VaultDirectory($path) {
$dir = [IO.Path]::GetDirectoryName($path)
if (-not $dir) { return }
[void][IO.Directory]::CreateDirectory($dir)
if ([IO.Path]::GetFileName($dir) -ieq 'AntigravityUsageMonitor') {
try {
$acl = Get-Acl -LiteralPath $dir
if (-not $acl.AreAccessRulesProtected) {
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
$sysSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$admSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$inherit = [Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
$prop = [Security.AccessControl.PropagationFlags]::None
$right = [Security.AccessControl.FileSystemRights]::FullControl
$allow = [Security.AccessControl.AccessControlType]::Allow
$acl.SetAccessRuleProtection($true, $false)
foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRule($rule) }
foreach ($sid in @($userSid, $sysSid, $admSid)) {
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, $right, $inherit, $prop, $allow))
}
Set-Acl -LiteralPath $dir -AclObject $acl
}
} catch {}
}
try {
$cutoff = [DateTime]::UtcNow.AddMinutes(-10)
Get-ChildItem -LiteralPath $dir -Filter 'switch-*.dpapi' -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTimeUtc -lt $cutoff } |
ForEach-Object { [IO.File]::Delete($_.FullName) }
} catch {}
}
function Save-Vault($path, $vault) {
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress))
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
Write-AccountFile $path $encrypted
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 10 -Compress))
try {
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
Ensure-VaultDirectory $path
Write-AccountFile $path $encrypted
} finally {
if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) }
}
}
function Write-SwitchState($request, $state, $errorCode = '') {
$data = @{ email = $request.email; state = $state; error = $errorCode; updatedAt = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }
Write-AccountFile $request.statusFile ($utf8.GetBytes((ConvertTo-Json -InputObject $data -Compress)))
}
function Get-AccountClients {
$sessionId = (Get-Process -Id $PID).SessionId
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$candidates = @(Get-CimInstance Win32_Process -Filter "Name = 'Antigravity.exe' OR Name = 'Antigravity IDE.exe' OR Name = 'agy.exe' OR Name = 'language_server.exe'")
$owned = @($candidates | Where-Object {
$_.SessionId -eq $sessionId -and $_.ExecutablePath -and (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $userSid
})
$roots = @($owned | Where-Object {
$_.Name -in @('Antigravity.exe', 'Antigravity IDE.exe') -and
$_.CommandLine -notmatch '(?:^|\s)(?:--type|--import|--inspect|--inspect-brk|--ms-enable-electron-run-as-node)(?:=|\s)' -and
$_.CommandLine -notmatch 'sidecar_sdk[\\/]register_loader\.js' -and
[Diagnostics.FileVersionInfo]::GetVersionInfo($_.ExecutablePath).ProductName -like 'Antigravity*'
})
$installDirectories = @($roots | ForEach-Object { [IO.Path]::GetDirectoryName($_.ExecutablePath) + [IO.Path]::DirectorySeparatorChar } | Select-Object -Unique)
$agyCliHubPath = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE '.gemini\bin\agy.exe'))
$hubs = @($owned | Where-Object {
$candidate = $_
$trustedPath = [string]::Equals($candidate.ExecutablePath, $agyCliHubPath, [StringComparison]::OrdinalIgnoreCase) -or
@($installDirectories | Where-Object { $candidate.ExecutablePath.StartsWith($_, [StringComparison]::OrdinalIgnoreCase) }).Count -gt 0
($candidate.Name -eq 'language_server.exe' -or
($candidate.Name -eq 'agy.exe' -and $candidate.CommandLine -match '(?:^|\s)--hub(?:\s|$)')) -and $trustedPath
})
return @{ roots = $roots; hubs = $hubs; sessionId = $sessionId }
}
function Stop-AccountClients {
$snapshot = Get-AccountClients
$roots = $snapshot.roots
$hubs = $snapshot.hubs
$sessionId = $snapshot.sessionId
$byExe = @{}
$launch = @()
foreach ($root in $roots) {
$exeKey = $root.ExecutablePath.ToLowerInvariant()
$hasDebugPort = $root.CommandLine -match '(?:^|\s)--remote-debugging-port(?:=|\s)'
if (-not $byExe.ContainsKey($exeKey)) {
$entry = @{ path = $root.ExecutablePath; useDebugPort = [bool]$hasDebugPort }
$byExe[$exeKey] = $entry
$launch += $entry
} elseif ($hasDebugPort) {
$byExe[$exeKey].useDebugPort = $true
}
}
$script:clientsToRestart = $launch
$script:clientsStopped = $true
foreach ($root in $roots) {
$process = Get-Process -Id $root.ProcessId -ErrorAction SilentlyContinue
if ($process -and $process.MainWindowHandle -ne 0) { [void]$process.CloseMainWindow() }
}
$clientPaths = @($launch | ForEach-Object { $_.path })
if ($roots.Count) {
for ($i = 0; $i -lt 10; $i++) {
$aliveRoots = @(Get-Process -Id @($roots.ProcessId) -ErrorAction SilentlyContinue)
if ($aliveRoots.Count -eq 0) { break }
Start-Sleep -Milliseconds 150
}
}
$remaining = @(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId -and $_.Path -in $clientPaths })
foreach ($process in $remaining) { Stop-Process -Id $process.Id -Force -ErrorAction SilentlyContinue }
foreach ($hub in $hubs) {
if (Get-Process -Id $hub.ProcessId -ErrorAction SilentlyContinue) { Stop-Process -Id $hub.ProcessId -Force -ErrorAction SilentlyContinue }
}
foreach ($processId in @($remaining.Id) + @($hubs.ProcessId)) {
if ($processId) { Wait-Process -Id $processId -Timeout 10 -ErrorAction SilentlyContinue }
}
if (@(Get-Process -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $sessionId -and $_.Path -in $clientPaths }).Count) {
throw 'clientCloseFailed'
}
foreach ($hub in $hubs) {
if (Get-Process -Id $hub.ProcessId -ErrorAction SilentlyContinue) { throw 'clientCloseFailed' }
}
}
function Start-AccountClients {
foreach ($envVar in @('ELECTRON_RUN_AS_NODE', 'ELECTRON_NO_ATTACH_CONSOLE', 'VSCODE_IPC_HOOK', 'CHROME_CRASHPAD_PIPE_NAME')) {
Remove-Item -Path ("Env:\" + $envVar) -ErrorAction SilentlyContinue
}
foreach ($client in $script:clientsToRestart) {
$start = @{ FilePath = $client.path; WorkingDirectory = [IO.Path]::GetDirectoryName($client.path) }
if ($client.useDebugPort) { $start.ArgumentList = '--remote-debugging-port=0' }
[void](Start-Process @start -PassThru)
}
$script:clientsToRestart = @()
$script:clientsStopped = $false
}
function Schedule-AccountSwitch($request) {
if (Test-AccountFile $request.statusFile) {
$status = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile))
if ($status.state -eq 'starting' -and ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $status.updatedAt) -lt 120000) {
return @{ error = 'busy' }
}
}
$request.action = 'switch'
$request | Add-Member -NotePropertyName restartClients -NotePropertyValue $true -Force
$job = Join-Path ([IO.Path]::GetDirectoryName($request.vault)) ('switch-' + [guid]::NewGuid().ToString() + '.dpapi')
Save-Vault $job $request
Write-SwitchState $request 'starting'
$scriptPath = $request.scriptPath.Replace("'", "''")
$jobLiteral = $job.Replace("'", "''")
$code = "& '$scriptPath' -JobPath '$jobLiteral'"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))
$shell = Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe'
$command = '"' + $shell + '" -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -EncodedCommand ' + $encoded
try {
# WMI starts the worker outside the client job so closing the App cannot terminate the switch.
$started = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $command }
if ($started.ReturnValue -ne 0) { throw 'switchStartFailed' }
} catch {
[IO.File]::Delete($job)
Write-SwitchState $request 'failed' 'switchStartFailed'
return @{ error = 'switchStartFailed' }
}
return @{ scheduled = $true; accounts = @(); selectedEmail = $request.email }
}
function Add-NativeCredentialType {
@@ -114,91 +275,201 @@ function Invoke-AccountAction($request) {
$vault = @{ entries = @(); selectedEmail = '' }
if (Test-AccountFile $request.vault) {
$plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser')
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
try {
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
} finally {
if ($plain) { [Array]::Clear($plain, 0, $plain.Length) }
}
}
$vaultSecured = [bool]($vault.security -and $vault.security.enabled)
$entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1
if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) {
return @{ error = 'credentialChanged' }
}
switch ($request.action) {
'inspectClients' {
$clients = Get-AccountClients
return @{ clients = @($clients.roots | ForEach-Object { @{ name = $_.Name; path = $_.ExecutablePath } }); hubs = $clients.hubs.Count }
}
'readVault' {
return @{
entries = @($vault.entries)
selectedEmail = [string]$vault.selectedEmail
security = $vault.security
}
}
'writeVault' {
$nextVault = @{
entries = @($request.entries)
selectedEmail = [string]$request.selectedEmail
}
if ($request.security) {
$nextVault.security = $request.security
}
Save-Vault $request.vault $nextVault
$vault = $nextVault
$vaultSecured = [bool]($vault.security -and $vault.security.enabled)
if ($request.clearStatus -and $request.statusFile -and (Test-AccountFile $request.statusFile)) {
try { [IO.File]::Delete($request.statusFile) } catch {}
}
}
'scheduleSwitch' {
if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) {
return @{ error = 'vaultLocked' }
}
if (-not $entry) { return @{ error = 'notFound' } }
$scheduled = Schedule-AccountSwitch $request
$scheduled.accounts = @($vault.entries | ForEach-Object { $_.email })
if ($vaultSecured) {
$scheduled.security = @{ enabled = $true; salt = [string]$vault.security.salt }
}
return $scheduled
}
'readCurrent' {
Add-NativeCredentialType
$bytes = [NativeAccountCredential]::Read($request.target)
if (-not $bytes) {
foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) {
$bytes = [IO.File]::ReadAllBytes($path)
if ($bytes) { break }
try {
if (-not $bytes) {
foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) {
$bytes = [IO.File]::ReadAllBytes($path)
if ($bytes) { break }
}
}
}
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
} finally {
if ($bytes) { [Array]::Clear($bytes, 0, $bytes.Length) }
}
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
}
'read' {
if (-not $entry) { return @{ error = 'notFound' } }
return @{ credential = $entry.credential }
$readOut = @{ credential = $entry.credential }
if ($vaultSecured) {
$readOut.security = @{ enabled = $true; salt = [string]$vault.security.salt }
}
return $readOut
}
'save' {
if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) {
return @{ error = 'vaultLocked' }
}
if ($entry) { $entry.credential = $request.credential }
else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) }
Save-Vault $request.vault $vault
}
'saveQuota' {
if (-not $entry) { return @{ error = 'notFound' } }
$entry | Add-Member -NotePropertyName quota -NotePropertyValue $request.quota -Force
Save-Vault $request.vault $vault
}
'switch' {
if (-not $entry) { return @{ error = 'notFound' } }
$replacement = $utf8.GetBytes($request.credential)
if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } }
if ($replacement.Length -gt 2560) {
[Array]::Clear($replacement, 0, $replacement.Length)
return @{ error = 'credentialTooLarge' }
}
Add-NativeCredentialType
if ($request.restartClients) { Stop-AccountClients }
$previous = [NativeAccountCredential]::Read($request.target)
$fallbacks = @(foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } }
elseif ([IO.Directory]::Exists([IO.Path]::GetDirectoryName($path))) { @{ path = $path; original = $null } }
})
$written = @()
[NativeAccountCredential]::Write($request.target, $replacement)
try {
foreach ($fallback in $fallbacks) {
Write-AccountFile $fallback.path $replacement
$written += $fallback
[NativeAccountCredential]::Write($request.target, $replacement)
try {
foreach ($fallback in $fallbacks) {
Write-AccountFile $fallback.path $replacement
$written += $fallback
}
$entry.credential = if ($request.vaultCredential) { $request.vaultCredential } else { $entry.credential }
$vault.selectedEmail = $request.email
Save-Vault $request.vault $vault
} catch {
$restored = $true
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
foreach ($fallback in $written) {
try {
if ($null -eq $fallback.original) { [IO.File]::Delete($fallback.path) }
else { Write-AccountFile $fallback.path $fallback.original }
} catch { $restored = $false }
}
if (-not $restored) { return @{ error = 'rollbackFailed' } }
throw
}
$entry.credential = $request.credential
$vault.selectedEmail = $request.email
Save-Vault $request.vault $vault
} catch {
$restored = $true
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
foreach ($fallback in $written) {
try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false }
}
if (-not $restored) { return @{ error = 'rollbackFailed' } }
throw
} finally {
if ($replacement) { [Array]::Clear($replacement, 0, $replacement.Length) }
if ($previous) { [Array]::Clear($previous, 0, $previous.Length) }
}
}
'remove' {
if ($vaultSecured -and (-not $request.vaultUnlocked -or $request.expectedSecuritySalt -cne [string]$vault.security.salt)) {
return @{ error = 'vaultLocked' }
}
if (-not $entry) { return @{ error = 'notFound' } }
$vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email })
if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' }
Save-Vault $request.vault $vault
if ($request.statusFile -and (Test-AccountFile $request.statusFile)) {
try {
$st = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile))
if ($st.email -eq $request.email -and $st.state -ne 'starting') { [IO.File]::Delete($request.statusFile) }
} catch {}
}
}
}
return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail }
$quotas = @{}
foreach ($account in $vault.entries) { if ($account.quota) { $quotas[$account.email] = $account.quota } }
$result = @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail; quotas = $quotas }
if ($vaultSecured) {
$result.security = @{ enabled = $true; salt = [string]$vault.security.salt }
}
if ($request.statusFile -and (Test-AccountFile $request.statusFile)) {
try { $result.switchState = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($request.statusFile)) } catch {}
}
return $result
}
$mutex = $null
$locked = $false
try {
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
if ($JobPath) {
Add-Type -AssemblyName System.Security
$jobPlain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($JobPath), $null, 'CurrentUser')
try {
$request = ConvertFrom-Json -InputObject ($utf8.GetString($jobPlain))
} finally {
if ($jobPlain) { [Array]::Clear($jobPlain, 0, $jobPlain.Length) }
}
} else {
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
}
$mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials')
try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true }
$waitTimeoutMs = if ($JobPath) { 15000 } else { 5000 }
try { $locked = $mutex.WaitOne($waitTimeoutMs) } catch [Threading.AbandonedMutexException] { $locked = $true }
$result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } }
if ($JobPath) { Write-SwitchState $request $(if ($result.error) { 'failed' } else { 'written' }) $result.error }
} catch {
$result = @{ error = 'storeFailed' }
$nativeError = $_.Exception.InnerException
if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) {
$result.error = 'credentialAccessDenied'
}
if ($_.Exception.Message -match 'clientCloseFailed') { $result.error = 'clientCloseFailed' }
if ($JobPath -and $request) { Write-SwitchState $request 'failed' $result.error }
} finally {
if ($JobPath) {
if ($script:clientsStopped) {
try { Start-AccountClients } catch { Write-SwitchState $request 'failed' 'clientRestartFailed' }
}
[IO.File]::Delete($JobPath)
}
if ($locked) { $mutex.ReleaseMutex() }
if ($mutex) { $mutex.Dispose() }
}
[Console]::Write((ConvertTo-Json -InputObject $result -Compress))
[Console]::Write((ConvertTo-Json -InputObject $result -Depth 10 -Compress))
+67
View File
@@ -0,0 +1,67 @@
/** @fileoverview Google account requests using the panel's system proxy transport. */
import * as http from 'node:http';
import * as https from 'node:https';
import * as net from 'node:net';
import * as tls from 'node:tls';
import { detectSystemHttpsProxy, openCcProxyTunnelSocket } from './cloudcode-proxy.mjs';
export async function fetchGoogleAccount(url, { method = 'GET', body, headers = {}, signal } = {}) {
const target = new URL(url);
if (target.protocol !== 'https:' || !/^(?:oauth2|www|cloudcode-pa|daily-cloudcode-pa(?:\.sandbox)?)\.googleapis\.com$/.test(target.hostname)) {
throw new Error('Unsupported Google account endpoint');
}
signal?.throwIfAborted();
const proxy = await detectSystemHttpsProxy(target.hostname);
signal?.throwIfAborted();
const socket = proxy
? await openCcProxyTunnelSocket({ http, https, net, tls }, target.hostname, 443, proxy, { timeoutMs: 4500 })
: null;
if (signal?.aborted) {
socket?.destroy();
signal.throwIfAborted();
}
const textBody = body === undefined ? undefined : String(body);
const requestHeaders = { Accept: 'application/json', ...headers };
if (body instanceof URLSearchParams) requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
if (textBody !== undefined) requestHeaders['Content-Length'] = Buffer.byteLength(textBody);
let socketConsumed = false;
const agent = socket ? new https.Agent({ keepAlive: false }) : null;
if (agent) {
agent.createConnection = () => {
socketConsumed = true;
return socket;
};
}
const onAbort = () => {
if (!socketConsumed) socket?.destroy();
};
signal?.addEventListener?.('abort', onAbort, { once: true });
return new Promise((resolve, reject) => {
const request = https.request(target, { method, headers: requestHeaders, signal, ...(agent ? { agent } : {}) }, (response) => {
const chunks = [];
let bytes = 0;
response.on('data', (chunk) => {
bytes += chunk.length;
if (bytes > 4 * 1024 * 1024) return request.destroy(new Error('Account response too large'));
chunks.push(chunk);
});
response.on('error', reject);
response.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
const status = response.statusCode || 0;
resolve({ status, ok: status >= 200 && status < 300, json: async () => JSON.parse(raw) });
});
});
request.on('error', (err) => {
if (!socketConsumed) socket?.destroy();
reject(err);
});
request.on('close', () => {
signal?.removeEventListener?.('abort', onAbort);
agent?.destroy();
});
request.end(textBody);
});
}
+168
View File
@@ -0,0 +1,168 @@
/** @fileoverview Browser authorization and loopback callbacks for adding Google accounts. */
import { execFile } from 'node:child_process';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { createServer } from 'node:http';
import { join } from 'node:path';
import { buildGoogleAccountLoginUrl, exchangeGoogleAccountCode } from './account-oauth.mjs';
function openGoogleAccountBrowser(url) {
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
return new Promise((resolve) => {
execFile(shell, ['-NoProfile', '-NonInteractive', '-Command', 'Start-Process -FilePath $env:USAGE_MONITOR_LOGIN_URL'], {
windowsHide: true, timeout: 5000,
env: { ...process.env, USAGE_MONITOR_LOGIN_URL: url },
}, (error) => resolve(!error));
});
}
function loginCallbackPage(language, success) {
const english = language === 'en-US';
const title = english ? success ? 'Account added' : 'Sign-in incomplete' : success ? '账号已添加' : '登录未完成';
const detail = english ? 'Return to the Antigravity account page. You can close this browser tab.' : '请返回 Antigravity 的账号页,可关闭此浏览器标签页。';
return `<!doctype html><html lang="${english ? 'en' : 'zh-CN'}"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${title}</title><style>body{font:16px system-ui,sans-serif;max-width:36rem;margin:15vh auto;padding:24px;line-height:1.6}h1{font-size:24px}</style><h1>${title}</h1><p>${detail}</p></html>`;
}
export function createAccountLoginController({
openBrowser = openGoogleAccountBrowser,
buildLoginUrl = buildGoogleAccountLoginUrl,
exchangeCode = exchangeGoogleAccountCode,
getClients,
timeoutMs = 10 * 60 * 1000,
} = {}) {
let current = null;
let starting = null;
function snapshot(flow = current) {
if (!flow) return null;
return { id: flow.id, status: flow.status, error: flow.error || '',
...(flow.status === 'waiting' ? { url: flow.url, opened: flow.opened } : {}),
...(flow.email ? { email: flow.email } : {}) };
}
function finish(flow, status, error = '') {
clearTimeout(flow.timer);
flow.status = status;
flow.error = error;
flow.server?.close();
flow.codeVerifier = '';
}
function cancel(id) {
if (!current || current.id !== id) return null;
if (current.status === 'waiting' || current.status === 'exchanging') finish(current, 'cancelled');
return snapshot();
}
async function start(onCredential, language = 'zh-CN') {
if (starting) return starting;
if (current && ['waiting', 'exchanging', 'saving'].includes(current.status)) return snapshot();
starting = prepare(onCredential, language).finally(() => { starting = null; });
return starting;
}
async function prepare(onCredential, language) {
const flow = { id: randomUUID(), state: randomBytes(32).toString('base64url'),
codeVerifier: randomBytes(32).toString('base64url'), status: 'waiting', opened: false };
current = flow;
const server = createServer({ maxHeaderSize: 16384 }, async (request, response) => {
response.setHeader('Cache-Control', 'no-store');
response.setHeader('Referrer-Policy', 'no-referrer');
response.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'");
let url;
try { url = new URL(request.url || '/', 'http://127.0.0.1'); } catch {
response.writeHead(400).end();
return;
}
if (!flow.redirectUri || request.method !== 'GET' || request.headers.host !== new URL(flow.redirectUri).host || url.pathname !== '/oauth-callback') {
response.writeHead(404).end();
return;
}
if (url.searchParams.get('state') !== flow.state) {
response.writeHead(400).end();
return;
}
if (current !== flow || flow.status !== 'waiting') {
response.writeHead(409).end();
return;
}
response.setHeader('Content-Type', 'text/html; charset=utf-8');
if (url.searchParams.has('error')) {
finish(flow, 'cancelled', 'loginDenied');
response.writeHead(200).end(loginCallbackPage(language, false));
return;
}
const code = url.searchParams.get('code');
if (!code || code.length > 4096) {
response.writeHead(400).end(loginCallbackPage(language, false));
return;
}
flow.status = 'exchanging';
try {
const credential = await exchangeCode(
code,
flow.redirectUri,
flow.codeVerifier,
getClients ? { getClients } : undefined
);
if (current !== flow || flow.status !== 'exchanging') {
response.writeHead(409).end(loginCallbackPage(language, false));
return;
}
flow.status = 'saving';
await onCredential(credential);
flow.email = credential.email;
finish(flow, 'success');
response.writeHead(200).end(loginCallbackPage(language, true));
} catch (error) {
if (current === flow && ['exchanging', 'saving'].includes(flow.status)) {
const preservedError = [
'storeFailed',
'credentialTooLarge',
'credentialAccessDenied',
'busy',
'oauthClientUnavailable',
].includes(error?.message);
finish(flow, 'error', preservedError ? error.message : 'loginExchangeFailed');
}
response.writeHead(500).end(loginCallbackPage(language, false));
}
});
flow.server = server;
server.headersTimeout = 10000;
server.requestTimeout = 30000;
server.keepAliveTimeout = 1000;
try {
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => { server.off('error', reject); resolve(); });
});
flow.redirectUri = `http://127.0.0.1:${server.address().port}/oauth-callback`;
const challenge = createHash('sha256').update(flow.codeVerifier).digest('base64url');
flow.url = await buildLoginUrl(
flow.redirectUri,
flow.state,
challenge,
getClients ? { getClients } : undefined
);
server.unref();
flow.timer = setTimeout(() => {
if (current === flow && ['waiting', 'exchanging'].includes(flow.status)) finish(flow, 'expired', 'loginExpired');
}, timeoutMs);
flow.timer.unref?.();
flow.opened = await openBrowser(flow.url).catch(() => false);
return snapshot(flow);
} catch (error) {
finish(
flow,
'error',
error?.message === 'oauthClientUnavailable' ? 'oauthClientUnavailable' : 'loginStartFailed'
);
return snapshot(flow);
}
}
return { start, cancel, getStatus: (id) => !id || current?.id === id ? snapshot() : null };
}
export const accountLoginController = createAccountLoginController();
+444 -69
View File
@@ -1,86 +1,413 @@
/** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */
import { readFile } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, promises as fsPromises } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { basename, dirname, join } from 'node:path';
import { fetchGoogleAccount } from './account-http.mjs';
import { buildOfficialQuotaPools } from './quota-pools.mjs';
const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com'];
let nativeOAuthClients;
const CLOUD_CODE_HOSTS = [
'daily-cloudcode-pa.googleapis.com',
'cloudcode-pa.googleapis.com',
'daily-cloudcode-pa.sandbox.googleapis.com',
];
const OAUTH_CLIENT_ID_RE = /^\d+-[\w-]+\.apps\.googleusercontent\.com$/;
const OAUTH_CLIENT_SECRET_RE = /^GOCSPX-[\w-]+$/;
// One-way SHA-256 digest of the official Antigravity desktop OAuth client_id for synchronous allowlist checks
// without embedding plaintext OAuth credentials in source control.
const OFFICIAL_OAUTH_CLIENT_ID_HASHES = Object.freeze(
new Set(['bf00c418024ba6bf606ccdc37120976e41bc429dd1d46ecf16a729aa532626ea'])
);
const ACCOUNT_USER_AGENT = `antigravity/hub/4.3.0 (os_type=${process.platform === 'win32' ? 'windows' : process.platform}; arch=${process.arch === 'x64' ? 'amd64' : process.arch})`;
const PE_ID_LEN_OP = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
const PE_LEA_RIP_OP = Buffer.from([0x48, 0x8d, 0x0d]);
const PE_BETWEEN_OP = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
let nativeOAuthClientsPromise = null;
const discoveredAllowedClientIds = new Set();
function sha256Hex(value) {
return createHash('sha256').update(String(value || ''), 'utf8').digest('hex');
}
function parsePeTextAndRdata(headerBuf) {
if (!Buffer.isBuffer(headerBuf) || headerBuf.length < 64) return null;
const pe = headerBuf.readUInt16LE(0) === 0x5a4d ? headerBuf.readUInt32LE(60) : 0;
if (!pe || pe + 24 > headerBuf.length || headerBuf.readUInt32LE(pe) !== 0x4550 || headerBuf.readUInt16LE(pe + 4) !== 0x8664) {
return null;
}
const count = headerBuf.readUInt16LE(pe + 6);
const table = pe + 24 + headerBuf.readUInt16LE(pe + 20);
if (table + count * 40 > headerBuf.length) return null;
let text = null;
let rodata = null;
for (let i = 0; i < count; i += 1) {
const offset = table + i * 40;
const name = headerBuf.toString('ascii', offset, offset + 8).replace(/\0+$/, '');
const section = {
name,
rva: headerBuf.readUInt32LE(offset + 12),
size: headerBuf.readUInt32LE(offset + 16),
start: headerBuf.readUInt32LE(offset + 20),
};
if (name === '.text') text = section;
else if (name === '.rdata') rodata = section;
}
return text && rodata ? { text, rodata } : null;
}
// Go's x64 OAuth config initializer stores ClientID and ClientSecret as two consecutive pointer/length pairs.
function scanGoOAuthInitializerMatches(machineCode, textRva, rodata) {
const matches = [];
for (
let i = machineCode.indexOf(PE_ID_LEN_OP);
i >= 0 && i + 33 <= machineCode.length;
i = machineCode.indexOf(PE_ID_LEN_OP, i + 1)
) {
if (
!machineCode.subarray(i + 8, i + 11).equals(PE_LEA_RIP_OP) ||
!machineCode.subarray(i + 15, i + 22).equals(PE_BETWEEN_OP) ||
!machineCode.subarray(i + 26, i + 29).equals(PE_LEA_RIP_OP)
) {
continue;
}
const idLen = machineCode.readUInt32LE(i + 4);
const secretLen = machineCode.readUInt32LE(i + 22);
if (idLen <= 0 || idLen > 100 || secretLen <= 0 || secretLen > 100) continue;
const idRva = textRva + (i + 11) + 4 + machineCode.readInt32LE(i + 11);
const secretRva = textRva + (i + 29) + 4 + machineCode.readInt32LE(i + 29);
const idOffset = idRva - rodata.rva;
const secretOffset = secretRva - rodata.rva;
if (
idOffset < 0 ||
idOffset + idLen > rodata.size ||
secretOffset < 0 ||
secretOffset + secretLen > rodata.size
) {
continue;
}
matches.push({ idOffset, idLen, secretOffset, secretLen });
}
return matches;
}
export function extractNativeOAuthClients(binary) {
const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0;
if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return [];
const count = binary.readUInt16LE(pe + 6);
const table = pe + 24 + binary.readUInt16LE(pe + 20);
if (table + count * 40 > binary.length) return [];
const sections = Array.from({ length: count }, (_, i) => {
const offset = table + i * 40;
return {
name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''),
rva: binary.readUInt32LE(offset + 12),
size: binary.readUInt32LE(offset + 16),
start: binary.readUInt32LE(offset + 20),
};
});
const text = sections.find(({ name }) => name === '.text');
const rodata = sections.find(({ name }) => name === '.rdata');
if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return [];
const machineCode = binary.subarray(text.start, text.start + text.size);
function readLiteral(displacementOffset, length) {
const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset);
const offset = rva - rodata.rva;
if (length > 100 || offset < 0 || offset + length > rodata.size) return '';
return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length);
const sections = parsePeTextAndRdata(binary);
if (!sections) return [];
const { text, rodata } = sections;
if (text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) {
return [];
}
// Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs.
const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]);
const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
const machineCode = binary.subarray(text.start, text.start + text.size);
const clients = new Map();
for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) {
if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) ||
!machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) ||
!machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue;
const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4));
const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22));
if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) {
for (const m of scanGoOAuthInitializerMatches(machineCode, text.rva, rodata)) {
const id = binary.toString('ascii', rodata.start + m.idOffset, rodata.start + m.idOffset + m.idLen);
const secret = binary.toString('ascii', rodata.start + m.secretOffset, rodata.start + m.secretOffset + m.secretLen);
if (OAUTH_CLIENT_ID_RE.test(id) && OAUTH_CLIENT_SECRET_RE.test(secret)) {
clients.set(id, { id, secret });
}
}
return Array.from(clients.values()).reverse();
}
async function loadNativeOAuthClients() {
if (!nativeOAuthClients) {
nativeOAuthClients = (async () => {
const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
const binaries = [
join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'),
join(homedir(), '.gemini', 'bin', 'agy.exe'),
];
for (const filename of binaries) {
const binary = await readFile(filename).catch(() => null);
const clients = binary ? extractNativeOAuthClients(binary) : [];
if (clients.length) return clients;
async function extractNativeOAuthClientsFromFile(filePath) {
if (typeof fsPromises === 'undefined' || typeof fsPromises?.open !== 'function') {
return [];
}
let handle = null;
try {
handle = await fsPromises.open(filePath, 'r');
const st = await handle.stat();
if (!st.isFile() || st.size < 64) return [];
const headerLen = Math.min(4096, st.size);
const headerBuf = Buffer.alloc(headerLen);
await handle.read(headerBuf, 0, headerLen, 0);
const sections = parsePeTextAndRdata(headerBuf);
if (!sections) return [];
const { text, rodata } = sections;
if (text.start + text.size > st.size || rodata.start + rodata.size > st.size) {
return [];
}
// Read only .text into memory and fetch matching <=100B literals directly from .rdata on demand.
const textBuf = Buffer.allocUnsafe(text.size);
let offset = 0;
while (offset < text.size) {
const { bytesRead } = await handle.read(textBuf, offset, text.size - offset, text.start + offset);
if (bytesRead <= 0) return [];
offset += bytesRead;
}
const matches = scanGoOAuthInitializerMatches(textBuf, text.rva, rodata);
const clients = new Map();
for (const m of matches) {
const idBuf = Buffer.allocUnsafe(m.idLen);
const secBuf = Buffer.allocUnsafe(m.secretLen);
const [idRead, secRead] = await Promise.all([
handle.read(idBuf, 0, m.idLen, rodata.start + m.idOffset),
handle.read(secBuf, 0, m.secretLen, rodata.start + m.secretOffset),
]);
if (idRead.bytesRead !== m.idLen || secRead.bytesRead !== m.secretLen) continue;
const id = idBuf.toString('ascii');
const secret = secBuf.toString('ascii');
if (OAUTH_CLIENT_ID_RE.test(id) && OAUTH_CLIENT_SECRET_RE.test(secret)) {
clients.set(id, { id, secret });
}
}
return Array.from(clients.values()).reverse();
} catch {
return [];
} finally {
await handle?.close?.().catch(() => {});
}
}
export function collectNativeOAuthBinaryCandidates({
env = process.env,
homeDir = homedir(),
existsFn = existsSync,
} = {}) {
const seen = new Set();
const candidates = [];
const add = (filePath) => {
const clean = String(filePath || '').trim();
if (!clean) return;
const key = clean.toLowerCase();
if (seen.has(key)) return;
seen.add(key);
candidates.push(clean);
};
const addFromInstallRoot = (installRoot) => {
if (!installRoot) return;
add(join(installRoot, 'resources', 'bin', 'language_server.exe'));
add(join(installRoot, 'resources', 'app', 'extensions', 'antigravity', 'bin', 'language_server_windows_x64.exe'));
};
add(env?.ANTIGRAVITY_LS_BIN);
const hints = [
env?.USAGE_MONITOR_HOST_EXE,
env?.ANTIGRAVITY_AGENTAPI_EXE,
env?.CHROME_DEVTOOLS_MCP_JS,
];
for (const rawHint of hints) {
const hint = String(rawHint || '').trim();
if (!hint) continue;
const leaf = basename(hint).toLowerCase();
if (/^(?:language_server.*|agy)\.exe$/i.test(leaf)) {
add(hint);
continue;
}
if (/\.exe$/i.test(leaf)) {
addFromInstallRoot(dirname(hint));
}
let cur = hint;
for (let depth = 0; depth < 8 && cur && dirname(cur) !== cur; depth += 1) {
if (basename(cur).toLowerCase() === 'resources') {
addFromInstallRoot(dirname(cur));
break;
}
cur = dirname(cur);
}
}
const localAppData = String(env?.LOCALAPPDATA || '').trim() || join(homeDir, 'AppData', 'Local');
const programFiles = String(env?.ProgramFiles || '').trim() || 'C:\\Program Files';
const geminiBase = String(env?.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homeDir, '.gemini');
addFromInstallRoot(join(localAppData, 'Programs', 'Antigravity'));
addFromInstallRoot(join(localAppData, 'Programs', 'Antigravity IDE'));
addFromInstallRoot(join(programFiles, 'Antigravity'));
addFromInstallRoot(join(programFiles, 'Antigravity IDE'));
add(join(geminiBase, 'bin', 'agy.exe'));
if (typeof existsFn !== 'function') return candidates;
return candidates.filter((p) => {
try {
return Boolean(existsFn(p));
} catch {
return false;
}
});
}
function discoverRunningOAuthBinaryPaths() {
if (process.platform !== 'win32' || typeof execFile !== 'function') {
return Promise.resolve([]);
}
const shell = join(
process.env.SystemRoot || 'C:/Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe'
);
const cmd =
"Get-CimInstance Win32_Process -Filter \"Name LIKE 'language_server%' OR Name LIKE 'agy%'\" | Select-Object -ExpandProperty ExecutablePath -Unique";
return new Promise((resolve) => {
execFile(
shell,
['-NoProfile', '-NonInteractive', '-Command', cmd],
{ windowsHide: true, timeout: 3000, encoding: 'utf8' },
(err, stdout) => {
if (err || !stdout) {
resolve([]);
return;
}
const paths = String(stdout)
.split(/\r?\n/)
.map((line) => line.trim())
.filter((p) => /^(?:language_server.*|agy)\.exe$/i.test(basename(p)));
resolve(paths);
}
return [];
})();
);
});
}
function rememberDiscoveredClients(clients) {
for (const client of clients) {
if (client?.id) discoveredAllowedClientIds.add(client.id);
}
return Object.freeze(clients.map((c) => Object.freeze({ id: c.id, secret: c.secret })));
}
export async function loadNativeOAuthClients(options = undefined) {
const customRun = Boolean(options && Object.keys(options).length > 0);
const env = options?.env ?? process.env;
const overrideId = String(env?.USAGE_MONITOR_OAUTH_CLIENT_ID || '').trim();
const overrideSecret = String(env?.USAGE_MONITOR_OAUTH_CLIENT_SECRET || '').trim();
if (OAUTH_CLIENT_ID_RE.test(overrideId) && OAUTH_CLIENT_SECRET_RE.test(overrideSecret)) {
return rememberDiscoveredClients([{ id: overrideId, secret: overrideSecret }]);
}
const runLoad = async () => {
const extractFromFileFn = options?.extractFromFileFn || extractNativeOAuthClientsFromFile;
const discoverRunningFn = options?.discoverRunningFn || discoverRunningOAuthBinaryPaths;
const candidates = collectNativeOAuthBinaryCandidates({
env,
homeDir: options?.homeDir ?? homedir(),
existsFn: options?.existsFn ?? existsSync,
});
const tried = new Set();
for (const filePath of candidates) {
tried.add(filePath.toLowerCase());
const clients = await extractFromFileFn(filePath);
if (Array.isArray(clients) && clients.length > 0) {
return rememberDiscoveredClients(clients);
}
}
const runningPaths = await discoverRunningFn().catch(() => []);
for (const filePath of runningPaths) {
const key = String(filePath || '').trim().toLowerCase();
if (!key || tried.has(key)) continue;
tried.add(key);
const clients = await extractFromFileFn(filePath);
if (Array.isArray(clients) && clients.length > 0) {
return rememberDiscoveredClients(clients);
}
}
return Object.freeze([]);
};
if (customRun) {
return runLoad();
}
if (!nativeOAuthClientsPromise) {
nativeOAuthClientsPromise = runLoad();
}
const clients = await nativeOAuthClientsPromise;
if (!clients.length) {
nativeOAuthClientsPromise = null;
}
const clients = await nativeOAuthClients;
if (!clients.length) nativeOAuthClients = null;
return clients;
}
export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) {
export function isAllowedOAuthClientId(clientId, allowedIds = null) {
if (typeof clientId !== 'string') return false;
const clean = clientId.trim();
if (!clean) return false;
if (allowedIds) {
if (allowedIds instanceof Set && allowedIds.has(clean)) return true;
if (Array.isArray(allowedIds) && allowedIds.includes(clean)) return true;
}
if (discoveredAllowedClientIds.has(clean)) return true;
return OFFICIAL_OAUTH_CLIENT_ID_HASHES.has(sha256Hex(clean));
}
export async function buildGoogleAccountLoginUrl(
redirectUri,
state,
codeChallenge,
{ getClients = loadNativeOAuthClients } = {}
) {
const clients = await getClients();
if (!Array.isArray(clients) || !clients.length || !clients[0]?.id) {
throw new Error('oauthClientUnavailable');
}
const url = new URL('https://accounts.google.com/o/oauth2/v2/auth');
url.search = new URLSearchParams({
client_id: clients[0].id,
redirect_uri: redirectUri,
response_type: 'code',
scope: [
'openid',
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/aicode',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/cclog',
'https://www.googleapis.com/auth/experimentsandconfigs',
].join(' '),
access_type: 'offline',
prompt: 'consent select_account',
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
}).toString();
return url.toString();
}
export async function exchangeGoogleAccountCode(
code,
redirectUri,
codeVerifier,
{ fetchFn = fetchGoogleAccount, getClients = loadNativeOAuthClients } = {}
) {
const clients = await getClients();
if (!Array.isArray(clients) || !clients.length || !clients[0]?.id || !clients[0]?.secret) {
throw new Error('oauthClientUnavailable');
}
const client = clients[0];
const response = await fetchFn(OAUTH_TOKEN_URL, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(15000),
headers: { 'User-Agent': ACCOUNT_USER_AGENT },
body: new URLSearchParams({
client_id: client.id,
client_secret: client.secret,
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
}),
});
const result = await response.json();
if (!response.ok || !result.access_token || !result.refresh_token ||
!Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('loginExchangeFailed');
return resolveGoogleCredential({
token: { ...result, expiry: new Date(Date.now() + result.expires_in * 1000).toISOString() },
...(result.id_token ? { id_token: result.id_token } : {}),
}, { fetchFn, getClients: async () => clients });
}
export async function resolveGoogleCredential(
credential,
{ refresh = false, fetchFn = fetchGoogleAccount, getClients = loadNativeOAuthClients } = {}
) {
let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token;
let idToken = credential.id_token;
if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) {
if (refresh || !accessToken || !Number.isFinite(Date.parse(expiry)) || Date.parse(expiry) <= Date.now() + 60_000) {
const clients = await getClients();
if (!clients.length) throw new Error('oauthClientUnavailable');
let refreshed = false;
@@ -117,23 +444,67 @@ export async function resolveGoogleCredential(credential, { refresh = false, fet
auth_method: 'consumer',
id_token_email: user.email,
...(idToken ? { id_token: idToken } : {}),
...(Number.isSafeInteger(credential.aicode_scope_sign_out_attempted_at) &&
credential.aicode_scope_sign_out_attempted_at > 0
? { aicode_scope_sign_out_attempted_at: credential.aicode_scope_sign_out_attempted_at }
: {}),
},
};
}
export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
async function post(method, data) {
for (const host of CLOUD_CODE_HOSTS) {
export function resolveSetupTierInfo(setup) {
const tierObj = setup?.paidTier || setup?.currentTier || setup?.userTier || null;
if (!tierObj) return null;
const tierId = String(tierObj?.id || '').trim();
const rawName = String(tierObj?.name || '').trim();
const rawDesc = String(tierObj?.description || '').trim();
const tierIdLower = tierId.toLowerCase();
const tierText = `${tierId} ${rawName} ${rawDesc}`;
const tierMultiplier = /(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(tierText)
? '5x'
: /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(tierText) ||
tierIdLower === 'g1-ultra-tier' ||
(/^g1-ultra(?:-[a-z0-9]+)?-tier$/i.test(tierIdLower) && !/lite|5x/i.test(tierIdLower))
? '20x'
: '';
const tierName =
rawName ||
(/ultra/i.test(tierIdLower)
? 'Google AI Ultra'
: /pro/i.test(tierIdLower)
? 'Google AI Pro'
: /free|standard/i.test(tierIdLower)
? 'Google AI Free'
: '');
if (!tierName && !tierId) return null;
return { tierId, tierName: tierName || 'Google AI', tierMultiplier };
}
export async function retrieveCredentialQuota(accessToken, fetchFn = fetchGoogleAccount) {
let preferredHost = '';
async function post(method, data, retryWithoutProject = true) {
const hosts = preferredHost
? [preferredHost, ...CLOUD_CODE_HOSTS.filter((h) => h !== preferredHost)]
: CLOUD_CODE_HOSTS;
for (const host of hosts) {
const response = await fetchFn(`https://${host}/v1internal:${method}`, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500),
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json', 'User-Agent': ACCOUNT_USER_AGENT },
body: JSON.stringify(data),
}).catch(() => null);
if (response?.ok) {
const payload = await response.json().catch(() => null);
if (payload) return payload.response ?? payload;
const result = payload?.response ?? payload;
const valid = method === 'loadCodeAssist' ? result && typeof result === 'object' :
method === 'fetchAvailableModels' ? result?.models && typeof result.models === 'object' :
Array.isArray(result?.groups) || Array.isArray(result?.quotaSummary?.groups) || Array.isArray(result?.buckets);
if (valid) {
preferredHost = host;
return result;
}
}
if (response?.status === 401 || response?.status === 403) break;
if (response?.status === 401) throw new Error('credentialRejected');
if (response?.status === 403 && data.project && retryWithoutProject) return post(method, {}, false);
}
return null;
}
@@ -141,9 +512,8 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } });
const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject;
if (!setup) throw new Error('quotaUnavailable');
const request = {
project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise',
};
const tierInfo = resolveSetupTierInfo(setup);
const request = typeof project === 'string' && project ? { project } : {};
const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs;
const [summary, available] = await Promise.all([
post('retrieveUserQuotaSummary', request),
@@ -167,7 +537,7 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
buckets: adaptBuckets(raw?.buckets),
};
const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs);
return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
const pools = Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
poolKey: pool.poolKey,
poolLabel: pool.poolLabel,
remainingPct: pool.remainingPct,
@@ -175,4 +545,9 @@ export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
resetTime: pool.resetTime,
weeklyResetTime: pool.weeklyResetTime,
}));
if (tierInfo) {
Object.defineProperty(pools, 'tierInfo', { value: tierInfo, enumerable: false });
Object.defineProperty(pools, 'tierName', { value: tierInfo.tierName, enumerable: false });
}
return pools;
}
@@ -0,0 +1,477 @@
/**
* @fileoverview Compact, collinear-compressed per-account quota history store
* (`account-quota-history.mjs`).
*
* Records 5-hour and weekly remaining-percentage trajectories across quota pools
* for the active host account (from live telemetry) and saved backup accounts
* (from scheduled OAuth refreshes). Bootstraps initial history from existing
* `quota_reservation_state.json` observations when available.
*/
import { parseIsoMs } from '../trajectory-metrics.mjs';
import {
ACCOUNT_QUOTA_HISTORY_FILE,
QUOTA_RESERVATION_STATE_FILE,
loadJson,
lsRuntimeEndpoint,
saveJson,
} from './config.mjs';
const AQH_SCHEMA_VERSION = 1;
const AQH_MAX_ACCOUNTS = 32;
const AQH_MAX_POOLS_PER_ACCOUNT = 8;
const AQH_MAX_POINTS_PER_POOL = 1600;
const AQH_PERSIST_MIN_INTERVAL_MS = 5000;
const AQH_CHANGE_EPSILON_PCT = 0.05;
const AQH_MAX_FLAT_MERGE_GAP_MS = 6 * 3600 * 1000;
function aqhClampPct(val) {
if (val === null || val === undefined || val === '') return null;
const num = Number(val);
if (!Number.isFinite(num)) return null;
return Math.round(Math.max(0, Math.min(100, num)) * 10) / 10;
}
function aqhNormEmail(raw) {
return typeof raw === 'string' ? raw.trim().toLowerCase() : '';
}
function aqhSameVal(a, b) {
if (a === null && b === null) return true;
if (a === null || b === null) return false;
return Math.abs(a - b) < AQH_CHANGE_EPSILON_PCT;
}
const AQH_IMPULSE_MAX_SPAN_MS = 20 * 60_000;
const AQH_IMPULSE_MIN_JUMP_PCT = 3;
const AQH_IMPULSE_MAX_NEIGHBOR_DIFF_PCT = 1.2;
function aqhIsIsolatedUpwardImpulse(prevVal, curVal, nextVal) {
if (prevVal === null || curVal === null || nextVal === null) return false;
return (
curVal - prevVal >= AQH_IMPULSE_MIN_JUMP_PCT &&
curVal - nextVal >= AQH_IMPULSE_MIN_JUMP_PCT &&
Math.abs(nextVal - prevVal) <= AQH_IMPULSE_MAX_NEIGHBOR_DIFF_PCT
);
}
/**
* Removes isolated single-sample upward spikes (e.g. cross-account `init` seed events
* where remaining % momentarily jumps `94.8 -> 100 -> 94.7` within minutes and snaps
* right back to the pre-spike trajectory).
*/
export function sanitizeQuotaHistoryPoints(points) {
if (!Array.isArray(points) || points.length < 3) return false;
let removed = false;
let i = 1;
while (i < points.length - 1) {
const prev = points[i - 1];
const cur = points[i];
const next = points[i + 1];
const spanMs = next[0] - prev[0];
if (
spanMs >= 0 &&
spanMs <= AQH_IMPULSE_MAX_SPAN_MS &&
(aqhIsIsolatedUpwardImpulse(prev[1], cur[1], next[1]) ||
aqhIsIsolatedUpwardImpulse(prev[2], cur[2], next[2]))
) {
points.splice(i, 1);
removed = true;
if (i > 1) i -= 1;
continue;
}
i += 1;
}
return removed;
}
function aqhDownsamplePoints(points, targetLen) {
if (points.length <= targetLen) return points;
const keepRecent = Math.floor(targetLen * 0.65);
const oldEnd = points.length - keepRecent;
const oldQuota = Math.max(2, targetLen - keepRecent);
const stride = Math.max(2, Math.ceil(oldEnd / oldQuota));
const compacted = [];
for (let i = 0; i < oldEnd; i += stride) {
const sliceEnd = Math.min(oldEnd, i + stride);
let minPt = points[i];
let maxPt = points[i];
for (let j = i + 1; j < sliceEnd; j++) {
const p = points[j];
const v = p[1] ?? p[2] ?? 100;
if (v < (minPt[1] ?? minPt[2] ?? 100)) minPt = p;
if (v > (maxPt[1] ?? maxPt[2] ?? 0)) maxPt = p;
}
if (minPt === maxPt) {
compacted.push(minPt);
} else if (minPt[0] <= maxPt[0]) {
compacted.push(minPt, maxPt);
} else {
compacted.push(maxPt, minPt);
}
}
for (let i = oldEnd; i < points.length; i++) {
compacted.push(points[i]);
}
return compacted;
}
function aqhAppendPoint(points, tsMs, r5h, rWk) {
const len = points.length;
if (len === 0) {
points.push([tsMs, r5h, rWk]);
return true;
}
const last = points[len - 1];
if (tsMs < last[0]) {
return false;
}
const resolved5h = r5h !== null ? r5h : last[1];
const resolvedWk = rWk !== null ? rWk : last[2];
if (tsMs === last[0]) {
if (!aqhSameVal(last[1], resolved5h) || !aqhSameVal(last[2], resolvedWk)) {
last[1] = resolved5h;
last[2] = resolvedWk;
return true;
}
return false;
}
const unchanged = aqhSameVal(last[1], resolved5h) && aqhSameVal(last[2], resolvedWk);
if (unchanged && len >= 2) {
const prev = points[len - 2];
const prevSame = aqhSameVal(prev[1], resolved5h) && aqhSameVal(prev[2], resolvedWk);
if (prevSame && tsMs - prev[0] <= AQH_MAX_FLAT_MERGE_GAP_MS) {
// Collinear flat segment: advance trailing endpoint timestamp in place
if (tsMs - last[0] < 60_000) return false;
last[0] = tsMs;
return true;
}
}
if (unchanged && tsMs - last[0] < 10 * 60_000) {
return false;
}
points.push([tsMs, resolved5h, resolvedWk]);
if (points.length > AQH_MAX_POINTS_PER_POOL) {
const trimmed = aqhDownsamplePoints(points, Math.floor(AQH_MAX_POINTS_PER_POOL * 0.8));
points.length = 0;
for (let i = 0; i < trimmed.length; i++) points.push(trimmed[i]);
}
return true;
}
export function createAccountQuotaHistoryTracker({
loadState = () => null,
saveState = () => {},
loadSeedEvents = () => null,
} = {}) {
const accountsMap = new Map();
let latestHostEmail = '';
let hydrated = false;
let seededFromQr = false;
let lastPersistMs = 0;
let dirty = false;
function ensureAccountEntry(email, nowMs) {
let acc = accountsMap.get(email);
if (acc) {
acc.updatedAtMs = nowMs;
return acc;
}
if (accountsMap.size >= AQH_MAX_ACCOUNTS) {
let oldestEmail = null;
let oldestTs = Infinity;
for (const [k, v] of accountsMap.entries()) {
if ((v.updatedAtMs || 0) < oldestTs) {
oldestTs = v.updatedAtMs || 0;
oldestEmail = k;
}
}
if (oldestEmail) accountsMap.delete(oldestEmail);
}
acc = { updatedAtMs: nowMs, pools: new Map() };
accountsMap.set(email, acc);
return acc;
}
function hydrate() {
if (hydrated) return;
hydrated = true;
try {
const raw = loadState();
if (raw && typeof raw === 'object' && raw.accounts && typeof raw.accounts === 'object') {
seededFromQr = Boolean(raw.seededFromQr);
for (const [rawEmail, accVal] of Object.entries(raw.accounts)) {
const email = aqhNormEmail(rawEmail);
if (!email || !accVal || typeof accVal !== 'object') continue;
const poolsMap = new Map();
for (const [pk, pVal] of Object.entries(accVal.pools || {})) {
if (!pk || !pVal || !Array.isArray(pVal.points)) continue;
const cleanPts = [];
for (let i = 0; i < pVal.points.length; i++) {
const pt = pVal.points[i];
if (!Array.isArray(pt) || !(Number(pt[0]) > 0)) continue;
const r5 = aqhClampPct(pt[1]);
const rw = aqhClampPct(pt[2]);
if (r5 === null && rw === null) continue;
cleanPts.push([Math.floor(Number(pt[0])), r5, rw]);
}
if (cleanPts.length > 0) {
if (sanitizeQuotaHistoryPoints(cleanPts)) {
dirty = true;
}
poolsMap.set(pk, {
label: String(pVal.label || pk),
reset5hMs: Number(pVal.reset5hMs) > 0 ? Math.floor(Number(pVal.reset5hMs)) : 0,
resetWeeklyMs:
Number(pVal.resetWeeklyMs) > 0 ? Math.floor(Number(pVal.resetWeeklyMs)) : 0,
points: cleanPts.slice(-AQH_MAX_POINTS_PER_POOL),
});
}
}
if (poolsMap.size > 0) {
accountsMap.set(email, {
updatedAtMs: Number(accVal.updatedAtMs) || Date.now(),
pools: poolsMap,
});
}
}
}
} catch {
// Ignore corrupt history file and start fresh
}
}
function seedFromReservationEventsIfEmpty(activeEmail) {
if (seededFromQr || !activeEmail) return;
const existing = accountsMap.get(activeEmail);
if (existing && existing.pools.size > 0) {
seededFromQr = true;
return;
}
seededFromQr = true;
try {
const qr = loadSeedEvents();
const events = Array.isArray(qr?.events) ? qr.events : [];
if (events.length === 0) return;
const acc = ensureAccountEntry(activeEmail, Date.now());
for (let i = 0; i < events.length; i++) {
const ev = events[i];
const pk = String(ev?.pool || '').trim();
const win = String(ev?.win || '').trim();
const tsMs = parseIsoMs(ev?.ts);
const used = Number(ev?.usedPct);
if (!pk || !(tsMs > 0) || !Number.isFinite(used)) continue;
const rem = aqhClampPct(100 - used);
if (rem === null) continue;
let poolEntry = acc.pools.get(pk);
if (!poolEntry) {
if (acc.pools.size >= AQH_MAX_POOLS_PER_ACCOUNT) continue;
poolEntry = { label: pk, reset5hMs: 0, resetWeeklyMs: 0, points: [] };
acc.pools.set(pk, poolEntry);
}
if (ev?.event === 'init' && poolEntry.points.length > 0) {
const lastPt = poolEntry.points[poolEntry.points.length - 1];
const prevVal = win === 'weekly' ? lastPt[2] : lastPt[1];
if (prevVal !== null && rem - prevVal >= AQH_IMPULSE_MIN_JUMP_PCT) {
continue;
}
}
aqhAppendPoint(
poolEntry.points,
tsMs,
win === '5h' ? rem : null,
win === 'weekly' ? rem : null
);
dirty = true;
}
for (const poolEntry of acc.pools.values()) {
sanitizeQuotaHistoryPoints(poolEntry.points);
}
} catch {
// Optional seed is best-effort
}
}
function persistIfNeeded(nowMs, force = false) {
if (!dirty) return;
if (!force && lastPersistMs > 0 && nowMs - lastPersistMs < AQH_PERSIST_MIN_INTERVAL_MS) {
return;
}
lastPersistMs = nowMs;
dirty = false;
const serializedAccounts = {};
for (const [email, acc] of accountsMap.entries()) {
const poolsObj = {};
for (const [pk, pVal] of acc.pools.entries()) {
if (!pVal.points.length) continue;
poolsObj[pk] = {
label: pVal.label,
...(pVal.reset5hMs > 0 ? { reset5hMs: pVal.reset5hMs } : {}),
...(pVal.resetWeeklyMs > 0 ? { resetWeeklyMs: pVal.resetWeeklyMs } : {}),
points: pVal.points,
};
}
if (Object.keys(poolsObj).length > 0) {
serializedAccounts[email] = {
updatedAtMs: acc.updatedAtMs,
pools: poolsObj,
};
}
}
try {
saveState({
schemaVersion: AQH_SCHEMA_VERSION,
seededFromQr,
updatedAt: new Date(nowMs).toISOString(),
accounts: serializedAccounts,
});
} catch {
// Best-effort persistence
}
}
function recordSnapshot(rawEmail, pools, nowMs = Date.now(), { isActiveHost = false } = {}) {
const email = aqhNormEmail(rawEmail);
if (!email || !Array.isArray(pools) || pools.length === 0) return;
hydrate();
if (isActiveHost) {
latestHostEmail = email;
seedFromReservationEventsIfEmpty(email);
}
const tsMs = Number.isFinite(Number(nowMs)) && Number(nowMs) > 0 ? Math.floor(Number(nowMs)) : Date.now();
const acc = ensureAccountEntry(email, tsMs);
let anyChanged = false;
for (let i = 0; i < pools.length; i++) {
const p = pools[i];
const pk = String(p?.poolKey || p?.family || p?.poolLabel || '').trim();
if (!pk || pk === 'Unknown') continue;
const r5h = aqhClampPct(p?.remainingPct ?? p?.remaining5hPct);
const rWk = aqhClampPct(p?.weeklyRemainingPct ?? p?.remainingWeeklyPct);
if (r5h === null && rWk === null) continue;
let poolEntry = acc.pools.get(pk);
if (!poolEntry) {
if (acc.pools.size >= AQH_MAX_POOLS_PER_ACCOUNT) continue;
poolEntry = {
label: String(p?.poolLabel || pk),
reset5hMs: 0,
resetWeeklyMs: 0,
points: [],
};
acc.pools.set(pk, poolEntry);
}
if (p?.poolLabel) poolEntry.label = String(p.poolLabel);
const nextReset5h = parseIsoMs(p?.resetTime || p?.reset5h);
const nextResetWk = parseIsoMs(p?.weeklyResetTime || p?.resetWeekly);
if (nextReset5h > 0 && nextReset5h !== poolEntry.reset5hMs) {
poolEntry.reset5hMs = nextReset5h;
anyChanged = true;
}
if (nextResetWk > 0 && nextResetWk !== poolEntry.resetWeeklyMs) {
poolEntry.resetWeeklyMs = nextResetWk;
anyChanged = true;
}
if (aqhAppendPoint(poolEntry.points, tsMs, r5h, rWk)) {
anyChanged = true;
}
}
if (anyChanged) {
dirty = true;
persistIfNeeded(tsMs, false);
}
}
function removeAccount(rawEmail, nowMs = Date.now()) {
const email = aqhNormEmail(rawEmail);
if (!email) return;
hydrate();
if (accountsMap.delete(email)) {
dirty = true;
persistIfNeeded(nowMs, true);
}
}
function getHistoryPayload({ allowedEmails = null } = {}) {
hydrate();
const allowSet = Array.isArray(allowedEmails)
? new Set(allowedEmails.map(aqhNormEmail).filter(Boolean))
: null;
const out = {};
for (const [email, acc] of accountsMap.entries()) {
if (allowSet && !allowSet.has(email)) continue;
const poolsObj = {};
for (const [pk, pVal] of acc.pools.entries()) {
if (!pVal.points.length) continue;
poolsObj[pk] = {
label: pVal.label,
...(pVal.reset5hMs > 0 ? { reset5hMs: pVal.reset5hMs } : {}),
...(pVal.resetWeeklyMs > 0 ? { resetWeeklyMs: pVal.resetWeeklyMs } : {}),
points: pVal.points,
};
}
if (Object.keys(poolsObj).length > 0) {
out[email] = { pools: poolsObj };
}
}
return out;
}
function reset() {
accountsMap.clear();
latestHostEmail = '';
hydrated = true;
seededFromQr = false;
lastPersistMs = 0;
dirty = false;
}
return {
recordSnapshot,
removeAccount,
getHistoryPayload,
getLatestHostEmail: () => latestHostEmail,
flush: (nowMs = Date.now()) => persistIfNeeded(nowMs, true),
reset,
};
}
function aqhIsTestRuntime() {
return (
lsRuntimeEndpoint?.addr === 'test.invalid' ||
String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid'
);
}
const defaultAccountQuotaHistoryTracker = createAccountQuotaHistoryTracker({
loadState: () => (aqhIsTestRuntime() ? null : loadJson(ACCOUNT_QUOTA_HISTORY_FILE, null)),
saveState: (payload) => {
if (!aqhIsTestRuntime()) saveJson(ACCOUNT_QUOTA_HISTORY_FILE, payload);
},
loadSeedEvents: () => (aqhIsTestRuntime() ? null : loadJson(QUOTA_RESERVATION_STATE_FILE, null)),
});
export function recordAccountQuotaSnapshot(email, pools, nowMs = Date.now(), opts = {}) {
defaultAccountQuotaHistoryTracker.recordSnapshot(email, pools, nowMs, opts);
}
export function removeAccountQuotaHistory(email, nowMs = Date.now()) {
defaultAccountQuotaHistoryTracker.removeAccount(email, nowMs);
}
export function getAccountQuotaHistoryPayload(opts = {}) {
return defaultAccountQuotaHistoryTracker.getHistoryPayload(opts);
}
export function getLatestRecordedHostEmail() {
return defaultAccountQuotaHistoryTracker.getLatestHostEmail();
}
export function flushAccountQuotaHistoryNow(nowMs = Date.now()) {
defaultAccountQuotaHistoryTracker.flush(nowMs);
}
export function resetAccountQuotaHistoryState() {
defaultAccountQuotaHistoryTracker.reset();
}
+753 -59
View File
@@ -1,11 +1,35 @@
/** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */
import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { statSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs';
import { accountLoginController } from './account-login.mjs';
import {
isAllowedOAuthClientId,
loadNativeOAuthClients,
resolveGoogleCredential,
retrieveCredentialQuota,
} from './account-oauth.mjs';
import {
recordAccountQuotaSnapshot,
removeAccountQuotaHistory,
} from './account-quota-history.mjs';
import {
checkVaultUnlockCooldown,
createVaultSecurityMetadata,
decryptVaultEntryCredential,
encryptVaultEntryCredential,
getUnlockedVaultSessionKey,
isEncryptedVaultCredential,
isVaultSessionUnlocked,
lockVaultSession,
normalizeVaultPassword,
recordVaultUnlockFailure,
resetVaultUnlockFailures,
setUnlockedVaultSessionKey,
verifyVaultPassword,
} from './account-vault-crypto.mjs';
import { HERE } from './config.mjs';
import { callLsRpc } from './ls-rpc.mjs';
@@ -14,33 +38,113 @@ const ACCOUNT_ERRORS = new Set([
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
'oauthUnavailable', 'quotaUnavailable',
'switchStartFailed', 'clientCloseFailed', 'clientRestartFailed',
'vaultLocked', 'wrongPassword', 'invalidPassword', 'passwordRateLimited',
'vaultDecryptFailed', 'invalidActionNonce', 'riskNotAccepted',
]);
const ALLOWED_ACTIONS = new Set([
'list', 'save', 'capture', 'switch', 'remove', 'quota',
'loginStart', 'loginStatus', 'loginCancel',
'setPassword', 'unlockVault', 'lockVault', 'changePassword', 'disablePassword', 'resetVault',
]);
const MAX_TRANSIENT_TOKENS = 32;
const transientAccessTokens = new Map();
const vaultSecurityByPath = new Map();
export function clearAccountVaultRuntimeState() {
lockVaultSession();
resetVaultUnlockFailures();
transientAccessTokens.clear();
vaultSecurityByPath.clear();
}
function rememberTransientAccessToken(email, credential) {
const addr = normalizeAccountEmail(email);
const tok = credential?.token;
if (!addr || !tok?.access_token || !tok?.refresh_token) return;
const expiryMs = Date.parse(tok.expiry || '');
if (!Number.isFinite(expiryMs) || expiryMs <= Date.now() + 60_000) return;
if (!transientAccessTokens.has(addr) && transientAccessTokens.size >= MAX_TRANSIENT_TOKENS) {
const oldestKey = transientAccessTokens.keys().next().value;
if (oldestKey !== undefined) transientAccessTokens.delete(oldestKey);
}
transientAccessTokens.set(addr, {
refreshToken: tok.refresh_token,
accessToken: tok.access_token,
expiry: tok.expiry,
...(typeof credential.id_token === 'string' && credential.id_token
? { idToken: credential.id_token }
: {}),
});
}
function clearTransientAccessTokens(email = '') {
if (email) {
transientAccessTokens.delete(normalizeAccountEmail(email));
return;
}
transientAccessTokens.clear();
}
export function normalizeAccountEmail(value) {
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : '';
}
export function normalizeAccountCredential(input) {
export function normalizeAccountCredential(input, { allowedClientIds = null } = {}) {
if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null;
const text = input.trim();
let source;
try { source = JSON.parse(text); } catch {
try {
source = JSON.parse(text);
} catch {
if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null;
source = { refresh_token: text };
}
if (!source || typeof source !== 'object' || Array.isArray(source)) return null;
if (
source.type !== undefined &&
!['authorized_user', 'oauth2'].includes(String(source.type).trim().toLowerCase())
) {
return null;
}
const explicitClientId =
source.client_id ??
source.token?.client_id ??
source.installed?.client_id ??
source.web?.client_id;
if (explicitClientId !== undefined && explicitClientId !== null && String(explicitClientId).trim() !== '') {
if (
typeof explicitClientId !== 'string' ||
!isAllowedOAuthClientId(explicitClientId, allowedClientIds)
) {
return null;
}
}
const token = source?.token || source;
if (!token || (source.auth_method && source.auth_method !== 'consumer') ||
typeof token.refresh_token !== 'string' || !token.refresh_token.trim() ||
/\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null;
const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000);
const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z');
if (
!token ||
(source.auth_method && source.auth_method !== 'consumer') ||
typeof token.refresh_token !== 'string' ||
!token.refresh_token.trim() ||
/\s/.test(token.refresh_token) ||
(token.token_type && !/^bearer$/i.test(token.token_type))
) {
return null;
}
const timestamp = token.expiry_date ?? Number(token.expiry_timestamp) * 1000;
const expiry =
token.expiry ||
(Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
? new Date(timestamp).toISOString()
: '1970-01-01T00:00:00Z');
if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null;
const payload = {
token: {
access_token: typeof token.access_token === 'string' ? token.access_token : '',
refresh_token: token.refresh_token,
refresh_token: token.refresh_token.trim(),
token_type: 'Bearer',
expiry: new Date(expiry).toISOString(),
},
@@ -48,125 +152,715 @@ export function normalizeAccountCredential(input) {
};
const idToken = source.id_token || token.id_token;
if (typeof idToken === 'string' && idToken) payload.id_token = idToken;
if (
Number.isSafeInteger(source.aicode_scope_sign_out_attempted_at) &&
source.aicode_scope_sign_out_attempted_at > 0
) {
payload.aicode_scope_sign_out_attempted_at = source.aicode_scope_sign_out_attempted_at;
}
return JSON.stringify(payload);
}
/**
* At-rest minimization: strips short-lived `access_token`, `id_token`, `expiry`,
* and any extra fields before persisting to `accounts.dpapi`.
*/
export function serializeVaultCredential(credential) {
const refreshToken = String(credential?.token?.refresh_token || '').trim();
if (!refreshToken || /\s/.test(refreshToken)) {
throw new Error('invalidCredential');
}
return JSON.stringify({
token: { refresh_token: refreshToken, token_type: 'Bearer' },
auth_method: 'consumer',
});
}
export function runWindowsCredentialStore(request) {
const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8');
const encoded = Buffer.from(script, 'utf16le').toString('base64');
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
const scriptPath = join(HERE, 'backend', 'account-credentials.ps1');
const shell = join(
process.env.SystemRoot || 'C:/Windows',
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe'
);
return new Promise((resolve, reject) => {
// The helper exchanges private data over its pipes, keeping it out of process arguments.
const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
const child = spawn(
shell,
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
{ windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] }
);
let output = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => { output += chunk; });
child.stdout.on('data', (chunk) => {
output += chunk;
});
child.on('error', reject);
child.stdin.on('error', reject);
child.on('close', (code) => {
if (code !== 0) return reject(new Error('storeFailed'));
try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); }
try {
resolve(JSON.parse(output.replace(/^\uFEFF/, '')));
} catch {
reject(new Error('storeFailed'));
}
});
child.stdin.end(JSON.stringify(request), 'utf8');
});
}
function serializeHostCredential(credential) {
let payload = JSON.stringify(credential);
if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) {
const { id_token, ...compact } = credential;
function serializeHostCredential(credential, { forHostSwitch = false } = {}) {
const target =
forHostSwitch && !credential.aicode_scope_sign_out_attempted_at
? { ...credential, aicode_scope_sign_out_attempted_at: Math.floor(Date.now() / 1000) }
: credential;
let payload = JSON.stringify(target);
if (Buffer.byteLength(payload, 'utf8') > 2560 && target.id_token) {
const { id_token: _ignored, ...compact } = target;
payload = JSON.stringify(compact);
}
if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge');
return payload;
}
async function confirmHostCredential(email, rpc) {
for (let attempt = 0; attempt < 3; attempt += 1) {
await rpc('GetAuthStatus', {}, 1200).catch(() => null);
const status = await rpc('GetUserStatus', {}, 1200).catch(() => null);
if (normalizeAccountEmail(status?.userStatus?.email) === email) return true;
if (attempt < 2) await delay(300);
let cachedPublicVaultState = null;
let cachedPublicVaultSig = '';
function computePublicVaultDiskSig(config) {
try {
const vStat = statSync(config.vault, { throwIfNoEntry: false });
const sStat = config.statusFile ? statSync(config.statusFile, { throwIfNoEntry: false }) : null;
return `${config.vault}|${vStat ? `${vStat.size}:${vStat.mtimeMs}` : '0'}|${sStat ? `${sStat.size}:${sStat.mtimeMs}` : '0'}`;
} catch {
return '';
}
return false;
}
export async function handleAccountCredentialAction(data, {
platform = process.platform,
store = runWindowsCredentialStore,
rpc = callLsRpc,
resolveCredential = resolveGoogleCredential,
getQuota = retrieveCredentialQuota,
} = {}) {
function recordKnownVaultSecurity(vaultPath, security) {
if (!vaultPath) return;
if (security?.enabled) {
vaultSecurityByPath.set(vaultPath, { enabled: true, salt: String(security.salt || '') });
} else {
vaultSecurityByPath.delete(vaultPath);
}
}
function cacheSanitizedVaultState(config, result) {
const sig = computePublicVaultDiskSig(config);
if (!sig || !result || !Array.isArray(result.accounts)) return;
cachedPublicVaultSig = sig;
cachedPublicVaultState = {
accounts: [...result.accounts],
selectedEmail: result.selectedEmail || '',
quotas: result.quotas ? { ...result.quotas } : {},
...(result.security?.enabled
? { security: { enabled: true, salt: String(result.security.salt || '') } }
: {}),
...(result.switchState ? { switchState: { ...result.switchState } } : {}),
};
}
export async function warmAccountPublicListCache() {
if (process.platform !== 'win32') return;
await handleAccountCredentialAction({ action: 'list' }).catch(() => null);
}
function openStoredVaultCredential(storedRaw, email, vaultSecurity) {
let jsonText = storedRaw;
if (isEncryptedVaultCredential(storedRaw)) {
const keyBuf = getUnlockedVaultSessionKey(vaultSecurity?.salt || '');
if (!keyBuf) throw new Error('vaultLocked');
jsonText = decryptVaultEntryCredential(storedRaw, keyBuf, email);
} else if (vaultSecurity?.enabled && !isVaultSessionUnlocked(vaultSecurity)) {
throw new Error('vaultLocked');
}
const normalized = normalizeAccountCredential(jsonText);
if (!normalized) throw new Error('invalidCredential');
const parsed = JSON.parse(normalized);
if (!parsed.token.access_token) {
const cached = transientAccessTokens.get(normalizeAccountEmail(email));
if (
cached &&
cached.refreshToken === parsed.token.refresh_token &&
Date.parse(cached.expiry) > Date.now() + 60_000
) {
parsed.token.access_token = cached.accessToken;
parsed.token.expiry = cached.expiry;
if (cached.idToken && !parsed.id_token) parsed.id_token = cached.idToken;
}
}
return parsed;
}
function sealVaultCredential(credentialObj, email, vaultSecurity) {
const minJson = serializeVaultCredential(credentialObj);
if (vaultSecurity?.enabled) {
const keyBuf = getUnlockedVaultSessionKey(vaultSecurity.salt);
if (!keyBuf) throw new Error('vaultLocked');
return {
stored: encryptVaultEntryCredential(minJson, keyBuf, email),
vaultUnlocked: true,
expectedSecuritySalt: String(vaultSecurity.salt),
};
}
return { stored: minJson, vaultUnlocked: false, expectedSecuritySalt: '' };
}
export async function handleAccountCredentialAction(
data,
{
platform = process.platform,
store = runWindowsCredentialStore,
rpc = callLsRpc,
resolveCredential = resolveGoogleCredential,
getQuota = retrieveCredentialQuota,
login = accountLoginController,
} = {}
) {
if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' };
const action = data?.action || 'list';
if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' };
if (!ALLOWED_ACTIONS.has(action)) return { error: 'invalidCredential' };
const email = normalizeAccountEmail(data?.email);
if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' };
const gemini = String(process.env.ANTIGRAVITY_GEMINI_DIR || '').trim() || join(homedir(), '.gemini');
const config = {
target: 'gemini:antigravity',
vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'),
fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')],
vault: join(
process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'),
'AntigravityUsageMonitor',
'accounts.dpapi'
),
statusFile: join(
process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'),
'AntigravityUsageMonitor',
'switch-state.json'
),
scriptPath: join(HERE, 'backend', 'account-credentials.ps1'),
fallbacks: [
join(gemini, 'jetski-standalone-oauth-token'),
join(gemini, 'antigravity-cli', 'antigravity-oauth-token'),
],
};
const useDiskSigCache = store === runWindowsCredentialStore;
async function runStore(fields) {
const result = await store({ ...config, ...fields });
if (!result || result.error) throw new Error(result?.error || 'storeFailed');
if (['list', 'read', 'readVault', 'writeVault', 'scheduleSwitch'].includes(fields.action)) {
recordKnownVaultSecurity(config.vault, result.security);
}
if (useDiskSigCache) {
if (fields.action === 'scheduleSwitch') {
cachedPublicVaultState = null;
cachedPublicVaultSig = '';
} else if (['list', 'save', 'remove', 'saveQuota', 'writeVault'].includes(fields.action)) {
cacheSanitizedVaultState(config, result);
}
}
return result;
}
function resolveKnownVaultSecurity() {
if (useDiskSigCache && cachedPublicVaultState) {
return cachedPublicVaultState.security || null;
}
return vaultSecurityByPath.get(config.vault) || null;
}
async function ensureUnlockedVaultContext() {
if (useDiskSigCache && !cachedPublicVaultState) {
await runStore({ action: 'list', email: '' });
}
const sec = resolveKnownVaultSecurity();
if (sec?.enabled && !isVaultSessionUnlocked(sec)) {
throw new Error('vaultLocked');
}
return sec;
}
function publicList(result) {
const rawSwitchState = result.switchState;
const switchAgeMs = rawSwitchState ? Date.now() - Number(rawSwitchState.updatedAt || 0) : Infinity;
const stalled = rawSwitchState?.state === 'starting' && switchAgeMs > 120000;
const expiredSwitchState =
rawSwitchState && rawSwitchState.state !== 'starting' && switchAgeMs > 5 * 60 * 1000;
const switchState = expiredSwitchState ? null : rawSwitchState;
const sec = result.security?.enabled ? result.security : null;
const cooldownSec = checkVaultUnlockCooldown();
return {
supported: true,
accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean),
selectedEmail: normalizeAccountEmail(result.selectedEmail),
accounts: (Array.isArray(result.accounts) ? result.accounts : [])
.map(normalizeAccountEmail)
.filter(Boolean),
selectedEmail: expiredSwitchState ? '' : normalizeAccountEmail(result.selectedEmail),
quotas: result.quotas || {},
...(sec || data?.includeSecurity
? {
security: {
enabled: Boolean(sec?.enabled),
unlocked: isVaultSessionUnlocked(sec),
...(cooldownSec > 0 ? { cooldownSec } : {}),
},
}
: {}),
...(login.getStatus() ? { login: login.getStatus() } : {}),
...(switchState
? {
switchState: {
email: normalizeAccountEmail(switchState.email),
state:
!stalled && ['starting', 'written', 'failed'].includes(switchState.state)
? switchState.state
: 'failed',
error: stalled
? 'switchStartFailed'
: ACCOUNT_ERRORS.has(switchState.error)
? switchState.error
: '',
},
}
: {}),
};
}
async function verifyCredential(raw, refresh = false) {
const normalized = normalizeAccountCredential(raw);
if (!normalized) throw new Error('invalidCredential');
async function verifyCredentialObj(parsedObj, refresh = false) {
let result;
try {
result = await resolveCredential(JSON.parse(normalized), { refresh });
result = await resolveCredential(parsedObj, { refresh });
} catch (error) {
throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable');
}
result.email = normalizeAccountEmail(result.email);
if (!result.email) throw new Error('credentialRejected');
rememberTransientAccessToken(result.email, result.credential);
return result;
}
try {
if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email }));
if (action === 'save') {
const verified = await verifyCredential(data.credential, true);
return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) }));
async function verifyCredential(raw, refresh = false) {
let normalized = normalizeAccountCredential(raw);
if (!normalized && typeof raw === 'string' && raw.includes('client_id')) {
const liveClients = await loadNativeOAuthClients().catch(() => []);
if (liveClients.length > 0) {
normalized = normalizeAccountCredential(raw, {
allowedClientIds: liveClients.map((c) => c.id),
});
}
}
if (!normalized) throw new Error('invalidCredential');
return verifyCredentialObj(JSON.parse(normalized), refresh);
}
try {
if (action === 'list') {
if (useDiskSigCache && cachedPublicVaultState) {
const curSig = computePublicVaultDiskSig(config);
if (curSig && curSig === cachedPublicVaultSig) {
return publicList(cachedPublicVaultState);
}
}
return publicList(await runStore({ action, email }));
}
if (action === 'setPassword') {
const vaultData = await runStore({ action: 'readVault' });
if (vaultData.security?.enabled) throw new Error('credentialChanged');
const { security, keyBuf } = await createVaultSecurityMetadata(
data?.newPassword ?? data?.password
);
try {
const nextEntries = (Array.isArray(vaultData.entries) ? vaultData.entries : []).map((entry) => {
const entryEmail = normalizeAccountEmail(entry?.email);
if (!entryEmail) throw new Error('invalidEmail');
const norm = normalizeAccountCredential(entry.credential);
if (!norm) throw new Error('invalidCredential');
const minJson = serializeVaultCredential(JSON.parse(norm));
return {
...entry,
email: entryEmail,
credential: encryptVaultEntryCredential(minJson, keyBuf, entryEmail),
};
});
const savedVault = await runStore({
action: 'writeVault',
entries: nextEntries,
selectedEmail: vaultData.selectedEmail || '',
security,
});
setUnlockedVaultSessionKey(security.salt, keyBuf);
resetVaultUnlockFailures();
return publicList(savedVault);
} finally {
keyBuf.fill(0);
}
}
if (action === 'unlockVault') {
const cooldownSec = checkVaultUnlockCooldown();
if (cooldownSec > 0) {
return { error: 'passwordRateLimited', retryAfterSec: cooldownSec };
}
const vaultData = await runStore({ action: 'readVault' });
if (!vaultData.security?.enabled) {
return publicList({
accounts: (vaultData.entries || []).map((e) => e.email),
selectedEmail: vaultData.selectedEmail || '',
quotas: Object.fromEntries(
(vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota])
),
});
}
let keyBuf = null;
try {
keyBuf = await verifyVaultPassword(data?.password, vaultData.security);
} catch (err) {
if (err?.message === 'wrongPassword') {
const waitSec = recordVaultUnlockFailure();
return waitSec > 0
? { error: 'passwordRateLimited', retryAfterSec: waitSec }
: { error: 'wrongPassword' };
}
throw err;
}
try {
const firstEnc = (vaultData.entries || []).find((e) =>
isEncryptedVaultCredential(e?.credential)
);
if (firstEnc) {
decryptVaultEntryCredential(firstEnc.credential, keyBuf, firstEnc.email);
}
setUnlockedVaultSessionKey(vaultData.security.salt, keyBuf);
resetVaultUnlockFailures();
return publicList({
accounts: (vaultData.entries || []).map((e) => e.email),
selectedEmail: vaultData.selectedEmail || '',
quotas: Object.fromEntries(
(vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota])
),
security: { enabled: true, salt: vaultData.security.salt },
});
} finally {
keyBuf.fill(0);
}
}
if (action === 'lockVault') {
lockVaultSession();
clearTransientAccessTokens();
const curLogin = login.getStatus();
if (curLogin?.id && curLogin.status === 'waiting') {
login.cancel(curLogin.id);
}
return publicList(await runStore({ action: 'list', email: '' }));
}
if (action === 'changePassword') {
const cooldownSec = checkVaultUnlockCooldown();
if (cooldownSec > 0) {
return { error: 'passwordRateLimited', retryAfterSec: cooldownSec };
}
if (!normalizeVaultPassword(data?.newPassword)) {
throw new Error('invalidPassword');
}
const vaultData = await runStore({ action: 'readVault' });
if (!vaultData.security?.enabled) throw new Error('notFound');
let oldKeyBuf = null;
try {
oldKeyBuf = await verifyVaultPassword(data?.currentPassword, vaultData.security);
} catch (err) {
if (err?.message === 'wrongPassword') {
const waitSec = recordVaultUnlockFailure();
return waitSec > 0
? { error: 'passwordRateLimited', retryAfterSec: waitSec }
: { error: 'wrongPassword' };
}
throw err;
}
resetVaultUnlockFailures();
let newKeyBuf = null;
try {
const created = await createVaultSecurityMetadata(data.newPassword);
newKeyBuf = created.keyBuf;
const nextEntries = (vaultData.entries || []).map((entry) => {
const entryEmail = normalizeAccountEmail(entry?.email);
if (!entryEmail) throw new Error('invalidEmail');
const plainJson = isEncryptedVaultCredential(entry.credential)
? decryptVaultEntryCredential(entry.credential, oldKeyBuf, entryEmail)
: entry.credential;
const norm = normalizeAccountCredential(plainJson);
if (!norm) throw new Error('invalidCredential');
const minJson = serializeVaultCredential(JSON.parse(norm));
return {
...entry,
email: entryEmail,
credential: encryptVaultEntryCredential(minJson, newKeyBuf, entryEmail),
};
});
const savedVault = await runStore({
action: 'writeVault',
entries: nextEntries,
selectedEmail: vaultData.selectedEmail || '',
security: created.security,
});
clearTransientAccessTokens();
setUnlockedVaultSessionKey(created.security.salt, newKeyBuf);
return publicList(savedVault);
} finally {
oldKeyBuf?.fill(0);
newKeyBuf?.fill(0);
}
}
if (action === 'disablePassword') {
const cooldownSec = checkVaultUnlockCooldown();
if (cooldownSec > 0) {
return { error: 'passwordRateLimited', retryAfterSec: cooldownSec };
}
const vaultData = await runStore({ action: 'readVault' });
if (!vaultData.security?.enabled) {
return publicList({
accounts: (vaultData.entries || []).map((e) => e.email),
selectedEmail: vaultData.selectedEmail || '',
quotas: Object.fromEntries(
(vaultData.entries || []).filter((e) => e?.quota).map((e) => [e.email, e.quota])
),
});
}
let oldKeyBuf = null;
try {
oldKeyBuf = await verifyVaultPassword(data?.currentPassword, vaultData.security);
} catch (err) {
if (err?.message === 'wrongPassword') {
const waitSec = recordVaultUnlockFailure();
return waitSec > 0
? { error: 'passwordRateLimited', retryAfterSec: waitSec }
: { error: 'wrongPassword' };
}
throw err;
}
resetVaultUnlockFailures();
try {
const plainEntries = (vaultData.entries || []).map((entry) => {
const entryEmail = normalizeAccountEmail(entry?.email);
if (!entryEmail) throw new Error('invalidEmail');
const plainJson = isEncryptedVaultCredential(entry.credential)
? decryptVaultEntryCredential(entry.credential, oldKeyBuf, entryEmail)
: entry.credential;
const norm = normalizeAccountCredential(plainJson);
if (!norm) throw new Error('invalidCredential');
return {
...entry,
email: entryEmail,
credential: serializeVaultCredential(JSON.parse(norm)),
};
});
const savedVault = await runStore({
action: 'writeVault',
entries: plainEntries,
selectedEmail: vaultData.selectedEmail || '',
security: null,
});
lockVaultSession();
clearTransientAccessTokens();
return publicList(savedVault);
} finally {
oldKeyBuf?.fill(0);
}
}
if (action === 'resetVault') {
if (data?.confirmReset !== 'RESET') throw new Error('invalidCredential');
lockVaultSession();
clearTransientAccessTokens();
resetVaultUnlockFailures();
const curLogin = login.getStatus();
if (curLogin?.id && curLogin.status === 'waiting') {
login.cancel(curLogin.id);
}
const savedVault = await runStore({
action: 'writeVault',
entries: [],
selectedEmail: '',
security: null,
clearStatus: true,
});
return publicList(savedVault);
}
if (action === 'loginStart') {
await ensureUnlockedVaultContext();
const session = await login.start(async (verified) => {
const address = normalizeAccountEmail(verified.email);
if (!address) throw new Error('credentialRejected');
rememberTransientAccessToken(address, verified.credential);
const activeSec = await ensureUnlockedVaultContext();
const sealed = sealVaultCredential(verified.credential, address, activeSec);
await runStore({
action: 'save',
email: address,
credential: sealed.stored,
...(sealed.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt }
: {}),
});
}, data.language);
return { supported: true, login: session };
}
if (action === 'loginStatus' || action === 'loginCancel') {
const session = action === 'loginCancel' ? login.cancel(data.id) : login.getStatus(data.id);
return {
supported: true,
login: session || { id: data.id, status: 'expired', error: 'loginExpired' },
};
}
if (action === 'remove') {
const activeSec = await ensureUnlockedVaultContext();
clearTransientAccessTokens(email);
removeAccountQuotaHistory(email);
return publicList(
await runStore({
action,
email,
...(activeSec?.enabled
? { vaultUnlocked: true, expectedSecuritySalt: String(activeSec.salt) }
: {}),
})
);
}
if (action === 'save') {
const activeSec = await ensureUnlockedVaultContext();
const verified = await verifyCredential(data.credential, true);
const sealed = sealVaultCredential(verified.credential, verified.email, activeSec);
return publicList(
await runStore({
action,
email: verified.email,
credential: sealed.stored,
...(sealed.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt }
: {}),
})
);
}
if (action === 'capture') {
const activeSec = await ensureUnlockedVaultContext();
const status = await rpc('GetUserStatus', {}, 2000).catch(() => null);
const activeEmail = normalizeAccountEmail(status?.userStatus?.email);
if (!activeEmail) throw new Error('noCurrentCredential');
const { credential } = await runStore({ action: 'readCurrent' });
const verified = await verifyCredential(credential);
if (verified.email !== activeEmail) throw new Error('identityMismatch');
return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) }));
const sealed = sealVaultCredential(verified.credential, activeEmail, activeSec);
return publicList(
await runStore({
action: 'save',
email: activeEmail,
credential: sealed.stored,
...(sealed.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealed.expectedSecuritySalt }
: {}),
})
);
}
const saved = await runStore({ action: 'read', email });
const verified = await verifyCredential(saved.credential);
const entrySec = saved.security || resolveKnownVaultSecurity();
const openedObj = openStoredVaultCredential(saved.credential, email, entrySec);
const verified = await verifyCredentialObj(openedObj);
if (verified.email !== email) throw new Error('identityMismatch');
const credential = serializeHostCredential(verified.credential);
const sealedCurrent = sealVaultCredential(verified.credential, email, entrySec);
if (action === 'quota') {
if (credential !== saved.credential) {
await runStore({ action: 'save', email, credential, expectedCredential: saved.credential });
const tokenRotated =
verified.credential.token.refresh_token !== openedObj.token.refresh_token;
const legacyUnminimized =
useDiskSigCache && !entrySec?.enabled && saved.credential !== sealedCurrent.stored;
let expectedCredForQuota = saved.credential;
if (tokenRotated || legacyUnminimized) {
await runStore({
action: 'save',
email,
credential: sealedCurrent.stored,
expectedCredential: saved.credential,
...(sealedCurrent.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealedCurrent.expectedSecuritySalt }
: {}),
});
expectedCredForQuota = sealedCurrent.stored;
}
const pools = await getQuota(verified.credential.token.access_token);
return { email, pools };
const tierInfo = pools?.tierInfo || null;
const tierName = tierInfo?.tierName || (typeof pools?.tierName === 'string' ? pools.tierName : '');
const tierMeta = {
...(tierInfo?.tierId ? { tierId: tierInfo.tierId } : {}),
...(tierName ? { tierName } : {}),
...(tierInfo?.tierMultiplier ? { tierMultiplier: tierInfo.tierMultiplier } : {}),
};
const fetchedAt = Date.now();
const quotaPayload = { pools, fetchedAt, ...tierMeta };
await runStore({
action: 'saveQuota',
email,
expectedCredential: expectedCredForQuota,
quota: quotaPayload,
});
if (useDiskSigCache) {
recordAccountQuotaSnapshot(email, pools, fetchedAt, { isActiveHost: false });
}
return { email, pools, fetchedAt, ...tierMeta };
}
const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential });
const confirmed = await confirmHostCredential(email, rpc);
return { ...publicList(updated), confirmed };
const prevActiveEmail = normalizeAccountEmail(data?.activeEmail);
if (prevActiveEmail && prevActiveEmail !== email) {
try {
const existingPrev = await store({ ...config, action: 'read', email: prevActiveEmail });
if (!existingPrev || existingPrev.error === 'notFound') {
const currentHost = await store({ ...config, action: 'readCurrent' });
if (currentHost?.credential) {
const verifiedPrev = await verifyCredential(currentHost.credential);
if (verifiedPrev.email === prevActiveEmail) {
const sealedPrev = sealVaultCredential(
verifiedPrev.credential,
prevActiveEmail,
entrySec
);
await runStore({
action: 'save',
email: prevActiveEmail,
credential: sealedPrev.stored,
...(sealedPrev.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealedPrev.expectedSecuritySalt }
: {}),
});
}
}
}
} catch {
// Best-effort backup of active host login before switching away
}
}
const hostSwitchCredential = serializeHostCredential(verified.credential, {
forHostSwitch: true,
});
const updated = await runStore({
action: 'scheduleSwitch',
email,
credential: hostSwitchCredential,
vaultCredential: sealedCurrent.stored,
expectedCredential: saved.credential,
...(sealedCurrent.vaultUnlocked
? { vaultUnlocked: true, expectedSecuritySalt: sealedCurrent.expectedSecuritySalt }
: {}),
});
return { ...publicList(updated), restarting: updated.scheduled === true };
} catch (error) {
return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' };
}
@@ -0,0 +1,245 @@
/**
* @fileoverview Inner envelope encryption (scrypt + AES-256-GCM) for saved account
* credentials, in-memory session unlock lifecycle, unlock rate-limiting, and
* HMAC action nonces against local CSRF / blind mutation requests.
*/
import {
createCipheriv,
createDecipheriv,
createHmac,
randomBytes,
scrypt,
timingSafeEqual,
} from 'node:crypto';
export const VAULT_CIPHER_PREFIX = 'agv1:';
const VAULT_VERIFIER_CHALLENGE = 'ag-vault-v1:ok';
const VAULT_VERIFIER_AAD = 'ag-vault-verifier:v1';
const VAULT_ENTRY_AAD_PREFIX = 'ag-vault-entry:v1:';
const VAULT_SCRYPT_N = 16384;
const VAULT_SCRYPT_R = 8;
const VAULT_SCRYPT_P = 1;
const VAULT_KEY_LEN = 32;
const VAULT_SCRYPT_MAXMEM = 64 * 1024 * 1024;
export const VAULT_PASSWORD_MIN_LEN = 4;
export const VAULT_PASSWORD_MAX_LEN = 128;
const ACTION_NONCE_SECRET = randomBytes(32);
const ACTION_NONCE_BUCKET_MS = 10 * 60 * 1000;
let activeVaultKeyState = null;
let unlockFailureCount = 0;
let unlockCooldownUntilMs = 0;
export function normalizeVaultPassword(raw) {
if (typeof raw !== 'string') return null;
if (raw.length < VAULT_PASSWORD_MIN_LEN || raw.length > VAULT_PASSWORD_MAX_LEN) return null;
if (!raw.trim()) return null;
return raw;
}
export function isEncryptedVaultCredential(raw) {
return typeof raw === 'string' && raw.startsWith(VAULT_CIPHER_PREFIX);
}
function isPowerOfTwo(n) {
return Number.isInteger(n) && n >= 1024 && n <= 65536 && (n & (n - 1)) === 0;
}
function deriveVaultKey(password, saltBuf, params = {}) {
const N = isPowerOfTwo(params.N) ? params.N : VAULT_SCRYPT_N;
const r = Number.isInteger(params.r) && params.r >= 1 && params.r <= 16 ? params.r : VAULT_SCRYPT_R;
const p = Number.isInteger(params.p) && params.p >= 1 && params.p <= 8 ? params.p : VAULT_SCRYPT_P;
return new Promise((resolve, reject) => {
scrypt(
Buffer.from(password, 'utf8'),
saltBuf,
VAULT_KEY_LEN,
{ N, r, p, maxmem: VAULT_SCRYPT_MAXMEM },
(err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
}
);
});
}
function aeadSeal(plaintextUtf8, keyBuf, aadUtf8) {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', keyBuf, iv);
cipher.setAAD(Buffer.from(aadUtf8, 'utf8'));
const enc = Buffer.concat([cipher.update(plaintextUtf8, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, enc]).toString('base64');
}
function aeadOpen(b64Payload, keyBuf, aadUtf8) {
const raw = Buffer.from(String(b64Payload || ''), 'base64');
if (raw.length < 28) {
throw new Error('vaultDecryptFailed');
}
const iv = raw.subarray(0, 12);
const tag = raw.subarray(12, 28);
const enc = raw.subarray(28);
const decipher = createDecipheriv('aes-256-gcm', keyBuf, iv, { authTagLength: 16 });
decipher.setAAD(Buffer.from(aadUtf8, 'utf8'));
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
}
export async function createVaultSecurityMetadata(password) {
const validPassword = normalizeVaultPassword(password);
if (!validPassword) {
throw new Error('invalidPassword');
}
const saltBuf = randomBytes(16);
const salt = saltBuf.toString('base64');
const keyBuf = await deriveVaultKey(validPassword, saltBuf);
const verifier = aeadSeal(VAULT_VERIFIER_CHALLENGE, keyBuf, VAULT_VERIFIER_AAD);
return {
security: {
enabled: true,
version: 1,
kdf: 'scrypt',
salt,
N: VAULT_SCRYPT_N,
r: VAULT_SCRYPT_R,
p: VAULT_SCRYPT_P,
verifier,
},
keyBuf,
};
}
export async function verifyVaultPassword(password, security) {
if (!security?.enabled || typeof security.salt !== 'string' || typeof security.verifier !== 'string') {
throw new Error('storeFailed');
}
const validPassword = normalizeVaultPassword(password);
if (!validPassword) {
throw new Error('wrongPassword');
}
const saltBuf = Buffer.from(security.salt, 'base64');
if (saltBuf.length < 16) {
throw new Error('storeFailed');
}
const keyBuf = await deriveVaultKey(validPassword, saltBuf, security);
try {
const opened = aeadOpen(security.verifier, keyBuf, VAULT_VERIFIER_AAD);
if (opened !== VAULT_VERIFIER_CHALLENGE) {
keyBuf.fill(0);
throw new Error('wrongPassword');
}
return keyBuf;
} catch {
keyBuf.fill(0);
throw new Error('wrongPassword');
}
}
export function encryptVaultEntryCredential(plainJson, keyBuf, email) {
const normalizedEmail = String(email || '').trim().toLowerCase();
if (!normalizedEmail || !Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) {
throw new Error('storeFailed');
}
return `${VAULT_CIPHER_PREFIX}${aeadSeal(plainJson, keyBuf, `${VAULT_ENTRY_AAD_PREFIX}${normalizedEmail}`)}`;
}
export function decryptVaultEntryCredential(storedText, keyBuf, email) {
const normalizedEmail = String(email || '').trim().toLowerCase();
if (!isEncryptedVaultCredential(storedText) || !normalizedEmail) {
throw new Error('vaultDecryptFailed');
}
if (!Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) {
throw new Error('vaultLocked');
}
const payload = storedText.slice(VAULT_CIPHER_PREFIX.length);
try {
return aeadOpen(payload, keyBuf, `${VAULT_ENTRY_AAD_PREFIX}${normalizedEmail}`);
} catch {
throw new Error('vaultDecryptFailed');
}
}
export function setUnlockedVaultSessionKey(salt, keyBuf) {
if (!salt || !Buffer.isBuffer(keyBuf) || keyBuf.length !== VAULT_KEY_LEN) {
throw new Error('storeFailed');
}
const nextCopy = Buffer.from(keyBuf);
if (activeVaultKeyState?.keyBuf) {
activeVaultKeyState.keyBuf.fill(0);
}
activeVaultKeyState = { salt: String(salt), keyBuf: nextCopy };
}
export function lockVaultSession() {
if (activeVaultKeyState?.keyBuf) {
activeVaultKeyState.keyBuf.fill(0);
}
activeVaultKeyState = null;
}
export function getUnlockedVaultSessionKey(expectedSalt = '') {
if (!activeVaultKeyState?.keyBuf) return null;
if (expectedSalt && activeVaultKeyState.salt !== String(expectedSalt)) {
lockVaultSession();
return null;
}
return activeVaultKeyState.keyBuf;
}
export function isVaultSessionUnlocked(security) {
if (!security?.enabled) return true;
return Boolean(getUnlockedVaultSessionKey(security.salt));
}
export function checkVaultUnlockCooldown(nowMs = Date.now()) {
if (unlockCooldownUntilMs <= nowMs) return 0;
return Math.max(1, Math.ceil((unlockCooldownUntilMs - nowMs) / 1000));
}
export function recordVaultUnlockFailure(nowMs = Date.now()) {
unlockFailureCount += 1;
if (unlockFailureCount >= 5) {
const delayMs = Math.min(60_000, 5_000 * 2 ** Math.min(4, unlockFailureCount - 5));
unlockCooldownUntilMs = nowMs + delayMs;
}
return checkVaultUnlockCooldown(nowMs);
}
export function resetVaultUnlockFailures() {
unlockFailureCount = 0;
unlockCooldownUntilMs = 0;
}
function computeBucketNonceMac(bucket) {
return createHmac('sha256', ACTION_NONCE_SECRET)
.update(`ag-acct-nonce:${bucket}`)
.digest('base64url')
.slice(0, 32);
}
export function issueAccountActionNonce(nowMs = Date.now()) {
const bucket = Math.floor(nowMs / ACTION_NONCE_BUCKET_MS).toString(36);
return `${bucket}.${computeBucketNonceMac(bucket)}`;
}
export function verifyAccountActionNonce(token, nowMs = Date.now()) {
if (typeof token !== 'string' || token.length < 16 || token.length > 96) return false;
const dotIdx = token.indexOf('.');
if (dotIdx <= 0) return false;
const bucketStr = token.slice(0, dotIdx);
const macStr = token.slice(dotIdx + 1);
const bucketNum = Number.parseInt(bucketStr, 36);
if (!Number.isSafeInteger(bucketNum) || bucketNum <= 0) return false;
const curBucket = Math.floor(nowMs / ACTION_NONCE_BUCKET_MS);
if (Math.abs(curBucket - bucketNum) > 1) return false;
const expectedMac = computeBucketNonceMac(bucketNum.toString(36));
const a = Buffer.from(macStr, 'utf8');
const b = Buffer.from(expectedMac, 'utf8');
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
+162 -10
View File
@@ -9,7 +9,12 @@
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { BRIDGE_API_ROUTE_DEFS, LOCAL_ENDPOINT_ID } from '../shared/window-bridge-protocol.mjs';
import { handleAccountCredentialAction } from './account-switch.mjs';
import {
getAccountQuotaHistoryPayload,
getLatestRecordedHostEmail,
} from './account-quota-history.mjs';
import { handleAccountCredentialAction, warmAccountPublicListCache } from './account-switch.mjs';
import { issueAccountActionNonce, verifyAccountActionNonce } from './account-vault-crypto.mjs';
import {
clearRemoteEndpointCaches,
resolveEndpointContext,
@@ -18,7 +23,10 @@ import {
} from './endpoint-registry.mjs';
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
import { revealLocalExportFile, writeLocalExportFile } from './file-exporter.mjs';
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
import {
clearScannerRuntimeMemos,
collectAuthoritativeLiveCascadeIds,
} from './local-scanner.mjs';
import {
SETTINGS_FILE,
clearRuntimeCaches,
@@ -58,12 +66,19 @@ import {
triggerDesktopHostRelaunch,
} from './desktop-launcher-config.mjs';
import {
collectHostI18nUntranslatedFromActiveTargets,
ensureIdeRemoteDebuggingArgv,
getDefaultWindowBridgeStatus,
notifyHostI18nChanged,
notifyModelContextWindowsChanged,
notifyWindowOverlaySetting,
resolveDevToolsPortCandidates,
startDefaultWindowBridge,
} from './window-bridge.mjs';
import {
handleHostI18nGetRequest,
handleHostI18nPostAction,
} from './host-i18n/index.mjs';
import { getQuotaReservationLogSnapshot } from './quota-reservation.mjs';
import { getSessionMigrationCatalog, migrateSessions } from './session-migrator.mjs';
import {
@@ -90,7 +105,7 @@ function sanitizePositiveFiniteMs(val) {
function projectDisplayStep(st) {
const {
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel,
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason, anomaly, anomalySig,
contextTokens, inputTokens, cacheReadTokens,
@@ -103,7 +118,7 @@ function projectDisplayStep(st) {
rootTurnMediaOnly,
} = st;
return {
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
stepIndex, createdAtMs, isCompactionStep, isImageGenStep, modelKey, modelShort, modelLabel,
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
nativeStreamSec, thinkingDurationSec, hasToolCalls, selectedSpeedReason,
...(anomaly ? { anomaly, anomalySig } : {}),
@@ -255,8 +270,10 @@ export async function executeTelemetryAction(data, opts = {}) {
rawScope === 'conversation'
? rawScope
: '';
const rawPool = typeof data?.pool === 'string' ? data.pool.trim().slice(0, 48) : '';
const filterOpts = {
range: data?.range || 'all',
...(rawPool ? { pool: rawPool } : {}),
startMs: sanitizePositiveFiniteMs(data?.startMs),
endMs: sanitizePositiveFiniteMs(data?.endMs),
...(scope ? { scope } : {}),
@@ -556,9 +573,12 @@ export function executeRebuildCacheAction(data = undefined, opts = {}) {
if (!epCtx.ok) {
return buildEndpointErrorResponse(epCtx);
}
const liveCascadeIds = collectAuthoritativeLiveCascadeIds(
epCtx.isRemote ? epCtx.endpoint : null
);
const ok = epCtx.isRemote
? clearRemoteEndpointCaches(epCtx.id)
: clearRuntimeCaches();
? clearRemoteEndpointCaches(epCtx.id, { liveCascadeIds })
: clearRuntimeCaches({ liveCascadeIds });
if (!ok) {
return {
ok: false,
@@ -606,6 +626,20 @@ export async function executePluginUpdateAction() {
};
}
const NONCE_PROTECTED_ACCOUNT_ACTIONS = new Set([
'save',
'capture',
'switch',
'remove',
'loginStart',
'setPassword',
'unlockVault',
'lockVault',
'changePassword',
'disablePassword',
'resetVault',
]);
export async function executeAccountCredentialAction(data, opts = {}) {
const epCtx = resolveActionEndpoint(data, opts);
if (!epCtx.ok) {
@@ -620,15 +654,83 @@ export async function executeAccountCredentialAction(data, opts = {}) {
};
}
const cleanData = stripEndpointField(data);
const result = await handleAccountCredentialAction(cleanData);
if (cleanData?.action === 'switch') {
const action = cleanData?.action || 'list';
const riskAccepted =
opts?.bypassRiskCheck === true || loadSettings().accountSwitchRiskAccepted === true;
if (!riskAccepted) {
if (action !== 'list') {
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({
error: 'riskNotAccepted',
actionNonce: issueAccountActionNonce(),
}),
};
}
const hostEmail = getLatestRecordedHostEmail();
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({
supported: process.platform === 'win32',
riskLocked: true,
accounts: [],
selectedEmail: '',
quotas: {},
quotaHistory: getAccountQuotaHistoryPayload({
allowedEmails: hostEmail ? [hostEmail] : [],
}),
actionNonce: issueAccountActionNonce(),
}),
};
}
if (NONCE_PROTECTED_ACCOUNT_ACTIONS.has(action) && !verifyAccountActionNonce(cleanData?.actionNonce)) {
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify({
error: 'invalidActionNonce',
actionNonce: issueAccountActionNonce(),
}),
};
}
const result = await handleAccountCredentialAction({
...(isPlainObject(cleanData) ? cleanData : {}),
action,
includeSecurity: true,
});
if (action === 'switch' && !result?.error) {
clearTelemetryBuilderMemo(LOCAL_ENDPOINT_ID);
}
const hostEmail = getLatestRecordedHostEmail();
const allowedHistoryEmails = Array.isArray(result?.accounts)
? [...new Set([...result.accounts, ...(hostEmail ? [hostEmail] : [])])]
: hostEmail
? [hostEmail]
: null;
const enriched =
result && typeof result === 'object'
? {
...result,
...(action === 'list' || Array.isArray(result.accounts)
? {
quotaHistory: getAccountQuotaHistoryPayload({
allowedEmails: allowedHistoryEmails,
}),
}
: {}),
actionNonce: issueAccountActionNonce(),
}
: result;
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
body: JSON.stringify(enriched),
};
}
@@ -772,6 +874,37 @@ export function executeQuotaReservationLogAction() {
};
}
export async function executeHostI18nGetAction(opts = {}) {
const result = await handleHostI18nGetRequest({
bridgeStatus: getDefaultWindowBridgeStatus(),
...(opts?.hostI18nManager ? { manager: opts.hostI18nManager } : {}),
});
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
export async function executeHostI18nPostAction(data = {}, opts = {}) {
const out = await handleHostI18nPostAction(isPlainObject(data) ? data : {}, {
bridgeStatus: getDefaultWindowBridgeStatus(),
onChanged: typeof opts?.onHostI18nChanged === 'function' ? opts.onHostI18nChanged : notifyHostI18nChanged,
collectFromTargets:
typeof opts?.collectHostI18nUntranslated === 'function'
? opts.collectHostI18nUntranslated
: collectHostI18nUntranslatedFromActiveTargets,
...(opts?.hostI18nManager ? { manager: opts.hostI18nManager } : {}),
});
return {
status: Number(out?.status || 200),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(out?.payload || { ok: false, error: 'Invalid host-i18n response' }),
};
}
export function executeRevealFileAction(data, opts = {}) {
const result = revealLocalExportFile(data?.filePath, {
...(opts?.platform ? { platform: opts.platform } : {}),
@@ -816,6 +949,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
if (isPlainObject(data) && data.__quotaReservationAction === 'log') {
return executeQuotaReservationLogAction();
}
if (isPlainObject(data) && typeof data.__hostI18nAction === 'string') {
if (data.__hostI18nAction === 'get') {
return executeHostI18nGetAction(opts);
}
return executeHostI18nPostAction(
{ ...(isPlainObject(data.payload) ? data.payload : {}), action: data.__hostI18nAction },
opts
);
}
return executeSettingsAction(data);
case 'accounts_get':
return executeAccountCredentialAction(undefined, opts);
@@ -843,6 +985,10 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
return executeRevealFileAction(data, opts);
case 'quota_reservation_log':
return executeQuotaReservationLogAction();
case 'host_i18n_get':
return executeHostI18nGetAction(opts);
case 'host_i18n_action':
return executeHostI18nPostAction(data, opts);
default:
return {
status: 404,
@@ -861,7 +1007,13 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
if (lsRuntimeEndpoint.addr === 'test.invalid') return null;
if (!allowDynamicLs && !lsRuntimeEndpoint.addr) return null;
ensureCliStatusLineConfigured({ enabled: loadSettings().enableCliStatusLine !== false });
const bootSettings = loadSettings();
ensureCliStatusLineConfigured({ enabled: bootSettings.enableCliStatusLine !== false });
if (allowDynamicLs && bootSettings.accountSwitchRiskAccepted === true) {
setTimeout(() => {
void warmAccountPublicListCache();
}, 80).unref?.();
}
const triggerRestart =
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
+278 -18
View File
@@ -10,10 +10,13 @@
* 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。
*/
import { existsSync, readFileSync } from 'node:fs';
import { closeSync, existsSync, openSync, readFileSync, readSync } from 'node:fs';
import { basename, join } from 'node:path';
import { extractShortPromptTitle } from '../shared/prompt-clean.mjs';
import { parseWorkspaceUrisColumn } from '../shared/workspace-uri.mjs';
import {
decodeWorkspaceFileUriToPath,
parseWorkspaceUrisColumn,
} from '../shared/workspace-uri.mjs';
import { parseIsoMs } from '../trajectory-metrics.mjs';
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
import {
@@ -21,6 +24,7 @@ import {
computeSqliteWalSig,
getNodeSqliteDatabaseSync,
hasBuiltinNodeSqlite,
isSqliteDbReadyForRead,
normalizeSqliteIsoTime,
withReadOnlySqliteDb,
} from './sqlite-client.mjs';
@@ -40,6 +44,7 @@ export {
computeSqliteWalSig,
getNodeSqliteDatabaseSync,
hasBuiltinNodeSqlite,
isSqliteDbReadyForRead,
withReadOnlySqliteDb,
};
@@ -1522,8 +1527,193 @@ function decodeProtoInvokeSubagentSlice(buf, state, end) {
return { subagents, results };
}
function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
const imageDimsMemo = new Map();
function parseImageBufferDimensions(buf) {
if (!buf || buf.length < 11) return null;
// PNG: 89 50 4E 47 0D 0A 1A 0A + IHDR
if (
buf[0] === 0x89 &&
buf[1] === 0x50 &&
buf[2] === 0x4e &&
buf[3] === 0x47 &&
buf.length >= 24
) {
const width = buf.readUInt32BE(16);
const height = buf.readUInt32BE(20);
return width > 0 && height > 0 ? { width, height } : null;
}
// JPEG: FF D8 ... SOF0..SOF3 (FF C0..C3)
if (buf[0] === 0xff && buf[1] === 0xd8) {
let i = 2;
while (i + 9 <= buf.length) {
if (buf[i] !== 0xff) {
i += 1;
continue;
}
const marker = buf[i + 1];
if (marker === 0xff) {
i += 1;
continue;
}
if (marker === 0xd8 || marker === 0xd9 || (marker >= 0xd0 && marker <= 0xd7)) {
i += 2;
continue;
}
if (
(marker >= 0xc0 && marker <= 0xc3) ||
(marker >= 0xc5 && marker <= 0xc7) ||
(marker >= 0xc9 && marker <= 0xcb) ||
(marker >= 0xcd && marker <= 0xcf)
) {
const height = buf.readUInt16BE(i + 5);
const width = buf.readUInt16BE(i + 7);
return width > 0 && height > 0 ? { width, height } : null;
}
if (i + 4 > buf.length) break;
const segLen = buf.readUInt16BE(i + 2);
if (segLen < 2) break;
i += 2 + segLen;
}
return null;
}
// WebP: RIFF....WEBP
if (
buf.length >= 30 &&
buf[0] === 0x52 &&
buf[1] === 0x49 &&
buf[2] === 0x46 &&
buf[3] === 0x46 &&
buf[8] === 0x57 &&
buf[9] === 0x45 &&
buf[10] === 0x42 &&
buf[11] === 0x50
) {
const chunk = buf.subarray(12, 16).toString('ascii');
if (chunk === 'VP8X' && buf.length >= 30) {
const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16));
const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16));
return width > 0 && height > 0 ? { width, height } : null;
}
if (chunk === 'VP8 ' && buf.length >= 30) {
const width = buf.readUInt16LE(26) & 0x3fff;
const height = buf.readUInt16LE(28) & 0x3fff;
return width > 0 && height > 0 ? { width, height } : null;
}
if (chunk === 'VP8L' && buf.length >= 25) {
const bits = buf.readUInt32LE(21);
const width = (bits & 0x3fff) + 1;
const height = ((bits >>> 14) & 0x3fff) + 1;
return width > 0 && height > 0 ? { width, height } : null;
}
}
return null;
}
/**
* 仅读取本地生成图片文件前 32KB 头部字节解析真实像素尺寸(PNG / JPEG / WebP),用于精确匹配图片分辨率计费档位。
*
* @param {string} rawUri
* @returns {{ width: number, height: number } | null}
*/
export function readLocalImageDimensionsFromUri(rawUri) {
const localPath = decodeWorkspaceFileUriToPath(rawUri);
if (!localPath) return null;
if (imageDimsMemo.has(localPath)) {
return imageDimsMemo.get(localPath);
}
let dims = null;
try {
if (existsSync(localPath)) {
if (typeof openSync === 'function' && typeof readSync === 'function' && typeof closeSync === 'function') {
const fd = openSync(localPath, 'r');
try {
const head = Buffer.allocUnsafe(32768);
const bytesRead = readSync(fd, head, 0, head.length, 0);
if (bytesRead >= 11) {
dims = parseImageBufferDimensions(head.subarray(0, bytesRead));
}
} finally {
closeSync(fd);
}
} else if (typeof readFileSync === 'function') {
const raw = readFileSync(localPath);
const buf = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
dims = parseImageBufferDimensions(buf);
}
}
} catch {
dims = null;
}
if (dims) {
if (imageDimsMemo.size >= 512) {
const firstKey = imageDimsMemo.keys().next().value;
if (firstKey !== undefined) imageDimsMemo.delete(firstKey);
}
imageDimsMemo.set(localPath, dims);
}
return dims;
}
function decodeProtoGenerateImageSlice(buf, state, end) {
let prompt = '';
let aspectRatio = '';
let uri = '';
let fileSizeBytes = 0;
let modelName = '';
let imageName = '';
while (state.off < end) {
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
const fn = tag >>> 3;
const wt = tag & 7;
if (fn === 1 && wt === 2) {
prompt = readProtoString(buf, state, end);
} else if (fn === 3 && wt === 2) {
aspectRatio = readProtoString(buf, state, end);
} else if (fn === 4 && wt === 2) {
uri = readProtoString(buf, state, end);
} else if (fn === 5 && wt === 0) {
fileSizeBytes = Number(readProtoVarint(buf, state, end));
} else if (fn === 6 && wt === 2) {
modelName = readProtoString(buf, state, end);
} else if (fn === 8 && wt === 2) {
imageName = readProtoString(buf, state, end);
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
return { prompt, aspectRatio, uri, fileSizeBytes, modelName, imageName };
}
function decodeProtoGeneratedMediaSlice(buf, state, end) {
let mimeType = '';
let uri = '';
while (state.off < end) {
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
const fn = tag >>> 3;
const wt = tag & 7;
if (fn === 1 && wt === 2) {
mimeType = readProtoString(buf, state, end);
} else if (fn === 5 && wt === 2) {
uri = readProtoString(buf, state, end);
} else {
skipProtoField(buf, state, wt, end);
}
}
state.off = end;
return mimeType || uri ? { mimeType, uri } : null;
}
function decodeProtoGenericStepToolPayloadSlice(
buf,
state,
end,
{ wantInvokeSubagent = false, wantGenerateImage = false } = {}
) {
let invokeSubagent = null;
let generateImage = null;
let mediaFallback = null;
while (state.off < end) {
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
const fn = tag >>> 3;
@@ -1532,7 +1722,11 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
const resEnd = readSubEnd(buf, state, end);
while (state.off < resEnd) {
const resTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd)));
if ((resTag >>> 3) === 6 && (resTag & 7) === 2) {
const rFn = resTag >>> 3;
const rWt = resTag & 7;
if (rFn === 4 && rWt === 2 && wantGenerateImage) {
mediaFallback = decodeProtoGeneratedMediaSlice(buf, state, readSubEnd(buf, state, resEnd));
} else if (rFn === 6 && rWt === 2) {
const anyEnd = readSubEnd(buf, state, resEnd);
let typeUrl = '';
let valStart = 0;
@@ -1550,15 +1744,23 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
}
}
state.off = anyEnd;
if (
valEnd > valStart &&
(typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') ||
typeUrl === 'exa.cortex.core.tools.InvokeSubagent')
) {
invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd);
if (valEnd > valStart) {
if (
wantInvokeSubagent &&
(typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') ||
typeUrl === 'exa.cortex.core.tools.InvokeSubagent')
) {
invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd);
} else if (
wantGenerateImage &&
(typeUrl.endsWith('/exa.cortex.core.tools.GenerateImage') ||
typeUrl === 'exa.cortex.core.tools.GenerateImage')
) {
generateImage = decodeProtoGenerateImageSlice(buf, { off: valStart }, valEnd);
}
}
} else {
skipProtoField(buf, state, resTag & 7, resEnd);
skipProtoField(buf, state, rWt, resEnd);
}
}
state.off = resEnd;
@@ -1567,7 +1769,27 @@ function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) {
}
}
state.off = end;
return invokeSubagent;
if (generateImage || mediaFallback) {
const resolvedUri = generateImage?.uri || mediaFallback?.uri || '';
const dims = resolvedUri ? readLocalImageDimensionsFromUri(resolvedUri) : null;
generateImage = {
prompt: generateImage?.prompt || '',
imageName: generateImage?.imageName || '',
aspectRatio: generateImage?.aspectRatio || '',
modelName: generateImage?.modelName || '',
...(generateImage?.fileSizeBytes > 0 ? { fileSizeBytes: generateImage.fileSizeBytes } : {}),
...(resolvedUri || mediaFallback?.mimeType
? {
generatedMedia: {
mimeType: mediaFallback?.mimeType || '',
uri: resolvedUri,
},
}
: {}),
...(dims ? { width: dims.width, height: dims.height } : {}),
};
}
return { invokeSubagent, generateImage };
}
function decodeProtoSystemMessageSlice(buf, state, end) {
@@ -1588,7 +1810,13 @@ function decodeProtoSystemMessageSlice(buf, state, end) {
function decodeProtoSelectiveStepPayload(
rawBlob,
{ stepTypeNum, isInvokeSubagent, includeSystemMessage = false, keepFullText }
{
stepTypeNum,
isInvokeSubagent,
isGenerateImage = false,
includeSystemMessage = false,
keepFullText,
}
) {
const buf = toUint8Array(rawBlob);
if (!buf || buf.length === 0) return {};
@@ -1616,9 +1844,15 @@ function decodeProtoSelectiveStepPayload(
} else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) {
const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end));
if (sysMsg) out.systemMessage = { message: sysMsg };
} else if (fn === 140 && wt === 2 && isInvokeSubagent) {
const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end));
if (inv) out.invokeSubagent = inv;
} else if (fn === 140 && wt === 2 && (isInvokeSubagent || isGenerateImage)) {
const toolParsed = decodeProtoGenericStepToolPayloadSlice(
buf,
state,
readSubEnd(buf, state, end),
{ wantInvokeSubagent: isInvokeSubagent, wantGenerateImage: isGenerateImage }
);
if (toolParsed.invokeSubagent) out.invokeSubagent = toolParsed.invokeSubagent;
if (toolParsed.generateImage) out.generateImage = toolParsed.generateImage;
} else if (fn === 143 && wt === 2 && isInvokeSubagent) {
out.invokeSubagent = decodeProtoInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end));
} else {
@@ -1632,6 +1866,10 @@ function isInvokeSubagentToolName(rawName) {
return /^(?:default_api:)?invoke_subagent$/i.test(String(rawName || '').trim());
}
function isGenerateImageToolName(rawName) {
return /^(?:default_api:)?generate_image$/i.test(String(rawName || '').trim());
}
function mapRunningGenericToolStepType(rawToolName) {
const name = String(rawToolName || '')
.trim()
@@ -1639,6 +1877,7 @@ function mapRunningGenericToolStepType(rawToolName) {
.replace(/^default_api:/, '');
if (!name) return 'CORTEX_STEP_TYPE_GENERIC';
if (name === 'invoke_subagent') return 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT';
if (name === 'generate_image') return 'CORTEX_STEP_TYPE_GENERATE_IMAGE';
if (name === 'run_command') return 'CORTEX_STEP_TYPE_RUN_COMMAND';
if (name === 'command_status') return 'CORTEX_STEP_TYPE_COMMAND_STATUS';
if (name === 'send_command_input') return 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT';
@@ -1807,15 +2046,23 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
if (ownGenRecords.length > 0) {
// 从末尾向前定位最近一条包含完整上下文拆解(tokenBreakdown / promptSections / tools / messagePrompts)的记录,
// 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成。
// 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成;
// 若末尾完整记录因回退/中断成为 `stepIndices: []`,继续跳过被宿主裁剪的轻量记录并尝试补解更早的完整带索引记录。
let foundUnindexedBreakdown = false;
for (let i = ownGenRecords.length - 1; i >= 0; i--) {
const rec = ownGenRecords[i];
if (foundUnindexedBreakdown && Number(rec?.rawData?.byteLength || 0) <= 2048) {
continue;
}
try {
const fullDecoded = decodeProtoGeneratorMeta(rec.rawData, true);
if (fullDecoded) {
rec.gm = fullDecoded;
if (hasContextBreakdownPayload(fullDecoded.chatModel)) {
break;
if (Array.isArray(fullDecoded.stepIndices) && fullDecoded.stepIndices.length > 0) {
break;
}
foundUnindexedBreakdown = true;
}
}
} catch {
@@ -1887,12 +2134,16 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
const isInvSub =
rec.stepTypeNum === 127 ||
(rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name));
const isGenImg =
rec.stepTypeNum === 91 ||
(rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name));
if (
rec.stepTypeNum === 14 ||
rec.stepTypeNum === 15 ||
rec.stepTypeNum === 17 ||
(isChildTrajectory && rec.stepTypeNum === 101) ||
isInvSub ||
isGenImg ||
(inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson))
) {
payloadIndices.push(rec.idx);
@@ -1930,10 +2181,15 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
const isInvSub =
rec.stepTypeNum === 127 ||
(rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name));
const isGenImg =
rec.stepTypeNum === 91 ||
(rec.stepTypeNum === 132 && isGenerateImageToolName(rec.metadata?.toolCall?.name));
let type = '';
if (isInvSub) {
type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT';
} else if (isGenImg) {
type = 'CORTEX_STEP_TYPE_GENERATE_IMAGE';
} else if (rec.stepTypeNum === 132 && inRunningTail) {
type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name);
} else {
@@ -1954,6 +2210,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, {
stepTypeNum: rec.stepTypeNum,
isInvokeSubagent: isInvSub,
isGenerateImage: isGenImg,
includeSystemMessage: isChildTrajectory && rec.stepTypeNum === 101,
keepFullText: inRunningTail,
});
@@ -1979,6 +2236,9 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
if (decodedPayload.invokeSubagent) {
stepObj.invokeSubagent = decodedPayload.invokeSubagent;
}
if (decodedPayload.generateImage) {
stepObj.generateImage = decodedPayload.generateImage;
}
} catch {
// 忽略单步载荷解析异常
}
+619 -74
View File
@@ -10,7 +10,7 @@
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { lsRuntimeEndpoint } from './config.mjs';
import { DATA_DIR, loadJson, lsRuntimeEndpoint, saveJson } from './config.mjs';
import { callLsRpc } from './ls-rpc.mjs';
export const DEFAULT_UPSTREAM_CLOUDCODE_URL = 'https://daily-cloudcode-pa.googleapis.com';
@@ -21,6 +21,18 @@ const CC_PROXY_CHECKPOINTER_PREFIX = `${CC_PROXY_CHECKPOINTER_KEY}/`;
const CC_PROXY_MAX_LOG_READ_BYTES = 512 * 1024;
const CC_PROXY_RETRY_COOLDOWN_MS = 15_000;
const CC_PROXY_SYS_PROXY_CACHE_MS = 15_000;
const CC_PROXY_DEFAULT_TUNNEL_TIMEOUT_MS = 15_000;
const CC_PROXY_AGENT_FREE_SOCKET_TIMEOUT_MS = 25_000;
const CC_PROXY_HOP_BY_HOP_HEADERS = [
'connection',
'keep-alive',
'proxy-connection',
'proxy-authorization',
'te',
'trailer',
'upgrade',
];
const ccProxyNoopSocketError = () => {};
let ccProxyNodeModulesPromise = null;
@@ -29,13 +41,15 @@ async function loadCcProxyNodeModules() {
ccProxyNodeModulesPromise = Promise.all([
import('node:http'),
import('node:https'),
import('node:net'),
import('node:tls'),
import('node:zlib'),
import('node:child_process'),
import('node:fs'),
]).then(([httpMod, httpsMod, tlsMod, zlibMod, cpMod, fsMod]) => ({
]).then(([httpMod, httpsMod, netMod, tlsMod, zlibMod, cpMod, fsMod]) => ({
http: httpMod.default || httpMod,
https: httpsMod.default || httpsMod,
net: netMod.default || netMod,
tls: tlsMod.default || tlsMod,
zlib: zlibMod.default || zlibMod,
execFile: cpMod.execFile,
@@ -154,15 +168,32 @@ export function detectUpstreamCloudCodeUrl({
return DEFAULT_UPSTREAM_CLOUDCODE_URL;
}
function shouldCcProxyBypassHost(hostname, noProxyRaw) {
const target = String(hostname || '').trim().toLowerCase();
export function shouldCcProxyBypassHost(hostname, noProxyRaw) {
const target = String(hostname || '').trim().toLowerCase().replace(/^\[|\]$/g, '');
const list = String(noProxyRaw || '').trim();
if (!target || !list) return false;
for (const part of list.split(/[;,]/)) {
for (const part of list.split(/[;,\s]+/)) {
const raw = part.trim().toLowerCase();
if (!raw) continue;
if (raw === '*') return true;
const rule = raw.replace(/^\*\./, '.').replace(/:\d+$/, '');
if (raw === '<local>') {
if (isCcProxyLoopbackHost(target) || (!target.includes('.') && !target.includes(':'))) {
return true;
}
continue;
}
const strippedPort = raw.startsWith('[')
? raw.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
: raw.includes(':') && raw.indexOf(':') === raw.lastIndexOf(':')
? raw.replace(/:\d+$/, '')
: raw;
if (!strippedPort) continue;
if (strippedPort.includes('*') && !(strippedPort.startsWith('*.') && !strippedPort.slice(2).includes('*'))) {
const pattern = `^${strippedPort.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`;
if (new RegExp(pattern, 'i').test(target)) return true;
continue;
}
const rule = strippedPort.replace(/^\*\./, '.');
if (!rule) continue;
if (rule.startsWith('.')) {
if (target.endsWith(rule) || target === rule.slice(1)) return true;
@@ -173,18 +204,48 @@ function shouldCcProxyBypassHost(hostname, noProxyRaw) {
return false;
}
export function normalizeCcProxyCandidateUrl(rawVal) {
let s = String(rawVal || '').trim();
if (!s) return '';
if (/^socks:\/\//i.test(s)) {
s = `socks5://${s.slice('socks://'.length)}`;
}
const hasExplicitScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s);
if (hasExplicitScheme && !/^(?:https?|socks5h?):\/\//i.test(s)) {
return '';
}
const candidate = hasExplicitScheme ? s : `http://${s}`;
try {
const parsed = new URL(candidate);
if (!parsed.hostname) return '';
if (parsed.port) {
const p = Number(parsed.port);
if (!Number.isInteger(p) || p <= 0 || p > 65535) return '';
}
return candidate;
} catch {
return '';
}
}
function parseWindowsProxyServerValue(rawVal) {
let srv = String(rawVal || '').trim();
const srv = String(rawVal || '').trim();
if (!srv) return '';
if (srv.includes('=')) {
const parts = srv.split(';').map((p) => p.trim()).filter(Boolean);
const httpsPart = parts.find((p) => p.toLowerCase().startsWith('https='));
const httpPart = parts.find((p) => p.toLowerCase().startsWith('http='));
const chosen = httpsPart || httpPart || '';
srv = chosen.slice(chosen.indexOf('=') + 1).trim();
const socksPart = parts.find((p) => p.toLowerCase().startsWith('socks='));
const chosen = httpsPart || httpPart || socksPart || '';
if (!chosen) return '';
const rawHostPort = chosen.slice(chosen.indexOf('=') + 1).trim();
if (!rawHostPort) return '';
if (chosen === socksPart && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(rawHostPort)) {
return normalizeCcProxyCandidateUrl(`socks5://${rawHostPort}`);
}
return normalizeCcProxyCandidateUrl(rawHostPort);
}
if (!srv) return '';
return /^https?:\/\//i.test(srv) ? srv : `http://${srv}`;
return normalizeCcProxyCandidateUrl(srv);
}
let winRegProxyMemo = {
@@ -231,10 +292,16 @@ async function readWindowsInternetSettingsAsync() {
export async function detectSystemHttpsProxy(targetHostname = '', { env = process.env, platform = process.platform } = {}) {
const noProxy = env?.NO_PROXY || env?.no_proxy || '';
if (shouldCcProxyBypassHost(targetHostname, noProxy)) return '';
const envProxy = String(
env?.HTTPS_PROXY || env?.https_proxy || env?.ALL_PROXY || env?.all_proxy || ''
).trim();
if (envProxy) return /^https?:\/\//i.test(envProxy) ? envProxy : `http://${envProxy}`;
const envCandidates = [
env?.HTTPS_PROXY,
env?.https_proxy,
env?.ALL_PROXY,
env?.all_proxy,
];
for (const rawCandidate of envCandidates) {
const normalized = normalizeCcProxyCandidateUrl(rawCandidate);
if (normalized) return normalized;
}
if (platform !== 'win32') return '';
try {
const out = await readWindowsInternetSettingsAsync();
@@ -410,28 +477,311 @@ function decompressCcProxyBody(zlib, buf, encoding) {
return buf;
}
function openCcProxyTunnelSocket(http, tls, targetHost, targetPort, proxyUrl) {
if (!proxyUrl) return Promise.resolve(null);
const parsedProxy = new URL(proxyUrl);
function ccProxySafeDecodeUriPart(raw) {
if (!raw) return '';
try {
return decodeURIComponent(raw);
} catch {
return String(raw);
}
}
function ccProxyReadExactBytes(socket, count) {
return new Promise((resolve, reject) => {
const connectReq = http.request({
host: parsedProxy.hostname,
port: Number(parsedProxy.port || (parsedProxy.protocol === 'https:' ? 443 : 80)),
method: 'CONNECT',
path: `${targetHost}:${targetPort}`,
headers: { Host: `${targetHost}:${targetPort}` },
let acc = Buffer.alloc(0);
const cleanup = () => {
socket.off('data', onData);
socket.off('error', onErr);
socket.off('close', onClose);
socket.off('end', onClose);
};
const onErr = (err) => {
cleanup();
reject(err);
};
const onClose = () => {
cleanup();
reject(new Error('SOCKS5 proxy closed connection prematurely'));
};
const onData = (chunk) => {
acc = acc.length === 0 ? chunk : Buffer.concat([acc, chunk]);
if (acc.length >= count) {
cleanup();
socket.pause();
const needed = acc.subarray(0, count);
const rest = acc.subarray(count);
if (rest.length > 0) {
socket.unshift(rest);
}
resolve(needed);
}
};
socket.on('data', onData);
socket.once('error', onErr);
socket.once('close', onClose);
socket.once('end', onClose);
socket.resume();
});
}
function ccProxyEncodeIpv6Bytes(ipv6Str) {
let host = String(ipv6Str || '').trim().replace(/^\[|\]$/g, '');
const zoneIdx = host.indexOf('%');
if (zoneIdx !== -1) host = host.slice(0, zoneIdx);
const lastColon = host.lastIndexOf(':');
if (lastColon !== -1 && host.slice(lastColon + 1).includes('.')) {
const v4Parts = host
.slice(lastColon + 1)
.split('.')
.map((n) => Number(n));
if (v4Parts.length !== 4 || v4Parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {
return null;
}
const hi = ((v4Parts[0] << 8) | v4Parts[1]).toString(16);
const lo = ((v4Parts[2] << 8) | v4Parts[3]).toString(16);
host = `${host.slice(0, lastColon)}:${hi}:${lo}`;
}
const dblParts = host.split('::');
if (dblParts.length > 2) return null;
const left = dblParts[0] ? dblParts[0].split(':') : [];
const right = dblParts.length === 2 && dblParts[1] ? dblParts[1].split(':') : [];
const missing = 8 - (left.length + right.length);
if (dblParts.length === 1 ? left.length !== 8 : missing < 1) return null;
const groups = dblParts.length === 2 ? [...left, ...new Array(missing).fill('0'), ...right] : left;
if (groups.length !== 8) return null;
const buf = Buffer.allocUnsafe(16);
for (let i = 0; i < 8; i += 1) {
const val = Number.parseInt(groups[i], 16);
if (!Number.isInteger(val) || val < 0 || val > 0xffff) return null;
buf.writeUInt16BE(val, i * 2);
}
return buf;
}
async function ccProxyConnectSocks5Socket(net, parsedProxy, targetHost, targetPort) {
const proxyHost = parsedProxy.hostname.replace(/^\[|\]$/g, '');
const proxyPort = Number(parsedProxy.port || 1080);
const rawUser = ccProxySafeDecodeUriPart(parsedProxy.username);
const rawPass = ccProxySafeDecodeUriPart(parsedProxy.password);
const hasAuth = Boolean(rawUser || rawPass);
const socket = await new Promise((resolve, reject) => {
const s = net.connect({ host: proxyHost, port: proxyPort });
const onErr = (err) => {
s.destroy();
reject(err);
};
s.once('error', onErr);
s.once('connect', () => {
s.off('error', onErr);
s.on('error', ccProxyNoopSocketError);
resolve(s);
});
connectReq.on('connect', (res, socket) => {
if (res.statusCode !== 200) {
});
try {
// 1. Method negotiation (RFC 1928)
const greeting = hasAuth
? Buffer.from([0x05, 0x02, 0x00, 0x02])
: Buffer.from([0x05, 0x01, 0x00]);
socket.write(greeting);
const methodReply = await ccProxyReadExactBytes(socket, 2);
if (methodReply[0] !== 0x05 || methodReply[1] === 0xff) {
throw new Error('SOCKS5 proxy rejected authentication methods');
}
if (methodReply[1] === 0x02) {
if (!hasAuth) {
throw new Error('SOCKS5 proxy requires username/password authentication');
}
const userBuf = Buffer.from(rawUser, 'utf8');
const passBuf = Buffer.from(rawPass, 'utf8');
if (userBuf.length > 255 || passBuf.length > 255) {
throw new Error('SOCKS5 credentials exceed 255 bytes');
}
const authReq = Buffer.concat([
Buffer.from([0x01, userBuf.length]),
userBuf,
Buffer.from([passBuf.length]),
passBuf,
]);
socket.write(authReq);
const authReply = await ccProxyReadExactBytes(socket, 2);
if (authReply[1] !== 0x00) {
throw new Error('SOCKS5 username/password authentication failed');
}
} else if (methodReply[1] !== 0x00) {
throw new Error(`Unsupported SOCKS5 auth method (${methodReply[1]})`);
}
// 2. CONNECT targetHost:targetPort
const cleanHost = String(targetHost || '').replace(/^\[|\]$/g, '');
const ipVer = net.isIP(cleanHost);
let addrPart;
if (ipVer === 4) {
const octets = cleanHost.split('.').map((n) => Number(n));
addrPart = Buffer.from([0x01, octets[0], octets[1], octets[2], octets[3]]);
} else if (ipVer === 6) {
const ipv6Bytes = ccProxyEncodeIpv6Bytes(cleanHost);
if (!ipv6Bytes) {
throw new Error('Invalid SOCKS5 target IPv6 address');
}
addrPart = Buffer.concat([Buffer.from([0x04]), ipv6Bytes]);
} else {
const hostBuf = Buffer.from(cleanHost, 'utf8');
if (hostBuf.length === 0 || hostBuf.length > 255) {
throw new Error('Invalid SOCKS5 target hostname');
}
addrPart = Buffer.concat([Buffer.from([0x03, hostBuf.length]), hostBuf]);
}
const portBuf = Buffer.allocUnsafe(2);
portBuf.writeUInt16BE(Number(targetPort), 0);
socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), addrPart, portBuf]));
const repHead = await ccProxyReadExactBytes(socket, 4);
if (repHead[0] !== 0x05 || repHead[1] !== 0x00) {
throw new Error(`SOCKS5 CONNECT failed (code ${repHead[1]})`);
}
const atyp = repHead[3];
if (atyp === 0x01) {
await ccProxyReadExactBytes(socket, 4 + 2);
} else if (atyp === 0x03) {
const lenBuf = await ccProxyReadExactBytes(socket, 1);
await ccProxyReadExactBytes(socket, lenBuf[0] + 2);
} else if (atyp === 0x04) {
await ccProxyReadExactBytes(socket, 16 + 2);
} else {
throw new Error(`Unsupported SOCKS5 reply address type (${atyp})`);
}
socket.resume();
return socket;
} catch (err) {
socket.destroy();
throw err;
}
}
export function openCcProxyTunnelSocket(
mods,
targetHost,
targetPort,
proxyUrl,
{ timeoutMs = CC_PROXY_DEFAULT_TUNNEL_TIMEOUT_MS, tlsOptions = null } = {}
) {
const normalizedUrl = normalizeCcProxyCandidateUrl(proxyUrl);
if (!normalizedUrl) return Promise.resolve(null);
const parsedProxy = new URL(normalizedUrl);
const { http, https, net, tls } = mods;
const cleanTargetHost = String(targetHost || '').replace(/^\[|\]$/g, '');
const sniOpts = net && net.isIP(cleanTargetHost) !== 0 ? {} : { servername: cleanTargetHost };
const connectAuthority = cleanTargetHost.includes(':')
? `[${cleanTargetHost}]:${targetPort}`
: `${cleanTargetHost}:${targetPort}`;
return new Promise((resolve, reject) => {
let settled = false;
let connectReq = null;
let rawSocket = null;
let tlsSocket = null;
const timer =
Number.isFinite(timeoutMs) && timeoutMs > 0
? setTimeout(() => {
fail(new Error(`Proxy tunnel timed out after ${timeoutMs}ms`));
}, timeoutMs)
: null;
timer?.unref?.();
function cleanupTimer() {
if (timer) clearTimeout(timer);
}
function fail(err) {
if (settled) return;
settled = true;
cleanupTimer();
try {
connectReq?.destroy();
} catch {}
try {
tlsSocket?.destroy();
} catch {}
try {
rawSocket?.destroy();
} catch {}
reject(err);
}
function upgradeToTls(sock, headBuf = null) {
rawSocket = sock;
sock.on('error', ccProxyNoopSocketError);
if (headBuf && headBuf.length > 0) {
sock.unshift(headBuf);
}
tlsSocket = tls.connect({
socket: sock,
ALPNProtocols: ['http/1.1'],
...sniOpts,
...(tlsOptions && typeof tlsOptions === 'object' ? tlsOptions : {}),
});
tlsSocket.on('error', ccProxyNoopSocketError);
tlsSocket.once('secureConnect', () => {
if (settled) {
tlsSocket.destroy();
return;
}
settled = true;
cleanupTimer();
tlsSocket.off('error', fail);
resolve(tlsSocket);
});
tlsSocket.once('error', fail);
}
const proto = parsedProxy.protocol.toLowerCase();
if (proto === 'socks5:' || proto === 'socks5h:') {
ccProxyConnectSocks5Socket(net, parsedProxy, cleanTargetHost, targetPort)
.then((sock) => {
if (settled) {
sock.destroy();
return;
}
upgradeToTls(sock);
})
.catch(fail);
return;
}
const isHttpsProxy = proto === 'https:';
const proxyTransport = isHttpsProxy ? https : http;
const headers = { Host: connectAuthority };
if (parsedProxy.username || parsedProxy.password) {
const user = ccProxySafeDecodeUriPart(parsedProxy.username);
const pass = ccProxySafeDecodeUriPart(parsedProxy.password);
const token = Buffer.from(`${user}:${pass}`, 'utf8').toString('base64');
headers['Proxy-Authorization'] = `Basic ${token}`;
}
connectReq = proxyTransport.request({
hostname: parsedProxy.hostname.replace(/^\[|\]$/g, ''),
port: Number(parsedProxy.port || (isHttpsProxy ? 443 : 80)),
method: 'CONNECT',
path: connectAuthority,
headers,
});
connectReq.on('connect', (res, socket, head) => {
socket.on('error', ccProxyNoopSocketError);
if (settled) {
socket.destroy();
reject(new Error(`Proxy CONNECT failed (${res.statusCode})`));
return;
}
const tlsSocket = tls.connect({ socket, servername: targetHost });
tlsSocket.once('secureConnect', () => resolve(tlsSocket));
tlsSocket.once('error', reject);
if (res.statusCode !== 200) {
socket.destroy();
fail(new Error(`Proxy CONNECT failed (${res.statusCode})`));
return;
}
upgradeToTls(socket, head);
});
connectReq.on('error', reject);
connectReq.on('error', fail);
connectReq.end();
});
}
@@ -449,17 +799,25 @@ export function createCloudCodeProxyController({
allowHttpUpstream = false,
allowTestEndpoint = false,
retryCooldownMs = CC_PROXY_RETRY_COOLDOWN_MS,
tunnelTimeoutMs = CC_PROXY_DEFAULT_TUNNEL_TIMEOUT_MS,
upstreamTlsOptions = null,
stateFilePath = '',
loadJsonFn = loadJson,
saveJsonFn = saveJson,
} = {}) {
let server = null;
let localUrl = '';
let preferredPort = 0;
let upstreamUrl = '';
let lsSwitched = false;
let stateHydratedOnce = false;
let activeRules = {};
let upstreamDefaults = {};
let appliedSig = '';
let lastFailedSig = '';
let lastErrorAtMs = 0;
let cachedSysProxy = { url: '', checkedAtMs: 0, host: '' };
let activeAgentEntry = null;
let syncChain = Promise.resolve();
let status = {
@@ -473,6 +831,99 @@ export function createCloudCodeProxyController({
error: '',
};
function hydratePersistedStateOnce() {
if (stateHydratedOnce) return;
stateHydratedOnce = true;
if (!stateFilePath || typeof loadJsonFn !== 'function') return;
try {
const saved = loadJsonFn(stateFilePath, null);
if (!saved || typeof saved !== 'object') return;
const savedPort = Number(saved.localPort || 0);
if (Number.isInteger(savedPort) && savedPort > 0 && savedPort <= 65535) {
preferredPort = savedPort;
}
const savedUpstream = String(saved.upstreamUrl || '').trim();
if (
savedUpstream &&
!upstreamUrl &&
isValidUpstreamCloudCodeUrl(savedUpstream, { allowHttp: allowHttpUpstream })
) {
upstreamUrl = savedUpstream.replace(/\/+$/, '');
}
if (saved.switched === true) {
lsSwitched = true;
}
} catch {
// 忽略损坏的状态快照
}
}
function persistProxyStateSnapshot(switchedFlag) {
if (!stateFilePath || typeof saveJsonFn !== 'function') return;
try {
saveJsonFn(stateFilePath, {
switched: Boolean(switchedFlag),
localPort: preferredPort > 0 ? preferredPort : undefined,
localUrl: switchedFlag && localUrl ? localUrl : undefined,
upstreamUrl: upstreamUrl || DEFAULT_UPSTREAM_CLOUDCODE_URL,
updatedAtMs: Date.now(),
});
} catch {
// 忽略持久化状态异常
}
}
function destroyActiveUpstreamAgent() {
if (!activeAgentEntry) return;
const prevAgent = activeAgentEntry.agent;
activeAgentEntry = null;
try {
prevAgent?.destroy?.();
} catch {
// 忽略连接池销毁异常
}
}
function getPooledUpstreamAgent(mods, isUpstreamHttps, upstreamHost, upstreamPort, proxyUrl) {
const cleanProxy = isUpstreamHttps ? String(proxyUrl || '') : '';
const key = `${isUpstreamHttps ? 'https' : 'http'}|${upstreamHost}:${upstreamPort}|${cleanProxy || 'direct'}`;
if (activeAgentEntry && activeAgentEntry.key === key) {
return activeAgentEntry.agent;
}
destroyActiveUpstreamAgent();
const baseAgentOpts = {
keepAlive: true,
keepAliveMsecs: 10_000,
maxSockets: 32,
maxFreeSockets: 4,
timeout: CC_PROXY_AGENT_FREE_SOCKET_TIMEOUT_MS,
...(isUpstreamHttps && upstreamTlsOptions ? upstreamTlsOptions : {}),
};
let agent;
if (isUpstreamHttps && cleanProxy) {
class CcProxyTunnelHttpsAgent extends mods.https.Agent {
createConnection(_opts, callback) {
openCcProxyTunnelSocket(mods, upstreamHost, upstreamPort, cleanProxy, {
timeoutMs: tunnelTimeoutMs,
tlsOptions: upstreamTlsOptions,
}).then(
(tlsSock) => callback(null, tlsSock),
(err) => callback(err)
);
return null;
}
}
agent = new CcProxyTunnelHttpsAgent(baseAgentOpts);
} else {
const AgentCtor = isUpstreamHttps ? mods.https.Agent : mods.http.Agent;
agent = new AgentCtor(baseAgentOpts);
}
activeAgentEntry = { key, agent };
return agent;
}
function getStatus() {
return {
...status,
@@ -523,7 +974,8 @@ export function createCloudCodeProxyController({
}
let proxyUrl = '';
if (typeof detectProxyFn === 'function') {
proxyUrl = String((await detectProxyFn(targetHostname)) || '').trim();
const rawDetected = String((await detectProxyFn(targetHostname)) || '').trim();
proxyUrl = normalizeCcProxyCandidateUrl(rawDetected);
} else {
proxyUrl = await detectSystemHttpsProxy(targetHostname);
}
@@ -532,6 +984,7 @@ export function createCloudCodeProxyController({
}
async function closeProxyServer() {
destroyActiveUpstreamAgent();
const srv = server;
server = null;
localUrl = '';
@@ -552,7 +1005,8 @@ export function createCloudCodeProxyController({
async function ensureProxyServerStarted() {
if (server && localUrl) return localUrl;
const { http, https, tls, zlib } = await loadCcProxyNodeModules();
const mods = await loadCcProxyNodeModules();
const { http, https, zlib } = mods;
const targetBase = await resolveUpstreamUrl();
const upstreamParsed = new URL(targetBase);
const isUpstreamHttps = upstreamParsed.protocol === 'https:';
@@ -561,38 +1015,79 @@ export function createCloudCodeProxyController({
const srv = http.createServer(async (req, res) => {
const reqUrl = req.url || '/';
const isFetchModels = reqUrl.includes('fetchAvailableModels');
let clientAborted = false;
let activeUpReq = null;
let activeUpRes = null;
const abortUpstreamOnClientDisconnect = () => {
if (res.writableEnded) return;
clientAborted = true;
try {
activeUpRes?.destroy();
} catch {}
try {
activeUpReq?.destroy();
} catch {}
};
req.once('aborted', abortUpstreamOnClientDisconnect);
res.once('close', abortUpstreamOnClientDisconnect);
req.on('error', abortUpstreamOnClientDisconnect);
res.on('error', abortUpstreamOnClientDisconnect);
try {
const fwdHeaders = { ...req.headers, host: upstreamParsed.host };
for (const hopKey of CC_PROXY_HOP_BY_HOP_HEADERS) {
delete fwdHeaders[hopKey];
}
if (isFetchModels) {
delete fwdHeaders['accept-encoding'];
}
let customSocket = null;
if (isUpstreamHttps) {
const proxyUrl = await resolveSystemProxyForHost(upstreamParsed.hostname);
if (proxyUrl) {
customSocket = await openCcProxyTunnelSocket(
http,
tls,
upstreamParsed.hostname,
upstreamPort,
proxyUrl
);
}
const proxyUrl = isUpstreamHttps
? await resolveSystemProxyForHost(upstreamParsed.hostname)
: '';
if (clientAborted || req.destroyed || res.destroyed || res.writableEnded) {
return;
}
const agent = getPooledUpstreamAgent(
mods,
isUpstreamHttps,
upstreamParsed.hostname,
upstreamPort,
proxyUrl
);
const upOpts = {
hostname: upstreamParsed.hostname,
port: upstreamPort,
path: reqUrl,
method: req.method,
headers: fwdHeaders,
...(customSocket ? { agent: false, createConnection: () => customSocket } : {}),
agent,
...(isUpstreamHttps && upstreamTlsOptions ? upstreamTlsOptions : {}),
};
req.setTimeout?.(0);
const transport = isUpstreamHttps ? https : http;
const upReq = transport.request(upOpts, (upRes) => {
activeUpRes = upRes;
upRes.on('error', (err) => {
if (clientAborted || res.destroyed || res.writableEnded) return;
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Upstream stream error: ${err.message}`);
} else {
res.destroy();
}
});
if (clientAborted || res.destroyed || res.writableEnded) {
upRes.destroy();
return;
}
if (!isFetchModels || Number(upRes.statusCode || 0) !== 200) {
res.writeHead(upRes.statusCode || 502, upRes.headers);
const passthroughHeaders = { ...upRes.headers };
for (const hopKey of CC_PROXY_HOP_BY_HOP_HEADERS) {
delete passthroughHeaders[hopKey];
}
res.writeHead(upRes.statusCode || 502, passthroughHeaders);
res.flushHeaders?.();
upRes.pipe(res);
return;
@@ -600,9 +1095,13 @@ export function createCloudCodeProxyController({
const chunks = [];
upRes.on('data', (chunk) => chunks.push(chunk));
upRes.on('end', () => {
if (clientAborted || res.destroyed || res.writableEnded) return;
const rawBuf = Buffer.concat(chunks);
let outBuf = rawBuf;
const outHeaders = { ...upRes.headers };
for (const hopKey of CC_PROXY_HOP_BY_HOP_HEADERS) {
delete outHeaders[hopKey];
}
try {
const plain = decompressCcProxyBody(zlib, rawBuf, upRes.headers['content-encoding']);
const parsed = JSON.parse(plain.toString('utf8'));
@@ -627,52 +1126,86 @@ export function createCloudCodeProxyController({
res.writeHead(upRes.statusCode || 200, outHeaders);
res.end(outBuf);
});
upRes.on('error', (err) => {
if (!res.headersSent) res.writeHead(502);
res.end(`Upstream stream error: ${err.message}`);
});
});
activeUpReq = upReq;
upReq.setTimeout?.(0);
upReq.on('error', (err) => {
if (!res.headersSent) res.writeHead(502);
res.end(`Proxy upstream error: ${err.message}`);
if (clientAborted || res.destroyed || res.writableEnded) return;
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Proxy upstream error: ${err.message}`);
} else {
res.destroy();
}
});
req.pipe(upReq);
} catch (err) {
if (!res.headersSent) res.writeHead(502);
res.end(`Proxy setup error: ${err.message}`);
if (clientAborted || res.destroyed || res.writableEnded) return;
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Proxy setup error: ${err.message}`);
} else {
res.destroy();
}
}
});
await new Promise((resolve, reject) => {
srv.once('error', reject);
srv.listen(0, '127.0.0.1', () => {
srv.off('error', reject);
resolve();
const tryListenOnPort = (candidatePort) =>
new Promise((resolve, reject) => {
const onErr = (err) => {
srv.off('listening', onListening);
reject(err);
};
const onListening = () => {
srv.off('error', onErr);
resolve();
};
srv.once('error', onErr);
srv.once('listening', onListening);
srv.listen(candidatePort, '127.0.0.1');
});
});
if (preferredPort > 0) {
try {
await tryListenOnPort(preferredPort);
} catch {
await tryListenOnPort(0);
}
} else {
await tryListenOnPort(0);
}
srv.unref?.();
const addrInfo = srv.address();
const port = typeof addrInfo === 'object' && addrInfo ? Number(addrInfo.port || 0) : 0;
if (port > 0) {
preferredPort = port;
}
server = srv;
localUrl = `http://127.0.0.1:${port}`;
return localUrl;
}
async function restoreLsCloudCodeUrl() {
if (!lsSwitched) return;
lsSwitched = false;
async function restoreLsCloudCodeUrl({ timeoutMs = 4000, clearEvenOnFailure = false } = {}) {
if (!lsSwitched) return true;
appliedSig = '';
const targetRestore = upstreamUrl || DEFAULT_UPSTREAM_CLOUDCODE_URL;
const targetRestore = (await resolveUpstreamUrl().catch(() => '')) || DEFAULT_UPSTREAM_CLOUDCODE_URL;
try {
await callRpcFn('SetCloudCodeURL', { url: targetRestore }, 4000);
await callRpcFn('SetCloudCodeURL', { url: targetRestore }, timeoutMs);
lsSwitched = false;
persistProxyStateSnapshot(false);
return true;
} catch {
// 忽略 LS 已退出或暂不可达时的还原异常
if (clearEvenOnFailure) {
lsSwitched = false;
}
return false;
}
}
async function reconcileInternal({ enabled = false, rulesByModelId = {}, initialCatalogModels = null } = {}) {
hydratePersistedStateOnce();
if (initialCatalogModels) {
seedUpstreamDefaultsFromCatalog(initialCatalogModels);
}
@@ -687,11 +1220,9 @@ export function createCloudCodeProxyController({
activeRules = {};
lastFailedSig = '';
lastErrorAtMs = 0;
appliedSig = '';
if (lsSwitched && hasUsableLs) {
await restoreLsCloudCodeUrl();
} else {
lsSwitched = false;
appliedSig = '';
await restoreLsCloudCodeUrl({ timeoutMs: 3000 });
}
await closeProxyServer();
status = {
@@ -742,11 +1273,13 @@ export function createCloudCodeProxyController({
try {
const targetUpstream = await resolveUpstreamUrl();
const listenUrl = await ensureProxyServerStarted();
persistProxyStateSnapshot(true);
await callRpcFn('SetCloudCodeURL', { url: listenUrl }, 5000);
lsSwitched = true;
appliedSig = desiredSig;
lastFailedSig = '';
lastErrorAtMs = 0;
persistProxyStateSnapshot(true);
status = {
state: 'active',
active: true,
@@ -761,6 +1294,7 @@ export function createCloudCodeProxyController({
lastFailedSig = desiredSig;
lastErrorAtMs = Date.now();
if (!lsSwitched) {
persistProxyStateSnapshot(false);
await closeProxyServer();
}
status = {
@@ -785,17 +1319,18 @@ export function createCloudCodeProxyController({
function stop() {
syncChain = syncChain
.then(async () => {
hydratePersistedStateOnce();
activeRules = {};
lastFailedSig = '';
lastErrorAtMs = 0;
appliedSig = '';
const ep = getEndpointFn() || {};
const hasUsableLs =
Boolean(ep.baseUrl) && (allowTestEndpoint || String(ep.addr || '') !== 'test.invalid');
if (lsSwitched && hasUsableLs) {
await restoreLsCloudCodeUrl();
await restoreLsCloudCodeUrl({ timeoutMs: 900, clearEvenOnFailure: true });
} else {
lsSwitched = false;
appliedSig = '';
}
await closeProxyServer();
status = {
@@ -823,11 +1358,21 @@ export function createCloudCodeProxyController({
};
}
function resolveDefaultCloudCodeProxyStatePath() {
const normDir = String(DATA_DIR || '').replace(/\\/g, '/');
if (!normDir || normDir.startsWith('/test/') || normDir.startsWith('/test-home/')) {
return '';
}
return join(DATA_DIR, 'cloudcode-proxy-state.json');
}
let defaultCloudCodeProxyController = null;
export function getDefaultCloudCodeProxy() {
if (!defaultCloudCodeProxyController) {
defaultCloudCodeProxyController = createCloudCodeProxyController();
defaultCloudCodeProxyController = createCloudCodeProxyController({
stateFilePath: resolveDefaultCloudCodeProxyStatePath(),
});
}
return defaultCloudCodeProxyController;
}
+28 -5
View File
@@ -165,9 +165,11 @@ function resolveDefaultDataDir() {
export const DATA_DIR = resolveDefaultDataDir();
export const SETTINGS_FILE = join(DATA_DIR, 'settings.json');
export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json');
export const TRAJECTORY_DB_FILE = join(DATA_DIR, 'trajectory_store.sqlite');
export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json');
export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json');
export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json');
export const ACCOUNT_QUOTA_HISTORY_FILE = join(DATA_DIR, 'account_quota_history.json');
/**
* 本地对话记录目录、脑图日志目录、守护发现目录与跨端深层统计缓存路径候选列表(联合覆盖 Desktop / CLI / IDE)。
@@ -380,7 +382,7 @@ export function computeRuntimeCodeVersion(options = {}) {
join(HERE, 'trajectory-metrics.mjs'),
LOCAL_CATALOG_FILE,
];
for (const subDir of ['shared', 'backend']) {
for (const subDir of ['shared', 'backend', join('backend', 'host-i18n')]) {
const absDir = join(HERE, subDir);
try {
if (existsSync(absDir)) {
@@ -417,15 +419,28 @@ export function computeRuntimeCodeVersion(options = {}) {
/**
* 本机内存态轨迹步骤缓存容器(委托 `createTrajectoryCacheStore`,首次读取时惰性加载历史缓存)。
*/
const isUnscopedHostTestRunner = Boolean(
typeof process !== 'undefined' &&
process?.env?.NODE_TEST_CONTEXT &&
!process?.env?.USAGE_MONITOR_APP_DATA_DIR &&
!process?.env?.ANTIGRAVITY_APP_DATA_DIR &&
!process?.env?.ANTIGRAVITY_GEMINI_DIR
);
const localTrajectoryCacheStore = createTrajectoryCacheStore({
cacheFilePath: CACHE_FILE,
cacheFilePath: isUnscopedHostTestRunner ? '' : CACHE_FILE,
sqliteFilePath: isUnscopedHostTestRunner ? '' : TRAJECTORY_DB_FILE,
loadJsonFn: loadJson,
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
shouldBypassThrottleFn: (allowThrottleInTest) =>
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
registerExitHook: true,
registerExitHook: !isUnscopedHostTestRunner,
});
export function getLocalTrajectoryCacheStore() {
return localTrajectoryCacheStore;
}
export function getCachedTrajectory(cascadeId) {
return localTrajectoryCacheStore.getCachedTrajectory(cascadeId);
}
@@ -434,6 +449,14 @@ export function getCachedTrajectoryEntryByLower(cascadeId) {
return localTrajectoryCacheStore.getCachedTrajectoryEntryByLower(cascadeId);
}
export function getHydratedTrajectory(cascadeId) {
return localTrajectoryCacheStore.getHydratedTrajectory(cascadeId);
}
export function getHydratedTrajectoryEntryByLower(cascadeId) {
return localTrajectoryCacheStore.getHydratedTrajectoryEntryByLower(cascadeId);
}
export function listCachedTrajectoryEntries() {
return localTrajectoryCacheStore.listCachedTrajectoryEntries();
}
@@ -518,8 +541,8 @@ export const pluginUpdateState = {
*
* @returns {boolean} 是否成功写回空白缓存文件
*/
export function clearRuntimeCaches() {
if (!localTrajectoryCacheStore.clearCache()) return false;
export function clearRuntimeCaches(options = {}) {
if (!localTrajectoryCacheStore.clearCache(options)) return false;
externalDeepStatsMemo.sig = '';
externalDeepStatsMemo.convos.clear();
localSummaryMemo.sig = '';
+43 -13
View File
@@ -18,6 +18,8 @@ import {
flushTrajectoryCacheNow,
getCachedTrajectory,
getCachedTrajectoryEntryByLower,
getHydratedTrajectory,
getHydratedTrajectoryEntryByLower,
hasPendingTrajectoryCacheSave,
listCachedTrajectoryEntries,
loadJson,
@@ -108,8 +110,8 @@ export function buildRemoteEndpointIdentity({ origin = '', hostLabel = '', stabl
};
}
function buildRemoteCacheFilePath(stableHostKey) {
if (!stableHostKey) return '';
function buildRemoteCacheFilePaths(stableHostKey) {
if (!stableHostKey) return { cacheFilePath: '', sqliteFilePath: '' };
const safePrefix = stableHostKey
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '_')
@@ -117,7 +119,10 @@ function buildRemoteCacheFilePath(stableHostKey) {
.slice(0, 32) || 'ssh';
const hash = createHash('sha256').update(stableHostKey.toLowerCase()).digest('hex').slice(0, 12);
// 前缀加上 `ssh-` 可彻底规避 Windows 保留文件名(CON/NUL/PRN/AUX/COM1 等)
return join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`);
return {
cacheFilePath: join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.json`),
sqliteFilePath: join(ENDPOINT_REMOTE_CACHE_DIR, `ssh-${safePrefix}-${hash}.sqlite`),
};
}
function createRemoteQuotaCache() {
@@ -131,9 +136,10 @@ function createRemoteQuotaCache() {
};
}
function createRemoteEndpointStore(cacheFilePath) {
function createRemoteEndpointStore(cacheFilePath, sqliteFilePath = '') {
return createTrajectoryCacheStore({
cacheFilePath,
sqliteFilePath,
loadJsonFn: loadJson,
shouldBypassThrottleFn: (allowThrottleInTest) =>
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
@@ -175,9 +181,9 @@ export function registerRemoteEndpoint(info = {}) {
let entry = remoteEndpointRegistry.get(identity.id);
if (!entry) {
const cacheFilePath = identity.hasStableHostKey
? buildRemoteCacheFilePath(identity.stableHostKey)
: '';
const { cacheFilePath, sqliteFilePath } = identity.hasStableHostKey
? buildRemoteCacheFilePaths(identity.stableHostKey)
: { cacheFilePath: '', sqliteFilePath: '' };
entry = {
id: identity.id,
instanceId: ++nextEndpointInstanceId,
@@ -192,11 +198,12 @@ export function registerRemoteEndpoint(info = {}) {
lastSeenMs: nowMs,
preferTier2UntilMs: 0,
inFlightCount: 0,
store: createRemoteEndpointStore(cacheFilePath),
store: createRemoteEndpointStore(cacheFilePath, sqliteFilePath),
quotaSummaryCache: createRemoteQuotaCache(),
contextModelCatalog: null,
failedFetchCooldownMap: new Map(),
liveActivityMemo: new Map(),
lastKnownLiveCascadeIds: null,
};
remoteEndpointRegistry.set(identity.id, entry);
} else {
@@ -315,6 +322,8 @@ export function getEndpointCacheStore(endpointOrId = null) {
endpointId: LOCAL_ENDPOINT_ID,
getCachedTrajectory,
getCachedTrajectoryEntryByLower,
getHydratedTrajectory,
getHydratedTrajectoryEntryByLower,
listCachedTrajectoryEntries,
setCachedTrajectory,
removeCachedTrajectory,
@@ -344,15 +353,21 @@ export function getEndpointQuotaCache(endpointOrId = null) {
* 清空目标远端端点的内存与持久化缓存(包含配额、模型目录、扫描冷却表与实时活动缓存)。
*
* @param {string} endpointId
* @param {{ liveCascadeIds?: Iterable<string> | null }} [options]
* @returns {boolean}
*/
export function clearRemoteEndpointCaches(endpointId) {
export function clearRemoteEndpointCaches(endpointId, options = {}) {
const ep = getRegisteredRemoteEndpoint(endpointId);
if (!ep) return false;
const ok = ep.store.clearCache();
const liveCascadeIds =
options && Object.prototype.hasOwnProperty.call(options, 'liveCascadeIds')
? options.liveCascadeIds
: ep.lastKnownLiveCascadeIds;
const ok = ep.store.clearCache({ liveCascadeIds });
if (!ok) return false;
ep.failedFetchCooldownMap.clear();
ep.liveActivityMemo.clear();
ep.lastKnownLiveCascadeIds = null;
ep.contextModelCatalog = null;
ep.quotaSummaryCache.ts = 0;
ep.quotaSummaryCache.lastAttemptTs = 0;
@@ -461,13 +476,28 @@ export function getRemoteWindowRpcInvoker() {
return registeredWindowRpcInvoker;
}
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
process.once('exit', () => {
for (const ep of remoteEndpointRegistry.values()) {
export function flushAllEndpointCachesNow() {
try {
if (hasPendingTrajectoryCacheSave()) {
flushTrajectoryCacheNow();
}
} catch {
// 忽略关闭阶段本机刷盘异常
}
for (const ep of remoteEndpointRegistry.values()) {
try {
if (ep.store.hasPendingTrajectoryCacheSave()) {
ep.store.flushTrajectoryCacheNow();
}
ep.store.cancelFlushTimer();
} catch {
// 忽略关闭阶段远端端点刷盘异常
}
}
}
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
process.once('exit', () => {
flushAllEndpointCachesNow();
});
}
+3 -3
View File
@@ -1,7 +1,7 @@
/**
* @fileoverview 本机安全文本文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。
* 仅允许导出受控白名单文本扩展名(.json / .csv / .md / .txt),严格清洗文件名防止路径穿越,
* 并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。
* @fileoverview 本机安全文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。
* 仅允许导出受控白名单扩展名(.json / .csv / .md / .txt / .xlsx,含 UTF-8 文本和 Base64 二进制工作簿),
* 严格清洗文件名防止路径穿越,并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。
*/
import { spawn } from 'node:child_process';
@@ -0,0 +1,254 @@
/**
* @fileoverview 受控的 Antigravity 宿主语言包 HTTPS 拉取器。
*
* - 严格限制仅允许官方白名单域名(`raw.githubusercontent.com` / `cdn.jsdelivr.net`);
* - 复用 `cloudcode-proxy.mjs` 的系统 HTTPS 代理检测与 CONNECT 隧道,兼容代理环境;
* - 主源超时或 5xx/网络失败时自动回退至 jsDelivr CDN 镜像;
* - 响应体严格限制大小上限,避免异常大载荷撑爆内存。
*/
import { detectSystemHttpsProxy, openCcProxyTunnelSocket } from '../cloudcode-proxy.mjs';
export const HOST_I18N_ALLOWED_HOSTS = Object.freeze([
'raw.githubusercontent.com',
'cdn.jsdelivr.net',
]);
export const HOST_I18N_MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
export const HOST_I18N_DEFAULT_TIMEOUT_MS = 8_000;
const HOST_I18N_MAX_REDIRECTS = 3;
let hostI18nNetModulesPromise = null;
async function loadHostI18nNetModules() {
if (!hostI18nNetModulesPromise) {
hostI18nNetModulesPromise = Promise.all([
import('node:http'),
import('node:https'),
import('node:net'),
import('node:tls'),
]).then(([httpMod, httpsMod, netMod, tlsMod]) => ({
http: httpMod.default || httpMod,
https: httpsMod.default || httpsMod,
net: netMod.default || netMod,
tls: tlsMod.default || tlsMod,
}));
}
return hostI18nNetModulesPromise;
}
/**
* 校验下载 URL 是否属于允许的 HTTPS 白名单源。
*
* @param {string} rawUrl
* @returns {URL}
*/
export function assertAllowedHostI18nUrl(rawUrl) {
let parsed;
try {
parsed = new URL(String(rawUrl || '').trim());
} catch {
throw new Error('Invalid host-i18n download URL');
}
if (parsed.protocol !== 'https:') {
throw new Error(`Unsupported host-i18n protocol: ${parsed.protocol}`);
}
const host = parsed.hostname.toLowerCase();
if (!HOST_I18N_ALLOWED_HOSTS.includes(host)) {
throw new Error(`Disallowed host-i18n host: ${host}`);
}
return parsed;
}
/**
* 通过原生 `https` + 系统 HTTPS 代理隧道拉取单个白名单 URL 的 UTF-8 文本。
*
* @param {string} rawUrl
* @param {{ timeoutMs?: number, maxBytes?: number, redirectCount?: number }} [options]
* @returns {Promise<{ ok: boolean, status: number, text: string, url: string }>}
*/
async function fetchAllowedUrlViaNodeHttps(
rawUrl,
{
timeoutMs = HOST_I18N_DEFAULT_TIMEOUT_MS,
maxBytes = HOST_I18N_MAX_RESPONSE_BYTES,
redirectCount = 0,
} = {}
) {
const target = assertAllowedHostI18nUrl(rawUrl);
const mods = await loadHostI18nNetModules();
const { http, https, net, tls } = mods;
const proxy = await detectSystemHttpsProxy(target.hostname).catch(() => null);
const socket = proxy
? await openCcProxyTunnelSocket(
{ http, https, net, tls },
target.hostname,
Number(target.port || 443),
proxy,
{ timeoutMs: Math.min(timeoutMs, 5_000) }
)
: null;
let socketConsumed = false;
const agent = socket ? new https.Agent({ keepAlive: false }) : null;
if (agent) {
agent.createConnection = () => {
socketConsumed = true;
return socket;
};
}
return new Promise((resolve, reject) => {
let settled = false;
const finish = (ok, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (!socketConsumed) {
try {
socket?.destroy();
} catch {
// 忽略关闭异常
}
}
try {
agent?.destroy();
} catch {
// 忽略关闭异常
}
if (ok) resolve(value);
else reject(value);
};
const req = https.request(
target,
{
method: 'GET',
headers: {
Accept: 'application/json, text/plain;q=0.9',
'Cache-Control': 'no-cache',
'User-Agent': 'antigravity-usage-monitor-host-i18n/1.0',
},
...(agent ? { agent } : {}),
},
(res) => {
const status = Number(res.statusCode || 0);
if (
(status === 301 || status === 302 || status === 307 || status === 308) &&
res.headers?.location &&
redirectCount < HOST_I18N_MAX_REDIRECTS
) {
res.resume();
let nextUrl = '';
try {
nextUrl = new URL(String(res.headers.location), target).href;
assertAllowedHostI18nUrl(nextUrl);
} catch (err) {
finish(false, err);
return;
}
clearTimeout(timer);
fetchAllowedUrlViaNodeHttps(nextUrl, {
timeoutMs,
maxBytes,
redirectCount: redirectCount + 1,
}).then(
(val) => finish(true, val),
(err) => finish(false, err)
);
return;
}
const chunks = [];
let totalBytes = 0;
res.on('data', (chunk) => {
totalBytes += chunk.length;
if (totalBytes > maxBytes) {
req.destroy(new Error(`host-i18n response exceeds ${maxBytes} bytes`));
return;
}
chunks.push(chunk);
});
res.on('error', (err) => finish(false, err));
res.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
finish(true, {
ok: status >= 200 && status < 300,
status,
text,
url: target.href,
});
});
}
);
const timer = setTimeout(() => {
req.destroy(new Error(`host-i18n request timeout after ${timeoutMs}ms`));
}, timeoutMs);
timer.unref?.();
req.on('error', (err) => finish(false, err));
req.end();
});
}
/**
* 依次尝试多个白名单候选 URL(主源 GitHub Raw -> 备用 jsDelivr CDN),返回首个成功的文本响应。
*
* @param {string[]} urls
* @param {{
* timeoutMs?: number,
* maxBytes?: number,
* fetchImpl?: ((url: string, init?: object) => Promise<{ ok: boolean, status?: number, text: () => Promise<string> }>)|null,
* }} [options]
* @returns {Promise<{ text: string, url: string, status: number }>}
*/
export async function fetchHostI18nTextWithFallback(
urls,
{
timeoutMs = HOST_I18N_DEFAULT_TIMEOUT_MS,
maxBytes = HOST_I18N_MAX_RESPONSE_BYTES,
fetchImpl = null,
} = {}
) {
const list = Array.isArray(urls) ? urls.filter(Boolean) : [];
if (list.length === 0) {
throw new Error('No host-i18n candidate URLs configured');
}
const errors = [];
for (const rawUrl of list) {
const validated = assertAllowedHostI18nUrl(rawUrl);
try {
if (typeof fetchImpl === 'function') {
const res = await fetchImpl(validated.href, {
method: 'GET',
headers: { Accept: 'application/json', 'Cache-Control': 'no-cache' },
signal:
typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
? AbortSignal.timeout(timeoutMs)
: undefined,
});
const status = Number(res?.status || (res?.ok ? 200 : 500));
if (!res?.ok) {
throw new Error(`HTTP ${status}`);
}
const text = await res.text();
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
throw new Error(`host-i18n response exceeds ${maxBytes} bytes`);
}
return { text, url: validated.href, status };
}
const res = await fetchAllowedUrlViaNodeHttps(validated.href, { timeoutMs, maxBytes });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return { text: res.text, url: res.url, status: res.status };
} catch (err) {
errors.push(`${validated.hostname}: ${err?.message || 'request failed'}`);
}
}
throw new Error(`Failed to fetch host-i18n asset (${errors.join('; ')})`);
}
+209
View File
@@ -0,0 +1,209 @@
/**
* @fileoverview Antigravity 宿主多语言子系统统一门面 (`backend/host-i18n/index.mjs`)。
*
* 主程序其余模块(`window-bridge.mjs`、`api-actions.mjs`)仅通过本门面与宿主翻译子系统交互,
* 保持极薄的集成边界与完整可剥离性。
*/
import {
HOST_I18N_DEFAULT_DEPTH,
HOST_I18N_OFF_LOCALE,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../shared/host-i18n-protocol.mjs';
import { createHostI18nPackManager } from './pack-manager.mjs';
import {
createHostI18nApplyExpression,
createHostI18nCollectExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
} from './runtime-translator.mjs';
export {
HOST_I18N_DEFAULT_DEPTH,
HOST_I18N_OFF_LOCALE,
createHostI18nApplyExpression,
createHostI18nCollectExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
createHostI18nPackManager,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
};
let defaultHostI18nManager = null;
/**
* 获取进程级默认宿主语言包管理器单例。
*/
export function getDefaultHostI18nManager() {
if (!defaultHostI18nManager) {
defaultHostI18nManager = createHostI18nPackManager();
}
return defaultHostI18nManager;
}
/**
* 供 `window-bridge.mjs` 读取当前宿主翻译是否激活及按需下发描述。
*/
export function getHostI18nBridgeDescriptor() {
return getDefaultHostI18nManager().getActiveBridgeDescriptor();
}
/**
* 判断宿主语言翻译当前是否处于激活状态(用于独立保活 CDP 调试端口)。
*
* @returns {boolean}
*/
export function isHostI18nActiveForBridge() {
return Boolean(getHostI18nBridgeDescriptor()?.active);
}
/**
* 处理 `GET /api/host-i18n`:返回当前状态、已安装包与远端语言清单(必要时静默拉取缓存清单)。
*
* @param {{ bridgeStatus?: object|null, manager?: ReturnType<typeof createHostI18nPackManager> }} [options]
*/
export async function handleHostI18nGetRequest({ bridgeStatus = null, manager = null } = {}) {
const mgr = manager || getDefaultHostI18nManager();
const manifestResult = await mgr.refreshManifest({ force: false });
return {
ok: true,
...mgr.getStatusSnapshot({ manifestResult, bridgeStatus }),
};
}
/**
* 处理 `POST /api/host-i18n` 控制指令:
* - `refresh_manifest`:强制刷新仓库语言包清单
* - `select`:选择语言(未下载时自动拉取并校验 SHA-256 后生效,传 `'off'` 即关闭并还原)
* - `set_depth`:在 `'light'` / `'deep'` 间零网络热切换
* - `install` / `update`:显式下载或更新指定语言包
* - `remove`:删除指定语言的本地缓存包
* - `collect_untranslated`:按需采集当前打开宿主页面中未翻译的英文 UI 短语
*
* @param {object} body
* @param {{
* bridgeStatus?: object|null,
* onChanged?: (() => Promise<any>|any)|null,
* collectFromTargets?: (() => Promise<{ targets: number, items: Array<{ text: string, kind: string, count: number }> }>)|null,
* manager?: ReturnType<typeof createHostI18nPackManager>|null,
* }} [options]
*/
export async function handleHostI18nPostAction(
body = {},
{ bridgeStatus = null, onChanged = null, collectFromTargets = null, manager = null } = {}
) {
const mgr = manager || getDefaultHostI18nManager();
const action = String(body?.action || '').trim().toLowerCase();
try {
if (action === 'refresh_manifest') {
const manifestResult = await mgr.refreshManifest({ force: true });
return {
status: 200,
payload: {
ok: manifestResult.ok,
...(manifestResult.error ? { error: manifestResult.error } : {}),
...mgr.getStatusSnapshot({ manifestResult, bridgeStatus }),
},
};
}
if (action === 'select') {
const res = await mgr.selectLanguage({
locale: body?.locale,
depth: body?.depth,
});
await Promise.resolve(onChanged?.()).catch(() => {});
return {
status: 200,
payload: {
ok: true,
downloaded: Boolean(res.downloaded),
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'set_depth') {
mgr.setDepth(body?.depth);
await Promise.resolve(onChanged?.()).catch(() => {});
return {
status: 200,
payload: {
ok: true,
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'install' || action === 'update') {
const res = await mgr.installPack(body?.locale, { forceManifestRefresh: true });
const cur = mgr.loadState();
if (cur.locale === res.locale) {
await Promise.resolve(onChanged?.()).catch(() => {});
}
return {
status: 200,
payload: {
ok: true,
installed: res,
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'remove') {
const res = mgr.removePack(body?.locale);
await Promise.resolve(onChanged?.()).catch(() => {});
return {
status: res.ok ? 200 : 400,
payload: {
ok: res.ok,
...(res.error ? { error: res.error } : {}),
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'collect_untranslated') {
if (typeof collectFromTargets !== 'function') {
return {
status: 400,
payload: { ok: false, error: 'collector_unavailable', count: 0, items: [], template: { base: {} } },
};
}
const collected = await collectFromTargets();
const items = Array.isArray(collected?.items) ? collected.items : [];
const templateBase = {};
for (const item of items) {
if (item?.text) templateBase[item.text] = '';
}
return {
status: 200,
payload: {
ok: true,
targets: Number(collected?.targets || 0),
count: items.length,
items,
template: { base: templateBase },
},
};
}
return {
status: 400,
payload: { ok: false, error: `Unknown host-i18n action: ${action || '(empty)'}` },
};
} catch (err) {
return {
status: 500,
payload: {
ok: false,
error: err?.message || 'Host I18n action failed',
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
}
@@ -0,0 +1,799 @@
/**
* @fileoverview 独立解耦的 Antigravity 宿主语言包状态、远端清单同步、SHA-256 校验与本地缓存管理器。
*
* 持久化边界:
* 全部落盘在 `DATA_DIR/host-i18n/` 下,与主插件 `settings.json` 及监控遥测状态完全隔离:
* - `state.json` :当前选中的 `locale`(`'off'` 或 BCP-47)与 `depth`(`'light' | 'deep'`)
* - `manifest-cache.json` :远端仓库可用语言包清单缓存
* - `installed-meta.json` :已下载语言包元信息索引
* - `packs/<locale>.json` :通过 SHA-256 校验后的单语言分层语言包本体
*/
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
import { join } from 'node:path';
import {
HOST_I18N_DEFAULT_DEPTH,
HOST_I18N_OFF_LOCALE,
HOST_I18N_SCHEMA_VERSION,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../shared/host-i18n-protocol.mjs';
import { DATA_DIR, OFFICIAL_GITHUB_REPO, detectCustomGitForkRepo } from '../config.mjs';
import { writeJsonAtomicSync, writeTextFileAtomicSync } from '../fs-atomic.mjs';
import { isPlainObject } from '../http-helpers.mjs';
import { fetchHostI18nTextWithFallback } from './http-fetch.mjs';
export const DEFAULT_HOST_I18N_REF = 'main';
export const HOST_I18N_MANIFEST_TTL_MS = 6 * 3600 * 1000;
const HOST_I18N_SHA256_RE = /^[a-f0-9]{64}$/i;
const HOST_I18N_ALLOWED_REGEX_FLAGS_RE = /^[i]?$/;
const HOST_I18N_UNSAFE_REGEX_RE = /\([^)]*[+*][^)]*\)[+*{]/;
function hostI18nSha256(text) {
return createHash('sha256').update(String(text || ''), 'utf8').digest('hex');
}
function hostI18nResolveStoragePaths(baseDataDir = DATA_DIR) {
const rootDir = join(baseDataDir, 'host-i18n');
return {
rootDir,
stateFile: join(rootDir, 'state.json'),
manifestCacheFile: join(rootDir, 'manifest-cache.json'),
installedMetaFile: join(rootDir, 'installed-meta.json'),
packsDir: join(rootDir, 'packs'),
};
}
function hostI18nResolveRepoAndRef(options = {}) {
const envRepo = String(process?.env?.USAGE_MONITOR_HOST_I18N_REPO || '').trim();
const repo =
String(options?.repo || '').trim() ||
envRepo ||
detectCustomGitForkRepo() ||
OFFICIAL_GITHUB_REPO;
const envRef = String(process?.env?.USAGE_MONITOR_HOST_I18N_REF || '').trim();
const ref = String(options?.ref || '').trim() || envRef || DEFAULT_HOST_I18N_REF;
const localDir =
String(options?.localSourceDir || '').trim() ||
String(process?.env?.USAGE_MONITOR_HOST_I18N_LOCAL_DIR || '').trim();
return { repo, ref, localDir };
}
/**
* 构建仓库内语言包文件的主/备下载 URL(GitHub Raw 主源 + jsDelivr 镜像兜底)。
*
* @param {string} relPath 如 `'manifest.json'` 或 `'packs/zh-CN.json'`
* @param {{ repo?: string, ref?: string }} [options]
* @returns {string[]}
*/
export function buildHostI18nAssetUrls(relPath, options = {}) {
const cleanRel = String(relPath || '')
.replace(/\\/g, '/')
.replace(/^\/+/, '');
if (!cleanRel || cleanRel.includes('..')) {
throw new Error(`Invalid host-i18n relative asset path: ${relPath}`);
}
const { repo, ref } = hostI18nResolveRepoAndRef(options);
return [
`https://raw.githubusercontent.com/${repo}/${ref}/host-i18n/dist/${cleanRel}`,
`https://cdn.jsdelivr.net/gh/${repo}@${ref}/host-i18n/dist/${cleanRel}`,
];
}
function sanitizeHostI18nExactMap(rawMap) {
const out = {};
if (!isPlainObject(rawMap)) return out;
for (const [k, v] of Object.entries(rawMap)) {
const key = String(k || '').replace(/\r\n/g, '\n').trim();
const val = typeof v === 'string' ? v.replace(/\r\n/g, '\n').trim() : '';
if (!key || !val || key.length > 1000 || val.length > 1500) continue;
out[key] = val;
}
return out;
}
function sanitizeHostI18nPatterns(rawList) {
const out = [];
if (!Array.isArray(rawList)) return out;
for (const item of rawList) {
if (!isPlainObject(item)) continue;
const source = typeof item.source === 'string' ? item.source : '';
const flags = typeof item.flags === 'string' ? item.flags : '';
const replace = typeof item.replace === 'string' ? item.replace : '';
const hint = typeof item.hint === 'string' ? item.hint.trim() : '';
if (!source || source.length > 360 || !source.startsWith('^') || !source.endsWith('$')) {
continue;
}
if (!HOST_I18N_ALLOWED_REGEX_FLAGS_RE.test(flags) || HOST_I18N_UNSAFE_REGEX_RE.test(source)) {
continue;
}
if (!replace || replace.length > 800) continue;
try {
// 校验正则可合法编译
// eslint-disable-next-line no-new
new RegExp(source, flags);
} catch {
continue;
}
out.push(hint ? { source, flags, replace, hint } : { source, flags, replace });
}
return out;
}
/**
* 校验并规范化远端或本地的 `manifest.json` 载荷。
*
* @param {unknown} raw
* @returns {{ schemaVersion: number, packs: Array<object> }}
*/
export function sanitizeHostI18nManifest(raw) {
if (!isPlainObject(raw)) {
throw new Error('Invalid host-i18n manifest payload');
}
const schemaVersion = Number(raw.schemaVersion || 0);
if (schemaVersion !== HOST_I18N_SCHEMA_VERSION) {
throw new Error(`Unsupported host-i18n manifest schemaVersion: ${schemaVersion}`);
}
const rawPacks = Array.isArray(raw.packs) ? raw.packs : [];
const packs = [];
const seen = new Set();
for (const item of rawPacks) {
if (!isPlainObject(item)) continue;
const locale = normalizeHostI18nLocale(item.locale);
if (locale === HOST_I18N_OFF_LOCALE || seen.has(locale)) continue;
const sha256 = String(item.sha256 || '').trim().toLowerCase();
const version = String(item.version || '').trim();
const file = String(item.file || `packs/${locale}.json`)
.replace(/\\/g, '/')
.replace(/^\/+/, '');
if (!HOST_I18N_SHA256_RE.test(sha256) || !version || file.includes('..') || !file.endsWith('.json')) {
continue;
}
seen.add(locale);
packs.push({
locale,
name: String(item.name || locale).trim(),
nativeName: String(item.nativeName || item.name || locale).trim(),
version,
file,
sha256,
bytes: Math.max(0, Number(item.bytes || 0) || 0),
depths: Array.isArray(item.depths)
? item.depths.map((d) => normalizeHostI18nDepth(d)).filter((v, i, a) => a.indexOf(v) === i)
: ['light', 'deep'],
stats: isPlainObject(item.stats)
? {
baseExact: Number(item.stats.baseExact || 0) || 0,
lightExact: Number(item.stats.lightExact || 0) || 0,
deepExact: Number(item.stats.deepExact || 0) || 0,
basePatterns: Number(item.stats.basePatterns || 0) || 0,
lightPatterns: Number(item.stats.lightPatterns || 0) || 0,
deepPatterns: Number(item.stats.deepPatterns || 0) || 0,
}
: null,
});
}
return { schemaVersion, packs };
}
/**
* 校验并规范化单个语言包 JSON 内容。
*
* @param {unknown} raw
* @param {string} expectedLocale
*/
export function sanitizeHostI18nPack(raw, expectedLocale = '') {
if (!isPlainObject(raw)) {
throw new Error('Invalid host-i18n pack payload');
}
const schemaVersion = Number(raw.schemaVersion || 0);
if (schemaVersion !== HOST_I18N_SCHEMA_VERSION) {
throw new Error(`Unsupported host-i18n pack schemaVersion: ${schemaVersion}`);
}
const locale = normalizeHostI18nLocale(raw.locale);
if (locale === HOST_I18N_OFF_LOCALE) {
throw new Error('Invalid locale in host-i18n pack');
}
if (expectedLocale && locale !== normalizeHostI18nLocale(expectedLocale)) {
throw new Error(`Pack locale mismatch: expected ${expectedLocale}, got ${locale}`);
}
const version = String(raw.version || '').trim();
if (!version) {
throw new Error('Missing version in host-i18n pack');
}
const baseExact = sanitizeHostI18nExactMap(raw.base?.exact);
const basePatterns = sanitizeHostI18nPatterns(raw.base?.patterns);
const lightExact = sanitizeHostI18nExactMap(raw.modes?.light?.exact);
const lightPatterns = sanitizeHostI18nPatterns(raw.modes?.light?.patterns);
const deepExact = sanitizeHostI18nExactMap(raw.modes?.deep?.exact);
const deepPatterns = sanitizeHostI18nPatterns(raw.modes?.deep?.patterns);
return {
schemaVersion,
locale,
name: String(raw.name || locale).trim(),
nativeName: String(raw.nativeName || raw.name || locale).trim(),
version,
base: { exact: baseExact, patterns: basePatterns },
modes: {
light: { exact: lightExact, patterns: lightPatterns },
deep: { exact: deepExact, patterns: deepPatterns },
},
};
}
function hostI18nPatternSpecificityScore(source) {
const s = String(source || '');
let literalChars = 0;
let parenDepth = 0;
let inCharClass = false;
for (let i = 0; i < s.length; i += 1) {
const ch = s[i];
if (ch === '\\' && i + 1 < s.length) {
const next = s[i + 1];
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
literalChars += 1;
}
i += 1;
continue;
}
if (ch === '[' && !inCharClass) {
inCharClass = true;
continue;
}
if (ch === ']' && inCharClass) {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(') {
parenDepth += 1;
continue;
}
if (ch === ')') {
if (parenDepth > 0) parenDepth -= 1;
continue;
}
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
literalChars += 1;
}
}
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
const typedCaptures = (s.match(/\\d\+/g) || []).length;
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
}
/**
* 根据语言包与深/浅档位合成运行期单层查找载荷。
*
* @param {object} pack
* @param {'light'|'deep'} depth
* @param {string} sha256
*/
export function compileHostI18nRuntimePayload(pack, depth, sha256 = '') {
const safeDepth = normalizeHostI18nDepth(depth);
const modeBucket = safeDepth === 'deep' ? pack?.modes?.deep : pack?.modes?.light;
const exact = {
...(pack?.base?.exact || {}),
...(modeBucket?.exact || {}),
};
const taggedPatterns = [
...(Array.isArray(pack?.base?.patterns)
? pack.base.patterns.map((rule) => ({ rule, tierRank: 0 }))
: []),
...(Array.isArray(modeBucket?.patterns)
? modeBucket.patterns.map((rule) => ({ rule, tierRank: 1 }))
: []),
];
taggedPatterns.sort((a, b) => {
const scoreDiff =
hostI18nPatternSpecificityScore(b.rule?.source) -
hostI18nPatternSpecificityScore(a.rule?.source);
if (scoreDiff !== 0) return scoreDiff;
if (b.tierRank !== a.tierRank) return b.tierRank - a.tierRank;
return String(b.rule?.source || '').length - String(a.rule?.source || '').length;
});
const patterns = taggedPatterns.map((entry) => entry.rule);
const hashTag = String(sha256 || hostI18nSha256(JSON.stringify(exact))).slice(0, 12);
return {
locale: pack.locale,
depth: safeDepth,
version: pack.version,
revision: `${pack.locale}:${safeDepth}:${pack.version}:${hashTag}`,
exact,
patterns,
};
}
/**
* 创建独立的 Host I18n 包与状态管理器实例(可注入 `dataDir` / `fetchImpl` 便于隔离测试)。
*
* @param {{
* dataDir?: string,
* repo?: string,
* ref?: string,
* localSourceDir?: string,
* fetchImpl?: Function|null,
* timeoutMs?: number,
* }} [options]
*/
export function createHostI18nPackManager(options = {}) {
const paths = hostI18nResolveStoragePaths(options.dataDir || DATA_DIR);
const inFlightDownloads = new Map();
let inFlightManifest = null;
let cachedState = null;
let cachedStateMtimeMs = -1;
let cachedInstalledMeta = null;
let cachedInstalledMetaMtimeMs = -1;
const cachedPacks = new Map(); // locale -> { mtimeMs, sha256, pack }
let cachedCompiledRuntime = null; // { revision, payload }
function readMtimeMs(filePath) {
try {
const st = statSync(filePath, { throwIfNoEntry: false });
return st ? Number(st.mtimeMs || 0) : -1;
} catch {
return -1;
}
}
function readJsonFileSafe(filePath, fallback) {
if (!existsSync(filePath)) return fallback;
try {
return JSON.parse(readFileSync(filePath, 'utf8'));
} catch {
return fallback;
}
}
function loadState() {
const mtimeMs = readMtimeMs(paths.stateFile);
if (mtimeMs < 0) {
cachedState = {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale: HOST_I18N_OFF_LOCALE,
depth: HOST_I18N_DEFAULT_DEPTH,
updatedAtMs: 0,
};
cachedStateMtimeMs = -1;
return { ...cachedState };
}
if (cachedState && cachedStateMtimeMs === mtimeMs) {
return { ...cachedState };
}
const raw = readJsonFileSafe(paths.stateFile, {});
cachedState = {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale: normalizeHostI18nLocale(raw?.locale),
depth: normalizeHostI18nDepth(raw?.depth),
updatedAtMs: Number(raw?.updatedAtMs || 0) || 0,
};
cachedStateMtimeMs = mtimeMs;
return { ...cachedState };
}
function saveState(nextPartial) {
const prev = loadState();
const next = {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale:
nextPartial?.locale !== undefined
? normalizeHostI18nLocale(nextPartial.locale)
: prev.locale,
depth:
nextPartial?.depth !== undefined
? normalizeHostI18nDepth(nextPartial.depth)
: prev.depth,
updatedAtMs: Date.now(),
};
mkdirSync(paths.rootDir, { recursive: true });
writeJsonAtomicSync(paths.stateFile, next);
cachedState = next;
cachedStateMtimeMs = readMtimeMs(paths.stateFile);
return { ...next };
}
function loadInstalledMeta() {
const mtimeMs = readMtimeMs(paths.installedMetaFile);
if (mtimeMs < 0) {
cachedInstalledMeta = {};
cachedInstalledMetaMtimeMs = -1;
return {};
}
if (cachedInstalledMeta && cachedInstalledMetaMtimeMs === mtimeMs) {
return { ...cachedInstalledMeta };
}
const raw = readJsonFileSafe(paths.installedMetaFile, {});
const clean = {};
if (isPlainObject(raw)) {
for (const [k, v] of Object.entries(raw)) {
const loc = normalizeHostI18nLocale(k);
if (loc === HOST_I18N_OFF_LOCALE || !isPlainObject(v)) continue;
clean[loc] = {
locale: loc,
name: String(v.name || loc),
nativeName: String(v.nativeName || v.name || loc),
version: String(v.version || ''),
sha256: String(v.sha256 || '').toLowerCase(),
bytes: Number(v.bytes || 0) || 0,
downloadedAtMs: Number(v.downloadedAtMs || 0) || 0,
source: String(v.source || ''),
};
}
}
cachedInstalledMeta = clean;
cachedInstalledMetaMtimeMs = mtimeMs;
return { ...clean };
}
function saveInstalledMeta(metaObj) {
mkdirSync(paths.rootDir, { recursive: true });
writeJsonAtomicSync(paths.installedMetaFile, metaObj);
cachedInstalledMeta = { ...metaObj };
cachedInstalledMetaMtimeMs = readMtimeMs(paths.installedMetaFile);
}
function getPackFilePath(locale) {
const clean = normalizeHostI18nLocale(locale);
if (clean === HOST_I18N_OFF_LOCALE) return '';
return join(paths.packsDir, `${clean}.json`);
}
function loadInstalledPack(locale) {
const clean = normalizeHostI18nLocale(locale);
if (clean === HOST_I18N_OFF_LOCALE) return null;
const filePath = getPackFilePath(clean);
const mtimeMs = readMtimeMs(filePath);
if (mtimeMs < 0) {
cachedPacks.delete(clean);
return null;
}
const memo = cachedPacks.get(clean);
if (memo && memo.mtimeMs === mtimeMs) {
return memo;
}
try {
const rawText = readFileSync(filePath, 'utf8');
const sha256 = hostI18nSha256(rawText);
const pack = sanitizeHostI18nPack(JSON.parse(rawText), clean);
const rec = { mtimeMs, sha256, pack, bytes: Buffer.byteLength(rawText, 'utf8') };
cachedPacks.set(clean, rec);
return rec;
} catch {
cachedPacks.delete(clean);
return null;
}
}
function loadCachedManifest() {
const raw = readJsonFileSafe(paths.manifestCacheFile, null);
if (!isPlainObject(raw)) return null;
try {
const clean = sanitizeHostI18nManifest(raw.manifest || raw);
return {
manifest: clean,
fetchedAtMs: Number(raw.fetchedAtMs || 0) || 0,
source: String(raw.source || ''),
lastError: raw.lastError ? String(raw.lastError) : null,
};
} catch {
return null;
}
}
async function fetchAssetText(relPath) {
const resolved = hostI18nResolveRepoAndRef(options);
if (resolved.localDir) {
const localPath = join(resolved.localDir, relPath);
if (!existsSync(localPath)) {
throw new Error(`Local host-i18n file not found: ${localPath}`);
}
return {
text: readFileSync(localPath, 'utf8'),
url: `local:${localPath}`,
status: 200,
};
}
if (!options.fetchImpl && String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid') {
throw new Error('Remote host-i18n fetch disabled in test.invalid environment');
}
const urls = buildHostI18nAssetUrls(relPath, resolved);
return fetchHostI18nTextWithFallback(urls, {
fetchImpl: options.fetchImpl || null,
timeoutMs: options.timeoutMs,
});
}
async function refreshManifest({ force = false } = {}) {
const cached = loadCachedManifest();
const now = Date.now();
if (!force && cached && now - cached.fetchedAtMs < HOST_I18N_MANIFEST_TTL_MS) {
return { ok: true, fromCache: true, ...cached };
}
if (inFlightManifest) return inFlightManifest;
inFlightManifest = (async () => {
try {
const res = await fetchAssetText('manifest.json');
const manifest = sanitizeHostI18nManifest(JSON.parse(res.text));
const record = {
manifest,
fetchedAtMs: Date.now(),
source: res.url,
lastError: null,
};
mkdirSync(paths.rootDir, { recursive: true });
writeJsonAtomicSync(paths.manifestCacheFile, record);
return { ok: true, fromCache: false, ...record };
} catch (err) {
const message = err?.message || 'Failed to fetch host-i18n manifest';
return {
ok: false,
fromCache: Boolean(cached),
manifest: cached?.manifest || { schemaVersion: HOST_I18N_SCHEMA_VERSION, packs: [] },
fetchedAtMs: cached?.fetchedAtMs || 0,
source: cached?.source || '',
error: message,
};
}
})().finally(() => {
inFlightManifest = null;
});
return inFlightManifest;
}
async function installPack(rawLocale, { forceManifestRefresh = false } = {}) {
const locale = normalizeHostI18nLocale(rawLocale);
if (locale === HOST_I18N_OFF_LOCALE) {
throw new Error('Cannot install pack for "off" locale');
}
if (inFlightDownloads.has(locale)) {
return inFlightDownloads.get(locale);
}
const task = (async () => {
const manifestRes = await refreshManifest({ force: forceManifestRefresh });
let entry = manifestRes.manifest?.packs?.find((p) => p.locale === locale) || null;
if (!entry && !forceManifestRefresh) {
const refreshed = await refreshManifest({ force: true });
entry = refreshed.manifest?.packs?.find((p) => p.locale === locale) || null;
}
if (!entry) {
throw new Error(
manifestRes.error
? `Language pack "${locale}" unavailable: ${manifestRes.error}`
: `Language pack "${locale}" not found in repository manifest`
);
}
const res = await fetchAssetText(entry.file);
const actualHash = hostI18nSha256(res.text);
if (actualHash !== entry.sha256) {
throw new Error(
`Integrity check failed for "${locale}" (expected ${entry.sha256.slice(0, 12)}, got ${actualHash.slice(0, 12)})`
);
}
const pack = sanitizeHostI18nPack(JSON.parse(res.text), locale);
mkdirSync(paths.packsDir, { recursive: true });
const targetPath = getPackFilePath(locale);
writeTextFileAtomicSync(targetPath, res.text);
const meta = loadInstalledMeta();
meta[locale] = {
locale,
name: pack.name,
nativeName: pack.nativeName,
version: pack.version,
sha256: actualHash,
bytes: Buffer.byteLength(res.text, 'utf8'),
downloadedAtMs: Date.now(),
source: res.url,
};
saveInstalledMeta(meta);
cachedPacks.delete(locale);
if (cachedCompiledRuntime?.payload?.locale === locale) {
cachedCompiledRuntime = null;
}
const loaded = loadInstalledPack(locale);
return {
ok: true,
locale,
version: pack.version,
sha256: actualHash,
bytes: loaded?.bytes || meta[locale].bytes,
source: res.url,
};
})().finally(() => {
inFlightDownloads.delete(locale);
});
inFlightDownloads.set(locale, task);
return task;
}
async function selectLanguage({ locale: rawLocale, depth: rawDepth } = {}) {
const locale = normalizeHostI18nLocale(rawLocale);
const current = loadState();
const depth =
rawDepth !== undefined ? normalizeHostI18nDepth(rawDepth) : current.depth;
if (locale === HOST_I18N_OFF_LOCALE) {
const nextState = saveState({ locale: HOST_I18N_OFF_LOCALE, depth });
return { ok: true, downloaded: false, state: nextState };
}
let downloaded = false;
let loaded = loadInstalledPack(locale);
if (!loaded) {
await installPack(locale, { forceManifestRefresh: false });
downloaded = true;
loaded = loadInstalledPack(locale);
}
if (!loaded) {
throw new Error(`Language pack "${locale}" failed to load after installation`);
}
const nextState = saveState({ locale, depth });
return {
ok: true,
downloaded,
state: nextState,
packVersion: loaded.pack.version,
};
}
function setDepth(rawDepth) {
const depth = normalizeHostI18nDepth(rawDepth);
const nextState = saveState({ depth });
return { ok: true, state: nextState };
}
function removePack(rawLocale) {
const locale = normalizeHostI18nLocale(rawLocale);
if (locale === HOST_I18N_OFF_LOCALE) {
return { ok: false, error: 'Invalid locale' };
}
const targetPath = getPackFilePath(locale);
if (targetPath && existsSync(targetPath)) {
rmSync(targetPath, { force: true });
}
cachedPacks.delete(locale);
if (cachedCompiledRuntime?.payload?.locale === locale) {
cachedCompiledRuntime = null;
}
const meta = loadInstalledMeta();
delete meta[locale];
saveInstalledMeta(meta);
const cur = loadState();
let nextState = cur;
if (cur.locale === locale) {
nextState = saveState({ locale: HOST_I18N_OFF_LOCALE });
}
return { ok: true, removedLocale: locale, state: nextState };
}
function getActiveBridgeDescriptor() {
const st = loadState();
if (st.locale === HOST_I18N_OFF_LOCALE) {
return { active: false, locale: HOST_I18N_OFF_LOCALE, depth: st.depth, revision: '', getPayload: null };
}
const loaded = loadInstalledPack(st.locale);
if (!loaded) {
return { active: false, locale: st.locale, depth: st.depth, revision: '', getPayload: null };
}
const revision = `${loaded.pack.locale}:${st.depth}:${loaded.pack.version}:${loaded.sha256.slice(0, 12)}`;
return {
active: true,
locale: loaded.pack.locale,
depth: st.depth,
version: loaded.pack.version,
revision,
getPayload: () => {
if (cachedCompiledRuntime && cachedCompiledRuntime.revision === revision) {
return cachedCompiledRuntime.payload;
}
const payload = compileHostI18nRuntimePayload(loaded.pack, st.depth, loaded.sha256);
cachedCompiledRuntime = { revision, payload };
return payload;
},
};
}
function getStatusSnapshot({ manifestResult = null, bridgeStatus = null } = {}) {
const state = loadState();
const installedMeta = loadInstalledMeta();
const cachedManifest = manifestResult || loadCachedManifest();
const remotePacks = Array.isArray(cachedManifest?.manifest?.packs)
? cachedManifest.manifest.packs
: [];
const byLocale = new Map();
for (const remote of remotePacks) {
const localPack = loadInstalledPack(remote.locale);
const localInfo = installedMeta[remote.locale] || null;
const installed = Boolean(localPack);
const installedSha = localPack?.sha256 || localInfo?.sha256 || '';
const installedVersion = localPack?.pack?.version || localInfo?.version || '';
byLocale.set(remote.locale, {
locale: remote.locale,
name: remote.name,
nativeName: remote.nativeName,
remoteVersion: remote.version,
remoteSha256: remote.sha256,
remoteBytes: remote.bytes,
depths: remote.depths || ['light', 'deep'],
stats: remote.stats || null,
installed,
installedVersion,
installedBytes: localPack?.bytes || localInfo?.bytes || 0,
downloadedAtMs: localInfo?.downloadedAtMs || 0,
updateAvailable: Boolean(installed && installedSha && installedSha !== remote.sha256),
});
}
// 保留仅在本地存在(离线/自定义)的已安装包条目
for (const [loc, localInfo] of Object.entries(installedMeta)) {
if (byLocale.has(loc)) continue;
const localPack = loadInstalledPack(loc);
if (!localPack) continue;
byLocale.set(loc, {
locale: loc,
name: localPack.pack.name,
nativeName: localPack.pack.nativeName,
remoteVersion: '',
remoteSha256: '',
remoteBytes: 0,
depths: ['light', 'deep'],
stats: {
baseExact: Object.keys(localPack.pack.base.exact).length,
lightExact: Object.keys(localPack.pack.modes.light.exact).length,
deepExact: Object.keys(localPack.pack.modes.deep.exact).length,
basePatterns: localPack.pack.base.patterns.length,
lightPatterns: localPack.pack.modes.light.patterns.length,
deepPatterns: localPack.pack.modes.deep.patterns.length,
},
installed: true,
installedVersion: localPack.pack.version,
installedBytes: localPack.bytes,
downloadedAtMs: localInfo.downloadedAtMs || 0,
updateAvailable: false,
});
}
const activeDesc = getActiveBridgeDescriptor();
const resolvedRepo = hostI18nResolveRepoAndRef(options);
return {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale: state.locale,
depth: state.depth,
active: activeDesc.active,
activeRevision: activeDesc.revision,
updatedAtMs: state.updatedAtMs,
manifestFetchedAtMs: Number(cachedManifest?.fetchedAtMs || 0) || 0,
manifestError: cachedManifest?.error || null,
repo: resolvedRepo.repo,
ref: resolvedRepo.ref,
packs: Array.from(byLocale.values()),
...(bridgeStatus ? { bridgeStatus } : {}),
};
}
return {
paths,
loadState,
saveState,
loadInstalledPack,
refreshManifest,
installPack,
selectLanguage,
setDepth,
removePack,
getActiveBridgeDescriptor,
getStatusSnapshot,
};
}
@@ -0,0 +1,914 @@
/**
* @fileoverview 注入到 Antigravity 渲染进程的无损运行时 DOM 翻译引擎与按需词条采集器。
*
* 工程底线:
* 1. 绝不替换、拆裂或增删 React 托管的任何 DOM 元素,仅原地改写 `Text.nodeValue` 及
* `placeholder` / `title` / `aria-label` / `aria-description` / `aria-placeholder` 属性;
* 2. 通过 `WeakMap` 精确记录每个被改写节点/属性的原文与译文,既支持 `light ↔ deep` /
* `关闭` 秒级无损还原,也能自动识别 React 原地更新的新英文文案并重新翻译;
* 3. 对齐 Antigravity 真实 DOM 结构,严格豁免用户消息正文(`user-message-content`)、
* 代码块、Diff 行、编辑器、终端、可编辑区以及本插件双 Shadow Host,不误伤工具栏按钮;
* 4. 针对数千条精确词条 + 数百条动态模板做 O(1) 精确查表 + 首词桶索引,并经
* `requestAnimationFrame` 分帧合批,杜绝流式输出掉帧。
*/
import { HOST_I18N_GLOBAL_KEY } from '../../shared/host-i18n-protocol.mjs';
/**
* 在宿主页面执行:安装或热更新无损 DOM 翻译器,并续期 18 秒看门狗。
*
* @param {object} payload `{ locale, depth, revision, exact, patterns }`
* @param {string} bootId
* @param {string} [globalKey]
*/
export function applyHostI18nInPage(payload, bootId, globalKey = '__AGUsageMonitorHostI18n') {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { applied: false, reason: 'no_dom' };
}
const root = document.body || document.documentElement;
if (!root) {
return { applied: false, reason: 'no_root' };
}
const WATCHDOG_MS = 18_000;
const FRAME_NODE_BUDGET = 450;
const INITIAL_SCAN_BUDGET = 4000;
const MAX_PENDING_NODES = 4096;
const MAX_MISS_CACHE = 1024;
const MAX_EXACT_LEN = 1000;
const MAX_PATTERN_LEN = 360;
const TRANSLATABLE_ATTRS = [
'placeholder',
'title',
'aria-label',
'aria-description',
'aria-placeholder',
];
const SKIP_TAGS = new Set([
'SCRIPT',
'STYLE',
'NOSCRIPT',
'CODE',
'PRE',
'TEXTAREA',
'SVG',
'MATH',
'KBD',
'SAMP',
'VAR',
'CANVAS',
'VIDEO',
'AUDIO',
'IFRAME',
]);
const SKIP_TESTIDS = new Set([
'user-message-content',
'markdown-code-block-preview',
'markdown-frontmatter',
'automation-instructions-markdown',
'code-gutter',
'code-gutter-diff',
'diff-gutter-strip',
'artifact-pdf-view',
]);
const SKIP_CLASSES = new Set([
'monaco-editor',
'xterm',
'cm-editor',
'ProseMirror',
'markdown-body',
'prose',
'diff-line',
'view-lines',
]);
function isSkippedSelf(el) {
if (!el || el.nodeType !== 1) return false;
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable === true) return true;
const id = el.id;
if (id === 'ag-usage-monitor-capsule' || id === 'ag-usage-monitor-portal') return true;
if (typeof el.hasAttribute === 'function' && el.hasAttribute('data-ag-i18n-ignore')) return true;
if (typeof el.getAttribute === 'function') {
if (el.getAttribute('contenteditable') === 'true') return true;
const tid = el.getAttribute('data-testid');
if (tid && SKIP_TESTIDS.has(tid)) return true;
}
const cls = el.className;
if (typeof cls === 'string' && cls) {
if (cls.indexOf(' ') === -1) {
if (SKIP_CLASSES.has(cls)) return true;
} else {
const parts = cls.split(/\s+/);
for (let i = 0; i < parts.length; i += 1) {
if (SKIP_CLASSES.has(parts[i])) return true;
}
}
}
return false;
}
function isSkippedElement(el) {
let cur = el;
while (cur && cur.nodeType === 1) {
if (isSkippedSelf(cur)) return true;
cur = cur.parentElement || (cur.parentNode && cur.parentNode.nodeType === 1 ? cur.parentNode : null);
}
return false;
}
function hasAsciiLetter(str) {
for (let i = 0; i < str.length; i += 1) {
const code = str.charCodeAt(i);
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) return true;
}
return false;
}
function isAsciiLetterCode(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
function extractFirstWordLower(str) {
const m = str.match(/^[A-Za-z][A-Za-z0-9'-]*/);
return m ? m[0].toLowerCase() : '';
}
function extractLastWordLower(str) {
const m = str.match(/([A-Za-z]{2,})[.)?!'"\u201d\u2019…]*$/);
return m ? m[1].toLowerCase() : '';
}
function extractPatternLeadingWordLower(source) {
// 匹配以 `^Word` 开头的锚定模板(忽略反转义前的普通字母首词)
const m = String(source || '').match(/^\^([A-Za-z]{2,})/);
return m ? m[1].toLowerCase() : '';
}
function isNumericStartPattern(source) {
return /^\^(?:\\d|\(\\d|\\\(|\\\+|, \\\+)/.test(String(source || ''));
}
function extractPatternTrailingWordsLower(source) {
const s = String(source || '');
// 跳过结尾是通配捕获或字符集的模板,仅索引以固定英文词结尾的模板(兼容可选复数 s?)
const plural = s.match(/([A-Za-z]{2,})s\?(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
if (plural) {
const base = plural[1].toLowerCase();
return [base, `${base}s`];
}
const exact = s.match(/(?:^|[\s(\\/-])([A-Za-z]{2,})(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
if (exact) {
return [exact[1].toLowerCase()];
}
return [];
}
function computePatternSpecificity(source) {
const s = String(source || '');
let literalChars = 0;
let parenDepth = 0;
let inCharClass = false;
for (let i = 0; i < s.length; i += 1) {
const ch = s[i];
if (ch === '\\' && i + 1 < s.length) {
const next = s[i + 1];
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
literalChars += 1;
}
i += 1;
continue;
}
if (ch === '[' && !inCharClass) {
inCharClass = true;
continue;
}
if (ch === ']' && inCharClass) {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(') {
parenDepth += 1;
continue;
}
if (ch === ')') {
if (parenDepth > 0) parenDepth -= 1;
continue;
}
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
literalChars += 1;
}
}
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
const typedCaptures = (s.match(/\\d\+/g) || []).length;
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
}
function compileMatchers(rawPayload) {
const exactMap = new Map();
const exactLowerMap = new Map();
const rawExact = rawPayload?.exact;
if (rawExact && typeof rawExact === 'object') {
for (const [k, v] of Object.entries(rawExact)) {
if (typeof v !== 'string' || !v) continue;
exactMap.set(k, v);
if (k.length <= 80) {
const lowerK = k.toLowerCase();
if (!exactLowerMap.has(lowerK)) {
exactLowerMap.set(lowerK, v);
}
}
}
}
const prefixBuckets = new Map();
const suffixBuckets = new Map();
const numericFallbacks = [];
const fallbackPatterns = [];
const rawPatterns = Array.isArray(rawPayload?.patterns) ? rawPayload.patterns : [];
for (let i = 0; i < rawPatterns.length; i += 1) {
const item = rawPatterns[i];
if (!item || typeof item.source !== 'string' || typeof item.replace !== 'string') continue;
try {
const compiled = {
re: new RegExp(item.source, typeof item.flags === 'string' ? item.flags : ''),
replace: item.replace,
hintLower: typeof item.hint === 'string' ? item.hint.toLowerCase() : '',
specificity: computePatternSpecificity(item.source),
sourceLen: item.source.length,
order: i,
};
const leadWord = extractPatternLeadingWordLower(item.source);
if (leadWord) {
let bucket = prefixBuckets.get(leadWord);
if (!bucket) {
bucket = [];
prefixBuckets.set(leadWord, bucket);
}
bucket.push(compiled);
} else if (isNumericStartPattern(item.source)) {
numericFallbacks.push(compiled);
} else {
const tailWords = extractPatternTrailingWordsLower(item.source);
if (tailWords.length > 0) {
for (let t = 0; t < tailWords.length; t += 1) {
const tw = tailWords[t];
let sBucket = suffixBuckets.get(tw);
if (!sBucket) {
sBucket = [];
suffixBuckets.set(tw, sBucket);
}
sBucket.push(compiled);
}
} else {
fallbackPatterns.push(compiled);
}
}
} catch {
// 忽略单条非法正则
}
}
const sortBySpecificity = (a, b) =>
b.specificity - a.specificity || b.sourceLen - a.sourceLen || a.order - b.order;
for (const bucket of prefixBuckets.values()) {
if (bucket.length > 1) bucket.sort(sortBySpecificity);
}
for (const bucket of suffixBuckets.values()) {
if (bucket.length > 1) bucket.sort(sortBySpecificity);
}
if (numericFallbacks.length > 1) numericFallbacks.sort(sortBySpecificity);
if (fallbackPatterns.length > 1) fallbackPatterns.sort(sortBySpecificity);
return {
exactMap,
exactLowerMap,
prefixBuckets,
suffixBuckets,
numericFallbacks,
fallbackPatterns,
missCache: new Set(),
};
}
function runPatternList(trimmed, lowerRef, list) {
if (!list || list.length === 0) return undefined;
for (let i = 0; i < list.length; i += 1) {
const pat = list[i];
if (pat.hintLower) {
if (lowerRef.value === null) lowerRef.value = trimmed.toLowerCase();
if (!lowerRef.value.includes(pat.hintLower)) continue;
}
if (pat.re.test(trimmed)) {
const next = trimmed.replace(pat.re, pat.replace);
if (next && next !== trimmed) return next;
}
}
return undefined;
}
function translateTextWithMatchers(rawText, matchers) {
if (typeof rawText !== 'string' || !rawText || rawText.length > MAX_EXACT_LEN) return null;
const normalizedRaw = rawText.includes('\r') ? rawText.replace(/\r\n/g, '\n') : rawText;
const trimmed = normalizedRaw.trim();
if (!trimmed || trimmed.length > MAX_EXACT_LEN) return null;
if (trimmed.length <= 160 && matchers.missCache.has(trimmed)) return null;
let translatedCore = matchers.exactMap.get(trimmed);
const hasLetter = translatedCore === undefined ? hasAsciiLetter(trimmed) : false;
let lowerRef = { value: null };
if (translatedCore === undefined && trimmed.length <= 80 && hasLetter) {
lowerRef.value = trimmed.toLowerCase();
translatedCore = matchers.exactLowerMap.get(lowerRef.value);
}
if (
translatedCore === undefined &&
trimmed.length <= MAX_PATTERN_LEN &&
!trimmed.includes('\n') &&
hasLetter
) {
const firstCode = trimmed.charCodeAt(0);
if (isAsciiLetterCode(firstCode)) {
const leadWord = extractFirstWordLower(trimmed);
if (leadWord) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.prefixBuckets.get(leadWord));
}
} else if (matchers.numericFallbacks.length > 0) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.numericFallbacks);
}
if (translatedCore === undefined) {
const tailWord = extractLastWordLower(trimmed);
if (tailWord) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.suffixBuckets.get(tailWord));
}
}
if (translatedCore === undefined && matchers.fallbackPatterns.length > 0) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.fallbackPatterns);
}
}
if (translatedCore === undefined || translatedCore === trimmed) {
if (trimmed.length <= 160) {
if (matchers.missCache.size >= MAX_MISS_CACHE) {
matchers.missCache.clear();
}
matchers.missCache.add(trimmed);
}
return null;
}
const startIdx = normalizedRaw.indexOf(trimmed);
const leading = startIdx > 0 ? normalizedRaw.slice(0, startIdx) : '';
const trailing =
startIdx + trimmed.length < normalizedRaw.length
? normalizedRaw.slice(startIdx + trimmed.length)
: '';
return leading + translatedCore + trailing;
}
let state = window[globalKey];
function restoreSubtree(scanRoot, targetState) {
if (!scanRoot) return;
if (typeof document.createTreeWalker === 'function') {
const textWalker = document.createTreeWalker(scanRoot, 4);
let node = textWalker.nextNode();
while (node) {
const rec = targetState.textRecords.get(node);
if (rec) {
if (node.nodeValue === rec.translated) {
node.nodeValue = rec.orig;
}
targetState.textRecords.delete(node);
}
node = textWalker.nextNode();
}
const elWalker = document.createTreeWalker(scanRoot, 1);
let el = elWalker.nextNode();
while (el) {
const attrMap = targetState.attrRecords.get(el);
if (attrMap) {
for (const [attrName, rec] of attrMap.entries()) {
if (el.getAttribute(attrName) === rec.translated) {
el.setAttribute(attrName, rec.orig);
}
}
targetState.attrRecords.delete(el);
}
if (el.shadowRoot && el.id !== 'ag-usage-monitor-capsule' && el.id !== 'ag-usage-monitor-portal') {
restoreSubtree(el.shadowRoot, targetState);
}
el = elWalker.nextNode();
}
} else {
const walkFallback = (cur) => {
if (!cur) return;
if (cur.nodeType === 3) {
const rec = targetState.textRecords.get(cur);
if (rec) {
if (cur.nodeValue === rec.translated) cur.nodeValue = rec.orig;
targetState.textRecords.delete(cur);
}
return;
}
if (cur.nodeType === 1 || cur.nodeType === 11) {
if (cur.nodeType === 1) {
const attrMap = targetState.attrRecords.get(cur);
if (attrMap) {
for (const [attrName, rec] of attrMap.entries()) {
if (cur.getAttribute?.(attrName) === rec.translated) {
cur.setAttribute(attrName, rec.orig);
}
}
targetState.attrRecords.delete(cur);
}
if (cur.shadowRoot && cur.id !== 'ag-usage-monitor-capsule' && cur.id !== 'ag-usage-monitor-portal') {
walkFallback(cur.shadowRoot);
}
}
const children = cur.childNodes || [];
for (let i = 0; i < children.length; i += 1) {
walkFallback(children[i]);
}
}
};
walkFallback(scanRoot);
}
}
function restoreAllTracked(targetState) {
if (!targetState) return;
targetState.isMutating = true;
try {
const scanRoot = document.body || document.documentElement;
restoreSubtree(scanRoot, targetState);
} finally {
targetState.isMutating = false;
}
}
if (state && state.bootId !== bootId) {
state.dispose?.();
state = null;
}
if (!state) {
const scheduleFrame =
typeof window.requestAnimationFrame === 'function'
? (cb) => ({ kind: 'raf', id: window.requestAnimationFrame(cb) })
: (cb) => ({ kind: 'timer', id: setTimeout(cb, 16) });
const cancelFrame = (handle) => {
if (!handle) return;
if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function') {
window.cancelAnimationFrame(handle.id);
} else {
clearTimeout(handle.id);
}
};
state = {
bootId,
revision: '',
locale: '',
depth: '',
matchers: {
exactMap: new Map(),
exactLowerMap: new Map(),
prefixBuckets: new Map(),
suffixBuckets: new Map(),
numericFallbacks: [],
fallbackPatterns: [],
missCache: new Set(),
},
textRecords: new WeakMap(),
attrRecords: new WeakMap(),
pendingNodes: new Set(),
fullRescanPending: false,
frameHandle: null,
watchdogTimer: null,
observer: null,
isMutating: false,
translatedCount: 0,
applyTextNode(node, parentVerifiedSafe = false) {
if (!node || node.nodeType !== 3) return;
if (!parentVerifiedSafe) {
const parent = node.parentElement || node.parentNode;
if (parent && isSkippedElement(parent)) return;
}
const curVal = node.nodeValue;
if (typeof curVal !== 'string' || !curVal) return;
const existing = state.textRecords.get(node);
let origVal = curVal;
if (existing) {
if (curVal === existing.translated) {
return;
}
origVal = curVal;
state.textRecords.delete(node);
}
const nextVal = translateTextWithMatchers(origVal, state.matchers);
if (nextVal !== null && nextVal !== origVal) {
state.textRecords.set(node, { orig: origVal, translated: nextVal });
state.isMutating = true;
try {
node.nodeValue = nextVal;
state.translatedCount += 1;
} finally {
state.isMutating = false;
}
}
},
applyElementAttrs(el, selfVerifiedSafe = false) {
if (!el || el.nodeType !== 1) return;
if (!selfVerifiedSafe && isSkippedElement(el)) return;
if (typeof el.getAttribute !== 'function' || typeof el.setAttribute !== 'function') return;
for (let i = 0; i < TRANSLATABLE_ATTRS.length; i += 1) {
const attrName = TRANSLATABLE_ATTRS[i];
const curVal = el.getAttribute(attrName);
if (!curVal) continue;
let attrMap = state.attrRecords.get(el);
const existing = attrMap?.get(attrName);
let origVal = curVal;
if (existing) {
if (curVal === existing.translated) continue;
origVal = curVal;
attrMap.delete(attrName);
}
const nextVal = translateTextWithMatchers(origVal, state.matchers);
if (nextVal !== null && nextVal !== origVal) {
if (!attrMap) {
attrMap = new Map();
state.attrRecords.set(el, attrMap);
}
attrMap.set(attrName, { orig: origVal, translated: nextVal });
state.isMutating = true;
try {
el.setAttribute(attrName, nextVal);
state.translatedCount += 1;
} finally {
state.isMutating = false;
}
}
}
},
walkSubtree(node, budgetRef, ancestorsVerifiedSafe = false) {
if (!node || budgetRef.remaining <= 0) return false;
if (node.nodeType === 3) {
budgetRef.remaining -= 1;
state.applyTextNode(node, ancestorsVerifiedSafe);
return true;
}
if (node.nodeType !== 1 && node.nodeType !== 11) return true;
if (node.nodeType === 1) {
if (ancestorsVerifiedSafe ? isSkippedSelf(node) : isSkippedElement(node)) return true;
budgetRef.remaining -= 1;
state.applyElementAttrs(node, true);
if (node.shadowRoot && node.id !== 'ag-usage-monitor-capsule' && node.id !== 'ag-usage-monitor-portal') {
state.walkSubtree(node.shadowRoot, budgetRef, true);
}
}
const children = node.childNodes || [];
for (let i = 0; i < children.length; i += 1) {
if (budgetRef.remaining <= 0) {
state.pendingNodes.add(children[i]);
return false;
}
if (!state.walkSubtree(children[i], budgetRef, true)) {
for (let j = i + 1; j < children.length; j += 1) {
state.pendingNodes.add(children[j]);
}
return false;
}
}
return true;
},
flushPending() {
state.frameHandle = null;
if (state.fullRescanPending) {
state.fullRescanPending = false;
state.pendingNodes.clear();
const scanRoot = document.body || document.documentElement;
if (scanRoot) state.pendingNodes.add(scanRoot);
}
const budgetRef = { remaining: FRAME_NODE_BUDGET };
const batch = Array.from(state.pendingNodes);
state.pendingNodes.clear();
for (let i = 0; i < batch.length; i += 1) {
if (budgetRef.remaining <= 0) {
for (let j = i; j < batch.length; j += 1) {
state.pendingNodes.add(batch[j]);
}
break;
}
state.walkSubtree(batch[i], budgetRef, false);
}
if (state.pendingNodes.size > 0 || state.fullRescanPending) {
state.scheduleFlush();
}
},
scheduleFlush() {
if (state.frameHandle) return;
state.frameHandle = scheduleFrame(() => state.flushPending());
},
enqueue(node) {
if (!node) return;
if (state.pendingNodes.size >= MAX_PENDING_NODES) {
state.fullRescanPending = true;
state.pendingNodes.clear();
} else {
state.pendingNodes.add(node);
}
state.scheduleFlush();
},
scanAllNow() {
const scanRoot = document.body || document.documentElement;
if (!scanRoot) return;
const budgetRef = { remaining: INITIAL_SCAN_BUDGET };
state.walkSubtree(scanRoot, budgetRef, true);
if (state.pendingNodes.size > 0) {
state.scheduleFlush();
}
},
touchWatchdog() {
clearTimeout(state.watchdogTimer);
state.watchdogTimer = setTimeout(() => {
state.dispose();
}, WATCHDOG_MS);
},
dispose() {
clearTimeout(state.watchdogTimer);
state.watchdogTimer = null;
cancelFrame(state.frameHandle);
state.frameHandle = null;
try {
state.observer?.disconnect?.();
} catch {
// 忽略断开异常
}
state.observer = null;
state.pendingNodes.clear();
state.fullRescanPending = false;
restoreAllTracked(state);
state.matchers.exactMap.clear();
state.matchers.exactLowerMap.clear();
state.matchers.prefixBuckets.clear();
state.matchers.suffixBuckets.clear();
state.matchers.numericFallbacks.length = 0;
state.matchers.fallbackPatterns.length = 0;
state.matchers.missCache.clear();
if (window[globalKey] === state) {
delete window[globalKey];
}
},
};
if (typeof window.MutationObserver === 'function') {
state.observer = new window.MutationObserver((mutations) => {
if (state.isMutating) return;
for (let i = 0; i < mutations.length; i += 1) {
const m = mutations[i];
if (m.type === 'characterData' || m.type === 'attributes') {
state.enqueue(m.target);
} else if (m.type === 'childList') {
const added = m.addedNodes || [];
for (let j = 0; j < added.length; j += 1) {
state.enqueue(added[j]);
}
}
}
});
state.observer.observe(root, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: TRANSLATABLE_ATTRS,
});
}
window[globalKey] = state;
}
state.touchWatchdog();
const nextRevision = String(payload?.revision || '');
if (state.revision !== nextRevision) {
if (state.revision) {
restoreAllTracked(state);
}
state.revision = nextRevision;
state.locale = String(payload?.locale || '');
state.depth = String(payload?.depth || '');
state.matchers = compileMatchers(payload);
state.translatedCount = 0;
state.scanAllNow();
}
return {
applied: true,
revision: state.revision,
locale: state.locale,
depth: state.depth,
translatedCount: state.translatedCount,
};
}
/**
* 轻量心跳表达式:若当前页面已加载同一 `bootId` 且同 `revision`,直接续期看门狗,无需重传大词表。
*/
export function createHostI18nHeartbeatExpression(bootId, revision) {
return `(() => {
try {
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
if (!st || st.bootId !== ${JSON.stringify(bootId)} || st.revision !== ${JSON.stringify(revision)}) {
return { alive: false, needsApply: true };
}
st.touchWatchdog?.();
return { alive: true, needsApply: false, revision: st.revision, translatedCount: Number(st.translatedCount || 0) };
} catch {
return { alive: false, needsApply: true };
}
})()`;
}
/**
* 生成完整注入/切换词表表达式。
*/
export function createHostI18nApplyExpression(payload, bootId) {
return `(${applyHostI18nInPage.toString()})(${JSON.stringify(payload)}, ${JSON.stringify(bootId)}, ${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
}
/**
* 生成停止翻译并无损还原原文的清理表达式。
*/
export function createHostI18nDisposeExpression() {
return `(() => {
try {
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
if (!st) return { disposed: false };
st.dispose?.();
return { disposed: true };
} catch {
return { disposed: false };
}
})()`;
}
/**
* 在宿主页面按需执行:只读采集当前可见 UI 控件与说明中尚未翻译的英文短语
* (严格排除聊天用户正文、代码块、Diff、编辑器与隐私路径)。
*/
export function collectUntranslatedHostUiInPage(globalKey = '__AGUsageMonitorHostI18n') {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { count: 0, items: [] };
}
const root = document.body || document.documentElement;
if (!root) return { count: 0, items: [] };
const activeState = window[globalKey] || null;
const SKIP_TAGS = new Set([
'SCRIPT',
'STYLE',
'NOSCRIPT',
'CODE',
'PRE',
'TEXTAREA',
'SVG',
'MATH',
'KBD',
'SAMP',
'VAR',
'CANVAS',
'VIDEO',
'AUDIO',
'IFRAME',
]);
const SKIP_SELECTOR = [
'#ag-usage-monitor-capsule',
'#ag-usage-monitor-portal',
'[data-ag-i18n-ignore]',
'[contenteditable="true"]',
'.monaco-editor',
'.xterm',
'.cm-editor',
'.ProseMirror',
'.markdown-body',
'.prose',
'[data-testid="user-message-content"]',
'[data-testid="markdown-code-block-preview"]',
'[data-testid="markdown-frontmatter"]',
'[data-testid="automation-instructions-markdown"]',
'[data-testid="code-gutter"]',
'[data-testid="code-gutter-diff"]',
'[data-testid="diff-gutter-strip"]',
'[data-testid="artifact-pdf-view"]',
'.diff-line',
'.view-lines',
].join(',');
const UI_CONTROL_SELECTOR = [
'button',
'[role="button"]',
'[role="menuitem"]',
'[role="tab"]',
'[role="option"]',
'[role="switch"]',
'[role="checkbox"]',
'[role="radio"]',
'[role="heading"]',
'[role="tooltip"]',
'[role="status"]',
'label',
'legend',
'caption',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'th',
'dt',
'dd',
'p',
'span',
'nav a',
'[placeholder]',
'[title]',
'[aria-label]',
'[aria-description]',
].join(',');
const NON_LATIN_RE = /[\u3000-\u9fff\uac00-\ud7af\u0400-\u04ff]/;
const NOISE_RE =
/^(?:https?:\/\/|file:\/\/|\/|~\.|[A-Za-z]:\\|[\w.+-]+@[\w.-]+\.[a-z]{2,}$|[0-9a-f]{8}-[0-9a-f]{4}-|v?\d+(?:\.\d+)+$|\/[a-z0-9_-]+$|(?:gemini|claude|gpt|o[134])\b)/i;
function isSkipped(el) {
if (!el || el.nodeType !== 1) return false;
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable === true) return true;
if (el.id === 'ag-usage-monitor-capsule' || el.id === 'ag-usage-monitor-portal') return true;
if (typeof el.closest === 'function') {
try {
if (el.closest(SKIP_SELECTOR)) return true;
} catch {
// 忽略选择器异常
}
}
return false;
}
const counts = new Map();
const kinds = new Map();
function recordCandidate(raw, kind) {
if (typeof raw !== 'string') return;
if (raw.includes('\n') || raw.includes('\r')) return;
const text = raw.trim();
if (text.length < 2 || text.length > 260) return;
if (!/[A-Za-z]{2,}/.test(text)) return;
if (NON_LATIN_RE.test(text)) return;
if (NOISE_RE.test(text)) return;
if (/^[0-9.,:%$+\-*/\s()[\]]+$/.test(text)) return;
if (activeState?.matchers?.exactMap?.has(text)) return;
if (text.length <= 80 && activeState?.matchers?.exactLowerMap?.has(text.toLowerCase())) return;
counts.set(text, (counts.get(text) || 0) + 1);
if (!kinds.has(text)) kinds.set(text, kind);
}
const elements =
typeof root.querySelectorAll === 'function' ? root.querySelectorAll(UI_CONTROL_SELECTOR) : [];
for (let i = 0; i < elements.length; i += 1) {
const el = elements[i];
if (isSkipped(el)) continue;
for (const attrName of ['placeholder', 'title', 'aria-label', 'aria-description']) {
const val = el.getAttribute?.(attrName);
const attrMap = activeState?.attrRecords?.get(el);
if (val && !(attrMap && attrMap.has(attrName))) {
recordCandidate(val, attrName);
}
}
const children = el.childNodes || [];
for (let j = 0; j < children.length; j += 1) {
const ch = children[j];
if (ch && ch.nodeType === 3) {
if (activeState?.textRecords?.has(ch)) continue;
recordCandidate(ch.nodeValue, 'text');
}
}
}
const items = Array.from(counts.entries())
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
.slice(0, 500)
.map(([text, count]) => ({ text, kind: kinds.get(text) || 'text', count }));
return { count: items.length, items };
}
/**
* 生成按需采集未命中 UI 词条的只读 CDP 表达式。
*/
export function createHostI18nCollectExpression() {
return `(${collectUntranslatedHostUiInPage.toString()})(${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
}
File diff suppressed because it is too large Load Diff
+29 -2
View File
@@ -234,6 +234,16 @@ export function formatGenericModelSlug(slug = '') {
if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash';
if (/^gemini-3-flash-c$/i.test(s)) return 'Gemini 3 Flash';
if (/^gemini-pro-(?:default|agent|b)$/i.test(s)) return 'Gemini 3.1 Pro';
const imgMatch = s.match(
/^gemini-(\d+(?:\.\d+)?)-(pro|flash)(?:-(lite))?-image(?:-(preview))?$/i
);
if (imgMatch) {
const ver = imgMatch[1];
const tier = imgMatch[2].charAt(0).toUpperCase() + imgMatch[2].slice(1).toLowerCase();
const lite = imgMatch[3] ? ' Lite' : '';
const prev = imgMatch[4] ? ' (Preview)' : '';
return `Gemini ${ver} ${tier}${lite} Image${prev}`;
}
const m = s.match(
/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon|neon|hydrogen|helix)(?:-(lite))?(?:-(xhigh|high|medium|low|extra-low|tiered|preview))?$/i
);
@@ -317,10 +327,12 @@ export function resolvePricingAt(pricingEntry, atMs) {
? parseIsoMs(ph.until.trim()) || Infinity
: Infinity;
if (tMs >= fromMs && tMs < untilMs) {
const nextImgOut = ph.imageOutput ?? baseEntry.imageOutput;
if (
ph.input === baseEntry.input &&
ph.cache === baseEntry.cache &&
ph.output === baseEntry.output
ph.output === baseEntry.output &&
nextImgOut === baseEntry.imageOutput
) {
return baseEntry;
}
@@ -329,6 +341,7 @@ export function resolvePricingAt(pricingEntry, atMs) {
input: ph.input,
cache: ph.cache,
output: ph.output,
...(nextImgOut !== undefined ? { imageOutput: nextImgOut } : {}),
};
Object.defineProperty(resolved, '_basePricing', {
value: baseEntry,
@@ -641,6 +654,19 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
* @param {{ input: number, cache: number, output: number } | null} pricing
* @returns {number|null}
*/
export function resolveEffectiveOutputRate(pricing, step) {
if (!pricing || typeof pricing !== 'object') return null;
if (
step?.isImageGenStep &&
typeof pricing.imageOutput === 'number' &&
Number.isFinite(pricing.imageOutput) &&
pricing.imageOutput > 0
) {
return pricing.imageOutput;
}
return pricing.output;
}
export function computeStepCost(step, pricing) {
if (!pricing) return null;
const stepMs = extractStepTimestampMs(step);
@@ -652,8 +678,9 @@ export function computeStepCost(step, pricing) {
const n = Number(v);
return Number.isFinite(n) && n > 0 ? n : 0;
};
const outRate = resolveEffectiveOutputRate(effectivePricing, step);
const inCost = (safeTok(step?.inputTokens) / 1_000_000) * effectivePricing.input;
const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * effectivePricing.cache;
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * effectivePricing.output;
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * outRate;
return inCost + cacheCost + outCost;
}
+15 -1
View File
@@ -229,6 +229,10 @@ function isValidPricingRateTriplet(entry) {
* 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。
* 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。
*/
function sanitizeOptionalImageOutputRate(val) {
return typeof val === 'number' && Number.isFinite(val) && val > 0 && val <= 10000 ? val : null;
}
function sanitizePricingPhase(rawPhase) {
if (!isValidPricingRateTriplet(rawPhase)) return null;
let from = null;
@@ -251,12 +255,14 @@ function sanitizePricingPhase(rawPhase) {
}
if (from === null && until === null) return null;
if (fromMs >= untilMs) return null;
const imageOutput = sanitizeOptionalImageOutputRate(rawPhase.imageOutput);
return {
...(from !== null ? { from, fromMs } : {}),
...(until !== null ? { until, untilMs } : {}),
input: rawPhase.input,
cache: rawPhase.cache,
output: rawPhase.output,
...(imageOutput !== null ? { imageOutput } : {}),
};
}
@@ -305,10 +311,12 @@ export function sanitizeCatalogPayload(raw) {
phases = cleanedPhases;
}
}
const imageOutput = sanitizeOptionalImageOutputRate(v.imageOutput);
pricing[key] = {
input: v.input,
cache: v.cache,
output: v.output,
...(imageOutput !== null ? { imageOutput } : {}),
short: String(v.short).trim(),
family: normalizeModelFamily(v.family),
...(phases ? { phases } : {}),
@@ -413,7 +421,13 @@ export function rebuildActiveCatalog() {
: DEFAULT_ARCHIVE_FALLBACK_URL;
for (const { kind, cat } of layers) {
Object.assign(nextPricing, cat.pricing);
for (const [pk, pv] of Object.entries(cat.pricing)) {
const prevImgOut = nextPricing[pk]?.imageOutput;
nextPricing[pk] =
prevImgOut !== undefined && pv.imageOutput === undefined
? { ...pv, imageOutput: prevImgOut }
: pv;
}
Object.assign(nextPlaceholders, cat.placeholders);
if (kind === 'remote' || cat.catalogVersion || cat.updatedAt) {
activeSource = kind;
+7 -2
View File
@@ -370,9 +370,14 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
}
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs);
const cfgResetMs = parseIsoMs(cfgQuota?.resetTime);
const isCfgWeekly =
targetIdent.poolKey === 'Argon' ||
targetIdent.poolKey === 'Carbon' ||
cfgResetMs > nowForQuotaMs + 6 * 3600 * 1000;
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') {
builder.bucketWeekly = cfgQuota;
if (isCfgWeekly) {
builder.bucketWeekly = { ...cfgQuota, window: 'weekly' };
} else {
builder.fallback5h = cfgQuota;
}
File diff suppressed because it is too large Load Diff
+83 -35
View File
@@ -202,6 +202,8 @@ function migratorDecodeMetaBlobLight(rawBlob) {
let workspaceUri = '';
let projectId = '';
let parentConversationId = '';
let nestingDepth = 0;
let hasSubagentSpec = false;
let createdMs = 0;
for (const field of fields) {
if (field.fn === 7 && field.wt === 2 && !workspaceUri) {
@@ -212,8 +214,24 @@ function migratorDecodeMetaBlobLight(rawBlob) {
if (fn1) workspaceUri = fn1.payload.toString('utf8').trim();
} else if (field.fn === 18 && field.wt === 2) {
projectId = field.payload.toString('utf8').trim();
} else if (field.fn === 9 && field.wt === 2) {
} else if (field.fn === 5 && field.wt === 2) {
parentConversationId = field.payload.toString('utf8').trim().toLowerCase();
} else if (field.fn === 8 && field.wt === 2 && field.payload.length > 0) {
const specFields = splitProtoRawFields(field.payload);
if (
specFields.some(
(sf) =>
(sf.fn === 1 || sf.fn === 2) &&
sf.wt === 2 &&
sf.payload.toString('utf8').trim().length > 0
)
) {
hasSubagentSpec = true;
}
} else if (field.fn === 17 && field.wt === 0) {
const st = { off: 0 };
const depth = Number(BigInt.asIntN(32, readProtoVarint(field.payload, st, field.payload.length)));
if (Number.isFinite(depth) && depth > 0) nestingDepth = depth;
} else if (field.fn === 2 && field.wt === 2 && !createdMs) {
const tsFields = splitProtoRawFields(field.payload);
const secField = tsFields.find((item) => item.fn === 1 && item.wt === 0);
@@ -224,7 +242,55 @@ function migratorDecodeMetaBlobLight(rawBlob) {
}
}
}
return { workspaceUri, projectId, parentConversationId, createdMs };
return {
workspaceUri,
projectId,
parentConversationId,
nestingDepth,
hasSubagentSpec,
createdMs,
};
}
function migratorIsDbLightNonRoot(dbLight) {
if (!dbLight) return false;
return Boolean(
dbLight.trajectoryType === 22 ||
dbLight.sourceNum === 16 ||
dbLight.parentConversationId ||
Number(dbLight.nestingDepth || 0) > 0 ||
dbLight.hasSubagentSpec
);
}
function migratorIsSummaryNonRoot(summary) {
if (!summary) return false;
const parentId = String(summary.parent_conversation_id || '').trim();
const depth = Number(summary.nesting_depth || 0);
const sourceStr = String(summary.source || '').trim();
if (parentId || depth > 0 || sourceStr === 'CORTEX_TRAJECTORY_SOURCE_SUBAGENT') {
return true;
}
if (summary.raw_summary) {
const rawFields = splitProtoRawFields(summary.raw_summary);
for (const f of rawFields) {
if (f.fn === 22 && f.wt === 0) {
const st = { off: 0 };
const ttVal = Number(BigInt.asUintN(32, readProtoVarint(f.payload, st, f.payload.length)));
if (ttVal === 22) return true; // 旁路提问
} else if (f.fn === 20 && f.wt === 0) {
const st = { off: 0 };
const srcVal = Number(BigInt.asUintN(32, readProtoVarint(f.payload, st, f.payload.length)));
if (srcVal === 16) return true; // CORTEX_TRAJECTORY_SOURCE_SUBAGENT
} else if (f.fn === 17 && f.wt === 2) {
const sumMeta = migratorDecodeMetaBlobLight(f.payload);
if (sumMeta.parentConversationId || sumMeta.nestingDepth > 0 || sumMeta.hasSubagentSpec) {
return true;
}
}
}
}
return false;
}
function migratorInspectConversationDbLight(dbPath, { needPromptTitle = false } = {}) {
@@ -271,7 +337,14 @@ function migratorInspectConversationDbLight(dbPath, { needPromptTitle = false }
// 忽略步骤读取异常
}
let metaBlobInfo = { workspaceUri: '', projectId: '', parentConversationId: '', createdMs: 0 };
let metaBlobInfo = {
workspaceUri: '',
projectId: '',
parentConversationId: '',
nestingDepth: 0,
hasSubagentSpec: false,
createdMs: 0,
};
try {
const blobRow = db
.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1")
@@ -488,20 +561,7 @@ function migratorListClientSessions(clientDef, clientRoot, summaryMap, runningSe
if (sessions.length >= MIGRATOR_MAX_SESSIONS_PER_CLIENT) break;
const { cid, summary, info } = cand;
if (summary) {
const parentId = String(summary.parent_conversation_id || '').trim();
const depth = Number(summary.nesting_depth || 0);
if (parentId || depth > 0) continue;
if (summary.raw_summary) {
const rawFields = splitProtoRawFields(summary.raw_summary);
const ttField = rawFields.find((f) => f.fn === 22 && f.wt === 0);
if (ttField) {
const st = { off: 0 };
const ttVal = Number(BigInt.asUintN(32, readProtoVarint(ttField.payload, st, ttField.payload.length)));
if (ttVal === 22) continue; // 跳过旁路提问
}
}
}
if (migratorIsSummaryNonRoot(summary)) continue;
const annTitle = migratorReadAnnotationTitle(clientRoot, cid);
const sumTitle = String(summary?.title || '').trim();
@@ -519,9 +579,7 @@ function migratorListClientSessions(clientDef, clientRoot, summaryMap, runningSe
});
}
if (dbLight) {
if (dbLight.trajectoryType === 22 || dbLight.parentConversationId) continue;
}
if (migratorIsDbLightNonRoot(dbLight)) continue;
const stepCount =
summaryStepCount >= 0 ? summaryStepCount : Math.max(0, Number(dbLight?.stepCount || 0));
@@ -691,7 +749,7 @@ function migratorBuildWorkspaceSubmessage(rawUri, targetClientId) {
function migratorBuildSummaryMetaBlob(
sourceMetaBlob,
{ srcCid = '', newCid, targetClientId, targetProjectId, rawUri, encodedUri }
{ newCid, targetClientId, targetProjectId, rawUri, encodedUri }
) {
const wsBytes = migratorBuildWorkspaceSubmessage(rawUri, targetClientId);
const primaryUri = targetClientId === 'cli' ? rawUri : encodedUri;
@@ -703,12 +761,6 @@ function migratorBuildSummaryMetaBlob(
[18, encodeProtoStringField(18, targetProjectId)],
]);
if (sourceMetaBlob && sourceMetaBlob.byteLength > 0) {
if (srcCid) {
const fn8 = splitProtoRawFields(sourceMetaBlob).find((f) => f.fn === 8 && f.wt === 2);
if (fn8 && fn8.payload.toString('utf8').trim().toLowerCase() === srcCid) {
replacements.set(8, encodeProtoStringField(8, newCid));
}
}
return patchProtoMessageFields(sourceMetaBlob, replacements);
}
const parts = [];
@@ -819,7 +871,6 @@ function migratorPatchGenMetadataOwnership(rawBlob, srcCid, newCid) {
function migratorBuildPatchedRawSummary({
sourceRawSummary,
sourceMetaBlob,
srcCid = '',
newCid,
newTid,
title,
@@ -845,7 +896,6 @@ function migratorBuildPatchedRawSummary({
const rawFields = splitProtoRawFields(sourceRawSummary);
const fn17 = rawFields.find((f) => f.fn === 17 && f.wt === 2);
const patchedFn17 = migratorBuildSummaryMetaBlob(fn17?.payload || sourceMetaBlob, {
srcCid,
newCid,
targetClientId,
targetProjectId,
@@ -875,7 +925,6 @@ function migratorBuildPatchedRawSummary({
const createdTsBytes = encodeProtoTimestamp(createdMs || nowMs);
const lastUiTsBytes = encodeProtoTimestamp(lastUserInputMs || nowMs);
const synthMeta = migratorBuildSummaryMetaBlob(sourceMetaBlob, {
srcCid,
newCid,
targetClientId,
targetProjectId,
@@ -1100,6 +1149,10 @@ export function migrateSessions(params = {}, options = {}) {
const dbLight = migratorInspectConversationDbLight(srcDbPath, {
needPromptTitle: !annTitle && !srcSummary?.title && !srcSummary?.preview,
});
if (migratorIsSummaryNonRoot(srcSummary) || migratorIsDbLightNonRoot(dbLight)) {
results.push({ ok: false, sourceCascadeId: srcCid, error: 'non_root_session' });
continue;
}
const stepCount = Math.max(
0,
Number(srcSummary?.step_count ?? dbLight?.stepCount ?? 0)
@@ -1186,10 +1239,6 @@ export function migrateSessions(params = {}, options = {}) {
[7, primaryMetaUri ? encodeProtoStringField(7, primaryMetaUri) : null],
[18, encodeProtoStringField(18, resolvedProjectId)],
]);
const fn8 = splitProtoRawFields(sourceMetaBlob).find((f) => f.fn === 8 && f.wt === 2);
if (fn8 && fn8.payload.toString('utf8').trim().toLowerCase() === srcCid) {
metaReplacements.set(8, encodeProtoStringField(8, newCid));
}
const patchedMeta = patchProtoMessageFields(sourceMetaBlob, metaReplacements);
dstDb
.prepare("UPDATE trajectory_metadata_blob SET data = ? WHERE id = 'main'")
@@ -1304,7 +1353,6 @@ export function migrateSessions(params = {}, options = {}) {
const patchedRawSummary = migratorBuildPatchedRawSummary({
sourceRawSummary: srcSummary?.raw_summary || null,
sourceMetaBlob,
srcCid,
newCid,
newTid,
title: finalTitle,
@@ -6,8 +6,10 @@
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
import {
ACCOUNT_QUOTA_REFRESH_MINUTES,
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
@@ -32,6 +34,7 @@ import {
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalModernUi,
@@ -59,8 +62,10 @@ import {
} from '../shared/settings-normalization.mjs';
export {
ACCOUNT_QUOTA_REFRESH_MINUTES,
CLI_STATUSLINE_PRESETS,
CONTEXT_AGENT_MODES,
DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES,
DEFAULT_CLI_STATUSLINE_SLOTS,
DEFAULT_CONTEXT_AGENT_MODE,
DEFAULT_HOVER_MODULES,
@@ -85,6 +90,7 @@ export {
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalModernUi,
@@ -162,6 +168,8 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT,
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
experimentalQuotaReservation: true,
accountQuotaRefreshMinutes: DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES,
accountSwitchRiskAccepted: false,
contextWindowRiskAccepted: false,
contextWindowMainEnabled: true,
contextWindowSwarmEnabled: false,
@@ -246,6 +254,10 @@ export function normalizeFullSettings(rawInput) {
experimentalQuotaReservation: normalizeExperimentalQuotaReservation(
safeRaw.experimentalQuotaReservation
),
accountQuotaRefreshMinutes: normalizeAccountQuotaRefreshMinutes(
safeRaw.accountQuotaRefreshMinutes
),
accountSwitchRiskAccepted: safeRaw.accountSwitchRiskAccepted === true,
contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true,
contextWindowMainEnabled: safeRaw.contextWindowMainEnabled !== false,
contextWindowSwarmEnabled: safeRaw.contextWindowSwarmEnabled === true,
@@ -14,6 +14,8 @@ import {
dispatchBridgeApiRequest,
} from './api-actions.mjs';
import { computeRuntimeCodeVersion } from './config.mjs';
import { flushAccountQuotaHistoryNow } from './account-quota-history.mjs';
import { flushAllEndpointCachesNow } from './endpoint-registry.mjs';
let shuttingDown = false;
let reloadRequested = false;
@@ -50,6 +52,12 @@ async function gracefulStop() {
if (shuttingDown) return;
shuttingDown = true;
clearInterval(driftWatchTimer);
try {
flushAccountQuotaHistoryNow();
flushAllEndpointCachesNow();
} catch {
// Ignore cache flush errors
}
try {
await bridgeController?.stop?.({ disposeWindows: false });
} catch {
+118 -2
View File
@@ -7,9 +7,15 @@
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
*/
import { existsSync, statSync } from 'node:fs';
import { closeSync, existsSync, openSync, readSync, statSync } from 'node:fs';
export const SQLITE_IN_CHUNK_SIZE = 400;
const SQLITE_MIN_READY_BYTES = 4096;
const SQLITE_HEADER_BYTES = 100;
const SQLITE_WAL_HEADER_BYTES = 32;
const SQLITE_MAGIC_PREFIX = 'SQLite format 3\0';
const MAX_SQLITE_READY_MEMO = 512;
const sqliteWalReadyMemo = new Map();
let sqliteResolved = false;
let sqliteDatabaseSyncCtor = null;
@@ -59,8 +65,117 @@ export function hasBuiltinNodeSqlite() {
return Boolean(getNodeSqliteDatabaseSync());
}
/**
* 通过零 SQLite 锁的 100 字节文件头探测判断本地 `.db` 是否已完成表结构初始化(或已切入 WAL 且含有效提交帧)。
*
* Windows 下宿主(如 `agy` CLI)新建 `<cid>.db` 执行 `schema init` / `PRAGMA journal_mode = WAL` 的数毫秒内,
* 若外部进程对 0 字节或仍处于回滚日志模式(`writeVersion !== 2`)的库发起 `sqlite3_open_v2` 查询并持有 `SHARED` 锁,
* 会直接触发宿主 `trajectory db schema init: database is locked` 并迫使整场会话永久降级至加密 `.pb`。
* 纯 `fs.openSync` / `fs.readSync` 不申请任何 SQLite 字节区间锁(`LockFileEx`),可安全跳过初始化途中的半成品库。
*
* @param {string} dbPath
* @param {{ dbStat?: import('node:fs').Stats | null, walStat?: import('node:fs').Stats | null, skipWalStat?: boolean }} [opts={}]
* @returns {boolean}
*/
export function isSqliteDbReadyForRead(
dbPath,
{ dbStat: preDbStat = null, walStat: preWalStat = null, skipWalStat = false } = {}
) {
if (!dbPath || typeof dbPath !== 'string') return false;
if (
typeof openSync !== 'function' ||
typeof readSync !== 'function' ||
typeof closeSync !== 'function'
) {
return typeof globalThis.DatabaseSync === 'function';
}
let dbStat = preDbStat;
if (!dbStat) {
try {
dbStat = statSync(dbPath, { throwIfNoEntry: false });
} catch {
return false;
}
}
const dbSize = Number(dbStat?.size || 0);
if (!dbStat || dbSize < SQLITE_MIN_READY_BYTES) {
sqliteWalReadyMemo.delete(dbPath);
return false;
}
const birthKey = `${Number(dbStat.birthtimeMs || 0)}:${Number(dbStat.ino || 0)}`;
const cachedReady = sqliteWalReadyMemo.get(dbPath);
if (cachedReady && cachedReady.birthKey === birthKey && dbSize >= cachedReady.minVerifiedSize) {
return true;
}
try {
const journalStat = statSync(`${dbPath}-journal`, { throwIfNoEntry: false });
if (journalStat && Number(journalStat.size || 0) > 0) {
return false;
}
} catch {
// 忽略瞬时回滚日志探测异常
}
let fd = -1;
try {
fd = openSync(dbPath, 'r');
const header = Buffer.allocUnsafe(SQLITE_HEADER_BYTES);
const bytesRead = readSync(fd, header, 0, SQLITE_HEADER_BYTES, 0);
if (bytesRead < SQLITE_HEADER_BYTES) return false;
if (header.toString('latin1', 0, 16) !== SQLITE_MAGIC_PREFIX) return false;
const writeVersion = header[18];
const readVersion = header[19];
const pageCount = header.readUInt32BE(28);
const schemaCookie = header.readUInt32BE(40);
const isWalMode = writeVersion === 2 && readVersion === 2;
if (isWalMode) {
let hasCommittedSchema = pageCount >= 2 && schemaCookie > 0;
if (!hasCommittedSchema) {
let walStat = preWalStat;
if (!walStat && !skipWalStat) {
try {
walStat = statSync(`${dbPath}-wal`, { throwIfNoEntry: false });
} catch {
walStat = null;
}
}
hasCommittedSchema = Number(walStat?.size || 0) > SQLITE_WAL_HEADER_BYTES;
}
if (!hasCommittedSchema) return false;
if (sqliteWalReadyMemo.size >= MAX_SQLITE_READY_MEMO && !sqliteWalReadyMemo.has(dbPath)) {
const oldestKey = sqliteWalReadyMemo.keys().next().value;
if (oldestKey !== undefined) sqliteWalReadyMemo.delete(oldestKey);
}
sqliteWalReadyMemo.set(dbPath, {
birthKey,
minVerifiedSize: SQLITE_MIN_READY_BYTES,
});
return true;
}
return pageCount >= 2 && schemaCookie > 0;
} catch {
return false;
} finally {
if (fd >= 0) {
try {
closeSync(fd);
} catch {
// 忽略关闭异常
}
}
}
}
/**
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
* 实际打开前由 `withReadOnlySqliteDb` 经 `isSqliteDbReadyForRead` 拦截未完成 `schema init` 的空文件。
*
* @param {string} dbPath
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
@@ -104,7 +219,7 @@ export function isSqliteBusyError(err) {
/**
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
* 打开前先执行无锁头部就绪校验;遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
*
* @template T
* @param {string} dbPath
@@ -114,6 +229,7 @@ export function isSqliteBusyError(err) {
export function withReadOnlySqliteDb(dbPath, queryFn) {
const DatabaseSync = getNodeSqliteDatabaseSync();
if (!DatabaseSync) return null;
if (!isSqliteDbReadyForRead(dbPath)) return null;
for (let attempt = 0; attempt < 2; attempt++) {
let db = null;
try {
+57 -14
View File
@@ -16,12 +16,12 @@ import {
readLocalAsync,
} from './api-actions.mjs';
import { loadSettings, lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs';
import { flushAllEndpointCachesNow } from './endpoint-registry.mjs';
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
import { syncCloudCatalog } from './plugin-updater.mjs';
const MAX_JSON_BODY_BYTES = 1024 * 1024;
const MAX_EXPORT_JSON_BODY_BYTES = 8 * 1024 * 1024;
const AUTH_COOKIE_NAME = 'ag_um_token';
const NO_STORE_HEADERS = {
'Cache-Control': 'no-store, no-cache, must-revalidate',
@@ -512,10 +512,20 @@ export function createStandaloneWebServer(options = {}) {
}
if (pathname.startsWith('/api/')) {
if (
(pathname === '/api/export-file' || pathname === '/api/reveal-file') &&
!isLoopbackRemoteAddress(req.socket?.remoteAddress)
) {
if (pathname === '/api/accounts' || pathname === '/api/accounts/update') {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
supported: false,
accounts: [],
error: 'unsupported',
})
);
return;
}
if (pathname === '/api/export-file' || pathname === '/api/reveal-file') {
sendResponse(
res,
403,
@@ -523,7 +533,25 @@ export function createStandaloneWebServer(options = {}) {
JSON.stringify({
ok: false,
fallbackBrowser: true,
error: 'Local file export is restricted to loopback clients',
error: 'Standalone web mode uses browser file download instead of server disk export',
})
);
return;
}
const remoteAddr = String(req.socket?.remoteAddress || '').trim();
const isLoopbackClient =
!remoteAddr ||
remoteAddr === '127.0.0.1' ||
remoteAddr === '::1' ||
remoteAddr === '::ffff:127.0.0.1';
if (pathname === '/api/host-i18n' && method === 'POST' && !isLoopbackClient) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
error: 'Host I18n mutations are only allowed from loopback clients',
})
);
return;
@@ -533,11 +561,7 @@ export function createStandaloneWebServer(options = {}) {
data = Object.fromEntries(urlObj.searchParams.entries());
delete data.token;
} else if (method === 'POST') {
const maxBody =
pathname === '/api/export-file' || pathname === '/api/settings'
? MAX_EXPORT_JSON_BODY_BYTES
: MAX_JSON_BODY_BYTES;
const rawBody = await readRawBody(req, maxBody);
const rawBody = await readRawBody(req, MAX_JSON_BODY_BYTES);
if (rawBody.trim()) {
try {
data = JSON.parse(rawBody);
@@ -557,8 +581,26 @@ export function createStandaloneWebServer(options = {}) {
pathname === '/api/settings' &&
data &&
typeof data === 'object' &&
typeof data.__exportFileAction === 'string' &&
!isLoopbackRemoteAddress(req.socket?.remoteAddress)
typeof data.__hostI18nAction === 'string' &&
data.__hostI18nAction !== 'get' &&
!isLoopbackClient
) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
error: 'Host I18n mutations are only allowed from loopback clients',
})
);
return;
}
if (
pathname === '/api/settings' &&
data &&
typeof data === 'object' &&
typeof data.__exportFileAction === 'string'
) {
sendResponse(
res,
@@ -567,7 +609,7 @@ export function createStandaloneWebServer(options = {}) {
JSON.stringify({
ok: false,
fallbackBrowser: true,
error: 'Local file export is restricted to loopback clients',
error: 'Standalone web mode uses browser file download instead of server disk export',
})
);
return;
@@ -652,6 +694,7 @@ export function createStandaloneWebServer(options = {}) {
}
async function stop() {
flushAllEndpointCachesNow();
const srv = server;
server = null;
boundPort = 0;
+406 -33
View File
@@ -45,6 +45,7 @@ import {
} from './model-pricing.mjs';
import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs';
import { buildOfficialQuotaPools } from './quota-pools.mjs';
import { recordAccountQuotaSnapshot } from './account-quota-history.mjs';
import { updatePoolQuotaReservationEstimates } from './quota-reservation.mjs';
import { getDefaultCloudCodeProxyStatus } from './cloudcode-proxy.mjs';
import { getDefaultWindowBridgeStatus } from './window-bridge.mjs';
@@ -93,9 +94,16 @@ function roundSessionCost(val) {
return val < 0.01 ? +val.toFixed(4) : +val.toFixed(2);
}
function findTrajectoryCacheEntry(cascadeId, cacheStore = null) {
function findTrajectoryCacheEntry(cascadeId, cacheStore = null, { hydrate = false } = {}) {
if (!cascadeId) return null;
const store = cacheStore || getEndpointCacheStore(null);
if (hydrate && typeof store.getHydratedTrajectoryEntryByLower === 'function') {
return store.getHydratedTrajectoryEntryByLower(cascadeId)?.entry || null;
}
if (hydrate && typeof store.getHydratedTrajectory === 'function') {
const hit = store.getHydratedTrajectory(cascadeId);
if (hit) return hit;
}
if (typeof store.getCachedTrajectoryEntryByLower === 'function') {
return store.getCachedTrajectoryEntryByLower(cascadeId)?.entry || null;
}
@@ -130,7 +138,7 @@ function readTrajectoryModelFacts(steps) {
fallbackModelKeys.add(step.modelKey);
}
}
if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
if (!step?.isCompactionStep && !step?.isImageGenStep && step?.reportedContextLimitTokens > 0) {
sortableLimits &&= Number.isFinite(step.createdAtMs);
rememberModelContextLimit(limits, step);
}
@@ -149,6 +157,16 @@ function buildKnownUpstreamModelMap(contextLimits, cacheStore = null) {
const facts = readTrajectoryModelFacts(entry.steps);
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
if (entry.subagentSpec) continue;
if (Array.isArray(entry._stepFlags?.modelLimits) && entry._stepFlags.modelLimits.length > 0) {
for (const [key, tokens, at] of entry._stepFlags.modelLimits) {
if (!key || !(tokens > 0)) continue;
const previous = contextLimits.get(key);
if (!previous || at > previous.at) {
contextLimits.set(key, { tokens, at });
}
}
continue;
}
if (facts.limits) {
for (const [key, limit] of facts.limits) {
const previous = contextLimits.get(key);
@@ -209,7 +227,15 @@ function enrichActiveConversationSteps(
const cacheCostUsd = mInfo.pricing
? (st.cacheReadTokens / 1_000_000) * mInfo.pricing.cache
: null;
const outCostUsd = mInfo.pricing ? (st.outputTokens / 1_000_000) * mInfo.pricing.output : null;
const effectiveOutRate = mInfo.pricing
? st.isImageGenStep &&
typeof mInfo.pricing.imageOutput === 'number' &&
mInfo.pricing.imageOutput > 0
? mInfo.pricing.imageOutput
: mInfo.pricing.output
: null;
const outCostUsd =
effectiveOutRate !== null ? (st.outputTokens / 1_000_000) * effectiveOutRate : null;
const resolvedResponseModel =
st.responseModel ||
(st.modelKey && st.modelKey !== 'unknown'
@@ -296,11 +322,13 @@ function enrichActiveConversationSteps(
const latestEnriched =
enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null;
const lastKnownTtftSec = findLastValidStepTtft(enrichedActiveSteps);
const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec);
return {
enrichedActiveSteps,
latestEnriched,
lastKnownTtftSec,
sessionSpeed,
sessionTtft,
sessionAvgTokPerSec,
@@ -312,6 +340,21 @@ function enrichActiveConversationSteps(
};
}
function findLastValidStepTtft(steps) {
if (!Array.isArray(steps)) return null;
for (let i = steps.length - 1; i >= 0; i -= 1) {
const candidateTtft = steps[i]?.ttftSec;
if (
candidateTtft != null &&
Number.isFinite(Number(candidateTtft)) &&
Number(candidateTtft) >= 0
) {
return Number(candidateTtft);
}
}
return null;
}
const CONTEXT_CHANNEL_KEYS = [
'userInput',
'assistant',
@@ -325,6 +368,35 @@ const CONTEXT_CHANNEL_KEYS = [
'userRules',
];
const STATIC_CONTEXT_CHANNEL_KEYS = [
'systemTools',
'mcpTools',
'skills',
'systemPrompt',
'userRules',
];
function applyFallbackStaticChannels(channels, fallbackStaticContext, capTotal = 0) {
if (!fallbackStaticContext || typeof fallbackStaticContext !== 'object') return 0;
let staticMap = {
systemTools: Math.max(0, Math.round(Number(fallbackStaticContext.systemToolsTokens || 0))),
mcpTools: Math.max(0, Math.round(Number(fallbackStaticContext.mcpToolsTokens || 0))),
skills: Math.max(0, Math.round(Number(fallbackStaticContext.skillsTokens || 0))),
systemPrompt: Math.max(0, Math.round(Number(fallbackStaticContext.systemPromptTokens || 0))),
userRules: Math.max(0, Math.round(Number(fallbackStaticContext.userRulesTokens || 0))),
};
let staticSum = STATIC_CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + staticMap[k], 0);
if (staticSum <= 0) return 0;
if (capTotal > 0 && staticSum > capTotal) {
staticMap = scaleBucketsExact(staticMap, STATIC_CONTEXT_CHANNEL_KEYS, Math.round(capTotal));
staticSum = STATIC_CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + staticMap[k], 0);
}
for (const k of STATIC_CONTEXT_CHANNEL_KEYS) {
channels[k] = staticMap[k];
}
return staticSum;
}
function resolveStepOutputTokens(st) {
const explicitOut = Number(st?.outputTokens || 0);
if (explicitOut > 0) return explicitOut;
@@ -388,7 +460,8 @@ function extractActiveContextTelemetry(
enrichedActiveSteps,
latestEnriched,
sessionInputTokens,
sessionCacheReadTokens
sessionCacheReadTokens,
fallbackStaticContext = null
) {
let lastCompactionIdx = -1;
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
@@ -427,6 +500,7 @@ function extractActiveContextTelemetry(
for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) {
const stepM = enrichedActiveSteps[m];
if (!stepM || stepM.isCompactionStep) break;
if (stepM.isImageGenStep) continue;
const mPrompt =
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
const mOut = resolveStepOutputTokens(stepM);
@@ -470,6 +544,8 @@ function extractActiveContextTelemetry(
channels.skills = preChannels.skills;
channels.systemPrompt = preChannels.systemPrompt;
channels.userRules = preChannels.userRules;
} else if (fallbackStaticContext) {
applyFallbackStaticChannels(channels, fallbackStaticContext, 0);
}
channels.userInput = 0;
channels.assistant = 0;
@@ -480,7 +556,7 @@ function extractActiveContextTelemetry(
let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
for (let m = lastCompactionIdx + 1; m < enrichedActiveSteps.length; m++) {
const stepM = enrichedActiveSteps[m];
if (!stepM || stepM.isCompactionStep) continue;
if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue;
const mPrompt =
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
const mOut = resolveStepOutputTokens(stepM);
@@ -499,6 +575,59 @@ function extractActiveContextTelemetry(
runningTotal = mPrompt + mOut;
}
}
} else if (enrichedActiveSteps.length > 0) {
// 当宿主回退或历史裁剪导致全部步骤均无 `contextBreakdown` 且未发生过压缩时,
// 基于缓存的 5 通道静态基线(如有)和各步真实计费增量重建上下文通道,避免进度条和 10 项图例全归零。
let runningTotal = 0;
let seededInitial = false;
for (let m = 0; m < enrichedActiveSteps.length; m++) {
const stepM = enrichedActiveSteps[m];
if (!stepM || stepM.isCompactionStep || stepM.isImageGenStep) continue;
const mPrompt =
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
const mOut = resolveStepOutputTokens(stepM);
if (!seededInitial) {
if (mPrompt <= 0 && mOut <= 0) continue;
seededInitial = true;
if (mPrompt > 0) {
const staticUsed = applyFallbackStaticChannels(
channels,
fallbackStaticContext,
mPrompt
);
channels.userInput += Math.max(0, mPrompt - staticUsed);
}
channels.assistant += mOut;
runningTotal = mPrompt + mOut;
} else if (mPrompt > 0) {
if (mPrompt > runningTotal) {
const delta = mPrompt - runningTotal;
if (enrichedActiveSteps[m - 1]?.hasToolCalls) {
channels.toolResults += delta;
} else {
channels.userInput += delta;
}
} else if (mPrompt < runningTotal) {
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt);
}
channels.assistant += mOut;
runningTotal = mPrompt + mOut;
}
}
if (runningTotal === 0) {
const estFallback = Math.max(
0,
Math.round(Number(latestEnriched?.estimatedContextTokens || 0))
);
if (estFallback > 0) {
const staticUsed = applyFallbackStaticChannels(
channels,
fallbackStaticContext,
estFallback
);
channels.userInput += Math.max(0, estFallback - staticUsed);
}
}
}
const ctxUserInput = channels.userInput;
@@ -516,25 +645,39 @@ function extractActiveContextTelemetry(
const ctxBreakdownTotal =
ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules;
const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep);
const ctxCached = latestEnriched?.cacheReadTokens || 0;
const ctxFreshInput = latestEnriched?.inputTokens || 0;
const ctxThinking = latestEnriched?.thinkingTokens || 0;
const ctxResponse = latestEnriched?.responseTokens || 0;
const ctxOut = resolveStepOutputTokens(latestEnriched);
let ctxRefStep = latestEnriched;
if (ctxRefStep?.isImageGenStep) {
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
if (!enrichedActiveSteps[i]?.isImageGenStep) {
ctxRefStep = enrichedActiveSteps[i];
break;
}
}
}
const isLatestCompaction = Boolean(ctxRefStep?.isCompactionStep);
const ctxCached = ctxRefStep?.cacheReadTokens || 0;
const ctxFreshInput = ctxRefStep?.inputTokens || 0;
const ctxThinking = ctxRefStep?.thinkingTokens || 0;
const ctxResponse = ctxRefStep?.responseTokens || 0;
const ctxOut = resolveStepOutputTokens(ctxRefStep);
const ctxTotal = isLatestCompaction
? ctxBreakdownTotal
: ctxBreakdownTotal > 0
? ctxBreakdownTotal
: ctxCached + ctxFreshInput + ctxOut;
: (ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput + ctxOut) ||
Number(ctxRefStep?.estimatedContextTokens || 0);
const compactionLimitTokens = Number(
(isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
(isLatestCompaction && !ctxRefStep?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
? fallbackPreCompactionLimit
: latestEnriched?.maxContextBudgetTokens) || 256000
: ctxRefStep?.maxContextBudgetTokens) || 256000
);
const compactionUsedTokens = isLatestCompaction
? Number(ctxTotal)
: Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput);
: Number(
ctxTotal ||
ctxRefStep?.estimatedContextTokens ||
(ctxRefStep?.isImageGenStep ? 0 : ctxCached + ctxFreshInput)
);
const compactionUsedPct =
compactionLimitTokens > 0
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
@@ -598,7 +741,14 @@ function sameFallbackUpstreams(prevMap, fallbackModelKeys, upstream) {
return true;
}
function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, reuseInputs) {
function prepareAgentSteps(
rawSteps,
resolveStepModel,
upstream,
agentFields,
reuseInputs,
fallbackStaticContext = null
) {
const facts = readTrajectoryModelFacts(rawSteps);
for (const [key, model] of facts.upstream) upstream.set(key, model);
const canCache = Boolean(reuseInputs && Array.isArray(rawSteps));
@@ -610,6 +760,7 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
previous.catalogRevision === reuseInputs.catalogRevision &&
previous.phaseEpoch === reuseInputs.phaseEpoch &&
isDeepStrictEqual(previous.dynamicModelMap, reuseInputs.dynamicModelMap) &&
isDeepStrictEqual(previous.fallbackStaticContext || null, fallbackStaticContext || null) &&
sameFallbackUpstreams(previous.fallbackUpstreams, facts.fallbackModelKeys, upstream)
) {
return previous.prepared;
@@ -620,8 +771,13 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
const prepared = {
enrichedRes,
recentSteps: taggedSteps.slice().reverse(),
ctxRes: extractActiveContextTelemetry(taggedSteps, enrichedRes.latestEnriched,
enrichedRes.sessionInputTokens, enrichedRes.sessionCacheReadTokens),
ctxRes: extractActiveContextTelemetry(
taggedSteps,
enrichedRes.latestEnriched,
enrichedRes.sessionInputTokens,
enrichedRes.sessionCacheReadTokens,
fallbackStaticContext
),
modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel),
};
// 按 rawSteps 数组引用缓存各代理(含多代理子代理)步骤富化结果,步骤变更后由 WeakMap 自动淘汰。
@@ -631,6 +787,7 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
catalogRevision: reuseInputs.catalogRevision,
phaseEpoch: reuseInputs.phaseEpoch,
dynamicModelMap: reuseInputs.dynamicModelMap,
fallbackStaticContext: fallbackStaticContext || null,
fallbackUpstreams: snapshotFallbackUpstreams(facts.fallbackModelKeys, upstream),
prepared,
});
@@ -660,6 +817,7 @@ export function buildAgentUnitTelemetry({
agentLabel,
status,
rawSteps,
fallbackStaticContext = null,
liveActivity = null,
fallbackLastModMs,
resolveStepModel,
@@ -684,7 +842,8 @@ export function buildAgentUnitTelemetry({
isSubagent: !isMain,
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
},
reuseInputs
reuseInputs,
fallbackStaticContext
);
const taggedSteps = enrichedRes.enrichedActiveSteps;
const lastModifiedMs =
@@ -721,6 +880,7 @@ export function buildAgentUnitTelemetry({
stepCount: taggedSteps.length,
latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null,
latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null,
lastKnownTtftSec: enrichedRes.lastKnownTtftSec ?? null,
latestSpeedReason: enrichedRes.latestEnriched?.selectedSpeedReason ?? null,
avgTokPerSec: enrichedRes.sessionAvgTokPerSec,
speedSummary: enrichedRes.sessionSpeed,
@@ -782,6 +942,7 @@ async function readTelemetrySources(
summariesObj: localSummaries.available
? localSummaries.summariesObj
: allTrajRes?.trajectorySummaries || {},
summariesFromLocalDb: localSummaries.available,
sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {},
currentAccountName: accountScope,
requestedConvId,
@@ -930,7 +1091,7 @@ function buildActiveConversationAssembly({
const cacheKey = `${epKey}::${String(activeCascadeId || '__empty__').toLowerCase()}`;
const subEntries = subagentSummaries.map((subSum) =>
findTrajectoryCacheEntry(subSum.cascadeId, cacheStore)
findTrajectoryCacheEntry(subSum.cascadeId, cacheStore, { hydrate: true })
);
const subRawStepsList = subEntries.map((entry) => entry?.steps || []);
const combinedFallbackKeys = new Set();
@@ -951,6 +1112,7 @@ function buildActiveConversationAssembly({
activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
activeConvSummary?.liveActivity?.signature || '',
activeConvSummary?.liveActivity?.startedAtMs || 0,
activeEntry?.lastKnownStaticContext || null,
subagentSummaries.map((subSum, idx) => {
const subEntry = subEntries[idx];
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
@@ -967,6 +1129,7 @@ function buildActiveConversationAssembly({
subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
subSum.liveActivity?.signature || '',
subSum.liveActivity?.startedAtMs || 0,
subEntry?.lastKnownStaticContext || null,
subSpec?.role || '',
subSpec?.typeName || '',
];
@@ -1007,6 +1170,7 @@ function buildActiveConversationAssembly({
agentLabel: '主代理',
status: activeConvSummary?.status || 'IDLE',
rawSteps: activeSteps,
fallbackStaticContext: activeEntry?.lastKnownStaticContext || null,
liveActivity: activeConvSummary?.liveActivity || null,
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
resolveStepModel,
@@ -1088,6 +1252,7 @@ function buildActiveConversationAssembly({
agentLabel,
status: subSum.status || 'IDLE',
rawSteps: subRawSteps,
fallbackStaticContext: subEntry?.lastKnownStaticContext || null,
liveActivity: subSum.liveActivity || null,
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
resolveStepModel,
@@ -1269,6 +1434,11 @@ function buildActiveConversationAssembly({
}
: null;
const combinedLastKnownTtftSec =
findLastValidStepTtft(allCombinedEnrichedSteps) ??
latestMetricAgent.lastKnownTtftSec ??
null;
aggregatedTelemetry = {
agentId: 'all',
cascadeId: activeCascadeId,
@@ -1292,6 +1462,7 @@ function buildActiveConversationAssembly({
stepCount: allCombinedEnrichedSteps.length,
latestTokPerSec: latestMetricAgent.latestTokPerSec,
latestTtftSec: latestMetricAgent.latestTtftSec,
lastKnownTtftSec: combinedLastKnownTtftSec,
latestSpeedReason: latestMetricAgent.latestSpeedReason,
avgTokPerSec: combinedAvgTokPerSec,
speedSummary: combinedSpeed,
@@ -1341,6 +1512,8 @@ function buildActiveConversationAssembly({
: enrichedActiveSteps.length,
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
latestTtftSec: latestEnriched?.ttftSec ?? null,
lastKnownTtftSec:
mainAgentTelemetry.lastKnownTtftSec ?? findLastValidStepTtft(enrichedActiveSteps),
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
avgTokPerSec: sessionAvgTokPerSec,
speedSummary: sessionSpeed,
@@ -1640,7 +1813,7 @@ export async function buildTelemetryPayloadInternal(
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
const reportedContextLimits = new Map();
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, cacheStore);
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore, { hydrate: true });
const modelInputs = {
catalogRevision: pricingCatalogRevision,
phaseEpoch: getPricingPhaseEpoch(),
@@ -1729,11 +1902,57 @@ export async function buildTelemetryPayloadInternal(
poolObj.cycleWeekly = pStats?.cycleWeekly || createEmptyCycleSummary();
}
const runningPoolKeys = new Set();
let hasUnknownRunningPool = false;
for (const rootConv of conversations) {
const isMainRunning = rootConv?.status === 'CASCADE_RUN_STATUS_RUNNING';
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
const runningSubs = rawSubs.filter((s) => s?.status === 'CASCADE_RUN_STATUS_RUNNING');
if (!isMainRunning && runningSubs.length === 0) continue;
const recordRunningPool = (cid) => {
const entry = findTrajectoryCacheEntry(cid, cacheStore);
const steps = Array.isArray(entry?.steps) ? entry.steps : [];
const lastStep = steps.length > 0 ? steps[steps.length - 1] : null;
if (!lastStep) {
if (activePoolKey && activePoolKey !== 'Unknown') {
runningPoolKeys.add(activePoolKey);
} else {
hasUnknownRunningPool = true;
}
return;
}
const mInfo = resolveStepModel(lastStep);
const { activePoolKey: pKey } = resolveActivePoolKeyFromStep(
{
modelKey: lastStep.modelKey || mInfo.modelId || 'unknown',
family: mInfo.family,
modelLabel: mInfo.label,
modelShort: mInfo.shortName,
modelUpstream: mInfo.modelId,
},
quotaPoolsMap
);
if (pKey && pKey !== 'Unknown') {
runningPoolKeys.add(pKey);
} else {
hasUnknownRunningPool = true;
}
};
if (isMainRunning) recordRunningPool(rootConv.cascadeId);
for (const sub of runningSubs) {
recordRunningPool(sub.cascadeId);
}
}
updatePoolQuotaReservationEstimates({
endpointId,
accountScope: accountScope || '',
quotaPoolsMap,
poolCycleStats,
runningPoolKeys,
hasUnknownRunningPool,
quotaFetchedAtMs: officialQuotaInfo?.fetchedAtMs || 0,
nowMs: Date.now(),
});
@@ -1798,7 +2017,7 @@ export async function buildTelemetryPayloadInternal(
if (cidKey && quickStatsMemo.has(cidKey)) {
return quickStatsMemo.get(cidKey);
}
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore);
const rootEntry = findTrajectoryCacheEntry(rootConv?.cascadeId, cacheStore, { hydrate: true });
const rootSteps = rootEntry?.steps || [];
const rawSubs = Array.isArray(rootConv?.subagents) ? rootConv.subagents : [];
@@ -1838,8 +2057,13 @@ export async function buildTelemetryPayloadInternal(
let contextUsedPct = null;
if (lastRootStep) {
contextUsedPct = extractActiveContextTelemetry(rootSteps, lastRootStep, 0, 0).context
.compactionUsedPct;
contextUsedPct = extractActiveContextTelemetry(
rootSteps,
lastRootStep,
0,
0,
rootEntry?.lastKnownStaticContext || null
).context.compactionUsedPct;
}
let modelShort = '';
@@ -2093,6 +2317,30 @@ export async function buildTelemetryPayloadInternal(
});
}
const sortedQuotaPools = Array.from(quotaPoolsMap.values()).sort((a, b) => {
const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 };
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
});
if (
!isRemote &&
accountStatus === 'signedIn' &&
userStatus?.email &&
officialQuotaInfo?.data &&
!officialQuotaInfo.isStale
) {
recordAccountQuotaSnapshot(
userStatus.email,
sortedQuotaPools,
officialQuotaInfo.fetchedAtMs || Date.now(),
{ isActiveHost: true }
);
}
const weeklyCapacityEstimate = buildWeeklyCapacityEstimate({
sortedPools: sortedQuotaPools,
isCustomWeeklyMode,
hasOfficialData: Boolean(officialQuotaInfo?.data),
});
const finalPayload = {
timestamp: new Date().toISOString(),
hostPlatform: process.platform || 'unknown',
@@ -2176,6 +2424,9 @@ export async function buildTelemetryPayloadInternal(
revision: usageRevision,
selectedRange: {
key: selectedWindow.key,
...(selectedWindow.pool ? { pool: selectedWindow.pool } : {}),
...(selectedWindow.poolLabel ? { poolLabel: selectedWindow.poolLabel } : {}),
...(selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
label: selectedWindow.label,
startMs: trendStartMs,
endMs: trendEndMs,
@@ -2200,11 +2451,9 @@ export async function buildTelemetryPayloadInternal(
errorMessage: officialQuotaInfo?.error || null,
},
activePool: activePoolQuota,
pools: Array.from(quotaPoolsMap.values()).sort((a, b) => {
const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 };
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
}),
pools: sortedQuotaPools,
weekly: weeklyQuota,
weeklyCapacityEstimate,
},
modelBreakdown,
};
@@ -2291,11 +2540,16 @@ function resolveValidFastSnapshot(endpoint = null) {
}
function entryNeedsLazyTelemetryUpgrade(entry) {
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false;
if (!entry || entry.archived || !Array.isArray(entry.steps) || entry.steps.length === 0) {
return false;
}
const grpVer = Number(entry.contextGroupsTelemetry || 0);
const needsUndoCtxUpgrade =
grpVer < 2 || (grpVer === 2 && !entry.steps.some((st) => Boolean(st?.contextBreakdown)));
return (
!entry.turnRailTelemetry ||
!entry.anomalyTelemetry ||
entry.contextGroupsTelemetry !== 2
needsUndoCtxUpgrade
);
}
@@ -2318,7 +2572,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
if (!activeConvSummary?.cascadeId) return null;
const activeCascadeId = activeConvSummary.cascadeId;
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore);
const activeEntry = findTrajectoryCacheEntry(activeCascadeId, cacheStore, { hydrate: true });
if (!activeEntry) return null;
const subagentSummaries = Array.isArray(activeConvSummary.subagents)
@@ -2333,7 +2587,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
needsBackgroundSync = true;
break;
}
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore);
const subEntry = findTrajectoryCacheEntry(subSum?.cascadeId, cacheStore, { hydrate: true });
if (!subEntry || entryNeedsLazyTelemetryUpgrade(subEntry)) {
needsBackgroundSync = true;
break;
@@ -2397,6 +2651,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
quotas: {
activePool: activePoolQuota,
weekly: weeklyQuota,
weeklyCapacityEstimate: snap.basePayload.quotas?.weeklyCapacityEstimate || null,
},
consumption: {
session: sessionUsage.finalizedSelectedSession,
@@ -2406,6 +2661,120 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
};
}
function buildWeeklyCapacityEstimate({
sortedPools = [],
isCustomWeeklyMode = false,
hasOfficialData = false,
} = {}) {
if (isCustomWeeklyMode) {
return {
status: 'custom_mode',
totalEqWeeklyUsd: null,
totalEqWeeklyTokens: null,
readyPoolCount: 0,
totalPoolCount: 0,
hasPreliminary: false,
pools: [],
};
}
const rawPools = Array.isArray(sortedPools) ? sortedPools : [];
const candidatePools = rawPools.filter(
(p) =>
p &&
(p.hasWeekly ||
p.weeklyUsedPct != null ||
Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd))
);
const targetPools = candidatePools.length > 0 ? candidatePools : rawPools;
if (!hasOfficialData && targetPools.length === 0) {
return {
status: 'unavailable',
totalEqWeeklyUsd: null,
totalEqWeeklyTokens: null,
readyPoolCount: 0,
totalPoolCount: 0,
hasPreliminary: false,
pools: [],
};
}
let sumUsd = 0;
let sumTokens = 0;
let readyPoolCount = 0;
let tokenReadyPoolCount = 0;
let hasPreliminary = false;
const pools = [];
for (const p of targetPools) {
const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null;
let eqUsd =
Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0
? Number(est.eqFullWeeklyUsd)
: null;
let eqTok =
Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0
? Math.round(Number(est.eqFullWeeklyTokens))
: null;
if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) {
const wkModels = est.models.filter(
(m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0
);
if (wkModels.length > 0) {
eqUsd =
wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length;
const tokModels = wkModels.filter(
(m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0
);
if (tokModels.length === wkModels.length) {
eqTok = Math.round(
tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length
);
}
}
}
const isPrelim = Boolean(est?.isPreliminaryWeekly);
if (eqUsd !== null) {
readyPoolCount += 1;
sumUsd += eqUsd;
if (isPrelim) hasPreliminary = true;
if (eqTok !== null) {
tokenReadyPoolCount += 1;
sumTokens += eqTok;
}
}
pools.push({
poolKey: p.poolKey || p.family || '',
poolLabel: p.poolLabel || p.family || p.poolKey || 'Pool',
usedWeeklyPct: Number.isFinite(Number(p.weeklyUsedPct)) ? +Number(p.weeklyUsedPct).toFixed(1) : null,
eqFullWeeklyUsd: eqUsd !== null ? +eqUsd.toFixed(1) : null,
eqFullWeeklyTokens: eqTok,
source: est?.sourceWeekly || null,
isPreliminary: isPrelim,
});
}
const totalPoolCount = pools.length;
const status =
readyPoolCount === 0
? 'collecting'
: readyPoolCount < totalPoolCount
? 'partial'
: 'ready';
return {
status,
totalEqWeeklyUsd: readyPoolCount > 0 ? +sumUsd.toFixed(1) : null,
totalEqWeeklyTokens:
readyPoolCount > 0 && tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null,
readyPoolCount,
totalPoolCount,
hasPreliminary,
pools,
};
}
function enrichTopConversationTitles(topList, convSummaries) {
if (!Array.isArray(topList) || topList.length === 0) return [];
const titleMap = new Map();
@@ -2478,6 +2847,9 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) {
revision: agg.usageRevision,
selectedRange: {
key: agg.selectedWindow.key,
...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}),
...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}),
...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
label: agg.selectedWindow.label,
startMs: agg.trendStartMs,
endMs: agg.trendEndMs,
@@ -2584,6 +2956,7 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) {
latestTokPerSec: capSource.latestTokPerSec ?? ac.latestTokPerSec ?? null,
avgTokPerSec: capSource.avgTokPerSec ?? ac.avgTokPerSec ?? null,
latestTtftSec: capSource.latestTtftSec ?? ac.latestTtftSec ?? null,
lastKnownTtftSec: capSource.lastKnownTtftSec ?? ac.lastKnownTtftSec ?? null,
latestStepCostUsd: capSource.latestStepCostUsd ?? ac.latestStepCostUsd ?? null,
sessionCostUsd: capSource.sessionCostUsd ?? ac.sessionCostUsd ?? null,
latestCacheHitPct: capSource.latestCacheHitPct ?? ac.latestCacheHitPct ?? null,
@@ -2645,7 +3018,7 @@ export function buildTelemetryPayload(
}
}
}
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.pool || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`;
if (inFlightRequests.has(key)) {
return inFlightRequests.get(key);
+419 -27
View File
@@ -1,15 +1,64 @@
/**
* @fileoverview Shared lazy-loaded, $O(1)$ case-insensitive, 30s-throttled trajectory cache store
* reused by both the local sidecar (`config.mjs`) and remote SSH endpoints (`endpoint-registry.mjs`).
*
* Supports dual persistence backends behind a 100% compatible API:
* - SQLite incremental ledger (`trajectory-sqlite-ledger.mjs`) with 24-session hot `detail` LRU
* and permanent archived ledger retention when conversations are deleted in Antigravity;
* - JSON/in-memory fallback for environments without `node:sqlite` or VM unit-test sandboxes.
*/
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
import { isPlainObject } from './http-helpers.mjs';
import { hasBuiltinNodeSqlite } from './sqlite-client.mjs';
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
import {
computePrecomputedStepFlags,
createTrajectorySqliteLedger,
} from './trajectory-sqlite-ledger.mjs';
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
export const DEFAULT_HOT_SESSION_LRU_LIMIT = 64;
const TCS_WAL_SYNC_MIN_INTERVAL_MS = 250;
function tcsMarkColdSlimSteps(steps) {
if (Array.isArray(steps)) {
Object.defineProperty(steps, '_isColdSlimSteps', {
value: true,
enumerable: false,
configurable: true,
writable: true,
});
}
return steps;
}
function tcsIsColdEntry(entry) {
return Boolean(entry && (entry._coldSteps === true || entry.steps?._isColdSlimSteps === true));
}
function tcsDefineHiddenProp(obj, key, value) {
if (!obj || typeof obj !== 'object') return;
Object.defineProperty(obj, key, {
value,
enumerable: false,
configurable: true,
writable: true,
});
}
function tcsAttachEntryStepFlags(entry, flags) {
if (!entry || typeof entry !== 'object') return;
const resolved = flags || entry._stepFlags || computePrecomputedStepFlags(entry.steps);
tcsDefineHiddenProp(entry, '_stepFlags', resolved);
}
function tcsIsVirtualSandboxPath(filePath) {
const norm = String(filePath || '').replace(/\\/g, '/');
return norm.startsWith('/test/') || norm.startsWith('/test-home/');
}
/**
* Normalizes and repairs raw trajectory cache JSON into an unprototyped map.
@@ -42,7 +91,9 @@ export function hydrateTrajectoryCacheObject(rawLoaded) {
break;
}
}
cacheObj[id] = { ...entry, steps: finalSteps };
const nextEntry = { ...entry, steps: finalSteps };
tcsAttachEntryStepFlags(nextEntry, computePrecomputedStepFlags(finalSteps));
cacheObj[id] = nextEntry;
}
}
return { cacheObj, migrated };
@@ -50,26 +101,59 @@ export function hydrateTrajectoryCacheObject(rawLoaded) {
/**
* Creates an isolated trajectory cache store with lazy first-read hydration,
* case-insensitive canonical key index, and 30-second throttled disk flushes.
* case-insensitive canonical key index, 24-session hot detail LRU, and 30-second throttled disk flushes.
*
* @param {{
* cacheFilePath: string,
* loadJsonFn: (filePath: string, fallback: any) => any,
* cacheFilePath?: string,
* sqliteFilePath?: string,
* enableSqlite?: boolean | null,
* hotSessionLimit?: number,
* loadJsonFn?: (filePath: string, fallback: any) => any,
* writeCacheFn?: (filePath: string, cacheObj: Record<string, any>) => boolean,
* shouldBypassThrottleFn?: (allowThrottleInTest: boolean) => boolean,
* registerExitHook?: boolean,
* }} options
*/
export function createTrajectoryCacheStore({
cacheFilePath,
loadJsonFn,
cacheFilePath = '',
sqliteFilePath = '',
enableSqlite = null,
hotSessionLimit = DEFAULT_HOT_SESSION_LRU_LIMIT,
loadJsonFn = null,
writeCacheFn = null,
shouldBypassThrottleFn = () => false,
registerExitHook = false,
}) {
const maxHotSessions = Math.max(1, Math.floor(Number(hotSessionLimit) || DEFAULT_HOT_SESSION_LRU_LIMIT));
const useSqlite =
enableSqlite === true
? Boolean(sqliteFilePath && hasBuiltinNodeSqlite())
: enableSqlite === false
? false
: Boolean(
sqliteFilePath &&
hasBuiltinNodeSqlite() &&
!tcsIsVirtualSandboxPath(sqliteFilePath)
);
const sqliteLedger = useSqlite
? createTrajectorySqliteLedger({
sqliteFilePath,
legacyJsonPath: cacheFilePath,
loadJsonFn,
})
: null;
let cacheObj = Object.create(null);
const byLower = new Map();
// Map<lowerId, true> preserving insertion order (oldest -> newest) for hot hydrated sessions
const hotLru = new Map();
const dirtyUpserts = new Set();
const dirtyRemovals = new Set();
let pendingEpochBump = false;
let loadedOnce = false;
let lastWalSyncCheckMs = 0;
const state = {
needsSave: false,
lastSavedAtMs: 0,
@@ -88,15 +172,92 @@ export function createTrajectoryCacheStore({
}
}
const doWrite = writeCacheFn || defaultWriteCache;
const doWriteJson = writeCacheFn || defaultWriteCache;
function finalizeColdEntryInPlace(entry) {
if (!entry || typeof entry !== 'object') return entry;
const preFlags = entry._stepFlags || null;
if (Object.prototype.hasOwnProperty.call(entry, '_coldSteps')) {
delete entry._coldSteps;
}
if (Object.prototype.hasOwnProperty.call(entry, '_stepFlags')) {
delete entry._stepFlags;
}
tcsDefineHiddenProp(entry, '_coldSteps', true);
if (preFlags) {
tcsDefineHiddenProp(entry, '_stepFlags', preFlags);
}
tcsMarkColdSlimSteps(entry.steps);
return entry;
}
function touchHotSession(lower) {
if (!useSqlite || !lower) return;
if (hotLru.has(lower)) {
hotLru.delete(lower);
}
hotLru.set(lower, true);
evictOverflowHotSessions();
}
function dehydrateSingleSessionToCold(lower) {
if (!useSqlite || !sqliteLedger || !lower) return false;
if (dirtyUpserts.has(lower)) return false;
const canon = byLower.get(lower);
const entry = canon ? cacheObj[canon] : null;
if (!entry || entry.wasRunning) return false;
if (tcsIsColdEntry(entry)) {
hotLru.delete(lower);
return true;
}
const curSteps = Array.isArray(entry.steps) ? entry.steps : [];
const flags = entry._stepFlags || computePrecomputedStepFlags(curSteps);
const slimSteps = tcsMarkColdSlimSteps(curSteps.map((s) => sqliteLedger.dehydrateStep(s)));
entry.steps = slimSteps;
tcsDefineHiddenProp(entry, '_coldSteps', true);
tcsDefineHiddenProp(entry, '_stepFlags', flags);
hotLru.delete(lower);
return true;
}
function evictOverflowHotSessions() {
if (!useSqlite || hotLru.size <= maxHotSessions) return;
for (const candidateLower of Array.from(hotLru.keys())) {
if (hotLru.size <= maxHotSessions) break;
dehydrateSingleSessionToCold(candidateLower);
}
}
function rebuildLowerIndexFromCacheObj(markCold = false) {
byLower.clear();
hotLru.clear();
for (const key of Object.keys(cacheObj)) {
const lower = key.toLowerCase();
byLower.set(lower, key);
if (markCold) {
finalizeColdEntryInPlace(cacheObj[key]);
}
}
}
function ensureLoaded() {
if (loadedOnce) return;
loadedOnce = true;
if (!cacheFilePath) return;
if (useSqlite && sqliteLedger) {
const hydrated = sqliteLedger.openAndHydrateInitial();
cacheObj = hydrated.cacheObj;
loadedOnce = true;
rebuildLowerIndexFromCacheObj(true);
lastWalSyncCheckMs = Date.now();
return;
}
if (!cacheFilePath || typeof loadJsonFn !== 'function') {
loadedOnce = true;
return;
}
const loaded = loadJsonFn(cacheFilePath, {});
const hydrated = hydrateTrajectoryCacheObject(loaded);
cacheObj = hydrated.cacheObj;
loadedOnce = true;
for (const key of Object.keys(cacheObj)) {
byLower.set(key.toLowerCase(), key);
}
@@ -105,6 +266,63 @@ export function createTrajectoryCacheStore({
}
}
function syncExternalChangesNow() {
if (!useSqlite || !sqliteLedger || !loadedOnce) return false;
lastWalSyncCheckMs = Date.now();
let res;
try {
res = sqliteLedger.syncExternalChangesIfNeeded();
} catch {
return false;
}
if (!res || !res.changed) return false;
if (res.fullReset && res.cacheObj) {
for (const [cid, entry] of Object.entries(res.cacheObj)) {
const lower = cid.toLowerCase();
if (dirtyUpserts.has(lower)) continue;
finalizeColdEntryInPlace(entry);
}
// Preserve any local unflushed dirty entries on top of the peer reset
const preservedDirty = [];
for (const dirtyLower of dirtyUpserts) {
const canon = byLower.get(dirtyLower);
if (canon && cacheObj[canon]) {
preservedDirty.push([canon, cacheObj[canon]]);
}
}
cacheObj = res.cacheObj;
rebuildLowerIndexFromCacheObj(true);
for (const [canon, dirtyEntry] of preservedDirty) {
cacheObj[canon] = dirtyEntry;
byLower.set(canon.toLowerCase(), canon);
touchHotSession(canon.toLowerCase());
}
return true;
}
if (Array.isArray(res.updatedEntries)) {
for (const { cascadeId, lowerId, entry } of res.updatedEntries) {
if (dirtyUpserts.has(lowerId) || dirtyRemovals.has(lowerId)) continue;
const prevCanon = byLower.get(lowerId);
if (prevCanon && prevCanon !== cascadeId) {
delete cacheObj[prevCanon];
}
finalizeColdEntryInPlace(entry);
cacheObj[cascadeId] = entry;
byLower.set(lowerId, cascadeId);
hotLru.delete(lowerId);
}
return true;
}
return false;
}
function syncExternalIfDue() {
if (!useSqlite || !loadedOnce) return;
const now = Date.now();
if (now - lastWalSyncCheckMs < TCS_WAL_SYNC_MIN_INTERVAL_MS) return;
syncExternalChangesNow();
}
function cancelFlushTimer() {
if (state.flushTimer) {
try {
@@ -119,11 +337,47 @@ export function createTrajectoryCacheStore({
function flushTrajectoryCacheNow() {
ensureLoaded();
cancelFlushTimer();
if (useSqlite && sqliteLedger) {
if (dirtyUpserts.size === 0 && dirtyRemovals.size === 0 && !pendingEpochBump) {
state.needsSave = false;
return true;
}
const upserts = [];
for (const lower of dirtyUpserts) {
const canon = byLower.get(lower);
const entry = canon ? cacheObj[canon] : null;
if (canon && entry) {
upserts.push({ cascadeId: canon, entry });
}
}
const removals = Array.from(dirtyRemovals);
try {
sqliteLedger.flushDeltaBatch({
upserts,
removals,
bumpEpoch: pendingEpochBump,
});
dirtyUpserts.clear();
dirtyRemovals.clear();
pendingEpochBump = false;
state.needsSave = false;
state.lastSavedAtMs = Date.now();
lastWalSyncCheckMs = state.lastSavedAtMs;
evictOverflowHotSessions();
return true;
} catch (err) {
console.error(`Failed flushing trajectory SQLite ledger ${sqliteFilePath}: ${err.message}`);
state.needsSave = true;
return false;
}
}
if (!cacheFilePath) {
state.needsSave = false;
return true;
}
const ok = doWrite(cacheFilePath, cacheObj);
const ok = doWriteJson(cacheFilePath, cacheObj);
state.needsSave = !ok;
if (ok) {
state.lastSavedAtMs = Date.now();
@@ -135,7 +389,7 @@ export function createTrajectoryCacheStore({
hasRunningSessions = false,
allowThrottleInTest = false,
} = {}) {
if (!cacheFilePath) {
if (!useSqlite && !cacheFilePath) {
state.needsSave = false;
return;
}
@@ -169,16 +423,103 @@ export function createTrajectoryCacheStore({
}
}
function clearCache() {
if (cacheFilePath && !doWrite(cacheFilePath, {})) {
function hydrateEntryInPlaceIfNeeded(canonId, entry) {
if (!canonId || !entry) return entry;
const lower = canonId.toLowerCase();
if (!useSqlite || !sqliteLedger) return entry;
if (!tcsIsColdEntry(entry)) {
touchHotSession(lower);
return entry;
}
const fullSteps = sqliteLedger.loadHydratedStepsForConversation(canonId, entry);
if (Array.isArray(fullSteps)) {
const flags = entry._stepFlags || computePrecomputedStepFlags(fullSteps);
entry.steps = fullSteps;
tcsDefineHiddenProp(entry, '_coldSteps', false);
tcsDefineHiddenProp(entry, '_stepFlags', flags);
touchHotSession(lower);
}
return entry;
}
/**
* Non-destructively clears live/empty cached entries to force fresh re-scanning, while
* permanently archiving & preserving any conversation with `steps.length > 0` whose source
* conversation has already been deleted (`!liveSet.has(lower)` or `entry.archived === true`).
*
* @param {{ liveCascadeIds?: Iterable<string> | null }} [options]
*/
function clearCache({ liveCascadeIds = null } = {}) {
ensureLoaded();
syncExternalChangesNow();
const liveSet =
liveCascadeIds !== null && liveCascadeIds !== undefined
? new Set(
Array.from(liveCascadeIds, (id) => String(id || '').trim().toLowerCase()).filter(
Boolean
)
)
: null;
const retainedEntries = Object.create(null);
const removedLowers = [];
const archivedUpserts = [];
for (const [key, entry] of Object.entries(cacheObj)) {
const lower = key.toLowerCase();
const hasSteps = Array.isArray(entry?.steps) && entry.steps.length > 0;
const isDeletedHistorical =
hasSteps && (entry.archived === true || (liveSet !== null && !liveSet.has(lower)));
if (isDeletedHistorical) {
const archivedEntry = entry.archived === true ? entry : { ...entry, archived: true };
if (tcsIsColdEntry(entry)) {
tcsDefineHiddenProp(archivedEntry, '_coldSteps', true);
}
if (entry._stepFlags) {
tcsDefineHiddenProp(archivedEntry, '_stepFlags', entry._stepFlags);
}
retainedEntries[key] = archivedEntry;
if (entry.archived !== true || dirtyUpserts.has(lower)) {
archivedUpserts.push({ cascadeId: key, entry: archivedEntry });
}
} else {
removedLowers.push(lower);
}
}
if (useSqlite && sqliteLedger) {
try {
sqliteLedger.flushDeltaBatch({
upserts: archivedUpserts,
removals: removedLowers,
bumpEpoch: true,
});
} catch (err) {
console.error(`Failed clearing trajectory SQLite ledger ${sqliteFilePath}: ${err.message}`);
return false;
}
} else if (cacheFilePath && !doWriteJson(cacheFilePath, retainedEntries)) {
return false;
}
cancelFlushTimer();
loadedOnce = true;
for (const key of Object.keys(cacheObj)) {
delete cacheObj[key];
}
cacheObj = retainedEntries;
byLower.clear();
for (const key of Object.keys(cacheObj)) {
const lower = key.toLowerCase();
byLower.set(lower, key);
}
for (const remLower of removedLowers) {
hotLru.delete(remLower);
dirtyUpserts.delete(remLower);
dirtyRemovals.delete(remLower);
}
for (const { cascadeId } of archivedUpserts) {
dirtyUpserts.delete(cascadeId.toLowerCase());
}
pendingEpochBump = false;
state.needsSave = false;
state.lastSavedAtMs = 0;
return true;
@@ -192,27 +533,57 @@ export function createTrajectoryCacheStore({
});
}
function lookupRawByLower(cascadeId) {
if (!cascadeId) return null;
ensureLoaded();
syncExternalIfDue();
const direct = cacheObj[cascadeId];
if (direct) return { id: String(cascadeId), entry: direct };
const canon = byLower.get(String(cascadeId).toLowerCase());
if (canon && cacheObj[canon]) {
return { id: canon, entry: cacheObj[canon] };
}
return null;
}
return {
cacheFilePath,
sqliteFilePath: useSqlite ? sqliteFilePath : '',
isSqliteBacked: useSqlite,
cacheState: state,
cancelFlushTimer,
syncExternalChangesNow,
getHotSessionCount() {
return hotLru.size;
},
isConversationCold(cascadeId) {
const hit = lookupRawByLower(cascadeId);
return hit ? tcsIsColdEntry(hit.entry) : false;
},
getCachedTrajectory(cascadeId) {
ensureLoaded();
syncExternalIfDue();
return cacheObj[cascadeId];
},
getCachedTrajectoryEntryByLower(cascadeId) {
if (!cascadeId) return null;
ensureLoaded();
const direct = cacheObj[cascadeId];
if (direct) return { id: String(cascadeId), entry: direct };
const canon = byLower.get(String(cascadeId).toLowerCase());
if (canon && cacheObj[canon]) {
return { id: canon, entry: cacheObj[canon] };
}
return null;
return lookupRawByLower(cascadeId);
},
getHydratedTrajectory(cascadeId) {
const hit = lookupRawByLower(cascadeId);
if (!hit) return undefined;
return hydrateEntryInPlaceIfNeeded(hit.id, hit.entry);
},
getHydratedTrajectoryEntryByLower(cascadeId) {
const hit = lookupRawByLower(cascadeId);
if (!hit) return null;
return {
id: hit.id,
entry: hydrateEntryInPlaceIfNeeded(hit.id, hit.entry),
};
},
listCachedTrajectoryEntries() {
ensureLoaded();
syncExternalIfDue();
return Object.entries(cacheObj);
},
setCachedTrajectory(cascadeId, entry) {
@@ -226,6 +597,18 @@ export function createTrajectoryCacheStore({
) {
delete cacheObj[prevCanon];
}
if (entry && typeof entry === 'object') {
const isStillCold = Boolean(entry.steps?._isColdSlimSteps === true);
tcsDefineHiddenProp(entry, '_coldSteps', isStillCold);
tcsAttachEntryStepFlags(entry, entry._stepFlags || null);
if (useSqlite && lower) {
dirtyRemovals.delete(lower);
dirtyUpserts.add(lower);
if (!isStillCold) {
touchHotSession(lower);
}
}
}
cacheObj[cascadeId] = entry;
if (lower) {
byLower.set(lower, String(cascadeId));
@@ -234,10 +617,19 @@ export function createTrajectoryCacheStore({
removeCachedTrajectory(cascadeId) {
ensureLoaded();
const lower = String(cascadeId || '').toLowerCase();
if (lower && byLower.get(lower) === cascadeId) {
byLower.delete(lower);
const canon = lower ? byLower.get(lower) : undefined;
if (canon && Object.prototype.hasOwnProperty.call(cacheObj, canon)) {
delete cacheObj[canon];
}
delete cacheObj[cascadeId];
if (lower) {
byLower.delete(lower);
hotLru.delete(lower);
if (useSqlite) {
dirtyUpserts.delete(lower);
dirtyRemovals.add(lower);
}
}
},
hasPendingTrajectoryCacheSave() {
ensureLoaded();
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,187 @@
/**
* @fileoverview 共享的 `transcript.jsonl` / `transcript_full.jsonl` 安全解析与离线模型步骤合成辅助模块。
*
* 供 `local-scanner.mjs` 与 `cli-statusline.mjs` 共用,避免重复维护状态归一化、Token 字段映射
* 以及超大 `transcript_full.jsonl` 的体积保护逻辑。
*/
import { existsSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
export const TRANSCRIPT_COMPACT_MAX_BYTES = 24 * 1024 * 1024;
export const TRANSCRIPT_FULL_MAX_BYTES = 12 * 1024 * 1024;
/**
* 在单个日志目录内优先解析 `transcript.jsonl`,不存在时按体积上限安全回退至 `transcript_full.jsonl`。
*
* @param {string} logsDir
* @param {{ maxFullBytes?: number }} [opts={}]
* @returns {string}
*/
export function resolveTranscriptPathInLogsDir(
logsDir,
{ maxFullBytes = TRANSCRIPT_FULL_MAX_BYTES } = {}
) {
if (!logsDir || typeof logsDir !== 'string') return '';
const primary = join(logsDir, 'transcript.jsonl');
if (existsSync(primary)) return primary;
const full = join(logsDir, 'transcript_full.jsonl');
if (!existsSync(full)) return '';
if (Number.isFinite(maxFullBytes) && maxFullBytes > 0) {
try {
const st = statSync(full, { throwIfNoEntry: false });
if (st && Number(st.size || 0) > maxFullBytes) return '';
} catch {
return '';
}
}
return full;
}
/**
* 安全读取并解析 JSONL 格式的 transcript 文件,按文件类型施加体积保护并跳过损坏行。
*
* @param {string} transcriptPath
* @param {{ maxBytes?: number }} [opts={}]
* @returns {object[]}
*/
export function readTranscriptJsonlLines(transcriptPath, { maxBytes } = {}) {
if (!transcriptPath || !existsSync(transcriptPath)) return [];
const isFullFile = /transcript_full\.jsonl$/i.test(transcriptPath);
const limitBytes =
Number.isFinite(maxBytes) && maxBytes > 0
? maxBytes
: isFullFile
? TRANSCRIPT_FULL_MAX_BYTES
: TRANSCRIPT_COMPACT_MAX_BYTES;
try {
const st = statSync(transcriptPath, { throwIfNoEntry: false });
if (st && Number(st.size || 0) > limitBytes) {
return [];
}
} catch {
return [];
}
let raw = '';
try {
raw = readFileSync(transcriptPath, 'utf8');
} catch {
return [];
}
if (typeof raw !== 'string' || !raw.trim()) return [];
const lines = [];
for (const rawLine of raw.split(/\r?\n/)) {
const trimmed = rawLine.trim();
if (!trimmed) continue;
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === 'object') {
lines.push(parsed);
}
} catch {
// 忽略尾部半行或损坏 JSON 行
}
}
return lines;
}
/**
* 将单条含 Token 统计的 transcript JSONL 记录合成为标准轨迹模型步骤对象。
*
* @param {object} line
* @param {{ stepIndex?: number, deepStep?: object | null }} [opts={}]
* @returns {object}
*/
export function synthesizeTranscriptModelStep(line, { stepIndex = 0, deepStep = null } = {}) {
const rawType = String(line?.type || '').trim();
const upperType = rawType.toUpperCase();
const isCheckpoint =
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT';
const rawStatus = String(line?.status || '').trim().toUpperCase();
const mappedStatus = /CANCEL/.test(rawStatus)
? 'CORTEX_STEP_STATUS_CANCELED'
: /ERROR/.test(rawStatus)
? 'CORTEX_STEP_STATUS_ERROR'
: /INTERRUPT/.test(rawStatus)
? 'CORTEX_STEP_STATUS_INTERRUPTED'
: 'CORTEX_STEP_STATUS_DONE';
const finishedAt = String(
line?.finished_generating_at ||
line?.finishedGeneratingAt ||
line?.completed_at ||
line?.completedAt ||
''
).trim();
const modelKey =
String(line?.model || line?.generator_model || deepStep?.modelKey || 'unknown').trim() ||
'unknown';
const responseModel = String(line?.response_model || deepStep?.responseModel || '').trim();
const apiProvider = String(line?.api_provider || deepStep?.apiProvider || '').trim();
const modelDisplayName = String(
line?.model_display_name || deepStep?.modelDisplayName || ''
).trim();
const thinkingTokens = Number(line?.thinking_tokens ?? deepStep?.thinkingTokens ?? 0) || 0;
const responseTokens = line?.response_tokens ?? deepStep?.responseTokens;
const resolvedStepIndex = Number.isFinite(Number(line?.step_index))
? Number(line.step_index)
: stepIndex;
return {
type: isCheckpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : rawType || 'PLANNER_RESPONSE',
status: mappedStatus,
plannerResponse: {
response: typeof line?.content === 'string' ? line.content : '',
thinking: typeof line?.thinking === 'string' ? line.thinking : '',
toolCalls: Array.isArray(line?.tool_calls) ? line.tool_calls : [],
...(thinkingTokens > 0 ? { thinkingTokens } : {}),
...(responseTokens !== undefined ? { responseTokens } : {}),
},
metadata: {
createdAt: String(line?.created_at || line?.createdAt || deepStep?.createdAt || ''),
...(finishedAt ? { finishedGeneratingAt: finishedAt } : {}),
sourceTrajectoryStepInfo: { stepIndex: resolvedStepIndex },
modelUsage: {
model: modelKey,
...(responseModel ? { responseModel } : {}),
...(apiProvider ? { apiProvider } : {}),
inputTokens: line?.input_tokens ?? deepStep?.inputTokens ?? 0,
cacheReadTokens: line?.cache_read_tokens ?? deepStep?.cacheReadTokens ?? 0,
outputTokens: line?.output_tokens ?? deepStep?.outputTokens ?? 0,
...(thinkingTokens > 0 ? { thinkingOutputTokens: thinkingTokens } : {}),
...(responseTokens !== undefined ? { responseOutputTokens: responseTokens } : {}),
},
...(modelDisplayName
? { generatorMetadata: [{ chatModel: { modelDisplayName } }] }
: {}),
},
};
}
/**
* 从 `transcript.jsonl`(或受体积保护的 `transcript_full.jsonl`)构建 CLI 状态栏兼容的轨迹载荷。
*
* @param {string} transcriptPath
* @param {string} cascadeId
* @param {{ maxBytes?: number }} [opts={}]
* @returns {{ cascadeId: string, steps: object[], generatorMetadata: object[] } | null}
*/
export function buildTranscriptFallbackTrajectory(transcriptPath, cascadeId, opts = {}) {
const lines = readTranscriptJsonlLines(transcriptPath, opts);
if (lines.length === 0) return null;
const rawSteps = [];
for (let idx = 0; idx < lines.length; idx++) {
const parsed = lines[idx];
const hasTokens =
parsed.input_tokens !== undefined ||
parsed.cache_read_tokens !== undefined ||
parsed.output_tokens !== undefined;
if (!hasTokens) {
rawSteps.push(parsed);
continue;
}
rawSteps.push(synthesizeTranscriptModelStep(parsed, { stepIndex: idx }));
}
return rawSteps.length > 0 ? { cascadeId, steps: rawSteps, generatorMetadata: [] } : null;
}
+399 -127
View File
@@ -348,6 +348,7 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
accumulateSpeed(agg.speedAccumulator, st);
if (
!st.isCompactionStep &&
!st.isImageGenStep &&
st.measurementVersion === MEASUREMENT_VERSION &&
st.isComplete &&
Number.isFinite(st.totalDurationSec) &&
@@ -785,17 +786,22 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000)
: nowMs - 5 * 3600 * 1000;
const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0;
const startWkMs =
resetWkMs > nowMs
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
: weekFallbackStartMs;
const hasOfficialWk = resetWkMs > nowMs;
const startWkMs = hasOfficialWk
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
: weekFallbackStartMs;
poolCycleBuckets.set(poolKey, {
start5hMs,
startWkMs,
hasOfficialWk,
b5h: createUsageBucket(),
bWk: createUsageBucket(),
pricedTokens5h: 0,
pricedTokensWk: 0,
modelCosts5h: new Map(),
modelCostsWk: new Map(),
modelTokens5h: new Map(),
modelTokensWk: new Map(),
lastActivityMs: 0,
recent10mSessions: new Map(),
});
@@ -804,7 +810,27 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
return poolCycleBuckets;
}
function resolvePoolBucketForStep(
export function normalizeCyclePoolFilter(rawPool, availablePoolKeys = null) {
const raw = typeof rawPool === 'string' ? rawPool.trim() : '';
if (!raw || raw.toLowerCase() === 'all') return 'all';
const lower = raw.toLowerCase();
let canonical = raw;
if (lower === 'gemini') canonical = 'Gemini';
else if (lower === 'argon' || lower === 'gemini 4 argon') canonical = 'Argon';
else if (lower === 'carbon' || lower === 'gemini 4 carbon') canonical = 'Carbon';
else if (lower === 'claude & gpt' || lower === 'claude' || lower === 'gpt') {
canonical = 'Claude & GPT';
}
if (availablePoolKeys && availablePoolKeys.size > 0 && !availablePoolKeys.has(canonical)) {
for (const k of availablePoolKeys.keys()) {
if (String(k).toLowerCase() === lower) return k;
}
return 'all';
}
return canonical;
}
function resolveStepPoolAssignment(
st,
mInfo,
poolCycleBuckets,
@@ -812,7 +838,6 @@ function resolvePoolBucketForStep(
hasDedicatedCarbonPool,
hasDedicatedArgonPool
) {
if (poolCycleBuckets.size === 0) return null;
let cachedPool = poolByModel.get(mInfo);
if (
!cachedPool ||
@@ -836,11 +861,68 @@ function resolvePoolBucketForStep(
key: st.modelKey,
response: st.responseModel,
displayName: st.modelDisplayName,
bucket: poolCycleBuckets.get(poolKey) || null,
poolKey,
bucket: poolKey && poolCycleBuckets.size > 0 ? poolCycleBuckets.get(poolKey) || null : null,
};
poolByModel.set(mInfo, cachedPool);
}
return cachedPool.bucket;
return cachedPool;
}
function resolveEffectiveSelectedCycleWindow({
selectedWindow,
effectiveCyclePool = 'all',
isCustomWeeklyMode = false,
cycleAnchors = {},
nowMs = Date.now(),
poolCycleBuckets,
quotaPoolsMap = null,
earliestActiveCyclePoolStartMs = Infinity,
earliestSelectedStepMs = Infinity,
}) {
if (!selectedWindow || selectedWindow.key !== 'cycle') return selectedWindow;
if (effectiveCyclePool !== 'all') {
const poolBucket = poolCycleBuckets?.get?.(effectiveCyclePool) || null;
const poolMeta = quotaPoolsMap instanceof Map ? quotaPoolsMap.get(effectiveCyclePool) : null;
const poolLabel = poolMeta?.poolLabel || effectiveCyclePool;
const baseStartMs =
!isCustomWeeklyMode && poolBucket ? poolBucket.startWkMs : selectedWindow.startMs;
const startMs =
Number.isFinite(earliestSelectedStepMs) && earliestSelectedStepMs < Infinity
? Math.min(baseStartMs, earliestSelectedStepMs)
: baseStartMs;
const isFallbackWeek = !isCustomWeeklyMode && !poolBucket?.hasOfficialWk;
return {
...selectedWindow,
pool: effectiveCyclePool,
poolLabel,
isFallbackWeek,
label: `${isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期'} · ${poolLabel}`,
startMs,
};
}
let hasAnyOfficialWk = !isCustomWeeklyMode && (cycleAnchors?.weeklyResetMs || 0) > nowMs;
if (!hasAnyOfficialWk && poolCycleBuckets instanceof Map) {
for (const b of poolCycleBuckets.values()) {
if (b?.hasOfficialWk) {
hasAnyOfficialWk = true;
break;
}
}
}
const isFallbackWeek = !isCustomWeeklyMode && !hasAnyOfficialWk;
const startMs =
Number.isFinite(earliestActiveCyclePoolStartMs) && earliestActiveCyclePoolStartMs < Infinity
? Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs)
: selectedWindow.startMs;
return {
...selectedWindow,
pool: 'all',
poolLabel: '',
isFallbackWeek,
label: isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期',
startMs,
};
}
function buildUsageTrendSeries(
@@ -857,43 +939,34 @@ function buildUsageTrendSeries(
earliestSelectedStepMs,
latestSelectedStepMs
);
const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend;
const { start: trendStartMs, end: trendEndMs, hourly: useHourly, stepMs: plannedStepMs } = trend;
const pad2 = (n) => String(n).padStart(2, '0');
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const trendSeries = [];
if (useHourly) {
let firstHourMs = trend.first;
let lastHourMs = trend.last;
if (selectedWindow.key === 'today') {
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
if (lastHourMs < minTodayEndMs) {
lastHourMs = minTodayEndMs;
}
} else if (lastHourMs - firstHourMs < 5 * 3600 * 1000) {
firstHourMs = lastHourMs - 5 * 3600 * 1000;
}
const firstSlotMs = trend.first;
const lastSlotMs = trend.last;
const slotMs = Math.max(60 * 1000, Number(plannedStepMs) || 3600 * 1000);
const stepMinutes = Math.max(1, Math.round(slotMs / (60 * 1000)));
const isSubHour = stepMinutes < 60;
const slotCount = Math.max(1, Math.floor((lastSlotMs - firstSlotMs) / slotMs) + 1);
const totalHours = Math.max(2, Math.round((lastHourMs - firstHourMs) / (3600 * 1000)) + 1);
const stepHours = totalHours > 72 ? Math.ceil(totalHours / 48) : 1;
const slotMs = stepHours * 3600 * 1000;
const slotCount = Math.max(2, Math.ceil((lastHourMs - firstHourMs + 3600 * 1000) / slotMs));
const firstD = new Date(firstHourMs);
const lastD = new Date(firstHourMs + (slotCount - 1) * slotMs);
const firstD = new Date(firstSlotMs);
const lastD = new Date(firstSlotMs + (slotCount - 1) * slotMs);
const isSameDay =
firstD.getFullYear() === lastD.getFullYear() &&
firstD.getMonth() === lastD.getMonth() &&
firstD.getDate() === lastD.getDate();
for (let idx = 0; idx < slotCount; idx++) {
const sMs = firstHourMs + idx * slotMs;
const sMs = firstSlotMs + idx * slotMs;
const eMs = sMs + slotMs;
const sd = new Date(sMs);
const ed = new Date(eMs);
if (Number.isNaN(sd.getTime())) continue;
const hh = `${pad2(sd.getHours())}:00`;
const endHh = `${pad2(ed.getHours())}:00`;
const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`;
const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`;
const dateStr = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
const axisLabel = isSameDay ? hh : `${dateStr} ${hh}`;
const fullLabel = `${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`;
@@ -901,7 +974,8 @@ function buildUsageTrendSeries(
index: idx,
startMs: sMs,
endMs: eMs,
granularity: 'hour',
granularity: isSubHour ? 'minute' : 'hour',
...(isSubHour ? { stepMinutes } : {}),
label: axisLabel,
fullLabel,
tokens: 0,
@@ -928,11 +1002,10 @@ function buildUsageTrendSeries(
cursor.setHours(0, 0, 0, 0);
safety++;
}
while (dayStarts.length < 2) {
const prev = new Date(dayStarts[0] || firstDayMs);
prev.setDate(prev.getDate() - 1);
prev.setHours(0, 0, 0, 0);
dayStarts.unshift(prev.getTime());
if (dayStarts.length === 0) {
const fallbackDay = new Date(firstDayMs);
fallbackDay.setHours(0, 0, 0, 0);
dayStarts.push(fallbackDay.getTime());
}
const firstYear = new Date(dayStarts[0]).getFullYear();
@@ -1082,26 +1155,61 @@ function buildUsageTrendSeries(
return { trend, trendStartMs, trendEndMs, trendSeries };
}
function resolveIntradayStepMinutes(spanMs, windowKey = '') {
if (windowKey !== 'all') {
if (spanMs < 15 * 60 * 1000) return 1;
if (spanMs < 60 * 60 * 1000) return 5;
if (spanMs < 2 * 3600 * 1000) return 15;
}
const totalHours = Math.max(2, Math.floor(spanMs / (3600 * 1000)) + 1);
return totalHours > 72 ? Math.ceil(totalHours / 48) * 60 : 60;
}
function floorToLocalTrendSlotMs(ms, stepMinutes) {
const d = new Date(ms);
if (stepMinutes < 60) {
const alignedMin = Math.floor(d.getMinutes() / stepMinutes) * stepMinutes;
d.setMinutes(alignedMin, 0, 0);
} else {
d.setMinutes(0, 0, 0);
}
return d.getTime();
}
function planUsageTrend(window, nowMs, earliest, latest) {
const safeMs = (value, fallback) =>
Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback;
const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest);
const defaultStart = end - 24 * 3600 * 1000;
const start = window.key === 'all'
? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000)
: Math.min(safeMs(window.startMs, defaultStart), end);
const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' ||
end - start <= 72 * 3600 * 1000;
const start =
window.key === 'all'
? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000)
: Math.min(safeMs(window.startMs, defaultStart), end);
const spanMs = Math.max(0, end - start);
const hourly =
window.key === 'today' ||
window.key === '24h' ||
window.key === '5h' ||
spanMs <= 72 * 3600 * 1000;
if (hourly) {
const stepMinutes = resolveIntradayStepMinutes(spanMs, window.key);
const stepMs = stepMinutes * 60 * 1000;
const first = floorToLocalTrendSlotMs(start, stepMinutes);
const last = floorToLocalTrendSlotMs(end, stepMinutes);
return { start, end, hourly, stepMs, first, last };
}
const first = new Date(start);
const last = new Date(end);
if (hourly) {
first.setMinutes(0, 0, 0);
last.setMinutes(0, 0, 0);
} else {
first.setHours(0, 0, 0, 0);
last.setHours(0, 0, 0, 0);
}
return { start, end, hourly, first: first.getTime(), last: last.getTime() };
first.setHours(0, 0, 0, 0);
last.setHours(0, 0, 0, 0);
return {
start,
end,
hourly,
stepMs: 24 * 3600 * 1000,
first: first.getTime(),
last: last.getTime(),
};
}
function sameUsageEntries(previous, current) {
@@ -1124,6 +1232,7 @@ function computeFamilySessionBuckets({
presetKeys = [],
presetWindows = {},
selectedWindow,
effectiveCyclePool = 'all',
isCustomWeeklyMode = false,
poolCycleBuckets = new Map(),
normalizedQuotaAccount = '',
@@ -1135,8 +1244,11 @@ function computeFamilySessionBuckets({
for (const k of presetKeys) {
sessionBuckets[k] = createUsageBucket();
}
const isScopedCyclePool = selectedWindow?.key === 'cycle' && effectiveCyclePool !== 'all';
const selectedSessionBucket =
(selectedWindow?.key && sessionBuckets[selectedWindow.key]) || createUsageBucket();
selectedWindow?.key && !isScopedCyclePool && sessionBuckets[selectedWindow.key]
? sessionBuckets[selectedWindow.key]
: createUsageBucket();
if (!(familySet instanceof Set) || familySet.size === 0) {
const sessionPresets = {};
for (const k of presetKeys) {
@@ -1202,17 +1314,15 @@ function computeFamilySessionBuckets({
unpriced,
};
const poolBucketEntry =
poolCycleBuckets.size > 0
? resolvePoolBucketForStep(
st,
mInfo,
poolCycleBuckets,
poolByModel,
hasDedicatedCarbonPool,
hasDedicatedArgonPool
)
: null;
const stepPool = resolveStepPoolAssignment(
st,
mInfo,
poolCycleBuckets,
poolByModel,
hasDedicatedCarbonPool,
hasDedicatedArgonPool
);
const poolBucketEntry = stepPool.bucket;
let inCurrentCycle = false;
if (qMs > 0 && qMs <= nowMs) {
@@ -1242,14 +1352,19 @@ function computeFamilySessionBuckets({
}
}
if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) {
if (
selectedWindow &&
(!sessionBuckets[selectedWindow.key] ||
selectedWindow.key === 'custom' ||
isScopedCyclePool)
) {
const selCmpMs =
selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs;
const inSelectedWindow =
selectedWindow.key === 'all'
? true
: selectedWindow.key === 'cycle'
? inCurrentCycle
? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool)
: selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
if (inSelectedWindow) {
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId);
@@ -1376,16 +1491,30 @@ export function aggregateMultiWindowUsage({
sessionBuckets[k] = createUsageBucket();
}
// 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
// 为每个配额池建立独立的 5h 及周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs);
const effectiveCyclePool =
selectedWindow.key === 'cycle'
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
: 'all';
const isScopedCyclePool = selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all';
const selectedRangeCacheKey = isScopedCyclePool
? `cycle:${effectiveCyclePool}`
: selectedWindow.key;
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
const poolByModel = new Map();
const quotaWeekBucket = createUsageBucket();
const normalizedQuotaAccount =
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
const selectedAccountBucket =
!isScopedCyclePool && accountBuckets[selectedWindow.key]
? accountBuckets[selectedWindow.key]
: createUsageBucket();
const selectedSessionBucket =
!isScopedCyclePool && sessionBuckets[selectedWindow.key]
? sessionBuckets[selectedWindow.key]
: createUsageBucket();
const perModelStats = new Map();
const perConvStats = new Map();
const perWorkspaceStats = new Map();
@@ -1432,16 +1561,34 @@ export function aggregateMultiWindowUsage({
modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
const previous = sameSnapshot ? snapshot.ranges.get(selectedRangeCacheKey) : null;
if (previous) {
// 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。
const probeEffectiveWin =
selectedWindow.key === 'cycle'
? resolveEffectiveSelectedCycleWindow({
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
cycleAnchors,
nowMs,
poolCycleBuckets,
quotaPoolsMap,
earliestActiveCyclePoolStartMs: previous.earliestActiveCyclePoolStartMs,
earliestSelectedStepMs: previous.earliest,
})
: selectedWindow;
const effectivePrevWin =
selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow
? { ...previous.effectiveSelectedWindow, endMs: nowMs }
? { ...probeEffectiveWin, endMs: nowMs }
: selectedWindow;
const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest);
if (
trend.hourly === previous.trend.hourly && trend.first === previous.trend.first &&
Boolean(effectivePrevWin.isFallbackWeek) ===
Boolean(previous.effectiveSelectedWindow?.isFallbackWeek) &&
trend.hourly === previous.trend.hourly &&
trend.stepMs === previous.trend.stepMs &&
trend.first === previous.trend.first &&
trend.last === previous.trend.last &&
sameUsageWindows(
previous.windows,
@@ -1450,8 +1597,8 @@ export function aggregateMultiWindowUsage({
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
)
) {
snapshot.ranges.delete(selectedWindow.key);
snapshot.ranges.set(selectedWindow.key, previous);
snapshot.ranges.delete(selectedRangeCacheKey);
snapshot.ranges.set(selectedRangeCacheKey, previous);
if (previous.familySig === familySig) {
return {
...previous.result,
@@ -1468,6 +1615,7 @@ export function aggregateMultiWindowUsage({
presetKeys,
presetWindows,
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
poolCycleBuckets,
normalizedQuotaAccount,
@@ -1555,7 +1703,7 @@ export function aggregateMultiWindowUsage({
}
}
const poolBucketEntry = resolvePoolBucketForStep(
const stepPool = resolveStepPoolAssignment(
st,
mInfo,
poolCycleBuckets,
@@ -1563,6 +1711,7 @@ export function aggregateMultiWindowUsage({
hasDedicatedCarbonPool,
hasDedicatedArgonPool
);
const poolBucketEntry = stepPool.bucket;
if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) {
if (qMs > poolBucketEntry.lastActivityMs) {
@@ -1582,20 +1731,38 @@ export function aggregateMultiWindowUsage({
const quotaModelKey = mInfo.baseLabel || mInfo.label || '';
if (qMs >= poolBucketEntry.start5hMs) {
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
if (stepUsage.resolvedCost > 0 && stepTotalTokens > 0) {
poolBucketEntry.pricedTokens5h += stepTotalTokens;
}
if (quotaModelKey && stepUsage.resolvedCost > 0) {
poolBucketEntry.modelCosts5h.set(
quotaModelKey,
(poolBucketEntry.modelCosts5h.get(quotaModelKey) || 0) + stepUsage.resolvedCost
);
if (stepTotalTokens > 0) {
poolBucketEntry.modelTokens5h.set(
quotaModelKey,
(poolBucketEntry.modelTokens5h.get(quotaModelKey) || 0) + stepTotalTokens
);
}
}
}
if (qMs >= poolBucketEntry.startWkMs) {
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
if (stepUsage.resolvedCost > 0 && stepTotalTokens > 0) {
poolBucketEntry.pricedTokensWk += stepTotalTokens;
}
if (quotaModelKey && stepUsage.resolvedCost > 0) {
poolBucketEntry.modelCostsWk.set(
quotaModelKey,
(poolBucketEntry.modelCostsWk.get(quotaModelKey) || 0) + stepUsage.resolvedCost
);
if (stepTotalTokens > 0) {
poolBucketEntry.modelTokensWk.set(
quotaModelKey,
(poolBucketEntry.modelTokensWk.get(quotaModelKey) || 0) + stepTotalTokens
);
}
}
}
}
@@ -1640,7 +1807,7 @@ export function aggregateMultiWindowUsage({
selectedWindow.key === 'all'
? true
: selectedWindow.key === 'cycle'
? inCurrentCycle
? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool)
: selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
if (inSelectedWindow) {
@@ -1652,7 +1819,7 @@ export function aggregateMultiWindowUsage({
) {
earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs;
}
if (selectedWindow.key === 'custom') {
if (selectedWindow.key === 'custom' || isScopedCyclePool) {
accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
if (isCurrentConv) {
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
@@ -1734,15 +1901,17 @@ export function aggregateMultiWindowUsage({
);
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
const effectiveSelectedWindow =
selectedWindow.key === 'cycle' &&
Number.isFinite(earliestActiveCyclePoolStartMs) &&
earliestActiveCyclePoolStartMs < Infinity
? {
...selectedWindow,
startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs),
}
: selectedWindow;
const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
cycleAnchors,
nowMs,
poolCycleBuckets,
quotaPoolsMap,
earliestActiveCyclePoolStartMs,
earliestSelectedStepMs,
});
const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries(
selectedWindow,
effectiveSelectedWindow,
@@ -1808,6 +1977,16 @@ export function aggregateMultiWindowUsage({
}
return out;
};
const serializeModelTokens = (mMap) => {
const out = {};
if (!(mMap instanceof Map)) return out;
for (const [mKey, tokVal] of mMap.entries()) {
if (mKey && Number.isFinite(tokVal) && tokVal > 0) {
out[mKey] = Math.round(tokVal);
}
}
return out;
};
for (const [poolKey, entry] of poolCycleBuckets.entries()) {
let recent10mCostUsd = 0;
for (const sStat of entry.recent10mSessions.values()) {
@@ -1816,10 +1995,14 @@ export function aggregateMultiWindowUsage({
poolCycleStats.set(poolKey, {
cycle5h: formatCycleSummary(entry.b5h),
cycleWeekly: formatCycleSummary(entry.bWk),
pricedTokens5h: Math.round(entry.pricedTokens5h || 0),
pricedTokensWeekly: Math.round(entry.pricedTokensWk || 0),
exactCost5hUsd: +entry.b5h.costUsd.toFixed(6),
exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6),
modelCosts5h: serializeModelCosts(entry.modelCosts5h),
modelCostsWeekly: serializeModelCosts(entry.modelCostsWk),
modelTokens5h: serializeModelTokens(entry.modelTokens5h),
modelTokensWeekly: serializeModelTokens(entry.modelTokensWk),
recent10m: {
lastActivityMs: entry.lastActivityMs,
activeSessionCount: entry.recent10mSessions.size,
@@ -1864,6 +2047,11 @@ export function aggregateMultiWindowUsage({
if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey);
}
lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap);
} else if (previous) {
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
activeSnap.revision = resolvedUsageRevision;
activeSnap.ranges.clear();
activeSnap.selectedRanges?.clear?.();
} else {
resolvedUsageRevision = activeSnap.revision;
}
@@ -1894,19 +2082,20 @@ export function aggregateMultiWindowUsage({
};
if (modelInputs && activeSnap) {
const { ranges } = activeSnap;
ranges.delete(selectedWindow.key);
ranges.set(selectedWindow.key, {
ranges.delete(selectedRangeCacheKey);
ranges.set(selectedRangeCacheKey, {
familySig,
windows,
selectedWindow,
effectiveSelectedWindow,
earliestActiveCyclePoolStartMs,
trend,
result,
earliest: earliestSelectedStepMs,
latest: latestSelectedStepMs,
});
// 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。
if (ranges.size > 10) ranges.delete(ranges.keys().next().value);
if (ranges.size > 16) ranges.delete(ranges.keys().next().value);
}
return result;
}
@@ -1954,6 +2143,14 @@ export function aggregateSelectedWindowUsage({
: 0;
const poolCycleBuckets =
selectedWindow.key === 'cycle' ? buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) : new Map();
const effectiveCyclePool =
selectedWindow.key === 'cycle'
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
: 'all';
const selectedRangeCacheKey =
selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all'
? `cycle:${effectiveCyclePool}`
: selectedWindow.key;
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
const poolByModel = new Map();
@@ -1967,6 +2164,19 @@ export function aggregateSelectedWindowUsage({
const currentYear = new Date(nowMs).getFullYear();
const timeZone = modelInputs ? resolveCachedLocalTimeZone() : '';
const currentCheckWindows =
selectedWindow.key === 'cycle'
? [
selectedWindow,
...Array.from(poolCycleBuckets, ([key, { startWkMs }]) => ({
key: `${key}:week`,
label: `${key}:week`,
startMs: startWkMs,
endMs: nowMs,
})),
]
: [selectedWindow];
const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
const sameSnapshot = Boolean(
modelInputs &&
@@ -1982,23 +2192,45 @@ export function aggregateSelectedWindowUsage({
if (sameSnapshot) {
snapshot.selectedRanges ??= new Map();
const cachedFull = snapshot.ranges.get(selectedWindow.key);
const cachedLite = snapshot.selectedRanges.get(selectedWindow.key);
const cachedFull = snapshot.ranges.get(selectedRangeCacheKey);
const cachedLite = snapshot.selectedRanges.get(selectedRangeCacheKey);
const candidate = cachedFull || cachedLite;
if (candidate) {
const prevWin = candidate.selectedWindow || candidate.windows?.[0] || selectedWindow;
const probeEffectiveWin =
selectedWindow.key === 'cycle'
? resolveEffectiveSelectedCycleWindow({
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
cycleAnchors,
nowMs,
poolCycleBuckets,
quotaPoolsMap,
earliestActiveCyclePoolStartMs: candidate.earliestActiveCyclePoolStartMs,
earliestSelectedStepMs: candidate.earliest,
})
: selectedWindow;
const effectivePrevWin =
selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow
? { ...candidate.effectiveSelectedWindow, endMs: nowMs }
? { ...probeEffectiveWin, endMs: nowMs }
: selectedWindow;
const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest);
const prevCheckWindows = candidate.checkWindows || [prevWin];
const compareNextWindows =
prevCheckWindows.length === currentCheckWindows.length
? currentCheckWindows
: [selectedWindow];
if (
Boolean(effectivePrevWin.isFallbackWeek) ===
Boolean(candidate.effectiveSelectedWindow?.isFallbackWeek) &&
trend.hourly === candidate.trend.hourly &&
trend.stepMs === candidate.trend.stepMs &&
trend.first === candidate.trend.first &&
trend.last === candidate.trend.last &&
sameUsageWindows(
[prevWin],
[selectedWindow],
prevCheckWindows.length === compareNextWindows.length ? prevCheckWindows : [prevWin],
compareNextWindows,
(snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)),
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
)
@@ -2013,6 +2245,7 @@ export function aggregateSelectedWindowUsage({
presetKeys: [],
presetWindows: {},
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
poolCycleBuckets,
normalizedQuotaAccount,
@@ -2034,6 +2267,9 @@ export function aggregateSelectedWindowUsage({
topWorkspaces: res.topWorkspaces || [],
};
}
snapshot.revision = ++usageSnapshotRevisionSeq;
snapshot.ranges.clear();
snapshot.selectedRanges.clear();
}
}
@@ -2049,6 +2285,11 @@ export function aggregateSelectedWindowUsage({
maxCutoffMs = nowMs;
if (isCustomWeeklyMode) {
minCutoffMs = weekStartMs;
} else if (effectiveCyclePool !== 'all' && poolCycleBuckets.has(effectiveCyclePool)) {
minCutoffMs = Math.max(
0,
poolCycleBuckets.get(effectiveCyclePool).startWkMs - maxSettlementSlackMs
);
} else if (poolCycleBuckets.size > 0) {
minCutoffMs = selectedWindow.startMs;
for (const entry of poolCycleBuckets.values()) {
@@ -2124,20 +2365,24 @@ export function aggregateSelectedWindowUsage({
: normalizedQuotaAccount === '' || stepOwner === ''
? true
: stepOwner === normalizedQuotaAccount;
mInfo = resolveStepModel(st);
const stepPool = resolveStepPoolAssignment(
st,
mInfo,
poolCycleBuckets,
poolByModel,
hasDedicatedCarbonPool,
hasDedicatedArgonPool
);
poolBucketEntry = stepPool.bucket;
if (effectiveCyclePool !== 'all' && stepPool.poolKey !== effectiveCyclePool) {
continue;
}
let inCurrentCycle = false;
if (isCustomWeeklyMode) {
inCurrentCycle = tMs >= weekStartMs;
} else if (poolCycleBuckets.size > 0) {
if (!includeInQuotaPools) continue;
mInfo = resolveStepModel(st);
poolBucketEntry = resolvePoolBucketForStep(
st,
mInfo,
poolCycleBuckets,
poolByModel,
hasDedicatedCarbonPool,
hasDedicatedArgonPool
);
const effCycleStartMs = poolBucketEntry
? poolBucketEntry.startWkMs
: selectedWindow.startMs;
@@ -2254,15 +2499,17 @@ export function aggregateSelectedWindowUsage({
}
}
const effectiveSelectedWindow =
selectedWindow.key === 'cycle' &&
Number.isFinite(earliestActiveCyclePoolStartMs) &&
earliestActiveCyclePoolStartMs < Infinity
? {
...selectedWindow,
startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs),
}
: selectedWindow;
const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
cycleAnchors,
nowMs,
poolCycleBuckets,
quotaPoolsMap,
earliestActiveCyclePoolStartMs,
earliestSelectedStepMs,
});
const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries(
selectedWindow,
@@ -2303,17 +2550,19 @@ export function aggregateSelectedWindowUsage({
if (sameSnapshot) {
snapshot.selectedRanges ??= new Map();
snapshot.selectedRanges.delete(selectedWindow.key);
snapshot.selectedRanges.set(selectedWindow.key, {
snapshot.selectedRanges.delete(selectedRangeCacheKey);
snapshot.selectedRanges.set(selectedRangeCacheKey, {
familySig,
checkWindows: currentCheckWindows,
selectedWindow,
effectiveSelectedWindow,
earliestActiveCyclePoolStartMs,
trend,
result: sliceResult,
earliest: earliestSelectedStepMs,
latest: latestSelectedStepMs,
});
if (snapshot.selectedRanges.size > 12) {
if (snapshot.selectedRanges.size > 16) {
snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value);
}
}
@@ -2360,6 +2609,10 @@ export function aggregateSessionUsageForFamily({
presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode);
}
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs);
const effectiveCyclePool =
selectedWindow.key === 'cycle'
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
: 'all';
const normalizedQuotaAccount =
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
@@ -2398,6 +2651,7 @@ export function aggregateSessionUsageForFamily({
presetKeys,
presetWindows,
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
poolCycleBuckets,
normalizedQuotaAccount,
@@ -2407,7 +2661,7 @@ export function aggregateSessionUsageForFamily({
}
/**
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
* 批量预聚合全部 7 个用量页预设区间及各配额池独立周期(复用同一次条目收集和时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
*/
export function aggregateConsumptionPresetBundle(params) {
const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {};
@@ -2422,6 +2676,25 @@ export function aggregateConsumptionPresetBundle(params) {
const ranges = {};
let usageRevision = usageSnapshotRevisionSeq;
const packSlice = (agg) => ({
selectedRange: {
key: agg.selectedWindow.key,
...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}),
...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}),
...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
label: agg.selectedWindow.label,
startMs: agg.trendStartMs,
endMs: agg.trendEndMs,
},
session: agg.finalizedSelectedSession,
account: agg.finalizedSelectedAccount,
trendSeries: agg.trendSeries,
sourcesBreakdown: agg.sourcesBreakdown,
modelBreakdown: agg.modelBreakdown,
topConversations: agg.topConversations || [],
topWorkspaces: agg.topWorkspaces || [],
});
for (const rangeKey of CONSUMPTION_PRESET_RANGE_KEYS) {
const agg = aggregateSelectedWindowUsage({
...params,
@@ -2429,21 +2702,20 @@ export function aggregateConsumptionPresetBundle(params) {
precollectedEntries,
});
usageRevision = agg.usageRevision;
ranges[rangeKey] = {
selectedRange: {
key: agg.selectedWindow.key,
label: agg.selectedWindow.label,
startMs: agg.trendStartMs,
endMs: agg.trendEndMs,
},
session: agg.finalizedSelectedSession,
account: agg.finalizedSelectedAccount,
trendSeries: agg.trendSeries,
sourcesBreakdown: agg.sourcesBreakdown,
modelBreakdown: agg.modelBreakdown,
topConversations: agg.topConversations || [],
topWorkspaces: agg.topWorkspaces || [],
};
ranges[rangeKey] = packSlice(agg);
}
if (params?.quotaPoolsMap instanceof Map) {
for (const poolKey of params.quotaPoolsMap.keys()) {
if (!poolKey || poolKey === 'all') continue;
const agg = aggregateSelectedWindowUsage({
...params,
filterOpts: { range: 'cycle', pool: poolKey },
precollectedEntries,
});
usageRevision = agg.usageRevision;
ranges[`cycle:${poolKey}`] = packSlice(agg);
}
}
return { usageRevision, ranges };
+443 -45
View File
@@ -31,6 +31,7 @@ import {
WINDOW_OVERLAY_KEY,
WINDOW_OVERLAY_METHODS,
} from '../shared/window-bridge-protocol.mjs';
import { HOST_I18N_GLOBAL_KEY } from '../shared/host-i18n-protocol.mjs';
import {
DATA_DIR,
computeRuntimeCodeVersion,
@@ -45,6 +46,13 @@ import {
getContextWindowModels,
resolveContextWindowRules,
} from './context-windows.mjs';
import {
createHostI18nApplyExpression,
createHostI18nCollectExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
getHostI18nBridgeDescriptor,
} from './host-i18n/index.mjs';
import {
ensureDesktopLaunchEntriesConfigured,
resolveDesktopHostExecutable,
@@ -64,6 +72,7 @@ import { getDefaultCloudCodeProxy } from './cloudcode-proxy.mjs';
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
const windowHostI18nRef = `window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}]`;
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
const windowBridgeEndpointKey = JSON.stringify(WINDOW_BRIDGE_ENDPOINT_KEY);
const overlayMethods = Object.fromEntries(
@@ -71,8 +80,74 @@ const overlayMethods = Object.fromEntries(
);
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
const BRIDGE_MAX_EXPORT_BODY_BYTES = 8 * 1024 * 1024;
// 8 MiB 原始导出文件经 Base64 (4/3x) 编码和 JSON 封装后约 10.7 MiB,预留 12 MiB 请求体上限
const BRIDGE_MAX_EXPORT_BODY_BYTES = 12 * 1024 * 1024;
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const IDE_ROUTE_PROBE_MAX_TIMEOUT_MS = 1000;
function sanitizeRouteCascadeId(raw) {
const id = String(raw || '').trim();
return CASCADE_UUID_RE.test(id) ? id : '';
}
const WINDOW_VISIBLE_EXPR = `Boolean(
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
!(typeof document !== 'undefined' && document?.hidden === true)
)`;
/**
* 构建单一事实来源的页面内会话路由提取 IIFE 片段,供常规保活探测与 IDE 聊天 iframe 路由探测共用:
* 优先解析 `/c/<uuid>`,其次在非隐藏且非零尺寸的 `conversation-view` 中按聚焦态、选中行交集及首个可见视图裁决。
*
* @returns {string}
*/
function buildDomRouteCascadeIdSnippet() {
return `(() => {
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i);
if (m && uuidRe.test(m[1])) return m[1];
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') return '';
const selectedRow = document.querySelector(
'[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]'
);
const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim();
if (typeof document.querySelectorAll === 'function') {
const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]');
const visibleIds = [];
let focusedId = '';
const activeEl = document.activeElement || null;
for (const viewEl of views) {
const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim();
if (!uuidRe.test(cid)) continue;
if (viewEl.hasAttribute?.('hidden')) continue;
if (viewEl.getBoundingClientRect) {
const r = viewEl.getBoundingClientRect();
if (r.width <= 0 && r.height <= 0) continue;
}
visibleIds.push(cid);
if (activeEl && viewEl.contains?.(activeEl)) {
focusedId = cid;
}
}
if (focusedId) return focusedId;
if (
selectedRowId &&
uuidRe.test(selectedRowId) &&
visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase())
) {
return selectedRowId;
}
if (visibleIds.length > 0) return visibleIds[0];
}
const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]');
const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim();
if (uuidRe.test(singleViewId)) return singleViewId;
if (uuidRe.test(selectedRowId)) return selectedRowId;
return '';
})()`;
}
/**
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
@@ -1084,6 +1159,10 @@ export function createWindowBridgeController(options) {
cloudCodeProxy = null,
manageCloudCodeProxy = false,
resolveLocalContextRulesFn = null,
getHostI18nDescriptorFn =
options?.env === undefined && options?.homeDir === undefined
? getHostI18nBridgeDescriptor
: () => ({ active: false, revision: '', getPayload: null }),
} = options || {};
const activeCloudCodeProxy =
@@ -1144,6 +1223,10 @@ export function createWindowBridgeController(options) {
};
let hadContextWindows = false;
let contextWindowBootId = `${process.pid}:${Date.now()}`;
let hadHostI18n = false;
let hostI18nBootId = `hi18n:${process.pid}:${Date.now()}`;
let lastHostI18nAppliedCount = 0;
let cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
const cachedBackendCtxModelsByEndpoint = new Map();
const targetClassifyCache = new Map();
let nodeDepsPromise = null;
@@ -1343,17 +1426,34 @@ export function createWindowBridgeController(options) {
return;
}
const maxBodyBytes =
let maxBodyBytes =
parsedUrl.pathname === '/api/export-file'
? BRIDGE_MAX_EXPORT_BODY_BYTES
: BRIDGE_MAX_BODY_BYTES;
const chunks = [];
let totalBytes = 0;
let aborted = false;
let checkedSettingsExportPrefix = false;
req.on('data', (chunk) => {
totalBytes += chunk.length;
const nextTotal = totalBytes + chunk.length;
if (
nextTotal > maxBodyBytes &&
!checkedSettingsExportPrefix &&
parsedUrl.pathname === '/api/settings' &&
nextTotal <= BRIDGE_MAX_EXPORT_BODY_BYTES
) {
checkedSettingsExportPrefix = true;
const sampleParts = chunks.length > 0 ? [...chunks, chunk] : [chunk];
const headBuf = Buffer.concat(sampleParts, Math.min(nextTotal, 512));
const headStr = headBuf.toString('utf8').trimStart();
if (/^\{\s*"__exportFileAction"\s*:\s*"(?:save|reveal)"/.test(headStr)) {
maxBodyBytes = BRIDGE_MAX_EXPORT_BODY_BYTES;
}
}
totalBytes = nextTotal;
if (totalBytes > maxBodyBytes) {
aborted = true;
chunks.length = 0;
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' }));
req.destroy();
@@ -1372,6 +1472,18 @@ export function createWindowBridgeController(options) {
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
return;
}
if (
totalBytes > BRIDGE_MAX_BODY_BYTES &&
parsedUrl.pathname === '/api/settings' &&
(!bodyObj ||
typeof bodyObj !== 'object' ||
Array.isArray(bodyObj) ||
typeof bodyObj.__exportFileAction !== 'string')
) {
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' }));
return;
}
Promise.resolve(invokeApiHandler(parsedUrl.pathname, 'POST', bodyObj, normalizedReqEndpoint))
.then((out) => {
const hdrs = {
@@ -1548,14 +1660,18 @@ export function createWindowBridgeController(options) {
return { reachableCount, targets: merged };
}
async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0) {
async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0, signal = null) {
const WS = WebSocketImpl || globalThis.WebSocket;
if (typeof WS !== 'function') {
throw new Error('WebSocket runtime unavailable');
}
if (signal?.aborted) {
throw new Error('CDP Runtime.evaluate aborted');
}
const effectiveTimeoutMs = Math.max(500, Number(timeoutMsOverride) || cdpTimeoutMs);
let ws = null;
let timer = null;
let onAbort = null;
try {
ws = new WS(wsUrl);
const evalResult = await new Promise((resolve, reject) => {
@@ -1563,6 +1679,11 @@ export function createWindowBridgeController(options) {
reject(new Error('CDP Runtime.evaluate timeout'));
}, effectiveTimeoutMs);
if (signal && typeof signal.addEventListener === 'function') {
onAbort = () => reject(new Error('CDP Runtime.evaluate aborted'));
signal.addEventListener('abort', onAbort, { once: true });
}
const onOpen = () => {
try {
ws.send(
@@ -1604,6 +1725,9 @@ export function createWindowBridgeController(options) {
return evalResult;
} finally {
if (timer) clearTimeout(timer);
if (onAbort && signal && typeof signal.removeEventListener === 'function') {
signal.removeEventListener('abort', onAbort);
}
if (ws) {
try {
ws.close();
@@ -1772,10 +1896,21 @@ export function createWindowBridgeController(options) {
const needsMainCdpContext = hasContextWindows && ctxMainEnabled;
const needsCloudCodeProxy = hasContextWindows && ctxSwarmEnabled;
const needsAnyCdpContext = hasContextWindows && (ctxMainEnabled || ctxSwarmEnabled);
const hostI18nDesc =
typeof getHostI18nDescriptorFn === 'function' ? getHostI18nDescriptorFn() : null;
const needsHostI18n = Boolean(
hostI18nDesc?.active &&
hostI18nDesc?.revision &&
typeof hostI18nDesc?.getPayload === 'function'
);
let leasedBySelf = false;
let currentLease = null;
if ((enabled || needsAnyCdpContext || needsCloudCodeProxy) && leaseFilePath && !forceReinject) {
if (
(enabled || needsAnyCdpContext || needsCloudCodeProxy || needsHostI18n) &&
leaseFilePath &&
!forceReinject
) {
const lease = loadJson(leaseFilePath, null);
currentLease = lease;
const leasePid = Number(lease?.pid || 0);
@@ -1844,7 +1979,7 @@ export function createWindowBridgeController(options) {
}
const shouldCheckLaunchers =
(enabled || needsMainCdpContext) &&
(enabled || needsMainCdpContext || needsHostI18n) &&
autoConfigureIdeArgv &&
(lastLauncherProvisionAtMs === 0 ||
Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs);
@@ -1859,12 +1994,15 @@ export function createWindowBridgeController(options) {
if (provPending) {
await provPending.catch(() => {});
}
updateBridgeStatus(enabled || needsMainCdpContext ? 'no_devtools_port' : 'disabled', {
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
});
updateBridgeStatus(
enabled || needsMainCdpContext || needsHostI18n ? 'no_devtools_port' : 'disabled',
{
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
}
);
return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 };
}
@@ -1877,12 +2015,15 @@ export function createWindowBridgeController(options) {
if (provPending) {
await provPending.catch(() => {});
}
updateBridgeStatus(enabled || needsMainCdpContext ? 'cdp_unreachable' : 'disabled', {
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
});
updateBridgeStatus(
enabled || needsMainCdpContext || needsHostI18n ? 'cdp_unreachable' : 'disabled',
{
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
}
);
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
}
@@ -1905,6 +2046,8 @@ export function createWindowBridgeController(options) {
!enabled &&
!needsAnyCdpContext &&
!hadContextWindows &&
!needsHostI18n &&
!hadHostI18n &&
!hadInjectedTargets &&
!hadInjectedChatFrames &&
!forceReinject
@@ -2144,6 +2287,66 @@ export function createWindowBridgeController(options) {
hadContextWindows = needsAnyCdpContext;
}
if (needsHostI18n || hadHostI18n) {
const hostI18nWsUrls = new Set();
for (const target of targets) {
if (target.isIdeWorkbench) continue;
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
if (wsUrl) hostI18nWsUrls.add(wsUrl);
}
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
if (chatUrl) hostI18nWsUrls.add(chatUrl);
}
if (!needsHostI18n) {
const disposeHostI18nExpr = createHostI18nDisposeExpression();
await Promise.allSettled(
Array.from(hostI18nWsUrls).map((wsUrl) => evaluateOnTarget(wsUrl, disposeHostI18nExpr))
);
hadHostI18n = false;
lastHostI18nAppliedCount = 0;
cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
} else {
const heartbeatExpr = createHostI18nHeartbeatExpression(
hostI18nBootId,
hostI18nDesc.revision
);
let appliedTargets = 0;
await Promise.allSettled(
Array.from(hostI18nWsUrls).map(async (wsUrl) => {
try {
const hbRes = await evaluateOnTarget(wsUrl, heartbeatExpr, 1800);
const hbVal = hbRes?.result?.result?.value;
if (hbVal?.alive === true && hbVal?.needsApply === false) {
appliedTargets += 1;
return;
}
} catch {
// 心跳异常时回退完整注入
}
if (
!cachedHostI18nApply.expr ||
cachedHostI18nApply.revision !== hostI18nDesc.revision ||
cachedHostI18nApply.bootId !== hostI18nBootId
) {
const payload = hostI18nDesc.getPayload();
cachedHostI18nApply = {
revision: hostI18nDesc.revision,
bootId: hostI18nBootId,
expr: createHostI18nApplyExpression(payload, hostI18nBootId),
};
}
const applyRes = await evaluateOnTarget(wsUrl, cachedHostI18nApply.expr, 8000);
if (applyRes?.result?.result?.value?.applied) {
appliedTargets += 1;
}
})
);
hadHostI18n = true;
lastHostI18nAppliedCount = appliedTargets;
}
}
const disposeExpr = `(() => {
try {
const existed = Boolean(${windowOverlayRef} || ${windowBridgeRef});
@@ -2199,6 +2402,7 @@ export function createWindowBridgeController(options) {
}
const { port, token } = await ensureBridgeServer();
const domRouteExpr = buildDomRouteCascadeIdSnippet();
const probeExpr = `(() => {
try {
const ov = ${windowOverlayRef};
@@ -2206,28 +2410,11 @@ export function createWindowBridgeController(options) {
const alive = Boolean(ov && typeof ov[${overlayMethods.ensureAlive}] === 'function' && ov[${overlayMethods.ensureAlive}]());
const dockKind = String(ov?.[${overlayMethods.getDockKind}]?.() || '');
const clientMountMode = String(ov?.[${overlayMethods.getMountMode}]?.() || '');
const visible = Boolean(
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
!(typeof document !== 'undefined' && document?.hidden === true)
);
const visible = ${WINDOW_VISIBLE_EXPR};
const rpcBatch = Array.isArray(br?.rpcQueue) && br.rpcQueue.length > 0
? br.rpcQueue.splice(0, 8)
: [];
let routeCascadeId = '';
if (!alive) {
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i);
if (m && uuidRe.test(m[1])) {
routeCascadeId = m[1];
} else if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
const el =
document.querySelector('[data-testid="conversation-view"][data-cascade-id]') ||
document.querySelector('[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]');
const cand = String(el?.getAttribute?.('data-cascade-id') || '').trim();
if (uuidRe.test(cand)) routeCascadeId = cand;
}
}
const routeCascadeId = !alive ? ${domRouteExpr} : '';
return {
alive,
dockKind,
@@ -2248,6 +2435,107 @@ export function createWindowBridgeController(options) {
}
})()`;
const ideChatRouteProbeExpr = `(() => {
try {
const visible = ${WINDOW_VISIBLE_EXPR};
const focused = Boolean(
typeof document !== 'undefined' && typeof document.hasFocus === 'function' && document.hasFocus()
);
const routeCascadeId = ${domRouteExpr};
return { routeCascadeId, visible, focused };
} catch {
return { routeCascadeId: '', visible: false, focused: false };
}
})()`;
const ideRouteProbeTimeoutMs = Math.max(
500,
Math.min(Number(cdpTimeoutMs) || IDE_ROUTE_PROBE_MAX_TIMEOUT_MS, IDE_ROUTE_PROBE_MAX_TIMEOUT_MS)
);
async function resolveIdeWorkbenchRouteId(targetObj) {
const staticRouteId = sanitizeRouteCascadeId(targetObj?.ideRouteCascadeId);
const chatList = Array.isArray(targetObj?.ideChatTargets) ? targetObj.ideChatTargets : [];
const probeUrls = chatList
.map((chatTarget) => String(chatTarget?.webSocketDebuggerUrl || '').trim())
.filter(Boolean);
if (probeUrls.length === 0) {
return staticRouteId;
}
if (probeUrls.length === 1) {
try {
const res = await evaluateOnTarget(probeUrls[0], ideChatRouteProbeExpr, ideRouteProbeTimeoutMs);
const cid = sanitizeRouteCascadeId(res?.result?.result?.value?.routeCascadeId);
return cid || staticRouteId;
} catch {
return staticRouteId;
}
}
const abortCtrl = typeof AbortController === 'function' ? new AbortController() : null;
const results = new Array(probeUrls.length).fill(null);
let settledCount = 0;
let resolved = false;
return new Promise((resolve) => {
const pickBest = () => {
let bestRouteId = '';
let bestRank = 0;
for (const item of results) {
if (!item || !item.cid) continue;
if (item.rank > bestRank) {
bestRank = item.rank;
bestRouteId = item.cid;
if (bestRank === 3) break;
}
}
return bestRouteId || staticRouteId;
};
const finishEarly = (routeId) => {
if (resolved) return;
resolved = true;
try {
abortCtrl?.abort();
} catch {
// 忽略中止异常
}
resolve(routeId);
};
probeUrls.forEach((chatWsUrl, idx) => {
evaluateOnTarget(
chatWsUrl,
ideChatRouteProbeExpr,
ideRouteProbeTimeoutMs,
abortCtrl?.signal || null
)
.then((res) => {
const val = res?.result?.result?.value;
const cid = sanitizeRouteCascadeId(val?.routeCascadeId);
if (cid) {
const rank = val?.focused && val?.visible ? 3 : val?.visible ? 2 : 1;
results[idx] = { cid, rank };
if (rank === 3) {
finishEarly(cid);
}
}
})
.catch(() => {
// 单个聊天子视图探测异常、超时或提前中止均不阻断其他视图及静态路由兜底
})
.finally(() => {
settledCount += 1;
if (!resolved && settledCount === probeUrls.length) {
resolved = true;
resolve(pickBest());
}
});
});
});
}
let cachedAssets = null;
let injected = 0;
let aliveCount = 0;
@@ -2258,7 +2546,7 @@ export function createWindowBridgeController(options) {
const wsUrl = String(targetObj?.webSocketDebuggerUrl || '').trim();
if (!wsUrl) return { alive: false, dockKind: '', visible: false };
let probedRouteId = '';
const ideRouteId = String(ideRouteOverride || targetObj.ideRouteCascadeId || '').trim();
const ideRouteId = sanitizeRouteCascadeId(ideRouteOverride || targetObj.ideRouteCascadeId);
const targetEndpointId = String(targetObj.endpointId || LOCAL_ENDPOINT_ID);
const targetIsRemote = Boolean(targetObj.isRemoteEndpoint && targetEndpointId !== LOCAL_ENDPOINT_ID);
const targetEndpointLabel = targetIsRemote ? String(targetObj.endpointLabel || 'SSH') : '';
@@ -2266,7 +2554,7 @@ export function createWindowBridgeController(options) {
if (!forceReinject) {
const probeRes = await evaluateOnTarget(wsUrl, probeExpr);
const snap = probeRes?.result?.result?.value;
probedRouteId = String(snap?.routeCascadeId || '').trim();
probedRouteId = sanitizeRouteCascadeId(snap?.routeCascadeId);
if (snap && snap.alive === true) {
const snapVerNum = Number(snap.bundleVersion) || 0;
const curVerNum = Number(bundleVersion) || 0;
@@ -2456,12 +2744,16 @@ export function createWindowBridgeController(options) {
if (chatComposerActive) {
await disposeSingleTarget(target.webSocketDebuggerUrl);
} else {
await syncSingleTarget(target);
const ideRouteOverride = await resolveIdeWorkbenchRouteId(target);
await syncSingleTarget(target, { ideRouteOverride });
}
continue;
}
await syncSingleTarget(target);
const ideRouteOverride = target.isIdeWorkbench
? await resolveIdeWorkbenchRouteId(target)
: '';
await syncSingleTarget(target, { ideRouteOverride });
} catch {
// 单个窗口注入异常不阻断其他窗口
}
@@ -2588,7 +2880,10 @@ export function createWindowBridgeController(options) {
clearTimeout(pollTimer);
pollTimer = null;
}
if (disposeWindows && (hadInjectedTargets || hadInjectedChatFrames || hadContextWindows)) {
if (
disposeWindows &&
(hadInjectedTargets || hadInjectedChatFrames || hadContextWindows || hadHostI18n)
) {
const prevStopped = stopped;
stopped = false;
try {
@@ -2599,6 +2894,7 @@ export function createWindowBridgeController(options) {
}));
const disposeExpr = `(() => {
try {
${windowHostI18nRef}?.dispose?.();
${windowContextWindowsRef}?.dispose?.();
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
delete ${windowOverlayRef};
@@ -2624,6 +2920,9 @@ export function createWindowBridgeController(options) {
hadInjectedTargets = false;
hadInjectedChatFrames = false;
hadContextWindows = false;
hadHostI18n = false;
lastHostI18nAppliedCount = 0;
cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
if (activeCloudCodeProxy) {
await activeCloudCodeProxy.stop().catch(() => {});
}
@@ -2646,7 +2945,10 @@ export function createWindowBridgeController(options) {
const hasCtx =
Object.keys(cur.modelContextWindows || {}).length > 0 &&
cur.contextWindowMainEnabled !== false;
if (!hasCtx && autoConfigureIdeArgv) {
const hasHostI18n = Boolean(
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
);
if (!hasCtx && !hasHostI18n && autoConfigureIdeArgv) {
launcherConfigured = false;
hasReadOnlyShortcuts = false;
lastLauncherProvisionAtMs = 0;
@@ -2674,9 +2976,12 @@ export function createWindowBridgeController(options) {
const hasCtx =
Object.keys(cur.modelContextWindows || {}).length > 0 &&
cur.contextWindowMainEnabled !== false;
const hasHostI18n = Boolean(
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
);
if (hasCtx) {
lastLauncherProvisionAtMs = 0;
} else if (!overlayOn && autoConfigureIdeArgv) {
} else if (!overlayOn && !hasHostI18n && autoConfigureIdeArgv) {
launcherConfigured = false;
hasReadOnlyShortcuts = false;
lastLauncherProvisionAtMs = 0;
@@ -2693,16 +2998,97 @@ export function createWindowBridgeController(options) {
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
}
function notifyHostI18nChanged() {
const cur = getSettingsFn() || {};
const mountMode = normalizeWindowMountMode(cur.windowMountMode, cur.enableWindowOverlay);
const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar');
const hasCtx =
Object.keys(cur.modelContextWindows || {}).length > 0 &&
cur.contextWindowMainEnabled !== false;
const hasHostI18n = Boolean(
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
);
if (hasHostI18n) {
lastLauncherProvisionAtMs = 0;
} else {
hadHostI18n = true;
if (!overlayOn && !hasCtx && autoConfigureIdeArgv) {
launcherConfigured = false;
hasReadOnlyShortcuts = false;
lastLauncherProvisionAtMs = 0;
void ensureDesktopLaunchEntriesConfigured({
enabled: false,
env,
platform,
homeDir,
execFileFn: launcherExecFileFn,
fsOps: launcherFsOps,
allowInTest: allowDesktopLauncherInTest,
}).catch(() => {});
}
}
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
}
async function collectHostI18nUntranslatedFromTargets() {
const cdpPorts = findActiveDevToolsPorts();
if (!cdpPorts.length) {
return { targets: 0, items: [] };
}
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({ targets: [] }));
const wsUrls = new Set();
for (const target of targets) {
if (target.isIdeWorkbench) continue;
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
if (wsUrl) wsUrls.add(wsUrl);
}
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
if (chatUrl) wsUrls.add(chatUrl);
}
if (wsUrls.size === 0) {
return { targets: 0, items: [] };
}
const collectExpr = createHostI18nCollectExpression();
const settled = await Promise.allSettled(
Array.from(wsUrls).map((wsUrl) => evaluateOnTarget(wsUrl, collectExpr, 3500))
);
const mergedCounts = new Map();
const mergedKinds = new Map();
let scannedTargets = 0;
for (const res of settled) {
if (res.status !== 'fulfilled') continue;
const val = res.value?.result?.result?.value;
if (!val || !Array.isArray(val.items)) continue;
scannedTargets += 1;
for (const item of val.items) {
const text = String(item?.text || '').trim();
if (!text) continue;
mergedCounts.set(text, (mergedCounts.get(text) || 0) + (Number(item?.count || 1) || 1));
if (!mergedKinds.has(text)) mergedKinds.set(text, String(item?.kind || 'text'));
}
}
const items = Array.from(mergedCounts.entries())
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
.slice(0, 200)
.map(([text, count]) => ({ text, kind: mergedKinds.get(text) || 'text', count }));
return { targets: scannedTargets, items };
}
return {
ensureBridgeServer,
syncAllWindows,
invokeRemoteWindowRpc,
notifySettingChanged,
notifyContextWindowsChanged,
notifyHostI18nChanged,
collectHostI18nUntranslatedFromTargets,
start,
stop,
getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }),
getBridgeStatus: () => ({ ...lastBridgeStatus }),
getBridgeStatus: () => ({
...lastBridgeStatus,
hostI18nAppliedCount: lastHostI18nAppliedCount,
}),
};
}
@@ -2761,3 +3147,15 @@ export function notifyModelContextWindowsChanged() {
if (!defaultBridgeController) return Promise.resolve({ ok: false });
return defaultBridgeController.notifyContextWindowsChanged();
}
export function notifyHostI18nChanged() {
if (!defaultBridgeController) return Promise.resolve({ ok: false });
return defaultBridgeController.notifyHostI18nChanged();
}
export function collectHostI18nUntranslatedFromActiveTargets() {
if (!defaultBridgeController) {
return Promise.resolve({ targets: 0, items: [] });
}
return defaultBridgeController.collectHostI18nUntranslatedFromTargets();
}
+138 -43
View File
@@ -37,6 +37,10 @@ import {
readLocalSummaryIndex,
} from './backend/cli-sqlite-reader.mjs';
import { computeSqliteWalSig, withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
import {
buildTranscriptFallbackTrajectory,
resolveTranscriptPathInLogsDir,
} from './backend/transcript-fallback.mjs';
import {
buildCliJsonStatusOutput,
ensureCliStatusLineConfigured,
@@ -189,8 +193,13 @@ function findConversationIdByWorkspaceFts(cliRoot, cwd) {
}
}
function resolveCliTranscriptPath(cliRoot, cid) {
if (!cliRoot || !cid) return '';
return resolveTranscriptPathInLogsDir(join(cliRoot, 'brain', cid, '.system_generated', 'logs'));
}
/**
* 解析当前 CLI 窗口对应的本地 `.db` 会话轨迹并计算最新测速、延迟、缓存与成本指标。
* 解析当前 CLI 窗口对应的本地 `.db`(或降级 `.pb` + `transcript.jsonl`)会话轨迹并计算最新测速、延迟、缓存与成本指标。
*
* @param {{ cliRoot: string, stdinData?: object|null, nowMs?: number }} params
*/
@@ -234,35 +243,49 @@ export function resolveCliLocalSessionMetrics({
'';
if (!targetCid && effectiveCwd) {
const ftsCid = findConversationIdByWorkspaceFts(cliRoot, effectiveCwd);
if (ftsCid && existsSync(join(convDir, `${ftsCid}.db`))) {
if (
ftsCid &&
(existsSync(join(convDir, `${ftsCid}.db`)) || existsSync(join(convDir, `${ftsCid}.pb`)))
) {
targetCid = ftsCid;
}
}
let dbPath = targetCid ? join(convDir, `${targetCid}.db`) : '';
if (!dbPath || !existsSync(dbPath)) {
let pbPath = targetCid ? join(convDir, `${targetCid}.pb`) : '';
if (!targetCid || (!existsSync(dbPath) && !existsSync(pbPath))) {
let candidates = [];
try {
candidates = readdirSync(convDir)
.filter((name) => name.endsWith('.db'))
.map((name) => {
const cid = name.slice(0, -3).toLowerCase();
const full = join(convDir, name);
let mtimeMs = 0;
try {
mtimeMs = statSync(full).mtimeMs || 0;
} catch {
// 忽略单文件 stat 异常
}
const byCid = new Map();
for (const name of readdirSync(convDir)) {
const isDb = name.endsWith('.db');
const isPb = !isDb && name.endsWith('.pb');
if (!isDb && !isPb) continue;
const cid = name.slice(0, -3).toLowerCase();
const full = join(convDir, name);
let mtimeMs = 0;
try {
mtimeMs = statSync(full).mtimeMs || 0;
} catch {
// 忽略单文件 stat 异常
}
const existing = byCid.get(cid);
if (!existing) {
const summary = summariesMap.get(cid);
return {
byCid.set(cid, {
cid,
full,
dbFull: isDb ? full : '',
pbFull: isPb ? full : '',
mtimeMs,
isSubagent: Boolean(summary?.parentConversationId),
};
})
.sort((a, b) => b.mtimeMs - a.mtimeMs);
});
} else {
if (isDb) existing.dbFull = full;
if (isPb) existing.pbFull = full;
if (mtimeMs > existing.mtimeMs) existing.mtimeMs = mtimeMs;
}
}
candidates = Array.from(byCid.values()).sort((a, b) => b.mtimeMs - a.mtimeMs);
} catch {
candidates = [];
}
@@ -270,11 +293,14 @@ export function resolveCliLocalSessionMetrics({
const picked = candidates.find((c) => !c.isSubagent) || candidates[0];
if (picked) {
targetCid = picked.cid;
dbPath = picked.full;
dbPath = picked.dbFull || join(convDir, `${picked.cid}.db`);
pbPath = picked.pbFull || join(convDir, `${picked.cid}.pb`);
}
}
if (!dbPath || !existsSync(dbPath)) {
const hasDbFile = Boolean(dbPath && existsSync(dbPath));
const hasPbFile = Boolean(pbPath && existsSync(pbPath));
if (!hasDbFile && !hasPbFile) {
return {
found: false,
runningRootCount,
@@ -282,23 +308,69 @@ export function resolveCliLocalSessionMetrics({
};
}
const parentLink = readLocalSqliteParentLink(dbPath);
if (parentLink?.parentConversationId || parentLink?.rootConversationId) {
const candidateRootId = parentLink.rootConversationId || parentLink.parentConversationId;
const rootDb = join(convDir, `${candidateRootId}.db`);
if (candidateRootId && existsSync(rootDb)) {
targetCid = candidateRootId;
dbPath = rootDb;
if (hasDbFile) {
const parentLink = readLocalSqliteParentLink(dbPath);
if (parentLink?.parentConversationId || parentLink?.rootConversationId) {
const candidateRootId = parentLink.rootConversationId || parentLink.parentConversationId;
const rootDb = join(convDir, `${candidateRootId}.db`);
const rootPb = join(convDir, `${candidateRootId}.pb`);
if (candidateRootId && (existsSync(rootDb) || existsSync(rootPb))) {
targetCid = candidateRootId;
dbPath = rootDb;
pbPath = rootPb;
}
}
} else {
const summaryParent = summariesMap.get(targetCid)?.parentConversationId || '';
if (summaryParent) {
const rootDb = join(convDir, `${summaryParent}.db`);
const rootPb = join(convDir, `${summaryParent}.pb`);
if (existsSync(rootDb) || existsSync(rootPb)) {
targetCid = summaryParent;
dbPath = rootDb;
pbPath = rootPb;
}
}
}
const walInfo = computeSqliteWalSig(dbPath);
const dbMtimeMs = walInfo.mtimeMs || 0;
const walInfo = dbPath ? computeSqliteWalSig(dbPath) : { exists: false, mtimeMs: 0, sig: '' };
let fallbackMtimeMs = 0;
let fallbackSigPart = '';
if (!walInfo.exists || (pbPath && existsSync(pbPath))) {
const fbParts = [];
if (pbPath) {
try {
const pbSt = statSync(pbPath, { throwIfNoEntry: false });
if (pbSt) {
fallbackMtimeMs = Math.max(fallbackMtimeMs, Number(pbSt.mtimeMs || 0));
fbParts.push(`p:${Math.floor(Number(pbSt.mtimeMs || 0))}:${Number(pbSt.size || 0)}`);
}
} catch {
// 忽略 stat 异常
}
}
const trPath = resolveCliTranscriptPath(cliRoot, targetCid);
if (trPath) {
try {
const trSt = statSync(trPath, { throwIfNoEntry: false });
if (trSt) {
fallbackMtimeMs = Math.max(fallbackMtimeMs, Number(trSt.mtimeMs || 0));
fbParts.push(`t:${Math.floor(Number(trSt.mtimeMs || 0))}:${Number(trSt.size || 0)}`);
}
} catch {
// 忽略 stat 异常
}
}
fallbackSigPart = fbParts.join(',');
}
const dbMtimeMs = Math.max(walInfo.mtimeMs || 0, fallbackMtimeMs);
const targetLower = String(targetCid || '').toLowerCase();
const targetIsRunning = freshRunningRootIds.includes(targetLower);
const cliTrajMemoFile = join(DATA_DIR, 'cli-statusline-traj-memo.json');
const prevMemo = walInfo.sig ? loadJson(cliTrajMemoFile, null) : null;
const effectiveDataDir = String(process.env.USAGE_MONITOR_DATA_DIR || '').trim() || DATA_DIR;
const cliTrajMemoFile = join(effectiveDataDir, 'cli-statusline-traj-memo.json');
const combinedSig = [walInfo.sig, fallbackSigPart].filter(Boolean).join('~');
const prevMemo = combinedSig ? loadJson(cliTrajMemoFile, null) : null;
const prevOtherCache =
prevMemo && typeof prevMemo.otherWaiting === 'object' && prevMemo.otherWaiting !== null
? prevMemo.otherWaiting
@@ -342,7 +414,7 @@ export function resolveCliLocalSessionMetrics({
}
}
const targetMemoKey = walInfo.sig ? `v1::${dbPath}::${walInfo.sig}` : '';
const targetMemoKey = combinedSig ? `v1::${targetCid}::${combinedSig}` : '';
if (
targetMemoKey &&
prevMemo?.targetKey === targetMemoKey &&
@@ -401,21 +473,44 @@ export function resolveCliLocalSessionMetrics({
};
}
let traj = readLocalSqliteTrajectory(dbPath, {
cascadeId: targetCid,
isRunning: targetIsRunning,
});
let traj = walInfo.exists
? readLocalSqliteTrajectory(dbPath, {
cascadeId: targetCid,
isRunning: targetIsRunning,
})
: null;
if (traj?.parentConversationId) {
const rootDb = join(convDir, `${traj.rootConversationId || traj.parentConversationId}.db`);
if (rootDb !== dbPath && existsSync(rootDb)) {
const rootTraj = readLocalSqliteTrajectory(rootDb, { isRunning: true });
if (rootTraj) {
targetCid = traj.rootConversationId || traj.parentConversationId;
const rootCid = traj.rootConversationId || traj.parentConversationId;
const rootDb = join(convDir, `${rootCid}.db`);
const rootPb = join(convDir, `${rootCid}.pb`);
if (rootCid && rootCid !== targetCid) {
if (existsSync(rootDb)) {
const rootTraj = readLocalSqliteTrajectory(rootDb, { isRunning: true });
if (rootTraj) {
targetCid = rootCid;
dbPath = rootDb;
pbPath = rootPb;
traj = rootTraj;
} else if (existsSync(rootPb) || resolveCliTranscriptPath(cliRoot, rootCid)) {
targetCid = rootCid;
dbPath = rootDb;
pbPath = rootPb;
traj = null;
}
} else if (existsSync(rootPb) || resolveCliTranscriptPath(cliRoot, rootCid)) {
targetCid = rootCid;
dbPath = rootDb;
traj = rootTraj;
pbPath = rootPb;
traj = null;
}
}
}
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
const fallbackTranscriptPath = resolveCliTranscriptPath(cliRoot, targetCid);
traj = fallbackTranscriptPath
? buildTranscriptFallbackTrajectory(fallbackTranscriptPath, targetCid)
: null;
}
if (!traj || !Array.isArray(traj.steps) || traj.steps.length === 0) {
if (targetMemoKey) {
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795426864084">
<link rel="stylesheet" href="/styles.css?v=1795581433079">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795426864084"></script>
<script src="/app.js?v=1795581433079"></script>
</body>
</html>
+12
View File
@@ -175,6 +175,18 @@ async function handleProtectedApi(pathname, method, data, req) {
contentType: 'application/json',
});
}
if (
!isTestHarnessEnv &&
pathname === '/api/accounts/update' &&
req?.headers &&
!req.headers.origin &&
!req.headers['sec-fetch-site']
) {
return new Response(JSON.stringify({ error: 'Forbidden non-webview account mutation' }), {
status: 403,
contentType: 'application/json',
});
}
const out = await forwardApiCall(pathname, method, data);
return new Response(out.body, {
status: out.status,
+9
View File
@@ -592,6 +592,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'shared/settings-normalization.mjs',
'shared/telemetry-display-rules.mjs',
'shared/window-bridge-protocol.mjs',
'shared/host-i18n-protocol.mjs',
'src/icons/svgRegistry.js',
'src/icons/SvgIcon.js',
'src/core/reactive.js',
@@ -609,6 +610,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/core/httpClient.js',
'src/store/uiStore.js',
'src/core/fileExportClient.js',
'src/core/hostI18nClient.js',
'src/store/telemetryStore.js',
'src/components/ui/TopLongPillNav.js',
'src/components/ui/SearchInput.js',
@@ -622,25 +624,31 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/components/ui/ContextSegmentMeter.js',
'src/components/ui/FourSegmentBar.js',
'src/components/ui/ConsumptionTooltipContent.js',
'src/components/charts/chartMotion.js',
'src/components/charts/TrendAreaChart.js',
'src/components/charts/stepChartMath.js',
'src/components/charts/SessionStepCharts.js',
'src/registries/metricRegistry.js',
'src/components/widgets/MetricMatrixWidget.js',
'src/components/widgets/ContextWindowWidget.js',
'src/components/widgets/QuotaPoolsWidget.js',
'src/components/widgets/AccountQuotaTrendCard.js',
'src/components/widgets/LiveActivityWidget.js',
'src/registries/widgetRegistry.js',
'src/registries/stepColumnRegistry.js',
'src/components/widgets/CapsuleBarWidget.js',
'src/components/widgets/StepTableWidget.js',
'src/components/widgets/ConsumptionBreakdownRows.js',
'src/components/settings/structurePreviewMock.js',
'src/components/settings/CollapsibleSection.js',
'src/components/settings/EditableSlotList.js',
'src/components/settings/ThemeColorPicker.js',
'src/components/settings/BridgeStatusNotice.js',
'src/components/settings/SessionMigrationCard.js',
'src/components/settings/HostI18nCard.js',
'src/views/settings/SettingsGeneralTab.js',
'src/views/settings/SettingsStructureTab.js',
'src/views/settings/SettingsAccountTab.js',
'src/views/settings/SettingsOtherTab.js',
'src/components/layout/TopSessionHeader.js',
'src/views/LiveOverviewView.js',
@@ -648,6 +656,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/views/StepsDetailView.js',
'src/views/SettingsView.js',
'src/App.js',
'src/components/layout/overlayHostAnchors.js',
'src/components/layout/WindowOverlayShell.js',
'src/main.js',
];
@@ -0,0 +1,58 @@
/**
* @fileoverview Zero-dependency shared protocol constants and normalizers
* for the decoupled Antigravity Host I18n subsystem.
*/
export const HOST_I18N_GLOBAL_KEY = '__AGUsageMonitorHostI18n';
export const HOST_I18N_API_PATH = '/api/host-i18n';
export const HOST_I18N_SCHEMA_VERSION = 1;
export const HOST_I18N_OFF_LOCALE = 'off';
export const HOST_I18N_DEFAULT_DEPTH = 'light';
export const HOST_I18N_DEPTHS = Object.freeze(['light', 'deep']);
export const HOST_I18N_LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/;
/**
* Normalizes a host translation locale identifier (`'off'` or canonical BCP-47 tag).
*
* @param {unknown} value
* @returns {string}
*/
export function normalizeHostI18nLocale(value) {
const raw = String(value || '').trim();
if (!raw) return HOST_I18N_OFF_LOCALE;
const lower = raw.toLowerCase();
if (
lower === 'off' ||
lower === 'none' ||
lower === 'disabled' ||
lower === 'original' ||
lower === 'default'
) {
return HOST_I18N_OFF_LOCALE;
}
const normalized = raw.replace(/_/g, '-');
if (!HOST_I18N_LOCALE_RE.test(normalized)) {
return HOST_I18N_OFF_LOCALE;
}
const parts = normalized.split('-');
return parts
.map((part, idx) => {
if (idx === 0) return part.toLowerCase();
if (part.length === 2) return part.toUpperCase();
if (part.length === 4) return part[0].toUpperCase() + part.slice(1).toLowerCase();
return part;
})
.join('-');
}
/**
* Normalizes translation depth (`'light'` or `'deep'`).
*
* @param {unknown} value
* @returns {'light'|'deep'}
*/
export function normalizeHostI18nDepth(value) {
const lower = String(value || '').trim().toLowerCase();
if (lower === 'deep' || lower === 'full') return 'deep';
return HOST_I18N_DEFAULT_DEPTH;
}
@@ -546,6 +546,22 @@ export function normalizeModernUi(val) {
export const CONTEXT_AGENT_MODES = Object.freeze(['main', 'auto']);
export const DEFAULT_CONTEXT_AGENT_MODE = 'main';
export const ACCOUNT_QUOTA_REFRESH_MINUTES = Object.freeze([10, 30, 60, 180, 360, 720, 1440]);
export const DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES = 60;
/**
* 归一化非当前账号的后台配额刷新间隔(分钟,默认 `60` 即 1 小时)。
*
* @param {unknown} raw
* @returns {10|30|60|180|360|720|1440}
*/
export function normalizeAccountQuotaRefreshMinutes(raw) {
const num = Number(raw);
return ACCOUNT_QUOTA_REFRESH_MINUTES.includes(num)
? /** @type {any} */ (num)
: DEFAULT_ACCOUNT_QUOTA_REFRESH_MINUTES;
}
/**
* 归一化顶栏胶囊及悬停速览浮窗的上下文代理来源(默认 `'main'` 锁定主代理,可选 `'auto'` 跟随活跃)。
*
@@ -45,6 +45,8 @@ export const BRIDGE_API_ROUTE_DEFS = Object.freeze([
method: 'GET',
action: 'quota_reservation_log',
}),
Object.freeze({ path: '/api/host-i18n', method: 'GET', action: 'host_i18n_get' }),
Object.freeze({ path: '/api/host-i18n', method: 'POST', action: 'host_i18n_action' }),
]);
export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path));
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,764 @@
/**
* @fileoverview Pure regression math (OLS + IRLS-LOESS), nice axis tick generators,
* SVG spline/polyline path builders, and step metric formatters extracted from SessionStepCharts.js.
*/
import {
formatAgentBadgeText,
formatMetric,
formatPctNumber,
formatSpeedMetric,
formatTokens,
formatTokensPrecise,
formatUsd,
} from '../../core/formatters.js';
import { t } from '../../i18n/index.js';
/** 多模型节点和多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性和交叉曲线区分度) */
export const MODEL_COLOR_VARS = Object.freeze([
'var(--ctx-cached)',
'var(--ctx-skills)',
'var(--ctx-user-input)',
'var(--ctx-checkpoint)',
'var(--ctx-tool-results)',
'var(--ctx-subagent-msg)',
]);
/**
* 提取步骤所属的基础模型分组键(和后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致),
* 且不受“精简代号 / 原始模型 ID”或“自动压缩”后缀切换影响。
*
* @param {object|null|undefined} step
* @returns {string}
*/
export function getStepModelGroupKey(step) {
if (!step || typeof step !== 'object') return t('fmt.unknownModel');
const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '')
.replace(/\s*\[自动压缩\]\s*$/u, '')
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
.trim();
if (rawLabel) return rawLabel;
const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '')
.replace(/·(?:压缩|Compact)\s*$/iu, '')
.trim();
return rawShort || t('fmt.unknownModel');
}
/**
* 将逆序或混合代理的步骤列表归一化为严格时间升序序列(最旧 -> 最新)。
*
* @param {Array<object>} steps
* @param {boolean} isMergedAllAgents
* @returns {Array<object>}
*/
export function toChronologicalSteps(steps, isMergedAllAgents = false) {
if (!Array.isArray(steps) || steps.length === 0) return [];
const copy = steps.slice();
if (isMergedAllAgents) {
copy.sort(
(a, b) =>
(Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) ||
(Number(a?.agentIndex) || 0) - (Number(b?.agentIndex) || 0) ||
(Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0)
);
return copy;
}
copy.sort(
(a, b) =>
(Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) ||
(Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0)
);
return copy;
}
export function clampValue(v, minVal = 0, maxVal = Infinity) {
if (!Number.isFinite(v)) return minVal;
return Math.max(minVal, Math.min(maxVal, v));
}
/**
* 双侧 95% 置信区间对应的 Student-t 临界值近似表(t_{0.975, df})。
*
* @param {number} df 残差自由度
* @returns {number}
*/
function tCritical95(df) {
if (!Number.isFinite(df) || df <= 1.5) return 3.182;
if (df <= 2.5) return 3.182 + (2.5 - df) * 0.9;
if (df <= 3.5) return 2.776 + (3.5 - df) * 0.406;
if (df <= 4.5) return 2.571 + (4.5 - df) * 0.205;
if (df <= 6) return 2.447;
if (df <= 8) return 2.306;
if (df <= 10) return 2.228;
if (df <= 15) return 2.131;
if (df <= 20) return 2.086;
if (df <= 30) return 2.042;
if (df <= 60) return 2.0;
if (df <= 120) return 1.98;
return 1.96;
}
/**
* 计算普通最小二乘线性回归(OLS: y = intercept + slope * x)。
*
* @param {number[]} ys 样本纵坐标序列
* @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [options]
* @returns {{ values: number[], slope: number, intercept: number, mean: number, r: number, r2: number }}
*/
export function computeLinearFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) {
const n = Array.isArray(ys) ? ys.length : 0;
if (n === 0) {
return { values: [], slope: 0, intercept: 0, mean: 0, r: 0, r2: 0 };
}
const xArr =
Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx);
const meanY = ys.reduce((acc, v) => acc + v, 0) / n;
if (n === 1) {
const c = clampValue(ys[0], minVal, maxVal);
return { values: [c], slope: 0, intercept: c, mean: c, r: 0, r2: 0 };
}
const meanX = xArr.reduce((acc, v) => acc + v, 0) / n;
let sxx = 0;
let sxy = 0;
let syy = 0;
for (let i = 0; i < n; i++) {
const dx = xArr[i] - meanX;
const dy = ys[i] - meanY;
sxx += dx * dx;
sxy += dx * dy;
syy += dy * dy;
}
const slope = sxx > 1e-12 ? sxy / sxx : 0;
const intercept = meanY - slope * meanX;
const r =
sxx > 1e-12 && syy > 1e-12 ? clampValue(sxy / Math.sqrt(sxx * syy), -1, 1) : 0;
const values = xArr.map((x) => clampValue(intercept + slope * x, minVal, maxVal));
return { values, slope, intercept, mean: meanY, r, r2: r * r };
}
/**
* 学术论文级回归和 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误,
* 小样本 n <= 5 时自动采用精确 OLS 线性回归和双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。
*
* @param {number[]} xs 严格递增或单调的样本横坐标序列
* @param {number[]} ys 样本纵坐标序列
* @param {{ minVal?: number, maxVal?: number, gridSize?: number, span?: number }} [options]
*/
export function computePublicationFit(
xs,
ys,
{ minVal = 0, maxVal = Infinity, gridSize = 64, span = 0.5 } = {}
) {
const n = Math.min(Array.isArray(xs) ? xs.length : 0, Array.isArray(ys) ? ys.length : 0);
if (n === 0) {
return {
method: 'OLS',
mean: 0,
sd: 0,
slope: 0,
intercept: 0,
r: 0,
r2: 0,
sampleFits: [],
sampleCiLow: [],
sampleCiHigh: [],
sampleCiHalf: [],
grid: [],
};
}
const ols = computeLinearFit(ys, { minVal, maxVal, xs });
let syy = 0;
for (let i = 0; i < n; i++) {
const dy = ys[i] - ols.mean;
syy += dy * dy;
}
const sd = n > 1 ? Math.sqrt(syy / (n - 1)) : 0;
if (n === 1) {
const val = clampValue(ys[0], minVal, maxVal);
return {
method: 'OLS',
mean: val,
sd: 0,
slope: 0,
intercept: val,
r: 0,
r2: 0,
sampleFits: [val],
sampleCiLow: [val],
sampleCiHigh: [val],
sampleCiHalf: [0],
grid: [{ x: xs[0], fit: val, ciLow: val, ciHigh: val }],
};
}
const xMin = xs[0];
const xMax = xs[n - 1];
const xSpan = Math.max(1e-9, xMax - xMin);
const M = Math.max(2, gridSize);
const gridXs = Array.from({ length: M }, (_, k) => xMin + (k / (M - 1)) * xSpan);
// 小样本(n <= 5):采用精确 OLS 线性回归和 Student-t 双曲 95% CI 置信带
if (n <= 5) {
const meanX = xs.reduce((a, b) => a + b, 0) / n;
let sxx = 0;
let sse = 0;
for (let i = 0; i < n; i++) {
const dx = xs[i] - meanX;
sxx += dx * dx;
const resid = ys[i] - (ols.intercept + ols.slope * xs[i]);
sse += resid * resid;
}
const df = n - 2;
const seResid = df >= 1 ? Math.sqrt(sse / df) : 0;
const tCrit = df >= 1 ? tCritical95(df) : 0;
const evalOlsAt = (x0) => {
const rawFit = ols.intercept + ols.slope * x0;
const sePred =
seResid > 0
? seResid * Math.sqrt(1 / n + (sxx > 1e-12 ? ((x0 - meanX) * (x0 - meanX)) / sxx : 0))
: 0;
const half = tCrit * sePred;
return {
fit: clampValue(rawFit, minVal, maxVal),
ciLow: clampValue(rawFit - half, minVal, maxVal),
ciHigh: clampValue(rawFit + half, minVal, maxVal),
half,
};
};
const sampleEval = xs.map(evalOlsAt);
const grid = gridXs.map((gx) => {
const g = evalOlsAt(gx);
return { x: gx, fit: g.fit, ciLow: g.ciLow, ciHigh: g.ciHigh };
});
return {
method: 'OLS',
mean: ols.mean,
sd,
slope: ols.slope,
intercept: ols.intercept,
r: ols.r,
r2: ols.r2,
sampleFits: sampleEval.map((e) => e.fit),
sampleCiLow: sampleEval.map((e) => e.ciLow),
sampleCiHigh: sampleEval.map((e) => e.ciHigh),
sampleCiHalf: sampleEval.map((e) => e.half),
grid,
};
}
// n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带
const q = Math.max(5, Math.min(n, Math.ceil(span * n)));
const wBuf = new Float64Array(n);
const sortedXs = q <= n && xs.slice(0, n).every(
(x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x)
);
function loessBandwidth(x0) {
// 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。
let left = 0;
let right = n - q;
while (left < right) {
const mid = (left + right) >>> 1;
if (x0 - xs[mid] > xs[mid + q] - x0) {
left = mid + 1;
} else {
right = mid;
}
}
return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0));
}
function evalLoessPoint(x0, diagIdx = -1) {
let h;
if (sortedXs) {
h = loessBandwidth(x0);
if (h <= 1e-9) {
h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6);
}
} else {
const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b);
h = sortedDists[q - 1];
if (h <= 1e-9) {
h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6);
}
}
const maxDist = h * 1.0001;
let start = 0;
let end = n;
if (sortedXs) {
// 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。
let right = n;
while (start < right) {
const mid = (start + right) >>> 1;
if (x0 - xs[mid] >= maxDist) start = mid + 1;
else right = mid;
}
let left = start;
while (left < end) {
const mid = (left + end) >>> 1;
if (xs[mid] - x0 < maxDist) left = mid + 1;
else end = mid;
}
}
let sw = 0;
let swx = 0;
for (let j = start; j < end; j++) {
const u = Math.abs(xs[j] - x0) / maxDist;
const base = 1 - u * u * u;
const w = u >= 1 ? 0 : base * base * base;
wBuf[j] = w;
sw += w;
swx += w * xs[j];
}
if (sw <= 1e-12) {
const fallbackVal = ols.intercept + ols.slope * x0;
return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n };
}
const mx = swx / sw;
let sxxW = 0;
for (let j = start; j < end; j++) {
const w = wBuf[j];
if (w <= 0) continue;
const dx = xs[j] - mx;
sxxW += w * dx * dx;
}
const dx0 = x0 - mx;
const useSlope = sxxW > 1e-12;
const inverseWeightSum = 1 / sw;
const slopeScale = useSlope ? dx0 / sxxW : 0;
const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0);
let rawFit = 0;
let leverageNormSq = 0;
let diagHat = 0;
for (let j = start; j < end; j++) {
const w = wBuf[j];
if (w <= 0) continue;
const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0);
rawFit += lj * ys[j];
leverageNormSq += lj * lj;
if (j === diagIdx) diagHat = lj;
}
return { rawFit, leverageNormSq, diagHat, localHatDiag };
}
const rawSampleFits = new Float64Array(n);
const sampleLevSq = new Float64Array(n);
let sse = 0;
let traceL = 0;
let precomputedGridEval = null;
// 大样本(n > 200 且 x 单调有序)采用和 R `stats::loess(surface = "interpolate")` 一致的网格插值加速:
// 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值和杠杆度,避免 O(N²) 阻塞主线程。
if (n > 200 && sortedXs && M >= 2) {
const gridRawFit = new Float64Array(M);
const gridLevSq = new Float64Array(M);
const gridHatDiag = new Float64Array(M);
for (let k = 0; k < M; k++) {
const res = evalLoessPoint(gridXs[k], -1);
gridRawFit[k] = res.rawFit;
gridLevSq[k] = res.leverageNormSq;
gridHatDiag[k] = res.localHatDiag;
}
precomputedGridEval = { gridRawFit, gridLevSq };
const invSpan = (M - 1) / xSpan;
const maxK0 = M - 2;
for (let i = 0; i < n; i++) {
const u = (xs[i] - xMin) * invSpan;
const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u);
const frac = Math.max(0, Math.min(1, u - k0));
const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]);
const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0]));
const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]);
rawSampleFits[i] = rf;
sampleLevSq[i] = ls;
traceL += hd;
const diff = ys[i] - rf;
sse += diff * diff;
}
} else {
for (let i = 0; i < n; i++) {
const res = evalLoessPoint(xs[i], i);
rawSampleFits[i] = res.rawFit;
sampleLevSq[i] = res.leverageNormSq;
traceL += res.diagHat;
const diff = ys[i] - res.rawFit;
sse += diff * diff;
}
}
const dfRes = Math.max(1, n - traceL);
const sigmaHat = Math.sqrt(sse / dfRes);
const tCrit = tCritical95(dfRes);
const sampleFits = new Array(n);
const sampleCiLow = new Array(n);
const sampleCiHigh = new Array(n);
const sampleCiHalf = new Array(n);
let clampedSse = 0;
for (let i = 0; i < n; i++) {
const fitVal = clampValue(rawSampleFits[i], minVal, maxVal);
const half = tCrit * sigmaHat * Math.sqrt(sampleLevSq[i]);
sampleFits[i] = fitVal;
sampleCiLow[i] = clampValue(rawSampleFits[i] - half, minVal, maxVal);
sampleCiHigh[i] = clampValue(rawSampleFits[i] + half, minVal, maxVal);
sampleCiHalf[i] = half;
const d = ys[i] - fitVal;
clampedSse += d * d;
}
const grid = precomputedGridEval
? gridXs.map((gx, k) => {
const rf = precomputedGridEval.gridRawFit[k];
const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k]));
return {
x: gx,
fit: clampValue(rf, minVal, maxVal),
ciLow: clampValue(rf - half, minVal, maxVal),
ciHigh: clampValue(rf + half, minVal, maxVal),
};
})
: gridXs.map((gx) => {
const res = evalLoessPoint(gx, -1);
const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq);
return {
x: gx,
fit: clampValue(res.rawFit, minVal, maxVal),
ciLow: clampValue(res.rawFit - half, minVal, maxVal),
ciHigh: clampValue(res.rawFit + half, minVal, maxVal),
};
});
const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1;
return {
method: 'LOESS',
mean: ols.mean,
sd,
slope: ols.slope,
intercept: ols.intercept,
r: ols.r,
r2: r2Loess,
sampleFits,
sampleCiLow,
sampleCiHigh,
sampleCiHalf,
grid,
};
}
/**
* Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。
*/
export function niceStepNumber(range, round) {
if (!Number.isFinite(range) || range <= 0) return 1;
const exponent = Math.floor(Math.log10(range));
const fraction = range / 10 ** exponent;
let niceFraction;
if (round) {
if (fraction < 1.5) niceFraction = 1;
else if (fraction < 3) niceFraction = 2;
else if (fraction < 7) niceFraction = 5;
else niceFraction = 10;
} else if (fraction <= 1) niceFraction = 1;
else if (fraction <= 2) niceFraction = 2;
else if (fraction <= 5) niceFraction = 5;
else niceFraction = 10;
return niceFraction * 10 ** exponent;
}
export function computeNiceYScale(dataMin, dataMax, { minBound = 0, maxBound = Infinity, tickCount = 4 } = {}) {
let lo = Number.isFinite(dataMin) ? dataMin : 0;
let hi = Number.isFinite(dataMax) ? dataMax : 1;
if (minBound === 0 && lo >= 0 && hi > 0 && lo <= hi * 0.32) {
lo = 0;
}
if (hi - lo <= 1e-9) {
const pad = lo > 0 ? lo * 0.15 : 1;
lo = Math.max(minBound, lo - pad);
hi = Math.min(maxBound, hi + pad);
if (hi - lo <= 1e-9) {
lo = Math.max(minBound, hi - 1);
}
} else {
const pad = (hi - lo) * 0.05;
lo = Math.max(minBound, lo - (lo === 0 ? 0 : pad));
hi = Math.min(maxBound, hi + pad);
}
const rawRange = niceStepNumber(hi - lo, false);
const step = niceStepNumber(rawRange / Math.max(2, tickCount - 1), true);
let graphMin = Math.max(minBound, Math.floor(lo / step) * step);
let graphMax = Math.min(maxBound, Math.ceil(hi / step) * step);
if (graphMax - graphMin <= 1e-9) {
graphMax = graphMin + step;
}
const ticks = [];
for (let v = graphMin; v <= graphMax + step * 0.25; v += step) {
const clamped = clampValue(+v.toPrecision(10), minBound, maxBound);
if (ticks.length === 0 || Math.abs(clamped - ticks[ticks.length - 1]) > step * 1e-4) {
ticks.push(clamped);
}
if (ticks.length >= 8) break;
}
return {
min: ticks[0] ?? graphMin,
max: ticks[ticks.length - 1] ?? graphMax,
step,
ticks,
};
}
export function computeNiceXStepTicks(xs) {
const n = xs.length;
if (n === 0) return [];
if (n <= 5) {
return Array.from(new Set(xs.map((x) => Math.round(x))));
}
const xMin = xs[0];
const xMax = xs[n - 1];
const span = xMax - xMin;
if (span <= 5) {
return Array.from(new Set(xs.map((x) => Math.round(x))));
}
const step = Math.max(1, Math.round(niceStepNumber(span / 4.5, true)));
const firstTick = Math.ceil(xMin / step) * step;
const ticks = [];
if (firstTick - xMin > step * 0.45) {
ticks.push(Math.round(xMin));
}
for (let v = firstTick; v <= xMax + 1e-6; v += step) {
ticks.push(Math.round(v));
if (ticks.length >= 7) break;
}
if (ticks.length === 0) {
return [Math.round(xMin), Math.round(xMax)];
}
return ticks;
}
export function formatYAxisTick(metric, val, step) {
if (!Number.isFinite(val)) return '';
if (Math.abs(val) < 1e-9) {
return metric === 'cost' ? '$0' : metric === 'cache' ? '0%' : metric === 'ttft' ? '0s' : '0';
}
if (metric === 'tps') {
return step >= 1 ? `${Math.round(val)}` : val.toFixed(1);
}
if (metric === 'ttft') {
return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`;
}
if (metric === 'cache') {
return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true });
}
if (metric === 'cost') {
if (step >= 1) return `$${Math.round(val)}`;
if (step >= 0.1) return `$${val.toFixed(1)}`;
if (step >= 0.01) return `$${val.toFixed(2)}`;
return `$${val.toFixed(3)}`;
}
return String(val);
}
export function buildPolylinePath(points) {
if (!points.length) return '';
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
for (let i = 1; i < points.length; i++) {
d += ` L ${points[i].x.toFixed(1)} ${points[i].y.toFixed(1)}`;
}
return d;
}
export function buildSplinePath(points) {
if (!points.length) return '';
if (points.length === 1) {
return `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
}
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];
const cpx1 = p0.x + (p1.x - p0.x) * 0.38;
const cpx2 = p1.x - (p1.x - p0.x) * 0.38;
d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
}
return d;
}
export function computeStepTickIndices(count) {
if (count <= 0) return [];
if (count <= 6) return Array.from({ length: count }, (_, i) => i);
const maxTicks = 6;
const set = new Set();
for (let k = 0; k < maxTicks; k++) {
set.add(Math.round((k / (maxTicks - 1)) * (count - 1)));
}
return Array.from(set).sort((a, b) => a - b);
}
export function formatStepAxisTag(st, showAgentPrefix) {
const num = `#${Number(st?.stepIndex ?? 0)}`;
if (!showAgentPrefix) return num;
const badge = formatAgentBadgeText({
agentKind:
st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'),
agentOrdinal:
st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0),
isMain: !st?.isSubagent,
isSideQuestion: Boolean(st?.isSideQuestion),
sideIndex: st?.sideIndex || 0,
index: st?.agentIndex || 0,
badgeText: st?.agentBadge,
});
return `${badge}${num}`;
}
export function formatChartMetricValue(metric, val) {
if (!Number.isFinite(val)) return '—';
switch (metric) {
case 'totalTokens':
case 'context':
return `${formatTokensPrecise(val)} tok`;
case 'tps':
return formatSpeedMetric(val, ' tok/s');
case 'ttft':
return formatMetric(val, 's');
case 'cache':
return formatPctNumber(val, { withSymbol: true });
case 'cost':
return formatUsd(val, { precise: true });
default:
return String(val);
}
}
export function formatChartMetricCompact(metric, val) {
if (!Number.isFinite(val)) return '—';
switch (metric) {
case 'totalTokens':
case 'context':
return formatTokens(val);
case 'tps':
return formatSpeedMetric(val, ' tok/s');
case 'ttft':
return formatMetric(val, 's');
case 'cache':
return formatPctNumber(val, { withSymbol: true });
case 'cost':
return formatUsd(val, { precise: true });
default:
return String(val);
}
}
/**
* Downsamples dense chronological step series (`> maxPoints`, e.g. 1,500–5,000 steps) to an
* adaptive visual vertex budget (`~2.1px` per segment) so cubic splines never overplot into an
* opaque solid wall while strictly preserving the start step, end step, and exact global peak step.
*
* @template {{ value?: number }} T
* @param {T[]} points
* @param {number} [maxPoints=208]
* @returns {T[]}
*/
export function downsampleStepPointsForPlot(points, maxPoints = 208) {
if (!Array.isArray(points) || points.length <= maxPoints || maxPoints < 8) {
return points;
}
const n = points.length;
let globalPeakIdx = -1;
let globalPeakVal = -Infinity;
for (let i = 0; i < n; i += 1) {
const v = Number(points[i]?.value);
if (Number.isFinite(v) && v >= globalPeakVal) {
globalPeakVal = v;
globalPeakIdx = i;
}
}
const out = [points[0]];
const bucketCount = maxPoints - 2;
const interiorLen = n - 2;
for (let b = 0; b < bucketCount; b += 1) {
const bStart = 1 + Math.floor((b * interiorLen) / bucketCount);
const bEnd = Math.max(bStart + 1, 1 + Math.floor(((b + 1) * interiorLen) / bucketCount));
let pickIdx = -1;
if (globalPeakIdx >= bStart && globalPeakIdx < bEnd) {
pickIdx = globalPeakIdx;
} else {
for (let k = bStart; k < bEnd; k += 1) {
if (points[k]?.anomalySummary) {
if (pickIdx < 0 || points[k]?.anomalySeverity === 'danger') {
pickIdx = k;
if (points[k]?.anomalySeverity === 'danger') break;
}
}
}
if (pickIdx < 0) {
pickIdx = bStart + Math.floor((bEnd - bStart) / 2);
}
}
const picked = points[pickIdx];
if (picked && picked !== out[out.length - 1]) {
out.push(picked);
}
}
const lastPt = points[n - 1];
if (lastPt && lastPt !== out[out.length - 1]) {
out.push(lastPt);
}
return out;
}
/**
* Evaluates the exact `y` coordinate on `buildSplinePath(plotPoints)` at horizontal coordinate `targetX`
* so overlay markers (such as anomaly dots) sit flush on the rendered curve even between downsampled knots.
*
* @param {Array<{ x: number, y: number }>} plotPoints
* @param {number} targetX
* @returns {number}
*/
export function evalStepSplineYAtX(plotPoints, targetX) {
if (!Array.isArray(plotPoints) || plotPoints.length === 0) return 0;
if (plotPoints.length === 1 || targetX <= plotPoints[0].x) return plotPoints[0].y;
const last = plotPoints[plotPoints.length - 1];
if (targetX >= last.x) return last.y;
let loIdx = 0;
let hiIdx = plotPoints.length - 1;
while (loIdx + 1 < hiIdx) {
const mid = (loIdx + hiIdx) >>> 1;
if (plotPoints[mid].x <= targetX) loIdx = mid;
else hiIdx = mid;
}
const p0 = plotPoints[loIdx];
const p1 = plotPoints[hiIdx];
const dx = p1.x - p0.x;
if (!(dx > 1e-6)) return p0.y;
const uTarget = Math.max(0, Math.min(1, (targetX - p0.x) / dx));
let sLo = 0;
let sHi = 1;
for (let it = 0; it < 14; it += 1) {
const s = (sLo + sHi) * 0.5;
const inv = 1 - s;
const u = 3 * inv * inv * s * 0.38 + 3 * inv * s * s * 0.62 + s * s * s;
if (u < uTarget) sLo = s;
else sHi = s;
}
const s = (sLo + sHi) * 0.5;
return p0.y + (p1.y - p0.y) * s * s * (3 - 2 * s);
}
@@ -22,18 +22,49 @@ import {
import { uiStore } from '../../store/uiStore.js';
import { CustomSelect } from '../ui/CustomSelect.js';
function formatConvOptionMeta(c) {
const base = formatConversationMeta(c);
const wsName = String(c?.workspaceName || '').trim();
if (!wsName) return base;
return base ? `${wsName} · ${base}` : wsName;
const INLINE_UUID_RE =
/(?<![0-9a-f-])([0-9a-f]{8})-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![0-9a-f-])/gi;
function compactInlineUuids(text) {
const str = String(text || '').trim();
if (!str || str.length < 36) return str;
return str.replace(INLINE_UUID_RE, '$1…');
}
function formatCompactConvStepsMeta(c) {
if (!c) return '';
const main = Number(c.stepCount || 0);
const totalSubs = Number(c.subagentCount || 0);
const swarm = Number(c.swarmCount || 0);
const otherSubs = Math.max(0, totalSubs - swarm);
const total = Number(c.totalStepCount ?? c.totalStepsAllAgents ?? main);
if (swarm > 0 && otherSubs > 0) {
return t('header.convCompactSwarmAndSubs', { swarm, subs: otherSubs, total });
}
if (swarm > 0) {
return t('header.convCompactSwarm', { swarm, total });
}
if (totalSubs > 0) {
return t('header.convCompactSubs', { subs: totalSubs, total });
}
return t('header.convMetaSteps', { count: main });
}
function resolveConvTotalSteps(c) {
if (!c) return 0;
const main = Number(c.stepCount || 0);
return Number(c.totalStepCount ?? c.totalStepsAllAgents ?? main);
}
function formatConvOptionTitle(c) {
const parts = [];
const label = String(c?.title || c?.cascadeId?.slice?.(0, 8) || '').trim();
if (c?.swarmTitle && c.swarmTitle !== c.title) {
parts.push(`${label} · ${c.swarmTitle}`);
if (label) {
parts.push(c?.swarmTitle && c.swarmTitle !== c.title ? `${label} · ${c.swarmTitle}` : label);
}
const fullMeta = formatConversationMeta(c);
if (fullMeta) {
parts.push(fullMeta);
}
const wsPath = String(c?.workspacePath || c?.workspaceName || '').trim();
if (wsPath) {
@@ -46,6 +77,7 @@ export const TopSessionHeader = defineComponent({
name: 'TopSessionHeader',
setup({ onCleanup }) {
const convSelect = CustomSelect({
className: 'session-select',
modelValue: telemetryStore.getState().selectedConversationId,
placeholder: t('header.followLatest'),
searchable: true,
@@ -220,53 +252,63 @@ export const TopSessionHeader = defineComponent({
routeMatch?.isChildRoute && routeMatch.childAgent
? formatAgentBadgeText(routeMatch.childAgent)
: '';
const hostBaseTitle = hostMatchedConv?.title || hostRouteId.slice(0, 8);
const hostBaseTitle = compactInlineUuids(
hostMatchedConv?.title || hostRouteId.slice(0, 8)
);
const hostDisplayTitle = childRouteBadge
? `${hostBaseTitle} · ${childRouteBadge}`
: hostBaseTitle;
const defaultOptLabel = hostRouteId
const defaultTriggerLabel = hostRouteId
? t('header.currentWindowNamed', {
title: hostDisplayTitle,
})
: convs[0]?.title
? t('header.latestNamed', { title: convs[0].title })
? t('header.latestNamed', { title: compactInlineUuids(convs[0].title) })
: t('header.followLatest');
const defaultOptMeta = hostRouteId
? hostMatchedConv
? formatConvOptionMeta(hostMatchedConv)
: ''
: convs[0]
? formatConvOptionMeta(convs[0])
: '';
const lockedId = telSt.selectedConversationId;
const defaultMenuLabel = hostRouteId
? t('header.followCurrentWindow')
: t('header.followLatest');
const options = [
{
value: '',
label: defaultOptLabel,
meta: defaultOptMeta,
label: defaultMenuLabel,
shortLabel: defaultTriggerLabel,
meta: t('header.autoFollowBadge'),
dividerAfter: convs.length > 0 || Boolean(lockedId),
...(hostMatchedConv?.swarmTitle ? { title: hostMatchedConv.swarmTitle } : {}),
},
...convs.map((c) => {
const rawTitle = c.title || c.cascadeId.slice(0, 8);
const cleanLabel = compactInlineUuids(rawTitle);
const wsName = String(c?.workspaceName || '').trim();
const optTitle = formatConvOptionTitle(c);
return {
value: c.cascadeId,
label: c.title || c.cascadeId.slice(0, 8),
meta: formatConvOptionMeta(c),
label: cleanLabel,
meta: formatCompactConvStepsMeta(c),
dimMeta: resolveConvTotalSteps(c) === 0,
searchText: `${rawTitle} ${wsName} ${c.workspacePath || ''} ${c.swarmTitle || ''}`,
...(optTitle ? { title: optTitle } : {}),
};
}),
];
const lockedId = telSt.selectedConversationId;
if (lockedId && !convs.some((c) => c.cascadeId === lockedId)) {
const isLoadedLocked = actConv?.cascadeId === lockedId;
const lockedTitle =
const rawLockedTitle =
isLoadedLocked && actConv?.title
? actConv.title
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
const lockedMeta = isLoadedLocked ? formatConvOptionMeta(actConv) : t('header.lockedMeta');
const lockedLabel = compactInlineUuids(rawLockedTitle);
const lockedWs = isLoadedLocked ? String(actConv?.workspaceName || '').trim() : '';
const lockedMeta = isLoadedLocked ? formatCompactConvStepsMeta(actConv) : t('header.lockedMeta');
options.splice(1, 0, {
value: lockedId,
label: lockedTitle,
label: lockedLabel,
meta: lockedMeta,
searchText: `${rawLockedTitle} ${lockedWs}`,
});
}
convSelect.setProps({
@@ -66,916 +66,25 @@ import {
} from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js';
const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule';
const PORTAL_HOST_ID = 'ag-usage-monitor-portal';
import {
CAPSULE_HOST_ID,
PORTAL_HOST_ID,
attachShadowStyles,
computeCapsuleLayoutMode,
findNativeTopRightAnchor,
getLeftSidebarRightEdge,
isIdeExtensionChatFrame,
isImmediatelyBeforeNode,
resolveActiveDockTarget,
} from './overlayHostAnchors.js';
export { computeCapsuleLayoutMode };
const FLOATING_CARD_WIDTH = 522;
const POPOVER_BASE_WIDTH = 540;
const POPOVER_MAX_AUTO_WIDTH = 960;
const MULTI_PANEL_WIDTH = 464;
/**
* 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。
* 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊;
* 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。
*
* @param {number} availWidth
* @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode
* @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options]
* @returns {'wide'|'compact'|'minimal'|'ring-only'}
*/
export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) {
if (availWidth == null || Number.isNaN(availWidth)) return 'wide';
const showMulti = options?.showMulti !== false;
const updateReserve = options?.hasUpdate ? 52 : 0;
const slotCount = Number(options?.slotCount || 3);
const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0;
const wideKeep = 256 + extraSlotWidth;
const wideEnter = 272 + extraSlotWidth;
const baseEffWidth = showMulti ? availWidth : availWidth + 76;
const effWidth = baseEffWidth - updateReserve;
if (currentMode === 'wide') {
if (baseEffWidth < 78) return 'ring-only';
if (effWidth < 196) return 'minimal';
if (effWidth < wideKeep) return 'compact';
return 'wide';
}
if (currentMode === 'compact') {
if (effWidth >= wideEnter) return 'wide';
if (baseEffWidth < 78) return 'ring-only';
if (effWidth < 196) return 'minimal';
return 'compact';
}
if (currentMode === 'minimal') {
if (effWidth >= wideEnter) return 'wide';
if (effWidth >= 212) return 'compact';
if (baseEffWidth < 78) return 'ring-only';
return 'minimal';
}
if (effWidth >= wideEnter) return 'wide';
if (effWidth >= 212) return 'compact';
if (baseEffWidth >= 92) return 'minimal';
return 'ring-only';
}
function findIdeWorkbenchTitlebar() {
try {
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
return null;
}
const workbench = document.querySelector('.monaco-workbench');
if (!workbench?.querySelector) return null;
const partTitlebar = workbench.querySelector('.part.titlebar');
if (!partTitlebar?.querySelector) return null;
if (partTitlebar.getBoundingClientRect) {
const pr = partTitlebar.getBoundingClientRect();
if (pr.width <= 0 || pr.height <= 0) return null;
}
const container =
partTitlebar.querySelector(':scope > .titlebar-container') ||
partTitlebar.querySelector('.titlebar-container');
const rightGroup =
container?.querySelector?.(':scope > .titlebar-right') ||
container?.querySelector?.('.titlebar-right');
if (!container || !rightGroup) return null;
const actionToolbar =
rightGroup.querySelector?.(':scope > .action-toolbar-container') ||
rightGroup.querySelector?.('.action-toolbar-container') ||
null;
return {
kind: 'ide-titlebar',
workbench,
titlebar: container,
targetContainer: rightGroup,
actionToolbar,
};
} catch {
return null;
}
}
function findHostTitlebar() {
try {
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
return null;
}
const tb = document.querySelector('[class*="@container/titlebar"]');
if (tb?.getBoundingClientRect) {
const r = tb.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) return null;
}
return tb;
} catch {
return null;
}
}
const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR =
'.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]';
const COMPOSER_MODEL_LABEL_RE =
/\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i;
const COMPOSER_MODEL_ATTR_RE =
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
const COMPOSER_MODE_TEXT_RE =
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i;
const COMPOSER_MODE_ATTR_RE =
/\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i;
const COMPOSER_ICON_FONT_CLASS_RE =
/\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i;
function querySimpleSelectorList(root, selectors) {
if (!root || typeof root.querySelectorAll !== 'function') return [];
const seen = new Set();
const out = [];
for (const sel of selectors) {
let list = [];
try {
list = root.querySelectorAll(sel) || [];
} catch {
list = [];
}
for (const item of list) {
if (item && !seen.has(item)) {
seen.add(item);
out.push(item);
}
}
}
return out;
}
function extractVisibleButtonText(node, isRoot = true) {
if (!node) return '';
const tag = String(node.tagName || node.nodeName || '').toLowerCase();
if (tag === 'svg' || tag === 'style' || tag === 'script') return '';
if (!isRoot) {
if (node.getAttribute?.('aria-hidden') === 'true') return '';
const cls = String(node.className || '');
if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return '';
}
if (tag === '#text' || node.nodeType === 3) {
return String(node.nodeValue ?? node.textContent ?? '');
}
const childNodes = node.childNodes || node.children;
if (!childNodes || childNodes.length === 0) {
return String(node.textContent || '');
}
let acc = '';
for (const ch of childNodes) {
acc += ` ${extractVisibleButtonText(ch, false)}`;
}
return acc;
}
function cleanComposerButtonText(btn) {
const raw = extractVisibleButtonText(btn, true)
.replace(/[\u200B-\u200D\uFEFF]/g, '')
.replace(/\s+/g, ' ')
.trim();
if (!raw) return '';
return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim();
}
function isComposerModelButtonItem(item) {
if (!item) return false;
if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true;
if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true;
return false;
}
function hasExcludedComposerAncestor(el) {
if (!el) return false;
if (typeof el.closest === 'function') {
try {
if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true;
} catch {
// 忽略选择器异常并回退祖先链遍历
}
}
let cur = el.parentElement || el.parentNode;
while (cur) {
const cls = String(cur.className || '');
if (
cls.includes('@container/titlebar') ||
cls.includes('quick-input-widget') ||
cls.includes('suggest-widget') ||
cls.includes('find-widget') ||
cls.includes('scm-editor') ||
cls.includes('search-view') ||
(cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar')))
) {
return true;
}
cur = cur.parentElement || cur.parentNode;
}
return false;
}
function isNodeHiddenByStyle(el) {
if (!el) return true;
if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const cs = window.getComputedStyle(el);
if (cs?.display === 'none' || cs?.visibility === 'hidden') return true;
} catch {
// 忽略样式读取异常
}
}
return false;
}
function getInFlowHostChildren(container, capsuleNode, portalNode) {
const rawChildren = container?.children || [];
const out = [];
for (const ch of rawChildren) {
if (!ch || ch === capsuleNode || ch === portalNode) continue;
if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue;
if (ch.hasAttribute?.('hidden')) continue;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const cs = window.getComputedStyle(ch);
if (cs?.display === 'none') continue;
if (cs?.position === 'absolute' || cs?.position === 'fixed') continue;
} catch {
// 忽略计算样式异常
}
}
out.push(ch);
}
return out;
}
function isHorizontalFlexContainer(el) {
if (!el) return false;
const cls = String(el.className || '');
if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const cs = window.getComputedStyle(el);
const disp = String(cs?.display || '');
const dir = String(cs?.flexDirection || 'row');
if (disp.includes('flex') && !dir.startsWith('column')) return true;
} catch {
// 忽略计算样式异常
}
}
return false;
}
function isSpaceDistributedFlexContainer(el) {
if (!el) return false;
const cls = String(el.className || '');
if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const jc = String(window.getComputedStyle(el)?.justifyContent || '');
if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) {
return true;
}
} catch {
// 忽略计算样式异常
}
}
return false;
}
function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) {
if (!autoBtn || !composerCard) return null;
let item = autoBtn;
while (
(item.parentElement || item.parentNode) &&
(item.parentElement || item.parentNode) !== composerCard &&
(item.parentElement || item.parentNode) !== document.body
) {
const parent = item.parentElement || item.parentNode;
const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode);
if (hostSiblings.length >= 2) break;
const grandParent = parent.parentElement || parent.parentNode;
const parentCls = String(parent.className || '');
const parentInlineMl = String(parent.style?.marginLeft || '').trim();
const isSingleClusterInSplitRow =
!/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) &&
parentInlineMl !== 'auto' &&
isHorizontalFlexContainer(parent) &&
grandParent &&
isSpaceDistributedFlexContainer(grandParent) &&
getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2;
if (isSingleClusterInSplitRow) {
break;
}
item = parent;
}
const anchorNode = item;
const targetContainer = anchorNode.parentElement || anchorNode.parentNode;
if (!targetContainer) return null;
const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode);
const anchorIdx = hostChildren.indexOf(anchorNode);
const isFirstHostChild = anchorIdx <= 0;
let needsAutoMarginTransfer = false;
let patchMarginNode = null;
if (!isFirstHostChild) {
const cls = String(anchorNode.className || '');
const inlineMl = String(anchorNode.style?.marginLeft || '').trim();
let computedLargeMl = false;
if (
patchedNode !== anchorNode &&
typeof window !== 'undefined' &&
typeof window.getComputedStyle === 'function'
) {
try {
const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0;
const prevSib = hostChildren[anchorIdx - 1];
const aRect = anchorNode.getBoundingClientRect?.();
const pRect = prevSib?.getBoundingClientRect?.();
if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) {
computedLargeMl = true;
}
} catch {
// 忽略边距测量异常
}
}
if (
/\b(?:ml-auto|ms-auto)\b/.test(cls) ||
inlineMl === 'auto' ||
patchedNode === anchorNode ||
computedLargeMl
) {
needsAutoMarginTransfer = true;
patchMarginNode = anchorNode;
} else if (isSpaceDistributedFlexContainer(targetContainer)) {
needsAutoMarginTransfer = true;
}
}
const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.();
let leftClusterRightEdge = 0;
if (autoRect && Array.isArray(bottomRowBtns)) {
for (const entry of bottomRowBtns) {
if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue;
if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) {
if (entry.rect.right > leftClusterRightEdge) {
leftClusterRightEdge = entry.rect.right;
}
}
}
}
return {
kind: 'composer',
workbench: null,
titlebar: composerCard,
targetContainer,
actionToolbar: patchMarginNode,
anchorNode,
needsAutoMarginTransfer,
leftClusterRightEdge,
};
}
function buildComposerRightEndDockDescriptor(
leftAnchorBtn,
composerCard,
bottomRowBtns,
capsuleNode,
portalNode
) {
if (!leftAnchorBtn || !composerCard) return null;
const cardRect = composerCard.getBoundingClientRect?.();
const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180;
let toolbarRow = null;
let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) {
const r = cur.getBoundingClientRect?.();
if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) {
toolbarRow = cur;
break;
}
cur = cur.parentElement || cur.parentNode;
}
if (!toolbarRow) {
const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
if (!p || !isHorizontalFlexContainer(p)) return null;
toolbarRow = p;
}
let leftClusterRightEdge = 0;
if (Array.isArray(bottomRowBtns)) {
for (const entry of bottomRowBtns) {
if (entry?.rect?.right > leftClusterRightEdge) {
leftClusterRightEdge = entry.rect.right;
}
}
}
const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode);
const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null;
if (
lastChild &&
!lastChild.contains?.(leftAnchorBtn) &&
isHorizontalFlexContainer(lastChild) &&
getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0
) {
return {
kind: 'composer',
workbench: null,
titlebar: composerCard,
targetContainer: lastChild,
actionToolbar: null,
anchorNode: null,
needsAutoMarginTransfer: false,
leftClusterRightEdge,
};
}
return {
kind: 'composer',
workbench: null,
titlebar: composerCard,
targetContainer: toolbarRow,
actionToolbar: null,
anchorNode: null,
needsAutoMarginTransfer: true,
leftClusterRightEdge,
};
}
function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) {
const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']);
const hostBtns = [];
for (const btn of rawBtns) {
if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue;
if (editorEl && btn.contains?.(editorEl)) continue;
if (
btn.id === CAPSULE_HOST_ID ||
btn.id === PORTAL_HOST_ID ||
capsuleNode?.contains?.(btn) ||
portalNode?.contains?.(btn)
) {
continue;
}
if (isNodeHiddenByStyle(btn)) continue;
// 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮
let nestedInBtn = false;
let p = btn.parentElement || btn.parentNode;
while (p && p !== container) {
const pTag = String(p.tagName || '').toLowerCase();
if (pTag === 'button') {
nestedInBtn = true;
break;
}
if (
(p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) &&
!(editorEl && p.contains?.(editorEl))
) {
const pr = p.getBoundingClientRect?.();
if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) {
nestedInBtn = true;
break;
}
}
p = p.parentElement || p.parentNode;
}
if (nestedInBtn) continue;
const br = btn.getBoundingClientRect?.();
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue;
const centerY = (br.top + br.bottom) / 2;
if (editorRect && centerY < editorRect.top - 4) continue;
hostBtns.push({
btn,
rect: br,
centerY,
centerX: (br.left + br.right) / 2,
cleanText: cleanComposerButtonText(btn),
attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(),
});
}
if (hostBtns.length === 0) return [];
let maxCenterY = -Infinity;
for (const item of hostBtns) {
if (item.centerY > maxCenterY) maxCenterY = item.centerY;
}
const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22);
bottomBand.sort((a, b) => a.rect.left - b.rect.left);
return bottomBand;
}
function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) {
if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null;
const requireModelForFallback = Boolean(options?.requireModelForFallback);
const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0;
const rightFirst = [
...bottomRowBtns.filter((b) => b.centerX >= rightSplitX),
...bottomRowBtns.filter((b) => b.centerX < rightSplitX),
];
// Tier 1: 精确文本 Auto / 自动 匹配
for (const item of rightFirst) {
if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) {
return { btn: item.btn, tier: 1 };
}
}
// Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮)
for (const item of rightFirst) {
if (isComposerModelButtonItem(item)) continue;
if (
(item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) ||
(item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText))
) {
return { btn: item.btn, tier: 2 };
}
}
const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem);
// Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局)
if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) {
let maxGap = -Infinity;
let splitIdx = -1;
for (let i = 1; i < bottomRowBtns.length; i += 1) {
const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right;
if (gap > maxGap) {
maxGap = gap;
splitIdx = i;
}
}
if (splitIdx >= 1 && maxGap >= 16) {
return { btn: bottomRowBtns[splitIdx].btn, tier: 3 };
}
}
// Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧
if (hasModelBtn && containerRect && containerRect.width >= 200) {
const lastItem = bottomRowBtns[bottomRowBtns.length - 1];
if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) {
return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 };
}
}
return null;
}
function resolveComposerEditorRect(ed) {
const er = ed?.getBoundingClientRect?.();
if (er && er.width >= 80 && er.height >= 12) return er;
let cur = ed;
for (let d = 0; d < 6 && cur; d += 1) {
if (String(cur.className || '').includes('monaco-editor')) {
const mr = cur.getBoundingClientRect?.();
if (mr && mr.width >= 80 && mr.height >= 12) return mr;
break;
}
cur = cur.parentElement || cur.parentNode;
}
return er || null;
}
function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) {
try {
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
return null;
}
const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null;
const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null;
const activeRouteId = extractHostRouteCascadeId();
// 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏与 Auto / 右簇发送按钮
const rawEditors = querySimpleSelectorList(document, [
'textarea',
'[contenteditable]',
'[role="textbox"]',
'[data-lexical-editor]',
'.ProseMirror',
'.monaco-editor',
]);
const scoredEditors = [];
for (const ed of rawEditors) {
if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue;
if (ed.hasAttribute?.('contenteditable')) {
const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase();
if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue;
}
if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue;
const er = resolveComposerEditorRect(ed);
if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue;
let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2;
if (activeRouteId) {
let anc = ed.parentElement || ed.parentNode;
while (anc) {
const cid = anc.getAttribute?.('data-cascade-id');
if (cid) {
score += cid === activeRouteId ? 4000 : -2000;
break;
}
anc = anc.parentElement || anc.parentNode;
}
}
if (
document.activeElement &&
(ed === document.activeElement || ed.contains?.(document.activeElement))
) {
score += 1000;
}
scoredEditors.push({ ed, rect: er, score });
}
scoredEditors.sort((a, b) => b.score - a.score);
for (const { ed, rect: er } of scoredEditors) {
const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') ||
String(ed.className || '').includes('inputarea');
let tier3Candidate = null;
let tier4Candidate = null;
let cur = ed.parentElement || ed.parentNode;
for (let depth = 0; depth < 18 && cur; depth += 1) {
if (cur === document.body || cur === document.documentElement) break;
const tag = String(cur.tagName || '').toLowerCase();
if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break;
const cr = cur.getBoundingClientRect?.();
if (cr && cr.height > 680) break;
if (cr && cr.width >= 180 && cr.height > 0) {
const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl);
const picked = pickAutoButtonFromRow(bottomRowBtns, cr, {
requireModelForFallback: isMonacoCandidate,
});
if (picked) {
if (picked.tier <= 2) {
const desc = buildComposerDockDescriptor(
picked.btn,
cur,
bottomRowBtns,
capEl,
porEl,
patchedNode
);
if (desc) return desc;
} else if (picked.tier === 3 && !tier3Candidate) {
tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns };
} else if (picked.tier === 4 && !tier4Candidate) {
tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns };
}
}
}
cur = cur.parentElement || cur.parentNode;
}
if (tier3Candidate) {
const desc = buildComposerDockDescriptor(
tier3Candidate.btn,
tier3Candidate.card,
tier3Candidate.bottomRowBtns,
capEl,
porEl,
patchedNode
);
if (desc) return desc;
}
if (tier4Candidate) {
const desc = buildComposerRightEndDockDescriptor(
tier4Candidate.leftAnchorBtn,
tier4Candidate.card,
tier4Candidate.bottomRowBtns,
capEl,
porEl
);
if (desc) return desc;
}
}
// 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏
const vh = Number(window.innerHeight || 800);
const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']);
let modelToolbarFallback = null;
for (const btn of allBtns) {
if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue;
if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue;
const br = btn.getBoundingClientRect?.();
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue;
const clean = cleanComposerButtonText(btn);
const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim();
const itemProbe = { cleanText: clean, attrText: attr };
const isModeBtn =
COMPOSER_MODE_EXACT_RE.test(clean) ||
(!isComposerModelButtonItem(itemProbe) &&
((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr))));
const isModelBtn = isComposerModelButtonItem(itemProbe);
if (!isModeBtn && !isModelBtn) continue;
let cur = btn.parentElement || btn.parentNode;
for (let depth = 0; depth < 12 && cur; depth += 1) {
if (cur === document.body || cur === document.documentElement) break;
if (String(cur.className || '').includes('monaco-workbench')) break;
const cr = cur.getBoundingClientRect?.();
if (!cr || cr.height > 560) break;
if (cr.width >= 200) {
const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl);
if (isModeBtn) {
const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b));
if (hasModelSibling) {
const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode);
if (desc) return desc;
}
} else if (isModelBtn && !modelToolbarFallback) {
const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true });
if (picked) {
const desc =
picked.tier <= 3 && picked.btn
? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode)
: picked.tier === 4 && picked.leftAnchorBtn
? buildComposerRightEndDockDescriptor(
picked.leftAnchorBtn,
cur,
rowBtns,
capEl,
porEl
)
: null;
if (desc) {
if (picked.tier <= 2) return desc;
modelToolbarFallback = desc;
break;
}
}
}
}
cur = cur.parentElement || cur.parentNode;
}
}
if (modelToolbarFallback) return modelToolbarFallback;
} catch {
// 忽略输入框探测异常
}
return null;
}
function isImmediatelyBeforeNode(node, refNode) {
if (!node || !refNode) return false;
if (node.nextElementSibling !== undefined) {
return node.nextElementSibling === refNode;
}
if (node.nextSibling !== undefined) {
return node.nextSibling === refNode;
}
const parent = node.parentElement || node.parentNode;
if (!parent?.children) return false;
const idx = Array.prototype.indexOf.call(parent.children, node);
return idx >= 0 && parent.children[idx + 1] === refNode;
}
function isIdeExtensionChatFrame() {
try {
if (typeof window === 'undefined') return false;
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
} catch {
return false;
}
}
function resolveActiveDockTarget(options = undefined) {
const settings = telemetryStore.getState().telemetry?.settings;
const rawMode =
settings?.windowMountMode ??
readInjectedWindowBridge()?.mountMode;
const mountMode =
options?.mountMode ||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
if (isIdeExtensionChatFrame()) {
if (mountMode !== 'composer') return null;
return findHostComposerAutoTarget(
options?.capsuleNode || null,
options?.portalNode || null,
options?.patchedNode || null
);
}
if (mountMode === 'composer') {
const composerTarget = findHostComposerAutoTarget(
options?.capsuleNode || null,
options?.portalNode || null,
options?.patchedNode || null
);
if (composerTarget) return composerTarget;
}
const ideTarget = findIdeWorkbenchTitlebar();
if (ideTarget) return ideTarget;
const titlebar = findHostTitlebar();
if (!titlebar) return null;
let targetContainer = titlebar;
try {
const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild;
if (rightGroup && rightGroup !== titlebar.firstElementChild) {
targetContainer = rightGroup;
}
} catch {
// 忽略子选择器不兼容场景
}
return {
kind: 'flow',
workbench: null,
titlebar,
targetContainer,
actionToolbar: null,
};
}
function findNativeTopRightAnchor() {
try {
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
return null;
}
const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]');
if (auxToggle?.closest) {
return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle;
}
const candidates = document.querySelectorAll('button, a, [role="button"]');
for (const btn of candidates) {
const text = String(btn.textContent || '').trim();
if (
(text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) &&
btn.getBoundingClientRect?.().top < 52
) {
return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn;
}
}
return document.querySelector('div.absolute.right-0.top-0');
} catch {
return null;
}
}
function getLeftSidebarRightEdge(vw) {
try {
if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
if (document.querySelector('.monaco-workbench')) {
return 0;
}
const navEl = document.querySelector('div[role="navigation"]');
if (navEl?.getBoundingClientRect) {
const nr = navEl.getBoundingClientRect();
if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) {
return Math.ceil(nr.right);
}
}
}
} catch {
// 忽略侧栏测量异常
}
return 0;
}
/**
* 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。
*/
const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([
'src/styles/views-overview.css',
'src/styles/views-consumption.css',
'src/styles/views-tables.css',
'src/styles/views-settings.css',
'src/styles/controls.css',
]);
let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null };
function buildSlimCapsuleCss(fullCss) {
if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss;
return fullCss
.split(/(?=\/\* --- src\/styles\/)/)
.filter((block) => {
const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//);
return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]);
})
.join('');
}
function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) {
if (!shadowRoot) return;
if (
fullCss &&
typeof CSSStyleSheet === 'function' &&
Array.isArray(shadowRoot.adoptedStyleSheets)
) {
try {
if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(fullCss);
sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet };
}
shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet];
return;
} catch {
// 降级到传统 <style> 节点
}
}
const styleEl = document.createElement('style');
styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss;
shadowRoot.appendChild(styleEl);
}
export function mountWindowOverlay() {
if (typeof window === 'undefined' || typeof document === 'undefined') return null;
@@ -1556,6 +665,55 @@ export function mountWindowOverlay() {
let observedWorkbench = null;
let themeObserver = null;
const mirroredThemeVars = new Map();
const mirroredTypographyVars = new Map();
function isUsableHostFontStack(raw) {
const val = String(raw || '').trim();
if (!val) return false;
const bare = val.replace(/["']/g, '').trim();
return !/^(?:initial|inherit|unset|revert|serif|sans-serif|monospace|times new roman|arial)$/i.test(
bare
);
}
function syncHostTypographyVars(rootCs, bodyCs, wbCs) {
const readProp = (cs, prop, fallbackKey = '') => {
if (!cs) return '';
const v = String(cs.getPropertyValue?.(prop) || (fallbackKey ? cs[fallbackKey] : '') || '').trim();
return isUsableHostFontStack(v) ? v : '';
};
const hostFontSans =
readProp(rootCs, '--font-sans') ||
readProp(bodyCs, '--font-sans') ||
readProp(wbCs, '--vscode-font-family') ||
readProp(bodyCs, 'font-family', 'fontFamily') ||
readProp(rootCs, 'font-family', 'fontFamily');
const hostFontMono =
readProp(rootCs, '--font-mono') ||
readProp(bodyCs, '--font-mono') ||
readProp(wbCs, '--vscode-editor-font-family') ||
readProp(rootCs, '--font-code');
for (const [cssVar, val] of [
['--font-sans', hostFontSans],
['--font-mono', hostFontMono],
]) {
const prevVal = mirroredTypographyVars.get(cssVar) || '';
if (val) {
if (prevVal !== val) {
portalHost.style.setProperty?.(cssVar, val);
mirroredTypographyVars.set(cssVar, val);
}
} else if (prevVal) {
if (typeof portalHost.style.removeProperty === 'function') {
portalHost.style.removeProperty(cssVar);
} else {
portalHost.style.setProperty?.(cssVar, '');
}
mirroredTypographyVars.delete(cssVar);
}
}
}
function restorePatchedActionToolbar() {
if (!patchedActionToolbar) return;
@@ -1585,6 +743,8 @@ export function mountWindowOverlay() {
? window.getComputedStyle(document.documentElement)
: null;
const bodyCs = document.body ? window.getComputedStyle(document.body) : null;
const wbOnlyCs = workbenchEl ? window.getComputedStyle(workbenchEl) : null;
syncHostTypographyVars(rootCs, bodyCs, wbOnlyCs);
const nativeRootBg = String(
rootCs?.getPropertyValue?.('--background') ||
bodyCs?.getPropertyValue?.('--background') ||
@@ -0,0 +1,919 @@
/**
* @fileoverview Host IDE/Desktop titlebar & composer button anchor discovery,
* 4-stage responsive capsule hysteresis, and shared ShadowRoot CSSStyleSheet mounting
* extracted from WindowOverlayShell.js.
*/
import { readInjectedWindowBridge } from '../../../shared/window-bridge-protocol.mjs';
import {
extractHostRouteCascadeId,
normalizeClientWindowMountMode,
telemetryStore,
} from '../../store/telemetryStore.js';
export const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule';
export const PORTAL_HOST_ID = 'ag-usage-monitor-portal';
/**
* 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。
* 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊;
* 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。
*
* @param {number} availWidth
* @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode
* @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options]
* @returns {'wide'|'compact'|'minimal'|'ring-only'}
*/
export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) {
if (availWidth == null || Number.isNaN(availWidth)) return 'wide';
const showMulti = options?.showMulti !== false;
const updateReserve = options?.hasUpdate ? 52 : 0;
const slotCount = Number(options?.slotCount || 3);
const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0;
const wideKeep = 256 + extraSlotWidth;
const wideEnter = 272 + extraSlotWidth;
const baseEffWidth = showMulti ? availWidth : availWidth + 76;
const effWidth = baseEffWidth - updateReserve;
if (currentMode === 'wide') {
if (baseEffWidth < 78) return 'ring-only';
if (effWidth < 196) return 'minimal';
if (effWidth < wideKeep) return 'compact';
return 'wide';
}
if (currentMode === 'compact') {
if (effWidth >= wideEnter) return 'wide';
if (baseEffWidth < 78) return 'ring-only';
if (effWidth < 196) return 'minimal';
return 'compact';
}
if (currentMode === 'minimal') {
if (effWidth >= wideEnter) return 'wide';
if (effWidth >= 212) return 'compact';
if (baseEffWidth < 78) return 'ring-only';
return 'minimal';
}
if (effWidth >= wideEnter) return 'wide';
if (effWidth >= 212) return 'compact';
if (baseEffWidth >= 92) return 'minimal';
return 'ring-only';
}
function findIdeWorkbenchTitlebar() {
try {
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
return null;
}
const workbench = document.querySelector('.monaco-workbench');
if (!workbench?.querySelector) return null;
const partTitlebar = workbench.querySelector('.part.titlebar');
if (!partTitlebar?.querySelector) return null;
if (partTitlebar.getBoundingClientRect) {
const pr = partTitlebar.getBoundingClientRect();
if (pr.width <= 0 || pr.height <= 0) return null;
}
const container =
partTitlebar.querySelector(':scope > .titlebar-container') ||
partTitlebar.querySelector('.titlebar-container');
const rightGroup =
container?.querySelector?.(':scope > .titlebar-right') ||
container?.querySelector?.('.titlebar-right');
if (!container || !rightGroup) return null;
const actionToolbar =
rightGroup.querySelector?.(':scope > .action-toolbar-container') ||
rightGroup.querySelector?.('.action-toolbar-container') ||
null;
return {
kind: 'ide-titlebar',
workbench,
titlebar: container,
targetContainer: rightGroup,
actionToolbar,
};
} catch {
return null;
}
}
function findHostTitlebar() {
try {
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
return null;
}
const tb = document.querySelector('[class*="@container/titlebar"]');
if (tb?.getBoundingClientRect) {
const r = tb.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) return null;
}
return tb;
} catch {
return null;
}
}
const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR =
'.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]';
const COMPOSER_MODEL_LABEL_RE =
/\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i;
const COMPOSER_MODEL_ATTR_RE =
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
const COMPOSER_MODE_TEXT_RE =
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|planning|act|review|confirm|normal|fast|自动|询问|始终询问|手动|始终允许|受控|规划|快速)(?:\s*(?:mode|模式))?$/i;
const COMPOSER_MODE_ATTR_RE =
/\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i;
const COMPOSER_ICON_FONT_CLASS_RE =
/\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i;
function querySimpleSelectorList(root, selectors) {
if (!root || typeof root.querySelectorAll !== 'function') return [];
const seen = new Set();
const out = [];
for (const sel of selectors) {
let list = [];
try {
list = root.querySelectorAll(sel) || [];
} catch {
list = [];
}
for (const item of list) {
if (item && !seen.has(item)) {
seen.add(item);
out.push(item);
}
}
}
return out;
}
function extractVisibleButtonText(node, isRoot = true) {
if (!node) return '';
const tag = String(node.tagName || node.nodeName || '').toLowerCase();
if (tag === 'svg' || tag === 'style' || tag === 'script') return '';
if (!isRoot) {
if (node.getAttribute?.('aria-hidden') === 'true') return '';
const cls = String(node.className || '');
if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return '';
}
if (tag === '#text' || node.nodeType === 3) {
return String(node.nodeValue ?? node.textContent ?? '');
}
const childNodes = node.childNodes || node.children;
if (!childNodes || childNodes.length === 0) {
return String(node.textContent || '');
}
let acc = '';
for (const ch of childNodes) {
acc += ` ${extractVisibleButtonText(ch, false)}`;
}
return acc;
}
function cleanComposerButtonText(btn) {
const raw = extractVisibleButtonText(btn, true)
.replace(/[\u200B-\u200D\uFEFF]/g, '')
.replace(/\s+/g, ' ')
.trim();
if (!raw) return '';
return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim();
}
function isComposerModelButtonItem(item) {
if (!item) return false;
if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true;
if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true;
return false;
}
function hasExcludedComposerAncestor(el) {
if (!el) return false;
if (typeof el.closest === 'function') {
try {
if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true;
} catch {
// 忽略选择器异常并回退祖先链遍历
}
}
let cur = el.parentElement || el.parentNode;
while (cur) {
const cls = String(cur.className || '');
if (
cls.includes('@container/titlebar') ||
cls.includes('quick-input-widget') ||
cls.includes('suggest-widget') ||
cls.includes('find-widget') ||
cls.includes('scm-editor') ||
cls.includes('search-view') ||
(cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar')))
) {
return true;
}
cur = cur.parentElement || cur.parentNode;
}
return false;
}
function isNodeHiddenByStyle(el) {
if (!el) return true;
if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const cs = window.getComputedStyle(el);
if (cs?.display === 'none' || cs?.visibility === 'hidden') return true;
} catch {
// 忽略样式读取异常
}
}
return false;
}
function getInFlowHostChildren(container, capsuleNode, portalNode) {
const rawChildren = container?.children || [];
const out = [];
for (const ch of rawChildren) {
if (!ch || ch === capsuleNode || ch === portalNode) continue;
if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue;
if (ch.hasAttribute?.('hidden')) continue;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const cs = window.getComputedStyle(ch);
if (cs?.display === 'none') continue;
if (cs?.position === 'absolute' || cs?.position === 'fixed') continue;
} catch {
// 忽略计算样式异常
}
}
out.push(ch);
}
return out;
}
function isHorizontalFlexContainer(el) {
if (!el) return false;
const cls = String(el.className || '');
if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const cs = window.getComputedStyle(el);
const disp = String(cs?.display || '');
const dir = String(cs?.flexDirection || 'row');
if (disp.includes('flex') && !dir.startsWith('column')) return true;
} catch {
// 忽略计算样式异常
}
}
return false;
}
function isSpaceDistributedFlexContainer(el) {
if (!el) return false;
const cls = String(el.className || '');
if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true;
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
try {
const jc = String(window.getComputedStyle(el)?.justifyContent || '');
if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) {
return true;
}
} catch {
// 忽略计算样式异常
}
}
return false;
}
function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) {
if (!autoBtn || !composerCard) return null;
let item = autoBtn;
while (
(item.parentElement || item.parentNode) &&
(item.parentElement || item.parentNode) !== composerCard &&
(item.parentElement || item.parentNode) !== document.body
) {
const parent = item.parentElement || item.parentNode;
const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode);
if (hostSiblings.length >= 2) break;
const grandParent = parent.parentElement || parent.parentNode;
const parentCls = String(parent.className || '');
const parentInlineMl = String(parent.style?.marginLeft || '').trim();
const isSingleClusterInSplitRow =
!/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) &&
parentInlineMl !== 'auto' &&
isHorizontalFlexContainer(parent) &&
grandParent &&
isSpaceDistributedFlexContainer(grandParent) &&
getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2;
if (isSingleClusterInSplitRow) {
break;
}
item = parent;
}
const anchorNode = item;
const targetContainer = anchorNode.parentElement || anchorNode.parentNode;
if (!targetContainer) return null;
const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode);
const anchorIdx = hostChildren.indexOf(anchorNode);
const isFirstHostChild = anchorIdx <= 0;
let needsAutoMarginTransfer = false;
let patchMarginNode = null;
if (!isFirstHostChild) {
const cls = String(anchorNode.className || '');
const inlineMl = String(anchorNode.style?.marginLeft || '').trim();
let computedLargeMl = false;
if (
patchedNode !== anchorNode &&
typeof window !== 'undefined' &&
typeof window.getComputedStyle === 'function'
) {
try {
const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0;
const prevSib = hostChildren[anchorIdx - 1];
const aRect = anchorNode.getBoundingClientRect?.();
const pRect = prevSib?.getBoundingClientRect?.();
if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) {
computedLargeMl = true;
}
} catch {
// 忽略边距测量异常
}
}
if (
/\b(?:ml-auto|ms-auto)\b/.test(cls) ||
inlineMl === 'auto' ||
patchedNode === anchorNode ||
computedLargeMl
) {
needsAutoMarginTransfer = true;
patchMarginNode = anchorNode;
} else if (isSpaceDistributedFlexContainer(targetContainer)) {
needsAutoMarginTransfer = true;
}
}
const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.();
let leftClusterRightEdge = 0;
if (autoRect && Array.isArray(bottomRowBtns)) {
for (const entry of bottomRowBtns) {
if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue;
if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) {
if (entry.rect.right > leftClusterRightEdge) {
leftClusterRightEdge = entry.rect.right;
}
}
}
}
return {
kind: 'composer',
workbench: null,
titlebar: composerCard,
targetContainer,
actionToolbar: patchMarginNode,
anchorNode,
needsAutoMarginTransfer,
leftClusterRightEdge,
};
}
function buildComposerRightEndDockDescriptor(
leftAnchorBtn,
composerCard,
bottomRowBtns,
capsuleNode,
portalNode
) {
if (!leftAnchorBtn || !composerCard) return null;
const cardRect = composerCard.getBoundingClientRect?.();
const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180;
let toolbarRow = null;
let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) {
const r = cur.getBoundingClientRect?.();
if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) {
toolbarRow = cur;
break;
}
cur = cur.parentElement || cur.parentNode;
}
if (!toolbarRow) {
const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
if (!p || !isHorizontalFlexContainer(p)) return null;
toolbarRow = p;
}
let leftClusterRightEdge = 0;
if (Array.isArray(bottomRowBtns)) {
for (const entry of bottomRowBtns) {
if (entry?.rect?.right > leftClusterRightEdge) {
leftClusterRightEdge = entry.rect.right;
}
}
}
const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode);
const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null;
if (
lastChild &&
!lastChild.contains?.(leftAnchorBtn) &&
isHorizontalFlexContainer(lastChild) &&
getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0
) {
return {
kind: 'composer',
workbench: null,
titlebar: composerCard,
targetContainer: lastChild,
actionToolbar: null,
anchorNode: null,
needsAutoMarginTransfer: false,
leftClusterRightEdge,
};
}
return {
kind: 'composer',
workbench: null,
titlebar: composerCard,
targetContainer: toolbarRow,
actionToolbar: null,
anchorNode: null,
needsAutoMarginTransfer: true,
leftClusterRightEdge,
};
}
function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) {
const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']);
const hostBtns = [];
for (const btn of rawBtns) {
if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue;
if (editorEl && btn.contains?.(editorEl)) continue;
if (
btn.id === CAPSULE_HOST_ID ||
btn.id === PORTAL_HOST_ID ||
capsuleNode?.contains?.(btn) ||
portalNode?.contains?.(btn)
) {
continue;
}
if (isNodeHiddenByStyle(btn)) continue;
// 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮
let nestedInBtn = false;
let p = btn.parentElement || btn.parentNode;
while (p && p !== container) {
const pTag = String(p.tagName || '').toLowerCase();
if (pTag === 'button') {
nestedInBtn = true;
break;
}
if (
(p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) &&
!(editorEl && p.contains?.(editorEl))
) {
const pr = p.getBoundingClientRect?.();
if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) {
nestedInBtn = true;
break;
}
}
p = p.parentElement || p.parentNode;
}
if (nestedInBtn) continue;
const br = btn.getBoundingClientRect?.();
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue;
const centerY = (br.top + br.bottom) / 2;
if (editorRect && centerY < editorRect.top - 4) continue;
hostBtns.push({
btn,
rect: br,
centerY,
centerX: (br.left + br.right) / 2,
cleanText: cleanComposerButtonText(btn),
attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(),
});
}
if (hostBtns.length === 0) return [];
let maxCenterY = -Infinity;
for (const item of hostBtns) {
if (item.centerY > maxCenterY) maxCenterY = item.centerY;
}
const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22);
bottomBand.sort((a, b) => a.rect.left - b.rect.left);
return bottomBand;
}
function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) {
if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null;
const requireModelForFallback = Boolean(options?.requireModelForFallback);
const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0;
const rightFirst = [
...bottomRowBtns.filter((b) => b.centerX >= rightSplitX),
...bottomRowBtns.filter((b) => b.centerX < rightSplitX),
];
// Tier 1: 精确文本 Auto / 自动 匹配
for (const item of rightFirst) {
if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) {
return { btn: item.btn, tier: 1 };
}
}
// Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮)
for (const item of rightFirst) {
if (isComposerModelButtonItem(item)) continue;
if (
(item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) ||
(item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText))
) {
return { btn: item.btn, tier: 2 };
}
}
const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem);
// Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局)
if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) {
let maxGap = -Infinity;
let splitIdx = -1;
for (let i = 1; i < bottomRowBtns.length; i += 1) {
const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right;
if (gap > maxGap) {
maxGap = gap;
splitIdx = i;
}
}
if (splitIdx >= 1 && maxGap >= 16) {
return { btn: bottomRowBtns[splitIdx].btn, tier: 3 };
}
}
// Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧
if (hasModelBtn && containerRect && containerRect.width >= 200) {
const lastItem = bottomRowBtns[bottomRowBtns.length - 1];
if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) {
return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 };
}
}
return null;
}
function resolveComposerEditorRect(ed) {
const er = ed?.getBoundingClientRect?.();
if (er && er.width >= 80 && er.height >= 12) return er;
let cur = ed;
for (let d = 0; d < 6 && cur; d += 1) {
if (String(cur.className || '').includes('monaco-editor')) {
const mr = cur.getBoundingClientRect?.();
if (mr && mr.width >= 80 && mr.height >= 12) return mr;
break;
}
cur = cur.parentElement || cur.parentNode;
}
return er || null;
}
function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) {
try {
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
return null;
}
const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null;
const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null;
const activeRouteId = extractHostRouteCascadeId();
// 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏和 Auto / 右簇发送按钮
const rawEditors = querySimpleSelectorList(document, [
'textarea',
'[contenteditable]',
'[role="textbox"]',
'[data-lexical-editor]',
'.ProseMirror',
'.monaco-editor',
]);
const scoredEditors = [];
for (const ed of rawEditors) {
if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue;
if (ed.hasAttribute?.('contenteditable')) {
const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase();
if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue;
}
if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue;
const er = resolveComposerEditorRect(ed);
if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue;
let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2;
if (activeRouteId) {
let anc = ed.parentElement || ed.parentNode;
while (anc) {
const cid = anc.getAttribute?.('data-cascade-id');
if (cid) {
score += cid === activeRouteId ? 4000 : -2000;
break;
}
anc = anc.parentElement || anc.parentNode;
}
}
if (
document.activeElement &&
(ed === document.activeElement || ed.contains?.(document.activeElement))
) {
score += 1000;
}
scoredEditors.push({ ed, rect: er, score });
}
scoredEditors.sort((a, b) => b.score - a.score);
for (const { ed, rect: er } of scoredEditors) {
const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') ||
String(ed.className || '').includes('inputarea');
let tier3Candidate = null;
let tier4Candidate = null;
let cur = ed.parentElement || ed.parentNode;
for (let depth = 0; depth < 18 && cur; depth += 1) {
if (cur === document.body || cur === document.documentElement) break;
const tag = String(cur.tagName || '').toLowerCase();
if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break;
const cr = cur.getBoundingClientRect?.();
if (cr && cr.height > 680) break;
if (cr && cr.width >= 180 && cr.height > 0) {
const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl);
const picked = pickAutoButtonFromRow(bottomRowBtns, cr, {
requireModelForFallback: isMonacoCandidate,
});
if (picked) {
if (picked.tier <= 2) {
const desc = buildComposerDockDescriptor(
picked.btn,
cur,
bottomRowBtns,
capEl,
porEl,
patchedNode
);
if (desc) return desc;
} else if (picked.tier === 3 && !tier3Candidate) {
tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns };
} else if (picked.tier === 4 && !tier4Candidate) {
tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns };
}
}
}
cur = cur.parentElement || cur.parentNode;
}
if (tier3Candidate) {
const desc = buildComposerDockDescriptor(
tier3Candidate.btn,
tier3Candidate.card,
tier3Candidate.bottomRowBtns,
capEl,
porEl,
patchedNode
);
if (desc) return desc;
}
if (tier4Candidate) {
const desc = buildComposerRightEndDockDescriptor(
tier4Candidate.leftAnchorBtn,
tier4Candidate.card,
tier4Candidate.bottomRowBtns,
capEl,
porEl
);
if (desc) return desc;
}
}
// 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏
const vh = Number(window.innerHeight || 800);
const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']);
let modelToolbarFallback = null;
for (const btn of allBtns) {
if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue;
if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue;
const br = btn.getBoundingClientRect?.();
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue;
const clean = cleanComposerButtonText(btn);
const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim();
const itemProbe = { cleanText: clean, attrText: attr };
const isModeBtn =
COMPOSER_MODE_EXACT_RE.test(clean) ||
(!isComposerModelButtonItem(itemProbe) &&
((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr))));
const isModelBtn = isComposerModelButtonItem(itemProbe);
if (!isModeBtn && !isModelBtn) continue;
let cur = btn.parentElement || btn.parentNode;
for (let depth = 0; depth < 12 && cur; depth += 1) {
if (cur === document.body || cur === document.documentElement) break;
if (String(cur.className || '').includes('monaco-workbench')) break;
const cr = cur.getBoundingClientRect?.();
if (!cr || cr.height > 560) break;
if (cr.width >= 200) {
const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl);
if (isModeBtn) {
const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b));
if (hasModelSibling) {
const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode);
if (desc) return desc;
}
} else if (isModelBtn && !modelToolbarFallback) {
const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true });
if (picked) {
const desc =
picked.tier <= 3 && picked.btn
? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode)
: picked.tier === 4 && picked.leftAnchorBtn
? buildComposerRightEndDockDescriptor(
picked.leftAnchorBtn,
cur,
rowBtns,
capEl,
porEl
)
: null;
if (desc) {
if (picked.tier <= 2) return desc;
modelToolbarFallback = desc;
break;
}
}
}
}
cur = cur.parentElement || cur.parentNode;
}
}
if (modelToolbarFallback) return modelToolbarFallback;
} catch {
// 忽略输入框探测异常
}
return null;
}
export function isImmediatelyBeforeNode(node, refNode) {
if (!node || !refNode) return false;
if (node.nextElementSibling !== undefined) {
return node.nextElementSibling === refNode;
}
if (node.nextSibling !== undefined) {
return node.nextSibling === refNode;
}
const parent = node.parentElement || node.parentNode;
if (!parent?.children) return false;
const idx = Array.prototype.indexOf.call(parent.children, node);
return idx >= 0 && parent.children[idx + 1] === refNode;
}
export function isIdeExtensionChatFrame() {
try {
if (typeof window === 'undefined') return false;
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
} catch {
return false;
}
}
export function resolveActiveDockTarget(options = undefined) {
const settings = telemetryStore.getState().telemetry?.settings;
const rawMode =
settings?.windowMountMode ??
readInjectedWindowBridge()?.mountMode;
const mountMode =
options?.mountMode ||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
if (isIdeExtensionChatFrame()) {
if (mountMode !== 'composer') return null;
return findHostComposerAutoTarget(
options?.capsuleNode || null,
options?.portalNode || null,
options?.patchedNode || null
);
}
if (mountMode === 'composer') {
const composerTarget = findHostComposerAutoTarget(
options?.capsuleNode || null,
options?.portalNode || null,
options?.patchedNode || null
);
if (composerTarget) return composerTarget;
}
const ideTarget = findIdeWorkbenchTitlebar();
if (ideTarget) return ideTarget;
const titlebar = findHostTitlebar();
if (!titlebar) return null;
let targetContainer = titlebar;
try {
const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild;
if (rightGroup && rightGroup !== titlebar.firstElementChild) {
targetContainer = rightGroup;
}
} catch {
// 忽略子选择器不兼容场景
}
return {
kind: 'flow',
workbench: null,
titlebar,
targetContainer,
actionToolbar: null,
};
}
export function findNativeTopRightAnchor() {
try {
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
return null;
}
const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]');
if (auxToggle?.closest) {
return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle;
}
const candidates = document.querySelectorAll('button, a, [role="button"]');
for (const btn of candidates) {
const text = String(btn.textContent || '').trim();
if (
(text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) &&
btn.getBoundingClientRect?.().top < 52
) {
return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn;
}
}
return document.querySelector('div.absolute.right-0.top-0');
} catch {
return null;
}
}
export function getLeftSidebarRightEdge(vw) {
try {
if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
if (document.querySelector('.monaco-workbench')) {
return 0;
}
const navEl = document.querySelector('div[role="navigation"]');
if (navEl?.getBoundingClientRect) {
const nr = navEl.getBoundingClientRect();
if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) {
return Math.ceil(nr.right);
}
}
}
} catch {
// 忽略侧栏测量异常
}
return 0;
}
/**
* 在主窗口挂载双栖顶栏胶囊和完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。
*/
const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([
'src/styles/views-overview.css',
'src/styles/views-consumption.css',
'src/styles/views-tables.css',
'src/styles/views-settings.css',
'src/styles/controls.css',
]);
let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null };
function buildSlimCapsuleCss(fullCss) {
if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss;
return fullCss
.split(/(?=\/\* --- src\/styles\/)/)
.filter((block) => {
const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//);
return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]);
})
.join('');
}
export function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) {
if (!shadowRoot) return;
if (
fullCss &&
typeof CSSStyleSheet === 'function' &&
Array.isArray(shadowRoot.adoptedStyleSheets)
) {
try {
if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(fullCss);
sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet };
}
shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet];
return;
} catch {
// 降级到传统 <style> 节点
}
}
const styleEl = document.createElement('style');
styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss;
shadowRoot.appendChild(styleEl);
}
@@ -0,0 +1,667 @@
/**
* @fileoverview Self-contained Antigravity Host UI Language card (`HostI18nCard.js`).
*
* Mounted inside `SettingsGeneralTab` with minimal glue; manages:
* - Language selection (`off` or any pack listed in repository `manifest.json`),
* - Conditional Light / Deep translation depth switching (0-network hot switch),
* - On-demand repository pack download, update, and local cache removal,
* - CDP bridge notice when DevTools port is unavailable,
* - Optional collapsed developer drawer to collect untranslated UI strings.
*/
import {
HOST_I18N_OFF_LOCALE,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../../shared/host-i18n-protocol.mjs';
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { abortSidecarApiKey } from '../../core/httpClient.js';
import {
copyTextWithFeedback,
exportTextFileWithFeedback,
} from '../../core/fileExportClient.js';
import {
collectHostI18nUntranslated,
fetchHostI18nStatus,
installOrUpdateHostI18nPack,
refreshHostI18nManifest,
removeHostI18nPack,
selectHostI18nLanguage,
updateHostI18nDepth,
} from '../../core/hostI18nClient.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.js';
import { CustomSelect } from '../ui/CustomSelect.js';
import { SegmentedControl } from '../ui/SegmentedControl.js';
import { BridgeStatusNotice } from './BridgeStatusNotice.js';
function formatHostI18nBytes(bytes) {
const num = Number(bytes || 0);
if (!Number.isFinite(num) || num <= 0) return '';
if (num < 1024) return `${num} B`;
return `${(num / 1024).toFixed(1)} KB`;
}
function getHostI18nDepthOptions() {
return [
{ value: 'light', label: t('settings.hostI18n.depthLight') },
{ value: 'deep', label: t('settings.hostI18n.depthDeep') },
];
}
export const HostI18nCard = defineComponent({
name: 'HostI18nCard',
setup({ props, onCleanup }) {
let status = null;
let draftLocale = HOST_I18N_OFF_LOCALE;
let draftDepth = 'light';
let latestWindowBridge = null;
let latestHostPlatform = 'win32';
let lastBridgeRenderSig = '';
let hasLoadedOnce = false;
let isBusy = false;
let isCollecting = false;
let destroyed = false;
let feedbackTimer = null;
let devExpanded = false;
let lastCollected = null;
const titleEl = h('span', { text: t('settings.hostI18n.title') });
const statusMsgEl = h('span', {
className: 'text-muted host-i18n-status-msg',
text: '',
});
function showFeedback(text, { isError = false, autoClearMs = 2800 } = {}) {
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
patchText(statusMsgEl, text || '');
patchClasses(statusMsgEl, { 'is-error': Boolean(isError && text) });
if (text && autoClearMs > 0) {
feedbackTimer = setTimeout(() => {
feedbackTimer = null;
if (!destroyed) {
patchText(statusMsgEl, '');
patchClasses(statusMsgEl, { 'is-error': false });
}
}, autoClearMs);
}
}
function getPackList() {
return Array.isArray(status?.packs) ? status.packs : [];
}
function findPackByLocale(locale) {
return getPackList().find((p) => p.locale === locale) || null;
}
function buildLocaleOptions() {
const opts = [{ value: HOST_I18N_OFF_LOCALE, label: t('settings.hostI18n.langOff') }];
for (const pack of getPackList()) {
const displayName =
pack.nativeName && pack.nativeName !== pack.name
? `${pack.nativeName} (${pack.locale})`
: `${pack.name || pack.locale} (${pack.locale})`;
const tag = pack.installed
? t('settings.hostI18n.optInstalled', { ver: pack.installedVersion || pack.remoteVersion || '1.0.0' })
: t('settings.hostI18n.optRemote', {
size: formatHostI18nBytes(pack.remoteBytes) || 'pack',
});
opts.push({
value: pack.locale,
label: `${displayName} · ${tag}`,
});
}
if (
draftLocale !== HOST_I18N_OFF_LOCALE &&
!opts.some((o) => o.value === draftLocale)
) {
opts.push({ value: draftLocale, label: draftLocale });
}
return opts;
}
const langLabelEl = h('span', {
className: 'form-label',
text: t('settings.hostI18n.langLabel'),
});
const langSelect = CustomSelect({
ariaLabel: t('settings.hostI18n.langLabel'),
icon: 'globe',
modelValue: draftLocale,
options: buildLocaleOptions(),
onUpdateModelValue: async (val) => {
if (isBusy || destroyed) return;
const nextLocale = normalizeHostI18nLocale(val);
const targetPack = findPackByLocale(nextLocale);
const needsDownload =
nextLocale !== HOST_I18N_OFF_LOCALE && !targetPack?.installed;
isBusy = true;
draftLocale = nextLocale;
syncControls();
showFeedback(
needsDownload
? t('settings.hostI18n.downloadingMsg', { locale: nextLocale })
: t('settings.saving'),
{ autoClearMs: 0 }
);
try {
const res = await selectHostI18nLanguage(nextLocale, draftDepth);
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
} else if (nextLocale === HOST_I18N_OFF_LOCALE) {
showFeedback(t('settings.hostI18n.disabledMsg'), { autoClearMs: 2500 });
} else if (res?.downloaded) {
showFeedback(t('settings.hostI18n.downloadedAndAppliedMsg'), { autoClearMs: 3200 });
} else {
showFeedback(t('settings.hostI18n.appliedMsg'), { autoClearMs: 2200 });
}
} catch (err) {
if (!destroyed) {
if (status) applyStatusPayload(status);
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
});
const refreshManifestBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm host-i18n-icon-btn',
title: t('settings.hostI18n.refreshManifestTip'),
'aria-label': t('settings.hostI18n.refreshManifestTip'),
onClick: async () => {
if (isBusy || destroyed) return;
isBusy = true;
syncControls();
showFeedback(t('settings.hostI18n.refreshingManifestMsg'), { autoClearMs: 0 });
try {
const res = await refreshHostI18nManifest();
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.manifestFailedMsg'), {
isError: true,
autoClearMs: 4500,
});
} else {
showFeedback(
t('settings.hostI18n.manifestSyncedMsg', { count: getPackList().length }),
{ autoClearMs: 2600 }
);
}
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.manifestFailedMsg'), {
isError: true,
autoClearMs: 4500,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
},
[createSvgIcon('refresh', { size: 12 })]
);
const langHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.langHint'),
});
// --- Conditional Depth Row (visible only when locale !== 'off') ---
const depthLabelEl = h('span', {
className: 'form-label',
text: t('settings.hostI18n.depthLabel'),
});
const depthSwitch = SegmentedControl({
ariaLabel: t('settings.hostI18n.depthLabel'),
modelValue: draftDepth,
options: getHostI18nDepthOptions(),
onUpdateModelValue: async (val) => {
if (isBusy || destroyed) return;
const nextDepth = normalizeHostI18nDepth(val);
if (nextDepth === draftDepth) return;
isBusy = true;
draftDepth = nextDepth;
syncControls();
showFeedback(t('settings.saving'), { autoClearMs: 0 });
try {
const res = await updateHostI18nDepth(nextDepth);
if (destroyed) return;
applyStatusPayload(res);
showFeedback(t('settings.hostI18n.depthSwitchedMsg'), { autoClearMs: 2000 });
} catch (err) {
if (!destroyed) {
if (status) applyStatusPayload(status);
showFeedback(err?.message || t('settings.saveFailed'), {
isError: true,
autoClearMs: 3500,
});
}
} finally {
isBusy = false;
if (!destroyed) syncControls();
}
},
});
const depthHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.depthLightHint'),
});
const depthRowEl = h('div', { className: 'form-row', hidden: true }, [
depthLabelEl,
depthSwitch.el,
depthHintEl,
]);
// --- Pack Meta & Actions Bar (visible only when locale !== 'off') ---
const packMetaTextEl = h('span', { className: 'host-i18n-pack-meta text-muted', text: '' });
const updatePackBtnText = h('span', { text: t('settings.hostI18n.redownloadBtn') });
const updatePackBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return;
isBusy = true;
syncControls();
showFeedback(t('settings.hostI18n.downloadingMsg', { locale: draftLocale }), {
autoClearMs: 0,
});
try {
const res = await installOrUpdateHostI18nPack(draftLocale);
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
} else {
showFeedback(t('settings.hostI18n.packUpdatedMsg'), { autoClearMs: 3000 });
}
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
}
} finally {
isBusy = false;
if (!destroyed) syncControls();
}
},
},
[createSvgIcon('download', { size: 12 }), updatePackBtnText]
);
const removePackBtnText = h('span', { text: t('settings.hostI18n.removeCacheBtn') });
const removePackBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
onClick: async () => {
if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return;
isBusy = true;
syncControls();
showFeedback(t('settings.saving'), { autoClearMs: 0 });
try {
const res = await removeHostI18nPack(draftLocale);
if (destroyed) return;
applyStatusPayload(res);
showFeedback(t('settings.hostI18n.cacheRemovedMsg'), { autoClearMs: 2800 });
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 4500,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
},
[removePackBtnText]
);
const packBarEl = h('div', { className: 'host-i18n-pack-bar', hidden: true }, [
packMetaTextEl,
h('div', { className: 'host-i18n-pack-actions' }, [updatePackBtn, removePackBtn]),
]);
// --- CDP Bridge Diagnostic Notice (shown only when active locale cannot reach CDP) ---
const bridgeNotice = BridgeStatusNotice({ contextMode: true });
// --- Collapsed Developer Drawer: Untranslated UI String Collector ---
const devChevron = createSvgIcon('chevron-right', {
size: 11,
className: 'host-i18n-dev-chevron',
});
const devToggleText = h('span', { text: t('settings.hostI18n.devToolsTitle') });
const devToggleBtn = h(
'button',
{
type: 'button',
className: 'host-i18n-dev-toggle',
'aria-expanded': 'false',
onClick: () => {
devExpanded = !devExpanded;
patchAttr(devToggleBtn, 'aria-expanded', devExpanded ? 'true' : 'false');
patchClasses(devDrawerEl, { 'is-expanded': devExpanded });
patchAttr(devBodyEl, 'hidden', !devExpanded);
props.onLayoutChange?.();
},
},
[devChevron, devToggleText]
);
const devHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.devToolsHint'),
});
const collectBtnText = h('span', { text: t('settings.hostI18n.collectBtn') });
const collectResultEl = h('span', { className: 'settings-hint-text', text: '' });
const copyCollectedBtnText = h('span', { text: t('settings.hostI18n.copyJsonBtn') });
const copyCollectedBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
hidden: true,
onClick: async () => {
if (!lastCollected?.template) return;
await copyTextWithFeedback(JSON.stringify(lastCollected.template, null, 2), {
onFeedback: (msg) => showFeedback(msg, { autoClearMs: 2400 }),
});
},
},
[createSvgIcon('copy', { size: 11 }), copyCollectedBtnText]
);
const exportCollectedBtnText = h('span', { text: t('settings.hostI18n.exportJsonBtn') });
const exportCollectedBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
hidden: true,
onClick: async () => {
if (!lastCollected?.template) return;
const fileLocale = draftLocale === HOST_I18N_OFF_LOCALE ? 'en-source' : draftLocale;
await exportTextFileWithFeedback({
filename: `host-i18n-missing-${fileLocale}.json`,
content: JSON.stringify(lastCollected.template, null, 2) + '\n',
mimeType: 'application/json',
onFeedback: (msg) => showFeedback(msg, { autoClearMs: 3200 }),
});
},
},
[createSvgIcon('download', { size: 11 }), exportCollectedBtnText]
);
const collectBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isCollecting || destroyed) return;
isCollecting = true;
patchAttr(collectBtn, 'disabled', true);
patchText(collectBtnText, t('settings.hostI18n.collectingBtn'));
try {
const res = await collectHostI18nUntranslated();
if (destroyed) return;
if (res?.ok) {
lastCollected = res;
patchText(
collectResultEl,
res.count > 0
? t('settings.hostI18n.collectedResult', {
count: res.count,
targets: res.targets || 1,
})
: t('settings.hostI18n.collectedEmpty')
);
patchAttr(copyCollectedBtn, 'hidden', !(res.count > 0));
patchAttr(exportCollectedBtn, 'hidden', !(res.count > 0));
} else {
patchText(collectResultEl, res?.error || t('settings.hostI18n.collectFailed'));
}
} catch (err) {
if (!destroyed) {
patchText(collectResultEl, err?.message || t('settings.hostI18n.collectFailed'));
}
} finally {
isCollecting = false;
if (!destroyed) {
patchAttr(collectBtn, 'disabled', false);
patchText(collectBtnText, t('settings.hostI18n.collectBtn'));
props.onLayoutChange?.();
}
}
},
},
[createSvgIcon('search', { size: 12 }), collectBtnText]
);
const devBodyEl = h('div', { className: 'host-i18n-dev-body', hidden: true }, [
devHintEl,
h('div', { className: 'host-i18n-dev-actions' }, [
collectBtn,
copyCollectedBtn,
exportCollectedBtn,
]),
collectResultEl,
]);
const devDrawerEl = h('div', { className: 'host-i18n-dev-drawer' }, [
devToggleBtn,
devBodyEl,
]);
const rootEl = h('section', { className: 'panel host-i18n-panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('globe', { size: 13 }),
titleEl,
]),
statusMsgEl,
]),
h('div', { className: 'form-row' }, [
langLabelEl,
h('div', { className: 'host-i18n-select-row' }, [langSelect.el, refreshManifestBtn]),
langHintEl,
]),
depthRowEl,
packBarEl,
bridgeNotice.el,
devDrawerEl,
]);
function applyStatusPayload(payload) {
if (!payload || typeof payload !== 'object') return;
status = payload;
draftLocale = normalizeHostI18nLocale(payload.locale);
draftDepth = normalizeHostI18nDepth(payload.depth);
if (payload.bridgeStatus) {
latestWindowBridge = payload.bridgeStatus;
}
syncControls();
}
function syncControls() {
const enabled = draftLocale !== HOST_I18N_OFF_LOCALE;
const activePack = enabled ? findPackByLocale(draftLocale) : null;
langSelect.setProps({
modelValue: draftLocale,
options: buildLocaleOptions(),
disabled: isBusy,
});
patchAttr(refreshManifestBtn, 'disabled', isBusy);
patchAttr(depthRowEl, 'hidden', !enabled);
depthSwitch.setProps({
modelValue: draftDepth,
options: getHostI18nDepthOptions(),
});
patchText(
depthHintEl,
draftDepth === 'deep'
? t('settings.hostI18n.depthDeepHint')
: t('settings.hostI18n.depthLightHint')
);
patchAttr(packBarEl, 'hidden', !enabled);
if (enabled) {
const ver = activePack?.installedVersion || activePack?.remoteVersion || '1.0.0';
const stats = activePack?.stats;
const entryCount = stats
? Number(stats.baseExact || 0) +
Number(draftDepth === 'deep' ? stats.deepExact || 0 : stats.lightExact || 0) +
Number(stats.basePatterns || 0) +
Number(draftDepth === 'deep' ? stats.deepPatterns || 0 : stats.lightPatterns || 0)
: 0;
const sizeStr = formatHostI18nBytes(
activePack?.installedBytes || activePack?.remoteBytes || 0
);
const appliedCount = Number(latestWindowBridge?.hostI18nAppliedCount || 0);
const metaParts = [`v${ver}`];
if (entryCount > 0) {
metaParts.push(t('settings.hostI18n.entriesCount', { count: entryCount }));
}
if (sizeStr) metaParts.push(sizeStr);
if (appliedCount > 0) {
metaParts.push(t('settings.hostI18n.appliedWindows', { count: appliedCount }));
}
patchText(packMetaTextEl, metaParts.join(' · '));
const hasUpdate = Boolean(activePack?.updateAvailable);
patchText(
updatePackBtnText,
hasUpdate
? t('settings.hostI18n.updatePackBtn', { ver: activePack.remoteVersion })
: t('settings.hostI18n.redownloadBtn')
);
patchClasses(updatePackBtn, {
'btn-primary': hasUpdate,
'btn-secondary': !hasUpdate,
});
patchAttr(updatePackBtn, 'disabled', isBusy);
patchAttr(removePackBtn, 'disabled', isBusy || !activePack?.installed);
}
bridgeNotice.refs.update({
visible: enabled,
windowBridge: latestWindowBridge,
hostPlatform: latestHostPlatform,
contextMode: true,
});
}
async function load(force = false) {
if (destroyed) return;
if (hasLoadedOnce && !force) return;
hasLoadedOnce = true;
try {
const res = await fetchHostI18nStatus();
if (destroyed) return;
applyStatusPayload(res);
props.onLayoutChange?.();
} catch {
// 静默兜底,保留手动刷新入口
}
}
function renderBridgeStatus(windowBridge, hostPlatform) {
if (windowBridge) latestWindowBridge = windowBridge;
if (hostPlatform) latestHostPlatform = hostPlatform;
const sig = [
Number(latestWindowBridge?.hostI18nAppliedCount || 0),
Boolean(latestWindowBridge?.connected),
Boolean(latestWindowBridge?.available),
String(latestWindowBridge?.reason || ''),
String(latestWindowBridge?.ideStatus?.reason || ''),
String(latestHostPlatform || ''),
].join('|');
if (sig === lastBridgeRenderSig) return;
lastBridgeRenderSig = sig;
syncControls();
}
function refreshLabels() {
patchText(titleEl, t('settings.hostI18n.title'));
patchText(langLabelEl, t('settings.hostI18n.langLabel'));
patchText(langHintEl, t('settings.hostI18n.langHint'));
patchText(depthLabelEl, t('settings.hostI18n.depthLabel'));
patchText(removePackBtnText, t('settings.hostI18n.removeCacheBtn'));
patchText(devToggleText, t('settings.hostI18n.devToolsTitle'));
patchText(devHintEl, t('settings.hostI18n.devToolsHint'));
if (!isCollecting) patchText(collectBtnText, t('settings.hostI18n.collectBtn'));
patchText(copyCollectedBtnText, t('settings.hostI18n.copyJsonBtn'));
patchText(exportCollectedBtnText, t('settings.hostI18n.exportJsonBtn'));
patchAttr(refreshManifestBtn, 'title', t('settings.hostI18n.refreshManifestTip'));
patchAttr(refreshManifestBtn, 'aria-label', t('settings.hostI18n.refreshManifestTip'));
bridgeNotice.refs.refreshLabels();
syncControls();
}
onCleanup(() => {
destroyed = true;
abortSidecarApiKey('host-i18n-get');
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
langSelect.destroy();
depthSwitch.destroy();
bridgeNotice.destroy();
});
return {
el: rootEl,
refs: {
langSelect,
depthSwitch,
load,
renderBridgeStatus,
refreshLabels,
},
};
},
});
@@ -62,7 +62,7 @@ export function filterSelectOptionsByQuery(options = [], rawQuery = '') {
const opt = options[i];
if (!opt) continue;
const haystack =
`${opt.label || ''} ${opt.meta || ''} ${opt.title || ''} ${opt.value || ''}`.toLowerCase();
`${opt.label || ''} ${opt.subLabel || ''} ${opt.meta || ''} ${opt.searchText || ''} ${opt.title || ''} ${opt.value || ''}`.toLowerCase();
let matched = true;
for (let k = 0; k < terms.length; k++) {
if (!haystack.includes(terms[k])) {
@@ -222,7 +222,7 @@ export const CustomSelect = defineComponent({
let sig = `${labelText}|${searchShown}|${searchQuery}|${options.length}`;
for (let i = 0; i < options.length; i++) {
const o = options[i];
sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.meta ?? ''}`;
sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.subLabel ?? ''}:${o?.meta ?? ''}`;
}
return sig;
}
@@ -375,15 +375,17 @@ export const CustomSelect = defineComponent({
patchKeyedList(optionsListEl, visibleOpts, {
keyFn: (opt) => opt.value,
sigFn: (opt, idx) =>
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
`${multiple}::${opt.value}::${opt.label}::${opt.subLabel || ''}::${opt.meta || ''}::${Boolean(opt.dimMeta)}::${Boolean(opt.dividerAfter)}::${opt.title || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
createRow: (opt) => {
const checkboxIcon = createSvgIcon('check', { size: 10 });
const checkboxBox = h('span', { className: 'select-checkbox', hidden: true }, [
checkboxIcon,
]);
const textSpan = h('span', { className: 'select-option-text' });
const subSpan = h('span', { className: 'text-muted select-option-sub', hidden: true });
const bodyWrap = h('span', { className: 'select-option-body' }, [textSpan, subSpan]);
const metaSpan = h('span', { className: 'text-muted select-option-meta' });
const checkIcon = createSvgIcon('check', { size: 12 });
const checkIcon = createSvgIcon('check', { size: 12, className: 'select-option-check' });
const btn = h(
'button',
{
@@ -397,9 +399,12 @@ export const CustomSelect = defineComponent({
chooseOption(latestOpt);
},
},
[checkboxBox, textSpan, metaSpan, checkIcon]
[checkboxBox, bodyWrap, metaSpan, checkIcon]
);
return { el: btn, refs: { checkboxBox, checkboxIcon, textSpan, metaSpan, checkIcon } };
return {
el: btn,
refs: { checkboxBox, checkboxIcon, textSpan, subSpan, metaSpan, checkIcon },
};
},
updateRow: (refs, opt, idx, el) => {
const isMulti = Boolean(getProps().multiple);
@@ -410,14 +415,20 @@ export const CustomSelect = defineComponent({
patchClasses(refs.checkboxBox, { 'is-checked': selected });
patchAttr(refs.checkboxIcon, 'hidden', !selected);
patchText(refs.textSpan, opt.label);
patchText(refs.subSpan, opt.subLabel || '');
patchAttr(refs.subSpan, 'hidden', !opt.subLabel);
patchText(refs.metaSpan, opt.meta || '');
patchAttr(refs.metaSpan, 'hidden', !opt.meta);
patchClasses(refs.metaSpan, { 'is-dim': Boolean(opt.dimMeta) });
patchAttr(refs.checkIcon, 'hidden', isMulti || !selected);
patchClasses(el, {
'is-selected': selected,
'is-focused': focused,
'is-disabled': isDisabled,
'has-sub': Boolean(opt.subLabel),
'has-divider-after': Boolean(opt.dividerAfter),
});
patchAttr(el, 'title', opt.title || null);
patchAttr(el, 'disabled', isDisabled);
patchAttr(el, 'aria-disabled', isDisabled ? 'true' : null);
patchAttr(el, 'aria-selected', selected ? 'true' : 'false');
@@ -469,8 +480,8 @@ export const CustomSelect = defineComponent({
const fallbackText = modelValue
? `${placeholder} (${String(modelValue).slice(0, 8)})`
: placeholder;
labelText = selectedOpt ? selectedOpt.label : fallbackText;
titleText = labelText;
labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText;
titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText;
}
patchText(triggerLabel, labelText);
File diff suppressed because it is too large Load Diff
@@ -182,6 +182,28 @@ export function patchCapsuleOdometerText(
return true;
}
function isValidTtftSec(val) {
return val != null && Number.isFinite(Number(val)) && Number(val) >= 0;
}
function findFallbackRecentStepTtft(steps) {
if (!Array.isArray(steps) || steps.length === 0) return null;
const firstIdx = Number(steps[0]?.stepIndex ?? 0);
const lastIdx = Number(steps[steps.length - 1]?.stepIndex ?? 0);
if (firstIdx >= lastIdx) {
for (let i = 0; i < steps.length; i += 1) {
const candidate = steps[i]?.ttftSec;
if (isValidTtftSec(candidate)) return Number(candidate);
}
return null;
}
for (let i = steps.length - 1; i >= 0; i -= 1) {
const candidate = steps[i]?.ttftSec;
if (isValidTtftSec(candidate)) return Number(candidate);
}
return null;
}
/**
* Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation.
*/
@@ -204,11 +226,29 @@ export function buildCapsuleSlotContext(
).toFixed(2);
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
const convId = String(capActive.cascadeId || activeConv.cascadeId || '')
.trim()
.toLowerCase();
const scopeId = String(scopedConv?.agentId || aggregated?.agentId || 'main');
const conversationKey = convId ? `${convId}::${scopeId}` : '';
const stepCount = Math.max(0, Number(capActive.stepCount ?? activeConv.stepCount ?? 0));
const rawTtft =
scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null;
const fallbackTtft = isValidTtftSec(rawTtft)
? Number(rawTtft)
: scopedConv?.lastKnownTtftSec ??
findFallbackRecentStepTtft(scopedConv?.recentSteps) ??
aggregated?.lastKnownTtftSec ??
activeConv.lastKnownTtftSec ??
findFallbackRecentStepTtft(activeConv.recentSteps);
const resolvedTtft = isValidTtftSec(fallbackTtft) ? Number(fallbackTtft) : null;
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
const sessionTokens =
Number(capActive.stepCount || 0) > 0 ||
stepCount > 0 ||
capActive.totalTokens != null ||
capInTok + capCacheTok + capOutTok > 0
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
@@ -216,12 +256,14 @@ export function buildCapsuleSlotContext(
return {
hasTelemetry: true,
conversationKey,
stepCount,
usedPct,
dashOffset,
isRunning,
tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null,
avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null,
ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null,
ttft: resolvedTtft,
stepCost:
scopedConv?.latestStepCostUsd ??
aggregated?.latestStepCostUsd ??
@@ -351,6 +393,7 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) {
textSpan,
ringMounted: isCtx,
prefixMounted: false,
heldTtft: null,
};
}
@@ -363,7 +406,25 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt
for (let i = 0; i < capsuleSlots.length; i += 1) {
const slot = capsuleSlots[i];
const metricKey = i < slotKeys.length ? slotKeys[i] : 'none';
const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
if (!slotCtx?.hasTelemetry || metricKey !== 'ttft') {
slot.heldTtft = null;
}
let pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
if (metricKey === 'ttft' && slotCtx?.hasTelemetry) {
const convKey = String(slotCtx.conversationKey || '');
if (isValidTtftSec(slotCtx.ttft)) {
slot.heldTtft = convKey ? { conversationKey: convKey, pres } : null;
} else if (
convKey &&
slot.heldTtft &&
slot.heldTtft.conversationKey === convKey &&
(slotCtx.isRunning || Number(slotCtx.stepCount) > 0)
) {
pres = { ...slot.heldTtft.pres, running: Boolean(slotCtx.isRunning) };
} else {
slot.heldTtft = null;
}
}
if (pres.hidden) {
patchAttr(slot.el, 'hidden', true);
patchAttr(slot.el, 'data-metric', 'none');
@@ -0,0 +1,887 @@
/**
* @fileoverview Reusable model, client-source, workspace, and top-conversation breakdown
* row builders (`ConsumptionBreakdownRows.js`) extracted from `ConsumptionView.js`.
* Consolidates shared long-tail model partitioning, hover-popover event binding, and top-model pill rendering.
*/
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchStyleVar,
patchText,
} from '../../core/domPatch.js';
import {
formatCnyApprox,
formatMetric,
formatPctNumber,
formatSpeedMetric,
formatTokensPrecise,
formatUsd,
getCanonicalModelColorSeed,
resolveDeterministicModelColor,
} from '../../core/formatters.js';
import { t } from '../../i18n/index.js';
import { createFourSegmentBar } from '../ui/FourSegmentBar.js';
function createSourceModelSegment() {
const segEl = h('div', { className: 'progress-seg cons-model-seg' });
return { el: segEl, refs: { segEl } };
}
function createSourceTopModelItem() {
const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' });
const nameEl = h('span', { className: 'cons-source-top-name' });
const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' });
const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]);
return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } };
}
function formatCompactSourceSharePct(pct) {
const num = Number(pct || 0);
if (!Number.isFinite(num) || num <= 0) return '0%';
if (num >= 10) return `${Math.round(num)}%`;
return `${num.toFixed(1)}%`;
}
function renderSegmentedModelBarAndTopPills(
trackEl,
topModelsEl,
partitioned,
scaleRatio,
fallbackKey
) {
const barItems =
partitioned.length > 0
? partitioned.map((seg) => ({
key: seg.key,
segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0,
color: seg.color,
}))
: scaleRatio > 0
? [
{
key: fallbackKey,
segPct: scaleRatio * 100,
color: 'var(--accent-primary)',
},
]
: [];
patchKeyedList(trackEl, barItems, {
keyFn: (seg) => seg.key,
sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`,
createRow: createSourceModelSegment,
updateRow: (segRefs, seg) => {
patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`);
patchStyleVar(segRefs.segEl, '--seg-color', seg.color);
},
});
const topModels = partitioned
.filter((seg) => !seg.isOther)
.slice(0, 3)
.map((seg) => ({
key: seg.key,
label: seg.label,
pctText: formatCompactSourceSharePct(seg.pct),
color: seg.color,
}));
patchAttr(topModelsEl, 'hidden', topModels.length === 0);
patchKeyedList(topModelsEl, topModels, {
keyFn: (m) => m.key,
sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`,
createRow: createSourceTopModelItem,
updateRow: (mRefs, m) => {
patchStyleVar(mRefs.dotEl, '--dot-color', m.color);
patchText(mRefs.nameEl, m.label);
patchText(mRefs.pctEl, m.pctText);
patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`);
},
});
return topModels;
}
/**
* Collapses long-tail model entries into primary segments + an aggregated "Other (N)" tail.
*/
export function partitionModelSegments(
mergedModels,
modelColorMap,
{ maxMain = 5, minSharePct = 1.5 } = {}
) {
if (!Array.isArray(mergedModels) || mergedModels.length === 0) return [];
const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0);
const mainModels = [];
const tailModels = [];
for (let i = 0; i < mergedModels.length; i += 1) {
const m = mergedModels[i];
const mTok = Number(m.totalTokens || 0);
const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0;
if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) {
mainModels.push(m);
} else {
tailModels.push(m);
}
}
if (tailModels.length === 1) {
mainModels.push(tailModels.pop());
}
const out = mainModels.map((m) => {
const seed = getCanonicalModelColorSeed(m);
const color =
modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText);
const tok = Number(m.totalTokens || 0);
const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0;
const label = m.displayText || m.label || m.shortName || '—';
const inputTokens = Math.max(0, Number(m.inputTokens || 0));
const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0));
const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0));
const responseTokens =
m.responseTokens != null
? Math.max(0, Number(m.responseTokens))
: Math.max(0, Number(m.outputTokens || 0) - thinkingTokens);
return {
key: label,
label,
tok,
pct,
inputTokens,
cacheReadTokens,
thinkingTokens,
responseTokens,
outputTokens: responseTokens + thinkingTokens,
tokText: formatTokensPrecise(tok),
pctText: formatPctNumber(pct, { withSymbol: true }),
color,
isOther: false,
};
});
if (tailModels.length >= 2) {
let otherTok = 0;
let otherIn = 0;
let otherCache = 0;
let otherThink = 0;
let otherResp = 0;
for (const m of tailModels) {
const mt = Math.max(0, Number(m.thinkingTokens || 0));
const mr =
m.responseTokens != null
? Math.max(0, Number(m.responseTokens))
: Math.max(0, Number(m.outputTokens || 0) - mt);
otherTok += Number(m.totalTokens || 0);
otherIn += Math.max(0, Number(m.inputTokens || 0));
otherCache += Math.max(0, Number(m.cacheReadTokens || 0));
otherThink += mt;
otherResp += mr;
}
const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0;
const otherLabel = t('cons.otherModelsCount', { count: tailModels.length });
out.push({
key: '__other__',
label: otherLabel,
tok: otherTok,
pct: otherPct,
inputTokens: otherIn,
cacheReadTokens: otherCache,
thinkingTokens: otherThink,
responseTokens: otherResp,
outputTokens: otherResp + otherThink,
tokText: formatTokensPrecise(otherTok),
pctText: formatPctNumber(otherPct, { withSymbol: true }),
color: 'var(--cons-other-seg)',
isOther: true,
});
}
return out;
}
/**
* Creates a model ranking row (`tokens` | `cost` | `speed` | `calls` sort modes).
*/
export function createBreakdownItemRow() {
const nameTextEl = h('span', { className: 'cons-row-title-text' });
const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]);
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
const segBar = createFourSegmentBar();
const inLbl = h('span', { text: t('cons.footInput') });
const cacheLbl = h('span', { text: t('cons.footCache') });
const outLbl = h('span', { text: t('cons.footOutput') });
const thinkLbl = h('span', { text: t('cons.footThinking') });
const callsLbl = h('span', { text: t('cons.footCalls') });
const inVal = h('strong', { className: 'text-mono' });
const cacheVal = h('strong', { className: 'text-mono' });
const outVal = h('strong', { className: 'text-mono' });
const thinkVal = h('strong', { className: 'text-mono' });
const callsVal = h('strong', { className: 'text-mono' });
const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' });
const metricBarEl = h(
'div',
{ className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true },
[metricBarFillEl]
);
const tokenFootEl = h('div', { className: 'cons-item-foot' }, [
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-input' }),
inLbl,
inVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-cached' }),
cacheLbl,
cacheVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-thinking' }),
thinkLbl,
thinkVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-output' }),
outLbl,
outVal,
]),
h('span', { className: 'legend-left' }, [callsLbl, callsVal]),
]);
const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' });
const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true });
const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [
perfMainEl,
perfUnitCostEl,
]);
const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' });
const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' });
const focusFootEl = h(
'div',
{ className: 'cons-item-foot cons-model-focus-foot', hidden: true },
[focusLeftEl, focusRightEl]
);
const rowEl = h('div', { className: 'cons-item-row' }, [
h('div', { className: 'panel-header' }, [
nameEl,
h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]),
]),
segBar.el,
metricBarEl,
tokenFootEl,
perfFootEl,
focusFootEl,
]);
return {
el: rowEl,
refs: {
nameEl,
nameTextEl,
pctBadge,
totalTokEl,
costEl,
segBar,
metricBarEl,
metricBarFillEl,
tokenFootEl,
inLbl,
cacheLbl,
outLbl,
thinkLbl,
callsLbl,
inVal,
cacheVal,
outVal,
thinkVal,
callsVal,
perfFootEl,
perfMainEl,
perfUnitCostEl,
focusFootEl,
focusLeftEl,
focusRightEl,
},
};
}
/**
* Incrementally patches a model ranking row.
*/
export function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') {
const displayLabel = item.label || item.name || item.shortName || '—';
patchText(refs.nameTextEl, displayLabel);
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
const total = Number(item.totalTokens || 0);
const costVal = Number(item.costUsd || 0);
const callsCount = Number(item.calls || 0);
const isAllUnpriced =
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
const costText = formatUsd(isAllUnpriced ? null : costVal, {
precise: costVal > 0 && costVal < 0.1,
});
const avgTps =
item.avgTokPerSec != null &&
Number.isFinite(Number(item.avgTokPerSec)) &&
Number(item.avgTokPerSec) > 0
? Number(item.avgTokPerSec)
: null;
const avgTtft =
item.avgTtftSec != null &&
Number.isFinite(Number(item.avgTtftSec)) &&
Number(item.avgTtftSec) >= 0
? Number(item.avgTtftSec)
: null;
const hasExplicitCachePct =
item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct));
const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0);
const cachePctVal = hasExplicitCachePct
? Number(item.cacheHitPct)
: promptTok > 0 && Number(item.cacheReadTokens || 0) > 0
? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1)
: 0;
const cachePctStr = formatPctNumber(cachePctVal);
const effCostPer1M =
!isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null;
const outTok = Number(
item.outputTokens ?? Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0)
);
if (sortMode === 'cost') {
const costBase = Number(totalsCtx?.totalCost || 0);
const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0;
const barPct =
costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0;
patchAttr(refs.pctBadge, 'hidden', false);
patchAttr(refs.pctBadge, 'title', null);
patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true }));
patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal));
patchText(refs.costEl, costText);
patchAttr(refs.segBar.el, 'hidden', true);
patchAttr(refs.metricBarEl, 'hidden', false);
patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`);
patchClasses(refs.metricBarFillEl, {
'tone-cost': true,
'tone-speed': false,
'tone-calls': false,
});
patchAttr(refs.tokenFootEl, 'hidden', true);
patchAttr(refs.perfFootEl, 'hidden', true);
patchAttr(refs.focusFootEl, 'hidden', false);
const unitPart =
effCostPer1M !== null
? t('cons.modelUnitCost', {
cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }),
})
: '';
const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr });
patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart);
patchText(
refs.focusRightEl,
`${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}`
);
return;
}
if (sortMode === 'speed') {
const maxTps = Number(totalsCtx?.maxAvgTps || 0);
const speedPct =
maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0;
patchAttr(refs.pctBadge, 'hidden', avgTps === null);
patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null);
patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : '');
patchText(
refs.totalTokEl,
avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : ''
);
patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s'));
patchAttr(refs.segBar.el, 'hidden', true);
patchAttr(refs.metricBarEl, 'hidden', false);
patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`);
patchClasses(refs.metricBarFillEl, {
'tone-cost': false,
'tone-speed': true,
'tone-calls': false,
});
patchAttr(refs.tokenFootEl, 'hidden', true);
patchAttr(refs.perfFootEl, 'hidden', true);
patchAttr(refs.focusFootEl, 'hidden', false);
patchText(
refs.focusLeftEl,
t('cons.focusSpeedMeta', {
ttft: formatMetric(avgTtft, 's'),
cache: cachePctStr,
out: formatTokensPrecise(outTok),
})
);
patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount }));
return;
}
if (sortMode === 'calls') {
const callsBase = Number(totalsCtx?.totalCalls || 0);
const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0;
const barPct =
callsBase > 0 && callsCount > 0
? Math.min(100, Math.max(1, (callsCount / callsBase) * 100))
: 0;
patchAttr(refs.pctBadge, 'hidden', false);
patchAttr(refs.pctBadge, 'title', null);
patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true }));
patchText(refs.totalTokEl, formatTokensPrecise(total));
patchText(refs.costEl, t('cons.callsCount', { calls: callsCount }));
patchAttr(refs.segBar.el, 'hidden', true);
patchAttr(refs.metricBarEl, 'hidden', false);
patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`);
patchClasses(refs.metricBarFillEl, {
'tone-cost': false,
'tone-speed': false,
'tone-calls': true,
});
patchAttr(refs.tokenFootEl, 'hidden', true);
patchAttr(refs.perfFootEl, 'hidden', true);
patchAttr(refs.focusFootEl, 'hidden', false);
const avgPerCall = callsCount > 0 ? total / callsCount : 0;
patchText(
refs.focusLeftEl,
t('cons.focusCallsMeta', {
avgTok: formatTokensPrecise(avgPerCall),
cost: costText,
})
);
patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr }));
return;
}
patchText(refs.inLbl, t('cons.footInput'));
patchText(refs.cacheLbl, t('cons.footCache'));
patchText(refs.outLbl, t('cons.footOutput'));
patchText(refs.thinkLbl, t('cons.footThinking'));
patchText(refs.callsLbl, t('cons.footCalls'));
const grandTotalTokens = Number(totalsCtx?.totalTokens || 0);
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
const scaleRatio =
grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0;
patchAttr(refs.pctBadge, 'hidden', false);
patchAttr(refs.pctBadge, 'title', null);
patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true }));
patchText(refs.totalTokEl, formatTokensPrecise(total));
patchText(refs.costEl, costText);
const responseTok =
item.responseTokens != null
? Number(item.responseTokens)
: Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0));
const thinkingTok = Number(item.thinkingTokens || 0);
patchAttr(refs.segBar.el, 'hidden', false);
patchAttr(refs.metricBarEl, 'hidden', true);
refs.segBar.update({
inputTokens: Number(item.inputTokens || 0),
cacheReadTokens: Number(item.cacheReadTokens || 0),
responseTokens: responseTok,
thinkingTokens: thinkingTok,
scaleRatio,
});
patchAttr(refs.tokenFootEl, 'hidden', false);
patchAttr(refs.focusFootEl, 'hidden', true);
patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0));
patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0));
patchText(refs.outVal, formatTokensPrecise(responseTok));
patchText(refs.thinkVal, formatTokensPrecise(thinkingTok));
patchText(refs.callsVal, String(callsCount));
const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null;
patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta);
if (hasPerfMeta) {
if (avgTps !== null || avgTtft !== null) {
patchText(
refs.perfMainEl,
t('steps.modelPerfFoot', {
tps: formatSpeedMetric(avgTps, ' tok/s'),
ttft: formatMetric(avgTtft, 's'),
cache: cachePctStr,
})
);
} else {
patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr }));
}
patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null);
patchText(
refs.perfUnitCostEl,
effCostPer1M !== null
? t('cons.modelUnitCost', {
cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }),
})
: ''
);
}
}
/**
* Binds shared popover hover callbacks to build source-breakdown and workspace/conversation rows.
*/
export function createConsumptionBreakdownRowBuilders({
showPopover,
movePopover,
hidePopover,
isHoveredTarget,
onSelectConversation,
}) {
function isNodeInside(root, node) {
if (!root || !node) return false;
if (typeof root.contains === 'function') return root.contains(node);
let cur = node;
while (cur) {
if (cur === root) return true;
cur = cur.parentNode || null;
}
return false;
}
function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) {
zoneEl.addEventListener('mouseenter', (e) => {
if (rowState.hoverPayload) {
showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null);
}
});
zoneEl.addEventListener('mousemove', (e) => {
if (rowState.hoverPayload && isHoveredTarget(zoneEl)) {
movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null);
}
});
zoneEl.addEventListener('mouseleave', () => {
if (isHoveredTarget(zoneEl)) hidePopover();
});
for (const childEl of compatTargets) {
if (!childEl) continue;
childEl.addEventListener('mouseenter', (e) => {
if (rowState.hoverPayload) {
showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null);
}
});
childEl.addEventListener('mousemove', (e) => {
if (rowState.hoverPayload && isHoveredTarget(zoneEl)) {
movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null);
}
});
childEl.addEventListener('mouseleave', (e) => {
const nextEl = e?.relatedTarget || null;
if (isNodeInside(zoneEl, nextEl)) {
return;
}
if (isHoveredTarget(zoneEl)) hidePopover();
});
}
}
function createSourceBreakdownRow() {
const nameTextEl = h('span', { className: 'cons-row-title-text' });
const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]);
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
const rowState = { hoverPayload: null };
const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]);
const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true });
const callsLbl = h('span', { text: t('cons.footCalls') });
const callsVal = h('strong', { className: 'text-mono' });
const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [
barHitEl,
h('div', { className: 'cons-item-foot cons-source-foot' }, [
topModelsEl,
h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]),
]),
]);
attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState);
const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [
h('div', { className: 'panel-header' }, [
nameEl,
h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]),
]),
hoverZoneEl,
]);
return {
el: rowEl,
refs: {
nameEl,
nameTextEl,
pctBadge,
totalTokEl,
costEl,
hoverZoneEl,
barHitEl,
trackEl,
topModelsEl,
callsLbl,
callsVal,
rowState,
},
};
}
function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) {
patchText(refs.callsLbl, t('cons.footCalls'));
const displayLabel = item.label || item.name || '—';
patchText(refs.nameTextEl, displayLabel);
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
const total = Number(item.totalTokens || 0);
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
const scaleRatio =
grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0;
patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true }));
patchText(refs.totalTokEl, formatTokensPrecise(total));
const costVal = Number(item.costUsd || 0);
const callsCount = Number(item.calls || 0);
const isAllUnpriced =
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
const costText = formatUsd(isAllUnpriced ? null : costVal, {
precise: costVal > 0 && costVal < 0.1,
});
patchText(refs.costEl, costText);
patchText(refs.callsVal, String(callsCount));
const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : [];
const partitioned = partitionModelSegments(sourceModels, modelColorMap, {
maxMain: 5,
minSharePct: 1.5,
});
renderSegmentedModelBarAndTopPills(
refs.trackEl,
refs.topModelsEl,
partitioned,
total > 0 ? scaleRatio : 0,
'__source_fallback__'
);
refs.rowState.hoverPayload =
total > 0 || callsCount > 0
? {
title: displayLabel,
calls: callsCount,
totalTokens: total,
costText,
inputTokens: item.inputTokens,
cacheReadTokens: item.cacheReadTokens,
thinkingTokens: item.thinkingTokens,
responseTokens: item.responseTokens,
outputTokens: item.outputTokens,
segments: partitioned,
}
: null;
patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) });
}
function createTopConversationRow() {
const titleTextEl = h('span', { className: 'cons-row-title-text' });
const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true });
const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [
titleTextEl,
wsBadgeEl,
]);
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
const rowState = { cascadeId: '', canJump: false, hoverPayload: null };
const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]);
const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true });
const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true });
const callsLbl = h('span', { text: t('cons.footCalls') });
const callsVal = h('strong', { className: 'text-mono' });
const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [
barHitEl,
h('div', { className: 'cons-item-foot cons-source-foot' }, [
topModelsEl,
fallbackMetaEl,
h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]),
]),
]);
attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState);
const rowEl = h(
'div',
{
className: 'cons-top-conv-row',
onClick: () => {
if (!rowState.canJump || !rowState.cascadeId) return;
hidePopover();
onSelectConversation?.(rowState.cascadeId);
},
},
[
h('div', { className: 'panel-header' }, [
titleEl,
h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]),
]),
hoverZoneEl,
]
);
return {
el: rowEl,
refs: {
rowEl,
titleEl,
titleTextEl,
wsBadgeEl,
pctBadge,
totalTokEl,
costEl,
hoverZoneEl,
barHitEl,
trackEl,
topModelsEl,
fallbackMetaEl,
callsLbl,
callsVal,
rowState,
},
};
}
function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') {
patchText(refs.callsLbl, t('cons.footCalls'));
const isWorkspaceRow = Boolean(item.isWorkspaceRow);
const title = isWorkspaceRow
? item.isUnbound
? t('cons.workspaceUnbound')
: String(item.label || item.workspacePath || '—').trim()
: String(item.title || item.cascadeId || '—').trim();
refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || '');
refs.rowState.canJump =
!isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId);
patchClasses(refs.rowEl, {
'is-jumpable': refs.rowState.canJump,
'cons-workspace-row': isWorkspaceRow,
});
const baseTip =
isWorkspaceRow && item.workspacePath && item.workspacePath !== title
? `${title} (${item.workspacePath})`
: title;
patchAttr(
refs.rowEl,
'title',
refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip
);
patchText(refs.titleTextEl, title);
if (refs.wsBadgeEl) {
const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0;
patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge);
if (showWsBadge) {
patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount }));
}
}
const total = Number(item.totalTokens || 0);
const costVal = Number(item.costUsd || 0);
const callsCount = Number(item.calls || 0);
const isAllUnpriced =
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
const costText = formatUsd(isAllUnpriced ? null : costVal, {
precise: costVal > 0 && costVal < 0.1,
});
const tokBase = Number(bases?.tokens || 0);
const costBase = Number(bases?.cost || 0);
const useCostBasis = sortMode === 'cost' && costBase > 0;
const share = useCostBasis
? +((costVal / costBase) * 100).toFixed(1)
: tokBase > 0
? +((total / tokBase) * 100).toFixed(1)
: 0;
const scaleRatio = useCostBasis
? costVal > 0
? Math.min(1, Math.max(0.01, costVal / costBase))
: 0
: tokBase > 0 && total > 0
? Math.min(1, Math.max(0.01, total / tokBase))
: 0;
patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true }));
if (sortMode === 'tokens') {
patchText(refs.totalTokEl, costText);
patchText(refs.costEl, formatTokensPrecise(total));
} else {
patchText(refs.totalTokEl, formatTokensPrecise(total));
patchText(refs.costEl, costText);
}
patchText(refs.callsVal, String(callsCount));
const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : [];
const partitioned = partitionModelSegments(convModels, modelColorMap, {
maxMain: 5,
minSharePct: 1.5,
});
const topModels = renderSegmentedModelBarAndTopPills(
refs.trackEl,
refs.topModelsEl,
partitioned,
scaleRatio,
'__conv_fallback__'
);
const showFallbackMeta = topModels.length === 0;
patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta);
if (showFallbackMeta) {
const srcLabel = item.sourceName || item.appSource || '';
const cacheLabel = t('cons.topConvCacheMeta', {
pct: formatPctNumber(item.cacheHitPct ?? 0),
});
patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel);
}
refs.rowState.hoverPayload =
partitioned.length > 0 && (total > 0 || callsCount > 0)
? {
title,
calls: callsCount,
totalTokens: total,
costText,
inputTokens: item.inputTokens,
cacheReadTokens: item.cacheReadTokens,
thinkingTokens: item.thinkingTokens,
responseTokens: item.responseTokens,
outputTokens: item.outputTokens,
segments: partitioned,
}
: null;
patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) });
}
return {
createSourceBreakdownRow,
updateSourceBreakdownRow,
createTopConversationRow,
updateTopConversationRow,
};
}
@@ -244,21 +244,24 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
patchText(refs.title5h, `5h (${poolLabel})`);
const c5h = poolData?.cycle5h;
const est = poolData?.rateEstimate;
if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) {
const tok5h = formatTokens(c5h.tokens || 0);
const cost5h = formatUsd(c5h.costUsd || 0);
const calls5h = Number(c5h.calls || 0);
const full5hRef = formatPoolFullCapRef(est?.eqFull5hUsd, est?.eqFull5hTokens);
const baseTip5h = t('quota.cycle5hTitle', {
pool: poolLabel,
tok: tok5h,
cost: cost5h,
calls: calls5h,
});
refs.usage5h.hidden = false;
patchText(refs.usage5h, `· ${tok5h} (${cost5h})`);
patchAttr(
refs.left5h,
'title',
t('quota.cycle5hTitle', {
pool: poolLabel,
tok: tok5h,
cost: cost5h,
calls: calls5h,
})
full5hRef ? `${baseTip5h} · ${t('quota.cycleFullSuffix', { full: full5hRef })}` : baseTip5h
);
} else {
refs.usage5h.hidden = true;
@@ -291,19 +294,23 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
const tokWk = formatTokens(cWk.tokens || 0);
const costWk = formatUsd(cWk.costUsd || 0);
const callsWk = Number(cWk.calls || 0);
const fullWkRef = !useCustomWeekly
? formatPoolFullCapRef(est?.eqFullWeeklyUsd, est?.eqFullWeeklyTokens)
: '';
const baseTipWk = useCustomWeekly
? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk })
: t('quota.cycleWkPoolTitle', {
pool: poolLabel,
tok: tokWk,
cost: costWk,
calls: callsWk,
});
refs.usageWk.hidden = false;
patchText(refs.usageWk, `· ${tokWk} (${costWk})`);
patchAttr(
refs.leftWk,
'title',
useCustomWeekly
? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk })
: t('quota.cycleWkPoolTitle', {
pool: poolLabel,
tok: tokWk,
cost: costWk,
calls: callsWk,
})
fullWkRef ? `${baseTipWk} · ${t('quota.cycleFullSuffix', { full: fullWkRef })}` : baseTipWk
);
} else {
refs.usageWk.hidden = true;
@@ -328,8 +335,9 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) {
export function quotaPoolRowSig(item, idx) {
const c5h = item.poolData?.cycle5h;
const cWk = item.poolData?.cycleWeekly;
const est = item.poolData?.rateEstimate;
const fw = item.fallbackWeekly;
return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`;
return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${est?.eqFull5hUsd}:${est?.eqFull5hTokens}:${est?.eqFullWeeklyUsd}:${est?.eqFullWeeklyTokens}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`;
}
/**
@@ -405,6 +413,17 @@ function formatRateEqUsd(val) {
return `$${Number(num.toFixed(1))}`;
}
function formatPoolFullCapRef(eqUsd, eqTok) {
const usdNum = Number(eqUsd);
if (!Number.isFinite(usdNum) || usdNum <= 0) return '';
const usdStr = formatRateEqUsd(usdNum);
const tokNum = Number(eqTok);
if (Number.isFinite(tokNum) && tokNum > 0) {
return `${usdStr} (${formatTokens(tokNum)})`;
}
return usdStr;
}
function formatRatePerUsdValue(rate) {
const num = Number(rate);
if (!Number.isFinite(num) || num <= 0) return '--';
@@ -426,7 +445,11 @@ function createRateModelCard({
rateWeeklyPctPerUsd = null,
eqFull5hUsd = null,
eqFullWeeklyUsd = null,
eqFull5hTokens = null,
eqFullWeeklyTokens = null,
samples = 0,
source = null,
isPreliminary = false,
}) {
const leftNodes = [
h('span', {
@@ -455,32 +478,50 @@ function createRateModelCard({
})
);
}
if (Number(samples) > 0) {
if (isPreliminary) {
subParts.push(
source === 'anchor_slope' ? t('quota.ratePopPrelimSlope') : t('quota.ratePopPrelimCycle')
);
} else if (Number(samples) > 0) {
subParts.push(t('quota.ratePopSamples', { n: Number(samples) }));
}
const eqCells = [];
if (eqFull5hUsd != null) {
eqCells.push(
h('div', { className: 'quota-rate-eq-cell' }, [
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }),
const cell5hChildren = [
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }),
h('span', {
className: 'quota-rate-eq-v text-mono',
text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`,
}),
];
if (Number.isFinite(Number(eqFull5hTokens)) && Number(eqFull5hTokens) > 0) {
cell5hChildren.push(
h('span', {
className: 'quota-rate-eq-v text-mono',
text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`,
}),
])
);
className: 'quota-rate-eq-tok text-mono',
text: `· ${formatTokens(Number(eqFull5hTokens))}`,
})
);
}
eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cell5hChildren));
}
if (eqFullWeeklyUsd != null) {
eqCells.push(
h('div', { className: 'quota-rate-eq-cell' }, [
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }),
const cellWkChildren = [
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }),
h('span', {
className: 'quota-rate-eq-v text-mono',
text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`,
}),
];
if (Number.isFinite(Number(eqFullWeeklyTokens)) && Number(eqFullWeeklyTokens) > 0) {
cellWkChildren.push(
h('span', {
className: 'quota-rate-eq-v text-mono',
text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`,
}),
])
);
className: 'quota-rate-eq-tok text-mono',
text: `· ${formatTokens(Number(eqFullWeeklyTokens))}`,
})
);
}
eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cellWkChildren));
}
const cardChildren = [
@@ -530,10 +571,6 @@ export const QuotaPoolsWidget = defineComponent({
text: t('quota.ratePopAccountCurrent'),
});
const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' });
const ratePopNoteEl = h('div', {
className: 'quota-rate-pop-note',
text: t('quota.ratePopNote'),
});
const ratePopoverEl = h(
'div',
{
@@ -544,7 +581,6 @@ export const QuotaPoolsWidget = defineComponent({
[
h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]),
ratePopBodyEl,
ratePopNoteEl,
]
);
ratePopoverEl.hidden = true;
@@ -622,7 +658,6 @@ export const QuotaPoolsWidget = defineComponent({
lastRatePopSig = sig;
patchText(ratePopTitleEl, t('quota.ratePopTitle'));
patchText(ratePopNoteEl, t('quota.ratePopNote'));
patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria'));
const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || '');
@@ -648,41 +683,114 @@ export const QuotaPoolsWidget = defineComponent({
const hasPoolFallback =
models.length === 0 &&
(Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd));
if (models.length === 0 && !hasPoolFallback) continue;
const ext = est.externalUsage && est.externalUsage.detected ? est.externalUsage : null;
if (models.length === 0 && !hasPoolFallback && !ext) continue;
const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool';
const fallbackPrimaryIs5h = est.rate5hPctPerUsd != null;
const anyModelHasWeekly = models.some((m) => m?.eqFullWeeklyUsd != null);
const needsWeeklyFallbackRow =
models.length > 0 &&
!anyModelHasWeekly &&
Number.isFinite(est.rateWeeklyPctPerUsd) &&
est.eqFullWeeklyUsd != null;
const rows =
models.length > 0
? models.map((item) =>
createRateModelCard({
name: item.model,
multiplier: item.multiplier,
rate5hPctPerUsd: item.rate5hPctPerUsd,
rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd,
eqFull5hUsd: item.eqFull5hUsd,
eqFullWeeklyUsd: item.eqFullWeeklyUsd,
samples: item.samples,
})
)
: [
createRateModelCard({
name: t('quota.ratePopPoolFallback'),
isMutedName: true,
isFallback: true,
rate5hPctPerUsd: est.rate5hPctPerUsd,
rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd,
eqFull5hUsd: est.eqFull5hUsd,
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
}),
];
? [
...models.map((item) =>
createRateModelCard({
name: item.model,
multiplier: item.multiplier,
rate5hPctPerUsd: item.rate5hPctPerUsd,
rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd,
eqFull5hUsd: item.eqFull5hUsd,
eqFullWeeklyUsd: item.eqFullWeeklyUsd,
eqFull5hTokens: item.eqFull5hTokens,
eqFullWeeklyTokens: item.eqFullWeeklyTokens,
samples: item.samples,
})
),
...(needsWeeklyFallbackRow
? [
createRateModelCard({
name: t('quota.ratePopPoolFallback'),
isMutedName: true,
isFallback: true,
rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd,
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
eqFullWeeklyTokens: est.eqFullWeeklyTokens,
samples: Number(est.samplesWeekly) || 0,
source: est.sourceWeekly || null,
isPreliminary: Boolean(est.isPreliminaryWeekly),
}),
]
: []),
]
: hasPoolFallback
? [
createRateModelCard({
name: t('quota.ratePopPoolFallback'),
isMutedName: true,
isFallback: true,
rate5hPctPerUsd: est.rate5hPctPerUsd,
rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd,
eqFull5hUsd: est.eqFull5hUsd,
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
eqFull5hTokens: est.eqFull5hTokens,
eqFullWeeklyTokens: est.eqFullWeeklyTokens,
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
source: fallbackPrimaryIs5h ? est.source5h || null : est.sourceWeekly || null,
isPreliminary: fallbackPrimaryIs5h
? Boolean(est.isPreliminary5h)
: Boolean(est.isPreliminaryWeekly),
}),
]
: [];
populatedGroups.push(
h('div', { className: 'quota-rate-pool-group' }, [
h('div', { className: 'quota-rate-pool-label', text: poolLabel }),
h('div', { className: 'quota-rate-model-list' }, rows),
])
);
const headChildren = [h('div', { className: 'quota-rate-pool-label', text: poolLabel })];
if (ext?.activeRecently) {
headChildren.push(
h('span', {
className: 'quota-rate-shared-badge',
text: t('quota.ratePopSharedBadge'),
title: t('quota.ratePopSharedBadgeTip'),
})
);
}
const groupChildren = [h('div', { className: 'quota-rate-pool-head' }, headChildren)];
if (rows.length > 0) {
groupChildren.push(h('div', { className: 'quota-rate-model-list' }, rows));
} else {
groupChildren.push(
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
);
}
if (ext) {
const extParts = [];
if (Number(ext.used5hPct) >= 0.1) {
extParts.push(
t('quota.ratePopExt5h', { pct: formatPctNumber(Number(ext.used5hPct)) })
);
}
if (Number(ext.usedWeeklyPct) >= 0.1) {
extParts.push(
t('quota.ratePopExtWk', { pct: formatPctNumber(Number(ext.usedWeeklyPct)) })
);
}
const extText =
extParts.length > 0
? t('quota.ratePopExternalDetail', { detail: extParts.join(' · ') })
: t('quota.ratePopExternalBaseline');
groupChildren.push(
h('div', {
className: `quota-rate-ext-banner${ext.activeRecently ? ' is-active' : ''}`,
text: extText,
})
);
}
populatedGroups.push(h('div', { className: 'quota-rate-pool-group' }, groupChildren));
}
if (populatedGroups.length === 0) {
@@ -17,6 +17,8 @@ import {
buildStepAnomalyDiagnostic,
buildStepCompactionDiagnostic,
buildStepTimingDiagnostic,
formatMetric,
formatUsd,
hasStepTimingData,
resolveModelDisplayInfo,
speedReasonText,
@@ -55,24 +57,44 @@ const SIZER_ROW_KEY = '__vsizer__';
const SPACER_TOP_KEY = '__vspacer_top__';
const SPACER_BOTTOM_KEY = '__vspacer_bottom__';
function estTokenChars(val) {
const n = Math.max(0, Number(val || 0));
if (n >= 1_000_000) return n >= 10_000_000 ? 6 : 5;
if (n >= 100_000) return 6;
if (n >= 10_000) return 5;
if (n >= 1_000) return 4;
if (n >= 100) return 3;
if (n >= 10) return 2;
return 1;
function estProportionalTextWidth(text) {
const s = String(text || '');
let w = 0;
for (let i = 0; i < s.length; i++) {
const code = s.charCodeAt(i);
if (code > 0x2e7f) {
w += 1.8;
} else if (
code === 105 || code === 108 || code === 73 || code === 116 || code === 102 ||
code === 114 || code === 46 || code === 44 || code === 58 || code === 59 ||
code === 45 || code === 47 || code === 32
) {
w += 0.55;
} else if (
code === 109 || code === 119 || code === 77 || code === 87 || code === 71 ||
code === 79 || code === 81 || code === 67
) {
w += 1.32;
} else {
w += 1.0;
}
}
return w;
}
function estCostChars(val) {
const n = Number(val);
if (!Number.isFinite(n) || n <= 0) return 1;
if (n >= 100) return 7;
if (n >= 10) return 6;
if (n >= 0.01) return 5;
return 7;
function estTokenChars(val) {
const n = Math.max(0, Number(val || 0));
if (n >= 1_000_000) return n >= 10_000_000 ? 6.4 : 5.6;
if (n >= 100_000) return 6.0;
if (n >= 10_000) return 5.0;
if (n >= 1_000) return 4.1;
if (n >= 100) return 3.0;
if (n >= 10) return 2.0;
return 1.0;
}
function estCostWidth(st) {
return estProportionalTextWidth(formatUsd(st?.costUsd, { precise: true }));
}
function estSegmentChars(seg, st) {
@@ -168,19 +190,27 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
let bestCostObj = firstStep;
let bestBadgeText = '';
let bestBadgeWidth = -1;
let bestBadgeClass = '';
let hasBoldFirstCol = false;
const badgeCandidates = cellCtx?.showAgentBadge ? new Set() : null;
for (let i = 0; i < tableSteps.length; i++) {
const st = tableSteps[i];
if (!st || typeof st !== 'object') continue;
if (!hasBoldFirstCol && (isCompactionStepItem(st) || Number(st?.anomaly?.count) > 0)) {
hasBoldFirstCol = true;
}
if (badgeCandidates) {
const bKey = `${st.agentKind || ''}|${st.isSubagent ? 1 : 0}|${st.isSideQuestion ? 1 : 0}|${st.agentOrdinal || 0}|${st.sideIndex || 0}|${st.agentIndex || 0}|${st.agentBadge || ''}`;
if (!badgeCandidates.has(bKey)) {
badgeCandidates.add(bKey);
const text = resolveBadgeTextForStep(st);
if (text.length > bestBadgeText.length) {
const bw = estProportionalTextWidth(text);
if (bw > bestBadgeWidth) {
bestBadgeWidth = bw;
bestBadgeText = text;
bestBadgeClass = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
}
@@ -224,17 +254,23 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
if (needTtft) {
const v = Number(st.ttftSec);
if (Number.isFinite(v) && v > maxTtftVal) {
maxTtftVal = v;
bestTtftObj = st;
if (Number.isFinite(v) && v >= 0) {
const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v;
if (score > maxTtftVal) {
maxTtftVal = score;
bestTtftObj = st;
}
}
}
if (needDuration) {
const v = Number(st.totalDurationSec ?? st.streamDurationSec);
if (Number.isFinite(v) && v > maxDurVal) {
maxDurVal = v;
bestDurObj = st;
if (Number.isFinite(v) && v >= 0) {
const score = estProportionalTextWidth(formatMetric(v, 's')) * 1e6 + v;
if (score > maxDurVal) {
maxDurVal = score;
bestDurObj = st;
}
}
}
@@ -320,7 +356,7 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
if (needCost) {
const c = Number(st.costUsd);
const score = estCostChars(c) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0);
const score = estCostWidth(st) * 1e6 + (Number.isFinite(c) && c > 0 ? c : 0);
if (score > bestCostScore) {
bestCostScore = score;
bestCostObj = st;
@@ -331,13 +367,13 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
if (needStep) colSteps.step = bestStepObj;
if (needTime) colSteps.time = bestTimeObj || firstStep;
if (needModel && modelCandidates) {
let bestModelLen = -1;
let bestModelWidth = -1;
let bestModelObj = firstStep;
for (const cand of modelCandidates.values()) {
const disp = resolveModelDisplayInfo(cand, cellCtx?.displaySettings, { fallback: '—' });
const len = disp.baseText?.length || 0;
if (len > bestModelLen) {
bestModelLen = len;
const w = estProportionalTextWidth(disp.baseText || '');
if (w > bestModelWidth) {
bestModelWidth = w;
bestModelObj = cand;
}
}
@@ -345,19 +381,20 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
}
if (needTps) {
let longestReasonKey = null;
let longestReasonLen = 0;
let longestReasonWidth = 0;
if (reasonCandidates) {
for (const rk of reasonCandidates) {
const txt = speedReasonText(rk);
if (txt && txt.length > longestReasonLen) {
longestReasonLen = txt.length;
const w = txt ? estProportionalTextWidth(txt) : 0;
if (w > longestReasonWidth) {
longestReasonWidth = w;
longestReasonKey = rk;
}
}
}
colSteps.tps = {
...(maxTpsObj || firstStep),
tokPerSec: maxTpsVal > 0 ? maxTpsVal : firstStep.tokPerSec,
tokPerSec: maxTpsObj ? maxTpsObj.tokPerSec : firstStep.tokPerSec,
selectedSpeedReason: longestReasonKey,
};
}
@@ -380,7 +417,8 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
colSteps,
badgeText: bestBadgeText,
badgeClass: bestBadgeClass,
sig: `sizer:${bestBadgeText}:${sigParts.join('|')}`,
hasBoldFirstCol,
sig: `sizer:${bestBadgeText}:${hasBoldFirstCol ? 1 : 0}:${sigParts.join('|')}`,
};
}
@@ -648,8 +686,66 @@ export const StepTableWidget = defineComponent({
let lastFontScale = 1;
let calibratedSingleRowH = 0;
let calibratedReasonRowH = 0;
let lockedColKey = '';
let lockedPaneWidth = 0;
const rowPool = [];
function computeColLockKey(ds) {
if (!ds?.isVirtualized) return '';
return `${ds.locale}:${ds.colOrderSig}:${lastFontScale}:${ds.showAgentBadge ? 1 : 0}:${ds.railActive ? 1 : 0}:${ds.sortKey || ''}:${ds.sortDir || ''}:${ds.sizerSpec?.sig || ''}`;
}
function unlockColumnWidths() {
lockedColKey = '';
lockedPaneWidth = 0;
patchClasses(stepsTableEl, { 'is-cols-locked': false });
if (stepsTableEl.style) {
stepsTableEl.style.minWidth = '';
}
const ths = stepsTheadRow.children || [];
for (let i = 0; i < ths.length; i++) {
if (ths[i]?.style) ths[i].style.width = '';
}
}
function lockColumnWidthsIfNeeded() {
if (!activeDataset?.isVirtualized) return;
const paneW = Number(stepsTablePane.clientWidth || 0);
if (paneW <= 0) return;
const nextKey = computeColLockKey(activeDataset);
if (lockedColKey === nextKey && Math.abs(paneW - lockedPaneWidth) < 1) return;
const ths = stepsTheadRow.children || [];
const colCount = activeDataset.colKeys.length;
if (ths.length !== colCount) return;
// Release fixed layout momentarily if stale so browser resolves natural widths from sizer + header
if (stepsTableEl.classList?.contains('is-cols-locked')) {
unlockColumnWidths();
}
const widths = [];
for (let i = 0; i < colCount; i++) {
const w = Number(ths[i]?.getBoundingClientRect?.()?.width || 0);
if (!Number.isFinite(w) || w <= 0) return;
widths.push(w);
}
const tableW = Number(stepsTableEl.getBoundingClientRect?.()?.width || 0);
if (!Number.isFinite(tableW) || tableW <= 0) return;
for (let i = 0; i < colCount; i++) {
if (ths[i]?.style) {
ths[i].style.width = `${widths[i].toFixed(2)}px`;
}
}
if (stepsTableEl.style) {
stepsTableEl.style.minWidth = tableW > paneW + 0.5 ? `${tableW.toFixed(2)}px` : '';
}
patchClasses(stepsTableEl, { 'is-cols-locked': true });
lockedColKey = nextKey;
lockedPaneWidth = paneW;
}
function readUiFontScale() {
try {
if (typeof getComputedStyle === 'function') {
@@ -712,6 +808,7 @@ export const StepTableWidget = defineComponent({
lastFontScale = nextScale;
calibratedSingleRowH = 0;
calibratedReasonRowH = 0;
unlockColumnWidths();
if (activeDataset?.isVirtualized) {
const rebuilt = buildRowTops(activeDataset.tableSteps.length, activeDataset.hasReasonFlags);
activeDataset.rowTops = rebuilt.rowTops;
@@ -860,6 +957,7 @@ export const StepTableWidget = defineComponent({
calibrateRafId = 0;
if (!activeDataset?.isVirtualized) return;
if (Number(stepsTablePane.clientHeight || 0) <= 0) return;
lockColumnWidthsIfNeeded();
const needSingle = calibratedSingleRowH <= 0;
const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason;
if (!needSingle && !needReason) return;
@@ -952,7 +1050,12 @@ export const StepTableWidget = defineComponent({
if (!activeDataset?.isVirtualized) return;
const needSingle = calibratedSingleRowH <= 0;
const needReason = calibratedReasonRowH <= 0 && activeDataset.hasAnyReason;
if (!needSingle && !needReason) return;
const paneW = Number(stepsTablePane.clientWidth || 0);
const needColLock =
!lockedColKey ||
lockedColKey !== computeColLockKey(activeDataset) ||
(paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1);
if (!needSingle && !needReason && !needColLock) return;
if (calibrateRafId) return;
if (typeof requestAnimationFrame === 'function') {
calibrateRafId = requestAnimationFrame(calibrateRowHeights);
@@ -1185,6 +1288,7 @@ export const StepTableWidget = defineComponent({
updateRow: (refs, item, _idx, tr) => {
if (item.isSizer) {
const spec = item.sizerSpec;
patchClasses(tr, { 'has-bold-first': Boolean(spec.hasBoldFirstCol) });
if (refs.colOrderSig !== colOrderSig) {
for (const [oldColKey, entry] of refs.cellMap) {
if (!wantedSet.has(oldColKey)) {
@@ -1517,6 +1621,10 @@ export const StepTableWidget = defineComponent({
function refreshViewport() {
if (!activeDataset?.isVirtualized) return;
const scaleChanged = syncFontScaleIfChanged();
const paneW = Number(stepsTablePane.clientWidth || 0);
if (lockedColKey && paneW > 0 && Math.abs(paneW - lockedPaneWidth) >= 1) {
unlockColumnWidths();
}
renderCurrentWindow({ force: scaleChanged, enteringRowKeys: null });
scheduleCalibrateRowHeights();
}
@@ -1740,8 +1848,13 @@ export const StepTableWidget = defineComponent({
totalBodyH,
sizerSpec,
effectiveScopes,
sortKey: normSortKey,
sortDir: normSortDir,
formattedPrompts: new Map(),
};
if (!isVirtualized || computeColLockKey(activeDataset) !== lockedColKey) {
unlockColumnWidths();
}
renderedSliceStart = -1;
renderedSliceEnd = -1;
renderedTopSpacerH = -1;
+19 -19
View File
@@ -46,7 +46,7 @@ function getPickerTypesForFilename(filename, mimeType) {
* @returns {Promise<boolean>}
*/
export async function revealExportedFile(filePath) {
if (!filePath) return false;
if (!filePath || !isHostEmbeddedWebview()) return false;
try {
const res = await callSidecarApi('/api/reveal-file', {
method: 'POST',
@@ -118,25 +118,25 @@ async function runExportPipelineWithFeedback({
backendPayload,
writablePayload,
}) {
const { res: localRes } = await requestLocalBackendExport(backendPayload);
if (localRes && localRes.ok && localRes.filePath) {
const savedPath = String(localRes.filePath);
const savedName = String(localRes.fileName || safeName);
showUiToast({
message: t('export.savedLocal', { file: savedName }),
detail: savedPath,
actionLabel: t('export.openFolder'),
onAction: () => {
void revealExportedFile(savedPath);
},
tone: 'ok',
durationMs: 7000,
});
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
}
// 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
if (isHostEmbeddedWebview()) {
const { res: localRes } = await requestLocalBackendExport(backendPayload);
if (localRes && localRes.ok && localRes.filePath) {
const savedPath = String(localRes.filePath);
const savedName = String(localRes.fileName || safeName);
showUiToast({
message: t('export.savedLocal', { file: savedName }),
detail: savedPath,
actionLabel: t('export.openFolder'),
onAction: () => {
void revealExportedFile(savedPath);
},
tone: 'ok',
durationMs: 7000,
});
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
}
// 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
showUiToast({
message: t('export.failed'),
detail: t('export.hostUnavailable'),
+80 -2
View File
@@ -21,6 +21,14 @@ const EN_MONTH_SHORT = Object.freeze([
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
]);
const ZH_WEEKDAY_SHORT = Object.freeze([
'周日', '周一', '周二', '周三', '周四', '周五', '周六',
]);
const EN_WEEKDAY_SHORT = Object.freeze([
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat',
]);
export function formatMetric(value, unit = '') {
if (!Number.isFinite(value)) return '—';
const numStr = Math.abs(value) >= 100 ? String(Math.round(value)) : value.toFixed(1);
@@ -96,20 +104,90 @@ export function formatCnyApprox(usdAmount, rate = 7.2) {
export function formatDateSpanBadge(startMs, endMs) {
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date();
const sameYear = s.getFullYear() === e.getFullYear();
const sameMonth = sameYear && s.getMonth() === e.getMonth();
const sameDay = sameMonth && s.getDate() === e.getDate();
if (isEnglishLocale()) {
const sMon = EN_MONTH_SHORT[s.getMonth()] || '';
const eMon = EN_MONTH_SHORT[e.getMonth()] || '';
if (s.getFullYear() !== e.getFullYear()) {
if (!sameYear) {
return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`;
}
if (sameDay) {
return `${sMon} ${s.getDate()}`;
}
if (sameMonth) {
return `${sMon} ${s.getDate()} ~ ${e.getDate()}`;
}
return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`;
}
if (s.getFullYear() !== e.getFullYear()) {
if (!sameYear) {
return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`;
}
if (sameDay) {
return `${s.getMonth() + 1}月${s.getDate()}日`;
}
if (sameMonth) {
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getDate()}日`;
}
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
}
export function formatTrendSlotFullLabel(slot, { locale, showFullYear = false } = {}) {
const en =
typeof locale === 'string' && locale.trim()
? locale.trim().toLowerCase().startsWith('en')
: isEnglishLocale();
const sMs = Number(slot?.startMs);
if (Number.isFinite(sMs) && sMs > 0) {
const sd = new Date(sMs);
const pad2 = (n) => String(n).padStart(2, '0');
const rawFull = String(slot?.fullLabel || '');
const includeYear = Boolean(
showFullYear || /^\d{4}年/.test(rawFull) || sd.getFullYear() !== new Date().getFullYear()
);
const gran = String(slot?.granularity || '').toLowerCase();
const isSubDay =
gran === 'minute' ||
gran === 'hour' ||
(!gran && Number(slot?.endMs) > sMs && Number(slot.endMs) - sMs <= 3600_000 * 2);
if (isSubDay) {
const eMs = Number(slot?.endMs);
const ed = Number.isFinite(eMs) && eMs > 0 ? new Date(eMs) : new Date(sMs + 3600_000);
const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`;
const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`;
if (en) {
const mon = EN_MONTH_SHORT[sd.getMonth()] || '';
return includeYear
? `${mon} ${sd.getDate()}, ${sd.getFullYear()}, ${hh} - ${endHh}`
: `${mon} ${sd.getDate()}, ${hh} - ${endHh}`;
}
const yearPrefix = includeYear ? `${sd.getFullYear()}年` : '';
return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`;
}
if (en) {
const mon = EN_MONTH_SHORT[sd.getMonth()] || '';
const wday = EN_WEEKDAY_SHORT[sd.getDay()] || '';
return includeYear
? `${mon} ${sd.getDate()}, ${sd.getFullYear()} (${wday})`
: `${mon} ${sd.getDate()} (${wday})`;
}
const yearPrefix = includeYear ? `${sd.getFullYear()}年` : '';
return `${yearPrefix}${sd.getMonth() + 1}月${sd.getDate()}日 (${ZH_WEEKDAY_SHORT[sd.getDay()] || ''})`;
}
const rawFull = String(slot?.fullLabel || '').trim();
const rawShort = String(slot?.label || '').trim();
if (en && rawFull && /[\u4e00-\u9fff]/.test(rawFull)) {
return rawShort || rawFull;
}
return rawFull || rawShort;
}
export function formatUsd(amount, { precise = false } = {}) {
if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending');
const val = Number(amount || 0);
+80
View File
@@ -0,0 +1,80 @@
/**
* @fileoverview Decoupled HTTP/CDP client for `/api/host-i18n`.
* Completely independent from `telemetryStore.js`.
*/
import {
HOST_I18N_API_PATH,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../shared/host-i18n-protocol.mjs';
import { callSidecarApi } from './httpClient.js';
export async function fetchHostI18nStatus() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'GET',
abortKey: 'host-i18n-get',
cdpTimeoutMs: 12000,
});
}
export async function refreshHostI18nManifest() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: { action: 'refresh_manifest' },
cdpTimeoutMs: 18000,
});
}
export async function selectHostI18nLanguage(locale, depth) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'select',
locale: normalizeHostI18nLocale(locale),
...(depth !== undefined ? { depth: normalizeHostI18nDepth(depth) } : {}),
},
cdpTimeoutMs: 22000,
});
}
export async function updateHostI18nDepth(depth) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'set_depth',
depth: normalizeHostI18nDepth(depth),
},
cdpTimeoutMs: 10000,
});
}
export async function installOrUpdateHostI18nPack(locale) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'update',
locale: normalizeHostI18nLocale(locale),
},
cdpTimeoutMs: 22000,
});
}
export async function removeHostI18nPack(locale) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'remove',
locale: normalizeHostI18nLocale(locale),
},
cdpTimeoutMs: 10000,
});
}
export async function collectHostI18nUntranslated() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: { action: 'collect_untranslated' },
cdpTimeoutMs: 15000,
});
}
+48 -16
View File
@@ -11,6 +11,7 @@ import {
formatPctNumber,
formatSpeedMetric,
formatTokensPrecise,
formatTrendSlotFullLabel,
formatUsd,
mergeModelsByDisplayName,
resolveModelDisplayInfo,
@@ -20,8 +21,10 @@ import { buildXlsxWorkbookBytes } from './xlsxBuilder.js';
const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/;
const RANGE_LABELS_ZH = Object.freeze({
'5h': '近5小时',
today: '今日',
'24h': '近24小时',
week: '本周',
'7d': '近7天',
'14d': '近14天',
'30d': '近30天',
@@ -31,8 +34,10 @@ const RANGE_LABELS_ZH = Object.freeze({
});
const RANGE_LABELS_EN = Object.freeze({
'5h': 'Last 5 Hours',
today: 'Today',
'24h': 'Last 24 Hours',
week: 'This Week',
'7d': 'Last 7 Days',
'14d': 'Last 14 Days',
'30d': 'Last 30 Days',
@@ -94,10 +99,18 @@ function formatExportDate(ms) {
function resolveLocalizedRangeLabel(range, en) {
const r = range || {};
const key = String(r.key || '').trim().toLowerCase();
const poolSuffix =
key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : '';
if (en) {
return RANGE_LABELS_EN[key] || r.label || key || 'All Time';
const baseEn =
key === 'cycle' && r.isFallbackWeek
? 'This Week'
: RANGE_LABELS_EN[key] || r.label || key || 'All Time';
return `${baseEn}${poolSuffix}`;
}
return r.label || RANGE_LABELS_ZH[key] || key || '全部时间';
if (r.label) return r.label;
const baseZh = RANGE_LABELS_ZH[key] || key || '全部时间';
return `${baseZh}${poolSuffix}`;
}
function resolveRangeSpanNote(range) {
@@ -209,6 +222,7 @@ function summarizeStepsForExport(list, displaySettings) {
const validTps =
!st.isCompactionStep &&
!st.isImageGenStep &&
outTok >= 50 &&
!st.selectedSpeedReason &&
Number.isFinite(Number(st.tokPerSec)) &&
@@ -219,7 +233,11 @@ function summarizeStepsForExport(list, displaySettings) {
: outTok / Number(st.tokPerSec)
: 0;
const validTtft =
!st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0;
!st.isCompactionStep &&
!st.isImageGenStep &&
st.ttftSec != null &&
Number.isFinite(Number(st.ttftSec)) &&
Number(st.ttftSec) >= 0;
if (validTps && stepSpeedSec > 0) {
tpsTokSum += outTok;
tpsSecSum += stepSpeedSec;
@@ -550,9 +568,13 @@ export function buildStepsXlsx(
? en
? 'Compaction'
: '自动压缩'
: en
? 'Normal'
: '常规';
: st.isImageGenStep
? en
? 'Image Gen'
: '生成图片'
: en
? 'Normal'
: '常规';
const tone = anomCount > 0 ? 'danger' : st.isCompactionStep ? 'info' : '';
stepRows.push({
@@ -824,8 +846,10 @@ export function buildStepsMarkdownReport(
export function buildConsumptionCsv(
consumption,
modelBreakdown = [],
{ displaySettings = {}, includeBom = true } = {}
{ displaySettings = {}, includeBom = true, locale } = {}
) {
const en = resolveExportEnglish(locale);
const effectiveLocale = en ? 'en-US' : 'zh-CN';
const cons = consumption || {};
const acc = cons.account || {};
const range = cons.selectedRange || {};
@@ -851,7 +875,7 @@ export function buildConsumptionCsv(
]),
csvRow([
'summary',
range.label || range.key || 'all',
resolveLocalizedRangeLabel(range, en),
Number(acc.calls || 0),
Number(acc.inputTokens || 0),
Number(acc.cacheReadTokens || 0),
@@ -919,7 +943,7 @@ export function buildConsumptionCsv(
rows.push(
csvRow([
'trend',
slot.fullLabel || slot.label || '',
formatTrendSlotFullLabel(slot, { locale: effectiveLocale }) || slot.label || '',
Number(slot.calls || 0),
Number(slot.inputTokens || 0),
Number(slot.cacheReadTokens || 0),
@@ -1307,8 +1331,11 @@ export function buildConsumptionXlsx(
let tTot = 0;
let tCost = 0;
const trendRows = trend.map((slot) => {
const isMinute = slot.granularity === 'minute';
const isHourly =
slot.granularity === 'hour' || String(slot.label || '').includes(':');
isMinute ||
slot.granularity === 'hour' ||
String(slot.label || '').includes(':');
const calls = Math.max(0, Number(slot.calls || 0));
const inTok = Math.max(0, Number(slot.inputTokens || 0));
const cacheTok = Math.max(0, Number(slot.cacheReadTokens || 0));
@@ -1321,13 +1348,18 @@ export function buildConsumptionXlsx(
tOut += outTok;
tTot += totTok;
tCost += cost;
const granLabel = isHourly
const stepMins = Math.max(1, Number(slot.stepMinutes) || 5);
const granLabel = isMinute
? en
? 'Hourly'
: '按小时'
: en
? 'Daily'
: '按天';
? `${stepMins}m`
: `按 ${stepMins} 分钟`
: isHourly
? en
? 'Hourly'
: '按小时'
: en
? 'Daily'
: '按天';
return [
formatTrendWindowLabel(slot, isHourly),
granLabel,
@@ -4,6 +4,7 @@
*/
import {
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalQuotaReservation,
@@ -212,6 +213,7 @@ const PORTABLE_SETTING_DESCRIPTORS = Object.freeze([
normField('stepTokenComboFormat', normalizeStepTokenComboFormat),
arrayField('stepTableColumns', normalizeStepTableColumns),
normField('experimentalQuotaReservation', normalizeExperimentalQuotaReservation),
normField('accountQuotaRefreshMinutes', normalizeAccountQuotaRefreshMinutes),
]);
/**
+24 -4
View File
@@ -8,7 +8,10 @@
* - 全部字符串采用 `inlineStr` 并剔除 XML 1.0 非法控制符,天然免疫公式注入及 Excel 损坏警告。
*/
export const MAX_EXCEL_CELL_CHARS = 32767;
const INVALID_XML_CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g;
const LONE_SURROGATE_RE =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
const INVALID_SHEET_NAME_RE = /[\\/?*[\]:]/g;
// --- 样式索引常量(对应下方 STYLES_XML 中的 cellXfs 顺序) ---
@@ -204,9 +207,24 @@ function buildZipStoreArchive(entries) {
return archive;
}
function escapeXmlText(val) {
return String(val ?? '')
function sanitizeExcelCellText(val) {
const clean = String(val ?? '')
.replace(INVALID_XML_CTRL_RE, '')
.replace(LONE_SURROGATE_RE, '\uFFFD');
if (clean.length <= MAX_EXCEL_CELL_CHARS) {
return clean;
}
// 桌面版 Excel 单格文本硬上限为 32,767 UTF-16 码元;预留 1 位给省略号并避免劈断代理对
let cut = MAX_EXCEL_CELL_CHARS - 1;
const prevCode = clean.charCodeAt(cut - 1);
if (prevCode >= 0xd800 && prevCode <= 0xdbff) {
cut -= 1;
}
return `${clean.slice(0, cut)}…`;
}
function escapeXmlText(val) {
return sanitizeExcelCellText(val)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
@@ -226,10 +244,12 @@ function columnIndexToLetter(index) {
}
/**
* 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽)。
* 估算文本在 Excel 单元格中的视觉字符宽度(中文/全角约占 2.05 宽,ASCII 约 1.05 宽;
* 列宽上限为 64,因此仅采样前 128 个字符即可达到饱和,避免超长文本全量遍历)。
*/
function measureExcelVisualWidth(str) {
const s = String(str ?? '').replace(/\r?\n/g, ' ');
const raw = String(str ?? '');
const s = (raw.length > 128 ? raw.slice(0, 128) : raw).replace(/\r?\n/g, ' ');
let w = 0;
for (let i = 0; i < s.length; i += 1) {
const code = s.charCodeAt(i);
+151 -8
View File
@@ -12,6 +12,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
// Top Session Header
'header.followLatest': 'Follow Latest Session',
'header.followCurrentWindow': 'Follow Current Window',
'header.autoFollowBadge': 'Auto',
'header.currentWindowNamed': 'Current ({title})',
'header.latestNamed': 'Latest ({title})',
'header.lockedSession': 'Pinned Session ({id})',
@@ -19,6 +21,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
'header.convMetaWithSwarm': 'Main {main} · {swarm} swarm ({total} steps)',
'header.convMetaWithSwarmAndSubs': 'Main {main} · {swarm} swarm · {subs} sub ({total} steps)',
'header.convCompactSubs': '{subs} sub · {total} steps',
'header.convCompactSwarm': '{swarm} swm · {total} steps',
'header.convCompactSwarmAndSubs': '{swarm} swm {subs} sub · {total} steps',
'header.convMetaSteps': '{count} steps',
'header.hasUpdate': 'Update',
'header.upgradeToVer': 'Update v{ver}',
@@ -32,6 +37,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'header.statusQuotaCached': 'Quota Cached',
'header.statusQuotaOffline': 'Quota Offline',
'header.statusLive': 'Monitoring',
'header.scopeAll': 'All Agents',
'header.scopeAllShort': 'All',
'header.searchSessionPlaceholder': 'Search sessions, projects, or ID…',
'select.searchPlaceholder': 'Filter options…',
'select.noMatches': 'No matching items',
@@ -190,6 +197,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls',
'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls',
'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls',
'quota.cycleFullSuffix': 'Full ~{full}',
'quota.footTokensCustom': 'Week Total: {tok} ({cost})',
'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})',
'quota.footCredits': 'AI Credits: {credits}',
@@ -206,8 +214,15 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'quota.ratePopEqWkLabel': 'Weekly full',
'quota.ratePopPerUsd': '{win} {rate}%/$',
'quota.ratePopSamples': '{n} samples',
'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.',
'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.',
'quota.ratePopPrelimSlope': 'slope est.',
'quota.ratePopPrelimCycle': 'cycle est.',
'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).',
'quota.ratePopSharedBadge': 'Shared active',
'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification',
'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)',
'quota.ratePopExternalBaseline': 'Family group / other-device usage detected this cycle; reservations & rates calibrate on local steps only',
'quota.ratePopExt5h': '5h {pct}%',
'quota.ratePopExtWk': 'Weekly {pct}%',
// Live Activity Widget
'live.currentSession': 'Current Session',
@@ -230,6 +245,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
// Consumption View
'cons.rangeCycle': 'Cycle',
'cons.cyclePoolAll': 'All Pools',
'cons.cyclePoolAllShort': 'All',
'cons.cyclePoolAria': 'Filter current cycle by quota pool',
'cons.cyclePoolRemMeta': '{pct} left',
'cons.currentCycle': 'Current Cycle',
'cons.cycleFallbackWeek': 'This Week',
'cons.cycleFallbackWeekTip': 'Official weekly reset time unavailable; using calendar week from Monday',
'cons.rangeToday': 'Today',
'cons.range24h': '24h',
'cons.range7d': '7d',
@@ -254,7 +276,12 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'cons.replyAndThink': 'Think {think} · Reply {resp}',
'cons.trendTitle': 'Usage Trend',
'cons.allTime': 'All Time',
'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details',
'cons.hmModeAria': 'Heatmap view mode',
'cons.hmModeDay': 'Day',
'cons.hmModeWeek': 'Week',
'cons.hmModeMonth': 'Month',
'cons.hmModeAll': 'Total',
'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details',
'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details',
'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details',
'cons.topModels': 'Top Models',
@@ -281,7 +308,6 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'cons.rankTabWorkspacesCount': 'Projects ({count})',
'cons.workspaceUnbound': 'Unbound Workspace',
'cons.workspaceSessions': '{count} sessions',
'cons.workspaceJumpTip': 'Click to inspect latest session in this project',
'cons.exportMenuAria': 'Export and report actions',
'cons.exportXlsx': 'Export Excel (.xlsx)',
'cons.exportXlsxTip': 'Export styled multi-sheet Excel workbook with auto column width and alignment',
@@ -471,26 +497,54 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.account.signedOut': 'Signed out',
'settings.account.unknown': 'Account status unavailable',
'settings.account.email': 'Account email',
'settings.account.googleLogin': 'Sign in with Google',
'settings.account.loginHint': 'Sign in with Google in your browser. The account will appear in this list automatically.',
'settings.account.loginWaiting': 'Choose a Google account and complete authorization in your browser. This list will update automatically.',
'settings.account.loginFinishing': 'Authorization received. Saving the account…',
'settings.account.loginSuccess': 'Signed in. The account has been added.',
'settings.account.loginCancelled': 'Sign-in cancelled.',
'settings.account.loginExpired': 'Sign-in expired. Click Sign in with Google to try again.',
'settings.account.loginDenied': 'Google authorization was cancelled. Try signing in again.',
'settings.account.loginStartFailed': 'Sign-in could not start. Try again.',
'settings.account.loginExchangeFailed': 'Sign-in could not finish. Check your connection and authorize again.',
'settings.account.openLoginPage': 'Reopen Google authorization',
'settings.account.cancelLogin': 'Cancel sign-in',
'settings.account.importExisting': 'Import existing credentials',
'settings.account.credential': 'OAuth credential',
'settings.account.credentialPlaceholder': 'Paste 1// refresh token or OAuth JSON…',
'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.',
'settings.account.save': 'Import credential',
'settings.account.capture': 'Save current credential',
'settings.account.reload': 'Refresh list',
'settings.account.switch': 'Switch',
'settings.account.switch': 'Switch and restart',
'settings.account.switchHint': 'Switching closes and reopens Antigravity App and the IDE sharing its sign-in. Save your work first.',
'settings.account.restarting': 'Restarting Antigravity with the selected account…',
'settings.account.switchStartFailed': 'The account switch could not start. Refresh the list and try again.',
'settings.account.clientCloseFailed': 'Antigravity could not fully exit. The switch is incomplete.',
'settings.account.clientRestartFailed': 'The credential was updated. Open Antigravity manually to finish switching.',
'settings.account.remove': 'Remove',
'settings.account.active': 'In use',
'settings.account.savedBadge': 'Backed up',
'settings.account.written': 'Credential written',
'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.',
'settings.account.savedCredentials': 'Saved credentials',
'settings.account.savedCredentials': 'Saved accounts',
'settings.account.empty': 'No saved credentials.',
'settings.account.loading': 'Loading saved credentials…',
'settings.account.saved': 'Credential saved.',
'settings.account.removed': 'Saved credential removed.',
'settings.account.switched': 'Account switched. Refreshing the current quota.',
'settings.account.switching': 'Replacing the credential and confirming the active account…',
'settings.account.switching': 'Verifying the credential and preparing to restart…',
'settings.account.verifying': 'Verifying the credential owner…',
'settings.account.loadQuota': 'Check quota',
'settings.account.loadingQuota': 'Checking quota for this credential…',
'settings.account.loadingQuota': 'Checking…',
'settings.account.refreshFreqAria': 'Background account quota refresh interval',
'settings.account.refresh10m': '10 min',
'settings.account.refresh30m': '30 min',
'settings.account.refresh1h': '1 hr',
'settings.account.refresh3h': '3 hr',
'settings.account.refresh6h': '6 hr',
'settings.account.refresh12h': '12 hr',
'settings.account.refresh24h': '24 hr',
'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.',
'settings.account.quota': 'Quota remaining by pool',
'settings.account.quota5h': '5 hours {percent}%',
@@ -513,6 +567,49 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.',
'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.',
'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.',
'settings.account.switchConfirm': 'Confirm switch',
'settings.account.removeConfirm': 'Confirm remove',
'settings.account.pwdBtnSet': 'Passphrase',
'settings.account.pwdBtnManage': 'Passphrase',
'settings.account.lockNow': 'Lock',
'settings.account.lockNowTip': 'Lock credential vault now',
'settings.account.unlockBtn': 'Unlock',
'settings.account.unlockPlaceholder': 'Enter passphrase to unlock…',
'settings.account.vaultLockedHint': 'Credential vault is locked. Enter your passphrase to switch accounts, manage credentials, or refresh quotas.',
'settings.account.forgotPwdToggle': 'Forgot?',
'settings.account.resetVaultHint': 'Encrypted backups cannot be recovered without the passphrase (your active IDE sign-in is unaffected). You can clear and reset the vault.',
'settings.account.resetVaultBtn': 'Reset vault',
'settings.account.resetVaultConfirm': 'Confirm reset',
'settings.account.pwdTabChange': 'Change passphrase',
'settings.account.pwdTabDisable': 'Remove passphrase',
'settings.account.pwdCurrentPlaceholder': 'Current passphrase…',
'settings.account.pwdNewPlaceholder': 'New passphrase (4–128 chars)…',
'settings.account.pwdConfirmPlaceholder': 'Confirm passphrase…',
'settings.account.pwdEnableSubmit': 'Enable',
'settings.account.pwdChangeSubmit': 'Update',
'settings.account.pwdDisableSubmit': 'Disable',
'settings.account.pwdSetHint': 'Adds passphrase encryption to all saved refresh tokens. Asked once per session when managing accounts; cannot be recovered if forgotten.',
'settings.account.pwdManageHint': 'Verify your current passphrase to set a new one or return to default OS encryption.',
'settings.account.pwdEnabledToast': 'Passphrase encryption enabled.',
'settings.account.pwdChangedToast': 'Passphrase updated.',
'settings.account.pwdDisabledToast': 'Passphrase protection disabled.',
'settings.account.vaultUnlockedToast': 'Credential vault unlocked.',
'settings.account.vaultLockedToast': 'Credential vault locked.',
'settings.account.vaultResetToast': 'Credential vault cleared and reset.',
'settings.account.vaultLocked': 'Enter your passphrase to unlock the vault first.',
'settings.account.wrongPassword': 'Incorrect passphrase. Try again.',
'settings.account.invalidPassword': 'Passphrase must be 4–128 characters and not blank.',
'settings.account.passwordMismatch': 'Passphrases do not match.',
'settings.account.passwordRateLimited': 'Too many failed attempts. Wait a moment and try again.',
'settings.account.vaultDecryptFailed': 'Vault decryption check failed.',
'settings.account.invalidActionNonce': 'Security token expired. Please try again.',
'settings.account.riskNotAccepted': 'Acknowledge the unofficial feature risk warning first.',
'settings.account.riskBody': 'Google has not authorized importing, storing, or switching Antigravity credentials or polling multi-account quotas in Antigravity App / IDE. Enabling multi-account management may get your Antigravity access, GCP services, or Google account disabled or banned; enabling this feature means you assume all associated risks. Make sure you know what you are doing!',
'settings.account.trendTitle': 'Quota Trend',
'settings.account.trendWinAria': 'Quota window selector',
'settings.account.win5h': '5 Hours',
'settings.account.winWeekly': 'Weekly',
'settings.account.trendEmpty': 'No quota history recorded in the selected time range.',
'settings.subTab.aria': 'Preferences category tabs',
'settings.saving': 'Saving…',
'settings.saved': 'Saved',
@@ -578,6 +675,45 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.gen.updateOffSub': 'Notifications off ({mode})',
'settings.gen.latestSub': 'Up to date ({mode})',
// Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n)
'settings.hostI18n.title': 'Antigravity UI Language',
'settings.hostI18n.langLabel': 'Host Language',
'settings.hostI18n.langOff': 'Original (Off)',
'settings.hostI18n.langHint': 'Downloads built language packs on demand from the repository and applies lossless runtime UI translation without patching app files or chat content',
'settings.hostI18n.optInstalled': 'Installed v{ver}',
'settings.hostI18n.optRemote': 'Download · {size}',
'settings.hostI18n.refreshManifestTip': 'Refresh repository language pack manifest',
'settings.hostI18n.refreshingManifestMsg': 'Refreshing language manifest…',
'settings.hostI18n.manifestSyncedMsg': 'Manifest updated ({count} packs)',
'settings.hostI18n.manifestFailedMsg': 'Failed to fetch language manifest',
'settings.hostI18n.depthLabel': 'Translation Depth',
'settings.hostI18n.depthLight': 'Light',
'settings.hostI18n.depthDeep': 'Deep',
'settings.hostI18n.depthLightHint': 'Light mode keeps common English engineering terms (MCP, Skill, Workspace, Subagent, Swarm, Diff, Terminal) and model names untranslated',
'settings.hostI18n.depthDeepHint': 'Deep mode localizes engineering terms alongside general UI copy while preserving model names and slash commands',
'settings.hostI18n.downloadingMsg': 'Downloading {locale} pack…',
'settings.hostI18n.downloadedAndAppliedMsg': 'Pack verified and applied',
'settings.hostI18n.appliedMsg': 'Language applied live',
'settings.hostI18n.disabledMsg': 'Translation disabled and UI restored',
'settings.hostI18n.depthSwitchedMsg': 'Translation depth switched',
'settings.hostI18n.packUpdatedMsg': 'Language pack updated and reapplied',
'settings.hostI18n.cacheRemovedMsg': 'Local pack cache removed',
'settings.hostI18n.actionFailed': 'Language pack operation failed',
'settings.hostI18n.entriesCount': '{count} entries',
'settings.hostI18n.appliedWindows': '{count} window(s) active',
'settings.hostI18n.updatePackBtn': 'Update to v{ver}',
'settings.hostI18n.redownloadBtn': 'Check Update',
'settings.hostI18n.removeCacheBtn': 'Remove Cache',
'settings.hostI18n.devToolsTitle': 'Missing UI String Collector',
'settings.hostI18n.devToolsHint': 'Scans visible Antigravity UI controls for untranslated English phrases (excluding chat content and code) to help complete packs or author new languages',
'settings.hostI18n.collectBtn': 'Collect Missing Strings',
'settings.hostI18n.collectingBtn': 'Collecting…',
'settings.hostI18n.collectedResult': 'Collected {count} untranslated UI strings across {targets} window(s)',
'settings.hostI18n.collectedEmpty': 'No untranslated English UI strings detected on active pages',
'settings.hostI18n.collectFailed': 'Collection failed — verify remote debugging bridge is active',
'settings.hostI18n.copyJsonBtn': 'Copy JSON',
'settings.hostI18n.exportJsonBtn': 'Export JSON',
// Preferences -> Structure Tab
'settings.str.thirdTabAria': 'Structure section tabs',
'settings.str.tabMount': 'Mount & Bar',
@@ -796,6 +932,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'live.act.schedule': 'Schedule Task',
'live.act.ask_question': 'Waiting for User Choice',
'live.act.search_marketplace': 'Search Plugins',
'live.act.generate_image': 'Generate Image',
'live.act.mcp_tool': 'Call MCP Tool',
'live.act.tool_call': 'Call Tool',
'live.act.thinking': 'Thinking',
@@ -864,6 +1001,12 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'chart.trend.hmMore': 'More',
'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}',
'chart.trend.hmActiveZero': 'Active 0/{total}d',
'chart.trend.hmWeekPeak': 'Active {active}/{total}w · Peak {label} · {tokens}',
'chart.trend.hmWeekZero': 'Active 0/{total}w',
'chart.trend.hmMonthPeak': 'Active {active}/{total}m · Peak {label} · {tokens}',
'chart.trend.hmMonthZero': 'Active 0/{total}m',
'chart.trend.hmCumSummary': 'Cumulative {days}d · Total {tokens} · {cost}',
'chart.trend.hmCumThrough': 'Cumulative through {date}',
'chart.trend.peakPill': 'Peak {label} · {tokens}',
// Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl)
+152 -9
View File
@@ -12,6 +12,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
// Top Session Header
'header.followLatest': '跟随最新会话',
'header.followCurrentWindow': '跟随当前窗口会话',
'header.autoFollowBadge': '自动',
'header.currentWindowNamed': '当前窗口 ({title})',
'header.latestNamed': '最新 ({title})',
'header.lockedSession': '已锁定会话 ({id})',
@@ -19,6 +21,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
'header.convMetaWithSwarm': '主{main} · {swarm}蜂 (共{total}步)',
'header.convMetaWithSwarmAndSubs': '主{main} · {swarm}蜂 · {subs}子 (共{total}步)',
'header.convCompactSubs': '{subs}子 · {total}步',
'header.convCompactSwarm': '{swarm}蜂 · {total}步',
'header.convCompactSwarmAndSubs': '{swarm}蜂{subs}子 · {total}步',
'header.convMetaSteps': '{count}步',
'header.hasUpdate': '有新版本',
'header.upgradeToVer': '升级 v{ver}',
@@ -32,6 +37,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'header.statusQuotaCached': '额度缓存',
'header.statusQuotaOffline': '额度离线',
'header.statusLive': '监控中',
'header.scopeAll': '全部代理',
'header.scopeAllShort': '全',
'header.searchSessionPlaceholder': '搜索会话标题、项目或 ID…',
'select.searchPlaceholder': '输入关键词筛选…',
'select.noMatches': '没有匹配的选项',
@@ -190,6 +197,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用',
'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用',
'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用',
'quota.cycleFullSuffix': '满池约 {full}',
'quota.footTokensCustom': '本周累计: {tok} ({cost})',
'quota.footTokensCycle': '周期累计: {tok} ({cost})',
'quota.footCredits': 'AI 积分: {credits}',
@@ -206,8 +214,15 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'quota.ratePopEqWkLabel': '周限满池',
'quota.ratePopPerUsd': '{win} {rate}%/$',
'quota.ratePopSamples': '{n} 样本',
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
'quota.ratePopPrelimSlope': '斜率初估',
'quota.ratePopPrelimCycle': '周期初估',
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。',
'quota.ratePopSharedBadge': '共享活跃',
'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示',
'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占',
'quota.ratePopExternalBaseline': '检测到本周期存在家庭组 / 其他设备消耗,预占和费率仅按本机实测校准',
'quota.ratePopExt5h': '5h {pct}%',
'quota.ratePopExtWk': '周限 {pct}%',
// Live Activity Widget
'live.currentSession': '当前会话',
@@ -230,6 +245,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
// Consumption View
'cons.rangeCycle': '周期',
'cons.cyclePoolAll': '全部池',
'cons.cyclePoolAllShort': '全部',
'cons.cyclePoolAria': '当前周期配额池筛选',
'cons.cyclePoolRemMeta': '剩 {pct}',
'cons.currentCycle': '当前周期',
'cons.cycleFallbackWeek': '本周',
'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计',
'cons.rangeToday': '今天',
'cons.range24h': '1天',
'cons.range7d': '7天',
@@ -254,7 +276,12 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.replyAndThink': '思考 {think} · 回复 {resp}',
'cons.trendTitle': '用量趋势',
'cons.allTime': '全部时间',
'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看',
'cons.hmModeAria': '热力图查看维度',
'cons.hmModeDay': '日',
'cons.hmModeWeek': '周',
'cons.hmModeMonth': '月',
'cons.hmModeAll': '全部',
'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看',
'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看',
'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看',
'cons.topModels': '模型排行',
@@ -281,7 +308,6 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.rankTabWorkspacesCount': '项目排行 ({count})',
'cons.workspaceUnbound': '未绑定工作区',
'cons.workspaceSessions': '{count} 会话',
'cons.workspaceJumpTip': '点击跳转到该项目最近会话',
'cons.exportMenuAria': '导出及报告选项',
'cons.exportXlsx': '导出 Excel (.xlsx)',
'cons.exportXlsxTip': '导出多工作表排版精美的 Excel 报表(自动列宽、千分位及对齐)',
@@ -472,26 +498,54 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.account.signedOut': '未登录',
'settings.account.unknown': '暂未获取账号状态',
'settings.account.email': '账号邮箱',
'settings.account.googleLogin': '使用 Google 登录',
'settings.account.loginHint': '通过浏览器登录 Google,完成后账号会自动添加到列表。',
'settings.account.loginWaiting': '请在浏览器中选择 Google 账号并完成授权,完成后这里会自动更新。',
'settings.account.loginFinishing': '授权已收到,正在保存账号…',
'settings.account.loginSuccess': '登录成功,账号已添加。',
'settings.account.loginCancelled': '已取消本次登录。',
'settings.account.loginExpired': '登录已超时,请重新点击「使用 Google 登录」。',
'settings.account.loginDenied': 'Google 授权已取消,请重新登录。',
'settings.account.loginStartFailed': '未能开始登录,请重试。',
'settings.account.loginExchangeFailed': '未能完成登录,请检查网络后重新授权。',
'settings.account.openLoginPage': '重新打开 Google 授权页面',
'settings.account.cancelLogin': '取消登录',
'settings.account.importExisting': '导入已有凭证',
'settings.account.credential': 'OAuth 凭证',
'settings.account.credentialPlaceholder': '粘贴 1// 刷新令牌或 OAuth JSON…',
'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。',
'settings.account.save': '导入凭证',
'settings.account.capture': '保存当前凭证',
'settings.account.reload': '刷新列表',
'settings.account.switch': '切换',
'settings.account.switch': '切换并重启',
'settings.account.switchHint': '切换会关闭并重新打开 Antigravity App 和共享登录的 IDE,请先保存工作。',
'settings.account.restarting': '正在重启 Antigravity 并应用所选账号…',
'settings.account.switchStartFailed': '未能启动切号,请刷新列表后重试。',
'settings.account.clientCloseFailed': 'Antigravity 未能完全退出,切换未完成。',
'settings.account.clientRestartFailed': '凭证已更新,但自动重新打开失败,请手动打开 Antigravity。',
'settings.account.remove': '移除',
'settings.account.active': '当前使用',
'settings.account.savedBadge': '已备份',
'settings.account.written': '凭证已写入',
'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。',
'settings.account.savedCredentials': '已保存的凭证',
'settings.account.savedCredentials': '已保存的账号',
'settings.account.empty': '暂无已保存的凭证。',
'settings.account.loading': '正在读取已保存的凭证…',
'settings.account.saved': '凭证已保存。',
'settings.account.removed': '已移除保存的凭证。',
'settings.account.switched': '已切换账号,正在刷新当前额度。',
'settings.account.switching': '正在替换凭证并确认宿主账号…',
'settings.account.switching': '正在验证凭证并准备重启…',
'settings.account.verifying': '正在验证凭证所属账号…',
'settings.account.loadQuota': '查额度',
'settings.account.loadingQuota': '正在查询此凭证的额度…',
'settings.account.loadingQuota': '查询中…',
'settings.account.refreshFreqAria': '非当前账号配额刷新间隔',
'settings.account.refresh10m': '10 分钟',
'settings.account.refresh30m': '30 分钟',
'settings.account.refresh1h': '1 小时',
'settings.account.refresh3h': '3 小时',
'settings.account.refresh6h': '6 小时',
'settings.account.refresh12h': '12 小时',
'settings.account.refresh24h': '24 小时',
'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。',
'settings.account.quota': '额度池剩余',
'settings.account.quota5h': '5 小时 {percent}%',
@@ -510,10 +564,53 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。',
'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。',
'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。',
'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。',
'settings.account.identityMismatch': '凭证所属账号跟宿主或保存的账号不一致,请重新导入该凭证。',
'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。',
'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。',
'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。',
'settings.account.switchConfirm': '确认切换',
'settings.account.removeConfirm': '确认移除',
'settings.account.pwdBtnSet': '二级密码',
'settings.account.pwdBtnManage': '密码设置',
'settings.account.lockNow': '锁定',
'settings.account.lockNowTip': '立即锁定凭证库',
'settings.account.unlockBtn': '解锁',
'settings.account.unlockPlaceholder': '输入二级密码解锁…',
'settings.account.vaultLockedHint': '凭证库已加密锁定,输入二级密码后可切换账号、管理凭证和刷新后台配额。',
'settings.account.forgotPwdToggle': '忘记密码?',
'settings.account.resetVaultHint': '二级密码采用真实密钥派生加密,遗忘后无法解密旧备份(不影响当前正在使用的账号),可清空凭证库后重新添加。',
'settings.account.resetVaultBtn': '清空凭证库',
'settings.account.resetVaultConfirm': '确认清空重置',
'settings.account.pwdTabChange': '修改密码',
'settings.account.pwdTabDisable': '关闭密码',
'settings.account.pwdCurrentPlaceholder': '当前二级密码…',
'settings.account.pwdNewPlaceholder': '设置二级密码(4~128 位)…',
'settings.account.pwdConfirmPlaceholder': '再次确认密码…',
'settings.account.pwdEnableSubmit': '启用加密',
'settings.account.pwdChangeSubmit': '更新密码',
'settings.account.pwdDisableSubmit': '关闭保护',
'settings.account.pwdSetHint': '使用二级密码对所有已存刷新令牌追加一层加密,每次启动首次操作时解锁一次;请牢记密码,遗忘后无法找回备份。',
'settings.account.pwdManageHint': '验证当前二级密码后可更换新密码,或退回系统默认加密。',
'settings.account.pwdEnabledToast': '已启用二级密码加密。',
'settings.account.pwdChangedToast': '二级密码已更新。',
'settings.account.pwdDisabledToast': '已关闭二级密码保护。',
'settings.account.vaultUnlockedToast': '凭证库已解锁。',
'settings.account.vaultLockedToast': '凭证库已锁定。',
'settings.account.vaultResetToast': '凭证库已清空重置。',
'settings.account.vaultLocked': '请先输入二级密码解锁凭证库。',
'settings.account.wrongPassword': '二级密码不正确,请核对后重试。',
'settings.account.invalidPassword': '密码长度需在 4 到 128 个字符之间且不能全为空格。',
'settings.account.passwordMismatch': '两次输入的密码不一致。',
'settings.account.passwordRateLimited': '密码连续输错次数过多,请稍候再试。',
'settings.account.vaultDecryptFailed': '凭证解密校验失败,请确认密码或重置凭证库。',
'settings.account.invalidActionNonce': '安全校验令牌已过期,请重试。',
'settings.account.riskNotAccepted': '请先确认并接受非官方能力风险提示。',
'settings.account.riskBody': 'Google 官方并未授权在 Antigravity App / IDE 中通过第三方插件导入、保存、切换账号凭证或后台查询多账号配额。擅自启用可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!',
'settings.account.trendTitle': '额度变化',
'settings.account.trendWinAria': '配额窗口切换',
'settings.account.win5h': '5 小时',
'settings.account.winWeekly': '每周',
'settings.account.trendEmpty': '当前时间范围内暂无配额记录。',
'settings.saving': '保存中…',
'settings.saved': '已保存',
'settings.saveFailed': '保存失败',
@@ -578,6 +675,45 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.gen.updateOffSub': '已关闭更新提醒 ({mode})',
'settings.gen.latestSub': '已是最新 ({mode})',
// Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n)
'settings.hostI18n.title': 'Antigravity 界面语言',
'settings.hostI18n.langLabel': '目标语言',
'settings.hostI18n.langOff': '原始语言(不翻译)',
'settings.hostI18n.langHint': '从仓库按需独立下载语言包并在渲染层无损应用,不修改宿主安装包,不影响聊天内容与代码',
'settings.hostI18n.optInstalled': '已下载 v{ver}',
'settings.hostI18n.optRemote': '仓库拉取 · {size}',
'settings.hostI18n.refreshManifestTip': '刷新仓库语言包清单',
'settings.hostI18n.refreshingManifestMsg': '正在拉取语言清单…',
'settings.hostI18n.manifestSyncedMsg': '已更新清单({count} 个语言包)',
'settings.hostI18n.manifestFailedMsg': '拉取语言清单失败,请检查网络或代理',
'settings.hostI18n.depthLabel': '翻译深度',
'settings.hostI18n.depthLight': '浅度',
'settings.hostI18n.depthDeep': '深度',
'settings.hostI18n.depthLightHint': '浅度模式:保留 MCP、Skill、Workspace、Subagent、Swarm、Diff、Terminal 等高频英文术语及模型名称,仅翻译常规界面',
'settings.hostI18n.depthDeepHint': '深度模式:将常见工程术语一并译为目标语言(如工作区、子代理、蜂群、终端、沙箱),仅保留模型名与命令',
'settings.hostI18n.downloadingMsg': '正在下载 {locale} 语言包…',
'settings.hostI18n.downloadedAndAppliedMsg': '语言包已下载校验并生效',
'settings.hostI18n.appliedMsg': '已切换并即时生效',
'settings.hostI18n.disabledMsg': '已关闭翻译并还原原始界面',
'settings.hostI18n.depthSwitchedMsg': '已热切换翻译深度',
'settings.hostI18n.packUpdatedMsg': '语言包已更新并重新应用',
'settings.hostI18n.cacheRemovedMsg': '已删除本地语言包缓存',
'settings.hostI18n.actionFailed': '语言包操作失败,请重试',
'settings.hostI18n.entriesCount': '{count} 条词条',
'settings.hostI18n.appliedWindows': '已应用 {count} 窗口',
'settings.hostI18n.updatePackBtn': '更新至 v{ver}',
'settings.hostI18n.redownloadBtn': '检查更新',
'settings.hostI18n.removeCacheBtn': '删除缓存',
'settings.hostI18n.devToolsTitle': '词条采集与多语言扩展',
'settings.hostI18n.devToolsHint': '仅扫描当前打开的 Antigravity 界面控件中未命中的英文短语(自动排除聊天正文与代码),便于补全漏翻词条或制作新语言包',
'settings.hostI18n.collectBtn': '采集未翻译 UI 文案',
'settings.hostI18n.collectingBtn': '采集中…',
'settings.hostI18n.collectedResult': '共采集到 {count} 条待翻译 UI 文案(扫描 {targets} 个窗口)',
'settings.hostI18n.collectedEmpty': '当前页面未检测到待翻译的英文 UI 短语',
'settings.hostI18n.collectFailed': '采集失败,请确认已开启调试端口并打开主窗口',
'settings.hostI18n.copyJsonBtn': '复制 JSON',
'settings.hostI18n.exportJsonBtn': '导出 JSON',
// Preferences -> Structure Tab
'settings.str.thirdTabAria': '结构子菜单切换',
'settings.str.tabMount': '挂载胶囊',
@@ -796,6 +932,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'live.act.schedule': '定时任务',
'live.act.ask_question': '等待用户选择',
'live.act.search_marketplace': '查询插件',
'live.act.generate_image': '生成图片',
'live.act.mcp_tool': '调用 MCP',
'live.act.tool_call': '调用工具',
'live.act.thinking': '推理中',
@@ -864,6 +1001,12 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'chart.trend.hmMore': '多',
'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}',
'chart.trend.hmActiveZero': '活跃 0/{total} 天',
'chart.trend.hmWeekPeak': '活跃 {active}/{total} 周 · 峰值 {label} · {tokens}',
'chart.trend.hmWeekZero': '活跃 0/{total} 周',
'chart.trend.hmMonthPeak': '活跃 {active}/{total} 月 · 峰值 {label} · {tokens}',
'chart.trend.hmMonthZero': '活跃 0/{total} 月',
'chart.trend.hmCumSummary': '累计 {days} 天 · 总计 {tokens} · {cost}',
'chart.trend.hmCumThrough': '截至 {date} 累计',
'chart.trend.peakPill': '峰值 {label} · {tokens}',
// Base UI Controls (CustomDateTimePicker, CustomNumberInput, SegmentedControl)
+14
View File
@@ -131,4 +131,18 @@ export const SVG_ICON_DEFS = Object.freeze({
{ tag: 'circle', attrs: { cx: '6', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } },
],
lock: [
{ tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } },
{ tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.6 0V7' } },
{ tag: 'circle', attrs: { cx: '8', cy: '10.5', r: '0.9', fill: 'currentColor', stroke: 'none' } },
],
unlock: [
{ tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } },
{ tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } },
],
globe: [
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } },
{ tag: 'ellipse', attrs: { cx: '8', cy: '8', rx: '2.7', ry: '6' } },
{ tag: 'path', attrs: { d: 'M2.3 6h11.4M2.3 10h11.4' } },
],
});
+116 -10
View File
@@ -42,6 +42,7 @@ import {
OVERVIEW_MODULE_KEYS,
STEP_TABLE_COLUMN_KEYS,
TOPBAR_SLOT_KEYS,
normalizeAccountQuotaRefreshMinutes,
normalizeCliStatusLineSlots,
normalizeContextAgentMode,
normalizeExperimentalQuotaReservation,
@@ -148,6 +149,7 @@ export const telemetryStore = createReactiveStore({
selectedConversationId: initialConversationId,
hostRouteConversationId: extractHostRouteCascadeId(),
selectedTimeRange: 'today',
selectedCyclePool: 'all',
customStartMs: Date.now() - 24 * 3600 * 1000,
customEndMs: Date.now(),
syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error'
@@ -169,7 +171,7 @@ let inFlightTelemetryPoll = null;
let inFlightPresetsPrefetch = null;
let lastPrefetchedUsageRevision = 0;
let consumptionCacheScopeSig = '';
const MAX_CONSUMPTION_RANGE_CACHE = 12;
const MAX_CONSUMPTION_RANGE_CACHE = 24;
const MAX_CONVERSATION_VIEW_CACHE = 12;
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
const consumptionRangeCache = new Map();
@@ -191,11 +193,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
'enableWindowOverlay',
]);
function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) {
function makeConsumptionRangeCacheKey(
range,
customStartMs = 0,
customEndMs = 0,
cyclePool = 'all'
) {
const key = String(range || 'all');
if (key === 'custom') {
return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`;
}
if (key === 'cycle' && cyclePool && cyclePool !== 'all') {
return `cycle:${String(cyclePool)}`;
}
return key;
}
@@ -222,6 +232,17 @@ function buildConsumptionScopeSig(payload) {
return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`;
}
function reconcileSelectedCyclePool(payload) {
const curPool = telemetryStore.getState().selectedCyclePool || 'all';
if (curPool === 'all') return;
const pools = payload?.quotas?.pools;
if (!Array.isArray(pools) || pools.length === 0) return;
const exists = pools.some((p) => String(p?.poolKey || p?.family || '') === curPool);
if (!exists) {
telemetryStore.setState({ selectedCyclePool: 'all' });
}
}
function syncConsumptionCacheScope(payload) {
const nextSig = buildConsumptionScopeSig(payload);
if (!nextSig) return;
@@ -230,6 +251,7 @@ function syncConsumptionCacheScope(payload) {
clearConversationViewCache();
}
consumptionCacheScopeSig = nextSig;
reconcileSelectedCyclePool(payload);
}
function recordConversationViewToCache(payload) {
@@ -345,14 +367,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) {
function recordConsumptionSliceToCache(
cons,
modelBreakdown,
{ customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {}
{ customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {}
) {
const rangeKey = String(cons?.selectedRange?.key || '');
if (!rangeKey) return;
const resolvedPool =
rangeKey === 'cycle'
? String(cons?.selectedRange?.pool || cyclePool || 'all')
: 'all';
const cacheKey = makeConsumptionRangeCacheKey(
rangeKey,
rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0,
rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0
rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0,
resolvedPool
);
putConsumptionRangeCacheEntry(cacheKey, {
revision: Number(cons.revision ?? usageRevision ?? 0),
@@ -470,6 +497,7 @@ export const normalizeClientModelDisplayMode = normalizeModelDisplayMode;
export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots;
export const normalizeClientContextAgentMode = normalizeContextAgentMode;
export const normalizeClientExperimentalQuotaReservation = normalizeExperimentalQuotaReservation;
export const normalizeClientAccountQuotaRefreshMinutes = normalizeAccountQuotaRefreshMinutes;
export const normalizeClientCliStatusLineSlots = normalizeCliStatusLineSlots;
/**
@@ -628,6 +656,15 @@ export function isEquivalentTelemetry(prev, next) {
) {
return false;
}
if (
normalizeClientAccountQuotaRefreshMinutes(pSet?.accountQuotaRefreshMinutes) !==
normalizeClientAccountQuotaRefreshMinutes(nSet?.accountQuotaRefreshMinutes)
) {
return false;
}
if (Boolean(pSet?.accountSwitchRiskAccepted) !== Boolean(nSet?.accountSwitchRiskAccepted)) {
return false;
}
if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false;
if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false;
if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false;
@@ -719,6 +756,7 @@ export function isEquivalentTelemetry(prev, next) {
if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false;
if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false;
if (pAct?.aggregated?.latestTtftSec !== nAct?.aggregated?.latestTtftSec) return false;
if (pAct?.aggregated?.lastKnownTtftSec !== nAct?.aggregated?.lastKnownTtftSec) return false;
if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false;
if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false;
if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false;
@@ -730,6 +768,7 @@ export function isEquivalentTelemetry(prev, next) {
if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false;
if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false;
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
if (pAct?.lastKnownTtftSec !== nAct?.lastKnownTtftSec) return false;
if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false;
if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false;
if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false;
@@ -768,6 +807,7 @@ export function isEquivalentTelemetry(prev, next) {
pa?.liveActivity?.signature !== na?.liveActivity?.signature ||
pa?.latestTokPerSec !== na?.latestTokPerSec ||
pa?.latestTtftSec !== na?.latestTtftSec ||
pa?.lastKnownTtftSec !== na?.lastKnownTtftSec ||
pa?.avgTokPerSec !== na?.avgTokPerSec ||
pa?.latestCacheHitPct !== na?.latestCacheHitPct ||
pa?.sessionCacheHitPct !== na?.sessionCacheHitPct ||
@@ -900,11 +940,14 @@ export function isEquivalentTelemetry(prev, next) {
}
}
// 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费
// 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费
const pRange = prev.consumption?.selectedRange;
const nRange = next.consumption?.selectedRange;
if (pRange?.key !== nRange?.key) return false;
if (nRange?.key === 'custom') {
if ((pRange?.pool || 'all') !== (nRange?.pool || 'all')) return false;
if ((pRange?.label || '') !== (nRange?.label || '')) return false;
if (Boolean(pRange?.isFallbackWeek) !== Boolean(nRange?.isFallbackWeek)) return false;
if (nRange?.key === 'custom' || nRange?.key === 'cycle') {
if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false;
}
@@ -967,6 +1010,8 @@ export function isEquivalentTelemetry(prev, next) {
pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens ||
pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens ||
pTrend[i]?.calls !== nTrend[i]?.calls ||
pTrend[i]?.granularity !== nTrend[i]?.granularity ||
pTrend[i]?.stepMinutes !== nTrend[i]?.stepMinutes ||
pTrend[i]?.label !== nTrend[i]?.label ||
pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel ||
!areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models)
@@ -1112,6 +1157,12 @@ export function isEquivalentTelemetry(prev, next) {
return false;
}
}
if (
JSON.stringify(prev.quotas?.weeklyCapacityEstimate || null) !==
JSON.stringify(next.quotas?.weeklyCapacityEstimate || null)
) {
return false;
}
const pConvs = prev.conversations || [];
const nConvs = next.conversations || [];
@@ -1223,6 +1274,13 @@ export async function fetchTelemetry({ force = false } = {}) {
const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId);
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange);
if (
current.selectedTimeRange === 'cycle' &&
current.selectedCyclePool &&
current.selectedCyclePool !== 'all'
) {
params.set('pool', current.selectedCyclePool);
}
if (current.selectedTimeRange === 'custom') {
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
@@ -1270,6 +1328,7 @@ async function requestTelemetry(params, force) {
const reqSeq = ++latestRequestSeq;
const reqSettingsRev = settingsRevision;
const reqRange = String(params.get('range') || '');
const reqPool = String(params.get('pool') || 'all');
const reqStartMs = Number(params.get('startMs') || 0);
const reqEndMs = Number(params.get('endMs') || 0);
const startMs = Date.now();
@@ -1329,14 +1388,17 @@ async function requestTelemetry(params, force) {
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
customStartMs: reqStartMs,
customEndMs: reqEndMs,
cyclePool: reqPool,
});
}
const latestSt = telemetryStore.getState();
const incomingRev = Number(resolvedPayload?.consumption?.revision || 0);
const activePoolPref = latestSt.selectedCyclePool || 'all';
const matchesCurrentRange =
!reqRange ||
(reqRange === latestSt.selectedTimeRange &&
(reqRange !== 'cycle' || reqPool === activePoolPref) &&
(reqRange !== 'custom' ||
(reqStartMs === Number(latestSt.customStartMs || 0) &&
reqEndMs === Number(latestSt.customEndMs || 0))));
@@ -1348,7 +1410,8 @@ async function requestTelemetry(params, force) {
const activeKey = makeConsumptionRangeCacheKey(
latestSt.selectedTimeRange,
latestSt.customStartMs,
latestSt.customEndMs
latestSt.customEndMs,
activePoolPref
);
const cachedActive = consumptionRangeCache.get(activeKey);
if (cachedActive) {
@@ -1357,7 +1420,9 @@ async function requestTelemetry(params, force) {
needsSilentRangeRevalidate = true;
}
} else if (
latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange
latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange &&
(latestSt.selectedTimeRange !== 'cycle' ||
(latestSt.telemetry?.consumption?.selectedRange?.pool || 'all') === activePoolPref)
) {
resolvedPayload = {
...resolvedPayload,
@@ -1409,6 +1474,7 @@ async function requestTelemetry(params, force) {
range: latestSt.selectedTimeRange,
customStartMs: latestSt.customStartMs,
customEndMs: latestSt.customEndMs,
cyclePool: latestSt.selectedCyclePool || 'all',
});
}
return resolvedPayload;
@@ -1434,15 +1500,20 @@ async function fetchConsumptionRangeSlice({
range,
customStartMs = 0,
customEndMs = 0,
cyclePool = 'all',
} = {}) {
const reqEpoch = endpointSwitchEpoch;
const reqSeq = ++latestConsumptionReqSeq;
const targetRange = String(range || 'today');
const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all';
const current = telemetryStore.getState();
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId);
params.set('range', targetRange);
if (targetRange === 'cycle' && targetPool !== 'all') {
params.set('pool', targetPool);
}
if (targetRange === 'custom') {
if (customStartMs > 0) params.set('startMs', String(customStartMs));
if (customEndMs > 0) params.set('endMs', String(customEndMs));
@@ -1461,6 +1532,7 @@ async function fetchConsumptionRangeSlice({
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
customStartMs,
customEndMs,
cyclePool: targetPool,
usageRevision: usageRev,
});
if (reqSeq !== latestConsumptionReqSeq) return payload;
@@ -1468,6 +1540,7 @@ async function fetchConsumptionRangeSlice({
const latestSt = telemetryStore.getState();
const stillMatches =
latestSt.selectedTimeRange === targetRange &&
(targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) &&
(targetRange !== 'custom' ||
(Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) &&
Number(latestSt.customEndMs || 0) === Number(customEndMs || 0)));
@@ -1573,6 +1646,13 @@ export async function selectConversation(
const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId);
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange);
if (
current.selectedTimeRange === 'cycle' &&
current.selectedCyclePool &&
current.selectedCyclePool !== 'all'
) {
params.set('pool', current.selectedCyclePool);
}
if (current.selectedTimeRange === 'custom') {
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
@@ -1679,7 +1759,7 @@ export async function selectConversation(
*/
export function selectConsumptionTimeRange(
nextRange,
{ customStartMs = undefined, customEndMs = undefined } = {}
{ customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {}
) {
const targetRange = String(nextRange || 'today');
const prevSt = telemetryStore.getState();
@@ -1691,14 +1771,26 @@ export function selectConsumptionTimeRange(
targetRange === 'custom'
? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0)
: prevSt.customEndMs;
const nextCyclePool =
targetRange === 'cycle'
? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all')
: prevSt.selectedCyclePool || 'all';
const statePatch = { selectedTimeRange: targetRange };
if (cyclePool !== undefined) {
statePatch.selectedCyclePool = nextCyclePool;
}
if (targetRange === 'custom') {
statePatch.customStartMs = nextStartMs;
statePatch.customEndMs = nextEndMs;
}
const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs);
const cacheKey = makeConsumptionRangeCacheKey(
targetRange,
nextStartMs,
nextEndMs,
targetRange === 'cycle' ? nextCyclePool : 'all'
);
const cached = consumptionRangeCache.get(cacheKey);
const prevTelemetry = prevSt.telemetry;
@@ -1717,6 +1809,7 @@ export function selectConsumptionTimeRange(
range: targetRange,
customStartMs: nextStartMs,
customEndMs: nextEndMs,
cyclePool: nextCyclePool,
});
}
@@ -1725,9 +1818,14 @@ export function selectConsumptionTimeRange(
range: targetRange,
customStartMs: nextStartMs,
customEndMs: nextEndMs,
cyclePool: nextCyclePool,
});
}
export function selectConsumptionCyclePool(nextPool = 'all') {
return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') });
}
/**
* 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。
*/
@@ -1829,6 +1927,14 @@ export async function saveSettingsPatch(patch) {
safePatch.experimentalQuotaReservation
);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'accountQuotaRefreshMinutes')) {
safePatch.accountQuotaRefreshMinutes = normalizeClientAccountQuotaRefreshMinutes(
safePatch.accountQuotaRefreshMinutes
);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'accountSwitchRiskAccepted')) {
safePatch.accountSwitchRiskAccepted = Boolean(safePatch.accountSwitchRiskAccepted);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
}
+5
View File
@@ -31,6 +31,11 @@ body {
color: var(--text-primary);
font-family: var(--font-sans);
font-size: var(--fs-body);
font-weight: 400;
font-stretch: 100%;
font-variation-settings: normal;
font-feature-settings: normal;
letter-spacing: normal;
line-height: 1.4;
font-variant-numeric: tabular-nums;
-webkit-font-smoothing: antialiased;
+70 -1
View File
@@ -45,6 +45,30 @@
min-width: 0;
}
.session-select .select-menu {
min-width: 100%;
width: min(444px, calc(100vw - 28px));
max-width: calc(100vw - 24px);
}
.session-select .select-menu.has-search {
max-height: 304px;
}
.session-select .select-option {
padding: 5px 8px;
gap: 8px;
}
.session-select .select-option-check {
flex-shrink: 0;
}
.session-select .select-option-check[hidden] {
display: inline-flex !important;
visibility: hidden;
}
.session-right {
display: flex;
align-items: center;
@@ -512,21 +536,66 @@
background: transparent;
}
.select-option-text {
.select-option-body {
display: flex;
flex-direction: column;
gap: 1px;
flex: 1;
min-width: 0;
}
.select-option-text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.select-option-sub {
font-size: var(--fs-xs);
line-height: 1.25;
font-family: var(--font-mono);
font-weight: 400;
opacity: 0.72;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.select-option.is-selected .select-option-sub {
color: var(--text-secondary);
opacity: 0.85;
}
.select-option.has-divider-after {
position: relative;
margin-bottom: 5px;
}
.select-option.has-divider-after::after {
content: '';
position: absolute;
left: 6px;
right: 6px;
bottom: -3px;
height: 1px;
background: var(--border-hairline);
pointer-events: none;
}
.select-option-meta {
font-size: var(--fs-md);
flex-shrink: 0;
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
.select-option-meta.is-dim {
opacity: 0.48;
}
.select-checkbox {
display: inline-flex;
align-items: center;
+72 -18
View File
@@ -479,6 +479,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
border-top-color: color-mix(in srgb, var(--text-primary) 8%, transparent);
}
[data-modern-ui="true"] .cons-source-hover-zone.is-interactive:hover .cons-source-model-bar,
[data-modern-ui="true"] .cons-source-hover-zone.is-hovered .cons-source-model-bar,
[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar,
[data-modern-ui="true"] .cons-source-bar-hit.is-hovered .cons-source-model-bar,
[data-modern-ui="true"] .month-col.is-interactive:hover .month-stack,
@@ -568,6 +570,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
}
[data-modern-ui="true"] .form-row > .custom-select > .select-trigger,
[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger,
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger,
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger {
@@ -578,6 +581,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
}
[data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover,
[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover,
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover {
@@ -585,6 +589,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
}
[data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger,
[data-modern-ui="true"] .cons-cycle-pool-select.is-open .select-trigger,
[data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger,
[data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger {
@@ -618,15 +623,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
background: var(--accent-primary-soft);
}
[data-modern-ui="true"] .steps-anomaly-filterbar,
[data-modern-ui="true"] .steps-anomaly-strip {
[data-modern-ui="true"] .steps-anomaly-filterbar {
border: none;
border-radius: var(--radius-xs);
background: var(--metric-warn-soft);
background: var(--modern-surface-subtle);
margin: 4px 2px 2px;
}
[data-modern-ui="true"] .steps-anomaly-filterbar {
margin: 4px 2px 2px;
[data-modern-ui="true"] .steps-anomaly-strip {
border: none;
background: transparent;
}
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
@@ -668,6 +674,21 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
border: none;
}
[data-modern-ui="true"] .ctx-risk-mask {
border-radius: var(--radius-sm);
background: color-mix(in srgb, var(--metric-warn) 8%, transparent);
}
[data-modern-ui="true"] .btn-danger-confirm {
border: none !important;
background: color-mix(in srgb, var(--metric-danger) 14%, transparent) !important;
}
[data-modern-ui="true"] .btn-danger-confirm:hover:not(:disabled) {
border: none !important;
background: color-mix(in srgb, var(--metric-danger) 22%, transparent) !important;
}
[data-modern-ui="true"] .number-input,
[data-modern-ui="true"] .dt-trigger,
[data-modern-ui="true"] .dt-mini-step,
@@ -823,19 +844,18 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
}
[data-modern-ui="true"] .step-anomaly-tip-list,
[data-modern-ui="true"] .step-anomaly-tip-hint,
[data-modern-ui="true"] .quota-rate-pop-head,
[data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group,
[data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row,
[data-modern-ui="true"] .quota-rate-pop-note,
:host([data-modern-ui="true"]) .quota-rate-pop-head,
:host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group,
:host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row,
:host([data-modern-ui="true"]) .quota-rate-pop-note {
[data-modern-ui="true"] .step-anomaly-tip-hint {
border-color: var(--modern-surface-hover);
}
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) {
[data-modern-ui="true"] .quota-rate-shared-badge,
[data-modern-ui="true"] .quota-rate-ext-banner,
:host([data-modern-ui="true"]) .quota-rate-shared-badge,
:host([data-modern-ui="true"]) .quota-rate-ext-banner {
border: none;
}
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown):not(.is-floating-tip) {
top: 2px;
bottom: auto;
transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0);
@@ -849,6 +869,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
translateX(var(--tip-shift, 0px));
}
[data-modern-ui="true"] .trend-tooltip.is-floating-tip {
top: 0;
bottom: auto;
left: 0;
transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0)
translateX(var(--tip-shift, 0px));
}
[data-modern-ui="true"] .trend-tooltip.is-tracking {
transition:
left 150ms var(--ease-modern),
@@ -861,7 +889,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
transition: transform 150ms var(--ease-modern);
}
[data-modern-ui="true"] .trend-hover-dot.is-tracking {
[data-modern-ui="true"] .trend-tooltip.is-floating-tip.is-tracking {
transition: transform 150ms var(--ease-modern);
}
[data-modern-ui="true"] .trend-hover-dot.is-tracking,
[data-modern-ui="true"] .sstep-hover-raw-dot.is-tracking {
transition:
cx 150ms var(--ease-modern),
cy 150ms var(--ease-modern);
@@ -901,7 +934,11 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
}
[data-modern-ui="true"] .wm-multi-header,
:host([data-modern-ui="true"]) .wm-multi-header,
:host([data-modern-ui="true"]) .wm-multi-header {
border: none;
padding-bottom: 6px;
}
[data-modern-ui="true"].wm-multi-panel .live-task-card + .live-task-card,
:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card + .live-task-card {
border: none;
@@ -919,12 +956,22 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
[data-modern-ui="true"].wm-multi-panel .live-task-card,
:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card {
padding: 10px 2px;
padding: 8px 0;
border-radius: 0;
background: transparent;
box-shadow: none;
}
[data-modern-ui="true"].wm-multi-panel .live-task-card:first-child,
:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card:first-child {
padding-top: 8px;
}
[data-modern-ui="true"].wm-multi-panel .live-task-card:last-child,
:host([data-modern-ui="true"]) .wm-multi-panel .live-task-card:last-child {
padding-bottom: 0;
}
/* --- 8. 顶栏胶囊老虎机滚动数字 (0.15s) 与语义色平滑渐变 (0.1s),严格限定实验性新 UI --- */
:host([data-modern-ui="true"]) .wm-cap-slot,
:host([data-modern-ui="true"]) .wm-cap-slot .wm-slot-text,
@@ -989,6 +1036,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
will-change: transform;
}
@starting-style {
:host([data-modern-ui="true"]) .wm-od-track,
[data-modern-ui="true"] .wm-od-track {
transform: translate3d(0, 0, 0);
}
}
:host([data-modern-ui="true"]) .wm-od-cell,
[data-modern-ui="true"] .wm-od-cell {
display: block;
+18 -16
View File
@@ -561,6 +561,11 @@
z-index: 2147483000;
font-family: var(--font-sans);
font-size: var(--fs-body);
font-weight: 400;
font-stretch: 100%;
font-variation-settings: normal;
font-feature-settings: normal;
letter-spacing: normal;
line-height: 1.4;
font-variant-numeric: tabular-nums;
-webkit-font-smoothing: antialiased;
@@ -642,14 +647,14 @@
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
}
/* 左侧在线多会话实时看板浮层(单层无套娃细线卡片,仅显示在线运行会话,留足呼吸感) */
/* 左侧在线多会话实时看板浮层(单层无套娃细线卡片,宽度与排版密度与侧边栏保持一致) */
.wm-multi-panel {
position: fixed;
top: 42px;
left: 12px;
width: min(calc(464px * var(--ui-panel-scale, 1)), calc(100vw - 24px));
width: min(calc(522px * var(--ui-panel-scale, 1)), calc(100vw - 24px));
max-height: calc(100vh - 54px);
padding: 14px 16px;
padding: 12px 14px;
display: flex;
flex-direction: column;
gap: 0;
@@ -783,53 +788,50 @@
}
.wm-task-metrics {
font-size: var(--fs-md);
color: var(--text-secondary);
font-size: var(--fs-sm);
font-weight: 500;
color: var(--text-muted);
white-space: nowrap;
flex-shrink: 0;
}
.wm-multi-header {
padding-bottom: 10px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border-hairline);
}
/* 多会话单层面板内去除重复边框与底色,留足行距与段落呼吸感,仅靠左侧圆点闪烁表达状态 */
/* 多会话单层面板内去除重复边框与底色,对齐侧边栏任务卡片间距与左侧基线 */
.wm-multi-panel .live-activity-list {
gap: 0;
}
.wm-multi-panel .live-task-card {
gap: 8px;
padding: 12px 2px;
gap: 7px;
padding: 10px 0;
border: none;
border-radius: 0;
background: transparent;
}
.wm-multi-panel .live-task-card:first-child {
padding-top: 11px;
padding-top: 9px;
}
.wm-multi-panel .live-task-card:last-child {
padding-bottom: 2px;
padding-bottom: 0;
}
.wm-multi-panel .live-task-card + .live-task-card {
border-top: 1px solid var(--border-hairline);
}
.wm-multi-panel .live-task-title {
font-size: var(--fs-body);
}
.wm-multi-empty {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
min-height: 36px;
padding: 12px 2px 4px;
padding: 10px 0 2px;
font-size: var(--fs-base);
color: var(--text-secondary);
}
+1
View File
@@ -171,6 +171,7 @@
--ui-panel-scale: 1.18;
}
:host([data-font-scale]),
[data-font-scale] {
--fs-2xs: calc(10.5px * var(--ui-font-scale, 1));
--fs-xs: calc(11px * var(--ui-font-scale, 1));
+197 -8
View File
@@ -14,6 +14,53 @@
gap: 6px;
}
.cons-overview-title {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.cons-cycle-pool-select {
flex: 0 1 auto;
width: auto;
min-width: 0;
max-width: 112px;
}
.cons-cycle-pool-select .select-trigger {
width: auto;
min-height: calc(20px * var(--ui-font-scale, 1));
height: auto;
padding: 1px 7px;
gap: 4px;
font-size: var(--fs-sm);
line-height: 1.25;
border: none;
border-radius: var(--radius-pill);
background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel));
}
.cons-cycle-pool-select .select-trigger:hover {
background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel));
}
.cons-cycle-pool-select.is-open .select-trigger {
background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel));
}
.cons-cycle-pool-select .select-trigger .svg-icon {
width: 11px;
height: 11px;
}
.cons-cycle-pool-select .select-menu {
right: auto;
min-width: 224px;
width: max-content;
max-width: 280px;
}
.cons-overview-controls {
display: inline-flex;
align-items: center;
@@ -305,6 +352,31 @@
}
/* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */
.cons-trend-head {
flex-wrap: wrap;
gap: 6px;
}
.cons-trend-head-right {
display: inline-flex;
align-items: center;
margin-left: auto;
}
.cons-trend-hint[hidden],
.cons-hm-mode-switch[hidden] {
display: none !important;
}
.cons-hm-mode-switch.segmented {
gap: 1px;
}
.cons-hm-mode-switch .seg-btn {
padding: 1px 7px;
font-size: var(--fs-xs);
}
.trend-chart-wrap {
position: relative;
width: 100%;
@@ -329,6 +401,7 @@
height: 184px;
display: block;
overflow: visible;
pointer-events: none;
}
.trend-grid line {
@@ -387,6 +460,64 @@
z-index: 2;
}
.cons-view-stage .progress-seg,
.models-analytics-pane .progress-seg {
flex: 0 0 auto;
transition:
background-color 80ms ease,
width 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
.cons-view-stage .progress-fill,
.account-cards-stack .progress-fill {
transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
@starting-style {
.cons-view-stage.is-ready .progress-seg,
.cons-view-stage.is-ready .progress-fill,
.models-analytics-pane .progress-seg,
.account-cards-stack .progress-fill {
width: 0%;
}
}
.trend-peak-pill.is-ready {
transition: left 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
@keyframes anim-cons-bar-grow {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}
.cons-item-list.is-bars-revealing .progress-track {
transform-origin: left center;
animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
@media (prefers-reduced-motion: reduce) {
.cons-view-stage .progress-seg,
.cons-view-stage .progress-fill,
.models-analytics-pane .progress-seg,
.account-cards-stack .progress-fill,
.trend-peak-pill.is-ready,
.trend-hm-cell,
.trend-tooltip.is-tracking,
.trend-hover-dot.is-tracking,
.sstep-hover-raw-dot.is-tracking,
.sstep-anomaly-dot {
transition: none !important;
}
.cons-item-list.is-bars-revealing .progress-track {
animation: none !important;
}
}
.trend-tooltip {
position: absolute;
top: 2px;
@@ -664,7 +795,9 @@
border-radius: 2px;
box-sizing: border-box;
cursor: pointer;
transition: transform var(--dur-instant) var(--ease-fast);
transition:
background-color 180ms ease-out,
transform var(--dur-instant) var(--ease-fast);
}
.trend-hm-cell.is-pad {
@@ -704,6 +837,20 @@
z-index: 2;
}
.trend-hm-cell.is-bar-hovered {
filter: brightness(1.22);
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 52%, transparent);
z-index: 2;
}
.trend-hm-cell.is-month-edge:not(.lv-0) {
box-shadow: inset 1px 0 0 color-mix(in srgb, var(--surface-panel) 55%, transparent);
}
.trend-hm-cell.is-month-edge.is-bar-hovered:not(.lv-0) {
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 52%, transparent);
}
.trend-hm-footer {
display: flex;
align-items: center;
@@ -891,12 +1038,27 @@
container-type: inline-size;
}
.cons-source-bar-hit {
padding: 5px 0;
margin: -5px 0;
.cons-source-hover-zone {
display: flex;
flex-direction: column;
gap: 5px;
padding: 4px 0 2px;
margin: -4px 0 -2px;
min-width: 0;
}
.cons-source-hover-zone.is-interactive {
cursor: pointer;
}
.cons-source-bar-hit {
padding: 0;
margin: 0;
cursor: inherit;
}
.cons-source-hover-zone.is-interactive:hover .cons-source-model-bar,
.cons-source-hover-zone.is-hovered .cons-source-model-bar,
.cons-source-bar-hit:hover .cons-source-model-bar,
.cons-source-bar-hit.is-hovered .cons-source-model-bar {
box-shadow: 0 0 0 1px var(--border-strong);
@@ -959,6 +1121,8 @@
transition: color 120ms ease;
}
.cons-source-hover-zone.is-interactive:hover .cons-source-top-name,
.cons-source-hover-zone.is-hovered .cons-source-top-name,
.cons-source-top-models:hover .cons-source-top-name,
.cons-source-top-models.is-hovered .cons-source-top-name {
color: var(--text-primary);
@@ -1037,6 +1201,28 @@
contain: layout style;
}
.trend-tooltip.is-floating-tip {
top: 0;
bottom: auto;
left: 0;
transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0)
translateX(var(--tip-shift, 0px));
will-change: transform;
contain: layout style;
}
.trend-tooltip.is-floating-tip.is-tracking,
.trend-tooltip.is-rich-breakdown.is-tracking {
transition: transform 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1));
}
.trend-hover-dot.is-tracking,
.sstep-hover-raw-dot.is-tracking {
transition:
cx 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)),
cy 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1));
}
.trend-tooltip.is-rich-breakdown,
.cons-breakdown-popover.is-rich-breakdown {
min-width: 212px;
@@ -1236,17 +1422,20 @@
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
.monthly-grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 3px;
align-items: end;
padding-top: var(--space-2);
grid-template-columns: repeat(12, minmax(0, 1fr));
gap: 0;
align-items: stretch;
margin: var(--space-2) -1.5px 0;
}
.month-col {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
gap: 3px;
padding: 0 1.5px;
box-sizing: border-box;
min-width: 0;
}
+57 -24
View File
@@ -175,7 +175,7 @@
.live-task-header-right {
display: inline-flex;
align-items: center;
gap: 8px;
gap: 6px;
flex-shrink: 0;
}
@@ -284,7 +284,7 @@
font-weight: 500;
color: var(--text-secondary);
white-space: nowrap;
min-width: 28px;
min-width: 22px;
text-align: right;
flex-shrink: 0;
}
@@ -676,7 +676,7 @@
position: absolute;
top: 38px;
left: 12px;
width: min(332px, calc(100% - 24px));
width: min(352px, calc(100% - 24px));
z-index: 45;
display: flex;
flex-direction: column;
@@ -699,8 +699,6 @@
justify-content: space-between;
gap: 10px;
min-width: 0;
padding-bottom: 6px;
border-bottom: 1px solid var(--border-hairline);
}
.quota-rate-pop-title {
@@ -724,7 +722,11 @@
.quota-rate-pop-body {
display: flex;
flex-direction: column;
gap: 8px;
gap: 10px;
max-height: min(300px, 58vh);
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
}
.quota-rate-pool-group {
@@ -733,9 +735,11 @@
gap: 5px;
}
.quota-rate-pool-group + .quota-rate-pool-group {
padding-top: 7px;
border-top: 1px solid var(--border-hairline);
.quota-rate-pool-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.quota-rate-pool-label {
@@ -744,10 +748,42 @@
color: var(--text-muted);
}
.quota-rate-shared-badge {
display: inline-flex;
align-items: center;
padding: 1px 6px;
border-radius: 999px;
font-size: var(--fs-2xs);
font-weight: 600;
line-height: 1.4;
color: var(--metric-warn);
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--metric-warn) 28%, transparent);
white-space: nowrap;
flex-shrink: 0;
}
.quota-rate-ext-banner {
margin-top: 2px;
padding: 5px 8px;
border-radius: 6px;
font-size: var(--fs-2xs);
line-height: 1.45;
color: var(--text-secondary);
background: color-mix(in srgb, var(--metric-warn) 8%, transparent);
border: 1px solid color-mix(in srgb, var(--metric-warn) 22%, var(--border-hairline));
}
.quota-rate-ext-banner.is-active {
color: var(--text-primary);
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
border-color: color-mix(in srgb, var(--metric-warn) 34%, var(--border-hairline));
}
.quota-rate-model-list {
display: flex;
flex-direction: column;
gap: 7px;
gap: 8px;
}
.quota-rate-model-row {
@@ -757,11 +793,6 @@
min-width: 0;
}
.quota-rate-model-row + .quota-rate-model-row {
padding-top: 7px;
border-top: 1px solid var(--border-hairline);
}
.quota-rate-row-top {
display: flex;
align-items: baseline;
@@ -816,9 +847,11 @@
.quota-rate-eq-grid {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 12px;
column-gap: 10px;
row-gap: 3px;
}
.quota-rate-eq-grid.is-single {
@@ -846,20 +879,20 @@
white-space: nowrap;
}
.quota-rate-eq-tok {
font-size: var(--fs-xs);
font-weight: 400;
font-variant-numeric: tabular-nums;
color: var(--text-muted);
white-space: nowrap;
}
.quota-rate-pop-empty {
font-size: var(--fs-sm);
line-height: 1.5;
color: var(--text-secondary);
}
.quota-rate-pop-note {
padding-top: 6px;
border-top: 1px solid var(--border-hairline);
font-size: var(--fs-2xs);
line-height: 1.45;
color: var(--text-muted);
}
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
.ctx-legend-grid {
display: grid;
+413 -11
View File
@@ -641,6 +641,287 @@
line-height: 1.35;
}
.settings-account-root [hidden] {
display: none !important;
}
.account-toolbar-panel {
padding: var(--space-3) var(--space-5);
gap: var(--space-2);
}
.account-toolbar-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
flex-wrap: wrap;
}
.account-toolbar-left,
.account-toolbar-right {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
min-width: 0;
}
.account-toolbar-right {
margin-left: auto;
}
.account-toolbar-panel .btn-primary,
.account-toolbar-panel .btn-secondary {
min-height: calc(26px * var(--ui-font-scale, 1));
padding: 2px 10px;
font-size: var(--fs-md);
white-space: nowrap;
}
.account-toolbar-panel .btn-secondary.is-open {
color: var(--accent-primary);
background: var(--accent-primary-soft);
}
.account-refresh-select {
flex: 0 0 auto;
width: auto;
min-width: 0;
}
.account-refresh-select .select-trigger {
width: auto;
min-height: calc(26px * var(--ui-font-scale, 1));
height: auto;
padding: 2px 8px;
gap: 5px;
font-size: var(--fs-sm);
}
.account-refresh-select .select-menu {
right: 0;
left: auto;
min-width: 108px;
width: max-content;
}
.account-status-inline {
font-size: var(--fs-sm);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 210px;
}
.account-status-inline.is-ok {
color: var(--metric-ok);
}
.account-status-inline.is-error,
.account-card-note.is-error {
color: var(--metric-danger);
}
.account-import-drawer {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 6px;
padding-top: 2px;
}
.account-import-drawer > .segmented {
align-self: flex-start;
}
.account-import-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.account-import-input {
flex: 1 1 150px;
min-width: 0;
min-height: calc(26px * var(--ui-font-scale, 1));
}
.account-cards-stack {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
/* Optically symmetrical vertical padding: 11px + 3px header leading == 14px bottom bar-to-edge */
.account-card {
gap: 10px;
padding: 11px var(--space-5) 14px;
}
.account-card-head {
min-height: calc(22px * var(--ui-font-scale, 1));
gap: 8px;
flex-wrap: wrap;
}
.account-card-meta {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
min-width: 0;
flex: 1 1 150px;
}
.account-card-email {
font-size: var(--fs-base);
font-weight: 600;
line-height: 1.3;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
}
.account-card-actions {
display: inline-flex;
align-items: center;
gap: 5px;
flex-shrink: 0;
margin-left: auto;
}
.account-card-actions .btn-ghost-sm {
min-height: calc(22px * var(--ui-font-scale, 1));
padding: 1px 8px;
}
.account-card-actions .icon-btn {
width: calc(22px * var(--ui-font-scale, 1));
height: calc(22px * var(--ui-font-scale, 1));
min-width: calc(22px * var(--ui-font-scale, 1));
padding: 0;
}
.account-pools-stack {
display: flex;
flex-direction: column;
gap: 9px;
}
.account-pool-label {
font-size: var(--fs-xs);
font-weight: 600;
color: var(--text-muted);
line-height: 1.25;
}
.account-pool-meters {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px 14px;
}
.account-pool-meters.is-single {
grid-template-columns: minmax(0, 1fr);
}
@media (max-width: 310px) {
.account-pool-meters {
grid-template-columns: minmax(0, 1fr);
}
}
.account-meter-col {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
/* Quota Trend Card minor layout helpers */
.account-trend-toprow {
gap: var(--space-2);
flex-wrap: wrap;
}
.account-trend-toprow .cons-cycle-pool-select {
flex: 0 0 auto;
}
.account-trend-subbar {
gap: 6px 8px;
flex-wrap: wrap;
}
.account-trend-email-select {
max-width: 156px;
}
.account-trend-legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px 12px;
padding-top: 2px;
}
.account-trend-leg-item {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: var(--fs-xs);
color: var(--text-secondary);
}
.account-trend-leg-item strong {
color: var(--text-primary);
}
.account-trend-tip-rows {
display: flex;
flex-direction: column;
gap: 4px;
}
.account-trend-tip-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: var(--fs-xs);
}
.account-empty-panel {
padding: 16px var(--space-5);
align-items: center;
justify-content: center;
}
.account-empty-text {
text-align: center;
color: var(--text-muted);
}
@keyframes anim-account-spin {
to {
transform: rotate(360deg);
}
}
.icon-btn.is-spinning .svg-icon {
animation: anim-account-spin 0.8s linear infinite;
}
@media (prefers-reduced-motion: reduce) {
.icon-btn.is-spinning .svg-icon {
animation: none !important;
}
}
.settings-context-model .select-option-meta {
max-width: 62%;
text-align: right;
@@ -733,8 +1014,11 @@
}
.ctx-controls-body.is-locked {
filter: blur(4px);
opacity: 0.24;
height: 0;
overflow: hidden;
opacity: 0;
visibility: hidden;
filter: none;
pointer-events: none;
user-select: none;
}
@@ -753,12 +1037,12 @@
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: var(--space-2);
justify-content: flex-start;
gap: 8px;
padding: var(--space-3) var(--space-4);
border-radius: var(--radius-xs);
border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline));
background: color-mix(in srgb, var(--surface-panel) 88%, var(--metric-warn) 7%);
border-radius: var(--radius-sm);
border: 1px solid color-mix(in srgb, var(--metric-warn) 36%, var(--border-hairline));
background: color-mix(in srgb, var(--surface-panel) 93%, var(--metric-warn) 7%);
}
.ctx-risk-mask[hidden] {
@@ -786,14 +1070,29 @@
.ctx-risk-desc {
margin: 0;
font-size: var(--fs-sm);
line-height: 1.5;
color: var(--text-primary);
line-height: 1.55;
color: var(--text-secondary);
}
.ctx-risk-accept-btn {
margin-top: 2px;
min-height: calc(26px * var(--ui-font-scale, 1));
padding: 2px var(--space-3);
min-height: calc(28px * var(--ui-font-scale, 1));
padding: 4px var(--space-3);
font-size: var(--fs-md);
}
/* 设置页卡片头部右侧状态提示(长路径自动单行省略,防止把左侧标题挤成 0px 造成文字重叠) */
.settings-panel-header > .panel-title {
flex: 0 0 auto;
}
.settings-panel-status {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
font-size: var(--fs-md);
}
@@ -1475,3 +1774,106 @@
white-space: nowrap;
flex-shrink: 0;
}
/* --- Decoupled Antigravity Host UI Language Card (HostI18nCard) --- */
.host-i18n-status-msg {
font-size: var(--fs-sm);
margin-left: auto;
max-width: 60%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.host-i18n-status-msg.is-error {
color: var(--metric-danger);
}
.host-i18n-select-row {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
min-width: 0;
}
.host-i18n-select-row > .custom-select {
flex: 1 1 auto;
min-width: 0;
}
.host-i18n-icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(28px * var(--ui-font-scale, 1));
height: calc(28px * var(--ui-font-scale, 1));
padding: 0;
flex-shrink: 0;
}
.host-i18n-pack-bar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px;
padding-top: 2px;
}
.host-i18n-pack-meta {
font-size: var(--fs-xs);
line-height: 1.4;
}
.host-i18n-pack-actions {
display: inline-flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.host-i18n-dev-drawer {
border-top: 1px solid var(--border-hairline);
padding-top: 8px;
margin-top: 2px;
}
.host-i18n-dev-toggle {
display: inline-flex;
align-items: center;
gap: 5px;
border: none;
background: transparent;
color: var(--text-muted);
font-size: var(--fs-xs);
font-weight: 600;
padding: 2px 0;
cursor: pointer;
}
.host-i18n-dev-toggle:hover {
color: var(--text-primary);
}
.host-i18n-dev-chevron {
transition: transform var(--dur-fast) var(--ease-standard);
}
.host-i18n-dev-drawer.is-expanded .host-i18n-dev-chevron {
transform: rotate(90deg);
}
.host-i18n-dev-body {
display: flex;
flex-direction: column;
gap: 8px;
padding-top: 6px;
}
.host-i18n-dev-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
+91 -36
View File
@@ -56,6 +56,19 @@
white-space: nowrap;
}
.data-table td {
font-variant-numeric: tabular-nums;
}
.data-table.is-cols-locked {
table-layout: fixed;
}
.data-table.is-cols-locked td:not(:first-child) {
overflow: hidden;
text-overflow: ellipsis;
}
.data-table th.is-right,
.data-table td.is-right {
text-align: right;
@@ -140,6 +153,10 @@
height: 0;
}
.data-table tbody tr.step-vsizer.has-bold-first td:first-child {
font-weight: 600;
}
.step-vsizer-inner {
display: block;
height: 0;
@@ -621,11 +638,10 @@
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 6px;
padding: 4px 8px;
border: 1px solid color-mix(in srgb, var(--metric-warn) 26%, var(--border-hairline));
border-radius: var(--radius-xs);
background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel));
gap: 4px 8px;
padding: 2px 2px 3px;
border: none;
background: transparent;
}
.steps-anomaly-strip[hidden] {
@@ -633,18 +649,35 @@
}
.steps-anomaly-strip-meta {
display: inline-flex;
align-items: center;
gap: 6px;
border: none;
background: transparent;
padding: 0;
font-size: var(--fs-xs);
font-weight: 600;
color: var(--metric-warn);
font-weight: 500;
color: var(--text-secondary);
cursor: pointer;
white-space: nowrap;
transition: color var(--dur-instant) var(--ease-fast);
}
.steps-anomaly-strip-meta::before {
content: '';
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--metric-warn);
flex-shrink: 0;
}
.steps-anomaly-strip.has-danger .steps-anomaly-strip-meta::before {
background: var(--metric-danger);
}
.steps-anomaly-strip-meta:hover {
text-decoration: underline;
color: var(--text-primary);
}
.steps-anomaly-strip-tags {
@@ -654,6 +687,41 @@
gap: 4px;
}
.steps-anomaly-strip .smodel-anomaly-tag,
.smodel-ident .smodel-anomaly-tag {
margin-left: 0;
padding: 1px 6px;
font-size: var(--fs-2xs);
font-weight: 500;
line-height: 1.35;
border-radius: var(--radius-pill);
border: none;
color: var(--text-secondary);
background: color-mix(in srgb, var(--text-primary) 6%, transparent);
cursor: pointer;
transition:
color var(--dur-instant) var(--ease-fast),
background-color var(--dur-instant) var(--ease-fast);
}
.steps-anomaly-strip .smodel-anomaly-tag:hover,
.smodel-ident .smodel-anomaly-tag:hover {
color: var(--text-primary);
background: color-mix(in srgb, var(--text-primary) 11%, transparent);
}
.steps-anomaly-strip .smodel-anomaly-tag.is-danger,
.smodel-ident .smodel-anomaly-tag.is-danger {
color: color-mix(in srgb, var(--metric-danger) 78%, var(--text-primary));
background: color-mix(in srgb, var(--metric-danger) 9%, transparent);
}
.steps-anomaly-strip .smodel-anomaly-tag.is-danger:hover,
.smodel-ident .smodel-anomaly-tag.is-danger:hover {
color: var(--metric-danger);
background: color-mix(in srgb, var(--metric-danger) 15%, transparent);
}
/* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */
.models-analytics-pane {
display: flex;
@@ -758,6 +826,7 @@
height: 106px;
display: block;
overflow: visible;
pointer-events: none;
}
.sstep-fit-svg {
@@ -802,6 +871,11 @@
stroke-width: 1.9;
}
.sstep-line-card .sstep-chart-wrap.is-dense .trend-line,
.sstep-line-card .sstep-chart-wrap.is-dense .sstep-fit-line {
stroke-width: 1.45;
}
.sstep-multi-area {
fill: var(--sstep-series-color, var(--ctx-cached));
fill-opacity: 0.08;
@@ -897,16 +971,16 @@
}
.sstep-anomaly-dot {
stroke: var(--metric-warn);
stroke-width: 1.5;
stroke-opacity: 0.82;
stroke-linecap: round;
fill: var(--metric-warn);
stroke: none;
pointer-events: none;
transition:
cx 240ms cubic-bezier(0.22, 1, 0.36, 1),
cy 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
.sstep-anomaly-dot.is-danger {
stroke: var(--metric-danger);
stroke-opacity: 0.92;
fill: var(--metric-danger);
}
.sstep-scatter-dot.is-anomaly {
@@ -1138,25 +1212,15 @@
white-space: nowrap;
}
.smodel-calls-pill {
flex-shrink: 0;
font-size: var(--fs-xs);
font-weight: 500;
padding: 1px 5px;
color: var(--text-secondary);
background: var(--surface-track);
border-radius: var(--radius-xs);
}
.smodel-totals {
display: inline-flex;
align-items: baseline;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.smodel-tok {
font-size: var(--fs-base-sm);
font-size: var(--fs-base);
font-weight: 500;
color: var(--text-secondary);
}
@@ -1174,22 +1238,13 @@
.smodel-foot {
display: flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
gap: 4px 10px;
font-size: var(--fs-md);
color: var(--text-secondary);
}
.smodel-split {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 10px;
color: var(--text-secondary);
}
.smodel-split strong {
.smodel-foot strong {
color: var(--text-primary);
font-weight: 600;
}
File diff suppressed because it is too large Load Diff
+20 -6
View File
@@ -11,11 +11,12 @@ import { telemetryStore } from '../store/telemetryStore.js';
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
export const SHOW_ACCOUNT_TAB = false;
export const SHOW_ACCOUNT_TAB = true;
function getSettingsSubTabOptions() {
return [
@@ -51,10 +52,11 @@ export const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
let showingAccount = false;
let preloadedAccountOnce = false;
function applyActiveSubTab(subTab, activeView) {
const target =
subTab === 'structure' ||
@@ -69,6 +71,10 @@ export const SettingsView = defineComponent({
patchAttr(otherTab.el, 'hidden', target !== 'other');
if (accountTab) {
patchAttr(accountTab.el, 'hidden', target !== 'account');
if (activeView === 'settings' && !preloadedAccountOnce) {
preloadedAccountOnce = true;
void accountTab.refs.preload?.();
}
const nextShowingAccount = target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
@@ -102,6 +108,9 @@ export const SettingsView = defineComponent({
if (getVisibleMonitorView(ui) !== 'settings') return;
const telemetry = telemetryStore.getState().telemetry;
const settings = telemetry?.settings;
if (accountTab) {
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas, settings);
}
if (settingsSubTab === 'structure') {
if (settings) {
structureTab.refs.renderSettings(
@@ -122,10 +131,15 @@ export const SettingsView = defineComponent({
telemetry?.cloudCodeProxy
);
}
} else if (accountTab && settingsSubTab === 'account') {
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
} else {
if (settings) generalTab.refs.renderSettings(settings);
} else if (settingsSubTab !== 'account') {
if (settings) {
generalTab.refs.renderSettings(
settings,
telemetry?.windowBridge,
telemetry?.hostPlatform
);
}
void generalTab.refs.loadHostI18n?.(false);
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
}
refreshScroll();

Some files were not shown because too many files have changed in this diff Show More