mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
fix(panel): parallelize IDE chat route probing and deduplicate DOM probe
- Probe multiple IDE chat iframes concurrently with a 1s timeout cap and AbortSignal early-abort once a focused visible view resolves, preventing hanging iframes from stalling window sync - Deduplicate DOM route extraction across probeExpr and ideChatRouteProbeExpr via buildDomRouteCascadeIdSnippet and enforce Node-side UUID validation before syncing host routes
This commit is contained in:
@@ -74,6 +74,71 @@ const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
||||
// 8 MiB 原始导出文件经 Base64 (4/3x) 编码和 JSON 封装后约 10.7 MiB,预留 12 MiB 请求体上限
|
||||
const BRIDGE_MAX_EXPORT_BODY_BYTES = 12 * 1024 * 1024;
|
||||
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
|
||||
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const IDE_ROUTE_PROBE_MAX_TIMEOUT_MS = 1000;
|
||||
|
||||
function sanitizeRouteCascadeId(raw) {
|
||||
const id = String(raw || '').trim();
|
||||
return CASCADE_UUID_RE.test(id) ? id : '';
|
||||
}
|
||||
|
||||
const WINDOW_VISIBLE_EXPR = `Boolean(
|
||||
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
|
||||
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
|
||||
!(typeof document !== 'undefined' && document?.hidden === true)
|
||||
)`;
|
||||
|
||||
/**
|
||||
* 构建单一事实来源的页面内会话路由提取 IIFE 片段,供常规保活探测与 IDE 聊天 iframe 路由探测共用:
|
||||
* 优先解析 `/c/<uuid>`,其次在非隐藏且非零尺寸的 `conversation-view` 中按聚焦态、选中行交集及首个可见视图裁决。
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildDomRouteCascadeIdSnippet() {
|
||||
return `(() => {
|
||||
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i);
|
||||
if (m && uuidRe.test(m[1])) return m[1];
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') return '';
|
||||
const selectedRow = document.querySelector(
|
||||
'[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]'
|
||||
);
|
||||
const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (typeof document.querySelectorAll === 'function') {
|
||||
const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]');
|
||||
const visibleIds = [];
|
||||
let focusedId = '';
|
||||
const activeEl = document.activeElement || null;
|
||||
for (const viewEl of views) {
|
||||
const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (!uuidRe.test(cid)) continue;
|
||||
if (viewEl.hasAttribute?.('hidden')) continue;
|
||||
if (viewEl.getBoundingClientRect) {
|
||||
const r = viewEl.getBoundingClientRect();
|
||||
if (r.width <= 0 && r.height <= 0) continue;
|
||||
}
|
||||
visibleIds.push(cid);
|
||||
if (activeEl && viewEl.contains?.(activeEl)) {
|
||||
focusedId = cid;
|
||||
}
|
||||
}
|
||||
if (focusedId) return focusedId;
|
||||
if (
|
||||
selectedRowId &&
|
||||
uuidRe.test(selectedRowId) &&
|
||||
visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase())
|
||||
) {
|
||||
return selectedRowId;
|
||||
}
|
||||
if (visibleIds.length > 0) return visibleIds[0];
|
||||
}
|
||||
const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]');
|
||||
const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (uuidRe.test(singleViewId)) return singleViewId;
|
||||
if (uuidRe.test(selectedRowId)) return selectedRowId;
|
||||
return '';
|
||||
})()`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
||||
@@ -1578,14 +1643,18 @@ export function createWindowBridgeController(options) {
|
||||
return { reachableCount, targets: merged };
|
||||
}
|
||||
|
||||
async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0) {
|
||||
async function evaluateOnTarget(wsUrl, expression, timeoutMsOverride = 0, signal = null) {
|
||||
const WS = WebSocketImpl || globalThis.WebSocket;
|
||||
if (typeof WS !== 'function') {
|
||||
throw new Error('WebSocket runtime unavailable');
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
throw new Error('CDP Runtime.evaluate aborted');
|
||||
}
|
||||
const effectiveTimeoutMs = Math.max(500, Number(timeoutMsOverride) || cdpTimeoutMs);
|
||||
let ws = null;
|
||||
let timer = null;
|
||||
let onAbort = null;
|
||||
try {
|
||||
ws = new WS(wsUrl);
|
||||
const evalResult = await new Promise((resolve, reject) => {
|
||||
@@ -1593,6 +1662,11 @@ export function createWindowBridgeController(options) {
|
||||
reject(new Error('CDP Runtime.evaluate timeout'));
|
||||
}, effectiveTimeoutMs);
|
||||
|
||||
if (signal && typeof signal.addEventListener === 'function') {
|
||||
onAbort = () => reject(new Error('CDP Runtime.evaluate aborted'));
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
|
||||
const onOpen = () => {
|
||||
try {
|
||||
ws.send(
|
||||
@@ -1634,6 +1708,9 @@ export function createWindowBridgeController(options) {
|
||||
return evalResult;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
if (onAbort && signal && typeof signal.removeEventListener === 'function') {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
if (ws) {
|
||||
try {
|
||||
ws.close();
|
||||
@@ -2229,6 +2306,7 @@ export function createWindowBridgeController(options) {
|
||||
}
|
||||
|
||||
const { port, token } = await ensureBridgeServer();
|
||||
const domRouteExpr = buildDomRouteCascadeIdSnippet();
|
||||
const probeExpr = `(() => {
|
||||
try {
|
||||
const ov = ${windowOverlayRef};
|
||||
@@ -2236,28 +2314,11 @@ export function createWindowBridgeController(options) {
|
||||
const alive = Boolean(ov && typeof ov[${overlayMethods.ensureAlive}] === 'function' && ov[${overlayMethods.ensureAlive}]());
|
||||
const dockKind = String(ov?.[${overlayMethods.getDockKind}]?.() || '');
|
||||
const clientMountMode = String(ov?.[${overlayMethods.getMountMode}]?.() || '');
|
||||
const visible = Boolean(
|
||||
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
|
||||
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
|
||||
!(typeof document !== 'undefined' && document?.hidden === true)
|
||||
);
|
||||
const visible = ${WINDOW_VISIBLE_EXPR};
|
||||
const rpcBatch = Array.isArray(br?.rpcQueue) && br.rpcQueue.length > 0
|
||||
? br.rpcQueue.splice(0, 8)
|
||||
: [];
|
||||
let routeCascadeId = '';
|
||||
if (!alive) {
|
||||
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i);
|
||||
if (m && uuidRe.test(m[1])) {
|
||||
routeCascadeId = m[1];
|
||||
} else if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
|
||||
const el =
|
||||
document.querySelector('[data-testid="conversation-view"][data-cascade-id]') ||
|
||||
document.querySelector('[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]');
|
||||
const cand = String(el?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (uuidRe.test(cand)) routeCascadeId = cand;
|
||||
}
|
||||
}
|
||||
const routeCascadeId = !alive ? ${domRouteExpr} : '';
|
||||
return {
|
||||
alive,
|
||||
dockKind,
|
||||
@@ -2280,94 +2341,103 @@ export function createWindowBridgeController(options) {
|
||||
|
||||
const ideChatRouteProbeExpr = `(() => {
|
||||
try {
|
||||
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const visible = Boolean(
|
||||
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
|
||||
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
|
||||
!(typeof document !== 'undefined' && document?.hidden === true)
|
||||
);
|
||||
const visible = ${WINDOW_VISIBLE_EXPR};
|
||||
const focused = Boolean(
|
||||
typeof document !== 'undefined' && typeof document.hasFocus === 'function' && document.hasFocus()
|
||||
);
|
||||
let routeCascadeId = '';
|
||||
const m = String(window.location?.pathname || '').match(/^\\/c\\/([0-9a-f-]{36})(?:\\/|$)/i);
|
||||
if (m && uuidRe.test(m[1])) {
|
||||
routeCascadeId = m[1];
|
||||
} else if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
|
||||
const selectedRow = document.querySelector(
|
||||
'[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]'
|
||||
);
|
||||
const selectedRowId = String(selectedRow?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (typeof document.querySelectorAll === 'function') {
|
||||
const views = document.querySelectorAll('[data-testid="conversation-view"][data-cascade-id]');
|
||||
const visibleIds = [];
|
||||
let focusedId = '';
|
||||
const activeEl = document.activeElement || null;
|
||||
for (const viewEl of views) {
|
||||
const cid = String(viewEl?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (!uuidRe.test(cid)) continue;
|
||||
if (viewEl.hasAttribute?.('hidden')) continue;
|
||||
if (viewEl.getBoundingClientRect) {
|
||||
const r = viewEl.getBoundingClientRect();
|
||||
if (r.width <= 0 && r.height <= 0) continue;
|
||||
}
|
||||
visibleIds.push(cid);
|
||||
if (activeEl && viewEl.contains?.(activeEl)) {
|
||||
focusedId = cid;
|
||||
}
|
||||
}
|
||||
if (focusedId) {
|
||||
routeCascadeId = focusedId;
|
||||
} else if (
|
||||
selectedRowId &&
|
||||
uuidRe.test(selectedRowId) &&
|
||||
visibleIds.some((id) => id.toLowerCase() === selectedRowId.toLowerCase())
|
||||
) {
|
||||
routeCascadeId = selectedRowId;
|
||||
} else if (visibleIds.length > 0) {
|
||||
routeCascadeId = visibleIds[0];
|
||||
}
|
||||
}
|
||||
if (!routeCascadeId) {
|
||||
const singleView = document.querySelector('[data-testid="conversation-view"][data-cascade-id]');
|
||||
const singleViewId = String(singleView?.getAttribute?.('data-cascade-id') || '').trim();
|
||||
if (uuidRe.test(singleViewId)) {
|
||||
routeCascadeId = singleViewId;
|
||||
} else if (uuidRe.test(selectedRowId)) {
|
||||
routeCascadeId = selectedRowId;
|
||||
}
|
||||
}
|
||||
}
|
||||
const routeCascadeId = ${domRouteExpr};
|
||||
return { routeCascadeId, visible, focused };
|
||||
} catch {
|
||||
return { routeCascadeId: '', visible: false, focused: false };
|
||||
}
|
||||
})()`;
|
||||
|
||||
const ideRouteProbeTimeoutMs = Math.max(
|
||||
500,
|
||||
Math.min(Number(cdpTimeoutMs) || IDE_ROUTE_PROBE_MAX_TIMEOUT_MS, IDE_ROUTE_PROBE_MAX_TIMEOUT_MS)
|
||||
);
|
||||
|
||||
async function resolveIdeWorkbenchRouteId(targetObj) {
|
||||
const staticRouteId = String(targetObj?.ideRouteCascadeId || '').trim();
|
||||
const staticRouteId = sanitizeRouteCascadeId(targetObj?.ideRouteCascadeId);
|
||||
const chatList = Array.isArray(targetObj?.ideChatTargets) ? targetObj.ideChatTargets : [];
|
||||
let bestRouteId = '';
|
||||
let bestRank = 0;
|
||||
for (const chatTarget of chatList) {
|
||||
const chatWsUrl = String(chatTarget?.webSocketDebuggerUrl || '').trim();
|
||||
if (!chatWsUrl) continue;
|
||||
const probeUrls = chatList
|
||||
.map((chatTarget) => String(chatTarget?.webSocketDebuggerUrl || '').trim())
|
||||
.filter(Boolean);
|
||||
if (probeUrls.length === 0) {
|
||||
return staticRouteId;
|
||||
}
|
||||
|
||||
if (probeUrls.length === 1) {
|
||||
try {
|
||||
const res = await evaluateOnTarget(chatWsUrl, ideChatRouteProbeExpr);
|
||||
const val = res?.result?.result?.value;
|
||||
const cid = String(val?.routeCascadeId || '').trim();
|
||||
if (!cid) continue;
|
||||
const rank = val?.focused && val?.visible ? 3 : val?.visible ? 2 : 1;
|
||||
if (rank > bestRank) {
|
||||
bestRank = rank;
|
||||
bestRouteId = cid;
|
||||
if (bestRank === 3) break;
|
||||
}
|
||||
const res = await evaluateOnTarget(probeUrls[0], ideChatRouteProbeExpr, ideRouteProbeTimeoutMs);
|
||||
const cid = sanitizeRouteCascadeId(res?.result?.result?.value?.routeCascadeId);
|
||||
return cid || staticRouteId;
|
||||
} catch {
|
||||
// 单个聊天子视图探测异常不阻断其他视图与静态路由兜底
|
||||
return staticRouteId;
|
||||
}
|
||||
}
|
||||
return bestRouteId || staticRouteId;
|
||||
|
||||
const abortCtrl = typeof AbortController === 'function' ? new AbortController() : null;
|
||||
const results = new Array(probeUrls.length).fill(null);
|
||||
let settledCount = 0;
|
||||
let resolved = false;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const pickBest = () => {
|
||||
let bestRouteId = '';
|
||||
let bestRank = 0;
|
||||
for (const item of results) {
|
||||
if (!item || !item.cid) continue;
|
||||
if (item.rank > bestRank) {
|
||||
bestRank = item.rank;
|
||||
bestRouteId = item.cid;
|
||||
if (bestRank === 3) break;
|
||||
}
|
||||
}
|
||||
return bestRouteId || staticRouteId;
|
||||
};
|
||||
|
||||
const finishEarly = (routeId) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
try {
|
||||
abortCtrl?.abort();
|
||||
} catch {
|
||||
// 忽略中止异常
|
||||
}
|
||||
resolve(routeId);
|
||||
};
|
||||
|
||||
probeUrls.forEach((chatWsUrl, idx) => {
|
||||
evaluateOnTarget(
|
||||
chatWsUrl,
|
||||
ideChatRouteProbeExpr,
|
||||
ideRouteProbeTimeoutMs,
|
||||
abortCtrl?.signal || null
|
||||
)
|
||||
.then((res) => {
|
||||
const val = res?.result?.result?.value;
|
||||
const cid = sanitizeRouteCascadeId(val?.routeCascadeId);
|
||||
if (cid) {
|
||||
const rank = val?.focused && val?.visible ? 3 : val?.visible ? 2 : 1;
|
||||
results[idx] = { cid, rank };
|
||||
if (rank === 3) {
|
||||
finishEarly(cid);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// 单个聊天子视图探测异常、超时或提前中止均不阻断其他视图及静态路由兜底
|
||||
})
|
||||
.finally(() => {
|
||||
settledCount += 1;
|
||||
if (!resolved && settledCount === probeUrls.length) {
|
||||
resolved = true;
|
||||
resolve(pickBest());
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let cachedAssets = null;
|
||||
@@ -2380,7 +2450,7 @@ export function createWindowBridgeController(options) {
|
||||
const wsUrl = String(targetObj?.webSocketDebuggerUrl || '').trim();
|
||||
if (!wsUrl) return { alive: false, dockKind: '', visible: false };
|
||||
let probedRouteId = '';
|
||||
const ideRouteId = String(ideRouteOverride || targetObj.ideRouteCascadeId || '').trim();
|
||||
const ideRouteId = sanitizeRouteCascadeId(ideRouteOverride || targetObj.ideRouteCascadeId);
|
||||
const targetEndpointId = String(targetObj.endpointId || LOCAL_ENDPOINT_ID);
|
||||
const targetIsRemote = Boolean(targetObj.isRemoteEndpoint && targetEndpointId !== LOCAL_ENDPOINT_ID);
|
||||
const targetEndpointLabel = targetIsRemote ? String(targetObj.endpointLabel || 'SSH') : '';
|
||||
@@ -2388,7 +2458,7 @@ export function createWindowBridgeController(options) {
|
||||
if (!forceReinject) {
|
||||
const probeRes = await evaluateOnTarget(wsUrl, probeExpr);
|
||||
const snap = probeRes?.result?.result?.value;
|
||||
probedRouteId = String(snap?.routeCascadeId || '').trim();
|
||||
probedRouteId = sanitizeRouteCascadeId(snap?.routeCascadeId);
|
||||
if (snap && snap.alive === true) {
|
||||
const snapVerNum = Number(snap.bundleVersion) || 0;
|
||||
const curVerNum = Number(bundleVersion) || 0;
|
||||
|
||||
@@ -6710,3 +6710,270 @@ test('Antigravity IDE dual mode (双栖挂载) probes live chat iframe DOM casca
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('IDE chat iframe route probe disambiguates multi-view DOM, aborts hanging siblings early in parallel, and rejects non-UUID payloads with static fallback', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-ide-route-edge-'));
|
||||
const roamingDir = path.join(tmpDir, 'Roaming');
|
||||
fs.mkdirSync(path.join(roamingDir, 'Antigravity IDE'), { recursive: true });
|
||||
|
||||
const convHidden = 'aaaaaaaa-1111-4222-8333-aaaaaaaaaaaa';
|
||||
const convZero = 'bbbbbbbb-1111-4222-8333-bbbbbbbbbbbb';
|
||||
const convVis1 = 'cccccccc-1111-4222-8333-cccccccccccc';
|
||||
const convVis2 = 'dddddddd-1111-4222-8333-dddddddddddd';
|
||||
const convStatic = 'eeeeeeee-1111-4222-8333-eeeeeeeeeeee';
|
||||
|
||||
const multiState = {
|
||||
focusedViewId: convVis2,
|
||||
selectedRowId: '',
|
||||
};
|
||||
const focusToken = { tag: 'textarea' };
|
||||
const makeViewNode = (id, { hidden = false, width = 760, height = 900 } = {}) => ({
|
||||
getAttribute: (name) => (name === 'data-cascade-id' ? id : null),
|
||||
hasAttribute: (name) => (name === 'hidden' ? hidden : false),
|
||||
getBoundingClientRect: () => ({ width, height }),
|
||||
contains: (el) => el === focusToken && multiState.focusedViewId === id,
|
||||
});
|
||||
|
||||
const multiDoc = {
|
||||
hidden: false,
|
||||
get activeElement() {
|
||||
return multiState.focusedViewId ? focusToken : null;
|
||||
},
|
||||
hasFocus: () => true,
|
||||
querySelector: (sel) => {
|
||||
if (sel.includes('conversation-row-')) {
|
||||
return multiState.selectedRowId
|
||||
? { getAttribute: (n) => (n === 'data-cascade-id' ? multiState.selectedRowId : null) }
|
||||
: null;
|
||||
}
|
||||
if (sel.includes('conversation-view')) {
|
||||
return makeViewNode(convHidden, { hidden: true });
|
||||
}
|
||||
return null;
|
||||
},
|
||||
querySelectorAll: (sel) => {
|
||||
if (!sel.includes('conversation-view')) return [];
|
||||
return [
|
||||
makeViewNode(convHidden, { hidden: true }),
|
||||
makeViewNode(convZero, { width: 0, height: 0 }),
|
||||
makeViewNode(convVis1),
|
||||
makeViewNode(convVis2),
|
||||
];
|
||||
},
|
||||
};
|
||||
const multiChatCtx = vm.createContext({
|
||||
window: {
|
||||
innerWidth: 760,
|
||||
innerHeight: 900,
|
||||
location: { pathname: '/', href: 'http://127.0.0.1:56598/?extensionView=true' },
|
||||
},
|
||||
document: multiDoc,
|
||||
console,
|
||||
});
|
||||
multiChatCtx.window.window = multiChatCtx.window;
|
||||
multiChatCtx.window.document = multiDoc;
|
||||
|
||||
const wbCtx = vm.createContext({
|
||||
window: {
|
||||
innerWidth: 1440,
|
||||
innerHeight: 900,
|
||||
location: { pathname: '/out/vs/code/electron-browser/workbench/workbench.html' },
|
||||
},
|
||||
document: { hidden: false, querySelector: () => null, querySelectorAll: () => [] },
|
||||
console,
|
||||
});
|
||||
wbCtx.window.window = wbCtx.window;
|
||||
|
||||
let scenario = 'multi_with_hanging';
|
||||
let hangSocketClosed = false;
|
||||
|
||||
class EdgeProbeMockWS {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.listeners = new Map();
|
||||
this.closed = false;
|
||||
queueMicrotask(() => {
|
||||
if (this.closed) return;
|
||||
const pathname = new URL(this.url).pathname;
|
||||
if (pathname === '/devtools/page/CHAT-ERR') {
|
||||
this._emit('error', new Error('simulated CDP disconnect'));
|
||||
return;
|
||||
}
|
||||
this._emit('open', {});
|
||||
});
|
||||
}
|
||||
addEventListener(type, fn) {
|
||||
if (!this.listeners.has(type)) this.listeners.set(type, []);
|
||||
this.listeners.get(type).push(fn);
|
||||
}
|
||||
send(raw) {
|
||||
const msg = JSON.parse(raw);
|
||||
if (msg.method !== 'Runtime.evaluate') return;
|
||||
const pathname = new URL(this.url).pathname;
|
||||
if (pathname === '/devtools/page/CHAT-HANG') {
|
||||
// Intentionally never reply to verify parallel probing + early abort
|
||||
return;
|
||||
}
|
||||
if (pathname === '/devtools/page/CHAT-MALFORMED') {
|
||||
queueMicrotask(() =>
|
||||
this._emit('message', {
|
||||
data: JSON.stringify({
|
||||
id: msg.id,
|
||||
result: { result: { value: { routeCascadeId: 'not-a-valid-uuid', visible: true, focused: true } } },
|
||||
}),
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
const targetCtx = pathname === '/devtools/page/WB-1' ? wbCtx : multiChatCtx;
|
||||
const val = vm.runInContext(msg.params.expression, targetCtx);
|
||||
queueMicrotask(() =>
|
||||
this._emit('message', {
|
||||
data: JSON.stringify({ id: msg.id, result: { result: { value: val } } }),
|
||||
})
|
||||
);
|
||||
}
|
||||
close() {
|
||||
this.closed = true;
|
||||
if (new URL(this.url).pathname === '/devtools/page/CHAT-HANG') {
|
||||
hangSocketClosed = true;
|
||||
}
|
||||
}
|
||||
_emit(type, ev) {
|
||||
for (const fn of this.listeners.get(type) || []) fn(ev);
|
||||
}
|
||||
}
|
||||
|
||||
const cdpSrv = http.createServer((req, res) => {
|
||||
if (req.url !== '/json/list') {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const p = cdpSrv.address().port;
|
||||
const targets = [
|
||||
{
|
||||
id: 'WB-1',
|
||||
type: 'page',
|
||||
url: 'vscode-file://vscode-app/c:/Antigravity%20IDE/resources/app/out/vs/code/electron-browser/workbench/workbench.html',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/WB-1`,
|
||||
},
|
||||
{
|
||||
id: 'WV-1',
|
||||
parentId: 'WB-1',
|
||||
type: 'iframe',
|
||||
url: 'vscode-webview://edge/index.html?purpose=webviewView',
|
||||
},
|
||||
];
|
||||
if (scenario === 'multi_with_hanging') {
|
||||
targets.push(
|
||||
{
|
||||
id: 'CHAT-HANG',
|
||||
parentId: 'WV-1',
|
||||
type: 'iframe',
|
||||
url: 'http://127.0.0.1:56598/?extensionView=true&extensionVariant=vs-code',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/CHAT-HANG`,
|
||||
},
|
||||
{
|
||||
id: 'CHAT-LIVE',
|
||||
parentId: 'WV-1',
|
||||
type: 'iframe',
|
||||
url: 'http://127.0.0.1:56598/?extensionView=true&extensionVariant=vs-code',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/CHAT-LIVE`,
|
||||
}
|
||||
);
|
||||
} else {
|
||||
targets.push(
|
||||
{
|
||||
id: 'CHAT-ERR',
|
||||
parentId: 'WV-1',
|
||||
type: 'iframe',
|
||||
url: `http://127.0.0.1:56598/c/${convStatic}?extensionView=true&extensionVariant=vs-code`,
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/CHAT-ERR`,
|
||||
},
|
||||
{
|
||||
id: 'CHAT-MALFORMED',
|
||||
parentId: 'WV-1',
|
||||
type: 'iframe',
|
||||
url: 'http://127.0.0.1:56598/?extensionView=true&extensionVariant=vs-code',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/CHAT-MALFORMED`,
|
||||
}
|
||||
);
|
||||
}
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(targets));
|
||||
});
|
||||
|
||||
await new Promise((resolve) => cdpSrv.listen(0, '127.0.0.1', resolve));
|
||||
fs.writeFileSync(
|
||||
path.join(roamingDir, 'Antigravity IDE', 'DevToolsActivePort'),
|
||||
`${cdpSrv.address().port}\n/devtools/browser/ide-edge-route`,
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const mockDualAppJs = `
|
||||
(() => {
|
||||
const br = window.__AGUsageMonitorBridge;
|
||||
let alive = true;
|
||||
window.__syncHostRouteHistory = [];
|
||||
window.__AGUsageMonitorOverlay = {
|
||||
bundleVersion: br.bundleVersion,
|
||||
ensureAlive: () => alive,
|
||||
getDockKind: () => 'ide-titlebar',
|
||||
getMountMode: () => 'dual',
|
||||
applyMountMode: () => alive,
|
||||
syncHostRoute: () => {
|
||||
window.__syncHostRouteHistory.push(String(br.hostRouteCascadeId || ''));
|
||||
},
|
||||
dispose: () => { alive = false; },
|
||||
};
|
||||
})();
|
||||
`;
|
||||
|
||||
const bridgeCtrl = createWindowBridgeController({
|
||||
handleApiRequest: async () => ({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ settings: { windowMountMode: 'dual', enableWindowOverlay: true } }),
|
||||
}),
|
||||
readAssetFn: async (rel) => (rel === 'styles.css' ? ':host{}' : mockDualAppJs),
|
||||
getSettingsFn: () => ({ windowMountMode: 'dual', enableWindowOverlay: true }),
|
||||
getBundleVersionFn: () => 'edge-route-v1',
|
||||
cdpTimeoutMs: 3500,
|
||||
env: { APPDATA: roamingDir, LOCALAPPDATA: tmpDir },
|
||||
platform: 'win32',
|
||||
homeDir: tmpDir,
|
||||
WebSocketImpl: EdgeProbeMockWS,
|
||||
});
|
||||
|
||||
try {
|
||||
// 1. Preceding hanging chat iframe must NOT stall focused sibling, and activeElement picks convVis2 over hidden/zero/vis1
|
||||
const t0 = Date.now();
|
||||
await bridgeCtrl.syncAllWindows();
|
||||
const elapsedMs = Date.now() - t0;
|
||||
assert.ok(elapsedMs < 600, `Expected parallel early-abort under 600ms, got ${elapsedMs}ms`);
|
||||
assert.equal(hangSocketClosed, true, 'Hanging sibling CDP socket must be closed on early abort');
|
||||
assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convVis2);
|
||||
|
||||
// 2. Without activeElement focus, selectedRow intersection with visible views picks convVis2
|
||||
multiState.focusedViewId = '';
|
||||
multiState.selectedRowId = convVis2;
|
||||
await bridgeCtrl.syncAllWindows();
|
||||
assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convVis2);
|
||||
|
||||
// 3. Without focus or matching selectedRow, ignores hidden & zero-rect views and picks first visible convVis1
|
||||
multiState.selectedRowId = convHidden;
|
||||
await bridgeCtrl.syncAllWindows();
|
||||
assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convVis1);
|
||||
|
||||
// 4. When all chat probes error or return malformed non-UUIDs, Node guard filters them and falls back to static URL route
|
||||
scenario = 'error_and_malformed';
|
||||
await bridgeCtrl.syncAllWindows();
|
||||
assert.equal(wbCtx.window.__AGUsageMonitorBridge.hostRouteCascadeId, convStatic);
|
||||
assert.deepEqual(Array.from(wbCtx.window.__syncHostRouteHistory), [convVis1, convStatic]);
|
||||
} finally {
|
||||
await bridgeCtrl.stop();
|
||||
await new Promise((resolve) => cdpSrv.close(resolve));
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user