feat(panel): add worker hot-reload, sticky bridge lease, custom token combos, trimmed model IDs, and adaptive popover width

- Isolate SidecarApp /api/* backend runtime inside a hot-swappable Worker thread (sidecar-worker.mjs) with 3s disk-drift detection and queued request handoff so live plugin updates never drop the host-assigned SidecarApp port
- Persist and reuse sticky loopback bridge port/token leases across bridge-daemon and worker reloads, pre-bind the bridge server on boot, allow /api/cache/rebuild on the bridge, and self-heal poisoned CDP fallback states back to HTTP
- Add billing-aligned In / Out / Cache (tokens_io_cache) preset with per-segment USD hover breakdown and custom format DSL (tokens_custom + stepTokenComboFormat, e.g. context:new:cache, in:out:cache)
- Add 3-way model name format (short / upstream / upstream_compact) stripping gemini-, claude-, and gpt- prefixes while protecting compaction suffixes from ellipsis truncation
- Add adaptive content-fit popover width (auto up to viewport bounds on wide step tables) alongside custom fixed width (440-1080 px)
This commit is contained in:
fish
2026-11-16 16:55:56 +09:00
parent cd841b55cf
commit 3b36ade911
33 changed files with 3124 additions and 381 deletions
+22 -8
View File
@@ -22,6 +22,7 @@ import {
loadSettings,
lsRuntimeEndpoint,
normalizeFullSettings,
normalizeModelDisplayMode,
normalizePluginUpdateMode,
normalizeWindowMountMode,
saveJson,
@@ -38,6 +39,7 @@ import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
import {
performPluginUpdate,
scheduleSidecarRestart,
setSidecarRestartHandler,
syncCloudCatalog,
} from './plugin-updater.mjs';
import { getCloudStatus } from './pricing-catalog.mjs';
@@ -124,19 +126,19 @@ function projectDisplayStep(st) {
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
isRootLatestTurn, rootTurnPrompt,
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
} = st;
return {
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
isRootLatestTurn, rootTurnPrompt,
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
};
}
@@ -288,6 +290,14 @@ export function executeSettingsAction(data) {
: 'dual'
: 'sidebar'
: normalizeWindowMountMode(current.windowMountMode, current.enableWindowOverlay);
const nextModelDisplayMode =
payload.modelDisplayMode !== undefined
? normalizeModelDisplayMode(payload.modelDisplayMode)
: typeof payload.showUpstreamModel === 'boolean'
? payload.showUpstreamModel
? 'upstream'
: 'short'
: normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel);
const updated = normalizeFullSettings({
...current,
...payload,
@@ -300,6 +310,7 @@ export function executeSettingsAction(data) {
payload.weeklyCostBudget,
current.weeklyCostBudget
),
modelDisplayMode: nextModelDisplayMode,
pluginUpdateMode: nextPluginUpdateMode,
windowMountMode: nextWindowMountMode,
});
@@ -528,6 +539,9 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
const triggerRestart =
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
if (typeof onRestart === 'function') {
setSidecarRestartHandler(onRestart);
}
if (lsRuntimeEndpoint.baseUrl) {
syncCloudCatalog({ force: false }).catch(() => {});
+23 -1
View File
@@ -18,16 +18,22 @@ import {
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
DEFAULT_POPOVER_WIDTH,
DEFAULT_SETTINGS_SCHEMA,
DEFAULT_STEP_TABLE_COLUMNS,
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
DEFAULT_TOPBAR_SLOTS,
FONT_SCALE_KEYS,
MAX_POPOVER_WIDTH,
MAX_TOPBAR_SLOTS,
MIN_POPOVER_WIDTH,
MIN_TOPBAR_SLOTS,
MODEL_DISPLAY_MODES,
ORCHESTRATOR_ID_MODES,
OVERVIEW_METRIC_KEYS,
OVERVIEW_MODULE_KEYS,
PLUGIN_UPDATE_MODES,
POPOVER_WIDTH_MODES,
STEP_TABLE_COLUMN_KEYS,
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
@@ -38,32 +44,43 @@ import {
normalizeFullSettings,
normalizeHoverModules,
normalizeLanguageSetting,
normalizeModelDisplayMode,
normalizeOrchestratorIdMode,
normalizeOverviewMetrics,
normalizeOverviewModules,
normalizePluginUpdateMode,
normalizePopoverWidth,
normalizePopoverWidthMode,
normalizeStandalonePort,
normalizeStepTableColumns,
normalizeStepTokenComboFormat,
normalizeThemeAccent,
normalizeTopbarCapsuleSlots,
normalizeWeeklyLimitMode,
normalizeWindowMountMode,
parseStepTokenComboSegments,
} from './settings-schema.mjs';
export {
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
DEFAULT_POPOVER_WIDTH,
DEFAULT_SETTINGS_SCHEMA,
DEFAULT_STEP_TABLE_COLUMNS,
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
DEFAULT_TOPBAR_SLOTS,
FONT_SCALE_KEYS,
MAX_POPOVER_WIDTH,
MAX_TOPBAR_SLOTS,
MIN_POPOVER_WIDTH,
MIN_TOPBAR_SLOTS,
MODEL_DISPLAY_MODES,
ORCHESTRATOR_ID_MODES,
OVERVIEW_METRIC_KEYS,
OVERVIEW_MODULE_KEYS,
PLUGIN_UPDATE_MODES,
POPOVER_WIDTH_MODES,
STEP_TABLE_COLUMN_KEYS,
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
@@ -74,16 +91,21 @@ export {
normalizeFullSettings,
normalizeHoverModules,
normalizeLanguageSetting,
normalizeModelDisplayMode,
normalizeOrchestratorIdMode,
normalizeOverviewMetrics,
normalizeOverviewModules,
normalizePluginUpdateMode,
normalizePopoverWidth,
normalizePopoverWidthMode,
normalizeStandalonePort,
normalizeStepTableColumns,
normalizeStepTokenComboFormat,
normalizeThemeAccent,
normalizeTopbarCapsuleSlots,
normalizeWeeklyLimitMode,
normalizeWindowMountMode,
parseStepTokenComboSegments,
} from './settings-schema.mjs';
/**
@@ -292,7 +314,7 @@ export function loadJson(filePath, fallback) {
*/
export function saveJson(filePath, data) {
try {
mkdirSync(DATA_DIR, { recursive: true });
mkdirSync(dirname(filePath), { recursive: true });
if (filePath === CACHE_FILE) {
writeTrajectoryCacheFile(filePath, data);
} else {
+26 -2
View File
@@ -72,15 +72,39 @@ function runExecFile(cmd, args, opts = {}) {
});
}
let customSidecarRestartHandler = null;
/**
* 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。
* 注册自定义运行时热重载回调(例如 `main.mjs` 的 `Worker` 热替换或 `bridge-daemon.mjs` 的平滑退出),
* 避免直接调用 `process.exit(0)` 导致宿主 `SidecarApp` 固定端口失联。
*
* @param {(() => void)|null} handler
*/
export function setSidecarRestartHandler(handler) {
customSidecarRestartHandler = typeof handler === 'function' ? handler : null;
}
/**
* 更新完成后调度 Sidecar 运行时热重载(若未注册自定义处理器,则回退平滑退出供父监督器拉起)。
* 在单元测试环境(`!LS_ADDR || LS_ADDR === 'test.invalid'`)下自动跳过。
*
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
*/
export function scheduleSidecarRestart(delayMs = 350) {
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
if (!activeAddr || activeAddr === 'test.invalid' || typeof process?.exit !== 'function') return;
if (!activeAddr || activeAddr === 'test.invalid') return;
if (typeof customSidecarRestartHandler === 'function') {
const fn = customSidecarRestartHandler;
setTimeout(() => {
try {
fn();
} catch {
// 忽略自定义热重载回调异常
}
}, delayMs);
return;
}
if (typeof process?.exit !== 'function') return;
setTimeout(() => {
try {
process.exit(0);
+142 -1
View File
@@ -84,6 +84,8 @@ export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
'ttft',
'duration',
'tokens_combo',
'tokens_io_cache',
'tokens_custom',
'input_tokens',
'cache_tokens',
'output_tokens',
@@ -101,12 +103,57 @@ export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
'cost',
]);
export const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
context: 'context',
ctx: 'context',
'上下文': 'context',
in: 'in',
new: 'in',
input: 'in',
'输入': 'in',
'新输入': 'in',
out: 'out',
output: 'out',
'输出': 'out',
'总输出': 'out',
cache: 'cache',
cached: 'cache',
cache_read: 'cache',
cacheread: 'cache',
'缓存': 'cache',
'缓存读': 'cache',
think: 'think',
thinking: 'think',
'思考': 'think',
reply: 'reply',
body: 'reply',
resp: 'reply',
response: 'reply',
text: 'reply',
'正文': 'reply',
'回复': 'reply',
total: 'total',
all: 'total',
sum: 'total',
'总计': 'total',
'总token': 'total',
});
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
export const MODEL_DISPLAY_MODES = Object.freeze(['short', 'upstream', 'upstream_compact']);
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
export const MIN_POPOVER_WIDTH = 440;
export const MAX_POPOVER_WIDTH = 1080;
export const DEFAULT_POPOVER_WIDTH = 580;
function isSchemaPlainObject(v) {
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
}
@@ -171,6 +218,25 @@ export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
return 'dual';
}
/**
* 归一化模型名称展示模式(`'short'` 精简代号 | `'upstream_compact'` 去前缀原始 ID | `'upstream'` 完整原始 ID),
* 兼容历史 `showUpstreamModel` 布尔开关,默认 `'short'`。
*
* @param {unknown} mode
* @param {unknown} [legacyShowUpstream]
* @returns {'short'|'upstream_compact'|'upstream'}
*/
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
const m = String(mode ?? '').trim().toLowerCase();
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
return 'upstream_compact';
}
if (m === 'short') return 'short';
if (legacyShowUpstream === true) return 'upstream';
return 'short';
}
/**
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
*
@@ -182,6 +248,65 @@ export function normalizeOrchestratorIdMode(mode) {
return m === 'full' ? 'full' : 'compact';
}
/**
* 归一化悬浮主面板宽度模式(`'auto'` 自适应内容宽度 | `'custom'` 指定像素宽度,默认 `'auto'`)。
*
* @param {unknown} mode
* @returns {'auto'|'custom'}
*/
export function normalizePopoverWidthMode(mode) {
const m = String(mode ?? '').trim().toLowerCase();
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
}
/**
* 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。
*
* @param {unknown} width
* @returns {number}
*/
export function normalizePopoverWidth(width) {
const num = Number(width);
if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH;
return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num)));
}
/**
* 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。
*
* @param {unknown} raw
* @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>}
*/
export function parseStepTokenComboSegments(raw) {
const str = String(raw ?? '').trim();
const out = [];
const seen = new Set();
if (str) {
for (const part of str.split(/[:/,|]+/)) {
const key = part.trim().toLowerCase();
if (!key) continue;
const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key)
? STEP_TOKEN_SEGMENT_ALIASES[key]
: null;
if (!mapped || seen.has(mapped)) continue;
seen.add(mapped);
out.push(/** @type {any} */ (mapped));
if (out.length >= 4) break;
}
}
return out.length > 0 ? out : ['context', 'in', 'cache'];
}
/**
* 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。
*
* @param {unknown} raw
* @returns {string}
*/
export function normalizeStepTokenComboFormat(raw) {
return parseStepTokenComboSegments(raw).join(':');
}
/**
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
*
@@ -362,12 +487,15 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
weeklyTokenBudget: 150000000,
weeklyCostBudget: 100,
weeklyLimitMode: 'official',
modelDisplayMode: 'short',
showUpstreamModel: false,
orchestratorIdMode: 'compact',
pluginUpdateMode: 'manual',
autoUpdatePlugin: false,
windowMountMode: 'dual',
enableWindowOverlay: true,
popoverWidthMode: 'auto',
popoverWidth: DEFAULT_POPOVER_WIDTH,
enableCliStatusLine: true,
standalonePort: 0,
showTopbarMultiSession: true,
@@ -378,6 +506,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
showStepTurnRail: false,
showStepAgentBadge: true,
showStepSpeedColor: false,
stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT,
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
modelContextWindows: Object.freeze({}),
});
@@ -393,12 +522,15 @@ export function createDefaultSettingsObject() {
weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget,
weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget,
weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode,
modelDisplayMode: DEFAULT_SETTINGS_SCHEMA.modelDisplayMode,
showUpstreamModel: DEFAULT_SETTINGS_SCHEMA.showUpstreamModel,
orchestratorIdMode: DEFAULT_SETTINGS_SCHEMA.orchestratorIdMode,
pluginUpdateMode: DEFAULT_SETTINGS_SCHEMA.pluginUpdateMode,
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
popoverWidthMode: DEFAULT_SETTINGS_SCHEMA.popoverWidthMode,
popoverWidth: DEFAULT_SETTINGS_SCHEMA.popoverWidth,
enableCliStatusLine: DEFAULT_SETTINGS_SCHEMA.enableCliStatusLine,
standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort,
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
@@ -409,6 +541,7 @@ export function createDefaultSettingsObject() {
showStepTurnRail: DEFAULT_SETTINGS_SCHEMA.showStepTurnRail,
showStepAgentBadge: DEFAULT_SETTINGS_SCHEMA.showStepAgentBadge,
showStepSpeedColor: DEFAULT_SETTINGS_SCHEMA.showStepSpeedColor,
stepTokenComboFormat: DEFAULT_SETTINGS_SCHEMA.stepTokenComboFormat,
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
modelContextWindows: {},
};
@@ -429,6 +562,10 @@ export function normalizeFullSettings(rawInput) {
safeRaw.windowMountMode,
safeRaw.enableWindowOverlay
);
const modelDisplayMode = normalizeModelDisplayMode(
safeRaw.modelDisplayMode,
safeRaw.showUpstreamModel
);
return {
language: normalizeLanguageSetting(safeRaw.language),
themeAccent: normalizeThemeAccent(safeRaw.themeAccent),
@@ -442,12 +579,15 @@ export function normalizeFullSettings(rawInput) {
DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget
),
weeklyLimitMode: normalizeWeeklyLimitMode(safeRaw.weeklyLimitMode),
showUpstreamModel: safeRaw.showUpstreamModel === true,
modelDisplayMode,
showUpstreamModel: modelDisplayMode !== 'short',
orchestratorIdMode: normalizeOrchestratorIdMode(safeRaw.orchestratorIdMode),
pluginUpdateMode,
autoUpdatePlugin: pluginUpdateMode === 'auto',
windowMountMode,
enableWindowOverlay: windowMountMode !== 'sidebar',
popoverWidthMode: normalizePopoverWidthMode(safeRaw.popoverWidthMode),
popoverWidth: normalizePopoverWidth(safeRaw.popoverWidth),
enableCliStatusLine: safeRaw.enableCliStatusLine !== false,
standalonePort: normalizeStandalonePort(safeRaw.standalonePort),
showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false,
@@ -458,6 +598,7 @@ export function normalizeFullSettings(rawInput) {
showStepTurnRail: safeRaw.showStepTurnRail === true,
showStepAgentBadge: safeRaw.showStepAgentBadge !== false,
showStepSpeedColor: safeRaw.showStepSpeedColor === true,
stepTokenComboFormat: normalizeStepTokenComboFormat(safeRaw.stepTokenComboFormat),
stepTableColumns: normalizeStepTableColumns(safeRaw.stepTableColumns),
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
};
+103
View File
@@ -0,0 +1,103 @@
/**
* @fileoverview Hot-reloadable backend Worker runtime (`sidecar-worker.mjs`) for `main.mjs`.
*
* Isolates all ESM backend modules (`api-actions.mjs`, `telemetry-builder.mjs`, `window-bridge.mjs`,
* `pricing-catalog.mjs`, etc.) inside a dedicated V8 Worker isolate so plugin updates (in-app Git/ZIP
* or external file overwrite while Antigravity is open) can tear down and respawn a fresh Worker
* without ever exiting the parent `SidecarApp` process or losing its host-assigned HTTP port.
*/
import { parentPort } from 'node:worker_threads';
import {
bootBundleVersion,
bootWindowBridgeRuntime,
dispatchBridgeApiRequest,
} from './api-actions.mjs';
import { computeRuntimeCodeVersion } from './config.mjs';
let shuttingDown = false;
let reloadRequested = false;
function requestWorkerReload() {
if (shuttingDown || reloadRequested) return;
reloadRequested = true;
try {
parentPort?.postMessage({ type: 'reload_request' });
} catch {
// Ignore postMessage errors if parent is already closing
}
}
const bridgeController = bootWindowBridgeRuntime({
allowDynamicLs: true,
onRestart: requestWorkerReload,
});
const driftWatchTimer = setInterval(() => {
if (shuttingDown || reloadRequested) return;
try {
const diskVersion = String(computeRuntimeCodeVersion() || '');
if (bootBundleVersion && diskVersion && diskVersion !== String(bootBundleVersion)) {
requestWorkerReload();
}
} catch {
// Ignore transient file stat errors while files are being overwritten
}
}, 3000);
driftWatchTimer.unref?.();
async function gracefulStop() {
if (shuttingDown) return;
shuttingDown = true;
clearInterval(driftWatchTimer);
try {
await bridgeController?.stop?.({ disposeWindows: false });
} catch {
// Ignore shutdown errors
}
}
parentPort?.on('message', async (msg) => {
if (!msg || typeof msg !== 'object') return;
if (msg.type === 'shutdown') {
await gracefulStop();
try {
parentPort?.postMessage({ type: 'shutdown_ack', id: msg.id });
} catch {
// Ignore closed channel
}
return;
}
if (msg.type === 'api') {
const reqId = msg.id;
try {
const out = await dispatchBridgeApiRequest(
String(msg.pathname || ''),
String(msg.method || 'GET'),
msg.data,
{ onRestart: requestWorkerReload }
);
parentPort?.postMessage({
type: 'api_result',
id: reqId,
ok: true,
response: {
status: out?.status || 200,
contentType: out?.contentType || 'application/json',
headers: out?.headers || { 'Cache-Control': 'no-store' },
body: typeof out?.body === 'string' ? out.body : JSON.stringify(out?.body ?? {}),
},
});
} catch (err) {
parentPort?.postMessage({
type: 'api_result',
id: reqId,
ok: false,
error: err?.message || 'Worker API execution failed',
});
}
}
});
parentPort?.postMessage({ type: 'ready', bundleVersion: bootBundleVersion });
+57 -8
View File
@@ -29,6 +29,7 @@ const ALLOWED_BRIDGE_PATHS = new Set([
'/api/telemetry',
'/api/settings',
'/api/settings/reset',
'/api/cache/rebuild',
'/api/accounts',
'/api/accounts/update',
'/api/context-window',
@@ -789,8 +790,13 @@ export function createWindowBridgeController(options) {
}
serverStartPromise = (async () => {
const { http, crypto } = await loadNodeDeps();
const persistedLease = leaseFilePath ? loadJson(leaseFilePath, null) : null;
const persistedToken = String(persistedLease?.bridgeToken || '').trim();
const persistedPort = Number(persistedLease?.bridgePort || 0);
if (!bridgeToken) {
bridgeToken = crypto.randomBytes(32).toString('hex');
bridgeToken = /^[0-9a-f]{64}$/i.test(persistedToken)
? persistedToken
: crypto.randomBytes(32).toString('hex');
}
const srv = http.createServer((req, res) => {
@@ -915,17 +921,47 @@ export function createWindowBridgeController(options) {
});
});
await new Promise((resolve, reject) => {
srv.once('error', reject);
srv.listen(0, '127.0.0.1', () => {
srv.removeListener('error', reject);
resolve();
const listenOnLoopback = (targetPort) =>
new Promise((resolve, reject) => {
const onErr = (err) => {
srv.removeListener('listening', onListening);
reject(err);
};
const onListening = () => {
srv.removeListener('error', onErr);
resolve();
};
srv.once('error', onErr);
srv.once('listening', onListening);
srv.listen(targetPort, '127.0.0.1');
});
});
const preferredPort =
Number.isInteger(persistedPort) && persistedPort >= 1024 && persistedPort <= 65535
? persistedPort
: 0;
if (preferredPort > 0) {
try {
await listenOnLoopback(preferredPort);
} catch {
await listenOnLoopback(0);
}
} else {
await listenOnLoopback(0);
}
srv.unref?.();
const addr = srv.address();
bridgePort = typeof addr === 'object' && addr ? Number(addr.port || 0) : 0;
server = srv;
if (leaseFilePath && bridgePort > 0) {
saveJson(leaseFilePath, {
pid: process.pid,
bundleVersion: String(getBundleVersionFn() || ''),
bridgePort,
bridgeToken,
updatedAtMs: Date.now(),
});
}
return { port: bridgePort, token: bridgeToken };
})().finally(() => {
serverStartPromise = null;
@@ -1133,6 +1169,8 @@ export function createWindowBridgeController(options) {
saveJson(leaseFilePath, {
pid: process.pid,
bundleVersion,
bridgePort: bridgePort > 0 ? bridgePort : Number(lease?.bridgePort || 0) || undefined,
bridgeToken: bridgeToken || String(lease?.bridgeToken || '') || undefined,
updatedAtMs: Date.now(),
});
}
@@ -1462,6 +1500,17 @@ export function createWindowBridgeController(options) {
if (initialTimer) clearTimeout(initialTimer);
if (pollTimer) clearTimeout(pollTimer);
if (leaseFilePath) {
const curSettings = getSettingsFn() || {};
const mountMode = normalizeWindowMountMode(
curSettings.windowMountMode,
curSettings.enableWindowOverlay
);
if (curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar') {
ensureBridgeServer().catch(() => {});
}
}
initialTimer = setTimeout(() => {
initialTimer = null;
syncAllWindows()
@@ -1469,7 +1518,7 @@ export function createWindowBridgeController(options) {
.finally(() => {
scheduleNextPoll();
});
}, 350);
}, 120);
initialTimer.unref?.();
}