scaling-swarms / backend /src /shared /embed-versions.ts
tfrere's picture
tfrere HF Staff
Cursor
feat(mcp): chart and publish tools, structured errors, JSON 404s
2525af6
Raw History Blame Contribute Delete
7.14 kB
/**
* Version history of every embed, shared by all collaborators through
* `Y.Map("embed-versions")` (src -> Y.Array of versions, oldest first).
* Used by the Embed Studio and by the MCP embed tools.
*
* No runtime Yjs import on purpose: the frontend and backend bundle their
* own Yjs and its classes must not be mixed, so the caller passes its
* Y.Array constructor (see createEmbedVersionStore in each package).
*
* One version per agent turn: every createEmbed / patchEmbed of the same
* turn updates that turn's version instead of stacking a new one. Restoring
* never rewrites history: it appends a copy of the old version, so the
* history stays linear and every state can be reached again.
*/
export type EmbedVersionKind = "initial" | "agent" | "restore" | "undo" | "tweak";
export interface EmbedVersion {
/** 1-based, monotonic per embed. */
n: number;
html: string;
/** Epoch ms of the last write into this version. */
at: number;
kind: EmbedVersionKind;
author?: string;
/** Id of the user message that started the agent turn. */
turnId?: string;
/** For restore / undo: the version that was copied. */
from?: number;
note?: string;
}
export interface RecordMeta {
kind: EmbedVersionKind;
author?: string;
turnId?: string;
from?: number;
note?: string;
at?: number;
}
/**
* Kept per embed. Older versions are dropped; Yjs garbage-collects the
* content of deleted items, so pruning keeps the document small.
*/
export const MAX_VERSIONS_PER_EMBED = 20;
export const EMBED_VERSIONS_MAP = "embed-versions";
/** The parts of Y.Array the store uses. */
export interface VersionArray {
readonly length: number;
get(index: number): EmbedVersion;
toArray(): EmbedVersion[];
push(items: EmbedVersion[]): void;
delete(index: number, length: number): void;
}
interface VersionRoot {
get(key: string): VersionArray | undefined;
set(key: string, value: VersionArray): unknown;
delete(key: string): void;
observeDeep(f: (events: any[]) => void): void;
unobserveDeep(f: (events: any[]) => void): void;
}
export interface VersionDoc {
getMap(name: string): unknown;
transact(fn: () => void, origin?: unknown): void;
}
export interface VersionStoreOptions {
max?: number;
/** Transaction origin for writes (the MCP agent's undo origin). */
origin?: unknown;
}
export function createEmbedVersionStoreWith(
newArray: () => VersionArray,
ydoc: VersionDoc,
opts: VersionStoreOptions = {},
) {
const max = opts.max ?? MAX_VERSIONS_PER_EMBED;
const root = ydoc.getMap(EMBED_VERSIONS_MAP) as VersionRoot;
const transact = (fn: () => void) => ydoc.transact(fn, opts.origin);
function arrayFor(src: string, create: boolean): VersionArray | null {
const existing = root.get(src);
if (existing || !create) return existing ?? null;
const arr = newArray();
root.set(src, arr);
return arr;
}
function list(src: string): EmbedVersion[] {
return arrayFor(src, false)?.toArray() ?? [];
}
function latest(src: string): EmbedVersion | null {
const arr = arrayFor(src, false);
return arr && arr.length ? arr.get(arr.length - 1) : null;
}
function get(src: string, n: number): EmbedVersion | null {
return list(src).find((v) => v.n === n) ?? null;
}
function forTurn(src: string, turnId: string): EmbedVersion | null {
const all = list(src);
for (let i = all.length - 1; i >= 0; i--) if (all[i].turnId === turnId) return all[i];
return null;
}
/**
* Record `html` as the newest version. Returns the version written, or null
* when nothing changed (same html as the latest version).
*/
function record(src: string, html: string, meta: RecordMeta): EmbedVersion | null {
if (!src || !html) return null;
const at = meta.at ?? Date.now();
let written = null as EmbedVersion | null;
transact(() => {
const arr = arrayFor(src, true)!;
const last = arr.length ? arr.get(arr.length - 1) : null;
if (last && last.html === html) return;
if (last && meta.turnId && last.turnId === meta.turnId && last.kind === meta.kind) {
written = { ...last, html, at };
arr.delete(arr.length - 1, 1);
arr.push([written]);
return;
}
written = {
n: (last?.n ?? 0) + 1,
html,
at,
kind: meta.kind,
...(meta.author ? { author: meta.author } : {}),
...(meta.turnId ? { turnId: meta.turnId } : {}),
...(meta.from !== undefined ? { from: meta.from } : {}),
...(meta.note ? { note: meta.note } : {}),
};
arr.push([written]);
if (arr.length > max) arr.delete(0, arr.length - max);
});
return written;
}
/** Append a copy of version `n` as the newest version. */
function restore(
src: string,
n: number,
meta: { author?: string; kind?: "restore" | "undo" } = {},
): EmbedVersion | null {
const target = get(src, n);
if (!target) return null;
const kind = meta.kind ?? "restore";
return record(src, target.html, {
kind,
author: meta.author,
from: n,
note: kind === "undo" ? `Undid back to v${n}` : `Restored v${n}`,
});
}
/**
* The version "Undo last change" goes back to: the newest version older
* than the one the current state came from, with different content.
* Repeated undos keep walking back instead of bouncing between two states.
*/
function undoTarget(src: string): EmbedVersion | null {
const all = list(src);
const last = all[all.length - 1];
if (!last) return null;
const base = (last.kind === "undo" || last.kind === "restore") && last.from !== undefined ? last.from : last.n;
for (let i = all.length - 1; i >= 0; i--) {
const v = all[i];
if (v.n < base && v.html !== last.html) return v;
}
return null;
}
function undo(src: string, author?: string): EmbedVersion | null {
const target = undoTarget(src);
return target ? restore(src, target.n, { author, kind: "undo" }) : null;
}
function rename(oldSrc: string, newSrc: string) {
const arr = root.get(oldSrc);
if (!arr || oldSrc === newSrc) return;
const items = arr.toArray();
transact(() => {
const next = newArray();
next.push(items);
root.set(newSrc, next);
root.delete(oldSrc);
});
}
function remove(src: string) {
transact(() => root.delete(src));
}
/** Fires on any change to `src`'s history. Returns an unsubscribe function. */
function observe(src: string, callback: () => void) {
const handler = (events: { target: unknown; keysChanged?: Set<string> }[]) => {
for (const ev of events) {
if (ev.target === root) {
if (ev.keysChanged?.has(src)) return callback();
} else if (root.get(src) === ev.target) {
return callback();
}
}
};
root.observeDeep(handler);
return () => root.unobserveDeep(handler);
}
return { list, latest, get, forTurn, record, restore, undoTarget, undo, rename, remove, observe };
}
export type EmbedVersionStore = ReturnType<typeof createEmbedVersionStoreWith>;