Download index.html from simonu5/chat: direct link, hf CLI and curl.
- Browser
- Download file 80.1 kB
-
https://huggingface.co/spaces/simonu5/chat/resolve/main/index.html
- Command line
-
hf download hf://spaces/simonu5/chat/index.html
-
curl -L -o index.html https://huggingface.co/spaces/simonu5/chat/resolve/main/index.html
80.1 kB
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Agent Chat</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--bg-primary: #ffffff;
--bg-secondary: #f7f7f8;
--bg-tertiary: #eeeeef;
--bg-chat: #f7f7f8;
--text-primary: #1a1a1b;
--text-secondary: #545455;
--text-muted: #8e8e93;
--border-color: #e5e5e6;
--accent: #0066cc;
--accent-hover: #0052a3;
--accent-light: #e8f0fe;
--user-bubble: #0066cc;
--user-text: #ffffff;
--assistant-bubble: #ffffff;
--code-bg: #f0f0f1;
--code-text: #1a1a1b;
--sidebar-bg: #ffffff;
--sidebar-border: #e5e5e6;
--shadow: 0 1px 3px rgba(0,0,0,0.08), 0 4px 12px rgba(0,0,0,0.05);
--shadow-lg: 0 8px 30px rgba(0,0,0,0.12);
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
--transition: 150ms ease;
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--font-mono: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;
}
[data-theme="dark"] {
--bg-primary: #1a1a1b;
--bg-secondary: #242425;
--bg-tertiary: #2d2d2e;
--bg-chat: #1a1a1b;
--text-primary: #ffffff;
--text-secondary: #b0b0b3;
--text-muted: #8e8e93;
--border-color: #3a3a3c;
--accent: #4d9fff;
--accent-hover: #6eb4ff;
--accent-light: #1e3a5f;
--user-bubble: #4d9fff;
--user-text: #1a1a1b;
--assistant-bubble: #242425;
--code-bg: #2d2d2e;
--code-text: #e4e4e7;
--sidebar-bg: #1a1a1b;
--sidebar-border: #3a3a3c;
--shadow: 0 1px 3px rgba(0,0,0,0.3), 0 4px 12px rgba(0,0,0,0.2);
--shadow-lg: 0 8px 30px rgba(0,0,0,0.4);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html { font-size: 16px; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
body {
font-family: var(--font-sans);
background: var(--bg-chat);
color: var(--text-primary);
line-height: 1.6;
height: 100vh;
overflow: hidden;
transition: background var(--transition), color var(--transition);
}
/* Layout */
.app {
display: grid;
grid-template-columns: 280px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"sidebar header"
"sidebar main"
"sidebar footer";
height: 100vh;
}
/* Sidebar */
.sidebar {
grid-area: sidebar;
background: var(--sidebar-bg);
border-right: 1px solid var(--sidebar-border);
display: flex;
flex-direction: column;
overflow-y: auto;
position: relative;
z-index: 10;
}
.sidebar-header { padding: 16px; border-bottom: 1px solid var(--sidebar-border); display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.sidebar-title { font-weight: 600; font-size: 1.1rem; color: var(--text-primary); }
.sidebar-close { display: none; background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 8px; border-radius: var(--radius-sm); }
.sidebar-close:hover { background: var(--bg-tertiary); color: var(--text-primary); }
.sidebar-tabs { display: flex; border-bottom: 1px solid var(--sidebar-border); background: var(--bg-secondary); }
.sidebar-tab { flex: 1; padding: 12px 16px; background: none; border: none; color: var(--text-secondary); font-size: 0.875rem; font-weight: 500; cursor: pointer; border-bottom: 2px solid transparent; transition: all var(--transition); }
.sidebar-tab.active { color: var(--accent); border-bottom-color: var(--accent); background: var(--sidebar-bg); }
.sidebar-tab:hover:not(.active) { color: var(--text-primary); background: var(--bg-tertiary); }
.sidebar-content { flex: 1; padding: 16px; overflow-y: auto; }
.sidebar-pane { display: none; }
.sidebar-pane.active { display: block; animation: fadeIn 150ms ease; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
/* Header */
.header {
grid-area: header;
background: var(--bg-primary);
border-bottom: 1px solid var(--border-color);
padding: 12px 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
position: sticky;
top: 0;
z-index: 5;
}
.header-left { display: flex; align-items: center; gap: 12px; }
.sidebar-toggle { display: none; background: none; border: none; color: var(--text-primary); cursor: pointer; padding: 8px; border-radius: var(--radius-sm); }
.sidebar-toggle:hover { background: var(--bg-tertiary); }
.header-title { font-weight: 600; font-size: 1rem; color: var(--text-primary); }
.header-right { display: flex; align-items: center; gap: 8px; }
/* Main Chat Area */
.main {
grid-area: main;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--bg-chat);
}
.messages {
flex: 1;
overflow-y: auto;
padding: 24px;
display: flex;
flex-direction: column;
gap: 20px;
}
.message { display: flex; gap: 12px; max-width: 85%; animation: slideUp 200ms ease; }
@keyframes slideUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
.message.user { align-self: flex-end; flex-direction: row-reverse; }
.message.assistant { align-self: flex-start; }
.message-avatar { width: 32px; height: 32px; border-radius: 50%; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 0.875rem; font-weight: 600; }
.message.user .message-avatar { background: var(--user-bubble); color: var(--user-text); }
.message.assistant .message-avatar { background: var(--accent-light); color: var(--accent); }
.message-bubble { padding: 12px 16px; border-radius: var(--radius-lg); position: relative; }
.message.user .message-bubble { background: var(--user-bubble); color: var(--user-text); border-bottom-right-radius: 4px; }
.message.assistant .message-bubble { background: var(--assistant-bubble); color: var(--text-primary); border: 1px solid var(--border-color); border-bottom-left-radius: 4px; box-shadow: var(--shadow); }
.message-content { white-space: pre-wrap; word-wrap: break-word; font-size: 0.9375rem; line-height: 1.7; }
.message-content code { font-family: var(--font-mono); font-size: 0.875em; background: var(--code-bg); color: var(--code-text); padding: 0.15em 0.4em; border-radius: 4px; }
.message-content pre { background: var(--code-bg); color: var(--code-text); padding: 12px; border-radius: var(--radius-md); overflow-x: auto; margin: 8px 0; font-size: 0.8125rem; line-height: 1.6; }
.message-content pre code { background: none; padding: 0; color: inherit; font-size: inherit; }
.message-meta { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: 0.75rem; color: var(--text-muted); }
.message-actions { display: flex; gap: 8px; opacity: 0; transition: opacity var(--transition); }
.message:hover .message-actions { opacity: 1; }
.message-action { background: none; border: none; color: var(--text-muted); cursor: pointer; padding: 4px 8px; border-radius: var(--radius-sm); font-size: 0.75rem; transition: all var(--transition); }
.message-action:hover { background: var(--bg-tertiary); color: var(--text-primary); }
.welcome { text-align: center; padding: 40px 20px; color: var(--text-secondary); }
.welcome h2 { font-size: 1.5rem; font-weight: 600; color: var(--text-primary); margin-bottom: 8px; }
.welcome p { font-size: 0.9375rem; }
/* Footer / Input Area */
.footer {
grid-area: footer;
background: var(--bg-primary);
border-top: 1px solid var(--border-color);
padding: 16px 24px;
}
.input-wrapper { display: flex; gap: 12px; align-items: flex-end; max-width: 900px; margin: 0 auto; }
.input-area { flex: 1; position: relative; }
.input-area textarea {
width: 100%;
min-height: 48px;
max-height: 200px;
padding: 12px 16px;
padding-right: 48px;
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
background: var(--bg-secondary);
color: var(--text-primary);
font-family: inherit;
font-size: 0.9375rem;
line-height: 1.6;
resize: none;
outline: none;
transition: border-color var(--transition), box-shadow var(--transition);
}
.input-area textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-light); }
.input-area textarea::placeholder { color: var(--text-muted); }
.input-actions { position: absolute; right: 12px; bottom: 12px; display: flex; gap: 4px; }
.send-btn {
width: 40px; height: 40px; border-radius: 50%; border: none; background: var(--accent); color: white; cursor: pointer;
display: flex; align-items: center; justify-content: center; transition: all var(--transition);
flex-shrink: 0;
}
.send-btn:hover:not(:disabled) { background: var(--accent-hover); transform: scale(1.05); }
.send-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.send-btn svg { width: 20px; height: 20px; }
/* Modal */
.modal-overlay {
position: fixed; inset: 0; background: rgba(0,0,0,0.5); backdrop-filter: blur(4px);
display: flex; align-items: center; justify-content: center; z-index: 100; opacity: 0; visibility: hidden; transition: all var(--transition);
}
.modal-overlay.active { opacity: 1; visibility: visible; }
.modal { background: var(--bg-primary); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); width: 90%; max-width: 560px; max-height: 90vh; overflow: hidden; transform: scale(0.95); transition: transform var(--transition); }
.modal-overlay.active .modal { transform: scale(1); }
.modal-header { padding: 20px 24px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between; }
.modal-title { font-weight: 600; font-size: 1.1rem; }
.modal-close { background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 8px; border-radius: var(--radius-sm); font-size: 1.25rem; line-height: 1; }
.modal-close:hover { background: var(--bg-tertiary); color: var(--text-primary); }
.modal-body { padding: 24px; overflow-y: auto; max-height: 60vh; }
.modal-footer { padding: 16px 24px; border-top: 1px solid var(--border-color); display: flex; justify-content: flex-end; gap: 12px; }
/* Form Elements */
.form-group { margin-bottom: 20px; }
.form-label { display: block; font-size: 0.875rem; font-weight: 500; color: var(--text-primary); margin-bottom: 8px; }
.form-input, .form-select, .form-textarea {
width: 100%; padding: 10px 12px; border: 1px solid var(--border-color); border-radius: var(--radius-md);
background: var(--bg-primary); color: var(--text-primary); font-family: inherit; font-size: 0.9375rem;
transition: border-color var(--transition), box-shadow var(--transition);
}
.form-input:focus, .form-select:focus, .form-textarea:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-light); }
.form-textarea { min-height: 100px; resize: vertical; font-family: var(--font-mono); }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.form-help { font-size: 0.75rem; color: var(--text-muted); margin-top: 6px; }
.btn { padding: 10px 20px; border-radius: var(--radius-md); font-weight: 500; font-size: 0.875rem; cursor: pointer; transition: all var(--transition); border: 1px solid transparent; }
.btn-primary { background: var(--accent); color: white; border-color: var(--accent); }
.btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
.btn-secondary { background: var(--bg-secondary); color: var(--text-primary); border-color: var(--border-color); }
.btn-secondary:hover { background: var(--bg-tertiary); border-color: var(--text-muted); }
.btn-danger { background: var(--bg-secondary); color: #dc2626; border-color: #fecaca; }
.btn-danger:hover { background: #fef2f2; border-color: #fca5a5; }
/* Provider List */
.provider-list { display: flex; flex-direction: column; gap: 12px; }
.provider-item { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: var(--radius-md); transition: all var(--transition); }
.provider-item:hover { border-color: var(--accent); }
.provider-item.active { border-color: var(--accent); background: var(--accent-light); }
.provider-info { display: flex; flex-direction: column; gap: 2px; }
.provider-name { font-weight: 500; color: var(--text-primary); }
.provider-base { font-size: 0.75rem; color: var(--text-muted); font-family: var(--font-mono); }
.provider-actions { display: flex; gap: 8px; }
.empty-state { text-align: center; padding: 40px 20px; color: var(--text-muted); }
.empty-state svg { width: 48px; height: 48px; margin-bottom: 12px; opacity: 0.5; }
/* History List */
.history-list { display: flex; flex-direction: column; gap: 8px; }
.history-item { padding: 12px 16px; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: var(--radius-md); cursor: pointer; transition: all var(--transition); display: flex; flex-direction: column; gap: 4px; }
.history-item:hover { border-color: var(--accent); background: var(--accent-light); }
.history-title { font-weight: 500; color: var(--text-primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.history-meta { display: flex; gap: 12px; font-size: 0.75rem; color: var(--text-muted); }
.history-actions { display: flex; gap: 8px; margin-top: 8px; opacity: 0; transition: opacity var(--transition); }
.history-item:hover .history-actions { opacity: 1; }
/* Settings Sections */
.settings-section { margin-bottom: 28px; }
.settings-section-title { font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); margin-bottom: 16px; }
.setting-row { display: flex; align-items: center; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid var(--border-color); }
.setting-info { display: flex; flex-direction: column; gap: 2px; }
.setting-label { font-weight: 500; color: var(--text-primary); }
.setting-desc { font-size: 0.75rem; color: var(--text-muted); }
/* Switch Toggle */
.switch { position: relative; width: 44px; height: 26px; }
.switch input { opacity: 0; width: 0; height: 0; }
.slider { position: absolute; cursor: pointer; inset: 0; background: var(--bg-tertiary); border: 1px solid var(--border-color); border-radius: 34px; transition: var(--transition); }
.slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background: var(--text-primary); border-radius: 50%; transition: var(--transition); box-shadow: 0 1px 3px rgba(0,0,0,0.2); }
input:checked + .slider { background: var(--accent); border-color: var(--accent); }
input:checked + .slider:before { transform: translateX(18px); background: white; }
/* Slider Input */
.slider-input { display: flex; align-items: center; gap: 12px; }
.slider-input input[type="range"] { flex: 1; accent-color: var(--accent); }
.slider-value { min-width: 48px; text-align: right; font-variant-numeric: tabular-nums; font-size: 0.875rem; color: var(--text-secondary); }
/* Select in modal */
.modal .form-select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%238e8e93' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 12px center; padding-right: 40px; }
/* Scrollbar */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
/* Mobile Responsive */
@media (max-width: 768px) {
.app { grid-template-columns: 1fr; grid-template-areas: "header" "main" "footer"; }
.sidebar { position: fixed; inset: 0; transform: translateX(-100%); transition: transform 250ms ease; box-shadow: var(--shadow-lg); width: 300px; max-width: 85vw; }
.sidebar.open { transform: translateX(0); }
.sidebar-close { display: flex; }
.sidebar-toggle { display: flex; }
.message { max-width: 92%; }
.footer { padding: 12px 16px; }
.input-wrapper { gap: 8px; }
.modal { width: 100%; max-width: none; height: 100%; max-height: 100%; border-radius: 0; }
.form-row { grid-template-columns: 1fr; }
}
@media (max-width: 480px) {
.header { padding: 10px 16px; }
.messages { padding: 16px; gap: 16px; }
.welcome h2 { font-size: 1.25rem; }
.modal-body { padding: 16px; }
.btn { padding: 12px 16px; }
}
/* Loading */
.typing-indicator { display: flex; gap: 4px; padding: 8px 12px; }
.typing-indicator span { width: 8px; height: 8px; background: var(--text-muted); border-radius: 50%; animation: bounce 1.4s infinite ease-in-out both; }
.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth_child(2) { animation-delay: -0.16s; }
@keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }
/* Markdown styling */
.message-content h1, .message-content h2, .message-content h3 { margin: 12px 0 8px; font-weight: 600; line-height: 1.3; }
.message-content h1 { font-size: 1.3rem; }
.message-content h2 { font-size: 1.15rem; }
.message-content h3 { font-size: 1.05rem; }
.message-content p { margin: 8px 0; }
.message-content ul, .message-content ol { margin: 8px 0; padding-left: 24px; }
.message-content li { margin: 4px 0; }
.message-content blockquote { border-left: 3px solid var(--accent); padding-left: 16px; margin: 12px 0; color: var(--text-secondary); font-style: italic; }
.message-content table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 0.8125rem; }
.message-content th, .message-content td { border: 1px solid var(--border-color); padding: 8px 12px; text-align: left; }
.message-content th { background: var(--bg-secondary); font-weight: 600; }
.message-content hr { border: none; border-top: 1px solid var(--border-color); margin: 16px 0; }
/* Toast */
.toast-container { position: fixed; bottom: 24px; right: 24px; z-index: 200; display: flex; flex-direction: column; gap: 8px; pointer-events: none; }
.toast { background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: var(--radius-md); padding: 12px 16px; box-shadow: var(--shadow-lg); display: flex; align-items: center; gap: 12px; min-width: 280px; max-width: 360px; animation: slideIn 300ms ease; pointer-events: auto; }
@keyframes slideIn { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: none; } }
.toast.success { border-left: 3px solid #16a34a; }
.toast.error { border-left: 3px solid #dc2626; }
.toast.info { border-left: 3px solid var(--accent); }
</style>
</head>
<body>
<div class="app" id="app">
<!-- Sidebar -->
<aside class="sidebar" id="sidebar" role="navigation" aria-label="側邊欄">
<div class="sidebar-header">
<h1 class="sidebar-title" data-i18n="sidebar.title">AI Agent Chat</h1>
<button class="sidebar-close" id="sidebarClose" aria-label="關閉側邊欄" type="button">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<div class="sidebar-tabs" role="tablist">
<button class="sidebar-tab active" role="tab" aria-selected="true" data-pane="providers" data-i18n="sidebar.providers" type="button">供應商</button>
<button class="sidebar-tab" role="tab" aria-selected="false" data-pane="history" data-i18n="sidebar.history" type="button">歷史記錄</button>
<button class="sidebar-tab" role="tab" aria-selected="false" data-pane="settings" data-i18n="sidebar.settings" type="button">設定</button>
</div>
<div class="sidebar-content">
<!-- Providers Pane -->
<div class="sidebar-pane active" id="pane-providers" role="tabpanel">
<div class="provider-list" id="providerList"></div>
<button class="btn btn-primary" style="width:100%;margin-top:16px;" id="addProviderBtn" data-i18n="providers.add" type="button">新增供應商</button>
</div>
<!-- History Pane -->
<div class="sidebar-pane" id="pane-history" role="tabpanel">
<div class="history-list" id="historyList"></div>
</div>
<!-- Settings Pane -->
<div class="sidebar-pane" id="pane-settings" role="tabpanel">
<div class="settings-section">
<div class="settings-section-title" data-i18n="settings.appearance">外觀</div>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label" data-i18n="settings.theme">主題</span>
<span class="setting-desc" data-i18n="settings.themeDesc">切換淺色/深色模式</span>
</div>
<label class="switch">
<input type="checkbox" id="themeToggle">
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label" data-i18n="settings.language">語言</span>
<span class="setting-desc" data-i18n="settings.languageDesc">介面顯示語言</span>
</div>
<select class="form-select" id="languageSelect" style="width:auto;min-width:140px;">
<option value="zh-TW">正體中文</option>
<option value="en">English</option>
</select>
</div>
</div>
<div class="settings-section">
<div class="settings-section-title" data-i18n="settings.data">資料管理</div>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label" data-i18n="settings.exportAll">導出所有對話</span>
<span class="setting-desc" data-i18n="settings.exportAllDesc">下載完整對話歷史為 JSON</span>
</div>
<button class="btn btn-secondary" id="exportAllBtn" data-i18n="settings.exportAllBtn" type="button">導出</button>
</div>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label" data-i18n="settings.importAll">導入對話</span>
<span class="setting-desc" data-i18n="settings.importAllDesc">從 JSON 檔案恢復歷史記錄</span>
</div>
<label class="btn btn-secondary" style="cursor:pointer;">
<input type="file" id="importFile" accept=".json" style="display:none;" data-i18n="settings.importAllBtn">導入
</label>
</div>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label" data-i18n="settings.clearAll">清空所有資料</span>
<span class="setting-desc" data-i18n="settings.clearAllDesc">刪除所有供應商、歷史與設定</span>
</div>
<button class="btn btn-danger" id="clearAllBtn" data-i18n="settings.clearAllBtn" type="button">清空</button>
</div>
</div>
<div class="settings-section">
<div class="settings-section-title" data-i18n="settings.about">關於</div>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label">版本</span>
<span class="setting-desc">v1.0.0 - Hugging Face Static Space</span>
</div>
</div>
</div>
</div>
</div>
</aside>
<!-- Header -->
<header class="header">
<div class="header-left">
<button class="sidebar-toggle" id="sidebarToggle" aria-label="開啟側邊欄" type="button">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
</button>
<h1 class="header-title" id="currentProviderName" data-i18n="header.selectProvider">選擇供應商</h1>
</div>
<div class="header-right">
<button class="btn btn-secondary" id="newChatBtn" style="padding:8px 12px;font-size:0.8125rem;" data-i18n="header.newChat" type="button">新對話</button>
</div>
</header>
<!-- Main Chat -->
<main class="main" role="main">
<div class="messages" id="messages" aria-live="polite">
<div class="welcome">
<h2 data-i18n="welcome.title">歡迎使用 AI Agent Chat</h2>
<p data-i18n="welcome.desc">請在側邊欄設定供應商並選擇模型,開始對話。</p>
</div>
</div>
</main>
<!-- Footer / Input -->
<footer class="footer">
<div class="input-wrapper">
<div class="input-area">
<textarea id="messageInput" placeholder="輸入訊息..." aria-label="輸入訊息" rows="1"></textarea>
<div class="input-actions">
<button class="btn btn-secondary" id="exportChatBtn" style="padding:6px 10px;font-size:0.75rem;" data-i18n="footer.exportMd" type="button">導出 MD</button>
</div>
</div>
<button class="send-btn" id="sendBtn" aria-label="發送訊息" disabled type="button">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
</button>
</div>
</footer>
</div>
<!-- Provider Modal -->
<div class="modal-overlay" id="providerModal" role="dialog" aria-modal="true" aria-labelledby="providerModalTitle">
<div class="modal">
<div class="modal-header">
<h2 class="modal-title" id="providerModalTitle" data-i18n="modal.providerTitle">新增供應商</h2>
<button class="modal-close" id="providerModalClose" aria-label="關閉" type="button">×</button>
</div>
<div class="modal-body">
<form id="providerForm" onsubmit="return false;">
<input type="hidden" id="providerId">
<div class="form-group">
<label class="form-label" for="providerName" data-i18n="modal.name">名稱</label>
<input type="text" class="form-input" id="providerName" placeholder="例如:My OpenAI" required>
</div>
<div class="form-group">
<label class="form-label" for="providerType" data-i18n="modal.type">類型</label>
<select class="form-select" id="providerType" required>
<option value="openai" data-i18n="modal.typeOpenAI">OpenAI 相容</option>
<option value="anthropic" data-i18n="modal.typeAnthropic">Anthropic</option>
<option value="gemini" data-i18n="modal.typeGemini">Google Gemini</option>
<option value="custom" data-i18n="modal.typeCustom">自訂 (OpenAI 格式)</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="providerBaseUrl" data-i18n="modal.baseUrl">Base URL</label>
<input type="url" class="form-input" id="providerBaseUrl" placeholder="https://api.openai.com/v1" required>
<span class="form-help" data-i18n="modal.baseUrlHelp">API 端點基礎網址,通常以 /v1 結尾</span>
</div>
<div class="form-group">
<label class="form-label" for="providerApiKey" data-i18n="modal.apiKey">API Key</label>
<input type="password" class="form-input" id="providerApiKey" placeholder="sk-..." required autocomplete="new-password">
<span class="form-help" data-i18n="modal.apiKeyHelp">儲存在本地瀏覽器,不會上傳至任何伺服器</span>
</div>
<div class="form-group">
<label class="form-label" for="providerModels" data-i18n="modal.models">可用模型 (每行一個)</label>
<textarea class="form-textarea" id="providerModels" placeholder="gpt-4o gpt-4o-mini gpt-3.5-turbo" required></textarea>
<span class="form-help" data-i18n="modal.modelsHelp">從官方文檔複製模型 ID,每行一個</span>
</div>
<div class="form-group">
<label class="form-label" for="providerDefaultModel" data-i18n="modal.defaultModel">預設模型</label>
<input type="text" class="form-input" id="providerDefaultModel" placeholder="gpt-4o-mini" required>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="providerModalCancel" data-i18n="modal.cancel" type="button">取消</button>
<button class="btn btn-primary" id="providerModalSave" data-i18n="modal.save" type="button">儲存</button>
</div>
</div>
</div>
<!-- Model/Params Modal -->
<div class="modal-overlay" id="paramsModal" role="dialog" aria-modal="true" aria-labelledby="paramsModalTitle">
<div class="modal">
<div class="modal-header">
<h2 class="modal-title" id="paramsModalTitle" data-i18n="modal.paramsTitle">模型參數設定</h2>
<button class="modal-close" id="paramsModalClose" aria-label="關閉" type="button">×</button>
</div>
<div class="modal-body">
<form id="paramsForm" onsubmit="return false;">
<div class="form-group">
<label class="form-label" for="paramModel" data-i18n="modal.model">模型</label>
<select class="form-select" id="paramModel" required></select>
</div>
<div class="form-group">
<label class="form-label" for="paramSystemPrompt" data-i18n="modal.systemPrompt">系統提示詞 (System Prompt)</label>
<textarea class="form-textarea" id="paramSystemPrompt" placeholder="你是一個有用的 AI 助理..."></textarea>
</div>
<div class="form-row">
<div class="form-group">
<label class="form-label" for="paramTemperature" data-i18n="modal.temperature">Temperature <span id="tempValue">0.7</span></label>
<input type="range" class="form-input" id="paramTemperature" min="0" max="2" step="0.1" value="0.7">
</div>
<div class="form-group">
<label class="form-label" for="paramTopP" data-i18n="modal.topP">Top P <span id="topPValue">1.0</span></label>
<input type="range" class="form-input" id="paramTopP" min="0" max="1" step="0.05" value="1">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label class="form-label" for="paramMaxTokens" data-i18n="modal.maxTokens">Max Tokens</label>
<input type="number" class="form-input" id="paramMaxTokens" min="1" max="128000" value="4096" step="1">
</div>
<div class="form-group">
<label class="form-label" for="paramTimeout" data-i18n="modal.timeout">超時 (秒)</label>
<input type="number" class="form-input" id="paramTimeout" min="10" max="300" value="60" step="5">
</div>
</div>
<div class="form-group">
<label class="form-label" for="paramPresencePenalty" data-i18n="modal.presencePenalty">Presence Penalty <span id="presenceValue">0</span></label>
<input type="range" class="form-input" id="paramPresencePenalty" min="-2" max="2" step="0.1" value="0">
</div>
<div class="form-group">
<label class="form-label" for="paramFrequencyPenalty" data-i18n="modal.frequencyPenalty">Frequency Penalty <span id="frequencyValue">0</span></label>
<input type="range" class="form-input" id="paramFrequencyPenalty" min="-2" max="2" step="0.1" value="0">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="paramsModalCancel" data-i18n="modal.cancel" type="button">取消</button>
<button class="btn btn-primary" id="paramsModalSave" data-i18n="modal.apply" type="button">套用</button>
</div>
</div>
</div>
<!-- Toast Container -->
<div class="toast-container" id="toastContainer"></div>
<script>
console.log('Script loading...');
window.onerror = function(msg, url, line) { console.error('Global Error: ' + msg + ' at ' + line); };
// ============ I18N ============
const I18N = {
'zh-TW': {
'sidebar.title': 'AI Agent Chat',
'sidebar.providers': '供應商',
'sidebar.history': '歷史記錄',
'sidebar.settings': '設定',
'providers.add': '新增供應商',
'providers.edit': '編輯',
'providers.delete': '刪除',
'providers.params': '參數',
'providers.empty': '暫無供應商,點擊上方按鈕新增',
'header.selectProvider': '選擇供應商',
'header.newChat': '新對話',
'welcome.title': '歡迎使用 AI Agent Chat',
'welcome.desc': '請在側邊欄設定供應商並選擇模型,開始對話。',
'footer.exportMd': '導出 MD',
'settings.appearance': '外觀',
'settings.theme': '主題',
'settings.themeDesc': '切換淺色/深色模式',
'settings.language': '語言',
'settings.languageDesc': '介面顯示語言',
'settings.data': '資料管理',
'settings.exportAll': '導出所有對話',
'settings.exportAllDesc': '下載完整對話歷史為 JSON',
'settings.exportAllBtn': '導出',
'settings.importAll': '導入對話',
'settings.importAllDesc': '從 JSON 檔案恢復歷史記錄',
'settings.importAllBtn': '導入',
'settings.clearAll': '清空所有資料',
'settings.clearAllDesc': '刪除所有供應商、歷史與設定',
'settings.clearAllBtn': '清空',
'settings.about': '關於',
'history.empty': '暫無對話歷史',
'history.untitled': '無標題對話',
'history.messages': '條訊息',
'history.export': '導出 MD',
'history.delete': '刪除',
'modal.providerTitle': '新增供應商',
'modal.editTitle': '編輯供應商',
'modal.name': '名稱',
'modal.type': '類型',
'modal.typeOpenAI': 'OpenAI 相容',
'modal.typeAnthropic': 'Anthropic',
'modal.typeGemini': 'Google Gemini',
'modal.typeCustom': '自訂 (OpenAI 格式)',
'modal.baseUrl': 'Base URL',
'modal.baseUrlHelp': 'API 端點基礎網址,通常以 /v1 結尾',
'modal.apiKey': 'API Key',
'modal.apiKeyHelp': '儲存在本地瀏覽器,不會上傳至任何伺服器',
'modal.models': '可用模型 (每行一個)',
'modal.modelsHelp': '從官方文檔複製模型 ID,每行一個',
'modal.defaultModel': '預設模型',
'modal.modelsRequired': '至少需要一個模型',
'modal.cancel': '取消',
'modal.save': '儲存',
'modal.confirmDelete': '確定要刪除此供應商嗎?',
'modal.confirmDeleteChat': '確定要刪除此對話嗎?',
'modal.confirmClearAll': '確定要清空所有資料嗎?此操作無法復原。',
'modal.paramsTitle': '模型參數設定',
'modal.model': '模型',
'modal.systemPrompt': '系統提示詞 (System Prompt)',
'modal.temperature': 'Temperature',
'modal.topP': 'Top P',
'modal.maxTokens': 'Max Tokens',
'modal.timeout': '超時 (秒)',
'modal.presencePenalty': 'Presence Penalty',
'modal.frequencyPenalty': 'Frequency Penalty',
'modal.apply': '套用',
'message.copy': '複製',
'message.regenerate': '重生',
'toast.streaming': '正在生成中,請先停止',
'toast.copied': '已複製',
'toast.exported': '已導出 Markdown',
'toast.exportedAll': '已導出所有資料',
'toast.imported': '導入成功',
'toast.importError': '導入失敗:無效的檔案',
'toast.saved': '供應商已儲存',
'toast.deleted': '已刪除',
'toast.cleared': '已清空所有資料',
'toast.paramsSaved': '參數已套用',
'toast.timeout': '請求超時',
'toast.error': '發生錯誤',
},
'en': {
'sidebar.title': 'AI Agent Chat',
'sidebar.providers': 'Providers',
'sidebar.history': 'History',
'sidebar.settings': 'Settings',
'providers.add': 'Add Provider',
'providers.edit': 'Edit',
'providers.delete': 'Delete',
'providers.params': 'Params',
'providers.empty': 'No providers yet, click above to add',
'header.selectProvider': 'Select Provider',
'header.newChat': 'New Chat',
'welcome.title': 'Welcome to AI Agent Chat',
'welcome.desc': 'Configure a provider in the sidebar and select a model to start chatting.',
'footer.exportMd': 'Export MD',
'settings.appearance': 'Appearance',
'settings.theme': 'Theme',
'settings.themeDesc': 'Toggle light/dark mode',
'settings.language': 'Language',
'settings.languageDesc': 'Interface display language',
'settings.data': 'Data Management',
'settings.exportAll': 'Export All Chats',
'settings.exportAllDesc': 'Download complete chat history as JSON',
'settings.exportAllBtn': 'Export',
'settings.importAll': 'Import Chats',
'settings.importAllDesc': 'Restore history from JSON file',
'settings.importAllBtn': 'Import',
'settings.clearAll': 'Clear All Data',
'settings.clearAllDesc': 'Delete all providers, history and settings',
'settings.clearAllBtn': 'Clear',
'settings.about': 'About',
'history.empty': 'No chat history yet',
'history.untitled': 'Untitled Chat',
'history.messages': 'messages',
'history.export': 'Export MD',
'history.delete': 'Delete',
'modal.providerTitle': 'Add Provider',
'modal.editTitle': 'Edit Provider',
'modal.name': 'Name',
'modal.type': 'Type',
'modal.typeOpenAI': 'OpenAI Compatible',
'modal.typeAnthropic': 'Anthropic',
'modal.typeGemini': 'Google Gemini',
'modal.typeCustom': 'Custom (OpenAI Format)',
'modal.baseUrl': 'Base URL',
'modal.baseUrlHelp': 'API base endpoint, usually ends with /v1',
'modal.apiKey': 'API Key',
'modal.apiKeyHelp': 'Stored locally in browser, never sent to any server',
'modal.models': 'Models (one per line)',
'modal.modelsHelp': 'Copy model IDs from official docs, one per line',
'modal.defaultModel': 'Default Model',
'modal.modelsRequired': 'At least one model required',
'modal.cancel': 'Cancel',
'modal.save': 'Save',
'modal.confirmDelete': 'Delete this provider?',
'modal.confirmDeleteChat': 'Delete this chat?',
'modal.confirmClearAll': 'Clear all data? This cannot be undone.',
'modal.paramsTitle': 'Model Parameters',
'modal.model': 'Model',
'modal.systemPrompt': 'System Prompt',
'modal.temperature': 'Temperature',
'modal.topP': 'Top P',
'modal.maxTokens': 'Max Tokens',
'modal.timeout': 'Timeout (seconds)',
'modal.presencePenalty': 'Presence Penalty',
'modal.frequencyPenalty': 'Frequency Penalty',
'modal.apply': 'Apply',
'message.copy': 'Copy',
'message.regenerate': 'Regenerate',
'toast.streaming': 'Generation in progress, please stop first',
'toast.copied': 'Copied',
'toast.exported': 'Markdown exported',
'toast.exportedAll': 'All data exported',
'toast.imported': 'Imported successfully',
'toast.importError': 'Import failed: invalid file',
'toast.saved': 'Provider saved',
'toast.deleted': 'Deleted',
'toast.cleared': 'All data cleared',
'toast.paramsSaved': 'Parameters applied',
'toast.timeout': '請求超時',
'toast.error': 'Error occurred',
}
};
// ============ State ============
let state = {
providers: [],
currentProviderId: null,
currentChatId: null,
chats: [],
settings: { theme: 'light', language: 'zh-TW' },
params: {
model: '',
systemPrompt: '',
temperature: 0.7,
topP: 1,
maxTokens: 4096,
timeout: 60,
presencePenalty: 0,
frequencyPenalty: 0
},
isStreaming: false,
abortController: null
};
// ============ DOM Elements ============
const els = {
app: document.getElementById('app'),
sidebar: document.getElementById('sidebar'),
sidebarToggle: document.getElementById('sidebarToggle'),
sidebarClose: document.getElementById('sidebarClose'),
sidebarTabs: document.querySelectorAll('.sidebar-tab'),
panes: document.querySelectorAll('.sidebar-pane'),
providerList: document.getElementById('providerList'),
addProviderBtn: document.getElementById('addProviderBtn'),
historyList: document.getElementById('historyList'),
currentProviderName: document.getElementById('currentProviderName'),
newChatBtn: document.getElementById('newChatBtn'),
messages: document.getElementById('messages'),
messageInput: document.getElementById('messageInput'),
sendBtn: document.getElementById('sendBtn'),
exportChatBtn: document.getElementById('exportChatBtn'),
themeToggle: document.getElementById('themeToggle'),
languageSelect: document.getElementById('languageSelect'),
exportAllBtn: document.getElementById('exportAllBtn'),
importFile: document.getElementById('importFile'),
clearAllBtn: document.getElementById('clearAllBtn'),
providerModal: document.getElementById('providerModal'),
providerModalClose: document.getElementById('providerModalClose'),
providerModalCancel: document.getElementById('providerModalCancel'),
providerModalSave: document.getElementById('providerModalSave'),
providerForm: document.getElementById('providerForm'),
providerId: document.getElementById('providerId'),
providerName: document.getElementById('providerName'),
providerType: document.getElementById('providerType'),
providerBaseUrl: document.getElementById('providerBaseUrl'),
providerApiKey: document.getElementById('providerApiKey'),
providerModels: document.getElementById('providerModels'),
providerDefaultModel: document.getElementById('providerDefaultModel'),
paramsModal: document.getElementById('paramsModal'),
paramsModalClose: document.getElementById('paramsModalClose'),
paramsModalCancel: document.getElementById('paramsModalCancel'),
paramsModalSave: document.getElementById('paramsModalSave'),
paramsForm: document.getElementById('paramsForm'),
paramModel: document.getElementById('paramModel'),
paramSystemPrompt: document.getElementById('paramSystemPrompt'),
paramTemperature: document.getElementById('paramTemperature'),
paramTopP: document.getElementById('paramTopP'),
paramMaxTokens: document.getElementById('paramMaxTokens'),
paramTimeout: document.getElementById('paramTimeout'),
paramPresencePenalty: document.getElementById('paramPresencePenalty'),
paramFrequencyPenalty: document.getElementById('paramFrequencyPenalty'),
tempValue: document.getElementById('tempValue'),
topPValue: document.getElementById('topPValue'),
presenceValue: document.getElementById('presenceValue'),
frequencyValue: document.getElementById('frequencyValue'),
toastContainer: document.getElementById('toastContainer'),
};
// ============ Utils ============
function generateId() { return Date.now().toString(36) + Math.random().toString(36).substr(2, 9); }
function t(key) { return I18N[state.settings.language]?.[key] || I18N['zh-TW'][key] || key; }
function applyI18n() {
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.dataset.i18n;
const text = t(key);
if (el.tagName === 'INPUT' && (el.type === 'submit' || el.type === 'button')) {
el.value = text;
} else if (el.tagName === 'OPTION') {
el.textContent = text;
} else {
el.textContent = text;
}
});
document.documentElement.lang = state.settings.language;
// Update placeholders
if (els.messageInput) els.messageInput.placeholder = state.settings.language === 'zh-TW' ? '輸入訊息...' : 'Type a message...';
if (els.providerName) els.providerName.placeholder = state.settings.language === 'zh-TW' ? '例如:My OpenAI' : 'e.g. My OpenAI';
if (els.providerBaseUrl) els.providerBaseUrl.placeholder = 'https://api.openai.com/v1';
if (els.providerApiKey) els.providerApiKey.placeholder = 'sk-...';
if (els.providerModels) els.providerModels.placeholder = 'gpt-4o\ngpt-4o-mini\ngpt-3.5-turbo';
if (els.providerDefaultModel) els.providerDefaultModel.placeholder = 'gpt-4o-mini';
if (els.paramSystemPrompt) els.paramSystemPrompt.placeholder = t('modal.systemPrompt') + '...';
}
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.textContent = message;
els.toastContainer.appendChild(toast);
setTimeout(() => { toast.style.animation = 'slideIn 300ms ease reverse'; setTimeout(() => toast.remove(), 300); }, 3000);
}
function escapeHtml(text) {
const map = {'&':'&','<':'<','>':'>','"':'"',"'":"'"}; return String(text).replace(/[&<>"']/g, c => map[c]);
}
function saveState() {
try {
localStorage.setItem('aiAgentState', JSON.stringify({
providers: state.providers,
chats: state.chats,
settings: state.settings,
params: state.params,
currentProviderId: state.currentProviderId,
currentChatId: state.currentChatId
}));
} catch (e) { console.error('saveState failed', e); showToast(t('toast.error'), 'error'); }
}
function loadState() {
try {
const data = JSON.parse(localStorage.getItem('aiAgentState') || '{}');
state.providers = data.providers || [];
state.chats = data.chats || [];
state.settings = { ...state.settings, ...data.settings };
state.params = { ...state.params, ...data.params };
state.currentProviderId = data.currentProviderId || null;
state.currentChatId = data.currentChatId || null;
console.log('State loaded:', { providers: state.providers.length, chats: state.chats.length });
} catch (e) { console.error('loadState failed', e); }
}
// ============ Render ============
function renderProviders() {
if (!els.providerList) return;
els.providerList.innerHTML = '';
if (state.providers.length === 0) {
els.providerList.innerHTML = `<div class="empty-state" data-i18n="providers.empty">${t('providers.empty')}</div>`;
applyI18n();
return;
}
state.providers.forEach(p => {
const div = document.createElement('div');
div.className = `provider-item${p.id === state.currentProviderId ? ' active' : ''}`;
div.innerHTML = `
<div class="provider-info">
<span class="provider-name">${escapeHtml(p.name)}</span>
<span class="provider-base">${escapeHtml(p.baseUrl)}</span>
</div>
<div class="provider-actions">
<button class="btn btn-secondary" data-action="params" data-id="${p.id}" style="padding:6px 10px;font-size:0.75rem;" type="button" data-i18n="providers.params">${t('providers.params')}</button>
<button class="btn btn-secondary" data-action="edit" data-id="${p.id}" style="padding:6px 10px;font-size:0.75rem;" type="button" data-i18n="providers.edit">${t('providers.edit')}</button>
<button class="btn btn-danger" data-action="delete" data-id="${p.id}" style="padding:6px 10px;font-size:0.75rem;" type="button" data-i18n="providers.delete">${t('providers.delete')}</button>
</div>
`;
div.querySelector('[data-action="params"]').addEventListener('click', (e) => { e.stopPropagation(); openParamsModal(p.id); });
div.querySelector('[data-action="edit"]').addEventListener('click', (e) => { e.stopPropagation(); openProviderModal(p.id); });
div.querySelector('[data-action="delete"]').addEventListener('click', (e) => { e.stopPropagation(); deleteProvider(p.id); });
div.addEventListener('click', () => selectProvider(p.id));
els.providerList.appendChild(div);
});
applyI18n();
updateHeader();
}
function renderHistory() {
if (!els.historyList) return;
els.historyList.innerHTML = '';
if (state.chats.length === 0) {
els.historyList.innerHTML = `<div class="empty-state" data-i18n="history.empty">${t('history.empty')}</div>`;
applyI18n();
return;
}
[...state.chats].reverse().forEach(chat => {
const div = document.createElement('div');
div.className = `history-item${chat.id === state.currentChatId ? ' active' : ''}`;
const msgCount = chat.messages?.length || 0;
const updated = new Date(chat.updatedAt).toLocaleString(state.settings.language === 'zh-TW' ? 'zh-TW' : 'en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
div.innerHTML = `
<span class="history-title">${escapeHtml(chat.title || t('history.untitled'))}</span>
<div class="history-meta">
<span>${msgCount} ${t('history.messages')}</span>
<span>${updated}</span>
</div>
<div class="history-actions">
<button class="btn btn-secondary" data-action="export" data-id="${chat.id}" style="padding:4px 8px;font-size:0.7rem;" type="button" data-i18n="history.export">${t('history.export')}</button>
<button class="btn btn-danger" data-action="delete" data-id="${chat.id}" style="padding:4px 8px;font-size:0.7rem;" type="button" data-i18n="history.delete">${t('history.delete')}</button>
</div>
`;
div.addEventListener('click', (e) => { if (!e.target.closest('button')) loadChat(chat.id); });
div.querySelector('[data-action="export"]').addEventListener('click', (e) => { e.stopPropagation(); exportChatMarkdown(chat); });
div.querySelector('[data-action="delete"]').addEventListener('click', (e) => { e.stopPropagation(); deleteChat(chat.id); });
els.historyList.appendChild(div);
});
applyI18n();
}
function renderMarkdown(text) {
let html = escapeHtml(text);
html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => `<pre><code class="language-${lang}">${code}</code></pre>`);
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>');
html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
html = html.replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>');
html = html.replace(/^\- (.*$)/gim, '<li>$1</li>');
html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
html = html.replace(/\n\n/g, '</p><p>');
html = '<p>' + html + '</p>';
html = html.replace(/<p><\/p>/g, '');
html = html.replace(/<p>(<pre><code[\s\S]*?<\/code><\/pre>)<\/p>/g, '$1');
html = html.replace(/<p>(<h[1-3]>.*<\/h[1-3]>)<\/p>/g, '$1');
html = html.replace(/<p>(<blockquote>.*<\/blockquote>)<\/p>/g, '$1');
html = html.replace(/<p>(<ul>.*<\/ul>)<\/p>/g, '$1');
return html;
}
function renderMessages() {
if (!els.messages) return;
const chat = state.chats.find(c => c.id === state.currentChatId);
els.messages.innerHTML = '';
if (!chat) {
els.messages.innerHTML = `<div class="welcome"><h2 data-i18n="welcome.title">${t('welcome.title')}</h2><p data-i18n="welcome.desc">${t('welcome.desc')}</p></div>`;
applyI18n();
return;
}
if (chat.messages.length === 0) {
els.messages.innerHTML = `<div class="welcome"><h2 data-i18n="welcome.title">${t('welcome.title')}</h2><p data-i18n="welcome.desc">${t('welcome.desc')}</p></div>`;
applyI18n();
return;
}
chat.messages.forEach((msg, idx) => {
const div = document.createElement('div');
div.className = `message ${msg.role}`;
const avatar = msg.role === 'user' ? 'U' : 'AI';
const content = renderMarkdown(msg.content);
div.innerHTML = `
<div class="message-avatar">${avatar}</div>
<div class="message-bubble">
<div class="message-content">${content}</div>
<div class="message-meta">
<span>${new Date(msg.timestamp).toLocaleTimeString()}</span>
<div class="message-actions">
<button class="message-action" data-action="copy" data-idx="${idx}" type="button" data-i18n="message.copy">${t('message.copy')}</button>
<button class="message-action" data-action="regenerate" data-idx="${idx}" type="button" data-i18n="message.regenerate">${t('message.regenerate')}</button>
</div>
</div>
</div>
`;
div.querySelector('[data-action="copy"]').addEventListener('click', () => copyMessage(msg.content));
div.querySelector('[data-action="regenerate"]').addEventListener('click', () => regenerateMessage(idx));
els.messages.appendChild(div);
});
scrollToBottom();
applyI18n();
}
function updateHeader() {
if (!els.currentProviderName) return;
const provider = state.providers.find(p => p.id === state.currentProviderId);
els.currentProviderName.textContent = provider ? provider.name : t('header.selectProvider');
if (els.newChatBtn) els.newChatBtn.style.display = state.currentProviderId ? 'inline-flex' : 'none';
if (els.messageInput) els.messageInput.disabled = !state.currentProviderId;
updateSendButton();
if (els.exportChatBtn) els.exportChatBtn.style.display = state.currentChatId ? 'inline-flex' : 'none';
// Update params modal model dropdown
if (provider && els.paramModel) {
els.paramModel.innerHTML = provider.models.map(m => `<option value="${escapeHtml(m)}">${escapeHtml(m)}</option>`).join('');
els.paramModel.value = state.params.model || provider.defaultModel;
}
}
function scrollToBottom() { if (els.messages) els.messages.scrollTop = els.messages.scrollHeight; }
// ============ Provider Management ============
function openProviderModal(providerId = null) {
if (!els.providerForm) return;
els.providerForm.reset();
els.providerId.value = '';
const titleEl = document.getElementById('providerModalTitle');
if (titleEl) titleEl.textContent = providerId ? t('modal.editTitle') : t('modal.providerTitle');
if (providerId) {
const p = state.providers.find(x => x.id === providerId);
if (p) {
els.providerId.value = p.id;
els.providerName.value = p.name;
els.providerType.value = p.type;
els.providerBaseUrl.value = p.baseUrl;
els.providerApiKey.value = p.apiKey;
els.providerModels.value = p.models.join('\n');
els.providerDefaultModel.value = p.defaultModel;
}
} else {
els.providerType.value = 'openai';
els.providerBaseUrl.value = 'https://api.openai.com/v1';
}
applyI18n();
if (els.providerModal) els.providerModal.classList.add('active');
}
function closeProviderModal() { if (els.providerModal) els.providerModal.classList.remove('active'); }
function saveProvider() {
const id = els.providerId.value || generateId();
const models = els.providerModels.value.split('\n').map(m => m.trim()).filter(Boolean);
if (models.length === 0) { showToast(t('modal.modelsRequired'), 'error'); return; }
const provider = {
id,
name: els.providerName.value.trim(),
type: els.providerType.value,
baseUrl: els.providerBaseUrl.value.trim().replace(/\/+$/, ''),
apiKey: els.providerApiKey.value.trim(),
models,
defaultModel: els.providerDefaultModel.value.trim() || models[0],
createdAt: Date.now()
};
const idx = state.providers.findIndex(p => p.id === id);
if (idx >= 0) state.providers[idx] = provider; else state.providers.push(provider);
if (!state.currentProviderId) selectProvider(id);
saveState();
renderProviders();
closeProviderModal();
showToast(t('modal.saved'), 'success');
}
function deleteProvider(id) {
if (!confirm(t('modal.confirmDelete'))) return;
state.providers = state.providers.filter(p => p.id !== id);
if (state.currentProviderId === id) {
state.currentProviderId = null;
state.currentChatId = null;
state.params.model = '';
}
saveState();
renderProviders();
renderHistory();
renderMessages();
showToast(t('modal.deleted'), 'success');
}
function selectProvider(id) {
state.currentProviderId = id;
state.currentChatId = null;
const provider = state.providers.find(p => p.id === id);
if (provider) {
state.params.model = provider.defaultModel;
state.params.systemPrompt = '';
state.params.temperature = 0.7;
state.params.topP = 1;
state.params.maxTokens = 4096;
state.params.timeout = 60;
state.params.presencePenalty = 0;
state.params.frequencyPenalty = 0;
}
saveState();
renderProviders();
renderHistory();
renderMessages();
updateHeader();
closeSidebar();
}
// ============ Chat Management ============
function newChat() {
if (!state.currentProviderId) return;
const chat = {
id: generateId(),
providerId: state.currentProviderId,
title: '',
messages: [],
createdAt: Date.now(),
updatedAt: Date.now()
};
state.chats.unshift(chat);
state.currentChatId = chat.id;
saveState();
renderHistory();
renderMessages();
updateHeader();
closeSidebar();
if (els.messageInput) els.messageInput.focus();
}
function loadChat(id) {
state.currentChatId = id;
saveState();
renderHistory();
renderMessages();
updateHeader();
closeSidebar();
}
function deleteChat(id) {
if (!confirm(t('modal.confirmDeleteChat'))) return;
state.chats = state.chats.filter(c => c.id !== id);
if (state.currentChatId === id) state.currentChatId = null;
saveState();
renderHistory();
renderMessages();
showToast(t('modal.deleted'), 'success');
}
function addMessage(role, content) {
if (!state.currentChatId) return;
const chat = state.chats.find(c => c.id === state.currentChatId);
if (!chat) return;
chat.messages.push({ role, content, timestamp: Date.now() });
chat.updatedAt = Date.now();
if (!chat.title && role === 'user') chat.title = content.slice(0, 50);
saveState();
renderMessages();
renderHistory();
}
// Target of the in-progress stream: only its bubble is updated per chunk (no full re-render)
let streamTarget = null; // { chatId, el }
let lastSaveAt = 0;
function updateLastMessage(content) {
if (!state.currentChatId) return;
const chat = state.chats.find(c => c.id === state.currentChatId);
if (!chat || chat.messages.length === 0) return;
chat.messages[chat.messages.length - 1].content = content;
chat.updatedAt = Date.now();
if (Date.now() - lastSaveAt > 400) { saveState(); lastSaveAt = Date.now(); }
if (streamTarget && streamTarget.chatId === chat.id && streamTarget.el && streamTarget.el.isConnected) {
// In-place update: only the streaming bubble repaints, nothing else touches
streamTarget.el.innerHTML = renderMarkdown(content);
scrollToBottom();
} else {
renderMessages();
}
}
function regenerateMessage(idx) {
if (!state.currentChatId) return;
if (state.isStreaming) { showToast(t('toast.streaming'), 'info'); return; }
const chat = state.chats.find(c => c.id === state.currentChatId);
if (!chat) return;
// Remove this and all subsequent messages
chat.messages = chat.messages.slice(0, idx);
// Find the last user message to resend
const lastUserMsg = [...chat.messages].reverse().find(m => m.role === 'user');
if (lastUserMsg) sendMessage(lastUserMsg.content, true);
saveState();
renderMessages();
}
function copyMessage(text) {
navigator.clipboard.writeText(text).then(() => showToast(t('toast.copied'), 'success')).catch(() => showToast('複製失敗', 'error'));
}
// ============ Export ============
function exportChatMarkdown(chat) {
const provider = state.providers.find(p => p.id === chat.providerId);
let md = `# ${escapeHtml(chat.title || t('history.untitled'))}\n\n`;
md += `**Provider:** ${provider?.name || 'Unknown'} \n`;
md += `**Model:** ${state.params.model || 'N/A'} \n`;
md += `**Date:** ${new Date(chat.createdAt).toLocaleString()} \n\n---\n\n`;
chat.messages.forEach(msg => {
md += `## ${msg.role === 'user' ? '👤 User' : '🤖 Assistant'}\n\n${msg.content}\n\n`;
});
downloadFile(`${(chat.title || 'chat').replace(/[\\/:*?"<>|]/g, '_')}.md`, md);
showToast(t('toast.exported'), 'success');
}
function exportAllChats() {
const data = { providers: state.providers, chats: state.chats, settings: state.settings, params: state.params, exportedAt: Date.now() };
downloadFile(`ai-agent-chat-backup-${new Date().toISOString().slice(0,10)}.json`, JSON.stringify(data, null, 2));
showToast(t('toast.exportedAll'), 'success');
}
function importChats(file) {
const reader = new FileReader();
reader.onload = e => {
try {
const data = JSON.parse(e.target.result);
if (data.providers) state.providers = data.providers;
if (data.chats) state.chats = data.chats;
if (data.settings) state.settings = { ...state.settings, ...data.settings };
if (data.params) state.params = { ...state.params, ...data.params };
state.currentProviderId = data.currentProviderId || state.providers[0]?.id || null;
state.currentChatId = data.currentChatId || null;
saveState();
applySettings();
renderProviders();
renderHistory();
renderMessages();
updateHeader();
showToast(t('toast.imported'), 'success');
} catch (err) { showToast(t('toast.importError'), 'error'); }
};
reader.readAsText(file);
}
function downloadFile(filename, content) {
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = filename; a.click();
URL.revokeObjectURL(url);
}
// ============ API Calls ============
async function sendMessage(content, isRegenerate = false) {
if (!state.currentProviderId) return;
if (!isRegenerate && state.isStreaming) return; // guard: never double-send
const provider = state.providers.find(p => p.id === state.currentProviderId);
if (!provider) return;
// Auto-create a new chat if none is active, so sending always works
let chat = state.chats.find(c => c.id === state.currentChatId);
if (!chat) {
if (isRegenerate) return;
newChat();
chat = state.chats.find(c => c.id === state.currentChatId);
if (!chat) return;
}
if (!isRegenerate) addMessage('user', content);
if (els.messageInput) { els.messageInput.value = ''; els.messageInput.style.height = 'auto'; }
updateSendButton();
chat.messages.push({ role: 'assistant', content: '', timestamp: Date.now() });
saveState();
renderMessages();
// Target the just-created assistant bubble: per-chunk updates only repaint this element
const lastBubble = els.messages ? els.messages.querySelector('.message:last-child .message-content') : null;
streamTarget = lastBubble ? { chatId: chat.id, el: lastBubble } : null;
state.isStreaming = true;
updateSendButton();
const messages = chat.messages.slice(0, -1).map(m => ({ role: m.role, content: m.content }));
if (state.params.systemPrompt) messages.unshift({ role: 'system', content: state.params.systemPrompt });
const payload = {
model: state.params.model || provider.defaultModel,
messages,
temperature: state.params.temperature,
top_p: state.params.topP,
max_tokens: state.params.maxTokens,
presence_penalty: state.params.presencePenalty,
frequency_penalty: state.params.frequencyPenalty,
stream: true
};
const url = `${provider.baseUrl}/chat/completions`;
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${provider.apiKey}`
};
let fullContent = '';
els.abortController = new AbortController();
try {
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(payload),
signal: els.abortController.signal
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error?.message || `HTTP ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(l => l.trim());
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const delta = parsed.choices?.[0]?.delta?.content || '';
if (delta) {
fullContent += delta;
updateLastMessage(fullContent);
}
} catch {}
}
}
}
} catch (err) {
if (err.name === 'AbortError') { updateLastMessage(fullContent + '\n\n> **Request canceled**'); showToast('請求已取消', 'info'); } else {
updateLastMessage(fullContent + `\n\n> **Error:** ${escapeHtml(err.message)}`);
showToast(err.message, 'error');
}
} finally {
streamTarget = null;
state.isStreaming = false;
updateSendButton();
saveState();
renderMessages(); // final pass with actions & correct timestamps
// Update chat title if first message
const c = state.chats.find(x => x.id === state.currentChatId);
if (c && !c.title && c.messages.length >= 2) {
c.title = c.messages[0].content.slice(0, 50);
saveState();
renderHistory();
}
}
}
function stopGeneration() {
if (els.abortController) els.abortController.abort();
state.isStreaming = false;
updateSendButton();
}
function updateSendButton() {
const hasText = els.messageInput && els.messageInput.value.trim().length > 0;
// While streaming the button acts as STOP, so it must stay enabled
if (els.sendBtn) els.sendBtn.disabled = state.isStreaming ? false : (!state.currentProviderId || !hasText);
if (state.isStreaming && els.sendBtn) {
els.sendBtn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="6" y="4" width="4" height="16"></rect><rect x="14" y="4" width="4" height="16"></rect></svg>';
} else if (els.sendBtn) {
els.sendBtn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
}
}
// ============ Params Modal ============
function openParamsModal(providerId) {
const provider = state.providers.find(p => p.id === providerId);
if (!provider) return;
if (els.paramModel) els.paramModel.value = state.params.model || provider.defaultModel;
if (els.paramSystemPrompt) els.paramSystemPrompt.value = state.params.systemPrompt;
if (els.paramTemperature) { els.paramTemperature.value = state.params.temperature; if (els.tempValue) els.tempValue.textContent = state.params.temperature.toFixed(1); }
if (els.paramTopP) { els.paramTopP.value = state.params.topP; if (els.topPValue) els.topPValue.textContent = state.params.topP.toFixed(2); }
if (els.paramMaxTokens) els.paramMaxTokens.value = state.params.maxTokens;
if (els.paramTimeout) els.paramTimeout.value = state.params.timeout;
if (els.paramPresencePenalty) { els.paramPresencePenalty.value = state.params.presencePenalty; if (els.presenceValue) els.presenceValue.textContent = state.params.presencePenalty.toFixed(1); }
if (els.paramFrequencyPenalty) { els.paramFrequencyPenalty.value = state.params.frequencyPenalty; if (els.frequencyValue) els.frequencyValue.textContent = state.params.frequencyPenalty.toFixed(1); }
applyI18n();
if (els.paramsModal) els.paramsModal.classList.add('active');
}
function closeParamsModal() { if (els.paramsModal) els.paramsModal.classList.remove('active'); }
function saveParams() {
if (els.paramModel) state.params.model = els.paramModel.value;
if (els.paramSystemPrompt) state.params.systemPrompt = els.paramSystemPrompt.value;
if (els.paramTemperature) state.params.temperature = parseFloat(els.paramTemperature.value);
if (els.paramTopP) state.params.topP = parseFloat(els.paramTopP.value);
if (els.paramMaxTokens) state.params.maxTokens = parseInt(els.paramMaxTokens.value) || 4096;
if (els.paramTimeout) state.params.timeout = parseInt(els.paramTimeout.value) || 60;
if (els.paramPresencePenalty) state.params.presencePenalty = parseFloat(els.paramPresencePenalty.value);
if (els.paramFrequencyPenalty) state.params.frequencyPenalty = parseFloat(els.paramFrequencyPenalty.value);
saveState();
closeParamsModal();
showToast(t('toast.paramsSaved'), 'success');
}
// ============ Settings ============
function applySettings() {
document.documentElement.setAttribute('data-theme', state.settings.theme);
if (els.themeToggle) els.themeToggle.checked = state.settings.theme === 'dark';
if (els.languageSelect) els.languageSelect.value = state.settings.language;
applyI18n();
}
function toggleTheme() {
state.settings.theme = state.settings.theme === 'dark' ? 'light' : 'dark';
applySettings();
saveState();
}
function changeLanguage(lang) {
state.settings.language = lang;
applySettings();
saveState();
renderProviders();
renderHistory();
renderMessages();
}
function clearAllData() {
if (!confirm(t('modal.confirmClearAll'))) return;
localStorage.removeItem('aiAgentState');
state = {
providers: [], currentProviderId: null, currentChatId: null, chats: [],
settings: { theme: 'light', language: 'zh-TW' },
params: { model: '', systemPrompt: '', temperature: 0.7, topP: 1, maxTokens: 4096, timeout: 60, presencePenalty: 0, frequencyPenalty: 0 },
isStreaming: false, abortController: null
};
applySettings();
renderProviders();
renderHistory();
renderMessages();
updateHeader();
showToast(t('toast.cleared'), 'success');
}
// ============ Sidebar ============
function switchPane(paneName) {
els.sidebarTabs.forEach(tab => {
const active = tab.dataset.pane === paneName;
tab.classList.toggle('active', active);
tab.setAttribute('aria-selected', active);
});
els.panes.forEach(pane => pane.classList.toggle('active', pane.id === `pane-${paneName}`));
}
function openSidebar() { if (els.sidebar) els.sidebar.classList.add('open'); }
function closeSidebar() { if (els.sidebar) els.sidebar.classList.remove('open'); }
// ============ Event Listeners ============
function initEvents() {
// Sidebar tabs
els.sidebarTabs.forEach(tab => tab.addEventListener('click', () => switchPane(tab.dataset.pane)));
if (els.sidebarToggle) els.sidebarToggle.addEventListener('click', openSidebar);
if (els.sidebarClose) els.sidebarClose.addEventListener('click', closeSidebar);
// Click outside sidebar to close on mobile
document.addEventListener('click', e => {
if (window.innerWidth <= 768 && els.sidebar && !els.sidebar.contains(e.target) && els.sidebarToggle && !els.sidebarToggle.contains(e.target)) closeSidebar();
});
// Provider modal
if (els.addProviderBtn) els.addProviderBtn.addEventListener('click', () => openProviderModal());
if (els.providerModalClose) els.providerModalClose.addEventListener('click', closeProviderModal);
if (els.providerModalCancel) els.providerModalCancel.addEventListener('click', closeProviderModal);
if (els.providerModalSave) els.providerModalSave.addEventListener('click', saveProvider);
if (els.providerModal) els.providerModal.addEventListener('click', e => { if (e.target === els.providerModal) closeProviderModal(); });
// Params modal
if (els.paramsModalClose) els.paramsModalClose.addEventListener('click', closeParamsModal);
if (els.paramsModalCancel) els.paramsModalCancel.addEventListener('click', closeParamsModal);
if (els.paramsModalSave) els.paramsModalSave.addEventListener('click', saveParams);
if (els.paramsModal) els.paramsModal.addEventListener('click', e => { if (e.target === els.paramsModal) closeParamsModal(); });
// Slider value updates
if (els.paramTemperature) els.paramTemperature.addEventListener('input', e => { if (els.tempValue) els.tempValue.textContent = parseFloat(e.target.value).toFixed(1); });
if (els.paramTopP) els.paramTopP.addEventListener('input', e => { if (els.topPValue) els.topPValue.textContent = parseFloat(e.target.value).toFixed(2); });
if (els.paramPresencePenalty) els.paramPresencePenalty.addEventListener('input', e => { if (els.presenceValue) els.presenceValue.textContent = parseFloat(e.target.value).toFixed(1); });
if (els.paramFrequencyPenalty) els.paramFrequencyPenalty.addEventListener('input', e => { if (els.frequencyValue) els.frequencyValue.textContent = parseFloat(e.target.value).toFixed(1); });
// Chat
if (els.newChatBtn) els.newChatBtn.addEventListener('click', newChat);
if (els.messageInput) {
els.messageInput.addEventListener('input', () => {
els.messageInput.style.height = 'auto';
els.messageInput.style.height = Math.min(els.messageInput.scrollHeight, 200) + 'px';
updateSendButton();
});
els.messageInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
const text = els.messageInput.value.trim();
if (text && !els.sendBtn?.disabled) sendMessage(text);
}
});
}
if (els.sendBtn) els.sendBtn.addEventListener('click', () => {
if (state.isStreaming) { stopGeneration(); return; }
if (els.messageInput) { const text = els.messageInput.value.trim(); if (text) sendMessage(text); }
});
if (els.exportChatBtn) els.exportChatBtn.addEventListener('click', () => {
const chat = state.chats.find(c => c.id === state.currentChatId);
if (chat) exportChatMarkdown(chat);
});
// Settings
if (els.themeToggle) els.themeToggle.addEventListener('change', toggleTheme);
if (els.languageSelect) els.languageSelect.addEventListener('change', e => changeLanguage(e.target.value));
if (els.exportAllBtn) els.exportAllBtn.addEventListener('click', exportAllChats);
if (els.importFile) els.importFile.addEventListener('change', e => { if (e.target.files[0]) importChats(e.target.files[0]); e.target.value = ''; });
if (els.clearAllBtn) els.clearAllBtn.addEventListener('click', clearAllData);
// Keyboard shortcuts
document.addEventListener('keydown', e => {
if (e.key === 'Escape') { closeProviderModal(); closeParamsModal(); closeSidebar(); }
if (e.ctrlKey && e.key === 'n') { e.preventDefault(); newChat(); }
if (e.ctrlKey && e.key === 's') { e.preventDefault(); if (state.currentProviderId) openParamsModal(state.currentProviderId); }
});
}
// ============ Init ============
function init() {
console.log('Initializing...');
loadState();
applySettings();
initEvents();
renderProviders();
renderHistory();
renderMessages();
updateHeader();
if (state.currentProviderId && els.messageInput) els.messageInput.focus();
console.log('Initialization complete');
}
init();
</script>
</body>
</html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Agent Chat</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--bg-primary: #ffffff;
--bg-secondary: #f7f7f8;
--bg-tertiary: #eeeeef;
--bg-chat: #f7f7f8;
--text-primary: #1a1a1b;
--text-secondary: #545455;
--text-muted: #8e8e93;
--border-color: #e5e5e6;
--accent: #0066cc;
--accent-hover: #0052a3;
--accent-light: #e8f0fe;
--user-bubble: #0066cc;
--user-text: #ffffff;
--assistant-bubble: #ffffff;
--code-bg: #f0f0f1;
--code-text: #1a1a1b;
--sidebar-bg: #ffffff;
--sidebar-border: #e5e5e6;
--shadow: 0 1px 3px rgba(0,0,0,0.08), 0 4px 12px rgba(0,0,0,0.05);
--shadow-lg: 0 8px 30px rgba(0,0,0,0.12);
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
--transition: 150ms ease;
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--font-mono: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;
}
[data-theme="dark"] {
--bg-primary: #1a1a1b;
--bg-secondary: #242425;
--bg-tertiary: #2d2d2e;
--bg-chat: #1a1a1b;
--text-primary: #ffffff;
--text-secondary: #b0b0b3;
--text-muted: #8e8e93;
--border-color: #3a3a3c;
--accent: #4d9fff;
--accent-hover: #6eb4ff;
--accent-light: #1e3a5f;
--user-bubble: #4d9fff;
--user-text: #1a1a1b;
--assistant-bubble: #242425;
--code-bg: #2d2d2e;
--code-text: #e4e4e7;
--sidebar-bg: #1a1a1b;
--sidebar-border: #3a3a3c;
--shadow: 0 1px 3px rgba(0,0,0,0.3), 0 4px 12px rgba(0,0,0,0.2);
--shadow-lg: 0 8px 30px rgba(0,0,0,0.4);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html { font-size: 16px; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
body {
font-family: var(--font-sans);
background: var(--bg-chat);
color: var(--text-primary);
line-height: 1.6;
height: 100vh;
overflow: hidden;
transition: background var(--transition), color var(--transition);
}
/* Layout */
.app {
display: grid;
grid-template-columns: 280px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"sidebar header"
"sidebar main"
"sidebar footer";
height: 100vh;
}
/* Sidebar */
.sidebar {
grid-area: sidebar;
background: var(--sidebar-bg);
border-right: 1px solid var(--sidebar-border);
display: flex;
flex-direction: column;
overflow-y: auto;
position: relative;
z-index: 10;
}
.sidebar-header { padding: 16px; border-bottom: 1px solid var(--sidebar-border); display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.sidebar-title { font-weight: 600; font-size: 1.1rem; color: var(--text-primary); }
.sidebar-close { display: none; background: none; border: none; color: var(--text-secondary); cursor: pointer; padding: 8px; border-radius: var(--radius-sm); }