Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309// Device identity for change attribution. Loro tags every change with a peer// id, but a fresh LoroDoc picks a random one per open, so on its own it cannot// answer "which device made this change". Here we derive one stable peer id// per device from its persistent deviceId, and keep a peer -> device map so// the history view can name any peer it meets, including remote ones pulled in// over sync. Each device also publishes its own entry into a shared `devices`// map in the workspace doc so a peer met only through sync isn't "Unknown".
import { LoroMap } from 'loro-crdt';import type { LoroDoc } from 'loro-crdt';import * as db from './db';import { newId } from './id';import { isTauri } from '../platform';import { m } from '@web/paraglide/messages';
// The replica's persistent identity, minted once and kept in local meta.export async function deviceId(): Promise<string> { let id = await db.getMeta<string>('deviceId'); if (!id) { id = newId(); await db.setMeta('deviceId', id); } return id;}
export interface DeviceInfo { name: string; kind: 'desktop' | 'mobile' | 'tablet'; // The deviceId of the replica, when known (always set for the local one). deviceId?: string; firstSeen: number;}
type PeerRegistry = Record<string, DeviceInfo>;
const REGISTRY_KEY = 'peerRegistry';const DEVICE_NAME_KEY = 'deviceName';
// The fixed peer id the server seed writes its docs under (must match// SEED_PEER_ID in apps/api/src/seed.ts). Naming it in the registry keeps the// example workspace's history from reading as "Unknown device".const SEED_PEER_ID = '700000000000001';
// Loro peer ids are u64, but JS numbers are only exact to 2^53, and Loro// accepts a decimal string, so derive a 53-bit value from the deviceId and// pass it as a string. FNV-1a over the uuid gives a stable, well-spread id;// two devices colliding needs a 1-in-2^53 clash, which is fine for a personal// device set.function peerIdFromDeviceId(id: string): string { let hash = 0xcbf29ce4n; for (const ch of id) { hash ^= BigInt(ch.charCodeAt(0)); hash = (hash * 0x01000193n) & 0x1fffffffffffffn; // keep it inside 2^53 } // 0 is a valid but confusing peer id (Loro's default-ish); nudge off it. return (hash === 0n ? 1n : hash).toString();}
let cachedPeerId: string | null = null;
export async function localPeerId(): Promise<string> { if (cachedPeerId) return cachedPeerId; cachedPeerId = peerIdFromDeviceId(await deviceId()); return cachedPeerId;}
const BOOT_TOKEN_KEY = 'bootToken';
// Clone detection. Copying a data dir (OS restore, duplicated VM, cloned Tauri// profile) yields two live replicas with the same deviceId, hence the same Loro// peer id: both mint ops under identical (peer, counter) with different content,// which Loro cannot reconcile and never reports. On boot each replica stamps a// fresh random token into the doc under its peer id and remembers it locally. If// the token found in the doc is not the one this replica last wrote, another// replica shares its identity, so it re-mints its deviceId (and peer id) before// making any edit. Returns true when it re-minted.export async function assertUniquePeerId(doc: LoroDoc): Promise<boolean> { const peerId = await localPeerId(); const mine = await db.getMeta<string>(BOOT_TOKEN_KEY); const inDoc = readBootToken(doc, peerId);
let reminted = false; // A token we did not write means a clone is (or was) live under our id. Only // act once we have booted before (mine set); a first-ever boot legitimately // finds someone else's seed entry absent. if (mine && inDoc && inDoc !== mine) { const fresh = newId(); await db.setMeta('deviceId', fresh); cachedPeerId = null; reminted = true; }
// Stamp this boot's token under the (possibly new) peer id, in the doc and // locally, so the next boot can tell our own writes from a clone's. const token = newId(); await db.setMeta(BOOT_TOKEN_KEY, token); writeBootToken(doc, await localPeerId(), token); return reminted;}
function readBootToken(doc: LoroDoc, peerId: string): string | null { const entry = doc.getMap(DEVICES_MAP).get(peerId); if (!(entry instanceof LoroMap)) return null; const token = entry.get('boot'); return typeof token === 'string' ? token : null;}
function writeBootToken(doc: LoroDoc, peerId: string, token: string): void { const devices = doc.getMap(DEVICES_MAP); const existing = devices.get(peerId); const entry = existing instanceof LoroMap ? existing : devices.setContainer(peerId, new LoroMap()); entry.set('boot', token);}
// A human name for this device. The desktop/mobile shell knows the real// hostname; the browser has none, so we build a readable one from the platform// and let the user rename it in Settings. Resolved once, then persisted.export async function localDeviceName(): Promise<string> { const saved = await db.getMeta<string>(DEVICE_NAME_KEY); // Heal a stale browser-guess name cached before the shell name resolved: a // native shell should never be labelled "Chrome on Android". if (saved && !(isTauri() && looksLikeBrowserGuess(saved))) return saved; const name = await resolveDeviceName(); await db.setMeta(DEVICE_NAME_KEY, name); return name;}
// The "{browser} on {os}" shape produced by guessBrowserName, which must never// stick to a native shell.function looksLikeBrowserGuess(name: string): boolean { return /^(Firefox|Edge|Chrome|Safari|Browser|Navigateur|Navegador) /.test(name);}
export async function setLocalDeviceName(name: string): Promise<void> { const trimmed = name.trim(); if (!trimmed) return; await db.setMeta(DEVICE_NAME_KEY, trimmed); // Reflect the rename in the registry so history updates without a reload. await recordDevice(await localPeerId(), { name: trimmed, kind: localDeviceKind(), deviceId: await deviceId(), });}
async function resolveDeviceName(): Promise<string> { if (isTauri()) { try { const { invoke } = await import('@tauri-apps/api/core'); // The shell's p2p_info returns a [label, port] tuple; the label is the // real device name (the machine hostname on desktop, the model name on // Android). Prefer it over any user-agent guess. const [label] = await invoke<[string, number]>('p2p_info'); if (label?.trim()) return label.trim(); } catch { // fall through } // In a shell but with no label yet (mDNS not up on first run): name by app // type, not the WebView's user agent. The Android WebView UA says // "Chrome on Android", which is misleading for a native shell. return shellDeviceName(); } return guessBrowserName();}
// A name for a native shell that has not reported a hostname yet: "Native app// on {os}", never the WebView's browser user agent.function shellDeviceName(): string { const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent; const os = firstUaMatch(ua, [ [/Android/, 'Android'], [/(iPhone|iPad|iPod)/, 'iOS'], [/Mac/, 'Mac'], [/Windows/, 'Windows'], [/Linux/, 'Linux'], ]) ?? m.device_generic_os(); return m.device_native_app({ os });}
// First matching name, in rule order (more specific patterns come first).function firstUaMatch(ua: string, rules: [RegExp, string][]): string | null { for (const [pattern, name] of rules) if (pattern.test(ua)) return name; return null;}
function guessBrowserName(): string { const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent; // Browser and OS names are proper nouns (kept as-is across locales); only // the generic fallbacks and the "{browser} on {os}" connective translate. const browser = firstUaMatch(ua, [ [/Firefox\//, 'Firefox'], [/Edg\//, 'Edge'], [/Chrome\//, 'Chrome'], [/Safari\//, 'Safari'], ]) ?? m.device_generic_browser(); const os = firstUaMatch(ua, [ [/Mac/, 'Mac'], [/Windows/, 'Windows'], [/Android/, 'Android'], [/(iPhone|iPad|iOS)/, 'iOS'], [/Linux/, 'Linux'], ]) ?? m.device_generic_os(); return m.device_name_generated({ browser, os });}
export function localDeviceKind(): DeviceInfo['kind'] { const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent; if (/iPad|Tablet/.test(ua)) return 'tablet'; if (/Mobi|Android|iPhone/.test(ua)) return 'mobile'; return 'desktop';}
// Bind a doc to this device: a stable peer id and timestamped changes, so its// history is attributable and orderable. Called once per doc as it loads,// before any local edit. setPeerId throws if the doc already has pending local// ops under another id, so it must run on a freshly loaded doc.export async function tagDocWithDevice(doc: LoroDoc): Promise<void> { doc.setRecordTimestamp(true); try { doc.setPeerId((await localPeerId()) as `${number}`); } catch { // Already has local ops (shouldn't happen on a fresh load); leave its id. }}
export async function getPeerRegistry(): Promise<PeerRegistry> { return (await db.getMeta<PeerRegistry>(REGISTRY_KEY)) ?? {};}
// Remember (or refresh) what we know about a peer. Keeps the earliest firstSeen// and lets a later, better name win.export async function recordDevice( peerId: string, info: Omit<DeviceInfo, 'firstSeen'> & { firstSeen?: number },): Promise<void> { const reg = await getPeerRegistry(); const prev = reg[peerId]; reg[peerId] = { name: info.name, kind: info.kind, deviceId: info.deviceId ?? prev?.deviceId, firstSeen: prev?.firstSeen ?? info.firstSeen ?? Date.now(), }; await db.setMeta(REGISTRY_KEY, reg);}
// Ensure the local device is in the registry under its stable peer id.export async function registerLocalDevice(): Promise<void> { await recordDevice(await localPeerId(), { name: await localDeviceName(), kind: localDeviceKind(), deviceId: await deviceId(), });}
// Name the seed's peer so the example workspace reads as coming from a real// device. Only fills the entry when it is missing, so a device that later takes// over the seed peer id (it will not, the id is reserved) is never overwritten.export async function registerSeedDevice(): Promise<void> { const reg = await getPeerRegistry(); if (reg[SEED_PEER_ID]) return; await recordDevice(SEED_PEER_ID, { name: m.device_seed(), kind: 'desktop' });}
const DEVICES_MAP = 'devices';
// Write this device's {name, kind} into the doc's shared `devices` map. Returns// true when it changed something (so the caller commits/persists), false when// the entry was already current.export async function publishLocalDevice(doc: LoroDoc): Promise<boolean> { const peerId = await localPeerId(); const name = await localDeviceName(); const kind = localDeviceKind(); const devices = doc.getMap(DEVICES_MAP); const existing = devices.get(peerId); const cur = existing instanceof LoroMap ? (existing.toJSON() as Partial<DeviceInfo>) : null; if (cur && cur.name === name && cur.kind === kind) return false; const entry = existing instanceof LoroMap ? existing : devices.setContainer(peerId, new LoroMap()); entry.set('name', name); entry.set('kind', kind); return true;}
// The peer -> device map carried in the doc itself (remote peers included).export function readSyncedDevices(doc: LoroDoc): PeerRegistry { const devices = doc.getMap(DEVICES_MAP); const out: PeerRegistry = {}; for (const peerId of devices.keys()) { const entry = devices.get(peerId); if (!(entry instanceof LoroMap)) continue; const info = entry.toJSON() as Partial<DeviceInfo>; if (info.name && info.kind) out[peerId] = { name: info.name, kind: info.kind, firstSeen: 0 }; } return out;}
// The peer id is derived once and cached; a fresh test device needs it cleared.export function resetIdentityForTests(): void { cachedPeerId = null;}
// Exposed for tests: the pure deviceId -> peerId derivation.export const _peerIdFromDeviceId = peerIdFromDeviceId;