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