/* ═══════════════════════════════════════════════════════════════════════════ KHIRA — Aurora Engineering Console ───────────────────────────────────────────────────────────────────────── App logic + interaction library (vanilla JS, no deps): · Custom glowing cursor (glow dot + tracer dot) · Sparkle particle canvas (ambient floating dots) · 3D tilt cards (perspective transform on mouse move) · Magnetic buttons (subtle pull toward cursor when nearby) · Ripple on click (Material-style) · Number ticker (spring-physics count up) · Stagger entrance for lists (via CSS class) · Auth tab glow (sliding indicator) · Spring-physics drawer/modal open/close · 8s silent polling, X-Khira-User header, mock fallback · 100% backend-compatible API contract preserved ═══════════════════════════════════════════════════════════════════════════ */ 'use strict'; /* ════════════════════════════════════════════════════════════════════ STATE ════════════════════════════════════════════════════════════════════ */ let currentUser = null; let allTickets = []; let allUsers = []; let allErrors = []; let errorStats = {}; let activeTicketId = null; let currentSection = 'tickets'; let currentErrView = 'table'; let currentScope = 'assigned'; let currentView = 'kanban'; let currentEscalateErrorId = null; let resolveTargetErrorId = null; let completeTargetTicketId = null; let holdTargetTicketId = null; let pollingTimer = null; let notificationsList = []; let lastUnreadCount = 0; let searchQuery = ''; let filterType = ''; let filterPriority = ''; let filterRole = ''; let filterStatus = ''; let createTicketType = 'application'; let errSearchQuery = ''; let errFilterApp = ''; let errFilterSeverity = ''; let errFilterStatus = ''; let linkComposerAttach = null; let createFormLinks = []; let createFormFiles = []; let desktopAlertsEnabled = false; let lastSyncTime = null; let SILENT = false; let USING_MOCK = false; let cursorRAF = null; let cursorX = 0, cursorY = 0; let glowX = 0, glowY = 0; let dotX = 0, dotY = 0; /* ════════════════════════════════════════════════════════════════════ MOCK BACKEND (preserved identical API contract) ════════════════════════════════════════════════════════════════════ */ const MOCK_USERS = [ { username: 'alice', name: 'Alice Walker', role: 'frontend', role_display: 'Frontend Dev', avatar: '👩💻' }, { username: 'bob', name: 'Bob Chen', role: 'backend', role_display: 'Backend Dev', avatar: '👨💻' }, { username: 'charlie', name: 'Charlie Diaz', role: 'tester', role_display: 'QA / Tester', avatar: '🕵️♂️' }, { username: 'admin', name: 'Admin Cole', role: 'lead', role_display: 'Team Lead', avatar: '⚡' } ]; const MOCK_PASSWORDS = { alice: 'alice123', bob: 'bob123', charlie: 'charlie123', admin: 'admin123' }; let MOCK_TICKETS = []; let MOCK_ERRORS = []; let MOCK_NOTIFS = []; let MOCK_TICKET_SEQ = 1; let MOCK_ERROR_SEQ = 1; function seedMockTicketsIfEmpty() { if (MOCK_TICKETS.length) return; MOCK_TICKETS = [ { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Hair Color Changer 500 Error when mask_image is omitted', app: 'Creator Suite Web', version: 'v2.4.1', feature: 'Hair Color Changer', api_key: 'Stable_Diffusion_Hair_Color_Changer', issue_type: 'API Failure / 500 / 400 Error', priority: 'P0', description: 'When a user submits the hair color change request without a mask_image, the backend returns 500 instead of a 400 with a friendly validation message.', assistance: 'Endpoint Debugging · Schema Validation Fix', context: 'curl -X POST /apis/flxk/hair-color-change -H "Content-Type: application/json" -d \'{"prompt":"red hair"}\'\n# 500 Internal Server Error\n# ZeroDivisionError: division by zero: normalized alpha matte has zero total density', status: 'open', assignee: MOCK_USERS[1], reporter: MOCK_USERS[2], created_at: new Date(Date.now() - 86400000).toISOString(), updated_at: new Date(Date.now() - 3600000).toISOString(), remarks: [], links: [{ url: 'https://github.com/khira/creator-suite/issues/142' }], files: [] }, { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Face Swapper UI misaligned on Safari 17', app: 'Creator Suite Web Unified Dashboard', version: 'v2.4.0', feature: 'Face Swapper', api_key: 'Face_Swapper_UI', issue_type: 'UI Layout / Rendering Bug', priority: 'P2', description: 'The face swapper component renders off-center on Safari 17 due to a flex baseline issue.', assistance: 'UI Layout Fix', context: 'Safari 17.0 on macOS 14 — viewport 1440x900', status: 'progress', assignee: MOCK_USERS[0], reporter: MOCK_USERS[2], created_at: new Date(Date.now() - 172800000).toISOString(), updated_at: new Date(Date.now() - 7200000).toISOString(), remarks: [{ author: MOCK_USERS[0], body: 'Investigating — confirmed the bug. Appears related to flex baseline alignment.', created_at: new Date(Date.now() - 7200000).toISOString() }], links: [{ url: 'https://github.com/khira/creator-suite/pull/142' }], files: [] }, { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Batch Inpaint queue stalls when GPU memory fragmented', app: 'FastAPI Backend', version: 'v2.3.5', feature: 'Batch Inpaint', api_key: 'Batch_Inpaint_Queue', issue_type: 'Performance / Latency', priority: 'P1', description: 'After ~3 hours of continuous batching, the queue stops draining. Likely torch.cuda memory fragmentation.', assistance: 'GPU Memory Profiling', context: 'CUDAOutOfMemory: try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True', status: 'hold', assignee: MOCK_USERS[1], reporter: MOCK_USERS[3], created_at: new Date(Date.now() - 259200000).toISOString(), updated_at: new Date(Date.now() - 86400000).toISOString(), remarks: [{ author: null, system: true, body: 'Ticket placed on hold: Waiting on GPU cluster node provisioning', created_at: new Date(Date.now() - 86400000).toISOString() }], links: [], files: [], hold_reason: 'Waiting on GPU cluster node provisioning' }, { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'general', title: 'Configure Redis cache cluster node for telemetry persistence', general_category: 'DevOps & Infrastructure', department: 'Core Infrastructure', app: 'General / Non-App', feature: 'DevOps & Infrastructure', priority: 'P1', description: 'Provision Redis v7.2 cluster node in Oregon region and connect to telemetry pipeline.', assistance: 'Cluster Configuration & IAM Security Group setup', context: 'AWS ElastiCache Redis Cluster · VPC subnet-08123\nRequires TLS in-transit encryption enabled.', status: 'open', assignee: MOCK_USERS[1], reporter: MOCK_USERS[3], created_at: new Date(Date.now() - 48000000).toISOString(), updated_at: new Date(Date.now() - 12000000).toISOString(), remarks: [], links: [{ url: 'https://aws.amazon.com/elasticache/' }], files: [] }, { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'general', title: 'Provision S3 staging bucket write credentials for QA team', general_category: 'Access & Permissions', department: 'Security & Access', app: 'General / Non-App', feature: 'Access & Permissions', priority: 'P2', description: 'Generate IAM read/write policy for s3://cre-staging-artifacts for regression testing suite.', assistance: 'IAM Policy & Access Key Creation', context: 'Bucket: s3://cre-staging-artifacts/qa-test-runs/\nExpiration: 90 days', status: 'progress', assignee: MOCK_USERS[0], reporter: MOCK_USERS[2], created_at: new Date(Date.now() - 72000000).toISOString(), updated_at: new Date(Date.now() - 18000000).toISOString(), remarks: [], links: [], files: [] }, { id: `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`, ticket_type: 'application', title: 'Auth token refresh race on tab focus', app: 'Creator Suite Web', version: 'v2.4.1', feature: 'Auth', api_key: 'Auth_Token_Refresh', issue_type: 'Auth / Permission', priority: 'P3', description: 'When two tabs are open and one refreshes the token, the other briefly shows "Unauthorized" until next sync.', assistance: 'Token Sync Fix', context: '', status: 'completed', assignee: MOCK_USERS[0], reporter: MOCK_USERS[3], created_at: new Date(Date.now() - 432000000).toISOString(), updated_at: new Date(Date.now() - 172800000).toISOString(), remarks: [{ author: MOCK_USERS[0], body: 'Added BroadcastChannel-based token sync. Verified across tabs.', created_at: new Date(Date.now() - 172800000).toISOString() }, { author: null, system: true, body: 'Ticket marked as completed: Fixed via BroadcastChannel sync, merged PR #142', created_at: new Date(Date.now() - 172800000).toISOString() }], links: [{ url: 'https://github.com/khira/creator-suite/pull/142' }], files: [], resolution: 'Fixed via BroadcastChannel sync, merged PR #142' } ]; } function seedMockErrorsIfEmpty() { if (MOCK_ERRORS.length) return; MOCK_ERRORS = [ { id: `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`, app: 'FastAPI Backend', environment: 'Production', service: 'Hair Color Changer', endpoint: 'POST /apis/flxk/hair-color-change', exception_type: 'ZeroDivisionError', severity: 'HIGH', message: 'division by zero: normalized alpha matte has zero total density', stack_trace: 'Traceback (most recent call last):\n File "/app/api/hair_color.py", line 142, in hair_color_change\n alpha = normalize_alpha(mask_image)\n File "/app/utils/alpha.py", line 28, in normalize_alpha\n return alpha / alpha.sum()\nZeroDivisionError: division by zero: normalized alpha matte has zero total density', payload: '{"api_key": "Stable_Diffusion_Hair_Color_Changer", "model": "flux-fill", "prompt": "red hair", "mask_image": null}', status: 'unresolved', events: 7, first_seen: new Date(Date.now() - 86400000).toISOString(), last_seen: new Date(Date.now() - 3600000).toISOString(), reported_by: 'telemetry', escalated_ticket_id: null, resolution_notes: null }, { id: `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`, app: 'Dashboard Client', environment: 'Production', service: 'Unified Dashboard', endpoint: 'GET /khira/api/stats', exception_type: 'TypeError', severity: 'MEDIUM', message: "Cannot read properties of undefined (reading 'length')", stack_trace: 'TypeError: Cannot read properties of undefined (reading \'length\')\n at renderKanban (app.js:318:42)\n at refreshData (app.js:201:9)', payload: '{"scope": "assigned"}', status: 'unresolved', events: 3, first_seen: new Date(Date.now() - 172800000).toISOString(), last_seen: new Date(Date.now() - 7200000).toISOString(), reported_by: 'telemetry', escalated_ticket_id: null, resolution_notes: null }, { id: `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`, app: 'Batch Inpaint', environment: 'Production', service: 'Batch Inpaint Queue', endpoint: 'POST /apis/batch/inpaint', exception_type: 'CUDAOutOfMemory', severity: 'CRITICAL', message: 'CUDA out of memory. Tried to allocate 2.00 GiB. GPU 0 has a total capacity of 23.71 GiB of which 1.23 GiB is free.', stack_trace: 'torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB.', payload: '{"batch_size": 16, "model": "flux-fill"}', status: 'resolved', events: 2, first_seen: new Date(Date.now() - 259200000).toISOString(), last_seen: new Date(Date.now() - 86400000).toISOString(), reported_by: 'telemetry', escalated_ticket_id: 'KHR-003', resolution_notes: 'Reduced default batch_size from 16 to 8' } ]; } function mockResponse(path, options) { const method = (options.method || 'GET').toUpperCase(); const body = options.body && options.body.startsWith('{') ? JSON.parse(options.body) : {}; const headers = options.headers || {}; if (path === '/khira/api/auth/me') { const u = headers['X-Khira-User'] && MOCK_USERS.find(x => x.username === headers['X-Khira-User']); return u ? { authenticated: true, user: u } : { authenticated: false }; } if (path === '/khira/api/auth/login') { const u = MOCK_USERS.find(x => x.username === body.username); return (u && MOCK_PASSWORDS[body.username] === body.password) ? { user: u } : { error: 'Invalid credentials' }; } if (path === '/khira/api/auth/register') { if (MOCK_USERS.find(x => x.username === body.username)) return { error: 'Username taken' }; const roleDisplay = { frontend: 'Frontend Dev', backend: 'Backend Dev', tester: 'QA / Tester', lead: 'Team Lead', engineer: 'Engineer', security: 'Security' }[body.role] || body.role; const u = { username: body.username, name: body.name, role: body.role, role_display: roleDisplay, avatar: '🚀' }; MOCK_USERS.push(u); MOCK_PASSWORDS[body.username] = body.password; return { user: u }; } if (path === '/khira/api/auth/logout') return { ok: true }; if (path === '/khira/api/auth/profile') { const u = MOCK_USERS.find(x => x.username === currentUser.username); if (u) { if (body.name) u.name = body.name; if (body.role) { u.role = body.role; u.role_display = { frontend: 'Frontend Dev', backend: 'Backend Dev', tester: 'QA / Tester', lead: 'Team Lead', engineer: 'Engineer', security: 'Security' }[body.role] || body.role; } if (body.avatar) u.avatar = body.avatar; return { user: u }; } return { error: 'Not found' }; } if (path === '/khira/api/users') return { users: MOCK_USERS }; if (path === '/khira/api/tickets' && method === 'GET') { seedMockTicketsIfEmpty(); return { tickets: MOCK_TICKETS }; } if (path === '/khira/api/tickets' && method === 'POST') { const id = `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`; const reporter = currentUser ? { username: currentUser.username, name: currentUser.name, role_display: currentUser.role_display, avatar: currentUser.avatar } : null; const assignee = MOCK_USERS.find(u => u.username === body.assignee_username); const isGen = (body.ticket_type === 'general'); const t = { id, ticket_type: isGen ? 'general' : 'application', general_category: body.general_category || '', department: body.department || '', title: body.title, app: body.app || (isGen ? 'General / Non-App' : '—'), version: body.version || (isGen ? '—' : ''), feature: body.feature || body.general_category || '', api_key: body.api_key || '', issue_type: body.issue_type || (isGen ? 'General Task' : ''), priority: body.priority, description: body.description, assistance: body.assistance, context: body.context || '', status: 'open', assignee, reporter, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), remarks: [], links: body.links || [], files: [] }; MOCK_TICKETS.unshift(t); return { ticket: t }; } if (path === '/khira/api/stats') { seedMockTicketsIfEmpty(); const u = headers['X-Khira-User']; const mine = MOCK_TICKETS.filter(t => t.assignee && t.assignee.username === u); const reported = MOCK_TICKETS.filter(t => t.reporter && t.reporter.username === u); return { total: MOCK_TICKETS.length, my_assigned: mine.filter(t => t.status === 'open' || t.status === 'progress').length, my_created: reported.length, on_hold: MOCK_TICKETS.filter(t => t.status === 'hold').length, completed: MOCK_TICKETS.filter(t => t.status === 'completed').length, my_held: mine.filter(t => t.status === 'hold').length, my_completed: mine.filter(t => t.status === 'completed').length }; } const tm = path.match(/^\/khira\/api\/tickets\/([^/]+)\/(.+)$/); if (tm) { const [, tid, action] = tm; const t = MOCK_TICKETS.find(x => x.id === tid); if (!t) return { error: 'Not found' }; if (action === 'links' && method === 'GET') return { links: t.links || [] }; if (action === 'attachments' && method === 'GET') return { files: t.files || [] }; if (action === 'remarks' && method === 'POST') { const r = { author: currentUser ? { username: currentUser.username, name: currentUser.name, avatar: currentUser.avatar, role_display: currentUser.role_display } : null, body: body.body, links: body.links || [], created_at: new Date().toISOString() }; t.remarks = t.remarks || []; t.remarks.unshift(r); t.updated_at = new Date().toISOString(); return { remark: r }; } if (action === 'links' && method === 'POST') { t.links = t.links || []; t.links.push({ url: body.url, added_at: new Date().toISOString() }); return { link: { url: body.url } }; } if (action === 'priority') { t.priority = body.priority; t.updated_at = new Date().toISOString(); return { ticket: t }; } if (action === 'reassign') { t.assignee = MOCK_USERS.find(u => u.username === body.assignee_username) || t.assignee; t.updated_at = new Date().toISOString(); return { ticket: t }; } if (action === 'hold') { t.status = 'hold'; t.hold_reason = body.reason; t.remarks = t.remarks || []; t.remarks.unshift({ author: null, system: true, body: `Ticket placed on hold: ${body.reason}`, created_at: new Date().toISOString() }); t.updated_at = new Date().toISOString(); return { ticket: t }; } if (action === 'complete') { t.status = 'completed'; t.resolution = body.resolution; t.remarks = t.remarks || []; t.remarks.unshift({ author: null, system: true, body: `Ticket marked as completed: ${body.resolution}`, created_at: new Date().toISOString() }); t.updated_at = new Date().toISOString(); return { ticket: t }; } if (action === 'resume') { t.status = 'progress'; t.remarks = t.remarks || []; t.remarks.unshift({ author: null, system: true, body: 'Ticket resumed from hold', created_at: new Date().toISOString() }); t.updated_at = new Date().toISOString(); return { ticket: t }; } } if (path === '/khira/api/notifications') return { notifications: MOCK_NOTIFS }; if (path === '/khira/api/notifications/read') { MOCK_NOTIFS.forEach(n => n.read = true); return { ok: true }; } if (path === '/khira/api/errors' && method === 'GET') { seedMockErrorsIfEmpty(); return { errors: MOCK_ERRORS }; } if (path === '/khira/api/errors' && method === 'POST') { const id = `ERR-${String(MOCK_ERROR_SEQ++).padStart(3, '0')}`; const e = { id, app: body.app, environment: body.environment, service: body.service, endpoint: body.endpoint || '', exception_type: body.exception_type, severity: body.severity, message: body.message, stack_trace: body.stack_trace || '', payload: body.payload || '', status: 'unresolved', events: 1, first_seen: new Date().toISOString(), last_seen: new Date().toISOString(), reported_by: currentUser ? currentUser.username : null, escalated_ticket_id: null, resolution_notes: null }; MOCK_ERRORS.unshift(e); return { error: e }; } if (path === '/khira/api/errors/stats') { seedMockErrorsIfEmpty(); return { total: MOCK_ERRORS.length, unresolved: MOCK_ERRORS.filter(e => e.status === 'unresolved').length, resolved: MOCK_ERRORS.filter(e => e.status === 'resolved').length, escalated: MOCK_ERRORS.filter(e => e.escalated_ticket_id).length }; } const em = path.match(/^\/khira\/api\/errors\/([^/]+)\/(.+)$/); if (em) { const [, eid, action] = em; const e = MOCK_ERRORS.find(x => x.id === eid); if (!e) return { error: 'Not found' }; if (action === 'status') { e.status = body.status; e.resolution_notes = body.resolution_notes; e.resolved_at = new Date().toISOString(); return { error: e }; } if (action === 'escalate') { const id = `KHR-${String(MOCK_TICKET_SEQ++).padStart(3, '0')}`; const assignee = MOCK_USERS.find(u => u.username === body.assignee_username); const t = { id, title: body.title, app: e.app, version: '—', feature: e.service, api_key: e.endpoint, issue_type: 'API Failure / 500 / 400 Error', priority: body.priority, description: e.message, assistance: body.notes || 'Escalated from error telemetry', context: e.stack_trace || e.payload || '', status: 'open', assignee, reporter: { username: 'system', name: 'Khira Telemetry', role_display: 'System', avatar: '⚡' }, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), remarks: [], links: [], files: [], escalated_from_error: e.id }; MOCK_TICKETS.unshift(t); e.escalated_ticket_id = id; e.status = 'escalated'; return { ticket: t }; } } return { error: 'Mock endpoint not found: ' + path }; } async function khiraFetch(path, options = {}) { try { const res = await fetch(path, options); const ct = res.headers.get('content-type') || ''; if (!res.ok || !ct.includes('application/json')) { // Not a real API JSON response (might be HTML fallback from static server) throw new Error('Not JSON API'); } USING_MOCK = false; return await res.json(); } catch (err) { USING_MOCK = true; return mockResponse(path, options); } } async function khiraSend(path, options) { try { const res = await fetch(path, options); const ct = res.headers.get('content-type') || ''; if (!res.ok || !ct.includes('application/json')) { throw new Error('Not JSON API'); } USING_MOCK = false; return await res.json(); } catch (err) { USING_MOCK = true; return mockResponse(path, options); } } /* ════════════════════════════════════════════════════════════════════ INTERACTION LIBRARY — vanilla JS implementations ════════════════════════════════════════════════════════════════════ */ /* ─── Custom cursor (glow + tracer dot) ───────────────────────────── */ function initCustomCursor() { const glow = document.getElementById('cursorGlow'); const dot = document.getElementById('cursorDot'); if (!glow || !dot) return; if (window.matchMedia('(hover: none) and (pointer: coarse)').matches) return; document.addEventListener('mousemove', (e) => { cursorX = e.clientX; cursorY = e.clientY; if (!cursorRAF) cursorRAF = requestAnimationFrame(animateCursor); }); document.addEventListener('mouseover', (e) => { if (e.target.closest('button, a, .kanban-card, .stat-tile, .err-card, [onclick], .persona-btn, .nav-item, input, select, textarea, label')) { glow.classList.add('is-hover'); } }); document.addEventListener('mouseout', (e) => { if (e.target.closest('button, a, .kanban-card, .stat-tile, .err-card, [onclick], .persona-btn, .nav-item, input, select, textarea, label')) { glow.classList.remove('is-hover'); } }); function animateCursor() { // Glow lags slightly (spring follow) glowX += (cursorX - glowX) * 0.18; glowY += (cursorY - glowY) * 0.18; // Dot follows tightly dotX += (cursorX - dotX) * 0.45; dotY += (cursorY - dotY) * 0.45; glow.style.transform = `translate(${glowX}px, ${glowY}px) translate(-50%, -50%)`; dot.style.transform = `translate(${dotX}px, ${dotY}px) translate(-50%, -50%)`; if (Math.abs(cursorX - glowX) > 0.1 || Math.abs(cursorY - glowY) > 0.1 || Math.abs(cursorX - dotX) > 0.1 || Math.abs(cursorY - dotY) > 0.1) { cursorRAF = requestAnimationFrame(animateCursor); } else { cursorRAF = null; } } // Kick off animation loop if (!cursorRAF) cursorRAF = requestAnimationFrame(animateCursor); } /* ─── Sparkle canvas (ambient floating particles) ─────────────────── */ function initSparkleCanvas() { const canvas = document.getElementById('sparkleCanvas'); if (!canvas) return; const ctx = canvas.getContext('2d'); let particles = []; let raf; function resize() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; } resize(); window.addEventListener('resize', resize); function spawnParticle() { return { x: Math.random() * canvas.width, y: Math.random() * canvas.height, size: Math.random() * 1.8 + 0.5, vx: (Math.random() - 0.5) * 0.18, vy: -Math.random() * 0.25 - 0.05, opacity: Math.random() * 0.6 + 0.2, color: ['#10B981', '#06B6D4', '#8B5CF6', '#EC4899'][Math.floor(Math.random() * 4)] }; } for (let i = 0; i < 70; i++) particles.push(spawnParticle()); function tick() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach((p, i) => { p.x += p.vx; p.y += p.vy; if (p.y < -10) { p.y = canvas.height + 10; p.x = Math.random() * canvas.width; } if (p.x < -10) p.x = canvas.width + 10; if (p.x > canvas.width + 10) p.x = -10; ctx.beginPath(); ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2); ctx.fillStyle = p.color + Math.floor(p.opacity * 255).toString(16).padStart(2, '0'); ctx.shadowColor = p.color; ctx.shadowBlur = 8; ctx.fill(); }); raf = requestAnimationFrame(tick); } tick(); } /* ─── 3D Tilt cards ─────────────────────────────────────────────── */ function initTilt() { document.querySelectorAll('.tilt').forEach(el => { let raf = null; let rect = null; el.addEventListener('mouseenter', () => { rect = el.getBoundingClientRect(); el.style.transition = 'transform 200ms ease-out'; }); el.addEventListener('mousemove', (e) => { if (!rect) rect = el.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; const cx = rect.width / 2; const cy = rect.height / 2; const rx = ((y - cy) / cy) * -8; // max 8deg const ry = ((x - cx) / cx) * 8; if (raf) cancelAnimationFrame(raf); raf = requestAnimationFrame(() => { el.style.transform = `perspective(800px) rotateX(${rx}deg) rotateY(${ry}deg) translateY(-3px)`; }); }); el.addEventListener('mouseleave', () => { el.style.transition = 'transform 400ms cubic-bezier(0.34, 1.56, 0.64, 1)'; el.style.transform = ''; rect = null; }); }); } /* ─── Magnetic buttons (subtle pull toward cursor) ─────────────────── */ function initMagnetic() { if (window.matchMedia('(hover: none) and (pointer: coarse)').matches) return; document.querySelectorAll('.magnetic').forEach(el => { let raf = null; el.addEventListener('mousemove', (e) => { const rect = el.getBoundingClientRect(); const x = e.clientX - (rect.left + rect.width / 2); const y = e.clientY - (rect.top + rect.height / 2); if (raf) cancelAnimationFrame(raf); raf = requestAnimationFrame(() => { el.style.transition = 'transform 200ms cubic-bezier(0.34, 1.56, 0.64, 1)'; el.style.transform = `translate(${x * 0.18}px, ${y * 0.18}px)`; }); }); el.addEventListener('mouseleave', () => { el.style.transition = 'transform 400ms cubic-bezier(0.34, 1.56, 0.64, 1)'; el.style.transform = ''; }); }); } /* ─── Ripple on click ────────────────────────────────────────────── */ function initRipple() { document.addEventListener('click', (e) => { const target = e.target.closest('.btn-aurora, .btn-ghost, .persona-btn, .nav-item, .scope-tab, .view-switch-btn'); if (!target) return; const rect = target.getBoundingClientRect(); const size = Math.max(rect.width, rect.height); const ripple = document.createElement('span'); ripple.className = 'ripple'; ripple.style.width = ripple.style.height = size + 'px'; ripple.style.left = (e.clientX - rect.left - size / 2) + 'px'; ripple.style.top = (e.clientY - rect.top - size / 2) + 'px'; // Ensure parent is positioned if (getComputedStyle(target).position === 'static') target.style.position = 'relative'; target.style.overflow = 'hidden'; target.appendChild(ripple); setTimeout(() => ripple.remove(), 600); }); } /* ─── Number ticker (spring physics count up) ───────────────────── */ function tickNumber(el, target) { if (!el) return; if (SILENT) { el.textContent = target; return; } const start = parseInt(String(el.textContent).replace(/[^\d-]/g, ''), 10) || 0; if (start === target) { el.textContent = target; return; } const t0 = performance.now(); const dur = 700; function step(t) { const p = Math.min(1, (t - t0) / dur); // Spring out: cubic ease-out with slight overshoot const eased = 1 - Math.pow(1 - p, 4); const val = Math.round(start + (target - start) * eased); el.textContent = val; if (p < 1) requestAnimationFrame(step); else el.textContent = target; } requestAnimationFrame(step); } /* ─── Theme ──────────────────────────────────────────────────────── */ function applyTheme(theme) { document.documentElement.setAttribute('data-theme', theme); try { localStorage.setItem('khira_theme', theme); } catch (e) {} const meta = document.getElementById('metaThemeColor'); if (meta) meta.setAttribute('content', theme === 'light' ? '#F8FAFC' : '#050816'); const icon = document.getElementById('themeIcon'); const label = document.getElementById('themeLabel'); if (icon) icon.className = theme === 'light' ? 'fa-solid fa-moon' : 'fa-solid fa-sun'; if (label) label.textContent = theme === 'light' ? 'Dark' : 'Light'; } function toggleTheme() { const next = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light'; applyTheme(next); } /* ─── Sync status ────────────────────────────────────────────────── */ function markSynced() { lastSyncTime = Date.now(); updateSyncLabel(); } function updateSyncLabel() { const dot = document.getElementById('syncDot'); const text = document.getElementById('syncText'); if (!text) return; if (!lastSyncTime) { text.textContent = 'Connecting…'; if (dot) dot.className = 'sync-dot connecting'; return; } if (dot) dot.className = 'sync-dot live'; const sec = Math.floor((Date.now() - lastSyncTime) / 1000); if (sec < 4) text.textContent = 'Live · synced just now'; else if (sec < 60) text.textContent = `Live · ${sec}s ago`; else text.textContent = `Live · ${Math.floor(sec / 60)}m ago`; } /* ════════════════════════════════════════════════════════════════════ BOOT ════════════════════════════════════════════════════════════════════ */ document.addEventListener('DOMContentLoaded', async () => { let theme = 'dark'; try { theme = localStorage.getItem('khira_theme') || 'dark'; } catch (e) {} applyTheme(theme); setInterval(updateSyncLabel, 5000); document.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); focusSearch(); } if (e.key === 'Escape') closeEverything(); }); const remarkTa = document.getElementById('remarkText'); if (remarkTa) { remarkTa.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); submitRemark(); } }); } document.addEventListener('click', (e) => { const dd = document.getElementById('notifDropdown'); const btn = document.querySelector('.notif-btn'); if (dd && dd.classList.contains('active') && !dd.contains(e.target) && !btn.contains(e.target)) { dd.classList.remove('active'); } }); /* Init interaction library */ initCustomCursor(); initSparkleCanvas(); initTilt(); initMagnetic(); initRipple(); await checkAuthStatus(); await loadTeamUsers(); await refreshData(); initAlertsToggle(); pollingTimer = setInterval(async () => { if (currentUser) await refreshData(true); }, 8000); }); /* ════════════════════════════════════════════════════════════════════ AUTH ════════════════════════════════════════════════════════════════════ */ async function checkAuthStatus() { try { const headers = {}; const stored = localStorage.getItem('khira_active_user'); if (stored) headers['X-Khira-User'] = stored; const data = await khiraFetch('/khira/api/auth/me', { headers }); if (data.authenticated && data.user) { currentUser = data.user; localStorage.setItem('khira_active_user', currentUser.username); updateUserUI(); showApp(); } else { currentUser = null; showAuth(); } } catch (err) { showAuth(); } } function showApp() { document.getElementById('authScreen').hidden = true; document.getElementById('appShell').hidden = false; initTilt(); initMagnetic(); } function showAuth() { document.getElementById('authScreen').hidden = false; document.getElementById('appShell').hidden = true; } function updateUserUI() { if (!currentUser) return; document.getElementById('chipAvatar').textContent = currentUser.avatar || '👤'; document.getElementById('chipName').textContent = currentUser.name; document.getElementById('chipRole').textContent = currentUser.role_display; document.getElementById('welcomeAvatar').textContent = currentUser.avatar || '👤'; document.getElementById('welcomeTitle').textContent = `${getGreeting()}, ${currentUser.name}`; document.getElementById('welcomeRole').innerHTML = ` ${currentUser.role_display}`; document.getElementById('createFormReporterName').textContent = currentUser.name; document.getElementById('createFormReporterRole').textContent = currentUser.role_display; } function getGreeting() { const h = new Date().getHours(); if (h < 5) return 'Burning the midnight oil'; if (h < 12) return 'Good morning'; if (h < 17) return 'Good afternoon'; if (h < 21) return 'Good evening'; return 'Working late'; } function switchAuthTab(tab) { const loginTab = document.getElementById('authTabLogin'); const regTab = document.getElementById('authTabRegister'); const loginForm = document.getElementById('authLoginForm'); const regForm = document.getElementById('authRegisterForm'); const glow = document.getElementById('authTabGlow'); if (tab === 'login') { loginTab.classList.add('active'); regTab.classList.remove('active'); loginForm.style.display = 'flex'; regForm.style.display = 'none'; if (glow) glow.classList.remove('right'); } else { regTab.classList.add('active'); loginTab.classList.remove('active'); regForm.style.display = 'flex'; loginForm.style.display = 'none'; if (glow) glow.classList.add('right'); } } async function handleLoginSubmit(e) { e.preventDefault(); const btn = document.getElementById('loginSubmitBtn'); const u = document.getElementById('loginUsername').value.trim(); const p = document.getElementById('loginPassword').value; if (!u || !p) return; setLoading(btn, true); try { const data = await khiraSend('/khira/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: u, password: p }) }); if (data.user) { currentUser = data.user; localStorage.setItem('khira_active_user', currentUser.username); updateUserUI(); showApp(); showToast(`Signed in as ${currentUser.name}`, 'success'); await loadTeamUsers(); await refreshData(); } else { showToast(data.error || 'Invalid credentials', 'error'); } } catch (err) { showToast('Failed to sign in', 'error'); } finally { setLoading(btn, false); } } async function handleRegisterSubmit(e) { e.preventDefault(); const name = document.getElementById('regName').value.trim(); const username = document.getElementById('regUsername').value.trim(); const role = document.getElementById('regRole').value; const password = document.getElementById('regPassword').value; if (!name || !username || !password) return; try { const data = await khiraSend('/khira/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, username, role, password }) }); if (data.user) { currentUser = data.user; localStorage.setItem('khira_active_user', currentUser.username); updateUserUI(); showApp(); showToast(`Welcome, ${currentUser.name}`, 'success'); await loadTeamUsers(); await refreshData(); } else { showToast(data.error || 'Registration failed', 'error'); } } catch (err) { showToast('Registration error', 'error'); } } async function quickLoginAs(persona) { document.getElementById('loginUsername').value = persona; document.getElementById('loginPassword').value = (MOCK_PASSWORDS[persona] || persona + '123'); await handleLoginSubmit(new Event('submit')); } async function handleLogout() { try { await khiraSend('/khira/api/auth/logout', { method: 'POST' }); } catch (e) {} localStorage.removeItem('khira_active_user'); currentUser = null; closeProfileModal(); showAuth(); showToast('Signed out', 'info'); } /* ════════════════════════════════════════════════════════════════════ TEAM USERS ════════════════════════════════════════════════════════════════════ */ async function loadTeamUsers() { try { const data = await khiraFetch('/khira/api/users'); allUsers = data.users || []; populateAssignees(); } catch (err) { console.error('Failed loading users:', err); } } function populateAssignees() { const opts = allUsers.map(u => ``).join(''); const c = document.getElementById('createAssignee'); const d = document.getElementById('drawerAssigneeSelect'); const e = document.getElementById('escalateAssignee'); if (c) c.innerHTML = '' + opts; if (d) d.innerHTML = '' + opts; if (e) e.innerHTML = '' + opts; } /* ════════════════════════════════════════════════════════════════════ DATA REFRESH & STATS ════════════════════════════════════════════════════════════════════ */ async function refreshData(silent = false) { if (!currentUser) return; SILENT = !!silent; try { const headers = { 'X-Khira-User': currentUser.username }; const data = await khiraFetch('/khira/api/tickets', { headers }); allTickets = data.tickets || []; const stats = await khiraFetch('/khira/api/stats', { headers }); updateStatsUI(stats); await refreshNotifications(); await loadErrors(true); if (currentSection === 'tickets') renderCurrentView(); else renderErrors(); markSynced(); } catch (err) { if (!silent) console.error('Refresh failed:', err); } finally { SILENT = false; } } function updateStatsUI(s) { tickNumber(document.getElementById('statAssigned'), s.my_assigned || 0); tickNumber(document.getElementById('statCreated'), s.my_created || 0); tickNumber(document.getElementById('statHold'), s.on_hold || 0); tickNumber(document.getElementById('statCompleted'), s.completed || 0); setText('scopeAssigned', s.my_assigned || 0); setText('scopeReported', s.my_created || 0); setText('scopeAll', s.total || 0); setText('navCountTickets', s.total || allTickets.length || 0); tickNumber(document.getElementById('wlActive'), s.my_assigned || 0); tickNumber(document.getElementById('wlHold'), s.my_held || 0); tickNumber(document.getElementById('wlDone'), s.my_completed || 0); tickNumber(document.getElementById('wlTotal'), s.total || 0); tickNumber(document.getElementById('profStatAssigned'), s.my_assigned || 0); tickNumber(document.getElementById('profStatHeld'), s.my_held || 0); tickNumber(document.getElementById('profStatDone'), s.my_completed || 0); const sum = document.getElementById('welcomeSummary'); if (sum) sum.textContent = `You have ${s.my_assigned || 0} active assigned tasks and ${s.my_held || 0} tickets on hold.`; } function setText(id, val) { const el = document.getElementById(id); if (el) el.textContent = val; } /* ════════════════════════════════════════════════════════════════════ SECTION / SCOPE / FILTERS ════════════════════════════════════════════════════════════════════ */ function switchSection(section) { currentSection = section; document.getElementById('navTickets').classList.toggle('active', section === 'tickets'); document.getElementById('navErrors').classList.toggle('active', section === 'errors'); document.getElementById('viewTickets').hidden = section !== 'tickets'; document.getElementById('viewErrors').hidden = section !== 'errors'; document.getElementById('ctaTickets').style.display = section === 'tickets' ? 'inline-flex' : 'none'; document.getElementById('ctaErrors').style.display = section === 'errors' ? 'inline-flex' : 'none'; if (section === 'tickets') { document.getElementById('crumbTitle').textContent = 'Tickets & Tasks'; document.getElementById('crumbSub').textContent = 'Engineering backlog'; renderCurrentView(); } else { document.getElementById('crumbTitle').textContent = 'Error Tracking'; document.getElementById('crumbSub').textContent = 'Runtime telemetry'; renderErrors(); } closeMobileSidebar(); } function openMobileSidebar() { document.getElementById('sidebar').classList.add('open'); document.getElementById('sidebarBackdrop').classList.add('active'); } function closeMobileSidebar() { const sb = document.getElementById('sidebar'); const bd = document.getElementById('sidebarBackdrop'); if (sb) sb.classList.remove('open'); if (bd) bd.classList.remove('active'); } function filterBySidebarWorkload(key) { if (currentSection !== 'tickets') { switchSection('tickets'); } if (key === 'active') { currentScope = 'assigned'; filterStatus = ''; const fs = document.getElementById('filterStatus'); if (fs) fs.value = ''; } else if (key === 'hold') { currentScope = 'assigned'; filterStatus = 'hold'; const fs = document.getElementById('filterStatus'); if (fs) fs.value = 'hold'; } else if (key === 'completed') { currentScope = 'assigned'; filterStatus = 'completed'; const fs = document.getElementById('filterStatus'); if (fs) fs.value = 'completed'; } else if (key === 'total') { currentScope = 'all'; filterStatus = ''; filterType = ''; filterPriority = ''; filterRole = ''; searchQuery = ''; ['filterType', 'filterPriority', 'filterRole', 'filterStatus', 'searchInput'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; }); } document.querySelectorAll('.scope-tab').forEach(t => t.classList.toggle('active', t.dataset.scope === currentScope)); updateSidebarActiveButtons(); renderCurrentView(); } function updateSidebarActiveButtons() { const btns = ['wlBtnActive', 'wlBtnHold', 'wlBtnDone', 'wlBtnTotal']; btns.forEach(id => { const el = document.getElementById(id); if (el) el.classList.remove('active'); }); if (currentScope === 'all' && !filterStatus && !filterPriority && !filterType && !filterRole && !searchQuery) { const el = document.getElementById('wlBtnTotal'); if (el) el.classList.add('active'); } else if (currentScope === 'assigned') { if (!filterStatus) { const el = document.getElementById('wlBtnActive'); if (el) el.classList.add('active'); } else if (filterStatus === 'hold') { const el = document.getElementById('wlBtnHold'); if (el) el.classList.add('active'); } else if (filterStatus === 'completed') { const el = document.getElementById('wlBtnDone'); if (el) el.classList.add('active'); } } } function switchScope(scope) { currentScope = scope; document.querySelectorAll('.scope-tab').forEach(t => t.classList.toggle('active', t.dataset.scope === scope)); updateSidebarActiveButtons(); renderCurrentView(); } function onSearchInput(v) { searchQuery = v.toLowerCase(); renderCurrentView(); } function onFilterChange(type, val) { if (type === 'type') { filterType = val; const el = document.getElementById('filterType'); if (el && el.value !== val) el.value = val; } if (type === 'priority') { filterPriority = val; const el = document.getElementById('filterPriority'); if (el && el.value !== val) el.value = val; } if (type === 'role') { filterRole = val; const el = document.getElementById('filterRole'); if (el && el.value !== val) el.value = val; } if (type === 'status') { filterStatus = val; const el = document.getElementById('filterStatus'); if (el && el.value !== val) el.value = val; } updateSidebarActiveButtons(); renderCurrentView(); } function focusSearch() { const el = currentSection === 'tickets' ? document.getElementById('searchInput') : document.getElementById('errSearchInput'); if (el) { el.focus(); el.select(); } } function getFilteredTickets() { return allTickets.filter(t => { if (currentScope === 'assigned' && (!t.assignee || t.assignee.username !== currentUser.username) && (t.assigned_to !== currentUser.username)) return false; if (currentScope === 'reported' && (!t.reporter || t.reporter.username !== currentUser.username) && (t.created_by !== currentUser.username)) return false; if (filterType && (t.ticket_type || 'application') !== filterType) return false; let pri = (t.priority || 'P3').toUpperCase(); if (pri === 'CRITICAL') pri = 'P0'; else if (pri === 'HIGH') pri = 'P1'; else if (pri === 'MEDIUM') pri = 'P2'; else if (pri === 'LOW') pri = 'P3'; if (filterPriority && pri !== filterPriority.toUpperCase()) return false; const assigneeRole = t.assignee ? t.assignee.role : (t.assigned_to_role || ''); if (filterRole && !assigneeRole.toLowerCase().includes(filterRole.toLowerCase())) return false; let s = (t.status || 'open').toLowerCase(); if (s === 'in_progress') s = 'progress'; if (s === 'on_hold') s = 'hold'; if (filterStatus && s !== filterStatus.toLowerCase()) return false; if (searchQuery) { const hay = `${t.id} ${t.title} ${t.ticket_type || ''} ${t.general_category || ''} ${t.department || ''} ${t.app || t.app_name || ''} ${t.feature || t.feature_name || ''} ${t.api_key || ''} ${t.assignee ? t.assignee.name : (t.assigned_to_name || '')}`.toLowerCase(); if (!hay.includes(searchQuery)) return false; } return true; }); } function switchView(view) { currentView = view; document.querySelectorAll('#viewTickets .view-switch-btn').forEach(b => b.classList.toggle('active', b.dataset.view === view)); document.getElementById('kanbanView').hidden = view !== 'kanban'; document.getElementById('tableView').hidden = view !== 'table'; renderCurrentView(); } function renderCurrentView() { if (currentView === 'kanban') renderKanban(); else renderTable(); } /* ════════════════════════════════════════════════════════════════════ KANBAN RENDER ════════════════════════════════════════════════════════════════════ */ function renderKanban() { const filtered = getFilteredTickets(); const cols = { open: [], progress: [], hold: [], completed: [] }; filtered.forEach(t => { let s = (t.status || 'open').toLowerCase(); if (s === 'in_progress') s = 'progress'; if (s === 'on_hold') s = 'hold'; if (cols[s]) cols[s].push(t); else cols.open.push(t); }); [['open', 'colOpen', 'colOpenCount'], ['progress', 'colProgress', 'colProgCount'], ['hold', 'colHold', 'colHoldCount'], ['completed', 'colCompleted', 'colDoneCount']].forEach(([s, bodyId, countId], idx) => { const body = document.getElementById(bodyId); const count = document.getElementById(countId); if (count) count.textContent = cols[s].length; if (!body) return; if (cols[s].length === 0) { body.innerHTML = '
${escapeHtml(e.exception_type)}