Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pam-rdp): streaming playback + redesigned replay player
bernie-gc8032dc51387
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 5d3b8d6470..4cd6b10fd4 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -897,9 +897,9 @@ export const pamAccountServiceFactory = ({);// Temporarily disable access to Windows Server- if ((resourceType as PamResource) === PamResource.Windows) {- throw new BadRequestError({ message: `Windows resources cannot be accessed at this time` });- }+ // if ((resourceType as PamResource) === PamResource.Windows) {+ // throw new BadRequestError({ message: `Windows resources cannot be accessed at this time` });+ // }if (resourceType === PamResource.Windows) {const recordingConfig = await pamProjectRecordingConfigDAL.findByProjectId(account.projectId);diff --git a/frontend/src/hooks/api/pam/session-playback/queries.tsx b/frontend/src/hooks/api/pam/session-playback/queries.tsxindex b79862dd9d..9cac268022 100644--- a/frontend/src/hooks/api/pam/session-playback/queries.tsx+++ b/frontend/src/hooks/api/pam/session-playback/queries.tsx@@ -46,6 +46,8 @@ export type PlaybackDecryptState = {brokenChunks: TBrokenChunkMarker[];missingChunks: number[];totalChunks: number;+ // Max endElapsedMs across chunks; known before decryption.+ totalDurationMs: number;};const fallbackUrlBuilderFor = (sessionId: string) => (chunkIndex: number) =>@@ -63,7 +65,8 @@ export const useDecryptedSessionLogs = (events: [],brokenChunks: [],missingChunks: [],- totalChunks: 0+ totalChunks: 0,+ totalDurationMs: 0});const fallbackUrlBuilder = useMemo(() => fallbackUrlBuilderFor(sessionId), [sessionId]);@@ -83,7 +86,8 @@ export const useDecryptedSessionLogs = (events: [],brokenChunks: [],missingChunks: [],- totalChunks: 0+ totalChunks: 0,+ totalDurationMs: 0});}return;@@ -116,6 +120,10 @@ export const useDecryptedSessionLogs = (const projectId = bundle.projectId ?? "";const sortedChunks = [...bundle.chunks].sort((a, b) => a.chunkIndex - b.chunkIndex);+ const totalDurationMs = sortedChunks.reduce(+ (max, c) => Math.max(max, c.endElapsedMs),+ 0+ );if (sortedChunks.length > PAM_PLAYBACK_MAX_CHUNKS) {if (!cancelled) {@@ -137,6 +145,14 @@ export const useDecryptedSessionLogs = (const maxIndex = sortedChunks.length ? sortedChunks[sortedChunks.length - 1].chunkIndex : 0;+ // Publish total before any chunk decrypts.+ setState((s) => ({+ ...s,+ totalChunks: sortedChunks.length,+ totalDurationMs,+ missingChunks+ }));+for (let i = 0; i <= maxIndex; i += 1) {if (cancelled) return;@@ -188,7 +204,8 @@ export const useDecryptedSessionLogs = (events: [...events],brokenChunks: [...brokenChunks],missingChunks,- totalChunks: sortedChunks.length+ totalChunks: sortedChunks.length,+ totalDurationMs});}@@ -200,7 +217,8 @@ export const useDecryptedSessionLogs = (events,brokenChunks,missingChunks,- totalChunks: sortedChunks.length+ totalChunks: sortedChunks.length,+ totalDurationMs});};diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsxindex 5593b1185e..e4eaf7d451 100644--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/PamSessionLogsSection.tsx@@ -1,6 +1,7 @@-import { lazy, Suspense } from "react";+import { lazy, Suspense, useEffect } from "react";import { ExternalLinkIcon, Loader2Icon } from "lucide-react";+import { Lottie } from "@app/components/v2";import { Button } from "@app/components/v3";import {PamResourceType,@@ -17,9 +18,9 @@ import { CommandLogView } from "./CommandLogView";import { HttpEventView } from "./HttpEventView";import { TerminalEventView } from "./TerminalEventView";-// The IronRDP decoder WASM is ~MB-scale; load it only when an RDP session is-// actually being viewed. The dynamic import keeps it out of the main bundle.-const RdpReplayView = lazy(() => import("./RdpReplayView/RdpReplayView"));+// Lazy-load to keep the WASM decoder out of the main bundle.+const importRdpReplayView = () => import("./RdpReplayView/RdpReplayView");+const RdpReplayView = lazy(importRdpReplayView);type Props = {session: TPamSession;@@ -53,10 +54,23 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {const isRdpSession = session.resourceType === PamResourceType.Windows;const hasLogs = logs.length > 0;+ // Warm the lazy chunk so Suspense doesn't fall back on first mount.+ useEffect(() => {+ if (isRdpSession) {+ void importRdpReplayView();+ }+ }, [isRdpSession]);+return (- <div className="flex h-full w-full flex-col gap-4 rounded-lg border border-border bg-container p-4">+ <div+ className={`flex w-full flex-col gap-4 rounded-lg border border-border bg-container p-4 ${+ isRdpSession ? "" : "h-full"+ }`}+ ><div className="flex items-center gap-3 border-b border-border pb-4">- <h3 className="text-lg font-medium text-foreground">Session Logs</h3>+ <h3 className="text-lg font-medium text-foreground">+ {isRdpSession ? "Session Recording" : "Session Logs"}+ </h3>{isActive && (<span className="flex animate-pulse items-center gap-1.5 rounded-full bg-success/10 px-2.5 py-1 text-xs font-medium text-success"><span className="size-1.5 animate-pulse rounded-full bg-success" />@@ -65,7 +79,7 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {)}</div>- {isLoading && !hasLogs && (+ {isLoading && !hasLogs && !isRdpSession && (<div className="flex grow items-center justify-center"><div className="flex items-center gap-2 text-sm text-muted"><Loader2Icon className="size-4 animate-spin" />@@ -79,20 +93,38 @@ export const PamSessionLogsSection = ({ session, scrollToLogIndex }: Props) => {)}{isSSHSession && hasLogs && <TerminalEventView events={logs as TTerminalEvent[]} />}{isHttpSession && hasLogs && <HttpEventView events={logs as THttpEvent[]} />}- {isRdpSession && hasLogs && (- <Suspense- fallback={- <div className="flex grow items-center justify-center">- <div className="flex items-center gap-2 text-sm text-muted">- <Loader2Icon className="size-4 animate-spin" />- <span>Loading RDP replay player...</span>+ {isRdpSession &&+ (hasLogs ? (+ <Suspense+ fallback={+ <div className="flex grow flex-col items-center justify-center gap-2">+ <Lottie+ isAutoPlay+ icon="infisical_loading"+ className="pointer-events-none size-12"+ />+ <span className="text-sm text-muted">Loading session recording</span></div>- </div>- }- >- <RdpReplayView events={logs as TTerminalEvent[]} />- </Suspense>- )}+ }+ >+ <RdpReplayView+ events={logs as TTerminalEvent[]}+ isStreaming={isLoading}+ totalDurationMs={+ isLegacyOrNoChunks ? undefined : playback.totalDurationMs+ }+ />+ </Suspense>+ ) : isLoading ? (+ <div className="flex grow flex-col items-center justify-center gap-2">+ <Lottie+ isAutoPlay+ icon="infisical_loading"+ className="pointer-events-none size-12"+ />+ <span className="text-sm text-muted">Loading session recording</span>+ </div>+ ) : null)}{isAwsIamSession && (<div className="flex grow items-center justify-center text-muted"><div className="text-center">diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsx b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsxindex e3e56a005b..16d4bee710 100644--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsx+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/RdpReplayView.tsx@@ -1,13 +1,19 @@-import { useEffect, useMemo, useRef, useState } from "react";-import { PauseIcon, PlayIcon, RotateCcwIcon } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { AnimatePresence, motion } from "framer-motion";+import { Loader2Icon, PauseIcon, PlayIcon, RotateCcwIcon } from "lucide-react";-import { Button } from "@app/components/v3";+import { IconButton } from "@app/components/v3";import { TTerminalEvent } from "@app/hooks/api/pam";+import { isBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";import { parseRdpLogEntry, RdpEvent, RdpReplayPlayer } from "./rdpReplayPlayer";const CANVAS_W = 1920;const CANVAS_H = 1080;+// Locks the player footprint so it doesn't reshape on first frame.+const OUTER_ASPECT_W = 16;+const OUTER_ASPECT_H = 9;+const OUTER_ASPECT = OUTER_ASPECT_W / OUTER_ASPECT_H;const formatMs = (ms: number) => {const s = Math.floor(ms / 1000);@@ -16,37 +22,83 @@ const formatMs = (ms: number) => {return `${m.toString().padStart(2, "0")}:${r.toString().padStart(2, "0")}`;};+const parseRange = (events: TTerminalEvent[], start: number, end: number): RdpEvent[] => {+ const out: RdpEvent[] = [];+ for (let i = start; i < end; i += 1) {+ const ev = parseRdpLogEntry(events[i]);+ if (ev) out.push(ev);+ }+ return out;+};+type Props = {events: TTerminalEvent[];+ isStreaming?: boolean;+ totalDurationMs?: number;};-export const RdpReplayView = ({ events }: Props) => {+export const RdpReplayView = ({+ events,+ isStreaming = false,+ totalDurationMs+}: Props) => {const canvasRef = useRef<HTMLCanvasElement | null>(null);const playerRef = useRef<RdpReplayPlayer | null>(null);+ const lastParsedIndexRef = useRef(0);+ // raf-frequency updates: write progress fill + time text via refs to+ // avoid re-rendering the player subtree at 60fps.+ const progressFillRef = useRef<HTMLDivElement | null>(null);+ const timeTextRef = useRef<HTMLSpanElement | null>(null);+ const currentMsRef = useRef(0);const [isPlaying, setIsPlaying] = useState(false);- const [currentMs, setCurrentMs] = useState(0);+ const [isBuffering, setIsBuffering] = useState(false);+ const [lastSeenEventMs, setLastSeenEventMs] = useState(0);const [error, setError] = useState<string | null>(null);+ // nonce remounts AnimatePresence on rapid toggles so the pulse restarts.+ const [feedback, setFeedback] = useState<{+ icon: "play" | "pause";+ nonce: number;+ } | null>(null);+ const totalMs =+ totalDurationMs && totalDurationMs > 0 ? totalDurationMs : lastSeenEventMs;+ const [contentBounds, setContentBounds] = useState({+ width: CANVAS_W,+ height: CANVAS_H+ });- const rdpEvents = useMemo<RdpEvent[]>(() => {- const parsed: RdpEvent[] = [];- for (const e of events) {- const ev = parseRdpLogEntry(e);- if (ev) parsed.push(ev);- }- parsed.sort((a, b) => a.elapsedMs - b.elapsedMs);- return parsed;- }, [events]);+ const totalMsRef = useRef(totalMs);+ totalMsRef.current = totalMs;- const totalMs = rdpEvents.length ? rdpEvents[rdpEvents.length - 1].elapsedMs : 0;+ const writeProgress = (ms: number) => {+ currentMsRef.current = ms;+ const total = totalMsRef.current;+ if (progressFillRef.current) {+ const pct = total > 0 ? Math.min(1, ms / total) * 100 : 0;+ progressFillRef.current.style.width = `${pct}%`;+ }+ if (timeTextRef.current) {+ timeTextRef.current.textContent = `${formatMs(ms)} / ${formatMs(total)}`;+ }+ };+ // Player lifetime is mount-scoped; later chunks land via appendEvents.useEffect(() => {let cancelled = false;const canvas = canvasRef.current;- if (!canvas || rdpEvents.length === 0) return undefined;+ if (!canvas) return undefined;- RdpReplayPlayer.create(rdpEvents, canvas, {- onTick: (ms) => setCurrentMs(ms),- onEnded: () => setIsPlaying(false)+ const initial = parseRange(events, 0, events.length);+ lastParsedIndexRef.current = events.length;+ if (initial.length > 0) setLastSeenEventMs(initial[initial.length - 1].elapsedMs);++ RdpReplayPlayer.create(initial, canvas, {+ onTick: writeProgress,+ onEnded: () => {+ setIsPlaying(false);+ setIsBuffering(false);+ },+ onContentBoundsChange: (width, height) => setContentBounds({ width, height }),+ onBuffering: (b) => setIsBuffering(b)}).then((player) => {if (cancelled) {@@ -65,8 +117,44 @@ export const RdpReplayView = ({ events }: Props) => {playerRef.current.dispose();playerRef.current = null;}+ lastParsedIndexRef.current = 0;};- }, [rdpEvents]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ const player = playerRef.current;+ if (!player) return;+ if (events.length <= lastParsedIndexRef.current) return;+ // RDP frames are deltas; one corrupt/missing chunk desyncs everything+ // after it. Halt playback and surface the failure rather than rendering+ // garbage frames.+ for (let i = lastParsedIndexRef.current; i < events.length; i += 1) {+ const ev = events[i];+ if (isBrokenChunkMarker(ev)) {+ player.pause();+ setError(`Chunk ${ev.chunkIndex}: ${ev.message}`);+ return;+ }+ }+ const more = parseRange(events, lastParsedIndexRef.current, events.length);+ lastParsedIndexRef.current = events.length;+ if (more.length > 0) {+ player.appendEvents(more);+ setLastSeenEventMs(more[more.length - 1].elapsedMs);+ }+ }, [events]);++ useEffect(() => {+ if (!isStreaming && playerRef.current) {+ playerRef.current.markStreamComplete();+ }+ }, [isStreaming]);++ useEffect(() => {+ writeProgress(currentMsRef.current);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [totalMs]);const onPlayPause = () => {const p = playerRef.current;@@ -74,67 +162,132 @@ export const RdpReplayView = ({ events }: Props) => {if (p.isPlaying) {p.pause();setIsPlaying(false);- } else {- p.play();- setIsPlaying(true);+ setFeedback({ icon: "pause", nonce: Date.now() });+ return;+ }+ // play() auto-replays from t=0 when at end-of-stream; reset bounds too.+ const willAutoReplay = p.currentMs >= p.totalMs && p.totalMs > 0;+ p.play();+ if (willAutoReplay) {+ setContentBounds({ width: CANVAS_W, height: CANVAS_H });}+ setIsPlaying(true);+ setFeedback({ icon: "play", nonce: Date.now() });};+ useEffect(() => {+ if (!feedback) return undefined;+ const t = setTimeout(() => setFeedback(null), 400);+ return () => clearTimeout(t);+ }, [feedback]);+const onRestart = () => {const p = playerRef.current;if (!p) return;p.restart();setIsPlaying(false);- setCurrentMs(0);+ setIsBuffering(false);+ setContentBounds({ width: CANVAS_W, height: CANVAS_H });};if (error) {return (- <div className="flex grow items-center justify-center text-sm text-danger">- RDP replay failed to load: {error}- </div>- );- }-- if (rdpEvents.length === 0) {- return (- <div className="flex grow items-center justify-center text-sm text-muted">- No RDP events to replay yet.+ <div className="flex flex-col gap-1 rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-xs text-danger">+ <span>Playback halted: recording chunks are unavailable or corrupted.</span>+ <span className="text-danger/70">{error}</span></div>);}return (<div className="flex flex-col gap-3">- <div className="flex items-center gap-2">- <Button variant="outline" size="xs" onClick={onPlayPause}>- {isPlaying ? (- <PauseIcon className="mr-1.5 size-3.5" />- ) : (- <PlayIcon className="mr-1.5 size-3.5" />+ <button+ type="button"+ onClick={onPlayPause}+ aria-label={isPlaying ? "Pause" : "Play"}+ className="group relative flex cursor-pointer items-center justify-center overflow-hidden rounded-md border border-border bg-black focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/30"+ style={{ aspectRatio: `${OUTER_ASPECT_W} / ${OUTER_ASPECT_H}` }}+ >+ <div+ className="relative overflow-hidden"+ style={{+ aspectRatio: `${contentBounds.width} / ${contentBounds.height}`,+ ...(contentBounds.width / contentBounds.height <= OUTER_ASPECT+ ? { height: "100%" }+ : { width: "100%" })+ }}+ >+ <canvas+ ref={canvasRef}+ width={CANVAS_W}+ height={CANVAS_H}+ style={{+ width: `${(CANVAS_W / contentBounds.width) * 100}%`,+ height: `${(CANVAS_H / contentBounds.height) * 100}%`,+ display: "block"+ }}+ aria-label="RDP session replay"+ />+ </div>+ <AnimatePresence>+ {feedback && (+ <motion.div+ key={feedback.nonce}+ initial={{ opacity: 0, scale: 0.6 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 1.4 }}+ transition={{ duration: 0.35, ease: "easeOut" }}+ className="pointer-events-none absolute inset-0 flex items-center justify-center"+ >+ <div className="flex size-16 items-center justify-center rounded-full bg-black/60 backdrop-blur-sm">+ {feedback.icon === "play" ? (+ <PlayIcon className="size-8 text-white" />+ ) : (+ <PauseIcon className="size-8 text-white" />+ )}+ </div>+ </motion.div>)}- {isPlaying ? "Pause" : "Play"}- </Button>- <Button variant="outline" size="xs" onClick={onRestart}>- <RotateCcwIcon className="mr-1.5 size-3.5" />- Restart- </Button>- <span className="ml-2 font-mono text-xs text-muted">- {formatMs(currentMs)} / {formatMs(totalMs)}+ </AnimatePresence>+ {isBuffering && (+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/40">+ <div className="flex items-center gap-2 rounded-md bg-black/70 px-3 py-1.5 text-xs text-foreground">+ <Loader2Icon className="size-3.5 animate-spin" />+ <span>Buffering...</span>+ </div>+ </div>+ )}+ </button>+ <div className="flex items-center gap-3">+ <IconButton+ variant="warning"+ size="sm"+ onClick={onPlayPause}+ aria-label={isPlaying ? "Pause" : "Play"}+ >+ {isPlaying ? <PauseIcon /> : <PlayIcon />}+ </IconButton>+ <div className="relative h-1 flex-1 overflow-hidden rounded-full bg-foreground/10">+ <div+ ref={progressFillRef}+ className="absolute inset-y-0 left-0 rounded-full bg-foreground/70"+ style={{ width: "0%" }}+ />+ </div>+ <span ref={timeTextRef} className="font-mono text-xs tabular-nums text-muted">+ {formatMs(0)} / {formatMs(totalMs)}</span>- </div>- <div className="overflow-hidden rounded-md border border-border bg-black">- <canvas- ref={canvasRef}- width={CANVAS_W}- height={CANVAS_H}- className="h-auto w-full"- aria-label="RDP session replay"- />+ <IconButton+ variant="ghost-muted"+ size="sm"+ onClick={onRestart}+ aria-label="Restart from beginning"+ >+ <RotateCcwIcon />+ </IconButton></div></div>);};-// Default export for React.lazy convenience.export default RdpReplayView;diff --git a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.ts b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.tsindex 8eb604a975..f9569103ff 100644--- a/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.ts+++ b/frontend/src/pages/pam/PamSessionsByIDPage/components/RdpReplayView/rdpReplayPlayer.ts@@ -1,16 +1,3 @@-/**- * RDP replay player.- *- * Consumes RDP-tagged events drained from the gateway tap (see- * cli packages/pam/handlers/rdp/proxy.go) and drives a canvas at real- * timings. Frame decoding is delegated to the WASM module at- * @app/lib/ironrdp-decoder, which wraps IronRDP's ActiveStage + DecodedImage.- *- * Control surface is deliberately minimal: play / pause / restart + tick- * callback. Seek is not supported (frames are deltas; real seek would need- * keyframes or a reset-then-fast-forward pass).- */-import wasmInit, { InitOutput, RdpDecoder } from "@app/lib/ironrdp-decoder/infisical_rdp_decoder";export type RdpEventType = "keyboard" | "unicode" | "mouse" | "target_frame";@@ -18,17 +5,12 @@ export type RdpEventType = "keyboard" | "unicode" | "mouse" | "target_frame";export type RdpEvent = {type: RdpEventType;elapsedMs: number;- // keyboardscancode?: number;- // unicodecodePoint?: number;- // mousex?: number;y?: number;wheelDelta?: number;- // commonflags?: number;- // target_frameaction?: "x224" | "fastpath";payload?: Uint8Array;};@@ -36,6 +18,8 @@ export type RdpEvent = {type PlayerCallbacks = {onTick: (currentMs: number) => void;onEnded: () => void;+ onContentBoundsChange: (width: number, height: number) => void;+ onBuffering: (buffering: boolean) => void;};let wasmReady: Promise<InitOutput> | null = null;@@ -65,6 +49,18 @@ export class RdpReplayPlayer {private raf: number | null = null;+ // Stays true while buffering so an append can auto-resume playback.+ private wantPlay = false;++ private streamComplete = false;++ private buffering = false;++ // Running max of blitted rects; discovers the real desktop size.+ private contentMaxX = 0;++ private contentMaxY = 0;+private constructor(events: RdpEvent[],canvas: HTMLCanvasElement,@@ -102,30 +98,47 @@ export class RdpReplayPlayer {}get isPlaying(): boolean {- return this.raf !== null;+ return this.wantPlay;+ }++ get isBuffering(): boolean {+ return this.buffering;}play = () => {- if (this.raf !== null) return;- if (this.index >= this.events.length) return;- this.wallStart = performance.now() - this.clockMs;- this.tick();+ if (this.wantPlay) return;+ // Play after end-of-stream replays from t=0.+ if (this.streamComplete && this.index >= this.events.length) {+ this.resetForReplay();+ }+ this.wantPlay = true;+ if (this.index >= this.events.length) {+ this.setBuffering(true);+ return;+ }+ this.startRaf();};pause = () => {- if (this.raf === null) return;- cancelAnimationFrame(this.raf);- this.raf = null;- this.wallStart = null;+ this.wantPlay = false;+ this.stopRaf();+ this.setBuffering(false);};restart = () => {- this.pause();+ this.resetForReplay();+ this.wantPlay = false;+ };++ // Shared between restart() and the play()-after-end auto-replay path.+ private resetForReplay = () => {+ this.stopRaf();+ this.setBuffering(false);this.index = 0;this.clockMs = 0;- // A restart needs a fresh decoder state -- frames are deltas, so- // replaying from T=0 against a non-fresh decoder would reuse already- // applied delta state on top of the still-present pixels.+ this.contentMaxX = 0;+ this.contentMaxY = 0;+ // Frames are deltas, so replaying needs a fresh decoder state.this.decoder.free();this.decoder = new RdpDecoder(this.canvas.width, this.canvas.height);this.ctx.fillStyle = "#000";@@ -133,8 +146,30 @@ export class RdpReplayPlayer {this.callbacks.onTick(0);};+ // Caller must preserve global elapsedMs ordering across calls.+ appendEvents = (more: RdpEvent[]) => {+ if (more.length === 0) return;+ this.events.push(...more);+ if (this.buffering && this.wantPlay) {+ this.setBuffering(false);+ this.startRaf();+ }+ };++ markStreamComplete = () => {+ if (this.streamComplete) return;+ this.streamComplete = true;+ if (this.buffering) {+ this.setBuffering(false);+ this.wantPlay = false;+ this.callbacks.onEnded();+ }+ };+dispose = () => {- this.pause();+ this.stopRaf();+ this.wantPlay = false;+ this.buffering = false;try {this.decoder.free();} catch {@@ -142,6 +177,25 @@ export class RdpReplayPlayer {}};+ private startRaf = () => {+ if (this.raf !== null) return;+ this.wallStart = performance.now() - this.clockMs;+ this.tick();+ };++ private stopRaf = () => {+ if (this.raf === null) return;+ cancelAnimationFrame(this.raf);+ this.raf = null;+ this.wallStart = null;+ };++ private setBuffering = (value: boolean) => {+ if (this.buffering === value) return;+ this.buffering = value;+ this.callbacks.onBuffering(value);+ };+private tick = () => {if (this.wallStart === null) return;const now = performance.now();@@ -157,7 +211,12 @@ export class RdpReplayPlayer {if (this.index >= this.events.length) {this.raf = null;this.wallStart = null;- this.callbacks.onEnded();+ if (this.streamComplete) {+ this.wantPlay = false;+ this.callbacks.onEnded();+ } else {+ this.setBuffering(true);+ }return;}@@ -170,19 +229,14 @@ export class RdpReplayPlayer {if (ev.payload) this.feedFrame(ev);break;case "mouse":+ // Server only sends PositionPointer for its own moves; drive cursor from input.if (ev.x !== undefined && ev.y !== undefined) {- // Drive the server-rendered pointer sprite from recorded mouse- // input. Windows only sends PositionPointer PDUs for server-- // initiated cursor moves; normal movement is resolved client-side,- // so replay has to replay it the same way.const count = this.decoder.move_pointer(ev.x, ev.y);if (count > 0) this.blitDirtyRects(count);}break;case "keyboard":case "unicode":- // V1 renders frames only; recorded input is in the event stream- // but not surfaced in the player UI.break;default:break;@@ -190,9 +244,7 @@ export class RdpReplayPlayer {};private blitDirtyRects = (count: number) => {- // Construct a view over the WASM-side framebuffer. We re-create the view- // each call because wasm-bindgen can reallocate linear memory on growth,- // which would invalidate any cached pointer/length pair.+ // Re-view: wasm-bindgen may reallocate linear memory between calls.const ptr = this.decoder.buffer_ptr();const len = this.decoder.buffer_len();const width = this.decoder.width();@@ -200,21 +252,35 @@ export class RdpReplayPlayer {const fb = new Uint8ClampedArray(this.wasm.memory.buffer, ptr, len);const fullImage = new ImageData(fb, width, height);+ let boundsExpanded = false;for (let i = 0; i < count; i += 1) {const r = this.decoder.dirty_rect(i);if (!r) continue;- // 8-arg putImageData clips to (dx, dy, dw, dh) rect of the source.this.ctx.putImageData(fullImage, 0, 0, r.x, r.y, r.w, r.h);+ const right = r.x + r.w;+ const bottom = r.y + r.h;+ if (right > this.contentMaxX) {+ this.contentMaxX = right;+ boundsExpanded = true;+ }+ if (bottom > this.contentMaxY) {+ this.contentMaxY = bottom;+ boundsExpanded = true;+ }r.free();}+ if (boundsExpanded) {+ this.callbacks.onContentBoundsChange(this.contentMaxX, this.contentMaxY);+ }};private feedFrame = (ev: RdpEvent) => {if (!ev.payload) return;- const action = ev.action === "x224" ? 0 : 1;+ // X.224 activation PDUs corrupt ActiveStage state; FastPath alone is enough.+ if (ev.action === "x224") return;let count: number;try {- count = this.decoder.feed(action, ev.payload);+ count = this.decoder.feed(1, ev.payload);} catch {return;}@@ -230,12 +296,7 @@ const decodeBase64ToUint8 = (b64: string): Uint8Array => {return out;};-/**- * Parse a TerminalEvent (channelType "rdp") into an RdpEvent, or null if- * the entry isn't a recognized RDP envelope. The gateway emits each event- * as base64-encoded JSON inside `data`; see the rdp*Envelope types in cli- * packages/pam/handlers/rdp/proxy.go for the wire shape.- */+// Wire shape: base64 JSON. See rdp*Envelope in cli/.../rdp/proxy.go.export const parseRdpLogEntry = (entry: unknown): RdpEvent | null => {const e = entry as { data?: string; channelType?: string };if (e?.channelType !== "rdp" || typeof e.data !== "string") return null;