mirror of
https://github.com/thecyberlearn/quantumtaskai-caprover.git
synced 2026-08-18 08:32:56 +00:00
Complete Django AI agent marketplace with security optimizations and clean deployment documentation without any API keys or secrets. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
1216 lines
36 KiB
HTML
1216 lines
36 KiB
HTML
{% extends 'base.html' %}
|
|
{% load static %}
|
|
|
|
{% block title %}{{ agent.name }} - Quantum Tasks AI{% endblock %}
|
|
|
|
{% block extra_css %}
|
|
<link rel="stylesheet" href="{% static 'css/agent-base.css' %}?v={{ timestamp }}">
|
|
<style>
|
|
/* Chat Interface Styles */
|
|
.chat-container {
|
|
max-width: 1000px;
|
|
margin: 0 auto;
|
|
padding: 20px;
|
|
}
|
|
|
|
/* Enhanced message formatting */
|
|
.message-bubble h1,
|
|
.message-bubble h2,
|
|
.message-bubble h3,
|
|
.message-bubble h4 {
|
|
margin: 16px 0 8px 0;
|
|
font-weight: 600;
|
|
line-height: 1.3;
|
|
}
|
|
|
|
.message-bubble h1 { font-size: 18px; color: var(--primary); }
|
|
.message-bubble h2 { font-size: 16px; color: var(--primary); }
|
|
.message-bubble h3 { font-size: 15px; color: var(--on-surface); }
|
|
.message-bubble h4 { font-size: 14px; color: var(--on-surface); }
|
|
|
|
/* Handle markdown-style headers in plain text */
|
|
.message-bubble p:has(strong):first-child,
|
|
.message-bubble p:contains("##"),
|
|
.message-bubble p:contains("###") {
|
|
font-weight: 600;
|
|
color: var(--primary);
|
|
margin-top: 16px;
|
|
margin-bottom: 8px;
|
|
}
|
|
|
|
/* Enhanced styling for better visual hierarchy */
|
|
.message-bubble {
|
|
font-size: 14px;
|
|
line-height: 1.6;
|
|
}
|
|
|
|
/* Better spacing for structured content */
|
|
.message-bubble p:first-child {
|
|
margin-top: 0;
|
|
}
|
|
|
|
.message-bubble p:last-child {
|
|
margin-bottom: 0;
|
|
}
|
|
|
|
.message-bubble ul,
|
|
.message-bubble ol {
|
|
margin: 12px 0;
|
|
padding-left: 20px;
|
|
}
|
|
|
|
.message-bubble li {
|
|
margin: 6px 0;
|
|
line-height: 1.5;
|
|
}
|
|
|
|
.message-bubble strong {
|
|
font-weight: 600;
|
|
color: var(--on-surface);
|
|
}
|
|
|
|
.message-bubble em {
|
|
font-style: italic;
|
|
color: var(--on-surface-variant);
|
|
}
|
|
|
|
.message-bubble p {
|
|
margin: 10px 0;
|
|
line-height: 1.6;
|
|
}
|
|
|
|
.message-bubble code {
|
|
background: var(--surface-variant);
|
|
padding: 2px 6px;
|
|
border-radius: 4px;
|
|
font-family: var(--font-mono);
|
|
font-size: 13px;
|
|
}
|
|
|
|
.message-bubble pre {
|
|
background: var(--surface-variant);
|
|
padding: 12px;
|
|
border-radius: 8px;
|
|
overflow-x: auto;
|
|
margin: 12px 0;
|
|
}
|
|
|
|
.message-bubble blockquote {
|
|
border-left: 3px solid var(--primary);
|
|
margin: 12px 0;
|
|
padding-left: 12px;
|
|
color: var(--on-surface-variant);
|
|
font-style: italic;
|
|
}
|
|
|
|
.chat-widget {
|
|
background: var(--surface);
|
|
border: 1px solid var(--outline);
|
|
border-radius: var(--radius-lg);
|
|
box-shadow: var(--shadow-lg);
|
|
height: 800px;
|
|
display: flex;
|
|
flex-direction: column;
|
|
}
|
|
|
|
.chat-header {
|
|
padding: 20px;
|
|
border-bottom: 1px solid var(--outline);
|
|
background: var(--gradient-primary);
|
|
color: white;
|
|
border-radius: var(--radius-lg) var(--radius-lg) 0 0;
|
|
display: flex;
|
|
justify-content: space-between;
|
|
align-items: flex-start;
|
|
}
|
|
|
|
.chat-title {
|
|
margin: 0;
|
|
font-size: 20px;
|
|
font-weight: 600;
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 10px;
|
|
}
|
|
|
|
.chat-subtitle {
|
|
margin: 5px 0 0 0;
|
|
font-size: 14px;
|
|
opacity: 0.9;
|
|
}
|
|
|
|
.chat-messages {
|
|
flex: 1;
|
|
padding: 20px;
|
|
overflow-y: auto;
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 15px;
|
|
}
|
|
|
|
.message {
|
|
display: flex;
|
|
margin-bottom: 15px;
|
|
}
|
|
|
|
.message.user {
|
|
justify-content: flex-end;
|
|
}
|
|
|
|
.message.agent {
|
|
justify-content: flex-start;
|
|
}
|
|
|
|
.message.system {
|
|
justify-content: center;
|
|
}
|
|
|
|
.message-bubble {
|
|
max-width: 70%;
|
|
padding: 12px 16px;
|
|
border-radius: 18px;
|
|
position: relative;
|
|
word-wrap: break-word;
|
|
}
|
|
|
|
.message.user .message-bubble {
|
|
background: var(--primary);
|
|
color: white;
|
|
border-bottom-right-radius: 6px;
|
|
}
|
|
|
|
.message.agent .message-bubble {
|
|
background: var(--surface-variant);
|
|
color: var(--on-surface);
|
|
border-bottom-left-radius: 6px;
|
|
}
|
|
|
|
.message.system .message-bubble {
|
|
background: var(--background-light);
|
|
color: var(--on-surface-variant);
|
|
font-style: italic;
|
|
font-size: 13px;
|
|
max-width: 90%;
|
|
text-align: center;
|
|
}
|
|
|
|
.message-time {
|
|
font-size: 11px;
|
|
opacity: 0.7;
|
|
margin-top: 4px;
|
|
}
|
|
|
|
.chat-input-area {
|
|
padding: 20px;
|
|
border-top: 1px solid var(--outline);
|
|
background: var(--surface-variant);
|
|
border-radius: 0 0 var(--radius-lg) var(--radius-lg);
|
|
}
|
|
|
|
.chat-input-form {
|
|
display: flex;
|
|
gap: 10px;
|
|
}
|
|
|
|
.chat-input {
|
|
flex: 1;
|
|
padding: 12px 16px;
|
|
border: 2px solid var(--outline-variant);
|
|
border-radius: 25px;
|
|
font-size: 14px;
|
|
background: var(--surface);
|
|
color: var(--on-surface);
|
|
outline: none;
|
|
}
|
|
|
|
.chat-input:focus {
|
|
border-color: var(--primary);
|
|
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
|
}
|
|
|
|
.chat-send-btn {
|
|
padding: 12px 20px;
|
|
background: var(--primary);
|
|
color: white;
|
|
border: none;
|
|
border-radius: 25px;
|
|
cursor: pointer;
|
|
font-weight: 600;
|
|
transition: var(--transition);
|
|
}
|
|
|
|
.chat-send-btn:hover:not(:disabled) {
|
|
background: var(--primary-dark);
|
|
transform: translateY(-1px);
|
|
}
|
|
|
|
.chat-send-btn:disabled {
|
|
opacity: 0.5;
|
|
cursor: not-allowed;
|
|
}
|
|
|
|
.typing-indicator {
|
|
display: none;
|
|
padding: 10px 16px;
|
|
color: var(--on-surface-variant);
|
|
font-style: italic;
|
|
font-size: 13px;
|
|
}
|
|
|
|
.typing-indicator.show {
|
|
display: block;
|
|
}
|
|
|
|
/* Session Info */
|
|
.session-info {
|
|
background: var(--background-light);
|
|
padding: 15px 20px;
|
|
border-radius: var(--radius-md);
|
|
margin-bottom: 20px;
|
|
display: flex;
|
|
justify-content: space-between;
|
|
align-items: center;
|
|
}
|
|
|
|
.session-status {
|
|
font-size: 14px;
|
|
color: var(--on-surface-variant);
|
|
}
|
|
|
|
.session-id {
|
|
font-family: var(--font-mono);
|
|
font-size: 12px;
|
|
color: var(--on-surface-variant);
|
|
background: var(--surface);
|
|
padding: 4px 8px;
|
|
border-radius: 4px;
|
|
}
|
|
|
|
/* Responsive */
|
|
@media (max-width: 768px) {
|
|
.chat-container {
|
|
padding: 10px;
|
|
}
|
|
|
|
.chat-widget {
|
|
height: 650px;
|
|
}
|
|
|
|
.message-bubble {
|
|
max-width: 85%;
|
|
}
|
|
|
|
.chat-input-form {
|
|
flex-direction: column;
|
|
gap: 10px;
|
|
}
|
|
|
|
.chat-send-btn {
|
|
align-self: flex-end;
|
|
width: auto;
|
|
}
|
|
}
|
|
|
|
/* Empty state */
|
|
.chat-empty {
|
|
flex: 1;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: center;
|
|
justify-content: center;
|
|
color: var(--on-surface-variant);
|
|
text-align: center;
|
|
padding: 40px 20px;
|
|
}
|
|
|
|
.chat-empty-icon {
|
|
font-size: 48px;
|
|
margin-bottom: 16px;
|
|
opacity: 0.5;
|
|
}
|
|
|
|
.chat-empty-text {
|
|
font-size: 16px;
|
|
margin-bottom: 8px;
|
|
}
|
|
|
|
.chat-empty-subtext {
|
|
font-size: 14px;
|
|
opacity: 0.7;
|
|
}
|
|
|
|
/* Download dropdown styles */
|
|
.download-dropdown {
|
|
position: relative;
|
|
}
|
|
|
|
.download-btn {
|
|
background: rgba(255, 255, 255, 0.2);
|
|
color: white;
|
|
border: 1px solid rgba(255, 255, 255, 0.3);
|
|
padding: 8px 16px;
|
|
border-radius: 6px;
|
|
font-size: 14px;
|
|
cursor: pointer;
|
|
transition: all 0.2s ease;
|
|
}
|
|
|
|
.download-btn:hover {
|
|
background: rgba(255, 255, 255, 0.3);
|
|
transform: translateY(-1px);
|
|
}
|
|
|
|
.download-menu {
|
|
position: absolute;
|
|
top: 100%;
|
|
right: 0;
|
|
background: white;
|
|
border: 1px solid var(--outline);
|
|
border-radius: 6px;
|
|
box-shadow: var(--shadow-lg);
|
|
min-width: 160px;
|
|
z-index: 1000;
|
|
display: none;
|
|
margin-top: 4px;
|
|
}
|
|
|
|
.download-menu.show {
|
|
display: block;
|
|
}
|
|
|
|
.download-option {
|
|
display: block;
|
|
padding: 12px 16px;
|
|
color: var(--on-surface);
|
|
text-decoration: none;
|
|
font-size: 14px;
|
|
border-bottom: 1px solid var(--outline-variant);
|
|
transition: background 0.2s ease;
|
|
}
|
|
|
|
.download-option:last-child {
|
|
border-bottom: none;
|
|
}
|
|
|
|
.download-option:hover {
|
|
background: var(--surface-variant);
|
|
color: var(--on-surface);
|
|
}
|
|
|
|
/* Sidebar layout */
|
|
.agent-sidebar {
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: var(--spacing-md);
|
|
flex: 0 0 auto;
|
|
min-width: 300px;
|
|
}
|
|
|
|
/* 5 Whys specific spacing adjustments */
|
|
.agent-container {
|
|
padding: var(--spacing-sm) !important;
|
|
}
|
|
|
|
.agent-header {
|
|
margin-bottom: 20px !important;
|
|
}
|
|
|
|
.agent-grid {
|
|
padding: 0 !important;
|
|
margin: 0 !important;
|
|
}
|
|
|
|
.agent-widget.widget-large {
|
|
padding: 20px !important;
|
|
margin: 0 !important;
|
|
}
|
|
|
|
/* Expired Session Modal */
|
|
.modal-overlay {
|
|
position: fixed;
|
|
top: 0;
|
|
left: 0;
|
|
width: 100%;
|
|
height: 100%;
|
|
background: rgba(0, 0, 0, 0.5);
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
z-index: 10000;
|
|
}
|
|
|
|
.modal-content {
|
|
background: var(--surface);
|
|
border-radius: var(--radius-lg);
|
|
padding: 30px;
|
|
max-width: 400px;
|
|
width: 90%;
|
|
text-align: center;
|
|
box-shadow: var(--shadow-xl);
|
|
border: 1px solid var(--outline);
|
|
}
|
|
|
|
.modal-content h3 {
|
|
margin: 0 0 15px 0;
|
|
color: var(--on-surface);
|
|
font-size: 20px;
|
|
font-weight: 600;
|
|
}
|
|
|
|
.modal-content p {
|
|
margin: 0 0 25px 0;
|
|
color: var(--on-surface-variant);
|
|
line-height: 1.5;
|
|
}
|
|
|
|
.modal-actions {
|
|
display: flex;
|
|
gap: 12px;
|
|
justify-content: center;
|
|
}
|
|
|
|
.modal-actions .btn {
|
|
padding: 10px 20px;
|
|
border-radius: 6px;
|
|
font-weight: 500;
|
|
border: none;
|
|
cursor: pointer;
|
|
transition: all 0.2s ease;
|
|
}
|
|
|
|
.modal-actions .btn-primary {
|
|
background: var(--primary);
|
|
color: white;
|
|
}
|
|
|
|
.modal-actions .btn-primary:hover {
|
|
background: var(--primary-dark);
|
|
}
|
|
|
|
.modal-actions .btn-secondary {
|
|
background: var(--surface-variant);
|
|
color: var(--on-surface);
|
|
border: 1px solid var(--outline);
|
|
}
|
|
|
|
.modal-actions .btn-secondary:hover {
|
|
background: var(--background);
|
|
}
|
|
</style>
|
|
{% endblock %}
|
|
|
|
{% block content %}
|
|
<script>
|
|
// Set data attributes for JavaScript access
|
|
document.body.setAttribute('data-user-authenticated', '{{ user.is_authenticated|yesno:"true,false" }}');
|
|
document.body.setAttribute('data-agent-price', '{{ agent.price }}');
|
|
document.body.setAttribute('data-agent-id', '{{ agent.id }}');
|
|
document.body.setAttribute('data-agent-slug', '{{ agent.slug }}');
|
|
document.body.setAttribute('data-webhook-url', '{{ agent.webhook_url }}');
|
|
{% if user.is_authenticated %}
|
|
document.body.setAttribute('data-user-balance', '{{ user.wallet_balance }}');
|
|
document.body.setAttribute('data-user-id', '{{ user.id }}');
|
|
{% endif %}
|
|
{% if chat_session %}
|
|
document.body.setAttribute('data-session-id', '{{ chat_session.session_id }}');
|
|
document.body.setAttribute('data-session-created', '{{ chat_session.created_at.isoformat }}');
|
|
document.body.setAttribute('data-session-expires', '{{ chat_session.expires_at.isoformat }}');
|
|
{% endif %}
|
|
</script>
|
|
|
|
<div class="agent-container">
|
|
<!-- Agent Header Component -->
|
|
{% include "components/agent_header.html" with agent_title=agent.name agent_subtitle=agent.short_description %}
|
|
|
|
<!-- Quick Agent Access Panel Component -->
|
|
{% include "components/quick_agents_panel.html" %}
|
|
|
|
<!-- Main Agent Grid -->
|
|
<div class="agent-grid">
|
|
<!-- Chat Widget -->
|
|
<div class="agent-widget widget-large" style="flex: 1; margin-right: clamp(0px, var(--spacing-lg), 2vw);">
|
|
{% if user.is_authenticated %}
|
|
{% if user.wallet_balance >= agent.price or chat_session %}
|
|
|
|
<!-- Chat Widget -->
|
|
<div class="chat-widget">
|
|
<div class="chat-header">
|
|
<div>
|
|
<h3 class="chat-title">
|
|
<span>{{ agent.category.icon }}</span>
|
|
{{ agent.name }}
|
|
</h3>
|
|
<p class="chat-subtitle">{{ agent.description }}</p>
|
|
</div>
|
|
{% if chat_session and messages %}
|
|
<div class="chat-actions">
|
|
<div class="download-dropdown">
|
|
<button class="download-btn" onclick="toggleDownloadMenu()" id="downloadBtn">
|
|
📥 Download
|
|
</button>
|
|
<div class="download-menu" id="downloadMenu">
|
|
<a href="#" onclick="downloadChat('pdf')" class="download-option">
|
|
📄 Download PDF
|
|
</a>
|
|
<a href="#" onclick="downloadChat('txt')" class="download-option">
|
|
📝 Download TXT
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
</div>
|
|
|
|
<div class="chat-messages" id="chatMessages">
|
|
{% if messages %}
|
|
{% for message in messages %}
|
|
<div class="message {{ message.message_type }}">
|
|
<div class="message-bubble" data-raw-content="{{ message.content|escape }}">
|
|
{{ message.content|linebreaks }}
|
|
<div class="message-time">{{ message.timestamp|date:"H:i" }}</div>
|
|
</div>
|
|
</div>
|
|
{% endfor %}
|
|
{% else %}
|
|
<div class="chat-empty">
|
|
<div class="chat-empty-icon">🤖</div>
|
|
<div class="chat-empty-text">Welcome to {{ agent.name }}!</div>
|
|
<div class="chat-empty-subtext">Send a message to start your conversation</div>
|
|
</div>
|
|
{% endif %}
|
|
</div>
|
|
|
|
<div class="typing-indicator" id="typingIndicator">
|
|
{{ agent.name }} is typing...
|
|
</div>
|
|
|
|
<div class="chat-input-area" id="chatInputArea">
|
|
{% if not chat_session or chat_session.status == 'active' %}
|
|
<form class="chat-input-form" id="chatForm">
|
|
{% csrf_token %}
|
|
<input type="text"
|
|
class="chat-input"
|
|
id="chatInput"
|
|
placeholder="Type your message..."
|
|
maxlength="500"
|
|
required>
|
|
<button type="submit" class="chat-send-btn" id="sendBtn">
|
|
Send
|
|
</button>
|
|
</form>
|
|
{% else %}
|
|
<div class="session-status">
|
|
Chat session {{ chat_session.get_status_display|lower }}.
|
|
<a href="{% url 'agents:detail' agent.slug %}" class="btn btn-primary btn-sm">Start New Chat</a>
|
|
</div>
|
|
{% endif %}
|
|
</div>
|
|
</div>
|
|
{% else %}
|
|
<!-- Insufficient Balance -->
|
|
<div class="chat-widget">
|
|
<div class="chat-header">
|
|
<h3 class="chat-title">
|
|
<span>{{ agent.category.icon }}</span>
|
|
{{ agent.name }}
|
|
</h3>
|
|
</div>
|
|
<div class="chat-messages">
|
|
<div class="chat-empty">
|
|
<div class="chat-empty-icon">💰</div>
|
|
<div class="chat-empty-text">Insufficient Balance</div>
|
|
<div class="chat-empty-subtext">
|
|
You need {{ agent.price }} AED to start a chat session.
|
|
</div>
|
|
<a href="{% url 'wallet:wallet' %}" class="btn btn-primary" style="margin-top: 20px;">
|
|
💰 Top Up Wallet
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
{% else %}
|
|
<!-- Not Authenticated -->
|
|
<div class="chat-widget">
|
|
<div class="chat-header">
|
|
<h3 class="chat-title">
|
|
<span>{{ agent.category.icon }}</span>
|
|
{{ agent.name }}
|
|
</h3>
|
|
</div>
|
|
<div class="chat-messages">
|
|
<div class="chat-empty">
|
|
<div class="chat-empty-icon">🔐</div>
|
|
<div class="chat-empty-text">Login Required</div>
|
|
<div class="chat-empty-subtext">
|
|
Please login to start chatting with {{ agent.name }}.
|
|
</div>
|
|
<a href="{% url 'authentication:login' %}?next={% url 'agents:detail' agent.slug %}"
|
|
class="btn btn-primary"
|
|
style="margin-top: 20px;">
|
|
🔐 Login to Continue
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
</div>
|
|
|
|
<!-- Expired Session Modal -->
|
|
<div id="expiredSessionModal" class="modal-overlay" style="display: none;">
|
|
<div class="modal-content">
|
|
<h3>Session Expired</h3>
|
|
<p>Start new chat session?<br>This will deduct {{ agent.price }} AED from your wallet.</p>
|
|
<div class="modal-actions">
|
|
<button onclick="startNewSessionFromExpired()" class="btn btn-primary">
|
|
Continue ({{ agent.price }} AED)
|
|
</button>
|
|
<button onclick="cancelNewSession()" class="btn btn-secondary">
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Sidebar -->
|
|
<div class="agent-sidebar">
|
|
<!-- How It Works Widget -->
|
|
{% include "components/how_it_works_widget.html" with steps="agents" %}
|
|
|
|
<!-- Current Session Info -->
|
|
{% include "components/current_session_widget.html" %}
|
|
|
|
<!-- Session Indicators -->
|
|
{% include "components/session_indicators.html" %}
|
|
|
|
<!-- Previous Sessions Widget -->
|
|
{% include "components/previous_sessions_widget.html" %}
|
|
</div>
|
|
</div>
|
|
{% endblock %}
|
|
|
|
{% block extra_js %}
|
|
<script src="{% static 'js/workflows-core.js' %}?v={{ timestamp }}"></script>
|
|
<script src="{% static 'js/agents-core.js' %}?v={{ timestamp }}"></script>
|
|
<script>
|
|
// Chat functionality
|
|
class ChatInterface {
|
|
constructor() {
|
|
this.agentSlug = document.body.getAttribute('data-agent-slug');
|
|
this.userId = document.body.getAttribute('data-user-id');
|
|
this.sessionId = document.body.getAttribute('data-session-id');
|
|
this.isAuthenticated = document.body.getAttribute('data-user-authenticated') === 'true';
|
|
|
|
this.chatMessages = document.getElementById('chatMessages');
|
|
this.chatForm = document.getElementById('chatForm');
|
|
this.chatInput = document.getElementById('chatInput');
|
|
this.sendBtn = document.getElementById('sendBtn');
|
|
this.typingIndicator = document.getElementById('typingIndicator');
|
|
|
|
this.init();
|
|
}
|
|
|
|
init() {
|
|
if (!this.isAuthenticated) {
|
|
console.log('User not authenticated, chat disabled');
|
|
return;
|
|
}
|
|
|
|
// Set up form submission
|
|
if (this.chatForm) {
|
|
this.chatForm.addEventListener('submit', (e) => this.handleSubmit(e));
|
|
}
|
|
|
|
// Auto-start session if no active session
|
|
if (!this.sessionId) {
|
|
this.startSession();
|
|
}
|
|
|
|
// Auto-scroll to bottom
|
|
this.scrollToBottom();
|
|
|
|
console.log('Chat interface initialized for agent:', this.agentSlug);
|
|
}
|
|
|
|
async startSession() {
|
|
try {
|
|
const response = await fetch('/agents/api/chat/start/', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': this.getCSRFToken()
|
|
},
|
|
body: JSON.stringify({
|
|
agent_slug: this.agentSlug
|
|
})
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
this.sessionId = data.session_id;
|
|
document.body.setAttribute('data-session-id', this.sessionId);
|
|
console.log('Chat session started:', this.sessionId);
|
|
|
|
// Reload page to show welcome message
|
|
setTimeout(() => {
|
|
window.location.reload();
|
|
}, 500);
|
|
} else {
|
|
this.showError(data.error || 'Failed to start chat session');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error starting chat session:', error);
|
|
this.showError('Failed to start chat session');
|
|
}
|
|
}
|
|
|
|
async handleSubmit(e) {
|
|
e.preventDefault();
|
|
|
|
const message = this.chatInput.value.trim();
|
|
if (!message || !this.sessionId) return;
|
|
|
|
// Disable input and show typing
|
|
this.setInputState(false);
|
|
this.showTyping(true);
|
|
|
|
// Add user message to UI immediately
|
|
this.addMessage('user', message);
|
|
this.chatInput.value = '';
|
|
this.scrollToBottom();
|
|
|
|
try {
|
|
const response = await fetch('/agents/api/chat/send/', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': this.getCSRFToken()
|
|
},
|
|
body: JSON.stringify({
|
|
session_id: this.sessionId,
|
|
message: message
|
|
})
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
// Add agent response
|
|
this.addMessage('agent', data.agent_message.content);
|
|
// Update message count indicators
|
|
if (typeof updateMessageCount === 'function') {
|
|
updateMessageCount();
|
|
}
|
|
} else {
|
|
this.showError(data.error || 'Failed to send message');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error sending message:', error);
|
|
this.addMessage('agent', 'Sorry, I\'m experiencing technical difficulties. Please try again.');
|
|
} finally {
|
|
this.showTyping(false);
|
|
this.setInputState(true);
|
|
this.scrollToBottom();
|
|
}
|
|
}
|
|
|
|
addMessage(type, content) {
|
|
const messageDiv = document.createElement('div');
|
|
messageDiv.className = `message ${type}`;
|
|
|
|
const bubbleDiv = document.createElement('div');
|
|
bubbleDiv.className = 'message-bubble';
|
|
|
|
// Use the shared formatting function
|
|
const formattedContent = formatMarkdownContent(content);
|
|
bubbleDiv.innerHTML = formattedContent;
|
|
|
|
// Add timestamp
|
|
const timeDiv = document.createElement('div');
|
|
timeDiv.className = 'message-time';
|
|
timeDiv.textContent = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
|
|
bubbleDiv.appendChild(timeDiv);
|
|
|
|
messageDiv.appendChild(bubbleDiv);
|
|
|
|
// Remove empty state if exists
|
|
const emptyState = this.chatMessages.querySelector('.chat-empty');
|
|
if (emptyState) {
|
|
emptyState.remove();
|
|
}
|
|
|
|
this.chatMessages.appendChild(messageDiv);
|
|
}
|
|
|
|
setInputState(enabled) {
|
|
if (this.chatInput) this.chatInput.disabled = !enabled;
|
|
if (this.sendBtn) this.sendBtn.disabled = !enabled;
|
|
}
|
|
|
|
showTyping(show) {
|
|
if (this.typingIndicator) {
|
|
this.typingIndicator.classList.toggle('show', show);
|
|
}
|
|
}
|
|
|
|
scrollToBottom() {
|
|
if (this.chatMessages) {
|
|
this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
|
|
}
|
|
}
|
|
|
|
showError(message) {
|
|
this.addMessage('system', `Error: ${message}`);
|
|
this.scrollToBottom();
|
|
}
|
|
|
|
getCSRFToken() {
|
|
const token = document.querySelector('[name=csrfmiddlewaretoken]');
|
|
return token ? token.value : '';
|
|
}
|
|
}
|
|
|
|
// Initialize chat interface when page loads
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
new ChatInterface();
|
|
|
|
// Format existing messages with markdown
|
|
formatExistingMessages();
|
|
|
|
// Clear any old localStorage data for sessions
|
|
const sessionId = document.body.getAttribute('data-session-id');
|
|
if (sessionId) {
|
|
// Clear old session start time cache
|
|
localStorage.removeItem(`session_start_${sessionId}`);
|
|
|
|
// Check if session is expired on page load
|
|
checkExpiredSessionOnLoad(sessionId);
|
|
}
|
|
|
|
// Initialize session indicators updates
|
|
if (document.getElementById('timeRemaining')) {
|
|
updateSessionIndicators();
|
|
setInterval(updateSessionIndicators, 30000); // Update every 30 seconds for better accuracy
|
|
}
|
|
});
|
|
|
|
// Format existing messages on page load
|
|
function formatExistingMessages() {
|
|
const messageBubbles = document.querySelectorAll('.message-bubble[data-raw-content]');
|
|
messageBubbles.forEach(bubble => {
|
|
const rawContent = bubble.getAttribute('data-raw-content');
|
|
if (rawContent) {
|
|
const formattedContent = formatMarkdownContent(rawContent);
|
|
// Only replace the content part, preserve the timestamp
|
|
const timeElement = bubble.querySelector('.message-time');
|
|
const timeHTML = timeElement ? timeElement.outerHTML : '';
|
|
bubble.innerHTML = formattedContent + timeHTML;
|
|
}
|
|
});
|
|
}
|
|
|
|
// Helper function to format markdown content
|
|
function formatMarkdownContent(content) {
|
|
return content
|
|
// Convert headers
|
|
.replace(/^## (.*$)/gim, '<h2>$1</h2>')
|
|
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
|
|
// Convert bold text
|
|
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
|
|
// Convert bullet points
|
|
.replace(/^• (.*$)/gim, '<li>$1</li>')
|
|
.replace(/^- (.*$)/gim, '<li>$1</li>')
|
|
// Convert line breaks
|
|
.replace(/\n/g, '<br>')
|
|
// Wrap consecutive list items in ul tags
|
|
.replace(/(<li>.*?<\/li>(<br>)*)+/gs, '<ul>$&</ul>')
|
|
// Clean up extra breaks around lists
|
|
.replace(/<ul>(<li>.*?<\/li>)(<br>)*(<li>.*?<\/li>)*<\/ul>/gs, function(match) {
|
|
return match.replace(/<br>/g, '');
|
|
});
|
|
}
|
|
|
|
// Download functionality
|
|
function toggleDownloadMenu() {
|
|
const menu = document.getElementById('downloadMenu');
|
|
menu.classList.toggle('show');
|
|
}
|
|
|
|
function downloadChat(format) {
|
|
const sessionId = document.body.getAttribute('data-session-id');
|
|
if (!sessionId) {
|
|
alert('No active session found');
|
|
return;
|
|
}
|
|
|
|
// Hide the dropdown menu
|
|
document.getElementById('downloadMenu').classList.remove('show');
|
|
|
|
// Show loading state
|
|
const downloadBtn = document.getElementById('downloadBtn');
|
|
const originalText = downloadBtn.textContent;
|
|
downloadBtn.textContent = '⏳ Preparing...';
|
|
downloadBtn.disabled = true;
|
|
|
|
// Create download URL
|
|
const downloadUrl = `/agents/api/chat/export/${sessionId}/?format=${format}`;
|
|
|
|
// Create a temporary link and trigger download
|
|
const link = document.createElement('a');
|
|
link.href = downloadUrl;
|
|
link.download = `5whys_chat_${sessionId}.${format}`;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
|
|
// Reset button state after a short delay
|
|
setTimeout(() => {
|
|
downloadBtn.textContent = originalText;
|
|
downloadBtn.disabled = false;
|
|
}, 2000);
|
|
}
|
|
|
|
// Close dropdown when clicking outside
|
|
document.addEventListener('click', function(event) {
|
|
const dropdown = document.querySelector('.download-dropdown');
|
|
const menu = document.getElementById('downloadMenu');
|
|
|
|
if (dropdown && !dropdown.contains(event.target)) {
|
|
menu.classList.remove('show');
|
|
}
|
|
});
|
|
|
|
// Session indicators real-time updates
|
|
function updateSessionIndicators() {
|
|
const sessionId = document.body.getAttribute('data-session-id');
|
|
if (!sessionId) return;
|
|
|
|
// Fetch real session data from server
|
|
fetch(`/agents/api/chat/session/${sessionId}/status/`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'X-CSRFToken': getCSRFToken(),
|
|
'Content-Type': 'application/json'
|
|
}
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success) {
|
|
updateTimeIndicator(data.time_remaining_seconds, data.time_remaining_str);
|
|
updateMessageIndicator(data.message_count, data.message_limit);
|
|
updateWarnings(data.time_percentage, data.message_percentage);
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error fetching session status:', error);
|
|
// Fallback to approximate calculation
|
|
updateSessionIndicatorsApproximate();
|
|
});
|
|
}
|
|
|
|
function updateSessionIndicatorsApproximate() {
|
|
const sessionId = document.body.getAttribute('data-session-id');
|
|
if (!sessionId) return;
|
|
|
|
// Use actual session expiration time from server
|
|
const sessionExpiresStr = document.body.getAttribute('data-session-expires');
|
|
|
|
if (sessionExpiresStr) {
|
|
const sessionExpires = new Date(sessionExpiresStr);
|
|
const now = new Date();
|
|
const timeRemaining = Math.max(0, sessionExpires - now);
|
|
|
|
const minutesRemaining = Math.floor(timeRemaining / (1000 * 60));
|
|
const timeRemainingStr = `${minutesRemaining}m`;
|
|
|
|
const sessionDuration = 30 * 60 * 1000; // 30 minutes in milliseconds
|
|
const timePercentage = Math.max(0, (timeRemaining / sessionDuration) * 100);
|
|
|
|
updateTimeIndicator(timeRemaining / 1000, timeRemainingStr);
|
|
|
|
// For messages, count current user messages
|
|
const messageElements = document.querySelectorAll('.message.user');
|
|
const currentCount = messageElements.length;
|
|
const maxMessages = 20;
|
|
updateMessageIndicator(currentCount, maxMessages);
|
|
|
|
updateWarnings(timePercentage, (currentCount / maxMessages) * 100);
|
|
} else {
|
|
console.warn('No session expiration data available');
|
|
}
|
|
}
|
|
|
|
function updateTimeIndicator(timeRemainingSeconds, timeRemainingStr) {
|
|
const timeElement = document.getElementById('timeRemaining');
|
|
const timeProgressElement = document.getElementById('timeProgress');
|
|
|
|
if (timeElement) {
|
|
timeElement.textContent = timeRemainingStr;
|
|
}
|
|
|
|
if (timeProgressElement) {
|
|
const totalTime = 30 * 60; // 30 minutes in seconds
|
|
const percentage = Math.max(0, (timeRemainingSeconds / totalTime) * 100);
|
|
timeProgressElement.style.width = percentage + '%';
|
|
|
|
// Update color based on time remaining
|
|
if (percentage <= 20) {
|
|
timeProgressElement.style.background = 'linear-gradient(90deg, #ef4444, #dc2626)';
|
|
} else if (percentage <= 40) {
|
|
timeProgressElement.style.background = 'linear-gradient(90deg, #f59e0b, #d97706)';
|
|
} else {
|
|
timeProgressElement.style.background = 'linear-gradient(90deg, #10b981, #059669)';
|
|
}
|
|
}
|
|
}
|
|
|
|
function updateMessageIndicator(currentCount, maxMessages) {
|
|
const messageCountElement = document.getElementById('messageCount');
|
|
const messageProgressElement = document.getElementById('messageProgress');
|
|
|
|
if (messageCountElement) {
|
|
messageCountElement.textContent = `${currentCount}/${maxMessages} used`;
|
|
}
|
|
|
|
if (messageProgressElement) {
|
|
const percentage = (currentCount / maxMessages) * 100;
|
|
messageProgressElement.style.width = percentage + '%';
|
|
|
|
// Update color based on usage
|
|
if (percentage >= 95) {
|
|
messageProgressElement.style.background = 'linear-gradient(90deg, #ef4444, #dc2626)';
|
|
} else if (percentage >= 80) {
|
|
messageProgressElement.style.background = 'linear-gradient(90deg, #f59e0b, #d97706)';
|
|
} else {
|
|
messageProgressElement.style.background = 'linear-gradient(90deg, #3b82f6, #2563eb)';
|
|
}
|
|
}
|
|
}
|
|
|
|
function updateWarnings(timePercentage, messagePercentage) {
|
|
const warningsElement = document.getElementById('sessionWarnings');
|
|
if (warningsElement) {
|
|
let warningHTML = '';
|
|
|
|
if (messagePercentage >= 80) {
|
|
warningHTML += '<div class="warning-item message-warning">⚠️ Approaching message limit!</div>';
|
|
}
|
|
|
|
if (timePercentage <= 20) {
|
|
warningHTML += '<div class="warning-item time-warning">⚠️ Session expires soon!</div>';
|
|
}
|
|
|
|
warningsElement.innerHTML = warningHTML;
|
|
}
|
|
}
|
|
|
|
function getCSRFToken() {
|
|
const token = document.querySelector('[name=csrfmiddlewaretoken]');
|
|
return token ? token.value : '';
|
|
}
|
|
|
|
// Update message count after sending a message
|
|
function updateMessageCount() {
|
|
// Update session indicators to refresh all counters
|
|
updateSessionIndicators();
|
|
}
|
|
|
|
// Handle wallet balance check
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
const userBalance = parseFloat(document.body.getAttribute('data-user-balance') || '0');
|
|
const agentPrice = parseFloat(document.body.getAttribute('data-agent-price') || '0');
|
|
const isAuthenticated = document.body.getAttribute('data-user-authenticated') === 'true';
|
|
|
|
if (isAuthenticated && userBalance < agentPrice) {
|
|
console.log('Insufficient balance for chat session');
|
|
}
|
|
});
|
|
|
|
// Expired Session Detection and Modal Functions
|
|
function checkExpiredSessionOnLoad(sessionId) {
|
|
// Only check if user is authenticated
|
|
const isAuthenticated = document.body.getAttribute('data-user-authenticated') === 'true';
|
|
if (!isAuthenticated) return;
|
|
|
|
// Check session status
|
|
fetch(`/agents/api/chat/session/${sessionId}/status/`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'X-CSRFToken': getCSRFToken(),
|
|
'Content-Type': 'application/json'
|
|
}
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.success && data.is_expired) {
|
|
// Session is expired, show modal
|
|
showExpiredSessionModal();
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error('Error checking session status:', error);
|
|
});
|
|
}
|
|
|
|
function showExpiredSessionModal() {
|
|
const modal = document.getElementById('expiredSessionModal');
|
|
if (modal) {
|
|
modal.style.display = 'flex';
|
|
}
|
|
}
|
|
|
|
function hideExpiredSessionModal() {
|
|
const modal = document.getElementById('expiredSessionModal');
|
|
if (modal) {
|
|
modal.style.display = 'none';
|
|
}
|
|
}
|
|
|
|
async function startNewSessionFromExpired() {
|
|
const agentSlug = document.body.getAttribute('data-agent-slug');
|
|
const userBalance = parseFloat(document.body.getAttribute('data-user-balance') || '0');
|
|
const agentPrice = parseFloat(document.body.getAttribute('data-agent-price') || '0');
|
|
|
|
// Check balance first
|
|
if (userBalance < agentPrice) {
|
|
alert('Insufficient balance. Please top up your wallet.');
|
|
window.location.href = '/wallet/';
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Start new session (this will deduct payment automatically)
|
|
const response = await fetch('/agents/api/chat/start/', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': getCSRFToken()
|
|
},
|
|
body: JSON.stringify({
|
|
agent_slug: agentSlug
|
|
})
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (response.ok) {
|
|
// Success - hide modal and reload page to show new session
|
|
hideExpiredSessionModal();
|
|
window.location.reload();
|
|
} else {
|
|
alert(data.error || 'Failed to start new session');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error starting new session:', error);
|
|
alert('Failed to start new session');
|
|
}
|
|
}
|
|
|
|
function cancelNewSession() {
|
|
hideExpiredSessionModal();
|
|
// Optionally redirect to marketplace or disable chat interface
|
|
window.location.href = '/agents/';
|
|
}
|
|
</script>
|
|
{% endblock %} |