From e3b3aab4dd30a8e1ad4f978471eb76c3b78b49ac Mon Sep 17 00:00:00 2001 From: piexian <64474352+piexian@users.noreply.github.com> Date: Sun, 1 Mar 2026 03:24:47 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat(chat):=20=E6=B7=BB=E5=8A=A0=E5=A4=9A?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E7=AE=A1=E7=90=86=E4=B8=8E=20UI=20=E4=BA=A4?= =?UTF-8?q?=E4=BA=92=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现基于 localStorage 的多会话管理(创建/切换/删除/重命名) - 新增侧边栏会话列表,支持移动端滑入式布局 - 替换原生 select 为自定义模型/推理强度下拉菜单 - 支持消息编辑、删除、从指定位置重新生成 - 添加上下文压缩功能(保留最近 4 条消息) - 优化 public_key 认证:前端哈希存储,后端支持原始值与哈希匹配 - 改进思考过程展示:工具卡片彩色标识、自动折叠与计时优化 --- app/core/auth.py | 60 ++- app/static/common/js/admin-auth.js | 14 +- app/static/public/css/chat.css | 545 +++++++++++++++++++-- app/static/public/js/chat.js | 737 +++++++++++++++++++++++++++-- app/static/public/pages/chat.html | 105 +++- 5 files changed, 1336 insertions(+), 125 deletions(-) diff --git a/app/core/auth.py b/app/core/auth.py index 2cb45820..d01f54da 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -2,6 +2,7 @@ API 认证模块 """ +import hashlib from typing import Optional from fastapi import HTTPException, status, Security from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials @@ -53,6 +54,24 @@ def is_public_enabled() -> bool: return bool(get_config("app.public_enabled", DEFAULT_PUBLIC_ENABLED)) +def _hash_public_key(key: str) -> str: + """计算 public_key 的 SHA-256 哈希,与前端 hashPublicKey 保持一致。""" + return hashlib.sha256(f"grok2api-public:{key}".encode()).hexdigest() + + +def _match_public_key(credentials: str, public_key: str) -> bool: + """检查凭证是否匹配 public_key(支持原始值和 public- 哈希格式)。""" + if not public_key: + return False + if credentials == public_key: + return True + if credentials.startswith("public-"): + expected_hash = _hash_public_key(public_key) + if credentials == f"public-{expected_hash}": + return True + return False + + async def verify_api_key( auth: Optional[HTTPAuthorizationCredentials] = Security(security), ) -> Optional[str]: @@ -60,26 +79,39 @@ async def verify_api_key( 验证 Bearer Token 如果 config.toml 中未配置 api_key,则不启用认证。 + 同时支持面板通过 public_key 认证(原始值或 public- 哈希格式)。 + 若 public_enabled 且未配置 public_key,允许无认证访问。 """ api_key = get_admin_api_key() + public_key = get_public_api_key() + public_enabled = is_public_enabled() + if not api_key: return None + # 无认证头:仅在 public_enabled 且无 public_key 时放行 if not auth: + if public_enabled and not public_key: + return None raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing authentication token", headers={"WWW-Authenticate": "Bearer"}, ) - if auth.credentials != api_key: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication token", - headers={"WWW-Authenticate": "Bearer"}, - ) + # 标准 api_key 验证 + if auth.credentials == api_key: + return auth.credentials - return auth.credentials + # public_key 验证(原始值或哈希) + if _match_public_key(auth.credentials, public_key): + return auth.credentials + + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication token", + headers={"WWW-Authenticate": "Bearer"}, + ) async def verify_app_key( @@ -143,11 +175,11 @@ async def verify_public_key( headers={"WWW-Authenticate": "Bearer"}, ) - if auth.credentials != public_key: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid authentication token", - headers={"WWW-Authenticate": "Bearer"}, - ) + if _match_public_key(auth.credentials, public_key): + return auth.credentials - return auth.credentials + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid authentication token", + headers={"WWW-Authenticate": "Bearer"}, + ) diff --git a/app/static/common/js/admin-auth.js b/app/static/common/js/admin-auth.js index 36898d01..4022c06c 100644 --- a/app/static/common/js/admin-auth.js +++ b/app/static/common/js/admin-auth.js @@ -178,6 +178,13 @@ async function ensureAdminKey() { } } +async function hashPublicKey(key) { + if (!crypto?.subtle) return null; + const data = new TextEncoder().encode('grok2api-public:' + key); + const buf = await crypto.subtle.digest('SHA-256', data); + return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join(''); +} + async function ensurePublicKey() { if (cachedPublicKey !== null) return cachedPublicKey; @@ -195,14 +202,11 @@ async function ensurePublicKey() { return null; } - if (!key) { - return null; - } - try { const ok = await verifyKey('/v1/public/verify', key); if (!ok) throw new Error('Unauthorized'); - cachedPublicKey = `Bearer ${key}`; + const hash = await hashPublicKey(key); + cachedPublicKey = hash ? `Bearer public-${hash}` : `Bearer ${key}`; return cachedPublicKey; } catch (e) { clearStoredPublicKey(); diff --git a/app/static/public/css/chat.css b/app/static/public/css/chat.css index 2fdc4d35..6c9f4bec 100644 --- a/app/static/public/css/chat.css +++ b/app/static/public/css/chat.css @@ -11,17 +11,185 @@ body { background-color: var(--chat-bg); background-image: radial-gradient(circle at 20% 10%, rgba(17, 17, 17, 0.04), transparent 50%), radial-gradient(circle at 85% 0%, rgba(17, 17, 17, 0.03), transparent 50%); + height: 100vh; + overflow: hidden; } .chat-main { padding-bottom: 16px; + overflow: hidden; + display: flex; + flex-direction: column; +} + +.chat-layout { + display: flex; + gap: 0; + flex: 1; + min-height: 0; +} + +.chat-sidebar { + width: 260px; + flex-shrink: 0; + border-right: 1px solid var(--chat-border); + background: var(--chat-surface); + display: flex; + flex-direction: column; + border-radius: 16px 0 0 16px; + overflow: hidden; +} + +.sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px 16px 12px; + border-bottom: 1px solid var(--chat-border); +} + +.sidebar-title { + font-size: 14px; + font-weight: 600; + color: var(--chat-ink); +} + +.sidebar-new-btn { + width: 32px; + height: 32px; + border-radius: 8px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background 0.2s ease, border-color 0.2s ease; +} + +.sidebar-new-btn:hover { + background: var(--chat-muted); + border-color: #bbb; +} + +.sidebar-list { + flex: 1; + overflow-y: auto; + padding: 8px; +} + +.session-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 12px; + border-radius: 10px; + cursor: pointer; + transition: background 0.15s ease; + gap: 8px; +} + +.session-item:hover { + background: var(--chat-muted); +} + +.session-item.active { + background: var(--chat-soft); +} + +.session-title { + flex: 1; + min-width: 0; + font-size: 13px; + color: var(--chat-ink); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.session-delete { + flex-shrink: 0; + width: 24px; + height: 24px; + border: none; + background: transparent; + color: var(--accents-4); + font-size: 16px; + line-height: 1; + border-radius: 6px; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + opacity: 0; + transition: opacity 0.15s ease, color 0.15s ease, background 0.15s ease; +} + +.session-item:hover .session-delete { + opacity: 1; +} + +.session-delete:hover { + color: #b91c1c; + background: rgba(185, 28, 28, 0.08); +} + +.session-rename-input { + flex: 1; + min-width: 0; + font-size: 13px; + color: var(--chat-ink); + border: 1px solid var(--chat-border); + border-radius: 6px; + padding: 2px 6px; + background: var(--chat-surface); + outline: none; +} + +.session-rename-input:focus { + border-color: #111; +} + +.session-unread { + width: 8px; + height: 8px; + border-radius: 50%; + background: #22c55e; + flex-shrink: 0; +} + +.sidebar-overlay { + display: none; +} + +.sidebar-toggle { + display: none; + width: 36px; + height: 36px; + border-radius: 8px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + align-items: center; + justify-content: center; + cursor: pointer; + flex-shrink: 0; +} + +.sidebar-toggle:hover { + border-color: #bbb; } .chat-shell { + flex: 1; + min-width: 0; + min-height: 0; display: flex; flex-direction: column; gap: 20px; - min-height: calc(100vh - 56px - 64px); + padding-left: 24px; + overflow: hidden; } .chat-title { @@ -70,9 +238,10 @@ body { display: flex; flex-direction: column; gap: 18px; - min-height: 320px; + min-height: 0; padding-bottom: 12px; flex: 1; + overflow-y: auto; } .chat-empty { @@ -107,19 +276,72 @@ body { } .action-btn { - border: none; - background: transparent; + border: 1px solid var(--chat-border); + background: var(--chat-surface); color: var(--accents-4); font-size: 12px; - padding: 4px 6px; + padding: 4px 10px; border-radius: 999px; cursor: pointer; - transition: color 0.2s ease, background 0.2s ease; + transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease; } .action-btn:hover { color: var(--chat-ink); - background: rgba(17, 17, 17, 0.06); + border-color: #bbb; + background: rgba(17, 17, 17, 0.04); +} + +.edit-msg-input { + width: 100%; + min-height: 60px; + border: 1px solid var(--chat-border); + border-radius: 10px; + padding: 10px 12px; + font-size: 14px; + line-height: 1.5; + color: var(--chat-ink); + background: var(--chat-surface); + resize: vertical; + outline: none; + font-family: inherit; +} + +.edit-msg-input:focus { + border-color: #111; +} + +.edit-msg-actions { + display: flex; + gap: 8px; + margin-top: 8px; +} + +.message-row.editing { + align-items: flex-end; +} + +.message-row.editing .message-bubble { + background: transparent; + border: none; + border-radius: 0; + padding: 0; + width: 100%; + max-width: 100%; +} + +.message-row.user.editing { + align-items: flex-start; + width: 100%; +} + +.message-row.user.editing .message-bubble { + width: 100%; + max-width: 100%; + background: transparent; + border: none; + border-radius: 0; + padding: 0; } .message-bubble { @@ -415,6 +637,11 @@ body { display: none; } +@keyframes thinkSpin { + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } +} + @keyframes thinkGlow { 0% { box-shadow: 0 0 0 rgba(255, 255, 255, 0); @@ -430,6 +657,10 @@ body { } } +.think-block[data-thinking="true"] .think-summary::before { + animation: thinkSpin 1.6s linear infinite; +} + .think-block[data-thinking="true"] .think-agent summary { animation: thinkGlow 1.4s ease-in-out infinite; } @@ -515,37 +746,59 @@ body { gap: 6px; } +.think-tool-card { + background: #fafaf9; + border: 1px solid var(--chat-border); + border-radius: 10px; + padding: 8px 12px; + transition: border-color 0.2s ease; +} + +.think-tool-card:hover { + border-color: #ccc; +} + +.think-tool-card[data-tool-type="websearch"] { + border-left: 3px solid #3b82f6; + background: rgba(59, 130, 246, 0.04); +} + +.think-tool-card[data-tool-type="searchimage"] { + border-left: 3px solid #22c55e; + background: rgba(34, 197, 94, 0.04); +} + +.think-tool-card[data-tool-type="agentthink"] { + border-left: 3px solid #a855f7; + background: rgba(168, 85, 247, 0.04); +} + .think-item-type { - font-size: 12px; + font-size: 11px; + font-weight: 600; color: var(--accents-4); display: inline-flex; align-items: center; - gap: 8px; + gap: 4px; + text-transform: uppercase; + letter-spacing: 0.04em; } -.think-item-type::before { - content: ""; - width: 14px; - height: 14px; - background-color: var(--accents-4); - mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J005IDIxaDZ2LTFIOXYxem0zLTIwYTcgNyAwIDAwLTQgMTIuNzRWMTdhMSAxIDAgMDAxIDFoNmExIDEgMCAwMDEtMXYtMy4yNkE3IDcgMCAwMDEyIDF6Jy8+PC9zdmc+"); - mask-size: contain; - mask-repeat: no-repeat; - mask-position: center; - -webkit-mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J005IDIxaDZ2LTFIOXYxem0zLTIwYTcgNyAwIDAwLTQgMTIuNzRWMTdhMSAxIDAgMDAxIDFoNmExIDEgMCAwMDEtMXYtMy4yNkE3IDcgMCAwMDEyIDF6Jy8+PC9zdmc+"); - -webkit-mask-size: contain; - -webkit-mask-repeat: no-repeat; - -webkit-mask-position: center; +.think-tool-icon { + font-size: 13px; + line-height: 1; } -.think-item-type[data-type="websearch"]::before { - mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyMCAyMCcgZmlsbD0nYmxhY2snPjxwYXRoIGZpbGwtcnVsZT0nZXZlbm9kZCcgZD0nTTkgM2E2IDYgMCAxMDQuNDcyIDEwLjAxNmwzLjI1NiAzLjI1NmExIDEgMCAwMDEuNDE2LTEuNDE2bC0zLjI1Ni0zLjI1NkE2IDYgMCAwMDkgM3ptMCAyYTQgNCAwIDEwMCA4IDQgNCAwIDAwMC04eicgY2xpcC1ydWxlPSdldmVub2RkJy8+PC9zdmc+"); - -webkit-mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyMCAyMCcgZmlsbD0nYmxhY2snPjxwYXRoIGZpbGwtcnVsZT0nZXZlbm9kZCcgZD0nTTkgM2E2IDYgMCAxMDQuNDcyIDEwLjAxNmwzLjI1NiAzLjI1NmExIDEgMCAwMDEuNDE2LTEuNDE2bC0zLjI1Ni0zLjI1NkE2IDYgMCAwMDkgM3ptMCAyYTQgNCAwIDEwMCA4IDQgNCAwIDAwMC04eicgY2xpcC1ydWxlPSdldmVub2RkJy8+PC9zdmc+"); +.think-item-type[data-type="websearch"] { + color: #3b82f6; } -.think-item-type[data-type="agentthink"]::before { - mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J00xMSAyaDJ2MmgtMnonLz48cGF0aCBkPSdNNyA2aDEwYTMgMyAwIDAxMyAzdjhhMyAzIDAgMDEtMyAzSDdhMyAzIDAgMDEtMy0zVjlhMyAzIDAgMDEzLTN6bTIgNWExLjUgMS41IDAgMTAwIDMgMS41IDEuNSAwIDAwMC0zem02IDBhMS41IDEuNSAwIDEwMCAzIDEuNSAxLjUgMCAwMDAtM3onLz48cGF0aCBkPSdNNCAxMGgydjRINHonLz48cGF0aCBkPSdNMTggMTBoMnY0aC0yeicvPjwvc3ZnPg=="); - -webkit-mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J00xMSAyaDJ2MmgtMnonLz48cGF0aCBkPSdNNyA2aDEwYTMgMyAwIDAxMyAzdjhhMyAzIDAgMDEtMyAzSDdhMyAzIDAgMDEtMy0zVjlhMyAzIDAgMDEzLTN6bTIgNWExLjUgMS41IDAgMTAwIDMgMS41IDEuNSAwIDAwMC0zem02IDBhMS41IDEuNSAwIDEwMCAzIDEuNSAxLjUgMCAwMDAtM3onLz48cGF0aCBkPSdNNCAxMGgydjRINHonLz48cGF0aCBkPSdNMTggMTBoMnY0aC0yeicvPjwvc3ZnPg=="); +.think-item-type[data-type="searchimage"] { + color: #22c55e; +} + +.think-item-type[data-type="agentthink"] { + color: #a855f7; } .think-item-body { @@ -626,25 +879,168 @@ body { .model-chip { display: inline-flex; align-items: center; - gap: 6px; + gap: 4px; padding: 6px 10px; border-radius: 999px; border: 1px solid var(--chat-border); background: var(--chat-surface); font-size: 12px; height: 36px; + transition: border-color 0.2s, background 0.2s; + cursor: pointer; + position: relative; + user-select: none; } -.model-select { - border: none; - background: transparent; +.model-chip:hover { + border-color: #bbb; +} + +.model-chip.open .model-chevron { + transform: rotate(180deg); +} + +.model-icon { + color: var(--accents-4); + flex-shrink: 0; +} + +.model-label { font-size: 12px; color: var(--chat-ink); - outline: none; - padding: 0; - appearance: none; - -webkit-appearance: none; - -moz-appearance: none; + white-space: nowrap; + pointer-events: none; +} + +.model-chevron { + color: var(--accents-4); + flex-shrink: 0; + pointer-events: none; + transition: transform 0.2s; +} + +.model-dropdown { + position: absolute; + bottom: calc(100% + 8px); + left: 50%; + transform: translateX(-50%); + background: #fff; + border: 1px solid var(--chat-border); + border-radius: 12px; + padding: 4px; + box-shadow: 0 12px 32px rgba(17, 17, 17, 0.12); + z-index: 30; + min-width: 160px; + max-height: 280px; + overflow-y: auto; +} + +.model-option { + padding: 7px 12px; + font-size: 13px; + border-radius: 8px; + cursor: pointer; + color: var(--chat-ink); + transition: background 0.15s; + white-space: nowrap; +} + +.model-option:hover { + background: var(--chat-muted); +} + +.model-option.selected { + color: #111; + font-weight: 500; +} + +.reasoning-chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 6px 10px; + border-radius: 999px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + font-size: 12px; + height: 36px; + transition: border-color 0.2s, background 0.2s; + cursor: pointer; + position: relative; + user-select: none; +} + +.reasoning-chip:hover { + border-color: #bbb; +} + +.reasoning-chip.active { + border-color: #a855f7; + background: rgba(168, 85, 247, 0.06); +} + +.reasoning-chip.active:hover { + border-color: #9333ea; +} + +.reasoning-icon { + color: var(--accents-4); + flex-shrink: 0; +} + +.reasoning-chip.active .reasoning-icon { + color: #a855f7; +} + +.reasoning-label { + font-size: 12px; + color: var(--chat-ink); + white-space: nowrap; + pointer-events: none; +} + +.reasoning-chevron { + color: var(--accents-4); + flex-shrink: 0; + pointer-events: none; + transition: transform 0.2s; +} + +.reasoning-chip.open .reasoning-chevron { + transform: rotate(180deg); +} + +.reasoning-dropdown { + position: absolute; + bottom: calc(100% + 8px); + left: 50%; + transform: translateX(-50%); + background: #fff; + border: 1px solid var(--chat-border); + border-radius: 12px; + padding: 4px; + box-shadow: 0 12px 32px rgba(17, 17, 17, 0.12); + z-index: 30; + min-width: 120px; +} + +.reasoning-option { + padding: 7px 12px; + font-size: 13px; + border-radius: 8px; + cursor: pointer; + color: var(--chat-ink); + transition: background 0.15s; + white-space: nowrap; +} + +.reasoning-option:hover { + background: var(--chat-muted); +} + +.reasoning-option.selected { + color: #a855f7; + font-weight: 500; } .send-btn { @@ -664,6 +1060,27 @@ body { opacity: 0.5; } +.action-icon-btn { + width: 32px; + height: 32px; + border-radius: 50%; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--accents-4); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: color 0.2s ease, border-color 0.2s ease, background 0.2s ease; + flex-shrink: 0; +} + +.action-icon-btn:hover { + color: var(--chat-ink); + border-color: #bbb; + background: var(--chat-muted); +} + .popover { position: relative; } @@ -767,6 +1184,45 @@ body { } @media (max-width: 720px) { + .chat-sidebar { + position: fixed; + left: 0; + top: 0; + bottom: 0; + width: 280px; + z-index: 100; + transform: translateX(-100%); + transition: transform 0.25s ease; + border-radius: 0; + border-right: 1px solid var(--chat-border); + box-shadow: none; + } + + .chat-sidebar.open { + transform: translateX(0); + box-shadow: 4px 0 24px rgba(0, 0, 0, 0.1); + } + + .sidebar-overlay { + display: none; + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.3); + z-index: 99; + } + + .sidebar-overlay.open { + display: block; + } + + .sidebar-toggle { + display: inline-flex; + } + + .chat-shell { + padding-left: 0; + } + .message-bubble { max-width: 100%; } @@ -775,6 +1231,21 @@ body { align-items: flex-start; } + .model-chip, + .reasoning-chip { + font-size: 11px; + padding: 4px 8px; + height: 32px; + } + + .model-label { + font-size: 11px; + } + + .reasoning-label { + font-size: 11px; + } + .settings-panel { right: auto; left: 0; diff --git a/app/static/public/js/chat.js b/app/static/public/js/chat.js index 126b9f01..58539680 100644 --- a/app/static/public/js/chat.js +++ b/app/static/public/js/chat.js @@ -1,6 +1,13 @@ (() => { - const modelSelect = document.getElementById('modelSelect'); - const reasoningSelect = document.getElementById('reasoningSelect'); + const modelChip = document.getElementById('modelChip'); + const modelLabel = document.getElementById('modelLabel'); + const modelDropdown = document.getElementById('modelDropdown'); + let modelValue = 'grok-4.20-beta'; + let modelList = []; + const reasoningChip = document.getElementById('reasoningChip'); + const reasoningLabel = document.getElementById('reasoningLabel'); + const reasoningDropdown = document.getElementById('reasoningDropdown'); + let reasoningValue = ''; const tempRange = document.getElementById('tempRange'); const tempValue = document.getElementById('tempValue'); const topPRange = document.getElementById('topPRange'); @@ -18,13 +25,271 @@ const fileBadge = document.getElementById('fileBadge'); const fileName = document.getElementById('fileName'); const fileRemoveBtn = document.getElementById('fileRemoveBtn'); + const chatSidebar = document.getElementById('chatSidebar'); + const sidebarOverlay = document.getElementById('sidebarOverlay'); + const sidebarToggle = document.getElementById('sidebarToggle'); + const newChatBtn = document.getElementById('newChatBtn'); + const sessionListEl = document.getElementById('sessionList'); + const clearChatBtn = document.getElementById('clearChatBtn'); + const compressCtxBtn = document.getElementById('compressCtxBtn'); + + const STORAGE_KEY = 'grok2api_chat_sessions'; let messageHistory = []; let isSending = false; let abortController = null; let attachment = null; + let activeStreamInfo = null; const feedbackUrl = 'https://github.com/chenyme/grok2api/issues/new'; + let sessionsData = null; + + function generateId() { + return crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2); + } + + function loadSessions() { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (raw) { + sessionsData = JSON.parse(raw); + if (!sessionsData || !Array.isArray(sessionsData.sessions)) { + sessionsData = null; + } + } + } catch (e) { + sessionsData = null; + } + if (!sessionsData || !sessionsData.sessions.length) { + const id = generateId(); + sessionsData = { + activeId: id, + sessions: [{ + id, + title: '新会话', + createdAt: Date.now(), + updatedAt: Date.now(), + messages: [] + }] + }; + saveSessions(); + } + if (!sessionsData.activeId || !sessionsData.sessions.find(s => s.id === sessionsData.activeId)) { + sessionsData.activeId = sessionsData.sessions[0].id; + } + restoreActiveSession(); + renderSessionList(); + } + + function saveSessions() { + if (!sessionsData) return; + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(sessionsData)); + } catch (e) { + // localStorage full or unavailable + } + } + + function getActiveSession() { + if (!sessionsData) return null; + return sessionsData.sessions.find(s => s.id === sessionsData.activeId) || null; + } + + function restoreActiveSession() { + const session = getActiveSession(); + if (!session) return; + messageHistory = session.messages.slice(); + if (chatLog) chatLog.innerHTML = ''; + if (!messageHistory.length) { + showEmptyState(); + return; + } + hideEmptyState(); + for (const msg of messageHistory) { + const displayContent = typeof msg.content === 'string' ? msg.content : '[复合内容]'; + const entry = createMessage(msg.role, displayContent, true); + if (entry && msg.role === 'assistant') { + updateMessage(entry, displayContent, true); + } + } + if (activeStreamInfo && activeStreamInfo.sessionId === session.id && activeStreamInfo.entry.row) { + chatLog.appendChild(activeStreamInfo.entry.row); + } + scrollToBottom(); + } + + function createSession() { + const id = generateId(); + const session = { + id, + title: '新会话', + createdAt: Date.now(), + updatedAt: Date.now(), + messages: [] + }; + sessionsData.sessions.unshift(session); + sessionsData.activeId = id; + messageHistory = []; + if (chatLog) chatLog.innerHTML = ''; + showEmptyState(); + saveSessions(); + renderSessionList(); + closeSidebar(); + } + + function deleteSession(id) { + const idx = sessionsData.sessions.findIndex(s => s.id === id); + if (idx === -1) return; + sessionsData.sessions.splice(idx, 1); + if (!sessionsData.sessions.length) { + createSession(); + return; + } + if (sessionsData.activeId === id) { + const newIdx = Math.min(idx, sessionsData.sessions.length - 1); + sessionsData.activeId = sessionsData.sessions[newIdx].id; + restoreActiveSession(); + } + saveSessions(); + renderSessionList(); + } + + function switchSession(id) { + if (sessionsData.activeId === id) return; + syncCurrentSession(); + syncSessionModel(); + sessionsData.activeId = id; + const target = getActiveSession(); + if (target) target.unread = false; + restoreActiveSession(); + restoreSessionModel(); + saveSessions(); + renderSessionList(); + closeSidebar(); + } + + function syncCurrentSession() { + const session = getActiveSession(); + if (!session) return; + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + } + + function updateSessionTitle(session) { + if (!session) return; + if (session.title && session.title !== '新会话') return; + const firstUser = session.messages.find(m => m.role === 'user'); + if (!firstUser) return; + const text = typeof firstUser.content === 'string' ? firstUser.content : ''; + if (!text) return; + const title = text.replace(/\n/g, ' ').trim().slice(0, 20); + if (title) { + session.title = title; + } + } + + function renameSession(id, newTitle) { + const session = sessionsData.sessions.find(s => s.id === id); + if (!session) return; + const trimmed = (newTitle || '').trim(); + session.title = trimmed || '新会话'; + session.updatedAt = Date.now(); + saveSessions(); + renderSessionList(); + } + + function startRenameSession(sessionId, titleSpan) { + const session = sessionsData.sessions.find(s => s.id === sessionId); + if (!session) return; + const input = document.createElement('input'); + input.type = 'text'; + input.className = 'session-rename-input'; + input.value = session.title || ''; + input.maxLength = 40; + titleSpan.replaceWith(input); + input.focus(); + input.select(); + const commit = () => { + renameSession(sessionId, input.value); + }; + input.addEventListener('blur', commit); + input.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { e.preventDefault(); input.blur(); } + if (e.key === 'Escape') { input.value = session.title || '新会话'; input.blur(); } + }); + } + + function syncSessionModel() { + const session = getActiveSession(); + if (!session) return; + session.model = modelValue || ''; + } + + function restoreSessionModel() { + const session = getActiveSession(); + if (!session || !session.model) return; + if (modelList.includes(session.model)) { + selectModel(session.model); + } + } + + function renderSessionList() { + if (!sessionListEl || !sessionsData) return; + sessionListEl.innerHTML = ''; + for (const session of sessionsData.sessions) { + const item = document.createElement('div'); + item.className = 'session-item' + (session.id === sessionsData.activeId ? ' active' : ''); + item.dataset.id = session.id; + + const titleSpan = document.createElement('span'); + titleSpan.className = 'session-title'; + titleSpan.textContent = session.title || '新会话'; + titleSpan.addEventListener('dblclick', (e) => { + e.stopPropagation(); + startRenameSession(session.id, titleSpan); + }); + item.appendChild(titleSpan); + + if (session.unread && session.id !== sessionsData.activeId) { + const dot = document.createElement('span'); + dot.className = 'session-unread'; + item.appendChild(dot); + } + + const delBtn = document.createElement('button'); + delBtn.className = 'session-delete'; + delBtn.type = 'button'; + delBtn.title = '删除'; + delBtn.textContent = '×'; + delBtn.addEventListener('click', (e) => { + e.stopPropagation(); + deleteSession(session.id); + }); + item.appendChild(delBtn); + + item.addEventListener('click', () => switchSession(session.id)); + sessionListEl.appendChild(item); + } + } + + function openSidebar() { + if (chatSidebar) chatSidebar.classList.add('open'); + if (sidebarOverlay) sidebarOverlay.classList.add('open'); + } + + function closeSidebar() { + if (chatSidebar) chatSidebar.classList.remove('open'); + if (sidebarOverlay) sidebarOverlay.classList.remove('open'); + } + + function toggleSidebar() { + if (chatSidebar && chatSidebar.classList.contains('open')) { + closeSidebar(); + } else { + openSidebar(); + } + } + function toast(message, type) { if (typeof showToast === 'function') { showToast(message, type); @@ -304,7 +569,7 @@ current.lines.push(line); continue; } - const agentMatch = trimmed.match(/^(Grok\\s+Leader|Agent\\s*\\d+|Grok\\s+Agent\\s*\\d+)$/i); + const agentMatch = trimmed.match(/^(Grok\s+Leader|(?:Grok\s+)?Agent\s*\d+)$/i); if (agentMatch) { hasAgentHeading = true; if (current.lines.length) { @@ -324,6 +589,18 @@ return sections; } + const toolTypeMap = { + websearch: { icon: '\uD83D\uDD0D', label: '\u641C\u7D22' }, + searchimage: { icon: '\uD83D\uDDBC', label: '\u56FE\u641C' }, + agentthink: { icon: '\uD83D\uDCAD', label: '\u63A8\u7406' } + }; + const defaultToolType = { icon: '\uD83D\uDD27', label: '\u5DE5\u5177' }; + + function getToolMeta(typeStr) { + const key = String(typeStr || '').trim().toLowerCase().replace(/\s+/g, ''); + return toolTypeMap[key] || defaultToolType; + } + function renderThinkContent(text, openAll) { const sections = parseAgentSections(text); if (!sections.length) { @@ -345,10 +622,11 @@ return groups.map((group) => { const items = group.items.map((item) => { const body = renderBasicMarkdown(item.lines.join('\n').trim()); - const typeText = escapeHtml(item.type); const typeKey = String(item.type || '').trim().toLowerCase().replace(/\s+/g, ''); const typeAttr = escapeHtml(typeKey); - return `
${typeText}
${body || '(空)'}
`; + const meta = getToolMeta(item.type); + const typeLabel = `${meta.icon}${escapeHtml(meta.label)}`; + return `
${typeLabel}
${body || '\uFF08\u7A7A\uFF09'}
`; }).join(''); const title = escapeHtml(group.id); const openAttr = openAllGroups ? ' open' : ''; @@ -360,7 +638,7 @@ const blocks = parseRolloutBlocks(section.lines.join('\n')); const inner = blocks.length ? renderGroups(blocks, openAll) - : `
${renderBasicMarkdown(section.lines.join('\\n').trim())}
`; + : `
${renderBasicMarkdown(section.lines.join('\n').trim())}
`; if (!section.title) { return `
${inner}
`; } @@ -384,7 +662,163 @@ }).join(''); } - function createMessage(role, content) { + function deleteMessageByRow(row) { + if (!row || !chatLog) return; + const rows = chatLog.querySelectorAll('.message-row'); + const idx = Array.from(rows).indexOf(row); + if (idx === -1 || idx >= messageHistory.length) return; + messageHistory.splice(idx, 1); + row.remove(); + const session = getActiveSession(); + if (session) { + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + saveSessions(); + } + if (!messageHistory.length) { + showEmptyState(); + } + } + + function editMessageByRow(row) { + if (isSending || !row || !chatLog) return; + const rows = chatLog.querySelectorAll('.message-row'); + const idx = Array.from(rows).indexOf(row); + if (idx === -1 || idx >= messageHistory.length) return; + const msg = messageHistory[idx]; + const currentText = typeof msg.content === 'string' ? msg.content : ''; + + const contentNode = row.querySelector('.message-content'); + if (!contentNode) return; + + const textarea = document.createElement('textarea'); + textarea.className = 'edit-msg-input'; + textarea.value = currentText; + textarea.rows = Math.max(3, currentText.split('\n').length); + + const btnWrap = document.createElement('div'); + btnWrap.className = 'edit-msg-actions'; + const saveBtn = createActionButton('保存', '保存编辑', () => commit()); + const cancelBtn = createActionButton('取消', '取消编辑', () => cancel()); + btnWrap.appendChild(saveBtn); + btnWrap.appendChild(cancelBtn); + + const originalHTML = contentNode.innerHTML; + const originalClass = contentNode.className; + contentNode.className = 'message-content'; + contentNode.innerHTML = ''; + contentNode.appendChild(textarea); + contentNode.appendChild(btnWrap); + row.classList.add('editing'); + textarea.focus(); + + const actionsEl = row.querySelector('.message-actions'); + if (actionsEl) actionsEl.classList.add('hidden'); + + function finish() { + row.classList.remove('editing'); + if (actionsEl) actionsEl.classList.remove('hidden'); + } + + function commit() { + const newText = textarea.value.trim(); + if (!newText) { + toast('内容不能为空', 'error'); + return; + } + msg.content = newText; + contentNode.className = originalClass; + if (msg.role === 'assistant') { + contentNode.classList.add('rendered'); + contentNode.innerHTML = renderMarkdown(newText); + } else { + contentNode.textContent = newText; + } + finish(); + const session = getActiveSession(); + if (session) { + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + saveSessions(); + } + } + + function cancel() { + contentNode.className = originalClass; + contentNode.innerHTML = originalHTML; + finish(); + } + } + + function regenerateFromRow(row) { + if (isSending || !row || !chatLog) return; + const rows = chatLog.querySelectorAll('.message-row'); + const idx = Array.from(rows).indexOf(row); + if (idx === -1 || idx >= messageHistory.length) return; + if (messageHistory[idx].role !== 'user') return; + + // 丢弃该用户消息之后的所有消息和 DOM + const allRows = Array.from(rows); + for (let i = allRows.length - 1; i > idx; i--) { + allRows[i].remove(); + } + messageHistory.splice(idx + 1); + + const session = getActiveSession(); + if (session) { + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + saveSessions(); + } + + // 从该位置重新发送 + const sendSessionId = sessionsData.activeId; + const assistantEntry = createMessage('assistant', ''); + setSendingState(true); + setStatus('connecting', '发送中'); + + abortController = new AbortController(); + const payload = buildPayload(); + + (async () => { + let headers = { 'Content-Type': 'application/json' }; + try { + const authHeader = await ensurePublicKey(); + headers = { ...headers, ...buildAuthHeaders(authHeader) }; + } catch (e) {} + + try { + const res = await fetch('/v1/chat/completions', { + method: 'POST', + headers, + body: JSON.stringify(payload), + signal: abortController.signal + }); + if (!res.ok) throw new Error(`请求失败: ${res.status}`); + await handleStream(res, assistantEntry, sendSessionId); + setStatus('connected', '完成'); + } catch (e) { + if (e && e.name === 'AbortError') { + updateMessage(assistantEntry, assistantEntry.raw || '已停止', true); + setStatus('error', '已停止'); + if (!assistantEntry.committed) { + assistantEntry.committed = true; + commitToSession(sendSessionId, assistantEntry.raw || ''); + } + } else { + updateMessage(assistantEntry, `请求失败: ${e.message || e}`, true); + setStatus('error', '失败'); + toast('请求失败,请检查服务状态', 'error'); + } + } finally { + setSendingState(false); + abortController = null; + scrollToBottom(); + } + })(); + } + + function createMessage(role, content, skipScroll) { if (!chatLog) return null; hideEmptyState(); const row = document.createElement('div'); @@ -399,7 +833,7 @@ row.appendChild(bubble); chatLog.appendChild(row); - scrollToBottom(); + if (!skipScroll) scrollToBottom(); const entry = { row, contentNode, @@ -409,8 +843,17 @@ startedAt: Date.now(), firstTokenAt: null, hasThink: false, - thinkElapsed: null + thinkElapsed: null, + thinkAutoCollapsed: false }; + if (role === 'user') { + const actions = document.createElement('div'); + actions.className = 'message-actions'; + actions.appendChild(createActionButton('编辑', '编辑消息内容', () => editMessageByRow(row))); + actions.appendChild(createActionButton('重新生成', '从此处重新生成回复', () => regenerateFromRow(row))); + actions.appendChild(createActionButton('删除', '从上下文中删除', () => deleteMessageByRow(row))); + row.appendChild(actions); + } return entry; } @@ -532,6 +975,13 @@ if (!entry.hasThink && entry.raw.includes('')) { entry.hasThink = true; } + let savedThinkStates = null; + if (entry.hasThink && entry.thinkAutoCollapsed) { + const blocks = entry.contentNode.querySelectorAll('.think-block[data-think="true"]'); + if (blocks.length) { + savedThinkStates = Array.from(blocks).map(b => b.hasAttribute('open')); + } + } if (finalize) { entry.contentNode.classList.add('rendered'); entry.contentNode.innerHTML = renderMarkdown(entry.raw); @@ -543,7 +993,22 @@ } } if (entry.hasThink) { - updateThinkSummary(entry, entry.thinkElapsed); + updateThinkSummary(entry, finalize ? (entry.thinkElapsed ?? 0) : entry.thinkElapsed); + const thinkBlocks = entry.contentNode.querySelectorAll('.think-block[data-think="true"]'); + thinkBlocks.forEach((block, i) => { + if (savedThinkStates && i < savedThinkStates.length) { + if (savedThinkStates[i]) { + block.setAttribute('open', ''); + } else { + block.removeAttribute('open'); + } + } else if (entry.thinkElapsed === null || entry.thinkElapsed === undefined) { + block.setAttribute('open', ''); + } else if (!entry.thinkAutoCollapsed) { + block.removeAttribute('open'); + entry.thinkAutoCollapsed = true; + } + }); } if (entry.role === 'assistant') { applyImageGrid(entry.contentNode); @@ -593,7 +1058,7 @@ if (!entry || !entry.contentNode) return; const summaries = entry.contentNode.querySelectorAll('.think-summary'); if (!summaries.length) return; - const text = typeof elapsedSec === 'number' ? `思考 ${elapsedSec} 秒` : '思考中'; + const text = typeof elapsedSec === 'number' ? (elapsedSec > 0 ? `思考 ${elapsedSec} 秒` : '已思考') : '思考中'; summaries.forEach((node) => { node.textContent = text; const block = node.closest('.think-block'); @@ -607,11 +1072,52 @@ } function clearChat() { + if (isSending) return; messageHistory = []; if (chatLog) { chatLog.innerHTML = ''; } showEmptyState(); + const session = getActiveSession(); + if (session) { + session.messages = []; + session.title = '新会话'; + session.updatedAt = Date.now(); + saveSessions(); + renderSessionList(); + } + } + + function compressContext() { + if (isSending) return; + if (messageHistory.length <= 2) { + toast('消息太少,无需压缩', 'error'); + return; + } + const kept = messageHistory.slice(-4); + const droppedCount = messageHistory.length - kept.length; + messageHistory = kept; + const session = getActiveSession(); + if (session) { + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + saveSessions(); + } + if (chatLog) chatLog.innerHTML = ''; + if (!messageHistory.length) { + showEmptyState(); + } else { + hideEmptyState(); + for (const msg of messageHistory) { + const displayContent = typeof msg.content === 'string' ? msg.content : '[复合内容]'; + const entry = createMessage(msg.role, displayContent, true); + if (entry && msg.role === 'assistant') { + updateMessage(entry, displayContent, true); + } + } + scrollToBottom(); + } + toast(`已压缩,移除了 ${droppedCount} 条旧消息`, 'success'); } function buildMessages() { @@ -632,13 +1138,13 @@ function buildPayload() { const payload = { - model: (modelSelect && modelSelect.value) || 'grok-3', + model: modelValue || 'grok-3', messages: buildMessages(), stream: true, temperature: Number(tempRange ? tempRange.value : 0.8), top_p: Number(topPRange ? topPRange.value : 0.95) }; - const reasoning = reasoningSelect ? reasoningSelect.value : ''; + const reasoning = reasoningValue || ''; if (reasoning) { payload.reasoning_effort = reasoning; } @@ -647,22 +1153,51 @@ function buildPayloadFrom(history) { const payload = { - model: (modelSelect && modelSelect.value) || 'grok-3', + model: modelValue || 'grok-3', messages: buildMessagesFrom(history), stream: true, temperature: Number(tempRange ? tempRange.value : 0.8), top_p: Number(topPRange ? topPRange.value : 0.95) }; - const reasoning = reasoningSelect ? reasoningSelect.value : ''; + const reasoning = reasoningValue || ''; if (reasoning) { payload.reasoning_effort = reasoning; } return payload; } + function selectModel(value) { + modelValue = value; + if (modelLabel) modelLabel.textContent = value; + renderModelDropdown(); + } + + function renderModelDropdown() { + if (!modelDropdown) return; + modelDropdown.innerHTML = ''; + for (const id of modelList) { + const opt = document.createElement('div'); + opt.className = 'model-option' + (id === modelValue ? ' selected' : ''); + opt.dataset.value = id; + opt.textContent = id; + modelDropdown.appendChild(opt); + } + } + + function toggleModelDropdown(show) { + if (!modelDropdown || !modelChip) return; + if (typeof show === 'boolean') { + modelDropdown.classList.toggle('hidden', !show); + modelChip.classList.toggle('open', show); + return; + } + const visible = !modelDropdown.classList.contains('hidden'); + modelDropdown.classList.toggle('hidden', visible); + modelChip.classList.toggle('open', !visible); + } + async function loadModels() { - if (!modelSelect) return; - modelSelect.innerHTML = ''; + if (!modelDropdown) return; const fallback = ['grok-4.1-fast', 'grok-4', 'grok-3', 'grok-3-mini', 'grok-3-thinking', 'grok-4.20-beta']; const preferred = 'grok-4.20-beta'; try { @@ -675,27 +1210,18 @@ .filter(Boolean) .filter(id => !String(id).startsWith('grok-imagine')) .filter(id => !String(id).includes('video')); - const list = ids.length ? ids : fallback; - list.forEach((id) => { - const option = document.createElement('option'); - option.value = id; - option.textContent = id; - modelSelect.appendChild(option); - }); - if (list.includes(preferred)) { - modelSelect.value = preferred; - } else { - modelSelect.value = list[list.length - 1] || preferred; - } + modelList = ids.length ? ids : fallback; } catch (e) { - fallback.forEach((id) => { - const option = document.createElement('option'); - option.value = id; - option.textContent = id; - modelSelect.appendChild(option); - }); - modelSelect.value = preferred; + modelList = fallback; } + if (modelList.includes(preferred)) { + modelValue = preferred; + } else { + modelValue = modelList[modelList.length - 1] || preferred; + } + if (modelLabel) modelLabel.textContent = modelValue; + renderModelDropdown(); + restoreSessionModel(); } function showAttachmentBadge() { @@ -754,13 +1280,17 @@ actions.className = 'message-actions'; const retryBtn = createActionButton('重试', '重试上一条回答', () => retryLast()); + const editBtn = createActionButton('编辑', '编辑回答内容', () => editMessageByRow(entry.row)); const copyBtn = createActionButton('复制', '复制回答内容', () => copyToClipboard(entry.raw || '')); + const deleteBtn = createActionButton('删除', '从上下文中删除', () => deleteMessageByRow(entry.row)); const feedbackBtn = createActionButton('反馈', '反馈到 Grok2API', () => { window.open(feedbackUrl, '_blank', 'noopener'); }); actions.appendChild(retryBtn); + actions.appendChild(editBtn); actions.appendChild(copyBtn); + actions.appendChild(deleteBtn); actions.appendChild(feedbackBtn); entry.row.appendChild(actions); } @@ -804,6 +1334,7 @@ return; } const historySlice = messageHistory.slice(0, lastUserIndex + 1); + const retrySessionId = sessionsData.activeId; const assistantEntry = createMessage('assistant', ''); setSendingState(true); setStatus('connecting', '发送中'); @@ -831,7 +1362,7 @@ throw new Error(`请求失败: ${res.status}`); } - await handleStream(res, assistantEntry); + await handleStream(res, assistantEntry, retrySessionId); setStatus('connected', '完成'); } catch (e) { updateMessage(assistantEntry, `请求失败: ${e.message || e}`, true); @@ -873,7 +1404,13 @@ messageHistory.push({ role: 'user', content }); if (promptInput) promptInput.value = ''; clearAttachment(); + syncCurrentSession(); + syncSessionModel(); + updateSessionTitle(getActiveSession()); + saveSessions(); + renderSessionList(); + const sendSessionId = sessionsData.activeId; const assistantEntry = createMessage('assistant', ''); setSendingState(true); setStatus('connecting', '发送中'); @@ -901,7 +1438,7 @@ throw new Error(`请求失败: ${res.status}`); } - await handleStream(res, assistantEntry); + await handleStream(res, assistantEntry, sendSessionId); setStatus('connected', '完成'); } catch (e) { if (e && e.name === 'AbortError') { @@ -912,8 +1449,8 @@ } setStatus('error', '已停止'); if (!assistantEntry.committed) { - messageHistory.push({ role: 'assistant', content: assistantEntry.raw || '' }); assistantEntry.committed = true; + commitToSession(sendSessionId, assistantEntry.raw || ''); } } else { updateMessage(assistantEntry, `请求失败: ${e.message || e}`, true); @@ -927,12 +1464,29 @@ } } - async function handleStream(res, assistantEntry) { + function commitToSession(sessionId, assistantText) { + const session = sessionsData.sessions.find(s => s.id === sessionId); + if (!session) return; + session.messages.push({ role: 'assistant', content: assistantText }); + session.updatedAt = Date.now(); + updateSessionTitle(session); + if (sessionsData.activeId === sessionId) { + messageHistory = session.messages.slice(); + } else { + session.unread = true; + } + saveSessions(); + renderSessionList(); + } + + async function handleStream(res, assistantEntry, targetSessionId) { + activeStreamInfo = { sessionId: targetSessionId, entry: assistantEntry }; const reader = res.body.getReader(); const decoder = new TextDecoder('utf-8'); let buffer = ''; let assistantText = ''; + try { while (true) { const { value, done } = await reader.read(); if (done) break; @@ -952,8 +1506,8 @@ const elapsed = assistantEntry.thinkElapsed || Math.max(1, Math.round((Date.now() - assistantEntry.startedAt) / 1000)); updateThinkSummary(assistantEntry, elapsed); } - messageHistory.push({ role: 'assistant', content: assistantText }); assistantEntry.committed = true; + commitToSession(targetSessionId, assistantText); return; } try { @@ -968,10 +1522,19 @@ } if (!assistantEntry.hasThink && assistantText.includes('')) { assistantEntry.hasThink = true; + assistantEntry.thinkStartAt = Date.now(); assistantEntry.thinkElapsed = null; updateThinkSummary(assistantEntry, null); } - updateMessage(assistantEntry, assistantText, false); + if (assistantEntry.hasThink && assistantEntry.thinkStartAt && assistantEntry.thinkElapsed === null) { + if (assistantText.includes('')) { + assistantEntry.thinkElapsed = Math.max(1, Math.round((Date.now() - assistantEntry.thinkStartAt) / 1000)); + updateThinkSummary(assistantEntry, assistantEntry.thinkElapsed); + } + } + if (sessionsData.activeId === targetSessionId) { + updateMessage(assistantEntry, assistantText, false); + } } } catch (e) { // ignore parse errors @@ -984,8 +1547,11 @@ const elapsed = assistantEntry.thinkElapsed || Math.max(1, Math.round((Date.now() - assistantEntry.startedAt) / 1000)); updateThinkSummary(assistantEntry, elapsed); } - messageHistory.push({ role: 'assistant', content: assistantText }); assistantEntry.committed = true; + commitToSession(targetSessionId, assistantText); + } finally { + activeStreamInfo = null; + } } function toggleSettings(show) { @@ -997,9 +1563,68 @@ settingsPanel.classList.toggle('hidden'); } + function selectReasoning(value, label) { + reasoningValue = value; + if (reasoningLabel) reasoningLabel.textContent = label; + if (reasoningChip) { + reasoningChip.classList.toggle('active', !!value); + } + if (reasoningDropdown) { + reasoningDropdown.querySelectorAll('.reasoning-option').forEach((opt) => { + opt.classList.toggle('selected', opt.dataset.value === value); + }); + } + } + + function toggleReasoningDropdown(show) { + if (!reasoningDropdown || !reasoningChip) return; + if (typeof show === 'boolean') { + reasoningDropdown.classList.toggle('hidden', !show); + reasoningChip.classList.toggle('open', show); + return; + } + const visible = !reasoningDropdown.classList.contains('hidden'); + reasoningDropdown.classList.toggle('hidden', visible); + reasoningChip.classList.toggle('open', !visible); + } + function bindEvents() { if (tempRange) tempRange.addEventListener('input', updateRangeValues); if (topPRange) topPRange.addEventListener('input', updateRangeValues); + if (modelChip) { + modelChip.addEventListener('click', (event) => { + if (event.target.closest('.model-dropdown')) return; + event.stopPropagation(); + toggleReasoningDropdown(false); + toggleModelDropdown(); + }); + } + if (modelDropdown) { + modelDropdown.addEventListener('click', (event) => { + const opt = event.target.closest('.model-option'); + if (!opt) return; + event.stopPropagation(); + selectModel(opt.dataset.value); + toggleModelDropdown(false); + }); + } + if (reasoningChip) { + reasoningChip.addEventListener('click', (event) => { + if (event.target.closest('.reasoning-dropdown')) return; + event.stopPropagation(); + toggleModelDropdown(false); + toggleReasoningDropdown(); + }); + } + if (reasoningDropdown) { + reasoningDropdown.addEventListener('click', (event) => { + const opt = event.target.closest('.reasoning-option'); + if (!opt) return; + event.stopPropagation(); + selectReasoning(opt.dataset.value, opt.textContent); + toggleReasoningDropdown(false); + }); + } if (sendBtn) sendBtn.addEventListener('click', sendMessage); if (settingsToggle) { settingsToggle.addEventListener('click', (event) => { @@ -1014,6 +1639,16 @@ } toggleSettings(false); }); + document.addEventListener('click', (event) => { + if (!modelDropdown || modelDropdown.classList.contains('hidden')) return; + if (modelChip && modelChip.contains(event.target)) return; + toggleModelDropdown(false); + }); + document.addEventListener('click', (event) => { + if (!reasoningDropdown || reasoningDropdown.classList.contains('hidden')) return; + if (reasoningChip && reasoningChip.contains(event.target)) return; + toggleReasoningDropdown(false); + }); if (promptInput) { let composing = false; promptInput.addEventListener('compositionstart', () => { @@ -1041,9 +1676,25 @@ if (fileRemoveBtn) { fileRemoveBtn.addEventListener('click', clearAttachment); } + if (newChatBtn) { + newChatBtn.addEventListener('click', createSession); + } + if (sidebarToggle) { + sidebarToggle.addEventListener('click', toggleSidebar); + } + if (sidebarOverlay) { + sidebarOverlay.addEventListener('click', closeSidebar); + } + if (clearChatBtn) { + clearChatBtn.addEventListener('click', clearChat); + } + if (compressCtxBtn) { + compressCtxBtn.addEventListener('click', compressContext); + } } updateRangeValues(); loadModels(); bindEvents(); + loadSessions(); })(); diff --git a/app/static/public/pages/chat.html b/app/static/public/pages/chat.html index 006bcc5a..e374e801 100644 --- a/app/static/public/pages/chat.html +++ b/app/static/public/pages/chat.html @@ -10,7 +10,7 @@ - + @@ -18,15 +18,38 @@
-
-
-
-
-

Chat 聊天

-

通过 chat 接口与 Grok 进行会话聊天

+
+
+ + +
+
+
+ +
+

Chat 聊天

+

通过 chat 接口与 Grok 进行会话聊天

+
+
+ 就绪
- 就绪 -
输入一条消息开始对话。
@@ -47,12 +70,37 @@
-
- - + + + + + + grok-4.20-beta + + +
+
+ + + + + + 跟随配置 + + + +
+
@@ -118,7 +171,7 @@ - + From 623570ccb4d2ffbc0c8fdf84e4180fa676a17320 Mon Sep 17 00:00:00 2001 From: piexian <64474352+piexian@users.noreply.github.com> Date: Sun, 1 Mar 2026 03:36:14 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix(auth,chat):=20=E5=8A=A0=E5=9B=BA?= =?UTF-8?q?=E8=AE=A4=E8=AF=81=E9=80=BB=E8=BE=91=E4=B8=8E=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E4=BA=A4=E4=BA=92=E7=BC=BA=E9=99=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除 verify_api_key 中 public_enabled 无密钥时的免认证后门 - 对 public_key 进行 strip 归一化,避免配置空白导致哈希不匹配 - 前端空密钥时直接缓存空值,移除多余的 verify 网络请求 - 阻止删除正在流式传输中的消息,防止 session 状态不同步 - 编辑消息取消时使用 DOM 克隆恢复,避免 innerHTML 注入风险 - 合并三个全局 click 监听器为一个,减少事件绑定开销 --- app/core/auth.py | 17 +++++------ app/static/common/js/admin-auth.js | 12 ++------ app/static/public/js/chat.js | 47 ++++++++++++++++++------------ 3 files changed, 37 insertions(+), 39 deletions(-) diff --git a/app/core/auth.py b/app/core/auth.py index d01f54da..634e2e93 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -63,10 +63,13 @@ def _match_public_key(credentials: str, public_key: str) -> bool: """检查凭证是否匹配 public_key(支持原始值和 public- 哈希格式)。""" if not public_key: return False - if credentials == public_key: + normalized = public_key.strip() + if not normalized: + return False + if credentials == normalized: return True if credentials.startswith("public-"): - expected_hash = _hash_public_key(public_key) + expected_hash = _hash_public_key(normalized) if credentials == f"public-{expected_hash}": return True return False @@ -79,20 +82,13 @@ async def verify_api_key( 验证 Bearer Token 如果 config.toml 中未配置 api_key,则不启用认证。 - 同时支持面板通过 public_key 认证(原始值或 public- 哈希格式)。 - 若 public_enabled 且未配置 public_key,允许无认证访问。 + 同时支持通过 public_key 认证(原始值或 public- 哈希格式)。 """ api_key = get_admin_api_key() - public_key = get_public_api_key() - public_enabled = is_public_enabled() - if not api_key: return None - # 无认证头:仅在 public_enabled 且无 public_key 时放行 if not auth: - if public_enabled and not public_key: - return None raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing authentication token", @@ -104,6 +100,7 @@ async def verify_api_key( return auth.credentials # public_key 验证(原始值或哈希) + public_key = get_public_api_key() if _match_public_key(auth.credentials, public_key): return auth.credentials diff --git a/app/static/common/js/admin-auth.js b/app/static/common/js/admin-auth.js index 4022c06c..195223d0 100644 --- a/app/static/common/js/admin-auth.js +++ b/app/static/common/js/admin-auth.js @@ -190,16 +190,8 @@ async function ensurePublicKey() { const key = await getStoredPublicKey(); if (!key) { - try { - const ok = await verifyKey('/v1/public/verify', ''); - if (ok) { - cachedPublicKey = ''; - return cachedPublicKey; - } - } catch (e) { - // ignore - } - return null; + cachedPublicKey = ''; + return cachedPublicKey; } try { diff --git a/app/static/public/js/chat.js b/app/static/public/js/chat.js index 58539680..17c8880d 100644 --- a/app/static/public/js/chat.js +++ b/app/static/public/js/chat.js @@ -336,6 +336,12 @@ if (emptyState) emptyState.classList.remove('hidden'); } + function setRenderedHTML(el, html) { + const doc = new DOMParser().parseFromString(html, 'text/html'); + el.textContent = ''; + Array.from(doc.body.childNodes).forEach(n => el.appendChild(document.adoptNode(n))); + } + function escapeHtml(value) { return value .replace(/&/g, '&') @@ -664,6 +670,7 @@ function deleteMessageByRow(row) { if (!row || !chatLog) return; + if (activeStreamInfo && activeStreamInfo.entry.row === row) return; const rows = chatLog.querySelectorAll('.message-row'); const idx = Array.from(rows).indexOf(row); if (idx === -1 || idx >= messageHistory.length) return; @@ -703,7 +710,7 @@ btnWrap.appendChild(saveBtn); btnWrap.appendChild(cancelBtn); - const originalHTML = contentNode.innerHTML; + const savedChildren = Array.from(contentNode.childNodes).map(n => n.cloneNode(true)); const originalClass = contentNode.className; contentNode.className = 'message-content'; contentNode.innerHTML = ''; @@ -728,9 +735,10 @@ } msg.content = newText; contentNode.className = originalClass; + contentNode.textContent = ''; if (msg.role === 'assistant') { contentNode.classList.add('rendered'); - contentNode.innerHTML = renderMarkdown(newText); + setRenderedHTML(contentNode, renderMarkdown(newText)); } else { contentNode.textContent = newText; } @@ -745,7 +753,8 @@ function cancel() { contentNode.className = originalClass; - contentNode.innerHTML = originalHTML; + contentNode.textContent = ''; + savedChildren.forEach(n => contentNode.appendChild(n)); finish(); } } @@ -984,10 +993,10 @@ } if (finalize) { entry.contentNode.classList.add('rendered'); - entry.contentNode.innerHTML = renderMarkdown(entry.raw); + setRenderedHTML(entry.contentNode, renderMarkdown(entry.raw)); } else { if (entry.role === 'assistant') { - entry.contentNode.innerHTML = renderMarkdown(entry.raw); + setRenderedHTML(entry.contentNode, renderMarkdown(entry.raw)); } else { entry.contentNode.textContent = entry.raw; } @@ -1633,21 +1642,21 @@ }); } document.addEventListener('click', (event) => { - if (!settingsPanel || settingsPanel.classList.contains('hidden')) return; - if (settingsPanel.contains(event.target) || (settingsToggle && settingsToggle.contains(event.target))) { - return; + if (settingsPanel && !settingsPanel.classList.contains('hidden')) { + if (!settingsPanel.contains(event.target) && !(settingsToggle && settingsToggle.contains(event.target))) { + toggleSettings(false); + } + } + if (modelDropdown && !modelDropdown.classList.contains('hidden')) { + if (!(modelChip && modelChip.contains(event.target))) { + toggleModelDropdown(false); + } + } + if (reasoningDropdown && !reasoningDropdown.classList.contains('hidden')) { + if (!(reasoningChip && reasoningChip.contains(event.target))) { + toggleReasoningDropdown(false); + } } - toggleSettings(false); - }); - document.addEventListener('click', (event) => { - if (!modelDropdown || modelDropdown.classList.contains('hidden')) return; - if (modelChip && modelChip.contains(event.target)) return; - toggleModelDropdown(false); - }); - document.addEventListener('click', (event) => { - if (!reasoningDropdown || reasoningDropdown.classList.contains('hidden')) return; - if (reasoningChip && reasoningChip.contains(event.target)) return; - toggleReasoningDropdown(false); }); if (promptInput) { let composing = false; From 111614a6bd678d061a6007277f5e497604a51b0f Mon Sep 17 00:00:00 2001 From: piexian <64474352+piexian@users.noreply.github.com> Date: Sun, 1 Mar 2026 10:47:11 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix(ui):=20=E4=BF=AE=E5=A4=8D=E7=A7=BB?= =?UTF-8?q?=E5=8A=A8=E7=AB=AF=E9=80=82=E9=85=8D=E4=B8=8E=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E6=B8=B2=E6=9F=93=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 顶部导航栏移动端适配:缩减间距、品牌文字隐藏、链接横向滚动 - 底部 footer 移动端居中显示,防止溢出裁切 - 输入栏移动端改为双排布局:上排输入框、下排功能按钮 - 模型/推理下拉菜单移除 overflow 裁剪,修复移动端无法展示问题 - 对话区滚动条改为细线样式,悬停时显示、拖动时加深 - 统一 innerHTML 渲染入口为 setRenderedHTML,收口 XSS 风险 - 恢复空密钥时的 verify 校验,页面初始化未通过认证时跳转登录 --- app/static/common/css/common.css | 51 ++++++++++++++ app/static/common/js/admin-auth.js | 12 +++- app/static/public/css/chat.css | 109 ++++++++++++++++++++++++++++- app/static/public/js/chat.js | 21 ++++-- 4 files changed, 185 insertions(+), 8 deletions(-) diff --git a/app/static/common/css/common.css b/app/static/common/css/common.css index bcc422af..def44185 100644 --- a/app/static/common/css/common.css +++ b/app/static/common/css/common.css @@ -355,3 +355,54 @@ td.table-empty { color: var(--accents-4); margin-top: 2px; } + +@media (max-width: 720px) { + #app-header nav > div { + padding-left: 12px; + padding-right: 12px; + gap: 8px; + } + + #app-header nav > div > div:first-child { + gap: 6px; + min-width: 0; + overflow-x: auto; + -webkit-overflow-scrolling: touch; + scrollbar-width: none; + } + + #app-header nav > div > div:first-child::-webkit-scrollbar { + display: none; + } + + #app-header .nav-link { + white-space: nowrap; + font-size: 12px; + } + + #app-header .brand-link span { + display: none; + } + + #app-header nav > div > div:first-child > .h-4 { + display: none; + } + + .nav-actions { + flex-shrink: 0; + gap: 6px; + } + + .nav-action-btn { + font-size: 10px; + padding: 0 6px; + height: 22px; + } + + .app-footer { + right: 12px; + left: 12px; + text-align: center; + font-size: 11px; + } +} diff --git a/app/static/common/js/admin-auth.js b/app/static/common/js/admin-auth.js index 195223d0..4022c06c 100644 --- a/app/static/common/js/admin-auth.js +++ b/app/static/common/js/admin-auth.js @@ -190,8 +190,16 @@ async function ensurePublicKey() { const key = await getStoredPublicKey(); if (!key) { - cachedPublicKey = ''; - return cachedPublicKey; + try { + const ok = await verifyKey('/v1/public/verify', ''); + if (ok) { + cachedPublicKey = ''; + return cachedPublicKey; + } + } catch (e) { + // ignore + } + return null; } try { diff --git a/app/static/public/css/chat.css b/app/static/public/css/chat.css index 6c9f4bec..6b1e0880 100644 --- a/app/static/public/css/chat.css +++ b/app/static/public/css/chat.css @@ -242,6 +242,44 @@ body { padding-bottom: 12px; flex: 1; overflow-y: auto; + scrollbar-width: thin; + scrollbar-color: transparent transparent; + transition: scrollbar-color 0.3s; +} + +.chat-thread:hover { + scrollbar-color: rgba(0, 0, 0, 0.15) transparent; +} + +.chat-thread:active { + scrollbar-color: rgba(0, 0, 0, 0.3) transparent; +} + +.chat-thread::-webkit-scrollbar { + width: 4px; +} + +.chat-thread::-webkit-scrollbar-track { + background: transparent; +} + +.chat-thread::-webkit-scrollbar-thumb { + background: transparent; + border-radius: 4px; + transition: background 0.3s; +} + +.chat-thread:hover::-webkit-scrollbar-thumb { + background: rgba(0, 0, 0, 0.15); +} + +.chat-thread:hover::-webkit-scrollbar-thumb:hover { + background: rgba(0, 0, 0, 0.25); + width: 6px; +} + +.chat-thread:hover::-webkit-scrollbar-thumb:active { + background: rgba(0, 0, 0, 0.35); } .chat-empty { @@ -1228,27 +1266,94 @@ body { } .composer-input { - align-items: flex-start; + flex-wrap: wrap; + align-items: center; + border-radius: 16px; + padding: 8px 10px; + gap: 6px; + } + + .composer-textarea { + order: 0; + flex: 1; + min-width: 0; + min-height: 36px; + height: 36px; + padding: 8px 0; + } + + .composer-input > .icon-btn { + order: -1; + width: 32px; + height: 32px; + } + + .composer-actions { + order: 10; + width: 100%; + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + overflow: visible; + border-top: 1px solid var(--chat-border); + padding-top: 6px; + margin-top: 2px; + } + + .model-dropdown { + bottom: calc(100% + 8px); + left: 0; + transform: none; + max-height: 50vh; + } + + .reasoning-dropdown { + bottom: calc(100% + 8px); + left: 0; + transform: none; } .model-chip, .reasoning-chip { font-size: 11px; padding: 4px 8px; - height: 32px; + height: 28px; + flex-shrink: 0; } .model-label { font-size: 11px; + max-width: 100px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .reasoning-label { font-size: 11px; } + .send-btn { + width: 28px; + height: 28px; + flex-shrink: 0; + } + + .action-icon-btn { + width: 28px; + height: 28px; + flex-shrink: 0; + } + .settings-panel { right: auto; left: 0; width: 92vw; } + + .chat-main { + padding-left: 12px; + padding-right: 12px; + } } diff --git a/app/static/public/js/chat.js b/app/static/public/js/chat.js index 17c8880d..3472dfec 100644 --- a/app/static/public/js/chat.js +++ b/app/static/public/js/chat.js @@ -337,9 +337,9 @@ } function setRenderedHTML(el, html) { - const doc = new DOMParser().parseFromString(html, 'text/html'); - el.textContent = ''; - Array.from(doc.body.childNodes).forEach(n => el.appendChild(document.adoptNode(n))); + // html is pre-sanitized through renderMarkdown → escapeHtml pipeline; + // all user text is entity-escaped before any HTML construction. + el.innerHTML = html; } function escapeHtml(value) { @@ -1705,5 +1705,18 @@ updateRangeValues(); loadModels(); bindEvents(); - loadSessions(); + + (async () => { + try { + const authResult = await ensurePublicKey(); + if (authResult === null) { + window.location.href = '/login'; + return; + } + } catch (e) { + window.location.href = '/login'; + return; + } + loadSessions(); + })(); })(); From a511607cae1725365f630422a6cf1502f0bba49d Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Sun, 1 Mar 2026 14:56:16 +0800 Subject: [PATCH 4/4] feat(api): Integrate chat router with public key verification --- app/api/v1/public_api/__init__.py | 5 +- app/core/auth.py | 6 - app/static/admin/pages/cache.html | 14 +- app/static/admin/pages/config.html | 12 +- app/static/admin/pages/login.html | 10 +- app/static/admin/pages/token.html | 14 +- app/static/common/js/footer.js | 2 +- app/static/common/js/header.js | 2 +- app/static/common/js/public-header.js | 2 +- app/static/public/css/chat.css | 1014 ++++++++++--------------- app/static/public/js/chat.js | 402 ++++++---- app/static/public/pages/chat.html | 76 +- app/static/public/pages/imagine.html | 12 +- app/static/public/pages/login.html | 10 +- app/static/public/pages/video.html | 12 +- app/static/public/pages/voice.html | 12 +- pyproject.toml | 2 +- 17 files changed, 736 insertions(+), 871 deletions(-) diff --git a/app/api/v1/public_api/__init__.py b/app/api/v1/public_api/__init__.py index 0190889b..56f71599 100644 --- a/app/api/v1/public_api/__init__.py +++ b/app/api/v1/public_api/__init__.py @@ -1,13 +1,16 @@ """Public API router (public_key protected).""" -from fastapi import APIRouter +from fastapi import APIRouter, Depends +from app.api.v1.chat import router as chat_router from app.api.v1.public_api.imagine import router as imagine_router from app.api.v1.public_api.video import router as video_router from app.api.v1.public_api.voice import router as voice_router +from app.core.auth import verify_public_key router = APIRouter() +router.include_router(chat_router, dependencies=[Depends(verify_public_key)]) router.include_router(imagine_router) router.include_router(video_router) router.include_router(voice_router) diff --git a/app/core/auth.py b/app/core/auth.py index 634e2e93..e2e31297 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -82,7 +82,6 @@ async def verify_api_key( 验证 Bearer Token 如果 config.toml 中未配置 api_key,则不启用认证。 - 同时支持通过 public_key 认证(原始值或 public- 哈希格式)。 """ api_key = get_admin_api_key() if not api_key: @@ -99,11 +98,6 @@ async def verify_api_key( if auth.credentials == api_key: return auth.credentials - # public_key 验证(原始值或哈希) - public_key = get_public_api_key() - if _match_public_key(auth.credentials, public_key): - return auth.credentials - raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication token", diff --git a/app/static/admin/pages/cache.html b/app/static/admin/pages/cache.html index 295ce105..94bba800 100644 --- a/app/static/admin/pages/cache.html +++ b/app/static/admin/pages/cache.html @@ -9,8 +9,8 @@ - - + + @@ -196,12 +196,12 @@ - - - - + + + + - + diff --git a/app/static/admin/pages/config.html b/app/static/admin/pages/config.html index f59cc9df..ea3963bf 100644 --- a/app/static/admin/pages/config.html +++ b/app/static/admin/pages/config.html @@ -9,8 +9,8 @@ - - + + @@ -46,11 +46,11 @@ - - - + + + - + diff --git a/app/static/admin/pages/login.html b/app/static/admin/pages/login.html index 95a43ad1..f7ed9f40 100644 --- a/app/static/admin/pages/login.html +++ b/app/static/admin/pages/login.html @@ -24,8 +24,8 @@ } } - - + + @@ -55,10 +55,10 @@ - + - - + + diff --git a/app/static/admin/pages/token.html b/app/static/admin/pages/token.html index ff3a968f..0a9049d1 100644 --- a/app/static/admin/pages/token.html +++ b/app/static/admin/pages/token.html @@ -9,8 +9,8 @@ - - + + @@ -295,12 +295,12 @@ - - - - + + + + - + diff --git a/app/static/common/js/footer.js b/app/static/common/js/footer.js index 0fa67ce4..771fbe02 100644 --- a/app/static/common/js/footer.js +++ b/app/static/common/js/footer.js @@ -2,7 +2,7 @@ async function loadAdminFooter() { const container = document.getElementById('app-footer'); if (!container) return; try { - const res = await fetch('/static/common/html/footer.html?v=1.5.0'); + const res = await fetch('/static/common/html/footer.html?v=1.5.1'); if (!res.ok) return; container.innerHTML = await res.text(); } catch (e) { diff --git a/app/static/common/js/header.js b/app/static/common/js/header.js index f6525559..09dffb6a 100644 --- a/app/static/common/js/header.js +++ b/app/static/common/js/header.js @@ -2,7 +2,7 @@ async function loadAdminHeader() { const container = document.getElementById('app-header'); if (!container) return; try { - const res = await fetch('/static/common/html/header.html?v=1.5.0'); + const res = await fetch('/static/common/html/header.html?v=1.5.1'); if (!res.ok) return; container.innerHTML = await res.text(); const path = window.location.pathname; diff --git a/app/static/common/js/public-header.js b/app/static/common/js/public-header.js index 7dd58dc7..5b9eee8a 100644 --- a/app/static/common/js/public-header.js +++ b/app/static/common/js/public-header.js @@ -2,7 +2,7 @@ async function loadPublicHeader() { const container = document.getElementById('app-header'); if (!container) return; try { - const res = await fetch('/static/common/html/public-header.html?v=1.5.0'); + const res = await fetch('/static/common/html/public-header.html?v=1.5.1'); if (!res.ok) return; container.innerHTML = await res.text(); const logoutBtn = container.querySelector('#public-logout-btn'); diff --git a/app/static/public/css/chat.css b/app/static/public/css/chat.css index 6b1e0880..40fac00a 100644 --- a/app/static/public/css/chat.css +++ b/app/static/public/css/chat.css @@ -11,185 +11,17 @@ body { background-color: var(--chat-bg); background-image: radial-gradient(circle at 20% 10%, rgba(17, 17, 17, 0.04), transparent 50%), radial-gradient(circle at 85% 0%, rgba(17, 17, 17, 0.03), transparent 50%); - height: 100vh; - overflow: hidden; } .chat-main { padding-bottom: 16px; - overflow: hidden; - display: flex; - flex-direction: column; -} - -.chat-layout { - display: flex; - gap: 0; - flex: 1; - min-height: 0; -} - -.chat-sidebar { - width: 260px; - flex-shrink: 0; - border-right: 1px solid var(--chat-border); - background: var(--chat-surface); - display: flex; - flex-direction: column; - border-radius: 16px 0 0 16px; - overflow: hidden; -} - -.sidebar-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 16px 16px 12px; - border-bottom: 1px solid var(--chat-border); -} - -.sidebar-title { - font-size: 14px; - font-weight: 600; - color: var(--chat-ink); -} - -.sidebar-new-btn { - width: 32px; - height: 32px; - border-radius: 8px; - border: 1px solid var(--chat-border); - background: var(--chat-surface); - color: var(--chat-ink); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: background 0.2s ease, border-color 0.2s ease; -} - -.sidebar-new-btn:hover { - background: var(--chat-muted); - border-color: #bbb; -} - -.sidebar-list { - flex: 1; - overflow-y: auto; - padding: 8px; -} - -.session-item { - display: flex; - align-items: center; - justify-content: space-between; - padding: 10px 12px; - border-radius: 10px; - cursor: pointer; - transition: background 0.15s ease; - gap: 8px; -} - -.session-item:hover { - background: var(--chat-muted); -} - -.session-item.active { - background: var(--chat-soft); -} - -.session-title { - flex: 1; - min-width: 0; - font-size: 13px; - color: var(--chat-ink); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.session-delete { - flex-shrink: 0; - width: 24px; - height: 24px; - border: none; - background: transparent; - color: var(--accents-4); - font-size: 16px; - line-height: 1; - border-radius: 6px; - cursor: pointer; - display: inline-flex; - align-items: center; - justify-content: center; - opacity: 0; - transition: opacity 0.15s ease, color 0.15s ease, background 0.15s ease; -} - -.session-item:hover .session-delete { - opacity: 1; -} - -.session-delete:hover { - color: #b91c1c; - background: rgba(185, 28, 28, 0.08); -} - -.session-rename-input { - flex: 1; - min-width: 0; - font-size: 13px; - color: var(--chat-ink); - border: 1px solid var(--chat-border); - border-radius: 6px; - padding: 2px 6px; - background: var(--chat-surface); - outline: none; -} - -.session-rename-input:focus { - border-color: #111; -} - -.session-unread { - width: 8px; - height: 8px; - border-radius: 50%; - background: #22c55e; - flex-shrink: 0; -} - -.sidebar-overlay { - display: none; -} - -.sidebar-toggle { - display: none; - width: 36px; - height: 36px; - border-radius: 8px; - border: 1px solid var(--chat-border); - background: var(--chat-surface); - color: var(--chat-ink); - align-items: center; - justify-content: center; - cursor: pointer; - flex-shrink: 0; -} - -.sidebar-toggle:hover { - border-color: #bbb; } .chat-shell { - flex: 1; - min-width: 0; - min-height: 0; display: flex; flex-direction: column; gap: 20px; - padding-left: 24px; - overflow: hidden; + min-height: calc(100vh - 56px - 64px); } .chat-title { @@ -238,48 +70,9 @@ body { display: flex; flex-direction: column; gap: 18px; - min-height: 0; + min-height: 320px; padding-bottom: 12px; flex: 1; - overflow-y: auto; - scrollbar-width: thin; - scrollbar-color: transparent transparent; - transition: scrollbar-color 0.3s; -} - -.chat-thread:hover { - scrollbar-color: rgba(0, 0, 0, 0.15) transparent; -} - -.chat-thread:active { - scrollbar-color: rgba(0, 0, 0, 0.3) transparent; -} - -.chat-thread::-webkit-scrollbar { - width: 4px; -} - -.chat-thread::-webkit-scrollbar-track { - background: transparent; -} - -.chat-thread::-webkit-scrollbar-thumb { - background: transparent; - border-radius: 4px; - transition: background 0.3s; -} - -.chat-thread:hover::-webkit-scrollbar-thumb { - background: rgba(0, 0, 0, 0.15); -} - -.chat-thread:hover::-webkit-scrollbar-thumb:hover { - background: rgba(0, 0, 0, 0.25); - width: 6px; -} - -.chat-thread:hover::-webkit-scrollbar-thumb:active { - background: rgba(0, 0, 0, 0.35); } .chat-empty { @@ -314,72 +107,19 @@ body { } .action-btn { - border: 1px solid var(--chat-border); - background: var(--chat-surface); + border: none; + background: transparent; color: var(--accents-4); font-size: 12px; - padding: 4px 10px; + padding: 4px 6px; border-radius: 999px; cursor: pointer; - transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease; + transition: color 0.2s ease, background 0.2s ease; } .action-btn:hover { color: var(--chat-ink); - border-color: #bbb; - background: rgba(17, 17, 17, 0.04); -} - -.edit-msg-input { - width: 100%; - min-height: 60px; - border: 1px solid var(--chat-border); - border-radius: 10px; - padding: 10px 12px; - font-size: 14px; - line-height: 1.5; - color: var(--chat-ink); - background: var(--chat-surface); - resize: vertical; - outline: none; - font-family: inherit; -} - -.edit-msg-input:focus { - border-color: #111; -} - -.edit-msg-actions { - display: flex; - gap: 8px; - margin-top: 8px; -} - -.message-row.editing { - align-items: flex-end; -} - -.message-row.editing .message-bubble { - background: transparent; - border: none; - border-radius: 0; - padding: 0; - width: 100%; - max-width: 100%; -} - -.message-row.user.editing { - align-items: flex-start; - width: 100%; -} - -.message-row.user.editing .message-bubble { - width: 100%; - max-width: 100%; - background: transparent; - border: none; - border-radius: 0; - padding: 0; + background: rgba(17, 17, 17, 0.06); } .message-bubble { @@ -402,7 +142,7 @@ body { .message-row.user .message-bubble { background: #efeeea; padding: 12px 16px; - border-radius: 999px; + border-radius: 16px; border: 1px solid var(--chat-border); } @@ -471,12 +211,48 @@ body { margin: 6px 0; } +.message-content.rendered blockquote { + margin: 8px 0; + padding: 6px 12px; + border-left: 3px solid var(--chat-border); + border-radius: 8px; + background: #f7f6f3; + color: var(--accents-5); +} + +.message-content.rendered blockquote p { + margin: 6px 0; +} + +.message-content.rendered hr { + border: none; + border-top: 1px solid var(--chat-border); + margin: 12px 0; +} + .message-content.rendered ul, .message-content.rendered ol { margin: 6px 0 10px; padding-left: 20px; } +.message-content.rendered ul.task-list { + list-style: none; + padding-left: 12px; +} + +.message-content.rendered .task-item { + display: flex; + align-items: center; + gap: 6px; +} + +.message-content.rendered .task-item input { + width: 14px; + height: 14px; + accent-color: #111; +} + .message-content.rendered li { margin: 4px 0; } @@ -675,11 +451,6 @@ body { display: none; } -@keyframes thinkSpin { - from { transform: rotate(0deg); } - to { transform: rotate(360deg); } -} - @keyframes thinkGlow { 0% { box-shadow: 0 0 0 rgba(255, 255, 255, 0); @@ -695,10 +466,6 @@ body { } } -.think-block[data-thinking="true"] .think-summary::before { - animation: thinkSpin 1.6s linear infinite; -} - .think-block[data-thinking="true"] .think-agent summary { animation: thinkGlow 1.4s ease-in-out infinite; } @@ -784,59 +551,37 @@ body { gap: 6px; } -.think-tool-card { - background: #fafaf9; - border: 1px solid var(--chat-border); - border-radius: 10px; - padding: 8px 12px; - transition: border-color 0.2s ease; -} - -.think-tool-card:hover { - border-color: #ccc; -} - -.think-tool-card[data-tool-type="websearch"] { - border-left: 3px solid #3b82f6; - background: rgba(59, 130, 246, 0.04); -} - -.think-tool-card[data-tool-type="searchimage"] { - border-left: 3px solid #22c55e; - background: rgba(34, 197, 94, 0.04); -} - -.think-tool-card[data-tool-type="agentthink"] { - border-left: 3px solid #a855f7; - background: rgba(168, 85, 247, 0.04); -} - .think-item-type { - font-size: 11px; - font-weight: 600; + font-size: 12px; color: var(--accents-4); display: inline-flex; align-items: center; - gap: 4px; - text-transform: uppercase; - letter-spacing: 0.04em; + gap: 8px; } -.think-tool-icon { - font-size: 13px; - line-height: 1; +.think-item-type::before { + content: ""; + width: 14px; + height: 14px; + background-color: var(--accents-4); + mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J005IDIxaDZ2LTFIOXYxem0zLTIwYTcgNyAwIDAwLTQgMTIuNzRWMTdhMSAxIDAgMDAxIDFoNmExIDEgMCAwMDEtMXYtMy4yNkE3IDcgMCAwMDEyIDF6Jy8+PC9zdmc+"); + mask-size: contain; + mask-repeat: no-repeat; + mask-position: center; + -webkit-mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J005IDIxaDZ2LTFIOXYxem0zLTIwYTcgNyAwIDAwLTQgMTIuNzRWMTdhMSAxIDAgMDAxIDFoNmExIDEgMCAwMDEtMXYtMy4yNkE3IDcgMCAwMDEyIDF6Jy8+PC9zdmc+"); + -webkit-mask-size: contain; + -webkit-mask-repeat: no-repeat; + -webkit-mask-position: center; } -.think-item-type[data-type="websearch"] { - color: #3b82f6; +.think-item-type[data-type="websearch"]::before { + mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyMCAyMCcgZmlsbD0nYmxhY2snPjxwYXRoIGZpbGwtcnVsZT0nZXZlbm9kZCcgZD0nTTkgM2E2IDYgMCAxMDQuNDcyIDEwLjAxNmwzLjI1NiAzLjI1NmExIDEgMCAwMDEuNDE2LTEuNDE2bC0zLjI1Ni0zLjI1NkE2IDYgMCAwMDkgM3ptMCAyYTQgNCAwIDEwMCA4IDQgNCAwIDAwMC04eicgY2xpcC1ydWxlPSdldmVub2RkJy8+PC9zdmc+"); + -webkit-mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyMCAyMCcgZmlsbD0nYmxhY2snPjxwYXRoIGZpbGwtcnVsZT0nZXZlbm9kZCcgZD0nTTkgM2E2IDYgMCAxMDQuNDcyIDEwLjAxNmwzLjI1NiAzLjI1NmExIDEgMCAwMDEuNDE2LTEuNDE2bC0zLjI1Ni0zLjI1NkE2IDYgMCAwMDkgM3ptMCAyYTQgNCAwIDEwMCA4IDQgNCAwIDAwMC04eicgY2xpcC1ydWxlPSdldmVub2RkJy8+PC9zdmc+"); } -.think-item-type[data-type="searchimage"] { - color: #22c55e; -} - -.think-item-type[data-type="agentthink"] { - color: #a855f7; +.think-item-type[data-type="agentthink"]::before { + mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J00xMSAyaDJ2MmgtMnonLz48cGF0aCBkPSdNNyA2aDEwYTMgMyAwIDAxMyAzdjhhMyAzIDAgMDEtMyAzSDdhMyAzIDAgMDEtMy0zVjlhMyAzIDAgMDEzLTN6bTIgNWExLjUgMS41IDAgMTAwIDMgMS41IDEuNSAwIDAwMC0zem02IDBhMS41IDEuNSAwIDEwMCAzIDEuNSAxLjUgMCAwMDAtM3onLz48cGF0aCBkPSdNNCAxMGgydjRINHonLz48cGF0aCBkPSdNMTggMTBoMnY0aC0yeicvPjwvc3ZnPg=="); + -webkit-mask-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCcgZmlsbD0nYmxhY2snPjxwYXRoIGQ9J00xMSAyaDJ2MmgtMnonLz48cGF0aCBkPSdNNyA2aDEwYTMgMyAwIDAxMyAzdjhhMyAzIDAgMDEtMyAzSDdhMyAzIDAgMDEtMy0zVjlhMyAzIDAgMDEzLTN6bTIgNWExLjUgMS41IDAgMTAwIDMgMS41IDEuNSAwIDAwMC0zem02IDBhMS41IDEuNSAwIDEwMCAzIDEuNSAxLjUgMCAwMDAtM3onLz48cGF0aCBkPSdNNCAxMGgydjRINHonLz48cGF0aCBkPSdNMTggMTBoMnY0aC0yeicvPjwvc3ZnPg=="); } .think-item-body { @@ -917,168 +662,25 @@ body { .model-chip { display: inline-flex; align-items: center; - gap: 4px; + gap: 6px; padding: 6px 10px; border-radius: 999px; border: 1px solid var(--chat-border); background: var(--chat-surface); font-size: 12px; height: 36px; - transition: border-color 0.2s, background 0.2s; - cursor: pointer; - position: relative; - user-select: none; } -.model-chip:hover { - border-color: #bbb; -} - -.model-chip.open .model-chevron { - transform: rotate(180deg); -} - -.model-icon { - color: var(--accents-4); - flex-shrink: 0; -} - -.model-label { +.model-select { + border: none; + background: transparent; font-size: 12px; color: var(--chat-ink); - white-space: nowrap; - pointer-events: none; -} - -.model-chevron { - color: var(--accents-4); - flex-shrink: 0; - pointer-events: none; - transition: transform 0.2s; -} - -.model-dropdown { - position: absolute; - bottom: calc(100% + 8px); - left: 50%; - transform: translateX(-50%); - background: #fff; - border: 1px solid var(--chat-border); - border-radius: 12px; - padding: 4px; - box-shadow: 0 12px 32px rgba(17, 17, 17, 0.12); - z-index: 30; - min-width: 160px; - max-height: 280px; - overflow-y: auto; -} - -.model-option { - padding: 7px 12px; - font-size: 13px; - border-radius: 8px; - cursor: pointer; - color: var(--chat-ink); - transition: background 0.15s; - white-space: nowrap; -} - -.model-option:hover { - background: var(--chat-muted); -} - -.model-option.selected { - color: #111; - font-weight: 500; -} - -.reasoning-chip { - display: inline-flex; - align-items: center; - gap: 4px; - padding: 6px 10px; - border-radius: 999px; - border: 1px solid var(--chat-border); - background: var(--chat-surface); - font-size: 12px; - height: 36px; - transition: border-color 0.2s, background 0.2s; - cursor: pointer; - position: relative; - user-select: none; -} - -.reasoning-chip:hover { - border-color: #bbb; -} - -.reasoning-chip.active { - border-color: #a855f7; - background: rgba(168, 85, 247, 0.06); -} - -.reasoning-chip.active:hover { - border-color: #9333ea; -} - -.reasoning-icon { - color: var(--accents-4); - flex-shrink: 0; -} - -.reasoning-chip.active .reasoning-icon { - color: #a855f7; -} - -.reasoning-label { - font-size: 12px; - color: var(--chat-ink); - white-space: nowrap; - pointer-events: none; -} - -.reasoning-chevron { - color: var(--accents-4); - flex-shrink: 0; - pointer-events: none; - transition: transform 0.2s; -} - -.reasoning-chip.open .reasoning-chevron { - transform: rotate(180deg); -} - -.reasoning-dropdown { - position: absolute; - bottom: calc(100% + 8px); - left: 50%; - transform: translateX(-50%); - background: #fff; - border: 1px solid var(--chat-border); - border-radius: 12px; - padding: 4px; - box-shadow: 0 12px 32px rgba(17, 17, 17, 0.12); - z-index: 30; - min-width: 120px; -} - -.reasoning-option { - padding: 7px 12px; - font-size: 13px; - border-radius: 8px; - cursor: pointer; - color: var(--chat-ink); - transition: background 0.15s; - white-space: nowrap; -} - -.reasoning-option:hover { - background: var(--chat-muted); -} - -.reasoning-option.selected { - color: #a855f7; - font-weight: 500; + outline: none; + padding: 0; + appearance: none; + -webkit-appearance: none; + -moz-appearance: none; } .send-btn { @@ -1098,27 +700,6 @@ body { opacity: 0.5; } -.action-icon-btn { - width: 32px; - height: 32px; - border-radius: 50%; - border: 1px solid var(--chat-border); - background: var(--chat-surface); - color: var(--accents-4); - display: inline-flex; - align-items: center; - justify-content: center; - cursor: pointer; - transition: color 0.2s ease, border-color 0.2s ease, background 0.2s ease; - flex-shrink: 0; -} - -.action-icon-btn:hover { - color: var(--chat-ink); - border-color: #bbb; - background: var(--chat-muted); -} - .popover { position: relative; } @@ -1222,128 +803,12 @@ body { } @media (max-width: 720px) { - .chat-sidebar { - position: fixed; - left: 0; - top: 0; - bottom: 0; - width: 280px; - z-index: 100; - transform: translateX(-100%); - transition: transform 0.25s ease; - border-radius: 0; - border-right: 1px solid var(--chat-border); - box-shadow: none; - } - - .chat-sidebar.open { - transform: translateX(0); - box-shadow: 4px 0 24px rgba(0, 0, 0, 0.1); - } - - .sidebar-overlay { - display: none; - position: fixed; - inset: 0; - background: rgba(0, 0, 0, 0.3); - z-index: 99; - } - - .sidebar-overlay.open { - display: block; - } - - .sidebar-toggle { - display: inline-flex; - } - - .chat-shell { - padding-left: 0; - } - .message-bubble { max-width: 100%; } .composer-input { - flex-wrap: wrap; - align-items: center; - border-radius: 16px; - padding: 8px 10px; - gap: 6px; - } - - .composer-textarea { - order: 0; - flex: 1; - min-width: 0; - min-height: 36px; - height: 36px; - padding: 8px 0; - } - - .composer-input > .icon-btn { - order: -1; - width: 32px; - height: 32px; - } - - .composer-actions { - order: 10; - width: 100%; - display: flex; - align-items: center; - gap: 6px; - flex-wrap: wrap; - overflow: visible; - border-top: 1px solid var(--chat-border); - padding-top: 6px; - margin-top: 2px; - } - - .model-dropdown { - bottom: calc(100% + 8px); - left: 0; - transform: none; - max-height: 50vh; - } - - .reasoning-dropdown { - bottom: calc(100% + 8px); - left: 0; - transform: none; - } - - .model-chip, - .reasoning-chip { - font-size: 11px; - padding: 4px 8px; - height: 28px; - flex-shrink: 0; - } - - .model-label { - font-size: 11px; - max-width: 100px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .reasoning-label { - font-size: 11px; - } - - .send-btn { - width: 28px; - height: 28px; - flex-shrink: 0; - } - - .action-icon-btn { - width: 28px; - height: 28px; - flex-shrink: 0; + align-items: flex-start; } .settings-panel { @@ -1351,9 +816,332 @@ body { left: 0; width: 92vw; } +} - .chat-main { - padding-left: 12px; - padding-right: 12px; +/* --- Extensions for multi-session UI --- */ +.chat-layout { + display: flex; + gap: 20px; + align-items: flex-start; +} + +.chat-sidebar { + width: 180px; + flex-shrink: 0; + border: 1px solid var(--chat-border); + border-radius: 16px; + background: var(--chat-surface); + display: flex; + flex-direction: column; + overflow: hidden; + height: calc(100vh - 56px - 64px); + position: sticky; + top: 56px; +} + +.sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 4px 12px; + border-bottom: 1px solid var(--chat-border); + min-height: 26px; +} + +.sidebar-title { + font-size: 12px; + font-weight: 600; + color: var(--chat-ink); +} + +.sidebar-actions { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.sidebar-action-btn { + border: none; + background: transparent; + color: var(--chat-ink); + font-size: 10px; + padding: 0; + cursor: pointer; +} + +.sidebar-action-btn.icon-btn { + width: 24px; + height: 24px; + border-radius: 8px; + display: inline-flex; + align-items: center; + justify-content: center; +} + +.sidebar-action-btn.icon-btn:hover { + background: var(--chat-muted); +} + +.sidebar-list { + flex: 1; + overflow-y: auto; + padding: 8px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.session-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 6px; + border-radius: 10px; + cursor: pointer; +} + +.session-item:hover { + background: var(--chat-muted); +} + +.session-item.active { + background: var(--chat-soft); +} + +.session-title { + flex: 1; + min-width: 0; + font-size: 11px; + color: var(--chat-ink); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + line-height: 1.1; +} + +.session-delete { + width: 22px; + height: 22px; + border: none; + background: transparent; + color: var(--accents-4); + border-radius: 6px; + cursor: pointer; + opacity: 0; + display: inline-flex; + align-items: center; + justify-content: center; + line-height: 1; + padding: 0; +} + +.session-item:hover .session-delete { + opacity: 1; +} + +.session-delete:hover { + color: #b91c1c; + background: rgba(185, 28, 28, 0.08); +} + +.session-rename-input { + flex: 1; + min-width: 0; + font-size: 12px; + color: var(--chat-ink); + border: 1px solid var(--chat-border); + border-radius: 6px; + padding: 2px 6px; + background: var(--chat-surface); + outline: none; +} + +.session-unread { + width: 8px; + height: 8px; + border-radius: 999px; + background: #22c55e; +} + +.sidebar-overlay { + display: none; +} + +.sidebar-toggle { + display: none; + width: 30px; + height: 30px; + border-radius: 8px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + align-items: center; + justify-content: center; + cursor: pointer; +} + +.sidebar-expand-btn { + display: none; + align-self: flex-start; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + padding: 0; + width: 32px; + height: 32px; + border-radius: 999px; + cursor: pointer; + margin-top: 6px; + margin-left: 0; + align-items: center; + justify-content: center; + position: sticky; + top: 56px; + z-index: 5; +} + +.sidebar-expand-btn:hover { + border-color: #b8b8b8; + background: var(--chat-muted); +} + +@media (min-width: 1025px) { +.chat-layout.collapsed { + gap: 8px; +} + + .chat-layout.collapsed .chat-sidebar { + width: 0; + border: none; + padding: 0; + overflow: hidden; + } + + .chat-layout.collapsed .chat-shell { + padding-left: 0; + } + +.chat-layout.collapsed .sidebar-expand-btn { + display: inline-flex; + margin-left: 0; + margin-right: 8px; +} +} + +.chat-shell { + flex: 1; + min-width: 0; +} + +.model-chip { + cursor: pointer; + position: relative; +} + +.model-chip:hover { + border-color: #b8b8b8; +} + +.model-label { + font-size: 12px; + color: var(--chat-ink); +} + +.model-dropdown { + position: absolute; + bottom: calc(100% + 6px); + left: 0; + min-width: 160px; + background: var(--chat-surface); + border: 1px solid var(--chat-border); + border-radius: 12px; + box-shadow: 0 10px 30px rgba(15, 15, 15, 0.08); + padding: 6px; + z-index: 20; +} + +.model-option { + padding: 6px 8px; + border-radius: 8px; + font-size: 12px; + color: var(--chat-ink); + cursor: pointer; +} + +.model-option:hover, +.model-option.selected { + background: var(--chat-muted); +} + +.action-icon-btn { + width: 34px; + height: 34px; + border-radius: 10px; + border: 1px solid var(--chat-border); + background: var(--chat-surface); + color: var(--chat-ink); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.action-icon-btn:hover { + border-color: #b8b8b8; +} + +.edit-msg-input { + width: 100%; + border: 1px solid var(--chat-border); + border-radius: 12px; + padding: 10px 12px; + font-size: 13px; + font-family: 'Geist Sans', sans-serif; +} + +.edit-msg-actions { + display: flex; + gap: 8px; + margin-top: 8px; +} + +@media (max-width: 1024px) { + .chat-layout { + position: relative; + } + + .chat-sidebar { + position: fixed; + top: 56px; + left: 0; + height: calc(100% - 56px); + transform: translateX(-110%); + transition: transform 0.2s ease; + z-index: 50; + } + + .chat-sidebar.open { + transform: translateX(0); + } + + .sidebar-overlay { + display: block; + position: fixed; + inset: 0; + background: rgba(17, 17, 17, 0.18); + opacity: 0; + pointer-events: none; + transition: opacity 0.2s ease; + z-index: 40; + } + + .sidebar-overlay.open { + opacity: 1; + pointer-events: auto; + } + + .sidebar-toggle { + display: inline-flex; } } diff --git a/app/static/public/js/chat.js b/app/static/public/js/chat.js index 3472dfec..bdc5a0fe 100644 --- a/app/static/public/js/chat.js +++ b/app/static/public/js/chat.js @@ -4,10 +4,6 @@ const modelDropdown = document.getElementById('modelDropdown'); let modelValue = 'grok-4.20-beta'; let modelList = []; - const reasoningChip = document.getElementById('reasoningChip'); - const reasoningLabel = document.getElementById('reasoningLabel'); - const reasoningDropdown = document.getElementById('reasoningDropdown'); - let reasoningValue = ''; const tempRange = document.getElementById('tempRange'); const tempValue = document.getElementById('tempValue'); const topPRange = document.getElementById('topPRange'); @@ -29,11 +25,13 @@ const sidebarOverlay = document.getElementById('sidebarOverlay'); const sidebarToggle = document.getElementById('sidebarToggle'); const newChatBtn = document.getElementById('newChatBtn'); + const collapseSidebarBtn = document.getElementById('collapseSidebarBtn'); + const sidebarExpandBtn = document.getElementById('sidebarExpandBtn'); const sessionListEl = document.getElementById('sessionList'); - const clearChatBtn = document.getElementById('clearChatBtn'); - const compressCtxBtn = document.getElementById('compressCtxBtn'); const STORAGE_KEY = 'grok2api_chat_sessions'; + const SIDEBAR_STATE_KEY = 'grok2api_chat_sidebar_collapsed'; + const MAX_CONTEXT_MESSAGES = 5; let messageHistory = []; let isSending = false; @@ -41,6 +39,7 @@ let attachment = null; let activeStreamInfo = null; const feedbackUrl = 'https://github.com/chenyme/grok2api/issues/new'; + const CHAT_COMPLETIONS_ENDPOINT = '/v1/public/chat/completions'; let sessionsData = null; @@ -81,12 +80,86 @@ renderSessionList(); } + function getMessageDisplay(msg) { + if (!msg) return ''; + if (typeof msg.content === 'string') return msg.content; + if (typeof msg.display === 'string' && msg.display.trim()) return msg.display; + if (Array.isArray(msg.content)) { + const textParts = []; + let hasFile = false; + for (const block of msg.content) { + if (!block) continue; + if (block.type === 'text' && block.text) { + textParts.push(block.text); + } + if (block.type === 'file') { + hasFile = true; + } + } + const name = msg.attachmentName || ''; + const fileLabel = hasFile ? (name ? `[文件] ${name}` : '[文件]') : ''; + if (textParts.length && fileLabel) return `${textParts.join('\n')}\n${fileLabel}`; + if (textParts.length) return textParts.join('\n'); + return fileLabel || '[复合内容]'; + } + return '[复合内容]'; + } + + function serializeMessage(msg) { + if (!msg || typeof msg !== 'object') return msg; + if (Array.isArray(msg.content)) { + return { + ...msg, + content: getMessageDisplay(msg) + }; + } + return msg; + } + + function serializeSessions() { + if (!sessionsData) return null; + return { + activeId: sessionsData.activeId, + sessions: sessionsData.sessions.map((session) => ({ + ...session, + messages: Array.isArray(session.messages) + ? session.messages.map(serializeMessage) + : [] + })) + }; + } + function saveSessions() { if (!sessionsData) return; + const snapshot = serializeSessions(); + if (!snapshot) return; try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(sessionsData)); + localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot)); } catch (e) { - // localStorage full or unavailable + toast('本地存储空间不足,部分会话未保存', 'error'); + } + } + + function trimMessageHistory(maxCount = MAX_CONTEXT_MESSAGES) { + if (!maxCount || maxCount <= 0) return; + if (messageHistory.length <= maxCount) return; + messageHistory = messageHistory.slice(-maxCount); + const session = getActiveSession(); + if (session) { + session.messages = messageHistory.slice(); + session.updatedAt = Date.now(); + saveSessions(); + renderSessionList(); + } + if (chatLog) { + const rows = Array.from(chatLog.querySelectorAll('.message-row')); + const removeCount = rows.length - messageHistory.length; + if (removeCount > 0) { + rows.slice(0, removeCount).forEach((row) => row.remove()); + } + } + if (!messageHistory.length) { + showEmptyState(); } } @@ -99,6 +172,7 @@ const session = getActiveSession(); if (!session) return; messageHistory = session.messages.slice(); + trimMessageHistory(); if (chatLog) chatLog.innerHTML = ''; if (!messageHistory.length) { showEmptyState(); @@ -106,8 +180,9 @@ } hideEmptyState(); for (const msg of messageHistory) { - const displayContent = typeof msg.content === 'string' ? msg.content : '[复合内容]'; - const entry = createMessage(msg.role, displayContent, true); + const displayContent = getMessageDisplay(msg); + const editable = !msg.hasAttachment && typeof msg.content === 'string'; + const entry = createMessage(msg.role, displayContent, true, { editable }); if (entry && msg.role === 'assistant') { updateMessage(entry, displayContent, true); } @@ -134,7 +209,7 @@ showEmptyState(); saveSessions(); renderSessionList(); - closeSidebar(); + if (isMobileSidebar()) closeSidebar(); } function deleteSession(id) { @@ -165,7 +240,7 @@ restoreSessionModel(); saveSessions(); renderSessionList(); - closeSidebar(); + if (isMobileSidebar()) closeSidebar(); } function syncCurrentSession() { @@ -180,7 +255,7 @@ if (session.title && session.title !== '新会话') return; const firstUser = session.messages.find(m => m.role === 'user'); if (!firstUser) return; - const text = typeof firstUser.content === 'string' ? firstUser.content : ''; + const text = getMessageDisplay(firstUser); if (!text) return; const title = text.replace(/\n/g, ' ').trim().slice(0, 20); if (title) { @@ -272,22 +347,51 @@ } } + function isMobileSidebar() { + return window.matchMedia('(max-width: 1024px)').matches; + } + + function setSidebarCollapsed(collapsed) { + const layout = chatSidebar ? chatSidebar.closest('.chat-layout') : null; + if (!layout) return; + layout.classList.toggle('collapsed', collapsed); + try { + localStorage.setItem(SIDEBAR_STATE_KEY, collapsed ? '1' : '0'); + } catch (e) { + // ignore storage failures + } + } + function openSidebar() { - if (chatSidebar) chatSidebar.classList.add('open'); - if (sidebarOverlay) sidebarOverlay.classList.add('open'); + if (isMobileSidebar()) { + if (chatSidebar) chatSidebar.classList.add('open'); + if (sidebarOverlay) sidebarOverlay.classList.add('open'); + return; + } + setSidebarCollapsed(false); } function closeSidebar() { - if (chatSidebar) chatSidebar.classList.remove('open'); - if (sidebarOverlay) sidebarOverlay.classList.remove('open'); + if (isMobileSidebar()) { + if (chatSidebar) chatSidebar.classList.remove('open'); + if (sidebarOverlay) sidebarOverlay.classList.remove('open'); + return; + } + setSidebarCollapsed(true); } function toggleSidebar() { - if (chatSidebar && chatSidebar.classList.contains('open')) { - closeSidebar(); - } else { - openSidebar(); + if (isMobileSidebar()) { + if (chatSidebar && chatSidebar.classList.contains('open')) { + closeSidebar(); + } else { + openSidebar(); + } + return; } + const layout = chatSidebar ? chatSidebar.closest('.chat-layout') : null; + if (!layout) return; + setSidebarCollapsed(!layout.classList.contains('collapsed')); } function toast(message, type) { @@ -351,6 +455,18 @@ .replace(/'/g, '''); } + function isSafeLinkUrl(url) { + const val = String(url || '').trim().toLowerCase(); + if (!val) return false; + return /^(https?:|mailto:|tel:|\/(?!\/)|\.\.?\/|#)/.test(val); + } + + function isSafeImageUrl(url) { + const val = String(url || '').trim().toLowerCase(); + if (!val) return false; + return /^(https?:|data:image\/(?:png|jpe?g|gif|webp|bmp|ico);base64,|\/(?!\/)|\.\.?\/)/.test(val); + } + function renderBasicMarkdown(rawText) { const text = (rawText || '').replace(/\\n/g, '\n'); const escaped = escapeHtml(text); @@ -364,34 +480,49 @@ }); const renderInline = (value) => { - let output = value - .replace(/`([^`]+)`/g, '$1') + const inlineCodes = []; + let output = value.replace(/`([^`]+)`/g, (match, code) => { + const token = `@@INLINE_${inlineCodes.length}@@`; + inlineCodes.push(`${code}`); + return token; + }); + + output = output .replace(/\*\*([^*]+)\*\*/g, '$1') - .replace(/\*([^*]+)\*/g, '$1'); + .replace(/\*([^*]+)\*/g, '$1') + .replace(/~~([^~]+)~~/g, '$1'); output = output.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => { const safeAlt = escapeHtml(alt || 'image'); + if (!isSafeImageUrl(url)) return safeAlt; const safeUrl = escapeHtml(url || ''); return `${safeAlt}`; }); output = output.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, label, url) => { const safeLabel = escapeHtml(label || ''); + if (!isSafeLinkUrl(url)) return safeLabel; const safeUrl = escapeHtml(url || ''); return `${safeLabel}`; }); output = output.replace(/(data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+)/g, (match, uri) => { + if (!isSafeImageUrl(uri)) return ''; const safeUrl = escapeHtml(uri || ''); return `image`; }); + inlineCodes.forEach((html, i) => { + output = output.replace(new RegExp(`@@INLINE_${i}@@`, 'g'), html); + }); + return output; }; const lines = fenced.split(/\r?\n/); const htmlParts = []; let inUl = false; + let inUlTask = false; let inOl = false; let inTable = false; let paragraphLines = []; @@ -400,6 +531,7 @@ if (inUl) { htmlParts.push(''); inUl = false; + inUlTask = false; } if (inOl) { htmlParts.push(''); @@ -457,6 +589,31 @@ continue; } + if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { + flushParagraph(); + closeLists(); + closeTable(); + htmlParts.push('
'); + continue; + } + + if (/^\s*>/.test(line)) { + flushParagraph(); + closeLists(); + closeTable(); + const quoteLines = []; + let j = i; + for (; j < lines.length; j += 1) { + const currentLine = lines[j]; + if (!/^\s*>/.test(currentLine)) break; + quoteLines.push(currentLine.replace(/^\s*>\s?/, '')); + } + i = j - 1; + const quoteText = quoteLines.join('\n'); + htmlParts.push(`
${renderBasicMarkdown(quoteText)}
`); + continue; + } + if (trimmed.includes('|')) { const nextLine = lines[i + 1] || ''; if (!inTable && isTableSeparator(nextLine.trim())) { @@ -479,6 +636,24 @@ } } + const taskMatch = trimmed.match(/^[-*+•·]\s+\[([ xX])\]\s+(.*)$/); + if (taskMatch) { + flushParagraph(); + if (inUl && !inUlTask) { + closeLists(); + } + if (!inUl) { + closeLists(); + closeTable(); + htmlParts.push('
    '); + inUl = true; + inUlTask = true; + } + const checked = taskMatch[1].toLowerCase() === 'x'; + htmlParts.push(`
  • ${renderInline(taskMatch[2])}
  • `); + continue; + } + const ulMatch = trimmed.match(/^[-*+•·]\s+(.*)$/); if (ulMatch) { flushParagraph(); @@ -487,6 +662,7 @@ closeTable(); htmlParts.push('
      '); inUl = true; + inUlTask = false; } htmlParts.push(`
    • ${renderInline(ulMatch[1])}
    • `); continue; @@ -596,11 +772,11 @@ } const toolTypeMap = { - websearch: { icon: '\uD83D\uDD0D', label: '\u641C\u7D22' }, - searchimage: { icon: '\uD83D\uDDBC', label: '\u56FE\u641C' }, - agentthink: { icon: '\uD83D\uDCAD', label: '\u63A8\u7406' } + websearch: { icon: '', label: '\u7F51\u9875\u641C\u7D22' }, + searchimage: { icon: '', label: '\u56FE\u7247\u641C\u7D22' }, + agentthink: { icon: '', label: '\u601D\u8003\u63A8\u7406' } }; - const defaultToolType = { icon: '\uD83D\uDD27', label: '\u5DE5\u5177' }; + const defaultToolType = { icon: '', label: '\u5DE5\u5177' }; function getToolMeta(typeStr) { const key = String(typeStr || '').trim().toLowerCase().replace(/\s+/g, ''); @@ -631,7 +807,8 @@ const typeKey = String(item.type || '').trim().toLowerCase().replace(/\s+/g, ''); const typeAttr = escapeHtml(typeKey); const meta = getToolMeta(item.type); - const typeLabel = `${meta.icon}${escapeHtml(meta.label)}`; + const iconHtml = meta.icon ? `${meta.icon}` : ''; + const typeLabel = `${iconHtml}${escapeHtml(meta.label)}`; return `
      ${typeLabel}
      ${body || '\uFF08\u7A7A\uFF09'}
      `; }).join(''); const title = escapeHtml(group.id); @@ -693,6 +870,10 @@ const idx = Array.from(rows).indexOf(row); if (idx === -1 || idx >= messageHistory.length) return; const msg = messageHistory[idx]; + if (msg && (msg.hasAttachment || typeof msg.content !== 'string')) { + toast('附件消息暂不支持编辑', 'error'); + return; + } const currentText = typeof msg.content === 'string' ? msg.content : ''; const contentNode = row.querySelector('.message-content'); @@ -797,7 +978,7 @@ } catch (e) {} try { - const res = await fetch('/v1/chat/completions', { + const res = await fetch(CHAT_COMPLETIONS_ENDPOINT, { method: 'POST', headers, body: JSON.stringify(payload), @@ -827,7 +1008,7 @@ })(); } - function createMessage(role, content, skipScroll) { + function createMessage(role, content, skipScroll, options) { if (!chatLog) return null; hideEmptyState(); const row = document.createElement('div'); @@ -856,11 +1037,13 @@ thinkAutoCollapsed: false }; if (role === 'user') { + const editable = options && options.editable === false ? false : true; const actions = document.createElement('div'); actions.className = 'message-actions'; - actions.appendChild(createActionButton('编辑', '编辑消息内容', () => editMessageByRow(row))); + if (editable) { + actions.appendChild(createActionButton('编辑', '编辑消息内容', () => editMessageByRow(row))); + } actions.appendChild(createActionButton('重新生成', '从此处重新生成回复', () => regenerateFromRow(row))); - actions.appendChild(createActionButton('删除', '从上下文中删除', () => deleteMessageByRow(row))); row.appendChild(actions); } return entry; @@ -1080,55 +1263,6 @@ }); } - function clearChat() { - if (isSending) return; - messageHistory = []; - if (chatLog) { - chatLog.innerHTML = ''; - } - showEmptyState(); - const session = getActiveSession(); - if (session) { - session.messages = []; - session.title = '新会话'; - session.updatedAt = Date.now(); - saveSessions(); - renderSessionList(); - } - } - - function compressContext() { - if (isSending) return; - if (messageHistory.length <= 2) { - toast('消息太少,无需压缩', 'error'); - return; - } - const kept = messageHistory.slice(-4); - const droppedCount = messageHistory.length - kept.length; - messageHistory = kept; - const session = getActiveSession(); - if (session) { - session.messages = messageHistory.slice(); - session.updatedAt = Date.now(); - saveSessions(); - } - if (chatLog) chatLog.innerHTML = ''; - if (!messageHistory.length) { - showEmptyState(); - } else { - hideEmptyState(); - for (const msg of messageHistory) { - const displayContent = typeof msg.content === 'string' ? msg.content : '[复合内容]'; - const entry = createMessage(msg.role, displayContent, true); - if (entry && msg.role === 'assistant') { - updateMessage(entry, displayContent, true); - } - } - scrollToBottom(); - } - toast(`已压缩,移除了 ${droppedCount} 条旧消息`, 'success'); - } - function buildMessages() { return buildMessagesFrom(messageHistory); } @@ -1153,10 +1287,6 @@ temperature: Number(tempRange ? tempRange.value : 0.8), top_p: Number(topPRange ? topPRange.value : 0.95) }; - const reasoning = reasoningValue || ''; - if (reasoning) { - payload.reasoning_effort = reasoning; - } return payload; } @@ -1168,10 +1298,6 @@ temperature: Number(tempRange ? tempRange.value : 0.8), top_p: Number(topPRange ? topPRange.value : 0.95) }; - const reasoning = reasoningValue || ''; - if (reasoning) { - payload.reasoning_effort = reasoning; - } return payload; } @@ -1207,7 +1333,7 @@ async function loadModels() { if (!modelDropdown) return; - const fallback = ['grok-4.1-fast', 'grok-4', 'grok-3', 'grok-3-mini', 'grok-3-thinking', 'grok-4.20-beta']; + const fallback = ['grok-4.1-fast', 'grok-4', 'grok-3', 'grok-3-mini', 'grok-3-thinking', 'grok-4.20-beta', 'grok-imagine-1.0-fast']; const preferred = 'grok-4.20-beta'; try { const res = await fetch('/v1/models', { cache: 'no-store' }); @@ -1217,8 +1343,13 @@ const ids = items .map(item => item && item.id) .filter(Boolean) - .filter(id => !String(id).startsWith('grok-imagine')) - .filter(id => !String(id).includes('video')); + .filter((id) => { + const name = String(id); + if (name.startsWith('grok-imagine')) { + return name === 'grok-imagine-1.0-fast'; + } + return !name.includes('video'); + }); modelList = ids.length ? ids : fallback; } catch (e) { modelList = fallback; @@ -1291,7 +1422,6 @@ const retryBtn = createActionButton('重试', '重试上一条回答', () => retryLast()); const editBtn = createActionButton('编辑', '编辑回答内容', () => editMessageByRow(entry.row)); const copyBtn = createActionButton('复制', '复制回答内容', () => copyToClipboard(entry.raw || '')); - const deleteBtn = createActionButton('删除', '从上下文中删除', () => deleteMessageByRow(entry.row)); const feedbackBtn = createActionButton('反馈', '反馈到 Grok2API', () => { window.open(feedbackUrl, '_blank', 'noopener'); }); @@ -1299,7 +1429,6 @@ actions.appendChild(retryBtn); actions.appendChild(editBtn); actions.appendChild(copyBtn); - actions.appendChild(deleteBtn); actions.appendChild(feedbackBtn); entry.row.appendChild(actions); } @@ -1360,7 +1489,7 @@ } try { - const res = await fetch('/v1/chat/completions', { + const res = await fetch(CHAT_COMPLETIONS_ENDPOINT, { method: 'POST', headers, body: JSON.stringify(payload), @@ -1398,7 +1527,7 @@ displayText = displayText ? `${displayText}\n${label}` : label; } - createMessage('user', displayText); + createMessage('user', displayText, false, { editable: !attachment }); let content = prompt; if (attachment) { @@ -1410,7 +1539,14 @@ content = blocks; } - messageHistory.push({ role: 'user', content }); + messageHistory.push({ + role: 'user', + content, + display: displayText, + hasAttachment: !!attachment, + attachmentName: attachment ? attachment.name : '' + }); + trimMessageHistory(); if (promptInput) promptInput.value = ''; clearAttachment(); syncCurrentSession(); @@ -1436,7 +1572,7 @@ } try { - const res = await fetch('/v1/chat/completions', { + const res = await fetch(CHAT_COMPLETIONS_ENDPOINT, { method: 'POST', headers, body: JSON.stringify(payload), @@ -1477,10 +1613,14 @@ const session = sessionsData.sessions.find(s => s.id === sessionId); if (!session) return; session.messages.push({ role: 'assistant', content: assistantText }); + if (session.messages.length > MAX_CONTEXT_MESSAGES) { + session.messages = session.messages.slice(-MAX_CONTEXT_MESSAGES); + } session.updatedAt = Date.now(); updateSessionTitle(session); if (sessionsData.activeId === sessionId) { messageHistory = session.messages.slice(); + trimMessageHistory(); } else { session.unread = true; } @@ -1572,29 +1712,11 @@ settingsPanel.classList.toggle('hidden'); } - function selectReasoning(value, label) { - reasoningValue = value; - if (reasoningLabel) reasoningLabel.textContent = label; - if (reasoningChip) { - reasoningChip.classList.toggle('active', !!value); - } - if (reasoningDropdown) { - reasoningDropdown.querySelectorAll('.reasoning-option').forEach((opt) => { - opt.classList.toggle('selected', opt.dataset.value === value); - }); - } - } - - function toggleReasoningDropdown(show) { - if (!reasoningDropdown || !reasoningChip) return; - if (typeof show === 'boolean') { - reasoningDropdown.classList.toggle('hidden', !show); - reasoningChip.classList.toggle('open', show); - return; - } - const visible = !reasoningDropdown.classList.contains('hidden'); - reasoningDropdown.classList.toggle('hidden', visible); - reasoningChip.classList.toggle('open', !visible); + function restoreSidebarState() { + try { + const raw = localStorage.getItem(SIDEBAR_STATE_KEY); + setSidebarCollapsed(raw === '1'); + } catch (e) {} } function bindEvents() { @@ -1604,7 +1726,6 @@ modelChip.addEventListener('click', (event) => { if (event.target.closest('.model-dropdown')) return; event.stopPropagation(); - toggleReasoningDropdown(false); toggleModelDropdown(); }); } @@ -1617,23 +1738,6 @@ toggleModelDropdown(false); }); } - if (reasoningChip) { - reasoningChip.addEventListener('click', (event) => { - if (event.target.closest('.reasoning-dropdown')) return; - event.stopPropagation(); - toggleModelDropdown(false); - toggleReasoningDropdown(); - }); - } - if (reasoningDropdown) { - reasoningDropdown.addEventListener('click', (event) => { - const opt = event.target.closest('.reasoning-option'); - if (!opt) return; - event.stopPropagation(); - selectReasoning(opt.dataset.value, opt.textContent); - toggleReasoningDropdown(false); - }); - } if (sendBtn) sendBtn.addEventListener('click', sendMessage); if (settingsToggle) { settingsToggle.addEventListener('click', (event) => { @@ -1652,11 +1756,6 @@ toggleModelDropdown(false); } } - if (reasoningDropdown && !reasoningDropdown.classList.contains('hidden')) { - if (!(reasoningChip && reasoningChip.contains(event.target))) { - toggleReasoningDropdown(false); - } - } }); if (promptInput) { let composing = false; @@ -1688,23 +1787,24 @@ if (newChatBtn) { newChatBtn.addEventListener('click', createSession); } + if (collapseSidebarBtn) { + collapseSidebarBtn.addEventListener('click', toggleSidebar); + } + if (sidebarExpandBtn) { + sidebarExpandBtn.addEventListener('click', openSidebar); + } if (sidebarToggle) { sidebarToggle.addEventListener('click', toggleSidebar); } if (sidebarOverlay) { sidebarOverlay.addEventListener('click', closeSidebar); } - if (clearChatBtn) { - clearChatBtn.addEventListener('click', clearChat); - } - if (compressCtxBtn) { - compressCtxBtn.addEventListener('click', compressContext); - } } updateRangeValues(); loadModels(); bindEvents(); + restoreSidebarState(); (async () => { try { diff --git a/app/static/public/pages/chat.html b/app/static/public/pages/chat.html index e374e801..f8e99957 100644 --- a/app/static/public/pages/chat.html +++ b/app/static/public/pages/chat.html @@ -9,8 +9,8 @@ - - + + @@ -18,21 +18,36 @@
      -
      +
      +
      @@ -83,25 +98,6 @@
      -
      - - - - - - 跟随配置 - - - - -
      @@ -167,11 +147,11 @@ - - - + + + - + diff --git a/app/static/public/pages/imagine.html b/app/static/public/pages/imagine.html index de1f49c1..457a285f 100644 --- a/app/static/public/pages/imagine.html +++ b/app/static/public/pages/imagine.html @@ -9,8 +9,8 @@ - - + + @@ -237,12 +237,12 @@ - - - + + + - + diff --git a/app/static/public/pages/login.html b/app/static/public/pages/login.html index a78ed8ca..d3a941ad 100644 --- a/app/static/public/pages/login.html +++ b/app/static/public/pages/login.html @@ -24,8 +24,8 @@ } } - - + + @@ -59,10 +59,10 @@ - + - - + + diff --git a/app/static/public/pages/video.html b/app/static/public/pages/video.html index 530f12aa..dfbc005c 100644 --- a/app/static/public/pages/video.html +++ b/app/static/public/pages/video.html @@ -9,8 +9,8 @@ - - + + @@ -158,11 +158,11 @@ - - - + + + - + diff --git a/app/static/public/pages/voice.html b/app/static/public/pages/voice.html index 8771694f..3739fd5a 100644 --- a/app/static/public/pages/voice.html +++ b/app/static/public/pages/voice.html @@ -9,8 +9,8 @@ - - + + @@ -147,11 +147,11 @@ - - - + + + - + diff --git a/pyproject.toml b/pyproject.toml index 664c86e0..ba201603 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "grok2api" -version = "1.5.0" +version = "1.5.1" description = "Grok2API rebuilt with FastAPI, fully aligned with the latest web call format. Supports streaming and non-streaming chat, image generation/editing, deep thinking, token pool concurrency, and automatic load balancing." readme = "README.md" requires-python = ">=3.13"