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
+95 -18
View File
@@ -172,6 +172,42 @@ export function formatElapsedSec(seconds) {
return `${h}h ${remM}m`;
}
/**
* 归一化普通模型显示模式(`'short'` 精简代号 | `'upstream_compact'` 去厂商前缀原始 ID | `'upstream'` 完整原始 ID)。
*
* @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';
}
/**
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
*
* @param {string} rawText
* @returns {string}
*/
export function stripVendorModelPrefix(rawText) {
return String(rawText || '')
.trim()
.replace(/^(?:gemini|claude|gpt)-(?=.+)/i, '');
}
function stripCompactionMarker(rawText) {
return String(rawText || '')
.replace(/(?:·(?:压缩|compact)|\[自动压缩\]|\[auto[- ]?compact\])\s*$/iu, '')
.trim();
}
/**
* 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。
*
@@ -188,17 +224,23 @@ export function normalizeOrchestratorIdDisplayMode(mode) {
* 规则:
* - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`)
* 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`;
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型“精简代号 / 原始模型 ID”切换影响;
* - 其余普通模型继续按 `showUpstreamModel` 与视图选项切换。
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响;
* - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`);
* - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。
*
* @param {object|null|undefined} target
* @param {{ showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
* @param {{ modelDisplayMode?: string, showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
* @param {{ preferLabelInShort?: boolean, fallback?: string }} [options]
* @returns {{ text: string, title: string, isOrchestratorSeries: boolean }}
* @returns {{ text: string, baseText: string, compactionSuffix: string, isCompaction: boolean, title: string, isOrchestratorSeries: boolean }}
*/
export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
const showUpstream =
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
const modelDisplayMode =
typeof settings === 'boolean'
? settings
? 'upstream'
: 'short'
: normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel);
const showUpstream = modelDisplayMode !== 'short';
const orchestratorMode = normalizeOrchestratorIdDisplayMode(
typeof settings === 'object' && settings ? settings.orchestratorIdMode : 'compact'
);
@@ -206,7 +248,14 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
const fallback = options?.fallback ?? t('fmt.unknownModel');
if (!target || typeof target !== 'object') {
return { text: fallback, title: fallback, isOrchestratorSeries: false };
return {
text: fallback,
baseText: fallback,
compactionSuffix: '',
isCompaction: false,
title: fallback,
isOrchestratorSeries: false,
};
}
const shortText = String(
@@ -223,9 +272,12 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
const isCompaction =
Boolean(target.isCompactionStep) ||
/·压缩\s*$/.test(shortText) ||
/·压缩\s*$/.test(upstreamText) ||
/·压缩\s*$/.test(labelText);
/·(?:压缩|compact)\s*$/iu.test(shortText) ||
/·(?:压缩|compact)\s*$/iu.test(upstreamText) ||
/·(?:压缩|compact)\s*$/iu.test(labelText) ||
/\[自动压缩\]\s*$/u.test(labelText);
const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : '';
const combined = `${modelKeyText} ${shortText} ${labelText} ${upstreamText} ${responseText}`;
const isOrchWorker =
@@ -248,27 +300,50 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
compactId = 'orchestrator-argon';
fullId = 'gemini-pro-orchestrator-argon (argon-4)';
}
const suffix = isCompaction ? '·压缩' : '';
const text = `${orchestratorMode === 'full' ? fullId : compactId}${suffix}`;
const baseText = orchestratorMode === 'full' ? fullId : compactId;
const text = `${baseText}${compactionSuffix}`;
const multiUpstream =
Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
? target.upstreamModels.join(' / ')
: '';
const title = multiUpstream || `${fullId}${suffix}`;
return { text, title, isOrchestratorSeries: true };
const title = multiUpstream || `${fullId}${compactionSuffix}`;
return {
text,
baseText,
compactionSuffix,
isCompaction,
title,
isOrchestratorSeries: true,
};
}
const standardText =
const rawSelected =
(showUpstream
? upstreamText || responseText || shortText || labelText
: preferLabelInShort
? labelText || shortText
: shortText || labelText) || fallback;
const cleanRawBase = stripCompactionMarker(rawSelected) || fallback;
const baseText =
modelDisplayMode === 'upstream_compact'
? stripVendorModelPrefix(cleanRawBase) || cleanRawBase
: cleanRawBase;
const text = `${baseText}${compactionSuffix}`;
const fullUpstreamWithSuffix = `${cleanRawBase}${compactionSuffix}`;
const standardTitle =
showUpstream && Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
? target.upstreamModels.join(' / ')
: standardText;
return { text: standardText, title: standardTitle, isOrchestratorSeries: false };
: showUpstream
? fullUpstreamWithSuffix
: text;
return {
text,
baseText,
compactionSuffix,
isCompaction,
title: standardTitle,
isOrchestratorSeries: false,
};
}
/**
@@ -284,7 +359,9 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
export function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
if (!Array.isArray(models) || models.length === 0) return [];
const showUpstream =
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
typeof settings === 'boolean'
? settings
: normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel) !== 'short';
const byDisplay = new Map();
for (const m of models) {
+63 -28
View File
@@ -118,7 +118,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs })
});
}
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 8000 } = {}) {
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
const upperMethod = method.toUpperCase();
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
@@ -138,43 +138,27 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
signal = requestController.signal;
}
const runRequest = async () => {
const execHttpOnce = async (activeBridge) => {
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
const fetchFn = sidecar?.fetch
? sidecar.fetch.bind(sidecar)
: typeof window !== 'undefined' && typeof window.fetch === 'function'
? window.fetch.bind(window)
: globalThis.fetch.bind(globalThis);
const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path;
const requestUrl = activeBridge ? `http://127.0.0.1:${activeBridge.port}${path}` : path;
const headers = {};
if (body !== undefined || !bridge) {
if (body !== undefined || !activeBridge) {
headers['Content-Type'] = 'application/json';
}
if (bridge) {
headers['X-Usage-Monitor-Token'] = bridge.token;
if (bridge.transportMode === 'cdp') {
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
}
let res;
try {
res = await fetchFn(requestUrl, {
method: upperMethod,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal,
});
} catch (fetchErr) {
if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') {
throw fetchErr;
}
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
bridge.transportMode = 'cdp';
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
if (activeBridge) {
headers['X-Usage-Monitor-Token'] = activeBridge.token;
}
const res = await fetchFn(requestUrl, {
method: upperMethod,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal,
});
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
abortErr.name = 'AbortError';
@@ -189,9 +173,60 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
if (!res.ok) {
throw new Error(data.error || `HTTP ${res.status}`);
}
if (activeBridge) {
activeBridge.transportMode = 'http';
}
return data;
};
const fallbackViaCdpWithRecovery = async (initialBridge) => {
initialBridge.transportMode = 'cdp';
try {
return await callViaCdpBridge(initialBridge, path, {
method: upperMethod,
body,
signal,
cdpTimeoutMs,
});
} catch (cdpErr) {
if (signal?.aborted || cdpErr?.name === 'AbortError') {
throw cdpErr;
}
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次
const latestBridge = getWindowBridgeConfig() || initialBridge;
latestBridge.transportMode = 'http';
return execHttpOnce(latestBridge);
}
};
const runRequest = async () => {
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
if (bridge && bridge.transportMode === 'cdp') {
return fallbackViaCdpWithRecovery(bridge);
}
try {
return await execHttpOnce(bridge);
} catch (fetchErr) {
if (signal?.aborted || fetchErr?.name === 'AbortError') {
throw fetchErr;
}
if (!bridge) {
// 辅助栏 Webview 在 Worker 热替换瞬间若有极短暂波动,延迟 180ms 自动无感重试一次
if (upperMethod === 'GET') {
await new Promise((r) => setTimeout(r, 180));
if (!signal?.aborted) {
return execHttpOnce(null);
}
}
throw fetchErr;
}
// 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道
return fallbackViaCdpWithRecovery(bridge);
}
};
const promise = runRequest().finally(() => {
if (dedupKey) {
inFlightGets.delete(dedupKey);