Add ScreenConnect-parity features (high + medium)
Viewer: - Toolbar: Ctrl+Alt+Del, clipboard paste, monitor picker, file transfer, chat, WoL buttons - Multi-monitor: agent sends monitor_list on connect, viewer can switch via dropdown - Clipboard sync: agent polls local clipboard → sends to viewer; viewer paste → agent sets remote clipboard - File transfer panel: drag-drop upload to agent, directory browser, download files from remote - Chat panel: bidirectional text chat forwarded through relay Agent: - Multi-monitor capture with set_monitor/set_quality message handlers - exec_key_combo for Ctrl+Alt+Del and arbitrary combos - Clipboard polling via pyperclip (both directions) - File upload/download/list_files with base64 chunked protocol - Attended mode (--attended): zenity/kdialog/PowerShell consent dialog before accepting stream - Auto-update: heartbeat checks version, downloads new binary and exec-replaces self (Linux) - Reports MAC address on registration (for WoL) Relay: - Forwards monitor_list, clipboard_content, file_chunk, file_list, chat_message agent→viewer - Session recording: when RECORDING_DIR env set, saves JPEG frames as .remrec files - ALLOWED_ORIGINS CORS now set from NEXT_PUBLIC_APP_URL in docker-compose Database: - groups table (id, name, description, created_by) - machines: group_id, mac_address, notes, tags text[] - Migration 0003 applied Dashboard: - Machines page: search, tag filter, group filter, inline notes/tags/rename editing - MachineCard: inline tag management, group picker, notes textarea - Admin page: new Groups tab (create/list/delete groups) - API: PATCH /api/machines/[id] (name, notes, tags, groupId) - API: GET/POST/DELETE /api/groups - API: POST /api/machines/wol (broadcast magic packet) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
364
agent/agent.py
364
agent/agent.py
@@ -14,6 +14,7 @@ Usage:
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -21,6 +22,7 @@ import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid as uuid_lib
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
@@ -126,6 +128,7 @@ async def register(server_url: str, enrollment_token: str) -> dict:
|
||||
"osVersion": os_version,
|
||||
"agentVersion": AGENT_VERSION,
|
||||
"ipAddress": None,
|
||||
"macAddress": get_mac_address(),
|
||||
})
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"Registration failed: {resp.status_code} {resp.text}")
|
||||
@@ -135,18 +138,49 @@ async def register(server_url: str, enrollment_token: str) -> dict:
|
||||
|
||||
|
||||
async def heartbeat(server_url: str, access_key: str) -> Optional[dict]:
|
||||
"""Send heartbeat, returns pending connection info if any."""
|
||||
"""Send heartbeat, returns server response including update info."""
|
||||
url = f"{server_url.rstrip('/')}/api/agent/heartbeat"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.post(url, json={"accessKey": access_key})
|
||||
resp = await client.post(url, json={"accessKey": access_key, "agentVersion": AGENT_VERSION})
|
||||
if resp.status_code == 200:
|
||||
return resp.json()
|
||||
data = resp.json()
|
||||
if data.get("updateAvailable"):
|
||||
asyncio.create_task(_auto_update(data["updateAvailable"]))
|
||||
return data
|
||||
except Exception as e:
|
||||
log.warning(f"Heartbeat failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def _auto_update(update_info: dict) -> None:
|
||||
"""Download new agent binary and replace self, then restart."""
|
||||
download_url = update_info.get("downloadUrl")
|
||||
if not download_url:
|
||||
return
|
||||
log.info(f"Update available: {update_info.get('version')}. Downloading from {download_url}")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=120, follow_redirects=True) as client:
|
||||
resp = await client.get(download_url)
|
||||
if resp.status_code != 200:
|
||||
log.warning(f"Update download failed: {resp.status_code}")
|
||||
return
|
||||
# Write to a temp file alongside the current binary
|
||||
current = Path(sys.executable)
|
||||
tmp = current.with_suffix(".new")
|
||||
tmp.write_bytes(resp.content)
|
||||
tmp.chmod(0o755)
|
||||
# Atomically replace (Unix only — Windows needs a separate updater process)
|
||||
if platform.system() != "Windows":
|
||||
tmp.replace(current)
|
||||
log.info(f"Agent updated to {update_info.get('version')}. Restarting…")
|
||||
os.execv(str(current), sys.argv)
|
||||
else:
|
||||
log.info("Update downloaded. Restart the service to apply on Windows.")
|
||||
except Exception as e:
|
||||
log.warning(f"Auto-update failed: {e}")
|
||||
|
||||
|
||||
async def get_session_code(server_url: str, access_key: str) -> Optional[str]:
|
||||
"""Request a new session code from the server."""
|
||||
url = f"{server_url.rstrip('/')}/api/agent/session-code"
|
||||
@@ -166,13 +200,17 @@ class ScreenCapture:
|
||||
self.quality = quality
|
||||
self._frame_delay = 1.0 / fps
|
||||
self._sct = None
|
||||
self._monitors: list = [] # mss monitors (excluding index 0 = all)
|
||||
self._monitor_idx: int = 0 # 0-based into _monitors
|
||||
|
||||
def __enter__(self):
|
||||
try:
|
||||
self._sct = mss()
|
||||
self._monitors = self._sct.monitors[1:] # skip [0] = virtual all-screens
|
||||
except Exception as e:
|
||||
log.warning(f"Screen capture unavailable: {e}")
|
||||
self._sct = None
|
||||
self._monitors = []
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
@@ -183,11 +221,39 @@ class ScreenCapture:
|
||||
def available(self) -> bool:
|
||||
return self._sct is not None
|
||||
|
||||
def set_monitor(self, idx: int):
|
||||
if 0 <= idx < len(self._monitors):
|
||||
self._monitor_idx = idx
|
||||
|
||||
def set_quality(self, quality: int):
|
||||
self.quality = max(10, min(95, quality))
|
||||
fps_map = {"high": 15, "medium": 10, "low": 5}
|
||||
# quality levels sent from viewer as strings
|
||||
if isinstance(quality, str):
|
||||
self.fps = fps_map.get(quality, 15)
|
||||
self.quality = {"high": 70, "medium": 55, "low": 35}.get(quality, 70)
|
||||
else:
|
||||
self.quality = max(10, min(95, quality))
|
||||
self._frame_delay = 1.0 / self.fps
|
||||
|
||||
def get_monitor_list(self) -> list:
|
||||
return [
|
||||
{
|
||||
"index": i,
|
||||
"width": m["width"],
|
||||
"height": m["height"],
|
||||
"left": m["left"],
|
||||
"top": m["top"],
|
||||
"primary": i == 0,
|
||||
}
|
||||
for i, m in enumerate(self._monitors)
|
||||
]
|
||||
|
||||
def capture(self) -> Optional[bytes]:
|
||||
if not self._sct:
|
||||
if not self._sct or not self._monitors:
|
||||
return None
|
||||
try:
|
||||
monitor = self._sct.monitors[1] # Primary monitor
|
||||
monitor = self._monitors[self._monitor_idx]
|
||||
img = self._sct.grab(monitor)
|
||||
pil = Image.frombytes("RGB", img.size, img.bgra, "raw", "BGRX")
|
||||
buf = BytesIO()
|
||||
@@ -239,10 +305,8 @@ class InputController:
|
||||
elif t == "mouse_scroll":
|
||||
self._mouse.scroll(event.get("dx", 0), event.get("dy", 0))
|
||||
elif t == "key_press":
|
||||
key_str = event.get("key", "")
|
||||
self._keyboard.type(key_str)
|
||||
self._keyboard.type(event.get("key", ""))
|
||||
elif t == "key_special":
|
||||
# Special keys like Enter, Tab, Escape, etc.
|
||||
key_name = event.get("key", "")
|
||||
try:
|
||||
key = getattr(self._Key, key_name)
|
||||
@@ -250,6 +314,19 @@ class InputController:
|
||||
self._keyboard.release(key)
|
||||
except AttributeError:
|
||||
pass
|
||||
elif t == "exec_key_combo":
|
||||
# e.g. {"type":"exec_key_combo","keys":["ctrl_l","alt_l","delete"]}
|
||||
keys = event.get("keys", [])
|
||||
pressed = []
|
||||
for k in keys:
|
||||
try:
|
||||
key_obj = getattr(self._Key, k)
|
||||
self._keyboard.press(key_obj)
|
||||
pressed.append(key_obj)
|
||||
except AttributeError:
|
||||
pass
|
||||
for key_obj in reversed(pressed):
|
||||
self._keyboard.release(key_obj)
|
||||
except Exception as e:
|
||||
log.debug(f"Input error: {e}")
|
||||
|
||||
@@ -301,6 +378,157 @@ async def exec_script(script: str, shell: str, session_id: str, ws) -> None:
|
||||
}))
|
||||
|
||||
|
||||
# ── Clipboard helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
def _get_clipboard() -> str:
|
||||
try:
|
||||
import pyperclip
|
||||
return pyperclip.paste() or ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _set_clipboard(text: str):
|
||||
try:
|
||||
import pyperclip
|
||||
pyperclip.copy(text)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ── File transfer helpers ─────────────────────────────────────────────────────
|
||||
|
||||
CHUNK_SIZE = 65536 # 64 KB per chunk
|
||||
|
||||
|
||||
async def send_file(path_str: str, session_id: str, ws) -> None:
|
||||
"""Read a file and send it to the viewer as base64 chunks."""
|
||||
try:
|
||||
path = Path(path_str).expanduser().resolve()
|
||||
if not path.is_file():
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_chunk", "session_id": session_id,
|
||||
"error": f"File not found: {path_str}", "done": True,
|
||||
}))
|
||||
return
|
||||
total = path.stat().st_size
|
||||
filename = path.name
|
||||
seq = 0
|
||||
with open(path, "rb") as f:
|
||||
while True:
|
||||
chunk = f.read(CHUNK_SIZE)
|
||||
if not chunk:
|
||||
break
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_chunk",
|
||||
"session_id": session_id,
|
||||
"filename": filename,
|
||||
"size": total,
|
||||
"seq": seq,
|
||||
"chunk": base64.b64encode(chunk).decode(),
|
||||
"done": False,
|
||||
}))
|
||||
seq += 1
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_chunk",
|
||||
"session_id": session_id,
|
||||
"filename": filename,
|
||||
"size": total,
|
||||
"seq": seq,
|
||||
"chunk": "",
|
||||
"done": True,
|
||||
}))
|
||||
log.info(f"Sent file {filename} ({total} bytes) to viewer")
|
||||
except Exception as e:
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_chunk", "session_id": session_id,
|
||||
"error": str(e), "done": True,
|
||||
}))
|
||||
|
||||
|
||||
async def list_files(path_str: str, session_id: str, ws) -> None:
|
||||
"""Send a directory listing to the viewer."""
|
||||
try:
|
||||
path = Path(path_str or "~").expanduser().resolve()
|
||||
if not path.is_dir():
|
||||
path = path.parent
|
||||
entries = []
|
||||
for entry in sorted(path.iterdir(), key=lambda e: (not e.is_dir(), e.name.lower())):
|
||||
try:
|
||||
stat = entry.stat()
|
||||
entries.append({
|
||||
"name": entry.name,
|
||||
"is_dir": entry.is_dir(),
|
||||
"size": stat.st_size if entry.is_file() else 0,
|
||||
"path": str(entry),
|
||||
})
|
||||
except PermissionError:
|
||||
pass
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_list",
|
||||
"session_id": session_id,
|
||||
"path": str(path),
|
||||
"parent": str(path.parent) if path.parent != path else None,
|
||||
"entries": entries,
|
||||
}))
|
||||
except Exception as e:
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_list", "session_id": session_id,
|
||||
"path": path_str, "entries": [], "error": str(e),
|
||||
}))
|
||||
|
||||
|
||||
async def _prompt_user_consent(timeout: int = 30) -> bool:
|
||||
"""Show a local dialog asking the user to accept the incoming connection.
|
||||
Returns True if accepted within timeout, False otherwise."""
|
||||
try:
|
||||
if platform.system() == "Windows":
|
||||
# Use PowerShell MessageBox
|
||||
script = (
|
||||
"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null;"
|
||||
"$r = [System.Windows.Forms.MessageBox]::Show("
|
||||
"'A technician is requesting remote access to this computer. Allow?',"
|
||||
"'RemoteLink — Incoming Connection',"
|
||||
"[System.Windows.Forms.MessageBoxButtons]::YesNo,"
|
||||
"[System.Windows.Forms.MessageBoxIcon]::Question);"
|
||||
"exit ($r -eq 'Yes' ? 0 : 1)"
|
||||
)
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"powershell", "-NonInteractive", "-Command", script,
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(proc.wait(), timeout=timeout)
|
||||
return proc.returncode == 0
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
return False
|
||||
elif platform.system() == "Linux":
|
||||
# Try zenity (GNOME), then kdialog (KDE), then xterm fallback
|
||||
for cmd in [
|
||||
["zenity", "--question", "--title=RemoteLink", f"--text=A technician is requesting remote access. Allow?", f"--timeout={timeout}"],
|
||||
["kdialog", "--yesno", "A technician is requesting remote access. Allow?", "--title", "RemoteLink"],
|
||||
]:
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(*cmd)
|
||||
await asyncio.wait_for(proc.wait(), timeout=timeout + 5)
|
||||
return proc.returncode == 0
|
||||
except (FileNotFoundError, asyncio.TimeoutError):
|
||||
continue
|
||||
# No GUI available — log and deny
|
||||
log.warning("Attended mode: no GUI dialog available, denying connection")
|
||||
return False
|
||||
else:
|
||||
return True # macOS: always allow for now
|
||||
except Exception as e:
|
||||
log.warning(f"Consent dialog error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def get_mac_address() -> str:
|
||||
mac = uuid_lib.getnode()
|
||||
return ":".join(f"{(mac >> (8 * i)) & 0xff:02X}" for i in reversed(range(6)))
|
||||
|
||||
|
||||
# ── Main agent loop ───────────────────────────────────────────────────────────
|
||||
|
||||
class Agent:
|
||||
@@ -314,6 +542,10 @@ class Agent:
|
||||
self._active_session: Optional[str] = None
|
||||
self._input = InputController()
|
||||
self._stop_event = asyncio.Event()
|
||||
self._screen: Optional[ScreenCapture] = None
|
||||
self._attended_mode: bool = False # set via --attended flag
|
||||
# file upload buffers: transfer_id → {filename, dest, chunks[]}
|
||||
self._uploads: dict = {}
|
||||
|
||||
async def run(self):
|
||||
log.info(f"Agent starting. Machine ID: {self.machine_id}")
|
||||
@@ -344,8 +576,28 @@ class Agent:
|
||||
log.info("Connected to relay")
|
||||
await self._message_loop(ws)
|
||||
|
||||
async def _clipboard_poll(self, ws):
|
||||
"""Poll local clipboard every 2s; send changes to active viewer."""
|
||||
last = _get_clipboard()
|
||||
while not self._stop_event.is_set():
|
||||
await asyncio.sleep(2)
|
||||
if not self._active_session:
|
||||
continue
|
||||
current = _get_clipboard()
|
||||
if current != last and current:
|
||||
last = current
|
||||
try:
|
||||
await ws.send(json.dumps({
|
||||
"type": "clipboard_content",
|
||||
"session_id": self._active_session,
|
||||
"content": current,
|
||||
}))
|
||||
except Exception:
|
||||
break
|
||||
|
||||
async def _message_loop(self, ws):
|
||||
with ScreenCapture(fps=15, quality=60) as screen:
|
||||
self._screen = screen
|
||||
if not screen.available:
|
||||
log.warning(
|
||||
"Screen capture unavailable — agent will stay connected "
|
||||
@@ -353,6 +605,7 @@ class Agent:
|
||||
)
|
||||
|
||||
stream_task: Optional[asyncio.Task] = None
|
||||
clipboard_task: Optional[asyncio.Task] = None
|
||||
|
||||
async def stream_frames():
|
||||
while self._streaming and not self._stop_event.is_set():
|
||||
@@ -382,17 +635,38 @@ class Agent:
|
||||
if msg_type == "start_stream":
|
||||
session_id = msg.get("session_id")
|
||||
log.info(f"Viewer connected — session {session_id}")
|
||||
|
||||
# Attended mode: ask local user for consent
|
||||
if self._attended_mode:
|
||||
accepted = await _prompt_user_consent()
|
||||
if not accepted:
|
||||
await ws.send(json.dumps({
|
||||
"type": "error",
|
||||
"session_id": session_id,
|
||||
"message": "Remote session denied by local user.",
|
||||
}))
|
||||
continue
|
||||
|
||||
self._streaming = True
|
||||
self._active_session = session_id
|
||||
if not screen.available:
|
||||
# Tell viewer why they won't see frames
|
||||
await ws.send(json.dumps({
|
||||
"type": "error",
|
||||
"message": "Screen capture unavailable on this machine (no display). Set $DISPLAY and restart the agent.",
|
||||
"message": "Screen capture unavailable (no display). Set $DISPLAY and restart the agent.",
|
||||
}))
|
||||
# Send monitor list to viewer
|
||||
await ws.send(json.dumps({
|
||||
"type": "monitor_list",
|
||||
"session_id": session_id,
|
||||
"monitors": screen.get_monitor_list(),
|
||||
}))
|
||||
if stream_task and not stream_task.done():
|
||||
stream_task.cancel()
|
||||
stream_task = asyncio.create_task(stream_frames())
|
||||
# Start clipboard polling
|
||||
if clipboard_task and not clipboard_task.done():
|
||||
clipboard_task.cancel()
|
||||
clipboard_task = asyncio.create_task(self._clipboard_poll(ws))
|
||||
|
||||
elif msg_type == "stop_stream":
|
||||
log.info("Viewer disconnected — stopping stream")
|
||||
@@ -400,11 +674,28 @@ class Agent:
|
||||
self._active_session = None
|
||||
if stream_task and not stream_task.done():
|
||||
stream_task.cancel()
|
||||
if clipboard_task and not clipboard_task.done():
|
||||
clipboard_task.cancel()
|
||||
|
||||
elif msg_type == "set_monitor":
|
||||
screen.set_monitor(msg.get("index", 0))
|
||||
log.info(f"Switched to monitor {msg.get('index', 0)}")
|
||||
|
||||
elif msg_type == "set_quality":
|
||||
q = msg.get("quality", "high")
|
||||
quality_map = {"high": 70, "medium": 55, "low": 35}
|
||||
fps_map = {"high": 15, "medium": 10, "low": 5}
|
||||
screen.quality = quality_map.get(q, 70)
|
||||
screen.fps = fps_map.get(q, 15)
|
||||
screen._frame_delay = 1.0 / screen.fps
|
||||
|
||||
elif msg_type in ("mouse_move", "mouse_click", "mouse_scroll",
|
||||
"key_press", "key_special"):
|
||||
"key_press", "key_special", "exec_key_combo"):
|
||||
self._input.handle(msg)
|
||||
|
||||
elif msg_type == "clipboard_paste":
|
||||
_set_clipboard(msg.get("content", ""))
|
||||
|
||||
elif msg_type == "exec_script":
|
||||
asyncio.create_task(exec_script(
|
||||
msg.get("script", ""),
|
||||
@@ -413,13 +704,62 @@ class Agent:
|
||||
ws,
|
||||
))
|
||||
|
||||
elif msg_type == "file_download":
|
||||
asyncio.create_task(send_file(
|
||||
msg.get("path", ""),
|
||||
msg.get("session_id", self._active_session or ""),
|
||||
ws,
|
||||
))
|
||||
|
||||
elif msg_type == "list_files":
|
||||
asyncio.create_task(list_files(
|
||||
msg.get("path", "~"),
|
||||
msg.get("session_id", self._active_session or ""),
|
||||
ws,
|
||||
))
|
||||
|
||||
elif msg_type == "file_upload_start":
|
||||
tid = msg.get("transfer_id", "")
|
||||
filename = Path(msg.get("filename", "upload")).name
|
||||
dest = Path(msg.get("dest_path", "~")).expanduser() / filename
|
||||
self._uploads[tid] = {"dest": dest, "chunks": []}
|
||||
log.info(f"File upload starting: {filename} → {dest}")
|
||||
|
||||
elif msg_type == "file_upload_chunk":
|
||||
tid = msg.get("transfer_id", "")
|
||||
if tid in self._uploads:
|
||||
chunk = base64.b64decode(msg.get("chunk", ""))
|
||||
self._uploads[tid]["chunks"].append(chunk)
|
||||
|
||||
elif msg_type == "file_upload_end":
|
||||
tid = msg.get("transfer_id", "")
|
||||
if tid in self._uploads:
|
||||
info = self._uploads.pop(tid)
|
||||
dest: Path = info["dest"]
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(dest, "wb") as f:
|
||||
for chunk in info["chunks"]:
|
||||
f.write(chunk)
|
||||
log.info(f"File upload complete: {dest}")
|
||||
await ws.send(json.dumps({
|
||||
"type": "file_chunk",
|
||||
"session_id": self._active_session or "",
|
||||
"transfer_id": tid,
|
||||
"done": True,
|
||||
"upload_complete": True,
|
||||
"path": str(dest),
|
||||
}))
|
||||
|
||||
elif msg_type == "ping":
|
||||
await ws.send(json.dumps({"type": "pong"}))
|
||||
|
||||
finally:
|
||||
self._streaming = False
|
||||
self._screen = None
|
||||
if stream_task and not stream_task.done():
|
||||
stream_task.cancel()
|
||||
if clipboard_task and not clipboard_task.done():
|
||||
clipboard_task.cancel()
|
||||
|
||||
def stop(self):
|
||||
self._stop_event.set()
|
||||
@@ -466,6 +806,7 @@ async def main():
|
||||
parser.add_argument("--relay", help="Relay WebSocket URL (e.g. ws://remotelink.example.com:8765)")
|
||||
parser.add_argument("--enroll", metavar="TOKEN", help="Enrollment token for first-time registration")
|
||||
parser.add_argument("--run-once", action="store_true", help="Exit after first session ends")
|
||||
parser.add_argument("--attended", action="store_true", help="Prompt local user to accept each incoming connection")
|
||||
parser.add_argument("--verbose", "-v", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -503,6 +844,7 @@ async def main():
|
||||
access_key = config["access_key"]
|
||||
|
||||
agent = Agent(server_url, machine_id, access_key, relay_url)
|
||||
agent._attended_mode = args.attended
|
||||
|
||||
# Handle Ctrl+C / SIGTERM gracefully
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
@@ -4,6 +4,7 @@ websockets==13.1
|
||||
mss==9.0.2
|
||||
Pillow==11.0.0
|
||||
pynput==1.7.7
|
||||
pyperclip==1.9.0
|
||||
|
||||
# Windows service support (Windows only)
|
||||
pywin32==308; sys_platform == "win32"
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from '@/components/ui/card'
|
||||
import {
|
||||
UserPlus, Copy, Check, Trash2, Clock, CheckCircle2,
|
||||
Loader2, KeyRound, Ban, Infinity, Hash,
|
||||
Loader2, KeyRound, Ban, Infinity, Hash, FolderOpen, Plus,
|
||||
} from 'lucide-react'
|
||||
|
||||
// ── Shared helper ─────────────────────────────────────────────────────────────
|
||||
@@ -421,23 +421,135 @@ function EnrollmentSection() {
|
||||
)
|
||||
}
|
||||
|
||||
// ── Groups ────────────────────────────────────────────────────────────────────
|
||||
|
||||
interface Group {
|
||||
id: string
|
||||
name: string
|
||||
description: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
function GroupsSection() {
|
||||
const [groups, setGroups] = useState<Group[]>([])
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
|
||||
const fetchGroups = useCallback(async () => {
|
||||
const res = await fetch('/api/groups')
|
||||
const data = await res.json()
|
||||
if (res.ok) setGroups(data.groups ?? [])
|
||||
setIsLoading(false)
|
||||
}, [])
|
||||
|
||||
useEffect(() => { fetchGroups() }, [fetchGroups])
|
||||
|
||||
const handleCreate = async (e: React.SyntheticEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
if (!name.trim()) return
|
||||
setIsCreating(true)
|
||||
await fetch('/api/groups', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, description }),
|
||||
})
|
||||
setName(''); setDescription('')
|
||||
await fetchGroups()
|
||||
setIsCreating(false)
|
||||
}
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await fetch('/api/groups', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id }),
|
||||
})
|
||||
await fetchGroups()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card className="border-border/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Create Group</CardTitle>
|
||||
<CardDescription>Groups let you organise machines and control which technicians have access to them.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleCreate} className="space-y-3">
|
||||
<div>
|
||||
<Label htmlFor="group-name">Name</Label>
|
||||
<Input id="group-name" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Client — Acme Corp" className="mt-1" />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="group-desc">Description (optional)</Label>
|
||||
<Input id="group-desc" value={description} onChange={e => setDescription(e.target.value)} placeholder="Optional description" className="mt-1" />
|
||||
</div>
|
||||
<Button type="submit" disabled={isCreating || !name.trim()}>
|
||||
{isCreating ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Plus className="mr-2 h-4 w-4" />}
|
||||
Create Group
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-border/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Groups</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground text-sm"><Loader2 className="h-4 w-4 animate-spin" /> Loading…</div>
|
||||
) : groups.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No groups yet. Create one above.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{groups.map(g => (
|
||||
<div key={g.id} className="flex items-center justify-between gap-4 p-3 rounded-lg border border-border/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<FolderOpen className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">{g.name}</p>
|
||||
{g.description && <p className="text-xs text-muted-foreground">{g.description}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive hover:bg-destructive/10" onClick={() => handleDelete(g.id)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Page ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
type Tab = 'invites' | 'enrollment'
|
||||
type Tab = 'invites' | 'enrollment' | 'groups'
|
||||
|
||||
export default function AdminPage() {
|
||||
const [tab, setTab] = useState<Tab>('invites')
|
||||
|
||||
const tabLabels: Record<Tab, string> = {
|
||||
invites: 'User invites',
|
||||
enrollment: 'Agent enrollment',
|
||||
groups: 'Groups',
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Admin</h2>
|
||||
<p className="text-muted-foreground">Manage users and agent deployment</p>
|
||||
<p className="text-muted-foreground">Manage users, agent deployment, and machine groups</p>
|
||||
</div>
|
||||
|
||||
{/* Tab bar */}
|
||||
<div className="flex gap-1 p-1 rounded-lg bg-muted/50 w-fit">
|
||||
{(['invites', 'enrollment'] as Tab[]).map((t) => (
|
||||
{(['invites', 'enrollment', 'groups'] as Tab[]).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => setTab(t)}
|
||||
@@ -447,12 +559,14 @@ export default function AdminPage() {
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{t === 'invites' ? 'User invites' : 'Agent enrollment'}
|
||||
{tabLabels[t]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === 'invites' ? <InvitesSection /> : <EnrollmentSection />}
|
||||
{tab === 'invites' && <InvitesSection />}
|
||||
{tab === 'enrollment' && <EnrollmentSection />}
|
||||
{tab === 'groups' && <GroupsSection />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,32 +1,63 @@
|
||||
import { auth } from '@/auth'
|
||||
import { db } from '@/lib/db'
|
||||
import { machines } from '@/lib/db/schema'
|
||||
import { eq, desc } from 'drizzle-orm'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { machines, groups } from '@/lib/db/schema'
|
||||
import { eq, desc, or, ilike, sql } from 'drizzle-orm'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import Link from 'next/link'
|
||||
import { Download, Laptop, Link2 } from 'lucide-react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { MachineActions } from '@/components/dashboard/machine-actions'
|
||||
import { Download, Laptop } from 'lucide-react'
|
||||
import { MachineCard } from '@/components/dashboard/machine-card'
|
||||
import { MachinesFilter } from '@/components/dashboard/machines-filter'
|
||||
|
||||
export default async function MachinesPage() {
|
||||
interface PageProps {
|
||||
searchParams: Promise<{ q?: string; tag?: string; group?: string }>
|
||||
}
|
||||
|
||||
export default async function MachinesPage({ searchParams }: PageProps) {
|
||||
const session = await auth()
|
||||
const machineList = await db
|
||||
const { q, tag, group } = await searchParams
|
||||
|
||||
// Build query conditions
|
||||
const conditions = [eq(machines.userId, session!.user.id)]
|
||||
if (group) conditions.push(eq(machines.groupId, group))
|
||||
|
||||
let machineList = await db
|
||||
.select()
|
||||
.from(machines)
|
||||
.where(eq(machines.userId, session!.user.id))
|
||||
.where(conditions.length === 1 ? conditions[0] : sql`${conditions.reduce((a, b) => sql`${a} AND ${b}`)}`)
|
||||
.orderBy(desc(machines.isOnline), desc(machines.lastSeen))
|
||||
|
||||
const onlineCount = machineList.filter((m) => m.isOnline).length
|
||||
// Text search (filter in JS — avoids complex SQL for small datasets)
|
||||
if (q) {
|
||||
const lower = q.toLowerCase()
|
||||
machineList = machineList.filter(m =>
|
||||
m.name.toLowerCase().includes(lower) ||
|
||||
(m.hostname ?? '').toLowerCase().includes(lower) ||
|
||||
(m.os ?? '').toLowerCase().includes(lower) ||
|
||||
(m.ipAddress ?? '').toLowerCase().includes(lower)
|
||||
)
|
||||
}
|
||||
|
||||
// Tag filter
|
||||
if (tag) {
|
||||
machineList = machineList.filter(m => m.tags?.includes(tag))
|
||||
}
|
||||
|
||||
// Collect all unique tags across machines
|
||||
const allTagsSet = new Set<string>()
|
||||
machineList.forEach(m => (m.tags ?? []).forEach(t => allTagsSet.add(t)))
|
||||
const allTags = [...allTagsSet].sort()
|
||||
|
||||
const onlineCount = machineList.filter(m => m.isOnline).length
|
||||
|
||||
// Fetch groups for group picker and machine card selects
|
||||
const groupList = await db.select({ id: groups.id, name: groups.name }).from(groups).orderBy(groups.name)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold">Machines</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{machineList.length} machine{machineList.length !== 1 ? 's' : ''} registered, {onlineCount} online
|
||||
</p>
|
||||
</div>
|
||||
<Button asChild>
|
||||
<Link href="/download">
|
||||
@@ -36,79 +67,42 @@ export default async function MachinesPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<MachinesFilter
|
||||
allTags={allTags}
|
||||
groups={groupList}
|
||||
currentSearch={q ?? ''}
|
||||
currentTag={tag ?? ''}
|
||||
currentGroup={group ?? ''}
|
||||
onlineCount={onlineCount}
|
||||
totalCount={machineList.length}
|
||||
/>
|
||||
|
||||
{machineList.length > 0 ? (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{machineList.map((machine) => (
|
||||
<Card key={machine.id} className="border-border/50">
|
||||
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`flex h-10 w-10 items-center justify-center rounded-lg ${machine.isOnline ? 'bg-green-500/10 text-green-500' : 'bg-muted text-muted-foreground'}`}>
|
||||
<Laptop className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-base">{machine.name}</CardTitle>
|
||||
<CardDescription className="text-xs">{machine.hostname || 'Unknown host'}</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
<MachineActions machine={machine} />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">Status</span>
|
||||
<span className={`flex items-center gap-1.5 ${machine.isOnline ? 'text-green-500' : 'text-muted-foreground'}`}>
|
||||
<span className={`h-2 w-2 rounded-full ${machine.isOnline ? 'bg-green-500' : 'bg-muted-foreground/30'}`} />
|
||||
{machine.isOnline ? 'Online' : 'Offline'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">OS</span>
|
||||
<span>{machine.os || 'Unknown'} {machine.osVersion || ''}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">Last seen</span>
|
||||
<span>
|
||||
{machine.lastSeen
|
||||
? formatDistanceToNow(new Date(machine.lastSeen), { addSuffix: true })
|
||||
: 'Never'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">Agent</span>
|
||||
<span className="font-mono text-xs">{machine.agentVersion || 'N/A'}</span>
|
||||
</div>
|
||||
<div className="pt-2">
|
||||
<Button className="w-full" size="sm" disabled={!machine.isOnline} asChild={machine.isOnline}>
|
||||
{machine.isOnline ? (
|
||||
<Link href={`/viewer/${machine.id}`}>
|
||||
<Link2 className="mr-2 h-4 w-4" />
|
||||
Connect
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
<Link2 className="mr-2 h-4 w-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<MachineCard key={machine.id} machine={machine} groups={groupList} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card className="border-border/50">
|
||||
<CardContent className="flex flex-col items-center justify-center py-16">
|
||||
<Laptop className="h-12 w-12 text-muted-foreground/30 mb-4" />
|
||||
<h3 className="text-lg font-semibold mb-2">No machines yet</h3>
|
||||
<h3 className="text-lg font-semibold mb-2">
|
||||
{q || tag || group ? 'No machines match your filter' : 'No machines yet'}
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-center mb-6 max-w-sm text-balance">
|
||||
Download and install the RemoteLink agent on the machines you want to control remotely.
|
||||
{q || tag || group
|
||||
? 'Try adjusting your search or filters.'
|
||||
: 'Download and install the RemoteLink agent on the machines you want to control remotely.'}
|
||||
</p>
|
||||
<Button asChild>
|
||||
<Link href="/download">
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download Agent
|
||||
</Link>
|
||||
</Button>
|
||||
{!(q || tag || group) && (
|
||||
<Button asChild>
|
||||
<Link href="/download">
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download Agent
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
@@ -3,9 +3,12 @@ import { machines, sessionCodes } from '@/lib/db/schema'
|
||||
import { eq, and, isNotNull, gt } from 'drizzle-orm'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
// Increment this when a new agent binary is published to /downloads/
|
||||
const CURRENT_AGENT_VERSION = '1.0.0'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { accessKey } = await request.json()
|
||||
const { accessKey, agentVersion } = await request.json()
|
||||
|
||||
if (!accessKey) {
|
||||
return NextResponse.json({ error: 'Access key required' }, { status: 400 })
|
||||
@@ -13,7 +16,7 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const result = await db
|
||||
.update(machines)
|
||||
.set({ isOnline: true, lastSeen: new Date() })
|
||||
.set({ isOnline: true, lastSeen: new Date(), agentVersion: agentVersion || undefined })
|
||||
.where(eq(machines.accessKey, accessKey))
|
||||
.returning({ id: machines.id })
|
||||
|
||||
@@ -38,11 +41,18 @@ export async function POST(request: NextRequest) {
|
||||
.orderBy(sessionCodes.usedAt)
|
||||
.limit(1)
|
||||
|
||||
const needsUpdate = agentVersion && agentVersion !== CURRENT_AGENT_VERSION
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || ''
|
||||
const downloadUrl = needsUpdate
|
||||
? `${appUrl}/downloads/remotelink-agent-${process.platform === 'win32' ? 'windows.exe' : 'linux'}`
|
||||
: null
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
pendingConnection: pending[0]
|
||||
? { sessionCodeId: pending[0].id, usedBy: pending[0].usedBy }
|
||||
: null,
|
||||
updateAvailable: needsUpdate ? { version: CURRENT_AGENT_VERSION, downloadUrl } : null,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[Heartbeat] Error:', error)
|
||||
|
||||
44
app/api/groups/route.ts
Normal file
44
app/api/groups/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { auth } from '@/auth'
|
||||
import { db } from '@/lib/db'
|
||||
import { groups } from '@/lib/db/schema'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
type AuthUser = { id: string; role?: string }
|
||||
|
||||
export async function GET() {
|
||||
const authSession = await auth()
|
||||
if (!authSession?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const list = await db.select().from(groups).orderBy(groups.name)
|
||||
return NextResponse.json({ groups: list })
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const authSession = await auth()
|
||||
if (!authSession?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
const u = authSession.user as AuthUser
|
||||
if (u.role !== 'admin') return NextResponse.json({ error: 'Admin only' }, { status: 403 })
|
||||
|
||||
const { name, description } = await request.json()
|
||||
if (!name?.trim()) return NextResponse.json({ error: 'Name required' }, { status: 400 })
|
||||
|
||||
const [group] = await db.insert(groups).values({
|
||||
name: String(name).slice(0, 100),
|
||||
description: description ? String(description).slice(0, 500) : null,
|
||||
createdBy: u.id,
|
||||
}).returning()
|
||||
|
||||
return NextResponse.json({ group })
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
const authSession = await auth()
|
||||
if (!authSession?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
const u = authSession.user as AuthUser
|
||||
if (u.role !== 'admin') return NextResponse.json({ error: 'Admin only' }, { status: 403 })
|
||||
|
||||
const { id } = await request.json()
|
||||
await db.delete(groups).where(eq(groups.id, id))
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -4,6 +4,40 @@ import { machines } from '@/lib/db/schema'
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const { id } = await params
|
||||
const body = await request.json()
|
||||
|
||||
const updates: Record<string, unknown> = {}
|
||||
if (body.name !== undefined) updates.name = String(body.name).slice(0, 255)
|
||||
if (body.notes !== undefined) updates.notes = body.notes ? String(body.notes) : null
|
||||
if (body.tags !== undefined) updates.tags = Array.isArray(body.tags) ? body.tags.map(String) : []
|
||||
if (body.groupId !== undefined) updates.groupId = body.groupId || null
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
return NextResponse.json({ error: 'Nothing to update' }, { status: 400 })
|
||||
}
|
||||
|
||||
const result = await db
|
||||
.update(machines)
|
||||
.set(updates)
|
||||
.where(and(eq(machines.id, id), eq(machines.userId, session.user.id)))
|
||||
.returning({ id: machines.id })
|
||||
|
||||
if (!result[0]) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
|
||||
60
app/api/machines/wol/route.ts
Normal file
60
app/api/machines/wol/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { auth } from '@/auth'
|
||||
import { db } from '@/lib/db'
|
||||
import { machines } from '@/lib/db/schema'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { createSocket } from 'dgram'
|
||||
|
||||
function buildMagicPacket(mac: string): Buffer {
|
||||
// Normalise: strip separators, expect 12 hex chars
|
||||
const hex = mac.replace(/[:\-]/g, '').toLowerCase()
|
||||
if (hex.length !== 12 || !/^[0-9a-f]+$/.test(hex)) {
|
||||
throw new Error('Invalid MAC address')
|
||||
}
|
||||
const macBytes = Buffer.from(hex, 'hex')
|
||||
// Magic packet: 6x 0xFF + 16x MAC
|
||||
const packet = Buffer.alloc(6 + 16 * 6)
|
||||
packet.fill(0xff, 0, 6)
|
||||
for (let i = 0; i < 16; i++) macBytes.copy(packet, 6 + i * 6)
|
||||
return packet
|
||||
}
|
||||
|
||||
async function sendMagicPacket(mac: string): Promise<void> {
|
||||
const packet = buildMagicPacket(mac)
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock = createSocket('udp4')
|
||||
sock.once('error', reject)
|
||||
sock.bind(() => {
|
||||
sock.setBroadcast(true)
|
||||
sock.send(packet, 0, packet.length, 9, '255.255.255.255', () => {
|
||||
sock.close()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { machineId } = await request.json()
|
||||
if (!machineId) return NextResponse.json({ error: 'machineId required' }, { status: 400 })
|
||||
|
||||
const result = await db
|
||||
.select({ macAddress: machines.macAddress, name: machines.name })
|
||||
.from(machines)
|
||||
.where(and(eq(machines.id, machineId), eq(machines.userId, session.user.id)))
|
||||
.limit(1)
|
||||
|
||||
const machine = result[0]
|
||||
if (!machine) return NextResponse.json({ error: 'Machine not found' }, { status: 404 })
|
||||
if (!machine.macAddress) return NextResponse.json({ error: 'No MAC address recorded for this machine. Agent must reconnect at least once.' }, { status: 422 })
|
||||
|
||||
try {
|
||||
await sendMagicPacket(machine.macAddress)
|
||||
return NextResponse.json({ success: true, message: `Magic packet sent to ${machine.macAddress}` })
|
||||
} catch (e) {
|
||||
return NextResponse.json({ error: String(e) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
import { useEffect, useState, useRef, useCallback } from 'react'
|
||||
import { useParams, useRouter, useSearchParams } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Maximize2, Minimize2, Monitor, Loader2, AlertCircle, WifiOff } from 'lucide-react'
|
||||
import { Monitor, Loader2, AlertCircle, WifiOff } from 'lucide-react'
|
||||
import { ViewerToolbar } from '@/components/viewer/toolbar'
|
||||
import { ConnectionStatus } from '@/components/viewer/connection-status'
|
||||
import { FileTransferPanel } from '@/components/viewer/file-transfer-panel'
|
||||
import { ChatPanel } from '@/components/viewer/chat-panel'
|
||||
|
||||
interface Session {
|
||||
id: string
|
||||
@@ -16,6 +18,13 @@ interface Session {
|
||||
connectionType: string | null
|
||||
}
|
||||
|
||||
interface MonitorInfo {
|
||||
index: number
|
||||
width: number
|
||||
height: number
|
||||
primary: boolean
|
||||
}
|
||||
|
||||
type ConnectionState = 'connecting' | 'waiting' | 'connected' | 'disconnected' | 'error'
|
||||
|
||||
export default function ViewerPage() {
|
||||
@@ -23,7 +32,6 @@ export default function ViewerPage() {
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const sessionId = params.sessionId as string
|
||||
// viewerToken is passed as a query param from the connect flow
|
||||
const viewerToken = searchParams.get('token')
|
||||
|
||||
const [session, setSession] = useState<Session | null>(null)
|
||||
@@ -31,46 +39,43 @@ export default function ViewerPage() {
|
||||
const [isFullscreen, setIsFullscreen] = useState(false)
|
||||
const [showToolbar, setShowToolbar] = useState(true)
|
||||
const [quality, setQuality] = useState<'high' | 'medium' | 'low'>('high')
|
||||
const [isMuted, setIsMuted] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [statusMsg, setStatusMsg] = useState('Connecting to relay…')
|
||||
const [fps, setFps] = useState(0)
|
||||
const [monitors, setMonitors] = useState<MonitorInfo[]>([])
|
||||
const [activeMonitor, setActiveMonitor] = useState(0)
|
||||
const [showFileTransfer, setShowFileTransfer] = useState(false)
|
||||
const [showChat, setShowChat] = useState(false)
|
||||
const [lastAgentMsg, setLastAgentMsg] = useState<Record<string, unknown> | null>(null)
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const wsRef = useRef<WebSocket | null>(null)
|
||||
const fpsCounterRef = useRef({ frames: 0, lastTime: Date.now() })
|
||||
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const connectionStateRef = useRef<ConnectionState>('connecting')
|
||||
|
||||
// Keep ref in sync so closures can read current value
|
||||
useEffect(() => { connectionStateRef.current = connectionState }, [connectionState])
|
||||
|
||||
// ── Load session info ──────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
fetch(`/api/sessions/${sessionId}`)
|
||||
.then((r) => r.json())
|
||||
.then((data) => {
|
||||
if (!data.session) {
|
||||
setError('Session not found')
|
||||
setConnectionState('error')
|
||||
return
|
||||
}
|
||||
if (data.session.endedAt) {
|
||||
setError('This session has ended')
|
||||
setConnectionState('disconnected')
|
||||
return
|
||||
}
|
||||
if (!data.session) { setError('Session not found'); setConnectionState('error'); return }
|
||||
if (data.session.endedAt) { setError('This session has ended'); setConnectionState('disconnected'); return }
|
||||
setSession(data.session)
|
||||
})
|
||||
.catch(() => {
|
||||
setError('Failed to load session')
|
||||
setConnectionState('error')
|
||||
})
|
||||
.catch(() => { setError('Failed to load session'); setConnectionState('error') })
|
||||
}, [sessionId])
|
||||
|
||||
// ── WebSocket connection ───────────────────────────────────────────────────
|
||||
const connectWS = useCallback(() => {
|
||||
if (!viewerToken) return
|
||||
if (reconnectTimerRef.current) { clearTimeout(reconnectTimerRef.current); reconnectTimerRef.current = null }
|
||||
|
||||
const relayHost = process.env.NEXT_PUBLIC_RELAY_URL ||
|
||||
`${window.location.hostname}:8765`
|
||||
const relayHost = process.env.NEXT_PUBLIC_RELAY_URL || `${window.location.hostname}:8765`
|
||||
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'
|
||||
const wsUrl = `${proto}://${relayHost}/ws/viewer?session_id=${sessionId}&viewer_token=${viewerToken}`
|
||||
|
||||
@@ -81,14 +86,10 @@ export default function ViewerPage() {
|
||||
ws.binaryType = 'arraybuffer'
|
||||
wsRef.current = ws
|
||||
|
||||
ws.onopen = () => {
|
||||
setStatusMsg('Waiting for agent…')
|
||||
setConnectionState('waiting')
|
||||
}
|
||||
ws.onopen = () => { setStatusMsg('Waiting for agent…'); setConnectionState('waiting') }
|
||||
|
||||
ws.onmessage = (evt) => {
|
||||
if (evt.data instanceof ArrayBuffer) {
|
||||
// Binary = JPEG frame
|
||||
renderFrame(evt.data)
|
||||
} else {
|
||||
try {
|
||||
@@ -100,22 +101,18 @@ export default function ViewerPage() {
|
||||
|
||||
ws.onclose = (evt) => {
|
||||
wsRef.current = null
|
||||
if (connectionState !== 'disconnected' && evt.code !== 4001) {
|
||||
if (connectionStateRef.current !== 'disconnected' && evt.code !== 4001) {
|
||||
setConnectionState('waiting')
|
||||
setStatusMsg('Connection lost — reconnecting…')
|
||||
reconnectTimerRef.current = setTimeout(connectWS, 3000)
|
||||
}
|
||||
}
|
||||
|
||||
ws.onerror = () => {
|
||||
setStatusMsg('Relay connection failed')
|
||||
}
|
||||
}, [sessionId, viewerToken])
|
||||
ws.onerror = () => { setStatusMsg('Relay connection failed') }
|
||||
}, [sessionId, viewerToken]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (session && viewerToken) {
|
||||
connectWS()
|
||||
}
|
||||
if (session && viewerToken) connectWS()
|
||||
return () => {
|
||||
wsRef.current?.close()
|
||||
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current)
|
||||
@@ -136,6 +133,18 @@ export default function ViewerPage() {
|
||||
setConnectionState('waiting')
|
||||
setStatusMsg('Agent disconnected — waiting for reconnect…')
|
||||
break
|
||||
case 'monitor_list':
|
||||
setMonitors((msg.monitors as MonitorInfo[]) ?? [])
|
||||
break
|
||||
case 'clipboard_content':
|
||||
// Write agent clipboard to browser clipboard
|
||||
navigator.clipboard.writeText(msg.content as string).catch(() => {})
|
||||
break
|
||||
case 'file_chunk':
|
||||
case 'file_list':
|
||||
case 'chat_message':
|
||||
setLastAgentMsg(msg)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +152,6 @@ export default function ViewerPage() {
|
||||
const renderFrame = useCallback((data: ArrayBuffer) => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
const blob = new Blob([data], { type: 'image/jpeg' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const img = new Image()
|
||||
@@ -156,8 +164,6 @@ export default function ViewerPage() {
|
||||
}
|
||||
ctx.drawImage(img, 0, 0)
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
// FPS counter
|
||||
const counter = fpsCounterRef.current
|
||||
counter.frames++
|
||||
const now = Date.now()
|
||||
@@ -195,12 +201,7 @@ export default function ViewerPage() {
|
||||
const handleMouseClick = useCallback((e: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
if (connectionState !== 'connected') return
|
||||
const { x, y } = getCanvasCoords(e)
|
||||
sendEvent({
|
||||
type: 'mouse_click',
|
||||
button: e.button === 2 ? 'right' : 'left',
|
||||
double: e.detail === 2,
|
||||
x, y,
|
||||
})
|
||||
sendEvent({ type: 'mouse_click', button: e.button === 2 ? 'right' : 'left', double: e.detail === 2, x, y })
|
||||
}, [connectionState, sendEvent, getCanvasCoords])
|
||||
|
||||
const handleMouseScroll = useCallback((e: React.WheelEvent<HTMLCanvasElement>) => {
|
||||
@@ -229,6 +230,30 @@ export default function ViewerPage() {
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
}, [handleKeyDown])
|
||||
|
||||
// ── Toolbar actions ────────────────────────────────────────────────────────
|
||||
const handleCtrlAltDel = useCallback(() => {
|
||||
sendEvent({ type: 'exec_key_combo', keys: ['ctrl_l', 'alt_l', 'delete'] })
|
||||
}, [sendEvent])
|
||||
|
||||
const handleClipboardPaste = useCallback(async () => {
|
||||
try {
|
||||
const text = await navigator.clipboard.readText()
|
||||
sendEvent({ type: 'clipboard_paste', content: text })
|
||||
} catch {
|
||||
// clipboard permission denied — ignore
|
||||
}
|
||||
}, [sendEvent])
|
||||
|
||||
const handleMonitorChange = useCallback((index: number) => {
|
||||
setActiveMonitor(index)
|
||||
sendEvent({ type: 'set_monitor', index })
|
||||
}, [sendEvent])
|
||||
|
||||
const handleQualityChange = useCallback((q: 'high' | 'medium' | 'low') => {
|
||||
setQuality(q)
|
||||
sendEvent({ type: 'set_quality', quality: q })
|
||||
}, [sendEvent])
|
||||
|
||||
// ── Fullscreen / toolbar auto-hide ─────────────────────────────────────────
|
||||
const toggleFullscreen = async () => {
|
||||
if (!containerRef.current) return
|
||||
@@ -245,8 +270,10 @@ export default function ViewerPage() {
|
||||
if (isFullscreen && connectionState === 'connected') {
|
||||
const timer = setTimeout(() => setShowToolbar(false), 3000)
|
||||
return () => clearTimeout(timer)
|
||||
} else {
|
||||
setShowToolbar(true)
|
||||
}
|
||||
}, [isFullscreen, connectionState, showToolbar])
|
||||
}, [isFullscreen, connectionState])
|
||||
|
||||
// ── End session ────────────────────────────────────────────────────────────
|
||||
const endSession = async () => {
|
||||
@@ -282,61 +309,91 @@ export default function ViewerPage() {
|
||||
className="min-h-svh bg-black flex flex-col"
|
||||
onMouseMove={() => isFullscreen && setShowToolbar(true)}
|
||||
>
|
||||
<div className={`transition-opacity duration-300 ${showToolbar ? 'opacity-100' : 'opacity-0'}`}>
|
||||
<div className={`transition-opacity duration-300 ${showToolbar ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
|
||||
<ViewerToolbar
|
||||
session={session}
|
||||
connectionState={connectionState}
|
||||
isFullscreen={isFullscreen}
|
||||
quality={quality}
|
||||
isMuted={isMuted}
|
||||
isMuted={true}
|
||||
monitors={monitors}
|
||||
activeMonitor={activeMonitor}
|
||||
onToggleFullscreen={toggleFullscreen}
|
||||
onQualityChange={(q) => {
|
||||
setQuality(q)
|
||||
sendEvent({ type: 'set_quality', quality: q })
|
||||
}}
|
||||
onToggleMute={() => setIsMuted(!isMuted)}
|
||||
onQualityChange={handleQualityChange}
|
||||
onToggleMute={() => {}}
|
||||
onDisconnect={endSession}
|
||||
onReconnect={connectWS}
|
||||
onCtrlAltDel={handleCtrlAltDel}
|
||||
onClipboardPaste={handleClipboardPaste}
|
||||
onMonitorChange={handleMonitorChange}
|
||||
onToggleFileTransfer={() => setShowFileTransfer(v => !v)}
|
||||
onToggleChat={() => setShowChat(v => !v)}
|
||||
onWakeOnLan={session?.machineId ? async () => {
|
||||
await fetch('/api/machines/wol', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ machineId: session.machineId }),
|
||||
})
|
||||
} : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex items-center justify-center relative">
|
||||
{(connectionState === 'connecting' || connectionState === 'waiting') && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/80 z-10">
|
||||
<div className="text-center space-y-4">
|
||||
{connectionState === 'waiting'
|
||||
? <WifiOff className="h-12 w-12 text-muted-foreground mx-auto" />
|
||||
: <Loader2 className="h-12 w-12 animate-spin text-primary mx-auto" />}
|
||||
<div>
|
||||
<p className="font-semibold">{statusMsg}</p>
|
||||
<p className="text-sm text-muted-foreground">{session?.machineName}</p>
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Main canvas area */}
|
||||
<div className="flex-1 flex items-center justify-center relative">
|
||||
{(connectionState === 'connecting' || connectionState === 'waiting') && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/80 z-10">
|
||||
<div className="text-center space-y-4">
|
||||
{connectionState === 'waiting'
|
||||
? <WifiOff className="h-12 w-12 text-muted-foreground mx-auto" />
|
||||
: <Loader2 className="h-12 w-12 animate-spin text-primary mx-auto" />}
|
||||
<div>
|
||||
<p className="font-semibold">{statusMsg}</p>
|
||||
<p className="text-sm text-muted-foreground">{session?.machineName}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="max-w-full max-h-full object-contain cursor-crosshair"
|
||||
style={{
|
||||
display: connectionState === 'connected' ? 'block' : 'none',
|
||||
imageRendering: quality === 'low' ? 'pixelated' : 'auto',
|
||||
}}
|
||||
onMouseMove={handleMouseMove}
|
||||
onClick={handleMouseClick}
|
||||
onWheel={handleMouseScroll}
|
||||
onContextMenu={(e) => { e.preventDefault(); handleMouseClick(e) }}
|
||||
/>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="max-w-full max-h-full object-contain cursor-crosshair"
|
||||
style={{
|
||||
display: connectionState === 'connected' ? 'block' : 'none',
|
||||
imageRendering: quality === 'low' ? 'pixelated' : 'auto',
|
||||
}}
|
||||
onMouseMove={handleMouseMove}
|
||||
onClick={handleMouseClick}
|
||||
onWheel={handleMouseScroll}
|
||||
onContextMenu={(e) => { e.preventDefault(); handleMouseClick(e) }}
|
||||
/>
|
||||
|
||||
{connectionState === 'disconnected' && (
|
||||
<div className="text-center space-y-4">
|
||||
<Monitor className="h-16 w-16 text-muted-foreground mx-auto" />
|
||||
<div>
|
||||
<p className="font-semibold">Session Ended</p>
|
||||
<p className="text-sm text-muted-foreground">The remote connection has been closed</p>
|
||||
{connectionState === 'disconnected' && (
|
||||
<div className="text-center space-y-4">
|
||||
<Monitor className="h-16 w-16 text-muted-foreground mx-auto" />
|
||||
<div>
|
||||
<p className="font-semibold">Session Ended</p>
|
||||
<p className="text-sm text-muted-foreground">The remote connection has been closed</p>
|
||||
</div>
|
||||
<Button onClick={() => router.push('/dashboard')}>Return to Dashboard</Button>
|
||||
</div>
|
||||
<Button onClick={() => router.push('/dashboard')}>Return to Dashboard</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sidebars */}
|
||||
{showFileTransfer && connectionState === 'connected' && (
|
||||
<FileTransferPanel
|
||||
onClose={() => setShowFileTransfer(false)}
|
||||
sendEvent={sendEvent}
|
||||
incomingMessage={lastAgentMsg}
|
||||
/>
|
||||
)}
|
||||
{showChat && connectionState === 'connected' && (
|
||||
<ChatPanel
|
||||
onClose={() => setShowChat(false)}
|
||||
sendEvent={sendEvent}
|
||||
incomingMessage={lastAgentMsg}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
2
auth.ts
2
auth.ts
@@ -42,7 +42,7 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
callbacks: {
|
||||
jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.id = user.id
|
||||
token.id = user.id ?? ''
|
||||
token.role = (user as { role: string }).role
|
||||
}
|
||||
return token
|
||||
|
||||
280
components/dashboard/machine-card.tsx
Normal file
280
components/dashboard/machine-card.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import {
|
||||
Laptop,
|
||||
Link2,
|
||||
MoreHorizontal,
|
||||
Trash2,
|
||||
Edit3,
|
||||
Check,
|
||||
X,
|
||||
Tag,
|
||||
StickyNote,
|
||||
} from 'lucide-react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import Link from 'next/link'
|
||||
|
||||
interface Group {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface Machine {
|
||||
id: string
|
||||
name: string
|
||||
hostname: string | null
|
||||
os: string | null
|
||||
osVersion: string | null
|
||||
agentVersion: string | null
|
||||
lastSeen: Date | null
|
||||
isOnline: boolean
|
||||
tags: string[] | null
|
||||
notes: string | null
|
||||
groupId: string | null
|
||||
}
|
||||
|
||||
interface MachineCardProps {
|
||||
machine: Machine
|
||||
groups: Group[]
|
||||
}
|
||||
|
||||
const TAG_COLORS: Record<string, string> = {
|
||||
server: 'bg-blue-500/10 text-blue-500 border-blue-500/20',
|
||||
windows: 'bg-cyan-500/10 text-cyan-500 border-cyan-500/20',
|
||||
linux: 'bg-orange-500/10 text-orange-500 border-orange-500/20',
|
||||
mac: 'bg-gray-500/10 text-gray-400 border-gray-500/20',
|
||||
workstation: 'bg-purple-500/10 text-purple-500 border-purple-500/20',
|
||||
laptop: 'bg-green-500/10 text-green-500 border-green-500/20',
|
||||
}
|
||||
|
||||
function tagColor(tag: string) {
|
||||
return TAG_COLORS[tag.toLowerCase()] || 'bg-muted text-muted-foreground border-border/50'
|
||||
}
|
||||
|
||||
export function MachineCard({ machine, groups }: MachineCardProps) {
|
||||
const router = useRouter()
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [name, setName] = useState(machine.name)
|
||||
const [notes, setNotes] = useState(machine.notes ?? '')
|
||||
const [tagInput, setTagInput] = useState('')
|
||||
const [tags, setTags] = useState<string[]>(machine.tags ?? [])
|
||||
const [groupId, setGroupId] = useState(machine.groupId ?? '')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [showNotes, setShowNotes] = useState(false)
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
await fetch(`/api/machines/${machine.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, notes: notes || null, tags, groupId: groupId || null }),
|
||||
})
|
||||
setSaving(false)
|
||||
setEditing(false)
|
||||
router.refresh()
|
||||
}
|
||||
|
||||
const cancel = () => {
|
||||
setName(machine.name)
|
||||
setNotes(machine.notes ?? '')
|
||||
setTags(machine.tags ?? [])
|
||||
setGroupId(machine.groupId ?? '')
|
||||
setEditing(false)
|
||||
}
|
||||
|
||||
const addTag = () => {
|
||||
const t = tagInput.trim().toLowerCase().replace(/\s+/g, '-')
|
||||
if (t && !tags.includes(t)) setTags([...tags, t])
|
||||
setTagInput('')
|
||||
}
|
||||
|
||||
const removeTag = (t: string) => setTags(tags.filter(x => x !== t))
|
||||
|
||||
const deleteMachine = async () => {
|
||||
if (!confirm(`Delete "${machine.name}"? This cannot be undone.`)) return
|
||||
await fetch(`/api/machines/${machine.id}`, { method: 'DELETE' })
|
||||
router.refresh()
|
||||
}
|
||||
|
||||
const currentGroup = groups.find(g => g.id === (groupId || machine.groupId))
|
||||
|
||||
return (
|
||||
<Card className="border-border/50">
|
||||
<CardHeader className="flex flex-row items-start justify-between space-y-0 pb-2">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className={`flex h-10 w-10 items-center justify-center rounded-lg shrink-0 ${machine.isOnline ? 'bg-green-500/10 text-green-500' : 'bg-muted text-muted-foreground'}`}>
|
||||
<Laptop className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
{editing ? (
|
||||
<Input
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
className="h-7 text-sm font-semibold"
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm font-semibold truncate">{machine.name}</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground truncate">{machine.hostname || 'Unknown host'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditing(true)}>
|
||||
<Edit3 className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShowNotes(v => !v)}>
|
||||
<StickyNote className="mr-2 h-4 w-4" />
|
||||
{showNotes ? 'Hide notes' : 'Show notes'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={deleteMachine} className="text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3">
|
||||
{/* Tags */}
|
||||
<div className="flex flex-wrap gap-1 min-h-5">
|
||||
{tags.map(t => (
|
||||
<Badge
|
||||
key={t}
|
||||
variant="outline"
|
||||
className={`text-xs py-0 h-5 ${tagColor(t)}`}
|
||||
>
|
||||
{t}
|
||||
{editing && (
|
||||
<button onClick={() => removeTag(t)} className="ml-1 hover:text-destructive">
|
||||
<X className="h-2.5 w-2.5" />
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
{editing && (
|
||||
<div className="flex gap-1">
|
||||
<Input
|
||||
value={tagInput}
|
||||
onChange={e => setTagInput(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addTag() } }}
|
||||
placeholder="Add tag…"
|
||||
className="h-5 text-xs py-0 px-1.5 w-20"
|
||||
/>
|
||||
<Button size="sm" variant="ghost" className="h-5 px-1" onClick={addTag}>
|
||||
<Tag className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Group */}
|
||||
{editing ? (
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Group</label>
|
||||
<select
|
||||
value={groupId}
|
||||
onChange={e => setGroupId(e.target.value)}
|
||||
className="mt-0.5 w-full text-xs rounded border border-border bg-background px-2 py-1"
|
||||
>
|
||||
<option value="">No group</option>
|
||||
{groups.map(g => (
|
||||
<option key={g.id} value={g.id}>{g.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : currentGroup ? (
|
||||
<p className="text-xs text-muted-foreground">Group: {currentGroup.name}</p>
|
||||
) : null}
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 gap-1 text-xs">
|
||||
<div className="text-muted-foreground">Status</div>
|
||||
<div className={`flex items-center gap-1.5 ${machine.isOnline ? 'text-green-500' : 'text-muted-foreground'}`}>
|
||||
<span className={`h-1.5 w-1.5 rounded-full ${machine.isOnline ? 'bg-green-500' : 'bg-muted-foreground/30'}`} />
|
||||
{machine.isOnline ? 'Online' : 'Offline'}
|
||||
</div>
|
||||
<div className="text-muted-foreground">OS</div>
|
||||
<div className="truncate">{machine.os || 'Unknown'} {machine.osVersion || ''}</div>
|
||||
<div className="text-muted-foreground">Last seen</div>
|
||||
<div className="truncate">
|
||||
{machine.lastSeen ? formatDistanceToNow(new Date(machine.lastSeen), { addSuffix: true }) : 'Never'}
|
||||
</div>
|
||||
<div className="text-muted-foreground">Agent</div>
|
||||
<div className="font-mono">{machine.agentVersion || 'N/A'}</div>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
{(showNotes || editing) && (
|
||||
<div>
|
||||
{editing ? (
|
||||
<Textarea
|
||||
value={notes}
|
||||
onChange={e => setNotes(e.target.value)}
|
||||
placeholder="Add notes about this machine…"
|
||||
className="text-xs min-h-16 resize-none"
|
||||
/>
|
||||
) : notes ? (
|
||||
<p className="text-xs text-muted-foreground bg-muted/30 rounded p-2">{notes}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground italic">No notes</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit controls */}
|
||||
{editing && (
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" className="flex-1 h-7 text-xs" onClick={save} disabled={saving}>
|
||||
<Check className="mr-1 h-3 w-3" />
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" className="h-7 text-xs" onClick={cancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Connect */}
|
||||
{!editing && (
|
||||
<Button className="w-full" size="sm" disabled={!machine.isOnline} asChild={machine.isOnline}>
|
||||
{machine.isOnline ? (
|
||||
<Link href={`/dashboard/connect?machineId=${machine.id}`}>
|
||||
<Link2 className="mr-2 h-4 w-4" />
|
||||
Connect
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
<Link2 className="mr-2 h-4 w-4" />
|
||||
Connect
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
108
components/dashboard/machines-filter.tsx
Normal file
108
components/dashboard/machines-filter.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
'use client'
|
||||
|
||||
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Search, X } from 'lucide-react'
|
||||
import { useTransition } from 'react'
|
||||
|
||||
interface Group {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface MachinesFilterProps {
|
||||
allTags: string[]
|
||||
groups: Group[]
|
||||
currentSearch: string
|
||||
currentTag: string
|
||||
currentGroup: string
|
||||
onlineCount: number
|
||||
totalCount: number
|
||||
}
|
||||
|
||||
export function MachinesFilter({
|
||||
allTags,
|
||||
groups,
|
||||
currentSearch,
|
||||
currentTag,
|
||||
currentGroup,
|
||||
onlineCount,
|
||||
totalCount,
|
||||
}: MachinesFilterProps) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
const [, startTransition] = useTransition()
|
||||
|
||||
const update = (key: string, value: string) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (value) params.set(key, value)
|
||||
else params.delete(key)
|
||||
startTransition(() => router.push(`${pathname}?${params.toString()}`))
|
||||
}
|
||||
|
||||
const clearAll = () => {
|
||||
startTransition(() => router.push(pathname))
|
||||
}
|
||||
|
||||
const hasFilters = currentSearch || currentTag || currentGroup
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search machines…"
|
||||
defaultValue={currentSearch}
|
||||
onChange={e => update('q', e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{groups.length > 0 && (
|
||||
<select
|
||||
value={currentGroup}
|
||||
onChange={e => update('group', e.target.value)}
|
||||
className="rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">All groups</option>
|
||||
{groups.map(g => (
|
||||
<option key={g.id} value={g.id}>{g.name}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground whitespace-nowrap">
|
||||
<span className="text-green-500 font-medium">{onlineCount} online</span>
|
||||
<span>/ {totalCount} total</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tag filter pills */}
|
||||
{allTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 items-center">
|
||||
<span className="text-xs text-muted-foreground">Filter:</span>
|
||||
{allTags.map(tag => (
|
||||
<Badge
|
||||
key={tag}
|
||||
variant={currentTag === tag ? 'default' : 'outline'}
|
||||
className="cursor-pointer text-xs h-5 py-0"
|
||||
onClick={() => update('tag', currentTag === tag ? '' : tag)}
|
||||
>
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
{hasFilters && (
|
||||
<Button variant="ghost" size="sm" className="h-5 px-1.5 text-xs" onClick={clearAll}>
|
||||
<X className="h-3 w-3 mr-1" />
|
||||
Clear
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
105
components/viewer/chat-panel.tsx
Normal file
105
components/viewer/chat-panel.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { X, Send } from 'lucide-react'
|
||||
|
||||
interface ChatMessage {
|
||||
id: string
|
||||
from: 'technician' | 'agent'
|
||||
text: string
|
||||
timestamp: Date
|
||||
}
|
||||
|
||||
interface ChatPanelProps {
|
||||
onClose: () => void
|
||||
sendEvent: (event: Record<string, unknown>) => void
|
||||
incomingMessage: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function ChatPanel({ onClose, sendEvent, incomingMessage }: ChatPanelProps) {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([])
|
||||
const [input, setInput] = useState('')
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!incomingMessage) return
|
||||
if (incomingMessage.type === 'chat_message') {
|
||||
setMessages(prev => [...prev, {
|
||||
id: crypto.randomUUID(),
|
||||
from: 'agent',
|
||||
text: incomingMessage.text as string,
|
||||
timestamp: new Date(),
|
||||
}])
|
||||
}
|
||||
}, [incomingMessage])
|
||||
|
||||
useEffect(() => {
|
||||
// Auto-scroll to bottom on new messages
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
|
||||
}
|
||||
}, [messages])
|
||||
|
||||
const send = () => {
|
||||
const text = input.trim()
|
||||
if (!text) return
|
||||
sendEvent({ type: 'chat_message', text })
|
||||
setMessages(prev => [...prev, {
|
||||
id: crypto.randomUUID(),
|
||||
from: 'technician',
|
||||
text,
|
||||
timestamp: new Date(),
|
||||
}])
|
||||
setInput('')
|
||||
}
|
||||
|
||||
const fmt = (d: Date) =>
|
||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
|
||||
return (
|
||||
<div className="w-72 border-l border-border/50 bg-card flex flex-col h-full">
|
||||
<div className="flex items-center justify-between p-3 border-b border-border/50">
|
||||
<span className="text-sm font-medium">Session Chat</span>
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={onClose}>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div ref={scrollRef} className="flex-1 overflow-y-auto p-3 space-y-3">
|
||||
{messages.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground text-center pt-8">
|
||||
Messages sent here are forwarded to the remote machine.
|
||||
</p>
|
||||
)}
|
||||
{messages.map((m) => (
|
||||
<div key={m.id} className={`flex flex-col gap-0.5 ${m.from === 'technician' ? 'items-end' : 'items-start'}`}>
|
||||
<div className={`max-w-[85%] rounded-lg px-3 py-1.5 text-xs ${
|
||||
m.from === 'technician'
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'bg-muted text-foreground'
|
||||
}`}>
|
||||
{m.text}
|
||||
</div>
|
||||
<span className="text-[10px] text-muted-foreground">{fmt(m.timestamp)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="p-2 border-t border-border/50 flex gap-1.5">
|
||||
<Input
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') send() }}
|
||||
placeholder="Type a message…"
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
<Button size="icon" className="h-8 w-8 shrink-0" onClick={send} disabled={!input.trim()}>
|
||||
<Send className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
296
components/viewer/file-transfer-panel.tsx
Normal file
296
components/viewer/file-transfer-panel.tsx
Normal file
@@ -0,0 +1,296 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, useCallback, useEffect } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import {
|
||||
Folder,
|
||||
File,
|
||||
Upload,
|
||||
Download,
|
||||
ChevronRight,
|
||||
ArrowLeft,
|
||||
X,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Loader2,
|
||||
} from 'lucide-react'
|
||||
|
||||
interface FileEntry {
|
||||
name: string
|
||||
is_dir: boolean
|
||||
size: number
|
||||
path: string
|
||||
}
|
||||
|
||||
interface TransferItem {
|
||||
id: string
|
||||
name: string
|
||||
direction: 'upload' | 'download'
|
||||
status: 'pending' | 'transferring' | 'done' | 'error'
|
||||
progress: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface FileTransferPanelProps {
|
||||
onClose: () => void
|
||||
sendEvent: (event: Record<string, unknown>) => void
|
||||
incomingMessage: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function FileTransferPanel({ onClose, sendEvent, incomingMessage }: FileTransferPanelProps) {
|
||||
const [remotePath, setRemotePath] = useState('~')
|
||||
const [remoteEntries, setRemoteEntries] = useState<FileEntry[]>([])
|
||||
const [remoteParent, setRemoteParent] = useState<string | null>(null)
|
||||
const [transfers, setTransfers] = useState<TransferItem[]>([])
|
||||
const [isDragOver, setIsDragOver] = useState(false)
|
||||
const [isLoadingDir, setIsLoadingDir] = useState(false)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
// Download accumulation: transfer_id → {chunks: string[], filename: string, size: number}
|
||||
const downloadBuffers = useRef<Record<string, {chunks: string[], filename: string, size: number}>>({})
|
||||
|
||||
const browseRemote = useCallback((path: string) => {
|
||||
setIsLoadingDir(true)
|
||||
sendEvent({ type: 'list_files', path })
|
||||
}, [sendEvent])
|
||||
|
||||
useEffect(() => {
|
||||
browseRemote('~')
|
||||
}, [browseRemote])
|
||||
|
||||
// Handle incoming relay messages
|
||||
useEffect(() => {
|
||||
if (!incomingMessage) return
|
||||
const msg = incomingMessage
|
||||
|
||||
if (msg.type === 'file_list') {
|
||||
setIsLoadingDir(false)
|
||||
setRemotePath(msg.path as string)
|
||||
setRemoteParent((msg.parent as string) ?? null)
|
||||
setRemoteEntries((msg.entries as FileEntry[]) ?? [])
|
||||
}
|
||||
|
||||
if (msg.type === 'file_chunk') {
|
||||
const tid = msg.transfer_id as string || ''
|
||||
const done = msg.done as boolean
|
||||
|
||||
if (msg.upload_complete) {
|
||||
setTransfers(prev => prev.map(t =>
|
||||
t.id === tid ? { ...t, status: 'done', progress: 100 } : t
|
||||
))
|
||||
return
|
||||
}
|
||||
|
||||
if (msg.error) {
|
||||
setTransfers(prev => prev.map(t =>
|
||||
t.id === tid ? { ...t, status: 'error', error: msg.error as string } : t
|
||||
))
|
||||
return
|
||||
}
|
||||
|
||||
// Download chunks
|
||||
const filename = msg.filename as string || 'download'
|
||||
const totalSize = msg.size as number || 0
|
||||
const chunk = msg.chunk as string || ''
|
||||
|
||||
if (!downloadBuffers.current[tid]) {
|
||||
downloadBuffers.current[tid] = { chunks: [], filename, size: totalSize }
|
||||
}
|
||||
if (chunk) {
|
||||
downloadBuffers.current[tid].chunks.push(chunk)
|
||||
const received = downloadBuffers.current[tid].chunks.reduce((sum, c) => sum + c.length * 0.75, 0)
|
||||
const progress = totalSize > 0 ? Math.min(99, Math.round((received / totalSize) * 100)) : 50
|
||||
setTransfers(prev => prev.map(t =>
|
||||
t.id === tid ? { ...t, status: 'transferring', progress } : t
|
||||
))
|
||||
}
|
||||
|
||||
if (done) {
|
||||
const buf = downloadBuffers.current[tid]
|
||||
if (buf) {
|
||||
delete downloadBuffers.current[tid]
|
||||
// Decode base64 chunks and create blob
|
||||
const binaryChunks = buf.chunks.map(c => {
|
||||
const binary = atob(c)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
|
||||
return bytes
|
||||
})
|
||||
const blob = new Blob(binaryChunks)
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = buf.filename
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
setTransfers(prev => prev.map(t =>
|
||||
t.id === tid ? { ...t, status: 'done', progress: 100 } : t
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [incomingMessage])
|
||||
|
||||
const uploadFiles = useCallback(async (files: FileList | File[]) => {
|
||||
const fileArr = Array.from(files)
|
||||
for (const file of fileArr) {
|
||||
const tid = crypto.randomUUID()
|
||||
setTransfers(prev => [{ id: tid, name: file.name, direction: 'upload', status: 'pending', progress: 0 }, ...prev])
|
||||
|
||||
const destPath = remotePath === '~' ? '~/Downloads' : remotePath
|
||||
sendEvent({ type: 'file_upload_start', transfer_id: tid, filename: file.name, dest_path: destPath })
|
||||
|
||||
const CHUNK = 65536
|
||||
const reader = file.stream().getReader()
|
||||
let seq = 0
|
||||
let sent = 0
|
||||
const total = file.size
|
||||
|
||||
const pump = async () => {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
// Convert to base64
|
||||
const b64 = btoa(String.fromCharCode(...value))
|
||||
sendEvent({ type: 'file_upload_chunk', transfer_id: tid, seq: seq++, chunk: b64 })
|
||||
sent += value.length
|
||||
const progress = Math.min(99, Math.round((sent / total) * 100))
|
||||
setTransfers(prev => prev.map(t => t.id === tid ? { ...t, status: 'transferring', progress } : t))
|
||||
}
|
||||
}
|
||||
await pump()
|
||||
sendEvent({ type: 'file_upload_end', transfer_id: tid })
|
||||
}
|
||||
}, [sendEvent, remotePath])
|
||||
|
||||
const downloadFile = useCallback((entry: FileEntry) => {
|
||||
const tid = crypto.randomUUID()
|
||||
setTransfers(prev => [{ id: tid, name: entry.name, direction: 'download', status: 'pending', progress: 0 }, ...prev])
|
||||
downloadBuffers.current[tid] = { chunks: [], filename: entry.name, size: entry.size }
|
||||
sendEvent({ type: 'file_download', path: entry.path, transfer_id: tid })
|
||||
}, [sendEvent])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragOver(false)
|
||||
if (e.dataTransfer.files.length > 0) uploadFiles(e.dataTransfer.files)
|
||||
}, [uploadFiles])
|
||||
|
||||
const formatSize = (bytes: number) => {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1048576).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-80 border-l border-border/50 bg-card flex flex-col h-full">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-3 border-b border-border/50">
|
||||
<span className="text-sm font-medium">File Transfer</span>
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={onClose}>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Remote file browser */}
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<div className="p-2 border-b border-border/50">
|
||||
<div className="flex items-center gap-1 mb-1.5">
|
||||
{remoteParent && (
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => browseRemote(remoteParent)}>
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground truncate flex-1 font-mono">{remotePath}</span>
|
||||
{isLoadingDir && <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground shrink-0" />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-1">
|
||||
{remoteEntries.map((entry) => (
|
||||
<div
|
||||
key={entry.path}
|
||||
className="flex items-center gap-2 px-2 py-1 rounded hover:bg-muted/50 cursor-pointer group"
|
||||
onClick={() => entry.is_dir ? browseRemote(entry.path) : undefined}
|
||||
>
|
||||
{entry.is_dir
|
||||
? <Folder className="h-4 w-4 text-blue-400 shrink-0" />
|
||||
: <File className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
}
|
||||
<span className="text-xs truncate flex-1">{entry.name}</span>
|
||||
{!entry.is_dir && (
|
||||
<>
|
||||
<span className="text-xs text-muted-foreground shrink-0">{formatSize(entry.size)}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5 opacity-0 group-hover:opacity-100 shrink-0"
|
||||
onClick={(e) => { e.stopPropagation(); downloadFile(entry) }}
|
||||
title="Download"
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{entry.is_dir && <ChevronRight className="h-3.5 w-3.5 text-muted-foreground shrink-0" />}
|
||||
</div>
|
||||
))}
|
||||
{remoteEntries.length === 0 && !isLoadingDir && (
|
||||
<p className="text-xs text-muted-foreground text-center py-4">Empty directory</p>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Upload drop zone */}
|
||||
<div
|
||||
className={`m-2 border-2 border-dashed rounded-lg p-3 text-center transition-colors cursor-pointer ${
|
||||
isDragOver ? 'border-primary bg-primary/5' : 'border-border/50 hover:border-border'
|
||||
}`}
|
||||
onDragOver={(e) => { e.preventDefault(); setIsDragOver(true) }}
|
||||
onDragLeave={() => setIsDragOver(false)}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="h-4 w-4 mx-auto mb-1 text-muted-foreground" />
|
||||
<p className="text-xs text-muted-foreground">Drop files to upload</p>
|
||||
<p className="text-xs text-muted-foreground">or click to browse</p>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => e.target.files && uploadFiles(e.target.files)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transfer queue */}
|
||||
{transfers.length > 0 && (
|
||||
<div className="border-t border-border/50">
|
||||
<div className="p-2">
|
||||
<p className="text-xs font-medium text-muted-foreground mb-1">Transfers</p>
|
||||
<div className="space-y-1 max-h-36 overflow-y-auto">
|
||||
{transfers.map((t) => (
|
||||
<div key={t.id} className="flex items-center gap-2 text-xs">
|
||||
{t.direction === 'upload'
|
||||
? <Upload className="h-3 w-3 text-muted-foreground shrink-0" />
|
||||
: <Download className="h-3 w-3 text-muted-foreground shrink-0" />
|
||||
}
|
||||
<span className="truncate flex-1">{t.name}</span>
|
||||
{t.status === 'done' && <CheckCircle2 className="h-3 w-3 text-green-500 shrink-0" />}
|
||||
{t.status === 'error' && <AlertCircle className="h-3 w-3 text-destructive shrink-0" />}
|
||||
{t.status === 'transferring' && (
|
||||
<span className="shrink-0 text-muted-foreground">{t.progress}%</span>
|
||||
)}
|
||||
{t.status === 'pending' && <Loader2 className="h-3 w-3 animate-spin shrink-0" />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -13,28 +13,37 @@ import {
|
||||
Maximize2,
|
||||
Minimize2,
|
||||
Monitor,
|
||||
Volume2,
|
||||
VolumeX,
|
||||
Settings,
|
||||
X,
|
||||
RefreshCw,
|
||||
Signal,
|
||||
SignalLow,
|
||||
SignalMedium,
|
||||
Keyboard,
|
||||
MousePointer2,
|
||||
Loader2,
|
||||
CheckCircle2
|
||||
CheckCircle2,
|
||||
RefreshCw,
|
||||
X,
|
||||
Clipboard,
|
||||
FolderOpen,
|
||||
ChevronDown,
|
||||
MessageSquare,
|
||||
Zap,
|
||||
} from 'lucide-react'
|
||||
|
||||
interface MonitorInfo {
|
||||
index: number
|
||||
width: number
|
||||
height: number
|
||||
primary: boolean
|
||||
}
|
||||
|
||||
interface Session {
|
||||
id: string
|
||||
machine_id: string | null
|
||||
machine_name: string | null
|
||||
started_at: string
|
||||
machineId: string | null
|
||||
machineName: string | null
|
||||
startedAt: string
|
||||
}
|
||||
|
||||
type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'
|
||||
type ConnectionState = 'connecting' | 'waiting' | 'connected' | 'disconnected' | 'error'
|
||||
|
||||
interface ViewerToolbarProps {
|
||||
session: Session | null
|
||||
@@ -42,11 +51,20 @@ interface ViewerToolbarProps {
|
||||
isFullscreen: boolean
|
||||
quality: 'high' | 'medium' | 'low'
|
||||
isMuted: boolean
|
||||
monitors: MonitorInfo[]
|
||||
activeMonitor: number
|
||||
onToggleFullscreen: () => void
|
||||
onQualityChange: (quality: 'high' | 'medium' | 'low') => void
|
||||
onToggleMute: () => void
|
||||
onDisconnect: () => void
|
||||
onReconnect: () => void
|
||||
onCtrlAltDel: () => void
|
||||
onClipboardPaste: () => void
|
||||
onMonitorChange: (index: number) => void
|
||||
onToggleFileTransfer: () => void
|
||||
onToggleChat: () => void
|
||||
onWakeOnLan?: () => void
|
||||
machineName?: string
|
||||
}
|
||||
|
||||
export function ViewerToolbar({
|
||||
@@ -54,13 +72,21 @@ export function ViewerToolbar({
|
||||
connectionState,
|
||||
isFullscreen,
|
||||
quality,
|
||||
isMuted,
|
||||
monitors,
|
||||
activeMonitor,
|
||||
onToggleFullscreen,
|
||||
onQualityChange,
|
||||
onToggleMute,
|
||||
onDisconnect,
|
||||
onReconnect,
|
||||
onCtrlAltDel,
|
||||
onClipboardPaste,
|
||||
onMonitorChange,
|
||||
onToggleFileTransfer,
|
||||
onToggleChat,
|
||||
onWakeOnLan,
|
||||
}: ViewerToolbarProps) {
|
||||
const connected = connectionState === 'connected'
|
||||
|
||||
const getQualityIcon = () => {
|
||||
switch (quality) {
|
||||
case 'high': return Signal
|
||||
@@ -73,28 +99,35 @@ export function ViewerToolbar({
|
||||
switch (connectionState) {
|
||||
case 'connecting':
|
||||
return (
|
||||
<span className="flex items-center gap-2 text-yellow-500">
|
||||
<span className="flex items-center gap-1.5 text-yellow-500 text-xs">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
Connecting
|
||||
</span>
|
||||
)
|
||||
case 'waiting':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-yellow-500 text-xs">
|
||||
<span className="h-2 w-2 rounded-full bg-yellow-500 animate-pulse" />
|
||||
Waiting for agent
|
||||
</span>
|
||||
)
|
||||
case 'connected':
|
||||
return (
|
||||
<span className="flex items-center gap-2 text-green-500">
|
||||
<span className="flex items-center gap-1.5 text-green-500 text-xs">
|
||||
<span className="h-2 w-2 rounded-full bg-green-500" />
|
||||
Connected
|
||||
</span>
|
||||
)
|
||||
case 'disconnected':
|
||||
return (
|
||||
<span className="flex items-center gap-2 text-muted-foreground">
|
||||
<span className="flex items-center gap-1.5 text-muted-foreground text-xs">
|
||||
<span className="h-2 w-2 rounded-full bg-muted-foreground" />
|
||||
Disconnected
|
||||
</span>
|
||||
)
|
||||
case 'error':
|
||||
return (
|
||||
<span className="flex items-center gap-2 text-destructive">
|
||||
<span className="flex items-center gap-1.5 text-destructive text-xs">
|
||||
<span className="h-2 w-2 rounded-full bg-destructive" />
|
||||
Error
|
||||
</span>
|
||||
@@ -105,32 +138,108 @@ export function ViewerToolbar({
|
||||
const QualityIcon = getQualityIcon()
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between h-12 px-4 bg-card/95 backdrop-blur border-b border-border/50">
|
||||
{/* Left section */}
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Monitor className="h-4 w-4 text-primary" />
|
||||
<span className="font-medium text-sm">
|
||||
{session?.machine_name || 'Remote Machine'}
|
||||
<div className="flex items-center justify-between h-12 px-4 bg-card/95 backdrop-blur border-b border-border/50 gap-2">
|
||||
{/* Left: machine name + status */}
|
||||
<div className="flex items-center gap-4 min-w-0">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Monitor className="h-4 w-4 text-primary shrink-0" />
|
||||
<span className="font-medium text-sm truncate">
|
||||
{session?.machineName || 'Remote Machine'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
{getConnectionBadge()}
|
||||
</div>
|
||||
<div className="shrink-0">{getConnectionBadge()}</div>
|
||||
</div>
|
||||
|
||||
{/* Right section */}
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Right: controls */}
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{/* Input indicators */}
|
||||
<div className="flex items-center gap-2 px-3 border-r border-border/50 mr-2">
|
||||
<MousePointer2 className="h-4 w-4 text-muted-foreground" />
|
||||
<Keyboard className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex items-center gap-1.5 px-2 border-r border-border/50 mr-1">
|
||||
<MousePointer2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Keyboard className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
{/* Monitor picker (only shown when multiple monitors) */}
|
||||
{connected && monitors.length > 1 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 gap-1 px-2 text-xs">
|
||||
<Monitor className="h-3.5 w-3.5" />
|
||||
{monitors[activeMonitor]
|
||||
? `${monitors[activeMonitor].width}×${monitors[activeMonitor].height}`
|
||||
: 'Monitor'}
|
||||
<ChevronDown className="h-3 w-3 opacity-50" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>Select Monitor</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{monitors.map((m) => (
|
||||
<DropdownMenuItem key={m.index} onClick={() => onMonitorChange(m.index)}>
|
||||
<Monitor className="mr-2 h-4 w-4" />
|
||||
{m.primary ? 'Primary' : `Display ${m.index + 1}`}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{m.width}×{m.height}</span>
|
||||
{activeMonitor === m.index && <CheckCircle2 className="ml-2 h-4 w-4 text-primary" />}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
|
||||
{/* Ctrl+Alt+Del */}
|
||||
{connected && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs font-mono"
|
||||
onClick={onCtrlAltDel}
|
||||
title="Send Ctrl+Alt+Del"
|
||||
>
|
||||
CAD
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Clipboard paste */}
|
||||
{connected && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={onClipboardPaste}
|
||||
title="Paste clipboard to remote"
|
||||
>
|
||||
<Clipboard className="h-4 w-4" />
|
||||
<span className="sr-only">Paste clipboard</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* File transfer */}
|
||||
{connected && (
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onToggleFileTransfer} title="File transfer">
|
||||
<FolderOpen className="h-4 w-4" />
|
||||
<span className="sr-only">File transfer</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Chat */}
|
||||
{connected && (
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onToggleChat} title="Session chat">
|
||||
<MessageSquare className="h-4 w-4" />
|
||||
<span className="sr-only">Chat</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Wake-on-LAN (shown when agent is offline) */}
|
||||
{!connected && onWakeOnLan && (
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onWakeOnLan} title="Wake on LAN">
|
||||
<Zap className="h-4 w-4 text-yellow-500" />
|
||||
<span className="sr-only">Wake on LAN</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Quality selector */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" title="Stream quality">
|
||||
<QualityIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Quality</span>
|
||||
</Button>
|
||||
@@ -156,31 +265,15 @@ export function ViewerToolbar({
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Mute toggle */}
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onToggleMute}>
|
||||
{isMuted ? (
|
||||
<VolumeX className="h-4 w-4" />
|
||||
) : (
|
||||
<Volume2 className="h-4 w-4" />
|
||||
)}
|
||||
<span className="sr-only">{isMuted ? 'Unmute' : 'Mute'}</span>
|
||||
</Button>
|
||||
|
||||
{/* Fullscreen toggle */}
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onToggleFullscreen}>
|
||||
{isFullscreen ? (
|
||||
<Minimize2 className="h-4 w-4" />
|
||||
) : (
|
||||
<Maximize2 className="h-4 w-4" />
|
||||
)}
|
||||
<span className="sr-only">{isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}</span>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onToggleFullscreen} title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
|
||||
{isFullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
|
||||
</Button>
|
||||
|
||||
{/* Reconnect */}
|
||||
{connectionState === 'disconnected' && (
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onReconnect}>
|
||||
{(connectionState === 'disconnected' || connectionState === 'waiting') && (
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onReconnect} title="Reconnect">
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
<span className="sr-only">Reconnect</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -190,9 +283,9 @@ export function ViewerToolbar({
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={onDisconnect}
|
||||
title="End session"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Disconnect</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
17
db/migrations/0003_enhancements.sql
Normal file
17
db/migrations/0003_enhancements.sql
Normal file
@@ -0,0 +1,17 @@
|
||||
-- Groups
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Machine enhancements
|
||||
ALTER TABLE machines
|
||||
ADD COLUMN IF NOT EXISTS group_id UUID REFERENCES groups(id) ON DELETE SET NULL,
|
||||
ADD COLUMN IF NOT EXISTS mac_address TEXT,
|
||||
ADD COLUMN IF NOT EXISTS notes TEXT,
|
||||
ADD COLUMN IF NOT EXISTS tags TEXT[] NOT NULL DEFAULT '{}';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_machines_group_id ON machines(group_id);
|
||||
@@ -12,6 +12,8 @@ services:
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./db/migrations/0001_initial.sql:/docker-entrypoint-initdb.d/0001_initial.sql:ro
|
||||
- ./db/migrations/0002_agent_relay.sql:/docker-entrypoint-initdb.d/0002_agent_relay.sql:ro
|
||||
- ./db/migrations/0003_enhancements.sql:/docker-entrypoint-initdb.d/0003_enhancements.sql:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-remotelink}"]
|
||||
interval: 10s
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
} from 'drizzle-orm/pg-core'
|
||||
import { sql } from 'drizzle-orm'
|
||||
|
||||
// Re-export for convenience
|
||||
export { sql }
|
||||
|
||||
export const users = pgTable('users', {
|
||||
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
||||
email: text('email').unique().notNull(),
|
||||
@@ -19,18 +22,30 @@ export const users = pgTable('users', {
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
})
|
||||
|
||||
export const groups = pgTable('groups', {
|
||||
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
||||
name: text('name').notNull(),
|
||||
description: text('description'),
|
||||
createdBy: uuid('created_by').references(() => users.id, { onDelete: 'set null' }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
})
|
||||
|
||||
export const machines = pgTable('machines', {
|
||||
id: uuid('id').primaryKey().default(sql`gen_random_uuid()`),
|
||||
userId: uuid('user_id').references(() => users.id, { onDelete: 'cascade' }).notNull(),
|
||||
groupId: uuid('group_id').references(() => groups.id, { onDelete: 'set null' }),
|
||||
name: text('name').notNull(),
|
||||
hostname: text('hostname'),
|
||||
os: text('os'),
|
||||
osVersion: text('os_version'),
|
||||
agentVersion: text('agent_version'),
|
||||
ipAddress: text('ip_address'),
|
||||
macAddress: text('mac_address'),
|
||||
accessKey: text('access_key').unique().notNull(),
|
||||
isOnline: boolean('is_online').default(false).notNull(),
|
||||
lastSeen: timestamp('last_seen', { withTimezone: true }),
|
||||
notes: text('notes'),
|
||||
tags: text('tags').array().default(sql`'{}'::text[]`),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
})
|
||||
@@ -86,6 +101,7 @@ export const invites = pgTable('invites', {
|
||||
})
|
||||
|
||||
export type User = typeof users.$inferSelect
|
||||
export type Group = typeof groups.$inferSelect
|
||||
export type Machine = typeof machines.$inferSelect
|
||||
export type SessionCode = typeof sessionCodes.$inferSelect
|
||||
export type Session = typeof sessions.$inferSelect
|
||||
|
||||
@@ -24,6 +24,8 @@ log = logging.getLogger("relay")
|
||||
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||
# Comma-separated list of allowed origins for CORS, e.g. "https://app.example.com"
|
||||
ALLOWED_ORIGINS = [o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "").split(",") if o.strip()]
|
||||
# Set RECORDING_DIR to enable session recording (JPEG frame archive)
|
||||
RECORDING_DIR = os.environ.get("RECORDING_DIR", "") # e.g. "/recordings"
|
||||
|
||||
# ── In-memory connection registry ────────────────────────────────────────────
|
||||
# machine_id (str) → WebSocket
|
||||
@@ -34,6 +36,12 @@ viewers: dict[str, WebSocket] = {}
|
||||
session_to_machine: dict[str, str] = {}
|
||||
# session_id → viewer's user role ("admin" | "user")
|
||||
viewer_roles: dict[str, str] = {}
|
||||
# session_id → open file handle for recording
|
||||
recordings: dict[str, "io.BufferedWriter"] = {}
|
||||
|
||||
import io
|
||||
import struct
|
||||
import time as _time
|
||||
|
||||
db_pool: Optional[asyncpg.Pool] = None
|
||||
|
||||
@@ -96,6 +104,48 @@ async def send_json(ws: WebSocket, data: dict):
|
||||
pass
|
||||
|
||||
|
||||
# ── Recording helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
def _start_recording(session_id: str):
|
||||
"""Open a .remrec file for this session (simple frame archive format)."""
|
||||
try:
|
||||
import pathlib
|
||||
rec_dir = pathlib.Path(RECORDING_DIR)
|
||||
rec_dir.mkdir(parents=True, exist_ok=True)
|
||||
ts = _time.strftime("%Y%m%d_%H%M%S")
|
||||
path = rec_dir / f"{ts}_{session_id[:8]}.remrec"
|
||||
recordings[session_id] = open(path, "wb")
|
||||
# File header: magic "RLREC" + version 1
|
||||
recordings[session_id].write(b"RLREC\x01")
|
||||
log.info(f"Recording started: {path}")
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to start recording for {session_id}: {e}")
|
||||
|
||||
|
||||
def _write_frame(session_id: str, frame_data: bytes):
|
||||
"""Append a JPEG frame with timestamp to the recording file."""
|
||||
f = recordings.get(session_id)
|
||||
if not f:
|
||||
return
|
||||
try:
|
||||
ts = int(_time.time() * 1000) # milliseconds
|
||||
# Frame record: 8-byte timestamp + 4-byte length + JPEG bytes
|
||||
f.write(struct.pack(">QI", ts, len(frame_data)))
|
||||
f.write(frame_data)
|
||||
except Exception as e:
|
||||
log.warning(f"Recording write error: {e}")
|
||||
|
||||
|
||||
def _stop_recording(session_id: str):
|
||||
f = recordings.pop(session_id, None)
|
||||
if f:
|
||||
try:
|
||||
f.close()
|
||||
log.info(f"Recording stopped: {session_id}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ── Agent WebSocket endpoint ──────────────────────────────────────────────────
|
||||
|
||||
@app.websocket("/ws/agent")
|
||||
@@ -129,21 +179,32 @@ async def agent_endpoint(
|
||||
if mid == machine_id and sid in viewers:
|
||||
try:
|
||||
await viewers[sid].send_bytes(frame_data)
|
||||
if RECORDING_DIR:
|
||||
_write_frame(sid, frame_data)
|
||||
except Exception:
|
||||
viewers.pop(sid, None)
|
||||
session_to_machine.pop(sid, None)
|
||||
|
||||
elif "text" in msg and msg["text"]:
|
||||
# JSON message from agent (script output, status, etc.)
|
||||
# JSON message from agent
|
||||
try:
|
||||
data = json.loads(msg["text"])
|
||||
# Forward script output to the relevant viewer
|
||||
if data.get("type") == "script_output":
|
||||
msg_type = data.get("type")
|
||||
if msg_type == "ping":
|
||||
await set_machine_online(machine_id, True)
|
||||
elif msg_type in {
|
||||
"script_output", "monitor_list", "clipboard_content",
|
||||
"file_chunk", "file_list", "chat_message",
|
||||
}:
|
||||
# Forward to the relevant viewer(s)
|
||||
session_id = data.get("session_id")
|
||||
if session_id and session_id in viewers:
|
||||
await send_json(viewers[session_id], data)
|
||||
elif data.get("type") == "ping":
|
||||
await set_machine_online(machine_id, True)
|
||||
else:
|
||||
# Broadcast to all viewers watching this machine
|
||||
for sid, mid in list(session_to_machine.items()):
|
||||
if mid == machine_id and sid in viewers:
|
||||
await send_json(viewers[sid], data)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
@@ -194,6 +255,9 @@ async def viewer_endpoint(
|
||||
"session_id": session_id,
|
||||
})
|
||||
await send_json(websocket, {"type": "agent_connected", "machine_name": session["machine_name"]})
|
||||
# Start recording if enabled
|
||||
if RECORDING_DIR:
|
||||
_start_recording(session_id)
|
||||
else:
|
||||
await send_json(websocket, {"type": "agent_offline"})
|
||||
|
||||
@@ -224,6 +288,8 @@ async def viewer_endpoint(
|
||||
viewers.pop(session_id, None)
|
||||
session_to_machine.pop(session_id, None)
|
||||
viewer_roles.pop(session_id, None)
|
||||
if RECORDING_DIR:
|
||||
_stop_recording(session_id)
|
||||
if machine_id in agents:
|
||||
await send_json(agents[machine_id], {"type": "stop_stream", "session_id": session_id})
|
||||
log.info(f"Viewer disconnected from session {session_id}")
|
||||
|
||||
1
tsconfig.tsbuildinfo
Normal file
1
tsconfig.tsbuildinfo
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user