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("""
""", unsafe_allow_html=True)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PASSWORD GATE
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _show_password_gate():
st.markdown("#### π¬ secforge")
st.markdown("
", 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"""
auth/validate
read/load
write/send
init/build
error/handle
calls
entry
function
class
external
"""
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# 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("", 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("""
""", 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"{icon} {fname}", 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("", 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("", unsafe_allow_html=True)
st.info(gdata["narrative"])
st.markdown("", 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"
"
f""
f"{kind} {count}
",
unsafe_allow_html=True,
)
st.caption("click any node to see its full description, explanation, and relationships")
st.markdown("", 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}")