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
+3 -4
View File
@@ -1,5 +1,4 @@
import type { RecordingDeviceSlot } from "@/lib/db/schema";
import type { ConnectedDeviceInfo } from "./types";
import type { ConnectedDeviceInfo, ReplayDeviceSlot } from "./types";
export interface DeviceRemapEntry {
slotLabel: string;
@@ -8,14 +7,14 @@ export interface DeviceRemapEntry {
}
/**
* Best-effort name match from a recording's saved device slots to the
* Best-effort name match from a session's device slots to the
* currently-connected devices. Web Bluetooth exposes no stable hardware id
* across sessions, so this is inherently approximate: two devices sharing an
* identical advertised name are indistinguishable and must be disambiguated
* manually in the remap UI - this isn't a bug, it's a hard BLE limitation.
*/
export function autoMapDeviceSlots(
slots: RecordingDeviceSlot[],
slots: ReplayDeviceSlot[],
connectedDevices: ConnectedDeviceInfo[],
): DeviceRemapEntry[] {
const usedIndexes = new Set<number>();
+12 -13
View File
@@ -13,21 +13,20 @@ interface ApiEvent {
/**
* Buffers every dispatched command (live or replay) and flushes it in
* batches to the play-session's events endpoint, so a dragged slider never
* batches to the session's events endpoint, so a dragged slider never
* fires one HTTP request per tick. Every command is always recorded here
* regardless of whether the session is later saved as a named recording -
* "recording" is a save decision made after the fact, not a separate
* capture pipeline (see lib/db/queries/recordings.ts).
* regardless of whether the session is later named - any completed session
* can be replayed directly, there's no separate "save as recording" step.
*/
class EventBuffer {
private buffer: CommandEvent[] = [];
private playSessionId: number | null = null;
private sessionId: number | null = null;
private sessionStartedAt = 0;
private sessionDeviceIdByDeviceIndex = new Map<number, number>();
private timer: ReturnType<typeof setInterval> | null = null;
start(playSessionId: number, sessionStartedAt: number): void {
this.playSessionId = playSessionId;
start(sessionId: number, sessionStartedAt: number): void {
this.sessionId = sessionId;
this.sessionStartedAt = sessionStartedAt;
this.sessionDeviceIdByDeviceIndex = new Map();
this.buffer = [];
@@ -46,16 +45,16 @@ class EventBuffer {
}
record(event: Omit<CommandEvent, "tsMs"> & { tsMs?: number }): void {
if (this.playSessionId === null) return;
if (this.sessionId === null) return;
const tsMs = event.tsMs ?? Date.now() - this.sessionStartedAt;
this.buffer.push({ ...event, tsMs });
}
async flush(): Promise<void> {
if (this.buffer.length === 0 || this.playSessionId === null) return;
if (this.buffer.length === 0 || this.sessionId === null) return;
const events = this.drain();
try {
await fetch(`/api/play-sessions/${this.playSessionId}/events`, {
await fetch(`/api/sessions/${this.sessionId}/events`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ events }),
@@ -71,7 +70,7 @@ class EventBuffer {
void this.flush();
if (this.timer) clearInterval(this.timer);
this.timer = null;
this.playSessionId = null;
this.sessionId = null;
if (typeof window !== "undefined") {
window.removeEventListener("beforeunload", this.flushBeacon);
document.removeEventListener("visibilitychange", this.onVisibilityChange);
@@ -83,10 +82,10 @@ class EventBuffer {
};
private flushBeacon = (): void => {
if (this.buffer.length === 0 || this.playSessionId === null || typeof navigator === "undefined") return;
if (this.buffer.length === 0 || this.sessionId === null || typeof navigator === "undefined") return;
const events = this.drain();
navigator.sendBeacon(
`/api/play-sessions/${this.playSessionId}/events`,
`/api/sessions/${this.sessionId}/events`,
new Blob([JSON.stringify({ events })], { type: "application/json" }),
);
};
+11 -19
View File
@@ -1,9 +1,8 @@
import { getDevice } from "./client";
import { buildOutputCommand, findFeature, type ButtplugRuntime } from "./commands";
import { eventBuffer } from "./event-buffer";
import type { ActuatorInfo, CommandEvent } from "./types";
export interface RecordingEventRow {
export interface SessionEventRow {
tsMs: number;
commandType: CommandEvent["commandType"];
featureIndex: number;
@@ -13,13 +12,14 @@ export interface RecordingEventRow {
}
export interface PlayerOptions {
events: RecordingEventRow[];
/** The recording's actual duration (recordings.durationMs from the DB) - this is the source
* of truth for playback length, NOT the last event's timestamp: a recording can run for a
* while after its last command (e.g. the user stopped the toy but let the session continue),
* so deriving duration from events would end playback early and misreport it as "finished". */
events: SessionEventRow[];
/** The source session's actual duration (sessions.duration_ms from the DB) - this is
* the source of truth for playback length, NOT the last event's timestamp: a session can run
* for a while after its last command (e.g. the user stopped the toy but let the session
* continue), so deriving duration from events would end playback early and misreport it as
* "finished". */
durationMs: number;
/** Recording's session_device_id -> currently-connected device index, from the remap step. */
/** Source session's session_device_id -> currently-connected device index, from the remap step. */
sessionDeviceIdToDeviceIndex: Map<number, number>;
actuatorsByDeviceIndex: Map<number, ActuatorInfo[]>;
runtime: ButtplugRuntime;
@@ -30,11 +30,11 @@ export interface PlayerOptions {
}
/**
* Replays a recording's events against the currently-connected devices,
* Replays a session's events against the currently-connected devices,
* using performance.now()-relative scheduling (not wall-clock Date.now())
* so long sessions don't accumulate drift from setTimeout jitter.
*/
export class RecordingPlayer {
export class SessionPlayer {
private readonly durationMs: number;
private startedAtPerf = 0;
private pausedAtMs = 0;
@@ -110,7 +110,7 @@ export class RecordingPlayer {
}, 200);
}
private async dispatch(event: RecordingEventRow): Promise<void> {
private async dispatch(event: SessionEventRow): Promise<void> {
const deviceIndex = this.options.sessionDeviceIdToDeviceIndex.get(event.sessionDeviceId);
if (deviceIndex === undefined) return;
@@ -130,14 +130,6 @@ export class RecordingPlayer {
const cmd = buildOutputCommand(this.options.runtime, actuator, event.value, event.durationMs ?? undefined);
await feature.runOutput(cmd);
}
eventBuffer.record({
deviceIndex,
commandType: event.commandType,
featureIndex: event.featureIndex,
value: event.value,
durationMs: event.durationMs ?? undefined,
});
} catch (err) {
this.options.onError?.(err instanceof Error ? err.message : String(err));
}
+17
View File
@@ -4,6 +4,8 @@
* rows) never has to import the client library directly.
*/
import type { DeviceCapabilities } from "@/lib/db/schema";
export type NormalizedOutputType = "vibrate" | "rotate" | "linear";
export type CommandType = NormalizedOutputType | "stop";
@@ -32,3 +34,18 @@ export interface CommandEvent {
value: number;
durationMs?: number;
}
/**
* A device that took part in a session, as needed to remap it onto a
* currently-connected device for replay. Computed live from that session's
* session_devices/devices rows - not a frozen snapshot.
*/
export interface ReplayDeviceSlot {
slotLabel: string;
recordedBleName: string;
deviceClass: string | null;
capabilities: DeviceCapabilities | null;
/** The session_devices.id this slot was captured from - lets the replay UI
* map a chosen live device back to this slot's session_events. */
sourceSessionDeviceId: number;
}
-133
View File
@@ -1,133 +0,0 @@
import { desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { playSessions, sessionDevices, devices, recordings } from "@/lib/db/schema";
import { upsertDeviceByBleName } from "./devices";
import { incrementPlayCount } from "./recordings";
import type { DeviceCapabilities } from "@/lib/db/schema";
import { PAGE_SIZE, type Page } from "@/lib/pagination";
export interface StartSessionDeviceInput {
slotLabel: string;
bleName: string;
deviceClass?: string | null;
capabilities?: DeviceCapabilities;
}
export interface StartSessionInput {
kind: "live" | "replay";
replayedRecordingId?: number;
name?: string;
devices: StartSessionDeviceInput[];
}
export async function startPlaySession(input: StartSessionInput) {
const now = Date.now();
const [session] = await db
.insert(playSessions)
.values({
kind: input.kind,
replayedRecordingId: input.replayedRecordingId,
name: input.name,
status: "active",
startedAt: now,
})
.returning();
const sessionDeviceRows = [];
for (const d of input.devices) {
const device = await upsertDeviceByBleName({
bleName: d.bleName,
deviceClass: d.deviceClass,
capabilities: d.capabilities,
});
const [sessionDevice] = await db
.insert(sessionDevices)
.values({
playSessionId: session.id,
deviceId: device.id,
slotLabel: d.slotLabel,
connectedAt: now,
})
.returning();
sessionDeviceRows.push(sessionDevice);
}
if (input.kind === "replay" && input.replayedRecordingId) {
await incrementPlayCount(input.replayedRecordingId, now);
}
return { session, sessionDevices: sessionDeviceRows };
}
export async function endPlaySession(
id: number,
input: { status: "completed" | "aborted" },
) {
const [existing] = await db.select().from(playSessions).where(eq(playSessions.id, id));
if (!existing) return undefined;
const endedAt = Date.now();
const durationMs = endedAt - existing.startedAt;
await db
.update(sessionDevices)
.set({ disconnectedAt: endedAt })
.where(eq(sessionDevices.playSessionId, id));
const [updated] = await db
.update(playSessions)
.set({ endedAt, durationMs, status: input.status })
.where(eq(playSessions.id, id))
.returning();
return updated;
}
export async function listPlaySessions() {
return db.select().from(playSessions).orderBy(playSessions.startedAt);
}
export async function listPlaySessionsPage(page: number, pageSize = PAGE_SIZE): Promise<Page<typeof playSessions.$inferSelect>> {
const [{ count }] = await db.select({ count: sql<number>`count(*)` }).from(playSessions);
const items = await db
.select()
.from(playSessions)
.orderBy(desc(playSessions.startedAt))
.limit(pageSize)
.offset((page - 1) * pageSize);
return { items, page, pageSize, total: count };
}
/** Lightweight name-only lookup for page titles - avoids getPlaySessionDetail's device join. */
export async function getPlaySessionName(id: number): Promise<string | null | undefined> {
const [row] = await db.select({ name: playSessions.name }).from(playSessions).where(eq(playSessions.id, id));
return row?.name;
}
export async function getPlaySessionDetail(id: number) {
const [session] = await db.select().from(playSessions).where(eq(playSessions.id, id));
if (!session) return undefined;
const sessionDeviceRows = await db
.select({
id: sessionDevices.id,
slotLabel: sessionDevices.slotLabel,
connectedAt: sessionDevices.connectedAt,
disconnectedAt: sessionDevices.disconnectedAt,
deviceId: devices.id,
deviceDisplayName: devices.displayName,
deviceBleName: devices.bleName,
})
.from(sessionDevices)
.innerJoin(devices, eq(sessionDevices.deviceId, devices.id))
.where(eq(sessionDevices.playSessionId, id));
return { session, devices: sessionDeviceRows };
}
export async function deletePlaySession(id: number, options?: { cascade?: boolean }) {
if (options?.cascade) {
await db.delete(recordings).where(eq(recordings.sourcePlaySessionId, id));
}
await db.delete(playSessions).where(eq(playSessions.id, id));
}
-111
View File
@@ -1,111 +0,0 @@
import { desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { recordings, sessionDevices, devices, playSessions, type RecordingDeviceSlot } from "@/lib/db/schema";
import { getEventsForSession } from "./session-events";
import { PAGE_SIZE, type Page } from "@/lib/pagination";
/**
* A recording is a thin pointer over an already-captured play_session, not a
* duplicated event pipeline: every live command is always persisted to
* session_events (stats need it regardless of whether the user saves a
* recording), so "saving a recording" just snapshots the session's device
* slots and points a new row at it. This keeps the replay-loader query and
* the stats-timeline query reading the exact same rows, with zero risk of
* live/recorded data drifting apart.
*/
export async function createRecording(input: {
sourcePlaySessionId: number;
name: string;
description?: string;
}) {
const [session] = await db.select().from(playSessions).where(eq(playSessions.id, input.sourcePlaySessionId));
if (!session) throw new Error("source play session not found");
const sessionDeviceRows = await db
.select({
sessionDeviceId: sessionDevices.id,
slotLabel: sessionDevices.slotLabel,
bleName: devices.bleName,
deviceClass: devices.deviceClass,
capabilities: devices.capabilities,
})
.from(sessionDevices)
.innerJoin(devices, eq(sessionDevices.deviceId, devices.id))
.where(eq(sessionDevices.playSessionId, input.sourcePlaySessionId));
const deviceSlots: RecordingDeviceSlot[] = sessionDeviceRows.map((row) => ({
slotLabel: row.slotLabel,
recordedBleName: row.bleName,
deviceClass: row.deviceClass,
capabilities: row.capabilities,
sourceSessionDeviceId: row.sessionDeviceId,
}));
const [recording] = await db
.insert(recordings)
.values({
sourcePlaySessionId: input.sourcePlaySessionId,
name: input.name,
description: input.description,
createdAt: Date.now(),
durationMs: session.durationMs ?? 0,
deviceSlots,
playCount: 0,
})
.returning();
return recording;
}
export async function listRecordings() {
return db.select().from(recordings).orderBy(desc(recordings.createdAt));
}
export async function listRecordingsPage(page: number, pageSize = PAGE_SIZE): Promise<Page<typeof recordings.$inferSelect>> {
const [{ count }] = await db.select({ count: sql<number>`count(*)` }).from(recordings);
const items = await db
.select()
.from(recordings)
.orderBy(desc(recordings.createdAt))
.limit(pageSize)
.offset((page - 1) * pageSize);
return { items, page, pageSize, total: count };
}
export async function getRecordingsForSession(playSessionId: number) {
return db
.select({ id: recordings.id, name: recordings.name })
.from(recordings)
.where(eq(recordings.sourcePlaySessionId, playSessionId));
}
/** Lightweight name-only lookup for page titles - avoids getRecording's event-table join. */
export async function getRecordingName(id: number): Promise<string | undefined> {
const [row] = await db.select({ name: recordings.name }).from(recordings).where(eq(recordings.id, id));
return row?.name;
}
export async function getRecording(id: number) {
const [recording] = await db.select().from(recordings).where(eq(recordings.id, id));
if (!recording) return undefined;
const events = await getEventsForSession(recording.sourcePlaySessionId);
return { recording, events };
}
export async function renameRecording(id: number, input: { name?: string; description?: string }) {
const [updated] = await db.update(recordings).set(input).where(eq(recordings.id, id)).returning();
return updated;
}
export async function deleteRecording(id: number) {
await db.delete(recordings).where(eq(recordings.id, id));
}
export async function incrementPlayCount(id: number, playedAt: number): Promise<void> {
const [existing] = await db.select().from(recordings).where(eq(recordings.id, id));
if (!existing) return;
await db
.update(recordings)
.set({ playCount: existing.playCount + 1, lastPlayedAt: playedAt })
.where(eq(recordings.id, id));
}
+4 -4
View File
@@ -11,14 +11,14 @@ export interface IncomingEvent {
durationMs?: number;
}
export async function insertEvents(playSessionId: number, events: IncomingEvent[]): Promise<void> {
export async function insertEvents(sessionId: number, events: IncomingEvent[]): Promise<void> {
if (events.length === 0) return;
const insertMany = sqlite.transaction((rows: IncomingEvent[]) => {
for (const row of rows) {
db.insert(sessionEvents)
.values({
playSessionId,
sessionId,
sessionDeviceId: row.sessionDeviceId,
tsMs: row.tsMs,
commandType: row.commandType,
@@ -33,10 +33,10 @@ export async function insertEvents(playSessionId: number, events: IncomingEvent[
insertMany(events);
}
export async function getEventsForSession(playSessionId: number) {
export async function getEventsForSession(sessionId: number) {
return db
.select()
.from(sessionEvents)
.where(eq(sessionEvents.playSessionId, playSessionId))
.where(eq(sessionEvents.sessionId, sessionId))
.orderBy(asc(sessionEvents.tsMs));
}
+178
View File
@@ -0,0 +1,178 @@
import { desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { sessions, sessionDevices, devices } from "@/lib/db/schema";
import { upsertDeviceByBleName } from "./devices";
import { getEventsForSession } from "./session-events";
import type { DeviceCapabilities } from "@/lib/db/schema";
import type { ReplayDeviceSlot } from "@/lib/buttplug/types";
import { PAGE_SIZE, type Page } from "@/lib/pagination";
export interface StartSessionDeviceInput {
slotLabel: string;
bleName: string;
deviceClass?: string | null;
capabilities?: DeviceCapabilities;
}
export interface StartSessionInput {
name?: string;
devices: StartSessionDeviceInput[];
}
/**
* Starts a live control session. Replaying an existing session does NOT go
* through here - it just plays back the source session's already-recorded
* events against newly-mapped devices (see components/sessions/ReplayPlayer)
* and bumps the source's playCount/lastPlayedAt (incrementSessionPlayCount)
* without creating a session or duplicate events of its own.
*/
export async function startSession(input: StartSessionInput) {
const now = Date.now();
const [session] = await db
.insert(sessions)
.values({
kind: "live",
name: input.name,
status: "active",
startedAt: now,
})
.returning();
const sessionDeviceRows = [];
for (const d of input.devices) {
const device = await upsertDeviceByBleName({
bleName: d.bleName,
deviceClass: d.deviceClass,
capabilities: d.capabilities,
});
const [sessionDevice] = await db
.insert(sessionDevices)
.values({
sessionId: session.id,
deviceId: device.id,
slotLabel: d.slotLabel,
connectedAt: now,
})
.returning();
sessionDeviceRows.push(sessionDevice);
}
return { session, sessionDevices: sessionDeviceRows };
}
export async function endSession(
id: number,
input: { status: "completed" | "aborted" },
) {
const [existing] = await db.select().from(sessions).where(eq(sessions.id, id));
if (!existing) return undefined;
const endedAt = Date.now();
const durationMs = endedAt - existing.startedAt;
await db
.update(sessionDevices)
.set({ disconnectedAt: endedAt })
.where(eq(sessionDevices.sessionId, id));
const [updated] = await db
.update(sessions)
.set({ endedAt, durationMs, status: input.status })
.where(eq(sessions.id, id))
.returning();
return updated;
}
export async function listSessions() {
return db.select().from(sessions).orderBy(sessions.startedAt);
}
export async function listSessionsPage(page: number, pageSize = PAGE_SIZE): Promise<Page<typeof sessions.$inferSelect>> {
const [{ count }] = await db.select({ count: sql<number>`count(*)` }).from(sessions);
const items = await db
.select()
.from(sessions)
.orderBy(desc(sessions.startedAt))
.limit(pageSize)
.offset((page - 1) * pageSize);
return { items, page, pageSize, total: count };
}
/** Lightweight name-only lookup for page titles - avoids getSessionDetail's device join. */
export async function getSessionName(id: number): Promise<string | null | undefined> {
const [row] = await db.select({ name: sessions.name }).from(sessions).where(eq(sessions.id, id));
return row?.name;
}
export async function getSessionDetail(id: number) {
const [session] = await db.select().from(sessions).where(eq(sessions.id, id));
if (!session) return undefined;
const sessionDeviceRows = await db
.select({
id: sessionDevices.id,
slotLabel: sessionDevices.slotLabel,
connectedAt: sessionDevices.connectedAt,
disconnectedAt: sessionDevices.disconnectedAt,
deviceId: devices.id,
deviceDisplayName: devices.displayName,
deviceBleName: devices.bleName,
})
.from(sessionDevices)
.innerJoin(devices, eq(sessionDevices.deviceId, devices.id))
.where(eq(sessionDevices.sessionId, id));
const replayedFromName = session.replayedSessionId ? await getSessionName(session.replayedSessionId) : undefined;
return { session, devices: sessionDeviceRows, replayedFromName };
}
/** Snapshot of a session's devices, shaped for the replay device-remap UI - computed live
* from session_devices/devices, not a frozen copy (see ReplayDeviceSlot). */
export async function getSessionForReplay(id: number) {
const [session] = await db.select().from(sessions).where(eq(sessions.id, id));
if (!session) return undefined;
const deviceSlotRows = await db
.select({
sessionDeviceId: sessionDevices.id,
slotLabel: sessionDevices.slotLabel,
bleName: devices.bleName,
deviceClass: devices.deviceClass,
capabilities: devices.capabilities,
})
.from(sessionDevices)
.innerJoin(devices, eq(sessionDevices.deviceId, devices.id))
.where(eq(sessionDevices.sessionId, id));
const deviceSlots: ReplayDeviceSlot[] = deviceSlotRows.map((row) => ({
slotLabel: row.slotLabel,
recordedBleName: row.bleName,
deviceClass: row.deviceClass,
capabilities: row.capabilities,
sourceSessionDeviceId: row.sessionDeviceId,
}));
const events = await getEventsForSession(id);
return { session, deviceSlots, events };
}
export async function renameSession(id: number, input: { name?: string; description?: string }) {
const [updated] = await db.update(sessions).set(input).where(eq(sessions.id, id)).returning();
return updated;
}
export async function incrementSessionPlayCount(id: number, playedAt: number): Promise<void> {
const [existing] = await db.select().from(sessions).where(eq(sessions.id, id));
if (!existing) return;
await db
.update(sessions)
.set({ playCount: existing.playCount + 1, lastPlayedAt: playedAt })
.where(eq(sessions.id, id));
}
export async function deleteSession(id: number) {
await db.delete(sessions).where(eq(sessions.id, id));
}
+12 -42
View File
@@ -1,26 +1,19 @@
import { sql, eq, and, ne } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { playSessions, sessionDevices, sessionEvents, devices, recordings } from "@/lib/db/schema";
import { sessions, sessionDevices, sessionEvents, devices } from "@/lib/db/schema";
export async function getSessionsSummary() {
const [totals] = await db
.select({
count: sql<number>`count(*)`,
totalDurationMs: sql<number>`coalesce(sum(${playSessions.durationMs}), 0)`,
avgDurationMs: sql<number>`coalesce(avg(${playSessions.durationMs}), 0)`,
totalDurationMs: sql<number>`coalesce(sum(${sessions.durationMs}), 0)`,
avgDurationMs: sql<number>`coalesce(avg(${sessions.durationMs}), 0)`,
// How many times sessions have been replayed - replaying itself creates no
// session of its own, it just bumps the source session's playCount.
totalReplays: sql<number>`coalesce(sum(${sessions.playCount}), 0)`,
})
.from(playSessions)
.where(eq(playSessions.status, "completed"));
const byKind = await db
.select({
kind: playSessions.kind,
count: sql<number>`count(*)`,
totalDurationMs: sql<number>`coalesce(sum(${playSessions.durationMs}), 0)`,
})
.from(playSessions)
.where(eq(playSessions.status, "completed"))
.groupBy(playSessions.kind);
.from(sessions)
.where(eq(sessions.status, "completed"));
const durationPerDevice = await db
.select({
@@ -33,10 +26,10 @@ export async function getSessionsSummary() {
.innerJoin(devices, eq(sessionDevices.deviceId, devices.id))
.groupBy(devices.id);
return { ...totals, byKind, durationPerDevice };
return { ...totals, durationPerDevice };
}
export async function getSessionTimeline(playSessionId: number, bucketMs = 1000) {
export async function getSessionTimeline(sessionId: number, bucketMs = 1000) {
// Reuse the same expression object (not a `sql`bucket`` alias reference)
// in groupBy/orderBy - drizzle doesn't emit a literal `AS bucket` that
// SQLite's GROUP BY/ORDER BY could resolve a bare "bucket" identifier
@@ -53,7 +46,7 @@ export async function getSessionTimeline(playSessionId: number, bucketMs = 1000)
})
.from(sessionEvents)
.innerJoin(sessionDevices, eq(sessionEvents.sessionDeviceId, sessionDevices.id))
.where(and(eq(sessionEvents.playSessionId, playSessionId), ne(sessionEvents.commandType, "stop")))
.where(and(eq(sessionEvents.sessionId, sessionId), ne(sessionEvents.commandType, "stop")))
.groupBy(bucket, sessionEvents.sessionDeviceId)
.orderBy(bucket);
}
@@ -64,7 +57,7 @@ export async function getDeviceUsageStats() {
deviceId: devices.id,
displayName: devices.displayName,
bleName: devices.bleName,
sessionCount: sql<number>`count(distinct ${sessionDevices.playSessionId})`,
sessionCount: sql<number>`count(distinct ${sessionDevices.sessionId})`,
totalActiveMs: sql<number>`coalesce(sum(coalesce(${sessionDevices.disconnectedAt}, ${sessionDevices.connectedAt}) - ${sessionDevices.connectedAt}), 0)`,
lastUsedAt: sql<number | null>`max(${sessionDevices.connectedAt})`,
})
@@ -84,26 +77,3 @@ export async function getDeviceCommandCounts() {
.leftJoin(sessionEvents, eq(sessionEvents.sessionDeviceId, sessionDevices.id))
.groupBy(devices.id);
}
export async function getRecordingLibraryStats() {
const [totals] = await db
.select({
count: sql<number>`count(*)`,
avgDurationMs: sql<number>`coalesce(avg(${recordings.durationMs}), 0)`,
totalPlayCount: sql<number>`coalesce(sum(${recordings.playCount}), 0)`,
})
.from(recordings);
const list = await db
.select({
id: recordings.id,
name: recordings.name,
durationMs: recordings.durationMs,
playCount: recordings.playCount,
lastPlayedAt: recordings.lastPlayedAt,
})
.from(recordings)
.orderBy(sql`${recordings.playCount} desc`);
return { ...totals, list };
}
+15 -34
View File
@@ -21,11 +21,13 @@ export const devices = sqliteTable("devices", {
lastConnectedAt: integer("last_connected_at"),
});
export const playSessions = sqliteTable("play_sessions", {
export const sessions = sqliteTable("sessions", {
id: integer("id").primaryKey({ autoIncrement: true }),
name: text("name"),
description: text("description"),
kind: text("kind", { enum: ["live", "replay"] }).notNull(),
replayedRecordingId: integer("replayed_recording_id").references((): AnySQLiteColumn => recordings.id, {
// Self-referencing: which session's events this session replayed, if any.
replayedSessionId: integer("replayed_session_id").references((): AnySQLiteColumn => sessions.id, {
onDelete: "set null",
}),
status: text("status", { enum: ["active", "completed", "aborted"] }).notNull().default("active"),
@@ -33,15 +35,20 @@ export const playSessions = sqliteTable("play_sessions", {
endedAt: integer("ended_at"),
durationMs: integer("duration_ms"),
notes: text("notes"),
// How many times (and when) this session's events have been replayed -
// any completed session can be a replay source, there's no separate
// "saved recording" concept anymore.
playCount: integer("play_count").notNull().default(0),
lastPlayedAt: integer("last_played_at"),
});
export const sessionDevices = sqliteTable(
"session_devices",
{
id: integer("id").primaryKey({ autoIncrement: true }),
playSessionId: integer("play_session_id")
sessionId: integer("session_id")
.notNull()
.references(() => playSessions.id, { onDelete: "cascade" }),
.references(() => sessions.id, { onDelete: "cascade" }),
deviceId: integer("device_id")
.notNull()
.references(() => devices.id, { onDelete: "restrict" }),
@@ -49,16 +56,16 @@ export const sessionDevices = sqliteTable(
connectedAt: integer("connected_at").notNull(),
disconnectedAt: integer("disconnected_at"),
},
(table) => [index("session_devices_play_session_id_idx").on(table.playSessionId)],
(table) => [index("session_devices_session_id_idx").on(table.sessionId)],
);
export const sessionEvents = sqliteTable(
"session_events",
{
id: integer("id").primaryKey({ autoIncrement: true }),
playSessionId: integer("play_session_id")
sessionId: integer("session_id")
.notNull()
.references(() => playSessions.id, { onDelete: "cascade" }),
.references(() => sessions.id, { onDelete: "cascade" }),
sessionDeviceId: integer("session_device_id")
.notNull()
.references(() => sessionDevices.id, { onDelete: "cascade" }),
@@ -72,33 +79,7 @@ export const sessionEvents = sqliteTable(
rawPayload: text("raw_payload", { mode: "json" }),
},
(table) => [
index("session_events_session_ts_idx").on(table.playSessionId, table.tsMs),
index("session_events_session_ts_idx").on(table.sessionId, table.tsMs),
index("session_events_session_device_idx").on(table.sessionDeviceId),
],
);
export interface RecordingDeviceSlot {
slotLabel: string;
recordedBleName: string;
deviceClass: string | null;
capabilities: DeviceCapabilities | null;
/** The original session_devices.id this slot was captured from - lets the
* replay UI map a chosen live device back to this slot's session_events. */
sourceSessionDeviceId: number;
}
export const recordings = sqliteTable("recordings", {
id: integer("id").primaryKey({ autoIncrement: true }),
// A recording is a thin pointer over an already-captured play_session, not
// a duplicated event pipeline - see lib/db/queries/recordings.ts for why.
sourcePlaySessionId: integer("source_play_session_id")
.notNull()
.references(() => playSessions.id, { onDelete: "restrict" }),
name: text("name").notNull(),
description: text("description"),
createdAt: integer("created_at").notNull(),
durationMs: integer("duration_ms").notNull(),
deviceSlots: text("device_slots", { mode: "json" }).$type<RecordingDeviceSlot[]>().notNull(),
playCount: integer("play_count").notNull().default(0),
lastPlayedAt: integer("last_played_at"),
});