From 63ea9d7ed7266ea532638b7cf13023bd7e1c0d5a Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Tue, 26 May 2026 20:58:11 +0800 Subject: [PATCH] =?UTF-8?q?1.=E4=BF=AE=E5=A4=8D=E9=97=AE=E9=A2=98=E5=90=8C?= =?UTF-8?q?=E6=97=B6=E6=89=93=E5=BC=80=E5=A4=9A=E4=B8=AA=E6=A0=87=E7=AD=BE?= =?UTF-8?q?=E9=A1=B5=EF=BC=8C=E9=80=80=E5=87=BA=E7=99=BB=E5=BD=95=EF=BC=8C?= =?UTF-8?q?=E5=85=B6=E5=AE=83=E5=87=A0=E4=B8=AA=E6=A0=87=E7=AD=BE=E9=A1=B5?= =?UTF-8?q?=E5=B9=B6=E6=B2=A1=E6=9C=89=E9=80=80=E5=87=BA=E7=99=BB=E5=BD=95?= =?UTF-8?q?=202.=E7=82=B9=E5=87=BB=E6=99=BA=E8=83=BD=E4=BD=93=E6=97=B6?= =?UTF-8?q?=EF=BC=8C=E8=8B=A5=E5=BD=93=E5=89=8D=E5=B7=B2=E7=BB=8F=E6=89=93?= =?UTF-8?q?=E5=BC=80=E6=99=BA=E8=83=BD=E4=BD=93=E6=A0=87=E7=AD=BE=EF=BC=8C?= =?UTF-8?q?=E5=88=99=E4=B8=8D=E4=BC=9A=E5=86=8D=E6=89=93=E5=BC=80=E6=96=B0?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/App.vue | 23 +++++++-- frontend/src/main.ts | 6 ++- frontend/src/utils/agentTabs.ts | 53 ++++++++++++++++++++ frontend/src/utils/auth.ts | 75 +++++++++++++++++++++++++++- frontend/src/views/ChatView.vue | 28 +++++++++-- frontend/src/views/WorkspaceView.vue | 35 +++++++++---- 6 files changed, 201 insertions(+), 19 deletions(-) create mode 100644 frontend/src/utils/agentTabs.ts diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 04447b2f..f1939bc7 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -5,7 +5,12 @@ import { watch, onMounted, onBeforeUnmount } from 'vue'; import { useTheme } from './composables/useTheme'; import LevelMessageDialog from './components/LevelMessageDialog.vue'; import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog'; -import { getAuthHeaders, clearAuthUser } from './utils/auth'; +import { useRouter } from 'vue-router'; +import { getAuthHeaders, logoutAuth } from './utils/auth'; + +const router = useRouter(); + +const PUBLIC_PATHS = ['/', '/workspace', '/casdoor-callback', '/reset-password']; const { locale } = useI18n(); const { themePreference, initTheme, setThemePreference } = useTheme(); @@ -58,14 +63,23 @@ watch(themePreference, (newTheme) => { const onUnauthorized = () => { showMessageDialog('error', '认证已过期或无效,请重新登录'); - clearAuthUser(); - if (window.location.pathname !== '/') { - window.location.href = '/'; + logoutAuth(); +}; + +const onLogout = (event: Event) => { + const detail = (event as CustomEvent<{ remote?: boolean }>).detail; + if (detail?.remote) { + showMessageDialog('info', '您已在其他标签页退出登录'); + } + const path = router.currentRoute.value.path; + if (!PUBLIC_PATHS.includes(path)) { + router.push('/workspace'); } }; onMounted(async () => { window.addEventListener('hxops:unauthorized', onUnauthorized as EventListener); + window.addEventListener('hxops:logout', onLogout as EventListener); initTheme(); @@ -90,6 +104,7 @@ onMounted(async () => { onBeforeUnmount(() => { window.removeEventListener('hxops:unauthorized', onUnauthorized as EventListener); + window.removeEventListener('hxops:logout', onLogout as EventListener); }); diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 48db241c..191d957e 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -4,7 +4,11 @@ import App from './App.vue' import router from './router' import i18n from './i18n' import { config } from './config' -import { refreshAccessToken, getAuthToken } from './utils/auth' +import { refreshAccessToken, getAuthToken, initAuthSync } from './utils/auth' +import { initAgentTabSync } from './utils/agentTabs' + +initAuthSync(); +initAgentTabSync(); // Set document title from config document.title = config.appTitle || 'AI工作台'; diff --git a/frontend/src/utils/agentTabs.ts b/frontend/src/utils/agentTabs.ts new file mode 100644 index 00000000..5c6d7291 --- /dev/null +++ b/frontend/src/utils/agentTabs.ts @@ -0,0 +1,53 @@ +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); + } + } +}; diff --git a/frontend/src/utils/auth.ts b/frontend/src/utils/auth.ts index f761c384..fd49f77e 100644 --- a/frontend/src/utils/auth.ts +++ b/frontend/src/utils/auth.ts @@ -58,13 +58,86 @@ export const saveAuthUser = (user: AuthUser, remember = false): void => { } }; -export const clearAuthUser = (): void => { +const AUTH_LOGOUT_KEY = 'hxops_auth_logout'; +const AUTH_BC_NAME = 'hxops_auth'; + +let _authBroadcast: BroadcastChannel | null = null; +let _authSyncInitialized = false; + +const clearAuthStorage = (): void => { localStorage.removeItem('hxops_user'); sessionStorage.removeItem('hxops_user'); sessionStorage.removeItem('hxops_wecom_state'); sessionStorage.removeItem('hxops_casdoor_state'); }; +const broadcastLogout = (): void => { + try { + localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now())); + localStorage.removeItem(AUTH_LOGOUT_KEY); + } catch { + // ignore quota / private mode errors + } + try { + if (!_authBroadcast) { + _authBroadcast = new BroadcastChannel(AUTH_BC_NAME); + } + _authBroadcast.postMessage({ type: 'logout', ts: Date.now() }); + } catch { + // BroadcastChannel may be unavailable + } +}; + +const dispatchLogout = (detail: Record = {}): void => { + window.dispatchEvent(new CustomEvent('hxops:logout', { detail })); +}; + +const handleRemoteLogout = (): void => { + if (!getStoredAuthUser()) return; + clearAuthStorage(); + dispatchLogout({ remote: true }); +}; + +/** Clear credentials and notify other tabs in the same browser. */ +export const logoutAuth = (): void => { + clearAuthStorage(); + broadcastLogout(); + dispatchLogout({ source: 'local' }); +}; + +export const clearAuthUser = (): void => { + logoutAuth(); +}; + +/** Listen for logout in other tabs (storage + BroadcastChannel). */ +export const initAuthSync = (): void => { + if (_authSyncInitialized) return; + _authSyncInitialized = true; + + window.addEventListener('storage', (event: StorageEvent) => { + if (event.key === 'hxops_user' && event.newValue === null && event.oldValue != null) { + handleRemoteLogout(); + return; + } + if (event.key === AUTH_LOGOUT_KEY && event.newValue != null) { + handleRemoteLogout(); + } + }); + + try { + if (!_authBroadcast) { + _authBroadcast = new BroadcastChannel(AUTH_BC_NAME); + } + _authBroadcast.onmessage = (event: MessageEvent) => { + if (event.data?.type === 'logout') { + handleRemoteLogout(); + } + }; + } catch { + // ignore + } +}; + let _refreshing: Promise | null = null; export const refreshAccessToken = async (): Promise => { diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index c3e132f2..f5a59ac3 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -23,9 +23,10 @@ import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue'; import { useMessage } from '../composables/useMessage'; import { useIsMobile } from '../composables/useIsMobile'; import { useTheme } from '../composables/useTheme'; -import { getAuthHeaders, getStoredAuthUser, clearAuthUser } from '../utils/auth'; +import { getAuthHeaders, getStoredAuthUser, logoutAuth } from '../utils/auth'; import { copyTextToClipboard } from '../utils/clipboard'; import { setLastChatAgentId } from '../utils/lastChatAgent'; +import { openAgentChatTab, registerOpenAgentId } from '../utils/agentTabs'; const { t, locale } = useI18n(); const { appliedTheme, toggleLightDark } = useTheme(); @@ -96,8 +97,13 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => { } }; +const onAuthLogout = () => { + currentUser.value = null; +}; + const handleLogout = () => { - clearAuthUser(); + logoutAuth(); + onAuthLogout(); router.push('/'); }; @@ -1879,11 +1885,21 @@ const switchToAgent = (agent: { id: number; name: string }) => { if (agent.id === agentId) return; setLastChatAgentId(agent.id); const url = router.resolve(`/chat/${agent.id}`).href; - window.open(url, '_blank'); + openAgentChatTab(url, agent.id); +}; + +const syncOpenAgentRegistration = () => { + const id = Number(route.params.agentId); + registerOpenAgentId(Number.isFinite(id) && id > 0 ? id : null); +}; + +const onPageHide = () => { + registerOpenAgentId(null); }; const goToWorkspace = (view?: string) => { setLastChatAgentId(Number(route.params.agentId)); + registerOpenAgentId(null); const query: Record = { no_redirect: '1' }; if (view) query.view = view; router.push({ path: '/workspace', query }); @@ -1891,6 +1907,9 @@ const goToWorkspace = (view?: string) => { // 组件挂载时,如果存在预设问题,则自动触发一次发送 onMounted(async () => { + syncOpenAgentRegistration(); + window.addEventListener('pagehide', onPageHide); + window.addEventListener('hxops:logout', onAuthLogout); document.addEventListener('mousedown', handleDocumentPointerDown); document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true }); document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside); @@ -1922,10 +1941,13 @@ watch( (id) => { const nextId = Number(id); if (Number.isFinite(nextId) && nextId > 0) setLastChatAgentId(nextId); + syncOpenAgentRegistration(); } ); onBeforeUnmount(() => { + window.removeEventListener('pagehide', onPageHide); + window.removeEventListener('hxops:logout', onAuthLogout); document.removeEventListener('mousedown', handleDocumentPointerDown); document.removeEventListener('touchstart', handleDocumentPointerDown); document.removeEventListener('mousedown', handleMobileAgentPopoverClickOutside); diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index fd35fbb5..d6c89d2a 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -4,7 +4,7 @@ * 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent * 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口 */ -import { ref, onMounted, computed, watch, nextTick } from 'vue'; +import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'; import { useRouter, useRoute } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { config } from '../config'; @@ -24,8 +24,9 @@ import { type WecomLoginDialogContent, type WecomMatchField, } from '../utils/wecom'; -import { getAuthHeaders, getStoredAuthUser, saveAuthUser } from '../utils/auth'; +import { getAuthHeaders, getStoredAuthUser, saveAuthUser, logoutAuth } from '../utils/auth'; import { getLastChatAgentId } from '../utils/lastChatAgent'; +import { openAgentChatTab } from '../utils/agentTabs'; import { Settings, LayoutGrid, @@ -405,7 +406,10 @@ const loadAuthUser = () => { stored = sessionStorage.getItem('hxops_user'); } - if (!stored) return; + if (!stored) { + currentUser.value = null; + return; + } try { const user = getStoredAuthUser(); @@ -847,10 +851,7 @@ const mobileTabTitle = computed(() => { return t('workspace.mobileTabs.applications'); }); -const handleLogout = () => { - localStorage.removeItem('hxops_user'); - sessionStorage.removeItem('hxops_user'); - sessionStorage.removeItem('hxops_wecom_state'); +const applyLoggedOutState = () => { currentUser.value = null; agents.value = []; quickQuestions.value = []; @@ -858,9 +859,18 @@ const handleLogout = () => { embeddedAgents.value = []; userReport.value = null; fetchPublicAgents(); +}; + +const handleLogout = () => { + logoutAuth(); + applyLoggedOutState(); router.push('/'); }; +const onAuthLogout = () => { + applyLoggedOutState(); +}; + const captureOriginalProfile = () => { originalProfile.value = { ...profileUser.value }; }; @@ -1178,7 +1188,7 @@ const navigateToChat = (id: number) => { return; } const url = router.resolve(`/chat/${id}`).href; - window.open(url, '_blank'); + openAgentChatTab(url, id); }; const navigateWithQuickQuestion = (agentId: number, question: string) => { @@ -1191,7 +1201,7 @@ const navigateWithQuickQuestion = (agentId: number, question: string) => { path: `/chat/${agentId}`, query: { preset: question }, }).href; - window.open(url, '_blank'); + openAgentChatTab(url, agentId); }; const handleWecomDeeplinkContext = async () => { @@ -1224,7 +1234,7 @@ const handleWecomDeeplinkContext = async () => { path: `/chat/${agentId}`, query: preset ? { preset } : {}, }).href; - window.open(url, '_blank'); + openAgentChatTab(url, agentId); } } @@ -1362,6 +1372,7 @@ const openAnnouncement = (ann: Announcement) => { }; onMounted(async () => { + window.addEventListener('hxops:logout', onAuthLogout); loadLanguagePreference(); fetchAnnouncements(); const handledCasdoor = await tryCasdoorCallbackLogin(); @@ -1392,6 +1403,10 @@ onMounted(async () => { isLoading.value = false; } }); + +onBeforeUnmount(() => { + window.removeEventListener('hxops:logout', onAuthLogout); +});