// app.js - 开发模式骨架版
// 1. 常量
if (typeof window.WS_COLORS === 'undefined') {
var WS_COLORS = ['#3b82f6', '#4ade80', '#a855f7', '#fb923c', '#ef4444', '#ec4899', '#8b5cf6', '#6366f1', '#60a5fa', '#2dd4bf', '#fbbf24', '#f59e0b'];
window.MAX_ATTACHMENTS = 10;
window.isIMEActive = false;
window.lastIMEEndTime = 0;
}
// 2. 状态机
if (!window.state) {
const savedUser = localStorage.getItem('sm_user');
window.state = {
user: savedUser ? JSON.parse(savedUser) : { phone: '', email: '' },
isGuest: !savedUser,
pendingAction: null,
authMode: 'sms',
id: "", intent: "", activeDomain: 'home', history: [],
tasks: JSON.parse(localStorage.getItem('sm_agent_tasks') || '[]'),
attachments: [], isMenuOpen: false, chatTurns: 0, activeView: 'home',
workspaces: JSON.parse(localStorage.getItem('sm_agent_workspaces') || '[]'),
activeWorkspaceId: null, tempColor: '#3b82f6'
};
}
window.attachments = window.state.attachments;
// 游客身份标识:生成并持久化 guest_id
if (!localStorage.getItem('cx_guest_id')) {
localStorage.setItem('cx_guest_id', 'gu_' + crypto.randomUUID());
}
window.state.guestId = localStorage.getItem('cx_guest_id');
// 3. 账户拦截
window.openAuthModal = function(mode) {
window.state.authMode = mode || 'sms';
document.getElementById('register-modal').classList.remove('hidden', 'opacity-0');
renderAuthUI();
};
function renderAuthUI() {
var container = document.getElementById('auth-ui-view');
if (!container) return;
if (window.state.authMode === 'login') {
container.innerHTML = `
`;
} else if (window.state.authMode === 'sms') {
container.innerHTML = `
Quick Login / Sign Up
Sign up with email
`;
} else {
container.innerHTML = `
`;
}
if (typeof lucide !== 'undefined') lucide.createIcons();
// 同样接入 sessionStorage 探测链路
const finalLang = localStorage.getItem('cx_lang') || sessionStorage.getItem('cx_auto_lang') || 'en';
if (typeof loadCoreLanguage === 'function') loadCoreLanguage(finalLang);
}
window.showRegisterModal = window.openAuthModal;
// 确保套餐弹窗逻辑在全局即刻生效
/**
* [行为] 动态渲染套餐按钮:文案严格同步为“专业实战版”与“首席决策版”
*/
window.togglePricingModal = function(show) {
const modal = document.getElementById('pricing-modal');
if (!modal) return;
if (show) {
let tier = (window.state && window.state.user && window.state.user.tier) ? window.state.user.tier : 'free';
if (tier === 'Professional') tier = 'functional';
const render = (id, targetTier, label) => {
const el = document.getElementById(id);
if (!el) return;
if (targetTier === 'free') {
if (tier === 'free') {
el.innerHTML = `${window.t('pricing.free.btn', '✓ Basic Edition')} `;
} else {
el.innerHTML = '';
}
} else {
const style = 'bg-white text-slate-900 border border-slate-300 hover:bg-slate-50';
let btnText = label;
if (tier === targetTier) {
btnText = window.t('pricing.btn.resubscribe', 'Resubscribe');
}
if (targetTier === 'cny') {
el.innerHTML = `${btnText} `;
return;
}
el.innerHTML = `${btnText} `;
}
};
render('btn-tier-free', 'free', '');
render('btn-tier-functional', 'functional', window.t('pricing.btn.subscribe', 'Subscribe'));
render('btn-tier-strategic', 'strategic', window.t('pricing.btn.subscribe', 'Subscribe'));
render('btn-tier-cny', 'cny', window.t('pricing.btn.subscribe', 'Subscribe'));
modal.classList.remove('hidden');
} else {
modal.classList.add('hidden');
}
};
window.closeModal = function() { document.getElementById('register-modal').classList.add('hidden'); };
window.handleSubscription = async function(tier) {
const token = localStorage.getItem('access_token');
if (!token) {
window.openAuthModal('login');
return;
}
const user = JSON.parse(localStorage.getItem('sm_user') || '{}');
const userId = user.user_id || user.id || user.email || '';
// 【核心修复】:为 Google 登录用户兜底提取邮箱,防 Paddle 崩溃
const safeEmail = user.email || (window.state && window.state.user && window.state.user.email) || '';
const priceMap = {
'functional': 'pri_01kkem2fz535g2nxf48ap9zntg',
'strategic': 'pri_01kkem0v8tzrq7t129tnenacp7'
};
const priceId = priceMap[tier];
if (!priceId) {
window.showToast(window.t('toast.invalid_tier', 'Invalid subscription type'), "error");
return;
}
window.showToast(window.t('toast.payment_env', 'Setting up secure payment environment...'), "info", 1000);
const checkoutConfig = {
items: [{ priceId: priceId, quantity: 1 }],
customData: {
user_id: userId,
tier: tier
}
};
// 只有在存在合法邮箱时,才塞入 customer 字段,否则宁愿不传也不能传空值
if (safeEmail && safeEmail.includes('@')) {
checkoutConfig.customer = { email: safeEmail };
}
Paddle.Checkout.open(checkoutConfig);
};
window.handleAuthSubmit = async function(type) {
if (type === 'sms') {
window.showToast(window.t('toast.sms_closed', 'SMS login is currently unavailable'), "error");
return;
}
// 恢复正确的极简弹窗原生 ID
const email = document.getElementById('auth-email')?.value.trim();
const password = document.getElementById('auth-pwd')?.value.trim();
if (!email || !password) {
window.showToast(window.t('toast.fill_auth', 'Please enter your email and password'), "error");
return;
}
try {
const loginRes = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const loginData = await loginRes.json();
if (loginData.success) {
localStorage.setItem('access_token', loginData.access_token);
localStorage.setItem('sm_user', JSON.stringify(loginData.user));
window.state.isGuest = false;
window.state.user = loginData.user;
document.getElementById('register-modal')?.classList.add('hidden');
if (typeof window.syncUIState === 'function') window.syncUIState();
window.showToast(window.t('toast.login_success', 'Login successful'), "success");
return;
}
// 登录失败,根据错误码处理
if (loginData.code === 'toast.email_not_found' || loginData.code === 'EMAIL_NOT_FOUND') {
// 邮箱不存在 → 自动注册
const currentLang = localStorage.getItem('cx_lang') || sessionStorage.getItem('cx_auto_lang') || 'en';
const registerRes = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, lang: currentLang })
});
const registerData = await registerRes.json();
if (registerData.success) {
window.showToast(registerData.message || window.t('toast.reg_success', 'Registration successful, please check your email'), "success");
gtag('event', 'conversion', {
'send_to': 'AW-17775725150/4v9BCKuCjo8cEN6UkJxC',
'value': 1.0,
'currency': 'USD'
});
window.openAuthModal('login');
} else {
window.showToast(registerData.error || window.t('toast.reg_fail', 'Registration failed'), "error");
}
} else if (loginData.code === 'INVALID_PASSWORD') {
window.showToast(window.t('toast.pwd_err', 'Incorrect password, please try again'), "error");
document.getElementById('auth-pwd').value = '';
} else {
window.showToast(loginData.error || window.t('toast.login_fail', 'Login failed'), "error");
}
} catch (err) {
window.showToast(window.t('toast.net_err', 'Network error'), "error");
console.error(err);
}
};
window.handleLoginAction = async function() {
const email = document.getElementById('login-id')?.value.trim();
const password = document.getElementById('login-pwd')?.value.trim();
if (!email || !password) {
if (window.Notice) window.Notice.show(window.t('toast.fill_auth', 'Please enter your email and password'), "error");
return;
}
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const data = await res.json();
if (data.success) {
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('sm_user', JSON.stringify(data.user));
window.state.isGuest = false;
window.state.user = data.user;
document.getElementById('register-modal')?.classList.add('hidden');
if (typeof window.syncUIState === 'function') window.syncUIState();
if (window.Notice) window.Notice.show(window.t('toast.login_success', 'Login successful'), "success");
} else {
if (window.Notice) window.Notice.show(data.error || window.t('toast.login_fail', 'Login failed'), "error");
}
} catch (err) {
if (window.Notice) window.Notice.show(window.t('toast.net_err', 'Network error'), "error");
console.error(err);
}
};
window.handleGoogleLogin = async function() {
try {
// [新增] 抓取当前精确语种
const currentLang = localStorage.getItem('cx_lang') || sessionStorage.getItem('cx_auto_lang') || 'en';
// 将语种通过 URL 参数传给咱们自己的后端
const urlParams = new URLSearchParams(window.location.search);
const ref = urlParams.get('ref') || '';
const res = await fetch(`/api/auth/gmail/login?lang=${currentLang}&ref=${ref}&guest_id=${window.state.guestId || ''}`);
const data = await res.json();
if (data.authorization_url) {
window.location.href = data.authorization_url;
} else {
window.showToast(window.t('toast.google_err', 'Google login configuration error'), "error");
}
} catch (err) {
window.showToast(window.t('toast.net_err', 'Network error'), "error");
console.error(err);
}
};
// 新增:极简查词引擎,找不到键时返回默认英文防崩溃
window.t = function(key, fallback) {
return (window.i18nCache && window.i18nCache[key]) ? window.i18nCache[key] : fallback;
};
window.syncUIState = function() {
// [物理锁死] 如果字典还在路上,绝对不准用英文兜底画界面!注册监听器等枪声,然后直接退出!
if (!window.i18nCache) {
window.addEventListener('i18n-ready', window.syncUIState, { once: true });
return;
}
const headerGroup = document.getElementById('header-auth-group');
const tagline = document.getElementById('dynamic-tagline');
const pillar = document.getElementById('sidebar-pillar');
const chatTitleContainer = document.getElementById('chat-header-container') || document.getElementById('chat-header-title');
if (!headerGroup) return;
// [行为] 状态固化:根据视图自动决定标题显隐,防止刷新时“闪现”
if (chatTitleContainer) {
const isChat = document.getElementById('landing-view')?.classList.contains('hidden');
isChat ? chatTitleContainer.classList.remove('hidden') : chatTitleContainer.classList.add('hidden');
}
if (!window.state.isGuest) {
if (tagline) tagline.innerText = window.t('ui.tagline.member', "Empowering Strategic and Management Transformation with AI");
if (pillar) { pillar.classList.remove('hidden'); pillar.classList.add('flex'); }
const u = window.state.user || {};
const userName = u.nickname || u.username || u.phone || "User";
const userEmail = u.email || "";
const userAvatar = u.avatar_url || "/1111.png";
const tier = u.tier || 'free';
let tierName = window.t('panel.acc.free_tier', 'Free');
let tierColor = 'text-slate-700';
let btnText = window.t('ui.btn.upgrade', 'Upgrade');
let btnStyle = 'bg-slate-900 text-white hover:bg-slate-800 shadow-sm';
if (tier === 'functional') {
tierName = window.t('pricing.pro.name', 'CerebrateX Functional Plan');
tierColor = 'text-amber-600';
btnText = window.t('panel.acc.btn_sub', 'Manage Plan');
btnStyle = 'bg-transparent text-slate-500 hover:text-slate-900 hover:bg-slate-200';
} else if (tier === 'strategic') {
tierName = window.t('pricing.ceo.name', 'CerebrateX Strategic Plan');
tierColor = 'text-amber-600';
btnText = window.t('panel.acc.btn_sub', 'Manage Plan');
btnStyle = 'bg-transparent text-slate-500 hover:text-slate-900 hover:bg-slate-200';
}
headerGroup.innerHTML = `
✨
${(window.state.user && window.state.user.points_balance !== undefined) ? window.state.user.points_balance.toLocaleString() : '...'}
${userName}
${userEmail ? `
${userEmail}
` : ''}
${window.t('panel.nav.account', 'Account')}
${window.t('panel.nav.settings', 'Settings')}
${window.t('panel.nav.history', 'Points & Workspaces')}
${window.t('panel.nav.help', 'Help Center')}
${window.t('panel.nav.invite', 'Invite & Rewards')}
${window.t('panel.nav.privacy', 'Privacy Policy')}
${window.t('panel.nav.terms', 'Terms')}
${window.t('panel.nav.report', 'Report Issue')}
${window.t('panel.nav.about', 'About Us')}
${window.t('ui.btn.logout', 'Log Out')}
`;
// 【架构升级】:移交控制权给全局积分同步引擎
if (window.syncGlobalPoints) window.syncGlobalPoints();
} else {
if (tagline) tagline.innerText = window.t('ui.tagline.guest', "Unlock Management Wisdom via AI Agent");
if (pillar) { pillar.classList.add('hidden'); pillar.classList.remove('flex'); }
headerGroup.innerHTML = `${window.t('ui.btn.login', 'Log In')}
${window.t('ui.btn.register', 'Sign Up')} `;
}
// [行为] 物理补丁:UI 更新后立刻重绘图标,解决手机端按钮“闪现消失”的问题
if (typeof lucide !== 'undefined') lucide.createIcons();
};
// 【全局积分同步引擎】:任何消费动作后调用此函数(window.syncGlobalPoints()),全站积分瞬间同步!
window.syncGlobalPoints = function() {
const token = localStorage.getItem('access_token');
if (!token) return;
fetch('/api/account/info', { headers: { 'Authorization': `Bearer ${token}` } })
.then(res => res.json())
.then(data => {
if (data && data.points) {
const pLimit = Number(data.points.limit || 0);
const pUsed = Number(data.points.used || 0);
const pRemaining = Number(data.points.remaining || Math.max(0, pLimit - pUsed));
// 1. 同步内存
if (!window.state.user) window.state.user = {};
window.state.user.points_balance = pRemaining;
// 2. 瞬间刷拉右上角药丸
const navPointsEl = document.getElementById('nav-points-display');
if (navPointsEl) navPointsEl.innerText = pRemaining.toLocaleString();
// 3. 瞬间刷拉大面板(即使它在后台没显示,数据也直接灌进去)
const elPoints = document.getElementById('panel-points');
const elPointsBar = document.getElementById('panel-points-bar');
const elPointsRemain = document.getElementById('panel-points-remaining');
if (elPoints) elPoints.textContent = `${pUsed}/${pLimit}`;
if (elPointsBar) elPointsBar.style.width = (pLimit > 0 ? Math.min((pUsed / pLimit * 100), 100).toFixed(0) : '0') + '%';
if (elPointsRemain) elPointsRemain.textContent = pRemaining.toLocaleString();
}
// 【核心修复】:身份越权提拔!收到后端真实数据后,立刻纠正前端的兜底“免费”身份
if (data && data.tier) {
if (!window.state.user) window.state.user = {};
const oldTier = window.state.user.tier;
window.state.user.tier = data.tier;
// 把真实身份写进本地缓存,下次刷新时 UI 画笔瞬间就能拿到对的身份
let uStr = localStorage.getItem('sm_user');
if (uStr) {
let uObj = JSON.parse(uStr);
uObj.tier = data.tier;
localStorage.setItem('sm_user', JSON.stringify(uObj));
}
// 如果身份发生了变化,强行踹一脚 UI 重新画下拉框
if (oldTier !== data.tier && typeof window.syncUIState === 'function') {
const temp = window.syncGlobalPoints;
window.syncGlobalPoints = null; // [物理锁] 临时缴械,防止 syncUIState 再次触发拉取造成死循环
window.syncUIState(); // 重动画笔,此时它会拿着 'strategic' 去查字典并变色!
window.syncGlobalPoints = temp; // 恢复兵权
}
}
}).catch(err => console.error("Failed to sync points:", err));
};
/**
* [行为] 对话标题更新钩子:供 LLM 编排器(Orchestration)生成标题后调用
*/
window.updateChatTitle = function(title) {
const textEl = document.getElementById('chat-header-text');
const container = document.getElementById('chat-header-container') || document.getElementById('chat-header-title');
if (!textEl || !title) return;
textEl.innerText = title;
// 如果当前处于对话流,则强制显示标题
if (!document.getElementById('landing-view').classList.contains('hidden')) {
container.classList.add('hidden');
} else {
container.classList.remove('hidden');
}
};
// 5. 基础函数
window.toggleUserMenu = function() {
const popup = document.getElementById('user-popup'); if (!popup) return;
window.state.isMenuOpen = !window.state.isMenuOpen;
popup.classList.toggle('hidden', !window.state.isMenuOpen);
};
window.handleLogout = async function() {
localStorage.removeItem('access_token');
localStorage.removeItem('sm_user');
location.reload();
};
window.showToast = function(message, type = 'info', duration = 3000) {
const container = document.getElementById('toast-container');
if (!container) return;
const colors = {
success: 'bg-green-500',
error: 'bg-red-500',
warning: 'bg-orange-500',
info: 'bg-blue-500'
};
const toast = document.createElement('div');
toast.className = `toast ${colors[type] || colors.info} text-white px-6 py-3 rounded-xl shadow-2xl text-sm font-medium`;
toast.textContent = message;
container.appendChild(toast);
setTimeout(() => {
toast.classList.add('toast-out');
setTimeout(() => toast.remove(), 300);
}, duration);
};
// 统一通知系统 [cite: 63-65]
window.Notice = {
show: function(msg, type = 'info') {
const container = document.getElementById('toast-container');
const colors = { success: 'bg-emerald-500', error: 'bg-red-500', info: 'bg-blue-600' };
const toast = document.createElement('div');
toast.className = `toast ${colors[type]} text-white px-6 py-3 rounded-xl shadow-xl text-sm font-bold animate-fade-in mb-3`;
toast.textContent = msg;
container.appendChild(toast);
setTimeout(() => { toast.classList.add('toast-out'); setTimeout(() => toast.remove(), 300); }, 3000);
}
};
window.alert = (msg) => window.Notice.show(msg, 'info'); // 劫持原生alert
// --- 新增:真实会话拉取与渲染核心(对接 index.html 的原生钩子) ---
window.loadSessionsFromCloud = async function() {
try {
const token = localStorage.getItem('access_token');
if (!token) return;
const res = await fetch('/api/conversations', {
method: 'GET',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }
});
const data = await res.json();
if (data.success && data.data) {
// 将后端真实数据同步到状态机
window.state.tasks = data.data;
}
} catch (error) {
console.error("加载历史失败:", error);
}
};
window.updateDrawerTasks = function() {
const list = document.getElementById('history-list');
list.style.maxHeight = '80vh';
if (!list) return;
const tasks = window.state.tasks || [];
tasks.sort((a, b) => (b.isPinned ? 1 : 0) - (a.isPinned ? 1 : 0));
if (tasks.length === 0) {
list.innerHTML = 'No history yet
';
return;
}
// 我们需要在JS中获取一些基础翻译,以便注入到非DOM结构的变量中
let newTitleStr = 'New Consulting Task';
let shareStr = 'Share';
let pinStr = 'Pin';
let unpinStr = 'Unpin';
let renameStr = 'Rename';
let delStr = 'Delete';
try {
// 尝试从内存中提取当前语言字典(需要稍后我们在loadCoreLanguage里存一个 window.i18nCache)
if (window.i18nCache) {
newTitleStr = window.i18nCache['history.new'] || newTitleStr;
shareStr = window.i18nCache['history.menu.share'] || shareStr;
pinStr = window.i18nCache['history.menu.pin'] || pinStr;
unpinStr = window.i18nCache['history.menu.unpin'] || unpinStr;
renameStr = window.i18nCache['history.menu.rename'] || renameStr;
delStr = window.i18nCache['history.menu.delete'] || delStr;
}
} catch(e){}
// [新增引擎] 智能标签翻译拦截器:把数据库的死数据,模糊匹配到您的多语言字典键名上
const translateTag = (raw) => {
if (!raw) return '';
const s = String(raw).toUpperCase();
const matchers = [
{ keys: ['CEO', '创始'], val: 'home.role.ceo_full' },
{ keys: ['高级', 'C-LEVEL', 'EXEC'], val: 'home.role.exec_full' },
{ keys: ['中层', 'MID'], val: 'home.role.mid_full' },
{ keys: ['骨干', 'CORE'], val: 'home.role.core_full' },
{ keys: ['创业', 'STARTUP'], val: 'home.role.startup_full' },
{ keys: ['AI', '数字化', 'DIGITAL'], val: 'home.intent.ai' },
{ keys: ['战略', '增长', 'STRATEGY'], val: 'home.intent.strategy' },
{ keys: ['组织', '运营', 'ORG'], val: 'home.intent.org' },
{ keys: ['绩效', '领导力', '人才', 'HR'], val: 'home.intent.hr' },
{ keys: ['BRAND', 'MARKET', '品牌', '市场'], val: 'home.intent.brand' }
];
for (let m of matchers) {
if (m.keys.some(k => s.includes(k))) {
return (window.i18nCache && window.i18nCache[m.val]) ? window.i18nCache[m.val] : raw;
}
}
return raw; // 匹配不到就原样输出兜底
};
list.innerHTML = tasks.map(t => {
const title = t.title || newTitleStr;
// [拦截洗练] 强行让 View 和 Intent 过一遍翻译引擎
const view = t.view ? translateTag(t.view) : '';
const intent = t.intent ? translateTag(t.intent) : '';
const safeTitle = String(title).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '"').replace(/\n/g, ' ');
// 极致克制:强制 1px 极细线,尺寸微缩至 3x3,剥离一切粗胖感
const pinIcon = t.isPinned ? ` ` : '';
// [UI 调优] 选中状态融入极微弱的品牌蓝(bg-blue-50/80),文字使用偏冷的深蓝(text-blue-900)
const isSelected = t.id == window.state.currentSessionId;
const bgClass = isSelected ? 'bg-blue-50/80 ring-1 ring-blue-100/50' : 'hover:bg-slate-100/80';
const titleClass = isSelected ? 'text-blue-900 font-semibold' : 'text-slate-500 group-hover:text-slate-900 group-hover:font-semibold';
return `
${t.time || ''}${view ? ' | ' + view : ''}${intent ? ' | ' + intent : ''}
${shareStr}
${t.isPinned ? unpinStr : pinStr}
${renameStr}
${delStr}
`}).join('');
if (typeof lucide !== 'undefined') lucide.createIcons();
};
window.switchToHistory = function(id, view, intent, title) {
window.state.currentSessionId = id;
if (window.updateDrawerTasks) window.updateDrawerTasks();
window.state.id = view;
window.state.activeView = view;
window.state.intent = intent;
window.state.activeWorkspaceId = null; // 【公私隔离】:进入历史必须切断工作区标记
document.getElementById('landing-view').classList.add('hidden');
document.getElementById('workspace-hub-view')?.classList.add('hidden'); // 强行隐藏工作区大厅
document.getElementById('chat-stream').classList.remove('hidden');
document.getElementById('bottom-bar').classList.remove('hidden');
window.updateChatTitle(title);
const input = document.getElementById('bottom-input');
if (input) {
if (view || intent) {
let ph = `[${view || ''}${intent ? ' · ' + intent : ''}] Ready. Let's continue...`;
if (window.i18nCache && window.i18nCache['prompt.default']) {
ph = window.i18nCache['prompt.default'].replace('${view}', view || '').replace('${intent}', intent || '');
}
input.placeholder = ph;
} else {
input.placeholder = window.t ? (window.t('input.placeholder_bottom', 'Type your question...')) : 'Type your question...';
}
}
const chatStream = document.getElementById('chat-stream');
let syncStr = 'Restoring context...';
let emptyStr = 'This record is empty. Send a message to start.';
if (window.i18nCache) {
syncStr = window.i18nCache['history.sync'] || syncStr;
emptyStr = window.i18nCache['history.empty_chat'] || emptyStr;
}
// 纯粹的私聊路由:直接清屏霸占整个流容器
chatStream.innerHTML = ` ${syncStr}
`;
if (typeof lucide !== 'undefined') lucide.createIcons();
setTimeout(async () => {
try {
const token = localStorage.getItem('access_token');
const res = await fetch(`/api/conversations/${id}/messages`, {
headers: { 'Authorization': `Bearer ${token}` }
});
const data = await res.json();
if (data.success) {
chatStream.innerHTML = ''; // 彻底清屏铺排气泡
window.state.history = [];
if (data.data.length === 0) {
chatStream.innerHTML = `${emptyStr}
`;
return;
}
data.data.forEach(msg => {
const uiRole = msg.role === 'user' ? 'user' : 'ai';
let displayContent = msg.content || "";
let extractedAttachments = [];
if (uiRole === 'user' && displayContent.includes("【附件参考资料 - ")) {
const parts = displayContent.split("【附件参考资料 - ");
displayContent = parts[0].trim();
for (let i = 1; i < parts.length; i++) {
const filenameEnd = parts[i].indexOf("】");
if (filenameEnd !== -1) {
const filename = parts[i].substring(0, filenameEnd);
const type = filename.match(/\.(jpg|jpeg|png|gif|webp)$/i) ? 'image' : 'file';
extractedAttachments.push({ filename, type });
}
}
}
if (typeof appendMessage === 'function') {
appendMessage(uiRole, displayContent, extractedAttachments);
}
const llmRole = msg.role === 'user' ? 'user' : 'model';
window.state.history.push({ role: llmRole, content: msg.content });
});
setTimeout(() => {
if (typeof window.renderCharts === 'function') window.renderCharts();
if (typeof lucide !== 'undefined') lucide.createIcons();
}, 50);
setTimeout(() => {
const scroller = document.getElementById('main-scroll-area');
if (scroller) scroller.scrollTop = scroller.scrollHeight;
}, 100);
}
} catch (error) {
const failStr = window.t ? window.t('history.load_fail', 'Failed to load history, please try again') : 'Failed to load history, please try again';
chatStream.innerHTML = `${failStr}
`;
console.error("Failed to fetch history details:", error);
}
}, 100);
};
// 6. 生命周期
document.addEventListener('DOMContentLoaded', async () => {
if (typeof window.loadWorkspacesFromCloud === 'function') {
await window.loadWorkspacesFromCloud();
}
// 页面唤醒时,自动获取真实历史
await window.loadSessionsFromCloud();
window.updateDrawerTasks();
if (typeof lucide !== 'undefined') lucide.createIcons();
// 检查 URL 中是否有 token 参数(来自 Gmail 登录回调)
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
const username = urlParams.get('user');
const email = urlParams.get('email'); // 【修复】:提取后端传回的真实邮箱
if (token && username) {
localStorage.setItem('access_token', token);
localStorage.setItem('user_id', urlParams.get('user_id'));
// 【修复】:把真实的 email 存入本地缓存,Paddle 唤起就不会崩溃了
localStorage.setItem('sm_user', JSON.stringify({
username: username,
email: email || ''
}));
window.state.isGuest = false;
window.state.user = {
username: username,
email: email || '' // 【修复】:拔除造假邮箱
};
window.history.replaceState({}, document.title, '/');
// 【修复】:强拉字典,打穿异步时差,并修正键名
// 允许读取 index.html 存下的探测结果,不再盲目退回英文
const lang = localStorage.getItem('cx_lang') || sessionStorage.getItem('cx_auto_lang') || 'en';
fetch(`/locales/${lang}.json?t=` + new Date().getTime())
.then(res => res.json())
.then(dict => {
window.showToast(dict['toast.login_succ'] || 'Login successful', "success");
})
.catch(() => window.showToast('Login successful', "success"));
window.syncUIState();
}
window.syncUIState();
});
window.triggerNewChatAndSync = async function() {
const token = localStorage.getItem('access_token');
if (token) {
try {
// 【核心修复】:必须用 await 拴住它!等包裹安全送进后端大门,再执行后续动作
await fetch('/api/memory/sync', {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` }
});
} catch(e) {
console.error("向量触发失败", e);
}
}
// 2. 等后端瞬间接收成功后,安全刷新页面
location.reload();
};
// ========================================================
// 历史记录悬浮面板:高级重命名弹窗与真实交互逻辑
// ========================================================
// 1. 全局点击拦截:点屏幕任意地方,自动收起所有的三点菜单
document.addEventListener('click', function(e) {
if (!e.target.closest('[id^="hist-menu-"]') && !e.target.closest('[onclick*="toggleHistoryMenu"]')) {
document.querySelectorAll('[id^="hist-menu-"]').forEach(el => el.classList.add('hidden'));
}
});
window.toggleHistoryMenu = function(e, id) {
e.stopPropagation();
// 排他:点开一个,关掉其他
document.querySelectorAll('[id^="hist-menu-"]').forEach(el => {
if(el.id !== `hist-menu-${id}`) el.classList.add('hidden');
});
const menu = document.getElementById(`hist-menu-${id}`);
if(menu) menu.classList.toggle('hidden');
};
// 2. 动态生成高级重命名弹窗(彻底去除动画,秒弹)
window.showRenamePrompt = function(currentTitle, popupTitle) {
const finalTitle = popupTitle || window.t('history.rename.title', 'Rename Session');
return new Promise((resolve) => {
const dialog = document.createElement('div');
dialog.className = 'fixed inset-0 z-[400] flex items-center justify-center bg-slate-900/50';
dialog.innerHTML = `
`;
document.body.appendChild(dialog);
const input = dialog.querySelector('input');
const okBtn = dialog.querySelector('.prompt-ok');
const cancelBtn = dialog.querySelector('.prompt-cancel');
input.focus();
input.select();
const cleanup = (result) => {
dialog.remove();
resolve(result);
};
okBtn.onclick = () => cleanup(input.value.trim());
cancelBtn.onclick = () => cleanup(null);
input.onkeydown = (e) => { if(e.key === 'Enter') cleanup(input.value.trim()); };
});
};
// 3. 真实动作:调用高级弹窗并重命名
window.handleRenameSession = async function(id, currentTitle, event) {
if(event) event.stopPropagation();
const menu = document.getElementById(`hist-menu-${id}`);
if(menu) menu.classList.add('hidden');
// 调用纯 JS 高级弹窗
const newTitle = await window.showRenamePrompt(currentTitle);
if (!newTitle || newTitle === "" || newTitle === currentTitle) return;
const token = localStorage.getItem('access_token');
try {
const res = await fetch(`/api/conversations/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ title: newTitle })
});
const data = await res.json();
if (!res.ok || !data.success) throw new Error(data.error || "Server error");
const task = window.state.tasks.find(t => t.id == id);
if (task) task.title = newTitle;
if (window.state.currentSessionId == id) window.updateChatTitle(newTitle);
localStorage.setItem('sm_agent_tasks', JSON.stringify(window.state.tasks));
window.updateDrawerTasks();
window.showToast(window.i18nCache ? window.i18nCache['history.toast.rename_succ'] : "Renamed successfully", "success");
} catch (e) {
const task = window.state.tasks.find(t => t.id == id);
if (task) task.title = newTitle;
if (window.state.currentSessionId == id) window.updateChatTitle(newTitle);
localStorage.setItem('sm_agent_tasks', JSON.stringify(window.state.tasks));
window.updateDrawerTasks();
window.showToast(window.i18nCache ? window.i18nCache['history.toast.rename_succ'] : "Renamed successfully", "success");
}
};
// 4. 真实动作:彻底删除会话(弹窗双重确认)
window.handleDeleteSession = async function(event, id) {
if(event) event.stopPropagation();
const menu = document.getElementById(`hist-menu-${id}`);
if(menu) menu.classList.add('hidden');
const confirmText = window.t('history.del.confirm', "Are you sure you want to delete this session? This action cannot be undone.");
const confirm = window.showConfirm ? await window.showConfirm(confirmText) : window.confirm(confirmText);
if (!confirm) return;
const token = localStorage.getItem('access_token');
try {
await fetch(`/api/conversations/${id}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
window.state.tasks = window.state.tasks.filter(t => t.id != id);
if (window.state.currentSessionId == id) {
window.state.currentSessionId = null;
document.getElementById('landing-view')?.classList.remove('hidden');
document.getElementById('chat-stream')?.classList.add('hidden');
document.getElementById('bottom-bar')?.classList.add('hidden');
document.getElementById('chat-header-container')?.classList.add('hidden');
}
window.updateDrawerTasks();
window.showToast(window.t('history.toast.del', "🗑️ Record destroyed"), "success");
} catch (e) {
window.state.tasks = window.state.tasks.filter(t => t.id != id);
if (window.state.currentSessionId == id) {
window.state.currentSessionId = null;
location.reload();
} else {
window.updateDrawerTasks();
}
window.showToast(window.t('history.del.local', "Deleted (Local Cache)"), "success");
}
};
// 5. 动作:分享链接拷贝
window.handleShareSession = function(event, id) {
if(event) event.stopPropagation();
document.getElementById(`hist-menu-${id}`)?.classList.add('hidden');
const shareLink = `${window.location.origin}/share/${id}`;
navigator.clipboard.writeText(shareLink).then(() => {
window.showToast(window.i18nCache ? window.i18nCache['history.toast.share'] : "🔗 Link copied", "success");
});
};
// 6. 动作:钉住固定会话
window.handlePinSession = async function(event, id, pinStatus) {
if(event) event.stopPropagation();
document.getElementById(`hist-menu-${id}`)?.classList.add('hidden');
const token = localStorage.getItem('access_token');
try {
await fetch(`/api/conversations/${id}/pin`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ isPinned: pinStatus })
});
} catch (e) { } // 无论后端有无,前端必须生效
const task = window.state.tasks.find(t => t.id == id);
if (task) task.isPinned = pinStatus;
window.updateDrawerTasks();
window.showToast(pinStatus ? (window.i18nCache?window.i18nCache['history.toast.pin']:"📌 Pinned") : (window.i18nCache?window.i18nCache['history.toast.unpin']:"Unpinned"), "success");
};
// ========================================================
// 🏢 工作区 (Workspace) 核心逻辑全家桶 (满血修复版)
// ========================================================
window.showWorkspaceHub = function() {
// 拦截:如果没登录,直接弹登录框,不准进大厅
if (window.state && window.state.isGuest) {
window.openAuthModal('login');
return;
}
document.getElementById('landing-view')?.classList.add('hidden');
document.getElementById('chat-stream')?.classList.add('hidden');
document.getElementById('bottom-bar')?.classList.add('hidden');
document.getElementById('chat-header-container')?.classList.add('hidden');
document.getElementById('workspace-hub-view')?.classList.remove('hidden');
if (typeof window.loadWorkspacesFromCloud === 'function') {
window.loadWorkspacesFromCloud();
}
};
window.openCreateWsModal = function() {
const modal = document.getElementById('ws-modal');
if (!modal) return;
const palette = document.getElementById('ws-color-palette');
if (palette && palette.children.length === 0) {
palette.innerHTML = window.WS_COLORS.map(c => `
`).join('');
window.selectWsColor(palette.firstElementChild, window.WS_COLORS[0]);
}
const nameInput = document.getElementById('ws-name-input');
const goalInput = document.getElementById('ws-goal-input');
if (nameInput) nameInput.value = '';
if (goalInput) goalInput.value = '';
modal.classList.remove('hidden');
};
window.closeWsModal = function() {
document.getElementById('ws-modal')?.classList.add('hidden');
};
window.selectWsColor = function(btn, color) {
if (!window.state) window.state = {};
window.state.tempColor = color;
document.querySelectorAll('#ws-color-palette button').forEach(b => {
b.style.borderColor = 'transparent';
b.style.transform = 'scale(1)';
});
if (btn) {
btn.style.borderColor = 'rgba(255, 255, 255, 0.8)';
btn.style.transform = 'scale(1.15)';
}
};
window.handleCreateWorkspace = async function() {
const nameInput = document.getElementById('ws-name-input');
const goalInput = document.getElementById('ws-goal-input');
if (!nameInput || !nameInput.value.trim()) {
window.showToast(window.t ? window.t('ws.toast.name_req', "Please enter a workspace name") : "Please enter a workspace name", "warning");
return;
}
const token = localStorage.getItem('access_token');
try {
const res = await fetch('/api/workspaces', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({
name: nameInput.value.trim(),
goal: goalInput ? goalInput.value.trim() : "",
color: window.state.tempColor || window.WS_COLORS[0]
})
});
const data = await res.json();
if (data.success) {
window.showToast(window.t ? window.t('ws.toast.created', "✅ Workspace created!") : "✅ Workspace created!", "success");
window.closeWsModal();
window.loadWorkspacesFromCloud();
} else {
window.showToast(data.error || (window.t ? window.t('ws.toast.create_fail', "Creation failed") : "Creation failed"), "error");
}
} catch (error) {
window.showToast(window.t ? window.t('toast.net_err', "Network error") : "Network error", "error");
}
};
window.loadWorkspacesFromCloud = async function() {
const token = localStorage.getItem('access_token');
if (!token) return;
try {
const res = await fetch('/api/workspaces', {
method: 'GET',
headers: { 'Authorization': `Bearer ${token}` }
});
const data = await res.json();
if (data.success && data.data) {
window.state.workspaces = data.data;
window.renderWorkspaceGrid();
}
} catch (error) {
console.error("Failed to load workspace list:", error);
}
};
window.renderWorkspaceGrid = function() {
const grid = document.getElementById('workspace-grid');
if (!grid) return;
const workspaces = window.state.workspaces || [];
let tEmpty = 'No Workspaces Yet';
let dEmpty = 'Create a project and invite team members to share context and files.';
let tag = 'Team Exclusive • Project Sync';
if(window.i18nCache){
tEmpty = window.i18nCache['ws.empty.title'] || tEmpty;
dEmpty = window.i18nCache['ws.empty.desc'] || dEmpty;
tag = window.i18nCache['ws.tag'] || tag;
}
if (workspaces.length === 0) {
grid.innerHTML = `
`;
} else {
grid.innerHTML = workspaces.map(ws => `
${ws.name.charAt(0).toUpperCase()}
${ws.name}
${ws.goal || ''}
${tag}
`).join('');
}
if (typeof lucide !== 'undefined') lucide.createIcons();
};
window.enterWorkspace = function(wsId, loadMainThread = true) {
let ws = window.state.workspaces.find(w => w.id === wsId);
if (!ws) ws = { id: wsId, name: 'Workspace', goal: '', color: '#3b82f6' };
window.state.activeWorkspaceId = wsId;
window.state.intent = ws.goal || 'Project';
window.state.id = 'Member';
window.state.activeView = 'Member';
window.state.currentSessionId = null;
document.getElementById('workspace-hub-view')?.classList.add('hidden');
document.getElementById('landing-view')?.classList.add('hidden');
document.getElementById('chat-stream')?.classList.remove('hidden');
document.getElementById('bottom-bar')?.classList.remove('hidden');
let tGoal = 'Project Goal: ';
let noGoal = 'No goal set';
let lMem = 'Loading members...';
let bInv = 'Invite Members';
let bDoc = 'Attachments';
let bSync = 'Sync Progress';
if(window.i18nCache){
tGoal = window.i18nCache['ws.target'] || tGoal;
noGoal = window.i18nCache['ws.no_target'] || noGoal;
lMem = window.i18nCache['ws.loading_mem'] || lMem;
bInv = window.i18nCache['ws.btn.invite'] || bInv;
bDoc = window.i18nCache['ws.btn.docs'] || bDoc;
bSync = window.i18nCache['ws.btn.sync'] || bSync;
}
document.getElementById('chat-stream').innerHTML = `
${ws.name.charAt(0).toUpperCase()}
${ws.name}
${tGoal}${ws.goal || noGoal}
${lMem}
${bInv}
${bDoc}
${bSync}
`;
window.updateChatTitle(ws.name);
const input = document.getElementById('bottom-input');
if (input) {
let ph = `Send command in project ${ws.name}...`;
if(window.i18nCache && window.i18nCache['prompt.ws']) ph = window.i18nCache['prompt.ws'].replace('${wsName}', ws.name);
input.placeholder = ph;
input.focus();
}
if (typeof lucide !== 'undefined') lucide.createIcons();
window.loadWorkspaceMembers(wsId);
if (loadMainThread) window.loadWorkspaceMainThread(wsId);
};
window.loadWorkspaceMainThread = async function(wsId) {
const token = localStorage.getItem('access_token');
try {
const res = await fetch(`/api/workspaces/${wsId}/main_thread`, {
headers: { 'Authorization': `Bearer ${token}` }
});
const data = await res.json();
if (data.success && data.conversation_id) {
window.state.currentSessionId = data.conversation_id;
const targetBox = document.getElementById('ws-messages-container');
if (!targetBox) return;
let sStr = 'Syncing War Room...';
let nStr = 'This is a new project thread. Send a message to start collaborating.';
if(window.i18nCache){
sStr = window.i18nCache['ws.syncing'] || sStr;
nStr = window.i18nCache['ws.new_thread'] || nStr;
}
targetBox.innerHTML = ` ${sStr}
`;
if (typeof lucide !== 'undefined') lucide.createIcons();
const histRes = await fetch(`/api/conversations/${data.conversation_id}/messages`, {
headers: { 'Authorization': `Bearer ${token}` }
});
const histData = await histRes.json();
if (histData.success) {
targetBox.innerHTML = '';
window.state.history = [];
if (histData.data.length === 0) {
targetBox.insertAdjacentHTML('beforeend', `${nStr}
`);
return;
}
histData.data.forEach(msg => {
const uiRole = msg.role === 'user' ? 'user' : 'ai';
let displayContent = msg.content || "";
let extractedAttachments = [];
if (uiRole === 'user' && displayContent.includes("【附件参考资料 - ")) {
const parts = displayContent.split("【附件参考资料 - ");
displayContent = parts[0].trim();
for (let i = 1; i < parts.length; i++) {
const filenameEnd = parts[i].indexOf("】");
if (filenameEnd !== -1) {
const filename = parts[i].substring(0, filenameEnd);
const type = filename.match(/\.(jpg|jpeg|png|gif|webp)$/i) ? 'image' : 'file';
extractedAttachments.push({ filename, type });
}
}
}
if (typeof appendMessage === 'function') {
appendMessage(uiRole, displayContent, extractedAttachments);
}
const llmRole = msg.role === 'user' ? 'user' : 'model';
window.state.history.push({ role: llmRole, content: msg.content });
});
setTimeout(() => {
if (typeof window.renderCharts === 'function') window.renderCharts();
const blocks = document.querySelectorAll('#chat-stream pre code');
if (blocks.length > 0) {
const isMermaid = (text) => /^\s*(graph|flowchart|sequenceDiagram|gantt|pie|classDiagram|stateDiagram|erDiagram|journey|quadrantChart)\b/mi.test(text);
const hasMermaid = Array.from(blocks).some(b => {
let t = b.textContent.replace(/:/g, ':').replace(/;/g, ';');
return isMermaid(t);
});
if (hasMermaid && typeof mermaid === 'undefined') {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js';
script.onload = () => {
mermaid.initialize({ startOnLoad: false, theme: 'default', suppressErrorRendering: true });
if (typeof renderMermaidBlocks === 'function') renderMermaidBlocks(document.getElementById('chat-stream'));
};
document.head.appendChild(script);
} else if (typeof mermaid !== 'undefined' && typeof renderMermaidBlocks === 'function') {
renderMermaidBlocks(document.getElementById('chat-stream'));
}
}
if (typeof lucide !== 'undefined') lucide.createIcons();
}, 50);
setTimeout(() => {
const scroller = document.getElementById('main-scroll-area');
if (scroller) scroller.scrollTop = scroller.scrollHeight;
}, 100);
}
}
} catch (e) {}
};
window.openWsAttachments = function(wsId) {
const existing = document.getElementById('ws-attachments-modal');
if (existing) existing.remove();
let tDoc = 'Project Attachments';
let dDoc = 'Directory of historical files fed to the AI in this project. For reference only; downloading source files is not supported.';
let sDoc = 'Inventorying database...';
let eDoc = 'No attachments';
if(window.i18nCache){
tDoc = window.i18nCache['ws.docs.title'] || tDoc;
dDoc = window.i18nCache['ws.docs.desc'] || dDoc;
sDoc = window.i18nCache['ws.docs.syncing'] || sDoc;
eDoc = window.i18nCache['ws.docs.empty'] || eDoc;
}
const modalHtml = `
`;
document.body.insertAdjacentHTML('beforeend', modalHtml);
if (typeof lucide !== 'undefined') lucide.createIcons();
let fileListHtml = '';
let fileCount = 0;
const seenFiles = new Set();
(window.state.history || []).forEach(msg => {
if (msg.role === 'user' && msg.content) {
const regex = /【附件参考资料 - (.*?)】|\[(.*?\.[a-zA-Z0-9]+)\]/g;
let match;
while ((match = regex.exec(msg.content)) !== null) {
const filename = match[1] || match[2];
if (!filename || seenFiles.has(filename)) continue;
seenFiles.add(filename);
fileCount++;
let iconType = 'file-text';
if (filename.match(/\.(jpg|jpeg|png|gif|webp)$/i)) iconType = 'image';
else if (filename.match(/\.(xlsx|xls|csv)$/i)) iconType = 'file-spreadsheet';
else if (filename.match(/\.(pptx|ppt)$/i)) iconType = 'presentation';
fileListHtml += `
`;
}
}
});
if (fileCount === 0) {
fileListHtml = `
`;
}
document.getElementById('ws-attachments-list').innerHTML = fileListHtml;
if (typeof lucide !== 'undefined') lucide.createIcons();
};
window.loadWorkspaceMembers = async function(wsId) {
const token = localStorage.getItem('access_token');
try {
const res = await fetch(`/api/workspaces/${wsId}/members`, { headers: { 'Authorization': `Bearer ${token}` }});
const data = await res.json();
const container = document.getElementById('ws-members-container');
if (!container) return;
let unStr = 'Unnamed';
let errStr = 'Failed to load member wall';
if(window.i18nCache){
unStr = window.i18nCache['ws.mem.unnamed'] || unStr;
errStr = window.i18nCache['ws.mem.fail'] || errStr;
}
if (data.success && data.data) {
container.innerHTML = data.data.map(m => `
${m.role === 'owner' ? '👑 ' : ''}
${m.username || m.email || unStr}
`).join('');
} else {
container.innerHTML = `${errStr} `;
}
} catch (e) {}
};
window.openInviteModal = function(wsId) {
const existing = document.getElementById('invite-member-modal');
if (existing) existing.remove();
let tInv = 'Invite Team Members';
let dInv = "Enter a member's email (an invite link will be sent if unregistered) to bring them into the War Room to share memory and compute.";
let phInv = 'Enter email (e.g., user@company.com)';
let bInv = 'Send Invite';
if(window.i18nCache){
tInv = window.i18nCache['ws.invite.title'] || tInv;
dInv = window.i18nCache['ws.invite.desc'] || dInv;
phInv = window.i18nCache['ws.invite.ph'] || phInv;
bInv = window.i18nCache['ws.invite.btn'] || bInv;
}
const modalHtml = `
`;
document.body.insertAdjacentHTML('beforeend', modalHtml);
if (typeof lucide !== 'undefined') lucide.createIcons();
document.getElementById('invite-email-input').focus();
};
window.submitInvite = async function(wsId) {
const emailInput = document.getElementById('ws-invite-email-input');
const email = emailInput ? emailInput.value.trim() : '';
if (!email) {
window.showToast(window.i18nCache ? window.i18nCache['ws.invite.ph'] : "Please enter email", "warning");
return;
}
const token = localStorage.getItem('access_token');
const btn = document.querySelector('#invite-member-modal button.bg-blue-600');
if(btn) { btn.disabled = true; btn.innerHTML = window.i18nCache ? window.i18nCache['ws.invite.loading'] : 'Validating...'; }
try {
const res = await fetch(`/api/workspaces/${wsId}/members`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ email: email })
});
const data = await res.json();
if (data.success) {
// [修复] 拦截后端传来的暗号,如果后端什么都没传,强制用默认暗号兜底,杜绝空胶囊
const msgKey = data.message || 'ws.toast.invite_succ';
const succMsg = window.t ? window.t(msgKey, '✅ Success') : '✅ Success';
window.showToast(succMsg, "success");
document.getElementById('invite-member-modal').remove();
window.loadWorkspaceMembers(wsId);
} else {
// [修复] 拦截报错暗号,去字典提货。哪怕字典里没有,也能直接显示报错信息
const errKey = data.error || 'ws.toast.invite_fail';
const errMsg = window.t ? window.t(errKey, errKey) : errKey;
window.showToast(errMsg, "error");
if(btn) { btn.disabled = false; btn.innerHTML = window.t ? window.t('ws.invite.resend', 'Resend') : 'Resend'; }
}
} catch (e) {
window.showToast(window.i18nCache ? window.i18nCache['toast.net_err'] : "Network error", "error");
if(btn) { btn.disabled = false; btn.innerHTML = window.i18nCache ? window.i18nCache['ws.invite.btn'] : 'Send Invite'; }
}
};
// ==========================================
// 账户面板:修改昵称功能 (复用原生组件)
// ==========================================
window.editNickname = async function() {
const nameEl = document.getElementById('panel-nickname');
if (!nameEl) return;
// 兼容中文旧缓存和英文新字典
let noNickStr = window.i18nCache ? window.i18nCache['panel.acc.no_nick'] : "No nickname set";
const currentName = (nameEl.innerText === noNickStr || nameEl.innerText === "未设置昵称") ? "" : nameEl.innerText;
let titleStr = window.i18nCache ? window.i18nCache['ws.rename.title'] : 'Change Nickname';
const newName = await window.showRenamePrompt(currentName, titleStr);
if (!newName || newName.trim() === "" || newName === currentName) return;
const token = localStorage.getItem('access_token');
try {
const res = await fetch('/api/account/update_nickname', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ nickname: newName.trim() })
});
const data = await res.json();
if (data.status === 'success') {
nameEl.innerText = data.nickname;
let userStr = localStorage.getItem('sm_user');
if (userStr) {
let u = JSON.parse(userStr); u.username = data.nickname;
localStorage.setItem('sm_user', JSON.stringify(u));
}
let succStr = window.i18nCache ? window.i18nCache['toast.nick_succ'] : "✅ Nickname updated successfully";
if (window.Notice) window.Notice.show(succStr, "success");
else window.showToast(succStr, "success");
} else {
let failStr = window.i18nCache ? window.i18nCache['toast.nick_fail'] : "Update failed";
if (window.Notice) window.Notice.show(data.message || failStr, "error");
else window.showToast(data.message || failStr, "error");
}
} catch (error) {
let errStr = window.i18nCache ? window.i18nCache['toast.net_err'] : "Network error";
if (window.Notice) window.Notice.show(errStr, "error");
else window.showToast(errStr, "error");
}
};
// [大陆专版] 新增独立支付逻辑
window.openCnyCheckout = async function() {
const token = localStorage.getItem('access_token');
if (!token) {
window.openAuthModal('login');
return;
}
const user = JSON.parse(localStorage.getItem('sm_user') || '{}');
const safeEmail = user.email || (window.state && window.state.user && window.state.user.email) || '';
window.showToast(window.t('toast.payment_env', '正在建立支付环境...'), "info", 1000);
let checkoutConfig = {
items: [{ priceId: 'pri_01kr2mekn3b8mb3hvgx13b80mq', quantity: 1 }]
};
if (safeEmail && safeEmail.includes('@')) {
checkoutConfig.customer = { email: safeEmail };
}
Paddle.Checkout.open(checkoutConfig);
};
window.deleteWorkspace = async function(event, wsId) {
event.stopPropagation(); // 阻止进入工作区
// 唤起您系统原生的自定义美化弹窗,它会自动去读字典里的确定/取消按钮
const confirmMsg = "Are you sure?";
const isConfirmed = window.showConfirm ? await window.showConfirm(confirmMsg) : window.confirm(confirmMsg);
if (!isConfirmed) return;
const token = localStorage.getItem('access_token');
try {
await fetch(`/api/workspaces/${wsId}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
} catch (e) {
console.error("Cloud delete failed", e);
}
// 清理内存并持久化
window.state.workspaces = window.state.workspaces.filter(ws => ws.id !== wsId);
localStorage.setItem('sm_agent_workspaces', JSON.stringify(window.state.workspaces));
// 重新画界面
if (typeof window.renderWorkspaceGrid === 'function') {
window.renderWorkspaceGrid();
}
// 弹窗提示
let delSuccMsg = window.i18nCache ? window.i18nCache['history.toast.del'] : "🗑️ Workspace deleted";
if (window.Notice) {
window.Notice.show(delSuccMsg, "success");
} else if (window.showToast) {
window.showToast(delSuccMsg, "success");
}
};