secforge / app.py
rk147's picture
Update app.py
eefeca0 verified
Raw History Blame Contribute Delete
31.5 kB
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}")