Spaces:
Paused
Paused
Update backend/main.py
Browse files1234565 unmodified lines121314151617181920212223242526273 unmodified lines313233343536373839404142434445464748495 unmodified lines5556575859606162636465666768697071727374757677787980813 unmodified lines858687888990914 unmodified lines969798991001011021031041051061071081091101111121 unmodified line1141151161171181191206 unmodified lines1271281291301311321332 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621633 unmodified lines1671681691701711721731741751761771781791801811821 unmodified line1841851861871881891902 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282291 unmodified line2312322332342352362372382392402412422432 unmodified lines246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408"""TreyOS Backend β FastAPIReal Linux filesystem, WebSocket terminal, system stats"""import asyncio5 unmodified linesimport timefrom datetime import datetimefrom pathlib import Pathfrom typing import Optionalimport psutilfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, UploadFile, File, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom watchfiles import awatchapp = FastAPI(title="TreyOS", version="1.0.0", description="Visual OS layer for Linux")app.add_middleware(CORSMiddleware,3 unmodified linesallow_headers=["*"],)# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββROOT_JAIL = Path(os.environ.get("TREY_ROOT", "/")) # Restrict to this path for safetydef safe_path(requested: str) -> Path:"""Resolve path safely within ROOT_JAIL."""p = (ROOT_JAIL / requested.lstrip("/")).resolve()if not str(p).startswith(str(ROOT_JAIL)):raise HTTPException(403, "Access denied")return pdef entry_info(p: Path) -> dict:"""Return metadata dict for a filesystem entry."""try:s = p.stat()return {5 unmodified lines"permissions": oct(stat.S_IMODE(s.st_mode)),"extension": p.suffix.lower() if p.is_file() else None,}except PermissionError:return {"name": p.name, "path": str(p), "type": "unknown", "size": 0, "modified": None, "permissions": None, "extension": None}# ββ Filesystem API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/api/files")async def list_files(path: str = "/", show_hidden: bool = False):"""List directory contents."""p = safe_path(path)if not p.exists():raise HTTPException(404, f"Path not found: {path}")if not p.is_dir():raise HTTPException(400, "Path is not a directory")try:entries = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))if not show_hidden:entries = [e for e in entries if not e.name.startswith(".")]return {"path": str(p),"parent": str(p.parent) if p != p.parent else None,"entries": [entry_info(e) for e in entries],"count": len(entries),}3 unmodified lines@app.get("/api/files/read")async def read_file(path: str):"""Read a text file."""p = safe_path(path)if not p.is_file():raise HTTPException(404, "File not found")4 unmodified lines@app.post("/api/files/write")async def write_file(path: str, content: str):"""Write content to a file."""p = safe_path(path)p.parent.mkdir(parents=True, exist_ok=True)p.write_text(content)return {"ok": True, "path": str(p)}@app.post("/api/files/mkdir")async def make_dir(path: str):"""Create a directory."""p = safe_path(path)p.mkdir(parents=True, exist_ok=True)return {"ok": True, "path": str(p)}1 unmodified line@app.delete("/api/files/delete")async def delete_entry(path: str):"""Delete a file or directory."""p = safe_path(path)if not p.exists():raise HTTPException(404, "Not found")6 unmodified lines@app.post("/api/files/rename")async def rename_entry(path: str, new_name: str):"""Rename a file or directory."""p = safe_path(path)dest = p.parent / new_namep.rename(dest)2 unmodified lines@app.post("/api/files/copy")async def copy_entry(src: str, dst: str):"""Copy a file or directory."""s = safe_path(src)d = safe_path(dst)if s.is_dir():shutil.copytree(s, d)else:shutil.copy2(s, d)return {"ok": True, "destination": str(d)}@app.post("/api/files/move")async def move_entry(src: str, dst: str):"""Move a file or directory."""s = safe_path(src)d = safe_path(dst)shutil.move(str(s), str(d))return {"ok": True, "destination": str(d)}@app.post("/api/files/upload")async def upload_file(path: str, file: UploadFile = File(...)):"""Upload a file to the given directory."""dest = safe_path(path) / file.filenamedest.parent.mkdir(parents=True, exist_ok=True)with open(dest, "wb") as f:3 unmodified lines@app.get("/api/files/download")async def download_file(path: str):"""Download a file."""p = safe_path(path)if not p.is_file():raise HTTPException(404, "File not found")return FileResponse(p, filename=p.name)@app.get("/api/files/search")async def search_files(path: str = "/", query: str = "", limit: int = 50):"""Search for files by name."""p = safe_path(path)results = []try:1 unmodified lineresults.append(entry_info(entry))if len(results) >= limit:breakexcept PermissionError:passreturn {"query": query, "results": results, "count": len(results)}2 unmodified lines@app.get("/api/system")async def system_stats():"""Return live system statistics."""disk = psutil.disk_usage("/")net = psutil.net_io_counters()boot = datetime.fromtimestamp(psutil.boot_time())uptime_s = int(time.time() - psutil.boot_time())h, r = divmod(uptime_s, 3600)m = r // 60return {"cpu": {"percent": psutil.cpu_percent(interval=0.1),"cores": psutil.cpu_count(),"freq_mhz": psutil.cpu_freq().current if psutil.cpu_freq() else None,},"memory": {"total_gb": round(psutil.virtual_memory().total / 1e9, 1),"used_gb": round(psutil.virtual_memory().used / 1e9, 1),"percent": psutil.virtual_memory().percent,},"disk": {"total_gb": round(disk.total / 1e9, 1),"used_gb": round(disk.used / 1e9, 1),"free_gb": round(disk.free / 1e9, 1),"percent": disk.percent,},"network": {"bytes_sent_mb": round(net.bytes_sent / 1e6, 1),"bytes_recv_mb": round(net.bytes_recv / 1e6, 1),},"uptime": f"{h}h {m}m","boot_time": boot.isoformat(),"hostname": os.uname().nodename,"os": f"{os.uname().sysname} {os.uname().release}",}1 unmodified line@app.get("/api/processes")async def list_processes(limit: int = 20):"""Return top processes by CPU usage."""procs = []for p in psutil.process_iter(["pid", "name", "cpu_percent", "memory_percent", "status"]):try:procs.append(p.info)except (psutil.NoSuchProcess, psutil.AccessDenied):passprocs.sort(key=lambda x: x.get("cpu_percent", 0), reverse=True)return {"processes": procs[:limit]}2 unmodified linesclass TerminalSession:def __init__(self, cwd: str = "/"):self.cwd = cwdself.env = {**os.environ, "TERM": "xterm-256color"}async def run(self, command: str, ws: WebSocket):"""Execute a shell command and stream output back."""# Built-in cdif command.strip().startswith("cd "):target = command.strip()[3:].strip()new_cwd = str((Path(self.cwd) / target).resolve())if os.path.isdir(new_cwd):self.cwd = new_cwdawait ws.send_json({"type": "output", "data": f"\r\n", "cwd": self.cwd})else:await ws.send_json({"type": "output", "data": f"cd: {target}: No such directory\r\n", "cwd": self.cwd})await ws.send_json({"type": "prompt", "cwd": self.cwd})returntry:proc = await asyncio.create_subprocess_shell(command,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,cwd=self.cwd,env=self.env,)async for chunk in proc.stdout:await ws.send_json({"type": "output", "data": chunk.decode(errors="replace")})await proc.wait()await ws.send_json({"type": "exit", "code": proc.returncode, "cwd": self.cwd})except Exception as e:await ws.send_json({"type": "error", "data": str(e)})finally:await ws.send_json({"type": "prompt", "cwd": self.cwd})@app.websocket("/ws/terminal")async def terminal_ws(ws: WebSocket, cwd: str = "/"):"""WebSocket terminal session."""await ws.accept()session = TerminalSession(cwd=cwd)await ws.send_json({"type": "welcome", "message": "TreyOS Terminal Ready", "cwd": session.cwd})await ws.send_json({"type": "prompt", "cwd": session.cwd})try:while True:msg = await ws.receive_json()if msg.get("type") == "command":await session.run(msg["data"], ws)elif msg.get("type") == "ping":await ws.send_json({"type": "pong"})except WebSocketDisconnect:pass# ββ WebSocket Filesystem Watcher ββββββββββββββββββββββββββββββββββββββββββββββ@app.websocket("/ws/watch")async def watch_ws(ws: WebSocket, path: str = "/"):"""Stream filesystem change events for a directory."""await ws.accept()p = safe_path(path)await ws.send_json({"type": "watching", "path": str(p)})try:async for changes in awatch(str(p)):events = [{"change": str(c[0].name), "path": c[1]} for c in changes]await ws.send_json({"type": "changes", "events": events})except WebSocketDisconnect:passexcept Exception as e:await ws.send_json({"type": "error", "message": str(e)})# ββ WebSocket System Monitor ββββββββββββββββββββββββββββββββββββββββββββββββββ@app.websocket("/ws/system")async def system_ws(ws: WebSocket, interval: float = 2.0):"""Stream live system stats every N seconds."""await ws.accept()try:while True:stats = await system_stats()await ws.send_json({"type": "stats", "data": stats})await asyncio.sleep(interval)except WebSocketDisconnect:pass# ββ Docker API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef run_docker(*args) -> dict:try:r = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=10)return {"ok": r.returncode == 0, "stdout": r.stdout, "stderr": r.stderr}except FileNotFoundError:return {"ok": False, "error": "Docker not installed"}except subprocess.TimeoutExpired:return {"ok": False, "error": "Docker command timed out"}@app.get("/api/docker/containers")async def docker_containers():r = run_docker("ps", "-a", "--format", "json")if not r["ok"]:return {"containers": [], "error": r.get("error") or r.get("stderr")}containers = []for line in r["stdout"].strip().splitlines():try:containers.append(json.loads(line))except json.JSONDecodeError:passreturn {"containers": containers}@app.post("/api/docker/start/{container_id}")async def docker_start(container_id: str):return run_docker("start", container_id)@app.post("/api/docker/stop/{container_id}")async def docker_stop(container_id: str):return run_docker("stop", container_id)@app.get("/api/docker/images")async def docker_images():r = run_docker("images", "--format", "json")images = []for line in r.get("stdout", "").strip().splitlines():try:images.append(json.loads(line))except:passreturn {"images": images}# ββ Health Check (Moved to avoid colliding with Root UI) ββββββββββββββββββββββ@app.get("/health")async def health_check():return {"status": "ok", "name": "TreyOS", "version": "1.0.0"}# ββ Serve Frontend UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββfrom fastapi.responses import HTMLResponse@app.get("/", response_class=HTMLResponse)async def serve_root_ui():"""Serves the main structural HTML interface directly at the app root."""# Looks for TreyOS-connected.html in the root workspace directory (/trey)root_html_path = Path(__file__).parent.parent / "TreyOS-connected.html"if root_html_path.exists():return root_html_path.read_text(encoding="utf-8")else:raise HTTPException(status_code=404, detail="TreyOS-connected.html not found in root context.")# Correctly mount the real frontend directory containing treyos-client.jsreal_frontend_path = Path(__file__).parent.parent / "frontend"if real_frontend_path.exists():app.mount("/frontend", StaticFiles(directory=str(real_frontend_path)), name="frontend")1234565 unmodified lines1213141516171819202122232425263 unmodified lines30313233343536373839404142434445464748495051525354555 unmodified lines6162636465666768697071727374757677787980818283848586873 unmodified lines9192939495964 unmodified lines1011021031041051061071081091101111121131141151 unmodified line1171181191201211226 unmodified lines1291301311321331342 unmodified lines1371381391401411421431441451461471481491501511521531541551563 unmodified lines1601611621631641651661671681691701711721731 unmodified line1751761771781791801812 unmodified lines1841851861871881891901911921931941951961971981992002012022032042051 unmodified line2072082092102112122132142152162 unmodified lines219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""TreyOS Backend β FastAPIReal Linux filesystem, WebSocket terminal, system stats, Playwright browser"""import asyncio5 unmodified linesimport timefrom datetime import datetimefrom pathlib import Pathimport psutilfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, UploadFile, Filefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom watchfiles import awatchapp = FastAPI(title="TreyOS", version="1.0.0")app.add_middleware(CORSMiddleware,3 unmodified linesallow_headers=["*"],)# ββ Path handling βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# TREY_ROOT jails access. Default "/" means full filesystem access.# The jail check is intentionally lenient β on HF the whole container is fair game.ROOT_JAIL = Path(os.environ.get("TREY_ROOT", "/")).resolve()def safe_path(requested: str) -> Path:"""Resolve path. If absolute, use as-is (within jail). If relative, join to ROOT_JAIL."""requested = requested.strip()if requested.startswith("/"):p = Path(requested).resolve()else:p = (ROOT_JAIL / requested).resolve()# Jail checktry:p.relative_to(ROOT_JAIL)except ValueError:raise HTTPException(403, f"Access denied: {p} is outside jail {ROOT_JAIL}")return pdef entry_info(p: Path) -> dict:try:s = p.stat()return {5 unmodified lines"permissions": oct(stat.S_IMODE(s.st_mode)),"extension": p.suffix.lower() if p.is_file() else None,}except (PermissionError, OSError):return {"name": p.name, "path": str(p), "type": "unknown","size": 0, "modified": None, "permissions": None, "extension": None}# ββ Filesystem API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/api/files")async def list_files(path: str = "/", show_hidden: bool = False):p = safe_path(path)if not p.exists():raise HTTPException(404, f"Path not found: {path}")if not p.is_dir():raise HTTPException(400, "Not a directory")try:entries = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))if not show_hidden:entries = [e for e in entries if not e.name.startswith(".")]return {"path": str(p),"parent": str(p.parent) if str(p) != "/" else None,"entries": [entry_info(e) for e in entries],"count": len(entries),}3 unmodified lines@app.get("/api/files/read")async def read_file(path: str):p = safe_path(path)if not p.is_file():raise HTTPException(404, "File not found")4 unmodified lines@app.post("/api/files/write")async def write_file(path: str, content: str = ""):p = safe_path(path)p.parent.mkdir(parents=True, exist_ok=True)p.write_text(content)return {"ok": True, "path": str(p), "size": p.stat().st_size}@app.post("/api/files/mkdir")async def make_dir(path: str):p = safe_path(path)p.mkdir(parents=True, exist_ok=True)return {"ok": True, "path": str(p)}1 unmodified line@app.delete("/api/files/delete")async def delete_entry(path: str):p = safe_path(path)if not p.exists():raise HTTPException(404, "Not found")6 unmodified lines@app.post("/api/files/rename")async def rename_entry(path: str, new_name: str):p = safe_path(path)dest = p.parent / new_namep.rename(dest)2 unmodified lines@app.post("/api/files/copy")async def copy_entry(src: str, dst: str):s, d = safe_path(src), safe_path(dst)shutil.copytree(s, d) if s.is_dir() else shutil.copy2(s, d)return {"ok": True, "destination": str(d)}@app.post("/api/files/move")async def move_entry(src: str, dst: str):s, d = safe_path(src), safe_path(dst)shutil.move(str(s), str(d))return {"ok": True, "destination": str(d)}@app.post("/api/files/upload")async def upload_file(path: str, file: UploadFile = File(...)):dest = safe_path(path) / file.filenamedest.parent.mkdir(parents=True, exist_ok=True)with open(dest, "wb") as f:3 unmodified lines@app.get("/api/files/download")async def download_file(path: str):p = safe_path(path)if not p.is_file():raise HTTPException(404, "File not found")return FileResponse(str(p), filename=p.name)@app.get("/api/files/search")async def search_files(path: str = "/", query: str = "", limit: int = 50):p = safe_path(path)results = []try:1 unmodified lineresults.append(entry_info(entry))if len(results) >= limit:breakexcept (PermissionError, OSError):passreturn {"query": query, "results": results, "count": len(results)}2 unmodified lines@app.get("/api/system")async def system_stats():disk = psutil.disk_usage("/")net = psutil.net_io_counters()uptime_s = int(time.time() - psutil.boot_time())h, r = divmod(uptime_s, 3600)m = r // 60return {"cpu": {"percent": psutil.cpu_percent(interval=0.1), "cores": psutil.cpu_count(),"freq_mhz": psutil.cpu_freq().current if psutil.cpu_freq() else None},"memory": {"total_gb": round(psutil.virtual_memory().total/1e9,1),"used_gb": round(psutil.virtual_memory().used/1e9,1),"percent": psutil.virtual_memory().percent},"disk": {"total_gb": round(disk.total/1e9,1), "used_gb": round(disk.used/1e9,1),"free_gb": round(disk.free/1e9,1), "percent": disk.percent},"network":{"bytes_sent_mb": round(net.bytes_sent/1e6,1), "bytes_recv_mb": round(net.bytes_recv/1e6,1)},"uptime": f"{h}h {m}m","boot_time": datetime.fromtimestamp(psutil.boot_time()).isoformat(),"hostname": os.uname().nodename,"os": f"{os.uname().sysname} {os.uname().release}",}1 unmodified line@app.get("/api/processes")async def list_processes(limit: int = 20):procs = []for p in psutil.process_iter(["pid","name","cpu_percent","memory_percent","status"]):try: procs.append(p.info)except (psutil.NoSuchProcess, psutil.AccessDenied): passprocs.sort(key=lambda x: x.get("cpu_percent", 0), reverse=True)return {"processes": procs[:limit]}2 unmodified linesclass TerminalSession:def __init__(self, cwd: str = "/"):self.cwd = cwd if Path(cwd).is_dir() else "/"self.env = {**os.environ, "TERM": "xterm-256color"}async def run(self, command: str, ws: WebSocket):cmd = command.strip()# Handle cd internallyif cmd.startswith("cd"):target = cmd[2:].strip() or str(Path.home())new_cwd = str((Path(self.cwd) / target).resolve())if os.path.isdir(new_cwd):self.cwd = new_cwdelse:await ws.send_json({"type":"output","data":f"cd: {target}: No such directory\r\n"})await ws.send_json({"type":"prompt","cwd":self.cwd})returntry:proc = await asyncio.create_subprocess_shell(cmd,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,cwd=self.cwd, env=self.env,)async for chunk in proc.stdout:await ws.send_json({"type":"output","data":chunk.decode(errors="replace")})await proc.wait()await ws.send_json({"type":"exit","code":proc.returncode,"cwd":self.cwd})except Exception as e:await ws.send_json({"type":"error","data":str(e)})finally:await ws.send_json({"type":"prompt","cwd":self.cwd})@app.websocket("/ws/terminal")async def terminal_ws(ws: WebSocket, cwd: str = "/"):await ws.accept()# Use ROOT_JAIL as default cwd if it exists, else /default_cwd = str(ROOT_JAIL) if ROOT_JAIL.is_dir() else "/"session = TerminalSession(cwd=cwd if Path(cwd).is_dir() else default_cwd)await ws.send_json({"type":"welcome","message":"TreyOS Terminal Ready","cwd":session.cwd})await ws.send_json({"type":"prompt","cwd":session.cwd})try:while True:msg = await ws.receive_json()if msg.get("type") == "command":await session.run(msg["data"], ws)elif msg.get("type") == "ping":await ws.send_json({"type":"pong"})except WebSocketDisconnect:pass@app.websocket("/ws/watch")async def watch_ws(ws: WebSocket, path: str = "/"):await ws.accept()p = safe_path(path)await ws.send_json({"type":"watching","path":str(p)})try:async for changes in awatch(str(p)):events = [{"change": str(c[0].name), "path": c[1]} for c in changes]await ws.send_json({"type":"changes","events":events})except WebSocketDisconnect:pass@app.websocket("/ws/system")async def system_ws(ws: WebSocket, interval: float = 2.0):await ws.accept()try:while True:stats = await system_stats()await ws.send_json({"type":"stats","data":stats})await asyncio.sleep(max(interval, 1.0))except WebSocketDisconnect:pass# ββ Playwright Browser Proxy ββββββββββββββββββββββββββββββββββββββββββββββββββ# Streams a real Chromium screenshot as JPEG for each navigation.# Install: pip install playwright && playwright install chromium_browser = None_playwright = Noneasync def get_browser():global _browser, _playwrightif _browser is None:try:from playwright.async_api import async_playwright_playwright = await async_playwright().start()_browser = await _playwright.chromium.launch(headless=True,args=["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage","--disable-gpu","--single-process"])except Exception as e:raise HTTPException(503, f"Playwright not available: {e}")return _browser@app.get("/api/browser/screenshot")async def browser_screenshot(url: str, width: int = 390, height: int = 700):"""Take a screenshot of a URL and return it as JPEG."""if not url.startswith(("http://","https://")):url = "https://" + urltry:browser = await get_browser()page = await browser.new_page(viewport={"width": width, "height": height})await page.goto(url, wait_until="domcontentloaded", timeout=20000)screenshot = await page.screenshot(type="jpeg", quality=80, full_page=False)await page.close()from fastapi.responses import Responsereturn Response(content=screenshot, media_type="image/jpeg",headers={"X-Final-URL": page.url if not page.is_closed() else url})except HTTPException:raiseexcept Exception as e:raise HTTPException(502, f"Browser error: {e}")@app.websocket("/ws/browser")async def browser_ws(ws: WebSocket):"""WebSocket browser session.Client sends: {"type":"navigate","url":"https://..."}Server sends: {"type":"screenshot","data":"<base64 jpeg>","url":"...","title":"..."}"""await ws.accept()await ws.send_json({"type":"status","message":"Browser session ready"})page = Nonetry:browser = await get_browser()page = await browser.new_page(viewport={"width":390,"height":700})async def send_screenshot(p):try:shot = await p.screenshot(type="jpeg", quality=75)import base64await ws.send_json({"type": "screenshot","data": base64.b64encode(shot).decode(),"url": p.url,"title": await p.title(),})except Exception as e:await ws.send_json({"type":"error","message":str(e)})while True:msg = await ws.receive_json()if msg.get("type") == "navigate":url = msg["url"]if not url.startswith(("http://","https://")):url = "https://" + urlawait ws.send_json({"type":"loading","url":url})try:await page.goto(url, wait_until="domcontentloaded", timeout=20000)await send_screenshot(page)except Exception as e:await ws.send_json({"type":"error","message":str(e)})elif msg.get("type") == "click":await page.mouse.click(msg.get("x",0), msg.get("y",0))await asyncio.sleep(0.5)await send_screenshot(page)elif msg.get("type") == "scroll":await page.mouse.wheel(0, msg.get("delta",200))await asyncio.sleep(0.2)await send_screenshot(page)elif msg.get("type") == "back":await page.go_back()await send_screenshot(page)elif msg.get("type") == "forward":await page.go_forward()await send_screenshot(page)elif msg.get("type") == "refresh":await page.reload()await send_screenshot(page)except WebSocketDisconnect:passfinally:if page and not page.is_closed():await page.close()# ββ Docker ββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββdef run_docker(*args) -> dict:try:r = subprocess.run(["docker",*args], capture_output=True, text=True, timeout=10)return {"ok": r.returncode==0, "stdout": r.stdout, "stderr": r.stderr}except FileNotFoundError:return {"ok":False,"error":"Docker not installed"}except subprocess.TimeoutExpired:return {"ok":False,"error":"Timed out"}@app.get("/api/docker/containers")async def docker_containers():r = run_docker("ps","-a","--format","json")containers = []for line in r.get("stdout","").strip().splitlines():try: containers.append(json.loads(line))except: passreturn {"containers": containers, "error": r.get("error") or r.get("stderr") if not r["ok"] else None}@app.post("/api/docker/start/{cid}")async def docker_start(cid: str): return run_docker("start", cid)@app.post("/api/docker/stop/{cid}")async def docker_stop(cid: str): return run_docker("stop", cid)@app.get("/api/docker/images")async def docker_images():r = run_docker("images","--format","json")images = []for line in r.get("stdout","").strip().splitlines():try: images.append(json.loads(line))except: passreturn {"images": images}# ββ Health ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/api/health")async def health():return {"status":"ok","name":"TreyOS","version":"1.0.0","root":str(ROOT_JAIL)}# ββ Serve frontend ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# HuggingFace Spaces loads the root URL "/" directly in an iframe, so the# TreyOS UI must be served there β not just at /app β or the Space will# render blank.frontend_path = Path(__file__).parent / "frontend"if not frontend_path.exists():frontend_path = Path(__file__).parent.parent / "frontend"if frontend_path.exists():index_file = frontend_path / "index.html"@app.get("/")async def serve_root():return FileResponse(str(index_file), media_type="text/html")@app.get("/app")async def serve_app():return FileResponse(str(index_file), media_type="text/html")app.mount("/static", StaticFiles(directory=str(frontend_path)), name="static")else:@app.get("/")async def serve_root_fallback():return JSONResponse({"status":"ok","name":"TreyOS","warning":"frontend/ directory not found"})
backend/main.py+215-150