feat(panel): dual-mount topbar capsule, live multi-session HUD, and customizable topbar metrics (v1.4.3)

This commit is contained in:
fish
2026-11-11 17:31:42 +09:00
parent d60a3cde9b
commit e1da514515
56 changed files with 13389 additions and 3679 deletions
+8 -30
View File
@@ -8,15 +8,6 @@ export function defineComponent({ name, setup }) {
return function createInstance(initialProps = {}) {
let props = { ...initialProps };
const cleanups = [];
const eventHandlers = new Map();
function on(event, fn) {
if (!eventHandlers.has(event)) {
eventHandlers.set(event, new Set());
}
eventHandlers.get(event).add(fn);
return () => eventHandlers.get(event)?.delete(fn);
}
function emit(event, payload) {
// Support Vue-style onUpdateModelValue / onChange prop callbacks
@@ -28,12 +19,6 @@ export function defineComponent({ name, setup }) {
props.onChange(payload);
}
}
const handlers = eventHandlers.get(event);
if (handlers) {
for (const fn of handlers) {
fn(payload);
}
}
}
function onCleanup(fn) {
@@ -42,15 +27,11 @@ export function defineComponent({ name, setup }) {
}
}
const setupResult = setup({
getProps: () => props,
emit,
onCleanup,
});
let setupResult = null;
function setProps(nextProps = {}) {
props = { ...props, ...nextProps };
if (typeof setupResult.onPropsChange === 'function') {
if (setupResult && typeof setupResult.onPropsChange === 'function') {
setupResult.onPropsChange(props);
}
}
@@ -59,11 +40,12 @@ export function defineComponent({ name, setup }) {
setProps({ modelValue: nextValue });
}
function getValue() {
return typeof setupResult.getValue === 'function'
? setupResult.getValue()
: props.modelValue;
}
setupResult = setup({
getProps: () => props,
setProps,
emit,
onCleanup,
});
function destroy() {
for (const fn of cleanups.splice(0)) {
@@ -73,7 +55,6 @@ export function defineComponent({ name, setup }) {
console.error(`[${name}] cleanup error:`, err);
}
}
eventHandlers.clear();
if (setupResult.el?.parentNode) {
setupResult.el.parentNode.removeChild(setupResult.el);
}
@@ -83,11 +64,8 @@ export function defineComponent({ name, setup }) {
name,
el: setupResult.el,
refs: setupResult.refs || {},
on,
emit,
setProps,
setValue,
getValue,
destroy,
...setupResult.methods,
};
+49 -13
View File
@@ -53,18 +53,28 @@ export function patchText(el, nextValue) {
export function patchAttr(el, attrName, nextValue) {
if (!el) return false;
if (nextValue === null || nextValue === undefined || nextValue === false) {
if (!el.hasAttribute(attrName)) {
return false;
let mutated = false;
if (el.hasAttribute(attrName)) {
el.removeAttribute(attrName);
mutated = true;
}
el.removeAttribute(attrName);
return true;
if (attrName === 'value' && 'value' in el && el.value !== '') {
el.value = '';
mutated = true;
}
return mutated;
}
const strVal = nextValue === true ? '' : String(nextValue);
if (el.getAttribute(attrName) === strVal) {
return false;
let mutated = false;
if (el.getAttribute(attrName) !== strVal) {
el.setAttribute(attrName, strVal);
mutated = true;
}
el.setAttribute(attrName, strVal);
return true;
if (attrName === 'value' && 'value' in el && el.value !== strVal) {
el.value = strVal;
mutated = true;
}
return mutated;
}
export function patchClasses(el, classMap) {
@@ -72,11 +82,14 @@ export function patchClasses(el, classMap) {
let mutated = false;
for (const [cls, active] of Object.entries(classMap)) {
if (!cls) continue;
const has = el.classList.contains(cls);
const shouldHave = Boolean(active);
if (has !== shouldHave) {
el.classList.toggle(cls, shouldHave);
mutated = true;
const tokens = String(cls).split(/\s+/).filter(Boolean);
for (const tok of tokens) {
const has = el.classList.contains(tok);
if (has !== shouldHave) {
el.classList.toggle(tok, shouldHave);
mutated = true;
}
}
}
return mutated;
@@ -93,6 +106,25 @@ export function patchStyleVar(el, varName, nextValue) {
return true;
}
/**
* 判断事件是否发生在目标节点内部(兼容 Shadow DOM 的 `composedPath()` 穿透)。
*
* @param {Event|null|undefined} event
* @param {Node|null|undefined} element
* @returns {boolean}
*/
export function isEventInside(event, element) {
if (!event || !element) return false;
if (typeof event.composedPath === 'function') {
const path = event.composedPath();
if (Array.isArray(path) && path.includes(element)) {
return true;
}
}
const target = event.target;
return Boolean(target && typeof element.contains === 'function' && element.contains(target));
}
const keyedListState = new WeakMap();
/**
@@ -108,11 +140,15 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
}
const nextKeys = new Set();
const seenInPass = new Map();
const orderedNodes = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const key = String(keyFn(item, i));
const rawKey = String(keyFn(item, i));
const dupIdx = seenInPass.get(rawKey) || 0;
seenInPass.set(rawKey, dupIdx + 1);
const key = dupIdx === 0 ? rawKey : `${rawKey}__dup_${dupIdx}`;
const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item);
nextKeys.add(key);
+8 -6
View File
@@ -37,15 +37,15 @@ export function formatDateSpanBadge(startMs, endMs) {
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
}
export function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) {
export function formatUsd(amount, { precise = false, unpricedCalls = 0, compactPending = false } = {}) {
if (amount == null || !Number.isFinite(Number(amount))) return '待定';
const val = Number(amount || 0);
const prefix = estimated ? '≈$' : '$';
const suffix = unpricedCalls > 0 ? ' + 待定' : '';
const suffix = unpricedCalls > 0 ? (compactPending ? '+' : ' + 待定') : '';
if (precise) {
return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix;
if (val > 0 && val < 0.001) return `<$0.001${suffix}`;
return (val >= 1 ? `$${val.toFixed(2)}` : `$${val.toFixed(3)}`) + suffix;
}
return `${prefix}${val.toFixed(2)}${suffix}`;
return `$${val.toFixed(2)}${suffix}`;
}
export function speedReasonText(reason) {
@@ -53,6 +53,7 @@ export function speedReasonText(reason) {
incomplete_or_invalid_timing: '生成未完成',
invalid_output_tokens: '无有效输出',
inconsistent_timing: '耗时数据异常',
short_timing: '耗时过短 (<0.5s)',
legacy_cache: '旧版缓存记录',
})[reason] || '';
}
@@ -66,9 +67,10 @@ export function sampleSummary(summary) {
export function formatCountdown(isoTime, nowMs = Date.now()) {
if (!isoTime) return '未知重置时间';
const targetMs = Date.parse(isoTime);
if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间';
if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间';
const diffMs = targetMs - nowMs;
if (diffMs <= 0) return '即将重置';
if (diffMs < 60_000) return '<1分钟后重置';
const totalMinutes = Math.floor(diffMs / 60000);
const days = Math.floor(totalMinutes / (60 * 24));
+145 -8
View File
@@ -1,11 +1,123 @@
/**
* @fileoverview Async HTTP client with AbortController cancellation for stale
* polling requests and concurrent GET deduplication.
* polling requests, concurrent GET deduplication, and dual-mode transport
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
*/
const inFlightGets = new Map();
const activeControllers = new Map();
/**
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
*
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
*/
export function getWindowBridgeConfig() {
if (typeof window === 'undefined') return null;
const br = window.__AGUsageMonitorBridge;
const port = Number(br?.port || 0);
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
return br;
}
return null;
}
/**
* 判断当前脚本是否以双栖悬浮模式运行在宿主主聊天窗口内(而非右侧辅助栏 Webview)。
*
* @returns {boolean}
*/
export function isWindowOverlayMode() {
if (typeof window === 'undefined') return false;
if (window.sidecar?.fetch) return false;
return Boolean(getWindowBridgeConfig());
}
/**
* 接收 Sidecar 通过 CDP `Runtime.evaluate` 批量投递的 RPC 响应,完成因 CSP/代理解除 HTTP 直连时的兜底请求。
*
* @param {Array<{ id: string, ok: boolean, status?: number, data?: any, error?: string }>} responses
* @returns {number}
*/
export function deliverCdpBridgeResponses(responses) {
const br = getWindowBridgeConfig();
if (!br || !(br.rpcPending instanceof Map) || !Array.isArray(responses)) return 0;
let delivered = 0;
for (const item of responses) {
const entry = br.rpcPending.get(item?.id);
if (!entry) continue;
br.rpcPending.delete(item.id);
delivered += 1;
if (item.ok) {
entry.resolve(item.data);
} else {
entry.reject(new Error(item.error || `HTTP ${item.status || 500}`));
}
}
return delivered;
}
function callViaCdpBridge(bridge, path, { method, body, signal }) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
abortErr.name = 'AbortError';
reject(abortErr);
return;
}
if (!Array.isArray(bridge.rpcQueue)) bridge.rpcQueue = [];
if (!(bridge.rpcPending instanceof Map)) bridge.rpcPending = new Map();
const reqId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
const cleanupQueueItem = () => {
if (!Array.isArray(bridge.rpcQueue)) return;
const idx = bridge.rpcQueue.findIndex((item) => item?.id === reqId);
if (idx >= 0) bridge.rpcQueue.splice(idx, 1);
};
const timeoutId = setTimeout(() => {
bridge.rpcPending.delete(reqId);
cleanupQueueItem();
reject(new Error('CDP bridge timeout'));
}, 8000);
const onAbort = () => {
clearTimeout(timeoutId);
bridge.rpcPending.delete(reqId);
cleanupQueueItem();
const abortErr = new Error('Request aborted');
abortErr.name = 'AbortError';
reject(abortErr);
};
if (signal) {
signal.addEventListener('abort', onAbort, { once: true });
}
bridge.rpcPending.set(reqId, {
resolve: (data) => {
clearTimeout(timeoutId);
if (signal) signal.removeEventListener('abort', onAbort);
resolve(data);
},
reject: (err) => {
clearTimeout(timeoutId);
if (signal) signal.removeEventListener('abort', onAbort);
reject(err);
},
});
if (bridge.rpcQueue.length >= 16) {
const dropped = bridge.rpcQueue.shift();
if (dropped?.id) {
const stale = bridge.rpcPending.get(dropped.id);
bridge.rpcPending.delete(dropped.id);
stale?.reject(new Error('CDP queue superseded'));
}
}
bridge.rpcQueue.push({ id: reqId, path, method, body });
});
}
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
const upperMethod = method.toUpperCase();
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
@@ -28,16 +140,41 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
const runRequest = async () => {
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
const fetchFn = sidecar?.fetch
? sidecar.fetch.bind(sidecar)
: globalThis.fetch.bind(globalThis);
: typeof window !== 'undefined' && typeof window.fetch === 'function'
? window.fetch.bind(window)
: globalThis.fetch.bind(globalThis);
const res = await fetchFn(path, {
method: upperMethod,
headers: { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
signal,
});
const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path;
const headers = {};
if (body !== undefined || !bridge) {
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 });
}
}
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 });
}
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
abortErr.name = 'AbortError';
+16 -15
View File
@@ -6,7 +6,7 @@
const pendingJobs = new Set();
let isFlushPending = false;
export function scheduleAsyncJob(job) {
function scheduleAsyncJob(job) {
pendingJobs.add(job);
if (!isFlushPending) {
isFlushPending = true;
@@ -14,7 +14,7 @@ export function scheduleAsyncJob(job) {
}
}
export function flushAsyncJobs() {
function flushAsyncJobs() {
isFlushPending = false;
const jobs = Array.from(pendingJobs);
pendingJobs.clear();
@@ -23,7 +23,7 @@ export function flushAsyncJobs() {
}
}
export function isShallowEqual(a, b) {
function isShallowEqual(a, b) {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
return false;
@@ -55,6 +55,19 @@ export function createReactiveStore(initialState) {
return state;
}
function notifyAll() {
for (const sub of Array.from(subscribers)) {
if (!subscribers.has(sub)) continue;
const nextSlice = sub.selector(state);
const equal = sub.compare(sub.lastSlice, nextSlice);
if (!equal) {
const prevSlice = sub.lastSlice;
sub.lastSlice = nextSlice;
sub.listener(nextSlice, prevSlice);
}
}
}
function setState(patchOrUpdater, { sync = false } = {}) {
const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater;
if (!patch || typeof patch !== 'object') return;
@@ -72,18 +85,6 @@ export function createReactiveStore(initialState) {
}
state = nextState;
const notifyAll = () => {
for (const sub of subscribers) {
const nextSlice = sub.selector(state);
const equal = sub.compare(sub.lastSlice, nextSlice);
if (!equal) {
const prevSlice = sub.lastSlice;
sub.lastSlice = nextSlice;
sub.listener(nextSlice, prevSlice);
}
}
};
if (sync) {
notifyAll();
} else {