mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): add local CloudCode proxy sync and independent Main/Subagent-Swarm context window toggles (#36)
This commit is contained in:
+144
-4
@@ -1955,6 +1955,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!',
|
||||
'settings.oth.ctxRiskAcceptBtn': '我已知晓风险,继续使用',
|
||||
'settings.oth.ctxModel': '模型',
|
||||
'settings.oth.ctxMainLabel': '主代理',
|
||||
'settings.oth.ctxSwarmLabel': '子代理与蜂群',
|
||||
'settings.oth.ctxSwarmError': '本地同步异常:{error}',
|
||||
'settings.oth.ctxBaselineLabel': '上下文窗口上限',
|
||||
'settings.oth.ctxChooseModel': '选择模型',
|
||||
'settings.oth.ctxDefault': '跟随宿主设置',
|
||||
@@ -2833,6 +2836,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits 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.oth.ctxRiskAcceptBtn': 'I Understand the Risk, Unlock',
|
||||
'settings.oth.ctxModel': 'Model',
|
||||
'settings.oth.ctxMainLabel': 'Main Agent',
|
||||
'settings.oth.ctxSwarmLabel': 'Subagents & Swarm',
|
||||
'settings.oth.ctxSwarmError': 'Local sync failed: {error}',
|
||||
'settings.oth.ctxBaselineLabel': 'Context Window Limit',
|
||||
'settings.oth.ctxChooseModel': 'Choose a model',
|
||||
'settings.oth.ctxDefault': 'Follow host settings',
|
||||
@@ -9211,6 +9217,20 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
(pSet?.contextWindowMainEnabled !== false) !== (nSet?.contextWindowMainEnabled !== false) ||
|
||||
Boolean(pSet?.contextWindowSwarmEnabled) !== Boolean(nSet?.contextWindowSwarmEnabled)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
(prev.cloudCodeProxy?.state || 'disabled') !== (next.cloudCodeProxy?.state || 'disabled') ||
|
||||
Number(prev.cloudCodeProxy?.ruleCount || 0) !== Number(next.cloudCodeProxy?.ruleCount || 0) ||
|
||||
String(prev.cloudCodeProxy?.error || '') !== String(next.cloudCodeProxy?.error || '') ||
|
||||
Number(prev.cloudCodeProxy?.syncedAtMs || 0) !== Number(next.cloudCodeProxy?.syncedAtMs || 0)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
JSON.stringify(pSet?.modelContextWindows) !== JSON.stringify(nSet?.modelContextWindows) ||
|
||||
JSON.stringify(prev.contextWindowModels) !== JSON.stringify(next.contextWindowModels)
|
||||
@@ -10527,6 +10547,12 @@ async function saveSettingsPatch(patch) {
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowRiskAccepted')) {
|
||||
safePatch.contextWindowRiskAccepted = Boolean(safePatch.contextWindowRiskAccepted);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowMainEnabled')) {
|
||||
safePatch.contextWindowMainEnabled = Boolean(safePatch.contextWindowMainEnabled);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowSwarmEnabled')) {
|
||||
safePatch.contextWindowSwarmEnabled = Boolean(safePatch.contextWindowSwarmEnabled);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) {
|
||||
safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode);
|
||||
}
|
||||
@@ -27065,8 +27091,12 @@ const SettingsOtherTab = defineComponent({
|
||||
let draftExperimentalQuotaReservation = false;
|
||||
let draftContextRiskAccepted = false;
|
||||
let acceptingContextRisk = false;
|
||||
let draftContextMainEnabled = true;
|
||||
let draftContextSwarmEnabled = false;
|
||||
let savingContextScope = false;
|
||||
let latestSettings = null;
|
||||
let latestWindowBridge = null;
|
||||
let latestCloudCodeProxy = null;
|
||||
let latestHostPlatform = 'win32';
|
||||
let contextWindowModels = [];
|
||||
let contextModelId = '';
|
||||
@@ -27346,10 +27376,79 @@ const SettingsOtherTab = defineComponent({
|
||||
},
|
||||
});
|
||||
const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true });
|
||||
const ctxMainLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.ctxMainLabel'),
|
||||
});
|
||||
const ctxMainToggle = SegmentedControl({
|
||||
modelValue: 'on',
|
||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||
const nextEnabled = val === 'on';
|
||||
const prevEnabled = draftContextMainEnabled;
|
||||
savingContextScope = true;
|
||||
draftContextMainEnabled = nextEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: nextEnabled };
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
await saveSettingsPatch({ contextWindowMainEnabled: nextEnabled });
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
draftContextMainEnabled = prevEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: prevEnabled };
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
savingContextScope = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
});
|
||||
const ctxSwarmLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.ctxSwarmLabel'),
|
||||
});
|
||||
const ctxSwarmToggle = SegmentedControl({
|
||||
modelValue: 'off',
|
||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||
const nextEnabled = val === 'on';
|
||||
const prevEnabled = draftContextSwarmEnabled;
|
||||
savingContextScope = true;
|
||||
draftContextSwarmEnabled = nextEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: nextEnabled };
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
await saveSettingsPatch({ contextWindowSwarmEnabled: nextEnabled });
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
draftContextSwarmEnabled = prevEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: prevEnabled };
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
savingContextScope = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
});
|
||||
const ctxMainRow = h('div', { className: 'form-row' }, [ctxMainLabelEl, ctxMainToggle.el]);
|
||||
const ctxSwarmRow = h('div', { className: 'form-row' }, [ctxSwarmLabelEl, ctxSwarmToggle.el]);
|
||||
const ctxSyncStatusEl = h('span', {
|
||||
className: 'settings-hint-text ctx-sync-status is-error',
|
||||
hidden: true,
|
||||
});
|
||||
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
|
||||
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
|
||||
const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [
|
||||
ctxBridgeNotice.el,
|
||||
ctxMainRow,
|
||||
ctxSwarmRow,
|
||||
ctxSyncStatusEl,
|
||||
ctxModelRow,
|
||||
ctxWindowRow,
|
||||
h('div', { className: 'form-row' }, [ctxHint]),
|
||||
@@ -27428,8 +27527,31 @@ const SettingsOtherTab = defineComponent({
|
||||
const saved = latestSettings?.modelContextWindows || {};
|
||||
const wbState = String(latestWindowBridge?.state || '').trim();
|
||||
const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable';
|
||||
const proxyState = String(latestCloudCodeProxy?.state || 'disabled');
|
||||
const isProxyActive = Boolean(latestCloudCodeProxy?.active && proxyState === 'active');
|
||||
|
||||
patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel'));
|
||||
ctxMainToggle.setProps({
|
||||
modelValue: draftContextMainEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
||||
});
|
||||
patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel'));
|
||||
ctxSwarmToggle.setProps({
|
||||
modelValue: draftContextSwarmEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
||||
});
|
||||
|
||||
const syncErrorText =
|
||||
draftContextSwarmEnabled && proxyState === 'error' && latestCloudCodeProxy?.error
|
||||
? t('settings.oth.ctxSwarmError', { error: latestCloudCodeProxy.error })
|
||||
: '';
|
||||
patchAttr(ctxSyncStatusEl, 'hidden', !syncErrorText);
|
||||
patchText(ctxSyncStatusEl, syncErrorText);
|
||||
|
||||
ctxBridgeNotice.refs.update({
|
||||
visible: unlocked,
|
||||
visible: unlocked && draftContextMainEnabled,
|
||||
windowBridge: latestWindowBridge,
|
||||
hostPlatform: latestHostPlatform,
|
||||
});
|
||||
@@ -27477,7 +27599,13 @@ const SettingsOtherTab = defineComponent({
|
||||
else if (value) {
|
||||
const name = formatLimit(value);
|
||||
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
|
||||
else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name });
|
||||
else if (
|
||||
isBridgeMissing &&
|
||||
draftContextMainEnabled &&
|
||||
!(draftContextSwarmEnabled && isProxyActive)
|
||||
) {
|
||||
meta = t('settings.oth.ctxPendingBridge', { name });
|
||||
}
|
||||
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
|
||||
meta = t('settings.oth.ctxConfiguredReported', {
|
||||
name,
|
||||
@@ -27765,13 +27893,15 @@ const SettingsOtherTab = defineComponent({
|
||||
settings,
|
||||
models = contextWindowModels,
|
||||
windowBridge = latestWindowBridge,
|
||||
hostPlatform = latestHostPlatform
|
||||
hostPlatform = latestHostPlatform,
|
||||
cloudCodeProxy = latestCloudCodeProxy
|
||||
) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
contextWindowModels = models;
|
||||
if (windowBridge !== undefined) latestWindowBridge = windowBridge;
|
||||
if (hostPlatform) latestHostPlatform = hostPlatform;
|
||||
if (cloudCodeProxy !== undefined) latestCloudCodeProxy = cloudCodeProxy;
|
||||
draftModelDisplayMode = normalizeClientModelDisplayMode(
|
||||
settings.modelDisplayMode,
|
||||
settings.showUpstreamModel
|
||||
@@ -27783,6 +27913,10 @@ const SettingsOtherTab = defineComponent({
|
||||
if (!acceptingContextRisk) {
|
||||
draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted);
|
||||
}
|
||||
if (!savingContextScope) {
|
||||
draftContextMainEnabled = settings.contextWindowMainEnabled !== false;
|
||||
draftContextSwarmEnabled = settings.contextWindowSwarmEnabled === true;
|
||||
}
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftModelDisplayMode,
|
||||
options: getStepModelDisplayOptions(),
|
||||
@@ -27858,6 +27992,8 @@ const SettingsOtherTab = defineComponent({
|
||||
orchestratorIdSelect.destroy();
|
||||
quotaReserveToggle.destroy();
|
||||
ctxBridgeNotice.destroy();
|
||||
ctxMainToggle.destroy();
|
||||
ctxSwarmToggle.destroy();
|
||||
ctxModelSelect.destroy();
|
||||
ctxWindowSelect.destroy();
|
||||
sessionMigrationCard.destroy();
|
||||
@@ -27871,6 +28007,8 @@ const SettingsOtherTab = defineComponent({
|
||||
quotaReserveToggle,
|
||||
exportReserveLogBtn,
|
||||
ctxBridgeNotice,
|
||||
ctxMainToggle,
|
||||
ctxSwarmToggle,
|
||||
ctxModelSelect,
|
||||
ctxWindowSelect,
|
||||
sessionMigrationCard,
|
||||
@@ -32899,7 +33037,8 @@ const SettingsView = defineComponent({
|
||||
settings,
|
||||
telemetry.contextWindowModels || [],
|
||||
telemetry?.windowBridge,
|
||||
telemetry?.hostPlatform
|
||||
telemetry?.hostPlatform,
|
||||
telemetry?.cloudCodeProxy
|
||||
);
|
||||
}
|
||||
} else if (accountTab && settingsSubTab === 'account') {
|
||||
@@ -32915,6 +33054,7 @@ const SettingsView = defineComponent({
|
||||
(st) => ({
|
||||
settings: st.telemetry?.settings,
|
||||
windowBridge: st.telemetry?.windowBridge,
|
||||
cloudCodeProxy: st.telemetry?.cloudCodeProxy,
|
||||
cliStatusLine: st.telemetry?.cliStatusLine,
|
||||
hostPlatform: st.telemetry?.hostPlatform,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
|
||||
@@ -376,12 +376,16 @@ export function executeSettingsAction(data) {
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
);
|
||||
const contextWindowScopeChanged =
|
||||
(updated.contextWindowMainEnabled !== false) !== (current.contextWindowMainEnabled !== false) ||
|
||||
(updated.contextWindowSwarmEnabled === true) !== (current.contextWindowSwarmEnabled === true);
|
||||
const affectsBackendTelemetry =
|
||||
updated.weeklyLimitMode !== current.weeklyLimitMode ||
|
||||
updated.weeklyTokenBudget !== current.weeklyTokenBudget ||
|
||||
updated.weeklyCostBudget !== current.weeklyCostBudget ||
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode;
|
||||
updated.windowMountMode !== prevMountMode ||
|
||||
contextWindowScopeChanged;
|
||||
inFlightRequests.clear();
|
||||
if (affectsBackendTelemetry) {
|
||||
clearTelemetryBuilderMemo();
|
||||
@@ -391,6 +395,8 @@ export function executeSettingsAction(data) {
|
||||
updated.windowMountMode !== prevMountMode
|
||||
) {
|
||||
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||
} else if (contextWindowScopeChanged) {
|
||||
void notifyModelContextWindowsChanged();
|
||||
}
|
||||
if ((updated.enableCliStatusLine !== false) !== (current.enableCliStatusLine !== false)) {
|
||||
ensureCliStatusLineConfigured({ enabled: updated.enableCliStatusLine !== false });
|
||||
@@ -514,7 +520,11 @@ export function executeResetSettingsAction() {
|
||||
updated.windowMountMode !== prevMountMode
|
||||
) {
|
||||
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||
} else if (Object.keys(current.modelContextWindows).length) {
|
||||
} else if (
|
||||
Object.keys(current.modelContextWindows).length ||
|
||||
current.contextWindowMainEnabled === false ||
|
||||
current.contextWindowSwarmEnabled === true
|
||||
) {
|
||||
void notifyModelContextWindowsChanged();
|
||||
}
|
||||
if ((updated.enableCliStatusLine !== false) !== (current.enableCliStatusLine !== false)) {
|
||||
|
||||
@@ -0,0 +1,827 @@
|
||||
/**
|
||||
* @fileoverview 本地透明 CloudCode 反代与 `SetCloudCodeURL` 调度器 (`cloudcode-proxy.mjs`)。
|
||||
*
|
||||
* 用于在不修改宿主二进制、无需 `--dev_mode` 或自签证书的前提下,通过 Language Server 原生
|
||||
* `SetCloudCodeURL` RPC 将 `/v1internal:fetchAvailableModels` 流量经由 `127.0.0.1` 随机端口
|
||||
* 透明转发至官方 CloudCode 上游,并在响应中按模型改写 `CASCADE_USE_EXPERIMENT_CHECKPOINTER`
|
||||
* 实验配置(覆盖非 `self` 子代理与蜂群 worker),其余请求零缓冲流式透传。
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { lsRuntimeEndpoint } from './config.mjs';
|
||||
import { callLsRpc } from './ls-rpc.mjs';
|
||||
|
||||
export const DEFAULT_UPSTREAM_CLOUDCODE_URL = 'https://daily-cloudcode-pa.googleapis.com';
|
||||
|
||||
const CC_PROXY_UPSTREAM_URL_RE = /https:\/\/[a-z0-9.-]*cloudcode-pa\.googleapis\.com/gi;
|
||||
const CC_PROXY_CHECKPOINTER_KEY = 'CASCADE_USE_EXPERIMENT_CHECKPOINTER';
|
||||
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;
|
||||
|
||||
let ccProxyNodeModulesPromise = null;
|
||||
|
||||
async function loadCcProxyNodeModules() {
|
||||
if (!ccProxyNodeModulesPromise) {
|
||||
ccProxyNodeModulesPromise = Promise.all([
|
||||
import('node:http'),
|
||||
import('node:https'),
|
||||
import('node:tls'),
|
||||
import('node:zlib'),
|
||||
import('node:child_process'),
|
||||
import('node:fs'),
|
||||
]).then(([httpMod, httpsMod, tlsMod, zlibMod, cpMod, fsMod]) => ({
|
||||
http: httpMod.default || httpMod,
|
||||
https: httpsMod.default || httpsMod,
|
||||
tls: tlsMod.default || tlsMod,
|
||||
zlib: zlibMod.default || zlibMod,
|
||||
execFileSync: cpMod.execFileSync,
|
||||
openSync: fsMod.openSync,
|
||||
readSync: fsMod.readSync,
|
||||
closeSync: fsMod.closeSync,
|
||||
}));
|
||||
}
|
||||
return ccProxyNodeModulesPromise;
|
||||
}
|
||||
|
||||
function isCcProxyLoopbackHost(hostname) {
|
||||
const host = String(hostname || '').trim().toLowerCase().replace(/^\[|\]$/g, '');
|
||||
return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '0.0.0.0';
|
||||
}
|
||||
|
||||
export function isValidUpstreamCloudCodeUrl(rawUrl, { allowHttp = false } = {}) {
|
||||
try {
|
||||
const parsed = new URL(String(rawUrl || '').trim());
|
||||
if (parsed.protocol !== 'https:' && !(allowHttp && parsed.protocol === 'http:')) {
|
||||
return false;
|
||||
}
|
||||
if (!allowHttp && isCcProxyLoopbackHost(parsed.hostname)) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(parsed.hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function readLogFileTailUtf8(filePath, sizeBytes, fsTailOps = null) {
|
||||
if (!Number.isFinite(sizeBytes) || sizeBytes <= CC_PROXY_MAX_LOG_READ_BYTES || !fsTailOps) {
|
||||
return readFileSync(filePath, 'utf8');
|
||||
}
|
||||
const { openSync, readSync, closeSync } = fsTailOps;
|
||||
const start = Math.max(0, sizeBytes - CC_PROXY_MAX_LOG_READ_BYTES);
|
||||
const length = sizeBytes - start;
|
||||
const fd = openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.allocUnsafe(length);
|
||||
const bytesRead = readSync(fd, buf, 0, length, start);
|
||||
return buf.subarray(0, bytesRead).toString('utf8');
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function getCcProxyLogCandidateDirs(env, platform, homeDir) {
|
||||
const safeEnv = env || {};
|
||||
const home = String(homeDir || '').trim();
|
||||
if (platform === 'win32') {
|
||||
return [
|
||||
safeEnv.APPDATA ? join(safeEnv.APPDATA, 'Antigravity', 'logs') : '',
|
||||
safeEnv.LOCALAPPDATA ? join(safeEnv.LOCALAPPDATA, 'Antigravity', 'logs') : '',
|
||||
home ? join(home, '.gemini', 'antigravity', 'logs') : '',
|
||||
].filter(Boolean);
|
||||
}
|
||||
if (platform === 'darwin') {
|
||||
return [
|
||||
home ? join(home, 'Library', 'Application Support', 'Antigravity', 'logs') : '',
|
||||
home ? join(home, '.gemini', 'antigravity', 'logs') : '',
|
||||
].filter(Boolean);
|
||||
}
|
||||
return [
|
||||
home ? join(home, '.config', 'Antigravity', 'logs') : '',
|
||||
home ? join(home, '.gemini', 'antigravity', 'logs') : '',
|
||||
].filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 探测宿主真实上游 CloudCode URL(严格排除本地回环地址,防止自环)。
|
||||
*
|
||||
* @param {object} [opts]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function detectUpstreamCloudCodeUrl({
|
||||
env = process.env,
|
||||
platform = process.platform,
|
||||
homeDir = homedir(),
|
||||
fsTailOps = null,
|
||||
} = {}) {
|
||||
const envUrl = String(env?.ANTIGRAVITY_CLOUDCODE_URL || env?.CLOUDCODE_URL || '').trim();
|
||||
if (isValidUpstreamCloudCodeUrl(envUrl)) {
|
||||
return envUrl.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
for (const dir of getCcProxyLogCandidateDirs(env, platform, homeDir)) {
|
||||
if (!existsSync(dir)) continue;
|
||||
try {
|
||||
const entries = readdirSync(dir)
|
||||
.filter((name) => /\.log$/i.test(String(name || '')))
|
||||
.map((name) => {
|
||||
const fullPath = join(dir, String(name));
|
||||
const st = statSync(fullPath);
|
||||
return { fullPath, mtimeMs: Number(st?.mtimeMs || 0), size: Number(st?.size || 0) };
|
||||
})
|
||||
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||||
for (const item of entries.slice(0, 5)) {
|
||||
const text = readLogFileTailUtf8(item.fullPath, item.size, fsTailOps);
|
||||
const matches = text.match(CC_PROXY_UPSTREAM_URL_RE);
|
||||
if (matches && matches.length > 0) {
|
||||
for (let i = matches.length - 1; i >= 0; i -= 1) {
|
||||
const candidate = matches[i].replace(/\/+$/, '');
|
||||
if (isValidUpstreamCloudCodeUrl(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略单个日志目录读取异常
|
||||
}
|
||||
}
|
||||
|
||||
return DEFAULT_UPSTREAM_CLOUDCODE_URL;
|
||||
}
|
||||
|
||||
function shouldCcProxyBypassHost(hostname, noProxyRaw) {
|
||||
const target = String(hostname || '').trim().toLowerCase();
|
||||
const list = String(noProxyRaw || '').trim();
|
||||
if (!target || !list) return false;
|
||||
for (const part of list.split(/[;,]/)) {
|
||||
const raw = part.trim().toLowerCase();
|
||||
if (!raw) continue;
|
||||
if (raw === '*') return true;
|
||||
const rule = raw.replace(/^\*\./, '.').replace(/:\d+$/, '');
|
||||
if (!rule) continue;
|
||||
if (rule.startsWith('.')) {
|
||||
if (target.endsWith(rule) || target === rule.slice(1)) return true;
|
||||
} else if (target === rule || target.endsWith(`.${rule}`)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function parseWindowsProxyServerValue(rawVal) {
|
||||
let 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();
|
||||
}
|
||||
if (!srv) return '';
|
||||
return /^https?:\/\//i.test(srv) ? srv : `http://${srv}`;
|
||||
}
|
||||
|
||||
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}`;
|
||||
if (platform !== 'win32') return '';
|
||||
try {
|
||||
const { execFileSync } = await loadCcProxyNodeModules();
|
||||
const out = execFileSync(
|
||||
'reg',
|
||||
['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'],
|
||||
{ encoding: 'utf8', timeout: 2500, windowsHide: true }
|
||||
);
|
||||
if (!/ProxyEnable\s+REG_DWORD\s+0x1\b/i.test(out)) return '';
|
||||
const overrideMatch = out.match(/ProxyOverride\s+REG_SZ\s+([^\r\n]+)/i);
|
||||
if (overrideMatch && shouldCcProxyBypassHost(targetHostname, overrideMatch[1])) {
|
||||
return '';
|
||||
}
|
||||
const serverMatch = out.match(/ProxyServer\s+REG_SZ\s+([^\r\n]+)/i);
|
||||
return serverMatch ? parseWindowsProxyServerValue(serverMatch[1]) : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function parseCcProxyPositiveLimit(rawValue) {
|
||||
const num = Number(rawValue);
|
||||
return Number.isSafeInteger(num) && num > 0 ? num : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从模型目录(`GetAvailableModels` 或 `/v1internal:fetchAvailableModels` 的 `models` 映射)中
|
||||
* 提取各模型上游原始的 `CASCADE_USE_EXPERIMENT_CHECKPOINTER.max_token_limit`。
|
||||
*
|
||||
* @param {Record<string, any>|null|undefined} modelsMap
|
||||
* @returns {Record<string, number>}
|
||||
*/
|
||||
export function extractUpstreamCheckpointDefaults(modelsMap) {
|
||||
const defaultsByModelId = {};
|
||||
if (!modelsMap || typeof modelsMap !== 'object' || Array.isArray(modelsMap)) {
|
||||
return defaultsByModelId;
|
||||
}
|
||||
for (const entry of Object.values(modelsMap)) {
|
||||
const modelId = typeof entry?.model === 'string' ? entry.model.trim() : '';
|
||||
if (!modelId) continue;
|
||||
const rawStr = entry?.modelExperiments?.experiments?.[CC_PROXY_CHECKPOINTER_KEY]?.stringValue;
|
||||
if (typeof rawStr !== 'string' || !rawStr.trim()) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(rawStr);
|
||||
const lim = parseCcProxyPositiveLimit(parsed?.max_token_limit ?? parsed?.maxTokenLimit);
|
||||
if (lim !== null) {
|
||||
defaultsByModelId[modelId] = lim;
|
||||
}
|
||||
} catch {
|
||||
// 忽略非法 JSON
|
||||
}
|
||||
}
|
||||
return defaultsByModelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按解析后的 `rulesByModelId`(键为 `MODEL_*` 枚举 ID,值为数值 token 上限或命名档位)
|
||||
* 原地改写 `/v1internal:fetchAvailableModels` 响应体中的 `CASCADE_USE_EXPERIMENT_CHECKPOINTER`。
|
||||
*
|
||||
* @param {any} fetchResp
|
||||
* @param {Record<string, number|string>} rulesByModelId
|
||||
* @returns {{ modified: boolean, applied: Array<{ modelKey: string, modelId: string, prevLimit: number|null, nextRule: number|string }>, defaultsByModelId: Record<string, number> }}
|
||||
*/
|
||||
export function rewriteFetchAvailableModelsPayload(fetchResp, rulesByModelId) {
|
||||
const models = fetchResp?.models;
|
||||
const defaultsByModelId = extractUpstreamCheckpointDefaults(models);
|
||||
if (
|
||||
!models ||
|
||||
typeof models !== 'object' ||
|
||||
Array.isArray(models) ||
|
||||
!rulesByModelId ||
|
||||
typeof rulesByModelId !== 'object'
|
||||
) {
|
||||
return { modified: false, applied: [], defaultsByModelId };
|
||||
}
|
||||
|
||||
const applied = [];
|
||||
for (const [modelKey, entry] of Object.entries(models)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const modelId = typeof entry.model === 'string' ? entry.model.trim() : '';
|
||||
if (!modelId || !Object.prototype.hasOwnProperty.call(rulesByModelId, modelId)) continue;
|
||||
const rule = rulesByModelId[modelId];
|
||||
const isNumericRule = typeof rule === 'number' && Number.isSafeInteger(rule) && rule > 0;
|
||||
const isNamedRule = typeof rule === 'string' && rule.trim().length > 0;
|
||||
if (!isNumericRule && !isNamedRule) continue;
|
||||
|
||||
if (!entry.modelExperiments || typeof entry.modelExperiments !== 'object') {
|
||||
entry.modelExperiments = {};
|
||||
}
|
||||
if (!entry.modelExperiments.experiments || typeof entry.modelExperiments.experiments !== 'object') {
|
||||
entry.modelExperiments.experiments = {};
|
||||
}
|
||||
const expMap = entry.modelExperiments.experiments;
|
||||
const ckKeys = Object.keys(expMap).filter(
|
||||
(k) => k === CC_PROXY_CHECKPOINTER_KEY || k.startsWith(CC_PROXY_CHECKPOINTER_PREFIX)
|
||||
);
|
||||
if (!ckKeys.includes(CC_PROXY_CHECKPOINTER_KEY)) {
|
||||
ckKeys.unshift(CC_PROXY_CHECKPOINTER_KEY);
|
||||
}
|
||||
|
||||
const prevLimit = defaultsByModelId[modelId] ?? null;
|
||||
if (isNumericRule) {
|
||||
for (const ckKey of ckKeys) {
|
||||
const prevRaw = expMap[ckKey]?.stringValue;
|
||||
let ckObj = {};
|
||||
if (typeof prevRaw === 'string' && prevRaw.trim()) {
|
||||
try {
|
||||
const parsed = JSON.parse(prevRaw);
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
ckObj = parsed;
|
||||
}
|
||||
} catch {
|
||||
ckObj = {};
|
||||
}
|
||||
}
|
||||
ckObj.max_token_limit = String(rule);
|
||||
delete ckObj.maxTokenLimit;
|
||||
expMap[ckKey] = {
|
||||
...(expMap[ckKey] && typeof expMap[ckKey] === 'object' ? expMap[ckKey] : {}),
|
||||
stringValue: JSON.stringify(ckObj),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
const variantKey = `${CC_PROXY_CHECKPOINTER_PREFIX}context-window_${rule.trim()}`;
|
||||
const variantRaw = expMap[variantKey]?.stringValue;
|
||||
if (typeof variantRaw !== 'string' || !variantRaw.trim()) {
|
||||
continue;
|
||||
}
|
||||
for (const ckKey of ckKeys) {
|
||||
expMap[ckKey] = {
|
||||
...(expMap[ckKey] && typeof expMap[ckKey] === 'object' ? expMap[ckKey] : {}),
|
||||
stringValue: variantRaw,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(entry.ignoreExperiments)) {
|
||||
entry.ignoreExperiments = entry.ignoreExperiments.filter(
|
||||
(x) =>
|
||||
x !== CC_PROXY_CHECKPOINTER_KEY &&
|
||||
!String(x || '').startsWith(CC_PROXY_CHECKPOINTER_PREFIX) &&
|
||||
x !== 'checkpoint-variant'
|
||||
);
|
||||
}
|
||||
|
||||
applied.push({ modelKey, modelId, prevLimit, nextRule: rule });
|
||||
}
|
||||
|
||||
return { modified: applied.length > 0, applied, defaultsByModelId };
|
||||
}
|
||||
|
||||
function sanitizeCcProxyRules(rulesByModelId) {
|
||||
const out = {};
|
||||
if (!rulesByModelId || typeof rulesByModelId !== 'object' || Array.isArray(rulesByModelId)) {
|
||||
return out;
|
||||
}
|
||||
for (const [modelId, value] of Object.entries(rulesByModelId)) {
|
||||
if (!modelId) continue;
|
||||
if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
|
||||
out[modelId] = value;
|
||||
} else if (typeof value === 'string' && value.trim().length > 0) {
|
||||
out[modelId] = value.trim();
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function canonicalizeCcProxyRules(rules) {
|
||||
const keys = Object.keys(rules).sort();
|
||||
return JSON.stringify(keys.map((k) => [k, rules[k]]));
|
||||
}
|
||||
|
||||
function decompressCcProxyBody(zlib, buf, encoding) {
|
||||
const enc = String(encoding || '').toLowerCase();
|
||||
if (enc.includes('gzip')) return zlib.gunzipSync(buf);
|
||||
if (enc.includes('deflate')) return zlib.inflateSync(buf);
|
||||
if (enc.includes('br')) return zlib.brotliDecompressSync(buf);
|
||||
return buf;
|
||||
}
|
||||
|
||||
function openCcProxyTunnelSocket(http, tls, targetHost, targetPort, proxyUrl) {
|
||||
if (!proxyUrl) return Promise.resolve(null);
|
||||
const parsedProxy = new URL(proxyUrl);
|
||||
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}` },
|
||||
});
|
||||
connectReq.on('connect', (res, socket) => {
|
||||
if (res.statusCode !== 200) {
|
||||
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);
|
||||
});
|
||||
connectReq.on('error', reject);
|
||||
connectReq.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建本地 CloudCode 反代生命周期控制器。
|
||||
*
|
||||
* @param {object} [options]
|
||||
*/
|
||||
export function createCloudCodeProxyController({
|
||||
callRpcFn = callLsRpc,
|
||||
getEndpointFn = () => lsRuntimeEndpoint,
|
||||
detectUpstreamFn = null,
|
||||
detectProxyFn = null,
|
||||
allowHttpUpstream = false,
|
||||
allowTestEndpoint = false,
|
||||
retryCooldownMs = CC_PROXY_RETRY_COOLDOWN_MS,
|
||||
} = {}) {
|
||||
let server = null;
|
||||
let localUrl = '';
|
||||
let upstreamUrl = '';
|
||||
let lsSwitched = false;
|
||||
let activeRules = {};
|
||||
let upstreamDefaults = {};
|
||||
let appliedSig = '';
|
||||
let lastFailedSig = '';
|
||||
let lastErrorAtMs = 0;
|
||||
let cachedSysProxy = { url: '', checkedAtMs: 0, host: '' };
|
||||
let syncChain = Promise.resolve();
|
||||
|
||||
let status = {
|
||||
state: 'disabled', // 'disabled' | 'active' | 'error'
|
||||
active: false,
|
||||
ruleCount: 0,
|
||||
appliedModels: [],
|
||||
upstreamUrl: '',
|
||||
localUrl: '',
|
||||
syncedAtMs: 0,
|
||||
error: '',
|
||||
};
|
||||
|
||||
function getStatus() {
|
||||
return {
|
||||
...status,
|
||||
appliedModels: [...status.appliedModels],
|
||||
};
|
||||
}
|
||||
|
||||
function getUpstreamDefaults() {
|
||||
return { ...upstreamDefaults };
|
||||
}
|
||||
|
||||
function seedUpstreamDefaultsFromCatalog(catalogModels) {
|
||||
if (lsSwitched) return;
|
||||
const extracted = extractUpstreamCheckpointDefaults(catalogModels);
|
||||
if (Object.keys(extracted).length > 0) {
|
||||
upstreamDefaults = { ...upstreamDefaults, ...extracted };
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveUpstreamUrl() {
|
||||
if (upstreamUrl && isValidUpstreamCloudCodeUrl(upstreamUrl, { allowHttp: allowHttpUpstream })) {
|
||||
return upstreamUrl;
|
||||
}
|
||||
let detected = '';
|
||||
if (typeof detectUpstreamFn === 'function') {
|
||||
detected = String((await detectUpstreamFn()) || '').trim();
|
||||
} else {
|
||||
const mods = await loadCcProxyNodeModules().catch(() => null);
|
||||
detected = detectUpstreamCloudCodeUrl({
|
||||
fsTailOps: mods
|
||||
? { openSync: mods.openSync, readSync: mods.readSync, closeSync: mods.closeSync }
|
||||
: null,
|
||||
});
|
||||
}
|
||||
upstreamUrl = isValidUpstreamCloudCodeUrl(detected, { allowHttp: allowHttpUpstream })
|
||||
? detected.replace(/\/+$/, '')
|
||||
: DEFAULT_UPSTREAM_CLOUDCODE_URL;
|
||||
return upstreamUrl;
|
||||
}
|
||||
|
||||
async function resolveSystemProxyForHost(targetHostname) {
|
||||
const now = Date.now();
|
||||
if (
|
||||
cachedSysProxy.host === targetHostname &&
|
||||
now - cachedSysProxy.checkedAtMs < CC_PROXY_SYS_PROXY_CACHE_MS
|
||||
) {
|
||||
return cachedSysProxy.url;
|
||||
}
|
||||
let proxyUrl = '';
|
||||
if (typeof detectProxyFn === 'function') {
|
||||
proxyUrl = String((await detectProxyFn(targetHostname)) || '').trim();
|
||||
} else {
|
||||
proxyUrl = await detectSystemHttpsProxy(targetHostname);
|
||||
}
|
||||
cachedSysProxy = { host: targetHostname, url: proxyUrl, checkedAtMs: now };
|
||||
return proxyUrl;
|
||||
}
|
||||
|
||||
async function closeProxyServer() {
|
||||
const srv = server;
|
||||
server = null;
|
||||
localUrl = '';
|
||||
if (!srv) return;
|
||||
try {
|
||||
srv.closeAllConnections?.();
|
||||
} catch {
|
||||
// Node <18.2 fallback
|
||||
}
|
||||
await new Promise((resolve) => {
|
||||
try {
|
||||
srv.close(() => resolve());
|
||||
} catch {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureProxyServerStarted() {
|
||||
if (server && localUrl) return localUrl;
|
||||
const { http, https, tls, zlib } = await loadCcProxyNodeModules();
|
||||
const targetBase = await resolveUpstreamUrl();
|
||||
const upstreamParsed = new URL(targetBase);
|
||||
const isUpstreamHttps = upstreamParsed.protocol === 'https:';
|
||||
const upstreamPort = Number(upstreamParsed.port || (isUpstreamHttps ? 443 : 80));
|
||||
|
||||
const srv = http.createServer(async (req, res) => {
|
||||
const reqUrl = req.url || '/';
|
||||
const isFetchModels = reqUrl.includes('fetchAvailableModels');
|
||||
try {
|
||||
const fwdHeaders = { ...req.headers, host: upstreamParsed.host };
|
||||
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 upOpts = {
|
||||
hostname: upstreamParsed.hostname,
|
||||
port: upstreamPort,
|
||||
path: reqUrl,
|
||||
method: req.method,
|
||||
headers: fwdHeaders,
|
||||
...(customSocket ? { agent: false, createConnection: () => customSocket } : {}),
|
||||
};
|
||||
|
||||
req.setTimeout?.(0);
|
||||
const transport = isUpstreamHttps ? https : http;
|
||||
const upReq = transport.request(upOpts, (upRes) => {
|
||||
if (!isFetchModels || Number(upRes.statusCode || 0) !== 200) {
|
||||
res.writeHead(upRes.statusCode || 502, upRes.headers);
|
||||
res.flushHeaders?.();
|
||||
upRes.pipe(res);
|
||||
return;
|
||||
}
|
||||
const chunks = [];
|
||||
upRes.on('data', (chunk) => chunks.push(chunk));
|
||||
upRes.on('end', () => {
|
||||
const rawBuf = Buffer.concat(chunks);
|
||||
let outBuf = rawBuf;
|
||||
const outHeaders = { ...upRes.headers };
|
||||
try {
|
||||
const plain = decompressCcProxyBody(zlib, rawBuf, upRes.headers['content-encoding']);
|
||||
const parsed = JSON.parse(plain.toString('utf8'));
|
||||
const rewriteRes = rewriteFetchAvailableModelsPayload(parsed, activeRules);
|
||||
if (Object.keys(rewriteRes.defaultsByModelId).length > 0) {
|
||||
upstreamDefaults = { ...upstreamDefaults, ...rewriteRes.defaultsByModelId };
|
||||
}
|
||||
if (rewriteRes.modified) {
|
||||
const rewritten = Buffer.from(JSON.stringify(parsed), 'utf8');
|
||||
delete outHeaders['content-encoding'];
|
||||
delete outHeaders['transfer-encoding'];
|
||||
outHeaders['content-length'] = String(rewritten.length);
|
||||
outBuf = rewritten;
|
||||
status = {
|
||||
...status,
|
||||
syncedAtMs: Date.now(),
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// 解析失败时原样回传上游响应
|
||||
}
|
||||
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}`);
|
||||
});
|
||||
});
|
||||
|
||||
upReq.setTimeout?.(0);
|
||||
upReq.on('error', (err) => {
|
||||
if (!res.headersSent) res.writeHead(502);
|
||||
res.end(`Proxy upstream error: ${err.message}`);
|
||||
});
|
||||
req.pipe(upReq);
|
||||
} catch (err) {
|
||||
if (!res.headersSent) res.writeHead(502);
|
||||
res.end(`Proxy setup error: ${err.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
srv.once('error', reject);
|
||||
srv.listen(0, '127.0.0.1', () => {
|
||||
srv.off('error', reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
srv.unref?.();
|
||||
const addrInfo = srv.address();
|
||||
const port = typeof addrInfo === 'object' && addrInfo ? Number(addrInfo.port || 0) : 0;
|
||||
server = srv;
|
||||
localUrl = `http://127.0.0.1:${port}`;
|
||||
return localUrl;
|
||||
}
|
||||
|
||||
async function restoreLsCloudCodeUrl() {
|
||||
if (!lsSwitched) return;
|
||||
lsSwitched = false;
|
||||
appliedSig = '';
|
||||
const targetRestore = upstreamUrl || DEFAULT_UPSTREAM_CLOUDCODE_URL;
|
||||
try {
|
||||
await callRpcFn('SetCloudCodeURL', { url: targetRestore }, 4000);
|
||||
} catch {
|
||||
// 忽略 LS 已退出或暂不可达时的还原异常
|
||||
}
|
||||
}
|
||||
|
||||
async function reconcileInternal({ enabled = false, rulesByModelId = {}, initialCatalogModels = null } = {}) {
|
||||
if (initialCatalogModels) {
|
||||
seedUpstreamDefaultsFromCatalog(initialCatalogModels);
|
||||
}
|
||||
const cleanRules = sanitizeCcProxyRules(rulesByModelId);
|
||||
const ruleKeys = Object.keys(cleanRules);
|
||||
const shouldEnable = Boolean(enabled && ruleKeys.length > 0);
|
||||
const ep = getEndpointFn() || {};
|
||||
const hasUsableLs =
|
||||
Boolean(ep.baseUrl) && (allowTestEndpoint || String(ep.addr || '') !== 'test.invalid');
|
||||
|
||||
if (!shouldEnable) {
|
||||
activeRules = {};
|
||||
lastFailedSig = '';
|
||||
lastErrorAtMs = 0;
|
||||
if (lsSwitched && hasUsableLs) {
|
||||
await restoreLsCloudCodeUrl();
|
||||
} else {
|
||||
lsSwitched = false;
|
||||
appliedSig = '';
|
||||
}
|
||||
await closeProxyServer();
|
||||
status = {
|
||||
state: 'disabled',
|
||||
active: false,
|
||||
ruleCount: 0,
|
||||
appliedModels: [],
|
||||
upstreamUrl: upstreamUrl || '',
|
||||
localUrl: '',
|
||||
syncedAtMs: 0,
|
||||
error: '',
|
||||
};
|
||||
return getStatus();
|
||||
}
|
||||
|
||||
if (!hasUsableLs) {
|
||||
activeRules = cleanRules;
|
||||
status = {
|
||||
state: 'disabled',
|
||||
active: false,
|
||||
ruleCount: ruleKeys.length,
|
||||
appliedModels: ruleKeys,
|
||||
upstreamUrl: upstreamUrl || '',
|
||||
localUrl: '',
|
||||
syncedAtMs: 0,
|
||||
error: '',
|
||||
};
|
||||
return getStatus();
|
||||
}
|
||||
|
||||
activeRules = cleanRules;
|
||||
const epKey = `${String(ep.addr || ep.baseUrl)}|${String(ep.csrfToken || '')}`;
|
||||
const rulesCanon = canonicalizeCcProxyRules(cleanRules);
|
||||
const desiredSig = `${epKey}|${rulesCanon}`;
|
||||
|
||||
if (lsSwitched && server && localUrl && appliedSig === desiredSig && status.state === 'active') {
|
||||
return getStatus();
|
||||
}
|
||||
|
||||
if (
|
||||
lastFailedSig === desiredSig &&
|
||||
lastErrorAtMs > 0 &&
|
||||
Date.now() - lastErrorAtMs < retryCooldownMs
|
||||
) {
|
||||
return getStatus();
|
||||
}
|
||||
|
||||
try {
|
||||
const targetUpstream = await resolveUpstreamUrl();
|
||||
const listenUrl = await ensureProxyServerStarted();
|
||||
await callRpcFn('SetCloudCodeURL', { url: listenUrl }, 5000);
|
||||
lsSwitched = true;
|
||||
appliedSig = desiredSig;
|
||||
lastFailedSig = '';
|
||||
lastErrorAtMs = 0;
|
||||
status = {
|
||||
state: 'active',
|
||||
active: true,
|
||||
ruleCount: ruleKeys.length,
|
||||
appliedModels: ruleKeys,
|
||||
upstreamUrl: targetUpstream,
|
||||
localUrl: listenUrl,
|
||||
syncedAtMs: Date.now(),
|
||||
error: '',
|
||||
};
|
||||
} catch (err) {
|
||||
lastFailedSig = desiredSig;
|
||||
lastErrorAtMs = Date.now();
|
||||
if (!lsSwitched) {
|
||||
await closeProxyServer();
|
||||
}
|
||||
status = {
|
||||
state: 'error',
|
||||
active: false,
|
||||
ruleCount: ruleKeys.length,
|
||||
appliedModels: ruleKeys,
|
||||
upstreamUrl: upstreamUrl || '',
|
||||
localUrl: lsSwitched ? localUrl : '',
|
||||
syncedAtMs: status.syncedAtMs || 0,
|
||||
error: String(err?.message || 'SetCloudCodeURL failed'),
|
||||
};
|
||||
}
|
||||
return getStatus();
|
||||
}
|
||||
|
||||
function reconcile(opts) {
|
||||
syncChain = syncChain.then(() => reconcileInternal(opts)).catch(() => getStatus());
|
||||
return syncChain;
|
||||
}
|
||||
|
||||
function stop() {
|
||||
syncChain = syncChain
|
||||
.then(async () => {
|
||||
activeRules = {};
|
||||
lastFailedSig = '';
|
||||
lastErrorAtMs = 0;
|
||||
const ep = getEndpointFn() || {};
|
||||
const hasUsableLs =
|
||||
Boolean(ep.baseUrl) && (allowTestEndpoint || String(ep.addr || '') !== 'test.invalid');
|
||||
if (lsSwitched && hasUsableLs) {
|
||||
await restoreLsCloudCodeUrl();
|
||||
} else {
|
||||
lsSwitched = false;
|
||||
appliedSig = '';
|
||||
}
|
||||
await closeProxyServer();
|
||||
status = {
|
||||
state: 'disabled',
|
||||
active: false,
|
||||
ruleCount: 0,
|
||||
appliedModels: [],
|
||||
upstreamUrl: upstreamUrl || '',
|
||||
localUrl: '',
|
||||
syncedAtMs: 0,
|
||||
error: '',
|
||||
};
|
||||
return getStatus();
|
||||
})
|
||||
.catch(() => getStatus());
|
||||
return syncChain;
|
||||
}
|
||||
|
||||
return {
|
||||
reconcile,
|
||||
stop,
|
||||
getStatus,
|
||||
getUpstreamDefaults,
|
||||
seedUpstreamDefaultsFromCatalog,
|
||||
};
|
||||
}
|
||||
|
||||
let defaultCloudCodeProxyController = null;
|
||||
|
||||
export function getDefaultCloudCodeProxy() {
|
||||
if (!defaultCloudCodeProxyController) {
|
||||
defaultCloudCodeProxyController = createCloudCodeProxyController();
|
||||
}
|
||||
return defaultCloudCodeProxyController;
|
||||
}
|
||||
|
||||
export function getDefaultCloudCodeProxyStatus() {
|
||||
if (!defaultCloudCodeProxyController) {
|
||||
return {
|
||||
state: 'disabled',
|
||||
active: false,
|
||||
ruleCount: 0,
|
||||
appliedModels: [],
|
||||
upstreamUrl: '',
|
||||
localUrl: '',
|
||||
syncedAtMs: 0,
|
||||
error: '',
|
||||
};
|
||||
}
|
||||
return defaultCloudCodeProxyController.getStatus();
|
||||
}
|
||||
|
||||
export function getDefaultCloudCodeUpstreamDefaults() {
|
||||
if (!defaultCloudCodeProxyController) return {};
|
||||
return defaultCloudCodeProxyController.getUpstreamDefaults();
|
||||
}
|
||||
|
||||
export function reconcileDefaultCloudCodeProxy(opts) {
|
||||
return getDefaultCloudCodeProxy().reconcile(opts);
|
||||
}
|
||||
|
||||
export function stopDefaultCloudCodeProxy() {
|
||||
if (!defaultCloudCodeProxyController) return Promise.resolve();
|
||||
return defaultCloudCodeProxyController.stop();
|
||||
}
|
||||
@@ -122,18 +122,29 @@ export async function syncHostContextWindows(
|
||||
bootId,
|
||||
key = '__AGUsageMonitorContextWindows',
|
||||
fallbackRules = {},
|
||||
allowRemoteHost = false
|
||||
allowRemoteHost = false,
|
||||
overrideRules = null
|
||||
) {
|
||||
let state = window[key];
|
||||
const appConfig = window.__APP_CONFIG__;
|
||||
const csrfToken = appConfig?.csrfToken || state?.observedCsrfToken || '';
|
||||
const hasPrefs = Boolean(rules && Object.keys(rules).length > 0);
|
||||
const hasOverrideMode = Boolean(
|
||||
overrideRules && typeof overrideRules === 'object' && !Array.isArray(overrideRules)
|
||||
);
|
||||
const safeOverride = hasOverrideMode ? overrideRules : null;
|
||||
const hasPrefs = hasOverrideMode
|
||||
? Object.keys(safeOverride).length > 0
|
||||
: Boolean(rules && Object.keys(rules).length > 0);
|
||||
const safeFallback =
|
||||
fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules)
|
||||
? fallbackRules
|
||||
: {};
|
||||
const hasFallback = Object.keys(safeFallback).length > 0;
|
||||
if (!hasPrefs || (!allowRemoteHost && appConfig?.isRemoteControl) || (!csrfToken && !hasFallback)) {
|
||||
if (
|
||||
!hasPrefs ||
|
||||
(!allowRemoteHost && appConfig?.isRemoteControl) ||
|
||||
(!hasOverrideMode && !csrfToken && !hasFallback)
|
||||
) {
|
||||
state?.dispose();
|
||||
return { attached: false, ruleCount: 0 };
|
||||
}
|
||||
@@ -274,6 +285,11 @@ export async function syncHostContextWindows(
|
||||
clearTimeout(state.timer);
|
||||
state.timer = setTimeout(() => state.dispose(), 15000);
|
||||
|
||||
if (hasOverrideMode) {
|
||||
state.rules = { ...safeOverride };
|
||||
return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length };
|
||||
}
|
||||
|
||||
if (!csrfToken) {
|
||||
state.rules = { ...safeFallback };
|
||||
return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length };
|
||||
@@ -324,8 +340,13 @@ export function createContextWindowSyncExpression(
|
||||
preferences,
|
||||
bootId,
|
||||
fallbackRules = {},
|
||||
allowRemoteHost = false
|
||||
allowRemoteHost = false,
|
||||
overrideRules = null
|
||||
) {
|
||||
const safeOverride =
|
||||
overrideRules && typeof overrideRules === 'object' && !Array.isArray(overrideRules)
|
||||
? overrideRules
|
||||
: null;
|
||||
return `(() => {
|
||||
${isContextWindowModelId.toString()}
|
||||
${isContextWindowSettingId.toString()}
|
||||
@@ -334,6 +355,6 @@ export function createContextWindowSyncExpression(
|
||||
${getContextWindowGroups.toString()}
|
||||
${resolveContextWindowOption.toString()}
|
||||
${resolveContextWindowRules.toString()}
|
||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}, ${JSON.stringify(Boolean(allowRemoteHost))});
|
||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}, ${JSON.stringify(Boolean(allowRemoteHost))}, ${JSON.stringify(safeOverride)});
|
||||
})()`;
|
||||
}
|
||||
|
||||
@@ -163,6 +163,8 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
|
||||
experimentalQuotaReservation: false,
|
||||
contextWindowRiskAccepted: false,
|
||||
contextWindowMainEnabled: true,
|
||||
contextWindowSwarmEnabled: false,
|
||||
modelContextWindows: Object.freeze({}),
|
||||
});
|
||||
|
||||
@@ -245,6 +247,8 @@ export function normalizeFullSettings(rawInput) {
|
||||
safeRaw.experimentalQuotaReservation
|
||||
),
|
||||
contextWindowRiskAccepted: safeRaw.contextWindowRiskAccepted === true,
|
||||
contextWindowMainEnabled: safeRaw.contextWindowMainEnabled !== false,
|
||||
contextWindowSwarmEnabled: safeRaw.contextWindowSwarmEnabled === true,
|
||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import { updatePoolQuotaReservationEstimates } from './quota-reservation.mjs';
|
||||
import { getDefaultCloudCodeProxyStatus } from './cloudcode-proxy.mjs';
|
||||
import { getDefaultWindowBridgeStatus } from './window-bridge.mjs';
|
||||
import {
|
||||
aggregateConsumptionPresetBundle,
|
||||
@@ -2112,6 +2113,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
},
|
||||
uiBundleVersion,
|
||||
windowBridge: getDefaultWindowBridgeStatus(),
|
||||
cloudCodeProxy: getDefaultCloudCodeProxyStatus(),
|
||||
cliStatusLine: getCliStatusLineRuntimeStatus(),
|
||||
settings: loadSettings(),
|
||||
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
||||
|
||||
@@ -60,6 +60,7 @@ import {
|
||||
} from './endpoint-registry.mjs';
|
||||
import { getLocalHubPorts } from './ls-discovery.mjs';
|
||||
import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
|
||||
import { getDefaultCloudCodeProxy } from './cloudcode-proxy.mjs';
|
||||
|
||||
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
||||
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
|
||||
@@ -1092,8 +1093,14 @@ export function createWindowBridgeController(options) {
|
||||
WebSocketImpl = globalThis.WebSocket,
|
||||
bindRemoteRpcInvoker = false,
|
||||
getLocalHubPortsFn = getLocalHubPorts,
|
||||
cloudCodeProxy = null,
|
||||
manageCloudCodeProxy = false,
|
||||
resolveLocalContextRulesFn = null,
|
||||
} = options || {};
|
||||
|
||||
const activeCloudCodeProxy =
|
||||
cloudCodeProxy || (manageCloudCodeProxy ? getDefaultCloudCodeProxy() : null);
|
||||
|
||||
function isPidAlive(pid) {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return false;
|
||||
if (pid === process.pid) return true;
|
||||
@@ -1678,6 +1685,74 @@ export function createWindowBridgeController(options) {
|
||||
return hostLauncherPromise;
|
||||
}
|
||||
|
||||
async function resolveFallbackRulesForEndpoint(endpointId, contextWindows) {
|
||||
if (!contextWindows || !Object.keys(contextWindows).length) {
|
||||
return { verified: false, rules: {}, catalog: null };
|
||||
}
|
||||
const epObj =
|
||||
endpointId && endpointId !== LOCAL_ENDPOINT_ID
|
||||
? getRegisteredRemoteEndpoint(endpointId)
|
||||
: null;
|
||||
if (!epObj && typeof resolveLocalContextRulesFn === 'function') {
|
||||
try {
|
||||
const custom = await resolveLocalContextRulesFn(contextWindows);
|
||||
if (custom && typeof custom === 'object') {
|
||||
return {
|
||||
verified: custom.verified !== false,
|
||||
rules: custom.rules && typeof custom.rules === 'object' ? custom.rules : {},
|
||||
catalog: custom.catalog || null,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return { verified: false, rules: {}, catalog: null };
|
||||
}
|
||||
}
|
||||
if (!epObj && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.addr === 'test.invalid')) {
|
||||
return { verified: false, rules: {}, catalog: null };
|
||||
}
|
||||
const cacheKey = epObj ? epObj.id : LOCAL_ENDPOINT_ID;
|
||||
let cached = cachedBackendCtxModelsByEndpoint.get(cacheKey) || {
|
||||
expiresAt: 0,
|
||||
verified: false,
|
||||
models: [],
|
||||
catalog: null,
|
||||
};
|
||||
if (Date.now() >= cached.expiresAt) {
|
||||
try {
|
||||
const [stRes, cat] = await Promise.all([
|
||||
callLsRpc('GetUserStatus', {}, 2000, epObj),
|
||||
getContextModelCatalog(epObj),
|
||||
]);
|
||||
const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||
if (Array.isArray(cfgs)) {
|
||||
cached = {
|
||||
expiresAt: Date.now() + 10_000,
|
||||
verified: true,
|
||||
models: getContextWindowModels(cfgs, cat),
|
||||
catalog: cat || null,
|
||||
};
|
||||
cachedBackendCtxModelsByEndpoint.delete(cacheKey);
|
||||
if (cachedBackendCtxModelsByEndpoint.size >= 16) {
|
||||
const oldestKey = cachedBackendCtxModelsByEndpoint.keys().next().value;
|
||||
if (oldestKey !== undefined) cachedBackendCtxModelsByEndpoint.delete(oldestKey);
|
||||
}
|
||||
cachedBackendCtxModelsByEndpoint.set(cacheKey, cached);
|
||||
}
|
||||
} catch {
|
||||
// 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退
|
||||
}
|
||||
}
|
||||
if (cached.verified) {
|
||||
return {
|
||||
verified: true,
|
||||
rules:
|
||||
cached.models.length > 0 ? resolveContextWindowRules(cached.models, contextWindows) : {},
|
||||
catalog: cached.catalog || null,
|
||||
};
|
||||
}
|
||||
return { verified: false, rules: {}, catalog: null };
|
||||
}
|
||||
|
||||
async function runSyncInternal({ forceReinject = false } = {}) {
|
||||
if (stopped) return { ok: false, reason: 'stopped' };
|
||||
const bundleVersion = String(getBundleVersionFn() || '');
|
||||
@@ -1694,10 +1769,15 @@ export function createWindowBridgeController(options) {
|
||||
const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||
const contextWindows = curSettings.modelContextWindows || {};
|
||||
const hasContextWindows = Object.keys(contextWindows).length > 0;
|
||||
const ctxMainEnabled = curSettings.contextWindowMainEnabled !== false;
|
||||
const ctxSwarmEnabled = curSettings.contextWindowSwarmEnabled === true;
|
||||
const needsMainCdpContext = hasContextWindows && ctxMainEnabled;
|
||||
const needsCloudCodeProxy = hasContextWindows && ctxSwarmEnabled;
|
||||
const needsAnyCdpContext = hasContextWindows && (ctxMainEnabled || ctxSwarmEnabled);
|
||||
|
||||
let leasedBySelf = false;
|
||||
let currentLease = null;
|
||||
if ((enabled || hasContextWindows) && leaseFilePath && !forceReinject) {
|
||||
if ((enabled || needsAnyCdpContext || needsCloudCodeProxy) && leaseFilePath && !forceReinject) {
|
||||
const lease = loadJson(leaseFilePath, null);
|
||||
currentLease = lease;
|
||||
const leasePid = Number(lease?.pid || 0);
|
||||
@@ -1747,8 +1827,25 @@ export function createWindowBridgeController(options) {
|
||||
});
|
||||
}
|
||||
|
||||
let preResolvedLocalCtx = null;
|
||||
if (activeCloudCodeProxy) {
|
||||
if (needsCloudCodeProxy) {
|
||||
preResolvedLocalCtx = await resolveFallbackRulesForEndpoint(
|
||||
LOCAL_ENDPOINT_ID,
|
||||
contextWindows
|
||||
);
|
||||
await activeCloudCodeProxy.reconcile({
|
||||
enabled: true,
|
||||
rulesByModelId: preResolvedLocalCtx.rules,
|
||||
initialCatalogModels: preResolvedLocalCtx.catalog,
|
||||
});
|
||||
} else {
|
||||
await activeCloudCodeProxy.reconcile({ enabled: false, rulesByModelId: {} });
|
||||
}
|
||||
}
|
||||
|
||||
const shouldCheckLaunchers =
|
||||
(enabled || hasContextWindows) &&
|
||||
(enabled || needsMainCdpContext) &&
|
||||
autoConfigureIdeArgv &&
|
||||
(lastLauncherProvisionAtMs === 0 ||
|
||||
Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs);
|
||||
@@ -1763,7 +1860,7 @@ export function createWindowBridgeController(options) {
|
||||
if (provPending) {
|
||||
await provPending.catch(() => {});
|
||||
}
|
||||
updateBridgeStatus(enabled || hasContextWindows ? 'no_devtools_port' : 'disabled', {
|
||||
updateBridgeStatus(enabled || needsMainCdpContext ? 'no_devtools_port' : 'disabled', {
|
||||
enabled,
|
||||
leasedBySelf,
|
||||
bundleVersion,
|
||||
@@ -1781,7 +1878,7 @@ export function createWindowBridgeController(options) {
|
||||
if (provPending) {
|
||||
await provPending.catch(() => {});
|
||||
}
|
||||
updateBridgeStatus(enabled || hasContextWindows ? 'cdp_unreachable' : 'disabled', {
|
||||
updateBridgeStatus(enabled || needsMainCdpContext ? 'cdp_unreachable' : 'disabled', {
|
||||
enabled,
|
||||
leasedBySelf,
|
||||
bundleVersion,
|
||||
@@ -1807,7 +1904,7 @@ export function createWindowBridgeController(options) {
|
||||
|
||||
if (
|
||||
!enabled &&
|
||||
!hasContextWindows &&
|
||||
!needsAnyCdpContext &&
|
||||
!hadContextWindows &&
|
||||
!hadInjectedTargets &&
|
||||
!hadInjectedChatFrames &&
|
||||
@@ -1947,58 +2044,24 @@ export function createWindowBridgeController(options) {
|
||||
}
|
||||
}
|
||||
|
||||
if (hasContextWindows || hadContextWindows) {
|
||||
async function resolveFallbackRulesForEndpoint(endpointId) {
|
||||
if (!hasContextWindows) return { verified: false, rules: {} };
|
||||
const epObj = endpointId && endpointId !== LOCAL_ENDPOINT_ID
|
||||
? getRegisteredRemoteEndpoint(endpointId)
|
||||
: null;
|
||||
if (!epObj && (!lsRuntimeEndpoint.baseUrl || lsRuntimeEndpoint.addr === 'test.invalid')) {
|
||||
return { verified: false, rules: {} };
|
||||
}
|
||||
const cacheKey = epObj ? epObj.id : LOCAL_ENDPOINT_ID;
|
||||
let cached = cachedBackendCtxModelsByEndpoint.get(cacheKey) || {
|
||||
expiresAt: 0,
|
||||
verified: false,
|
||||
models: [],
|
||||
};
|
||||
if (Date.now() >= cached.expiresAt) {
|
||||
try {
|
||||
const [stRes, cat] = await Promise.all([
|
||||
callLsRpc('GetUserStatus', {}, 2000, epObj),
|
||||
getContextModelCatalog(epObj),
|
||||
]);
|
||||
const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||
if (Array.isArray(cfgs)) {
|
||||
cached = {
|
||||
expiresAt: Date.now() + 10_000,
|
||||
verified: true,
|
||||
models: getContextWindowModels(cfgs, cat),
|
||||
};
|
||||
cachedBackendCtxModelsByEndpoint.delete(cacheKey);
|
||||
if (cachedBackendCtxModelsByEndpoint.size >= 16) {
|
||||
const oldestKey = cachedBackendCtxModelsByEndpoint.keys().next().value;
|
||||
if (oldestKey !== undefined) cachedBackendCtxModelsByEndpoint.delete(oldestKey);
|
||||
}
|
||||
cachedBackendCtxModelsByEndpoint.set(cacheKey, cached);
|
||||
}
|
||||
} catch {
|
||||
// 忽略瞬态 LS 查询失败,保留上次缓存或交由调用方回退
|
||||
if (needsAnyCdpContext || hadContextWindows) {
|
||||
const localFallbackRes = needsAnyCdpContext
|
||||
? preResolvedLocalCtx ||
|
||||
(await resolveFallbackRulesForEndpoint(LOCAL_ENDPOINT_ID, contextWindows))
|
||||
: { verified: false, rules: {}, catalog: null };
|
||||
const localFallbackRules = localFallbackRes.rules;
|
||||
const pinMainBackToDefaults = needsCloudCodeProxy && !ctxMainEnabled;
|
||||
const pinBackRules = {};
|
||||
if (pinMainBackToDefaults) {
|
||||
const upstreamDefaults = activeCloudCodeProxy?.getUpstreamDefaults?.() || {};
|
||||
for (const modelId of Object.keys(localFallbackRules)) {
|
||||
const defaultLimit = Number(upstreamDefaults[modelId]);
|
||||
if (Number.isSafeInteger(defaultLimit) && defaultLimit > 0) {
|
||||
pinBackRules[modelId] = defaultLimit;
|
||||
}
|
||||
}
|
||||
if (cached.verified) {
|
||||
return {
|
||||
verified: true,
|
||||
rules: cached.models.length > 0
|
||||
? resolveContextWindowRules(cached.models, contextWindows)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
return { verified: false, rules: {} };
|
||||
}
|
||||
|
||||
const localFallbackRes = await resolveFallbackRulesForEndpoint(LOCAL_ENDPOINT_ID);
|
||||
const localFallbackRules = localFallbackRes.rules;
|
||||
const remoteFallbackRulesById = new Map();
|
||||
const uniqueRemoteIds = new Set(
|
||||
targets
|
||||
@@ -2010,13 +2073,15 @@ export function createWindowBridgeController(options) {
|
||||
cachedBackendCtxModelsByEndpoint.delete(cachedKey);
|
||||
}
|
||||
}
|
||||
await Promise.allSettled(
|
||||
Array.from(uniqueRemoteIds).map(async (epId) => {
|
||||
const res = await resolveFallbackRulesForEndpoint(epId);
|
||||
// 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则
|
||||
remoteFallbackRulesById.set(epId, res.verified ? res.rules : localFallbackRules);
|
||||
})
|
||||
);
|
||||
if (needsMainCdpContext) {
|
||||
await Promise.allSettled(
|
||||
Array.from(uniqueRemoteIds).map(async (epId) => {
|
||||
const res = await resolveFallbackRulesForEndpoint(epId, contextWindows);
|
||||
// 仅在远端未能验证模型目录时安全回退本机规则;远端已验证但返回空规则时绝不套用本机高配规则
|
||||
remoteFallbackRulesById.set(epId, res.verified ? res.rules : localFallbackRules);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const ctxEvalTasks = [];
|
||||
const seenCtxUrls = new Set();
|
||||
@@ -2025,31 +2090,59 @@ export function createWindowBridgeController(options) {
|
||||
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
|
||||
if (!wsUrl || seenCtxUrls.has(wsUrl)) continue;
|
||||
seenCtxUrls.add(wsUrl);
|
||||
const epFallback =
|
||||
target.isRemoteEndpoint && target.endpointId
|
||||
? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules
|
||||
: localFallbackRules;
|
||||
const expr = createContextWindowSyncExpression(
|
||||
contextWindows,
|
||||
contextWindowBootId,
|
||||
epFallback,
|
||||
true
|
||||
);
|
||||
let expr;
|
||||
if (!needsAnyCdpContext) {
|
||||
expr = createContextWindowSyncExpression({}, contextWindowBootId, {}, true, null);
|
||||
} else if (pinMainBackToDefaults) {
|
||||
// 仅启用子代理与蜂群时:本地主窗口显式回填上游默认上限把主代理钉回默认;远端主窗口不注入覆盖
|
||||
expr = target.isRemoteEndpoint
|
||||
? createContextWindowSyncExpression({}, contextWindowBootId, {}, true, null)
|
||||
: createContextWindowSyncExpression(
|
||||
contextWindows,
|
||||
contextWindowBootId,
|
||||
pinBackRules,
|
||||
true,
|
||||
pinBackRules
|
||||
);
|
||||
} else {
|
||||
const epFallback =
|
||||
target.isRemoteEndpoint && target.endpointId
|
||||
? remoteFallbackRulesById.get(target.endpointId) || localFallbackRules
|
||||
: localFallbackRules;
|
||||
expr = createContextWindowSyncExpression(
|
||||
contextWindows,
|
||||
contextWindowBootId,
|
||||
epFallback,
|
||||
true,
|
||||
null
|
||||
);
|
||||
}
|
||||
ctxEvalTasks.push(evaluateOnTarget(wsUrl, expr));
|
||||
}
|
||||
const ideChatExpr = createContextWindowSyncExpression(
|
||||
contextWindows,
|
||||
contextWindowBootId,
|
||||
localFallbackRules,
|
||||
false
|
||||
);
|
||||
const ideChatExpr = !needsAnyCdpContext
|
||||
? createContextWindowSyncExpression({}, contextWindowBootId, {}, false, null)
|
||||
: pinMainBackToDefaults
|
||||
? createContextWindowSyncExpression(
|
||||
contextWindows,
|
||||
contextWindowBootId,
|
||||
pinBackRules,
|
||||
false,
|
||||
pinBackRules
|
||||
)
|
||||
: createContextWindowSyncExpression(
|
||||
contextWindows,
|
||||
contextWindowBootId,
|
||||
localFallbackRules,
|
||||
false,
|
||||
null
|
||||
);
|
||||
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
|
||||
if (!chatUrl || seenCtxUrls.has(chatUrl)) continue;
|
||||
seenCtxUrls.add(chatUrl);
|
||||
ctxEvalTasks.push(evaluateOnTarget(chatUrl, ideChatExpr));
|
||||
}
|
||||
await Promise.allSettled(ctxEvalTasks);
|
||||
hadContextWindows = hasContextWindows;
|
||||
hadContextWindows = needsAnyCdpContext;
|
||||
}
|
||||
|
||||
const disposeExpr = `(() => {
|
||||
@@ -2532,6 +2625,9 @@ export function createWindowBridgeController(options) {
|
||||
hadInjectedTargets = false;
|
||||
hadInjectedChatFrames = false;
|
||||
hadContextWindows = false;
|
||||
if (activeCloudCodeProxy) {
|
||||
await activeCloudCodeProxy.stop().catch(() => {});
|
||||
}
|
||||
if (bindRemoteRpcInvoker) {
|
||||
setRemoteWindowRpcInvoker(null);
|
||||
}
|
||||
@@ -2548,7 +2644,9 @@ export function createWindowBridgeController(options) {
|
||||
hadInjectedTargets = true;
|
||||
hadInjectedChatFrames = true;
|
||||
const cur = getSettingsFn() || {};
|
||||
const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0;
|
||||
const hasCtx =
|
||||
Object.keys(cur.modelContextWindows || {}).length > 0 &&
|
||||
cur.contextWindowMainEnabled !== false;
|
||||
if (!hasCtx && autoConfigureIdeArgv) {
|
||||
launcherConfigured = false;
|
||||
hasReadOnlyShortcuts = false;
|
||||
@@ -2574,7 +2672,9 @@ export function createWindowBridgeController(options) {
|
||||
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;
|
||||
const hasCtx =
|
||||
Object.keys(cur.modelContextWindows || {}).length > 0 &&
|
||||
cur.contextWindowMainEnabled !== false;
|
||||
if (hasCtx) {
|
||||
lastLauncherProvisionAtMs = 0;
|
||||
} else if (!overlayOn && autoConfigureIdeArgv) {
|
||||
@@ -2640,6 +2740,7 @@ export function startDefaultWindowBridge(options) {
|
||||
defaultBridgeController = createWindowBridgeController({
|
||||
leaseFilePath: join(DATA_DIR, 'window-bridge-lease.json'),
|
||||
bindRemoteRpcInvoker: true,
|
||||
manageCloudCodeProxy: true,
|
||||
...options,
|
||||
});
|
||||
defaultBridgeController.start();
|
||||
|
||||
@@ -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=1795348665835">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795349313901">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795348665835"></script>
|
||||
<script src="/app.js?v=1795349313901"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -242,5 +242,28 @@ if (isTestHarnessEnv) {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let processStopping = false;
|
||||
async function handleProcessExitSignal(exitCode = 0) {
|
||||
if (processStopping) return;
|
||||
processStopping = true;
|
||||
const forceTimer = setTimeout(() => process.exit(exitCode), 1800);
|
||||
forceTimer.unref?.();
|
||||
try {
|
||||
if (activeWorker) {
|
||||
const w = activeWorker;
|
||||
activeWorker = null;
|
||||
await stopWorkerGracefully(w);
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(forceTimer);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
}
|
||||
process.once('SIGTERM', () => {
|
||||
void handleProcessExitSignal(0);
|
||||
});
|
||||
process.once('SIGINT', () => {
|
||||
void handleProcessExitSignal(0);
|
||||
});
|
||||
void ensureActiveWorker();
|
||||
}
|
||||
|
||||
@@ -704,6 +704,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.oth.ctxRiskBody': 'Google has not authorized modifying model context limits in Antigravity App / IDE. Altering context limits 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.oth.ctxRiskAcceptBtn': 'I Understand the Risk, Unlock',
|
||||
'settings.oth.ctxModel': 'Model',
|
||||
'settings.oth.ctxMainLabel': 'Main Agent',
|
||||
'settings.oth.ctxSwarmLabel': 'Subagents & Swarm',
|
||||
'settings.oth.ctxSwarmError': 'Local sync failed: {error}',
|
||||
'settings.oth.ctxBaselineLabel': 'Context Window Limit',
|
||||
'settings.oth.ctxChooseModel': 'Choose a model',
|
||||
'settings.oth.ctxDefault': 'Follow host settings',
|
||||
|
||||
@@ -704,6 +704,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.oth.ctxRiskBody': 'Google 官方并未授权在 Antigravity App / IDE 中修改模型上下文上限。擅自修改可能导致 Antigravity 或 GCP 服务被禁用,甚至触发账号封禁;启用该功能即默认由你自行承担全部风险。你最好清楚自己在做什么!',
|
||||
'settings.oth.ctxRiskAcceptBtn': '我已知晓风险,继续使用',
|
||||
'settings.oth.ctxModel': '模型',
|
||||
'settings.oth.ctxMainLabel': '主代理',
|
||||
'settings.oth.ctxSwarmLabel': '子代理与蜂群',
|
||||
'settings.oth.ctxSwarmError': '本地同步异常:{error}',
|
||||
'settings.oth.ctxBaselineLabel': '上下文窗口上限',
|
||||
'settings.oth.ctxChooseModel': '选择模型',
|
||||
'settings.oth.ctxDefault': '跟随宿主设置',
|
||||
|
||||
@@ -540,6 +540,20 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
(pSet?.contextWindowMainEnabled !== false) !== (nSet?.contextWindowMainEnabled !== false) ||
|
||||
Boolean(pSet?.contextWindowSwarmEnabled) !== Boolean(nSet?.contextWindowSwarmEnabled)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
(prev.cloudCodeProxy?.state || 'disabled') !== (next.cloudCodeProxy?.state || 'disabled') ||
|
||||
Number(prev.cloudCodeProxy?.ruleCount || 0) !== Number(next.cloudCodeProxy?.ruleCount || 0) ||
|
||||
String(prev.cloudCodeProxy?.error || '') !== String(next.cloudCodeProxy?.error || '') ||
|
||||
Number(prev.cloudCodeProxy?.syncedAtMs || 0) !== Number(next.cloudCodeProxy?.syncedAtMs || 0)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
JSON.stringify(pSet?.modelContextWindows) !== JSON.stringify(nSet?.modelContextWindows) ||
|
||||
JSON.stringify(prev.contextWindowModels) !== JSON.stringify(next.contextWindowModels)
|
||||
@@ -1856,6 +1870,12 @@ export async function saveSettingsPatch(patch) {
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowRiskAccepted')) {
|
||||
safePatch.contextWindowRiskAccepted = Boolean(safePatch.contextWindowRiskAccepted);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowMainEnabled')) {
|
||||
safePatch.contextWindowMainEnabled = Boolean(safePatch.contextWindowMainEnabled);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'contextWindowSwarmEnabled')) {
|
||||
safePatch.contextWindowSwarmEnabled = Boolean(safePatch.contextWindowSwarmEnabled);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) {
|
||||
safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode);
|
||||
}
|
||||
|
||||
@@ -793,6 +793,14 @@
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ctx-sync-status {
|
||||
margin: -4px 0 2px;
|
||||
}
|
||||
|
||||
.ctx-sync-status.is-error {
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.ctx-risk-mask {
|
||||
grid-area: 1 / 1;
|
||||
z-index: 5;
|
||||
|
||||
@@ -118,7 +118,8 @@ export const SettingsView = defineComponent({
|
||||
settings,
|
||||
telemetry.contextWindowModels || [],
|
||||
telemetry?.windowBridge,
|
||||
telemetry?.hostPlatform
|
||||
telemetry?.hostPlatform,
|
||||
telemetry?.cloudCodeProxy
|
||||
);
|
||||
}
|
||||
} else if (accountTab && settingsSubTab === 'account') {
|
||||
@@ -134,6 +135,7 @@ export const SettingsView = defineComponent({
|
||||
(st) => ({
|
||||
settings: st.telemetry?.settings,
|
||||
windowBridge: st.telemetry?.windowBridge,
|
||||
cloudCodeProxy: st.telemetry?.cloudCodeProxy,
|
||||
cliStatusLine: st.telemetry?.cliStatusLine,
|
||||
hostPlatform: st.telemetry?.hostPlatform,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
|
||||
@@ -77,8 +77,12 @@ export const SettingsOtherTab = defineComponent({
|
||||
let draftExperimentalQuotaReservation = false;
|
||||
let draftContextRiskAccepted = false;
|
||||
let acceptingContextRisk = false;
|
||||
let draftContextMainEnabled = true;
|
||||
let draftContextSwarmEnabled = false;
|
||||
let savingContextScope = false;
|
||||
let latestSettings = null;
|
||||
let latestWindowBridge = null;
|
||||
let latestCloudCodeProxy = null;
|
||||
let latestHostPlatform = 'win32';
|
||||
let contextWindowModels = [];
|
||||
let contextModelId = '';
|
||||
@@ -358,10 +362,79 @@ export const SettingsOtherTab = defineComponent({
|
||||
},
|
||||
});
|
||||
const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true });
|
||||
const ctxMainLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.ctxMainLabel'),
|
||||
});
|
||||
const ctxMainToggle = SegmentedControl({
|
||||
modelValue: 'on',
|
||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||
const nextEnabled = val === 'on';
|
||||
const prevEnabled = draftContextMainEnabled;
|
||||
savingContextScope = true;
|
||||
draftContextMainEnabled = nextEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: nextEnabled };
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
await saveSettingsPatch({ contextWindowMainEnabled: nextEnabled });
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
draftContextMainEnabled = prevEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowMainEnabled: prevEnabled };
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
savingContextScope = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
});
|
||||
const ctxSwarmLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.ctxSwarmLabel'),
|
||||
});
|
||||
const ctxSwarmToggle = SegmentedControl({
|
||||
modelValue: 'off',
|
||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
||||
options: getEnableToggleOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
if (!draftContextRiskAccepted || savingContextScope) return;
|
||||
const nextEnabled = val === 'on';
|
||||
const prevEnabled = draftContextSwarmEnabled;
|
||||
savingContextScope = true;
|
||||
draftContextSwarmEnabled = nextEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: nextEnabled };
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
await saveSettingsPatch({ contextWindowSwarmEnabled: nextEnabled });
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
draftContextSwarmEnabled = prevEnabled;
|
||||
latestSettings = { ...(latestSettings || {}), contextWindowSwarmEnabled: prevEnabled };
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
savingContextScope = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
});
|
||||
const ctxMainRow = h('div', { className: 'form-row' }, [ctxMainLabelEl, ctxMainToggle.el]);
|
||||
const ctxSwarmRow = h('div', { className: 'form-row' }, [ctxSwarmLabelEl, ctxSwarmToggle.el]);
|
||||
const ctxSyncStatusEl = h('span', {
|
||||
className: 'settings-hint-text ctx-sync-status is-error',
|
||||
hidden: true,
|
||||
});
|
||||
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
|
||||
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
|
||||
const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [
|
||||
ctxBridgeNotice.el,
|
||||
ctxMainRow,
|
||||
ctxSwarmRow,
|
||||
ctxSyncStatusEl,
|
||||
ctxModelRow,
|
||||
ctxWindowRow,
|
||||
h('div', { className: 'form-row' }, [ctxHint]),
|
||||
@@ -440,8 +513,31 @@ export const SettingsOtherTab = defineComponent({
|
||||
const saved = latestSettings?.modelContextWindows || {};
|
||||
const wbState = String(latestWindowBridge?.state || '').trim();
|
||||
const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable';
|
||||
const proxyState = String(latestCloudCodeProxy?.state || 'disabled');
|
||||
const isProxyActive = Boolean(latestCloudCodeProxy?.active && proxyState === 'active');
|
||||
|
||||
patchText(ctxMainLabelEl, t('settings.oth.ctxMainLabel'));
|
||||
ctxMainToggle.setProps({
|
||||
modelValue: draftContextMainEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.ctxMainLabel'),
|
||||
});
|
||||
patchText(ctxSwarmLabelEl, t('settings.oth.ctxSwarmLabel'));
|
||||
ctxSwarmToggle.setProps({
|
||||
modelValue: draftContextSwarmEnabled ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
ariaLabel: t('settings.oth.ctxSwarmLabel'),
|
||||
});
|
||||
|
||||
const syncErrorText =
|
||||
draftContextSwarmEnabled && proxyState === 'error' && latestCloudCodeProxy?.error
|
||||
? t('settings.oth.ctxSwarmError', { error: latestCloudCodeProxy.error })
|
||||
: '';
|
||||
patchAttr(ctxSyncStatusEl, 'hidden', !syncErrorText);
|
||||
patchText(ctxSyncStatusEl, syncErrorText);
|
||||
|
||||
ctxBridgeNotice.refs.update({
|
||||
visible: unlocked,
|
||||
visible: unlocked && draftContextMainEnabled,
|
||||
windowBridge: latestWindowBridge,
|
||||
hostPlatform: latestHostPlatform,
|
||||
});
|
||||
@@ -489,7 +585,13 @@ export const SettingsOtherTab = defineComponent({
|
||||
else if (value) {
|
||||
const name = formatLimit(value);
|
||||
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
|
||||
else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name });
|
||||
else if (
|
||||
isBridgeMissing &&
|
||||
draftContextMainEnabled &&
|
||||
!(draftContextSwarmEnabled && isProxyActive)
|
||||
) {
|
||||
meta = t('settings.oth.ctxPendingBridge', { name });
|
||||
}
|
||||
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
|
||||
meta = t('settings.oth.ctxConfiguredReported', {
|
||||
name,
|
||||
@@ -777,13 +879,15 @@ export const SettingsOtherTab = defineComponent({
|
||||
settings,
|
||||
models = contextWindowModels,
|
||||
windowBridge = latestWindowBridge,
|
||||
hostPlatform = latestHostPlatform
|
||||
hostPlatform = latestHostPlatform,
|
||||
cloudCodeProxy = latestCloudCodeProxy
|
||||
) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
contextWindowModels = models;
|
||||
if (windowBridge !== undefined) latestWindowBridge = windowBridge;
|
||||
if (hostPlatform) latestHostPlatform = hostPlatform;
|
||||
if (cloudCodeProxy !== undefined) latestCloudCodeProxy = cloudCodeProxy;
|
||||
draftModelDisplayMode = normalizeClientModelDisplayMode(
|
||||
settings.modelDisplayMode,
|
||||
settings.showUpstreamModel
|
||||
@@ -795,6 +899,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
if (!acceptingContextRisk) {
|
||||
draftContextRiskAccepted = Boolean(settings.contextWindowRiskAccepted);
|
||||
}
|
||||
if (!savingContextScope) {
|
||||
draftContextMainEnabled = settings.contextWindowMainEnabled !== false;
|
||||
draftContextSwarmEnabled = settings.contextWindowSwarmEnabled === true;
|
||||
}
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftModelDisplayMode,
|
||||
options: getStepModelDisplayOptions(),
|
||||
@@ -870,6 +978,8 @@ export const SettingsOtherTab = defineComponent({
|
||||
orchestratorIdSelect.destroy();
|
||||
quotaReserveToggle.destroy();
|
||||
ctxBridgeNotice.destroy();
|
||||
ctxMainToggle.destroy();
|
||||
ctxSwarmToggle.destroy();
|
||||
ctxModelSelect.destroy();
|
||||
ctxWindowSelect.destroy();
|
||||
sessionMigrationCard.destroy();
|
||||
@@ -883,6 +993,8 @@ export const SettingsOtherTab = defineComponent({
|
||||
quotaReserveToggle,
|
||||
exportReserveLogBtn,
|
||||
ctxBridgeNotice,
|
||||
ctxMainToggle,
|
||||
ctxSwarmToggle,
|
||||
ctxModelSelect,
|
||||
ctxWindowSelect,
|
||||
sessionMigrationCard,
|
||||
|
||||
@@ -6276,6 +6276,14 @@ html[data-standalone="true"] .app-shell {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ctx-sync-status {
|
||||
margin: -4px 0 2px;
|
||||
}
|
||||
|
||||
.ctx-sync-status.is-error {
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.ctx-risk-mask {
|
||||
grid-area: 1 / 1;
|
||||
z-index: 5;
|
||||
|
||||
@@ -36,6 +36,7 @@ const BACKEND_MODULE_FILES = [
|
||||
'../backend/pricing-catalog.mjs',
|
||||
'../backend/plugin-updater.mjs',
|
||||
'../backend/ls-rpc.mjs',
|
||||
'../backend/cloudcode-proxy.mjs',
|
||||
'../backend/model-pricing.mjs',
|
||||
'../backend/quota-pools.mjs',
|
||||
'../backend/quota-reservation.mjs',
|
||||
@@ -209,6 +210,6 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeContextAgentMode,normalizeCliStatusLineSlots,resolveEffectiveCliStatusLineSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,extractManagedCliStatusLineFlags,getCliStatusLineRuntimeStatus,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,dispatchBridgeApiRequest,executeAccountCredentialAction,callLsRpc,getDefaultCloudCodeProxyStatus,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isNeonModelIdentifier,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeContextAgentMode,normalizeCliStatusLineSlots,resolveEffectiveCliStatusLineSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,extractManagedCliStatusLineFlags,getCliStatusLineRuntimeStatus,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule,registerRemoteEndpoint,getRegisteredRemoteEndpoint,resolveEndpointContext,clearRemoteEndpointCaches,clearRemoteEndpointRegistry,setRemoteWindowRpcInvoker,setLoopbackHttpsRequester,getEndpointCacheStore,pruneStaleRemoteEndpoints,trackEndpointRequestStart,trackEndpointRequestEnd,shouldRemoteEndpointPreferTier2,markRemoteEndpointPreferTier2};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import test from 'node:test';
|
||||
import vm from 'node:vm';
|
||||
import { createContextWindowSyncExpression } from '../backend/context-windows.mjs';
|
||||
import {
|
||||
createCloudCodeProxyController,
|
||||
extractUpstreamCheckpointDefaults,
|
||||
isValidUpstreamCloudCodeUrl,
|
||||
rewriteFetchAvailableModelsPayload,
|
||||
} from '../backend/cloudcode-proxy.mjs';
|
||||
import { createWindowBridgeController } from '../backend/window-bridge.mjs';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
import { createMockDom } from './mock-dom.mjs';
|
||||
|
||||
const argon = 'MODEL_PLACEHOLDER_M430';
|
||||
const flash = 'MODEL_PLACEHOLDER_M431';
|
||||
@@ -304,3 +313,474 @@ test('Issue #27: syncHostContextWindows falls back to backend pre-resolved rules
|
||||
}
|
||||
assert.equal(window.fetch, nativeFetch);
|
||||
});
|
||||
|
||||
test('cloudcode-proxy validates upstream URLs and rewrites checkpointer experiments cleanly', () => {
|
||||
assert.equal(isValidUpstreamCloudCodeUrl('https://daily-cloudcode-pa.googleapis.com'), true);
|
||||
assert.equal(isValidUpstreamCloudCodeUrl('https://cloudcode-pa.googleapis.com'), true);
|
||||
assert.equal(isValidUpstreamCloudCodeUrl('http://127.0.0.1:18148'), false);
|
||||
assert.equal(isValidUpstreamCloudCodeUrl('https://127.0.0.1:18148'), false);
|
||||
assert.equal(isValidUpstreamCloudCodeUrl('https://localhost:443'), false);
|
||||
assert.equal(isValidUpstreamCloudCodeUrl('http://daily-cloudcode-pa.googleapis.com'), false);
|
||||
|
||||
const payload = {
|
||||
models: {
|
||||
'gemini-4-carbon-high': {
|
||||
model: carbon,
|
||||
maxTokens: 1048576,
|
||||
maxOutputTokens: 32768,
|
||||
ignoreExperiments: ['CASCADE_USE_EXPERIMENT_CHECKPOINTER', 'checkpoint-variant', 'unrelated-flag'],
|
||||
modelExperiments: {
|
||||
experiments: {
|
||||
CASCADE_USE_EXPERIMENT_CHECKPOINTER: {
|
||||
stringValue: JSON.stringify({
|
||||
strategy: 'CHECKPOINT_STRATEGY_SAME_MODEL',
|
||||
max_token_limit: '512000',
|
||||
max_output_tokens: '32768',
|
||||
}),
|
||||
},
|
||||
'CASCADE_USE_EXPERIMENT_CHECKPOINTER/claude-1m_840k': {
|
||||
stringValue: JSON.stringify({ max_token_limit: '840000' }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'argon-named': {
|
||||
model: argon,
|
||||
maxTokens: 1048576,
|
||||
maxOutputTokens: 32768,
|
||||
modelExperiments: {
|
||||
experiments: {
|
||||
CASCADE_USE_EXPERIMENT_CHECKPOINTER: {
|
||||
stringValue: JSON.stringify({ max_token_limit: '256000' }),
|
||||
},
|
||||
'CASCADE_USE_EXPERIMENT_CHECKPOINTER/context-window_900K': {
|
||||
stringValue: JSON.stringify({ max_token_limit: '900000', enabled: true }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'untouched-flash': {
|
||||
model: flash,
|
||||
maxTokens: 1048576,
|
||||
modelExperiments: {
|
||||
experiments: {
|
||||
CASCADE_USE_EXPERIMENT_CHECKPOINTER: {
|
||||
stringValue: JSON.stringify({ max_token_limit: '128000' }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const beforeDefaults = extractUpstreamCheckpointDefaults(payload.models);
|
||||
assert.deepEqual(beforeDefaults, { [carbon]: 512000, [argon]: 256000, [flash]: 128000 });
|
||||
|
||||
const res = rewriteFetchAvailableModelsPayload(payload, { [carbon]: 300000, [argon]: '900K' });
|
||||
assert.equal(res.modified, true);
|
||||
assert.equal(res.applied.length, 2);
|
||||
assert.deepEqual(res.defaultsByModelId, { [carbon]: 512000, [argon]: 256000, [flash]: 128000 });
|
||||
|
||||
const carbonMain = JSON.parse(
|
||||
payload.models['gemini-4-carbon-high'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER
|
||||
.stringValue
|
||||
);
|
||||
const carbonVariant = JSON.parse(
|
||||
payload.models['gemini-4-carbon-high'].modelExperiments.experiments[
|
||||
'CASCADE_USE_EXPERIMENT_CHECKPOINTER/claude-1m_840k'
|
||||
].stringValue
|
||||
);
|
||||
assert.equal(carbonMain.max_token_limit, '300000');
|
||||
assert.equal(carbonMain.strategy, 'CHECKPOINT_STRATEGY_SAME_MODEL');
|
||||
assert.equal(carbonVariant.max_token_limit, '300000');
|
||||
assert.equal(payload.models['gemini-4-carbon-high'].maxTokens, 1048576);
|
||||
assert.deepEqual(payload.models['gemini-4-carbon-high'].ignoreExperiments, ['unrelated-flag']);
|
||||
|
||||
const argonMain = JSON.parse(
|
||||
payload.models['argon-named'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER.stringValue
|
||||
);
|
||||
assert.equal(argonMain.max_token_limit, '900000');
|
||||
assert.equal(argonMain.enabled, true);
|
||||
|
||||
const flashMain = JSON.parse(
|
||||
payload.models['untouched-flash'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER.stringValue
|
||||
);
|
||||
assert.equal(flashMain.max_token_limit, '128000');
|
||||
});
|
||||
|
||||
test('createCloudCodeProxyController proxies fetchAvailableModels, streams passthrough, and restores SetCloudCodeURL cleanly', async () => {
|
||||
const upstreamHits = [];
|
||||
const upstreamServer = http.createServer((req, res) => {
|
||||
upstreamHits.push(req.url);
|
||||
if (req.url?.includes('fetchAvailableModels')) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
models: {
|
||||
'gemini-4-carbon-high': {
|
||||
model: carbon,
|
||||
maxTokens: 1048576,
|
||||
modelExperiments: {
|
||||
experiments: {
|
||||
CASCADE_USE_EXPERIMENT_CHECKPOINTER: {
|
||||
stringValue: JSON.stringify({ max_token_limit: '512000' }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.write('chunk-1:');
|
||||
res.end('chunk-2');
|
||||
});
|
||||
await new Promise((resolve) => upstreamServer.listen(0, '127.0.0.1', resolve));
|
||||
const upstreamPort = upstreamServer.address().port;
|
||||
const upstreamUrl = `http://127.0.0.1:${upstreamPort}`;
|
||||
|
||||
const rpcCalls = [];
|
||||
let failSetUrl = false;
|
||||
const proxy = createCloudCodeProxyController({
|
||||
allowHttpUpstream: true,
|
||||
allowTestEndpoint: true,
|
||||
retryCooldownMs: 5000,
|
||||
detectUpstreamFn: () => upstreamUrl,
|
||||
detectProxyFn: async () => '',
|
||||
getEndpointFn: () => ({ addr: '127.0.0.1:44444', baseUrl: 'http://127.0.0.1:44444', csrfToken: 'tok-1' }),
|
||||
callRpcFn: async (method, body) => {
|
||||
rpcCalls.push({ method, body });
|
||||
if (failSetUrl && method === 'SetCloudCodeURL') {
|
||||
throw new Error('enterprise gateway pinned');
|
||||
}
|
||||
return {};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// 1. Enable with rule -> starts proxy & calls SetCloudCodeURL
|
||||
const st1 = await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } });
|
||||
assert.equal(st1.state, 'active');
|
||||
assert.equal(st1.active, true);
|
||||
assert.equal(st1.ruleCount, 1);
|
||||
assert.equal(rpcCalls.length, 1);
|
||||
assert.equal(rpcCalls[0].method, 'SetCloudCodeURL');
|
||||
assert.equal(rpcCalls[0].body.url, st1.localUrl);
|
||||
|
||||
// 2. Fetch through proxy: /v1internal:fetchAvailableModels rewritten + upstream default captured
|
||||
const modelsRes = await fetch(`${st1.localUrl}/v1internal:fetchAvailableModels`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
});
|
||||
assert.equal(modelsRes.status, 200);
|
||||
const modelsJson = await modelsRes.json();
|
||||
const rewrittenLimit = JSON.parse(
|
||||
modelsJson.models['gemini-4-carbon-high'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER
|
||||
.stringValue
|
||||
).max_token_limit;
|
||||
assert.equal(rewrittenLimit, '300000');
|
||||
assert.deepEqual(proxy.getUpstreamDefaults(), { [carbon]: 512000 });
|
||||
|
||||
// 3. Non-intercepted path passes through verbatim
|
||||
const streamRes = await fetch(`${st1.localUrl}/v1internal:streamGenerateContent`, {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
});
|
||||
assert.equal(await streamRes.text(), 'chunk-1:chunk-2');
|
||||
|
||||
// 4. Same reconcile is idempotent (no redundant SetCloudCodeURL)
|
||||
await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } });
|
||||
assert.equal(rpcCalls.length, 1);
|
||||
|
||||
// 5. Rule change re-triggers SetCloudCodeURL to flush LS cache
|
||||
await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 256000 } });
|
||||
assert.equal(rpcCalls.length, 2);
|
||||
assert.equal(rpcCalls[1].body.url, st1.localUrl);
|
||||
|
||||
// 6. Disabling restores upstream URL and closes proxy
|
||||
const stOff = await proxy.reconcile({ enabled: false, rulesByModelId: { [carbon]: 256000 } });
|
||||
assert.equal(stOff.state, 'disabled');
|
||||
assert.equal(stOff.active, false);
|
||||
assert.equal(rpcCalls.length, 3);
|
||||
assert.equal(rpcCalls[2].body.url, upstreamUrl);
|
||||
|
||||
// 7. Error handling & cooldown
|
||||
failSetUrl = true;
|
||||
const stErr = await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 256000 } });
|
||||
assert.equal(stErr.state, 'error');
|
||||
assert.match(stErr.error, /enterprise gateway pinned/);
|
||||
assert.equal(rpcCalls.length, 4);
|
||||
await proxy.reconcile({ enabled: true, rulesByModelId: { [carbon]: 256000 } });
|
||||
assert.equal(rpcCalls.length, 4, 'cooldown skips immediate retry');
|
||||
} finally {
|
||||
failSetUrl = false;
|
||||
await proxy.stop();
|
||||
await new Promise((resolve) => upstreamServer.close(() => resolve()));
|
||||
}
|
||||
assert.ok(upstreamHits.some((u) => u.includes('fetchAvailableModels')));
|
||||
assert.ok(upstreamHits.some((u) => u.includes('streamGenerateContent')));
|
||||
});
|
||||
|
||||
test('independent Main Agent & Subagents/Swarm switches persist, pin back main defaults, and reconcile across all 4 combos', async () => {
|
||||
// 1. Settings defaults, persistence, telemetry exposure, and factory reset
|
||||
const h = backendHarness({
|
||||
availableModels,
|
||||
userStatus: { cascadeModelConfigData: { clientModelConfigs: carbonModels } },
|
||||
});
|
||||
const initSettings = h.loadSettings();
|
||||
assert.equal(initSettings.contextWindowMainEnabled, true);
|
||||
assert.equal(initSettings.contextWindowSwarmEnabled, false);
|
||||
|
||||
const patchRes = h.executeSettingsAction({
|
||||
contextWindowMainEnabled: false,
|
||||
contextWindowSwarmEnabled: true,
|
||||
});
|
||||
assert.equal(patchRes.status, 200);
|
||||
assert.equal(h.loadSettings().contextWindowMainEnabled, false);
|
||||
assert.equal(h.loadSettings().contextWindowSwarmEnabled, true);
|
||||
|
||||
const tele = await h.buildTelemetryPayloadInternal('');
|
||||
assert.equal(tele.settings.contextWindowMainEnabled, false);
|
||||
assert.equal(tele.settings.contextWindowSwarmEnabled, true);
|
||||
assert.equal(tele.cloudCodeProxy.state, 'disabled');
|
||||
|
||||
h.executeResetSettingsAction();
|
||||
assert.equal(h.loadSettings().contextWindowMainEnabled, true);
|
||||
assert.equal(h.loadSettings().contextWindowSwarmEnabled, false);
|
||||
|
||||
// 2. syncHostContextWindows pin-back mode overrides preferences with upstream default even when csrfToken exists
|
||||
const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage';
|
||||
const host = 'https://127.0.0.1:26195';
|
||||
const nativeFetch = async (_url, init) => init;
|
||||
class WebSocket {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
}
|
||||
send(data) {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
const win = {
|
||||
location: new URL(host),
|
||||
fetch: nativeFetch,
|
||||
WebSocket,
|
||||
__APP_CONFIG__: { csrfToken: 'pin-test-token' },
|
||||
};
|
||||
const ctx = vm.createContext({
|
||||
window: win,
|
||||
URL,
|
||||
TextEncoder,
|
||||
TextDecoder,
|
||||
Headers,
|
||||
Uint8Array,
|
||||
AbortSignal,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
});
|
||||
try {
|
||||
const syncOut = await vm.runInContext(
|
||||
createContextWindowSyncExpression(
|
||||
{ [carbonGroup]: '300000' },
|
||||
'pin-boot',
|
||||
{ [carbon]: 512000 },
|
||||
true,
|
||||
{ [carbon]: 512000 }
|
||||
),
|
||||
ctx
|
||||
);
|
||||
assert.deepEqual({ ...syncOut }, { attached: true, ruleCount: 1 });
|
||||
const reqPayload = {
|
||||
cascadeConfig: {
|
||||
plannerConfig: { planModel: carbon },
|
||||
checkpointConfig: {},
|
||||
},
|
||||
};
|
||||
const out = await win.fetch(host + sendPath, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(reqPayload),
|
||||
});
|
||||
assert.equal(
|
||||
JSON.parse(out.body).cascadeConfig.checkpointConfig.maxTokenLimit,
|
||||
512000,
|
||||
'pin-back mode forces main agent back to upstream default limit'
|
||||
);
|
||||
} finally {
|
||||
await vm.runInContext(createContextWindowSyncExpression({}, 'pin-boot', {}, true, null), ctx);
|
||||
}
|
||||
assert.equal(win.fetch, nativeFetch);
|
||||
|
||||
// 3. Window bridge reconciles CloudCode proxy even without CDP ports when Swarm toggle is enabled
|
||||
const proxyLog = [];
|
||||
let proxyStopped = false;
|
||||
let currentSettings = {
|
||||
enableWindowOverlay: false,
|
||||
windowMountMode: 'sidebar',
|
||||
modelContextWindows: { [carbonGroup]: '300000' },
|
||||
contextWindowMainEnabled: false,
|
||||
contextWindowSwarmEnabled: true,
|
||||
};
|
||||
const mockCloudCodeProxy = {
|
||||
async reconcile(opts) {
|
||||
proxyLog.push(opts);
|
||||
return { state: opts.enabled ? 'active' : 'disabled', active: Boolean(opts.enabled) };
|
||||
},
|
||||
getUpstreamDefaults: () => ({ [carbon]: 512000 }),
|
||||
async stop() {
|
||||
proxyStopped = true;
|
||||
},
|
||||
};
|
||||
const bridgeCtrl = createWindowBridgeController({
|
||||
handleApiRequest: async () => ({ status: 200, body: '{}' }),
|
||||
readAssetFn: async () => '',
|
||||
getSettingsFn: () => currentSettings,
|
||||
env: {},
|
||||
homeDir: '/nonexistent-home-for-test',
|
||||
autoConfigureIdeArgv: false,
|
||||
cloudCodeProxy: mockCloudCodeProxy,
|
||||
resolveLocalContextRulesFn: async () => ({
|
||||
verified: true,
|
||||
rules: { [carbon]: 300000 },
|
||||
catalog: availableModels,
|
||||
}),
|
||||
});
|
||||
await bridgeCtrl.syncAllWindows();
|
||||
assert.equal(proxyLog.length, 1);
|
||||
assert.equal(proxyLog[0].enabled, true);
|
||||
assert.deepEqual(proxyLog[0].rulesByModelId, { [carbon]: 300000 });
|
||||
|
||||
// Turning off Swarm switch disables CloudCode proxy
|
||||
currentSettings = { ...currentSettings, contextWindowSwarmEnabled: false };
|
||||
await bridgeCtrl.syncAllWindows();
|
||||
assert.equal(proxyLog.length, 2);
|
||||
assert.equal(proxyLog[1].enabled, false);
|
||||
|
||||
await bridgeCtrl.stop();
|
||||
assert.equal(proxyStopped, true);
|
||||
});
|
||||
|
||||
test('SettingsOtherTab renders independent Main Agent and Subagents/Swarm switches with live sync feedback', async () => {
|
||||
const { document } = createMockDom();
|
||||
const origDocument = globalThis.document;
|
||||
const origWindow = globalThis.window;
|
||||
const origFetch = globalThis.fetch;
|
||||
const savedPatches = [];
|
||||
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
location: { origin: 'http://127.0.0.1:41234', href: 'http://127.0.0.1:41234/' },
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
globalThis.fetch = async (url, init = {}) => {
|
||||
if (String(url).includes('/api/settings') && init.method === 'POST') {
|
||||
const patch = JSON.parse(init.body || '{}');
|
||||
savedPatches.push(patch);
|
||||
return { ok: true, json: async () => ({ ...patch }) };
|
||||
}
|
||||
return { ok: true, json: async () => ({}) };
|
||||
};
|
||||
|
||||
try {
|
||||
const [{ setI18nLanguage }, { SettingsOtherTab }] = await Promise.all([
|
||||
import('../src/i18n/index.js'),
|
||||
import('../src/views/settings/SettingsOtherTab.js'),
|
||||
]);
|
||||
setI18nLanguage('zh-CN');
|
||||
const tab = SettingsOtherTab({ onLayoutChange: () => {} });
|
||||
const mockModels = [
|
||||
{
|
||||
id: carbonGroup,
|
||||
label: 'Gemini 4 Carbon',
|
||||
members: [carbon],
|
||||
capacity: 786432,
|
||||
options: [{ name: '300000', tokens: 300000 }],
|
||||
},
|
||||
];
|
||||
tab.refs.renderSettings(
|
||||
{
|
||||
contextWindowRiskAccepted: true,
|
||||
contextWindowMainEnabled: true,
|
||||
contextWindowSwarmEnabled: true,
|
||||
modelContextWindows: { [carbonGroup]: '300000' },
|
||||
},
|
||||
mockModels,
|
||||
{ state: 'active' },
|
||||
'win32',
|
||||
{ state: 'active', active: true, ruleCount: 1, error: '' }
|
||||
);
|
||||
|
||||
const statusEl = tab.el.querySelector('.ctx-sync-status');
|
||||
assert.ok(statusEl);
|
||||
assert.equal(statusEl.hasAttribute('hidden'), true, 'no extra status clutter when active');
|
||||
|
||||
// Toggle Main Agent off -> persists patch
|
||||
const mainOffBtn = tab.refs.ctxMainToggle.el.querySelectorAll('button')[1];
|
||||
mainOffBtn.dispatchEvent({
|
||||
type: 'click',
|
||||
target: mainOffBtn,
|
||||
currentTarget: mainOffBtn,
|
||||
stopPropagation() {},
|
||||
preventDefault() {},
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
assert.deepEqual(savedPatches[0], { contextWindowMainEnabled: false });
|
||||
|
||||
// Toggle Subagents & Swarm off -> persists patch
|
||||
const swarmOffBtn = tab.refs.ctxSwarmToggle.el.querySelectorAll('button')[1];
|
||||
swarmOffBtn.dispatchEvent({
|
||||
type: 'click',
|
||||
target: swarmOffBtn,
|
||||
currentTarget: swarmOffBtn,
|
||||
stopPropagation() {},
|
||||
preventDefault() {},
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
assert.deepEqual(savedPatches[1], { contextWindowSwarmEnabled: false });
|
||||
|
||||
// Error state surfaces cleanly
|
||||
tab.refs.renderSettings(
|
||||
{
|
||||
contextWindowRiskAccepted: true,
|
||||
contextWindowMainEnabled: false,
|
||||
contextWindowSwarmEnabled: true,
|
||||
modelContextWindows: { [carbonGroup]: '300000' },
|
||||
},
|
||||
mockModels,
|
||||
{ state: 'no_devtools_port' },
|
||||
'win32',
|
||||
{ state: 'error', active: false, ruleCount: 1, error: 'gateway pinned' }
|
||||
);
|
||||
assert.equal(statusEl.hasAttribute('hidden'), false);
|
||||
assert.match(statusEl.textContent, /gateway pinned/);
|
||||
|
||||
// English labels refresh cleanly
|
||||
setI18nLanguage('en-US');
|
||||
tab.refs.refreshLabels();
|
||||
assert.match(statusEl.textContent, /Local sync failed: gateway pinned/);
|
||||
|
||||
// Both off -> stays clean without extra small-text clutter
|
||||
tab.refs.renderSettings(
|
||||
{
|
||||
contextWindowRiskAccepted: true,
|
||||
contextWindowMainEnabled: false,
|
||||
contextWindowSwarmEnabled: false,
|
||||
modelContextWindows: { [carbonGroup]: '300000' },
|
||||
},
|
||||
mockModels,
|
||||
{ state: 'active' },
|
||||
'win32',
|
||||
{ state: 'disabled', active: false, ruleCount: 0, error: '' }
|
||||
);
|
||||
assert.equal(statusEl.hasAttribute('hidden'), true);
|
||||
|
||||
tab.destroy();
|
||||
} finally {
|
||||
globalThis.document = origDocument;
|
||||
globalThis.window = origWindow;
|
||||
globalThis.fetch = origFetch;
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user