rk147 commited on
Commit
cd6ca06
·
verified ·
1 Parent(s): aa57564

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -203
app.py CHANGED
@@ -1,14 +1,12 @@
1
  import streamlit as st
2
- import uuid
3
  import streamlit.components.v1 as components
 
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 (
10
- get_session, save_session, delete_session, rename_session,
11
- )
12
  from app.utils.crypto import derive_session_id
13
  from app.utils.map_builder import build_graph
14
  from app.utils.exporter import export_markdown, export_docx, export_pdf
@@ -25,16 +23,12 @@ h1 { font-family: 'IBM Plex Mono', monospace !important; font-size: 1.3rem !impo
25
  h2, h3, h4 { font-family: 'IBM Plex Mono', monospace !important; font-size: 0.95rem !important; color: #bbb; }
26
  [data-testid="stTabs"] button { font-family: 'IBM Plex Mono', monospace; font-size: 0.75rem; color: #555; background: transparent; border-bottom: 2px solid transparent; padding: 6px 14px; }
27
  [data-testid="stTabs"] button[aria-selected="true"] { color: #e0e0e0; border-bottom: 2px solid #e0e0e0; }
28
- [data-testid="stTextInput"] input,
29
- [data-testid="stTextArea"] textarea,
30
- [data-testid="stChatInput"] textarea {
31
  background-color: #16161a !important; border: 1px solid #252528 !important;
32
- color: #e0e0e0 !important; font-family: 'IBM Plex Mono', monospace; font-size: 0.82rem; border-radius: 3px;
33
- }
34
  [data-testid="stButton"] button {
35
  background: #18181c; border: 1px solid #2a2a2e; color: #bbb;
36
- font-family: 'IBM Plex Mono', monospace; font-size: 0.75rem; border-radius: 3px; transition: all 0.12s;
37
- }
38
  [data-testid="stButton"] button:hover { border-color: #777; color: #fff; }
39
  [data-testid="stButton"] button[kind="primary"] { background: #e0e0e0; color: #0e0e10; border: none; font-weight: 500; }
40
  [data-testid="stButton"] button[kind="primary"]:hover { background: #fff; }
@@ -51,7 +45,7 @@ hr { border-color: #1e1e22; margin: 0.5rem 0; }
51
 
52
 
53
  # ══════════════════════════════════════════════════════
54
- # PASSWORD GATE — runs before anything else
55
  # ══════════════════════════════════════════════════════
56
  def _show_password_gate():
57
  st.markdown("#### 🔬 secforge")
@@ -59,18 +53,12 @@ def _show_password_gate():
59
  st.markdown("**your session is private and encrypted.**")
60
  st.caption("set a password to create a new session, or enter your existing one to restore it.")
61
  st.caption("⚠ if you forget your password, your data cannot be recovered.")
62
-
63
  col1, col2 = st.columns([3, 1])
64
  with col1:
65
- password = st.text_input(
66
- "password", type="password",
67
- placeholder="enter a password…",
68
- label_visibility="collapsed",
69
- key="pw_input",
70
- )
71
  with col2:
72
  enter = st.button("→ enter", type="primary", use_container_width=True)
73
-
74
  if enter:
75
  if not password:
76
  st.warning("enter a password first")
@@ -78,11 +66,9 @@ def _show_password_gate():
78
  if len(password) < 4:
79
  st.error("password must be at least 4 characters")
80
  return
81
-
82
  sid = derive_session_id(password)
83
  try:
84
  data = get_session(sid, password)
85
- # Initialise all state keys before rerun
86
  st.session_state.authenticated = True
87
  st.session_state.session_id = sid
88
  st.session_state.password = password
@@ -96,7 +82,6 @@ def _show_password_gate():
96
  fname: tuple(v) if isinstance(v, list) else v
97
  for fname, v in raw.items()
98
  }
99
- # Re-index text files into RAG
100
  for fname, contents in st.session_state.file_contents.items():
101
  if isinstance(contents, tuple) and contents[1] != "image":
102
  try:
@@ -105,7 +90,7 @@ def _show_password_gate():
105
  pass
106
  st.rerun()
107
  except ValueError:
108
- st.error("wrong password — session exists but password doesn't match.")
109
  except Exception as e:
110
  st.error(f"error: {e}")
111
 
@@ -114,7 +99,6 @@ if not st.session_state.get("authenticated"):
114
  _show_password_gate()
115
  st.stop()
116
 
117
- # ── These are only reached when authenticated ─────────
118
  SID = st.session_state.session_id
119
  PASSWORD = st.session_state.password
120
 
@@ -128,14 +112,9 @@ def _save():
128
  for fname, v in st.session_state.file_contents.items()
129
  }
130
  try:
131
- save_session(
132
- SID, PASSWORD,
133
- st.session_state.messages,
134
- st.session_state.linked_files,
135
- serializable,
136
- st.session_state.session_label,
137
- st.session_state.map_data,
138
- )
139
  except Exception as e:
140
  st.error(f"save failed: {e}")
141
 
@@ -176,99 +155,198 @@ def _render_analysis(result: dict):
176
 
177
 
178
  def _render_map_html(nodes: list, edges: list) -> str:
179
- """
180
- Render graph as self-contained vis.js HTML.
181
- Hierarchical layout, top-down, no physics blob.
182
- Each node shows label + description tooltip on hover.
183
- """
184
  kind_colors = {
185
  "function": "#4a9eff",
186
  "class": "#a78bfa",
187
  "entry": "#34d399",
188
  "external": "#6b7280",
189
  }
 
 
 
 
 
 
190
 
191
  nodes_js = []
 
192
  for n in nodes:
193
  color = kind_colors.get(n["kind"], "#888")
194
- size = {"entry": 32, "class": 26, "function": 20, "external": 14}.get(n["kind"], 18)
195
- desc = n.get("description", "")
196
- tooltip = f"{n['kind']} · {n['file']}:{n['line']}"
197
- if desc:
198
- tooltip = f"{desc}\\n{tooltip}"
199
- label = n["label"]
200
- # Escape for JS string
201
- tooltip = tooltip.replace("'", "\\'").replace("\n", "\\n")
202
- label = label.replace("'", "\\'")
203
  nodes_js.append(
204
- f"{{id: '{n['id']}', label: '{label}', title: '{tooltip}', "
205
- f"color: {{background: '{color}', border: '{color}', "
206
- f"highlight: {{background: '#fff', border: '{color}'}}}}, "
207
- f"font: {{color: '#e0e0e0', size: 12, face: 'IBM Plex Mono'}}, "
208
- f"size: {size}, shape: 'dot'}}"
209
  )
 
 
 
 
 
 
210
 
211
  edges_js = []
 
212
  for i, e in enumerate(edges):
213
  src = e["source"].replace("'", "\\'")
214
  tgt = e["target"].replace("'", "\\'")
 
215
  edges_js.append(
216
  f"{{id: {i}, from: '{src}', to: '{tgt}', "
217
- f"arrows: 'to', color: {{color: '#3a3a55', highlight: '#888'}}, width: 1}}"
 
 
 
 
218
  )
 
 
 
 
219
 
220
- nodes_str = ",\n".join(nodes_js)
221
- edges_str = ",\n".join(edges_js)
 
 
222
 
223
- return f"""
224
- <!DOCTYPE html>
225
  <html>
226
  <head>
227
  <style>
228
- body {{ margin: 0; background: #0e0e10; }}
229
- #graph {{ width: 100%; height: 620px; border: 1px solid #1e1e22; border-radius: 4px; }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  </style>
 
231
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
232
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css"/>
233
  </head>
234
  <body>
235
- <div id="graph"></div>
 
 
 
 
 
 
 
 
 
 
 
 
236
  <script>
237
- var nodes = new vis.DataSet([{nodes_str}]);
238
- var edges = new vis.DataSet([{edges_str}]);
239
- var container = document.getElementById('graph');
240
- var options = {{
 
 
 
 
 
 
 
 
 
 
 
 
241
  layout: {{
242
  hierarchical: {{
243
- enabled: true,
244
- direction: 'UD',
245
- sortMethod: 'directed',
246
- levelSeparation: 100,
247
- nodeSpacing: 150,
248
- treeSpacing: 180,
249
- blockShifting: true,
250
- edgeMinimization: true,
251
- parentCentralization: true
252
  }}
253
  }},
254
  physics: {{ enabled: false }},
255
  interaction: {{
256
- hover: true,
257
- tooltipDelay: 100,
258
- navigationButtons: true,
259
- keyboard: true,
260
- zoomView: true
261
  }},
262
- nodes: {{ borderWidth: 1, borderWidthSelected: 2 }},
263
- edges: {{ smooth: {{ type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4 }} }},
264
- configure: {{ enabled: false }}
265
- }};
266
- var network = new vis.Network(container, {{nodes: nodes, edges: edges}}, options);
267
- network.on('stabilized', function() {{ network.fit(); }});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  </script>
269
  </body>
270
- </html>
271
- """
272
 
273
 
274
  # ══════════════════════════════════════════════════════
@@ -278,21 +356,17 @@ with st.sidebar:
278
  st.markdown("#### 🔬 secforge")
279
  st.caption(f"session `{SID}` · 🔒 encrypted")
280
 
281
- new_label = st.text_input(
282
- "session name", value=st.session_state.session_label,
283
- label_visibility="collapsed", placeholder="session name…", key="label_input",
284
- )
285
  if new_label != st.session_state.session_label:
286
  st.session_state.session_label = new_label
287
  _save()
288
 
289
- # Pinned controls
290
  c1, c2 = st.columns(2)
291
  with c1:
292
  if st.button("+ new", use_container_width=True):
293
- # Clear all state explicitly before rerun
294
- for key in list(st.session_state.keys()):
295
- del st.session_state[key]
296
  st.rerun()
297
  with c2:
298
  if st.button("🗑 clear", use_container_width=True):
@@ -302,63 +376,36 @@ with st.sidebar:
302
  st.rerun()
303
 
304
  if st.button("🔒 lock", use_container_width=True):
305
- for key in list(st.session_state.keys()):
306
- del st.session_state[key]
307
  st.rerun()
308
 
309
- # Export
310
  st.markdown("**export**")
311
  e1, e2, e3 = st.columns(3)
312
  with e1:
313
- st.download_button(
314
- "md",
315
- data=export_markdown(
316
- st.session_state.session_label,
317
- st.session_state.messages,
318
- st.session_state.get("last_analysis"),
319
- st.session_state.map_data,
320
- ),
321
- file_name=f"secforge_{SID}.md",
322
- mime="text/markdown",
323
- use_container_width=True,
324
- )
325
  with e2:
326
- st.download_button(
327
- "docx",
328
- data=export_docx(
329
- st.session_state.session_label,
330
- st.session_state.messages,
331
- st.session_state.get("last_analysis"),
332
- st.session_state.map_data,
333
- ),
334
  file_name=f"secforge_{SID}.docx",
335
  mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
336
- use_container_width=True,
337
- )
338
  with e3:
339
- st.download_button(
340
- "pdf",
341
- data=export_pdf(
342
- st.session_state.session_label,
343
- st.session_state.messages,
344
- st.session_state.get("last_analysis"),
345
- st.session_state.map_data,
346
- ),
347
- file_name=f"secforge_{SID}.pdf",
348
- mime="application/pdf",
349
- use_container_width=True,
350
- )
351
 
352
  st.markdown("<hr>", unsafe_allow_html=True)
353
-
354
- # File context
355
  st.markdown("**project context**")
356
- uploaded = st.file_uploader(
357
- "add files", label_visibility="collapsed",
358
- type=["py", "js", "ts", "jsx", "tsx", "java", "cpp", "c", "cs", "go", "rs",
359
- "txt", "md", "png", "jpg", "jpeg", "webp"],
360
- accept_multiple_files=True,
361
- )
362
 
363
  if uploaded:
364
  changed = False
@@ -383,23 +430,22 @@ with st.sidebar:
383
  if changed:
384
  _save()
385
 
386
- if st.session_state.linked_files:
387
- for fname in list(st.session_state.linked_files):
388
- col_f, col_x = st.columns([5, 1])
389
- with col_f:
390
- icon = "🖼" if fname.rsplit(".", 1)[-1].lower() in ("png", "jpg", "jpeg", "webp") else "📄"
391
- st.markdown(f"<span class='file-chip'>{icon} {fname}</span>", unsafe_allow_html=True)
392
- with col_x:
393
- if st.button("×", key=f"rm_{fname}"):
394
- st.session_state.linked_files.remove(fname)
395
- st.session_state.file_contents.pop(fname, None)
396
- remove_file(SID, fname)
397
- _save()
398
- st.rerun()
399
 
400
 
401
  # ══════════════════════════════════════════════════════
402
- # MAIN
403
  # ══════════════════════════════════════════════════════
404
  st.markdown("#### 🔬 secforge")
405
  st.caption("code analysis · multi-language · context-aware · 🔒 private")
@@ -416,10 +462,8 @@ with tab_workspace:
416
  if msg.get("analysis"):
417
  _render_analysis(msg["analysis"])
418
 
419
- img_upload = st.file_uploader(
420
- "attach image", type=["png", "jpg", "jpeg", "webp"],
421
- label_visibility="collapsed", key="inline_img",
422
- )
423
  prompt = st.chat_input("paste code, ask a question, or both…")
424
 
425
  if prompt or img_upload:
@@ -435,20 +479,15 @@ with tab_workspace:
435
  try:
436
  context = query_context(SID, user_content) if st.session_state.linked_files else ""
437
  linked = [f for f in st.session_state.linked_files
438
- if not f.endswith((".png", ".jpg", ".jpeg", ".webp"))]
439
-
440
  if img_upload:
441
- response = vision_response(
442
- user_content, img_upload.getvalue(),
443
- media_type=f"image/{img_upload.name.rsplit('.',1)[-1].lower()}",
444
- context=context,
445
- )
446
  st.markdown(response)
447
  st.session_state.messages.append({"role": "assistant", "content": response})
448
  else:
449
  intent = detect_intent(user_content)
450
  msg_entry = {"role": "assistant", "content": "", "analysis": None}
451
-
452
  if intent in ("analyze", "mixed"):
453
  try:
454
  result = analyze_code(user_content)
@@ -459,16 +498,13 @@ with tab_workspace:
459
  except Exception as e:
460
  st.error(f"analysis failed: {e}")
461
  msg_entry["content"] = f"Analysis failed: {e}"
462
-
463
  if intent in ("chat", "mixed"):
464
  response = chat_response(user_content, st.session_state.messages, context, linked)
465
  st.markdown(response)
466
  msg_entry["content"] = (msg_entry["content"] + "\n\n" + response).strip()
467
-
468
  st.session_state.messages.append(msg_entry)
469
  except Exception as e:
470
  st.error(f"something went wrong: {e}")
471
-
472
  _save()
473
 
474
 
@@ -482,12 +518,11 @@ with tab_map:
482
 
483
  if not code_files:
484
  if st.session_state.linked_files:
485
- st.warning("file names are saved but contents need re-uploading — please upload again via the sidebar.")
486
  else:
487
  st.markdown("*load code files via the sidebar to generate a map.*")
488
  else:
489
  st.markdown(f"**{len(code_files)} file(s)** — `{'`, `'.join(code_files.keys())}`")
490
-
491
  mc1, mc2 = st.columns([2, 2])
492
  with mc1:
493
  build_btn = st.button("→ build map", type="primary", use_container_width=True)
@@ -495,13 +530,13 @@ with tab_map:
495
  show_external = st.toggle("show external calls", value=False)
496
 
497
  if build_btn:
498
- with st.spinner("parsing and mapping…"):
499
  try:
500
  graph = build_graph(code_files)
501
  st.session_state.map_data = graph.to_dict()
502
  _save()
503
  if not graph.nodes:
504
- st.warning("no functions or classes found — check that files contain actual code.")
505
  except Exception as e:
506
  st.error(f"map build failed: {e}")
507
 
@@ -523,7 +558,6 @@ with tab_map:
523
  edges = [e for e in edges
524
  if e["source"] in visible_ids and e["target"] in visible_ids]
525
 
526
- # Stats
527
  kind_colors = {"function": "#4a9eff", "class": "#a78bfa", "entry": "#34d399", "external": "#6b7280"}
528
  kind_counts: dict = {}
529
  for n in nodes:
@@ -542,41 +576,14 @@ with tab_map:
542
  unsafe_allow_html=True,
543
  )
544
 
 
545
  st.markdown("<hr>", unsafe_allow_html=True)
546
 
547
  if nodes:
548
- # Render via inline vis.js — no dependency issues, works everywhere
549
  html = _render_map_html(nodes, edges)
550
- components.html(html, height=640, scrolling=False)
551
  else:
552
- st.info("no nodes to display with current filter settings.")
553
-
554
- # Node inspector
555
- st.markdown("<hr>", unsafe_allow_html=True)
556
- st.markdown("**inspect node**")
557
- node_map = {n["label"]: n for n in nodes if n["kind"] != "external"}
558
- if node_map:
559
- selected = st.selectbox("select node", list(node_map.keys()), label_visibility="collapsed")
560
- if selected:
561
- n = node_map[selected]
562
- callers = [e["source"].split("::")[-1] for e in edges if e["target"] == n["id"]]
563
- callees = [e["target"].split("::")[-1] for e in edges if e["source"] == n["id"]]
564
- color = kind_colors.get(n["kind"], "#888")
565
- st.markdown(
566
- f"<div style='background:#111113;border:1px solid {color}33;"
567
- f"border-radius:4px;padding:14px;margin-top:8px'>"
568
- f"<span style='color:{color};font-family:IBM Plex Mono,monospace;"
569
- f"font-size:0.75rem'>{n['kind']}</span><br>"
570
- f"<b style='font-size:1.05rem'>{n['label']}</b><br>"
571
- f"<span style='color:#555;font-size:0.72rem'>{n['file']}:{n['line']}</span><br><br>"
572
- f"<span style='color:#bbb;font-size:0.82rem'>{n.get('description') or 'no description generated'}</span><br><br>"
573
- f"<span style='color:#555;font-size:0.72rem'>called by: "
574
- f"{', '.join(callers) if callers else 'entry point — nothing calls this'}</span><br>"
575
- f"<span style='color:#555;font-size:0.72rem'>calls: "
576
- f"{', '.join(callees) if callees else 'nothing'}</span>"
577
- f"</div>",
578
- unsafe_allow_html=True,
579
- )
580
 
581
  if gdata.get("errors"):
582
  with st.expander("parse warnings"):
 
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
 
23
  h2, h3, h4 { font-family: 'IBM Plex Mono', monospace !important; font-size: 0.95rem !important; color: #bbb; }
24
  [data-testid="stTabs"] button { font-family: 'IBM Plex Mono', monospace; font-size: 0.75rem; color: #555; background: transparent; border-bottom: 2px solid transparent; padding: 6px 14px; }
25
  [data-testid="stTabs"] button[aria-selected="true"] { color: #e0e0e0; border-bottom: 2px solid #e0e0e0; }
26
+ [data-testid="stTextInput"] input, [data-testid="stTextArea"] textarea, [data-testid="stChatInput"] textarea {
 
 
27
  background-color: #16161a !important; border: 1px solid #252528 !important;
28
+ color: #e0e0e0 !important; font-family: 'IBM Plex Mono', monospace; font-size: 0.82rem; border-radius: 3px; }
 
29
  [data-testid="stButton"] button {
30
  background: #18181c; border: 1px solid #2a2a2e; color: #bbb;
31
+ font-family: 'IBM Plex Mono', monospace; font-size: 0.75rem; border-radius: 3px; transition: all 0.12s; }
 
32
  [data-testid="stButton"] button:hover { border-color: #777; color: #fff; }
33
  [data-testid="stButton"] button[kind="primary"] { background: #e0e0e0; color: #0e0e10; border: none; font-weight: 500; }
34
  [data-testid="stButton"] button[kind="primary"]:hover { background: #fff; }
 
45
 
46
 
47
  # ══════════════════════════════════════════════════════
48
+ # PASSWORD GATE
49
  # ══════════════════════════════════════════════════════
50
  def _show_password_gate():
51
  st.markdown("#### 🔬 secforge")
 
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
+ password = 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
  if not password:
64
  st.warning("enter a password first")
 
66
  if len(password) < 4:
67
  st.error("password must be at least 4 characters")
68
  return
 
69
  sid = derive_session_id(password)
70
  try:
71
  data = get_session(sid, password)
 
72
  st.session_state.authenticated = True
73
  st.session_state.session_id = sid
74
  st.session_state.password = password
 
82
  fname: tuple(v) if isinstance(v, list) else v
83
  for fname, v in raw.items()
84
  }
 
85
  for fname, contents in st.session_state.file_contents.items():
86
  if isinstance(contents, tuple) and contents[1] != "image":
87
  try:
 
90
  pass
91
  st.rerun()
92
  except ValueError:
93
+ st.error("wrong password — session exists but password does not match.")
94
  except Exception as e:
95
  st.error(f"error: {e}")
96
 
 
99
  _show_password_gate()
100
  st.stop()
101
 
 
102
  SID = st.session_state.session_id
103
  PASSWORD = st.session_state.password
104
 
 
112
  for fname, v in st.session_state.file_contents.items()
113
  }
114
  try:
115
+ save_session(SID, PASSWORD, st.session_state.messages,
116
+ st.session_state.linked_files, serializable,
117
+ st.session_state.session_label, st.session_state.map_data)
 
 
 
 
 
118
  except Exception as e:
119
  st.error(f"save failed: {e}")
120
 
 
155
 
156
 
157
  def _render_map_html(nodes: list, edges: list) -> str:
 
 
 
 
 
158
  kind_colors = {
159
  "function": "#4a9eff",
160
  "class": "#a78bfa",
161
  "entry": "#34d399",
162
  "external": "#6b7280",
163
  }
164
+ kind_bg = {
165
+ "function": "#0d2240",
166
+ "class": "#1a1040",
167
+ "entry": "#0d2e22",
168
+ "external": "#1a1a1e",
169
+ }
170
 
171
  nodes_js = []
172
+ nodes_data = []
173
  for n in nodes:
174
  color = kind_colors.get(n["kind"], "#888")
175
+ bg = kind_bg.get(n["kind"], "#111")
176
+ size = {"entry": 34, "class": 28, "function": 22, "external": 14}.get(n["kind"], 20)
177
+ label = n["label"].replace("'", "\\'").replace('"', '\\"')
178
+ desc = (n.get("description") or "").replace("'", "\\'").replace('"', '\\"').replace("\n", " ")
179
+ explanation = (n.get("explanation") or "").replace("'", "\\'").replace('"', '\\"').replace("\n", " ")
180
+ file_line = f"{n['file']}:{n['line']}".replace("'", "\\'")
181
+ kind = n["kind"]
182
+ nid = n["id"].replace("'", "\\'")
183
+
184
  nodes_js.append(
185
+ f"{{id: '{nid}', label: '{label}', "
186
+ f"color: {{background: '{bg}', border: '{color}', highlight: {{background: '{color}22', border: '{color}'}}, hover: {{background: '{color}22', border: '{color}'}}}}, "
187
+ f"font: {{color: '{color}', size: 13, face: 'IBM Plex Mono', bold: {{color: '#fff', size: 14}}}}, "
188
+ f"size: {size}, shape: 'dot', borderWidth: 2, borderWidthSelected: 3, "
189
+ f"title: '{desc}'}}"
190
  )
191
+ nodes_data.append({
192
+ "id": n["id"], "label": n["label"], "kind": kind,
193
+ "file": n["file"], "line": n["line"],
194
+ "description": n.get("description", ""),
195
+ "explanation": n.get("explanation", ""),
196
+ })
197
 
198
  edges_js = []
199
+ edges_data = []
200
  for i, e in enumerate(edges):
201
  src = e["source"].replace("'", "\\'")
202
  tgt = e["target"].replace("'", "\\'")
203
+ rel = (e.get("relationship") or "calls").replace("'", "\\'").replace('"', '\\"')
204
  edges_js.append(
205
  f"{{id: {i}, from: '{src}', to: '{tgt}', "
206
+ f"label: '{rel}', "
207
+ f"font: {{color: '#666', size: 10, face: 'IBM Plex Mono', align: 'middle', strokeWidth: 0}}, "
208
+ f"color: {{color: '#2a2a3a', highlight: '#4a9eff', hover: '#888'}}, "
209
+ f"arrows: {{to: {{enabled: true, scaleFactor: 0.6}}}}, "
210
+ f"width: 1.5, smooth: {{type: 'cubicBezier', forceDirection: 'vertical', roundness: 0.4}}}}"
211
  )
212
+ edges_data.append({
213
+ "source": e["source"], "target": e["target"],
214
+ "relationship": e.get("relationship", "calls"),
215
+ })
216
 
217
+ nodes_js_str = ",\n".join(nodes_js)
218
+ edges_js_str = ",\n".join(edges_js)
219
+ nodes_data_json = json.dumps(nodes_data)
220
+ edges_data_json = json.dumps(edges_data)
221
 
222
+ return f"""<!DOCTYPE html>
 
223
  <html>
224
  <head>
225
  <style>
226
+ * {{ box-sizing: border-box; margin: 0; padding: 0; }}
227
+ body {{ background: #0e0e10; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden; }}
228
+ #wrap {{ display: flex; width: 100vw; height: 100vh; }}
229
+ #graph {{ flex: 1; height: 100%; }}
230
+ #panel {{
231
+ width: 0; min-width: 0; height: 100%;
232
+ background: #111113; border-left: 1px solid #1e1e22;
233
+ overflow: hidden; transition: width 0.25s ease;
234
+ display: flex; flex-direction: column;
235
+ }}
236
+ #panel.open {{ width: 300px; min-width: 300px; }}
237
+ #panel-inner {{ padding: 18px; overflow-y: auto; height: 100%; }}
238
+ .p-kind {{ font-family: 'IBM Plex Mono', monospace; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }}
239
+ .p-name {{ font-family: 'IBM Plex Mono', monospace; font-size: 1.1rem; font-weight: 500; color: #f0f0f0; margin-bottom: 2px; }}
240
+ .p-file {{ font-size: 0.7rem; color: #444; margin-bottom: 14px; font-family: 'IBM Plex Mono', monospace; }}
241
+ .p-section {{ font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.8px; color: #444; margin: 12px 0 4px; }}
242
+ .p-text {{ font-size: 0.82rem; color: #bbb; line-height: 1.5; }}
243
+ .p-short {{ font-size: 0.85rem; color: #ddd; line-height: 1.4; margin-bottom: 8px; font-style: italic; }}
244
+ .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; }}
245
+ .p-close {{ position: absolute; top: 12px; right: 12px; background: none; border: none; color: #555; font-size: 1rem; cursor: pointer; }}
246
+ #panel {{ position: relative; }}
247
+ #legend {{
248
+ position: absolute; bottom: 12px; left: 12px;
249
+ display: flex; gap: 10px; flex-wrap: wrap;
250
+ }}
251
+ .leg {{ display: flex; align-items: center; gap: 4px; font-size: 0.68rem; color: #555; font-family: 'IBM Plex Mono', monospace; }}
252
+ .leg-dot {{ width: 8px; height: 8px; border-radius: 50%; }}
253
  </style>
254
+ <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">
255
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
256
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css"/>
257
  </head>
258
  <body>
259
+ <div id="wrap">
260
+ <div id="graph"></div>
261
+ <div id="panel">
262
+ <button class="p-close" onclick="closePanel()">✕</button>
263
+ <div id="panel-inner"></div>
264
+ </div>
265
+ </div>
266
+ <div id="legend">
267
+ <div class="leg"><div class="leg-dot" style="background:#34d399"></div>entry</div>
268
+ <div class="leg"><div class="leg-dot" style="background:#4a9eff"></div>function</div>
269
+ <div class="leg"><div class="leg-dot" style="background:#a78bfa"></div>class</div>
270
+ <div class="leg"><div class="leg-dot" style="background:#6b7280"></div>external</div>
271
+ </div>
272
  <script>
273
+ var nodesData = {nodes_data_json};
274
+ var edgesData = {edges_data_json};
275
+ var nodeIndex = {{}};
276
+ nodesData.forEach(function(n) {{ nodeIndex[n.id] = n; }});
277
+
278
+ var kindColors = {{
279
+ "function": "#4a9eff", "class": "#a78bfa",
280
+ "entry": "#34d399", "external": "#6b7280"
281
+ }};
282
+
283
+ var nodes = new vis.DataSet([{nodes_js_str}]);
284
+ var edges = new vis.DataSet([{edges_js_str}]);
285
+ var container = document.getElementById('graph');
286
+ var network = new vis.Network(container,
287
+ {{nodes: nodes, edges: edges}},
288
+ {{
289
  layout: {{
290
  hierarchical: {{
291
+ enabled: true, direction: 'UD', sortMethod: 'directed',
292
+ levelSeparation: 110, nodeSpacing: 160, treeSpacing: 200,
293
+ blockShifting: true, edgeMinimization: true, parentCentralization: true
 
 
 
 
 
 
294
  }}
295
  }},
296
  physics: {{ enabled: false }},
297
  interaction: {{
298
+ hover: true, tooltipDelay: 150,
299
+ navigationButtons: true, keyboard: true, zoomView: true
 
 
 
300
  }},
301
+ nodes: {{ borderWidth: 2, borderWidthSelected: 3, chosen: true }},
302
+ edges: {{ chosen: true }}
303
+ }}
304
+ );
305
+
306
+ network.on('click', function(params) {{
307
+ if (params.nodes.length > 0) {{
308
+ var nid = params.nodes[0];
309
+ var n = nodeIndex[nid];
310
+ if (!n) return;
311
+ showPanel(n, nid);
312
+ }}
313
+ }});
314
+
315
+ function showPanel(n, nid) {{
316
+ var color = kindColors[n.kind] || '#888';
317
+ var callers = edgesData.filter(function(e) {{ return e.target === nid; }})
318
+ .map(function(e) {{
319
+ var src = nodeIndex[e.source];
320
+ return '<span class="p-rel">← ' + (src ? src.label : e.source.split("::").pop()) + (e.relationship ? ' (' + e.relationship + ')' : '') + '</span>';
321
+ }}).join('');
322
+ var callees = edgesData.filter(function(e) {{ return e.source === nid; }})
323
+ .map(function(e) {{
324
+ var tgt = nodeIndex[e.target];
325
+ return '<span class="p-rel">→ ' + (tgt ? tgt.label : e.target.split("::").pop()) + (e.relationship ? ' (' + e.relationship + ')' : '') + '</span>';
326
+ }}).join('');
327
+
328
+ document.getElementById('panel-inner').innerHTML =
329
+ '<div class="p-kind" style="color:' + color + '">' + n.kind + '</div>' +
330
+ '<div class="p-name">' + n.label + '</div>' +
331
+ '<div class="p-file">' + n.file + ':' + n.line + '</div>' +
332
+ (n.description ? '<div class="p-short">' + n.description + '</div>' : '') +
333
+ (n.explanation ? '<div class="p-section">what it does</div><div class="p-text">' + n.explanation + '</div>' : '') +
334
+ (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>') +
335
+ (callees ? '<div class="p-section">calls</div>' + callees : '');
336
+
337
+ document.getElementById('panel').classList.add('open');
338
+ }}
339
+
340
+ function closePanel() {{
341
+ document.getElementById('panel').classList.remove('open');
342
+ }}
343
+
344
+ network.on('deselectNode', function() {{
345
+ document.getElementById('panel').classList.remove('open');
346
+ }});
347
  </script>
348
  </body>
349
+ </html>"""
 
350
 
351
 
352
  # ══════════════════════════════════════════════════════
 
356
  st.markdown("#### 🔬 secforge")
357
  st.caption(f"session `{SID}` · 🔒 encrypted")
358
 
359
+ new_label = st.text_input("session name", value=st.session_state.session_label,
360
+ label_visibility="collapsed", placeholder="session name…", key="label_input")
 
 
361
  if new_label != st.session_state.session_label:
362
  st.session_state.session_label = new_label
363
  _save()
364
 
 
365
  c1, c2 = st.columns(2)
366
  with c1:
367
  if st.button("+ new", use_container_width=True):
368
+ for k in list(st.session_state.keys()):
369
+ del st.session_state[k]
 
370
  st.rerun()
371
  with c2:
372
  if st.button("🗑 clear", use_container_width=True):
 
376
  st.rerun()
377
 
378
  if st.button("🔒 lock", use_container_width=True):
379
+ for k in list(st.session_state.keys()):
380
+ del st.session_state[k]
381
  st.rerun()
382
 
 
383
  st.markdown("**export**")
384
  e1, e2, e3 = st.columns(3)
385
  with e1:
386
+ st.download_button("md",
387
+ data=export_markdown(st.session_state.session_label, st.session_state.messages,
388
+ st.session_state.get("last_analysis"), st.session_state.map_data),
389
+ file_name=f"secforge_{SID}.md", mime="text/markdown", use_container_width=True)
 
 
 
 
 
 
 
 
390
  with e2:
391
+ st.download_button("docx",
392
+ data=export_docx(st.session_state.session_label, st.session_state.messages,
393
+ st.session_state.get("last_analysis"), st.session_state.map_data),
 
 
 
 
 
394
  file_name=f"secforge_{SID}.docx",
395
  mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
396
+ use_container_width=True)
 
397
  with e3:
398
+ st.download_button("pdf",
399
+ data=export_pdf(st.session_state.session_label, st.session_state.messages,
400
+ st.session_state.get("last_analysis"), st.session_state.map_data),
401
+ file_name=f"secforge_{SID}.pdf", mime="application/pdf", use_container_width=True)
 
 
 
 
 
 
 
 
402
 
403
  st.markdown("<hr>", unsafe_allow_html=True)
 
 
404
  st.markdown("**project context**")
405
+
406
+ uploaded = st.file_uploader("add files", label_visibility="collapsed",
407
+ type=["py","js","ts","jsx","tsx","java","cpp","c","cs","go","rs","txt","md","png","jpg","jpeg","webp"],
408
+ accept_multiple_files=True)
 
 
409
 
410
  if uploaded:
411
  changed = False
 
430
  if changed:
431
  _save()
432
 
433
+ for fname in list(st.session_state.linked_files):
434
+ col_f, col_x = st.columns([5, 1])
435
+ with col_f:
436
+ icon = "🖼" if fname.rsplit(".", 1)[-1].lower() in ("png","jpg","jpeg","webp") else "📄"
437
+ st.markdown(f"<span class='file-chip'>{icon} {fname}</span>", unsafe_allow_html=True)
438
+ with col_x:
439
+ if st.button("×", key=f"rm_{fname}"):
440
+ st.session_state.linked_files.remove(fname)
441
+ st.session_state.file_contents.pop(fname, None)
442
+ remove_file(SID, fname)
443
+ _save()
444
+ st.rerun()
 
445
 
446
 
447
  # ══════════════════════════════════════════════════════
448
+ # MAIN TABS
449
  # ══════════════════════════════════════════════════════
450
  st.markdown("#### 🔬 secforge")
451
  st.caption("code analysis · multi-language · context-aware · 🔒 private")
 
462
  if msg.get("analysis"):
463
  _render_analysis(msg["analysis"])
464
 
465
+ img_upload = st.file_uploader("attach image", type=["png","jpg","jpeg","webp"],
466
+ label_visibility="collapsed", key="inline_img")
 
 
467
  prompt = st.chat_input("paste code, ask a question, or both…")
468
 
469
  if prompt or img_upload:
 
479
  try:
480
  context = query_context(SID, user_content) if st.session_state.linked_files else ""
481
  linked = [f for f in st.session_state.linked_files
482
+ if not f.endswith((".png",".jpg",".jpeg",".webp"))]
 
483
  if img_upload:
484
+ response = vision_response(user_content, img_upload.getvalue(),
485
+ media_type=f"image/{img_upload.name.rsplit('.',1)[-1].lower()}", context=context)
 
 
 
486
  st.markdown(response)
487
  st.session_state.messages.append({"role": "assistant", "content": response})
488
  else:
489
  intent = detect_intent(user_content)
490
  msg_entry = {"role": "assistant", "content": "", "analysis": None}
 
491
  if intent in ("analyze", "mixed"):
492
  try:
493
  result = analyze_code(user_content)
 
498
  except Exception as e:
499
  st.error(f"analysis failed: {e}")
500
  msg_entry["content"] = f"Analysis failed: {e}"
 
501
  if intent in ("chat", "mixed"):
502
  response = chat_response(user_content, st.session_state.messages, context, linked)
503
  st.markdown(response)
504
  msg_entry["content"] = (msg_entry["content"] + "\n\n" + response).strip()
 
505
  st.session_state.messages.append(msg_entry)
506
  except Exception as e:
507
  st.error(f"something went wrong: {e}")
 
508
  _save()
509
 
510
 
 
518
 
519
  if not code_files:
520
  if st.session_state.linked_files:
521
+ st.warning("file names saved but contents need re-uploading — please re-upload via sidebar.")
522
  else:
523
  st.markdown("*load code files via the sidebar to generate a map.*")
524
  else:
525
  st.markdown(f"**{len(code_files)} file(s)** — `{'`, `'.join(code_files.keys())}`")
 
526
  mc1, mc2 = st.columns([2, 2])
527
  with mc1:
528
  build_btn = st.button("→ build map", type="primary", use_container_width=True)
 
530
  show_external = st.toggle("show external calls", value=False)
531
 
532
  if build_btn:
533
+ with st.spinner("parsing, generating descriptions and edge relationships…"):
534
  try:
535
  graph = build_graph(code_files)
536
  st.session_state.map_data = graph.to_dict()
537
  _save()
538
  if not graph.nodes:
539
+ st.warning("no functions or classes found.")
540
  except Exception as e:
541
  st.error(f"map build failed: {e}")
542
 
 
558
  edges = [e for e in edges
559
  if e["source"] in visible_ids and e["target"] in visible_ids]
560
 
 
561
  kind_colors = {"function": "#4a9eff", "class": "#a78bfa", "entry": "#34d399", "external": "#6b7280"}
562
  kind_counts: dict = {}
563
  for n in nodes:
 
576
  unsafe_allow_html=True,
577
  )
578
 
579
+ st.caption("click any node to see its full description, explanation, and relationships")
580
  st.markdown("<hr>", unsafe_allow_html=True)
581
 
582
  if nodes:
 
583
  html = _render_map_html(nodes, edges)
584
+ components.html(html, height=680, scrolling=False)
585
  else:
586
+ st.info("no nodes to display with current filter.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587
 
588
  if gdata.get("errors"):
589
  with st.expander("parse warnings"):