Spaces:
Runtime error
Runtime error
Download app.js from shensuming/gemini: direct link, hf CLI and curl.
- Browser
- Download file 84.6 kB
-
https://huggingface.co/spaces/shensuming/gemini/resolve/main/app.js
- Command line
-
hf download hf://spaces/shensuming/gemini/app.js
-
curl -L -o app.js https://huggingface.co/spaces/shensuming/gemini/resolve/main/app.js
84.6 kB
// 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 = `
<div class="animate-fade-in px-2">
<h3 class="text-2xl font-black text-slate-900 mb-6 tracking-tight" data-i18n="auth.mode.login">Member Login</h3>
<div class="space-y-6">
<input type="text" id="login-id" placeholder="Phone / Email" data-i18n="auth.mode.login_id" class="w-full px-4 py-4 rounded-xl border border-slate-100 bg-slate-50 outline-none focus:border-blue-500 text-lg">
<input type="password" id="login-pwd" placeholder="Password" data-i18n="auth.mode.login_pwd" class="w-full px-4 py-4 rounded-xl border border-slate-100 bg-slate-50 outline-none focus:border-blue-500 text-lg">
<button onclick="handleLoginAction()" class="w-full py-4 bg-slate-900 text-white rounded-2xl font-black text-base shadow-xl active:scale-95 transition-all" data-i18n="auth.mode.login_btn">Log In</button>
</div>
<div class="mt-8 text-center text-[11px] text-slate-400">
<span data-i18n="auth.mode.login_no_acc">No account?</span> <span onclick="window.openAuthModal('email')" class="text-blue-600 cursor-pointer underline" data-i18n="auth.mode.login_reg">Sign up now</span>
</div>
</div>`;
} else if (window.state.authMode === 'sms') {
container.innerHTML = `
<div class="animate-fade-in px-2">
<h3 class="text-xl font-black text-slate-900 mb-4 tracking-tight" data-i18n="auth.mode.sms">Quick Login / Sign Up</h3>
<div class="space-y-6">
<div class="flex items-center border-b-2 border-slate-100 focus-within:border-blue-600 transition-all py-3">
<div onclick="toggleCountryDropdown()" class="relative flex items-center gap-1 cursor-pointer pr-4 border-r border-slate-100 mr-4 hover:bg-slate-50 px-2 py-1 rounded transition-all">
<span id="country-code-display" class="text-sm font-bold text-slate-900">🇨🇳 +86</span>
<i data-lucide="chevron-down" class="w-3 h-3 text-slate-400"></i>
</div>
<input type="tel" id="auth-phone" placeholder="Enter phone number" data-i18n="auth.mode.sms_phone" class="flex-1 bg-transparent border-none outline-none text-lg">
</div>
<button onclick="handleAuthSubmit('sms')" class="w-full py-4 bg-blue-600 text-white rounded-2xl font-black text-base shadow-xl active:scale-95 transition-all" data-i18n="auth.mode.sms_btn">Confirm</button>
</div>
<div class="mt-10 flex justify-between items-center text-[11px] text-slate-400">
<span onclick="window.openAuthModal('email')" class="cursor-pointer hover:text-blue-600 underline" data-i18n="auth.mode.sms_email">Sign up with email</span>
</div>
</div>`;
} else {
container.innerHTML = `
<div class="animate-fade-in text-left px-2">
<h3 class="text-xl font-black text-slate-900 mb-6 text-center tracking-widest" data-i18n="auth.mode.reg">Sign Up</h3>
<div class="space-y-3">
<input type="text" id="reg-username" placeholder="Username (Required)" data-i18n="auth.mode.reg_user" required class="w-full px-4 py-3 rounded-xl border border-slate-200 text-sm outline-none focus:border-blue-500">
<input type="email" id="reg-email" placeholder="Email (Required)" data-i18n="auth.mode.reg_email" required class="w-full px-4 py-3 rounded-xl border border-slate-200 text-sm outline-none focus:border-blue-500">
<input type="password" id="reg-password" placeholder="Password (Required)" data-i18n="auth.mode.reg_pwd" required class="w-full px-4 py-3 rounded-xl border border-slate-200 text-sm outline-none focus:border-blue-500">
<button onclick="handleAuthSubmit('email')" class="w-full py-4 bg-slate-900 text-white rounded-2xl font-bold text-sm mt-4 shadow-xl active:scale-95 transition-all" data-i18n="auth.mode.reg_btn">Sign Up</button>
</div>
</div>`;
}
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 = `<button class="w-full py-3 rounded-lg bg-slate-100 text-slate-400 font-bold cursor-default text-sm border border-slate-200 shadow-inner">${window.t('pricing.free.btn', '✓ Basic Edition')}</button>`;
} 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 = `<button onclick="window.openCnyCheckout()" class="w-full py-3 rounded-lg font-bold transition-all text-sm shadow-sm active:scale-95 bg-white text-slate-900 border border-slate-300 hover:bg-slate-50">${btnText}</button>`;
return;
}
el.innerHTML = `<button onclick="handleSubscription('${targetTier}')" class="w-full py-3 rounded-lg font-bold transition-all text-sm shadow-sm active:scale-95 ${style}">${btnText}</button>`;
}
};
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 = `
<div class="flex items-center gap-2 md:gap-3 relative">
<button onclick="window.openUserPanel('history')" class="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-slate-200 rounded-full shadow-sm hover:bg-slate-50 transition-all active:scale-95 whitespace-nowrap shrink-0">
<span class="text-amber-400 text-sm shrink-0">✨</span>
<span id="nav-points-display" class="text-sm font-bold text-slate-700 tabular-nums tracking-tight">${(window.state.user && window.state.user.points_balance !== undefined) ? window.state.user.points_balance.toLocaleString() : '...'}</span>
</button>
<div onclick="document.getElementById('user-popup').classList.toggle('hidden')" class="w-9 h-9 rounded-full shadow-sm overflow-hidden border border-slate-200 cursor-pointer active:scale-95 transition-all hover:ring-2 hover:ring-slate-200">
<img src="${userAvatar}" class="w-full h-full object-cover">
</div>
<div id="user-popup" class="hidden absolute top-12 right-0 w-64 bg-white border border-slate-100 rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] py-2 z-50">
<div class="px-4 py-3 flex items-center gap-3 border-b border-slate-50">
<div class="w-10 h-10 rounded-full overflow-hidden flex-shrink-0 border border-slate-100 bg-slate-50">
<img src="${userAvatar}" class="w-full h-full object-cover">
</div>
<div class="flex flex-col min-w-0">
<div class="text-sm font-bold text-slate-900 truncate">${userName}</div>
${userEmail ? `<div class="text-xs text-slate-500 truncate">${userEmail}</div>` : ''}
</div>
</div>
<div class="px-3 py-2 border-b border-slate-50">
<div class="flex items-center justify-between bg-slate-50 rounded-xl px-3 py-2 border border-slate-100">
<div class="text-sm font-semibold ${tierColor}">${tierName}</div>
<button onclick="window.togglePricingModal(true); document.getElementById('user-popup').classList.add('hidden')" class="px-3 py-1.5 text-xs font-bold rounded-lg transition-colors ${btnStyle}">
${btnText}
</button>
</div>
</div>
<div class="px-2 py-1 flex flex-col gap-0.5 border-b border-slate-50 max-h-[40vh] overflow-y-auto no-scrollbar">
<button onclick="window.openUserPanel('account'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="user" class="w-4 h-4"></i>${window.t('panel.nav.account', 'Account')}</button>
<button onclick="window.openUserPanel('settings'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="settings" class="w-4 h-4"></i>${window.t('panel.nav.settings', 'Settings')}</button>
<button onclick="window.openUserPanel('history'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="clock" class="w-4 h-4"></i>${window.t('panel.nav.history', 'Points & Workspaces')}</button>
<button onclick="window.openUserPanel('help'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="help-circle" class="w-4 h-4"></i>${window.t('panel.nav.help', 'Help Center')}</button>
<button onclick="window.openUserPanel('invite'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="gift" class="w-4 h-4"></i>${window.t('panel.nav.invite', 'Invite & Rewards')}</button>
<button onclick="window.openUserPanel('privacy'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="shield" class="w-4 h-4"></i>${window.t('panel.nav.privacy', 'Privacy Policy')}</button>
<button onclick="window.openUserPanel('terms'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="file-text" class="w-4 h-4"></i>${window.t('panel.nav.terms', 'Terms')}</button>
<button onclick="window.openUserPanel('report'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="alert-circle" class="w-4 h-4"></i>${window.t('panel.nav.report', 'Report Issue')}</button>
<button onclick="window.openUserPanel('about'); document.getElementById('user-popup').classList.add('hidden')" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-slate-600 hover:bg-slate-50 hover:text-slate-900 transition-colors text-left"><i data-lucide="info" class="w-4 h-4"></i>${window.t('panel.nav.about', 'About Us')}</button>
</div>
<div class="px-2 pt-1 pb-1">
<button onclick="if(window.handleLogout) window.handleLogout(); else handleLogout();" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-red-500 hover:bg-red-50 transition-colors text-left">
<i data-lucide="log-out" class="w-4 h-4"></i>${window.t('ui.btn.logout', 'Log Out')}
</button>
</div>
</div>
</div>`;
// 【架构升级】:移交控制权给全局积分同步引擎
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 = `<button onclick="window.openAuthModal('login')" class="px-5 py-2 bg-[#1f1f1f] text-white rounded-xl text-sm font-bold shadow-lg">${window.t('ui.btn.login', 'Log In')}</button>
<button onclick="window.openAuthModal('email')" class="px-5 py-2 bg-white border border-slate-200 text-slate-700 rounded-xl text-sm font-bold shadow-sm active:scale-95 transition-all">${window.t('ui.btn.register', 'Sign Up')}</button>`;
}
// [行为] 物理补丁: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 = '<div class="py-12 px-6 text-center text-slate-400 text-xs" data-i18n="history.empty">No history yet</div>';
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 ? `<i data-lucide="pin" class="w-3 h-3 text-slate-400 stroke-[1px] fill-transparent shrink-0 mr-1.5"></i>` : '';
// [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 `
<div class="relative px-4 py-3 mb-1 group transition-colors ${bgClass} rounded-lg flex items-center justify-between">
<div class="flex-1 min-w-0 cursor-pointer pr-2" onclick="event.stopPropagation(); window.switchToHistory('${t.id}', '${view}', '${intent}', '${safeTitle}')">
<div class="flex items-center">
${pinIcon}
<p class="text-xs ${titleClass} truncate transition-colors">${title}</p>
</div>
<p class="text-[9px] text-slate-400 mt-1 tracking-wider uppercase truncate">${t.time || ''}${view ? ' | ' + view : ''}${intent ? ' | ' + intent : ''}</p>
</div>
<div class="relative opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
<button onclick="window.toggleHistoryMenu(event, '${t.id}')" class="p-1.5 text-slate-400 hover:bg-white hover:shadow-sm hover:text-slate-900 rounded-md transition-all">
<i data-lucide="more-vertical" class="w-4 h-4"></i>
</button>
<div id="hist-menu-${t.id}" class="hidden absolute right-0 top-full mt-1 w-32 bg-white border border-slate-100 rounded-xl shadow-xl z-[100] py-1 text-xs">
<button onclick="window.handleShareSession(event, '${t.id}')" class="w-full text-left px-3 py-2 text-slate-600 hover:bg-slate-50 flex items-center gap-2">
<i data-lucide="share-2" class="w-3.5 h-3.5"></i> ${shareStr}
</button>
<button onclick="window.handlePinSession(event, '${t.id}', ${!t.isPinned})" class="w-full text-left px-3 py-2 text-slate-600 hover:bg-slate-50 flex items-center gap-2">
<i data-lucide="pin" class="w-3.5 h-3.5"></i> ${t.isPinned ? unpinStr : pinStr}
</button>
<button onclick="window.handleRenameSession('${t.id}', '${safeTitle}', event)" class="w-full text-left px-3 py-2 text-slate-600 hover:bg-slate-50 flex items-center gap-2">
<i data-lucide="edit-3" class="w-3.5 h-3.5"></i> ${renameStr}
</button>
<div class="h-px bg-slate-100 my-1 mx-2"></div>
<button onclick="window.handleDeleteSession(event, '${t.id}')" class="w-full text-left px-3 py-2 text-red-500 hover:bg-red-50 flex items-center gap-2">
<i data-lucide="trash-2" class="w-3.5 h-3.5"></i> ${delStr}
</button>
</div>
</div>
</div>
`}).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 = `<div id="loading-hist" class="text-center text-slate-400 text-xs py-10"><i data-lucide="loader-2" class="w-5 h-5 animate-spin mx-auto mb-2"></i>${syncStr}</div>`;
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 = `<div class="text-center text-slate-400 text-xs py-10">${emptyStr}</div>`;
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 = `<div class="text-center text-red-400 text-xs py-10">${failStr}</div>`;
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 = `
<div class="bg-white rounded-2xl shadow-2xl p-6 max-w-sm w-full mx-4">
<h3 class="text-slate-800 text-sm font-bold mb-4 text-center">${finalTitle}</h3>
<input type="text" class="w-full bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500 outline-none mb-6 text-slate-700 font-medium" value="${currentTitle}">
<div class="flex gap-3">
<button class="prompt-cancel flex-1 py-2.5 bg-slate-100 text-slate-600 rounded-xl text-sm font-bold hover:bg-slate-200">${window.t('btn.cancel', 'Cancel')}</button>
<button class="prompt-ok flex-1 py-2.5 bg-slate-800 text-white rounded-xl text-sm font-bold hover:bg-slate-900 shadow-sm active:scale-95">${window.t('btn.save', 'Save')}</button>
</div>
</div>
`;
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 => `
<button onclick="window.selectWsColor(this, '${c}')" class="w-8 h-8 rounded-full border-2 border-transparent transition-all hover:scale-110" style="background-color: ${c}"></button>
`).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 = `
<div class="col-span-full py-16 text-center border-2 border-dashed border-slate-200 rounded-3xl bg-slate-50/50">
<div class="w-16 h-16 mx-auto mb-4 bg-white rounded-2xl shadow-sm flex items-center justify-center text-slate-300">
<i data-lucide="briefcase" class="w-8 h-8"></i>
</div>
<h3 class="text-sm font-bold text-slate-700 mb-1">${tEmpty}</h3>
<p class="text-xs text-slate-400">${dEmpty}</p>
</div>
`;
} else {
grid.innerHTML = workspaces.map(ws => `
<div onclick="window.enterWorkspace('${ws.id}')" class="group relative bg-white border border-slate-200 rounded-[20px] p-6 hover:shadow-xl hover:-translate-y-1 transition-all cursor-pointer overflow-hidden">
<div class="absolute top-0 left-0 w-full h-1.5" style="background-color: ${ws.color || '#3b82f6'}"></div>
<div class="flex items-start justify-between mb-4 mt-1">
<div class="w-12 h-12 rounded-[14px] flex items-center justify-center text-white shadow-sm" style="background-color: ${ws.color || '#3b82f6'}">
<span class="text-xl font-black">${ws.name.charAt(0).toUpperCase()}</span>
</div>
<button onclick="window.deleteWorkspace(event, '${ws.id}')" class="opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-red-500 transition-all"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path></svg></button>
</div>
<h3 class="text-lg font-bold text-slate-800 mb-2 truncate">${ws.name}</h3>
<p class="text-xs text-slate-500 line-clamp-2 mb-4 h-8">${ws.goal || ''}</p>
<div class="flex items-center justify-between pt-4 border-t border-slate-50">
<span class="text-[10px] font-bold text-slate-400 flex items-center gap-1">
<i data-lucide="database" class="w-3 h-3"></i> ${tag}
</span>
</div>
</div>
`).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 = `
<div class="flex flex-col items-center justify-center py-10 text-center animate-fade-in mt-6 border-b border-slate-100 pb-8 mb-6">
<div class="w-16 h-16 rounded-2xl mb-4 flex items-center justify-center text-white shadow-lg" style="background-color: ${ws.color || '#3b82f6'}">
<span class="text-3xl font-black">${ws.name.charAt(0).toUpperCase()}</span>
</div>
<h2 class="text-2xl font-black text-slate-800 mb-2">${ws.name}</h2>
<p class="text-sm text-slate-500 max-w-md mx-auto leading-relaxed px-4"><i data-lucide="target" class="w-4 h-4 inline text-blue-500 mr-1 relative -top-0.5"></i> ${tGoal}${ws.goal || noGoal}</p>
<div id="ws-members-container" class="mt-6 flex flex-wrap justify-center items-center gap-2 min-h-[40px]">
<span class="text-xs text-slate-400">${lMem}</span>
</div>
<div class="mt-8 flex flex-wrap justify-center gap-4">
<button onclick="window.openInviteModal('${wsId}')" class="px-5 py-2.5 bg-slate-900 text-white rounded-xl text-sm font-bold shadow-md hover:bg-slate-800 transition-all flex items-center gap-2">
<i data-lucide="user-plus" class="w-4 h-4"></i> ${bInv}
</button>
<button onclick="window.openWsAttachments('${wsId}')" class="px-5 py-2.5 bg-white border border-slate-200 text-slate-700 rounded-xl text-sm font-bold shadow-sm hover:bg-slate-50 transition-all flex items-center gap-2">
<i data-lucide="list" class="w-4 h-4"></i> ${bDoc}
</button>
<button onclick="window.enterWorkspace('${wsId}')" class="px-5 py-2.5 bg-blue-50 border border-blue-100 text-blue-600 rounded-xl text-sm font-bold shadow-sm hover:bg-blue-100 transition-all flex items-center gap-2">
<i data-lucide="refresh-cw" class="w-4 h-4"></i> ${bSync}
</button>
</div>
</div>
<div id="ws-messages-container" class="w-full flex flex-col"></div>
`;
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 = `<div class="text-center text-slate-400 text-xs py-10"><i data-lucide="loader-2" class="w-5 h-5 animate-spin mx-auto mb-2"></i>${sStr}</div>`;
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', `<div class="text-center text-slate-400 text-xs py-10">${nStr}</div>`);
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 = `
<div id="ws-attachments-modal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/80 animate-fade-in">
<div class="bg-white rounded-[24px] shadow-2xl w-full max-w-md mx-4 p-8 relative flex flex-col max-h-[80vh]">
<button onclick="document.getElementById('ws-attachments-modal').remove()" class="absolute top-6 right-6 text-slate-400 hover:text-slate-600"><i data-lucide="x" class="w-5 h-5"></i></button>
<h3 class="text-xl font-bold text-slate-800 mb-2 shrink-0">${tDoc}</h3>
<p class="text-[11px] text-slate-500 mb-4 border-b border-slate-100 pb-4 shrink-0">${dDoc}</p>
<div id="ws-attachments-list" class="space-y-2 overflow-y-auto pr-2 flex-1 no-scrollbar">
<div class="text-center text-xs text-slate-400 py-6">${sDoc}</div>
</div>
</div>
</div>`;
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 += `
<div class="flex items-center justify-between p-3 bg-slate-50 rounded-xl border border-slate-100">
<div class="flex items-center gap-3 overflow-hidden">
<i data-lucide="${iconType}" class="w-4 h-4 text-slate-400 shrink-0"></i>
<span class="text-xs font-bold text-slate-700 truncate" title="${filename}">${filename}</span>
</div>
</div>
`;
}
}
});
if (fileCount === 0) {
fileListHtml = `
<div class="flex flex-col items-center justify-center py-8 text-slate-300">
<i data-lucide="folder-open" class="w-8 h-8 mb-3 opacity-50"></i>
<p class="text-xs font-medium">${eDoc}</p>
</div>
`;
}
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 => `
<div class="group flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-slate-100 border border-slate-200 shadow-sm transition-all hover:bg-slate-200 hover:shadow-md cursor-pointer ${m.role === 'owner' ? 'bg-blue-50 border-blue-100' : ''}" title="${m.email}">
${m.role === 'owner' ? '<span class="text-[12px] leading-none" title="Owner">👑</span>' : ''}
<span class="text-xs font-bold ${m.role === 'owner' ? 'text-blue-600' : 'text-slate-700'} whitespace-nowrap">
${m.username || m.email || unStr}
</span>
</div>
`).join('');
} else {
container.innerHTML = `<span class="text-xs text-red-400">${errStr}</span>`;
}
} 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 = `
<div id="invite-member-modal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-900/40 animate-fade-in">
<div class="bg-white rounded-[24px] shadow-2xl w-full max-w-md mx-4 p-8 relative">
<button onclick="document.getElementById('invite-member-modal').remove()" class="absolute top-6 right-6 text-slate-400 hover:text-slate-600">
<i data-lucide="x" class="w-5 h-5"></i>
</button>
<h3 class="text-xl font-bold text-slate-800 mb-2">${tInv}</h3>
<p class="text-sm text-slate-500 mb-6 border-b border-slate-100 pb-4">${dInv}</p>
<input type="email" id="ws-invite-email-input" placeholder="${phInv}" class="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 mb-6 font-mono">
<button onclick="window.submitInvite('${wsId}')" class="w-full py-3.5 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 transition-colors flex items-center justify-center gap-2">
${bInv}
</button>
</div>
</div>
`;
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");
}
};
// 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 = `
<div class="animate-fade-in px-2">
<h3 class="text-2xl font-black text-slate-900 mb-6 tracking-tight" data-i18n="auth.mode.login">Member Login</h3>
<div class="space-y-6">
<input type="text" id="login-id" placeholder="Phone / Email" data-i18n="auth.mode.login_id" class="w-full px-4 py-4 rounded-xl border border-slate-100 bg-slate-50 outline-none focus:border-blue-500 text-lg">
<input type="password" id="login-pwd" placeholder="Password" data-i18n="auth.mode.login_pwd" class="w-full px-4 py-4 rounded-xl border border-slate-100 bg-slate-50 outline-none focus:border-blue-500 text-lg">
<button onclick="handleLoginAction()" class="w-full py-4 bg-slate-900 text-white rounded-2xl font-black text-base shadow-xl active:scale-95 transition-all" data-i18n="auth.mode.login_btn">Log In</button>
</div>
<div class="mt-8 text-center text-[11px] text-slate-400">
<span data-i18n="auth.mode.login_no_acc">No account?</span> <span onclick="window.openAuthModal('email')" class="text-blue-600 cursor-pointer underline" data-i18n="auth.mode.login_reg">Sign up now</span>
</div>
</div>`;
} else if (window.state.authMode === 'sms') {
container.innerHTML = `
<div class="animate-fade-in px-2">
<h3 class="text-xl font-black text-slate-900 mb-4 tracking-tight" data-i18n="auth.mode.sms">Quick Login / Sign Up</h3>
<div class="space-y-6">
<div class="flex items-center border-b-2 border-slate-100 focus-within:border-blue-600 transition-all py-3">
<div onclick="toggleCountryDropdown()" class="relative flex items-center gap-1 cursor-pointer pr-4 border-r border-slate-100 mr-4 hover:bg-slate-50 px-2 py-1 rounded transition-all">
<span id="country-code-display" class="text-sm font-bold text-slate-900">🇨🇳 +86</span>
<i data-lucide="chevron-down" class="w-3 h-3 text-slate-400"></i>
</div>
<input type="tel" id="auth-phone" placeholder="Enter phone number" data-i18n="auth.mode.sms_phone" class="flex-1 bg-transparent border-none outline-none text-lg">
</div>
<button onclick="handleAuthSubmit('sms')" class="w-full py-4 bg-blue-600 text-white rounded-2xl font-black text-base shadow-xl active:scale-95 transition-all" data-i18n="auth.mode.sms_btn">Confirm</button>
</div>
<div class="mt-10 flex justify-between items-center text-[11px] text-slate-400">
<span onclick="window.openAuthModal('email')" class="cursor-pointer hover:text-blue-600 underline" data-i18n="auth.mode.sms_email">Sign up with email</span>
</div>
</div>`;
} else {
container.innerHTML = `
<div class="animate-fade-in text-left px-2">
<h3 class="text-xl font-black text-slate-900 mb-6 text-center tracking-widest" data-i18n="auth.mode.reg">Sign Up</h3>
<div class="space-y-3">
<input type="text" id="reg-username" placeholder="Username (Required)" data-i18n="auth.mode.reg_user" required class="w-full px-4 py-3 rounded-xl border border-slate-200 text-sm outline-none focus:border-blue-500">
<input type="email" id="reg-email" placeholder="Email (Required)" data-i18n="auth.mode.reg_email" required class="w-full px-4 py-3 rounded-xl border border-slate-200 text-sm outline-none focus:border-blue-500">
<input type="password" id="reg-password" placeholder="Password (Required)" data-i18n="auth.mode.reg_pwd" required class="w-full px-4 py-3 rounded-xl border border-slate-200 text-sm outline-none focus:border-blue-500">
<button onclick="handleAuthSubmit('email')" class="w-full py-4 bg-slate-900 text-white rounded-2xl font-bold text-sm mt-4 shadow-xl active:scale-95 transition-all" data-i18n="auth.mode.reg_btn">Sign Up</button>
</div>
</div>`;
}
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;