Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851// The prototype's boot: sign in to Atmosphere, list Public notes from the PDS,// edit one in an Automerge document, and publish it only when Save is pressed.//// Deliberately no framework. This is a shape to argue about, not a product, and// the interesting decisions are in notes.ts (one record shape), automerge.ts// (sync ≠ publish) and fs.ts (the folder mirror).
import { clientId, listNotes, putNote, restore, signIn, signOut, type AtmosphereSession,} from "./auth.ts";import { docIdOf, documentFor, findDocument, openRepo } from "./automerge.ts";import { Connection } from "./connection.ts";import * as corliss from "./corliss.ts";
import * as doc from "./document.ts";import { mountEditor, type Editor } from "./editor.ts";import { createNote as createRelayNote, listWorkspaces, renameNote as renameEntryTo, nameKey as relayNameKey, walkWorkspace, type RelayNote, type Workspace,} from "./relay.ts";import * as mirror from "./mirror.ts";import { chooseFolder, FolderError, listMarkdown, permissionOf, readMarkdown, type LocalFile, requestPermission, storedFolder, supported as fsSupported, writeAll, writeNote, type Permission,} from "./fs.ts";import { getProfile, searchActors, type Actor } from "./typeahead.ts";import { activityByActor, ownersOf, profileOf, rank, RECENT, type Person } from "./people.ts";import { buildRecord, COLLECTION, fileNameFor, displayTitle, join, localNoteId, newTid, filenameOf, noteFromRecord, splitFrontmatter, type SceneNote,} from "./notes.ts";
const repo = openRepo();
/** * Who this tab is, for cursors. * * The colour comes from the repo's peer id, so two tabs of one account are two * colours rather than one — the cursor tag says "another tab" when the other * peer is the same DID, which is the honest thing to say and the only thing that * helps while testing alone. */const CURSOR_COLOURS = ["#d1495b", "#2e86ab", "#5b8c5a", "#8d5a97", "#b5651d", "#1f7a8c"];
function me(): { name: string; id: string; color: string } { const id = state.session?.did ?? "preview"; const handle = state.profile?.handle ?? id; let hash = 7; for (const character of repo.peerId) hash = (hash * 31 + character.charCodeAt(0)) | 0; return { name: `@${handle}`, id, color: CURSOR_COLOURS[Math.abs(hash) % CURSOR_COLOURS.length] };}
interface State { session: AtmosphereSession | null; /** The signed-in member's card: handle, display name, avatar. */ profile: Actor | null; /** What the handle field holds, so a re-render does not lose it. */ handle: string; notes: SceneNote[]; current: SceneNote | null; folder: FileSystemDirectoryHandle | null; /** Whether the folder handle may be written right now. */ folderPermission: Permission; /** Markdown already in the folder, matched against the PDS by filename. */ localFiles: LocalFile[]; /** The file the open note came from, so it is not listed twice. */ currentLocal: string | null; /** Files edited on disk *and* here since the last write. Not reconciled. */ diskConflicts: string[]; /** The live connection, if any. */ connection: Connection | null; /** The sync server's address, as typed. Defaults to the SCN relay. */ syncUrl: string; /** Discovery's answer, so the UI can say who the server trusts. */ syncServer: string | null; /** Whether the server-address entry is showing. Hidden until Sync is pressed. */ showSyncPanel: boolean; /** What the relay says the member may open, and the notes found by walking it. */ workspaces: Workspace[]; relayNotes: RelayNote[]; /** * Which sections and folders are open. **Everything starts closed** — a * workspace is a top-level folder, and so is every subfolder inside one. */ open: Set<string>; dirty: boolean; status: string; /** A record to link to, when the status is about one. */ statusLink: { href: string; label: string } | null;}
const state: State = { session: null, profile: null, handle: "", notes: [], current: null, folder: null, folderPermission: "prompt", localFiles: [], currentLocal: null, diskConflicts: [], connection: null, syncUrl: "https://notes.sharedcomputer.network", syncServer: null, showSyncPanel: false, workspaces: [], relayNotes: [], open: new Set<string>(), dirty: false, status: "starting", statusLink: null,};
const app = document.querySelector<HTMLDivElement>("#app")!;
function el<K extends keyof HTMLElementTagNameMap>( tag: K, attrs: Partial<Record<string, string>> = {}, ...children: (Node | string)[]): HTMLElementTagNameMap[K] { const node = document.createElement(tag); for (const [key, value] of Object.entries(attrs)) { if (value !== undefined) node.setAttribute(key, value); } for (const child of children) { node.append(typeof child === "string" ? document.createTextNode(child) : child); } return node;}
function render(): void { app.replaceChildren();
const header = el("header", { class: "bar" }); header.append(el("h1", {}, "SCN Scene Notes"));
const actions = el("div", { class: "bar__actions" }); if (state.session) { const identity = el("span", { class: "who" }); if (state.profile?.avatar) { identity.append( el("img", { class: "avatar", src: state.profile.avatar, alt: "", width: "24", height: "24" }), ); } // Handle only. The display name is the person's choice of words and carries // no authority; the handle is what actually names them here. const handle = state.profile?.handle ?? state.session.did; identity.append(el("span", {}, `@${handle}`)); identity.title = state.session.did; actions.append(identity); // Two accounts in one window: say so rather than letting the relay's answer // look like the PDS account's. if (relayDid && state.session.did !== relayDid) { actions.append( el( "span", { class: "chip", title: `Your PDS session is ${state.session.did}. The relay signs you in as ${relayDid} — the same only if you signed in to Corliss with this account. Everything on the relay is attributed to the relay account.`, }, relayHandle ? `relay: @${relayHandle}` : "relay: another account", ), ); } actions.append( button("Sign out", async () => { await signOut(state.session!.did); state.session = null; state.notes = []; state.current = null; setStatus("signed out"); render(); }), ); } else { // A real input, not `window.prompt`: a prompt is blocked in some contexts, // is dismissed by an accidental Escape, and leaves nothing on screen to // retry from when sign-in fails. const handleInput = el("input", { class: "handle", placeholder: "your.handle", autocapitalize: "none", spellcheck: "false", }) as HTMLInputElement; handleInput.value = state.handle;
// The suggestions live outside the app's re-render: rebuilding the header on // every keystroke would take the caret with it. const suggestions = el("div", { class: "suggestions" }); let controller: AbortController | null = null; let timer: number | undefined;
function typeahead(): void { const prefix = handleInput.value; state.handle = prefix; window.clearTimeout(timer); controller?.abort(); if (prefix.trim().replace(/^@/, "").length < 2) { suggestions.replaceChildren(); return; } // Debounced: the service is community-run and rate limited at 60/min. timer = window.setTimeout(() => { controller = new AbortController(); void searchActors(prefix, controller.signal) .then((actors) => { suggestions.replaceChildren(); for (const actor of actors.slice(0, 8)) { const option = el("button", { type: "button", class: "suggestion" }); if (actor.avatar) { option.append( el("img", { class: "avatar", src: actor.avatar, alt: "", width: "20", height: "20" }), ); } option.append(el("span", {}, actor.displayName ? `${actor.displayName} @${actor.handle}` : `@${actor.handle}`)); option.addEventListener("click", () => { handleInput.value = actor.handle; state.handle = actor.handle; suggestions.replaceChildren(); void attemptSignIn(); }); suggestions.append(option); } }) .catch((error) => { if ((error as Error).name !== "AbortError") console.warn("typeahead failed", error); }); }, 200); }
handleInput.addEventListener("input", typeahead); handleInput.addEventListener("blur", () => { // A click on a suggestion fires after blur; give it the frame it needs. window.setTimeout(() => suggestions.replaceChildren(), 150); }); handleInput.addEventListener("keydown", (event) => { if ((event as KeyboardEvent).key === "Enter") { suggestions.replaceChildren(); void attemptSignIn(); } });
async function attemptSignIn(): Promise<void> { const handle = handleInput.value.trim(); if (!handle) { handleInput.focus(); return; } setStatus(`signing in as ${handle}…`); render(); try { await signIn(handle); } catch (error) { // Sign-in navigates away on success, so a return here is a failure — // and silence is the worst way to report one. setStatus(`sign-in failed: ${describe(error)}`); console.error("sign-in failed", error); render(); } }
const field = el("div", { class: "handle-field" }, handleInput, suggestions); actions.append(field, button("Sign in", attemptSignIn)); }
// A Sync button, not a standing address. The server is a setting, and a field // that is always on screen makes it look like something to adjust. const syncField = el("div", { class: "sync-field" }); const syncButton = button("Sync", () => { state.showSyncPanel = !state.showSyncPanel; render(); });
syncField.append(syncButton);
if (state.showSyncPanel) { const panel = el("div", { class: "sync-panel" }); const syncUrl = el("input", { class: "handle", placeholder: "notes.sharedcomputer.network", spellcheck: "false", autocapitalize: "none", }) as HTMLInputElement; syncUrl.value = state.syncUrl; syncUrl.addEventListener("input", () => { state.syncUrl = syncUrl.value; });
const go = button(state.connection ? "Reconnect" : "Connect", async () => { try { if (!corliss.stored()) { setStatus(`signing in to ${state.syncUrl}…`); render(); window.location.assign(await corliss.begin(state.syncUrl)); return; } await startSync(); state.showSyncPanel = false; } catch (error) { setStatus(`sync: ${describe(error)}`); } render(); });
syncUrl.addEventListener("keydown", (event) => { if ((event as KeyboardEvent).key === "Enter") void go.click(); });
// Re-read the relay without reloading: the point of a second client is that // the other one's notes appear here, and waiting for a page load to notice // makes that feel broken. const refreshRelay = button("Refresh", async () => { await loadRelay(); await refresh(); render(); });
panel.append(syncUrl, go, refreshRelay); syncField.append(panel); }
actions.append(syncField);
header.append(actions); app.append(header);
if (!fsSupported()) { app.append( el( "p", { class: "notice" }, "The folder mirror needs Chrome or Edge (File System Access API). Everything else works without it.", ), ); }
const main = el("main", { class: "split" }); main.append(renderList(), renderEditor()); app.append(main);
// Pinned to the bottom: a status is about what just happened, and it should // not move the layout or compete with the identity in the header. const bar = el("div", { class: "statusbar", role: "status" }); paintStatus(bar); statusBar = bar; app.append(bar);}
let statusBar: HTMLElement | null = null;
/** Paint the bar. Cheap enough to call on every status change. */function paintStatus(bar: HTMLElement): void { bar.replaceChildren(el("span", {}, state.status || "ready")); if (!state.statusLink) return; // An emoji link with the sentence as its accessible name: the bar is glass for // a glance, and "☁️" says "it is out there" faster than "pdsls" does. bar.append( el( "a", { href: state.statusLink.href, target: "_blank", rel: "noreferrer", title: state.statusLink.label, "aria-label": state.statusLink.label, }, "☁️", ), );}
/** * Set the bottom bar. * * Repaints the bar alone when it exists: a status change must never tear down * the editor, because the editor may be holding the caret of someone typing. */function setStatus(text: string, link?: { href: string; label: string }): void { state.status = text; state.statusLink = link ?? null; if (statusBar) paintStatus(statusBar);}
function describe(error: unknown): string { if (error instanceof Error) return error.message; return String(error);}
function button(label: string, onClick: () => void | Promise<void>): HTMLButtonElement { const node = el("button", { type: "button" }, label); node.addEventListener("click", () => void onClick()); return node;}
/** * The folder control for a workspace. * * **The mirror is per workspace**, so the control belongs to the workspace, not * to the app: Public writes its notes into its own folder, and a workspace's * notes will do the same. Right now there is only Public, and one handle in * `state.folder` — the map is the thing to add when the second workspace gets * notes. * * It doubles as the re-grant button: permission on a stored handle does not * survive a reload, and `requestPermission` needs a click, so this is where the * click comes from. */function folderControl(): HTMLElement { const control = el( "button", { type: "button", class: `chip chip--button${state.folder ? "" : " chip--empty"}`, title: state.folder ? `Mirroring to ${state.folder.name} — click to change` : "Choose a folder to mirror this workspace's notes into", }, state.folder ? `📁 ${state.folder.name}${state.folderPermission === "granted" ? "" : " ⚠️"}` : "📁 Choose folder", );
control.addEventListener("click", async () => { try { if (state.folder) { // Already chosen: the click is a re-grant, not a re-pick. const permission = await requestPermission(state.folder); if (permission !== "granted") { setStatus("folder: write permission was not granted"); render(); return; } } else { state.folder = await chooseFolder(); }
state.folderPermission = await permissionOf(state.folder); await scanFolder(); setStatus(`folder: ${state.folder.name}`); if (state.notes.length) { const written = await writeAll(state.folder, state.notes); for (const note of state.notes) { const handle = await workingHandle(note); mirror.remember(filenameOf(note), join(note.head, note.body), doc.heads(handle)); } setStatus(`mirrored ${written} note(s) to ${state.folder.name}`); } } catch (error) { // A cancelled picker throws AbortError, which is not a failure. if ((error as Error).name !== "AbortError") { setStatus(`folder: ${(error as Error).message}`); } } render(); });
return control;}
/** Open a note that lives in the relay's tree, bound to its own document. */async function openRelayNote(entry: RelayNote): Promise<void> { const handle = await repo.find<doc.NoteDoc>(entry.url as never).catch(() => null); if (!handle) { setStatus(`could not open ${entry.name} from the relay`); render(); return; }
const full = doc.read(handle); const { properties, body, head } = splitFrontmatter(full); const fallback = entry.name.replace(/\.md$/i, "");
state.current = { rkey: "", title: displayTitle(properties, body, fallback), body, properties, tags: [], updated: "", createdAt: "", path: entry.path, head, raw: full, // The URL *is* the note's identity on the relay; a record may never // exist. The id half of it is what a record gets to keep, so a note that // is published here can be adopted elsewhere. docId: docIdOf(entry.url), record: { __url: entry.url, docId: docIdOf(entry.url) }, }; state.currentLocal = null; state.dirty = false; openHandle = handle; render(); scheduleActivity(); void refreshPeople();}
/** A row in the list: the title once, and when it last changed. */function noteRow(note: SceneNote, unsaved: boolean, conflicted = false): HTMLElement { const active = state.current?.rkey === note.rkey && (note.rkey !== "" || state.current === note); const row = el("button", { type: "button", class: `row${active ? " row--active" : ""}` }); row.append(el("span", { class: "row__name" }, note.title || "Untitled")); row.append( el( "span", { class: "row__meta" }, conflicted ? "changed on disk and here — not applied" : unsaved ? "not published" : relative(note.updated), ), ); row.addEventListener("click", () => void openNote(note)); return row;}
/** `2026-11-15 14:03`, in local time — a person reads a clock, not a Z. *//** * How long ago, in words, for a dense list. * * `updatedAt` is an ISO string, and printing sixteen characters of it put * `2026-11-17T18:12` under every title -- precise, unreadable, and as wide as * the title. A column wants a glance: a clock time today, "yesterday", a day * count inside the week, and a date beyond it. */function relative(value: string | number | null | undefined): string { if (!value) return ""; const date = new Date(value); if (Number.isNaN(date.getTime())) return "";
const minutes = Math.round((Date.now() - date.getTime()) / 60_000); if (minutes < 1) return "just now"; if (minutes < 60) return `${minutes} min ago`;
const pad = (n: number) => String(n).padStart(2, "0"); const clock = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
const midnight = new Date(); midnight.setHours(0, 0, 0, 0); const days = Math.round((midnight.getTime() - new Date(date).setHours(0, 0, 0, 0)) / 86_400_000);
// `days` counts forward from the note's day to today, so 1 is yesterday. if (days <= 0) return clock; if (days === 1) return "yesterday"; if (days < 7) return `${days} days ago`;
const month = date.toLocaleString(undefined, { month: "short" }); return date.getFullYear() === new Date().getFullYear() ? `${date.getDate()} ${month}` : `${date.getDate()} ${month} ${date.getFullYear()}`;}
function when(value: number | string | null | undefined): string { if (value === null || value === undefined || value === "") return "";
// A date with no time means that day, not midnight UTC. `new Date("2026-11-15")` // is UTC, so in Vancouver it renders as the 14th — the kind of off-by-one that // makes a note look older than it is. const dateOnly = typeof value === "string" ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(value.trim()) : null; if (dateOnly) return `${dateOnly[1]}-${dateOnly[2]}-${dateOnly[3]}`;
const date = new Date(value); if (Number.isNaN(date.getTime())) return ""; const pad = (n: number) => String(n).padStart(2, "0"); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;}
/** A front-matter date, whatever key it was written under. */function createdFrom(properties: [string, string][]): string { const key = properties.find(([k]) => ["created", "createdAt", "date"].includes(k))?.[1] ?? ""; return when(key.trim().replace(/^['"]|['"]$/g, ""));}
/** * The title field renames the note. * * On the relay a note has no other place to keep a name: the entry in its folder * document is the file name, and the sidebar, the MCP and the plugin all read it * from there. So a title edit is a folder change — one change to one document, * as the plugin's move and rename rules require. */async function renameFromTitle(note: SceneNote): Promise<void> { const url = typeof note.record.__url === "string" ? note.record.__url : ""; if (!url) return; const entry = state.relayNotes.find((candidate) => candidate.url === url); if (!entry) return;
const name = fileNameFor(note.title); if (!name || name === entry.name) return;
try { await renameEntryTo(repo, entry.folder, url, name); const parent = entry.path.includes("/") ? `${entry.path.slice(0, entry.path.lastIndexOf("/"))}/` : ""; entry.name = name; entry.path = `${parent}${name}`; note.path = entry.path; if (note.record.noteId) note.record.path = entry.path; setStatus(`renamed to ${name}`); repaintList(); } catch (error) { setStatus(`rename: ${describe(error)}`); }}
/** Rebuild the sidebar in place, so a rename does not rebuild the editor. */function repaintList(): void { const aside = app.querySelector("aside.list"); if (aside) aside.replaceWith(renderList());}
/** * Re-read the folder and reconcile it with the documents. * * **Three things can have moved since the last write: the file, the document, * and the record.** The manifest remembers what the file held when we last wrote * it, which is the only way to tell those apart. For each file: * * - no manifest entry → never mirrored: a local file, offered for publishing; * - file unchanged → nothing to do, unless the document moved, in which case the * document is written out; * - file changed, document still at the remembered text → apply the file's edit * to the document as a splice; * - file changed *and* document moved → concurrent edits: refuse, and say so. *//** Rebuild the folder and reconcile it with the documents. */async function scanFolder(): Promise<void> { if (!state.folder) return; try { state.localFiles = await listMarkdown(state.folder); } catch { state.localFiles = []; return; }
const conflicts: string[] = []; const applied: string[] = [];
for (const file of state.localFiles) { const entry = mirror.get(file.name); if (!entry) continue; if (entry.text === file.text) continue;
const note = state.notes.find((n) => filenameOf(n) === file.name); if (!note) continue;
const handle = await workingHandle(note); if (!doc.read(handle)) { // A document this device has not opened; seeding it from the record is // the only sensible base. doc.seed(handle, entry.text); }
if (doc.applyExternal(handle, entry.text, file.text)) { mirror.remember(file.name, file.text, doc.heads(handle)); applied.push(file.name); } else { conflicts.push(file.name); } }
state.diskConflicts = conflicts; if (conflicts.length) { setStatus( `${conflicts.length} file(s) changed on disk and here — left alone: ${conflicts.join(", ")}`, ); } else if (applied.length) { setStatus(`applied ${applied.length} change(s) from disk: ${applied.join(", ")}`); }}
/** Open a file that exists on disk but not in the PDS. */async function openLocalFile(name: string): Promise<void> { if (!state.folder) return; try { const text = await readMarkdown(state.folder, name); const onDisk = splitFrontmatter(text); const fallback = name.replace(/\.md$/i, ""); const noteId = localNoteId(name);
// The file has no record, so its id comes from its name — and that id is // what gives the note a document, which is where an unsaved edit lives. // Without it, typing into a file and clicking away lost the work. const handle = await documentFor(repo, noteId); const stored = doc.read(handle); if (!stored) doc.seed(handle, text);
const open = stored ? splitFrontmatter(stored) : onDisk;
state.current = { rkey: "", title: displayTitle(open.properties, open.body, fallback), body: open.body, properties: open.properties, tags: [], updated: "", createdAt: "", path: name, head: open.head, raw: stored || text, record: { noteId }, }; state.currentLocal = name; // Unsaved by definition until published, and unsaved *again* if the // document has moved past what the file holds. state.dirty = stored === "" || stored !== text; openHandle = handle; render(); } catch (error) { setStatus(`could not read ${name}: ${describe(error)}`); render(); }}
function isOpen(key: string): boolean { return state.open.has(key);}
/** * A section bar: the full width of the column, the workspace's name on it, the * count at the end. One click opens or closes what is under it. * * This replaced a disclosure triangle. A triangle says "there is more here" and * asks the reader to find it; a bar *is* the thing — the name is the control, * and the band across the column says "top level" without a glyph. The triangles * stay for folders inside a workspace, which are not workspaces and should not * read as if they were. */function sectionBar(text: string, key: string, count = ""): HTMLButtonElement { const node = el("button", { type: "button", class: "section__bar", "aria-expanded": isOpen(key) ? "true" : "false", title: `${isOpen(key) ? "Hide" : "Show"} ${text}`, }); node.append(el("span", { class: "section__name" }, text)); if (count) node.append(el("span", { class: "section__count" }, count)); node.addEventListener("click", () => { if (isOpen(key)) state.open.delete(key); else state.open.add(key); render(); }); return node;}
/** The body of an open section, or `null` when it is closed — nothing built. */function bodyOf(key: string): HTMLDivElement | null { if (!isOpen(key)) return null; return el("div", { class: "section__body", id: `section-${key.replace(/[^A-Za-z0-9_-]+/g, "-")}`, });}
/** A section: the bar, and the body under it when it is open. */function section(label: string, key: string, count: string, body: HTMLElement | null): HTMLElement { const wrapper = el("div", { class: "section" }); const bar = sectionBar(label, key, count); wrapper.append(bar); if (body) { bar.setAttribute("aria-controls", body.id); wrapper.append(body); } return wrapper;}
/** * What belongs to a section, on its own line directly under the bar. * * The `+` lives here rather than at the foot of the list, because making a note * is an act inside a workspace — the placement should say which one. */function actions(...children: HTMLElement[]): HTMLElement { return el("div", { class: "section__actions" }, ...children);}
function newNoteButton(label: string, make: () => void | Promise<void>): HTMLButtonElement { const node = el( "button", { type: "button", class: "icon-button", title: `New note in ${label}`, "aria-label": `New note in ${label}`, }, "+", ); node.addEventListener("click", () => void make()); return node;}
/** * Notes laid out by their path, so subfolders read as subfolders. * * Sorted by path and rendered in order, with a folder label emitted the first * time a prefix appears — a Set keeps that to once per folder without building * a tree structure for a list that is already sorted. */function tree(notes: RelayNote[], workspaceKey: string): HTMLElement { const container = el("div", { class: "tree" }); const seen = new Set<string>();
for (const note of [...notes].sort((a, b) => a.path.localeCompare(b.path))) { const parts = note.path.split("/"); let visible = true;
for (let depth = 1; depth < parts.length; depth += 1) { if (!visible) break; const prefix = parts.slice(0, depth).join("/"); const key = `${workspaceKey}/${prefix}`; if (!seen.has(key)) { seen.add(key); const folder = el("button", { type: "button", class: "tree__folder", "aria-expanded": isOpen(key) ? "true" : "false", }); folder.style.paddingLeft = `${0.4 + (depth - 1) * 0.85}rem`; folder.append(el("span", { class: "list__triangle" }, isOpen(key) ? "▾" : "▸")); folder.append(el("span", {}, parts[depth - 1])); folder.addEventListener("click", () => { if (isOpen(key)) state.open.delete(key); else state.open.add(key); render(); }); container.append(folder); } // A closed folder hides everything under it, including deeper folders. if (!isOpen(key)) visible = false; }
if (!visible) continue; const row = el("button", { type: "button", class: `row${state.current?.record.__url === note.url ? " row--active" : ""}`, title: note.path, }); row.style.paddingLeft = `${0.4 + (parts.length - 1) * 0.85}rem`; row.append(el("span", { class: "row__name" }, note.name.replace(/\.md$/i, ""))); row.addEventListener("click", () => void openRelayNote(note)); container.append(row); }
return container;}
/** * One workspace from the relay. * * **An empty workspace still gets a bar.** Hiding a workspace the account really * has made the sidebar disagree with Corliss, and made an empty `SCN Local` look * like a client failure rather than an empty workspace. */function relaySection( label: string, key: string, notes: RelayNote[], empty: string, workspace: Workspace | null,): HTMLElement { const body = bodyOf(key); if (body) { // The `+` is on every workspace now, because making a note in one is a // create on the folder document — no server endpoint needed. if (workspace) body.append(actions(newNoteButton(label, () => newRelayNote(workspace)))); if (notes.length) body.append(tree(notes, key)); else body.append(el("p", { class: "hint" }, empty)); } return section(label, key, `${notes.length}`, body);}
/** * A note made in a workspace, the way a note comes to exist: its own document, * then an entry in the workspace's root folder. * * The name is `Untitled` because that is what a new Obsidian note is called; * renaming it there moves the entry, which is the plugin's job and already * works. Nothing is published to a PDS by this: creating a note on the relay * and publishing a record are different verbs, as they have been all along. */async function newRelayNote(workspace: Workspace): Promise<void> { const taken = new Set( state.relayNotes .filter((note) => note.workspace === workspace.path) .map((note) => relayNameKey(note.name)), ); let name = "Untitled.md"; for (let index = 2; taken.has(relayNameKey(name)); index += 1) name = `Untitled ${index}.md`;
try { const made = await createRelayNote(repo, workspace.url, name, ""); const entry: RelayNote = { path: made.name, name: made.name, url: made.url, folder: workspace.url, workspace: workspace.path, }; state.relayNotes = [...state.relayNotes, entry]; state.open.add(`ws:${workspace.path}`); await openRelayNote(entry); setStatus(`made ${made.name} in ${workspace.name ?? workspace.path}`); } catch (error) { setStatus(`new note: ${describe(error)}`); } render();}
/** * The design fixture behind `?preview=sidebar` (dev only). * * It goes through `noteFromRecord`, so the sidebar is looking at the same * shape a real answer produces — a fixture that invents its own shape would * flatter the layout and lie about the data. */function previewSidebar(): void { const record = (title: string, body: string) => noteFromRecord(title.toLowerCase().replace(/\W+/g, "-"), { title, path: `${title.toLowerCase().replace(/\W+/g, "-")}.md`, createdAt: "2026-11-16T00:49:23.615Z", updatedAt: "2026-11-17T18:12:00.000Z", tags: ["scene-note"], body: { text: { markdown: `---\ntitle: ${title}\n---\n\n${body}` } }, });
state.notes = [ record("SCN Local", "A standalone editor."), record("Obsidian-flavored Markdown", "What OFM means."), record("Scene Note", "The record and the document."), ];
state.workspaces = [ { rootDocId: "root-private", url: "automerge:root-private", name: null, groupId: null, path: "Private" }, { rootDocId: "root-scn", url: "automerge:root-scn", name: "SCN Local", groupId: "g1", path: "Workspaces/SCN Local" }, { rootDocId: "root-dev", url: "automerge:root-dev", name: "SCN Development", groupId: "g2", path: "Workspaces/SCN Development" }, ];
state.relayNotes = [ { path: "Notes/202611172342.md", workspace: "Private", folder: "automerge:root-private", name: "202611172342.md", url: "automerge:p1" }, { path: "Reading/AT Protocol Spaces.md", workspace: "Private", folder: "automerge:root-private", name: "AT Protocol Spaces.md", url: "automerge:p2" }, { path: "scn-local.md", workspace: "Workspaces/SCN Local", folder: "automerge:root-scn", name: "scn-local.md", url: "automerge:s1" }, { path: "Code/scn-local/Issues/CM6 editor.md", workspace: "Workspaces/SCN Development", folder: "automerge:d-folder-issues", name: "CM6 editor.md", url: "automerge:d1", }, { path: "Code/Scene Note Lexicon.md", workspace: "Workspaces/SCN Development", folder: "automerge:d-folder-code", name: "Scene Note Lexicon.md", url: "automerge:d2", }, { path: "Worklog/November 17th, 2026.md", workspace: "Workspaces/SCN Development", folder: "automerge:d-folder-worklog", name: "November 17th, 2026.md", url: "automerge:d3" }, ];
state.localFiles = [{ name: "Draft from disk.md", modified: Date.now() - 3_600_000, text: "# Draft\n\nFrom disk." }]; state.profile = { did: "did:plc:preview", handle: "bmann.ca", name: "Boris", avatar: null } as unknown as Actor; // `?did=did:plc:...` makes two preview tabs two different people, which is the // only way to see the people row without two accounts. const previewDid = new URLSearchParams(window.location.search).get("did") ?? "did:plc:preview"; state.session = { did: previewDid, agent: null } as unknown as AtmosphereSession; state.status = "preview"; // Open a representative mix: a bar with notes, a bar with folders, an empty one. state.open = new Set([ "public", "ws:Private", "ws:Private/Notes", "ws:Workspaces/SCN Development", "ws:Workspaces/SCN Development/Code", ]);}
/** A blank note: text with no record behind it until Save. */function newNote(): void { state.current = { rkey: "", title: "", body: "", properties: [], tags: [], updated: "", createdAt: "", path: "", record: {}, }; state.currentLocal = null; // A note with no record and no document: the editor holds the text until // Save, and the document is made when the note exists. openHandle = null; state.dirty = true; render();}
function renderList(): HTMLElement { const aside = el("aside", { class: "list" });
// --- Public: our own records, which are what "public" means here --- const publicBody = bodyOf("public"); if (publicBody) { publicBody.append(actions(newNoteButton("Public", newNote), folderControl()));
if (state.current && !state.current.rkey && !state.currentLocal && !state.current.record.__url) { publicBody.append(noteRow(state.current, true)); } for (const note of state.notes) { const unsaved = state.dirty && state.current?.rkey === note.rkey; const conflicted = state.diskConflicts.includes(filenameOf(note)); publicBody.append(noteRow(note, unsaved, conflicted)); } if (state.notes.length === 0 && state.session) { // **Name the account.** An empty list usually means the wrong sign-in, not // an empty repository, and the only way to tell is to say whose. const who = state.profile?.handle ?? state.session.did; publicBody.append(el("p", { class: "hint" }, `No public notes in @${who}.`)); } } aside.append(section("Public", "public", `${state.notes.length}`, publicBody));
if (!state.session) { aside.append(el("p", { class: "hint" }, "Sign in to read your notes from your PDS.")); return aside; }
// --- The relay's workspaces: Private first, then the member's groups --- const byWorkspace = new Map<string, RelayNote[]>(); for (const note of state.relayNotes) { const key = note.workspace ?? ""; byWorkspace.set(key, [...(byWorkspace.get(key) ?? []), note]); }
// The relay makes a member's Private workspace when it first lists for them, // so an absent one means the listing has not happened yet, not that we should // create anything. const privateNotes = byWorkspace.get("Private") ?? []; aside.append( relaySection( "Private", "ws:Private", privateNotes, state.workspaces.length ? "No private notes yet." : "Connect a sync server to see your private workspace.", state.workspaces.find((workspace) => workspace.path === "Private") ?? null, ), );
for (const workspace of state.workspaces) { if (workspace.path === "Private") continue; const label = workspace.name ?? workspace.path.replace(/^Workspaces\//, ""); aside.append( relaySection(label, `ws:${workspace.path}`, byWorkspace.get(workspace.path) ?? [], "No notes yet.", workspace), ); }
// --- Files on disk that the PDS does not have --- const published = new Set(state.notes.map((note) => filenameOf(note))); const local = state.localFiles.filter((file) => !published.has(file.name)); if (local.length) { const diskBody = bodyOf("disk"); if (diskBody) { for (const file of local) { const open = state.currentLocal === file.name && state.current; const { properties, body } = splitFrontmatter(file.text); const title = open ? state.current!.title || file.name.replace(/\.md$/i, "") : displayTitle(properties, body, file.name.replace(/\.md$/i, ""));
const row = el("button", { type: "button", class: `row${open ? " row--active" : ""}`, title: "on disk, not in your PDS", });
const name = el("span", { class: "row__name" }); name.append(el("span", { class: "dot", "aria-hidden": "true" })); name.append(el("span", {}, title));
const created = createdFrom(properties); const meta = open && state.dirty ? "edited here · not saved to the PDS" : [created ? `created ${created}` : "", `modified ${when(file.modified)}`, "not in the PDS"] .filter(Boolean) .join(" · ");
row.append(name, el("span", { class: "row__meta" }, meta)); row.addEventListener("click", () => void openLocalFile(file.name)); diskBody.append(row); } } aside.append(section("On disk", "disk", `${local.length}`, diskBody)); }
return aside;}
function renderEditor(): HTMLElement { const section = el("section", { class: "editor" });
if (!state.current) { section.append(el("p", { class: "hint" }, "Pick a note, or make one.")); return section; }
const note = state.current;
const title = el("input", { class: "title", placeholder: "Title" }) as HTMLInputElement; title.value = note.record.title ? String(note.record.title) : note.title; title.addEventListener("input", () => { note.record.title = title.value; note.title = title.value; state.dirty = true; updateSave(); scheduleDiskWrite(note); }); // On the relay the entry's name *is* the file name, so the title renames the // note. On `change` rather than `input`: one folder change per edit, and no // re-render while the caret is still in the field. title.addEventListener("change", () => void renameFromTitle(note)); // Enter commits the field, and a text input only fires `change` on blur in // some browsers — one keystroke should be enough to make the rename happen. title.addEventListener("keydown", (event) => { if (event.key === "Enter") title.blur(); });
// The unsaved marker lives here, on the verb that resolves it — not beside a // filename, where it reads as part of the name. const save = el("button", { class: "primary" }); const saveLabel = el("span", {}, "Publish to PDS"); const saveDot = el("span", { class: "dot dot--button", title: "not published to the PDS", "aria-hidden": "true", }); save.append(saveLabel, saveDot); save.addEventListener("click", () => void publish(note, title.value));
function updateSave(): void { saveDot.hidden = !state.dirty; save.title = state.dirty ? "not published to the PDS" : ""; saveDotRef = updateSave; } updateSave();
const surface = el("div", { class: "editor__surface" }); mountEditorFor(surface, note);
// Who's here: bottom right, under the text rather than above it — presence is // about the note, not about the frame around it. const foot = el("div", { class: "editor__foot" }, save, el("div", { class: "editor__people" })); paintPeople(); void refreshPeople();
section.append(title, surface, foot); return section;}
/** * The editor, kept across renders. * * A CM6 view is rebuilt only when the note changes. `render()` runs for things * that have nothing to do with the text — a section opening, a status line — and * a fresh view each time would drop the undo stack and the scroll position. */let currentEditor: Editor | null = null;let editorFor: string | null = null;let editorHandle: doc.Handle | null = null;/** The document behind the open note, or null for one that has none yet. */let openHandle: doc.Handle | null = null;/** Repaints the Save dot, which a document change has to know about. */let saveDotRef: (() => void) | null = null;
function mountEditorFor(parent: HTMLElement, note: SceneNote): void { // `noteId` is what a file's note has instead of a key, and two files must not // share an editor — the view would stay bound to the other one's document. const identity = String(note.record.__url ?? note.rkey ?? note.record.noteId ?? "new");
if (currentEditor && editorFor === identity && editorHandle === openHandle) { parent.append(currentEditor.view.dom); currentEditor.view.requestMeasure(); return; }
currentEditor?.destroy(); currentEditor = null;
const editor = mountEditor({ parent, handle: openHandle, me: me(), onPeers: () => void refreshPeople(), lookup: profileOf, onChange: (text) => { const { properties: props, body, head } = splitFrontmatter(text); note.raw = text; note.head = head; note.body = body; note.properties = props; // A remote change lands here too: the document is the text, whoever // typed it, and the record is out of date either way. state.dirty = true; saveDotRef?.(); scheduleActivity(); scheduleDiskWrite(note); }, });
currentEditor = editor; editorFor = identity; editorHandle = openHandle; parent.append(editor.view.dom);}
// --- who is here -----------------------------------------------------------//// Two sources that answer different questions. Presence is only published by// this client, so it says "someone has a cursor here now". The document's own// history says who edited and when, whoever the client was — which is how an// edit from Obsidian shows up at all.
let people: Person[] = [];/** What the last attribution attempt found, for the row's hover and a "?". */let peopleNote = "";let activity = new Map<string, number>();/** Changes in the document whose actor the relay could not name. */let unattributed: { count: number; lastEdit: number } | null = null;let activityDoc: string | null = null;let activityTimer: number | undefined;
/** * This member's DID as the *relay* knows it. * * The PDS session is a good answer when it is there, and the relay token is the * better one: the relay knows who edited by the DID in the token that carried the * change, and that is the identity this has to filter against. The two are the * same person through Corliss, but only the token is present when the PDS session * is not. */let relayDid = "";let relayHandle = "";
function meId(): string { return relayDid || state.session?.did || "preview";}
/** * Name the account the *relay* signs us in as. * * There are two identities in this app and only one of them was on screen: the * PDS session in the header, and the Corliss token that everything on the relay * is attributed to. They are usually the same person, and when they are not, the * row of avatars is the last place to find out. */function noteRelayIdentity(): void { void corliss .accessToken() .then(async (token) => { const did = tokenSubject(token); if (!did) return; relayDid = did; if (state.session?.did && did !== state.session.did) { relayHandle = (await profileOf(did)).handle ?? ""; } render(); }) .catch(() => undefined);}
/** The `sub` of a JWT, without verifying it — this is our own token, not a check. */function tokenSubject(token: string): string { try { const part = token.split(".")[1] ?? ""; const payload = JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/"))); return typeof payload.sub === "string" ? payload.sub : ""; } catch { return ""; }}
/** * The document behind a note. * * Two ways to know it, and both must work: a note opened from the relay tree has * its URL; a note re-opened from its own record — which is what happens after * Publish — has the `docId` the record carries. Reading only the URL made the * people row go blank the moment a note had been published. */function documentIdOf(note: SceneNote): string { const url = typeof note.record.__url === "string" ? note.record.__url : ""; if (url) return docIdOf(url); if (note.docId) return note.docId; return typeof note.record.docId === "string" ? note.record.docId : "";}
/** The row of avatars, bottom right of the editor. */function paintPeople(): void { const row = document.querySelector<HTMLElement>(".editor__people"); if (!row) return; row.title = peopleNote; const nodes = people.map(personNode); if (nodes.length === 0 && /failed|not signed in/.test(peopleNote)) { // Something was asked and nothing came back: say so instead of showing an // empty corner and leaving "did anyone else edit this?" unanswerable. nodes.push(el("span", { class: "person person--unknown", title: peopleNote }, "?")); } row.replaceChildren(...nodes);}
function personNode(person: Person): HTMLElement { // Present, or edited within five minutes: both are "here". After that the // avatar dims but stays — they are still part of the note's record. const idle = !person.present && Date.now() - person.lastEdit > RECENT; if (person.unattributed) { // One chip for all of them: six unexplained actors should read as one fact, // not six. const minutes = Math.round((Date.now() - person.lastEdit) / 60_000); return el( "span", { class: `person person--unknown${idle ? " person--idle" : ""}`, title: `An editor the relay cannot name: ${person.unattributed.count} change${ person.unattributed.count === 1 ? "" : "s" }, last ${minutes < 1 ? "just now" : `${minutes} min ago`}.`, }, "?", ); } const name = (person.handle ?? person.did).replace(/^@/, ""); // The handle is the readable name; the DID is the fact. Both, because "which // account is that, really" is the question this row exists to answer. const shortDid = person.did.length > 22 ? `${person.did.slice(0, 20)}…` : person.did; const node = el("span", { class: `person${idle ? " person--idle" : ""}${idle ? "" : " person--here"}`, title: `@${name} · ${shortDid}${person.lastEdit ? "" : " · here now"}`, }); if (person.avatar) { node.append( el("img", { class: "person__image", src: person.avatar, alt: "", referrerpolicy: "no-referrer" }), ); } else { node.append(el("span", { class: "person__initial" }, name.slice(0, 1).toUpperCase() || "?")); } return node;}
/** Rebuild the people list: present peers first, then recent editors. */async function refreshPeople(): Promise<void> { const found = new Map<string, Person>();
for (const peer of currentEditor?.peers() ?? []) { if (!peer.id || peer.id === meId()) continue; found.set(peer.id, { did: peer.id, lastEdit: 0, present: true, handle: peer.name }); }
const docId = state.current ? documentIdOf(state.current) : ""; if (docId && activityDoc === docId) { for (const [did, at] of activity) { if (did === meId()) continue; const person = found.get(did) ?? { did, lastEdit: 0, present: false }; person.lastEdit = Math.max(person.lastEdit, at); found.set(did, person); } }
// **The relay cannot always name an editor.** The changes are in the document // — the text arrived — but `actor_members` has no member for their actor, so // the honest thing is to show that someone edited rather than nothing at all. if (docId && activityDoc === docId && unattributed && unattributed.lastEdit > 0) { found.set("unattributed", { did: "", handle: `${unattributed.count} unattributed ${unattributed.count === 1 ? "editor" : "editors"}`, lastEdit: unattributed.lastEdit, present: false, unattributed: { count: unattributed.count }, }); }
const next = rank(found.values()).slice(0, 8); await Promise.all( next.map(async (person) => { if (!person.did) return; const profile = await profileOf(person.did); // The profile is authoritative: presence carries whatever name the peer // chose to send, and a DID resolves to the handle other clients show. person.handle = profile.handle ?? person.handle; person.avatar = profile.avatar; }), ); people = next; paintPeople();}
/** Read who edited this document, from its changes and the relay's mapping. */function scheduleActivity(): void { const docId = state.current ? documentIdOf(state.current) : ""; // Not `state.session`: the actor lookup needs the **Corliss** token, and gating // on the PDS session meant a browser signed in to the relay but not to a PDS // never asked who edited. `loadActivity` reports when there is no token. if (!docId) return; window.clearTimeout(activityTimer); activityTimer = window.setTimeout(() => void loadActivity(docId), 1200);}
async function loadActivity(docId: string): Promise<void> { const handle = openHandle; if (!handle || !handle.isReady()) return;
const actors = activityByActor(handle.doc()); if (actors.size === 0) return;
const token = await corliss.accessToken().catch(() => null); if (!token) { peopleNote = "not signed in to the relay"; paintPeople(); return; } relayDid = tokenSubject(token) || relayDid;
try { const owners = await ownersOf(state.syncUrl, token, docId, [...actors.keys()]); const next = new Map<string, number>(); const unknown: number[] = []; for (const [actor, at] of actors) { const did = owners[actor]?.did ?? null; if (did) next.set(did, Math.max(next.get(did) ?? 0, at)); else unknown.push(at); } unattributed = unknown.length ? { count: unknown.length, lastEdit: Math.max(...unknown) } : null; activity = next; activityDoc = docId; const others = [...next.keys()].filter((did) => did !== meId()); peopleNote = `${actors.size} actor(s), ${next.size} member(s), me ${meId() || "unknown"}${ others.length === 0 && next.size > 0 ? " — the only member is this one" : "" }`; console.info("people:", { me: meId(), docId, attributed: [...actors].map(([actor, at]) => ({ actor: actor.slice(0, 8), did: owners[actor]?.did ?? null, handle: owners[actor]?.handle ?? null, minutesAgo: Math.round((Date.now() - at) / 60_000), })), }); } catch (error) { // No attribution — the relay is down, or this document is not one it knows. // Presence still says who is here; the history simply says nothing, and both // the console and the row's hover say why. peopleNote = `actor lookup failed: ${describe(error)}`; console.warn("people: could not attribute the document's actors", error); } void refreshPeople();}
let diskTimer: number | undefined;
/** * Write the open note back to its file, a moment after typing stops. * * The mirror was outbound only on Save, which made a file opened from disk a * dead end: the app held the edit and the file stayed as it was. The file is a * copy of the note, so it follows the note — debounced, because a write per * keystroke is a file write per keystroke. * * **And the manifest is updated after the write**, or the next scan sees the * file it just wrote as an external edit it has never seen. That is the plugin's * "do not echo your own writes" rule, arrived at from the other side. */function scheduleDiskWrite(note: SceneNote): void { window.clearTimeout(diskTimer); diskTimer = window.setTimeout(() => void writeToDisk(note), 600);}
async function writeToDisk(note: SceneNote): Promise<void> { if (!state.folder) return; // No identity means no document, and the manifest is keyed by one. if (!note.record.noteId && !note.rkey) return; if ((await permissionOf(state.folder)) !== "granted") return;
const name = state.currentLocal ?? filenameOf(note); try { await writeNote(state.folder, { ...note, path: name }); const handle = await workingHandle(note); const text = join(note.head, note.body); mirror.remember(name, text, doc.heads(handle));
// Update the listing in place rather than re-rendering: a render would take // the caret out of the textarea mid-sentence. const index = state.localFiles.findIndex((file) => file.name === name); if (index >= 0) state.localFiles[index] = { name, modified: Date.now(), text }; } catch (error) { const message = error instanceof FolderError ? error.message : describe(error); setStatus(`file not updated: ${message}`); }}
/** * Ask the relay what the member may open, then walk each workspace's folder * documents to find the notes. * * This is the step that makes a connection mean something: the socket exchanges * documents *by id*, and until we have these ids there is nothing to exchange. *//** * Open the connection and read the relay. * * One place, because both halves need a token and the token expires: the socket * reconnects itself with a fresh one, and this reads with a fresh one too. */async function startSync(): Promise<void> { state.connection?.stop();
const connection = new Connection({ repo, syncUrl: state.syncUrl, token: () => corliss.accessToken(), onState: (state_, detail) => { if (state_ === "online") setStatus(`sync: online — ${state.syncUrl}`); else if (state_ === "signed out") setStatus(`sync: signed out — ${detail ?? "sign in again"}`); else if (state_ === "offline") setStatus(`sync: ${detail ?? "offline"} — retrying`); else setStatus(`sync: connecting to ${state.syncUrl}…`); }, }); state.connection = connection; connection.start(); noteRelayIdentity();
await loadRelay();}
async function loadRelay(): Promise<void> { try { const token = await corliss.accessToken(); const workspaces = await listWorkspaces(state.syncUrl, token); const found: RelayNote[] = []; for (const workspace of workspaces) { const notes = await walkWorkspace(repo, workspace); // Tag each note with the workspace it came from: the sidebar groups by // workspace, and the walk only knows the tree below a root. found.push(...notes.map((note) => ({ ...note, workspace: workspace.path }))); } state.workspaces = workspaces; state.relayNotes = found; setStatus(`relay: ${workspaces.length} workspace(s), ${found.length} note(s)`); } catch (error) { setStatus(`relay: ${describe(error)}`); } render();}
/** * The document a note lives in. * * Three answers, in order of authority: the relay URL this session walked to, * the `docId` a record carries, and finally the local mapping this device * keeps. The third exists only because the first two can be absent; a note * that has a `docId` belongs to that document, not to a new one. * * `null` means the note names a document this device cannot reach — see * `openNote`, which keeps the note editable without inventing a second history * under the same id. */async function handleFor(note: SceneNote): Promise<doc.Handle | null> { const url = note.record.__url; if (typeof url === "string" && url) return await repo.find<doc.NoteDoc>(url as never); if (note.docId) return await findDocument(repo, note.docId); return await documentFor(repo, String(note.record.noteId ?? note.rkey));}
/** * The handle to edit with — the note's own document, or this device's copy * when the note names one it cannot reach. * * Callers that read or write text should use this, not `documentFor`: a note * with a `docId` must never be edited through a newly minted document, or the * manifest records heads from a document nobody else has. */async function workingHandle(note: SceneNote): Promise<doc.Handle> { const bound = await handleFor(note); // A record may name a document this device has never seen — the relay is not // attached, or this member is not in that workspace. Editing still has to // work, so the note falls back to a device-local document and says so. It // does **not** mint a document under the record's id: two clients seeding the // same id with their own history is the one thing Automerge warns against. if (bound) return bound; return await documentFor(repo, String(note.record.noteId ?? note.rkey));}
async function publish(note: SceneNote, title: string): Promise<void> { if (!state.session) return; // The editor holds the whole file, so the text is what the note is — never // re-composed from parsed properties, which would normalise line endings when // the spec says `content` is the file's text exactly. const text = note.raw ?? join(note.head, note.body); // **The document we are editing, not the one the record mentions.** A relay // note knows its id from the URL it was opened by; everything else passes // none, and `buildRecord` keeps whatever the record already said. const boundUrl = typeof note.record.__url === "string" ? note.record.__url : ""; const record = await buildRecord( note.record.noteId ? note.record : undefined, title, text, boundUrl ? docIdOf(boundUrl) : note.docId, ); // A note that came from a file keeps that file's name. Renaming it on publish // would leave the original on disk beside a new copy of the same note. if (state.currentLocal) record.path = state.currentLocal; // A note that lives in a workspace already has a path, and it is the file's // name there — the record should say where the note is, not where its title // would put it. else if (note.path) record.path = note.path; // A record key is a TID. A note that came from disk has an id but no key, and // its derived id is not a valid one. const rkey = note.rkey || newTid();
try { await putNote(state.session, COLLECTION, rkey, record); state.dirty = false; state.currentLocal = null; await refresh(); await scanFolder(); // Open the record that now exists, rather than leaving the editor bound to // whatever handle the unsaved note had: the note has an identity, and with // it a document, at exactly this moment. const fresh = state.notes.find((n) => n.rkey === rkey); if (fresh) await openNote(fresh); setStatus(`saved ${record.path}`, { href: `https://pdsls.dev/at://${state.session.did}/${COLLECTION}/${rkey}`, label: "view record on pdsls", });
// The record is published; the mirror is a separate promise to a separate // place, and its failure must not read as a failed save. if (state.folder && state.current) { try { await writeNote(state.folder, state.current); // The base: what the file holds now, and the document state it came // from. Without this a later disk edit is invisible. const handle = await workingHandle(state.current); mirror.remember(filenameOf(state.current), doc.read(handle) || join(state.current.head, state.current.body), doc.heads(handle)); } catch (error) { const message = error instanceof FolderError ? error.message : describe(error); setStatus(`saved ${record.path} — folder not updated: ${message}`, { href: `https://pdsls.dev/at://${state.session.did}/${COLLECTION}/${rkey}`, label: "view record on pdsls", }); state.folderPermission = await permissionOf(state.folder).catch(() => "prompt"); } } } catch (error) { const message = describe(error); // The likeliest failure on a real setup is not a broken writer but a // session granted before the notes scope existed: the token is valid, the // record is refused, and "ScopeMissingError" means nothing to a person. state.status = /scope/i.test(message) ? "save failed: this session was approved before note-writing was asked for — sign out, sign in again, and accept writing notes" : `save failed: ${message}`; } render();}
async function openNote(note: SceneNote): Promise<void> { state.current = note; // The open note is no longer the file we were looking at; leaving this set // would keep pointing the list's active row at the wrong thing. state.currentLocal = null;
// A note that has never been published has no identity, so no document: // `documentFor` would key it on the literal string "undefined" and give every // unsaved note the same one. The editor holds its text until Save. const identity = String(note.record.noteId ?? note.rkey ?? ""); if (!identity && !note.record.__url) { openHandle = null; state.dirty = true; render(); return; }
const bound = await handleFor(note); // A record may name a document this device has never seen — the relay is not // attached, or this member is not in that workspace. Editing still has to // work, so the note falls back to a device-local document and says so. It // does **not** mint a document under the record's id: two clients seeding the // same id with their own history is the one thing Automerge warns against. const handle = bound ?? (await documentFor(repo, String(note.record.noteId ?? note.rkey))); if (!bound && note.docId) { setStatus(`${note.path}: its document is not reachable here — editing a local copy`); }
const stored = doc.read(handle); // What the PDS has, before the document is allowed to overwrite it — the // comparison below is "has this note changed since it was published". const published = join(note.head, note.body);
if (!stored) { // First sight of this note on this device: seed the document from the PDS. doc.seed(handle, published); } else { // **The document wins.** It holds whatever was typed since the last save and // survives a reload; the record does not know about those edits yet, so // reading the record here would quietly discard them. const { properties, body, head } = splitFrontmatter(stored); note.properties = properties; note.body = body; note.head = head; }
state.dirty = stored !== "" && stored !== published; openHandle = handle; render(); scheduleActivity(); void refreshPeople();}
async function refresh(): Promise<void> { if (!state.session) return; try { const records = await listNotes(state.session.did, COLLECTION); const notes: SceneNote[] = []; const skipped: string[] = []; for (const record of records) { try { notes.push(noteFromRecord(record.rkey, record.value)); } catch (error) { // One unreadable record must not take the list with it. skipped.push(`${record.rkey}: ${(error as Error).message}`); } } state.notes = notes.sort((a, b) => b.updated.localeCompare(a.updated)); if (skipped.length) setStatus(`list: skipped ${skipped.length} unreadable note(s) — ${skipped[0]}`); } catch (error) { setStatus(`list failed: ${(error as Error).message}`); }}
async function boot(): Promise<void> { // **The loopback IP, not the name.** Corliss's redirect check ignores the port // on a loopback host and compares the host exactly — `localhost` and `127.0.0.1` // are different hosts to it, and the client document declares the IP. So an app // opened at `localhost:5173` asks for a redirect that was never registered. // // Redirecting once, at boot, keeps the whole flow on one origin: the pending // state and the callback both live in that origin's sessionStorage, so splitting // them across two hostnames would lose the sign-in rather than fix it. // A design fixture, not a feature: `?preview=sidebar` fills the column with a // plausible account so the layout can be looked at without a sign-in. The // `import.meta.env.DEV` branch is compiled out of a production build. if (import.meta.env.DEV && new URLSearchParams(window.location.search).has("preview")) { previewSidebar(); render(); return; }
if (window.location.hostname === "localhost") { const { protocol, port, pathname, search, hash } = window.location; window.location.replace(`${protocol}//127.0.0.1${port ? `:${port}` : ""}${pathname}${search}${hash}`); return; }
// A sign-in may have just come back in the URL. Do this first: it is the only // moment the code exists. try { const finished = await corliss.complete(); if (finished) { state.syncUrl = finished.syncUrl; setStatus(`sync: signed in to ${finished.syncUrl}`); } } catch (error) { setStatus(`sync: ${describe(error)}`); }
// Presence goes away by itself when someone closes a tab; being *away* is a // clock, so the row repaints on one rather than waiting for a change. window.setInterval(() => paintPeople(), 30_000);
const remembered = corliss.stored(); if (remembered) { state.syncUrl = remembered.syncUrl; // Before the first render, so the socket opens while the app boots. await startSync(); }
// The client id is what the authorization server judges, and a wrong one fails // in a way that looks like nothing happened — worth having in the console, // not worth a line of UI. console.debug("scn-local client_id:", clientId()); state.folder = await storedFolder().catch(() => null); if (state.folder) { state.folderPermission = await permissionOf(state.folder).catch(() => "prompt"); await scanFolder(); } state.session = await restore().catch(() => null);
// By now both sign-ins have had their chance at the callback. Anything left in // the query is spent, and a leftover `?code=` becomes the redirect URI of the // next attempt — which is how a deployed sign-in failed with "redirect_uri not // registered" while showing a URL that already had a code in it. if (new URLSearchParams(window.location.search).has("code")) { history.replaceState({}, "", window.location.pathname + window.location.hash); } if (state.session) { setStatus("signed in"); state.profile = await getProfile(state.session.did).catch(() => null); await refresh(); } else { setStatus("signed out"); } render();}
void boot();