Spaces:
Paused

dushyantsingh0 commited on
Commit
fea6aea
·
2 Parent(s): 520582bb3ffe76

Merge branch 'claude/bold-antonelli-322c67'

Browse files
agents/nexus_master.py CHANGED
@@ -145,7 +145,10 @@ def sanitize_mermaid(text: str) -> str:
145
  value_part = parts[1].strip()
146
  # Extract last number/decimal in the value part
147
  nums = re.findall(r'(\d+\.?\d*)', value_part)
148
- val = nums[-1] if nums else "0"
 
 
 
149
  new_lines.append(f' "{label}" : {val}')
150
  return f"```mermaid\n" + "\n".join(new_lines) + "\n```"
151
 
@@ -157,10 +160,23 @@ def sanitize_mermaid(text: str) -> str:
157
  t = m.group(1).strip().strip('"').strip("'")
158
  return f'title "{t}"'
159
  code = re.sub(r'title\s+(.*)', quote_title, code, count=1, flags=re.I)
160
-
161
- # Stripping hallucinated 'x from', 'y from', 'plot' to prevent hard syntax errors
162
- # We comment them out so they don't break the parser
163
- code = re.sub(r'^\s*(x from|y from|plot\s+).*$', r'%% \g<0>', code, flags=re.MULTILINE | re.I)
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  # 2. Robust Label Quoting
166
  def quote_label(m):
 
145
  value_part = parts[1].strip()
146
  # Extract last number/decimal in the value part
147
  nums = re.findall(r'(\d+\.?\d*)', value_part)
148
+ val = nums[-1] if nums else None
149
+ # Skip lines with no numeric value or zero value — Mermaid crashes on 0-value pie slices
150
+ if val is None or float(val) == 0:
151
+ continue
152
  new_lines.append(f' "{label}" : {val}')
153
  return f"```mermaid\n" + "\n".join(new_lines) + "\n```"
154
 
 
160
  t = m.group(1).strip().strip('"').strip("'")
161
  return f'title "{t}"'
162
  code = re.sub(r'title\s+(.*)', quote_title, code, count=1, flags=re.I)
163
+
164
+ # Valid xychart-beta line prefixes — anything else is hallucinated
165
+ VALID_XY_PREFIXES = (
166
+ 'xychart', 'title', 'x-axis', 'y-axis', 'bar', 'line', '%%',
167
+ )
168
+ cleaned_lines = []
169
+ for line in code.split('\n'):
170
+ stripped = line.strip().lower()
171
+ if not stripped:
172
+ cleaned_lines.append(line)
173
+ continue
174
+ if any(stripped.startswith(p) for p in VALID_XY_PREFIXES):
175
+ cleaned_lines.append(line)
176
+ else:
177
+ # Comment out the invalid line so the block still parses
178
+ cleaned_lines.append(f'%% {line}')
179
+ code = '\n'.join(cleaned_lines)
180
 
181
  # 2. Robust Label Quoting
182
  def quote_label(m):
frontend/apps/customer/src/components/NexusMasterAgent.tsx CHANGED
@@ -62,7 +62,36 @@ export const NexusMasterAgent: React.FC = () => {
62
  // 1. User Message (Standard)
63
  if (m.role === 'user') return <NexusMarkdown content={m.content} isMe={true} />;
64
 
65
- // 2. Assistant Message with HITL Action
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  if (m.content.includes("[ACTION_REQUIRED]")) {
67
  try {
68
  const parts = m.content.split("[ACTION_REQUIRED]");
@@ -73,7 +102,7 @@ export const NexusMasterAgent: React.FC = () => {
73
  return (
74
  <>
75
  {textPart && <NexusMarkdown content={textPart} isMe={false} />}
76
-
77
  {/* The Action Card - Only visible if it's the latest message, there's a pending action, and we are not loading */}
78
  {isLatest && pendingAction && !loading && (
79
  <div
@@ -152,7 +181,7 @@ export const NexusMasterAgent: React.FC = () => {
152
  }
153
  }
154
 
155
- // 3. Standard Assistant Message
156
  return <NexusMarkdown content={m.content} isMe={false} />;
157
  };
158
 
 
62
  // 1. User Message (Standard)
63
  if (m.role === 'user') return <NexusMarkdown content={m.content} isMe={true} />;
64
 
65
+ // 2. Resolved HITL action — show compact outcome badge
66
+ if (m.content.includes('[ACTION_RESOLVED:approved]') || m.content.includes('[ACTION_RESOLVED:rejected]')) {
67
+ const isApproved = m.content.includes('[ACTION_RESOLVED:approved]');
68
+ const textPart = m.content
69
+ .replace('[ACTION_RESOLVED:approved]', '')
70
+ .replace('[ACTION_RESOLVED:rejected]', '')
71
+ .trim();
72
+ return (
73
+ <>
74
+ {textPart && <NexusMarkdown content={textPart} isMe={false} />}
75
+ <div style={{
76
+ display: 'inline-flex',
77
+ alignItems: 'center',
78
+ gap: 6,
79
+ marginTop: 10,
80
+ padding: '7px 14px',
81
+ borderRadius: 10,
82
+ border: `1px solid ${isApproved ? '#10B981' : '#EF4444'}44`,
83
+ background: isApproved ? 'rgba(16,185,129,0.08)' : 'rgba(239,68,68,0.08)',
84
+ fontSize: 12,
85
+ fontWeight: 700,
86
+ color: isApproved ? '#10B981' : '#EF4444',
87
+ }}>
88
+ {isApproved ? '✅ Action Approved & Executed' : '❌ Action Rejected'}
89
+ </div>
90
+ </>
91
+ );
92
+ }
93
+
94
+ // 4. Assistant Message with HITL Action (pending)
95
  if (m.content.includes("[ACTION_REQUIRED]")) {
96
  try {
97
  const parts = m.content.split("[ACTION_REQUIRED]");
 
102
  return (
103
  <>
104
  {textPart && <NexusMarkdown content={textPart} isMe={false} />}
105
+
106
  {/* The Action Card - Only visible if it's the latest message, there's a pending action, and we are not loading */}
107
  {isLatest && pendingAction && !loading && (
108
  <div
 
181
  }
182
  }
183
 
184
+ // 5. Standard Assistant Message
185
  return <NexusMarkdown content={m.content} isMe={false} />;
186
  };
187
 
frontend/apps/internal/src/components/NexusMasterAgent.tsx CHANGED
@@ -181,11 +181,54 @@ export const NexusMasterAgent: React.FC<{ workspaceId?: string }> = ({ workspace
181
  )}
182
  {messages.map((m, i) => {
183
  const isAssistant = m.role === 'assistant';
184
- const hasAction = isAssistant && typeof m.content === 'string' && m.content.includes("[ACTION_REQUIRED]");
185
-
 
186
  let textPart = m.content;
187
  let actionData = null;
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  if (hasAction) {
190
  const parts = m.content.split("[ACTION_REQUIRED]");
191
  textPart = parts[0].trim();
@@ -211,7 +254,7 @@ export const NexusMasterAgent: React.FC<{ workspaceId?: string }> = ({ workspace
211
  animation: 'nexus-slide-up 0.4s ease-out'
212
  }}>
213
  {textPart && <NexusMarkdown content={textPart} isMe={m.role === 'user'} />}
214
-
215
  {hasAction && actionData && pendingAction && (i === messages.length - 1) && (
216
  <div style={{
217
  padding: '20px',
 
181
  )}
182
  {messages.map((m, i) => {
183
  const isAssistant = m.role === 'assistant';
184
+ const isResolved = isAssistant && typeof m.content === 'string' && (m.content.includes('[ACTION_RESOLVED:approved]') || m.content.includes('[ACTION_RESOLVED:rejected]'));
185
+ const hasAction = isAssistant && !isResolved && typeof m.content === 'string' && m.content.includes("[ACTION_REQUIRED]");
186
+
187
  let textPart = m.content;
188
  let actionData = null;
189
 
190
+ if (isResolved) {
191
+ const isApproved = m.content.includes('[ACTION_RESOLVED:approved]');
192
+ textPart = m.content
193
+ .replace('[ACTION_RESOLVED:approved]', '')
194
+ .replace('[ACTION_RESOLVED:rejected]', '')
195
+ .trim();
196
+ return (
197
+ <div key={i} style={{
198
+ alignSelf: 'flex-start',
199
+ maxWidth: '85%',
200
+ padding: '14px 20px',
201
+ borderRadius: '24px 24px 24px 4px',
202
+ background: 'var(--bg2)',
203
+ color: 'var(--text1)',
204
+ fontSize: 14,
205
+ lineHeight: 1.6,
206
+ boxShadow: '0 10px 30px rgba(0,0,0,0.05)',
207
+ border: `1px solid var(--border)`,
208
+ wordBreak: 'break-word',
209
+ fontWeight: 500,
210
+ animation: 'nexus-slide-up 0.4s ease-out'
211
+ }}>
212
+ {textPart && <NexusMarkdown content={textPart} isMe={false} />}
213
+ <div style={{
214
+ display: 'inline-flex',
215
+ alignItems: 'center',
216
+ gap: 6,
217
+ marginTop: 10,
218
+ padding: '7px 14px',
219
+ borderRadius: 10,
220
+ border: `1px solid ${isApproved ? '#10B981' : '#EF4444'}44`,
221
+ background: isApproved ? 'rgba(16,185,129,0.08)' : 'rgba(239,68,68,0.08)',
222
+ fontSize: 12,
223
+ fontWeight: 700,
224
+ color: isApproved ? '#10B981' : '#EF4444',
225
+ }}>
226
+ {isApproved ? '✅ Action Approved & Executed' : '❌ Action Rejected'}
227
+ </div>
228
+ </div>
229
+ );
230
+ }
231
+
232
  if (hasAction) {
233
  const parts = m.content.split("[ACTION_REQUIRED]");
234
  textPart = parts[0].trim();
 
254
  animation: 'nexus-slide-up 0.4s ease-out'
255
  }}>
256
  {textPart && <NexusMarkdown content={textPart} isMe={m.role === 'user'} />}
257
+
258
  {hasAction && actionData && pendingAction && (i === messages.length - 1) && (
259
  <div style={{
260
  padding: '20px',
frontend/packages/shared/src/components/NexusMermaid.tsx CHANGED
@@ -72,16 +72,40 @@ export const NexusMermaid: React.FC<MermaidProps> = ({ chart, theme }) => {
72
  fixed = `graph TD\n${fixed}`;
73
  }
74
 
75
- // 2. Fix Chart Indentation (Mermaid is sensitive to this)
76
- if (lowerFixed.startsWith('pie') || lowerFixed.startsWith('xychart')) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  const lines = fixed.split('\n');
78
  fixed = lines.map((line, index) => {
79
  const l = line.trim();
80
  if (index === 0 || !l || l.startsWith('%%') || l.toLowerCase().startsWith('title')) return line;
81
- // Add indentation if missing
82
- if (!line.startsWith(' ') && !line.startsWith('\t')) {
83
- return ' ' + line;
84
- }
85
  return line;
86
  }).join('\n');
87
  }
 
72
  fixed = `graph TD\n${fixed}`;
73
  }
74
 
75
+ // 2. Pie chart: remove 0-value slices (Mermaid crashes on them) and fix indentation
76
+ if (lowerFixed.startsWith('pie')) {
77
+ const lines = fixed.split('\n');
78
+ // Filter out data lines whose value is 0 (keep header/title/comment lines)
79
+ const filtered = lines.filter(line => {
80
+ const l = line.trim();
81
+ if (!l || l.startsWith('%%') || !l.includes(':')) return true;
82
+ const colonIdx = l.lastIndexOf(':');
83
+ const valStr = l.slice(colonIdx + 1).trim();
84
+ const val = parseFloat(valStr);
85
+ return isNaN(val) || val > 0;
86
+ });
87
+ // Only apply the filter if there's still at least one data line left
88
+ const hasData = filtered.some(l => {
89
+ const t = l.trim();
90
+ return t.includes(':') && !t.toLowerCase().startsWith('pie') && !t.toLowerCase().startsWith('title');
91
+ });
92
+ if (hasData) fixed = filtered.join('\n');
93
+ // Fix indentation
94
+ fixed = fixed.split('\n').map((line, index) => {
95
+ const l = line.trim();
96
+ if (index === 0 || !l || l.startsWith('%%') || l.toLowerCase().startsWith('title')) return line;
97
+ if (!line.startsWith(' ') && !line.startsWith('\t')) return ' ' + line;
98
+ return line;
99
+ }).join('\n');
100
+ }
101
+
102
+ // 2b. xychart: fix indentation and strip hallucinated syntax lines
103
+ if (lowerFixed.startsWith('xychart')) {
104
  const lines = fixed.split('\n');
105
  fixed = lines.map((line, index) => {
106
  const l = line.trim();
107
  if (index === 0 || !l || l.startsWith('%%') || l.toLowerCase().startsWith('title')) return line;
108
+ if (!line.startsWith(' ') && !line.startsWith('\t')) return ' ' + line;
 
 
 
109
  return line;
110
  }).join('\n');
111
  }
frontend/packages/shared/src/contexts/NexusContext.tsx CHANGED
@@ -217,7 +217,14 @@ export const NexusProvider: React.FC<{ children: ReactNode }> = ({ children }) =
217
  error: null,
218
  pendingAction: isApproval ? null : prev.pendingAction,
219
  messages: [
220
- ...prev.messages,
 
 
 
 
 
 
 
221
  { role: 'user' as const, content: text, senderName: 'You', timestamp: now },
222
  // Placeholder so the typing indicator appears immediately.
223
  { role: 'assistant' as const, content: '', senderName: 'Nexus', timestamp: now, _msgId: assistantMsgId },
@@ -383,11 +390,19 @@ export const NexusProvider: React.FC<{ children: ReactNode }> = ({ children }) =
383
  }, [state.threadId, query]);
384
 
385
  const rejectAction = useCallback(async () => {
386
- setState(prev => ({ ...prev, pendingAction: null, statusMessage: null }));
 
 
 
 
 
 
 
 
 
387
  try {
388
  if (state.threadId) {
389
  await api.post(`nexus/thread/${state.threadId}/reject/`);
390
- setState(prev => ({ ...prev, pendingAction: null, statusMessage: null }));
391
  }
392
  } catch (err) {}
393
  }, [state.threadId]);
 
217
  error: null,
218
  pendingAction: isApproval ? null : prev.pendingAction,
219
  messages: [
220
+ ...(isApproval
221
+ ? prev.messages.map(m =>
222
+ m.content.includes('[ACTION_REQUIRED]')
223
+ ? { ...m, content: m.content.replace(/\[ACTION_REQUIRED\][\s\S]*$/, '[ACTION_RESOLVED:approved]') }
224
+ : m
225
+ )
226
+ : prev.messages
227
+ ),
228
  { role: 'user' as const, content: text, senderName: 'You', timestamp: now },
229
  // Placeholder so the typing indicator appears immediately.
230
  { role: 'assistant' as const, content: '', senderName: 'Nexus', timestamp: now, _msgId: assistantMsgId },
 
390
  }, [state.threadId, query]);
391
 
392
  const rejectAction = useCallback(async () => {
393
+ setState(prev => ({
394
+ ...prev,
395
+ pendingAction: null,
396
+ statusMessage: null,
397
+ messages: prev.messages.map(m =>
398
+ m.content.includes('[ACTION_REQUIRED]')
399
+ ? { ...m, content: m.content.replace(/\[ACTION_REQUIRED\][\s\S]*$/, '[ACTION_RESOLVED:rejected]') }
400
+ : m
401
+ ),
402
+ }));
403
  try {
404
  if (state.threadId) {
405
  await api.post(`nexus/thread/${state.threadId}/reject/`);
 
406
  }
407
  } catch (err) {}
408
  }, [state.threadId]);