Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(mastery): add live v2 frontend client

Bingxi Zhao (Frank)ac8940f33e87
diff --git a/web/hooks/useMasteryPathActivity.ts b/web/hooks/useMasteryPathActivity.ts
index c5c90e060..f1170df47 100644
--- a/web/hooks/useMasteryPathActivity.ts
+++ b/web/hooks/useMasteryPathActivity.ts
@@ -2,71 +2,125 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { fetchProgressEvents, type MasteryEvent } from "@/lib/learning-api";
+import {
+ fetchProgressEvents,
+ type MasteryEvent,
+} from "@/lib/learning-api";
+import {
+ MasteryTopicSocket,
+ type MasterySocketEnvelope,
+} from "@/lib/mastery-ws";
-/**
- * Follow a mastery path while it changes underneath you.
- *
- * Tutoring happens in the chat, usually in another tab, so a snapshot taken
- * when the dashboard opened goes stale within a turn. Every committed change
- * to a path already emits an event numbered by the path's revision, so this
- * polls for events *after* the last revision it saw: a quiet path costs one
- * indexed query returning nothing, and a busy one streams in order with no
- * gaps and no duplicates.
- *
- * `revision` is the single "the path moved" signal — render off the event list
- * and re-read anything else (the map, the summary list) when it changes.
- * Polling pauses while the tab is hidden and catches up the moment it is
- * visible again, so a backgrounded dashboard costs nothing.
- */
-const DEFAULT_INTERVAL_MS = 4000;
+export type MasteryConnectionState = "connecting" | "live" | "offline";
+
+interface SocketStatus {
+ pathId: string | null;
+ connection: MasteryConnectionState;
+ error: string | null;
+}
export interface MasteryPathActivity {
events: MasteryEvent[];
revision: number;
- /** Poll now instead of waiting for the next tick. */
+ /** Changes for same-revision signals such as a newly bound session. */
+ signal: number;
+ connection: MasteryConnectionState;
+ error: string | null;
+ /** Reconcile from durable storage immediately. */
refresh: () => void;
}
-/** The feed is stamped with the path it belongs to, so switching paths shows
- * nothing rather than the previous path's history for one render. */
+/** The feed is stamped with its path so a route switch never flashes history. */
export interface ActivityFeed {
pathId: string | null;
events: MasteryEvent[];
revision: number;
+ signal: number;
}
export const EMPTY_FEED: ActivityFeed = {
pathId: null,
events: [],
revision: 0,
+ signal: 0,
};
-/**
- * Fold one polled batch into the feed.
- *
- * `since` is what the request asked for, and it decides append vs replace: a
- * batch read from revision 0 is the path's whole history, so it *replaces*
- * rather than doubling anything already on screen. Keeping that rule here (and
- * not in the effect) is what makes a forced refresh safe to trigger from
- * anywhere.
- */
+function eventIdentity(event: MasteryEvent): string {
+ return event.id
+ ? `id:${event.id}`
+ : [
+ event.revision,
+ event.event_type,
+ event.session_id,
+ event.turn_id,
+ event.created_at,
+ ].join(":");
+}
+
+/** Fold durable events into one sorted, duplicate-free per-topic feed. */
export function mergeEventBatch(
previous: ActivityFeed,
pathId: string,
since: number,
batch: MasteryEvent[],
+ headRevision?: number,
): ActivityFeed {
- if (batch.length === 0) return previous;
+ if (batch.length === 0 && headRevision === undefined) return previous;
const continues = since > 0 && previous.pathId === pathId;
+ const candidates = continues ? [...previous.events, ...batch] : batch;
+ const seen = new Set<string>();
+ const events = candidates
+ .filter((event) => {
+ const identity = eventIdentity(event);
+ if (seen.has(identity)) return false;
+ seen.add(identity);
+ return true;
+ })
+ .sort((left, right) => left.revision - right.revision || left.id - right.id);
+ const revision = Math.max(
+ continues ? previous.revision : 0,
+ latestRevision(since, events),
+ headRevision ?? 0,
+ );
+
+ if (
+ previous.pathId === pathId &&
+ previous.events.length === events.length &&
+ previous.events.every((event, index) => event === events[index]) &&
+ previous.revision === revision
+ ) {
+ return previous;
+ }
return {
pathId,
- events: continues ? [...previous.events, ...batch] : batch,
- revision: latestRevision(since, batch),
+ events,
+ revision,
+ signal: previous.pathId === pathId ? previous.signal : 0,
};
}
-/** Where the next read should start from after consuming ``batch``. */
+export function mergeSocketEnvelope(
+ previous: ActivityFeed,
+ pathId: string,
+ envelope: MasterySocketEnvelope,
+): ActivityFeed {
+ const since = previous.pathId === pathId ? previous.revision : 0;
+ const merged = mergeEventBatch(
+ previous,
+ pathId,
+ since,
+ envelope.events,
+ envelope.revision,
+ );
+ return {
+ ...merged,
+ // A session binding is committed product state but does not rewrite the
+ // learning aggregate. Keep a distinct signal so session lists still react.
+ signal: (previous.pathId === pathId ? previous.signal : 0) + 1,
+ };
+}
+
+/** Where the next durable read should start after consuming a batch. */
export function latestRevision(since: number, batch: MasteryEvent[]): number {
return batch.reduce(
(highest, event) => Math.max(highest, event.revision),
@@ -74,68 +128,148 @@ export function latestRevision(since: number, batch: MasteryEvent[]): number {
);
}
+/**
+ * Follow one topic via its dedicated WebSocket.
+ *
+ * The socket registers before server replay, resumes from the last committed
+ * revision, and reconnects with exponential backoff. Focus, visibility and an
+ * explicit refresh also reconcile against SQLite over REST, so a proxy that
+ * cannot upgrade WebSockets degrades to fresh-on-return instead of stale UI.
+ */
export function useMasteryPathActivity(
pathId: string | null,
- options?: { intervalMs?: number },
): MasteryPathActivity {
- const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
const [feed, setFeed] = useState<ActivityFeed>(EMPTY_FEED);
- // The read cursor, carried in a ref so a tick never closes over a stale
- // revision and a new batch never restarts the polling effect. It is stamped
- // with its path, so a path switch reads from the beginning again without
- // anything having to reset it — and so a forced refresh resumes rather than
- // re-reading a history the feed already holds.
+ const [socketStatus, setSocketStatus] = useState<SocketStatus>({
+ pathId: null,
+ connection: "offline",
+ error: null,
+ });
const cursorRef = useRef<{ pathId: string | null; revision: number }>({
pathId: null,
revision: 0,
});
- const [pollToken, setPollToken] = useState(0);
+ const reconcileRef = useRef<() => void>(() => {});
- const refresh = useCallback(() => setPollToken((token) => token + 1), []);
+ const refresh = useCallback(() => reconcileRef.current(), []);
useEffect(() => {
if (!pathId) return;
- let cancelled = false;
- const controller = new AbortController();
-
- const poll = async () => {
- if (
- typeof document !== "undefined" &&
- document.visibilityState !== "visible"
- )
- return;
+
+ let disposed = false;
+ let reconciliation: AbortController | null = null;
+ const initialRevision =
+ cursorRef.current.pathId === pathId ? cursorRef.current.revision : 0;
+ cursorRef.current = { pathId, revision: initialRevision };
+
+ const reconcile = () => {
+ if (disposed) return;
+ reconciliation?.abort();
+ reconciliation = new AbortController();
const since =
cursorRef.current.pathId === pathId ? cursorRef.current.revision : 0;
- try {
- const batch = await fetchProgressEvents(pathId, since, {
- signal: controller.signal,
+ void fetchProgressEvents(pathId, since, {
+ signal: reconciliation.signal,
+ })
+ .then((batch) => {
+ if (disposed) return;
+ const revision = latestRevision(since, batch);
+ cursorRef.current = { pathId, revision };
+ setFeed((previous) =>
+ mergeEventBatch(previous, pathId, since, batch, revision),
+ );
+ })
+ .catch((reason: unknown) => {
+ if (disposed || reconciliation?.signal.aborted) return;
+ setSocketStatus({
+ pathId,
+ connection: "offline",
+ error:
+ reason instanceof Error
+ ? reason.message
+ : "Live update unavailable",
+ });
});
- if (cancelled || batch.length === 0) return;
- cursorRef.current = { pathId, revision: latestRevision(since, batch) };
- setFeed((previous) => mergeEventBatch(previous, pathId, since, batch));
- } catch {
- // A path can be deleted or reset mid-poll; the next tick recovers.
- }
};
+ reconcileRef.current = reconcile;
- void poll();
- const timer = setInterval(poll, intervalMs);
- // A hidden tab may have missed many ticks — catch up on return rather than
- // making the learner wait out a full interval.
- const pollWhenVisible = () => {
- if (document.visibilityState === "visible") void poll();
+ const socket = new MasteryTopicSocket(
+ pathId,
+ {
+ onEnvelope: (envelope) => {
+ if (disposed) return;
+ cursorRef.current = {
+ pathId,
+ revision: Math.max(cursorRef.current.revision, envelope.revision),
+ };
+ setFeed((previous) =>
+ mergeSocketEnvelope(previous, pathId, envelope),
+ );
+ },
+ onConnecting: () => {
+ if (!disposed) {
+ setSocketStatus({ pathId, connection: "connecting", error: null });
+ }
+ },
+ onLive: () => {
+ if (disposed) return;
+ setSocketStatus({ pathId, connection: "live", error: null });
+ },
+ onDisconnect: () => {
+ if (disposed) return;
+ setSocketStatus({ pathId, connection: "offline", error: null });
+ reconcile();
+ },
+ onError: (message) => {
+ if (disposed) return;
+ setSocketStatus({ pathId, connection: "offline", error: message });
+ },
+ },
+ initialRevision,
+ {
+ shouldReconnect: () =>
+ !disposed &&
+ (typeof document === "undefined" ||
+ document.visibilityState === "visible"),
+ },
+ );
+ socket.start();
+
+ const wake = () => {
+ if (document.visibilityState !== "visible") return;
+ socket.wake();
+ reconcile();
};
- window.addEventListener("focus", pollWhenVisible);
- document.addEventListener("visibilitychange", pollWhenVisible);
+ window.addEventListener("focus", wake);
+ window.addEventListener("online", wake);
+ document.addEventListener("visibilitychange", wake);
+
return () => {
- cancelled = true;
- controller.abort();
- clearInterval(timer);
- window.removeEventListener("focus", pollWhenVisible);
- document.removeEventListener("visibilitychange", pollWhenVisible);
+ disposed = true;
+ reconciliation?.abort();
+ socket.stop();
+ reconcileRef.current = () => {};
+ window.removeEventListener("focus", wake);
+ window.removeEventListener("online", wake);
+ document.removeEventListener("visibilitychange", wake);
};
- }, [pathId, intervalMs, pollToken]);
+ }, [pathId]);
const current = feed.pathId === pathId ? feed : EMPTY_FEED;
- return { events: current.events, revision: current.revision, refresh };
+ const status =
+ socketStatus.pathId === pathId
+ ? socketStatus
+ : {
+ pathId,
+ connection: pathId ? ("connecting" as const) : ("offline" as const),
+ error: null,
+ };
+ return {
+ events: current.events,
+ revision: current.revision,
+ signal: current.signal,
+ connection: status.connection,
+ error: status.error,
+ refresh,
+ };
}
diff --git a/web/lib/learning-api.ts b/web/lib/learning-api.ts
index 657d7f994..115c9c5a1 100644
--- a/web/lib/learning-api.ts
+++ b/web/lib/learning-api.ts
@@ -66,6 +66,8 @@ export interface MapKnowledgePoint {
type: string;
status: ObjectiveStatus;
mastery: number;
+ mastery_source: "system" | "learner" | "";
+ override_note: string;
}
export interface MapModule {
@@ -200,6 +202,9 @@ export interface ObjectiveReport {
status: ObjectiveStatus;
gate: "quantitative" | "qualitative";
mastered: boolean;
+ assessed_mastered: boolean;
+ mastery_source: "system" | "learner" | "";
+ override_note: string;
mastery: number;
threshold: number;
attempts: ObjectiveAttempt[];
@@ -312,3 +317,213 @@ export async function generateModulesFromNotebook(
throw new Error(`Failed to generate modules from notebook: ${res.status}`);
return res.json();
}
+
+// ── Mastery Path V2 product surface ──────────────────────────────────────
+
+export type TopicSourceKind =
+ | "goal"
+ | "book"
+ | "notebook"
+ | "knowledge_base"
+ | "file"
+ | "chat";
+
+export interface TopicSource {
+ id: string;
+ kind: TopicSourceKind;
+ source_id: string;
+ label: string;
+ excerpt: string;
+ position: number;
+ available: boolean;
+ metadata: Record<string, unknown>;
+ created_at: number;
+}
+
+export interface TopicSourceInput {
+ id?: string;
+ kind: TopicSourceKind;
+ source_id?: string;
+ label: string;
+ excerpt?: string;
+ available?: boolean;
+ metadata?: Record<string, unknown>;
+}
+
+export interface TopicMetadata {
+ path_id: string;
+ goal: string;
+ description: string;
+ emoji: string;
+ map_seed: number;
+ status: "active" | "archived";
+ created_at: number;
+ updated_at: number;
+}
+
+export interface TopicReview {
+ id: string;
+ knowledge_point_id: string;
+ knowledge_point_name: string;
+ knowledge_type: string;
+ due_at: number;
+ priority: number;
+ due: boolean;
+}
+
+export interface MasteryTopic {
+ path_id: string;
+ name: string;
+ metadata: TopicMetadata;
+ sources: TopicSource[];
+ path_revision: number;
+ next: NextStep;
+ map: MasteryMap;
+ reviews: TopicReview[];
+ session_count: number;
+ updated_at: number;
+}
+
+export interface TopicDraft {
+ description: string;
+ modules: ModuleInit[];
+}
+
+export interface GenerateTopicInput {
+ name: string;
+ goal: string;
+ sources: TopicSourceInput[];
+}
+
+export interface CreateTopicInput extends GenerateTopicInput {
+ description?: string;
+ emoji?: string;
+ modules: ModuleInit[];
+}
+
+export interface TopicSession {
+ session_id: string;
+ title: string;
+ created_at: number;
+ updated_at: number;
+ status: string;
+ active_turn_id: string;
+ pinned: boolean;
+ archived: boolean;
+}
+
+async function masteryJson<T>(
+ path: string,
+ init?: RequestInit,
+ action = "load mastery data",
+): Promise<T> {
+ const res = await apiFetch(apiUrl(path), init);
+ if (!res.ok) {
+ let detail = "";
+ try {
+ const payload = (await res.json()) as { detail?: string };
+ detail = payload.detail ? `: ${payload.detail}` : "";
+ } catch {
+ // The status remains actionable when an upstream proxy returns HTML.
+ }
+ throw new Error(`Failed to ${action} (${res.status})${detail}`);
+ }
+ return res.json() as Promise<T>;
+}
+
+export async function fetchMasteryTopics(
+ init?: RequestInit,
+): Promise<MasteryTopic[]> {
+ const result = await masteryJson<{ topics: MasteryTopic[] }>(
+ "/api/v1/learning/topics",
+ init,
+ "load topics",
+ );
+ return result.topics;
+}
+
+export function fetchMasteryTopic(
+ pathId: string,
+ init?: RequestInit,
+): Promise<MasteryTopic> {
+ return masteryJson(
+ `/api/v1/learning/topics/${encodeURIComponent(pathId)}`,
+ init,
+ "load topic",
+ );
+}
+
+export function generateMasteryTopicDraft(
+ input: GenerateTopicInput,
+): Promise<TopicDraft> {
+ return masteryJson(
+ "/api/v1/learning/topics/draft",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ "generate learning route",
+ );
+}
+
+export function createMasteryTopic(
+ input: CreateTopicInput,
+): Promise<MasteryTopic> {
+ return masteryJson(
+ "/api/v1/learning/topics",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ },
+ "create topic",
+ );
+}
+
+export function updateMasteryTopicMap(
+ pathId: string,
+ modules: ModuleInit[],
+): Promise<MasteryTopic> {
+ return masteryJson(
+ `/api/v1/learning/topics/${encodeURIComponent(pathId)}/map`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ modules }),
+ },
+ "update route",
+ );
+}
+
+export function setMasteryObjectiveOverride(
+ pathId: string,
+ objectiveId: string,
+ mastered: boolean,
+ note = "",
+): Promise<{ status: string; path_revision: number; map: MasteryMap }> {
+ return masteryJson(
+ `/api/v1/learning/topics/${encodeURIComponent(pathId)}/objectives/${encodeURIComponent(objectiveId)}/override`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mastered, note }),
+ },
+ mastered ? "mark objective mastered" : "restore objective assessment",
+ );
+}
+
+export async function fetchMasteryTopicSessions(
+ pathId: string,
+ init?: RequestInit,
+): Promise<TopicSession[]> {
+ const result = await masteryJson<{
+ path_id: string;
+ sessions: TopicSession[];
+ }>(
+ `/api/v1/learning/topics/${encodeURIComponent(pathId)}/sessions`,
+ init,
+ "load topic sessions",
+ );
+ return result.sessions;
+}
diff --git a/web/lib/mastery-ws.ts b/web/lib/mastery-ws.ts
new file mode 100644
index 000000000..ca956119d
--- /dev/null
+++ b/web/lib/mastery-ws.ts
@@ -0,0 +1,148 @@
+import { wsUrl } from "@/lib/api";
+import {
+ ReconnectingWebSocket,
+ type ReconnectingWebSocketOptions,
+} from "@/lib/reconnecting-websocket";
+import type { MasteryEvent } from "@/lib/learning-api";
+
+export const MASTERY_WS_PATH = "/api/v1/learning/ws";
+
+export interface MasterySubscribedMessage {
+ type: "subscribed";
+ path_id: string;
+ revision: number;
+ events: MasteryEvent[];
+}
+
+export interface MasteryTopicEventMessage {
+ type: "topic_event";
+ path_id: string;
+ revision: number;
+ reason: string;
+ sequence: number;
+ events: MasteryEvent[];
+}
+
+export interface MasterySocketErrorMessage {
+ type: "error";
+ content: string;
+}
+
+export type MasterySocketMessage =
+ | MasterySubscribedMessage
+ | MasteryTopicEventMessage
+ | MasterySocketErrorMessage;
+
+export type MasterySocketEnvelope =
+ | MasterySubscribedMessage
+ | MasteryTopicEventMessage;
+
+export function masterySubscribePayload(
+ pathId: string,
+ afterRevision: number,
+): string {
+ return JSON.stringify({
+ type: "subscribe",
+ path_id: pathId,
+ after_revision: Math.max(0, Math.floor(afterRevision)),
+ });
+}
+
+export function parseMasterySocketMessage(
+ data: unknown,
+): MasterySocketMessage | null {
+ let value: unknown = data;
+ if (typeof data === "string") {
+ try {
+ value = JSON.parse(data) as unknown;
+ } catch {
+ return null;
+ }
+ }
+ if (!value || typeof value !== "object") return null;
+ const message = value as Record<string, unknown>;
+ if (message.type === "error" && typeof message.content === "string") {
+ return { type: "error", content: message.content };
+ }
+ if (
+ (message.type !== "subscribed" && message.type !== "topic_event") ||
+ typeof message.path_id !== "string" ||
+ typeof message.revision !== "number" ||
+ !Array.isArray(message.events)
+ ) {
+ return null;
+ }
+ if (message.type === "subscribed") {
+ return message as unknown as MasterySubscribedMessage;
+ }
+ if (typeof message.reason !== "string" || typeof message.sequence !== "number") {
+ return null;
+ }
+ return message as unknown as MasteryTopicEventMessage;
+}
+
+export interface MasteryTopicSocketHandlers {
+ onEnvelope: (message: MasterySocketEnvelope) => void;
+ onConnecting?: () => void;
+ onLive?: () => void;
+ onDisconnect?: () => void;
+ onError?: (message: string) => void;
+}
+
+/** One reconnecting, cursor-preserving subscription for a single topic. */
+export class MasteryTopicSocket {
+ private cursor: number;
+ private readonly transport: ReconnectingWebSocket;
+
+ constructor(
+ private readonly pathId: string,
+ private readonly handlers: MasteryTopicSocketHandlers,
+ initialRevision = 0,
+ options: ReconnectingWebSocketOptions = {},
+ ) {
+ this.cursor = Math.max(0, initialRevision);
+ this.transport = new ReconnectingWebSocket(
+ wsUrl(MASTERY_WS_PATH),
+ {
+ onOpen: () => {
+ this.handlers.onConnecting?.();
+ this.transport.send(masterySubscribePayload(this.pathId, this.cursor));
+ },
+ onMessage: (event) => this.receive(event.data),
+ onDisconnect: () => this.handlers.onDisconnect?.(),
+ onError: (error) => this.handlers.onError?.(String(error || "Socket error")),
+ },
+ options,
+ );
+ }
+
+ get revision(): number {
+ return this.cursor;
+ }
+
+ start(): void {
+ this.handlers.onConnecting?.();
+ this.transport.start();
+ }
+
+ wake(): void {
+ this.transport.wake();
+ }
+
+ stop(): void {
+ this.transport.stop();
+ }
+
+ private receive(data: unknown): void {
+ const message = parseMasterySocketMessage(data);
+ if (!message) return;
+ if (message.type === "error") {
+ this.handlers.onError?.(message.content);
+ return;
+ }
+ if (message.path_id !== this.pathId) return;
+ this.cursor = Math.max(this.cursor, message.revision);
+ this.handlers.onLive?.();
+ this.handlers.onEnvelope(message);
+ }
+}
diff --git a/web/lib/reconnecting-websocket.ts b/web/lib/reconnecting-websocket.ts
index 194898ff4..b3a6de688 100644
--- a/web/lib/reconnecting-websocket.ts
+++ b/web/lib/reconnecting-websocket.ts
@@ -13,19 +13,19 @@ export function reconnectDelayMs(
return Math.min(baseDelayMs * 2 ** Math.max(0, attempt), maxDelayMs);
}
-interface RetryScheduler {
+export interface RetryScheduler {
set(callback: () => void, delayMs: number): unknown;
clear(handle: unknown): void;
}
-interface ReconnectingWebSocketHandlers {
+export interface ReconnectingWebSocketHandlers {
onOpen?: () => void;
onMessage: (event: MessageEvent) => void;
onDisconnect?: () => void;
onError?: (error: unknown) => void;
}
-interface ReconnectingWebSocketOptions {
+export interface ReconnectingWebSocketOptions {
createSocket?: (url: string) => WebSocket;
shouldReconnect?: () => boolean;
scheduler?: RetryScheduler;
diff --git a/web/tests/mastery-path-activity.test.ts b/web/tests/mastery-path-activity.test.ts
index 15c4561b1..a215328eb 100644
--- a/web/tests/mastery-path-activity.test.ts
+++ b/web/tests/mastery-path-activity.test.ts
@@ -26,6 +26,7 @@ function feed(pathId: string, revisions: number[]): ActivityFeed {
pathId,
events: revisions.map((r) => event(r)),
revision: Math.max(0, ...revisions),
+ signal: 0,
};
}
@@ -72,3 +73,21 @@ test("the cursor never moves backwards past what was already requested", () => {
assert.equal(latestRevision(7, []), 7);
assert.equal(latestRevision(7, [event(9), event(8)]), 9);
});
+
+test("overlapping replay batches deduplicate events by durable id", () => {
+ const merged = mergeEventBatch(feed("p1", [1, 2]), "p1", 2, [
+ event(2),
+ event(3),
+ ]);
+ assert.deepEqual(
+ merged.events.map((e) => e.revision),
+ [1, 2, 3],
+ );
+});
+
+test("a socket head advances even when it carries no durable events", () => {
+ const merged = mergeEventBatch(EMPTY_FEED, "p1", 0, [], 7);
+ assert.equal(merged.pathId, "p1");
+ assert.equal(merged.revision, 7);
+ assert.deepEqual(merged.events, []);
+});
diff --git a/web/tests/mastery-ws.test.ts b/web/tests/mastery-ws.test.ts
new file mode 100644
index 000000000..839021d29
--- /dev/null
+++ b/web/tests/mastery-ws.test.ts
@@ -0,0 +1,132 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ MasteryTopicSocket,
+ masterySubscribePayload,
+ parseMasterySocketMessage,
+ type MasterySocketEnvelope,
+} from "../lib/mastery-ws";
+
+class FakeSocket {
+ readyState = 0;
+ sent: string[] = [];
+ onopen: ((event: Event) => void) | null = null;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onerror: ((event: Event) => void) | null = null;
+ onclose: ((event: CloseEvent) => void) | null = null;
+
+ open(): void {
+ this.readyState = 1;
+ this.onopen?.({} as Event);
+ }
+
+ message(payload: unknown): void {
+ this.onmessage?.({ data: JSON.stringify(payload) } as MessageEvent);
+ }
+
+ drop(): void {
+ this.readyState = 3;
+ this.onclose?.({} as CloseEvent);
+ }
+
+ close(): void {
+ if (this.readyState !== 3) this.drop();
+ }
+
+ send(payload: string): void {
+ this.sent.push(payload);
+ }
+}
+
+test("subscribe payload normalizes the durable cursor", () => {
+ assert.deepEqual(JSON.parse(masterySubscribePayload("topic-1", -9)), {
+ type: "subscribe",
+ path_id: "topic-1",
+ after_revision: 0,
+ });
+});
+
+test("socket message parser rejects malformed protocol data", () => {
+ assert.equal(parseMasterySocketMessage("not json"), null);
+ assert.equal(parseMasterySocketMessage({ type: "subscribed" }), null);
+ assert.deepEqual(
+ parseMasterySocketMessage({ type: "error", content: "Missing topic" }),
+ { type: "error", content: "Missing topic" },
+ );
+});
+
+test("topic socket reconnects with the latest server revision", () => {
+ const sockets: FakeSocket[] = [];
+ const scheduled: Array<{ callback: () => void; delay: number }> = [];
+ const envelopes: MasterySocketEnvelope[] = [];
+ const states: string[] = [];
+ const client = new MasteryTopicSocket(
+ "topic-1",
+ {
+ onEnvelope: (message) => envelopes.push(message),
+ onConnecting: () => states.push("connecting"),
+ onLive: () => states.push("live"),
+ onDisconnect: () => states.push("offline"),
+ },
+ 4,
+ {
+ createSocket: () => {
+ const socket = new FakeSocket();
+ sockets.push(socket);
+ return socket as unknown as WebSocket;
+ },
+ scheduler: {
+ set: (callback, delay) => {
+ scheduled.push({ callback, delay });
+ return scheduled.at(-1)!;
+ },
+ clear: () => {},
+ },
+ },
+ );
+
+ client.start();
+ sockets[0].open();
+ assert.deepEqual(JSON.parse(sockets[0].sent[0]), {
+ type: "subscribe",
+ path_id: "topic-1",
+ after_revision: 4,
+ });
+
+ sockets[0].message({
+ type: "subscribed",
+ path_id: "topic-1",
+ revision: 7,
+ events: [],
+ });
+ assert.equal(client.revision, 7);
+ assert.equal(envelopes.length, 1);
+
+ // Messages for a formerly selected path cannot contaminate the active feed.
+ sockets[0].message({
+ type: "topic_event",
+ path_id: "topic-2",
+ revision: 99,
+ reason: "path.saved",
+ sequence: 1,
+ events: [],
+ });
+ assert.equal(client.revision, 7);
+ assert.equal(envelopes.length, 1);
+
+ sockets[0].drop();
+ assert.equal(scheduled[0].delay, 250);
+ scheduled[0].callback();
+ sockets[1].open();
+ assert.equal(JSON.parse(sockets[1].sent[0]).after_revision, 7);
+ assert.deepEqual(states, [
+ "connecting",
+ "connecting",
+ "live",
+ "offline",
+ "connecting",
+ ]);
+
+ client.stop();
+});