Remove recordings feature, replay sessions directly, bump to 0.6.0
CI / Build and push image (push) Successful in 1m41s
CI / Static checks (push) Successful in 2m12s

Recordings were just a thin named pointer over an already-captured
session's events, so the whole separate feature (recordings table, API
routes, pages, UI) is gone: any completed session can now be named and
replayed directly. Replaying no longer creates a session or duplicates
events of its own - it just bumps the source session's playCount/lastPlayedAt.

Also renames play_sessions/playSession(s) to sessions/session(s) throughout
the schema, queries, API routes, and UI for consistency, and updates the
README to match the new flow.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-27 21:38:51 +02:00
co-authored by Claude Sonnet 5
parent 2a3c4ff1f2
commit 401b9b5033
46 changed files with 1710 additions and 1018 deletions
+94
View File
@@ -0,0 +1,94 @@
"use client";
import { useState } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { autoMapDeviceSlots } from "@/lib/buttplug/device-remap";
import type { ReplayDeviceSlot, ConnectedDeviceInfo } from "@/lib/buttplug/types";
interface DeviceRemapDialogProps {
open: boolean;
deviceSlots: ReplayDeviceSlot[];
connectedDevices: ConnectedDeviceInfo[];
onCancel: () => void;
onConfirm: (mapping: Map<number, number>) => void;
}
export function DeviceRemapDialog({
open,
deviceSlots,
connectedDevices,
onCancel,
onConfirm,
}: DeviceRemapDialogProps) {
const autoMapped = autoMapDeviceSlots(deviceSlots, connectedDevices);
const [assignments, setAssignments] = useState<Record<number, number | null>>(
Object.fromEntries(deviceSlots.map((slot, i) => [slot.sourceSessionDeviceId, autoMapped[i]?.matchedDeviceIndex ?? null])),
);
const allAssigned = deviceSlots.every((s) => assignments[s.sourceSessionDeviceId] !== null);
function handleConfirm() {
const mapping = new Map<number, number>();
for (const slot of deviceSlots) {
const deviceIndex = assignments[slot.sourceSessionDeviceId];
if (deviceIndex !== null && deviceIndex !== undefined) mapping.set(slot.sourceSessionDeviceId, deviceIndex);
}
onConfirm(mapping);
}
return (
<Dialog open={open} onOpenChange={(o) => !o && onCancel()}>
<DialogContent>
<DialogHeader>
<DialogTitle>Match devices for replay</DialogTitle>
<DialogDescription>
Web Bluetooth doesn&apos;t expose a stable device id across sessions, so match each recorded
device to a currently-connected one. Two identically-named devices can&apos;t be told apart
automatically.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
{deviceSlots.map((slot) => (
<div key={slot.sourceSessionDeviceId} className="flex items-center justify-between gap-3">
<span className="text-sm font-medium">{slot.slotLabel}</span>
<Select
value={assignments[slot.sourceSessionDeviceId]?.toString() ?? undefined}
onValueChange={(v) =>
setAssignments((prev) => ({ ...prev, [slot.sourceSessionDeviceId]: Number(v) }))
}
>
<SelectTrigger size="sm" className="w-48">
<SelectValue placeholder="Unmatched" />
</SelectTrigger>
<SelectContent>
{connectedDevices.map((d) => (
<SelectItem key={d.index} value={d.index.toString()}>
{d.displayName ?? d.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
))}
</div>
<DialogFooter>
<Button variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button onClick={handleConfirm} disabled={!allAssigned}>
Start replay
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+253
View File
@@ -0,0 +1,253 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Slider } from "@/components/ui/slider";
import { DeviceScanPanel } from "@/components/control/DeviceScanPanel";
import { DeviceRemapDialog } from "./DeviceRemapDialog";
import { disconnectAll, getButtplugClientHandle, getDevice, startScanning, stopScanning } from "@/lib/buttplug/client";
import { SessionPlayer, type SessionEventRow } from "@/lib/buttplug/player";
import { useButtplugStore } from "@/lib/buttplug/store";
import type { ActuatorInfo, ReplayDeviceSlot } from "@/lib/buttplug/types";
import { Pause, Play } from "lucide-react";
interface ReplayDataResponse {
session: {
id: number;
name: string | null;
durationMs: number;
};
deviceSlots: ReplayDeviceSlot[];
events: SessionEventRow[];
}
function formatTime(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
return `${Math.floor(totalSeconds / 60)}:${(totalSeconds % 60).toString().padStart(2, "0")}`;
}
export function ReplayPlayer({ sessionId }: { sessionId: number }) {
const scanning = useButtplugStore((s) => s.scanning);
const devices = useButtplugStore((s) => s.devices);
const setActuatorValue = useButtplugStore((s) => s.setActuatorValue);
const removeDevice = useButtplugStore((s) => s.removeDevice);
const connectedDevices = useMemo(() => Object.values(devices), [devices]);
const [data, setData] = useState<ReplayDataResponse | null>(null);
const [showRemap, setShowRemap] = useState(false);
const [starting, setStarting] = useState(false);
const [player, setPlayer] = useState<SessionPlayer | null>(null);
const [playing, setPlaying] = useState(false);
const [elapsedMs, setElapsedMs] = useState(0);
const [replayTargets, setReplayTargets] = useState<{ slotLabel: string; deviceName: string }[]>([]);
const [replayDeviceIndexes, setReplayDeviceIndexes] = useState<number[]>([]);
useEffect(() => {
fetch(`/api/sessions/${sessionId}/replay`)
.then((r) => r.json())
.then(setData)
.catch(() => toast.error("Could not load session"));
}, [sessionId]);
useEffect(() => {
return () => {
void disconnectAll();
};
}, []);
async function resetReplayDevices() {
await Promise.all(
replayDeviceIndexes.map(async (deviceIndex) => {
const liveDevice = await getDevice(deviceIndex);
await liveDevice?.stop().catch(() => {});
devices[deviceIndex]?.actuators.forEach((a) => setActuatorValue(deviceIndex, a.featureIndex, 0));
}),
);
}
async function handleConfirmRemap(mapping: Map<number, number>) {
if (!data) return;
setShowRemap(false);
setStarting(true);
try {
const orderedSlots = data.deviceSlots.filter((s) => mapping.has(s.sourceSessionDeviceId));
const targets = orderedSlots.map((slot) => {
const deviceIndex = mapping.get(slot.sourceSessionDeviceId)!;
const device = connectedDevices.find((d) => d.index === deviceIndex)!;
return { slotLabel: slot.slotLabel, deviceName: device.displayName ?? device.name };
});
// Replaying creates no session or events of its own - it just plays this
// session's already-recorded events back onto the mapped devices, and
// marks it as replayed (playCount/lastPlayedAt).
void fetch(`/api/sessions/${data.session.id}/replay`, { method: "POST" }).catch(() => {});
// `mapping` is already keyed by the source session's session_device id
// (see DeviceRemapDialog), exactly what SessionPlayer needs.
const sessionDeviceIdToDeviceIndex = mapping;
const actuatorsByDeviceIndex = new Map<number, ActuatorInfo[]>(
connectedDevices.map((d) => [d.index, d.actuators]),
);
// Reset every actuator on every device that will take part in this replay before
// the first scheduled event fires, so playback always starts from a known-zero
// state rather than whatever intensity was left over from manual control.
const deviceIndexes = new Set(sessionDeviceIdToDeviceIndex.values());
await Promise.all(
[...deviceIndexes].map(async (deviceIndex) => {
const liveDevice = await getDevice(deviceIndex);
await liveDevice?.stop().catch(() => {});
actuatorsByDeviceIndex.get(deviceIndex)?.forEach((a) => setActuatorValue(deviceIndex, a.featureIndex, 0));
}),
);
const { runtime } = await getButtplugClientHandle();
const instance = new SessionPlayer({
events: data.events,
durationMs: data.session.durationMs,
sessionDeviceIdToDeviceIndex,
actuatorsByDeviceIndex,
runtime,
onProgress: (elapsed) => setElapsedMs(elapsed),
onError: (message) => toast.error(`Replay command failed: ${message}`),
onComplete: () => {
setPlaying(false);
toast.success("Replay finished");
},
});
setReplayTargets(targets);
setReplayDeviceIndexes([...deviceIndexes]);
setPlayer(instance);
instance.play();
setPlaying(true);
} catch {
toast.error("Could not start replay");
} finally {
setStarting(false);
}
}
if (!data) {
return <p className="text-sm text-muted-foreground">Loading session...</p>;
}
return (
<div className="flex flex-col gap-6">
<Card className="bp-glass">
<CardHeader>
<CardTitle>{data.session.name ?? `Session #${data.session.id}`}</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{!player ? (
<>
<p className="text-sm text-muted-foreground">
Connect the devices you want to replay onto, then match them to the session&apos;s
original device slots.
</p>
<div className="flex items-center gap-3">
<DeviceScanPanel scanning={scanning} onScan={() => void startScanning()} onStopScan={() => void stopScanning()} />
<Button
onClick={async () => {
try {
await getButtplugClientHandle();
setShowRemap(true);
} catch {
toast.error("Could not connect to Buttplug client");
}
}}
disabled={connectedDevices.length === 0 || starting}
>
{starting ? "Starting..." : "Match devices & replay"}
</Button>
</div>
</>
) : (
<div className="flex flex-col gap-3">
{replayTargets.length > 0 && (
<div className="flex flex-wrap gap-2">
{replayTargets.map((t) => (
<span
key={t.slotLabel}
className="bp-readout rounded-md border border-border bg-card/60 px-2 py-1 text-xs text-muted-foreground"
>
{t.slotLabel} {t.deviceName}
</span>
))}
</div>
)}
<Slider
value={[elapsedMs]}
max={data.session.durationMs}
onValueChange={([v]) => player.seek(v)}
/>
<div className="flex items-center justify-between">
<span className="bp-readout text-xs text-muted-foreground">
{formatTime(elapsedMs)} / {formatTime(data.session.durationMs)}
</span>
<div className="flex items-center gap-2">
<Button
size="icon"
variant="outline"
onClick={async () => {
if (playing) {
player.pause();
setPlaying(false);
} else {
player.play();
setPlaying(true);
}
// Toggling either way leaves the toy holding whatever intensity was
// last sent - zero it out so pause always actually stops the device,
// and resume always starts from a clean, known state.
await resetReplayDevices();
}}
aria-label={playing ? "Pause" : "Play"}
>
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
</Button>
<Button
size="sm"
variant="ghost"
onClick={async () => {
player.stop();
setPlaying(false);
setElapsedMs(0);
// Fully disconnect every device that took part in this replay,
// not just stop the player - see handleDisconnectDevice in
// ButtplugConsole for why "stop + remove from store" is the
// closest equivalent Buttplug's protocol allows per-device.
await Promise.all(
replayDeviceIndexes.map(async (deviceIndex) => {
const liveDevice = await getDevice(deviceIndex);
await liveDevice?.stop().catch(() => {});
removeDevice(deviceIndex);
}),
);
setPlayer(null);
setReplayTargets([]);
setReplayDeviceIndexes([]);
}}
>
Stop
</Button>
</div>
</div>
</div>
)}
</CardContent>
</Card>
<DeviceRemapDialog
open={showRemap}
deviceSlots={data.deviceSlots}
connectedDevices={connectedDevices}
onCancel={() => setShowRemap(false)}
onConfirm={(mapping) => void handleConfirmRemap(mapping)}
/>
</div>
);
}
@@ -0,0 +1,13 @@
"use client";
import dynamic from "next/dynamic";
import { Skeleton } from "@/components/ui/skeleton";
const ReplayPlayer = dynamic(() => import("./ReplayPlayer").then((m) => m.ReplayPlayer), {
ssr: false,
loading: () => <Skeleton className="h-64 w-full" />,
});
export function ReplayPlayerLoader({ sessionId }: { sessionId: number }) {
return <ReplayPlayer sessionId={sessionId} />;
}
+33 -41
View File
@@ -14,23 +14,23 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Trash2 } from "lucide-react";
import { Play, Trash2 } from "lucide-react";
import { toast } from "sonner";
interface BlockingRecording {
id: number;
name: string;
}
export interface SessionRow {
id: number;
name: string | null;
kind: "live" | "replay";
status: "active" | "completed" | "aborted";
startedAt: number;
durationMs: number | null;
}
const STATUS_VARIANT = {
active: "default",
completed: "secondary",
aborted: "destructive",
} as const;
function formatDuration(ms: number | null): string {
if (ms === null) return "-";
const totalSeconds = Math.round(ms / 1000);
@@ -41,30 +41,17 @@ function formatDuration(ms: number | null): string {
export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
const router = useRouter();
const [conflict, setConflict] = useState<{ id: number; recordings: BlockingRecording[] } | null>(null);
const [pendingDelete, setPendingDelete] = useState<SessionRow | null>(null);
const [deleting, setDeleting] = useState(false);
async function handleDelete(id: number) {
const res = await fetch(`/api/play-sessions/${id}`, { method: "DELETE" });
if (res.ok) {
toast.success("Session deleted");
router.refresh();
} else if (res.status === 409) {
const body: { recordings?: BlockingRecording[] } = await res.json().catch(() => ({}));
setConflict({ id, recordings: body.recordings ?? [] });
} else {
toast.error("Could not delete session");
}
}
async function handleCascadeDelete() {
if (!conflict) return;
async function handleDelete() {
if (!pendingDelete) return;
setDeleting(true);
const res = await fetch(`/api/play-sessions/${conflict.id}?cascade=true`, { method: "DELETE" });
const res = await fetch(`/api/sessions/${pendingDelete.id}`, { method: "DELETE" });
setDeleting(false);
if (res.ok) {
toast.success("Session and recording deleted");
setConflict(null);
toast.success("Session deleted");
setPendingDelete(null);
router.refresh();
} else {
toast.error("Could not delete session");
@@ -81,7 +68,6 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
<TableHeader>
<TableRow>
<TableHead>Session</TableHead>
<TableHead>Kind</TableHead>
<TableHead>Status</TableHead>
<TableHead>Started</TableHead>
<TableHead>Duration</TableHead>
@@ -97,15 +83,21 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
</Link>
</TableCell>
<TableCell>
<Badge variant={s.kind === "live" ? "default" : "secondary"}>{s.kind}</Badge>
<Badge variant={STATUS_VARIANT[s.status]}>{s.status}</Badge>
</TableCell>
<TableCell className="text-muted-foreground">{s.status}</TableCell>
<TableCell className="bp-readout text-muted-foreground">
{new Date(s.startedAt).toLocaleString()}
</TableCell>
<TableCell className="bp-readout">{formatDuration(s.durationMs)}</TableCell>
<TableCell className="text-right">
<Button variant="ghost" size="icon-sm" onClick={() => void handleDelete(s.id)} aria-label="Delete">
<TableCell className="flex justify-end gap-1">
{s.status === "completed" && s.durationMs !== null && (
<Button asChild variant="ghost" size="icon-sm">
<Link href={`/sessions/${s.id}/replay`} aria-label="Replay">
<Play className="size-3.5" />
</Link>
</Button>
)}
<Button variant="ghost" size="icon-sm" onClick={() => setPendingDelete(s)} aria-label="Delete">
<Trash2 className="size-3.5" />
</Button>
</TableCell>
@@ -114,24 +106,24 @@ export function SessionsTable({ sessions }: { sessions: SessionRow[] }) {
</TableBody>
</Table>
<Dialog open={conflict !== null} onOpenChange={(open) => !open && setConflict(null)}>
<Dialog open={pendingDelete !== null} onOpenChange={(open) => !open && setPendingDelete(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Delete session and recording?</DialogTitle>
<DialogTitle>Delete session?</DialogTitle>
<DialogDescription>
This session has a saved recording
{conflict && conflict.recordings.length > 0
? ` (${conflict.recordings.map((r) => r.name).join(", ")})`
: ""}{" "}
that still points to it. Deleting the session will also delete that recording.
This permanently deletes{" "}
<span className="font-medium text-foreground">
{pendingDelete?.name ?? `Session #${pendingDelete?.id}`}
</span>{" "}
and all of its recorded events. This can&apos;t be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="ghost" onClick={() => setConflict(null)}>
<Button variant="ghost" onClick={() => setPendingDelete(null)}>
Cancel
</Button>
<Button variant="destructive" onClick={() => void handleCascadeDelete()} disabled={deleting}>
{deleting ? "Deleting..." : "Delete both"}
<Button variant="destructive" onClick={() => void handleDelete()} disabled={deleting}>
{deleting ? "Deleting..." : "Delete"}
</Button>
</DialogFooter>
</DialogContent>