From 049280219b36be2234bb01fddb1deb547658df51 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 5 Jun 2026 23:47:03 -0400 Subject: [PATCH] refac --- cptr/app.py | 50 +++++++++++++++++++++++ cptr/routers/events.py | 67 +++++++++++++++++++++++++++++-- cptr/routers/state.py | 84 ++++++++++++++++++++++++++++++++++++++- cptr/routers/workspace.py | 6 ++- cptr/utils/git.py | 4 +- cptr/utils/tools.py | 2 +- 6 files changed, 206 insertions(+), 7 deletions(-) diff --git a/cptr/app.py b/cptr/app.py index bb6d05d..ef64bc2 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -63,6 +63,56 @@ async def auth_middleware(request: Request, call_next): return await call_next(request) +# Path normalization middleware (Windows: \ → / in JSON responses) +import platform +if platform.system() == "Windows": + import json as _json + + @app.middleware("http") + async def normalize_paths_middleware(request: Request, call_next): + response = await call_next(request) + if ( + response.headers.get("content-type", "").startswith("application/json") + and hasattr(response, "body") + ): + try: + body = b"" + async for chunk in response.body_iterator: + body += chunk if isinstance(chunk, bytes) else chunk.encode() + text = body.decode("utf-8") + # Replace backslashes that appear in JSON string values + # (JSON already escapes \ as \\, so we replace \\\\ with /) + data = _json.loads(text) + _normalize_obj(data) + new_body = _json.dumps(data, ensure_ascii=False).encode("utf-8") + from starlette.responses import Response as StarletteResponse + return StarletteResponse( + content=new_body, + status_code=response.status_code, + headers=dict(response.headers), + media_type="application/json", + ) + except Exception: + pass + return response + + def _normalize_obj(obj): + """Recursively replace backslashes with forward slashes in string values + that look like file paths (contain :\\).""" + if isinstance(obj, dict): + for k, v in obj.items(): + if isinstance(v, str) and "\\" in v: + obj[k] = v.replace("\\", "/") + elif isinstance(v, (dict, list)): + _normalize_obj(v) + elif isinstance(obj, list): + for i, v in enumerate(obj): + if isinstance(v, str) and "\\" in v: + obj[i] = v.replace("\\", "/") + elif isinstance(v, (dict, list)): + _normalize_obj(v) + + @app.get("/api/config") async def get_config(): """Public config for the frontend.""" diff --git a/cptr/routers/events.py b/cptr/routers/events.py index 88af938..548b66a 100644 --- a/cptr/routers/events.py +++ b/cptr/routers/events.py @@ -98,6 +98,9 @@ async def _fs_watcher_loop(ws: WebSocket, initial_path: str, path_holder: dict) paths = handler.drain() if paths: + # Normalize to forward slashes so the frontend can compare with / + if sys.platform == "win32": + paths = [p.replace("\\", "/") for p in paths] try: await ws.send_json({"type": "fs_change", "paths": paths}) except Exception: @@ -125,7 +128,16 @@ _SYSTEM_PORTS = {22, 53, 80, 443, 631, 5353} def _get_ppid(pid: int) -> int: """Get parent PID. Cross-platform.""" try: - if sys.platform == "linux": + if sys.platform == "win32": + r = subprocess.run( + ["wmic", "process", "where", f"ProcessId={pid}", "get", "ParentProcessId", "/value"], + capture_output=True, text=True, timeout=3, + ) + for line in r.stdout.splitlines(): + if line.startswith("ParentProcessId="): + return int(line.split("=", 1)[1]) + return 0 + elif sys.platform == "linux": with open(f"/proc/{pid}/stat") as f: return int(f.read().split()[3]) else: @@ -145,8 +157,16 @@ def _find_session_for_pid(pid: int) -> Optional[str]: while current > 1 and current not in visited: visited.add(current) for session in manager._sessions.values(): + # Unix: match by child PID if session._pid == current: return session.session_id + # Windows: winpty process has a .pid attribute + if session._process is not None: + try: + if getattr(session._process, "pid", None) == current: + return session.session_id + except Exception: + pass current = _get_ppid(current) return None @@ -154,7 +174,17 @@ def _find_session_for_pid(pid: int) -> Optional[str]: def _get_process_name(pid: int) -> str: """Get process name from PID.""" try: - if sys.platform == "linux": + if sys.platform == "win32": + r = subprocess.run( + ["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"], + capture_output=True, text=True, timeout=3, + ) + # Output: "name.exe","1234",... + line = r.stdout.strip() + if line and line.startswith('"'): + return line.split('"')[1] + return "unknown" + elif sys.platform == "linux": with open(f"/proc/{pid}/comm") as f: return f.read().strip() else: @@ -249,6 +279,36 @@ def _inode_to_pid(inode: int) -> Optional[int]: return None +def _scan_ports_windows() -> list[dict]: + """Scan listening ports on Windows using netstat.""" + try: + r = subprocess.run( + ["netstat", "-ano", "-p", "TCP"], + capture_output=True, text=True, timeout=5, + ) + ports = [] + for line in r.stdout.splitlines(): + parts = line.split() + if len(parts) >= 5 and "LISTENING" in parts: + local = parts[1] + if ":" in local: + port_str = local.rsplit(":", 1)[1] + try: + port = int(port_str) + pid = int(parts[-1]) + ports.append({ + "port": port, + "pid": pid, + "process": _get_process_name(pid), + }) + except ValueError: + pass + return ports + except Exception as e: + logger.warning(f"Port scan failed: {e}") + return [] + + def _scan_ports() -> list[dict]: """Scan listening ports. Cross-platform.""" system = platform.system() @@ -256,8 +316,9 @@ def _scan_ports() -> list[dict]: raw = _scan_ports_darwin() elif system == "Linux": raw = _scan_ports_linux() + elif system == "Windows": + raw = _scan_ports_windows() else: - # Windows fallback, not implemented yet return [] # Get our own PID to filter ourselves out diff --git a/cptr/routers/state.py b/cptr/routers/state.py index 0c4faae..fe396d8 100644 --- a/cptr/routers/state.py +++ b/cptr/routers/state.py @@ -161,6 +161,25 @@ async def get_welcome(request: Request): mem[parts[0].rstrip(":")] = int(parts[1]) * 1024 system["memory_total"] = mem.get("MemTotal", 0) system["memory_available"] = mem.get("MemAvailable", 0) + elif platform.system() == "Windows": + import ctypes + class MEMORYSTATUSEX(ctypes.Structure): + _fields_ = [ + ("dwLength", ctypes.c_ulong), + ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), + ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), + ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), + ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong), + ] + mem_info = MEMORYSTATUSEX() + mem_info.dwLength = ctypes.sizeof(MEMORYSTATUSEX) + ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(mem_info)) + system["memory_total"] = mem_info.ullTotalPhys + system["memory_available"] = mem_info.ullAvailPhys except Exception: pass @@ -187,6 +206,10 @@ async def get_welcome(request: Request): elif platform.system() == "Linux": with open("/proc/uptime") as f: system["uptime_seconds"] = int(float(f.read().split()[0])) + elif platform.system() == "Windows": + import ctypes + ms = ctypes.windll.kernel32.GetTickCount64() + system["uptime_seconds"] = ms // 1000 except Exception: pass @@ -213,6 +236,15 @@ async def get_welcome(request: Request): cpus = system.get("cpu_count", 1) if load and cpus: system["cpu_usage"] = round(min(load[0] / cpus * 100, 100), 1) + elif platform.system() == "Windows": + result = subprocess.run( + ["wmic", "cpu", "get", "loadpercentage", "/value"], + capture_output=True, text=True, timeout=5, + ) + for line in result.stdout.splitlines(): + if line.startswith("LoadPercentage="): + system["cpu_usage"] = float(line.split("=", 1)[1]) + break except Exception: pass @@ -240,6 +272,19 @@ async def get_welcome(request: Request): parts = line.split() if len(parts) >= 4 and "127.0.0.1" not in parts[3]: interfaces.append({"name": parts[1], "ip": parts[3].split("/")[0]}) + elif platform.system() == "Windows": + result = subprocess.run( + ["ipconfig"], capture_output=True, text=True, timeout=3, + ) + current_iface = "" + for line in result.stdout.splitlines(): + stripped = line.strip() + if line and not line.startswith(" ") and ":" in line: + current_iface = line.split(":")[0].strip() + elif "IPv4" in stripped and ":" in stripped: + ip = stripped.rsplit(":", 1)[1].strip() + if ip != "127.0.0.1": + interfaces.append({"name": current_iface, "ip": ip}) if interfaces: system["network"] = interfaces except Exception: @@ -277,10 +322,42 @@ async def get_welcome(request: Request): "mem": float(parts[2]), "name": parts[3], }) + elif platform.system() == "Windows": + result = subprocess.run( + ["tasklist", "/FO", "CSV", "/NH"], + capture_output=True, text=True, timeout=5, + ) + import csv + from io import StringIO + reader = csv.reader(StringIO(result.stdout)) + mem_total = system.get("memory_total", 1) + entries = [] + for row in reader: + if len(row) >= 5: + try: + pid = int(row[1]) + # Memory is in "N,NNN K" format + mem_str = row[4].replace(",", "").replace(" K", "").strip() + mem_kb = int(mem_str) if mem_str.isdigit() else 0 + entries.append({ + "pid": pid, + "cpu": 0, # tasklist doesn't provide CPU% + "mem": round(mem_kb * 1024 / mem_total * 100, 1) if mem_total else 0, + "name": row[0], + "_mem_kb": mem_kb, + }) + except (ValueError, IndexError): + pass + # Sort by memory usage (best we can do without psutil) + entries.sort(key=lambda e: e.get("_mem_kb", 0), reverse=True) + for e in entries[:5]: + e.pop("_mem_kb", None) + processes.append(e) except Exception: pass # Suggested directories + import tempfile home = str(Path.home()) candidates = [ home, @@ -294,8 +371,13 @@ async def get_welcome(request: Request): str(Path.home() / "dev"), str(Path.home() / "workspace"), str(Path.home() / "src"), - "/tmp", ] + if platform.system() == "Windows": + candidates.extend([ + str(Path.home() / "source" / "repos"), + str(Path.home() / "OneDrive" / "Documents"), + ]) + candidates.append(tempfile.gettempdir()) suggestions = [] seen = set() for c in candidates: diff --git a/cptr/routers/workspace.py b/cptr/routers/workspace.py index 77e99d6..b7377b4 100644 --- a/cptr/routers/workspace.py +++ b/cptr/routers/workspace.py @@ -482,7 +482,11 @@ async def serve_static(file_path: str): HTML files in iframes can resolve relative CSS/JS/image references. E.g. /api/files/serve/home/user/project/index.html """ - target = Path("/" + file_path).resolve() + # Windows paths arrive as "C:/Users/..." - don't prepend / + if len(file_path) >= 2 and file_path[1] == ':': + target = Path(file_path).resolve() + else: + target = Path("/" + file_path).resolve() if not target.exists(): raise HTTPException(status_code=404, detail=f"File not found: {file_path}") diff --git a/cptr/utils/git.py b/cptr/utils/git.py index 3abcd71..a09cbfe 100644 --- a/cptr/utils/git.py +++ b/cptr/utils/git.py @@ -8,6 +8,7 @@ from __future__ import annotations import asyncio import os +import sys from typing import Any @@ -130,9 +131,10 @@ async def diff( """Get diff output as structured data.""" if untracked and file: # Untracked files: use --no-index to diff against empty + null_device = "NUL" if sys.platform == "win32" else "/dev/null" _, out, _ = await _run( "diff", "--no-index", "--unified=3", - "--", "/dev/null", file, + "--", null_device, file, cwd=root, check=False, ) return _parse_diff(out) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index ab4ba8f..a0d3e6c 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -227,7 +227,7 @@ async def _search_rg( raise FileNotFoundError(err) if "not found" in err.lower() else Exception(err) # Make paths relative - prefix = str(full) + "/" + prefix = str(full) + os.sep lines = output.splitlines()[:50] result = [line.replace(prefix, "") for line in lines] return "\n".join(result) if result else "No matches found."