Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/env_doctor/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from fastapi.staticfiles import StaticFiles

from . import database as _db
from .auth import require_token
from .auth import get_active_token, require_token
from .routes import router as api_router


Expand Down Expand Up @@ -58,9 +58,17 @@ async def serve_spa(full_path: str):
file_path = os.path.join(_WEB_DIR, full_path)
if full_path and os.path.isfile(file_path):
return FileResponse(file_path)
# Fallback to index.html for client-side routing
# Fallback to index.html for client-side routing.
# Inject the API token so the browser auto-authenticates without a login form.
index = os.path.join(_WEB_DIR, "index.html")
if os.path.isfile(index):
token = get_active_token()
if token:
from fastapi.responses import HTMLResponse
html = open(index, encoding="utf-8").read()
snippet = f'<script>window.__ENV_DOCTOR_TOKEN__="{token}"</script>'
html = html.replace("</head>", f"{snippet}</head>", 1)
return HTMLResponse(html)
return FileResponse(index)
return {"detail": "Frontend not built. Run 'npm run build' in web/ directory."}
else:
Expand Down
68 changes: 68 additions & 0 deletions src/env_doctor/server/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,71 @@ async def list_commands(
)
result = await session.execute(query)
return [c.to_dict() for c in result.scalars().all()]


# ---------------------------------------------------------------------------
# GET /api/commands (cross-fleet activity log)
# ---------------------------------------------------------------------------

_VALID_COMMAND_STATUSES = {"pending", "running", "done", "failed"}


def _parse_iso(value: str) -> datetime:
# datetime.fromisoformat in 3.11+ accepts trailing "Z"; older Pythons need a swap.
if value.endswith("Z"):
value = value[:-1] + "+00:00"
return datetime.fromisoformat(value)


@router.get("/commands")
async def list_command_activity(
status: Optional[str] = Query(None, description="pending | running | done | failed"),
machine_id: Optional[str] = Query(None),
since: Optional[str] = Query(None, description="ISO-8601 timestamp lower bound on created_at"),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_session),
):
"""Cross-fleet command activity log with hostname joined in."""
if status is not None and status not in _VALID_COMMAND_STATUSES:
raise HTTPException(
status_code=400,
detail=f"status must be one of {sorted(_VALID_COMMAND_STATUSES)}",
)

since_dt: Optional[datetime] = None
if since:
try:
since_dt = _parse_iso(since)
except ValueError:
raise HTTPException(status_code=400, detail="since must be an ISO-8601 timestamp")

query = (
select(Command, Machine.hostname)
.join(Machine, Command.machine_id == Machine.id, isouter=True)
.order_by(Command.created_at.desc())
.limit(limit)
.offset(offset)
)
if status:
query = query.where(Command.status == status)
if machine_id:
query = query.where(Command.machine_id == machine_id)
if since_dt is not None:
query = query.where(Command.created_at >= since_dt)

result = await session.execute(query)
rows = result.all()

output = []
for cmd, hostname in rows:
item = cmd.to_dict()
item["hostname"] = hostname
if cmd.created_at and cmd.executed_at:
created = cmd.created_at if cmd.created_at.tzinfo else cmd.created_at.replace(tzinfo=timezone.utc)
executed = cmd.executed_at if cmd.executed_at.tzinfo else cmd.executed_at.replace(tzinfo=timezone.utc)
item["duration_seconds"] = (executed - created).total_seconds()
else:
item["duration_seconds"] = None
output.append(item)
return output
11 changes: 11 additions & 0 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ function FleetIcon() {
);
}

function ActivityIcon() {
return (
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<polyline points="2 9 5 9 7 4 11 14 13 9 16 9" />
</svg>
);
}

const navStyle = (isActive: boolean): React.CSSProperties => ({
display: "flex",
alignItems: "center",
Expand Down Expand Up @@ -112,6 +120,9 @@ export default function App() {
<NavLink to="/fleet" style={({ isActive }) => navStyle(isActive)}>
<FleetIcon /> Fleet
</NavLink>
<NavLink to="/activity" style={({ isActive }) => navStyle(isActive)}>
<ActivityIcon /> Activity
</NavLink>
</div>

<div style={{
Expand Down
31 changes: 30 additions & 1 deletion web/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import type { CommandRecord, MachineListItem, MachineDetail, SnapshotSummary } from "./types";
import type {
CommandActivityFilters,
CommandActivityRow,
CommandRecord,
MachineDetail,
MachineListItem,
SnapshotSummary,
} from "./types";

const BASE = "/api";
const TOKEN_KEY = "envDoctorToken";

// When the server injects the token into the HTML, auto-store it so the login
// screen is skipped entirely. This runs before React mounts.
(function seedInjectedToken() {
const injected = (window as unknown as Record<string, unknown>).__ENV_DOCTOR_TOKEN__;
if (typeof injected === "string" && injected) {
try { localStorage.setItem(TOKEN_KEY, injected); } catch { /* ignore */ }
}
})();

export function getToken(): string | null {
try {
return localStorage.getItem(TOKEN_KEY);
Expand Down Expand Up @@ -88,6 +104,19 @@ export function getCommands(machineId: string): Promise<CommandRecord[]> {
return fetchJson(`${BASE}/machines/${machineId}/commands`);
}

export function getCommandActivity(
filters: CommandActivityFilters = {}
): Promise<CommandActivityRow[]> {
const params = new URLSearchParams();
if (filters.status) params.set("status", filters.status);
if (filters.machine_id) params.set("machine_id", filters.machine_id);
if (filters.since) params.set("since", filters.since);
if (filters.limit != null) params.set("limit", String(filters.limit));
if (filters.offset != null) params.set("offset", String(filters.offset));
const qs = params.toString();
return fetchJson(`${BASE}/commands${qs ? `?${qs}` : ""}`);
}

export async function verifyToken(): Promise<boolean> {
try {
const res = await apiFetch(`${BASE}/machines`);
Expand Down
2 changes: 2 additions & 0 deletions web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import App from "./App";
import Activity from "./pages/Activity";
import FleetOverview from "./pages/FleetOverview";
import MachineDetailPage from "./pages/MachineDetail";
import TopologyView from "./pages/TopologyView";
Expand All @@ -14,6 +15,7 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<Route index element={<Navigate to="/topology" replace />} />
<Route path="topology" element={<TopologyView />} />
<Route path="fleet" element={<FleetOverview />} />
<Route path="activity" element={<Activity />} />
<Route path="machines/:id" element={<MachineDetailPage />} />
</Route>
</Routes>
Expand Down
Loading
Loading