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/i18n.ts b/frontend/src/i18n.ts index e8958637..754fa13c 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1266,6 +1266,7 @@ const messages = { leaveBalanceTableUsed: 'Used', leaveBalanceTableRemaining: 'Remaining', leaveBalanceContactHr: 'If needed, please contact HR to confirm leave data.', + durationExceedsBalance: '{label}申请时长({requested})超出剩余额度({remaining}),无法提交。', leaveConfirmPrompt: 'Please confirm the following leave information before submitting to OA.', oaLeaveSubmitFailed: 'OA leave submission failed, please try again later.', leaveSubmitFailedPrefix: 'Leave submission failed: {error}', @@ -2699,6 +2700,7 @@ const messages = { leaveBalanceTableUsed: '已休', leaveBalanceTableRemaining: '当前剩余', leaveBalanceContactHr: '如有疑问,请联系人事部门确认假期数据。', + durationExceedsBalance: '{label}申请时长({requested})超出剩余额度({remaining}),无法提交。', leaveConfirmPrompt: '请确认以下请假信息,确认无误后再提交到 OA。', oaLeaveSubmitFailed: 'OA 请假提交失败,请稍后重试。', leaveSubmitFailedPrefix: '请假单提交失败:{error}', @@ -3991,6 +3993,7 @@ const messages = { leaveBalanceTableUsed: '已休', leaveBalanceTableRemaining: '目前剩餘', leaveBalanceContactHr: '如有疑問,請聯繫人事部門確認假期資料。', + durationExceedsBalance: '{label}申請時長({requested})超出剩餘額度({remaining}),無法提交。', leaveConfirmPrompt: '請確認以下請假資訊,確認無誤後再提交到 OA。', oaLeaveSubmitFailed: 'OA 請假提交失敗,請稍後重試。', leaveSubmitFailedPrefix: '請假單提交失敗:{error}', @@ -5200,6 +5203,7 @@ const messages = { leaveBalanceTableUsed: 'ใช้ไปแล้ว', leaveBalanceTableRemaining: 'คงเหลือปัจจุบัน', leaveBalanceContactHr: 'หากมีข้อสงสัย โปรดติดต่อฝ่ายบุคคลเพื่อตรวจสอบข้อมูลวันลา', + durationExceedsBalance: '{label}ระยะเวลาที่ขอ({requested})เกินยอดคงเหลือ({remaining}) ไม่สามารถส่งได้', leaveConfirmPrompt: 'โปรดยืนยันข้อมูลการลาพนักงานก่อนส่งไปยัง OA', oaLeaveSubmitFailed: 'ส่งคำขอลา OA ไม่สำเร็จ กรุณาลองใหม่อีกครั้ง', leaveSubmitFailedPrefix: 'ส่งใบลาล้มเหลว: {error}', 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/utils/lastChatAgent.ts b/frontend/src/utils/lastChatAgent.ts new file mode 100644 index 00000000..3ecc6a3c --- /dev/null +++ b/frontend/src/utils/lastChatAgent.ts @@ -0,0 +1,20 @@ +const STORAGE_KEY = 'hxops_last_chat_agent_id'; + +export function getLastChatAgentId(fallback = 16): number { + try { + const raw = sessionStorage.getItem(STORAGE_KEY); + const id = Number(raw); + return Number.isFinite(id) && id > 0 ? id : fallback; + } catch { + return fallback; + } +} + +export function setLastChatAgentId(agentId: number): void { + if (!Number.isFinite(agentId) || agentId <= 0) return; + try { + sessionStorage.setItem(STORAGE_KEY, String(agentId)); + } catch { + // ignore storage failures + } +} diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index 7bfa2b76..3464d67a 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -467,9 +467,9 @@ const scheduleRunColumnDefs = ref([ { key: 'total_count', label: '', width: 70, min: 40 }, { key: 'success_count', label: '', width: 70, min: 40 }, { key: 'failed_count', label: '', width: 70, min: 40 }, - { key: 'wecom_notified', label: '', width: 90, min: 50 }, - { key: 'detail', label: '', width: 90, min: 50 }, - { key: 'log', label: '', width: 90, min: 50 }, + { key: 'wecom_notified', label: '', width: 100, min: 80 }, + { key: 'detail', label: '', width: 100, min: 80 }, + { key: 'log', label: '', width: 100, min: 80 }, ]); const syncScheduleRunColumnLabels = () => { @@ -4587,8 +4587,8 @@ const handlePermissionImport = async (event: Event) => { {{ $t('admin.schedule.reset') }} -
- +
+
{ :style="{ width: `${col.width}px` }" /> - + @@ -4627,52 +4625,52 @@ const handlePermissionImport = async (event: Event) => { :key="r.id" class="text-slate-700 transition hover:bg-slate-50" > - - - - + + + - - - - + + + - -
{{ col.label }} - - + >
{{ r.run_no }}{{ formatDateTime(r.started_at) }}{{ formatDateTime(r.finished_at) }} + {{ r.run_no }}{{ formatDateTime(r.started_at) }}{{ formatDateTime(r.finished_at) }} {{ getScheduleRunStatusBadge(r.status).label }} ... {{ r.total_count }}{{ r.success_count }}{{ r.failed_count }} - - + {{ r.total_count }}{{ r.success_count }}{{ r.failed_count }} + + {{ $t('admin.schedule.notified') }} - {{ $t('admin.schedule.notifyError') }} + {{ $t('admin.schedule.notifyError') }} - + +
-
diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index df9fbdcd..d1a94812 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -23,8 +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(); @@ -95,8 +97,13 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => { } }; +const onAuthLogout = () => { + currentUser.value = null; +}; + const handleLogout = () => { - clearAuthUser(); + logoutAuth(); + onAuthLogout(); router.push('/'); }; @@ -916,6 +923,10 @@ const parseDateTime = (value: string) => { return Number.isNaN(date.getTime()) ? null : date; }; +const LEAVE_TYPE_BY_DAY = new Set(['010', '007', '401', '402', '403', '406', 'ZZ07', 'ZZ08', 'ZZ09', 'ZZ10']); + +const isLeaveTypeByDay = (leaveType: string) => LEAVE_TYPE_BY_DAY.has(leaveType); + const calculateDurationHours = (startTime: string, endTime: string) => { const start = parseDateTime(startTime); const end = parseDateTime(endTime); @@ -923,8 +934,12 @@ const calculateDurationHours = (startTime: string, endTime: string) => { return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2)); }; -const formatDurationLabel = (hours: number) => { - if (!hours) return `0 ${t('chat.hourUnit')}`; +const formatDurationLabel = (hours: number, leaveType?: string) => { + if (!hours) return `0 ${isLeaveTypeByDay(leaveType || '') ? t('chat.dayUnit') : t('chat.hourUnit')}`; + if (isLeaveTypeByDay(leaveType || '')) { + const days = Math.round(hours / 8); + return `${days} ${t('chat.dayUnit')}`; + } return `${hours} ${t('chat.hourUnit')}`; }; @@ -1062,7 +1077,18 @@ const extractLeaveInfoFromIntent = (content: string): ExtractedLeaveInfo | null } if (startTime && endTime) { - durationHours = durationHours || calculateDurationHours(startTime, endTime); + if (isLeaveTypeByDay(leaveType)) { + const s = parseDateTime(startTime); + const e = parseDateTime(endTime); + if (s && e && e.getTime() > s.getTime()) { + const sd = new Date(s.getFullYear(), s.getMonth(), s.getDate()); + const ed = new Date(e.getFullYear(), e.getMonth(), e.getDate()); + const days = Math.max(1, Math.round((ed.getTime() - sd.getTime()) / (24 * 3600 * 1000)) + 1); + durationHours = days * 8; + } + } else { + durationHours = durationHours || calculateDurationHours(startTime, endTime); + } } if (!leaveType && !startTime) return null; @@ -1077,13 +1103,31 @@ const extractLeaveInfoFromIntent = (content: string): ExtractedLeaveInfo | null const createLeaveFormData = (content?: string, extractedInfo?: ExtractedLeaveInfo | null): LeaveRequestFormData => { const now = new Date(); + const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content || ''); + const isByDay = isLeaveTypeByDay(initialLeaveType); + const sameDayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0); const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000); const defaultStart = formatDateTime(now); - const defaultEnd = formatDateTime(oneHourLater); - const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content || ''); + const defaultEnd = isByDay ? formatDateTime(sameDayEnd) : formatDateTime(oneHourLater); const startTime = extractedInfo?.startTime || defaultStart; const endTime = extractedInfo?.endTime || defaultEnd; - const durationHours = extractedInfo?.durationHours || calculateDurationHours(startTime, endTime); + let durationHours: number; + if (isByDay) { + const start = parseDateTime(startTime); + const end = parseDateTime(endTime); + if (start && end && end.getTime() > start.getTime()) { + const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate()); + const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate()); + const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1); + durationHours = days * 8; + } else { + durationHours = 8; + } + } else if (extractedInfo?.durationHours) { + durationHours = extractedInfo.durationHours; + } else { + durationHours = calculateDurationHours(startTime, endTime); + } return { applicantName: currentUserDisplayName.value, employeeId: currentUserEmployeeId.value, @@ -1108,7 +1152,20 @@ const newLocalMessageId = (prefix: string) => { }; const syncLeaveDuration = (form: LeaveRequestFormData) => { - form.durationHours = calculateDurationHours(form.startTime, form.endTime); + if (isLeaveTypeByDay(form.leaveType)) { + const start = parseDateTime(form.startTime); + const end = parseDateTime(form.endTime); + if (!start || !end || end.getTime() <= start.getTime()) { + form.durationHours = 0; + return; + } + const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate()); + const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate()); + const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1); + form.durationHours = days * 8; + } else { + form.durationHours = calculateDurationHours(form.startTime, form.endTime); + } }; const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, ''); @@ -1598,12 +1655,13 @@ const validateLeaveForm = (form: LeaveRequestFormData) => { if (!form.agentUid.trim()) return t('chat.leaveAgentRequired'); if (!parseDateTime(form.startTime)) return t('chat.startTimeRequired'); if (!parseDateTime(form.endTime)) return t('chat.endTimeRequired'); - if (calculateDurationHours(form.startTime, form.endTime) <= 0) return t('chat.durationInvalid'); + syncLeaveDuration(form); + if (form.durationHours <= 0) return t('chat.durationInvalid'); return ''; }; -const submitLeaveForm = (msg: any) => { - const payload = getLeaveFormPayload(msg); +const submitLeaveForm = async (chatMsg: any) => { + const payload = getLeaveFormPayload(chatMsg); if (!payload) return; syncLeaveDuration(payload.form); const error = validateLeaveForm(payload.form); @@ -1612,6 +1670,26 @@ const submitLeaveForm = (msg: any) => { return; } + if (NEED_BALANCE_CHECK_TYPES.has(payload.form.leaveType)) { + const balance = await checkLeaveBalance(payload.form.leaveType); + if (balance && balance.remaining_hours !== null && balance.remaining_hours !== undefined) { + const requestedHours = payload.form.durationHours; + if (requestedHours > balance.remaining_hours) { + const isByDay = isLeaveTypeByDay(payload.form.leaveType); + const unit = isByDay ? t('chat.dayUnit') : t('chat.hourUnit'); + const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours; + const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours; + const label = getLeaveTypeLabel(payload.form.leaveType); + msg.warning(t('chat.durationExceedsBalance', { + label, + requested: `${requestedDisplay}${unit}`, + remaining: `${remainingDisplay}${unit}`, + })); + return; + } + } + } + const existingConfirmIndex = messages.value.findIndex((item: any) => item?.type === 'leave-confirmation' && item?.payload?.formId === payload.formId); if (existingConfirmIndex >= 0) { messages.value.splice(existingConfirmIndex, 1); @@ -1633,13 +1711,12 @@ const submitLeaveForm = (msg: any) => { }; messages.value.push(confirmMsg); - // 保存更新后的表单消息和新的确认消息 - saveLocalMessageToBackend(msg); + saveLocalMessageToBackend(chatMsg); saveLocalMessageToBackend(confirmMsg); }; -const editLeaveConfirmation = (msg: any, index: number) => { - const payload = getLeaveConfirmationPayload(msg); +const editLeaveConfirmation = (chatMsg: any, index: number) => { + const payload = getLeaveConfirmationPayload(chatMsg); if (!payload) return; const sourceIndex = findMessageIndexByLocalId(payload.formId); if (sourceIndex >= 0) { @@ -1657,9 +1734,30 @@ const editLeaveConfirmation = (msg: any, index: number) => { messages.value.splice(index, 1); }; -const confirmLeaveSubmission = async (msg: any) => { - const payload = getLeaveConfirmationPayload(msg); +const confirmLeaveSubmission = async (chatMsg: any) => { + const payload = getLeaveConfirmationPayload(chatMsg); if (!payload || payload.submitting) return; + + if (NEED_BALANCE_CHECK_TYPES.has(payload.form.leaveType)) { + const balance = await checkLeaveBalance(payload.form.leaveType); + if (balance && balance.remaining_hours !== null && balance.remaining_hours !== undefined) { + const requestedHours = payload.form.durationHours; + if (requestedHours > balance.remaining_hours) { + const isByDay = isLeaveTypeByDay(payload.form.leaveType); + const unit = isByDay ? t('chat.dayUnit') : t('chat.hourUnit'); + const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours; + const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours; + const label = getLeaveTypeLabel(payload.form.leaveType); + msg.warning(t('chat.durationExceedsBalance', { + label, + requested: `${requestedDisplay}${unit}`, + remaining: `${remainingDisplay}${unit}`, + })); + return; + } + } + } + payload.submitting = true; const sourceIndex = findMessageIndexByLocalId(payload.formId); @@ -1701,8 +1799,8 @@ const confirmLeaveSubmission = async (msg: any) => { }; messages.value.push(resultMsg); payload.confirmed = true; - payload.submitting = false; // Add this line to immediately clear submitting state on success - saveLocalMessageToBackend(msg); + payload.submitting = false; + saveLocalMessageToBackend(chatMsg); saveLocalMessageToBackend(resultMsg); } catch (error: any) { const errorMessage = error?.message || t('chat.oaLeaveSubmitFailed'); @@ -1876,18 +1974,40 @@ const loadUserAgents = async () => { 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 }); }; // 组件挂载时,如果存在预设问题,则自动触发一次发送 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); document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true }); window.addEventListener('resize', syncViewportWidth); await syncCurrentUserProfile(); + setLastChatAgentId(Number(route.params.agentId)); await loadAgent(); await loadUserAgents(); @@ -1907,7 +2027,18 @@ onMounted(async () => { scheduleScrollChatToBottom(); }); +watch( + () => route.params.agentId, + (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); @@ -1983,7 +2114,7 @@ const showChatRating = ref(false); {{ (currentUser?.username || 'I').charAt(0).toUpperCase() }} - + @@ -2104,7 +2235,7 @@ const showChatRating = ref(false); - + @@ -2122,7 +2253,7 @@ const showChatRating = ref(false); - @@ -2236,6 +2367,7 @@ const showChatRating = ref(false); v-model="getLeaveFormPayload(msg)!.form.leaveType" class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100" :disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated" + @change="syncLeaveDuration(getLeaveFormPayload(msg)!.form)" > @@ -2310,7 +2442,7 @@ const showChatRating = ref(false);