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:
monoadmin
2026-04-10 23:57:47 -07:00
parent 27673daa63
commit 61edbf59bf
20 changed files with 1881 additions and 241 deletions

View File

@@ -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>
)
}

View File

@@ -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>
)}

View File

@@ -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
View 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 })
}

View File

@@ -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 }> }

View 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 })
}
}

View File

@@ -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>