diff --git a/README.md b/README.md index b66dc47..2b98693 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n - Saves are handled like a game: the main menu's "Load game" lists every save (open, rename, copy, delete, savegames, recently deleted, new, open a file), and in the editor Esc (with nothing selected) or the project button opens the pause menu: Resume, Save, Save as copy, Load, Settings, How to play, Main menu. Export a project file, open a file as a new project, or add the components of a file to the open project. - Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). One save per project on every device: if two computers changed the same project, the newer save wins everywhere and the other one is kept as a savegame of that project (never as a second project). A new browser keeps its starter project unsaved until something changes in it, and while signed in the main menu waits for the account's saves before anything can be started, so a second device never makes a twin. - Share links: `/p/`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link. -- Memory that stays: what latches, flip-flops, registers and RAM built from NANDs hold is kept per circuit, like a memory chip. Going into a component and back, reloading, or opening the project on another computer, a circuit starts from the bits it held. They are saved with the project (only the gates on feedback loops that are 1, plus the clocks that are high: 1,024 flip-flops take about 30 KB), whenever it is saved anyway. Between saves (a clock running, a button pressed) they go into this browser's copy every 30 seconds and when the page is left, without counting as a change, so they never start a sync or a savegame of their own; the account gets them with the next save. "Power off and on" (menu on the circuit's name, or Space) starts the circuit again from all zeros. Switches keep their positions as before; buttons are let go. +- Memory that stays: what latches, flip-flops, registers and RAM built from NANDs hold is kept per circuit, like a memory chip. Going into a component and back, reloading, or opening the project on another computer, a circuit starts from the bits it held. They are saved with the project (only the gates on feedback loops that are 1, plus the clocks that are high: 1,024 flip-flops take about 30 KB), whenever it is saved anyway. Between saves (a clock running, a button pressed) they go into this browser's copy every 30 seconds without counting as an edit; the account gets them when you leave the page or the project or sign out, never just because a clock runs, and an edit saved on another computer still wins over bits alone. A project that comes in (a newer save from another computer, a savegame) runs from its own bits. Each project has room for 500 KB of bits (roughly 15,000 flip-flops) on top of its 2 MB; when that is full, the circuits left longest ago start from 0, and a circuit that holds more than that on its own says so. "Power off and on" (menu on the circuit's name, or Space) starts the circuit again from all zeros. Switches keep their positions as before; buttons are let go. - Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted. - 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence. - Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, a counter demo with a hex display, and a 4×4 pixel screen with a demo. @@ -66,7 +66,7 @@ The editor UI is in [app/components/editor/](app/components/editor/) with state ## Accounts -[server/api/auth/](server/api/auth/) (register, login, logout, me, password, delete) and [server/api/me/projects/](server/api/me/projects/) (list, get, put, delete). Passwords are hashed with scrypt; the session is a random token in an httpOnly, SameSite=Lax cookie, stored server-side as a SHA-256. API calls that change something are refused when their Origin is another site. Storage: `data/users`, `data/sessions`, `data/accounts//` with an index (revision per project, deletions for a year), one file per project, and savegames in `h//`. Each save sends the revision it started from; a mismatch answers 409 and the browser keeps the other version as a copy. Limits: 1000 projects and 100 MB per account, 2 MB per project, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP. +[server/api/auth/](server/api/auth/) (register, login, logout, me, password, delete) and [server/api/me/projects/](server/api/me/projects/) (list, get, put, delete). Passwords are hashed with scrypt; the session is a random token in an httpOnly, SameSite=Lax cookie, stored server-side as a SHA-256. API calls that change something are refused when their Origin is another site. Storage: `data/users`, `data/sessions`, `data/accounts//` with an index (revision per project, deletions for a year), one file per project, and savegames in `h//`. Each save sends the revision it started from; a mismatch answers 409 and the browser keeps the other version as a copy. Limits: 1000 projects and 100 MB per account, 2 MB per project plus 500 KB for what its circuits hold, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP. ## Power cuts, savegames, backups diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts index 408f2da..04b05dd 100644 --- a/app/composables/useEditor.ts +++ b/app/composables/useEditor.ts @@ -53,7 +53,7 @@ import { type SwapTarget, } from '~/lib/logic/ops' import { arrangeNodes, byPosition, numberedNames, seriesLinks, type Arrange, type Link } from '~/lib/logic/bulk' -import { parseProject, toProject } from '~/lib/logic/project' +import { parseProject, toProject, trimState } from '~/lib/logic/project' import { Simulator } from '~/lib/logic/sim' import { packState, stateCarry } from '~/lib/logic/state' import { @@ -214,17 +214,20 @@ function create() { saveTimer = undefined // An untouched starter project is not saved (see initial()). if (placeholder) return - keepState() + // Bits that changed on their own (a clock, a button) go to the account too, but are no + // edit: the save time stays, so an edit saved on another computer still wins over them. + const bitsOnly = (keepState() || unsent) && !changed + unsent = false meta.value = { ...meta.value, name: project.value.name, - updated: Date.now(), + ...(bitsOnly ? {} : { updated: Date.now() }), ...(project.value.mode ? { mode: project.value.mode } : {}), - ...(changed ? { dirty: true, starter: undefined } : {}), + ...(changed ? { dirty: true, starter: undefined } : bitsOnly ? { dirty: true } : {}), } if (!saveProject(toRaw(meta.value), toRaw(project.value))) notify('Browser storage is full. Export your project to keep it.', 'error') projects.value = listProjects() - if (changed) scheduleCloud() + if (changed || bitsOnly) scheduleCloud() changed = false } @@ -358,32 +361,56 @@ function create() { const id = def.value.id if (!s || simRoot !== `${meta.value.id}/${id}`) return false const held = packState(s) - if (JSON.stringify(held) === JSON.stringify(project.value.state?.[id])) return false + const before = project.value.state?.[id] + if (JSON.stringify(held) === JSON.stringify(before)) return false setHeld(id, held) + if (held && !project.value.state?.[id]) { + // More than a project keeps: said once, and the circuit starts from 0 when it opens again. + if (!full.has(id)) notify('This circuit holds too many bits to keep: it starts from 0 when it opens again', 'error') + full.add(id) + return !!before + } return true } - /** What a circuit holds in the project; undefined forgets it. */ + /** Circuits whose bits were too many to keep, so that is said only once. */ + const full = new Set() + + /** What a circuit holds in the project, as the newest entry; undefined forgets it. The oldest go when there are too many bits. */ function setHeld(id: string, held: HeldState | undefined) { const state = { ...project.value.state } + delete state[id] if (held) state[id] = held - else delete state[id] - if (Object.keys(state).length) project.value.state = state + const kept = trimState(state) + if (Object.keys(kept).length) project.value.state = kept else delete project.value.state } + /** Bits put in this browser's copy that the account does not have yet. */ + let unsent = false + /** * What the open circuit holds, put in this browser's copy between saves - * (a clock running, a button pressed) without counting as a change, so it - * never starts a save or a sync of its own; the account gets it with the - * next save. A save that is due happens now instead. A save made since in - * another tab is never overwritten for the bits alone. + * (a clock running, a button pressed) without counting as an edit: no undo + * step, and the save time stays, so an edit saved on another computer wins + * over bits alone. The account gets them when the page is left (`leaving`), + * never just because a clock runs. A save that is due happens now instead. + * A save made since in another tab is never overwritten for the bits alone. */ - function saveState() { + function saveState(leaving = false) { if (saveTimer) return persistNow() const saved = listProjects().find(m => m.id === meta.value.id) - if (placeholder || saved?.updated !== meta.value.updated || !keepState()) return + if (placeholder || saved?.updated !== meta.value.updated) return + const held = keepState() + unsent ||= held + const send = leaving && unsent + if (!held && !send) return + if (send) { + meta.value = { ...meta.value, dirty: true } + unsent = false + } saveProject(toRaw(meta.value), toRaw(project.value)) + if (send) scheduleCloud() } /** Power off and on: the open circuit forgets what it held and starts again from all zeros. */ @@ -1770,6 +1797,9 @@ function create() { linkState.value = m.link ? (m.link.key ? 'saved' : 'viewer') : 'none' projects.value = listProjects() syncUrl() + // A project that arrives (another computer's newer save, a savegame) runs from the bits it brings, even with the same circuit open. + simRoot = '' + unsent = false rebuild() } @@ -2002,8 +2032,8 @@ function create() { } } - window.addEventListener('beforeunload', saveState) - document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && saveState()) + window.addEventListener('beforeunload', () => saveState(true)) + document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && saveState(true)) setInterval(saveState, 30_000) // ── Account ─────────────────────────────────────────────────────── @@ -2199,7 +2229,11 @@ function create() { async function signOut(removeHere: boolean) { const uid = account.value?.id - if (uid) await syncAccount() + if (uid) { + // Bits not sent yet are sent now, so removing the projects here does not lose them. + saveState(true) + await syncAccount() + } await authCall('POST', '/api/auth/logout').catch(() => {}) setAccount(null) if (removeHere && uid) { @@ -2260,7 +2294,7 @@ function create() { * state (which the server keeps as a savegame first, so this can be undone). */ async function restoreVersion(projectId: string, v: number, asCopy: boolean) { - if (projectId === meta.value.id && saveTimer) persistNow() + persistNow() const p = await fetchVersion(projectId, v) if (asCopy) { p.name = `${p.name} (${new Date(v).toLocaleDateString()})` diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts index 964c0bb..4fdef53 100644 --- a/app/lib/logic/project.ts +++ b/app/lib/logic/project.ts @@ -107,8 +107,8 @@ function cleanDesign(d: ComponentDef) { } } -/** Upper bounds for a project that comes from outside. */ -export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 } +/** Upper bounds for a project that comes from outside. What its circuits hold has its own room (`state`) on top of `bytes`. */ +export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000, state: 500_000 } /** Checks and normalises project data. Throws with a readable message. */ export function toProject(data: unknown): Project { @@ -161,7 +161,27 @@ function stateOf(raw: unknown, components: ComponentDef[]): Record): Record { + const ids = Object.keys(state) + const kept = new Set() + let room = LIMITS.state + for (let i = ids.length - 1; i >= 0; i--) { + const id = ids[i]! + const size = id.length + JSON.stringify(state[id]).length + 4 + if (size > room) continue + room -= size + kept.add(id) + } + return kept.size === ids.length ? state : Object.fromEntries(ids.filter(id => kept.has(id)).map(id => [id, state[id]!])) } /** Challenge records: challenge id → fewest transistors, whole non-negative numbers only. */ @@ -207,7 +227,7 @@ function puzzlesOf(raw: unknown): PuzzleSpec[] | null { } export function parseProject(json: string): Project { - if (json.length > LIMITS.bytes) throw new Error('File too large') + if (json.length > LIMITS.bytes + LIMITS.state) throw new Error('File too large') let data: unknown try { data = JSON.parse(json) diff --git a/server/api/me/projects/[id]/index.put.ts b/server/api/me/projects/[id]/index.put.ts index 89ca8e9..ed2ffee 100644 --- a/server/api/me/projects/[id]/index.put.ts +++ b/server/api/me/projects/[id]/index.put.ts @@ -1,4 +1,4 @@ -import { toProject } from '../../../../../app/lib/logic/project' +import { LIMITS, toProject } from '../../../../../app/lib/logic/project' import type { CloudMeta } from '../../../../utils/accounts' // Save a project to the account. `baseRev` is the revision the device last // had; if another device saved in between, this answers 409 with the newer @@ -9,7 +9,7 @@ export default defineEventHandler(async event => { const id = getRouterParam(event, 'id') if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' }) const raw = await readRawBody(event, 'utf8') - if (!raw || raw.length > 2_100_000) throw createError({ statusCode: 413, message: 'Project too large' }) + if (!raw || raw.length > 2_100_000 + LIMITS.state) throw createError({ statusCode: 413, message: 'Project too large' }) let body: { project?: unknown; baseRev?: unknown; force?: unknown; link?: unknown; snapshot?: unknown } try { body = JSON.parse(raw) diff --git a/server/api/me/projects/[id]/versions.post.ts b/server/api/me/projects/[id]/versions.post.ts index 6428f30..302781a 100644 --- a/server/api/me/projects/[id]/versions.post.ts +++ b/server/api/me/projects/[id]/versions.post.ts @@ -1,4 +1,4 @@ -import { toProject } from '../../../../../app/lib/logic/project' +import { LIMITS, toProject } from '../../../../../app/lib/logic/project' // Keep a device's own version of a project as a savegame, without making it // the current one. Used when another device saved something newer: the newer // save wins, and this one stays restorable from the project's savegames. @@ -8,7 +8,7 @@ export default defineEventHandler(async event => { const id = getRouterParam(event, 'id') if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' }) const raw = await readRawBody(event, 'utf8') - if (!raw || raw.length > 2_100_000) throw createError({ statusCode: 413, message: 'Project too large' }) + if (!raw || raw.length > 2_100_000 + LIMITS.state) throw createError({ statusCode: 413, message: 'Project too large' }) let body: { project?: unknown; baseRev?: unknown } try { body = JSON.parse(raw) diff --git a/server/utils/shares.ts b/server/utils/shares.ts index df7c247..2ed95cb 100644 --- a/server/utils/shares.ts +++ b/server/utils/shares.ts @@ -50,7 +50,7 @@ export function rateLimit(event: H3Event, bucket: string, max: number, windowMs: export async function readProjectBody(event: H3Event): Promise { const raw = await readRawBody(event, 'utf8') if (!raw) throw createError({ statusCode: 400, message: 'Empty request' }) - if (raw.length > LIMITS.bytes) throw createError({ statusCode: 413, message: 'Project too large to share' }) + if (raw.length > LIMITS.bytes + LIMITS.state) throw createError({ statusCode: 413, message: 'Project too large to share' }) let body: { project?: unknown } try { body = JSON.parse(raw) diff --git a/tests/state-editor.test.ts b/tests/state-editor.test.ts new file mode 100644 index 0000000..436d173 --- /dev/null +++ b/tests/state-editor.test.ts @@ -0,0 +1,344 @@ +// The editor itself keeping what circuits hold: going into a component and +// back, reloading, other projects, and the account on other computers. It +// runs the real composable in a stand-in browser (storage, events, a server). + +import * as vue from 'vue' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { compile } from '../app/lib/logic/compile' +import { chipPins } from '../app/lib/logic/geometry' +import { createProject, lookup } from '../app/lib/logic/ops' +import { toProject } from '../app/lib/logic/project' +import { Simulator } from '../app/lib/logic/sim' +import { packState, stateCarry } from '../app/lib/logic/state' +import { listProjects, loadProject, saveProject, setCachedAccount, setCurrentId, type ProjectMeta } from '../app/lib/logic/storage' +import type { Project } from '../app/lib/logic/types' + +const USER = { id: 'u1', email: 'me@example.com' } + +/** An SR latch with two buttons, so its bit changes without any edit, open as the circuit. */ +function latchProject(): Project { + const p = createProject({ examples: true }) + const pins = chipPins(lookup(p)('ex-sr')!) + const pin = (label: string) => pins.inputs.find(x => x.label === label)!.key + p.components.push({ + id: 'mem', + name: 'Memory', + symbol: 'box', + nodes: [ + { id: 's', kind: 'button', x: 0, y: 0, label: 'S' }, + { id: 'r', kind: 'button', x: 0, y: 4, label: 'R' }, + { id: 'u', kind: 'chip', chip: 'ex-sr', x: 6, y: 0 }, + { id: 'q', kind: 'output', x: 20, y: 0, label: 'Q' }, + ], + wires: [ + { id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'u', pin: pin('S') } }, + { id: 'w2', from: { node: 'r', pin: 'q' }, to: { node: 'u', pin: pin('R') } }, + { id: 'w3', from: { node: 'u', pin: pins.outputs[0]!.key }, to: { node: 'q', pin: 'a' } }, + ], + }) + p.openId = 'mem' + return p +} + +/** This browser's storage, kept across "reloads". */ +let store: Map + +/** A tab with the editor open: the stand-in browser around it, then the real composable. */ +async function openTab() { + const events = new Map void)[]>() + const on = (type: string, f: () => void) => events.set(type, [...(events.get(type) ?? []), f]) + const doc = { addEventListener: on, visibilityState: 'visible' } + vi.stubGlobal('window', { addEventListener: on }) + vi.stubGlobal('document', doc) + vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' }) + vi.stubGlobal('history', { state: null, replaceState() {} }) + for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch'] as const) vi.stubGlobal(k, vue[k]) + vi.resetModules() + const { useEditor } = await import('../app/composables/useEditor') + const ed = useEditor() + const fire = (type: string) => events.get(type)?.forEach(f => f()) + return { + ed, + /** Q of the latch as the editor shows it. */ + q: () => ed.val('q', 'a'), + /** A click on a button of the open circuit: down, settle, up, settle. */ + push(label: string) { + const node = ed.def.value.nodes.find(n => n.label === label)! + ed.press(node, true) + ed.sim.value!.run() + ed.press(node, false) + ed.sim.value!.run() + }, + hide() { + doc.visibilityState = 'hidden' + fire('visibilitychange') + }, + close: () => fire('beforeunload'), + } +} + +/** Puts a project in this browser's storage and makes it the one that opens. */ +function stored(p: Project, meta: Partial = {}): ProjectMeta { + const m: ProjectMeta = { id: 'p1', name: p.name, updated: Date.now(), ...meta } + saveProject(m, p) + setCurrentId(m.id) + return m +} + +const copy = (v: T): T => JSON.parse(JSON.stringify(v)) + +/** Q of the latch in a saved project, as it opens from what it held. */ +function bitOf(p: Project): number { + const nl = compile(lookup(p), 'mem') + const held = p.state?.mem + const s = new Simulator(nl, held && stateCarry(held, nl)) + s.run() + return s.pin('q', 'a') +} + +/** The project after the latch was set on another computer. */ +function setElsewhere(p: Project): Project { + const s = new Simulator(compile(lookup(p), 'mem')) + for (const [id, on] of [['s', true], ['s', false]] as const) { + s.setSource(id, on) + s.run() + } + p.state = { mem: packState(s)! } + return p +} + +/** The account on the server, as far as syncing uses it: one save per project with its revision, and savegames. */ +function account() { + const saves = new Map() + const versions = new Map() + const keep = (id: string, project: Project) => { + const list = versions.get(id) ?? [] + list.push({ v: Date.now() + list.length, project }) + versions.set(id, list) + } + const put = (id: string, project: Project) => { + const old = saves.get(id) + if (old) keep(id, old.project) + const meta = { id, name: project.name, updated: Date.now(), rev: (old?.meta.rev ?? 0) + 1 } + saves.set(id, { meta, project: toProject(copy(project)) }) + return meta + } + const route = (method: string, url: string, body: Record): [number, unknown] => { + if (url === '/api/auth/me') return [200, { user: USER }] + if (url === '/api/auth/logout') return [200, {}] + if (url === '/api/me/projects') return [200, { projects: [...saves.values()].map(s => s.meta), deleted: [] }] + const [, id, rest] = url.match(/^\/api\/me\/projects\/([^/]+)(.*)$/) ?? [] + if (!id) return [404, {}] + const save = saves.get(id) + if (rest === '' && method === 'GET') return save ? [200, { project: copy(save.project) }] : [404, {}] + if (rest === '' && method === 'PUT') { + if (save && save.meta.rev !== body.baseRev && body.force !== true) return [409, { conflict: true, meta: save.meta }] + return [200, { meta: put(id, body.project as Project) }] + } + if (rest === '/versions' && method === 'POST') return [200, keep(id, toProject(copy(body.project)))] + if (rest === '/versions') return [200, { versions: (versions.get(id) ?? []).map(x => ({ v: x.v, at: x.v, rev: 0, name: x.project.name, size: 0 })) }] + const v = versions.get(id)?.find(x => `/versions/${x.v}` === rest) + return v ? [200, { version: { project: copy(v.project) } }] : [404, {}] + } + vi.stubGlobal('fetch', async (url: string, init: { method?: string; body?: string } = {}) => { + const [status, data] = route(init.method ?? 'GET', url, init.body ? JSON.parse(init.body) : {}) + return { ok: status < 400, status, json: async () => data } + }) + setCachedAccount(USER) + return { saves, versions, put } +} + +/** Lets the timers due in `ms` run, and the requests they start finish. */ +async function wait(ms: number) { + await vi.advanceTimersByTimeAsync(ms) + await new Promise(r => setImmediate(r)) +} + +beforeEach(() => { + store = new Map() + vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => void store.set(k, String(v)), + removeItem: (k: string) => void store.delete(k), + }) + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] }) +}) + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +describe('the editor keeping what circuits hold', () => { + it('keeps a bit set with buttons when you go into a component and come back, and after a reload', async () => { + stored(latchProject()) + let tab = await openTab() + expect(tab.q()).toBe(0) + tab.push('S') + expect(tab.q()).toBe(1) + tab.ed.open('ex-sr') + tab.ed.back() + expect(tab.q()).toBe(1) + tab.ed.open('ex-sr') + tab.ed.goMain() + tab.ed.goTo(0) + tab.ed.open('mem') + expect(tab.q()).toBe(1) + tab.push('R') + tab.push('S') + tab.close() + tab = await openTab() + expect(tab.q()).toBe(1) + }) + + it('does not mix the bits of two projects with the same circuits', async () => { + const a = stored(latchProject()) + const b = { ...a, id: 'p2', name: 'Other' } + saveProject(b, latchProject()) + setCurrentId(a.id) + const tab = await openTab() + tab.push('S') + tab.ed.switchProject(b.id) + expect(tab.q()).toBe(0) + tab.ed.switchProject(a.id) + expect(tab.q()).toBe(1) + }) + + it('saves the bits of the circuit used last, and drops the oldest when there are too many', async () => { + const p = latchProject() + const filler = { names: [], on: 'x'.repeat(300_000) } + p.state = { main: filler, 'ex-sr': filler } + stored(p) + const tab = await openTab() + tab.push('S') + tab.ed.persist() + await wait(300) + const saved = loadProject('p1')! + expect(Object.keys(saved.state!)).toEqual(['ex-sr', 'mem']) + expect(bitOf(saved)).toBe(1) + }) + + it('says so once when a circuit holds more bits than a project keeps, and starts it from 0', async () => { + stored(latchProject()) + const tab = await openTab() + // The editor's own limits: a room so small that one latch is already too much. + const { LIMITS } = await import('../app/lib/logic/project') + LIMITS.state = 10 + tab.push('S') + tab.ed.open('ex-sr') + expect(tab.ed.notice.value).toEqual({ text: expect.stringContaining('too many bits'), kind: 'error' }) + tab.ed.back() + expect(tab.q()).toBe(0) + tab.ed.notice.value = null + tab.push('S') + tab.ed.open('ex-sr') + tab.ed.back() + expect(tab.ed.notice.value).toBeNull() + }) + + it('takes the bits of a newer save from another computer, also for the circuit that is open', async () => { + const server = account() + // Here: revision 1, the latch at 0. The other computer saved revision 2 with the latch at 1. + stored(latchProject(), { cloud: { owner: USER.id, rev: 1 } }) + server.put('p1', latchProject()) + server.put('p1', setElsewhere(latchProject())) + const tab = await openTab() + expect(tab.q()).toBe(0) + await tab.ed.startAccount() + expect(tab.q()).toBe(1) + // The next save here keeps that 1 instead of writing this computer's old 0 over it. + await tab.ed.saveNow() + expect(server.saves.get('p1')!.meta.rev).toBe(3) + expect(bitOf(server.saves.get('p1')!.project)).toBe(1) + }) + + it('brings back the bits of a savegame, so Power off and on can be undone', async () => { + const server = account() + stored(latchProject()) + const tab = await openTab() + await tab.ed.startAccount() + tab.push('S') + await tab.ed.saveNow() + tab.ed.resetState() + expect(tab.q()).toBe(0) + await tab.ed.saveNow() + expect(bitOf(server.saves.get('p1')!.project)).toBe(0) + const before = server.versions.get('p1')!.at(-1)! + expect(bitOf(before.project)).toBe(1) + await tab.ed.restoreVersion('p1', before.v, false) + expect(tab.q()).toBe(1) + }) + + it('sends bits set with buttons to the account when the page is left, not before', async () => { + const server = account() + stored(latchProject()) + const tab = await openTab() + await tab.ed.startAccount() + tab.push('S') + // A running page writes the bits only to this browser. + await wait(61_000) + expect(bitOf(loadProject('p1')!)).toBe(1) + expect(server.saves.get('p1')!.meta.rev).toBe(1) + tab.hide() + await wait(2_000) + expect(server.saves.get('p1')!.meta.rev).toBe(2) + expect(bitOf(server.saves.get('p1')!.project)).toBe(1) + }) + + it('lets an edit saved on another computer win over bits changed here', async () => { + const server = account() + stored(latchProject()) + const tab = await openTab() + await tab.ed.startAccount() + tab.push('S') + await wait(5_000) + const edited = latchProject() + edited.name = 'Edited elsewhere' + server.put('p1', edited) + tab.hide() + await wait(2_000) + expect(tab.ed.project.value.name).toBe('Edited elsewhere') + expect(server.saves.get('p1')!.project.name).toBe('Edited elsewhere') + // The bits of this computer are in the project's savegames. + expect(bitOf(server.versions.get('p1')!.at(-1)!.project)).toBe(1) + }) + + it('marks bits for the account when you leave the project, as no edit', async () => { + const a = stored(latchProject()) + saveProject({ ...a, id: 'p2', name: 'Other' }, latchProject()) + setCurrentId(a.id) + const tab = await openTab() + tab.push('S') + await wait(5_000) + tab.ed.switchProject('p2') + const left = listProjects().find(m => m.id === a.id)! + expect(left.dirty).toBe(true) + expect(left.updated).toBe(a.updated) + expect(bitOf(loadProject(a.id)!)).toBe(1) + }) + + it('keeps bits set with buttons when signing out and removing the projects from this browser', async () => { + const server = account() + stored(latchProject()) + const tab = await openTab() + await tab.ed.startAccount() + tab.push('S') + await tab.ed.signOut(true) + expect(listProjects().some(m => m.id === 'p1')).toBe(false) + expect(bitOf(server.saves.get('p1')!.project)).toBe(1) + }) + + it('keeps the bits of the project it leaves when a savegame opens as a copy', async () => { + const server = account() + stored(latchProject()) + const tab = await openTab() + await tab.ed.startAccount() + tab.push('S') + server.put('p9', createProject({ examples: false })) + server.put('p9', createProject({ examples: false })) + await tab.ed.restoreVersion('p9', server.versions.get('p9')![0]!.v, true) + expect(tab.ed.meta.value.id).not.toBe('p1') + expect(bitOf(loadProject('p1')!)).toBe(1) + }) +}) + diff --git a/tests/state.test.ts b/tests/state.test.ts index 7b09319..6af0a75 100644 --- a/tests/state.test.ts +++ b/tests/state.test.ts @@ -3,10 +3,10 @@ import { describe, expect, it } from 'vitest' import { compile, type Netlist } from '../app/lib/logic/compile' import { chipPins } from '../app/lib/logic/geometry' import { createProject, lookup } from '../app/lib/logic/ops' -import { parseProject, toProject } from '../app/lib/logic/project' +import { LIMITS, parseProject, toProject, trimState } from '../app/lib/logic/project' import { Simulator } from '../app/lib/logic/sim' import { flow, packState, stateCarry } from '../app/lib/logic/state' -import type { CircuitNode, ComponentDef, Project } from '../app/lib/logic/types' +import type { CircuitNode, ComponentDef, HeldState, Project } from '../app/lib/logic/types' /** A D latch from the examples between two switches and an output pin, open as the circuit. */ function memory(): Project { @@ -294,4 +294,36 @@ describe('saving what circuits hold', () => { expect(open(back, 'mem').pin('q', 'a')).toBe(1) expect(toProject({ ...data, state: [1, 2] }).state).toBeUndefined() }) + + it('keeps the newest bits when there are more than a project has room for', () => { + const big = (n: number): HeldState => ({ names: [], on: 'x'.repeat(n) }) + // Newest last: c fits, b no longer does next to it, a still does. + const kept = trimState({ a: big(200_000), b: big(400_000), c: big(100_000) }) + expect(Object.keys(kept)).toEqual(['a', 'c']) + expect(JSON.stringify(kept).length).toBeLessThanOrEqual(LIMITS.state) + // One circuit with more than all the room: nothing of it is kept. + expect(trimState({ a: big(LIMITS.state) })).toEqual({}) + const small = { a: big(10) } + expect(trimState(small)).toBe(small) + }) + + it('never makes a project too large to load, however much its circuits hold', () => { + const p = memory() + const s = open(p, 'mem') + store1(p, s) + leave(p, 'mem', s) + // Older entries far over the room, as a hand-made or older file might have them, then the latch. + const filler = { names: [], on: '0:0 '.repeat(100_000).trim() } + p.state = { 'ex-sr': filler, 'ex-dlatch': filler, mem: p.state!.mem! } + expect(JSON.stringify(p.state).length).toBeGreaterThan(LIMITS.state) + const loaded = parseProject(JSON.stringify(p)) + expect(Object.keys(loaded.state!)).toEqual(['ex-dlatch', 'mem']) + expect(open(loaded, 'mem').pin('q', 'a')).toBe(1) + // As large as a project may be without its bits, with the bits on top: it still loads. + const { state, ...rest } = loaded + rest.components[0]!.description = 'x'.repeat(LIMITS.bytes - JSON.stringify(rest).length - 100) + const json = JSON.stringify({ ...rest, state }) + expect(json.length).toBeGreaterThan(LIMITS.bytes) + expect(parseProject(json).state).toEqual(state) + }) }) diff --git a/vitest.config.ts b/vitest.config.ts index 48eb1de..33c7317 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,8 @@ +import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' export default defineConfig({ + // Nuxt's "~" is the app folder, so tests can run the editor's composable too. + resolve: { alias: { '~': fileURLToPath(new URL('./app', import.meta.url)) } }, test: { include: ['tests/**/*.test.ts'] }, })