From db9c1a58407089f426ebf2e885cfce71ae43b773 Mon Sep 17 00:00:00 2001 From: vshnosngh Date: Tue, 27 Oct 2026 18:34:24 +0530 Subject: [PATCH] feat(khira): add real-time SSE live updates and Kanban drag-and-drop --- internal/khira/enterprise.go | 21 ++++++ internal/khira/events.go | 119 +++++++++++++++++++++++++++++ internal/khira/handlers.go | 3 + internal/khira/store.go | 105 +++++++++++++++++++++++++- web/khira/app.js | 140 ++++++++++++++++++++++++++++++++++- web/khira/index.html | 12 ++- web/khira/styles.css | 75 +++++++++++++++++++ 7 files changed, 467 insertions(+), 8 deletions(-) create mode 100644 internal/khira/events.go diff --git a/internal/khira/enterprise.go b/internal/khira/enterprise.go index 47eec6e..910dac4 100644 --- a/internal/khira/enterprise.go +++ b/internal/khira/enterprise.go @@ -581,6 +581,14 @@ func (s *Store) BulkAction(ids []string, action, value string, actor *User) (map } } + if s.Broker != nil { + actorName := "" + if actor != nil { + actorName = actor.Username + } + s.Broker.Broadcast("tickets_bulk_updated", "", "", actorName, action, map[string]any{"updated": updated}) + } + return map[string]any{ "updated": updated, "skipped": skipped, @@ -598,12 +606,18 @@ func (s *Store) AddTicketTag(ticketID, tag string) error { INSERT INTO ticket_tags (ticket_id, tag) VALUES ($1, $2) ON CONFLICT (ticket_id, tag) DO NOTHING `, ticketID, tag) + if err == nil && s.Broker != nil { + s.Broker.Broadcast("ticket_tags_updated", ticketID, "", "", "tag_add", map[string]string{"tag": tag}) + } return err } func (s *Store) RemoveTicketTag(ticketID, tag string) error { tag = strings.ToLower(strings.TrimSpace(tag)) _, err := s.primaryDB.Exec(`DELETE FROM ticket_tags WHERE ticket_id = $1 AND tag = $2`, ticketID, tag) + if err == nil && s.Broker != nil { + s.Broker.Broadcast("ticket_tags_updated", ticketID, "", "", "tag_remove", map[string]string{"tag": tag}) + } return err } @@ -663,6 +677,10 @@ func (s *Store) LinkTickets(ticketA, ticketB, relType string, actor *User) error VALUES ($1, $2, $3, $4, $5, 'link', $6, NOW()) `, remID, ticketA, actor.Username, actor.Name, actor.RoleDisplay, fmt.Sprintf("Linked related ticket %s.", ticketB)) + if s.Broker != nil { + s.Broker.Broadcast("ticket_relations_updated", ticketA, "", actorUser, "link", map[string]string{"target": ticketB}) + } + return nil } @@ -671,6 +689,9 @@ func (s *Store) UnlinkTickets(ticketA, ticketB string) error { DELETE FROM ticket_relations WHERE (ticket_a = $1 AND ticket_b = $2) OR (ticket_a = $2 AND ticket_b = $1) `, ticketA, ticketB) + if err == nil && s.Broker != nil { + s.Broker.Broadcast("ticket_relations_updated", ticketA, "", "", "unlink", map[string]string{"target": ticketB}) + } return err } diff --git a/internal/khira/events.go b/internal/khira/events.go new file mode 100644 index 0000000..05ed4c8 --- /dev/null +++ b/internal/khira/events.go @@ -0,0 +1,119 @@ +package khira + +import ( + "encoding/json" + "fmt" + "net/http" + "sync" + "time" +) + +type RealtimeEvent struct { + Type string `json:"type"` // "ticket_created", "ticket_updated", "ticket_deleted", "ticket_archived", "ticket_completed", "remark_added", "error_logged", "notification", etc. + TicketID string `json:"ticket_id,omitempty"` // ID of the ticket affected + ErrorID string `json:"error_id,omitempty"` // ID of the runtime error affected + Actor string `json:"actor,omitempty"` // Username who performed the action + Action string `json:"action,omitempty"` // Action verb + Payload interface{} `json:"payload,omitempty"` // Extra metadata + Timestamp time.Time `json:"timestamp"` +} + +type EventBroker struct { + mu sync.RWMutex + clients map[chan RealtimeEvent]struct{} +} + +func NewEventBroker() *EventBroker { + return &EventBroker{ + clients: make(map[chan RealtimeEvent]struct{}), + } +} + +func (b *EventBroker) Subscribe() chan RealtimeEvent { + b.mu.Lock() + defer b.mu.Unlock() + ch := make(chan RealtimeEvent, 64) + b.clients[ch] = struct{}{} + return ch +} + +func (b *EventBroker) Unsubscribe(ch chan RealtimeEvent) { + b.mu.Lock() + defer b.mu.Unlock() + if _, ok := b.clients[ch]; ok { + delete(b.clients, ch) + close(ch) + } +} + +func (b *EventBroker) Broadcast(eventType, ticketID, errorID, actor, action string, payload interface{}) { + if b == nil { + return + } + evt := RealtimeEvent{ + Type: eventType, + TicketID: ticketID, + ErrorID: errorID, + Actor: actor, + Action: action, + Payload: payload, + Timestamp: time.Now(), + } + + b.mu.RLock() + defer b.mu.RUnlock() + for ch := range b.clients { + select { + case ch <- evt: + default: + // Non-blocking drop if channel buffer full + } + } +} + +// handleEventsSSE handles Server-Sent Events stream for connected clients +func (s *Server) handleEventsSSE(w http.ResponseWriter, r *http.Request) { + flusher, ok := w.(http.Flusher) + if !ok { + http.Error(w, "Streaming unsupported", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache, no-transform") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("X-Accel-Buffering", "no") + + ch := s.Store.Broker.Subscribe() + defer s.Store.Broker.Unsubscribe(ch) + + // Send initial handshake + fmt.Fprintf(w, "event: connected\ndata: {\"status\":\"live\",\"time\":%d}\n\n", time.Now().Unix()) + flusher.Flush() + + // 15-second heartbeat ticker to maintain proxy connection + ticker := time.NewTicker(15 * time.Second) + defer ticker.Stop() + + ctx := r.Context() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + fmt.Fprintf(w, ": ping\n\n") + flusher.Flush() + case evt, ok := <-ch: + if !ok { + return + } + data, err := json.Marshal(evt) + if err != nil { + continue + } + fmt.Fprintf(w, "event: message\ndata: %s\n\n", data) + flusher.Flush() + } + } +} diff --git a/internal/khira/handlers.go b/internal/khira/handlers.go index 2a7a2a0..0ee3208 100644 --- a/internal/khira/handlers.go +++ b/internal/khira/handlers.go @@ -195,6 +195,9 @@ func (s *Server) RegisterRoutes(r chi.Router) { api.Delete("/notifications/{id}", s.handleDeleteNotification) api.Delete("/notifications", s.handleClearNotifications) api.Post("/notifications/{id}/read", s.handleMarkNotificationReadSingle) + + // Realtime Server-Sent Events (SSE) Stream + api.Get("/events", s.handleEventsSSE) }) } diff --git a/internal/khira/store.go b/internal/khira/store.go index 8229cce..090fb10 100644 --- a/internal/khira/store.go +++ b/internal/khira/store.go @@ -21,6 +21,7 @@ type Store struct { primaryDB *sql.DB backupDB *sql.DB dataDir string + Broker *EventBroker mu sync.RWMutex } @@ -67,6 +68,7 @@ func NewStore(dataDir string) (*Store, error) { primaryDB: primaryDB, backupDB: backupDB, dataDir: dataDir, + Broker: NewEventBroker(), } // Check if backup is empty; if so, initial sync @@ -402,6 +404,11 @@ func (s *Store) CreateTicket(t *Ticket, actor *User) (*Ticket, error) { return nil, err } + // Realtime Broadcast + if s.Broker != nil { + s.Broker.Broadcast("ticket_created", t.ID, "", actor.Username, "create", map[string]string{"title": t.Title, "priority": t.Priority}) + } + // Notification if t.AssignedTo != "" && !strings.EqualFold(t.AssignedTo, actor.Username) { s.addNotification(t.AssignedTo, t.ID, "New ticket assigned to you", fmt.Sprintf("%s: %s", t.ID, t.Title), "assignment") @@ -556,7 +563,19 @@ func (s *Store) DeleteTicket(ticketID string, actor *User) error { return errors.New("ticket not found") } - return tx.Commit() + if err := tx.Commit(); err != nil { + return err + } + + if s.Broker != nil { + actorName := "unknown" + if actor != nil { + actorName = actor.Username + } + s.Broker.Broadcast("ticket_deleted", ticketID, "", actorName, "delete", nil) + } + + return nil } type AppMeta struct { @@ -875,6 +894,10 @@ func (s *Store) AddRemark(ticketID string, actor *User, remType, text string) (* s.addNotification(createdBy, ticketID, "New remark on ticket", fmt.Sprintf("%s: %s commented", ticketID, actor.Name), "remark") } + if s.Broker != nil { + s.Broker.Broadcast("remark_added", ticketID, "", actor.Username, "remark", map[string]string{"text": text, "type": remType}) + } + return s.GetTicket(ticketID) } @@ -905,6 +928,10 @@ func (s *Store) HoldTicket(ticketID string, actor *User, reason string) (*Ticket s.addNotification(assignedTo, ticketID, "Ticket placed on hold", fmt.Sprintf("%s placed on hold by %s", ticketID, actor.Name), "hold") } + if s.Broker != nil { + s.Broker.Broadcast("ticket_held", ticketID, "", actor.Username, "hold", map[string]string{"reason": reason}) + } + return s.GetTicket(ticketID) } @@ -934,6 +961,10 @@ func (s *Store) ResumeTicket(ticketID string, actor *User, remarks string) (*Tic VALUES ($1, $2, $3, $4, $5, 'resume', $6, $7) `, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, remText, now) + if s.Broker != nil { + s.Broker.Broadcast("ticket_resumed", ticketID, "", actor.Username, "resume", nil) + } + return s.GetTicket(ticketID) } @@ -964,6 +995,10 @@ func (s *Store) CompleteTicket(ticketID string, actor *User, remarks string) (*T s.addNotification(createdBy, ticketID, "Ticket completed", fmt.Sprintf("%s was marked as completed by %s", ticketID, actor.Name), "complete") } + if s.Broker != nil { + s.Broker.Broadcast("ticket_completed", ticketID, "", actor.Username, "complete", map[string]string{"remarks": remarks}) + } + return s.GetTicket(ticketID) } @@ -1009,6 +1044,10 @@ func (s *Store) ArchiveTicket(ticketID string, actor *User) (*Ticket, error) { VALUES ($1, $2, $3, $4, $5, 'archive', $6, $7) `, remID, ticketID, actorUsername, actorName, actorRole, "Moved ticket to archive.", now) + if s.Broker != nil { + s.Broker.Broadcast("ticket_archived", ticketID, "", actorUsername, "archive", nil) + } + return s.GetTicket(ticketID) } @@ -1050,6 +1089,10 @@ func (s *Store) UnarchiveTicket(ticketID string, actor *User) (*Ticket, error) { VALUES ($1, $2, $3, $4, $5, 'unarchive', $6, $7) `, remID, ticketID, actorUsername, actorName, actorRole, "Restored ticket from archive.", now) + if s.Broker != nil { + s.Broker.Broadcast("ticket_unarchived", ticketID, "", actorUsername, "unarchive", nil) + } + return s.GetTicket(ticketID) } @@ -1080,6 +1123,10 @@ func (s *Store) ChangePriority(ticketID string, actor *User, priority, note stri VALUES ($1, $2, $3, $4, $5, 'priority', $6, $7) `, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, remText, now) + if s.Broker != nil { + s.Broker.Broadcast("ticket_priority", ticketID, "", actor.Username, "priority", map[string]string{"priority": priority}) + } + return s.GetTicket(ticketID) } @@ -1120,6 +1167,10 @@ func (s *Store) ReassignTicket(ticketID string, actor *User, newAssignee, note s s.addNotification(newAssignee, ticketID, "Ticket reassigned to you", fmt.Sprintf("%s was reassigned to you by %s", ticketID, actor.Name), "assignment") } + if s.Broker != nil { + s.Broker.Broadcast("ticket_reassigned", ticketID, "", actor.Username, "reassign", map[string]string{"assigned_to": newAssignee}) + } + return s.GetTicket(ticketID) } @@ -1138,6 +1189,11 @@ func (s *Store) AddAttachment(ticketID string, actor *User, att Attachment) (*Ti } _, _ = s.primaryDB.Exec(`UPDATE tickets SET updated_at = $1 WHERE id = $2`, att.CreatedAt, ticketID) + + if s.Broker != nil { + s.Broker.Broadcast("ticket_updated", ticketID, "", actor.Username, "attachment", nil) + } + return s.GetTicket(ticketID) } @@ -1155,6 +1211,11 @@ func (s *Store) AddLink(ticketID string, actor *User, link string) (*Ticket, err } _, _ = s.primaryDB.Exec(`UPDATE tickets SET updated_at = $1 WHERE id = $2`, now, ticketID) + + if s.Broker != nil { + s.Broker.Broadcast("ticket_updated", ticketID, "", actor.Username, "link", nil) + } + return s.GetTicket(ticketID) } @@ -1168,6 +1229,10 @@ func (s *Store) addNotification(userID, ticketID, title, msg, notifType string) INSERT INTO notifications (id, user_id, ticket_id, title, message, type, read, created_at) VALUES ($1, $2, $3, $4, $5, $6, FALSE, $7) `, id, strings.ToLower(userID), ticketID, title, msg, notifType, time.Now()) + + if s.Broker != nil { + s.Broker.Broadcast("notification", ticketID, "", strings.ToLower(userID), notifType, map[string]string{"title": title, "message": msg}) + } } func (s *Store) GetNotifications(username string) []Notification { @@ -1256,6 +1321,10 @@ func (s *Store) IngestError(errItem *AppError, actor *User) (*AppError, error) { return nil, fmt.Errorf("failed to insert error: %w", err) } + if s.Broker != nil { + s.Broker.Broadcast("error_logged", "", errItem.ID, "", "log", map[string]string{"app": errItem.AppName, "severity": errItem.Severity}) + } + return errItem, nil } @@ -1411,6 +1480,14 @@ func (s *Store) UpdateErrorStatus(id string, status ErrorStatus, notes string, a return nil, errors.New("error not found") } + if s.Broker != nil { + actorName := "unknown" + if actor != nil { + actorName = actor.Username + } + s.Broker.Broadcast("error_updated", "", id, actorName, string(status), nil) + } + return s.GetError(id) } @@ -1429,6 +1506,15 @@ func (s *Store) ArchiveError(errorID string, actor *User) (*AppError, error) { if err != nil { return nil, err } + + if s.Broker != nil { + actorName := "unknown" + if actor != nil { + actorName = actor.Username + } + s.Broker.Broadcast("error_archived", "", errorID, actorName, "archive", nil) + } + return s.GetError(errorID) } @@ -1440,6 +1526,15 @@ func (s *Store) UnarchiveError(errorID string, actor *User) (*AppError, error) { if n, _ := res.RowsAffected(); n == 0 { return nil, errors.New("error not found") } + + if s.Broker != nil { + actorName := "unknown" + if actor != nil { + actorName = actor.Username + } + s.Broker.Broadcast("error_unarchived", "", errorID, actorName, "unarchive", nil) + } + return s.GetError(errorID) } @@ -1541,6 +1636,14 @@ func (s *Store) EscalateErrorToTicket(errorID, title, assignedTo, priority, note // Link error _, _ = s.primaryDB.Exec(`UPDATE errors SET linked_ticket_id = $1, status = 'investigating' WHERE id = $2`, created.ID, errorID) + if s.Broker != nil { + actorName := "unknown" + if actor != nil { + actorName = actor.Username + } + s.Broker.Broadcast("error_escalated", created.ID, errorID, actorName, "escalate", nil) + } + updatedErr, _ := s.GetError(errorID) return created, updatedErr, nil } diff --git a/web/khira/app.js b/web/khira/app.js index b0452db..407ddc9 100644 --- a/web/khira/app.js +++ b/web/khira/app.js @@ -380,7 +380,7 @@ function renderT(anim){ if(S.view==='board'){ put('#board',COLS.map(([k,c])=>{ const rows=f.filter(t=>st(t)===k||(!STAT[st(t)]&&k==='open')); - return`

${STAT[k]}${rows.length}

${rows.map((t,i)=>{ + return`

${STAT[k]}${rows.length}

${rows.map((t,i)=>{ const p=pri(t),n=(t.remarks||[]).length; const avElem=avHtml(t.assignee||{avatar:t.assigned_to_avatar||'👤',role:t.assigned_to_role,username:t.assigned_to},26); const isSel=S.bulkSelected.has(t.id); @@ -400,7 +400,7 @@ function renderT(anim){ const tagsHtml=(t.tags||[]).length?`
${t.tags.map(tg=>`${esc(tg)}`).join('')}
`:''; - return`
+ return`
${chkBox}
${esc(t.id)}${t.ticket_type==='general'?'General':'App'}${p}

${esc(t.title)}

@@ -410,6 +410,8 @@ function renderT(anim){
`; }).join('')||'
No tickets
'}
`; }).join('')); + + initBoardDragDrop(); }else{ const dateGroups=['Today','Yesterday','This Week','Earlier this Month','Older']; const grouped={}; @@ -438,6 +440,63 @@ function renderT(anim){ put('#title','Tickets'); } +function initBoardDragDrop(){ + const cards = $$('#board .card'); + const cols = $$('#board .col'); + + cards.forEach(card => { + card.addEventListener('dragstart', e => { + e.dataTransfer.setData('text/plain', card.dataset.t); + e.dataTransfer.effectAllowed = 'move'; + card.classList.add('dragging'); + }); + card.addEventListener('dragend', () => { + card.classList.remove('dragging'); + }); + }); + + cols.forEach(col => { + col.addEventListener('dragover', e => { + e.preventDefault(); + e.dataTransfer.dropEffect = 'move'; + col.classList.add('drop-hover'); + }); + col.addEventListener('dragleave', e => { + if (!col.contains(e.relatedTarget)) { + col.classList.remove('drop-hover'); + } + }); + col.addEventListener('drop', async e => { + e.preventDefault(); + col.classList.remove('drop-hover'); + const tid = e.dataTransfer.getData('text/plain'); + const targetCol = col.dataset.col; + if (!tid || !targetCol) return; + + const t = S.t.find(x => x.id === tid); + if (!t) return; + const curSt = st(t); + if (curSt === targetCol) return; + + if (targetCol === 'completed') { + S.tid = tid; + doneD(); + } else if (targetCol === 'hold') { + S.tid = tid; + holdD(); + } else if (targetCol === 'progress') { + await api(`/khira/api/tickets/${encodeURIComponent(tid)}/resume`, 'POST', { remarks: 'Moved to In Progress' }); + toast(`Ticket ${tid} moved to In Progress`); + await refresh(false); + } else if (targetCol === 'open') { + await api(`/khira/api/tickets/${encodeURIComponent(tid)}/resume`, 'POST', { remarks: 'Moved to Open' }); + toast(`Ticket ${tid} moved to Open`); + await refresh(false); + } + }); + }); +} + /* ── Errors View ── */ function renderE(anim){ const s=S.es; @@ -973,7 +1032,8 @@ async function remark(){ if(!b){toast('Write a remark first','err');return} const r=await api(`/khira/api/tickets/${encodeURIComponent(S.tid)}/remarks`,'POST',{text:b,body:b,links:[]}); if(r._f){toast(r.error,'err');return} - toast('Remark posted');await refresh();sheet(S.tid); + ta.value=''; + toast('Remark posted');await refresh(false);sheet(S.tid); } const holdD=()=>dlg({title:'Put ticket on hold',sub:'Say what is blocking this ticket.',body:fld('reason','Reason',{t:'area',rows:4,req:1}),ok:'Hold ticket',go:v=>act('hold',{reason:v.reason},'Ticket on hold')}); @@ -1821,6 +1881,77 @@ $('#btnForgot')?.addEventListener('click',()=>{ }); }); +/* ── Realtime SSE Engine ── */ +let sseSource = null; +let sseReconnectTimer = null; + +function updateLiveStatus(online) { + const pill = $('#livePill'); + if (!pill) return; + pill.classList.toggle('online', !!online); + pill.classList.toggle('offline', !online); + const lbl = pill.querySelector('.live-lbl'); + if (lbl) lbl.textContent = online ? 'Live' : 'Reconnecting...'; +} + +function initRealtime() { + if (sseSource) { + try { sseSource.close(); } catch(e) {} + sseSource = null; + } + + const un = S.u?.username || ls('khira_active_user'); + const url = un ? `/khira/api/events?u=${encodeURIComponent(un)}` : '/khira/api/events'; + sseSource = new EventSource(url); + + sseSource.addEventListener('connected', () => { + updateLiveStatus(true); + }); + + sseSource.addEventListener('message', async (e) => { + try { + const evt = JSON.parse(e.data); + handleRealtimeEvent(evt); + } catch(err) { + console.warn('Realtime event parse error', err); + } + }); + + sseSource.onerror = () => { + updateLiveStatus(false); + if (sseSource && sseSource.readyState === EventSource.CLOSED) { + clearTimeout(sseReconnectTimer); + sseReconnectTimer = setTimeout(initRealtime, 3000); + } + }; +} + +async function handleRealtimeEvent(evt) { + const tId = evt.ticket_id; + + // 1. Refresh background datasets silently without layout flicker + await refresh(false); + + // 2. If the user currently has the affected ticket sheet open: + if (S.tid && tId && S.tid === tId && $('#sheet')?.open) { + sheet(S.tid); + } + + // 3. If currently on Analytics view: + if (S.sec === 'analytics') { + renderA(false); + } + + // 4. Subtle visual highlight on affected card + if (tId) { + const card = document.querySelector(`.card[data-t="${tId}"]`); + if (card) { + card.classList.add('live-flash'); + setTimeout(() => card.classList.remove('live-flash'), 1200); + } + } +} + /* ── App Initialization ── */ async function boot(u){ S.u=u; @@ -1828,9 +1959,10 @@ async function boot(u){ $('#app').hidden=false; updateMe(u); initKubeLens(); + initRealtime(); await refresh(true); clearInterval(pollId); - pollId=setInterval(()=>refresh(false),8000); + pollId=setInterval(()=>refresh(false),30000); } (async function init(){ diff --git a/web/khira/index.html b/web/khira/index.html index 063eadf..5a98c33 100644 --- a/web/khira/index.html +++ b/web/khira/index.html @@ -9,7 +9,7 @@ - + @@ -71,7 +71,13 @@
-

Tickets

+
+

Tickets

+
+ + Live +
+