rk147 commited on
Commit
eefeca0
·
verified ·
1 Parent(s): b845721

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +378 -302
app.py CHANGED
@@ -1,44 +1,19 @@
1
  import streamlit as st
2
  import streamlit.components.v1 as components
3
-
4
- # Disable ChromaDB telemetry before any imports
5
- os.environ["ANONYMIZED_TELEMETRY"] = "False"
6
- os.environ["CHROMA_TELEMETRY"] = "False"
7
-
8
-
9
  from app.orchestrator import analyze_code
10
  from app.modules.llm import chat_response, vision_response
 
 
 
 
 
 
 
11
 
12
  st.set_page_config(page_title="secforge", page_icon="🔬", layout="wide")
13
 
14
  st.markdown("""
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
  <style>
43
  @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@300;400;500&display=swap');
44
  html, body, [class*="css"] { font-family: 'IBM Plex Sans', sans-serif; }
@@ -71,75 +46,104 @@ hr { border-color: #1e1e22; margin: 0.5rem 0; }
71
 
72
  # ══════════════════════════════════════════════════════
73
  # PASSWORD GATE
74
- # Fix: read password from session_state key, not widget return value
75
- # This prevents the "enter password first" bug on button click
76
  # ══════════════════════════════════════════════════════
77
  def _show_password_gate():
78
  st.markdown("#### 🔬 secforge")
79
-
 
 
 
80
  col1, col2 = st.columns([3, 1])
81
  with col1:
82
- # Store in session_state so button click can read it reliably
83
- st.text_input(
84
- "password", type="password",
85
- placeholder="enter a password…",
86
- label_visibility="collapsed",
87
- key="pw_input_value", # read via st.session_state["pw_input_value"]
88
- )
89
  with col2:
90
  enter = st.button("→ enter", type="primary", use_container_width=True)
91
-
92
- # Also allow Enter key submission
93
- if enter or st.session_state.get("_pw_submitted"):
94
- st.session_state["_pw_submitted"] = False
95
- # Read from session_state, not widget return — this is the fix
96
- password = st.session_state.get("pw_input_value", "")
97
-
98
  if not password:
99
  st.warning("enter a password first")
100
  return
101
  if len(password) < 4:
102
  st.error("password must be at least 4 characters")
103
  return
104
-
105
  sid = derive_session_id(password)
106
  try:
107
  data = get_session(sid, password)
108
- fname: tuple(v) if isinstance(v, list) else v
109
- for fname, v in raw.items()
110
- }
111
- # Re-index files into RAG on restore
 
 
 
 
 
 
 
 
 
112
  for fname, contents in st.session_state.file_contents.items():
113
- if isinstance(contents, tuple) and len(contents) == 2 and contents[1] != "image":
114
  try:
 
 
 
 
115
  except ValueError:
116
  st.error("wrong password — session exists but password does not match.")
117
  except Exception as e:
118
- st.error(f"error loading session: {e}")
119
 
120
 
121
  if not st.session_state.get("authenticated"):
122
  _show_password_gate()
123
  st.stop()
124
 
125
- # Only reached when authenticated
126
  SID = st.session_state.session_id
127
  PASSWORD = st.session_state.password
128
 
 
 
 
 
 
 
 
129
  for fname, v in st.session_state.file_contents.items()
130
  }
131
  try:
132
- save_session(
133
- SID, PASSWORD,
134
- st.session_state.messages,
135
- st.session_state.linked_files,
136
- serializable,
137
- st.session_state.session_label,
138
- st.session_state.map_data,
139
- )
140
  except Exception as e:
141
  st.error(f"save failed: {e}")
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  st.markdown(f"{dot} `line {iss['line']}` `{iss['symbol']}` · {iss['message']} *{iss['category']}*")
144
  else:
145
  st.markdown("*no issues found*")
@@ -151,25 +155,7 @@ PASSWORD = st.session_state.password
151
  st.code(fix["fix"], language=result.get("language", "python"))
152
 
153
 
154
- def _js_str(s: str) -> str:
155
- """Safely escape a string for embedding in JS — prevents JSON parse crashes."""
156
- return (s or "").\
157
- replace("\\", "\\\\").\
158
- replace("'", "\\'").\
159
- replace('"', '\\"').\
160
- replace("\n", "\\n").\
161
- replace("\r", "").\
162
- replace("`", "\\`")
163
-
164
-
165
  def _render_map_html(nodes: list, edges: list) -> str:
166
- """
167
- Render graph as self-contained vis.js HTML.
168
- - Physics-enabled with clustering for better layout
169
- - Curved edges with colored label backgrounds
170
- - Sliding detail panel on node click
171
- - Edge descriptions visible with background pill
172
- """
173
  kind_colors = {
174
  "function": "#4a9eff",
175
  "class": "#a78bfa",
@@ -182,50 +168,74 @@ def _render_map_html(nodes: list, edges: list) -> str:
182
  "entry": "#0d2e22",
183
  "external": "#1a1a1e",
184
  }
185
- # Edge label colors by relationship type keywords
186
- edge_label_colors = {
187
- "passes": "#34d399",
188
- "delegates": "#4a9eff",
189
- "triggers": "#f87171",
190
- "returns": "#a78bfa",
191
- "sends": "#fbbf24",
192
- "initializes": "#34d399",
193
- "calls": "#6b7280",
194
- "default": "#9ca3af",
195
- }
196
 
197
- # Serialize node/edge data as proper JSON — safe, no f-string injection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  nodes_data = []
199
  for n in nodes:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  nodes_data.append({
201
- "id": n["id"],
202
- "label": n["label"],
203
- "kind": n["kind"],
204
- "file": n["file"],
205
- "line": n["line"],
206
  "description": n.get("description", ""),
207
  "explanation": n.get("explanation", ""),
208
- "color_border": kind_colors.get(n["kind"], "#888"),
209
- "color_bg": kind_bg.get(n["kind"], "#111"),
210
- "size": {"entry": 34, "class": 28, "function": 22, "external": 14}.get(n["kind"], 20),
211
  })
212
 
 
213
  edges_data = []
214
  for i, e in enumerate(edges):
215
- rel = e.get("relationship", "calls") or "calls"
216
- # Pick edge label color based on first word of relationship
217
- first_word = rel.split()[0].lower() if rel else "calls"
218
- label_color = edge_label_colors.get(first_word, edge_label_colors["default"])
 
 
 
 
 
 
 
 
 
219
  edges_data.append({
220
- "id": i,
221
- "from": e["source"],
222
- "to": e["target"],
223
- "relationship": rel,
224
- "label_color": label_color,
225
  })
226
 
227
- nodes_json = json.dumps(nodes_data)
228
- edges_json = json.dumps(edges_data)
 
 
229
 
230
  return f"""<!DOCTYPE html>
231
  <html>
@@ -236,226 +246,174 @@ def _render_map_html(nodes: list, edges: list) -> str:
236
  #wrap {{ display: flex; width: 100vw; height: 100vh; }}
237
  #graph {{ flex: 1; height: 100%; }}
238
  #panel {{
239
- width: 0; min-width: 0; height: 100%; overflow: hidden;
240
  background: #111113; border-left: 1px solid #1e1e22;
241
- transition: width 0.22s ease; display: flex; flex-direction: column; position: relative;
 
242
  }}
243
  #panel.open {{ width: 300px; min-width: 300px; }}
244
- #panel-inner {{ padding: 18px 16px; overflow-y: auto; height: 100%; }}
245
- .p-close {{ position: absolute; top: 10px; right: 10px; background: none; border: none; color: #444; font-size: 1rem; cursor: pointer; line-height: 1; }}
246
- .p-close:hover {{ color: #fff; }}
247
- .p-kind {{ font-family: 'IBM Plex Mono', monospace; font-size: 0.65rem; text-transform: uppercase; letter-spacing: 1.2px; margin-bottom: 5px; }}
248
- .p-name {{ font-family: 'IBM Plex Mono', monospace; font-size: 1.05rem; font-weight: 500; color: #f0f0f0; margin-bottom: 2px; word-break: break-all; }}
249
- .p-file {{ font-size: 0.68rem; color: #3a3a3a; margin-bottom: 14px; font-family: 'IBM Plex Mono', monospace; }}
250
- .p-section {{ font-size: 0.65rem; text-transform: uppercase; letter-spacing: 0.8px; color: #333; margin: 14px 0 5px; }}
251
- .p-short {{ font-size: 0.84rem; color: #ddd; line-height: 1.5; font-style: italic; margin-bottom: 4px; }}
252
- .p-text {{ font-size: 0.8rem; color: #aaa; line-height: 1.6; }}
253
- .p-rel {{ font-size: 0.72rem; color: #888; font-family: 'IBM Plex Mono', monospace;
254
- padding: 3px 8px; background: #1a1a1e; border-radius: 3px; margin: 3px 0; display: block;
255
- border-left: 2px solid #2a2a2e; }}
256
- #legend {{ position: absolute; bottom: 12px; left: 12px; display: flex; gap: 10px; flex-wrap: wrap; pointer-events: none; }}
257
- .leg {{ display: flex; align-items: center; gap: 5px; font-size: 0.67rem; color: #444; font-family: 'IBM Plex Mono', monospace; }}
258
- .leg-dot {{ width: 9px; height: 9px; border-radius: 50%; }}
259
-
260
-
261
-
262
-
263
-
264
-
265
-
266
-
267
-
268
-
269
-
270
-
271
-
272
-
273
-
274
-
275
-
276
-
277
  </style>
278
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@300;400;500&display=swap" rel="stylesheet">
279
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
 
 
 
280
  <div id="wrap">
281
  <div id="graph"></div>
282
  <div id="panel">
283
  <button class="p-close" onclick="closePanel()">✕</button>
284
-
285
-
286
-
287
  <div id="panel-inner"></div>
288
  </div>
289
  </div>
 
 
 
 
 
 
 
 
 
 
 
290
  <div class="leg"><div class="leg-dot" style="background:#a78bfa"></div>class</div>
291
  <div class="leg"><div class="leg-dot" style="background:#6b7280"></div>external</div>
292
  </div>
293
-
294
-
295
-
296
-
297
-
298
  <script>
299
- // Data injected as proper JSON — no f-string escaping issues
300
- var nodesData = {nodes_json};
301
- var edgesData = {edges_json};
302
-
303
-
304
  var nodeIndex = {{}};
305
  nodesData.forEach(function(n) {{ nodeIndex[n.id] = n; }});
306
-
307
- // Build vis datasets
308
- var visNodes = new vis.DataSet(nodesData.map(function(n) {{
309
- return {{
310
- id: n.id,
311
- label: n.label,
312
- color: {{
313
- background: n.color_bg,
314
- border: n.color_border,
315
- highlight: {{ background: n.color_border + '22', border: n.color_border }},
316
- hover: {{ background: n.color_border + '18', border: n.color_border }}
317
- }},
318
- font: {{ color: n.color_border, size: 12, face: 'IBM Plex Mono' }},
319
- size: n.size,
320
- shape: 'dot',
321
- borderWidth: 2,
322
- borderWidthSelected: 3,
323
- title: n.description || n.label,
324
- }};
325
- }}));
326
-
327
- var visEdges = new vis.DataSet(edgesData.map(function(e) {{
328
- return {{
329
- id: e.id,
330
- from: e.from,
331
- to: e.to,
332
- label: e.relationship,
333
- font: {{
334
- color: e.label_color,
335
- size: 10,
336
- face: 'IBM Plex Mono',
337
- align: 'middle',
338
- background: '#111113', // label background — makes it visible on dark edges
339
- strokeWidth: 0,
340
  }},
341
- color: {{ color: '#2a2a3a', highlight: '#4a9eff', hover: '#555' }},
342
- arrows: {{ to: {{ enabled: true, scaleFactor: 0.5 }} }},
343
- width: 1.2,
344
- smooth: {{ type: 'dynamic' }}, // curved edges — not straight
345
- }};
346
- }}));
347
-
348
  enabled: true,
349
  solver: 'forceAtlas2Based',
350
  forceAtlas2Based: {{
351
  gravitationalConstant: -80,
352
  centralGravity: 0.01,
353
- springLength: 120,
354
  springConstant: 0.08,
355
- damping: 0.4,
356
- avoidOverlap: 1,
357
  }},
358
- stabilization: {{ iterations: 200, fit: true }},
 
 
 
 
 
359
  }},
360
  interaction: {{
361
- hover: true,
362
- tooltipDelay: 100,
363
- navigationButtons: false,
364
- keyboard: true,
365
- zoomView: true,
366
-
367
  }},
368
- nodes: {{ borderWidth: 2, borderWidthSelected: 3 }},
369
- edges: {{ chosen: true }},
370
- layout: {{ improvedLayout: true }},
371
  }}
372
  );
373
-
374
- // Disable physics after stabilization for clean static view
375
- network.on('stabilized', function() {{
376
  network.setOptions({{ physics: {{ enabled: false }} }});
377
- network.fit({{ animation: {{ duration: 600, easingFunction: 'easeInOutQuad' }} }});
378
  network.on('click', function(params) {{
379
  if (params.nodes.length > 0) {{
380
- showPanel(params.nodes[0]);
381
-
382
-
 
383
  }}
384
  }});
385
-
386
- if (!n) return;
387
- var color = n.color_border;
388
-
389
-
390
- var callers = edgesData
391
- .filter(function(e) {{ return e.to === nid; }})
392
  .map(function(e) {{
393
- var src = nodeIndex[e.from];
394
- var lbl = src ? src.label : e.from.split('::').pop();
395
- return '<span class="p-rel" style="border-left-color:' + (src ? src.color_border : '#444') + '">← ' + lbl + (e.relationship ? ' <span style="color:#555">(' + e.relationship + ')</span>' : '') + '</span>';
396
-
397
-
398
  }}).join('');
399
-
400
- var callees = edgesData
401
  .map(function(e) {{
402
- var tgt = nodeIndex[e.to];
403
- var lbl = tgt ? tgt.label : e.to.split('::').pop();
404
- return '<span class="p-rel" style="border-left-color:' + (tgt ? tgt.color_border : '#444') + '">→ ' + lbl + (e.relationship ? ' <span style="color:#555">(' + e.relationship + ')</span>' : '') + '</span>';
405
-
406
-
407
  }}).join('');
408
-
409
-
410
  document.getElementById('panel-inner').innerHTML =
411
  '<div class="p-kind" style="color:' + color + '">' + n.kind + '</div>' +
412
  '<div class="p-name">' + n.label + '</div>' +
413
  '<div class="p-file">' + n.file + ':' + n.line + '</div>' +
414
  (n.description ? '<div class="p-short">' + n.description + '</div>' : '') +
415
  (n.explanation ? '<div class="p-section">what it does</div><div class="p-text">' + n.explanation + '</div>' : '') +
416
-
417
-
418
-
419
-
420
- '<div class="p-section">called by</div>' +
421
- (callers || '<div class="p-text" style="color:#333">entry point</div>') +
422
- '<div class="p-section">calls</div>' +
423
- (callees || '<div class="p-text" style="color:#333">nothing</div>');
424
-
425
  document.getElementById('panel').classList.add('open');
426
  }}
 
427
  document.getElementById('panel').classList.remove('open');
428
- network.unselectAll();
429
  }}
430
-
431
  network.on('deselectNode', function() {{
432
  document.getElementById('panel').classList.remove('open');
433
  }});
434
  </script>
435
  </body>
436
  </html>"""
 
 
 
437
  # SIDEBAR
438
  # ══════════════════════════════════════════════════════
439
  with st.sidebar:
440
  st.markdown("#### 🔬 secforge")
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
-
449
-
450
  st.caption(f"session `{SID}` · 🔒 encrypted")
451
 
452
- new_label = st.text_input(
453
- "session name", value=st.session_state.session_label,
454
- label_visibility="collapsed", placeholder="session name…", key="label_input",
455
- )
456
  if new_label != st.session_state.session_label:
457
  st.session_state.session_label = new_label
458
  _save()
 
 
 
 
 
 
 
 
 
 
459
  st.session_state.last_analysis = None
460
  _save()
461
  st.rerun()
@@ -463,43 +421,88 @@ with st.sidebar:
463
  if st.button("🔒 lock", use_container_width=True):
464
  for k in list(st.session_state.keys()):
465
  del st.session_state[k]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466
  st.markdown("<hr>", unsafe_allow_html=True)
467
  st.markdown("**project context**")
468
 
469
- # Fix: process uploaded files immediately, check by name to avoid reprocessing
470
-
471
-
472
-
473
- uploaded = st.file_uploader(
474
- "add files", label_visibility="collapsed",
475
  type=["py","js","ts","jsx","tsx","java","cpp","c","cs","go","rs","txt","md","png","jpg","jpeg","webp"],
476
- accept_multiple_files=True,
477
- key="file_uploader",
478
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
 
480
  if uploaded:
 
 
481
  fname = f.name
482
  ext = fname.rsplit(".", 1)[-1].lower()
483
  is_image = ext in ("png", "jpg", "jpeg", "webp")
484
- # Always process — don't skip based on linked_files check
485
- # (that was causing files to be ignored on re-render)
 
486
  if is_image:
487
- if fname not in st.session_state.linked_files:
488
- st.session_state.linked_files.append(fname)
 
489
  try:
490
  text = f.getvalue().decode("utf-8")
491
  language = detect_language(fname)
492
- # Only re-index if content changed
493
- existing = st.session_state.file_contents.get(fname)
494
- if existing is None or (isinstance(existing, tuple) and existing[0] != text):
495
- st.session_state.file_contents[fname] = (text, language)
 
496
  if changed:
497
  _save()
 
498
 
499
- # Show loaded files with remove buttons
500
  for fname in list(st.session_state.linked_files):
501
  col_f, col_x = st.columns([5, 1])
502
  with col_f:
 
 
 
 
 
 
 
 
 
503
 
504
 
505
  # ══════════════════════════════════════════════════════
@@ -507,47 +510,84 @@ with st.sidebar:
507
  # ══════════════════════════════════════════════════════
508
  st.markdown("#### 🔬 secforge")
509
  st.caption("code analysis · multi-language · context-aware · 🔒 private")
 
 
 
 
 
 
 
 
 
 
510
  if msg.get("analysis"):
511
  _render_analysis(msg["analysis"])
512
 
513
- img_upload = st.file_uploader(
514
- "attach image", type=["png","jpg","jpeg","webp"],
515
- label_visibility="collapsed", key="inline_img",
516
- )
517
  prompt = st.chat_input("paste code, ask a question, or both…")
518
 
519
  if prompt or img_upload:
 
 
 
 
 
 
 
 
 
 
520
  context = query_context(SID, user_content) if st.session_state.linked_files else ""
521
  linked = [f for f in st.session_state.linked_files
522
  if not f.endswith((".png",".jpg",".jpeg",".webp"))]
523
-
524
  if img_upload:
525
- response = vision_response(
526
- user_content, img_upload.getvalue(),
527
- media_type=f"image/{img_upload.name.rsplit('.',1)[-1].lower()}",
528
- context=context,
529
- )
530
  st.markdown(response)
531
  st.session_state.messages.append({"role": "assistant", "content": response})
532
  else:
533
  intent = detect_intent(user_content)
534
  msg_entry = {"role": "assistant", "content": "", "analysis": None}
535
-
536
  if intent in ("analyze", "mixed"):
537
  try:
538
  result = analyze_code(user_content)
 
 
 
 
539
  except Exception as e:
540
  st.error(f"analysis failed: {e}")
541
  msg_entry["content"] = f"Analysis failed: {e}"
542
-
543
  if intent in ("chat", "mixed"):
544
  response = chat_response(user_content, st.session_state.messages, context, linked)
545
  st.markdown(response)
546
  msg_entry["content"] = (msg_entry["content"] + "\n\n" + response).strip()
547
-
548
  st.session_state.messages.append(msg_entry)
549
  except Exception as e:
550
  st.error(f"something went wrong: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551
  show_external = st.toggle("show external calls", value=False)
552
 
553
  if build_btn:
@@ -555,6 +595,38 @@ st.caption("code analysis · multi-language · context-aware · 🔒 private")
555
  try:
556
  graph = build_graph(code_files)
557
  st.session_state.map_data = graph.to_dict()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  color = kind_colors.get(kind, "#888")
559
  with stat_cols[i]:
560
  st.markdown(
@@ -565,11 +637,15 @@ st.caption("code analysis · multi-language · context-aware · 🔒 private")
565
  unsafe_allow_html=True,
566
  )
567
 
568
- st.caption("click any node to see full description and relationships")
569
  st.markdown("<hr>", unsafe_allow_html=True)
570
 
571
  if nodes:
572
  html = _render_map_html(nodes, edges)
573
  components.html(html, height=680, scrolling=False)
574
  else:
575
- st.info("no nodes to display with current filter.")
 
 
 
 
 
1
  import streamlit as st
2
  import streamlit.components.v1 as components
3
+ import json
 
 
 
 
 
4
  from app.orchestrator import analyze_code
5
  from app.modules.llm import chat_response, vision_response
6
+ from app.modules.language_detector import detect_language
7
+ from app.utils.rag import add_file, remove_file, query_context
8
+ from app.utils.intent_detector import detect_intent
9
+ from app.utils.session_manager import get_session, save_session, delete_session, rename_session
10
+ from app.utils.crypto import derive_session_id
11
+ from app.utils.map_builder import build_graph
12
+ from app.utils.exporter import export_markdown, export_docx, export_pdf
13
 
14
  st.set_page_config(page_title="secforge", page_icon="🔬", layout="wide")
15
 
16
  st.markdown("""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  <style>
18
  @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@300;400;500&display=swap');
19
  html, body, [class*="css"] { font-family: 'IBM Plex Sans', sans-serif; }
 
46
 
47
  # ══════════════════════════════════════════════════════
48
  # PASSWORD GATE
 
 
49
  # ══════════════════════════════════════════════════════
50
  def _show_password_gate():
51
  st.markdown("#### 🔬 secforge")
52
+ st.markdown("<hr>", unsafe_allow_html=True)
53
+ st.markdown("**your session is private and encrypted.**")
54
+ st.caption("set a password to create a new session, or enter your existing one to restore it.")
55
+ st.caption("⚠ if you forget your password, your data cannot be recovered.")
56
  col1, col2 = st.columns([3, 1])
57
  with col1:
58
+ st.text_input("password", type="password", placeholder="enter a password…",
59
+ label_visibility="collapsed", key="pw_input")
 
 
 
 
 
60
  with col2:
61
  enter = st.button("→ enter", type="primary", use_container_width=True)
62
+ if enter:
63
+ password = st.session_state.get("pw_input", "")
 
 
 
 
 
64
  if not password:
65
  st.warning("enter a password first")
66
  return
67
  if len(password) < 4:
68
  st.error("password must be at least 4 characters")
69
  return
 
70
  sid = derive_session_id(password)
71
  try:
72
  data = get_session(sid, password)
73
+ st.session_state.authenticated = True
74
+ st.session_state.session_id = sid
75
+ st.session_state.password = password
76
+ st.session_state.messages = data.get("messages", [])
77
+ st.session_state.linked_files = data.get("linked_files", [])
78
+ st.session_state.session_label = data.get("label", "untitled session")
79
+ st.session_state.map_data = data.get("map_data", None)
80
+ st.session_state.last_analysis = None
81
+ raw = data.get("file_contents", {})
82
+ # Fixed: explicit loop avoids dict comprehension indentation issues
83
+ st.session_state.file_contents = {}
84
+ for fname, v in raw.items():
85
+ st.session_state.file_contents[fname] = tuple(v) if isinstance(v, list) else v
86
  for fname, contents in st.session_state.file_contents.items():
87
+ if isinstance(contents, tuple) and contents[1] != "image":
88
  try:
89
+ add_file(sid, fname, contents[0])
90
+ except Exception:
91
+ pass
92
+ st.rerun()
93
  except ValueError:
94
  st.error("wrong password — session exists but password does not match.")
95
  except Exception as e:
96
+ st.error(f"error: {e}")
97
 
98
 
99
  if not st.session_state.get("authenticated"):
100
  _show_password_gate()
101
  st.stop()
102
 
 
103
  SID = st.session_state.session_id
104
  PASSWORD = st.session_state.password
105
 
106
+
107
+ # ══════════════════════════════════════════════════════
108
+ # HELPERS
109
+ # ══════════════════════════════════════════════════════
110
+ def _save():
111
+ serializable = {
112
+ fname: list(v) if isinstance(v, tuple) else v
113
  for fname, v in st.session_state.file_contents.items()
114
  }
115
  try:
116
+ save_session(SID, PASSWORD, st.session_state.messages,
117
+ st.session_state.linked_files, serializable,
118
+ st.session_state.session_label, st.session_state.map_data)
 
 
 
 
 
119
  except Exception as e:
120
  st.error(f"save failed: {e}")
121
 
122
+
123
+ def _render_analysis(result: dict):
124
+ if not result:
125
+ return
126
+ if result.get("error"):
127
+ st.error(f"analysis error: {result['error']}")
128
+ return
129
+ st.markdown(f"`{result.get('language_display', '')}` detected")
130
+ exp = result.get("explanation", {})
131
+ if exp and "error" not in exp:
132
+ with st.expander("explanation", expanded=True):
133
+ c1, c2 = st.columns(2)
134
+ with c1:
135
+ st.markdown(f"**summary** — {exp.get('summary', 'N/A')}")
136
+ st.markdown(f"**inputs** — {exp.get('inputs', 'N/A')}")
137
+ st.markdown(f"**outputs** — {exp.get('outputs', 'N/A')}")
138
+ with c2:
139
+ st.markdown(f"**logic** — {exp.get('logic', 'N/A')}")
140
+ st.markdown(f"**assumptions** — {exp.get('assumptions', 'N/A')}")
141
+ issues = result.get("issues", [])
142
+ st.markdown(f"**issues** — {len(issues)} found")
143
+ if issues:
144
+ for iss in issues:
145
+ sev = iss.get("severity", "low")
146
+ dot = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(sev, "⚪")
147
  st.markdown(f"{dot} `line {iss['line']}` `{iss['symbol']}` · {iss['message']} *{iss['category']}*")
148
  else:
149
  st.markdown("*no issues found*")
 
155
  st.code(fix["fix"], language=result.get("language", "python"))
156
 
157
 
 
 
 
 
 
 
 
 
 
 
 
158
  def _render_map_html(nodes: list, edges: list) -> str:
 
 
 
 
 
 
 
159
  kind_colors = {
160
  "function": "#4a9eff",
161
  "class": "#a78bfa",
 
168
  "entry": "#0d2e22",
169
  "external": "#1a1a1e",
170
  }
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ # Edge label color-coding by relationship keyword
173
+ def _edge_label_color(rel: str) -> str:
174
+ rel_lower = rel.lower()
175
+ if any(k in rel_lower for k in ("auth", "verif", "check", "valid")):
176
+ return "#f59e0b" # amber — security/validation
177
+ if any(k in rel_lower for k in ("parse", "read", "load", "fetch", "decode")):
178
+ return "#34d399" # green — data input
179
+ if any(k in rel_lower for k in ("write", "save", "export", "send", "emit")):
180
+ return "#f472b6" # pink — data output
181
+ if any(k in rel_lower for k in ("init", "creat", "setup", "build")):
182
+ return "#a78bfa" # purple — construction
183
+ if any(k in rel_lower for k in ("error", "fail", "except", "handl")):
184
+ return "#ef4444" # red — error handling
185
+ return "#6b93c4" # default blue-grey
186
+
187
+ nodes_js = []
188
  nodes_data = []
189
  for n in nodes:
190
+ color = kind_colors.get(n["kind"], "#888")
191
+ bg = kind_bg.get(n["kind"], "#111")
192
+ size = {"entry": 34, "class": 28, "function": 22, "external": 14}.get(n["kind"], 20)
193
+ label = n["label"].replace("'", "\\'").replace('"', '\\"')
194
+ desc = (n.get("description") or "").replace("'", "\\'").replace('"', '\\"').replace("\n", " ")
195
+ explanation = (n.get("explanation") or "").replace("'", "\\'").replace('"', '\\"').replace("\n", " ")
196
+ file_line = f"{n['file']}:{n['line']}".replace("'", "\\'")
197
+ kind = n["kind"]
198
+ nid = n["id"].replace("'", "\\'")
199
+
200
+ nodes_js.append(
201
+ f"{{id: '{nid}', label: '{label}', "
202
+ f"color: {{background: '{bg}', border: '{color}', highlight: {{background: '{color}22', border: '{color}'}}, hover: {{background: '{color}22', border: '{color}'}}}}, "
203
+ f"font: {{color: '{color}', size: 13, face: 'IBM Plex Mono', bold: {{color: '#fff', size: 14}}}}, "
204
+ f"size: {size}, shape: 'dot', borderWidth: 2, borderWidthSelected: 3, "
205
+ f"title: '{desc}'}}"
206
+ )
207
  nodes_data.append({
208
+ "id": n["id"], "label": n["label"], "kind": kind,
209
+ "file": n["file"], "line": n["line"],
 
 
 
210
  "description": n.get("description", ""),
211
  "explanation": n.get("explanation", ""),
 
 
 
212
  })
213
 
214
+ edges_js = []
215
  edges_data = []
216
  for i, e in enumerate(edges):
217
+ src = e["source"].replace("'", "\\'")
218
+ tgt = e["target"].replace("'", "\\'")
219
+ rel = (e.get("relationship") or "calls").replace("'", "\\'").replace('"', '\\"')
220
+ lcolor = _edge_label_color(rel)
221
+ edges_js.append(
222
+ f"{{id: {i}, from: '{src}', to: '{tgt}', "
223
+ f"label: '{rel}', "
224
+ f"font: {{color: '{lcolor}', size: 11, face: 'IBM Plex Mono', align: 'middle', "
225
+ f"strokeWidth: 3, strokeColor: '#0e0e10', background: '#111820'}}, "
226
+ f"color: {{color: '#2a2a3a', highlight: '{lcolor}', hover: '{lcolor}88'}}, "
227
+ f"arrows: {{to: {{enabled: true, scaleFactor: 0.6}}}}, "
228
+ f"width: 1.5, smooth: {{type: 'curvedCW', roundness: 0.2}}}}"
229
+ )
230
  edges_data.append({
231
+ "source": e["source"], "target": e["target"],
232
+ "relationship": e.get("relationship", "calls"),
 
 
 
233
  })
234
 
235
+ nodes_js_str = ",\n".join(nodes_js)
236
+ edges_js_str = ",\n".join(edges_js)
237
+ nodes_data_json = json.dumps(nodes_data)
238
+ edges_data_json = json.dumps(edges_data)
239
 
240
  return f"""<!DOCTYPE html>
241
  <html>
 
246
  #wrap {{ display: flex; width: 100vw; height: 100vh; }}
247
  #graph {{ flex: 1; height: 100%; }}
248
  #panel {{
249
+ width: 0; min-width: 0; height: 100%;
250
  background: #111113; border-left: 1px solid #1e1e22;
251
+ overflow: hidden; transition: width 0.25s ease;
252
+ display: flex; flex-direction: column;
253
  }}
254
  #panel.open {{ width: 300px; min-width: 300px; }}
255
+ #panel-inner {{ padding: 18px; overflow-y: auto; height: 100%; }}
256
+ .p-kind {{ font-family: 'IBM Plex Mono', monospace; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }}
257
+ .p-name {{ font-family: 'IBM Plex Mono', monospace; font-size: 1.1rem; font-weight: 500; color: #f0f0f0; margin-bottom: 2px; }}
258
+ .p-file {{ font-size: 0.7rem; color: #444; margin-bottom: 14px; font-family: 'IBM Plex Mono', monospace; }}
259
+ .p-section {{ font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.8px; color: #444; margin: 12px 0 4px; }}
260
+ .p-text {{ font-size: 0.82rem; color: #bbb; line-height: 1.5; }}
261
+ .p-short {{ font-size: 0.85rem; color: #ddd; line-height: 1.4; margin-bottom: 8px; font-style: italic; }}
262
+ .p-rel {{ font-size: 0.75rem; color: #666; font-family: 'IBM Plex Mono', monospace; padding: 3px 6px; background: #1a1a1e; border-radius: 3px; margin: 2px 0; display: block; }}
263
+ .p-close {{ position: absolute; top: 12px; right: 12px; background: none; border: none; color: #555; font-size: 1rem; cursor: pointer; }}
264
+ #panel {{ position: relative; }}
265
+ #legend {{
266
+ position: absolute; bottom: 12px; left: 12px;
267
+ display: flex; gap: 10px; flex-wrap: wrap;
268
+ pointer-events: none;
269
+ }}
270
+ .leg {{ display: flex; align-items: center; gap: 4px; font-size: 0.68rem; color: #555; font-family: 'IBM Plex Mono', monospace; }}
271
+ .leg-dot {{ width: 8px; height: 8px; border-radius: 50%; }}
272
+ #edge-legend {{
273
+ position: absolute; bottom: 32px; left: 12px;
274
+ display: flex; gap: 8px; flex-wrap: wrap;
275
+ pointer-events: none; margin-bottom: 4px;
276
+ }}
277
+ .eleg {{ display: flex; align-items: center; gap: 4px; font-size: 0.62rem; color: #555; font-family: 'IBM Plex Mono', monospace; }}
278
+ .eleg-line {{ width: 16px; height: 2px; border-radius: 1px; }}
 
 
 
 
 
 
 
 
 
279
  </style>
280
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@300;400;500&display=swap" rel="stylesheet">
281
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
282
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css"/>
283
+ </head>
284
+ <body>
285
  <div id="wrap">
286
  <div id="graph"></div>
287
  <div id="panel">
288
  <button class="p-close" onclick="closePanel()">✕</button>
 
 
 
289
  <div id="panel-inner"></div>
290
  </div>
291
  </div>
292
+ <div id="edge-legend">
293
+ <div class="eleg"><div class="eleg-line" style="background:#f59e0b"></div>auth/validate</div>
294
+ <div class="eleg"><div class="eleg-line" style="background:#34d399"></div>read/load</div>
295
+ <div class="eleg"><div class="eleg-line" style="background:#f472b6"></div>write/send</div>
296
+ <div class="eleg"><div class="eleg-line" style="background:#a78bfa"></div>init/build</div>
297
+ <div class="eleg"><div class="eleg-line" style="background:#ef4444"></div>error/handle</div>
298
+ <div class="eleg"><div class="eleg-line" style="background:#6b93c4"></div>calls</div>
299
+ </div>
300
+ <div id="legend">
301
+ <div class="leg"><div class="leg-dot" style="background:#34d399"></div>entry</div>
302
+ <div class="leg"><div class="leg-dot" style="background:#4a9eff"></div>function</div>
303
  <div class="leg"><div class="leg-dot" style="background:#a78bfa"></div>class</div>
304
  <div class="leg"><div class="leg-dot" style="background:#6b7280"></div>external</div>
305
  </div>
 
 
 
 
 
306
  <script>
307
+ var nodesData = {nodes_data_json};
308
+ var edgesData = {edges_data_json};
 
 
 
309
  var nodeIndex = {{}};
310
  nodesData.forEach(function(n) {{ nodeIndex[n.id] = n; }});
311
+ var kindColors = {{
312
+ "function": "#4a9eff", "class": "#a78bfa",
313
+ "entry": "#34d399", "external": "#6b7280"
314
+ }};
315
+ var nodes = new vis.DataSet([{nodes_js_str}]);
316
+ var edges = new vis.DataSet([{edges_js_str}]);
317
+ var container = document.getElementById('graph');
318
+ var network = new vis.Network(container,
319
+ {{nodes: nodes, edges: edges}},
320
+ {{
321
+ layout: {{
322
+ improvedLayout: true,
323
+ randomSeed: 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  }},
325
+ physics: {{
 
 
 
 
 
 
326
  enabled: true,
327
  solver: 'forceAtlas2Based',
328
  forceAtlas2Based: {{
329
  gravitationalConstant: -80,
330
  centralGravity: 0.01,
331
+ springLength: 140,
332
  springConstant: 0.08,
333
+ damping: 0.5,
334
+ avoidOverlap: 0.8
335
  }},
336
+ stabilization: {{
337
+ enabled: true,
338
+ iterations: 300,
339
+ updateInterval: 25,
340
+ fit: true
341
+ }}
342
  }},
343
  interaction: {{
344
+ hover: true, tooltipDelay: 150,
345
+ navigationButtons: true, keyboard: true, zoomView: true
 
 
 
 
346
  }},
347
+ nodes: {{ borderWidth: 2, borderWidthSelected: 3, chosen: true }},
348
+ edges: {{ chosen: true }}
 
349
  }}
350
  );
351
+ network.once('stabilizationIterationsDone', function() {{
 
 
352
  network.setOptions({{ physics: {{ enabled: false }} }});
353
+ }});
354
  network.on('click', function(params) {{
355
  if (params.nodes.length > 0) {{
356
+ var nid = params.nodes[0];
357
+ var n = nodeIndex[nid];
358
+ if (!n) return;
359
+ showPanel(n, nid);
360
  }}
361
  }});
362
+ function showPanel(n, nid) {{
363
+ var color = kindColors[n.kind] || '#888';
364
+ var callers = edgesData.filter(function(e) {{ return e.target === nid; }})
 
 
 
 
365
  .map(function(e) {{
366
+ var src = nodeIndex[e.source];
367
+ return '<span class="p-rel">← ' + (src ? src.label : e.source.split("::").pop()) + (e.relationship ? ' (' + e.relationship + ')' : '') + '</span>';
 
 
 
368
  }}).join('');
369
+ var callees = edgesData.filter(function(e) {{ return e.source === nid; }})
 
370
  .map(function(e) {{
371
+ var tgt = nodeIndex[e.target];
372
+ return '<span class="p-rel">→ ' + (tgt ? tgt.label : e.target.split("::").pop()) + (e.relationship ? ' (' + e.relationship + ')' : '') + '</span>';
 
 
 
373
  }}).join('');
 
 
374
  document.getElementById('panel-inner').innerHTML =
375
  '<div class="p-kind" style="color:' + color + '">' + n.kind + '</div>' +
376
  '<div class="p-name">' + n.label + '</div>' +
377
  '<div class="p-file">' + n.file + ':' + n.line + '</div>' +
378
  (n.description ? '<div class="p-short">' + n.description + '</div>' : '') +
379
  (n.explanation ? '<div class="p-section">what it does</div><div class="p-text">' + n.explanation + '</div>' : '') +
380
+ (callers ? '<div class="p-section">called by</div>' + callers : '<div class="p-section">called by</div><div class="p-text" style="color:#444">entry point</div>') +
381
+ (callees ? '<div class="p-section">calls</div>' + callees : '');
 
 
 
 
 
 
 
382
  document.getElementById('panel').classList.add('open');
383
  }}
384
+ function closePanel() {{
385
  document.getElementById('panel').classList.remove('open');
 
386
  }}
 
387
  network.on('deselectNode', function() {{
388
  document.getElementById('panel').classList.remove('open');
389
  }});
390
  </script>
391
  </body>
392
  </html>"""
393
+
394
+
395
+ # ══════════════════════════════════════════════════════
396
  # SIDEBAR
397
  # ══════════════════════════════════════════════════════
398
  with st.sidebar:
399
  st.markdown("#### 🔬 secforge")
 
 
 
 
 
 
 
 
 
400
  st.caption(f"session `{SID}` · 🔒 encrypted")
401
 
402
+ new_label = st.text_input("session name", value=st.session_state.session_label,
403
+ label_visibility="collapsed", placeholder="session name…", key="label_input")
 
 
404
  if new_label != st.session_state.session_label:
405
  st.session_state.session_label = new_label
406
  _save()
407
+
408
+ c1, c2 = st.columns(2)
409
+ with c1:
410
+ if st.button("+ new", use_container_width=True):
411
+ for k in list(st.session_state.keys()):
412
+ del st.session_state[k]
413
+ st.rerun()
414
+ with c2:
415
+ if st.button("🗑 clear", use_container_width=True):
416
+ st.session_state.messages = []
417
  st.session_state.last_analysis = None
418
  _save()
419
  st.rerun()
 
421
  if st.button("🔒 lock", use_container_width=True):
422
  for k in list(st.session_state.keys()):
423
  del st.session_state[k]
424
+ st.rerun()
425
+
426
+ st.markdown("**export**")
427
+ e1, e2, e3 = st.columns(3)
428
+ with e1:
429
+ st.download_button("md",
430
+ data=export_markdown(st.session_state.session_label, st.session_state.messages,
431
+ st.session_state.get("last_analysis"), st.session_state.map_data),
432
+ file_name=f"secforge_{SID}.md", mime="text/markdown", use_container_width=True)
433
+ with e2:
434
+ st.download_button("docx",
435
+ data=export_docx(st.session_state.session_label, st.session_state.messages,
436
+ st.session_state.get("last_analysis"), st.session_state.map_data),
437
+ file_name=f"secforge_{SID}.docx",
438
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
439
+ use_container_width=True)
440
+ with e3:
441
+ st.download_button("pdf",
442
+ data=export_pdf(st.session_state.session_label, st.session_state.messages,
443
+ st.session_state.get("last_analysis"), st.session_state.map_data),
444
+ file_name=f"secforge_{SID}.pdf", mime="application/pdf", use_container_width=True)
445
+
446
  st.markdown("<hr>", unsafe_allow_html=True)
447
  st.markdown("**project context**")
448
 
449
+ uploaded = st.file_uploader("add files", label_visibility="collapsed",
 
 
 
 
 
450
  type=["py","js","ts","jsx","tsx","java","cpp","c","cs","go","rs","txt","md","png","jpg","jpeg","webp"],
451
+ accept_multiple_files=True, key="file_uploader_widget")
452
+
453
+ # Add Ctrl+U keyboard shortcut for file upload
454
+ components.html("""
455
+ <script>
456
+ document.addEventListener('keydown', function(e) {
457
+ if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
458
+ e.preventDefault();
459
+ // Find and click the file uploader input
460
+ const fileInput = document.querySelector('input[type="file"]');
461
+ if (fileInput) {
462
+ fileInput.click();
463
+ }
464
+ }
465
+ });
466
+ </script>
467
+ """, height=0)
468
 
469
  if uploaded:
470
+ changed = False
471
+ for f in uploaded:
472
  fname = f.name
473
  ext = fname.rsplit(".", 1)[-1].lower()
474
  is_image = ext in ("png", "jpg", "jpeg", "webp")
475
+ if fname not in st.session_state.linked_files:
476
+ st.session_state.linked_files.append(fname)
477
+ changed = True
478
  if is_image:
479
+ st.session_state.file_contents[fname] = (f.getvalue(), "image")
480
+ changed = True
481
+ else:
482
  try:
483
  text = f.getvalue().decode("utf-8")
484
  language = detect_language(fname)
485
+ st.session_state.file_contents[fname] = (text, language)
486
+ changed = True
487
+ add_file(SID, fname, text)
488
+ except Exception as ex:
489
+ st.warning(f"could not read {fname}: {ex}")
490
  if changed:
491
  _save()
492
+ st.rerun()
493
 
 
494
  for fname in list(st.session_state.linked_files):
495
  col_f, col_x = st.columns([5, 1])
496
  with col_f:
497
+ icon = "🖼" if fname.rsplit(".", 1)[-1].lower() in ("png","jpg","jpeg","webp") else "📄"
498
+ st.markdown(f"<span class='file-chip'>{icon} {fname}</span>", unsafe_allow_html=True)
499
+ with col_x:
500
+ if st.button("×", key=f"rm_{fname}"):
501
+ st.session_state.linked_files.remove(fname)
502
+ st.session_state.file_contents.pop(fname, None)
503
+ remove_file(SID, fname)
504
+ _save()
505
+ st.rerun()
506
 
507
 
508
  # ══════════════════════════════════════════════════════
 
510
  # ══════════════════════════════════════════════════════
511
  st.markdown("#### 🔬 secforge")
512
  st.caption("code analysis · multi-language · context-aware · 🔒 private")
513
+ st.markdown("<hr style='margin:0.3rem 0 0.8rem'>", unsafe_allow_html=True)
514
+
515
+ tab_workspace, tab_map = st.tabs(["workspace", "map"])
516
+
517
+
518
+ # ── WORKSPACE ─────────────────────────────────────────
519
+ with tab_workspace:
520
+ for msg in st.session_state.messages:
521
+ with st.chat_message(msg["role"]):
522
+ st.markdown(msg["content"])
523
  if msg.get("analysis"):
524
  _render_analysis(msg["analysis"])
525
 
526
+ img_upload = st.file_uploader("attach image", type=["png","jpg","jpeg","webp"],
527
+ label_visibility="collapsed", key="inline_img")
 
 
528
  prompt = st.chat_input("paste code, ask a question, or both…")
529
 
530
  if prompt or img_upload:
531
+ user_content = prompt or "what is in this image?"
532
+ st.session_state.messages.append({"role": "user", "content": user_content})
533
+ with st.chat_message("user"):
534
+ st.markdown(user_content)
535
+ if img_upload:
536
+ st.image(img_upload, width=300)
537
+
538
+ with st.chat_message("assistant"):
539
+ with st.spinner(""):
540
+ try:
541
  context = query_context(SID, user_content) if st.session_state.linked_files else ""
542
  linked = [f for f in st.session_state.linked_files
543
  if not f.endswith((".png",".jpg",".jpeg",".webp"))]
 
544
  if img_upload:
545
+ response = vision_response(user_content, img_upload.getvalue(),
546
+ media_type=f"image/{img_upload.name.rsplit('.',1)[-1].lower()}", context=context)
 
 
 
547
  st.markdown(response)
548
  st.session_state.messages.append({"role": "assistant", "content": response})
549
  else:
550
  intent = detect_intent(user_content)
551
  msg_entry = {"role": "assistant", "content": "", "analysis": None}
 
552
  if intent in ("analyze", "mixed"):
553
  try:
554
  result = analyze_code(user_content)
555
+ st.session_state.last_analysis = result
556
+ _render_analysis(result)
557
+ msg_entry["analysis"] = result
558
+ msg_entry["content"] = f"[{result.get('language_display','code')} · {result.get('total_issues',0)} issues]"
559
  except Exception as e:
560
  st.error(f"analysis failed: {e}")
561
  msg_entry["content"] = f"Analysis failed: {e}"
 
562
  if intent in ("chat", "mixed"):
563
  response = chat_response(user_content, st.session_state.messages, context, linked)
564
  st.markdown(response)
565
  msg_entry["content"] = (msg_entry["content"] + "\n\n" + response).strip()
 
566
  st.session_state.messages.append(msg_entry)
567
  except Exception as e:
568
  st.error(f"something went wrong: {e}")
569
+ _save()
570
+
571
+
572
+ # ── MAP ───────────────────────────────────────────────
573
+ with tab_map:
574
+ code_files = {
575
+ fname: contents
576
+ for fname, contents in st.session_state.file_contents.items()
577
+ if isinstance(contents, (tuple, list)) and len(contents) == 2 and contents[1] != "image"
578
+ }
579
+
580
+ if not code_files:
581
+ if st.session_state.linked_files:
582
+ st.warning("file names saved but contents need re-uploading — please re-upload via sidebar.")
583
+ else:
584
+ st.markdown("*load code files via the sidebar to generate a map.*")
585
+ else:
586
+ st.markdown(f"**{len(code_files)} file(s)** — `{'`, `'.join(code_files.keys())}`")
587
+ mc1, mc2 = st.columns([2, 2])
588
+ with mc1:
589
+ build_btn = st.button("→ build map", type="primary", use_container_width=True)
590
+ with mc2:
591
  show_external = st.toggle("show external calls", value=False)
592
 
593
  if build_btn:
 
595
  try:
596
  graph = build_graph(code_files)
597
  st.session_state.map_data = graph.to_dict()
598
+ _save()
599
+ if not graph.nodes:
600
+ st.warning("no functions or classes found.")
601
+ except Exception as e:
602
+ st.error(f"map build failed: {e}")
603
+
604
+ if st.session_state.map_data:
605
+ gdata = st.session_state.map_data
606
+
607
+ if gdata.get("narrative"):
608
+ st.markdown("<hr>", unsafe_allow_html=True)
609
+ st.info(gdata["narrative"])
610
+
611
+ st.markdown("<hr>", unsafe_allow_html=True)
612
+
613
+ nodes = gdata.get("nodes", [])
614
+ edges = gdata.get("edges", [])
615
+
616
+ if not show_external:
617
+ visible_ids = {n["id"] for n in nodes if n["kind"] != "external"}
618
+ nodes = [n for n in nodes if n["kind"] != "external"]
619
+ edges = [e for e in edges
620
+ if e["source"] in visible_ids and e["target"] in visible_ids]
621
+
622
+ kind_colors = {"function": "#4a9eff", "class": "#a78bfa", "entry": "#34d399", "external": "#6b7280"}
623
+ kind_counts: dict = {}
624
+ for n in nodes:
625
+ kind_counts[n["kind"]] = kind_counts.get(n["kind"], 0) + 1
626
+
627
+ if kind_counts:
628
+ stat_cols = st.columns(len(kind_counts))
629
+ for i, (kind, count) in enumerate(kind_counts.items()):
630
  color = kind_colors.get(kind, "#888")
631
  with stat_cols[i]:
632
  st.markdown(
 
637
  unsafe_allow_html=True,
638
  )
639
 
640
+ st.caption("click any node to see its full description, explanation, and relationships")
641
  st.markdown("<hr>", unsafe_allow_html=True)
642
 
643
  if nodes:
644
  html = _render_map_html(nodes, edges)
645
  components.html(html, height=680, scrolling=False)
646
  else:
647
+ st.info("no nodes to display with current filter.")
648
+ if gdata.get("errors"):
649
+ with st.expander("parse warnings"):
650
+ for err in gdata["errors"]:
651
+ st.markdown(f"⚠ {err}")