Spaces:
Paused

dushyantsingh0 commited on
Commit
2131f07
·
1 Parent(s): fb7ec09

backend stabilization

Browse files
api/v1/messages.py CHANGED
@@ -137,10 +137,10 @@ async def send_message(
137
  await redis.close()
138
  except Exception as e:
139
  print(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")
140
-
141
  # --- 3. Refresh Summarization Context ---
142
  await arq_pool.enqueue_job("auto_summarize_ticket", ticket_id)
143
 
 
144
  # --- 4. Notify Customer of Expert Response ---
145
  # Only if sender is staff and message is public
146
  if is_staff and not payload.is_internal and ticket.created_by != current_user.id:
 
137
  await redis.close()
138
  except Exception as e:
139
  print(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")
 
140
  # --- 3. Refresh Summarization Context ---
141
  await arq_pool.enqueue_job("auto_summarize_ticket", ticket_id)
142
 
143
+
144
  # --- 4. Notify Customer of Expert Response ---
145
  # Only if sender is staff and message is public
146
  if is_staff and not payload.is_internal and ticket.created_by != current_user.id:
api/v1/tickets.py CHANGED
@@ -1062,6 +1062,7 @@ async def update_ticket(
1062
  ("description" in update_data or "title" in update_data):
1063
  await arq_pool.enqueue_job("auto_summarize_ticket", ticket.id)
1064
 
 
1065
  # 4. Proactive Cache Invalidation (Detail, Lists, and Reports)
1066
  from core.cache import invalidate_cache, delete_by_pattern
1067
  await invalidate_cache(f"ticket:detail:{ticket_id}")
@@ -1210,6 +1211,39 @@ async def reprocess_ticket_ai(
1210
  "ticket_id": str(ticket.id)
1211
  }
1212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1213
  @router.post("/{ticket_id}/escalate/", response_model=TicketResponse)
1214
  async def escalate_ticket(
1215
  ticket_id: UUID,
 
1062
  ("description" in update_data or "title" in update_data):
1063
  await arq_pool.enqueue_job("auto_summarize_ticket", ticket.id)
1064
 
1065
+
1066
  # 4. Proactive Cache Invalidation (Detail, Lists, and Reports)
1067
  from core.cache import invalidate_cache, delete_by_pattern
1068
  await invalidate_cache(f"ticket:detail:{ticket_id}")
 
1211
  "ticket_id": str(ticket.id)
1212
  }
1213
 
1214
+ @router.post("/{ticket_id}/summarize/", status_code=status.HTTP_202_ACCEPTED)
1215
+ async def summarize_ticket_ai(
1216
+ ticket_id: UUID,
1217
+ current_user: User = Depends(get_current_user),
1218
+ db: AsyncSession = Depends(get_db),
1219
+ arq_pool: ArqRedis = Depends(get_arq_pool)
1220
+ ) -> Any:
1221
+ """
1222
+ Manually trigger ONLY the AI summarization job for a ticket.
1223
+ Provides a lightweight refresh without full re-triage.
1224
+ """
1225
+ stmt = select(Ticket).where(Ticket.id == ticket_id, Ticket.deleted_at.is_(None))
1226
+ if current_user.role != UserRole.SC_ADMIN:
1227
+ stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id)
1228
+ # Regular customers can only summarize their own tickets
1229
+ if current_user.role == UserRole.CUSTOMER_USER:
1230
+ stmt = stmt.where(Ticket.created_by == current_user.id)
1231
+
1232
+ result = await db.execute(stmt)
1233
+ ticket = result.scalar_one_or_none()
1234
+ if not ticket:
1235
+ raise HTTPException(status_code=404, detail="Ticket not found")
1236
+
1237
+ job = await arq_pool.enqueue_job("auto_summarize_ticket", ticket.id)
1238
+ job_id = job.job_id if job else "ALREADY_ENQUEUED"
1239
+
1240
+ logger.info(f"Manual Summary Trigger: Ticket {ticket_id} (Job: {job_id}) by {current_user.id}")
1241
+ return {
1242
+ "status": "enqueued",
1243
+ "job_id": job_id,
1244
+ "ticket_id": str(ticket.id)
1245
+ }
1246
+
1247
  @router.post("/{ticket_id}/escalate/", response_model=TicketResponse)
1248
  async def escalate_ticket(
1249
  ticket_id: UUID,
core/tasks.py CHANGED
@@ -132,12 +132,20 @@ async def auto_summarize_ticket(ctx, ticket_id: UUID):
132
 
133
  # 7. Real-time Summary Hydration (Nexus UI Sync)
134
  from core.websockets import manager
135
- await manager.broadcast_to_workspace(
136
- ticket.workspace_id,
137
- {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("customer_summary")}
138
- )
 
 
 
 
 
 
 
 
139
 
140
- logger.info(f"Auto-summary generated for ticket {ticket_id}")
141
 
142
  def truncate_content(text: str, max_chars: int = 15000) -> str:
143
  """
 
132
 
133
  # 7. Real-time Summary Hydration (Nexus UI Sync)
134
  from core.websockets import manager
135
+ from models.user import UserRole
136
+
137
+ # A) Broadcast to Customers (Public Summary)
138
+ cust_payload = {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("customer_summary")}
139
+ await manager.broadcast_to_role(ticket.workspace_id, UserRole.CUSTOMER_USER, cust_payload)
140
+ await manager.broadcast_to_role(ticket.workspace_id, UserRole.CUSTOMER_ADMIN, cust_payload)
141
+
142
+ # B) Broadcast to Staff (Internal Summary)
143
+ staff_payload = {"event": "summary_updated", "ticket_id": str(ticket.id), "summary": summary_data.get("internal_summary")}
144
+ await manager.broadcast_to_role(ticket.workspace_id, UserRole.SC_AGENT, staff_payload)
145
+ await manager.broadcast_to_role(ticket.workspace_id, UserRole.SC_LEAD, staff_payload)
146
+ await manager.broadcast_to_role(ticket.workspace_id, UserRole.SC_ADMIN, staff_payload)
147
 
148
+ logger.info(f"Manual Auto-summary generated and role-broadcasted for ticket {ticket_id}")
149
 
150
  def truncate_content(text: str, max_chars: int = 15000) -> str:
151
  """
frontend/apps/customer/src/components/NewTicketModal.tsx CHANGED
@@ -39,8 +39,7 @@ export const NewTicketModal: React.FC<NewTicketModalProps> = ({ onClose, onCreat
39
  });
40
 
41
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
42
- const token = localStorage.getItem('nexus_token') || localStorage.getItem('token');
43
- const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/${token ? `?token=${encodeURIComponent(token)}` : ''}`;
44
 
45
  setAttachments(prev => [...prev, { ...resp.data, downloadUrl }]);
46
  return { ...resp.data, downloadUrl };
 
39
  });
40
 
41
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
42
+ const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/`;
 
43
 
44
  setAttachments(prev => [...prev, { ...resp.data, downloadUrl }]);
45
  return { ...resp.data, downloadUrl };
frontend/apps/customer/src/components/ThreadView.tsx CHANGED
@@ -132,15 +132,15 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
132
 
133
  const handleRegenerateSummary = async () => {
134
  // Only allow once per session to honor rate limit requirement
135
- if (hasRegeneratedThisSession) return;
136
 
137
  setIsRegeneratingSummary(true);
138
  try {
139
- await api.post(`tickets/${ticket.id}/reprocess/`);
 
140
  setHasRegeneratedThisSession(true);
141
- // We don't refreshData() immediately - we wait for the WebSocket event
142
  } catch (err) {
143
- console.error("Failed to trigger regeneration:", err);
144
  setIsRegeneratingSummary(false);
145
  }
146
  };
@@ -214,8 +214,7 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
214
  });
215
 
216
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
217
- const token = localStorage.getItem(getStorageKey('token'));
218
- const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/${token ? `?token=${encodeURIComponent(token)}` : ''}`;
219
 
220
  let finalMarkdown = "";
221
  if (isImage) {
@@ -458,29 +457,36 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
458
  width: 48, height: 48, borderRadius: '50%', background: '#fff',
459
  display: 'flex', alignItems: 'center', justifyContent: 'center',
460
  fontSize: 20, boxShadow: '0 4px 12px rgba(30, 64, 175, 0.1)',
461
- animation: 'pulse 2s infinite'
462
- }}>🧠</div>
463
  <div>
464
- <div style={{ fontSize: 13, fontWeight: 900, color: 'var(--primary)', textTransform: 'uppercase', letterSpacing: '0.15em', marginBottom: 4 }}>Awaiting Neural Triage</div>
 
 
465
  <div style={{ fontSize: 14, color: 'var(--text-muted)', fontWeight: 600, marginBottom: 16 }}>
466
- Strategic analysis is in the queue. Your intelligence summary will hydrate as soon as our agents process the forensic signals...
 
 
467
  </div>
468
  <button
469
  onClick={handleRegenerateSummary}
470
- disabled={isRegeneratingSummary || hasRegeneratedThisSession}
471
  style={{
472
  padding: "10px 24px",
473
- background: "var(--primary)",
474
  color: "#fff",
475
  border: "none",
476
  borderRadius: 10,
477
  fontSize: 12,
478
  fontWeight: 800,
479
- cursor: "pointer",
480
- boxShadow: "0 4px 12px rgba(30, 64, 175, 0.2)"
 
 
 
481
  }}
482
  >
483
- {isRegeneratingSummary ? "Analyzing Neural Pathways..." : (hasRegeneratedThisSession ? "Syncing Logic Active ✅" : "🚀 Generate Intelligence Now")}
484
  </button>
485
 
486
  </div>
@@ -749,14 +755,16 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
749
  }
750
 
751
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
752
- const token = localStorage.getItem(getStorageKey('token'));
753
-
754
  return allAttachments.map((att: any, i) => {
755
- const downloadUrl = `${backendBase}tickets/attachments/${att.id}/download/${token ? `?token=${encodeURIComponent(token)}` : ''}`;
756
  return (
757
  <div
758
  key={i}
759
- onClick={() => window.open(downloadUrl, '_blank')}
 
 
 
 
760
  style={{
761
  padding: "16px",
762
  background: "#f8fafc",
 
132
 
133
  const handleRegenerateSummary = async () => {
134
  // Only allow once per session to honor rate limit requirement
135
+ if (hasRegeneratedThisSession && !ticket.summary) return;
136
 
137
  setIsRegeneratingSummary(true);
138
  try {
139
+ // Use the lightweight summarize endpoint
140
+ await api.post(`tickets/${ticket.id}/summarize/`);
141
  setHasRegeneratedThisSession(true);
 
142
  } catch (err) {
143
+ console.error("Failed to trigger summary:", err);
144
  setIsRegeneratingSummary(false);
145
  }
146
  };
 
214
  });
215
 
216
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
217
+ const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/`;
 
218
 
219
  let finalMarkdown = "";
220
  if (isImage) {
 
457
  width: 48, height: 48, borderRadius: '50%', background: '#fff',
458
  display: 'flex', alignItems: 'center', justifyContent: 'center',
459
  fontSize: 20, boxShadow: '0 4px 12px rgba(30, 64, 175, 0.1)',
460
+ animation: isRegeneratingSummary ? 'pulse 2s infinite' : 'none'
461
+ }}>{isRegeneratingSummary ? "⚡" : "🧠"}</div>
462
  <div>
463
+ <div style={{ fontSize: 13, fontWeight: 900, color: 'var(--primary)', textTransform: 'uppercase', letterSpacing: '0.15em', marginBottom: 4 }}>
464
+ {isRegeneratingSummary ? "Neural Sync Active" : "Intelligence Ready"}
465
+ </div>
466
  <div style={{ fontSize: 14, color: 'var(--text-muted)', fontWeight: 600, marginBottom: 16 }}>
467
+ {isRegeneratingSummary
468
+ ? "Synchronizing forensic signals across the workspace..."
469
+ : "Tap below to generate a real-time intelligence summary for this ticket."}
470
  </div>
471
  <button
472
  onClick={handleRegenerateSummary}
473
+ disabled={isRegeneratingSummary}
474
  style={{
475
  padding: "10px 24px",
476
+ background: isRegeneratingSummary ? "#94a3b8" : "var(--primary)",
477
  color: "#fff",
478
  border: "none",
479
  borderRadius: 10,
480
  fontSize: 12,
481
  fontWeight: 800,
482
+ cursor: isRegeneratingSummary ? "default" : "pointer",
483
+ boxShadow: "0 4px 12px rgba(30, 64, 175, 0.2)",
484
+ display: 'flex',
485
+ alignItems: 'center',
486
+ gap: 8
487
  }}
488
  >
489
+ {isRegeneratingSummary ? "Analyzing Neural Pathways..." : "🚀 Generate Quick Summary"}
490
  </button>
491
 
492
  </div>
 
755
  }
756
 
757
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
 
 
758
  return allAttachments.map((att: any, i) => {
759
+ const downloadUrl = `${backendBase}tickets/attachments/${att.id}/download/`;
760
  return (
761
  <div
762
  key={i}
763
+ onClick={() => {
764
+ const token = localStorage.getItem(getStorageKey('token'));
765
+ const authedUrl = `${downloadUrl}${token ? `?token=${encodeURIComponent(token)}` : ''}`;
766
+ window.open(authedUrl, '_blank');
767
+ }}
768
  style={{
769
  padding: "16px",
770
  background: "#f8fafc",
frontend/apps/internal/src/components/TicketDetails.tsx CHANGED
@@ -15,7 +15,8 @@ import {
15
  Database,
16
  History,
17
  Sparkles,
18
- CheckCircle
 
19
  } from 'lucide-react';
20
 
21
  interface TicketDetailsProps {
@@ -412,9 +413,35 @@ export const TicketDetails: React.FC<TicketDetailsProps> = ({ initialTicket, onB
412
  </div>
413
 
414
  <div className={styles.panelSection}>
415
- <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
416
- <Shield size={14} color="var(--primary)" />
417
- <span className={styles.sectionTitle}>Internal Diagnostic</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  </div>
419
  <div className={styles.summaryBox}>
420
  <p>{internalSummary}</p>
@@ -454,8 +481,7 @@ export const TicketDetails: React.FC<TicketDetailsProps> = ({ initialTicket, onB
454
  {ticketAttachments.length > 0 ? ticketAttachments.map((att: any, i: number) => {
455
  const icon = getFileIcon(att.filename);
456
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
457
- const token = localStorage.getItem('nexus_token') || localStorage.getItem('token');
458
- const dlUrl = `${backendBase}tickets/attachments/${att.id}/download/${token ? `?token=${encodeURIComponent(token)}` : ''}`;
459
  return (
460
  <a key={i} href={dlUrl} target="_blank" rel="noreferrer" className={styles.attachmentItem} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', background: '#f8fafc', border: '1px solid var(--border-subtle)', borderRadius: 12, textDecoration: 'none', color: 'inherit' }}>
461
  <span style={{ fontSize: 18 }}>{icon}</span>
 
15
  Database,
16
  History,
17
  Sparkles,
18
+ CheckCircle,
19
+ RefreshCw
20
  } from 'lucide-react';
21
 
22
  interface TicketDetailsProps {
 
413
  </div>
414
 
415
  <div className={styles.panelSection}>
416
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
417
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
418
+ <Shield size={14} color="var(--primary)" />
419
+ <span className={styles.sectionTitle}>Internal Diagnostic</span>
420
+ </div>
421
+ <button
422
+ onClick={async () => {
423
+ try {
424
+ await api.post(`tickets/${ticket.id}/summarize/`);
425
+ } catch (err) {
426
+ console.error("Manual summary failed:", err);
427
+ }
428
+ }}
429
+ style={{
430
+ padding: '4px 10px',
431
+ fontSize: 9,
432
+ fontWeight: 900,
433
+ border: '1px solid var(--border-subtle)',
434
+ borderRadius: 6,
435
+ background: '#fff',
436
+ cursor: 'pointer',
437
+ color: 'var(--primary)',
438
+ display: 'flex',
439
+ alignItems: 'center',
440
+ gap: 4
441
+ }}
442
+ >
443
+ <RefreshCw size={10} /> QUICK REFRESH
444
+ </button>
445
  </div>
446
  <div className={styles.summaryBox}>
447
  <p>{internalSummary}</p>
 
481
  {ticketAttachments.length > 0 ? ticketAttachments.map((att: any, i: number) => {
482
  const icon = getFileIcon(att.filename);
483
  const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
484
+ const dlUrl = `${backendBase}tickets/attachments/${att.id}/download/`;
 
485
  return (
486
  <a key={i} href={dlUrl} target="_blank" rel="noreferrer" className={styles.attachmentItem} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', background: '#f8fafc', border: '1px solid var(--border-subtle)', borderRadius: 12, textDecoration: 'none', color: 'inherit' }}>
487
  <span style={{ fontSize: 18 }}>{icon}</span>
frontend/packages/shared/src/components/NexusMarkdown.tsx CHANGED
@@ -183,23 +183,38 @@ export const NexusMarkdown: React.FC<NexusMarkdownProps> = ({ content, isMe }) =
183
  th: ({ children }) => <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '700', color: COLORS.gray700 }}>{children}</th>,
184
  td: ({ children }) => <td style={{ padding: '12px 16px', borderBottom: `1px solid ${COLORS.gray100}`, color: COLORS.gray600 }}>{children}</td>,
185
  // Custom Image Styling
186
- img: ({ src, alt }) => (
187
- <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '24px 0' }}>
188
- <img
189
- src={src}
190
- alt={alt || "Embedded Image"}
191
- style={{
192
- maxWidth: '100%',
193
- maxHeight: '500px',
194
- objectFit: 'contain',
195
- borderRadius: 16,
196
- border: `1px solid ${COLORS.gray200}`,
197
- boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)'
198
- }}
199
- />
200
- {alt && <span style={{ fontSize: '12px', color: COLORS.gray500, marginTop: '8px', fontStyle: 'italic' }}>{alt}</span>}
201
- </div>
202
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  // Paragraph & List Density
204
  p: ({ children }) => <p style={{ margin: '0 0 16px 0', whiteSpace: 'pre-wrap' }}>{children}</p>,
205
  ul: ({ children }) => <ul style={{ margin: '14px 0', paddingLeft: '24px', listStyleType: 'disc' }}>{children}</ul>,
@@ -217,8 +232,10 @@ export const NexusMarkdown: React.FC<NexusMarkdownProps> = ({ content, isMe }) =
217
  if (isDownload && href) {
218
  const token = localStorage.getItem(getStorageKey('token'));
219
  if (token) {
220
- const connector = href.includes('?') ? '&' : '?';
221
- decoratedHref = `${href}${connector}token=${token}`;
 
 
222
  }
223
  }
224
 
 
183
  th: ({ children }) => <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '700', color: COLORS.gray700 }}>{children}</th>,
184
  td: ({ children }) => <td style={{ padding: '12px 16px', borderBottom: `1px solid ${COLORS.gray100}`, color: COLORS.gray600 }}>{children}</td>,
185
  // Custom Image Styling
186
+ img: ({ src, alt }) => {
187
+ const isDownload = src?.includes('/download/');
188
+ let decoratedSrc = src;
189
+
190
+ if (isDownload && src) {
191
+ const token = localStorage.getItem(getStorageKey('token'));
192
+ if (token) {
193
+ // Strip existing token if present to avoid stacking
194
+ const cleanSrc = src.split(/[?&]token=/)?.[0] || src;
195
+ const connector = cleanSrc.includes('?') ? '&' : '?';
196
+ decoratedSrc = `${cleanSrc}${connector}token=${token}`;
197
+ }
198
+ }
199
+
200
+ return (
201
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '24px 0' }}>
202
+ <img
203
+ src={decoratedSrc}
204
+ alt={alt || "Embedded Image"}
205
+ style={{
206
+ maxWidth: '100%',
207
+ maxHeight: '500px',
208
+ objectFit: 'contain',
209
+ borderRadius: 16,
210
+ border: `1px solid ${COLORS.gray200}`,
211
+ boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)'
212
+ }}
213
+ />
214
+ {alt && <span style={{ fontSize: '12px', color: COLORS.gray500, marginTop: '8px', fontStyle: 'italic' }}>{alt}</span>}
215
+ </div>
216
+ );
217
+ },
218
  // Paragraph & List Density
219
  p: ({ children }) => <p style={{ margin: '0 0 16px 0', whiteSpace: 'pre-wrap' }}>{children}</p>,
220
  ul: ({ children }) => <ul style={{ margin: '14px 0', paddingLeft: '24px', listStyleType: 'disc' }}>{children}</ul>,
 
232
  if (isDownload && href) {
233
  const token = localStorage.getItem(getStorageKey('token'));
234
  if (token) {
235
+ // Strip existing token if present to avoid stacking
236
+ const cleanHref = href.split(/[?&]token=/)?.[0] || href;
237
+ const connector = cleanHref.includes('?') ? '&' : '?';
238
+ decoratedHref = `${cleanHref}${connector}token=${token}`;
239
  }
240
  }
241