const agentWindowName = (agentId: number): string => `hxops_agent_${agentId}`; const isBlankWindow = (win: Window): boolean => { try { const href = win.location.href; return href === 'about:blank' || href.endsWith('about:blank'); } catch { return true; } }; /** Mark this browser tab as the chat window for an agent (used by window.open target name). */ export const registerOpenAgentId = (agentId: number | null): void => { if (agentId && Number.isFinite(agentId) && agentId > 0) { window.name = agentWindowName(agentId); return; } if (window.name.startsWith('hxops_agent_')) { window.name = ''; } }; /** App startup hook (kept for compatibility). */ export const initAgentTabSync = (): void => { // Named-window focus does not require background listeners. }; /** * Focus an existing same-agent tab without reload, or open a new one. * * Per HTML: window.open('', target) focuses an existing named window and * ignores the URL, so the page is not refreshed. */ export const openAgentChatTab = (url: string, agentId: number): void => { const target = agentWindowName(agentId); const existing = window.open('', target); if (!existing || existing.closed) { const opened = window.open(url, target); opened?.focus(); return; } existing.focus(); if (isBlankWindow(existing)) { try { existing.location.href = url; } catch { window.open(url, target); } } };