logigate/tests/state-editor.test.ts

345 lines
13 KiB
TypeScript
Raw Normal View History

BF memory: a newer save brings its own bits, bits reach the account when you leave, room for them A project that comes in with the same circuit open (a newer save from another computer, a savegame restored in place, a shared link opened again) now runs from the bits it brings. Before, the running circuit went on with this computer's old bits and wrote them over the newer ones at the next save, and a savegame could not undo Power off and on. Bits changed only by buttons or a clock are sent to the account when the page is hidden or closed, when you leave the project, and before signing out, so they are no longer lost by "remove from this browser" and reach the other computer. A running clock alone still sends nothing. Bits alone keep the project's save time, so an edit saved on another computer wins over them and they end up in its savegames. What circuits hold has its own room of 500 KB per project on top of the 2 MB limit, in the browser, the account and share links. When it is full, the circuits left longest ago start from 0; a circuit that holds more than that on its own says so once. A project can no longer become too large to load because of its memory. A savegame opened as a copy saves the project it leaves first, like every other way of switching projects. Tests now run the editor itself (in a stand-in browser with an account server) for going into components and back, reloads, two projects, other computers, savegames, signing out and the room limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:44:43 +00:00
// 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<string, string>
/** A tab with the editor open: the stand-in browser around it, then the real composable. */
async function openTab() {
const events = new Map<string, (() => 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> = {}): ProjectMeta {
const m: ProjectMeta = { id: 'p1', name: p.name, updated: Date.now(), ...meta }
saveProject(m, p)
setCurrentId(m.id)
return m
}
const copy = <T>(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<string, { meta: { id: string; name: string; updated: number; rev: number }; project: Project }>()
const versions = new Map<string, { v: number; project: Project }[]>()
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<string, unknown>): [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)
})
})