chore: update 8 file(s)
This commit is contained in:
62
www/404.html
Normal file
62
www/404.html
Normal file
@@ -0,0 +1,62 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Page Not Found</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
* {
|
||||
line-height: 1.2;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
html {
|
||||
color: #888;
|
||||
display: table;
|
||||
font-family: sans-serif;
|
||||
height: 100%;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
margin: 2em auto;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #555;
|
||||
font-size: 2em;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0 auto;
|
||||
width: 280px;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 280px) {
|
||||
|
||||
body,
|
||||
p {
|
||||
width: 95%;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.5em;
|
||||
margin: 0 0 0.3em;
|
||||
}
|
||||
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Page Not Found</h1>
|
||||
<p>Sorry, but the page you were trying to view does not exist.</p>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
<!-- IE needs 512+ bytes: https://docs.microsoft.com/archive/blogs/ieinternals/friendly-http-error-pages -->
|
||||
688
www/chatv3.js
Normal file
688
www/chatv3.js
Normal file
@@ -0,0 +1,688 @@
|
||||
const BACKENDS = {
|
||||
plato: {
|
||||
prod: '/api/plato',
|
||||
dev: 'http://192.168.1.74:8080/v1',
|
||||
name: 'Plato (192.168.1.74)'
|
||||
},
|
||||
stoic: {
|
||||
prod: '/api/stoic',
|
||||
dev: 'http://192.168.1.159:1234/v1',
|
||||
name: 'Stoic (192.168.1.159)'
|
||||
},
|
||||
ollama: {
|
||||
prod: '/api/ollama',
|
||||
dev: 'http://192.168.1.159:8081/v1',
|
||||
name: 'Ollama (192.168.1.159:8081)'
|
||||
}
|
||||
}
|
||||
const IS_PRODUCTION = window.location.hostname === 'jarvis-lan.appmodel.nl'
|
||||
const API_KEY = 'not-needed'
|
||||
const MAX_CHAT_HISTORY = 50
|
||||
|
||||
let currentBackendModel = null
|
||||
let availableBackendModels = []
|
||||
let currentStreamController = null
|
||||
let isStreaming = false
|
||||
let chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || []
|
||||
|
||||
// ✅ FIX: Generate unique IDs and validate message structure
|
||||
chatHistory = chatHistory.map((message, index) => ({
|
||||
role: message.role || 'user',
|
||||
content: message.content || '',
|
||||
markdown: message.markdown || false,
|
||||
messageId: message.messageId || `msg-${Date.now()}-${index}`
|
||||
})).filter(msg => msg.content && typeof msg.content === 'string')
|
||||
|
||||
const welcomeMessage = `# Welcome to LM Studio Chat!
|
||||
|
||||
I now support **full conversation history**, **real-time streaming responses** and **dark, readable text formatting**.
|
||||
|
||||
## Features:
|
||||
1. **Full Chat History** - Complete conversation context is now sent to the AI
|
||||
2. **Smart History Management** - Automatically keeps the last ${MAX_CHAT_HISTORY} messages
|
||||
3. **Streaming Mode** (enabled by default) - Watch responses appear word-by-word
|
||||
4. **Markdown Rendering** - Proper formatting for code, lists, tables, and more
|
||||
5. **Readable Dark Text** - No more eye strain from light gray text
|
||||
|
||||
## Try it out:
|
||||
- Ask follow-up questions that reference earlier messages
|
||||
- Have a multi-turn conversation with full context
|
||||
- Ask "what did I just ask?" to test history retention
|
||||
- Watch the streaming response in real-time!
|
||||
|
||||
> *Tip: You can toggle streaming and markdown using the checkboxes below.*`
|
||||
|
||||
// ✅ NEW: Robust parser for backend:model format
|
||||
function splitBackendModel(value) {
|
||||
if (!value || value === ':') {
|
||||
return { backendKey: '', model: '' };
|
||||
}
|
||||
|
||||
const colonIndex = value.indexOf(':');
|
||||
if (colonIndex === -1) {
|
||||
return { backendKey: value, model: '' };
|
||||
}
|
||||
|
||||
return {
|
||||
backendKey: value.substring(0, colonIndex),
|
||||
model: value.substring(colonIndex + 1)
|
||||
};
|
||||
}
|
||||
|
||||
function getApiUrl() {
|
||||
const { backendKey, model } = splitBackendModel(currentBackendModel);
|
||||
const effectiveBackendKey = backendKey || 'plato';
|
||||
const backend = BACKENDS[effectiveBackendKey];
|
||||
|
||||
if (!backend) {
|
||||
throw new Error(`Invalid backend: '${effectiveBackendKey}'`);
|
||||
}
|
||||
|
||||
return IS_PRODUCTION ? backend.prod : backend.dev;
|
||||
}
|
||||
|
||||
function updateBackendModelDisplay() {
|
||||
const { backendKey, model } = splitBackendModel(currentBackendModel);
|
||||
const backend = BACKENDS[backendKey];
|
||||
if (!backend) return;
|
||||
|
||||
const displayText = IS_PRODUCTION
|
||||
? `${backend.prod} - ${backend.name}`
|
||||
: backend.dev;
|
||||
const displayElement = document.getElementById('backendDisplay');
|
||||
if (displayElement) {
|
||||
displayElement.textContent = `${displayText} - Model: ${model || 'None'}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchBackendModels() {
|
||||
const selector = document.getElementById('backendModelSelector');
|
||||
let allModels = [];
|
||||
|
||||
for (const [backendKey, backendConfig] of Object.entries(BACKENDS)) {
|
||||
try {
|
||||
const apiUrl = IS_PRODUCTION ? backendConfig.prod : backendConfig.dev;
|
||||
console.log(`Fetching models from ${backendKey}: ${apiUrl}`);
|
||||
|
||||
const response = await fetch(`${apiUrl}/models`, {
|
||||
signal: AbortSignal.timeout(5000) // 5 second timeout
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.data && Array.isArray(data.data)) {
|
||||
const models = data.data.map(model => ({
|
||||
backend: backendKey,
|
||||
model: model.id
|
||||
}));
|
||||
allModels = [...allModels, ...models];
|
||||
}
|
||||
} else {
|
||||
console.error(`Failed to fetch models from ${backendKey}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error fetching models from ${backendKey}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
availableBackendModels = allModels;
|
||||
|
||||
if (selector) {
|
||||
if (availableBackendModels.length === 0) {
|
||||
selector.innerHTML = '<option value="">No models available (check backends)</option>';
|
||||
} else {
|
||||
populateBackendModelSelector();
|
||||
|
||||
// Auto-select if no valid model is set
|
||||
const hasModel = currentBackendModel && currentBackendModel.includes(':') && currentBackendModel.split(':')[1];
|
||||
if (!hasModel && availableBackendModels.length > 0) {
|
||||
currentBackendModel = `${availableBackendModels[0].backend}:${availableBackendModels[0].model}`;
|
||||
selector.value = currentBackendModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateBackendModelDisplay();
|
||||
}
|
||||
|
||||
function populateBackendModelSelector() {
|
||||
const selector = document.getElementById('backendModelSelector');
|
||||
if (!selector) return;
|
||||
|
||||
if (availableBackendModels.length === 0) {
|
||||
selector.innerHTML = '<option value="">No models available</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
selector.innerHTML = availableBackendModels.map(backendModel =>
|
||||
`<option value="${backendModel.backend}:${backendModel.model}">${BACKENDS[backendModel.backend].name} - ${backendModel.model}</option>`
|
||||
).join('');
|
||||
|
||||
if (currentBackendModel && selector.querySelector(`option[value="${currentBackendModel}"]`)) {
|
||||
selector.value = currentBackendModel;
|
||||
} else if (availableBackendModels.length > 0) {
|
||||
// If current selection is invalid, reset to first available
|
||||
currentBackendModel = `${availableBackendModels[0].backend}:${availableBackendModels[0].model}`;
|
||||
selector.value = currentBackendModel;
|
||||
}
|
||||
}
|
||||
|
||||
function getApiMessages() {
|
||||
return chatHistory.slice(-MAX_CHAT_HISTORY).map(({ role, content }) => ({
|
||||
role,
|
||||
content
|
||||
}));
|
||||
}
|
||||
|
||||
function trimChatHistory() {
|
||||
if (chatHistory.length > MAX_CHAT_HISTORY) {
|
||||
chatHistory = chatHistory.slice(-MAX_CHAT_HISTORY);
|
||||
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const backendModelSelector = document.getElementById('backendModelSelector');
|
||||
|
||||
if (backendModelSelector) {
|
||||
backendModelSelector.addEventListener('change', (e) => {
|
||||
currentBackendModel = e.target.value;
|
||||
updateBackendModelDisplay();
|
||||
fetchBackendModels();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const chatLog = document.getElementById('chatLog');
|
||||
const userInput = document.getElementById('userInput');
|
||||
const sendBtn = document.getElementById('sendBtn');
|
||||
const streamToggle = document.getElementById('streamToggle');
|
||||
const markdownToggle = document.getElementById('markdownToggle');
|
||||
const modelNameSpan = document.getElementById('modelName');
|
||||
|
||||
marked.setOptions({
|
||||
gfm: true,
|
||||
breaks: true,
|
||||
highlight: function(code, lang) {
|
||||
if (window.hljs) {
|
||||
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
|
||||
return hljs.highlight(code, { language }).value;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
});
|
||||
|
||||
function autoResize(textarea) {
|
||||
textarea.style.height = 'auto';
|
||||
textarea.style.height = Math.min(textarea.scrollHeight, 300) + 'px';
|
||||
}
|
||||
|
||||
function addMessage(role, content, markdown = false, messageId = null, saveToHistory = true) {
|
||||
const messageDiv = document.createElement('div');
|
||||
messageDiv.className = `message message-${role}`;
|
||||
if (messageId) {
|
||||
messageDiv.id = messageId;
|
||||
}
|
||||
|
||||
const headerDiv = document.createElement('div');
|
||||
headerDiv.className = `message-header ${role}`;
|
||||
|
||||
const avatar = document.createElement('div');
|
||||
avatar.className = `avatar ${role}-avatar`;
|
||||
avatar.textContent = role === 'user' ? '👤' : '🤖';
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.textContent = role === 'user' ? 'You' : 'Assistant';
|
||||
|
||||
headerDiv.appendChild(avatar);
|
||||
headerDiv.appendChild(name);
|
||||
|
||||
const contentDiv = document.createElement('div');
|
||||
|
||||
if (markdown && role === 'assistant' && markdownToggle.checked) {
|
||||
contentDiv.className = 'markdown-content';
|
||||
const processedContent = parseThinkingTags(content);
|
||||
contentDiv.innerHTML = marked.parse(processedContent);
|
||||
if (window.hljs) {
|
||||
setTimeout(() => {
|
||||
contentDiv.querySelectorAll('pre code').forEach((block) => {
|
||||
hljs.highlightElement(block);
|
||||
});
|
||||
}, 0);
|
||||
}
|
||||
} else {
|
||||
const processedContent = parseThinkingTags(content);
|
||||
contentDiv.innerHTML = processedContent;
|
||||
contentDiv.style.whiteSpace = 'pre-wrap';
|
||||
contentDiv.style.padding = '8px 0';
|
||||
contentDiv.style.color = '#e0e0e0';
|
||||
}
|
||||
|
||||
messageDiv.appendChild(headerDiv);
|
||||
messageDiv.appendChild(contentDiv);
|
||||
if (chatLog) {
|
||||
chatLog.appendChild(messageDiv);
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
}
|
||||
|
||||
if (saveToHistory) {
|
||||
chatHistory.push({ role, content, markdown, messageId });
|
||||
trimChatHistory();
|
||||
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
|
||||
}
|
||||
|
||||
return contentDiv;
|
||||
}
|
||||
|
||||
function parseThinkingTags(content) {
|
||||
let result = content;
|
||||
let thinkingCounter = 0;
|
||||
|
||||
const completeThinkRegex = /\[THINK\]([\s\S]*?)\[\/THINK\]/gi;
|
||||
result = result.replace(completeThinkRegex, (match, thinkContent) => {
|
||||
thinkingCounter++;
|
||||
const id = `thinking-${Date.now()}-${thinkingCounter}`;
|
||||
return `<div class="thinking-block">
|
||||
<div class="thinking-header" onclick="toggleThinking('${id}')">
|
||||
<span class="thinking-toggle" id="${id}-toggle">?</span>
|
||||
<span>? Thinking...</span>
|
||||
</div>
|
||||
<div class="thinking-content" id="${id}">${thinkContent.trim()}</div>
|
||||
</div>`;
|
||||
});
|
||||
|
||||
const incompleteThinkRegex = /\[THINK\]([\s\S]*?)$/gi;
|
||||
result = result.replace(incompleteThinkRegex, (match, thinkContent) => {
|
||||
thinkingCounter++;
|
||||
const id = `thinking-${Date.now()}-${thinkingCounter}`;
|
||||
return `<div class="thinking-block">
|
||||
<div class="thinking-header" onclick="toggleThinking('${id}')">
|
||||
<span class="thinking-toggle" id="${id}-toggle">?</span>
|
||||
<span>? Thinking...</span>
|
||||
</div>
|
||||
<div class="thinking-content" id="${id}">${thinkContent.trim()}</div>
|
||||
</div>`;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
window.toggleThinking = function(id) {
|
||||
const content = document.getElementById(id);
|
||||
const toggle = document.getElementById(id + '-toggle');
|
||||
|
||||
if (content && toggle) {
|
||||
content.classList.toggle('hidden');
|
||||
toggle.classList.toggle('collapsed');
|
||||
}
|
||||
};
|
||||
|
||||
function updateMessageContent(contentDiv, newContent, markdown = false, role) {
|
||||
const processedContent = parseThinkingTags(newContent);
|
||||
|
||||
if (markdown && role === 'assistant' && markdownToggle && markdownToggle.checked) {
|
||||
contentDiv.innerHTML = marked.parse(processedContent);
|
||||
if (window.hljs) {
|
||||
setTimeout(() => {
|
||||
contentDiv.querySelectorAll('pre code').forEach((block) => {
|
||||
hljs.highlightElement(block);
|
||||
});
|
||||
}, 0);
|
||||
}
|
||||
} else {
|
||||
contentDiv.innerHTML = processedContent;
|
||||
contentDiv.style.whiteSpace = 'pre-wrap';
|
||||
contentDiv.style.padding = '8px 0';
|
||||
contentDiv.style.color = '#e0e0e0';
|
||||
}
|
||||
if (chatLog) {
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
function showTypingIndicator() {
|
||||
const typingDiv = document.createElement('div');
|
||||
typingDiv.id = 'typingIndicator';
|
||||
typingDiv.className = 'message message-assistant';
|
||||
|
||||
const headerDiv = document.createElement('div');
|
||||
headerDiv.className = 'message-header assistant';
|
||||
|
||||
const avatar = document.createElement('div');
|
||||
avatar.className = 'avatar assistant-avatar';
|
||||
avatar.textContent = '🤖';
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.textContent = 'Assistant';
|
||||
|
||||
headerDiv.appendChild(avatar);
|
||||
headerDiv.appendChild(name);
|
||||
|
||||
const dotsDiv = document.createElement('div');
|
||||
dotsDiv.className = 'typing-indicator';
|
||||
dotsDiv.innerHTML = `
|
||||
<div class="typing-dot"></div>
|
||||
<div class="typing-dot"></div>
|
||||
<div class="typing-dot"></div>
|
||||
<span style="margin-left: 8px;">Thinking...</span>
|
||||
`;
|
||||
|
||||
typingDiv.appendChild(headerDiv);
|
||||
typingDiv.appendChild(dotsDiv);
|
||||
if (chatLog) {
|
||||
chatLog.appendChild(typingDiv);
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
}
|
||||
|
||||
return typingDiv;
|
||||
}
|
||||
|
||||
function removeTypingIndicator(typingDiv) {
|
||||
if (typingDiv && typingDiv.parentNode) {
|
||||
typingDiv.parentNode.removeChild(typingDiv);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStreamingResponse(userMessage) {
|
||||
const messageId = 'msg-' + Date.now();
|
||||
let accumulatedContent = '';
|
||||
let contentDiv = null;
|
||||
|
||||
const messageDiv = document.createElement('div');
|
||||
messageDiv.className = 'message message-assistant';
|
||||
messageDiv.id = messageId;
|
||||
|
||||
const headerDiv = document.createElement('div');
|
||||
headerDiv.className = 'message-header assistant';
|
||||
|
||||
const avatar = document.createElement('div');
|
||||
avatar.className = 'avatar assistant-avatar';
|
||||
avatar.textContent = '🤖';
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.textContent = 'Assistant';
|
||||
|
||||
headerDiv.appendChild(avatar);
|
||||
headerDiv.appendChild(name);
|
||||
|
||||
contentDiv = document.createElement('div');
|
||||
contentDiv.className = 'markdown-content';
|
||||
|
||||
messageDiv.appendChild(headerDiv);
|
||||
messageDiv.appendChild(contentDiv);
|
||||
if (chatLog) {
|
||||
chatLog.appendChild(messageDiv);
|
||||
}
|
||||
|
||||
const cursorSpan = document.createElement('span');
|
||||
cursorSpan.className = 'streaming-cursor';
|
||||
contentDiv.appendChild(cursorSpan);
|
||||
|
||||
// ✅ FIX: Create AbortController BEFORE fetch
|
||||
currentStreamController = new AbortController();
|
||||
isStreaming = true;
|
||||
|
||||
try {
|
||||
const { backendKey, model } = splitBackendModel(currentBackendModel);
|
||||
const selectedModel = model || availableBackendModels[0]?.model || 'local-model';
|
||||
|
||||
const requestBody = {
|
||||
model: selectedModel,
|
||||
messages: getApiMessages(),
|
||||
stream: true,
|
||||
temperature: 0.7,
|
||||
max_tokens: 2000
|
||||
};
|
||||
|
||||
const response = await fetch(`${getApiUrl()}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
signal: currentStreamController.signal // ✅ Now works correctly
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API Error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
let updateScheduled = false;
|
||||
let lastUpdate = Date.now();
|
||||
const MIN_UPDATE_INTERVAL = 100;
|
||||
|
||||
function scheduleUpdate() {
|
||||
if (updateScheduled) return;
|
||||
|
||||
const now = Date.now();
|
||||
const timeSinceLastUpdate = now - lastUpdate;
|
||||
|
||||
if (timeSinceLastUpdate >= MIN_UPDATE_INTERVAL) {
|
||||
updateScheduled = true;
|
||||
requestAnimationFrame(() => {
|
||||
updateMessageContent(contentDiv, accumulatedContent, markdownToggle && markdownToggle.checked, 'assistant');
|
||||
if (cursorSpan.parentNode) {
|
||||
contentDiv.appendChild(cursorSpan);
|
||||
}
|
||||
if (chatLog) {
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
}
|
||||
lastUpdate = Date.now();
|
||||
updateScheduled = false;
|
||||
});
|
||||
} else {
|
||||
updateScheduled = true;
|
||||
setTimeout(() => {
|
||||
requestAnimationFrame(() => {
|
||||
updateMessageContent(contentDiv, accumulatedContent, markdownToggle && markdownToggle.checked, 'assistant');
|
||||
if (cursorSpan.parentNode) {
|
||||
contentDiv.appendChild(cursorSpan);
|
||||
}
|
||||
if (chatLog) {
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
}
|
||||
lastUpdate = Date.now();
|
||||
updateScheduled = false;
|
||||
});
|
||||
}, MIN_UPDATE_INTERVAL - timeSinceLastUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split('\n').filter(line => line.trim() !== '');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const data = line.slice(6);
|
||||
|
||||
if (data === '[DONE]') {
|
||||
isStreaming = false;
|
||||
currentStreamController = null;
|
||||
updateMessageContent(contentDiv, accumulatedContent, markdownToggle.checked, 'assistant');
|
||||
if (cursorSpan.parentNode) {
|
||||
cursorSpan.parentNode.removeChild(cursorSpan);
|
||||
}
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
if (parsed.choices && parsed.choices[0].delta.content) {
|
||||
accumulatedContent += parsed.choices[0].delta.content;
|
||||
scheduleUpdate();
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Error parsing stream data:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateMessageContent(contentDiv, accumulatedContent, markdownToggle.checked, 'assistant');
|
||||
chatLog.scrollTop = chatLog.scrollHeight;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Streaming error:', error);
|
||||
if (error.name !== 'AbortError') {
|
||||
updateMessageContent(contentDiv, `Error: ${error.message}`, false, 'assistant');
|
||||
}
|
||||
} finally {
|
||||
isStreaming = false;
|
||||
currentStreamController = null;
|
||||
sendBtn.disabled = false;
|
||||
|
||||
if (cursorSpan && cursorSpan.parentNode) {
|
||||
cursorSpan.parentNode.removeChild(cursorSpan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleNonStreamingResponse(userMessage) {
|
||||
let typingIndicator = null;
|
||||
try {
|
||||
typingIndicator = showTypingIndicator();
|
||||
|
||||
const { backendKey, model } = splitBackendModel(currentBackendModel);
|
||||
const selectedModel = model || availableBackendModels[0]?.model || 'local-model';
|
||||
|
||||
const requestBody = {
|
||||
model: selectedModel,
|
||||
messages: getApiMessages(),
|
||||
stream: false,
|
||||
temperature: 0.7,
|
||||
max_tokens: 2000
|
||||
};
|
||||
|
||||
const response = await fetch(`${getApiUrl()}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`
|
||||
},
|
||||
body: JSON.stringify(requestBody)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API Error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
removeTypingIndicator(typingIndicator);
|
||||
|
||||
if (data.choices && data.choices.length > 0) {
|
||||
const assistantReply = data.choices[0].message.content;
|
||||
addMessage('assistant', assistantReply, markdownToggle.checked);
|
||||
} else {
|
||||
addMessage('assistant', 'No response generated.', false);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
if (typingIndicator) {
|
||||
removeTypingIndicator(typingIndicator);
|
||||
}
|
||||
addMessage('assistant', `Error: ${error.message}`, false);
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
userInput.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function stopStream() {
|
||||
if (currentStreamController) {
|
||||
currentStreamController.abort();
|
||||
isStreaming = false;
|
||||
currentStreamController = null;
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.textContent = 'Send';
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const userMessage = userInput.value.trim();
|
||||
if (!userMessage || isStreaming) return;
|
||||
|
||||
// ✅ FIX: Validate backend selection
|
||||
if (!currentBackendModel) {
|
||||
addMessage('assistant', 'Please select a backend model first.', false);
|
||||
return;
|
||||
}
|
||||
|
||||
addMessage('user', userMessage, false);
|
||||
|
||||
userInput.value = '';
|
||||
userInput.style.height = 'auto';
|
||||
sendBtn.disabled = true;
|
||||
|
||||
if (streamToggle.checked) {
|
||||
sendBtn.textContent = 'Stop';
|
||||
await handleStreamingResponse(userMessage);
|
||||
} else {
|
||||
await handleNonStreamingResponse(userMessage);
|
||||
}
|
||||
|
||||
sendBtn.textContent = 'Send';
|
||||
}
|
||||
|
||||
sendBtn.addEventListener('click', () => {
|
||||
if (isStreaming) {
|
||||
stopStream();
|
||||
} else {
|
||||
sendMessage();
|
||||
}
|
||||
});
|
||||
|
||||
userInput.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (!isStreaming) {
|
||||
sendMessage();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ Updated window.onload with better initialization
|
||||
window.onload = () => {
|
||||
if (userInput) userInput.focus();
|
||||
|
||||
// Set default backend BEFORE fetching
|
||||
if (!currentBackendModel) {
|
||||
currentBackendModel = 'plato';
|
||||
}
|
||||
|
||||
fetchBackendModels().then(() => {
|
||||
// Load chat history after models are fetched
|
||||
if (chatLog) {
|
||||
if (chatHistory.length === 0) {
|
||||
//addMessage('assistant', welcomeMessage, true, null, false);
|
||||
} else {
|
||||
chatHistory.forEach(msg => {
|
||||
if (typeof msg.content === 'string' && msg.content.trim()) {
|
||||
addMessage(msg.role, msg.content, msg.markdown, msg.messageId, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('resetBtn')?.addEventListener('click', resetChat);
|
||||
};
|
||||
|
||||
function resetChat() {
|
||||
chatHistory = [];
|
||||
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
|
||||
|
||||
if (chatLog) {
|
||||
chatLog.innerHTML = '';
|
||||
addMessage('assistant', welcomeMessage, true, null, false);
|
||||
}
|
||||
}
|
||||
42
www/favico.svg
Normal file
42
www/favico.svg
Normal file
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="200" height="200"
|
||||
viewBox="0 0 200 200">
|
||||
|
||||
<!-- Background circle -->
|
||||
<circle cx="100" cy="100" r="90" fill="#00A2E8"/>
|
||||
|
||||
<!-- Light‑blue gradient for the inner halo -->
|
||||
<defs>
|
||||
<radialGradient id="halo" cx="50%" cy="30%" r="80%">
|
||||
<stop offset="0%" stop-color="#6BC3FF"/>
|
||||
<stop offset="100%" stop-color="#00A2E8"/>
|
||||
</radialGradient>
|
||||
|
||||
<!-- Stroke for the “m” -->
|
||||
<linearGradient id="mGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#FFFFFF"/>
|
||||
<stop offset="100%" stop-color="#E5F3FF"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- The “m” – a stylised double‑stroke shape -->
|
||||
<path d="
|
||||
M 65,110
|
||||
L 70,80
|
||||
C 75,60 85,50 95,55
|
||||
C 105,60 115,40 125,45
|
||||
L 130,70
|
||||
L 135,90
|
||||
"
|
||||
fill="none" stroke="#FFFFFF" stroke-width="12" stroke-linecap="round"/>
|
||||
|
||||
<!-- The “IRC” text -->
|
||||
<text x="140" y="135"
|
||||
font-family="'Segoe UI', Arial, Helvetica, sans"
|
||||
font-weight="700"
|
||||
font-size="70"
|
||||
fill="url(#halo)">
|
||||
mIRC
|
||||
</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
BIN
www/favicon.ico
Normal file
BIN
www/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 174 KiB |
79
www/index.html
Normal file
79
www/index.html
Normal file
@@ -0,0 +1,79 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Chat</title>
|
||||
<link rel="stylesheet" href="style2.css">
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github-dark.min.css">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="chatContainer">
|
||||
<div id="header">
|
||||
<div>Chat with Streaming</div>
|
||||
<div style="font-size: 0.9em; opacity: 0.9; display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<span>Backend & Model:</span>
|
||||
<select id="backendModelSelector" style="padding: 4px 8px; border-radius: 4px; border: 1px solid #444; background: #2a2a2a; color: #e0e0e0; min-width: 200px;">
|
||||
<option value="">Loading backends and models...</option>
|
||||
</select>
|
||||
</div>
|
||||
<code id="backendDisplay" style="font-size: 0.85em;"></code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="chatLog">
|
||||
<div class="message message-assistant"><div class="message-header assistant"><div class="avatar assistant-avatar">?</div><span>Assistant</span></div><div class="markdown-content"><h1>Welcome to LM Studio Chat!</h1>
|
||||
<p>I now support <strong>full conversation history</strong>, <strong>real-time streaming responses</strong> and <strong>dark, readable text formatting</strong>.</p>
|
||||
<h2>Features:</h2>
|
||||
<ol>
|
||||
<li><strong>Full Chat History</strong> - Complete conversation context is now sent to the AI</li>
|
||||
<li><strong>Smart History Management</strong> - Automatically keeps the last 50 messages</li>
|
||||
<li><strong>Streaming Mode</strong> (enabled by default) - Watch responses appear word-by-word</li>
|
||||
<li><strong>Markdown Rendering</strong> - Proper formatting for code, lists, tables, and more</li>
|
||||
<li><strong>Readable Dark Text</strong> - No more eye strain from light gray text</li>
|
||||
</ol>
|
||||
<h2>Try it out:</h2>
|
||||
<ul>
|
||||
<li>Ask follow-up questions that reference earlier messages</li>
|
||||
<li>Have a multi-turn conversation with full context</li>
|
||||
<li>Ask "what did I just ask?" to test history retention</li>
|
||||
<li>Watch the streaming response in real-time!</li>
|
||||
</ul>
|
||||
<blockquote>
|
||||
<p><em>Tip: You can toggle streaming and markdown using the checkboxes below.</em></p>
|
||||
</blockquote>
|
||||
</div></div>
|
||||
</div>
|
||||
|
||||
<div id="inputArea">
|
||||
<textarea
|
||||
id="userInput"
|
||||
placeholder="Type your message here... (Shift+Enter for new line, Enter to send)"
|
||||
rows="1"
|
||||
oninput="autoResize(this)"
|
||||
></textarea>
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<div class="controls">
|
||||
<div>
|
||||
<label>
|
||||
<input type="checkbox" id="streamToggle" checked> Streaming
|
||||
</label>
|
||||
<label style="margin-left: 15px;">
|
||||
<input type="checkbox" id="markdownToggle" checked> Markdown
|
||||
</label>
|
||||
</div>
|
||||
<div id="modelInfo">Model: <span id="modelName">unknown</span></div>
|
||||
</div>
|
||||
<button id="sendBtn">Send</button>
|
||||
<button id="resetBtn">Reset Chat</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="chatv3.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
375
www/style2.css
Normal file
375
www/style2.css
Normal file
@@ -0,0 +1,375 @@
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
#chatContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: white;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 15px 20px;
|
||||
font-size: 1.2em;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#chatLog {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 25px;
|
||||
animation: fadeIn 0.3s ease-in;
|
||||
}
|
||||
|
||||
.message-user {
|
||||
background: #e3f2fd;
|
||||
border-left: 4px solid #2196f3;
|
||||
padding: 12px 15px;
|
||||
border-radius: 0 8px 8px 0;
|
||||
margin-left: 0;
|
||||
margin-right: 40px;
|
||||
}
|
||||
|
||||
.message-assistant {
|
||||
background: white;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
margin-right: 0;
|
||||
margin-left: 40px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.message-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.message-header.user {
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.message-header.assistant {
|
||||
color: #388e3c;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
margin-right: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
background: #2196f3;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.assistant-avatar {
|
||||
background: #4caf50;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#inputArea {
|
||||
border-top: 1px solid #e0e0e0;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
#userInput {
|
||||
width: 100%;
|
||||
padding: 16px 18px;
|
||||
border: 2px solid #ddd;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
resize: none;
|
||||
min-height: 100px;
|
||||
max-height: 300px;
|
||||
font-family: inherit;
|
||||
line-height: 1.6;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#userInput:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
#sendBtn {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 12px 24px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s, opacity 0.2s;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
#sendBtn:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
opacity: 0.95;
|
||||
}
|
||||
|
||||
#sendBtn:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.typing-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 10px 15px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.typing-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background: #4caf50;
|
||||
border-radius: 50%;
|
||||
animation: typing 1.4s infinite;
|
||||
}
|
||||
|
||||
.typing-dot:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
.typing-dot:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes typing {
|
||||
0%, 60%, 100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
30% {
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
}
|
||||
|
||||
.streaming-cursor {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 20px;
|
||||
background-color: #4caf50;
|
||||
margin-left: 2px;
|
||||
animation: blink 1s infinite;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
0%, 50% {
|
||||
opacity: 1;
|
||||
}
|
||||
51%, 100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.thinking-block {
|
||||
margin: 10px 0;
|
||||
border-left: 3px solid #ff9800;
|
||||
background: #fff3e0;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.thinking-header {
|
||||
padding: 8px 12px;
|
||||
background: #ffe0b2;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 600;
|
||||
color: #e65100;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.thinking-header:hover {
|
||||
background: #ffcc80;
|
||||
}
|
||||
|
||||
.thinking-toggle {
|
||||
transition: transform 0.2s;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.thinking-toggle.collapsed {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.thinking-content {
|
||||
padding: 12px;
|
||||
color: #5d4037;
|
||||
font-size: 0.9em;
|
||||
line-height: 1.5;
|
||||
border-top: 1px solid #ffcc80;
|
||||
}
|
||||
|
||||
.thinking-content.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.control-btn {
|
||||
padding: 6px 12px;
|
||||
background: #f5f5f5;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.control-btn:hover {
|
||||
background: #e9e9e9;
|
||||
}
|
||||
|
||||
#modelInfo {
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.markdown-content {
|
||||
color: #24292f;
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.markdown-content h1, .markdown-content h2, .markdown-content h3 {
|
||||
color: #1a1a1a;
|
||||
border-bottom: 1px solid #eaecef;
|
||||
padding-bottom: 0.3em;
|
||||
margin-top: 1.5em;
|
||||
margin-bottom: 0.8em;
|
||||
}
|
||||
|
||||
.markdown-content h1 {
|
||||
font-size: 1.8em;
|
||||
}
|
||||
|
||||
.markdown-content h2 {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
.markdown-content h3 {
|
||||
font-size: 1.25em;
|
||||
}
|
||||
|
||||
.markdown-content p {
|
||||
margin: 0.8em 0;
|
||||
color: #2d3339;
|
||||
}
|
||||
|
||||
.markdown-content code {
|
||||
background-color: #f6f8fa;
|
||||
color: #d63384;
|
||||
padding: 0.2em 0.4em;
|
||||
border-radius: 3px;
|
||||
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
|
||||
font-size: 0.9em;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.markdown-content pre {
|
||||
background-color: #0d1117;
|
||||
color: #c9d1d9;
|
||||
padding: 1em;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 1em 0;
|
||||
border: 1px solid #30363d;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
.markdown-content pre code {
|
||||
background-color: transparent;
|
||||
color: inherit;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.markdown-content ul, .markdown-content ol {
|
||||
padding-left: 1.8em;
|
||||
margin: 0.8em 0;
|
||||
color: #2d3339;
|
||||
}
|
||||
|
||||
.markdown-content li {
|
||||
margin: 0.3em 0;
|
||||
}
|
||||
|
||||
.markdown-content blockquote {
|
||||
border-left: 3px solid #d0d7de;
|
||||
padding-left: 1em;
|
||||
margin: 1em 0;
|
||||
color: #57606a;
|
||||
}
|
||||
|
||||
.markdown-content table {
|
||||
border-collapse: collapse;
|
||||
margin: 1em 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.markdown-content th, .markdown-content td {
|
||||
border: 1px solid #d0d7de;
|
||||
padding: 0.5em 1em;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.markdown-content th {
|
||||
background-color: #f6f8fa;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.markdown-content tr:nth-child(even) {
|
||||
background-color: #f6f8fa;
|
||||
}
|
||||
Reference in New Issue
Block a user