feat(panel): add Antigravity host UI localization and language packs

- Add standalone host-i18n language pack manager with GitHub/jsDelivr
  download, SHA-256 integrity checks, offline light/deep tier switching,
  and lossless DOM translation over the CDP window bridge
- Add Settings -> General host interface language controls, untranslated
  UI string collector, and loopback-only /api/host-i18n endpoints
- Include zh-CN layered language pack assets and source/audit/build scripts
  under host-i18n/ while keeping the Release ZIP runtime whitelist isolated
This commit is contained in:
fish
2026-11-25 13:38:23 +09:00
parent 5565133710
commit 8a01705e6f
48 changed files with 32522 additions and 38 deletions
+899 -4
View File
@@ -950,6 +950,8 @@ const BRIDGE_API_ROUTE_DEFS = Object.freeze([
method: 'GET',
action: 'quota_reservation_log',
}),
Object.freeze({ path: '/api/host-i18n', method: 'GET', action: 'host_i18n_get' }),
Object.freeze({ path: '/api/host-i18n', method: 'POST', action: 'host_i18n_action' }),
]);
const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path));
@@ -960,6 +962,69 @@ function readInjectedWindowBridge() {
return { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_BRIDGE_ENDPOINT_KEY, WINDOW_BRIDGE_ENDPOINT_HEADER, LOCAL_ENDPOINT_ID, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge };
})();
// --- shared/host-i18n-protocol.mjs ---
const { HOST_I18N_GLOBAL_KEY, HOST_I18N_API_PATH, HOST_I18N_SCHEMA_VERSION, HOST_I18N_OFF_LOCALE, HOST_I18N_DEFAULT_DEPTH, HOST_I18N_DEPTHS, HOST_I18N_LOCALE_RE, normalizeHostI18nLocale, normalizeHostI18nDepth } = (() => {
/**
* @fileoverview Zero-dependency shared protocol constants and normalizers
* for the decoupled Antigravity Host I18n subsystem.
*/
const HOST_I18N_GLOBAL_KEY = '__AGUsageMonitorHostI18n';
const HOST_I18N_API_PATH = '/api/host-i18n';
const HOST_I18N_SCHEMA_VERSION = 1;
const HOST_I18N_OFF_LOCALE = 'off';
const HOST_I18N_DEFAULT_DEPTH = 'light';
const HOST_I18N_DEPTHS = Object.freeze(['light', 'deep']);
const HOST_I18N_LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/;
/**
* Normalizes a host translation locale identifier (`'off'` or canonical BCP-47 tag).
*
* @param {unknown} value
* @returns {string}
*/
function normalizeHostI18nLocale(value) {
const raw = String(value || '').trim();
if (!raw) return HOST_I18N_OFF_LOCALE;
const lower = raw.toLowerCase();
if (
lower === 'off' ||
lower === 'none' ||
lower === 'disabled' ||
lower === 'original' ||
lower === 'default'
) {
return HOST_I18N_OFF_LOCALE;
}
const normalized = raw.replace(/_/g, '-');
if (!HOST_I18N_LOCALE_RE.test(normalized)) {
return HOST_I18N_OFF_LOCALE;
}
const parts = normalized.split('-');
return parts
.map((part, idx) => {
if (idx === 0) return part.toLowerCase();
if (part.length === 2) return part.toUpperCase();
if (part.length === 4) return part[0].toUpperCase() + part.slice(1).toLowerCase();
return part;
})
.join('-');
}
/**
* Normalizes translation depth (`'light'` or `'deep'`).
*
* @param {unknown} value
* @returns {'light'|'deep'}
*/
function normalizeHostI18nDepth(value) {
const lower = String(value || '').trim().toLowerCase();
if (lower === 'deep' || lower === 'full') return 'deep';
return HOST_I18N_DEFAULT_DEPTH;
}
return { HOST_I18N_GLOBAL_KEY, HOST_I18N_API_PATH, HOST_I18N_SCHEMA_VERSION, HOST_I18N_OFF_LOCALE, HOST_I18N_DEFAULT_DEPTH, HOST_I18N_DEPTHS, HOST_I18N_LOCALE_RE, normalizeHostI18nLocale, normalizeHostI18nDepth };
})();
// --- src/icons/svgRegistry.js ---
const { SVG_ICON_DEFS } = (() => {
/**
@@ -1104,6 +1169,11 @@ const SVG_ICON_DEFS = Object.freeze({
{ tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } },
{ tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } },
],
globe: [
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } },
{ tag: 'ellipse', attrs: { cx: '8', cy: '8', rx: '2.7', ry: '6' } },
{ tag: 'path', attrs: { d: 'M2.3 6h11.4M2.3 10h11.4' } },
],
});
return { SVG_ICON_DEFS };
})();
@@ -1959,6 +2029,45 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.gen.updateOffSub': '已关闭更新提醒 ({mode})',
'settings.gen.latestSub': '已是最新 ({mode})',
// Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n)
'settings.hostI18n.title': 'Antigravity 界面语言',
'settings.hostI18n.langLabel': '目标语言',
'settings.hostI18n.langOff': '原始语言(不翻译)',
'settings.hostI18n.langHint': '从仓库按需独立下载语言包并在渲染层无损应用,不修改宿主安装包,不影响聊天内容与代码',
'settings.hostI18n.optInstalled': '已下载 v{ver}',
'settings.hostI18n.optRemote': '仓库拉取 · {size}',
'settings.hostI18n.refreshManifestTip': '刷新仓库语言包清单',
'settings.hostI18n.refreshingManifestMsg': '正在拉取语言清单…',
'settings.hostI18n.manifestSyncedMsg': '已更新清单({count} 个语言包)',
'settings.hostI18n.manifestFailedMsg': '拉取语言清单失败,请检查网络或代理',
'settings.hostI18n.depthLabel': '翻译深度',
'settings.hostI18n.depthLight': '浅度',
'settings.hostI18n.depthDeep': '深度',
'settings.hostI18n.depthLightHint': '浅度模式:保留 MCP、Skill、Workspace、Subagent、Swarm、Diff、Terminal 等高频英文术语及模型名称,仅翻译常规界面',
'settings.hostI18n.depthDeepHint': '深度模式:将常见工程术语一并译为目标语言(如工作区、子代理、蜂群、终端、沙箱),仅保留模型名与命令',
'settings.hostI18n.downloadingMsg': '正在下载 {locale} 语言包…',
'settings.hostI18n.downloadedAndAppliedMsg': '语言包已下载校验并生效',
'settings.hostI18n.appliedMsg': '已切换并即时生效',
'settings.hostI18n.disabledMsg': '已关闭翻译并还原原始界面',
'settings.hostI18n.depthSwitchedMsg': '已热切换翻译深度',
'settings.hostI18n.packUpdatedMsg': '语言包已更新并重新应用',
'settings.hostI18n.cacheRemovedMsg': '已删除本地语言包缓存',
'settings.hostI18n.actionFailed': '语言包操作失败,请重试',
'settings.hostI18n.entriesCount': '{count} 条词条',
'settings.hostI18n.appliedWindows': '已应用 {count} 窗口',
'settings.hostI18n.updatePackBtn': '更新至 v{ver}',
'settings.hostI18n.redownloadBtn': '检查更新',
'settings.hostI18n.removeCacheBtn': '删除缓存',
'settings.hostI18n.devToolsTitle': '词条采集与多语言扩展',
'settings.hostI18n.devToolsHint': '仅扫描当前打开的 Antigravity 界面控件中未命中的英文短语(自动排除聊天正文与代码),便于补全漏翻词条或制作新语言包',
'settings.hostI18n.collectBtn': '采集未翻译 UI 文案',
'settings.hostI18n.collectingBtn': '采集中…',
'settings.hostI18n.collectedResult': '共采集到 {count} 条待翻译 UI 文案(扫描 {targets} 个窗口)',
'settings.hostI18n.collectedEmpty': '当前页面未检测到待翻译的英文 UI 短语',
'settings.hostI18n.collectFailed': '采集失败,请确认已开启调试端口并打开主窗口',
'settings.hostI18n.copyJsonBtn': '复制 JSON',
'settings.hostI18n.exportJsonBtn': '导出 JSON',
// Preferences -> Structure Tab
'settings.str.thirdTabAria': '结构子菜单切换',
'settings.str.tabMount': '挂载胶囊',
@@ -2951,6 +3060,45 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'settings.gen.updateOffSub': 'Notifications off ({mode})',
'settings.gen.latestSub': 'Up to date ({mode})',
// Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n)
'settings.hostI18n.title': 'Antigravity UI Language',
'settings.hostI18n.langLabel': 'Host Language',
'settings.hostI18n.langOff': 'Original (Off)',
'settings.hostI18n.langHint': 'Downloads built language packs on demand from the repository and applies lossless runtime UI translation without patching app files or chat content',
'settings.hostI18n.optInstalled': 'Installed v{ver}',
'settings.hostI18n.optRemote': 'Download · {size}',
'settings.hostI18n.refreshManifestTip': 'Refresh repository language pack manifest',
'settings.hostI18n.refreshingManifestMsg': 'Refreshing language manifest…',
'settings.hostI18n.manifestSyncedMsg': 'Manifest updated ({count} packs)',
'settings.hostI18n.manifestFailedMsg': 'Failed to fetch language manifest',
'settings.hostI18n.depthLabel': 'Translation Depth',
'settings.hostI18n.depthLight': 'Light',
'settings.hostI18n.depthDeep': 'Deep',
'settings.hostI18n.depthLightHint': 'Light mode keeps common English engineering terms (MCP, Skill, Workspace, Subagent, Swarm, Diff, Terminal) and model names untranslated',
'settings.hostI18n.depthDeepHint': 'Deep mode localizes engineering terms alongside general UI copy while preserving model names and slash commands',
'settings.hostI18n.downloadingMsg': 'Downloading {locale} pack…',
'settings.hostI18n.downloadedAndAppliedMsg': 'Pack verified and applied',
'settings.hostI18n.appliedMsg': 'Language applied live',
'settings.hostI18n.disabledMsg': 'Translation disabled and UI restored',
'settings.hostI18n.depthSwitchedMsg': 'Translation depth switched',
'settings.hostI18n.packUpdatedMsg': 'Language pack updated and reapplied',
'settings.hostI18n.cacheRemovedMsg': 'Local pack cache removed',
'settings.hostI18n.actionFailed': 'Language pack operation failed',
'settings.hostI18n.entriesCount': '{count} entries',
'settings.hostI18n.appliedWindows': '{count} window(s) active',
'settings.hostI18n.updatePackBtn': 'Update to v{ver}',
'settings.hostI18n.redownloadBtn': 'Check Update',
'settings.hostI18n.removeCacheBtn': 'Remove Cache',
'settings.hostI18n.devToolsTitle': 'Missing UI String Collector',
'settings.hostI18n.devToolsHint': 'Scans visible Antigravity UI controls for untranslated English phrases (excluding chat content and code) to help complete packs or author new languages',
'settings.hostI18n.collectBtn': 'Collect Missing Strings',
'settings.hostI18n.collectingBtn': 'Collecting…',
'settings.hostI18n.collectedResult': 'Collected {count} untranslated UI strings across {targets} window(s)',
'settings.hostI18n.collectedEmpty': 'No untranslated English UI strings detected on active pages',
'settings.hostI18n.collectFailed': 'Collection failed — verify remote debugging bridge is active',
'settings.hostI18n.copyJsonBtn': 'Copy JSON',
'settings.hostI18n.exportJsonBtn': 'Export JSON',
// Preferences -> Structure Tab
'settings.str.thirdTabAria': 'Structure section tabs',
'settings.str.tabMount': 'Mount & Bar',
@@ -9225,6 +9373,85 @@ async function copyTextWithFeedback(text, successMessage) {
return { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFeedback, copyTextWithFeedback };
})();
// --- src/core/hostI18nClient.js ---
const { fetchHostI18nStatus, refreshHostI18nManifest, selectHostI18nLanguage, updateHostI18nDepth, installOrUpdateHostI18nPack, removeHostI18nPack, collectHostI18nUntranslated } = (() => {
/**
* @fileoverview Decoupled HTTP/CDP client for `/api/host-i18n`.
* Completely independent from `telemetryStore.js`.
*/
async function fetchHostI18nStatus() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'GET',
abortKey: 'host-i18n-get',
cdpTimeoutMs: 12000,
});
}
async function refreshHostI18nManifest() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: { action: 'refresh_manifest' },
cdpTimeoutMs: 18000,
});
}
async function selectHostI18nLanguage(locale, depth) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'select',
locale: normalizeHostI18nLocale(locale),
...(depth !== undefined ? { depth: normalizeHostI18nDepth(depth) } : {}),
},
cdpTimeoutMs: 22000,
});
}
async function updateHostI18nDepth(depth) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'set_depth',
depth: normalizeHostI18nDepth(depth),
},
cdpTimeoutMs: 10000,
});
}
async function installOrUpdateHostI18nPack(locale) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'update',
locale: normalizeHostI18nLocale(locale),
},
cdpTimeoutMs: 22000,
});
}
async function removeHostI18nPack(locale) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'remove',
locale: normalizeHostI18nLocale(locale),
},
cdpTimeoutMs: 10000,
});
}
async function collectHostI18nUntranslated() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: { action: 'collect_untranslated' },
cdpTimeoutMs: 15000,
});
}
return { fetchHostI18nStatus, refreshHostI18nManifest, selectHostI18nLanguage, updateHostI18nDepth, installOrUpdateHostI18nPack, removeHostI18nPack, collectHostI18nUntranslated };
})();
// --- src/store/telemetryStore.js ---
const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientAccountQuotaRefreshMinutes, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => {
/**
@@ -30835,6 +31062,652 @@ const SessionMigrationCard = defineComponent({
return { SessionMigrationCard };
})();
// --- src/components/settings/HostI18nCard.js ---
const { HostI18nCard } = (() => {
/**
* @fileoverview Self-contained Antigravity Host UI Language card (`HostI18nCard.js`).
*
* Mounted inside `SettingsGeneralTab` with minimal glue; manages:
* - Language selection (`off` or any pack listed in repository `manifest.json`),
* - Conditional Light / Deep translation depth switching (0-network hot switch),
* - On-demand repository pack download, update, and local cache removal,
* - CDP bridge notice when DevTools port is unavailable,
* - Optional collapsed developer drawer to collect untranslated UI strings.
*/
function formatHostI18nBytes(bytes) {
const num = Number(bytes || 0);
if (!Number.isFinite(num) || num <= 0) return '';
if (num < 1024) return `${num} B`;
return `${(num / 1024).toFixed(1)} KB`;
}
function getHostI18nDepthOptions() {
return [
{ value: 'light', label: t('settings.hostI18n.depthLight') },
{ value: 'deep', label: t('settings.hostI18n.depthDeep') },
];
}
const HostI18nCard = defineComponent({
name: 'HostI18nCard',
setup({ props, onCleanup }) {
let status = null;
let draftLocale = HOST_I18N_OFF_LOCALE;
let draftDepth = 'light';
let latestWindowBridge = null;
let latestHostPlatform = 'win32';
let lastBridgeRenderSig = '';
let hasLoadedOnce = false;
let isBusy = false;
let isCollecting = false;
let destroyed = false;
let feedbackTimer = null;
let devExpanded = false;
let lastCollected = null;
const titleEl = h('span', { text: t('settings.hostI18n.title') });
const statusMsgEl = h('span', {
className: 'text-muted host-i18n-status-msg',
text: '',
});
function showFeedback(text, { isError = false, autoClearMs = 2800 } = {}) {
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
patchText(statusMsgEl, text || '');
patchClasses(statusMsgEl, { 'is-error': Boolean(isError && text) });
if (text && autoClearMs > 0) {
feedbackTimer = setTimeout(() => {
feedbackTimer = null;
if (!destroyed) {
patchText(statusMsgEl, '');
patchClasses(statusMsgEl, { 'is-error': false });
}
}, autoClearMs);
}
}
function getPackList() {
return Array.isArray(status?.packs) ? status.packs : [];
}
function findPackByLocale(locale) {
return getPackList().find((p) => p.locale === locale) || null;
}
function buildLocaleOptions() {
const opts = [{ value: HOST_I18N_OFF_LOCALE, label: t('settings.hostI18n.langOff') }];
for (const pack of getPackList()) {
const displayName =
pack.nativeName && pack.nativeName !== pack.name
? `${pack.nativeName} (${pack.locale})`
: `${pack.name || pack.locale} (${pack.locale})`;
const tag = pack.installed
? t('settings.hostI18n.optInstalled', { ver: pack.installedVersion || pack.remoteVersion || '1.0.0' })
: t('settings.hostI18n.optRemote', {
size: formatHostI18nBytes(pack.remoteBytes) || 'pack',
});
opts.push({
value: pack.locale,
label: `${displayName} · ${tag}`,
});
}
if (
draftLocale !== HOST_I18N_OFF_LOCALE &&
!opts.some((o) => o.value === draftLocale)
) {
opts.push({ value: draftLocale, label: draftLocale });
}
return opts;
}
const langLabelEl = h('span', {
className: 'form-label',
text: t('settings.hostI18n.langLabel'),
});
const langSelect = CustomSelect({
ariaLabel: t('settings.hostI18n.langLabel'),
icon: 'globe',
modelValue: draftLocale,
options: buildLocaleOptions(),
onUpdateModelValue: async (val) => {
if (isBusy || destroyed) return;
const nextLocale = normalizeHostI18nLocale(val);
const targetPack = findPackByLocale(nextLocale);
const needsDownload =
nextLocale !== HOST_I18N_OFF_LOCALE && !targetPack?.installed;
isBusy = true;
draftLocale = nextLocale;
syncControls();
showFeedback(
needsDownload
? t('settings.hostI18n.downloadingMsg', { locale: nextLocale })
: t('settings.saving'),
{ autoClearMs: 0 }
);
try {
const res = await selectHostI18nLanguage(nextLocale, draftDepth);
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
} else if (nextLocale === HOST_I18N_OFF_LOCALE) {
showFeedback(t('settings.hostI18n.disabledMsg'), { autoClearMs: 2500 });
} else if (res?.downloaded) {
showFeedback(t('settings.hostI18n.downloadedAndAppliedMsg'), { autoClearMs: 3200 });
} else {
showFeedback(t('settings.hostI18n.appliedMsg'), { autoClearMs: 2200 });
}
} catch (err) {
if (!destroyed) {
if (status) applyStatusPayload(status);
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
});
const refreshManifestBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm host-i18n-icon-btn',
title: t('settings.hostI18n.refreshManifestTip'),
'aria-label': t('settings.hostI18n.refreshManifestTip'),
onClick: async () => {
if (isBusy || destroyed) return;
isBusy = true;
syncControls();
showFeedback(t('settings.hostI18n.refreshingManifestMsg'), { autoClearMs: 0 });
try {
const res = await refreshHostI18nManifest();
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.manifestFailedMsg'), {
isError: true,
autoClearMs: 4500,
});
} else {
showFeedback(
t('settings.hostI18n.manifestSyncedMsg', { count: getPackList().length }),
{ autoClearMs: 2600 }
);
}
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.manifestFailedMsg'), {
isError: true,
autoClearMs: 4500,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
},
[createSvgIcon('refresh', { size: 12 })]
);
const langHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.langHint'),
});
// --- Conditional Depth Row (visible only when locale !== 'off') ---
const depthLabelEl = h('span', {
className: 'form-label',
text: t('settings.hostI18n.depthLabel'),
});
const depthSwitch = SegmentedControl({
ariaLabel: t('settings.hostI18n.depthLabel'),
modelValue: draftDepth,
options: getHostI18nDepthOptions(),
onUpdateModelValue: async (val) => {
if (isBusy || destroyed) return;
const nextDepth = normalizeHostI18nDepth(val);
if (nextDepth === draftDepth) return;
isBusy = true;
draftDepth = nextDepth;
syncControls();
showFeedback(t('settings.saving'), { autoClearMs: 0 });
try {
const res = await updateHostI18nDepth(nextDepth);
if (destroyed) return;
applyStatusPayload(res);
showFeedback(t('settings.hostI18n.depthSwitchedMsg'), { autoClearMs: 2000 });
} catch (err) {
if (!destroyed) {
if (status) applyStatusPayload(status);
showFeedback(err?.message || t('settings.saveFailed'), {
isError: true,
autoClearMs: 3500,
});
}
} finally {
isBusy = false;
if (!destroyed) syncControls();
}
},
});
const depthHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.depthLightHint'),
});
const depthRowEl = h('div', { className: 'form-row', hidden: true }, [
depthLabelEl,
depthSwitch.el,
depthHintEl,
]);
// --- Pack Meta & Actions Bar (visible only when locale !== 'off') ---
const packMetaTextEl = h('span', { className: 'host-i18n-pack-meta text-muted', text: '' });
const updatePackBtnText = h('span', { text: t('settings.hostI18n.redownloadBtn') });
const updatePackBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return;
isBusy = true;
syncControls();
showFeedback(t('settings.hostI18n.downloadingMsg', { locale: draftLocale }), {
autoClearMs: 0,
});
try {
const res = await installOrUpdateHostI18nPack(draftLocale);
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
} else {
showFeedback(t('settings.hostI18n.packUpdatedMsg'), { autoClearMs: 3000 });
}
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
}
} finally {
isBusy = false;
if (!destroyed) syncControls();
}
},
},
[createSvgIcon('download', { size: 12 }), updatePackBtnText]
);
const removePackBtnText = h('span', { text: t('settings.hostI18n.removeCacheBtn') });
const removePackBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
onClick: async () => {
if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return;
isBusy = true;
syncControls();
showFeedback(t('settings.saving'), { autoClearMs: 0 });
try {
const res = await removeHostI18nPack(draftLocale);
if (destroyed) return;
applyStatusPayload(res);
showFeedback(t('settings.hostI18n.cacheRemovedMsg'), { autoClearMs: 2800 });
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 4500,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
},
[removePackBtnText]
);
const packBarEl = h('div', { className: 'host-i18n-pack-bar', hidden: true }, [
packMetaTextEl,
h('div', { className: 'host-i18n-pack-actions' }, [updatePackBtn, removePackBtn]),
]);
// --- CDP Bridge Diagnostic Notice (shown only when active locale cannot reach CDP) ---
const bridgeNotice = BridgeStatusNotice({ contextMode: true });
// --- Collapsed Developer Drawer: Untranslated UI String Collector ---
const devChevron = createSvgIcon('chevron-right', {
size: 11,
className: 'host-i18n-dev-chevron',
});
const devToggleText = h('span', { text: t('settings.hostI18n.devToolsTitle') });
const devToggleBtn = h(
'button',
{
type: 'button',
className: 'host-i18n-dev-toggle',
'aria-expanded': 'false',
onClick: () => {
devExpanded = !devExpanded;
patchAttr(devToggleBtn, 'aria-expanded', devExpanded ? 'true' : 'false');
patchClasses(devDrawerEl, { 'is-expanded': devExpanded });
patchAttr(devBodyEl, 'hidden', !devExpanded);
props.onLayoutChange?.();
},
},
[devChevron, devToggleText]
);
const devHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.devToolsHint'),
});
const collectBtnText = h('span', { text: t('settings.hostI18n.collectBtn') });
const collectResultEl = h('span', { className: 'settings-hint-text', text: '' });
const copyCollectedBtnText = h('span', { text: t('settings.hostI18n.copyJsonBtn') });
const copyCollectedBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
hidden: true,
onClick: async () => {
if (!lastCollected?.template) return;
await copyTextWithFeedback(JSON.stringify(lastCollected.template, null, 2), {
onFeedback: (msg) => showFeedback(msg, { autoClearMs: 2400 }),
});
},
},
[createSvgIcon('copy', { size: 11 }), copyCollectedBtnText]
);
const exportCollectedBtnText = h('span', { text: t('settings.hostI18n.exportJsonBtn') });
const exportCollectedBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
hidden: true,
onClick: async () => {
if (!lastCollected?.template) return;
const fileLocale = draftLocale === HOST_I18N_OFF_LOCALE ? 'en-source' : draftLocale;
await exportTextFileWithFeedback({
filename: `host-i18n-missing-${fileLocale}.json`,
content: JSON.stringify(lastCollected.template, null, 2) + '\n',
mimeType: 'application/json',
onFeedback: (msg) => showFeedback(msg, { autoClearMs: 3200 }),
});
},
},
[createSvgIcon('download', { size: 11 }), exportCollectedBtnText]
);
const collectBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isCollecting || destroyed) return;
isCollecting = true;
patchAttr(collectBtn, 'disabled', true);
patchText(collectBtnText, t('settings.hostI18n.collectingBtn'));
try {
const res = await collectHostI18nUntranslated();
if (destroyed) return;
if (res?.ok) {
lastCollected = res;
patchText(
collectResultEl,
res.count > 0
? t('settings.hostI18n.collectedResult', {
count: res.count,
targets: res.targets || 1,
})
: t('settings.hostI18n.collectedEmpty')
);
patchAttr(copyCollectedBtn, 'hidden', !(res.count > 0));
patchAttr(exportCollectedBtn, 'hidden', !(res.count > 0));
} else {
patchText(collectResultEl, res?.error || t('settings.hostI18n.collectFailed'));
}
} catch (err) {
if (!destroyed) {
patchText(collectResultEl, err?.message || t('settings.hostI18n.collectFailed'));
}
} finally {
isCollecting = false;
if (!destroyed) {
patchAttr(collectBtn, 'disabled', false);
patchText(collectBtnText, t('settings.hostI18n.collectBtn'));
props.onLayoutChange?.();
}
}
},
},
[createSvgIcon('search', { size: 12 }), collectBtnText]
);
const devBodyEl = h('div', { className: 'host-i18n-dev-body', hidden: true }, [
devHintEl,
h('div', { className: 'host-i18n-dev-actions' }, [
collectBtn,
copyCollectedBtn,
exportCollectedBtn,
]),
collectResultEl,
]);
const devDrawerEl = h('div', { className: 'host-i18n-dev-drawer' }, [
devToggleBtn,
devBodyEl,
]);
const rootEl = h('section', { className: 'panel host-i18n-panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('globe', { size: 13 }),
titleEl,
]),
statusMsgEl,
]),
h('div', { className: 'form-row' }, [
langLabelEl,
h('div', { className: 'host-i18n-select-row' }, [langSelect.el, refreshManifestBtn]),
langHintEl,
]),
depthRowEl,
packBarEl,
bridgeNotice.el,
devDrawerEl,
]);
function applyStatusPayload(payload) {
if (!payload || typeof payload !== 'object') return;
status = payload;
draftLocale = normalizeHostI18nLocale(payload.locale);
draftDepth = normalizeHostI18nDepth(payload.depth);
if (payload.bridgeStatus) {
latestWindowBridge = payload.bridgeStatus;
}
syncControls();
}
function syncControls() {
const enabled = draftLocale !== HOST_I18N_OFF_LOCALE;
const activePack = enabled ? findPackByLocale(draftLocale) : null;
langSelect.setProps({
modelValue: draftLocale,
options: buildLocaleOptions(),
disabled: isBusy,
});
patchAttr(refreshManifestBtn, 'disabled', isBusy);
patchAttr(depthRowEl, 'hidden', !enabled);
depthSwitch.setProps({
modelValue: draftDepth,
options: getHostI18nDepthOptions(),
});
patchText(
depthHintEl,
draftDepth === 'deep'
? t('settings.hostI18n.depthDeepHint')
: t('settings.hostI18n.depthLightHint')
);
patchAttr(packBarEl, 'hidden', !enabled);
if (enabled) {
const ver = activePack?.installedVersion || activePack?.remoteVersion || '1.0.0';
const stats = activePack?.stats;
const entryCount = stats
? Number(stats.baseExact || 0) +
Number(draftDepth === 'deep' ? stats.deepExact || 0 : stats.lightExact || 0) +
Number(stats.basePatterns || 0) +
Number(draftDepth === 'deep' ? stats.deepPatterns || 0 : stats.lightPatterns || 0)
: 0;
const sizeStr = formatHostI18nBytes(
activePack?.installedBytes || activePack?.remoteBytes || 0
);
const appliedCount = Number(latestWindowBridge?.hostI18nAppliedCount || 0);
const metaParts = [`v${ver}`];
if (entryCount > 0) {
metaParts.push(t('settings.hostI18n.entriesCount', { count: entryCount }));
}
if (sizeStr) metaParts.push(sizeStr);
if (appliedCount > 0) {
metaParts.push(t('settings.hostI18n.appliedWindows', { count: appliedCount }));
}
patchText(packMetaTextEl, metaParts.join(' · '));
const hasUpdate = Boolean(activePack?.updateAvailable);
patchText(
updatePackBtnText,
hasUpdate
? t('settings.hostI18n.updatePackBtn', { ver: activePack.remoteVersion })
: t('settings.hostI18n.redownloadBtn')
);
patchClasses(updatePackBtn, {
'btn-primary': hasUpdate,
'btn-secondary': !hasUpdate,
});
patchAttr(updatePackBtn, 'disabled', isBusy);
patchAttr(removePackBtn, 'disabled', isBusy || !activePack?.installed);
}
bridgeNotice.refs.update({
visible: enabled,
windowBridge: latestWindowBridge,
hostPlatform: latestHostPlatform,
contextMode: true,
});
}
async function load(force = false) {
if (destroyed) return;
if (hasLoadedOnce && !force) return;
hasLoadedOnce = true;
try {
const res = await fetchHostI18nStatus();
if (destroyed) return;
applyStatusPayload(res);
props.onLayoutChange?.();
} catch {
// 静默兜底,保留手动刷新入口
}
}
function renderBridgeStatus(windowBridge, hostPlatform) {
if (windowBridge) latestWindowBridge = windowBridge;
if (hostPlatform) latestHostPlatform = hostPlatform;
const sig = [
Number(latestWindowBridge?.hostI18nAppliedCount || 0),
Boolean(latestWindowBridge?.connected),
Boolean(latestWindowBridge?.available),
String(latestWindowBridge?.reason || ''),
String(latestWindowBridge?.ideStatus?.reason || ''),
String(latestHostPlatform || ''),
].join('|');
if (sig === lastBridgeRenderSig) return;
lastBridgeRenderSig = sig;
syncControls();
}
function refreshLabels() {
patchText(titleEl, t('settings.hostI18n.title'));
patchText(langLabelEl, t('settings.hostI18n.langLabel'));
patchText(langHintEl, t('settings.hostI18n.langHint'));
patchText(depthLabelEl, t('settings.hostI18n.depthLabel'));
patchText(removePackBtnText, t('settings.hostI18n.removeCacheBtn'));
patchText(devToggleText, t('settings.hostI18n.devToolsTitle'));
patchText(devHintEl, t('settings.hostI18n.devToolsHint'));
if (!isCollecting) patchText(collectBtnText, t('settings.hostI18n.collectBtn'));
patchText(copyCollectedBtnText, t('settings.hostI18n.copyJsonBtn'));
patchText(exportCollectedBtnText, t('settings.hostI18n.exportJsonBtn'));
patchAttr(refreshManifestBtn, 'title', t('settings.hostI18n.refreshManifestTip'));
patchAttr(refreshManifestBtn, 'aria-label', t('settings.hostI18n.refreshManifestTip'));
bridgeNotice.refs.refreshLabels();
syncControls();
}
onCleanup(() => {
destroyed = true;
abortSidecarApiKey('host-i18n-get');
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
langSelect.destroy();
depthSwitch.destroy();
bridgeNotice.destroy();
});
return {
el: rootEl,
refs: {
langSelect,
depthSwitch,
load,
renderBridgeStatus,
refreshLabels,
},
};
},
});
return { HostI18nCard };
})();
// --- src/views/settings/SettingsGeneralTab.js ---
const { SettingsGeneralTab } = (() => {
/**
@@ -31228,9 +32101,20 @@ const SettingsGeneralTab = defineComponent({
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
]);
const rootEl = h('div', { className: 'settings-tab-stack' }, [appearancePanel, cloudPanel]);
const hostI18nCard = HostI18nCard({
onLayoutChange: () => props.onLayoutChange?.(),
});
function renderSettings(settings) {
const rootEl = h('div', { className: 'settings-tab-stack' }, [
appearancePanel,
hostI18nCard.el,
cloudPanel,
]);
function renderSettings(settings, windowBridge = null, hostPlatform = 'win32') {
if (windowBridge || hostPlatform) {
hostI18nCard.refs.renderBridgeStatus(windowBridge, hostPlatform);
}
if (!settings) return;
latestSettings = settings;
draftLanguage = normalizeI18nLanguage(settings.language);
@@ -31345,6 +32229,7 @@ const SettingsGeneralTab = defineComponent({
} else {
patchText(pricingSyncSub, t('quota.loading'));
}
hostI18nCard.refs.refreshLabels();
}
onCleanup(() => {
@@ -31355,6 +32240,7 @@ const SettingsGeneralTab = defineComponent({
fontScaleSwitch.destroy();
modernUiSwitch.destroy();
autoUpdateSelect.destroy();
hostI18nCard.destroy();
});
return {
@@ -31367,6 +32253,8 @@ const SettingsGeneralTab = defineComponent({
autoUpdateSelect,
syncPricingBtn,
updatePluginBtn,
hostI18nCard,
loadHostI18n: (force = false) => hostI18nCard.refs.load(force),
renderSettings,
renderCloudStatus,
refreshLabels,
@@ -39682,7 +40570,14 @@ const SettingsView = defineComponent({
);
}
} else if (settingsSubTab !== 'account') {
if (settings) generalTab.refs.renderSettings(settings);
if (settings) {
generalTab.refs.renderSettings(
settings,
telemetry?.windowBridge,
telemetry?.hostPlatform
);
}
void generalTab.refs.loadHostI18n?.(false);
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
}
refreshScroll();
@@ -40252,7 +41147,7 @@ const COMPOSER_MODEL_ATTR_RE =
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
const COMPOSER_MODE_TEXT_RE =
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i;
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|planning|act|review|confirm|normal|fast|自动|询问|始终询问|手动|始终允许|受控|规划|快速)(?:\s*(?:mode|模式))?$/i;
const COMPOSER_MODE_ATTR_RE =
/\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i;
const COMPOSER_ICON_FONT_CLASS_RE =
+51
View File
@@ -66,12 +66,19 @@ import {
triggerDesktopHostRelaunch,
} from './desktop-launcher-config.mjs';
import {
collectHostI18nUntranslatedFromActiveTargets,
ensureIdeRemoteDebuggingArgv,
getDefaultWindowBridgeStatus,
notifyHostI18nChanged,
notifyModelContextWindowsChanged,
notifyWindowOverlaySetting,
resolveDevToolsPortCandidates,
startDefaultWindowBridge,
} from './window-bridge.mjs';
import {
handleHostI18nGetRequest,
handleHostI18nPostAction,
} from './host-i18n/index.mjs';
import { getQuotaReservationLogSnapshot } from './quota-reservation.mjs';
import { getSessionMigrationCatalog, migrateSessions } from './session-migrator.mjs';
import {
@@ -867,6 +874,37 @@ export function executeQuotaReservationLogAction() {
};
}
export async function executeHostI18nGetAction(opts = {}) {
const result = await handleHostI18nGetRequest({
bridgeStatus: getDefaultWindowBridgeStatus(),
...(opts?.hostI18nManager ? { manager: opts.hostI18nManager } : {}),
});
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
export async function executeHostI18nPostAction(data = {}, opts = {}) {
const out = await handleHostI18nPostAction(isPlainObject(data) ? data : {}, {
bridgeStatus: getDefaultWindowBridgeStatus(),
onChanged: typeof opts?.onHostI18nChanged === 'function' ? opts.onHostI18nChanged : notifyHostI18nChanged,
collectFromTargets:
typeof opts?.collectHostI18nUntranslated === 'function'
? opts.collectHostI18nUntranslated
: collectHostI18nUntranslatedFromActiveTargets,
...(opts?.hostI18nManager ? { manager: opts.hostI18nManager } : {}),
});
return {
status: Number(out?.status || 200),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(out?.payload || { ok: false, error: 'Invalid host-i18n response' }),
};
}
export function executeRevealFileAction(data, opts = {}) {
const result = revealLocalExportFile(data?.filePath, {
...(opts?.platform ? { platform: opts.platform } : {}),
@@ -911,6 +949,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
if (isPlainObject(data) && data.__quotaReservationAction === 'log') {
return executeQuotaReservationLogAction();
}
if (isPlainObject(data) && typeof data.__hostI18nAction === 'string') {
if (data.__hostI18nAction === 'get') {
return executeHostI18nGetAction(opts);
}
return executeHostI18nPostAction(
{ ...(isPlainObject(data.payload) ? data.payload : {}), action: data.__hostI18nAction },
opts
);
}
return executeSettingsAction(data);
case 'accounts_get':
return executeAccountCredentialAction(undefined, opts);
@@ -938,6 +985,10 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
return executeRevealFileAction(data, opts);
case 'quota_reservation_log':
return executeQuotaReservationLogAction();
case 'host_i18n_get':
return executeHostI18nGetAction(opts);
case 'host_i18n_action':
return executeHostI18nPostAction(data, opts);
default:
return {
status: 404,
+1 -1
View File
@@ -382,7 +382,7 @@ export function computeRuntimeCodeVersion(options = {}) {
join(HERE, 'trajectory-metrics.mjs'),
LOCAL_CATALOG_FILE,
];
for (const subDir of ['shared', 'backend']) {
for (const subDir of ['shared', 'backend', join('backend', 'host-i18n')]) {
const absDir = join(HERE, subDir);
try {
if (existsSync(absDir)) {
@@ -0,0 +1,254 @@
/**
* @fileoverview 受控的 Antigravity 宿主语言包 HTTPS 拉取器。
*
* - 严格限制仅允许官方白名单域名(`raw.githubusercontent.com` / `cdn.jsdelivr.net`);
* - 复用 `cloudcode-proxy.mjs` 的系统 HTTPS 代理检测与 CONNECT 隧道,兼容代理环境;
* - 主源超时或 5xx/网络失败时自动回退至 jsDelivr CDN 镜像;
* - 响应体严格限制大小上限,避免异常大载荷撑爆内存。
*/
import { detectSystemHttpsProxy, openCcProxyTunnelSocket } from '../cloudcode-proxy.mjs';
export const HOST_I18N_ALLOWED_HOSTS = Object.freeze([
'raw.githubusercontent.com',
'cdn.jsdelivr.net',
]);
export const HOST_I18N_MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
export const HOST_I18N_DEFAULT_TIMEOUT_MS = 8_000;
const HOST_I18N_MAX_REDIRECTS = 3;
let hostI18nNetModulesPromise = null;
async function loadHostI18nNetModules() {
if (!hostI18nNetModulesPromise) {
hostI18nNetModulesPromise = Promise.all([
import('node:http'),
import('node:https'),
import('node:net'),
import('node:tls'),
]).then(([httpMod, httpsMod, netMod, tlsMod]) => ({
http: httpMod.default || httpMod,
https: httpsMod.default || httpsMod,
net: netMod.default || netMod,
tls: tlsMod.default || tlsMod,
}));
}
return hostI18nNetModulesPromise;
}
/**
* 校验下载 URL 是否属于允许的 HTTPS 白名单源。
*
* @param {string} rawUrl
* @returns {URL}
*/
export function assertAllowedHostI18nUrl(rawUrl) {
let parsed;
try {
parsed = new URL(String(rawUrl || '').trim());
} catch {
throw new Error('Invalid host-i18n download URL');
}
if (parsed.protocol !== 'https:') {
throw new Error(`Unsupported host-i18n protocol: ${parsed.protocol}`);
}
const host = parsed.hostname.toLowerCase();
if (!HOST_I18N_ALLOWED_HOSTS.includes(host)) {
throw new Error(`Disallowed host-i18n host: ${host}`);
}
return parsed;
}
/**
* 通过原生 `https` + 系统 HTTPS 代理隧道拉取单个白名单 URL 的 UTF-8 文本。
*
* @param {string} rawUrl
* @param {{ timeoutMs?: number, maxBytes?: number, redirectCount?: number }} [options]
* @returns {Promise<{ ok: boolean, status: number, text: string, url: string }>}
*/
async function fetchAllowedUrlViaNodeHttps(
rawUrl,
{
timeoutMs = HOST_I18N_DEFAULT_TIMEOUT_MS,
maxBytes = HOST_I18N_MAX_RESPONSE_BYTES,
redirectCount = 0,
} = {}
) {
const target = assertAllowedHostI18nUrl(rawUrl);
const mods = await loadHostI18nNetModules();
const { http, https, net, tls } = mods;
const proxy = await detectSystemHttpsProxy(target.hostname).catch(() => null);
const socket = proxy
? await openCcProxyTunnelSocket(
{ http, https, net, tls },
target.hostname,
Number(target.port || 443),
proxy,
{ timeoutMs: Math.min(timeoutMs, 5_000) }
)
: null;
let socketConsumed = false;
const agent = socket ? new https.Agent({ keepAlive: false }) : null;
if (agent) {
agent.createConnection = () => {
socketConsumed = true;
return socket;
};
}
return new Promise((resolve, reject) => {
let settled = false;
const finish = (ok, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (!socketConsumed) {
try {
socket?.destroy();
} catch {
// 忽略关闭异常
}
}
try {
agent?.destroy();
} catch {
// 忽略关闭异常
}
if (ok) resolve(value);
else reject(value);
};
const req = https.request(
target,
{
method: 'GET',
headers: {
Accept: 'application/json, text/plain;q=0.9',
'Cache-Control': 'no-cache',
'User-Agent': 'antigravity-usage-monitor-host-i18n/1.0',
},
...(agent ? { agent } : {}),
},
(res) => {
const status = Number(res.statusCode || 0);
if (
(status === 301 || status === 302 || status === 307 || status === 308) &&
res.headers?.location &&
redirectCount < HOST_I18N_MAX_REDIRECTS
) {
res.resume();
let nextUrl = '';
try {
nextUrl = new URL(String(res.headers.location), target).href;
assertAllowedHostI18nUrl(nextUrl);
} catch (err) {
finish(false, err);
return;
}
clearTimeout(timer);
fetchAllowedUrlViaNodeHttps(nextUrl, {
timeoutMs,
maxBytes,
redirectCount: redirectCount + 1,
}).then(
(val) => finish(true, val),
(err) => finish(false, err)
);
return;
}
const chunks = [];
let totalBytes = 0;
res.on('data', (chunk) => {
totalBytes += chunk.length;
if (totalBytes > maxBytes) {
req.destroy(new Error(`host-i18n response exceeds ${maxBytes} bytes`));
return;
}
chunks.push(chunk);
});
res.on('error', (err) => finish(false, err));
res.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
finish(true, {
ok: status >= 200 && status < 300,
status,
text,
url: target.href,
});
});
}
);
const timer = setTimeout(() => {
req.destroy(new Error(`host-i18n request timeout after ${timeoutMs}ms`));
}, timeoutMs);
timer.unref?.();
req.on('error', (err) => finish(false, err));
req.end();
});
}
/**
* 依次尝试多个白名单候选 URL(主源 GitHub Raw -> 备用 jsDelivr CDN),返回首个成功的文本响应。
*
* @param {string[]} urls
* @param {{
* timeoutMs?: number,
* maxBytes?: number,
* fetchImpl?: ((url: string, init?: object) => Promise<{ ok: boolean, status?: number, text: () => Promise<string> }>)|null,
* }} [options]
* @returns {Promise<{ text: string, url: string, status: number }>}
*/
export async function fetchHostI18nTextWithFallback(
urls,
{
timeoutMs = HOST_I18N_DEFAULT_TIMEOUT_MS,
maxBytes = HOST_I18N_MAX_RESPONSE_BYTES,
fetchImpl = null,
} = {}
) {
const list = Array.isArray(urls) ? urls.filter(Boolean) : [];
if (list.length === 0) {
throw new Error('No host-i18n candidate URLs configured');
}
const errors = [];
for (const rawUrl of list) {
const validated = assertAllowedHostI18nUrl(rawUrl);
try {
if (typeof fetchImpl === 'function') {
const res = await fetchImpl(validated.href, {
method: 'GET',
headers: { Accept: 'application/json', 'Cache-Control': 'no-cache' },
signal:
typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
? AbortSignal.timeout(timeoutMs)
: undefined,
});
const status = Number(res?.status || (res?.ok ? 200 : 500));
if (!res?.ok) {
throw new Error(`HTTP ${status}`);
}
const text = await res.text();
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
throw new Error(`host-i18n response exceeds ${maxBytes} bytes`);
}
return { text, url: validated.href, status };
}
const res = await fetchAllowedUrlViaNodeHttps(validated.href, { timeoutMs, maxBytes });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return { text: res.text, url: res.url, status: res.status };
} catch (err) {
errors.push(`${validated.hostname}: ${err?.message || 'request failed'}`);
}
}
throw new Error(`Failed to fetch host-i18n asset (${errors.join('; ')})`);
}
+209
View File
@@ -0,0 +1,209 @@
/**
* @fileoverview Antigravity 宿主多语言子系统统一门面 (`backend/host-i18n/index.mjs`)。
*
* 主程序其余模块(`window-bridge.mjs`、`api-actions.mjs`)仅通过本门面与宿主翻译子系统交互,
* 保持极薄的集成边界与完整可剥离性。
*/
import {
HOST_I18N_DEFAULT_DEPTH,
HOST_I18N_OFF_LOCALE,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../shared/host-i18n-protocol.mjs';
import { createHostI18nPackManager } from './pack-manager.mjs';
import {
createHostI18nApplyExpression,
createHostI18nCollectExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
} from './runtime-translator.mjs';
export {
HOST_I18N_DEFAULT_DEPTH,
HOST_I18N_OFF_LOCALE,
createHostI18nApplyExpression,
createHostI18nCollectExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
createHostI18nPackManager,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
};
let defaultHostI18nManager = null;
/**
* 获取进程级默认宿主语言包管理器单例。
*/
export function getDefaultHostI18nManager() {
if (!defaultHostI18nManager) {
defaultHostI18nManager = createHostI18nPackManager();
}
return defaultHostI18nManager;
}
/**
* 供 `window-bridge.mjs` 读取当前宿主翻译是否激活及按需下发描述。
*/
export function getHostI18nBridgeDescriptor() {
return getDefaultHostI18nManager().getActiveBridgeDescriptor();
}
/**
* 判断宿主语言翻译当前是否处于激活状态(用于独立保活 CDP 调试端口)。
*
* @returns {boolean}
*/
export function isHostI18nActiveForBridge() {
return Boolean(getHostI18nBridgeDescriptor()?.active);
}
/**
* 处理 `GET /api/host-i18n`:返回当前状态、已安装包与远端语言清单(必要时静默拉取缓存清单)。
*
* @param {{ bridgeStatus?: object|null, manager?: ReturnType<typeof createHostI18nPackManager> }} [options]
*/
export async function handleHostI18nGetRequest({ bridgeStatus = null, manager = null } = {}) {
const mgr = manager || getDefaultHostI18nManager();
const manifestResult = await mgr.refreshManifest({ force: false });
return {
ok: true,
...mgr.getStatusSnapshot({ manifestResult, bridgeStatus }),
};
}
/**
* 处理 `POST /api/host-i18n` 控制指令:
* - `refresh_manifest`:强制刷新仓库语言包清单
* - `select`:选择语言(未下载时自动拉取并校验 SHA-256 后生效,传 `'off'` 即关闭并还原)
* - `set_depth`:在 `'light'` / `'deep'` 间零网络热切换
* - `install` / `update`:显式下载或更新指定语言包
* - `remove`:删除指定语言的本地缓存包
* - `collect_untranslated`:按需采集当前打开宿主页面中未翻译的英文 UI 短语
*
* @param {object} body
* @param {{
* bridgeStatus?: object|null,
* onChanged?: (() => Promise<any>|any)|null,
* collectFromTargets?: (() => Promise<{ targets: number, items: Array<{ text: string, kind: string, count: number }> }>)|null,
* manager?: ReturnType<typeof createHostI18nPackManager>|null,
* }} [options]
*/
export async function handleHostI18nPostAction(
body = {},
{ bridgeStatus = null, onChanged = null, collectFromTargets = null, manager = null } = {}
) {
const mgr = manager || getDefaultHostI18nManager();
const action = String(body?.action || '').trim().toLowerCase();
try {
if (action === 'refresh_manifest') {
const manifestResult = await mgr.refreshManifest({ force: true });
return {
status: 200,
payload: {
ok: manifestResult.ok,
...(manifestResult.error ? { error: manifestResult.error } : {}),
...mgr.getStatusSnapshot({ manifestResult, bridgeStatus }),
},
};
}
if (action === 'select') {
const res = await mgr.selectLanguage({
locale: body?.locale,
depth: body?.depth,
});
await Promise.resolve(onChanged?.()).catch(() => {});
return {
status: 200,
payload: {
ok: true,
downloaded: Boolean(res.downloaded),
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'set_depth') {
mgr.setDepth(body?.depth);
await Promise.resolve(onChanged?.()).catch(() => {});
return {
status: 200,
payload: {
ok: true,
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'install' || action === 'update') {
const res = await mgr.installPack(body?.locale, { forceManifestRefresh: true });
const cur = mgr.loadState();
if (cur.locale === res.locale) {
await Promise.resolve(onChanged?.()).catch(() => {});
}
return {
status: 200,
payload: {
ok: true,
installed: res,
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'remove') {
const res = mgr.removePack(body?.locale);
await Promise.resolve(onChanged?.()).catch(() => {});
return {
status: res.ok ? 200 : 400,
payload: {
ok: res.ok,
...(res.error ? { error: res.error } : {}),
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
if (action === 'collect_untranslated') {
if (typeof collectFromTargets !== 'function') {
return {
status: 400,
payload: { ok: false, error: 'collector_unavailable', count: 0, items: [], template: { base: {} } },
};
}
const collected = await collectFromTargets();
const items = Array.isArray(collected?.items) ? collected.items : [];
const templateBase = {};
for (const item of items) {
if (item?.text) templateBase[item.text] = '';
}
return {
status: 200,
payload: {
ok: true,
targets: Number(collected?.targets || 0),
count: items.length,
items,
template: { base: templateBase },
},
};
}
return {
status: 400,
payload: { ok: false, error: `Unknown host-i18n action: ${action || '(empty)'}` },
};
} catch (err) {
return {
status: 500,
payload: {
ok: false,
error: err?.message || 'Host I18n action failed',
...mgr.getStatusSnapshot({ bridgeStatus }),
},
};
}
}
@@ -0,0 +1,799 @@
/**
* @fileoverview 独立解耦的 Antigravity 宿主语言包状态、远端清单同步、SHA-256 校验与本地缓存管理器。
*
* 持久化边界:
* 全部落盘在 `DATA_DIR/host-i18n/` 下,与主插件 `settings.json` 及监控遥测状态完全隔离:
* - `state.json` :当前选中的 `locale`(`'off'` 或 BCP-47)与 `depth`(`'light' | 'deep'`)
* - `manifest-cache.json` :远端仓库可用语言包清单缓存
* - `installed-meta.json` :已下载语言包元信息索引
* - `packs/<locale>.json` :通过 SHA-256 校验后的单语言分层语言包本体
*/
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
import { join } from 'node:path';
import {
HOST_I18N_DEFAULT_DEPTH,
HOST_I18N_OFF_LOCALE,
HOST_I18N_SCHEMA_VERSION,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../shared/host-i18n-protocol.mjs';
import { DATA_DIR, OFFICIAL_GITHUB_REPO, detectCustomGitForkRepo } from '../config.mjs';
import { writeJsonAtomicSync, writeTextFileAtomicSync } from '../fs-atomic.mjs';
import { isPlainObject } from '../http-helpers.mjs';
import { fetchHostI18nTextWithFallback } from './http-fetch.mjs';
export const DEFAULT_HOST_I18N_REF = 'main';
export const HOST_I18N_MANIFEST_TTL_MS = 6 * 3600 * 1000;
const HOST_I18N_SHA256_RE = /^[a-f0-9]{64}$/i;
const HOST_I18N_ALLOWED_REGEX_FLAGS_RE = /^[i]?$/;
const HOST_I18N_UNSAFE_REGEX_RE = /\([^)]*[+*][^)]*\)[+*{]/;
function hostI18nSha256(text) {
return createHash('sha256').update(String(text || ''), 'utf8').digest('hex');
}
function hostI18nResolveStoragePaths(baseDataDir = DATA_DIR) {
const rootDir = join(baseDataDir, 'host-i18n');
return {
rootDir,
stateFile: join(rootDir, 'state.json'),
manifestCacheFile: join(rootDir, 'manifest-cache.json'),
installedMetaFile: join(rootDir, 'installed-meta.json'),
packsDir: join(rootDir, 'packs'),
};
}
function hostI18nResolveRepoAndRef(options = {}) {
const envRepo = String(process?.env?.USAGE_MONITOR_HOST_I18N_REPO || '').trim();
const repo =
String(options?.repo || '').trim() ||
envRepo ||
detectCustomGitForkRepo() ||
OFFICIAL_GITHUB_REPO;
const envRef = String(process?.env?.USAGE_MONITOR_HOST_I18N_REF || '').trim();
const ref = String(options?.ref || '').trim() || envRef || DEFAULT_HOST_I18N_REF;
const localDir =
String(options?.localSourceDir || '').trim() ||
String(process?.env?.USAGE_MONITOR_HOST_I18N_LOCAL_DIR || '').trim();
return { repo, ref, localDir };
}
/**
* 构建仓库内语言包文件的主/备下载 URL(GitHub Raw 主源 + jsDelivr 镜像兜底)。
*
* @param {string} relPath 如 `'manifest.json'` 或 `'packs/zh-CN.json'`
* @param {{ repo?: string, ref?: string }} [options]
* @returns {string[]}
*/
export function buildHostI18nAssetUrls(relPath, options = {}) {
const cleanRel = String(relPath || '')
.replace(/\\/g, '/')
.replace(/^\/+/, '');
if (!cleanRel || cleanRel.includes('..')) {
throw new Error(`Invalid host-i18n relative asset path: ${relPath}`);
}
const { repo, ref } = hostI18nResolveRepoAndRef(options);
return [
`https://raw.githubusercontent.com/${repo}/${ref}/host-i18n/dist/${cleanRel}`,
`https://cdn.jsdelivr.net/gh/${repo}@${ref}/host-i18n/dist/${cleanRel}`,
];
}
function sanitizeHostI18nExactMap(rawMap) {
const out = {};
if (!isPlainObject(rawMap)) return out;
for (const [k, v] of Object.entries(rawMap)) {
const key = String(k || '').replace(/\r\n/g, '\n').trim();
const val = typeof v === 'string' ? v.replace(/\r\n/g, '\n').trim() : '';
if (!key || !val || key.length > 1000 || val.length > 1500) continue;
out[key] = val;
}
return out;
}
function sanitizeHostI18nPatterns(rawList) {
const out = [];
if (!Array.isArray(rawList)) return out;
for (const item of rawList) {
if (!isPlainObject(item)) continue;
const source = typeof item.source === 'string' ? item.source : '';
const flags = typeof item.flags === 'string' ? item.flags : '';
const replace = typeof item.replace === 'string' ? item.replace : '';
const hint = typeof item.hint === 'string' ? item.hint.trim() : '';
if (!source || source.length > 360 || !source.startsWith('^') || !source.endsWith('$')) {
continue;
}
if (!HOST_I18N_ALLOWED_REGEX_FLAGS_RE.test(flags) || HOST_I18N_UNSAFE_REGEX_RE.test(source)) {
continue;
}
if (!replace || replace.length > 800) continue;
try {
// 校验正则可合法编译
// eslint-disable-next-line no-new
new RegExp(source, flags);
} catch {
continue;
}
out.push(hint ? { source, flags, replace, hint } : { source, flags, replace });
}
return out;
}
/**
* 校验并规范化远端或本地的 `manifest.json` 载荷。
*
* @param {unknown} raw
* @returns {{ schemaVersion: number, packs: Array<object> }}
*/
export function sanitizeHostI18nManifest(raw) {
if (!isPlainObject(raw)) {
throw new Error('Invalid host-i18n manifest payload');
}
const schemaVersion = Number(raw.schemaVersion || 0);
if (schemaVersion !== HOST_I18N_SCHEMA_VERSION) {
throw new Error(`Unsupported host-i18n manifest schemaVersion: ${schemaVersion}`);
}
const rawPacks = Array.isArray(raw.packs) ? raw.packs : [];
const packs = [];
const seen = new Set();
for (const item of rawPacks) {
if (!isPlainObject(item)) continue;
const locale = normalizeHostI18nLocale(item.locale);
if (locale === HOST_I18N_OFF_LOCALE || seen.has(locale)) continue;
const sha256 = String(item.sha256 || '').trim().toLowerCase();
const version = String(item.version || '').trim();
const file = String(item.file || `packs/${locale}.json`)
.replace(/\\/g, '/')
.replace(/^\/+/, '');
if (!HOST_I18N_SHA256_RE.test(sha256) || !version || file.includes('..') || !file.endsWith('.json')) {
continue;
}
seen.add(locale);
packs.push({
locale,
name: String(item.name || locale).trim(),
nativeName: String(item.nativeName || item.name || locale).trim(),
version,
file,
sha256,
bytes: Math.max(0, Number(item.bytes || 0) || 0),
depths: Array.isArray(item.depths)
? item.depths.map((d) => normalizeHostI18nDepth(d)).filter((v, i, a) => a.indexOf(v) === i)
: ['light', 'deep'],
stats: isPlainObject(item.stats)
? {
baseExact: Number(item.stats.baseExact || 0) || 0,
lightExact: Number(item.stats.lightExact || 0) || 0,
deepExact: Number(item.stats.deepExact || 0) || 0,
basePatterns: Number(item.stats.basePatterns || 0) || 0,
lightPatterns: Number(item.stats.lightPatterns || 0) || 0,
deepPatterns: Number(item.stats.deepPatterns || 0) || 0,
}
: null,
});
}
return { schemaVersion, packs };
}
/**
* 校验并规范化单个语言包 JSON 内容。
*
* @param {unknown} raw
* @param {string} expectedLocale
*/
export function sanitizeHostI18nPack(raw, expectedLocale = '') {
if (!isPlainObject(raw)) {
throw new Error('Invalid host-i18n pack payload');
}
const schemaVersion = Number(raw.schemaVersion || 0);
if (schemaVersion !== HOST_I18N_SCHEMA_VERSION) {
throw new Error(`Unsupported host-i18n pack schemaVersion: ${schemaVersion}`);
}
const locale = normalizeHostI18nLocale(raw.locale);
if (locale === HOST_I18N_OFF_LOCALE) {
throw new Error('Invalid locale in host-i18n pack');
}
if (expectedLocale && locale !== normalizeHostI18nLocale(expectedLocale)) {
throw new Error(`Pack locale mismatch: expected ${expectedLocale}, got ${locale}`);
}
const version = String(raw.version || '').trim();
if (!version) {
throw new Error('Missing version in host-i18n pack');
}
const baseExact = sanitizeHostI18nExactMap(raw.base?.exact);
const basePatterns = sanitizeHostI18nPatterns(raw.base?.patterns);
const lightExact = sanitizeHostI18nExactMap(raw.modes?.light?.exact);
const lightPatterns = sanitizeHostI18nPatterns(raw.modes?.light?.patterns);
const deepExact = sanitizeHostI18nExactMap(raw.modes?.deep?.exact);
const deepPatterns = sanitizeHostI18nPatterns(raw.modes?.deep?.patterns);
return {
schemaVersion,
locale,
name: String(raw.name || locale).trim(),
nativeName: String(raw.nativeName || raw.name || locale).trim(),
version,
base: { exact: baseExact, patterns: basePatterns },
modes: {
light: { exact: lightExact, patterns: lightPatterns },
deep: { exact: deepExact, patterns: deepPatterns },
},
};
}
function hostI18nPatternSpecificityScore(source) {
const s = String(source || '');
let literalChars = 0;
let parenDepth = 0;
let inCharClass = false;
for (let i = 0; i < s.length; i += 1) {
const ch = s[i];
if (ch === '\\' && i + 1 < s.length) {
const next = s[i + 1];
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
literalChars += 1;
}
i += 1;
continue;
}
if (ch === '[' && !inCharClass) {
inCharClass = true;
continue;
}
if (ch === ']' && inCharClass) {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(') {
parenDepth += 1;
continue;
}
if (ch === ')') {
if (parenDepth > 0) parenDepth -= 1;
continue;
}
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
literalChars += 1;
}
}
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
const typedCaptures = (s.match(/\\d\+/g) || []).length;
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
}
/**
* 根据语言包与深/浅档位合成运行期单层查找载荷。
*
* @param {object} pack
* @param {'light'|'deep'} depth
* @param {string} sha256
*/
export function compileHostI18nRuntimePayload(pack, depth, sha256 = '') {
const safeDepth = normalizeHostI18nDepth(depth);
const modeBucket = safeDepth === 'deep' ? pack?.modes?.deep : pack?.modes?.light;
const exact = {
...(pack?.base?.exact || {}),
...(modeBucket?.exact || {}),
};
const taggedPatterns = [
...(Array.isArray(pack?.base?.patterns)
? pack.base.patterns.map((rule) => ({ rule, tierRank: 0 }))
: []),
...(Array.isArray(modeBucket?.patterns)
? modeBucket.patterns.map((rule) => ({ rule, tierRank: 1 }))
: []),
];
taggedPatterns.sort((a, b) => {
const scoreDiff =
hostI18nPatternSpecificityScore(b.rule?.source) -
hostI18nPatternSpecificityScore(a.rule?.source);
if (scoreDiff !== 0) return scoreDiff;
if (b.tierRank !== a.tierRank) return b.tierRank - a.tierRank;
return String(b.rule?.source || '').length - String(a.rule?.source || '').length;
});
const patterns = taggedPatterns.map((entry) => entry.rule);
const hashTag = String(sha256 || hostI18nSha256(JSON.stringify(exact))).slice(0, 12);
return {
locale: pack.locale,
depth: safeDepth,
version: pack.version,
revision: `${pack.locale}:${safeDepth}:${pack.version}:${hashTag}`,
exact,
patterns,
};
}
/**
* 创建独立的 Host I18n 包与状态管理器实例(可注入 `dataDir` / `fetchImpl` 便于隔离测试)。
*
* @param {{
* dataDir?: string,
* repo?: string,
* ref?: string,
* localSourceDir?: string,
* fetchImpl?: Function|null,
* timeoutMs?: number,
* }} [options]
*/
export function createHostI18nPackManager(options = {}) {
const paths = hostI18nResolveStoragePaths(options.dataDir || DATA_DIR);
const inFlightDownloads = new Map();
let inFlightManifest = null;
let cachedState = null;
let cachedStateMtimeMs = -1;
let cachedInstalledMeta = null;
let cachedInstalledMetaMtimeMs = -1;
const cachedPacks = new Map(); // locale -> { mtimeMs, sha256, pack }
let cachedCompiledRuntime = null; // { revision, payload }
function readMtimeMs(filePath) {
try {
const st = statSync(filePath, { throwIfNoEntry: false });
return st ? Number(st.mtimeMs || 0) : -1;
} catch {
return -1;
}
}
function readJsonFileSafe(filePath, fallback) {
if (!existsSync(filePath)) return fallback;
try {
return JSON.parse(readFileSync(filePath, 'utf8'));
} catch {
return fallback;
}
}
function loadState() {
const mtimeMs = readMtimeMs(paths.stateFile);
if (mtimeMs < 0) {
cachedState = {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale: HOST_I18N_OFF_LOCALE,
depth: HOST_I18N_DEFAULT_DEPTH,
updatedAtMs: 0,
};
cachedStateMtimeMs = -1;
return { ...cachedState };
}
if (cachedState && cachedStateMtimeMs === mtimeMs) {
return { ...cachedState };
}
const raw = readJsonFileSafe(paths.stateFile, {});
cachedState = {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale: normalizeHostI18nLocale(raw?.locale),
depth: normalizeHostI18nDepth(raw?.depth),
updatedAtMs: Number(raw?.updatedAtMs || 0) || 0,
};
cachedStateMtimeMs = mtimeMs;
return { ...cachedState };
}
function saveState(nextPartial) {
const prev = loadState();
const next = {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale:
nextPartial?.locale !== undefined
? normalizeHostI18nLocale(nextPartial.locale)
: prev.locale,
depth:
nextPartial?.depth !== undefined
? normalizeHostI18nDepth(nextPartial.depth)
: prev.depth,
updatedAtMs: Date.now(),
};
mkdirSync(paths.rootDir, { recursive: true });
writeJsonAtomicSync(paths.stateFile, next);
cachedState = next;
cachedStateMtimeMs = readMtimeMs(paths.stateFile);
return { ...next };
}
function loadInstalledMeta() {
const mtimeMs = readMtimeMs(paths.installedMetaFile);
if (mtimeMs < 0) {
cachedInstalledMeta = {};
cachedInstalledMetaMtimeMs = -1;
return {};
}
if (cachedInstalledMeta && cachedInstalledMetaMtimeMs === mtimeMs) {
return { ...cachedInstalledMeta };
}
const raw = readJsonFileSafe(paths.installedMetaFile, {});
const clean = {};
if (isPlainObject(raw)) {
for (const [k, v] of Object.entries(raw)) {
const loc = normalizeHostI18nLocale(k);
if (loc === HOST_I18N_OFF_LOCALE || !isPlainObject(v)) continue;
clean[loc] = {
locale: loc,
name: String(v.name || loc),
nativeName: String(v.nativeName || v.name || loc),
version: String(v.version || ''),
sha256: String(v.sha256 || '').toLowerCase(),
bytes: Number(v.bytes || 0) || 0,
downloadedAtMs: Number(v.downloadedAtMs || 0) || 0,
source: String(v.source || ''),
};
}
}
cachedInstalledMeta = clean;
cachedInstalledMetaMtimeMs = mtimeMs;
return { ...clean };
}
function saveInstalledMeta(metaObj) {
mkdirSync(paths.rootDir, { recursive: true });
writeJsonAtomicSync(paths.installedMetaFile, metaObj);
cachedInstalledMeta = { ...metaObj };
cachedInstalledMetaMtimeMs = readMtimeMs(paths.installedMetaFile);
}
function getPackFilePath(locale) {
const clean = normalizeHostI18nLocale(locale);
if (clean === HOST_I18N_OFF_LOCALE) return '';
return join(paths.packsDir, `${clean}.json`);
}
function loadInstalledPack(locale) {
const clean = normalizeHostI18nLocale(locale);
if (clean === HOST_I18N_OFF_LOCALE) return null;
const filePath = getPackFilePath(clean);
const mtimeMs = readMtimeMs(filePath);
if (mtimeMs < 0) {
cachedPacks.delete(clean);
return null;
}
const memo = cachedPacks.get(clean);
if (memo && memo.mtimeMs === mtimeMs) {
return memo;
}
try {
const rawText = readFileSync(filePath, 'utf8');
const sha256 = hostI18nSha256(rawText);
const pack = sanitizeHostI18nPack(JSON.parse(rawText), clean);
const rec = { mtimeMs, sha256, pack, bytes: Buffer.byteLength(rawText, 'utf8') };
cachedPacks.set(clean, rec);
return rec;
} catch {
cachedPacks.delete(clean);
return null;
}
}
function loadCachedManifest() {
const raw = readJsonFileSafe(paths.manifestCacheFile, null);
if (!isPlainObject(raw)) return null;
try {
const clean = sanitizeHostI18nManifest(raw.manifest || raw);
return {
manifest: clean,
fetchedAtMs: Number(raw.fetchedAtMs || 0) || 0,
source: String(raw.source || ''),
lastError: raw.lastError ? String(raw.lastError) : null,
};
} catch {
return null;
}
}
async function fetchAssetText(relPath) {
const resolved = hostI18nResolveRepoAndRef(options);
if (resolved.localDir) {
const localPath = join(resolved.localDir, relPath);
if (!existsSync(localPath)) {
throw new Error(`Local host-i18n file not found: ${localPath}`);
}
return {
text: readFileSync(localPath, 'utf8'),
url: `local:${localPath}`,
status: 200,
};
}
if (!options.fetchImpl && String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid') {
throw new Error('Remote host-i18n fetch disabled in test.invalid environment');
}
const urls = buildHostI18nAssetUrls(relPath, resolved);
return fetchHostI18nTextWithFallback(urls, {
fetchImpl: options.fetchImpl || null,
timeoutMs: options.timeoutMs,
});
}
async function refreshManifest({ force = false } = {}) {
const cached = loadCachedManifest();
const now = Date.now();
if (!force && cached && now - cached.fetchedAtMs < HOST_I18N_MANIFEST_TTL_MS) {
return { ok: true, fromCache: true, ...cached };
}
if (inFlightManifest) return inFlightManifest;
inFlightManifest = (async () => {
try {
const res = await fetchAssetText('manifest.json');
const manifest = sanitizeHostI18nManifest(JSON.parse(res.text));
const record = {
manifest,
fetchedAtMs: Date.now(),
source: res.url,
lastError: null,
};
mkdirSync(paths.rootDir, { recursive: true });
writeJsonAtomicSync(paths.manifestCacheFile, record);
return { ok: true, fromCache: false, ...record };
} catch (err) {
const message = err?.message || 'Failed to fetch host-i18n manifest';
return {
ok: false,
fromCache: Boolean(cached),
manifest: cached?.manifest || { schemaVersion: HOST_I18N_SCHEMA_VERSION, packs: [] },
fetchedAtMs: cached?.fetchedAtMs || 0,
source: cached?.source || '',
error: message,
};
}
})().finally(() => {
inFlightManifest = null;
});
return inFlightManifest;
}
async function installPack(rawLocale, { forceManifestRefresh = false } = {}) {
const locale = normalizeHostI18nLocale(rawLocale);
if (locale === HOST_I18N_OFF_LOCALE) {
throw new Error('Cannot install pack for "off" locale');
}
if (inFlightDownloads.has(locale)) {
return inFlightDownloads.get(locale);
}
const task = (async () => {
const manifestRes = await refreshManifest({ force: forceManifestRefresh });
let entry = manifestRes.manifest?.packs?.find((p) => p.locale === locale) || null;
if (!entry && !forceManifestRefresh) {
const refreshed = await refreshManifest({ force: true });
entry = refreshed.manifest?.packs?.find((p) => p.locale === locale) || null;
}
if (!entry) {
throw new Error(
manifestRes.error
? `Language pack "${locale}" unavailable: ${manifestRes.error}`
: `Language pack "${locale}" not found in repository manifest`
);
}
const res = await fetchAssetText(entry.file);
const actualHash = hostI18nSha256(res.text);
if (actualHash !== entry.sha256) {
throw new Error(
`Integrity check failed for "${locale}" (expected ${entry.sha256.slice(0, 12)}, got ${actualHash.slice(0, 12)})`
);
}
const pack = sanitizeHostI18nPack(JSON.parse(res.text), locale);
mkdirSync(paths.packsDir, { recursive: true });
const targetPath = getPackFilePath(locale);
writeTextFileAtomicSync(targetPath, res.text);
const meta = loadInstalledMeta();
meta[locale] = {
locale,
name: pack.name,
nativeName: pack.nativeName,
version: pack.version,
sha256: actualHash,
bytes: Buffer.byteLength(res.text, 'utf8'),
downloadedAtMs: Date.now(),
source: res.url,
};
saveInstalledMeta(meta);
cachedPacks.delete(locale);
if (cachedCompiledRuntime?.payload?.locale === locale) {
cachedCompiledRuntime = null;
}
const loaded = loadInstalledPack(locale);
return {
ok: true,
locale,
version: pack.version,
sha256: actualHash,
bytes: loaded?.bytes || meta[locale].bytes,
source: res.url,
};
})().finally(() => {
inFlightDownloads.delete(locale);
});
inFlightDownloads.set(locale, task);
return task;
}
async function selectLanguage({ locale: rawLocale, depth: rawDepth } = {}) {
const locale = normalizeHostI18nLocale(rawLocale);
const current = loadState();
const depth =
rawDepth !== undefined ? normalizeHostI18nDepth(rawDepth) : current.depth;
if (locale === HOST_I18N_OFF_LOCALE) {
const nextState = saveState({ locale: HOST_I18N_OFF_LOCALE, depth });
return { ok: true, downloaded: false, state: nextState };
}
let downloaded = false;
let loaded = loadInstalledPack(locale);
if (!loaded) {
await installPack(locale, { forceManifestRefresh: false });
downloaded = true;
loaded = loadInstalledPack(locale);
}
if (!loaded) {
throw new Error(`Language pack "${locale}" failed to load after installation`);
}
const nextState = saveState({ locale, depth });
return {
ok: true,
downloaded,
state: nextState,
packVersion: loaded.pack.version,
};
}
function setDepth(rawDepth) {
const depth = normalizeHostI18nDepth(rawDepth);
const nextState = saveState({ depth });
return { ok: true, state: nextState };
}
function removePack(rawLocale) {
const locale = normalizeHostI18nLocale(rawLocale);
if (locale === HOST_I18N_OFF_LOCALE) {
return { ok: false, error: 'Invalid locale' };
}
const targetPath = getPackFilePath(locale);
if (targetPath && existsSync(targetPath)) {
rmSync(targetPath, { force: true });
}
cachedPacks.delete(locale);
if (cachedCompiledRuntime?.payload?.locale === locale) {
cachedCompiledRuntime = null;
}
const meta = loadInstalledMeta();
delete meta[locale];
saveInstalledMeta(meta);
const cur = loadState();
let nextState = cur;
if (cur.locale === locale) {
nextState = saveState({ locale: HOST_I18N_OFF_LOCALE });
}
return { ok: true, removedLocale: locale, state: nextState };
}
function getActiveBridgeDescriptor() {
const st = loadState();
if (st.locale === HOST_I18N_OFF_LOCALE) {
return { active: false, locale: HOST_I18N_OFF_LOCALE, depth: st.depth, revision: '', getPayload: null };
}
const loaded = loadInstalledPack(st.locale);
if (!loaded) {
return { active: false, locale: st.locale, depth: st.depth, revision: '', getPayload: null };
}
const revision = `${loaded.pack.locale}:${st.depth}:${loaded.pack.version}:${loaded.sha256.slice(0, 12)}`;
return {
active: true,
locale: loaded.pack.locale,
depth: st.depth,
version: loaded.pack.version,
revision,
getPayload: () => {
if (cachedCompiledRuntime && cachedCompiledRuntime.revision === revision) {
return cachedCompiledRuntime.payload;
}
const payload = compileHostI18nRuntimePayload(loaded.pack, st.depth, loaded.sha256);
cachedCompiledRuntime = { revision, payload };
return payload;
},
};
}
function getStatusSnapshot({ manifestResult = null, bridgeStatus = null } = {}) {
const state = loadState();
const installedMeta = loadInstalledMeta();
const cachedManifest = manifestResult || loadCachedManifest();
const remotePacks = Array.isArray(cachedManifest?.manifest?.packs)
? cachedManifest.manifest.packs
: [];
const byLocale = new Map();
for (const remote of remotePacks) {
const localPack = loadInstalledPack(remote.locale);
const localInfo = installedMeta[remote.locale] || null;
const installed = Boolean(localPack);
const installedSha = localPack?.sha256 || localInfo?.sha256 || '';
const installedVersion = localPack?.pack?.version || localInfo?.version || '';
byLocale.set(remote.locale, {
locale: remote.locale,
name: remote.name,
nativeName: remote.nativeName,
remoteVersion: remote.version,
remoteSha256: remote.sha256,
remoteBytes: remote.bytes,
depths: remote.depths || ['light', 'deep'],
stats: remote.stats || null,
installed,
installedVersion,
installedBytes: localPack?.bytes || localInfo?.bytes || 0,
downloadedAtMs: localInfo?.downloadedAtMs || 0,
updateAvailable: Boolean(installed && installedSha && installedSha !== remote.sha256),
});
}
// 保留仅在本地存在(离线/自定义)的已安装包条目
for (const [loc, localInfo] of Object.entries(installedMeta)) {
if (byLocale.has(loc)) continue;
const localPack = loadInstalledPack(loc);
if (!localPack) continue;
byLocale.set(loc, {
locale: loc,
name: localPack.pack.name,
nativeName: localPack.pack.nativeName,
remoteVersion: '',
remoteSha256: '',
remoteBytes: 0,
depths: ['light', 'deep'],
stats: {
baseExact: Object.keys(localPack.pack.base.exact).length,
lightExact: Object.keys(localPack.pack.modes.light.exact).length,
deepExact: Object.keys(localPack.pack.modes.deep.exact).length,
basePatterns: localPack.pack.base.patterns.length,
lightPatterns: localPack.pack.modes.light.patterns.length,
deepPatterns: localPack.pack.modes.deep.patterns.length,
},
installed: true,
installedVersion: localPack.pack.version,
installedBytes: localPack.bytes,
downloadedAtMs: localInfo.downloadedAtMs || 0,
updateAvailable: false,
});
}
const activeDesc = getActiveBridgeDescriptor();
const resolvedRepo = hostI18nResolveRepoAndRef(options);
return {
schemaVersion: HOST_I18N_SCHEMA_VERSION,
locale: state.locale,
depth: state.depth,
active: activeDesc.active,
activeRevision: activeDesc.revision,
updatedAtMs: state.updatedAtMs,
manifestFetchedAtMs: Number(cachedManifest?.fetchedAtMs || 0) || 0,
manifestError: cachedManifest?.error || null,
repo: resolvedRepo.repo,
ref: resolvedRepo.ref,
packs: Array.from(byLocale.values()),
...(bridgeStatus ? { bridgeStatus } : {}),
};
}
return {
paths,
loadState,
saveState,
loadInstalledPack,
refreshManifest,
installPack,
selectLanguage,
setDepth,
removePack,
getActiveBridgeDescriptor,
getStatusSnapshot,
};
}
@@ -0,0 +1,914 @@
/**
* @fileoverview 注入到 Antigravity 渲染进程的无损运行时 DOM 翻译引擎与按需词条采集器。
*
* 工程底线:
* 1. 绝不替换、拆裂或增删 React 托管的任何 DOM 元素,仅原地改写 `Text.nodeValue` 及
* `placeholder` / `title` / `aria-label` / `aria-description` / `aria-placeholder` 属性;
* 2. 通过 `WeakMap` 精确记录每个被改写节点/属性的原文与译文,既支持 `light ↔ deep` /
* `关闭` 秒级无损还原,也能自动识别 React 原地更新的新英文文案并重新翻译;
* 3. 对齐 Antigravity 真实 DOM 结构,严格豁免用户消息正文(`user-message-content`)、
* 代码块、Diff 行、编辑器、终端、可编辑区以及本插件双 Shadow Host,不误伤工具栏按钮;
* 4. 针对数千条精确词条 + 数百条动态模板做 O(1) 精确查表 + 首词桶索引,并经
* `requestAnimationFrame` 分帧合批,杜绝流式输出掉帧。
*/
import { HOST_I18N_GLOBAL_KEY } from '../../shared/host-i18n-protocol.mjs';
/**
* 在宿主页面执行:安装或热更新无损 DOM 翻译器,并续期 18 秒看门狗。
*
* @param {object} payload `{ locale, depth, revision, exact, patterns }`
* @param {string} bootId
* @param {string} [globalKey]
*/
export function applyHostI18nInPage(payload, bootId, globalKey = '__AGUsageMonitorHostI18n') {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { applied: false, reason: 'no_dom' };
}
const root = document.body || document.documentElement;
if (!root) {
return { applied: false, reason: 'no_root' };
}
const WATCHDOG_MS = 18_000;
const FRAME_NODE_BUDGET = 450;
const INITIAL_SCAN_BUDGET = 4000;
const MAX_PENDING_NODES = 4096;
const MAX_MISS_CACHE = 1024;
const MAX_EXACT_LEN = 1000;
const MAX_PATTERN_LEN = 360;
const TRANSLATABLE_ATTRS = [
'placeholder',
'title',
'aria-label',
'aria-description',
'aria-placeholder',
];
const SKIP_TAGS = new Set([
'SCRIPT',
'STYLE',
'NOSCRIPT',
'CODE',
'PRE',
'TEXTAREA',
'SVG',
'MATH',
'KBD',
'SAMP',
'VAR',
'CANVAS',
'VIDEO',
'AUDIO',
'IFRAME',
]);
const SKIP_TESTIDS = new Set([
'user-message-content',
'markdown-code-block-preview',
'markdown-frontmatter',
'automation-instructions-markdown',
'code-gutter',
'code-gutter-diff',
'diff-gutter-strip',
'artifact-pdf-view',
]);
const SKIP_CLASSES = new Set([
'monaco-editor',
'xterm',
'cm-editor',
'ProseMirror',
'markdown-body',
'prose',
'diff-line',
'view-lines',
]);
function isSkippedSelf(el) {
if (!el || el.nodeType !== 1) return false;
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable === true) return true;
const id = el.id;
if (id === 'ag-usage-monitor-capsule' || id === 'ag-usage-monitor-portal') return true;
if (typeof el.hasAttribute === 'function' && el.hasAttribute('data-ag-i18n-ignore')) return true;
if (typeof el.getAttribute === 'function') {
if (el.getAttribute('contenteditable') === 'true') return true;
const tid = el.getAttribute('data-testid');
if (tid && SKIP_TESTIDS.has(tid)) return true;
}
const cls = el.className;
if (typeof cls === 'string' && cls) {
if (cls.indexOf(' ') === -1) {
if (SKIP_CLASSES.has(cls)) return true;
} else {
const parts = cls.split(/\s+/);
for (let i = 0; i < parts.length; i += 1) {
if (SKIP_CLASSES.has(parts[i])) return true;
}
}
}
return false;
}
function isSkippedElement(el) {
let cur = el;
while (cur && cur.nodeType === 1) {
if (isSkippedSelf(cur)) return true;
cur = cur.parentElement || (cur.parentNode && cur.parentNode.nodeType === 1 ? cur.parentNode : null);
}
return false;
}
function hasAsciiLetter(str) {
for (let i = 0; i < str.length; i += 1) {
const code = str.charCodeAt(i);
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) return true;
}
return false;
}
function isAsciiLetterCode(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
function extractFirstWordLower(str) {
const m = str.match(/^[A-Za-z][A-Za-z0-9'-]*/);
return m ? m[0].toLowerCase() : '';
}
function extractLastWordLower(str) {
const m = str.match(/([A-Za-z]{2,})[.)?!'"\u201d\u2019…]*$/);
return m ? m[1].toLowerCase() : '';
}
function extractPatternLeadingWordLower(source) {
// 匹配以 `^Word` 开头的锚定模板(忽略反转义前的普通字母首词)
const m = String(source || '').match(/^\^([A-Za-z]{2,})/);
return m ? m[1].toLowerCase() : '';
}
function isNumericStartPattern(source) {
return /^\^(?:\\d|\(\\d|\\\(|\\\+|, \\\+)/.test(String(source || ''));
}
function extractPatternTrailingWordsLower(source) {
const s = String(source || '');
// 跳过结尾是通配捕获或字符集的模板,仅索引以固定英文词结尾的模板(兼容可选复数 s?)
const plural = s.match(/([A-Za-z]{2,})s\?(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
if (plural) {
const base = plural[1].toLowerCase();
return [base, `${base}s`];
}
const exact = s.match(/(?:^|[\s(\\/-])([A-Za-z]{2,})(?:\\\)|\\\.|\?|!|"|'|…)*\$$/);
if (exact) {
return [exact[1].toLowerCase()];
}
return [];
}
function computePatternSpecificity(source) {
const s = String(source || '');
let literalChars = 0;
let parenDepth = 0;
let inCharClass = false;
for (let i = 0; i < s.length; i += 1) {
const ch = s[i];
if (ch === '\\' && i + 1 < s.length) {
const next = s[i + 1];
if (parenDepth === 0 && !inCharClass && !/[dDwWsSbB]/.test(next)) {
literalChars += 1;
}
i += 1;
continue;
}
if (ch === '[' && !inCharClass) {
inCharClass = true;
continue;
}
if (ch === ']' && inCharClass) {
inCharClass = false;
continue;
}
if (inCharClass) continue;
if (ch === '(') {
parenDepth += 1;
continue;
}
if (ch === ')') {
if (parenDepth > 0) parenDepth -= 1;
continue;
}
if (parenDepth === 0 && !'^$.*+?{}|'.includes(ch)) {
literalChars += 1;
}
}
const looseWildcards = (s.match(/\(\.\+\?\)|\(\.\*\?\)/g) || []).length;
const typedCaptures = (s.match(/\\d\+/g) || []).length;
return literalChars * 4 + typedCaptures * 3 - looseWildcards * 6;
}
function compileMatchers(rawPayload) {
const exactMap = new Map();
const exactLowerMap = new Map();
const rawExact = rawPayload?.exact;
if (rawExact && typeof rawExact === 'object') {
for (const [k, v] of Object.entries(rawExact)) {
if (typeof v !== 'string' || !v) continue;
exactMap.set(k, v);
if (k.length <= 80) {
const lowerK = k.toLowerCase();
if (!exactLowerMap.has(lowerK)) {
exactLowerMap.set(lowerK, v);
}
}
}
}
const prefixBuckets = new Map();
const suffixBuckets = new Map();
const numericFallbacks = [];
const fallbackPatterns = [];
const rawPatterns = Array.isArray(rawPayload?.patterns) ? rawPayload.patterns : [];
for (let i = 0; i < rawPatterns.length; i += 1) {
const item = rawPatterns[i];
if (!item || typeof item.source !== 'string' || typeof item.replace !== 'string') continue;
try {
const compiled = {
re: new RegExp(item.source, typeof item.flags === 'string' ? item.flags : ''),
replace: item.replace,
hintLower: typeof item.hint === 'string' ? item.hint.toLowerCase() : '',
specificity: computePatternSpecificity(item.source),
sourceLen: item.source.length,
order: i,
};
const leadWord = extractPatternLeadingWordLower(item.source);
if (leadWord) {
let bucket = prefixBuckets.get(leadWord);
if (!bucket) {
bucket = [];
prefixBuckets.set(leadWord, bucket);
}
bucket.push(compiled);
} else if (isNumericStartPattern(item.source)) {
numericFallbacks.push(compiled);
} else {
const tailWords = extractPatternTrailingWordsLower(item.source);
if (tailWords.length > 0) {
for (let t = 0; t < tailWords.length; t += 1) {
const tw = tailWords[t];
let sBucket = suffixBuckets.get(tw);
if (!sBucket) {
sBucket = [];
suffixBuckets.set(tw, sBucket);
}
sBucket.push(compiled);
}
} else {
fallbackPatterns.push(compiled);
}
}
} catch {
// 忽略单条非法正则
}
}
const sortBySpecificity = (a, b) =>
b.specificity - a.specificity || b.sourceLen - a.sourceLen || a.order - b.order;
for (const bucket of prefixBuckets.values()) {
if (bucket.length > 1) bucket.sort(sortBySpecificity);
}
for (const bucket of suffixBuckets.values()) {
if (bucket.length > 1) bucket.sort(sortBySpecificity);
}
if (numericFallbacks.length > 1) numericFallbacks.sort(sortBySpecificity);
if (fallbackPatterns.length > 1) fallbackPatterns.sort(sortBySpecificity);
return {
exactMap,
exactLowerMap,
prefixBuckets,
suffixBuckets,
numericFallbacks,
fallbackPatterns,
missCache: new Set(),
};
}
function runPatternList(trimmed, lowerRef, list) {
if (!list || list.length === 0) return undefined;
for (let i = 0; i < list.length; i += 1) {
const pat = list[i];
if (pat.hintLower) {
if (lowerRef.value === null) lowerRef.value = trimmed.toLowerCase();
if (!lowerRef.value.includes(pat.hintLower)) continue;
}
if (pat.re.test(trimmed)) {
const next = trimmed.replace(pat.re, pat.replace);
if (next && next !== trimmed) return next;
}
}
return undefined;
}
function translateTextWithMatchers(rawText, matchers) {
if (typeof rawText !== 'string' || !rawText || rawText.length > MAX_EXACT_LEN) return null;
const normalizedRaw = rawText.includes('\r') ? rawText.replace(/\r\n/g, '\n') : rawText;
const trimmed = normalizedRaw.trim();
if (!trimmed || trimmed.length > MAX_EXACT_LEN) return null;
if (trimmed.length <= 160 && matchers.missCache.has(trimmed)) return null;
let translatedCore = matchers.exactMap.get(trimmed);
const hasLetter = translatedCore === undefined ? hasAsciiLetter(trimmed) : false;
let lowerRef = { value: null };
if (translatedCore === undefined && trimmed.length <= 80 && hasLetter) {
lowerRef.value = trimmed.toLowerCase();
translatedCore = matchers.exactLowerMap.get(lowerRef.value);
}
if (
translatedCore === undefined &&
trimmed.length <= MAX_PATTERN_LEN &&
!trimmed.includes('\n') &&
hasLetter
) {
const firstCode = trimmed.charCodeAt(0);
if (isAsciiLetterCode(firstCode)) {
const leadWord = extractFirstWordLower(trimmed);
if (leadWord) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.prefixBuckets.get(leadWord));
}
} else if (matchers.numericFallbacks.length > 0) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.numericFallbacks);
}
if (translatedCore === undefined) {
const tailWord = extractLastWordLower(trimmed);
if (tailWord) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.suffixBuckets.get(tailWord));
}
}
if (translatedCore === undefined && matchers.fallbackPatterns.length > 0) {
translatedCore = runPatternList(trimmed, lowerRef, matchers.fallbackPatterns);
}
}
if (translatedCore === undefined || translatedCore === trimmed) {
if (trimmed.length <= 160) {
if (matchers.missCache.size >= MAX_MISS_CACHE) {
matchers.missCache.clear();
}
matchers.missCache.add(trimmed);
}
return null;
}
const startIdx = normalizedRaw.indexOf(trimmed);
const leading = startIdx > 0 ? normalizedRaw.slice(0, startIdx) : '';
const trailing =
startIdx + trimmed.length < normalizedRaw.length
? normalizedRaw.slice(startIdx + trimmed.length)
: '';
return leading + translatedCore + trailing;
}
let state = window[globalKey];
function restoreSubtree(scanRoot, targetState) {
if (!scanRoot) return;
if (typeof document.createTreeWalker === 'function') {
const textWalker = document.createTreeWalker(scanRoot, 4);
let node = textWalker.nextNode();
while (node) {
const rec = targetState.textRecords.get(node);
if (rec) {
if (node.nodeValue === rec.translated) {
node.nodeValue = rec.orig;
}
targetState.textRecords.delete(node);
}
node = textWalker.nextNode();
}
const elWalker = document.createTreeWalker(scanRoot, 1);
let el = elWalker.nextNode();
while (el) {
const attrMap = targetState.attrRecords.get(el);
if (attrMap) {
for (const [attrName, rec] of attrMap.entries()) {
if (el.getAttribute(attrName) === rec.translated) {
el.setAttribute(attrName, rec.orig);
}
}
targetState.attrRecords.delete(el);
}
if (el.shadowRoot && el.id !== 'ag-usage-monitor-capsule' && el.id !== 'ag-usage-monitor-portal') {
restoreSubtree(el.shadowRoot, targetState);
}
el = elWalker.nextNode();
}
} else {
const walkFallback = (cur) => {
if (!cur) return;
if (cur.nodeType === 3) {
const rec = targetState.textRecords.get(cur);
if (rec) {
if (cur.nodeValue === rec.translated) cur.nodeValue = rec.orig;
targetState.textRecords.delete(cur);
}
return;
}
if (cur.nodeType === 1 || cur.nodeType === 11) {
if (cur.nodeType === 1) {
const attrMap = targetState.attrRecords.get(cur);
if (attrMap) {
for (const [attrName, rec] of attrMap.entries()) {
if (cur.getAttribute?.(attrName) === rec.translated) {
cur.setAttribute(attrName, rec.orig);
}
}
targetState.attrRecords.delete(cur);
}
if (cur.shadowRoot && cur.id !== 'ag-usage-monitor-capsule' && cur.id !== 'ag-usage-monitor-portal') {
walkFallback(cur.shadowRoot);
}
}
const children = cur.childNodes || [];
for (let i = 0; i < children.length; i += 1) {
walkFallback(children[i]);
}
}
};
walkFallback(scanRoot);
}
}
function restoreAllTracked(targetState) {
if (!targetState) return;
targetState.isMutating = true;
try {
const scanRoot = document.body || document.documentElement;
restoreSubtree(scanRoot, targetState);
} finally {
targetState.isMutating = false;
}
}
if (state && state.bootId !== bootId) {
state.dispose?.();
state = null;
}
if (!state) {
const scheduleFrame =
typeof window.requestAnimationFrame === 'function'
? (cb) => ({ kind: 'raf', id: window.requestAnimationFrame(cb) })
: (cb) => ({ kind: 'timer', id: setTimeout(cb, 16) });
const cancelFrame = (handle) => {
if (!handle) return;
if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function') {
window.cancelAnimationFrame(handle.id);
} else {
clearTimeout(handle.id);
}
};
state = {
bootId,
revision: '',
locale: '',
depth: '',
matchers: {
exactMap: new Map(),
exactLowerMap: new Map(),
prefixBuckets: new Map(),
suffixBuckets: new Map(),
numericFallbacks: [],
fallbackPatterns: [],
missCache: new Set(),
},
textRecords: new WeakMap(),
attrRecords: new WeakMap(),
pendingNodes: new Set(),
fullRescanPending: false,
frameHandle: null,
watchdogTimer: null,
observer: null,
isMutating: false,
translatedCount: 0,
applyTextNode(node, parentVerifiedSafe = false) {
if (!node || node.nodeType !== 3) return;
if (!parentVerifiedSafe) {
const parent = node.parentElement || node.parentNode;
if (parent && isSkippedElement(parent)) return;
}
const curVal = node.nodeValue;
if (typeof curVal !== 'string' || !curVal) return;
const existing = state.textRecords.get(node);
let origVal = curVal;
if (existing) {
if (curVal === existing.translated) {
return;
}
origVal = curVal;
state.textRecords.delete(node);
}
const nextVal = translateTextWithMatchers(origVal, state.matchers);
if (nextVal !== null && nextVal !== origVal) {
state.textRecords.set(node, { orig: origVal, translated: nextVal });
state.isMutating = true;
try {
node.nodeValue = nextVal;
state.translatedCount += 1;
} finally {
state.isMutating = false;
}
}
},
applyElementAttrs(el, selfVerifiedSafe = false) {
if (!el || el.nodeType !== 1) return;
if (!selfVerifiedSafe && isSkippedElement(el)) return;
if (typeof el.getAttribute !== 'function' || typeof el.setAttribute !== 'function') return;
for (let i = 0; i < TRANSLATABLE_ATTRS.length; i += 1) {
const attrName = TRANSLATABLE_ATTRS[i];
const curVal = el.getAttribute(attrName);
if (!curVal) continue;
let attrMap = state.attrRecords.get(el);
const existing = attrMap?.get(attrName);
let origVal = curVal;
if (existing) {
if (curVal === existing.translated) continue;
origVal = curVal;
attrMap.delete(attrName);
}
const nextVal = translateTextWithMatchers(origVal, state.matchers);
if (nextVal !== null && nextVal !== origVal) {
if (!attrMap) {
attrMap = new Map();
state.attrRecords.set(el, attrMap);
}
attrMap.set(attrName, { orig: origVal, translated: nextVal });
state.isMutating = true;
try {
el.setAttribute(attrName, nextVal);
state.translatedCount += 1;
} finally {
state.isMutating = false;
}
}
}
},
walkSubtree(node, budgetRef, ancestorsVerifiedSafe = false) {
if (!node || budgetRef.remaining <= 0) return false;
if (node.nodeType === 3) {
budgetRef.remaining -= 1;
state.applyTextNode(node, ancestorsVerifiedSafe);
return true;
}
if (node.nodeType !== 1 && node.nodeType !== 11) return true;
if (node.nodeType === 1) {
if (ancestorsVerifiedSafe ? isSkippedSelf(node) : isSkippedElement(node)) return true;
budgetRef.remaining -= 1;
state.applyElementAttrs(node, true);
if (node.shadowRoot && node.id !== 'ag-usage-monitor-capsule' && node.id !== 'ag-usage-monitor-portal') {
state.walkSubtree(node.shadowRoot, budgetRef, true);
}
}
const children = node.childNodes || [];
for (let i = 0; i < children.length; i += 1) {
if (budgetRef.remaining <= 0) {
state.pendingNodes.add(children[i]);
return false;
}
if (!state.walkSubtree(children[i], budgetRef, true)) {
for (let j = i + 1; j < children.length; j += 1) {
state.pendingNodes.add(children[j]);
}
return false;
}
}
return true;
},
flushPending() {
state.frameHandle = null;
if (state.fullRescanPending) {
state.fullRescanPending = false;
state.pendingNodes.clear();
const scanRoot = document.body || document.documentElement;
if (scanRoot) state.pendingNodes.add(scanRoot);
}
const budgetRef = { remaining: FRAME_NODE_BUDGET };
const batch = Array.from(state.pendingNodes);
state.pendingNodes.clear();
for (let i = 0; i < batch.length; i += 1) {
if (budgetRef.remaining <= 0) {
for (let j = i; j < batch.length; j += 1) {
state.pendingNodes.add(batch[j]);
}
break;
}
state.walkSubtree(batch[i], budgetRef, false);
}
if (state.pendingNodes.size > 0 || state.fullRescanPending) {
state.scheduleFlush();
}
},
scheduleFlush() {
if (state.frameHandle) return;
state.frameHandle = scheduleFrame(() => state.flushPending());
},
enqueue(node) {
if (!node) return;
if (state.pendingNodes.size >= MAX_PENDING_NODES) {
state.fullRescanPending = true;
state.pendingNodes.clear();
} else {
state.pendingNodes.add(node);
}
state.scheduleFlush();
},
scanAllNow() {
const scanRoot = document.body || document.documentElement;
if (!scanRoot) return;
const budgetRef = { remaining: INITIAL_SCAN_BUDGET };
state.walkSubtree(scanRoot, budgetRef, true);
if (state.pendingNodes.size > 0) {
state.scheduleFlush();
}
},
touchWatchdog() {
clearTimeout(state.watchdogTimer);
state.watchdogTimer = setTimeout(() => {
state.dispose();
}, WATCHDOG_MS);
},
dispose() {
clearTimeout(state.watchdogTimer);
state.watchdogTimer = null;
cancelFrame(state.frameHandle);
state.frameHandle = null;
try {
state.observer?.disconnect?.();
} catch {
// 忽略断开异常
}
state.observer = null;
state.pendingNodes.clear();
state.fullRescanPending = false;
restoreAllTracked(state);
state.matchers.exactMap.clear();
state.matchers.exactLowerMap.clear();
state.matchers.prefixBuckets.clear();
state.matchers.suffixBuckets.clear();
state.matchers.numericFallbacks.length = 0;
state.matchers.fallbackPatterns.length = 0;
state.matchers.missCache.clear();
if (window[globalKey] === state) {
delete window[globalKey];
}
},
};
if (typeof window.MutationObserver === 'function') {
state.observer = new window.MutationObserver((mutations) => {
if (state.isMutating) return;
for (let i = 0; i < mutations.length; i += 1) {
const m = mutations[i];
if (m.type === 'characterData' || m.type === 'attributes') {
state.enqueue(m.target);
} else if (m.type === 'childList') {
const added = m.addedNodes || [];
for (let j = 0; j < added.length; j += 1) {
state.enqueue(added[j]);
}
}
}
});
state.observer.observe(root, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: TRANSLATABLE_ATTRS,
});
}
window[globalKey] = state;
}
state.touchWatchdog();
const nextRevision = String(payload?.revision || '');
if (state.revision !== nextRevision) {
if (state.revision) {
restoreAllTracked(state);
}
state.revision = nextRevision;
state.locale = String(payload?.locale || '');
state.depth = String(payload?.depth || '');
state.matchers = compileMatchers(payload);
state.translatedCount = 0;
state.scanAllNow();
}
return {
applied: true,
revision: state.revision,
locale: state.locale,
depth: state.depth,
translatedCount: state.translatedCount,
};
}
/**
* 轻量心跳表达式:若当前页面已加载同一 `bootId` 且同 `revision`,直接续期看门狗,无需重传大词表。
*/
export function createHostI18nHeartbeatExpression(bootId, revision) {
return `(() => {
try {
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
if (!st || st.bootId !== ${JSON.stringify(bootId)} || st.revision !== ${JSON.stringify(revision)}) {
return { alive: false, needsApply: true };
}
st.touchWatchdog?.();
return { alive: true, needsApply: false, revision: st.revision, translatedCount: Number(st.translatedCount || 0) };
} catch {
return { alive: false, needsApply: true };
}
})()`;
}
/**
* 生成完整注入/切换词表表达式。
*/
export function createHostI18nApplyExpression(payload, bootId) {
return `(${applyHostI18nInPage.toString()})(${JSON.stringify(payload)}, ${JSON.stringify(bootId)}, ${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
}
/**
* 生成停止翻译并无损还原原文的清理表达式。
*/
export function createHostI18nDisposeExpression() {
return `(() => {
try {
const st = typeof window !== 'undefined' ? window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}] : null;
if (!st) return { disposed: false };
st.dispose?.();
return { disposed: true };
} catch {
return { disposed: false };
}
})()`;
}
/**
* 在宿主页面按需执行:只读采集当前可见 UI 控件与说明中尚未翻译的英文短语
* (严格排除聊天用户正文、代码块、Diff、编辑器与隐私路径)。
*/
export function collectUntranslatedHostUiInPage(globalKey = '__AGUsageMonitorHostI18n') {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { count: 0, items: [] };
}
const root = document.body || document.documentElement;
if (!root) return { count: 0, items: [] };
const activeState = window[globalKey] || null;
const SKIP_TAGS = new Set([
'SCRIPT',
'STYLE',
'NOSCRIPT',
'CODE',
'PRE',
'TEXTAREA',
'SVG',
'MATH',
'KBD',
'SAMP',
'VAR',
'CANVAS',
'VIDEO',
'AUDIO',
'IFRAME',
]);
const SKIP_SELECTOR = [
'#ag-usage-monitor-capsule',
'#ag-usage-monitor-portal',
'[data-ag-i18n-ignore]',
'[contenteditable="true"]',
'.monaco-editor',
'.xterm',
'.cm-editor',
'.ProseMirror',
'.markdown-body',
'.prose',
'[data-testid="user-message-content"]',
'[data-testid="markdown-code-block-preview"]',
'[data-testid="markdown-frontmatter"]',
'[data-testid="automation-instructions-markdown"]',
'[data-testid="code-gutter"]',
'[data-testid="code-gutter-diff"]',
'[data-testid="diff-gutter-strip"]',
'[data-testid="artifact-pdf-view"]',
'.diff-line',
'.view-lines',
].join(',');
const UI_CONTROL_SELECTOR = [
'button',
'[role="button"]',
'[role="menuitem"]',
'[role="tab"]',
'[role="option"]',
'[role="switch"]',
'[role="checkbox"]',
'[role="radio"]',
'[role="heading"]',
'[role="tooltip"]',
'[role="status"]',
'label',
'legend',
'caption',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'th',
'dt',
'dd',
'p',
'span',
'nav a',
'[placeholder]',
'[title]',
'[aria-label]',
'[aria-description]',
].join(',');
const NON_LATIN_RE = /[\u3000-\u9fff\uac00-\ud7af\u0400-\u04ff]/;
const NOISE_RE =
/^(?:https?:\/\/|file:\/\/|\/|~\.|[A-Za-z]:\\|[\w.+-]+@[\w.-]+\.[a-z]{2,}$|[0-9a-f]{8}-[0-9a-f]{4}-|v?\d+(?:\.\d+)+$|\/[a-z0-9_-]+$|(?:gemini|claude|gpt|o[134])\b)/i;
function isSkipped(el) {
if (!el || el.nodeType !== 1) return false;
if (SKIP_TAGS.has(el.tagName)) return true;
if (el.isContentEditable === true) return true;
if (el.id === 'ag-usage-monitor-capsule' || el.id === 'ag-usage-monitor-portal') return true;
if (typeof el.closest === 'function') {
try {
if (el.closest(SKIP_SELECTOR)) return true;
} catch {
// 忽略选择器异常
}
}
return false;
}
const counts = new Map();
const kinds = new Map();
function recordCandidate(raw, kind) {
if (typeof raw !== 'string') return;
if (raw.includes('\n') || raw.includes('\r')) return;
const text = raw.trim();
if (text.length < 2 || text.length > 260) return;
if (!/[A-Za-z]{2,}/.test(text)) return;
if (NON_LATIN_RE.test(text)) return;
if (NOISE_RE.test(text)) return;
if (/^[0-9.,:%$+\-*/\s()[\]]+$/.test(text)) return;
if (activeState?.matchers?.exactMap?.has(text)) return;
if (text.length <= 80 && activeState?.matchers?.exactLowerMap?.has(text.toLowerCase())) return;
counts.set(text, (counts.get(text) || 0) + 1);
if (!kinds.has(text)) kinds.set(text, kind);
}
const elements =
typeof root.querySelectorAll === 'function' ? root.querySelectorAll(UI_CONTROL_SELECTOR) : [];
for (let i = 0; i < elements.length; i += 1) {
const el = elements[i];
if (isSkipped(el)) continue;
for (const attrName of ['placeholder', 'title', 'aria-label', 'aria-description']) {
const val = el.getAttribute?.(attrName);
const attrMap = activeState?.attrRecords?.get(el);
if (val && !(attrMap && attrMap.has(attrName))) {
recordCandidate(val, attrName);
}
}
const children = el.childNodes || [];
for (let j = 0; j < children.length; j += 1) {
const ch = children[j];
if (ch && ch.nodeType === 3) {
if (activeState?.textRecords?.has(ch)) continue;
recordCandidate(ch.nodeValue, 'text');
}
}
}
const items = Array.from(counts.entries())
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
.slice(0, 500)
.map(([text, count]) => ({ text, kind: kinds.get(text) || 'text', count }));
return { count: items.length, items };
}
/**
* 生成按需采集未命中 UI 词条的只读 CDP 表达式。
*/
export function createHostI18nCollectExpression() {
return `(${collectUntranslatedHostUiInPage.toString()})(${JSON.stringify(HOST_I18N_GLOBAL_KEY)})`;
}
@@ -538,6 +538,24 @@ export function createStandaloneWebServer(options = {}) {
);
return;
}
const remoteAddr = String(req.socket?.remoteAddress || '').trim();
const isLoopbackClient =
!remoteAddr ||
remoteAddr === '127.0.0.1' ||
remoteAddr === '::1' ||
remoteAddr === '::ffff:127.0.0.1';
if (pathname === '/api/host-i18n' && method === 'POST' && !isLoopbackClient) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
error: 'Host I18n mutations are only allowed from loopback clients',
})
);
return;
}
let data = undefined;
if (method === 'GET') {
data = Object.fromEntries(urlObj.searchParams.entries());
@@ -559,6 +577,25 @@ export function createStandaloneWebServer(options = {}) {
} else {
data = {};
}
if (
pathname === '/api/settings' &&
data &&
typeof data === 'object' &&
typeof data.__hostI18nAction === 'string' &&
data.__hostI18nAction !== 'get' &&
!isLoopbackClient
) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
error: 'Host I18n mutations are only allowed from loopback clients',
})
);
return;
}
if (
pathname === '/api/settings' &&
data &&
+220 -18
View File
@@ -31,6 +31,7 @@ import {
WINDOW_OVERLAY_KEY,
WINDOW_OVERLAY_METHODS,
} from '../shared/window-bridge-protocol.mjs';
import { HOST_I18N_GLOBAL_KEY } from '../shared/host-i18n-protocol.mjs';
import {
DATA_DIR,
computeRuntimeCodeVersion,
@@ -45,6 +46,13 @@ import {
getContextWindowModels,
resolveContextWindowRules,
} from './context-windows.mjs';
import {
createHostI18nApplyExpression,
createHostI18nCollectExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
getHostI18nBridgeDescriptor,
} from './host-i18n/index.mjs';
import {
ensureDesktopLaunchEntriesConfigured,
resolveDesktopHostExecutable,
@@ -64,6 +72,7 @@ import { getDefaultCloudCodeProxy } from './cloudcode-proxy.mjs';
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
const windowHostI18nRef = `window[${JSON.stringify(HOST_I18N_GLOBAL_KEY)}]`;
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
const windowBridgeEndpointKey = JSON.stringify(WINDOW_BRIDGE_ENDPOINT_KEY);
const overlayMethods = Object.fromEntries(
@@ -1150,6 +1159,10 @@ export function createWindowBridgeController(options) {
cloudCodeProxy = null,
manageCloudCodeProxy = false,
resolveLocalContextRulesFn = null,
getHostI18nDescriptorFn =
options?.env === undefined && options?.homeDir === undefined
? getHostI18nBridgeDescriptor
: () => ({ active: false, revision: '', getPayload: null }),
} = options || {};
const activeCloudCodeProxy =
@@ -1210,6 +1223,10 @@ export function createWindowBridgeController(options) {
};
let hadContextWindows = false;
let contextWindowBootId = `${process.pid}:${Date.now()}`;
let hadHostI18n = false;
let hostI18nBootId = `hi18n:${process.pid}:${Date.now()}`;
let lastHostI18nAppliedCount = 0;
let cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
const cachedBackendCtxModelsByEndpoint = new Map();
const targetClassifyCache = new Map();
let nodeDepsPromise = null;
@@ -1879,10 +1896,21 @@ export function createWindowBridgeController(options) {
const needsMainCdpContext = hasContextWindows && ctxMainEnabled;
const needsCloudCodeProxy = hasContextWindows && ctxSwarmEnabled;
const needsAnyCdpContext = hasContextWindows && (ctxMainEnabled || ctxSwarmEnabled);
const hostI18nDesc =
typeof getHostI18nDescriptorFn === 'function' ? getHostI18nDescriptorFn() : null;
const needsHostI18n = Boolean(
hostI18nDesc?.active &&
hostI18nDesc?.revision &&
typeof hostI18nDesc?.getPayload === 'function'
);
let leasedBySelf = false;
let currentLease = null;
if ((enabled || needsAnyCdpContext || needsCloudCodeProxy) && leaseFilePath && !forceReinject) {
if (
(enabled || needsAnyCdpContext || needsCloudCodeProxy || needsHostI18n) &&
leaseFilePath &&
!forceReinject
) {
const lease = loadJson(leaseFilePath, null);
currentLease = lease;
const leasePid = Number(lease?.pid || 0);
@@ -1951,7 +1979,7 @@ export function createWindowBridgeController(options) {
}
const shouldCheckLaunchers =
(enabled || needsMainCdpContext) &&
(enabled || needsMainCdpContext || needsHostI18n) &&
autoConfigureIdeArgv &&
(lastLauncherProvisionAtMs === 0 ||
Date.now() - lastLauncherProvisionAtMs >= launcherRecheckIntervalMs);
@@ -1966,12 +1994,15 @@ export function createWindowBridgeController(options) {
if (provPending) {
await provPending.catch(() => {});
}
updateBridgeStatus(enabled || needsMainCdpContext ? 'no_devtools_port' : 'disabled', {
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
});
updateBridgeStatus(
enabled || needsMainCdpContext || needsHostI18n ? 'no_devtools_port' : 'disabled',
{
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
}
);
return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 };
}
@@ -1984,12 +2015,15 @@ export function createWindowBridgeController(options) {
if (provPending) {
await provPending.catch(() => {});
}
updateBridgeStatus(enabled || needsMainCdpContext ? 'cdp_unreachable' : 'disabled', {
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
});
updateBridgeStatus(
enabled || needsMainCdpContext || needsHostI18n ? 'cdp_unreachable' : 'disabled',
{
enabled,
leasedBySelf,
bundleVersion,
prevLease: currentLease,
}
);
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
}
@@ -2012,6 +2046,8 @@ export function createWindowBridgeController(options) {
!enabled &&
!needsAnyCdpContext &&
!hadContextWindows &&
!needsHostI18n &&
!hadHostI18n &&
!hadInjectedTargets &&
!hadInjectedChatFrames &&
!forceReinject
@@ -2251,6 +2287,66 @@ export function createWindowBridgeController(options) {
hadContextWindows = needsAnyCdpContext;
}
if (needsHostI18n || hadHostI18n) {
const hostI18nWsUrls = new Set();
for (const target of targets) {
if (target.isIdeWorkbench) continue;
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
if (wsUrl) hostI18nWsUrls.add(wsUrl);
}
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
if (chatUrl) hostI18nWsUrls.add(chatUrl);
}
if (!needsHostI18n) {
const disposeHostI18nExpr = createHostI18nDisposeExpression();
await Promise.allSettled(
Array.from(hostI18nWsUrls).map((wsUrl) => evaluateOnTarget(wsUrl, disposeHostI18nExpr))
);
hadHostI18n = false;
lastHostI18nAppliedCount = 0;
cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
} else {
const heartbeatExpr = createHostI18nHeartbeatExpression(
hostI18nBootId,
hostI18nDesc.revision
);
let appliedTargets = 0;
await Promise.allSettled(
Array.from(hostI18nWsUrls).map(async (wsUrl) => {
try {
const hbRes = await evaluateOnTarget(wsUrl, heartbeatExpr, 1800);
const hbVal = hbRes?.result?.result?.value;
if (hbVal?.alive === true && hbVal?.needsApply === false) {
appliedTargets += 1;
return;
}
} catch {
// 心跳异常时回退完整注入
}
if (
!cachedHostI18nApply.expr ||
cachedHostI18nApply.revision !== hostI18nDesc.revision ||
cachedHostI18nApply.bootId !== hostI18nBootId
) {
const payload = hostI18nDesc.getPayload();
cachedHostI18nApply = {
revision: hostI18nDesc.revision,
bootId: hostI18nBootId,
expr: createHostI18nApplyExpression(payload, hostI18nBootId),
};
}
const applyRes = await evaluateOnTarget(wsUrl, cachedHostI18nApply.expr, 8000);
if (applyRes?.result?.result?.value?.applied) {
appliedTargets += 1;
}
})
);
hadHostI18n = true;
lastHostI18nAppliedCount = appliedTargets;
}
}
const disposeExpr = `(() => {
try {
const existed = Boolean(${windowOverlayRef} || ${windowBridgeRef});
@@ -2784,7 +2880,10 @@ export function createWindowBridgeController(options) {
clearTimeout(pollTimer);
pollTimer = null;
}
if (disposeWindows && (hadInjectedTargets || hadInjectedChatFrames || hadContextWindows)) {
if (
disposeWindows &&
(hadInjectedTargets || hadInjectedChatFrames || hadContextWindows || hadHostI18n)
) {
const prevStopped = stopped;
stopped = false;
try {
@@ -2795,6 +2894,7 @@ export function createWindowBridgeController(options) {
}));
const disposeExpr = `(() => {
try {
${windowHostI18nRef}?.dispose?.();
${windowContextWindowsRef}?.dispose?.();
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
delete ${windowOverlayRef};
@@ -2820,6 +2920,9 @@ export function createWindowBridgeController(options) {
hadInjectedTargets = false;
hadInjectedChatFrames = false;
hadContextWindows = false;
hadHostI18n = false;
lastHostI18nAppliedCount = 0;
cachedHostI18nApply = { revision: '', bootId: '', expr: '' };
if (activeCloudCodeProxy) {
await activeCloudCodeProxy.stop().catch(() => {});
}
@@ -2842,7 +2945,10 @@ export function createWindowBridgeController(options) {
const hasCtx =
Object.keys(cur.modelContextWindows || {}).length > 0 &&
cur.contextWindowMainEnabled !== false;
if (!hasCtx && autoConfigureIdeArgv) {
const hasHostI18n = Boolean(
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
);
if (!hasCtx && !hasHostI18n && autoConfigureIdeArgv) {
launcherConfigured = false;
hasReadOnlyShortcuts = false;
lastLauncherProvisionAtMs = 0;
@@ -2870,9 +2976,12 @@ export function createWindowBridgeController(options) {
const hasCtx =
Object.keys(cur.modelContextWindows || {}).length > 0 &&
cur.contextWindowMainEnabled !== false;
const hasHostI18n = Boolean(
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
);
if (hasCtx) {
lastLauncherProvisionAtMs = 0;
} else if (!overlayOn && autoConfigureIdeArgv) {
} else if (!overlayOn && !hasHostI18n && autoConfigureIdeArgv) {
launcherConfigured = false;
hasReadOnlyShortcuts = false;
lastLauncherProvisionAtMs = 0;
@@ -2889,16 +2998,97 @@ export function createWindowBridgeController(options) {
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
}
function notifyHostI18nChanged() {
const cur = getSettingsFn() || {};
const mountMode = normalizeWindowMountMode(cur.windowMountMode, cur.enableWindowOverlay);
const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar');
const hasCtx =
Object.keys(cur.modelContextWindows || {}).length > 0 &&
cur.contextWindowMainEnabled !== false;
const hasHostI18n = Boolean(
typeof getHostI18nDescriptorFn === 'function' && getHostI18nDescriptorFn()?.active
);
if (hasHostI18n) {
lastLauncherProvisionAtMs = 0;
} else {
hadHostI18n = true;
if (!overlayOn && !hasCtx && autoConfigureIdeArgv) {
launcherConfigured = false;
hasReadOnlyShortcuts = false;
lastLauncherProvisionAtMs = 0;
void ensureDesktopLaunchEntriesConfigured({
enabled: false,
env,
platform,
homeDir,
execFileFn: launcherExecFileFn,
fsOps: launcherFsOps,
allowInTest: allowDesktopLauncherInTest,
}).catch(() => {});
}
}
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
}
async function collectHostI18nUntranslatedFromTargets() {
const cdpPorts = findActiveDevToolsPorts();
if (!cdpPorts.length) {
return { targets: 0, items: [] };
}
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({ targets: [] }));
const wsUrls = new Set();
for (const target of targets) {
if (target.isIdeWorkbench) continue;
const wsUrl = String(target.webSocketDebuggerUrl || '').trim();
if (wsUrl) wsUrls.add(wsUrl);
}
for (const chatUrl of collectAllChatDebuggerUrls(targets)) {
if (chatUrl) wsUrls.add(chatUrl);
}
if (wsUrls.size === 0) {
return { targets: 0, items: [] };
}
const collectExpr = createHostI18nCollectExpression();
const settled = await Promise.allSettled(
Array.from(wsUrls).map((wsUrl) => evaluateOnTarget(wsUrl, collectExpr, 3500))
);
const mergedCounts = new Map();
const mergedKinds = new Map();
let scannedTargets = 0;
for (const res of settled) {
if (res.status !== 'fulfilled') continue;
const val = res.value?.result?.result?.value;
if (!val || !Array.isArray(val.items)) continue;
scannedTargets += 1;
for (const item of val.items) {
const text = String(item?.text || '').trim();
if (!text) continue;
mergedCounts.set(text, (mergedCounts.get(text) || 0) + (Number(item?.count || 1) || 1));
if (!mergedKinds.has(text)) mergedKinds.set(text, String(item?.kind || 'text'));
}
}
const items = Array.from(mergedCounts.entries())
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
.slice(0, 200)
.map(([text, count]) => ({ text, kind: mergedKinds.get(text) || 'text', count }));
return { targets: scannedTargets, items };
}
return {
ensureBridgeServer,
syncAllWindows,
invokeRemoteWindowRpc,
notifySettingChanged,
notifyContextWindowsChanged,
notifyHostI18nChanged,
collectHostI18nUntranslatedFromTargets,
start,
stop,
getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }),
getBridgeStatus: () => ({ ...lastBridgeStatus }),
getBridgeStatus: () => ({
...lastBridgeStatus,
hostI18nAppliedCount: lastHostI18nAppliedCount,
}),
};
}
@@ -2957,3 +3147,15 @@ export function notifyModelContextWindowsChanged() {
if (!defaultBridgeController) return Promise.resolve({ ok: false });
return defaultBridgeController.notifyContextWindowsChanged();
}
export function notifyHostI18nChanged() {
if (!defaultBridgeController) return Promise.resolve({ ok: false });
return defaultBridgeController.notifyHostI18nChanged();
}
export function collectHostI18nUntranslatedFromActiveTargets() {
if (!defaultBridgeController) {
return Promise.resolve({ targets: 0, items: [] });
}
return defaultBridgeController.collectHostI18nUntranslatedFromTargets();
}
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795580198302">
<link rel="stylesheet" href="/styles.css?v=1795581433079">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795580198302"></script>
<script src="/app.js?v=1795581433079"></script>
</body>
</html>
+3
View File
@@ -592,6 +592,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'shared/settings-normalization.mjs',
'shared/telemetry-display-rules.mjs',
'shared/window-bridge-protocol.mjs',
'shared/host-i18n-protocol.mjs',
'src/icons/svgRegistry.js',
'src/icons/SvgIcon.js',
'src/core/reactive.js',
@@ -609,6 +610,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/core/httpClient.js',
'src/store/uiStore.js',
'src/core/fileExportClient.js',
'src/core/hostI18nClient.js',
'src/store/telemetryStore.js',
'src/components/ui/TopLongPillNav.js',
'src/components/ui/SearchInput.js',
@@ -643,6 +645,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/components/settings/ThemeColorPicker.js',
'src/components/settings/BridgeStatusNotice.js',
'src/components/settings/SessionMigrationCard.js',
'src/components/settings/HostI18nCard.js',
'src/views/settings/SettingsGeneralTab.js',
'src/views/settings/SettingsStructureTab.js',
'src/views/settings/SettingsAccountTab.js',
@@ -0,0 +1,58 @@
/**
* @fileoverview Zero-dependency shared protocol constants and normalizers
* for the decoupled Antigravity Host I18n subsystem.
*/
export const HOST_I18N_GLOBAL_KEY = '__AGUsageMonitorHostI18n';
export const HOST_I18N_API_PATH = '/api/host-i18n';
export const HOST_I18N_SCHEMA_VERSION = 1;
export const HOST_I18N_OFF_LOCALE = 'off';
export const HOST_I18N_DEFAULT_DEPTH = 'light';
export const HOST_I18N_DEPTHS = Object.freeze(['light', 'deep']);
export const HOST_I18N_LOCALE_RE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2}$/;
/**
* Normalizes a host translation locale identifier (`'off'` or canonical BCP-47 tag).
*
* @param {unknown} value
* @returns {string}
*/
export function normalizeHostI18nLocale(value) {
const raw = String(value || '').trim();
if (!raw) return HOST_I18N_OFF_LOCALE;
const lower = raw.toLowerCase();
if (
lower === 'off' ||
lower === 'none' ||
lower === 'disabled' ||
lower === 'original' ||
lower === 'default'
) {
return HOST_I18N_OFF_LOCALE;
}
const normalized = raw.replace(/_/g, '-');
if (!HOST_I18N_LOCALE_RE.test(normalized)) {
return HOST_I18N_OFF_LOCALE;
}
const parts = normalized.split('-');
return parts
.map((part, idx) => {
if (idx === 0) return part.toLowerCase();
if (part.length === 2) return part.toUpperCase();
if (part.length === 4) return part[0].toUpperCase() + part.slice(1).toLowerCase();
return part;
})
.join('-');
}
/**
* Normalizes translation depth (`'light'` or `'deep'`).
*
* @param {unknown} value
* @returns {'light'|'deep'}
*/
export function normalizeHostI18nDepth(value) {
const lower = String(value || '').trim().toLowerCase();
if (lower === 'deep' || lower === 'full') return 'deep';
return HOST_I18N_DEFAULT_DEPTH;
}
@@ -45,6 +45,8 @@ export const BRIDGE_API_ROUTE_DEFS = Object.freeze([
method: 'GET',
action: 'quota_reservation_log',
}),
Object.freeze({ path: '/api/host-i18n', method: 'GET', action: 'host_i18n_get' }),
Object.freeze({ path: '/api/host-i18n', method: 'POST', action: 'host_i18n_action' }),
]);
export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path));
@@ -118,7 +118,7 @@ const COMPOSER_MODEL_ATTR_RE =
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
const COMPOSER_MODE_TEXT_RE =
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i;
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|planning|act|review|confirm|normal|fast|自动|询问|始终询问|手动|始终允许|受控|规划|快速)(?:\s*(?:mode|模式))?$/i;
const COMPOSER_MODE_ATTR_RE =
/\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i;
const COMPOSER_ICON_FONT_CLASS_RE =
@@ -0,0 +1,667 @@
/**
* @fileoverview Self-contained Antigravity Host UI Language card (`HostI18nCard.js`).
*
* Mounted inside `SettingsGeneralTab` with minimal glue; manages:
* - Language selection (`off` or any pack listed in repository `manifest.json`),
* - Conditional Light / Deep translation depth switching (0-network hot switch),
* - On-demand repository pack download, update, and local cache removal,
* - CDP bridge notice when DevTools port is unavailable,
* - Optional collapsed developer drawer to collect untranslated UI strings.
*/
import {
HOST_I18N_OFF_LOCALE,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../../shared/host-i18n-protocol.mjs';
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { abortSidecarApiKey } from '../../core/httpClient.js';
import {
copyTextWithFeedback,
exportTextFileWithFeedback,
} from '../../core/fileExportClient.js';
import {
collectHostI18nUntranslated,
fetchHostI18nStatus,
installOrUpdateHostI18nPack,
refreshHostI18nManifest,
removeHostI18nPack,
selectHostI18nLanguage,
updateHostI18nDepth,
} from '../../core/hostI18nClient.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { t } from '../../i18n/index.js';
import { CustomSelect } from '../ui/CustomSelect.js';
import { SegmentedControl } from '../ui/SegmentedControl.js';
import { BridgeStatusNotice } from './BridgeStatusNotice.js';
function formatHostI18nBytes(bytes) {
const num = Number(bytes || 0);
if (!Number.isFinite(num) || num <= 0) return '';
if (num < 1024) return `${num} B`;
return `${(num / 1024).toFixed(1)} KB`;
}
function getHostI18nDepthOptions() {
return [
{ value: 'light', label: t('settings.hostI18n.depthLight') },
{ value: 'deep', label: t('settings.hostI18n.depthDeep') },
];
}
export const HostI18nCard = defineComponent({
name: 'HostI18nCard',
setup({ props, onCleanup }) {
let status = null;
let draftLocale = HOST_I18N_OFF_LOCALE;
let draftDepth = 'light';
let latestWindowBridge = null;
let latestHostPlatform = 'win32';
let lastBridgeRenderSig = '';
let hasLoadedOnce = false;
let isBusy = false;
let isCollecting = false;
let destroyed = false;
let feedbackTimer = null;
let devExpanded = false;
let lastCollected = null;
const titleEl = h('span', { text: t('settings.hostI18n.title') });
const statusMsgEl = h('span', {
className: 'text-muted host-i18n-status-msg',
text: '',
});
function showFeedback(text, { isError = false, autoClearMs = 2800 } = {}) {
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
patchText(statusMsgEl, text || '');
patchClasses(statusMsgEl, { 'is-error': Boolean(isError && text) });
if (text && autoClearMs > 0) {
feedbackTimer = setTimeout(() => {
feedbackTimer = null;
if (!destroyed) {
patchText(statusMsgEl, '');
patchClasses(statusMsgEl, { 'is-error': false });
}
}, autoClearMs);
}
}
function getPackList() {
return Array.isArray(status?.packs) ? status.packs : [];
}
function findPackByLocale(locale) {
return getPackList().find((p) => p.locale === locale) || null;
}
function buildLocaleOptions() {
const opts = [{ value: HOST_I18N_OFF_LOCALE, label: t('settings.hostI18n.langOff') }];
for (const pack of getPackList()) {
const displayName =
pack.nativeName && pack.nativeName !== pack.name
? `${pack.nativeName} (${pack.locale})`
: `${pack.name || pack.locale} (${pack.locale})`;
const tag = pack.installed
? t('settings.hostI18n.optInstalled', { ver: pack.installedVersion || pack.remoteVersion || '1.0.0' })
: t('settings.hostI18n.optRemote', {
size: formatHostI18nBytes(pack.remoteBytes) || 'pack',
});
opts.push({
value: pack.locale,
label: `${displayName} · ${tag}`,
});
}
if (
draftLocale !== HOST_I18N_OFF_LOCALE &&
!opts.some((o) => o.value === draftLocale)
) {
opts.push({ value: draftLocale, label: draftLocale });
}
return opts;
}
const langLabelEl = h('span', {
className: 'form-label',
text: t('settings.hostI18n.langLabel'),
});
const langSelect = CustomSelect({
ariaLabel: t('settings.hostI18n.langLabel'),
icon: 'globe',
modelValue: draftLocale,
options: buildLocaleOptions(),
onUpdateModelValue: async (val) => {
if (isBusy || destroyed) return;
const nextLocale = normalizeHostI18nLocale(val);
const targetPack = findPackByLocale(nextLocale);
const needsDownload =
nextLocale !== HOST_I18N_OFF_LOCALE && !targetPack?.installed;
isBusy = true;
draftLocale = nextLocale;
syncControls();
showFeedback(
needsDownload
? t('settings.hostI18n.downloadingMsg', { locale: nextLocale })
: t('settings.saving'),
{ autoClearMs: 0 }
);
try {
const res = await selectHostI18nLanguage(nextLocale, draftDepth);
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
} else if (nextLocale === HOST_I18N_OFF_LOCALE) {
showFeedback(t('settings.hostI18n.disabledMsg'), { autoClearMs: 2500 });
} else if (res?.downloaded) {
showFeedback(t('settings.hostI18n.downloadedAndAppliedMsg'), { autoClearMs: 3200 });
} else {
showFeedback(t('settings.hostI18n.appliedMsg'), { autoClearMs: 2200 });
}
} catch (err) {
if (!destroyed) {
if (status) applyStatusPayload(status);
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
});
const refreshManifestBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm host-i18n-icon-btn',
title: t('settings.hostI18n.refreshManifestTip'),
'aria-label': t('settings.hostI18n.refreshManifestTip'),
onClick: async () => {
if (isBusy || destroyed) return;
isBusy = true;
syncControls();
showFeedback(t('settings.hostI18n.refreshingManifestMsg'), { autoClearMs: 0 });
try {
const res = await refreshHostI18nManifest();
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.manifestFailedMsg'), {
isError: true,
autoClearMs: 4500,
});
} else {
showFeedback(
t('settings.hostI18n.manifestSyncedMsg', { count: getPackList().length }),
{ autoClearMs: 2600 }
);
}
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.manifestFailedMsg'), {
isError: true,
autoClearMs: 4500,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
},
[createSvgIcon('refresh', { size: 12 })]
);
const langHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.langHint'),
});
// --- Conditional Depth Row (visible only when locale !== 'off') ---
const depthLabelEl = h('span', {
className: 'form-label',
text: t('settings.hostI18n.depthLabel'),
});
const depthSwitch = SegmentedControl({
ariaLabel: t('settings.hostI18n.depthLabel'),
modelValue: draftDepth,
options: getHostI18nDepthOptions(),
onUpdateModelValue: async (val) => {
if (isBusy || destroyed) return;
const nextDepth = normalizeHostI18nDepth(val);
if (nextDepth === draftDepth) return;
isBusy = true;
draftDepth = nextDepth;
syncControls();
showFeedback(t('settings.saving'), { autoClearMs: 0 });
try {
const res = await updateHostI18nDepth(nextDepth);
if (destroyed) return;
applyStatusPayload(res);
showFeedback(t('settings.hostI18n.depthSwitchedMsg'), { autoClearMs: 2000 });
} catch (err) {
if (!destroyed) {
if (status) applyStatusPayload(status);
showFeedback(err?.message || t('settings.saveFailed'), {
isError: true,
autoClearMs: 3500,
});
}
} finally {
isBusy = false;
if (!destroyed) syncControls();
}
},
});
const depthHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.depthLightHint'),
});
const depthRowEl = h('div', { className: 'form-row', hidden: true }, [
depthLabelEl,
depthSwitch.el,
depthHintEl,
]);
// --- Pack Meta & Actions Bar (visible only when locale !== 'off') ---
const packMetaTextEl = h('span', { className: 'host-i18n-pack-meta text-muted', text: '' });
const updatePackBtnText = h('span', { text: t('settings.hostI18n.redownloadBtn') });
const updatePackBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return;
isBusy = true;
syncControls();
showFeedback(t('settings.hostI18n.downloadingMsg', { locale: draftLocale }), {
autoClearMs: 0,
});
try {
const res = await installOrUpdateHostI18nPack(draftLocale);
if (destroyed) return;
applyStatusPayload(res);
if (res?.ok === false) {
showFeedback(res.error || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
} else {
showFeedback(t('settings.hostI18n.packUpdatedMsg'), { autoClearMs: 3000 });
}
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 5000,
});
}
} finally {
isBusy = false;
if (!destroyed) syncControls();
}
},
},
[createSvgIcon('download', { size: 12 }), updatePackBtnText]
);
const removePackBtnText = h('span', { text: t('settings.hostI18n.removeCacheBtn') });
const removePackBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
onClick: async () => {
if (isBusy || destroyed || draftLocale === HOST_I18N_OFF_LOCALE) return;
isBusy = true;
syncControls();
showFeedback(t('settings.saving'), { autoClearMs: 0 });
try {
const res = await removeHostI18nPack(draftLocale);
if (destroyed) return;
applyStatusPayload(res);
showFeedback(t('settings.hostI18n.cacheRemovedMsg'), { autoClearMs: 2800 });
} catch (err) {
if (!destroyed) {
showFeedback(err?.message || t('settings.hostI18n.actionFailed'), {
isError: true,
autoClearMs: 4500,
});
}
} finally {
isBusy = false;
if (!destroyed) {
syncControls();
props.onLayoutChange?.();
}
}
},
},
[removePackBtnText]
);
const packBarEl = h('div', { className: 'host-i18n-pack-bar', hidden: true }, [
packMetaTextEl,
h('div', { className: 'host-i18n-pack-actions' }, [updatePackBtn, removePackBtn]),
]);
// --- CDP Bridge Diagnostic Notice (shown only when active locale cannot reach CDP) ---
const bridgeNotice = BridgeStatusNotice({ contextMode: true });
// --- Collapsed Developer Drawer: Untranslated UI String Collector ---
const devChevron = createSvgIcon('chevron-right', {
size: 11,
className: 'host-i18n-dev-chevron',
});
const devToggleText = h('span', { text: t('settings.hostI18n.devToolsTitle') });
const devToggleBtn = h(
'button',
{
type: 'button',
className: 'host-i18n-dev-toggle',
'aria-expanded': 'false',
onClick: () => {
devExpanded = !devExpanded;
patchAttr(devToggleBtn, 'aria-expanded', devExpanded ? 'true' : 'false');
patchClasses(devDrawerEl, { 'is-expanded': devExpanded });
patchAttr(devBodyEl, 'hidden', !devExpanded);
props.onLayoutChange?.();
},
},
[devChevron, devToggleText]
);
const devHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.hostI18n.devToolsHint'),
});
const collectBtnText = h('span', { text: t('settings.hostI18n.collectBtn') });
const collectResultEl = h('span', { className: 'settings-hint-text', text: '' });
const copyCollectedBtnText = h('span', { text: t('settings.hostI18n.copyJsonBtn') });
const copyCollectedBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
hidden: true,
onClick: async () => {
if (!lastCollected?.template) return;
await copyTextWithFeedback(JSON.stringify(lastCollected.template, null, 2), {
onFeedback: (msg) => showFeedback(msg, { autoClearMs: 2400 }),
});
},
},
[createSvgIcon('copy', { size: 11 }), copyCollectedBtnText]
);
const exportCollectedBtnText = h('span', { text: t('settings.hostI18n.exportJsonBtn') });
const exportCollectedBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
hidden: true,
onClick: async () => {
if (!lastCollected?.template) return;
const fileLocale = draftLocale === HOST_I18N_OFF_LOCALE ? 'en-source' : draftLocale;
await exportTextFileWithFeedback({
filename: `host-i18n-missing-${fileLocale}.json`,
content: JSON.stringify(lastCollected.template, null, 2) + '\n',
mimeType: 'application/json',
onFeedback: (msg) => showFeedback(msg, { autoClearMs: 3200 }),
});
},
},
[createSvgIcon('download', { size: 11 }), exportCollectedBtnText]
);
const collectBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isCollecting || destroyed) return;
isCollecting = true;
patchAttr(collectBtn, 'disabled', true);
patchText(collectBtnText, t('settings.hostI18n.collectingBtn'));
try {
const res = await collectHostI18nUntranslated();
if (destroyed) return;
if (res?.ok) {
lastCollected = res;
patchText(
collectResultEl,
res.count > 0
? t('settings.hostI18n.collectedResult', {
count: res.count,
targets: res.targets || 1,
})
: t('settings.hostI18n.collectedEmpty')
);
patchAttr(copyCollectedBtn, 'hidden', !(res.count > 0));
patchAttr(exportCollectedBtn, 'hidden', !(res.count > 0));
} else {
patchText(collectResultEl, res?.error || t('settings.hostI18n.collectFailed'));
}
} catch (err) {
if (!destroyed) {
patchText(collectResultEl, err?.message || t('settings.hostI18n.collectFailed'));
}
} finally {
isCollecting = false;
if (!destroyed) {
patchAttr(collectBtn, 'disabled', false);
patchText(collectBtnText, t('settings.hostI18n.collectBtn'));
props.onLayoutChange?.();
}
}
},
},
[createSvgIcon('search', { size: 12 }), collectBtnText]
);
const devBodyEl = h('div', { className: 'host-i18n-dev-body', hidden: true }, [
devHintEl,
h('div', { className: 'host-i18n-dev-actions' }, [
collectBtn,
copyCollectedBtn,
exportCollectedBtn,
]),
collectResultEl,
]);
const devDrawerEl = h('div', { className: 'host-i18n-dev-drawer' }, [
devToggleBtn,
devBodyEl,
]);
const rootEl = h('section', { className: 'panel host-i18n-panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('globe', { size: 13 }),
titleEl,
]),
statusMsgEl,
]),
h('div', { className: 'form-row' }, [
langLabelEl,
h('div', { className: 'host-i18n-select-row' }, [langSelect.el, refreshManifestBtn]),
langHintEl,
]),
depthRowEl,
packBarEl,
bridgeNotice.el,
devDrawerEl,
]);
function applyStatusPayload(payload) {
if (!payload || typeof payload !== 'object') return;
status = payload;
draftLocale = normalizeHostI18nLocale(payload.locale);
draftDepth = normalizeHostI18nDepth(payload.depth);
if (payload.bridgeStatus) {
latestWindowBridge = payload.bridgeStatus;
}
syncControls();
}
function syncControls() {
const enabled = draftLocale !== HOST_I18N_OFF_LOCALE;
const activePack = enabled ? findPackByLocale(draftLocale) : null;
langSelect.setProps({
modelValue: draftLocale,
options: buildLocaleOptions(),
disabled: isBusy,
});
patchAttr(refreshManifestBtn, 'disabled', isBusy);
patchAttr(depthRowEl, 'hidden', !enabled);
depthSwitch.setProps({
modelValue: draftDepth,
options: getHostI18nDepthOptions(),
});
patchText(
depthHintEl,
draftDepth === 'deep'
? t('settings.hostI18n.depthDeepHint')
: t('settings.hostI18n.depthLightHint')
);
patchAttr(packBarEl, 'hidden', !enabled);
if (enabled) {
const ver = activePack?.installedVersion || activePack?.remoteVersion || '1.0.0';
const stats = activePack?.stats;
const entryCount = stats
? Number(stats.baseExact || 0) +
Number(draftDepth === 'deep' ? stats.deepExact || 0 : stats.lightExact || 0) +
Number(stats.basePatterns || 0) +
Number(draftDepth === 'deep' ? stats.deepPatterns || 0 : stats.lightPatterns || 0)
: 0;
const sizeStr = formatHostI18nBytes(
activePack?.installedBytes || activePack?.remoteBytes || 0
);
const appliedCount = Number(latestWindowBridge?.hostI18nAppliedCount || 0);
const metaParts = [`v${ver}`];
if (entryCount > 0) {
metaParts.push(t('settings.hostI18n.entriesCount', { count: entryCount }));
}
if (sizeStr) metaParts.push(sizeStr);
if (appliedCount > 0) {
metaParts.push(t('settings.hostI18n.appliedWindows', { count: appliedCount }));
}
patchText(packMetaTextEl, metaParts.join(' · '));
const hasUpdate = Boolean(activePack?.updateAvailable);
patchText(
updatePackBtnText,
hasUpdate
? t('settings.hostI18n.updatePackBtn', { ver: activePack.remoteVersion })
: t('settings.hostI18n.redownloadBtn')
);
patchClasses(updatePackBtn, {
'btn-primary': hasUpdate,
'btn-secondary': !hasUpdate,
});
patchAttr(updatePackBtn, 'disabled', isBusy);
patchAttr(removePackBtn, 'disabled', isBusy || !activePack?.installed);
}
bridgeNotice.refs.update({
visible: enabled,
windowBridge: latestWindowBridge,
hostPlatform: latestHostPlatform,
contextMode: true,
});
}
async function load(force = false) {
if (destroyed) return;
if (hasLoadedOnce && !force) return;
hasLoadedOnce = true;
try {
const res = await fetchHostI18nStatus();
if (destroyed) return;
applyStatusPayload(res);
props.onLayoutChange?.();
} catch {
// 静默兜底,保留手动刷新入口
}
}
function renderBridgeStatus(windowBridge, hostPlatform) {
if (windowBridge) latestWindowBridge = windowBridge;
if (hostPlatform) latestHostPlatform = hostPlatform;
const sig = [
Number(latestWindowBridge?.hostI18nAppliedCount || 0),
Boolean(latestWindowBridge?.connected),
Boolean(latestWindowBridge?.available),
String(latestWindowBridge?.reason || ''),
String(latestWindowBridge?.ideStatus?.reason || ''),
String(latestHostPlatform || ''),
].join('|');
if (sig === lastBridgeRenderSig) return;
lastBridgeRenderSig = sig;
syncControls();
}
function refreshLabels() {
patchText(titleEl, t('settings.hostI18n.title'));
patchText(langLabelEl, t('settings.hostI18n.langLabel'));
patchText(langHintEl, t('settings.hostI18n.langHint'));
patchText(depthLabelEl, t('settings.hostI18n.depthLabel'));
patchText(removePackBtnText, t('settings.hostI18n.removeCacheBtn'));
patchText(devToggleText, t('settings.hostI18n.devToolsTitle'));
patchText(devHintEl, t('settings.hostI18n.devToolsHint'));
if (!isCollecting) patchText(collectBtnText, t('settings.hostI18n.collectBtn'));
patchText(copyCollectedBtnText, t('settings.hostI18n.copyJsonBtn'));
patchText(exportCollectedBtnText, t('settings.hostI18n.exportJsonBtn'));
patchAttr(refreshManifestBtn, 'title', t('settings.hostI18n.refreshManifestTip'));
patchAttr(refreshManifestBtn, 'aria-label', t('settings.hostI18n.refreshManifestTip'));
bridgeNotice.refs.refreshLabels();
syncControls();
}
onCleanup(() => {
destroyed = true;
abortSidecarApiKey('host-i18n-get');
if (feedbackTimer) {
clearTimeout(feedbackTimer);
feedbackTimer = null;
}
langSelect.destroy();
depthSwitch.destroy();
bridgeNotice.destroy();
});
return {
el: rootEl,
refs: {
langSelect,
depthSwitch,
load,
renderBridgeStatus,
refreshLabels,
},
};
},
});
+80
View File
@@ -0,0 +1,80 @@
/**
* @fileoverview Decoupled HTTP/CDP client for `/api/host-i18n`.
* Completely independent from `telemetryStore.js`.
*/
import {
HOST_I18N_API_PATH,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../../shared/host-i18n-protocol.mjs';
import { callSidecarApi } from './httpClient.js';
export async function fetchHostI18nStatus() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'GET',
abortKey: 'host-i18n-get',
cdpTimeoutMs: 12000,
});
}
export async function refreshHostI18nManifest() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: { action: 'refresh_manifest' },
cdpTimeoutMs: 18000,
});
}
export async function selectHostI18nLanguage(locale, depth) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'select',
locale: normalizeHostI18nLocale(locale),
...(depth !== undefined ? { depth: normalizeHostI18nDepth(depth) } : {}),
},
cdpTimeoutMs: 22000,
});
}
export async function updateHostI18nDepth(depth) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'set_depth',
depth: normalizeHostI18nDepth(depth),
},
cdpTimeoutMs: 10000,
});
}
export async function installOrUpdateHostI18nPack(locale) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'update',
locale: normalizeHostI18nLocale(locale),
},
cdpTimeoutMs: 22000,
});
}
export async function removeHostI18nPack(locale) {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: {
action: 'remove',
locale: normalizeHostI18nLocale(locale),
},
cdpTimeoutMs: 10000,
});
}
export async function collectHostI18nUntranslated() {
return callSidecarApi(HOST_I18N_API_PATH, {
method: 'POST',
body: { action: 'collect_untranslated' },
cdpTimeoutMs: 15000,
});
}
+39
View File
@@ -675,6 +675,45 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'settings.gen.updateOffSub': 'Notifications off ({mode})',
'settings.gen.latestSub': 'Up to date ({mode})',
// Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n)
'settings.hostI18n.title': 'Antigravity UI Language',
'settings.hostI18n.langLabel': 'Host Language',
'settings.hostI18n.langOff': 'Original (Off)',
'settings.hostI18n.langHint': 'Downloads built language packs on demand from the repository and applies lossless runtime UI translation without patching app files or chat content',
'settings.hostI18n.optInstalled': 'Installed v{ver}',
'settings.hostI18n.optRemote': 'Download · {size}',
'settings.hostI18n.refreshManifestTip': 'Refresh repository language pack manifest',
'settings.hostI18n.refreshingManifestMsg': 'Refreshing language manifest…',
'settings.hostI18n.manifestSyncedMsg': 'Manifest updated ({count} packs)',
'settings.hostI18n.manifestFailedMsg': 'Failed to fetch language manifest',
'settings.hostI18n.depthLabel': 'Translation Depth',
'settings.hostI18n.depthLight': 'Light',
'settings.hostI18n.depthDeep': 'Deep',
'settings.hostI18n.depthLightHint': 'Light mode keeps common English engineering terms (MCP, Skill, Workspace, Subagent, Swarm, Diff, Terminal) and model names untranslated',
'settings.hostI18n.depthDeepHint': 'Deep mode localizes engineering terms alongside general UI copy while preserving model names and slash commands',
'settings.hostI18n.downloadingMsg': 'Downloading {locale} pack…',
'settings.hostI18n.downloadedAndAppliedMsg': 'Pack verified and applied',
'settings.hostI18n.appliedMsg': 'Language applied live',
'settings.hostI18n.disabledMsg': 'Translation disabled and UI restored',
'settings.hostI18n.depthSwitchedMsg': 'Translation depth switched',
'settings.hostI18n.packUpdatedMsg': 'Language pack updated and reapplied',
'settings.hostI18n.cacheRemovedMsg': 'Local pack cache removed',
'settings.hostI18n.actionFailed': 'Language pack operation failed',
'settings.hostI18n.entriesCount': '{count} entries',
'settings.hostI18n.appliedWindows': '{count} window(s) active',
'settings.hostI18n.updatePackBtn': 'Update to v{ver}',
'settings.hostI18n.redownloadBtn': 'Check Update',
'settings.hostI18n.removeCacheBtn': 'Remove Cache',
'settings.hostI18n.devToolsTitle': 'Missing UI String Collector',
'settings.hostI18n.devToolsHint': 'Scans visible Antigravity UI controls for untranslated English phrases (excluding chat content and code) to help complete packs or author new languages',
'settings.hostI18n.collectBtn': 'Collect Missing Strings',
'settings.hostI18n.collectingBtn': 'Collecting…',
'settings.hostI18n.collectedResult': 'Collected {count} untranslated UI strings across {targets} window(s)',
'settings.hostI18n.collectedEmpty': 'No untranslated English UI strings detected on active pages',
'settings.hostI18n.collectFailed': 'Collection failed — verify remote debugging bridge is active',
'settings.hostI18n.copyJsonBtn': 'Copy JSON',
'settings.hostI18n.exportJsonBtn': 'Export JSON',
// Preferences -> Structure Tab
'settings.str.thirdTabAria': 'Structure section tabs',
'settings.str.tabMount': 'Mount & Bar',
+39
View File
@@ -675,6 +675,45 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'settings.gen.updateOffSub': '已关闭更新提醒 ({mode})',
'settings.gen.latestSub': '已是最新 ({mode})',
// Preferences -> General Tab -> Antigravity Host UI Language (decoupled Host I18n)
'settings.hostI18n.title': 'Antigravity 界面语言',
'settings.hostI18n.langLabel': '目标语言',
'settings.hostI18n.langOff': '原始语言(不翻译)',
'settings.hostI18n.langHint': '从仓库按需独立下载语言包并在渲染层无损应用,不修改宿主安装包,不影响聊天内容与代码',
'settings.hostI18n.optInstalled': '已下载 v{ver}',
'settings.hostI18n.optRemote': '仓库拉取 · {size}',
'settings.hostI18n.refreshManifestTip': '刷新仓库语言包清单',
'settings.hostI18n.refreshingManifestMsg': '正在拉取语言清单…',
'settings.hostI18n.manifestSyncedMsg': '已更新清单({count} 个语言包)',
'settings.hostI18n.manifestFailedMsg': '拉取语言清单失败,请检查网络或代理',
'settings.hostI18n.depthLabel': '翻译深度',
'settings.hostI18n.depthLight': '浅度',
'settings.hostI18n.depthDeep': '深度',
'settings.hostI18n.depthLightHint': '浅度模式:保留 MCP、Skill、Workspace、Subagent、Swarm、Diff、Terminal 等高频英文术语及模型名称,仅翻译常规界面',
'settings.hostI18n.depthDeepHint': '深度模式:将常见工程术语一并译为目标语言(如工作区、子代理、蜂群、终端、沙箱),仅保留模型名与命令',
'settings.hostI18n.downloadingMsg': '正在下载 {locale} 语言包…',
'settings.hostI18n.downloadedAndAppliedMsg': '语言包已下载校验并生效',
'settings.hostI18n.appliedMsg': '已切换并即时生效',
'settings.hostI18n.disabledMsg': '已关闭翻译并还原原始界面',
'settings.hostI18n.depthSwitchedMsg': '已热切换翻译深度',
'settings.hostI18n.packUpdatedMsg': '语言包已更新并重新应用',
'settings.hostI18n.cacheRemovedMsg': '已删除本地语言包缓存',
'settings.hostI18n.actionFailed': '语言包操作失败,请重试',
'settings.hostI18n.entriesCount': '{count} 条词条',
'settings.hostI18n.appliedWindows': '已应用 {count} 窗口',
'settings.hostI18n.updatePackBtn': '更新至 v{ver}',
'settings.hostI18n.redownloadBtn': '检查更新',
'settings.hostI18n.removeCacheBtn': '删除缓存',
'settings.hostI18n.devToolsTitle': '词条采集与多语言扩展',
'settings.hostI18n.devToolsHint': '仅扫描当前打开的 Antigravity 界面控件中未命中的英文短语(自动排除聊天正文与代码),便于补全漏翻词条或制作新语言包',
'settings.hostI18n.collectBtn': '采集未翻译 UI 文案',
'settings.hostI18n.collectingBtn': '采集中…',
'settings.hostI18n.collectedResult': '共采集到 {count} 条待翻译 UI 文案(扫描 {targets} 个窗口)',
'settings.hostI18n.collectedEmpty': '当前页面未检测到待翻译的英文 UI 短语',
'settings.hostI18n.collectFailed': '采集失败,请确认已开启调试端口并打开主窗口',
'settings.hostI18n.copyJsonBtn': '复制 JSON',
'settings.hostI18n.exportJsonBtn': '导出 JSON',
// Preferences -> Structure Tab
'settings.str.thirdTabAria': '结构子菜单切换',
'settings.str.tabMount': '挂载胶囊',
+5
View File
@@ -140,4 +140,9 @@ export const SVG_ICON_DEFS = Object.freeze({
{ tag: 'rect', attrs: { x: '3', y: '7', width: '10', height: '7', rx: '1.5' } },
{ tag: 'path', attrs: { d: 'M5.2 7V5.1a2.8 2.8 0 0 1 5.3-1.2' } },
],
globe: [
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } },
{ tag: 'ellipse', attrs: { cx: '8', cy: '8', rx: '2.7', ry: '6' } },
{ tag: 'path', attrs: { d: 'M2.3 6h11.4M2.3 10h11.4' } },
],
});
@@ -1774,3 +1774,106 @@
white-space: nowrap;
flex-shrink: 0;
}
/* --- Decoupled Antigravity Host UI Language Card (HostI18nCard) --- */
.host-i18n-status-msg {
font-size: var(--fs-sm);
margin-left: auto;
max-width: 60%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.host-i18n-status-msg.is-error {
color: var(--metric-danger);
}
.host-i18n-select-row {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
min-width: 0;
}
.host-i18n-select-row > .custom-select {
flex: 1 1 auto;
min-width: 0;
}
.host-i18n-icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(28px * var(--ui-font-scale, 1));
height: calc(28px * var(--ui-font-scale, 1));
padding: 0;
flex-shrink: 0;
}
.host-i18n-pack-bar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px;
padding-top: 2px;
}
.host-i18n-pack-meta {
font-size: var(--fs-xs);
line-height: 1.4;
}
.host-i18n-pack-actions {
display: inline-flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.host-i18n-dev-drawer {
border-top: 1px solid var(--border-hairline);
padding-top: 8px;
margin-top: 2px;
}
.host-i18n-dev-toggle {
display: inline-flex;
align-items: center;
gap: 5px;
border: none;
background: transparent;
color: var(--text-muted);
font-size: var(--fs-xs);
font-weight: 600;
padding: 2px 0;
cursor: pointer;
}
.host-i18n-dev-toggle:hover {
color: var(--text-primary);
}
.host-i18n-dev-chevron {
transition: transform var(--dur-fast) var(--ease-standard);
}
.host-i18n-dev-drawer.is-expanded .host-i18n-dev-chevron {
transform: rotate(90deg);
}
.host-i18n-dev-body {
display: flex;
flex-direction: column;
gap: 8px;
padding-top: 6px;
}
.host-i18n-dev-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
+8 -1
View File
@@ -132,7 +132,14 @@ export const SettingsView = defineComponent({
);
}
} else if (settingsSubTab !== 'account') {
if (settings) generalTab.refs.renderSettings(settings);
if (settings) {
generalTab.refs.renderSettings(
settings,
telemetry?.windowBridge,
telemetry?.hostPlatform
);
}
void generalTab.refs.loadHostI18n?.(false);
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
}
refreshScroll();
@@ -22,6 +22,7 @@ import {
triggerPluginUpdate,
} from '../../store/telemetryStore.js';
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
import { HostI18nCard } from '../../components/settings/HostI18nCard.js';
import { CustomSelect } from '../../components/ui/CustomSelect.js';
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
import { ToggleSwitch } from '../../components/ui/ToggleSwitch.js';
@@ -410,9 +411,20 @@ export const SettingsGeneralTab = defineComponent({
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
]);
const rootEl = h('div', { className: 'settings-tab-stack' }, [appearancePanel, cloudPanel]);
const hostI18nCard = HostI18nCard({
onLayoutChange: () => props.onLayoutChange?.(),
});
function renderSettings(settings) {
const rootEl = h('div', { className: 'settings-tab-stack' }, [
appearancePanel,
hostI18nCard.el,
cloudPanel,
]);
function renderSettings(settings, windowBridge = null, hostPlatform = 'win32') {
if (windowBridge || hostPlatform) {
hostI18nCard.refs.renderBridgeStatus(windowBridge, hostPlatform);
}
if (!settings) return;
latestSettings = settings;
draftLanguage = normalizeI18nLanguage(settings.language);
@@ -527,6 +539,7 @@ export const SettingsGeneralTab = defineComponent({
} else {
patchText(pricingSyncSub, t('quota.loading'));
}
hostI18nCard.refs.refreshLabels();
}
onCleanup(() => {
@@ -537,6 +550,7 @@ export const SettingsGeneralTab = defineComponent({
fontScaleSwitch.destroy();
modernUiSwitch.destroy();
autoUpdateSelect.destroy();
hostI18nCard.destroy();
});
return {
@@ -549,6 +563,8 @@ export const SettingsGeneralTab = defineComponent({
autoUpdateSelect,
syncPricingBtn,
updatePluginBtn,
hostI18nCard,
loadHostI18n: (force = false) => hostI18nCard.refs.load(force),
renderSettings,
renderCloudStatus,
refreshLabels,
+103
View File
@@ -7546,6 +7546,109 @@ html[data-standalone="true"] .app-shell {
flex-shrink: 0;
}
/* --- Decoupled Antigravity Host UI Language Card (HostI18nCard) --- */
.host-i18n-status-msg {
font-size: var(--fs-sm);
margin-left: auto;
max-width: 60%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.host-i18n-status-msg.is-error {
color: var(--metric-danger);
}
.host-i18n-select-row {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
min-width: 0;
}
.host-i18n-select-row > .custom-select {
flex: 1 1 auto;
min-width: 0;
}
.host-i18n-icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(28px * var(--ui-font-scale, 1));
height: calc(28px * var(--ui-font-scale, 1));
padding: 0;
flex-shrink: 0;
}
.host-i18n-pack-bar {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px;
padding-top: 2px;
}
.host-i18n-pack-meta {
font-size: var(--fs-xs);
line-height: 1.4;
}
.host-i18n-pack-actions {
display: inline-flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.host-i18n-dev-drawer {
border-top: 1px solid var(--border-hairline);
padding-top: 8px;
margin-top: 2px;
}
.host-i18n-dev-toggle {
display: inline-flex;
align-items: center;
gap: 5px;
border: none;
background: transparent;
color: var(--text-muted);
font-size: var(--fs-xs);
font-weight: 600;
padding: 2px 0;
cursor: pointer;
}
.host-i18n-dev-toggle:hover {
color: var(--text-primary);
}
.host-i18n-dev-chevron {
transition: transform var(--dur-fast) var(--ease-standard);
}
.host-i18n-dev-drawer.is-expanded .host-i18n-dev-chevron {
transform: rotate(90deg);
}
.host-i18n-dev-body {
display: flex;
flex-direction: column;
gap: 8px;
padding-top: 6px;
}
.host-i18n-dev-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
/* --- src/styles/overlay.css --- */
/*
* 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css).
+5
View File
@@ -29,6 +29,7 @@ const BACKEND_MODULE_FILES = [
'../shared/settings-normalization.mjs',
'../shared/telemetry-display-rules.mjs',
'../shared/window-bridge-protocol.mjs',
'../shared/host-i18n-protocol.mjs',
'../shared/workspace-uri.mjs',
'../shared/prompt-clean.mjs',
'../backend/fs-atomic.mjs',
@@ -54,6 +55,10 @@ const BACKEND_MODULE_FILES = [
'../backend/plugin-updater.mjs',
'../backend/ls-rpc.mjs',
'../backend/cloudcode-proxy.mjs',
'../backend/host-i18n/http-fetch.mjs',
'../backend/host-i18n/pack-manager.mjs',
'../backend/host-i18n/runtime-translator.mjs',
'../backend/host-i18n/index.mjs',
'../backend/model-pricing.mjs',
'../backend/quota-pools.mjs',
'../backend/quota-reservation.mjs',
@@ -1136,13 +1136,15 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(normalizeI18nLanguage('system'), 'auto');
assert.equal(typeof isEquivalentTelemetry, 'function');
assert.equal(BRIDGE_API_ROUTE_DEFS.length, 15);
assert.equal(BRIDGE_API_ROUTE_DEFS.length, 17);
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/bridge/relaunch'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/catalog'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/migrate'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/export-file'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/reveal-file'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/quota-reservation/log'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/host-i18n' && r.method === 'GET'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/host-i18n' && r.method === 'POST'));
// 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry
const h = backendHarness();
+858
View File
@@ -0,0 +1,858 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import http from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
buildAllHostI18nPacks,
validatePatternRule,
} from '../../../host-i18n/scripts/build-packs.mjs';
import {
auditCatalogAgainstPack,
loadIgnoreLists,
} from '../../../host-i18n/scripts/audit-host-i18n.mjs';
import { mergeHostI18nTranslations } from '../../../host-i18n/scripts/merge-translations.mjs';
import {
HOST_I18N_GLOBAL_KEY,
HOST_I18N_OFF_LOCALE,
normalizeHostI18nDepth,
normalizeHostI18nLocale,
} from '../shared/host-i18n-protocol.mjs';
import {
assertAllowedHostI18nUrl,
fetchHostI18nTextWithFallback,
} from '../backend/host-i18n/http-fetch.mjs';
import {
compileHostI18nRuntimePayload,
createHostI18nPackManager,
} from '../backend/host-i18n/pack-manager.mjs';
import {
applyHostI18nInPage,
collectUntranslatedHostUiInPage,
createHostI18nApplyExpression,
createHostI18nDisposeExpression,
createHostI18nHeartbeatExpression,
} from '../backend/host-i18n/runtime-translator.mjs';
import { handleHostI18nPostAction } from '../backend/host-i18n/index.mjs';
import { createWindowBridgeController } from '../backend/window-bridge.mjs';
import { dispatchBridgeApiRequest } from '../backend/api-actions.mjs';
const REPO_ROOT = resolve(fileURLToPath(new URL('../../..', import.meta.url)));
const REAL_HOST_I18N_ROOT = join(REPO_ROOT, 'host-i18n');
function sha256(str) {
return createHash('sha256').update(String(str), 'utf8').digest('hex');
}
function createTempDir(t, prefix = 'ag-host-i18n-test-') {
const dir = mkdtempSync(join(tmpdir(), prefix));
t.after(() => {
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// ignore cleanup error
}
});
return dir;
}
// ---------------------------------------------------------------------------
// 1. Shared protocol & pack builder validation
// ---------------------------------------------------------------------------
test('host-i18n protocol normalizers handle edge cases cleanly', () => {
assert.equal(normalizeHostI18nLocale(''), HOST_I18N_OFF_LOCALE);
assert.equal(normalizeHostI18nLocale('original'), HOST_I18N_OFF_LOCALE);
assert.equal(normalizeHostI18nLocale('zh_cn'), 'zh-CN');
assert.equal(normalizeHostI18nLocale('ja-jp'), 'ja-JP');
assert.equal(normalizeHostI18nLocale('../evil'), HOST_I18N_OFF_LOCALE);
assert.equal(normalizeHostI18nDepth('deep'), 'deep');
assert.equal(normalizeHostI18nDepth('full'), 'deep');
assert.equal(normalizeHostI18nDepth('unknown'), 'light');
});
test('host-i18n build-packs --check verifies real repository dist artifacts and rejects unsafe patterns', (t) => {
const checked = buildAllHostI18nPacks({ rootDir: REAL_HOST_I18N_ROOT, checkOnly: true });
assert.equal(checked.checked, true);
const zhPackMeta = checked.manifest.packs.find((p) => p.locale === 'zh-CN');
assert.ok(zhPackMeta, 'zh-CN pack must exist in manifest');
assert.ok(
zhPackMeta.stats.baseExact + zhPackMeta.stats.deepExact >= 5000,
`Expected full zh-CN coverage >= 5000 exact entries, got ${zhPackMeta.stats.baseExact + zhPackMeta.stats.deepExact}`
);
assert.ok(
zhPackMeta.stats.basePatterns + zhPackMeta.stats.deepPatterns >= 800,
`Expected full zh-CN coverage >= 800 patterns, got ${zhPackMeta.stats.basePatterns + zhPackMeta.stats.deepPatterns}`
);
// Strict coverage audit against real en-US.catalog.json + ignore.json must have 0 gaps & 0 integrity issues
const realCatalog = JSON.parse(
readFileSync(join(REAL_HOST_I18N_ROOT, 'sources', 'en-US.catalog.json'), 'utf8')
);
const realPackObj = JSON.parse(
readFileSync(join(REAL_HOST_I18N_ROOT, 'dist', 'packs', 'zh-CN.json'), 'utf8')
);
const ignoreLists = loadIgnoreLists(join(REAL_HOST_I18N_ROOT, 'sources', 'ignore.json'));
const auditReport = auditCatalogAgainstPack(realCatalog, realPackObj, ignoreLists);
assert.equal(auditReport.missingExact.length, 0, 'Catalog must have 0 missing exact translations');
assert.equal(auditReport.missingTemplates.length, 0, 'Catalog must have 0 missing dynamic templates');
assert.equal(auditReport.brokenPatterns.length, 0, 'Pack must have 0 broken pattern backreferences');
assert.equal(auditReport.redundantModeExact.length, 0, 'Pack must have 0 redundant identical light/deep keys');
// Verify screenshot-reported Appearance, General Mode Copy, Queue, Outside-of-Projects & Model Tags translate cleanly
const deepMerged = compileHostI18nRuntimePayload(realPackObj, 'deep');
const lightMerged = compileHostI18nRuntimePayload(realPackObj, 'light');
assert.equal(deepMerged.exact['Leaving Soon'], '即将下线');
assert.equal(deepMerged.exact['Notice'], '提示');
assert.equal(deepMerged.exact['New'], '新');
assert.equal(deepMerged.exact['Contrast'], '对比度');
assert.equal(deepMerged.exact['Strong'], '强');
assert.equal(deepMerged.exact['Font'], '字体');
assert.equal(deepMerged.exact['Light Theme'], '浅色主题');
assert.equal(deepMerged.exact['Dark Theme'], '深色主题');
assert.equal(deepMerged.exact['Preset'], '预设');
assert.equal(deepMerged.exact['Background'], '背景色');
assert.equal(deepMerged.exact['Foreground'], '前景色');
assert.equal(deepMerged.exact['Accent'], '强调色');
assert.equal(deepMerged.exact['Code Preview'], '代码预览');
assert.equal(deepMerged.exact['Knowledge Work'], '知识工作');
assert.equal(deepMerged.exact['Software Engineering'], '软件工程');
assert.equal(deepMerged.exact['Queue'], '排队');
assert.equal(deepMerged.exact['Settings for conversations outside of projects.'], '非项目对话设置。');
assert.equal(
lightMerged.exact['Full interface for coding, developer tools, and managing agents.'],
'用于编写代码、使用开发者工具及管理 Agent 的完整界面。'
);
assert.equal(
deepMerged.exact['Full interface for coding, developer tools, and managing agents.'],
'用于编写代码、使用开发者工具及管理智能体的完整界面。'
);
assert.throws(
() => validatePatternRule({ source: 'unanchored (\\d+)', flags: '', replace: '$1' }),
/strictly anchored/
);
assert.throws(
() => validatePatternRule({ source: '^(a+)+$', flags: '', replace: 'x' }),
/nested quantifier/
);
assert.throws(
() => validatePatternRule({ source: '^ok$', flags: 'g', replace: 'x' }),
/unsupported regex flags/
);
// Verify duplicate base/light conflict fails loudly in isolated workspace
const workDir = createTempDir(t);
const srcDir = join(workDir, 'sources', 'ja-JP');
mkdirSync(srcDir, { recursive: true });
writeFileSync(
join(srcDir, 'meta.json'),
JSON.stringify({ locale: 'ja-JP', name: 'Japanese', nativeName: '日本語', version: '1.0.0' })
);
writeFileSync(
join(srcDir, 'common.json'),
JSON.stringify({ base: { Save: '保存' }, light: { Save: 'セーブ' }, deep: { Save: '保存' } })
);
assert.throws(
() => buildAllHostI18nPacks({ rootDir: workDir }),
/exists in both "base" and "light"/
);
// Verify mergeHostI18nTranslations resolves base vs light/deep splits cleanly without collisions
const mergeRoot = createTempDir(t);
const mergeLocaleDir = join(mergeRoot, 'sources', 'ja-JP');
mkdirSync(mergeLocaleDir, { recursive: true });
writeFileSync(
join(mergeLocaleDir, 'meta.json'),
JSON.stringify({ locale: 'ja-JP', name: 'Japanese', nativeName: '日本語', version: '1.0.0' })
);
writeFileSync(
join(mergeLocaleDir, 'common.json'),
JSON.stringify({ base: { Save: '保存', Agent: 'Agent' } })
);
const merged = mergeHostI18nTranslations({
locale: 'ja-JP',
rootDir: mergeRoot,
ignorePath: join(mergeRoot, 'sources', 'ignore.json'),
bump: 'patch',
patch: {
exact: {
Agent: { light: 'Agent', deep: 'エージェント' },
'Light Theme': 'ライトテーマ',
},
patterns: [
{ source: '^Archive (.+?)$', flags: '', hint: 'Archive', light: '$1 をアーカイブ', deep: '$1 をアーカイブ' },
],
ignore: { exact: ['Google Sans'], templates: ['^Bar (.+?)$'] },
},
});
assert.equal(merged.version, '1.0.1');
assert.equal(merged.exactAdded, 1);
assert.equal(merged.exactUpdated, 1);
assert.equal(merged.patternsAdded, 1);
assert.equal(merged.ignoreAdded, 2);
const builtJa = JSON.parse(readFileSync(join(mergeRoot, 'dist', 'packs', 'ja-JP.json'), 'utf8'));
assert.equal(builtJa.base.exact['Agent'], undefined, 'Upgraded split key must be removed from base');
assert.equal(builtJa.modes.light.exact['Agent'], 'Agent');
assert.equal(builtJa.modes.deep.exact['Agent'], 'エージェント');
assert.equal(builtJa.base.exact['Light Theme'], 'ライトテーマ');
});
// ---------------------------------------------------------------------------
// 2. HTTP allowlist, fallback, SHA-256 verification & PackManager lifecycle
// ---------------------------------------------------------------------------
test('host-i18n downloader enforces HTTPS allowlist and falls back from GitHub Raw to jsDelivr', async () => {
assert.throws(() => assertAllowedHostI18nUrl('http://raw.githubusercontent.com/a/b'));
assert.throws(() => assertAllowedHostI18nUrl('https://evil.example.com/manifest.json'));
const visited = [];
const res = await fetchHostI18nTextWithFallback(
[
'https://raw.githubusercontent.com/yuhuan-dev/antigravity-usage-monitor/main/host-i18n/dist/manifest.json',
'https://cdn.jsdelivr.net/gh/yuhuan-dev/antigravity-usage-monitor@main/host-i18n/dist/manifest.json',
],
{
fetchImpl: async (url) => {
visited.push(url);
if (url.includes('raw.githubusercontent.com')) {
return { ok: false, status: 503, text: async () => 'unavailable' };
}
return { ok: true, status: 200, text: async () => '{"ok":true}' };
},
}
);
assert.equal(visited.length, 2);
assert.match(res.url, /cdn\.jsdelivr\.net/);
assert.equal(res.text, '{"ok":true}');
});
test('PackManager verifies SHA-256, rejects tampered packs, hot-switches light/deep offline, and syncs cross-process via mtime', async (t) => {
const dataDir = createTempDir(t);
const realManifestText = readFileSync(join(REAL_HOST_I18N_ROOT, 'dist', 'manifest.json'), 'utf8');
const realPackText = readFileSync(join(REAL_HOST_I18N_ROOT, 'dist', 'packs', 'zh-CN.json'), 'utf8');
let tamperMode = true;
let fetchCalls = 0;
const mockFetch = async (url) => {
fetchCalls += 1;
if (url.endsWith('/manifest.json')) {
return { ok: true, status: 200, text: async () => realManifestText };
}
if (url.endsWith('/packs/zh-CN.json')) {
return {
ok: true,
status: 200,
text: async () => (tamperMode ? realPackText.replace('设置', '篡改') : realPackText),
};
}
return { ok: false, status: 404, text: async () => 'not found' };
};
const mgr = createHostI18nPackManager({ dataDir, fetchImpl: mockFetch, ref: 'main' });
// Tampered pack must be rejected and NOT persisted
await assert.rejects(() => mgr.selectLanguage({ locale: 'zh-CN', depth: 'light' }), /Integrity check failed/);
assert.equal(existsSync(join(dataDir, 'host-i18n', 'packs', 'zh-CN.json')), false);
assert.equal(mgr.loadState().locale, 'off');
// Valid pack downloads, verifies, and activates in light mode
tamperMode = false;
const sel = await mgr.selectLanguage({ locale: 'zh-CN', depth: 'light' });
assert.equal(sel.ok, true);
assert.equal(sel.downloaded, true);
assert.equal(sel.state.locale, 'zh-CN');
assert.equal(sel.state.depth, 'light');
const lightPayload = mgr.getActiveBridgeDescriptor().getPayload();
assert.equal(lightPayload.exact['Settings'], '设置');
assert.equal(lightPayload.exact['Manage MCP Servers'], '管理 MCP Servers');
assert.equal(lightPayload.exact['Subagent'], 'Subagent');
// Switching light -> deep must perform ZERO network requests
const fetchesBeforeDepth = fetchCalls;
mgr.setDepth('deep');
assert.equal(fetchCalls, fetchesBeforeDepth);
const deepPayload = mgr.getActiveBridgeDescriptor().getPayload();
assert.equal(deepPayload.exact['Manage MCP Servers'], '管理 MCP 服务');
assert.equal(deepPayload.exact['Subagent'], '子代理');
// A second independent manager instance (simulating separate daemon process) observes saved state immediately
const daemonMgr = createHostI18nPackManager({ dataDir, fetchImpl: mockFetch });
const daemonDesc = daemonMgr.getActiveBridgeDescriptor();
assert.equal(daemonDesc.active, true);
assert.equal(daemonDesc.locale, 'zh-CN');
assert.equal(daemonDesc.depth, 'deep');
// Removing active pack cleans disk and reverts state to 'off'
const removed = mgr.removePack('zh-CN');
assert.equal(removed.ok, true);
assert.equal(removed.state.locale, 'off');
assert.equal(existsSync(join(dataDir, 'host-i18n', 'packs', 'zh-CN.json')), false);
});
// ---------------------------------------------------------------------------
// 3. Lossless DOM runtime translator & untranslated collector
// ---------------------------------------------------------------------------
function createMockDom() {
class MockNode {
constructor(nodeType) {
this.nodeType = nodeType;
this.parentNode = null;
this.parentElement = null;
this.childNodes = [];
}
}
class MockText extends MockNode {
constructor(value) {
super(3);
this.nodeValue = value;
}
}
class MockElement extends MockNode {
constructor(tagName, { id = '', className = '', attrs = {}, contentEditable = false } = {}) {
super(1);
this.tagName = tagName.toUpperCase();
this.id = id;
this.className = className;
this.isContentEditable = contentEditable;
this._attrs = new Map(Object.entries(attrs));
if (id) this._attrs.set('id', id);
if (className) this._attrs.set('class', className);
}
appendChild(child) {
child.parentNode = this;
child.parentElement = this;
this.childNodes.push(child);
return child;
}
getAttribute(name) {
return this._attrs.has(name) ? this._attrs.get(name) : null;
}
setAttribute(name, value) {
this._attrs.set(name, String(value));
}
hasAttribute(name) {
return this._attrs.has(name);
}
_matchesSimple(sel) {
const s = sel.trim();
if (!s) return false;
if (s.startsWith('#')) return this.id === s.slice(1);
if (s.startsWith('.')) return this.className.split(/\s+/).includes(s.slice(1));
if (s === '[data-ag-i18n-ignore]') return this.hasAttribute('data-ag-i18n-ignore');
if (s === '[contenteditable="true"]') return this.isContentEditable || this.getAttribute('contenteditable') === 'true';
if (s === '[data-testid*="markdown"]') return String(this.getAttribute('data-testid') || '').includes('markdown');
if (s.startsWith('[') && s.endsWith(']')) {
const inner = s.slice(1, -1);
const eqIdx = inner.indexOf('=');
if (eqIdx < 0) return this.hasAttribute(inner);
const k = inner.slice(0, eqIdx);
const v = inner.slice(eqIdx + 1).replace(/^"|"$/g, '');
return this.getAttribute(k) === v;
}
if (s.includes(' ')) {
const [ancSel, selfSel] = s.split(/\s+/);
return this._matchesSimple(selfSel) && Boolean(this.parentElement?.closest(ancSel));
}
return this.tagName.toLowerCase() === s.toLowerCase();
}
closest(selectorList) {
const parts = String(selectorList || '').split(',');
let cur = this;
while (cur && cur.nodeType === 1) {
if (parts.some((sel) => cur._matchesSimple(sel))) return cur;
cur = cur.parentElement;
}
return null;
}
querySelectorAll(selectorList) {
const parts = String(selectorList || '').split(',');
const out = [];
const walk = (node) => {
if (!node || node.nodeType !== 1) return;
if (parts.some((sel) => node._matchesSimple(sel))) out.push(node);
for (const ch of node.childNodes) walk(ch);
};
walk(this);
return out;
}
}
const body = new MockElement('body');
const doc = { body, documentElement: body };
const observers = [];
class MockMutationObserver {
constructor(cb) {
this.cb = cb;
this.disconnected = false;
observers.push(this);
}
observe() {}
disconnect() {
this.disconnected = true;
}
trigger(mutations) {
if (!this.disconnected) this.cb(mutations);
}
}
const win = {
MutationObserver: MockMutationObserver,
requestAnimationFrame: (cb) => {
cb();
return 1;
},
cancelAnimationFrame: () => {},
};
return { win, doc, body, MockElement, MockText, observers };
}
test('runtime translator translates light/deep losslessly, skips code/chat/plugin Shadow Hosts, handles React updates, and collects missing UI strings', () => {
const { win, doc, body, MockElement, MockText, observers } = createMockDom();
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
globalThis.window = win;
globalThis.document = doc;
try {
const packObj = JSON.parse(
readFileSync(join(REAL_HOST_I18N_ROOT, 'dist', 'packs', 'zh-CN.json'), 'utf8')
);
const packHash = sha256(JSON.stringify(packObj));
const lightPayload = compileHostI18nRuntimePayload(packObj, 'light', packHash);
const deepPayload = compileHostI18nRuntimePayload(packObj, 'deep', packHash);
// Build mock Antigravity DOM
const btnSettings = body.appendChild(
new MockElement('button', { attrs: { title: 'Open Settings', 'aria-label': 'Settings' } })
);
const txtSettings = btnSettings.appendChild(new MockText(' Settings '));
const btnMcp = body.appendChild(new MockElement('button'));
const txtMcp = btnMcp.appendChild(new MockText('Manage MCP Servers'));
const statusSpan = body.appendChild(new MockElement('span'));
const txtThought = statusSpan.appendChild(new MockText('Thought for 12s'));
const pluginCountSpan = body.appendChild(new MockElement('span'));
const txtPluginCount = pluginCountSpan.appendChild(new MockText('3 plugins installed'));
const inputEl = body.appendChild(
new MockElement('input', { attrs: { placeholder: 'Ask anything...' } })
);
const btnUntranslated = body.appendChild(new MockElement('button'));
btnUntranslated.appendChild(new MockText('Quantum Hyperdrive Mode'));
// Dynamic specificity precedence: mode-specific pattern MUST beat generic base `^Show (.+?)$`
const subagentsMoreBtn = body.appendChild(new MockElement('button'));
const txtSubagentsMore = subagentsMoreBtn.appendChild(new MockText('Show 3 more subagents'));
// CloudCode server-pushed model badge & removal notice tooltip
const noticeBadge = body.appendChild(new MockElement('span'));
const txtNoticeBadge = noticeBadge.appendChild(new MockText('Notice'));
const noticeTip = body.appendChild(new MockElement('div'));
const txtNoticeTip = noticeTip.appendChild(
new MockText('GPT-OSS will be removed from Antigravity on November 30, 2026.')
);
// Shortcut suffix boundary safety: `Submit (Enter)` translates, `Submitted` must NOT be mangled
const submitShortcutBtn = body.appendChild(new MockElement('button'));
const txtSubmitShortcut = submitShortcutBtn.appendChild(new MockText('Submit (Enter)'));
const submittedSpan = body.appendChild(new MockElement('span'));
const txtSubmittedWord = submittedSpan.appendChild(new MockText('Submitted'));
// Case-insensitive short-label fallback (`Accept All` -> matches `Accept all`)
const acceptAllBtn = body.appendChild(new MockElement('button'));
const txtAcceptAll = acceptAllBtn.appendChild(new MockText('Accept All'));
// Real Antigravity UI toolbar inside markdown-table-* MUST be translated (NOT falsely skipped)
const mdTableBtn = body.appendChild(
new MockElement('button', { attrs: { 'data-testid': 'markdown-table-menu' } })
);
const txtMdTableBtn = mdTableBtn.appendChild(new MockText('Copy'));
// Excluded areas that MUST NEVER be translated or collected
const codeEl = body.appendChild(new MockElement('code'));
const txtCode = codeEl.appendChild(new MockText('Settings'));
const proseEl = body.appendChild(new MockElement('div', { className: 'prose' }));
const txtProse = proseEl.appendChild(new MockText('Manage MCP Servers'));
const userMsgEl = body.appendChild(
new MockElement('div', { attrs: { 'data-testid': 'user-message-content' } })
);
const txtUserMsg = userMsgEl.appendChild(new MockText('Settings'));
const codeGutterEl = body.appendChild(
new MockElement('div', { attrs: { 'data-testid': 'code-gutter' } })
);
const txtCodeGutter = codeGutterEl.appendChild(new MockText('Cancel'));
const mdCodeBlockEl = body.appendChild(
new MockElement('div', { attrs: { 'data-testid': 'markdown-code-block-preview' } })
);
const txtMdCodeBlock = mdCodeBlockEl.appendChild(new MockText('Open Settings'));
const pluginPortal = body.appendChild(new MockElement('div', { id: 'ag-usage-monitor-portal' }));
const txtPortal = pluginPortal.appendChild(new MockText('Settings'));
const monacoEl = body.appendChild(new MockElement('div', { className: 'monaco-editor' }));
const txtMonaco = monacoEl.appendChild(new MockText('Cancel'));
// 1. Apply Light mode
const lightRes = applyHostI18nInPage(lightPayload, 'boot-1', HOST_I18N_GLOBAL_KEY);
assert.equal(lightRes.applied, true);
assert.equal(txtSettings.nodeValue, ' 设置 ');
assert.equal(btnSettings.getAttribute('title'), '打开设置');
assert.equal(btnSettings.getAttribute('aria-label'), '设置');
assert.equal(txtMcp.nodeValue, '管理 MCP Servers');
assert.equal(txtThought.nodeValue, '已思考 12s');
assert.equal(txtPluginCount.nodeValue, '已安装 3 个 Plugin');
assert.equal(txtSubagentsMore.nodeValue, '展开其余 3 个 Subagent');
assert.equal(txtNoticeBadge.nodeValue, '提示');
assert.equal(
txtNoticeTip.nodeValue,
'GPT-OSS 将于 November 30, 2026 从 Antigravity 中移除。'
);
assert.equal(txtSubmitShortcut.nodeValue, '提交 (Enter)');
assert.notEqual(txtSubmittedWord.nodeValue, '提交ted');
assert.equal(txtAcceptAll.nodeValue, '全部接受');
assert.equal(txtMdTableBtn.nodeValue, '复制');
assert.equal(inputEl.getAttribute('placeholder'), '输入任何问题...');
// Excluded subtrees stayed 100% untouched
assert.equal(txtCode.nodeValue, 'Settings');
assert.equal(txtProse.nodeValue, 'Manage MCP Servers');
assert.equal(txtUserMsg.nodeValue, 'Settings');
assert.equal(txtCodeGutter.nodeValue, 'Cancel');
assert.equal(txtMdCodeBlock.nodeValue, 'Open Settings');
assert.equal(txtPortal.nodeValue, 'Settings');
assert.equal(txtMonaco.nodeValue, 'Cancel');
// 2. React updates a tracked TextNode in-place ("Thought for 12s" -> "Thought for 15s")
txtThought.nodeValue = 'Thought for 15s';
observers[0].trigger([{ type: 'characterData', target: txtThought }]);
assert.equal(txtThought.nodeValue, '已思考 15s');
// 3. Hot-switch Light -> Deep without page reload
const deepRes = applyHostI18nInPage(deepPayload, 'boot-1', HOST_I18N_GLOBAL_KEY);
assert.equal(deepRes.applied, true);
assert.equal(txtMcp.nodeValue, '管理 MCP 服务');
assert.equal(txtPluginCount.nodeValue, '已安装 3 个插件');
assert.equal(txtSubagentsMore.nodeValue, '展开其余 3 个子代理');
assert.equal(txtThought.nodeValue, '已思考 15s');
// 4. Collect untranslated UI strings (should pick up "Quantum Hyperdrive Mode", NOT excluded or translated items)
const collected = collectUntranslatedHostUiInPage(HOST_I18N_GLOBAL_KEY);
assert.ok(collected.items.some((item) => item.text === 'Quantum Hyperdrive Mode'));
assert.equal(
collected.items.some((item) => item.text === 'Settings' || item.text === 'Manage MCP Servers'),
false
);
// 5. Dispose restores every single translated text node and attribute losslessly
win[HOST_I18N_GLOBAL_KEY].dispose();
assert.equal(win[HOST_I18N_GLOBAL_KEY], undefined);
assert.equal(txtSettings.nodeValue, ' Settings ');
assert.equal(btnSettings.getAttribute('title'), 'Open Settings');
assert.equal(btnSettings.getAttribute('aria-label'), 'Settings');
assert.equal(txtMcp.nodeValue, 'Manage MCP Servers');
assert.equal(txtThought.nodeValue, 'Thought for 15s');
assert.equal(txtPluginCount.nodeValue, '3 plugins installed');
assert.equal(txtSubagentsMore.nodeValue, 'Show 3 more subagents');
assert.equal(txtSubmitShortcut.nodeValue, 'Submit (Enter)');
assert.equal(txtAcceptAll.nodeValue, 'Accept All');
assert.equal(txtMdTableBtn.nodeValue, 'Copy');
assert.equal(inputEl.getAttribute('placeholder'), 'Ask anything...');
} finally {
globalThis.window = prevWindow;
globalThis.document = prevDocument;
}
});
test('runtime translator handles long (>240 char) & multiline descriptions and scales cleanly across the full zh-CN@2.0.0 catalog', () => {
const { win, doc, body, MockElement, MockText } = createMockDom();
const prevWindow = globalThis.window;
const prevDocument = globalThis.document;
globalThis.window = win;
globalThis.document = doc;
try {
const packObj = JSON.parse(
readFileSync(join(REAL_HOST_I18N_ROOT, 'dist', 'packs', 'zh-CN.json'), 'utf8')
);
const packHash = sha256(JSON.stringify(packObj));
const deepPayload = compileHostI18nRuntimePayload(packObj, 'deep', packHash);
const exactEntries = Object.entries(deepPayload.exact);
const longEntry = exactEntries.find(([k]) => k.length > 240);
assert.ok(longEntry, 'zh-CN@2.0.0 should contain long (>240 char) settings descriptions');
const longP = body.appendChild(new MockElement('p'));
const txtLong = longP.appendChild(new MockText(longEntry[0]));
// Populate a large DOM (1,500 UI text nodes) to verify compile + scan + restore speed
const nodes = [];
for (let i = 0; i < 1500 && i < exactEntries.length; i += 1) {
const span = body.appendChild(new MockElement('span'));
const tn = span.appendChild(new MockText(exactEntries[i][0]));
nodes.push({ tn, orig: exactEntries[i][0] });
}
const t0 = performance.now();
const res = applyHostI18nInPage(deepPayload, 'boot-perf', HOST_I18N_GLOBAL_KEY);
const elapsedMs = performance.now() - t0;
assert.equal(res.applied, true);
assert.equal(txtLong.nodeValue, longEntry[1]);
assert.ok(elapsedMs < 1000, `Expected full pack compile+scan < 1000ms, got ${elapsedMs.toFixed(1)}ms`);
win[HOST_I18N_GLOBAL_KEY].dispose();
assert.equal(txtLong.nodeValue, longEntry[0]);
for (const item of nodes) {
assert.equal(item.tn.nodeValue, item.orig);
}
} finally {
globalThis.window = prevWindow;
globalThis.document = prevDocument;
}
});
// ---------------------------------------------------------------------------
// 4. CDP Bridge integration (Desktop + IDE chat iframe, skip IDE workbench, sidebar independence)
// ---------------------------------------------------------------------------
test('window-bridge injects Host I18n into Desktop & IDE chat iframe, skips IDE workbench, uses lightweight heartbeat, and disposes cleanly', async (t) => {
const homeDir = createTempDir(t);
const devToolsDir = join(homeDir, 'AppData', 'Roaming', 'Antigravity');
mkdirSync(devToolsDir, { recursive: true });
const evaluatedByWs = new Map();
const pageAliveRevision = new Map();
// Mock CDP HTTP /json/list server
const cdpServer = http.createServer((req, res) => {
if (req.url === '/json/list') {
const port = cdpServer.address().port;
const targets = [
{
id: 'desktop-1',
type: 'page',
title: 'Antigravity',
url: 'https://127.0.0.1:45123/c/11111111-1111-1111-1111-111111111111',
webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/page/desktop-1`,
},
{
id: 'ide-wb-1',
type: 'page',
title: 'Antigravity IDE',
url: 'vscode-file://vscode-app/c:/app/workbench.html',
webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/page/ide-wb-1`,
},
{
id: 'ide-chat-1',
parentId: 'ide-wb-1',
type: 'iframe',
title: 'Chat',
url: 'http://127.0.0.1:45124/c/22222222-2222-2222-2222-222222222222?extensionView=true',
webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/page/ide-chat-1`,
},
];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(targets));
return;
}
res.writeHead(404);
res.end();
});
await new Promise((r) => cdpServer.listen(0, '127.0.0.1', r));
t.after(() => cdpServer.close());
const cdpPort = cdpServer.address().port;
writeFileSync(join(devToolsDir, 'DevToolsActivePort'), `${cdpPort}\n/devtools/browser/test\n`);
// Mock WebSocket for CDP Runtime.evaluate
class FakeCdpWebSocket {
constructor(url) {
this.url = url;
this.listeners = new Map();
queueMicrotask(() => this._emit('open', {}));
}
addEventListener(type, fn) {
if (!this.listeners.has(type)) this.listeners.set(type, []);
this.listeners.get(type).push(fn);
}
_emit(type, ev) {
for (const fn of this.listeners.get(type) || []) fn(ev);
}
send(raw) {
const msg = JSON.parse(raw);
const expr = String(msg?.params?.expression || '');
if (!evaluatedByWs.has(this.url)) evaluatedByWs.set(this.url, []);
evaluatedByWs.get(this.url).push(expr);
let value = null;
if (expr.includes('needsApply: true')) {
const revMatch = expr.match(/st\.revision !== ("[^"]+")/);
const rev = revMatch ? JSON.parse(revMatch[1]) : '';
value =
pageAliveRevision.get(this.url) === rev
? { alive: true, needsApply: false, revision: rev, translatedCount: 4 }
: { alive: false, needsApply: true };
} else if (expr.includes('applyHostI18nInPage')) {
const revMatch = expr.match(/"revision":"([^"]+)"/);
if (revMatch) pageAliveRevision.set(this.url, revMatch[1]);
value = { applied: true, translatedCount: 4 };
} else if (expr.includes('disposed: true')) {
pageAliveRevision.delete(this.url);
value = { disposed: true };
} else {
value = { origin: 'https://127.0.0.1:45123', title: 'Antigravity', csrfToken: '', appConfig: null };
}
queueMicrotask(() =>
this._emit('message', {
data: JSON.stringify({ id: msg.id, result: { result: { value } } }),
})
);
}
close() {
this._emit('close', {});
}
}
let active = true;
let payloadBuilds = 0;
const controller = createWindowBridgeController({
handleApiRequest: async () => ({ status: 200, body: '{}' }),
readAssetFn: async () => '',
// Sidebar-only mode! Overlay is OFF, proving Host I18n works independently.
getSettingsFn: () => ({ windowMountMode: 'sidebar', enableWindowOverlay: false }),
getBundleVersionFn: () => 'vtest',
env: { APPDATA: join(homeDir, 'AppData', 'Roaming') },
platform: 'win32',
homeDir,
autoConfigureIdeArgv: false,
WebSocketImpl: FakeCdpWebSocket,
getHostI18nDescriptorFn: () =>
active
? {
active: true,
locale: 'zh-CN',
depth: 'light',
revision: 'zh-CN:light:1.0.0:abcdef123456',
getPayload: () => {
payloadBuilds += 1;
return {
locale: 'zh-CN',
depth: 'light',
revision: 'zh-CN:light:1.0.0:abcdef123456',
exact: { Settings: '设置' },
patterns: [],
};
},
}
: { active: false, revision: '', getPayload: null },
});
// First sync: applies full payload to Desktop + IDE chat iframe, skips IDE workbench
await controller.syncAllWindows();
const desktopUrl = `ws://127.0.0.1:${cdpPort}/devtools/page/desktop-1`;
const ideWbUrl = `ws://127.0.0.1:${cdpPort}/devtools/page/ide-wb-1`;
const ideChatUrl = `ws://127.0.0.1:${cdpPort}/devtools/page/ide-chat-1`;
assert.equal(payloadBuilds, 1, 'Payload should be built once per tick and shared across targets');
assert.ok(
(evaluatedByWs.get(desktopUrl) || []).some((e) => e.includes('applyHostI18nInPage')),
'Desktop window must receive Host I18n apply'
);
assert.ok(
(evaluatedByWs.get(ideChatUrl) || []).some((e) => e.includes('applyHostI18nInPage')),
'IDE extensionView chat iframe must receive Host I18n apply'
);
assert.equal(
(evaluatedByWs.get(ideWbUrl) || []).some((e) => e.includes('applyHostI18nInPage')),
false,
'IDE VS Code workbench shell must NOT receive Host I18n injection'
);
assert.equal(controller.getBridgeStatus().hostI18nAppliedCount, 2);
// Second sync: both targets are alive with matching revision -> lightweight heartbeat only!
await controller.syncAllWindows();
assert.equal(payloadBuilds, 1, 'Heartbeat tick must NOT rebuild or resend full dictionary');
// Turn off Host I18n -> disposes across targets cleanly
active = false;
await controller.notifyHostI18nChanged();
assert.ok((evaluatedByWs.get(desktopUrl) || []).some((e) => e.includes('disposed: true')));
assert.ok((evaluatedByWs.get(ideChatUrl) || []).some((e) => e.includes('disposed: true')));
assert.equal(controller.getBridgeStatus().hostI18nAppliedCount, 0);
await controller.stop();
});
// ---------------------------------------------------------------------------
// 5. API dispatcher contract
// ---------------------------------------------------------------------------
test('dispatchBridgeApiRequest routes GET/POST /api/host-i18n and __hostI18nAction compat channel cleanly', async (t) => {
const dataDir = createTempDir(t);
const localDistDir = join(REAL_HOST_I18N_ROOT, 'dist');
const mgr = createHostI18nPackManager({ dataDir, localSourceDir: localDistDir });
let notifyCount = 0;
const opts = {
hostI18nManager: mgr,
onHostI18nChanged: () => {
notifyCount += 1;
},
collectHostI18nUntranslated: async () => ({
targets: 1,
items: [{ text: 'Experimental Menu', kind: 'text', count: 2 }],
}),
};
const getRes = await dispatchBridgeApiRequest('/api/host-i18n', 'GET', undefined, opts);
assert.equal(getRes.status, 200);
const getBody = JSON.parse(getRes.body);
assert.equal(getBody.ok, true);
assert.equal(getBody.locale, 'off');
assert.ok(getBody.packs.some((p) => p.locale === 'zh-CN'));
const selRes = await dispatchBridgeApiRequest(
'/api/host-i18n',
'POST',
{ action: 'select', locale: 'zh-CN', depth: 'light' },
opts
);
assert.equal(selRes.status, 200);
const selBody = JSON.parse(selRes.body);
assert.equal(selBody.ok, true);
assert.equal(selBody.locale, 'zh-CN');
assert.equal(selBody.depth, 'light');
assert.equal(selBody.active, true);
assert.equal(notifyCount, 1);
const collectRes = await dispatchBridgeApiRequest(
'/api/settings',
'POST',
{ __hostI18nAction: 'collect_untranslated' },
opts
);
assert.equal(collectRes.status, 200);
const collectBody = JSON.parse(collectRes.body);
assert.equal(collectBody.ok, true);
assert.equal(collectBody.count, 1);
assert.deepEqual(collectBody.template, { base: { 'Experimental Menu': '' } });
// Verify unknown action returns 400
const badRes = await handleHostI18nPostAction({ action: 'invalid_op' }, { manager: mgr });
assert.equal(badRes.status, 400);
assert.equal(badRes.payload.ok, false);
});
+4 -1
View File
@@ -32,14 +32,17 @@ test('pack-release-zip ships only runtime-essential files, excludes dev bloat, a
'sidecars/panel/cli-statusline.mjs',
'sidecars/panel/trajectory-metrics.mjs',
'sidecars/panel/backend/api-actions.mjs',
'sidecars/panel/backend/host-i18n/index.mjs',
'sidecars/panel/backend/account-credentials.ps1',
'sidecars/panel/shared/settings-normalization.mjs',
'sidecars/panel/shared/host-i18n-protocol.mjs',
]) {
assert.ok(relFiles.includes(mustHave), `Release whitelist must include ${mustHave}`);
}
// Non-runtime dev/doc/test/preview files must NEVER enter the release ZIP
// Non-runtime dev/doc/test/preview files and standalone repository language packs must NEVER enter the release ZIP
for (const rel of relFiles) {
assert.doesNotMatch(rel, /^host-i18n\//);
assert.doesNotMatch(rel, /^sidecars\/panel\/(?:src|test|scripts)\//);
assert.doesNotMatch(rel, /\.png$/i);
assert.doesNotMatch(rel, /^README/i);
+11 -5
View File
@@ -1472,16 +1472,22 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(structurePane.hasAttribute('hidden'), true);
assert.equal(otherPane.hasAttribute('hidden'), true);
// --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, modernUiSwitch, pluginUpdateMode) ---
// --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, modernUiSwitch, hostI18nDepth, pluginUpdateMode) ---
const generalSegControls = generalPane.querySelectorAll('.segmented');
assert.equal(
generalSegControls.length,
3,
'General tab has Language, FontScale, and Experimental Modern UI segmented controls'
4,
'General tab has Language, FontScale, Experimental Modern UI, and Host I18n depth segmented controls'
);
const langBtns = generalSegControls[0].querySelectorAll('.seg-btn');
const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn');
const modernUiBtns = generalSegControls[2].querySelectorAll('.seg-btn');
const hostI18nDepthBtns = generalSegControls[3].querySelectorAll('.seg-btn');
assert.deepEqual(
hostI18nDepthBtns.map((button) => button.textContent),
['浅度', '深度'],
'Host I18n depth switch has 浅度 / 深度'
);
assert.equal(modernUiBtns.length, 2, 'Modern UI switch has 开启 / 关闭');
assert.equal(modernUiBtns[0].textContent, '开启');
assert.equal(modernUiBtns[1].textContent, '关闭');
@@ -1505,8 +1511,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(langBtns[2].textContent, 'English');
assert.equal(langBtns[1].classList.contains('is-active'), true, 'mockSettings language zh-CN selects index 1');
const generalSelects = generalPane.querySelectorAll('.custom-select');
assert.equal(generalSelects.length, 1, 'General tab has Update Mode select');
const updateModeSelectEl = generalSelects[0];
assert.equal(generalSelects.length, 2, 'General tab has Host I18n Language and Update Mode selects');
const updateModeSelectEl = generalSelects[1];
// Theme accent picker: switch to emerald, verify CSS vars injected on both hosts, then restore host
const swatchBtns = generalPane.querySelectorAll('.theme-swatch-btn');