Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
dash: adopt the kernel save queue — the dot goes out only for the revision written (#634)
nyblnet54d0226f67f9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5a3b859c..9f5e3489 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -946,6 +946,14 @@ jobs:# auth or calls itself an Editor — an allowlist, failing closed.run: node scripts/test-dash-share-dirty.ts+ - name: bento/dash save race (kernel SaveQueue)+ # The unsaved dot goes out only for the revision that was written; a+ # dropped file's handle swap waits for the write in flight; an in-place+ # update stops the old shell from writing again. Each guard is+ # sabotaged in the PR that introduced it; the rig carries two controls+ # that reproduce the bugs without the guard.+ run: node scripts/test-dash-save-revisions.ts+- name: bento/dash conditional formattingrun: node scripts/test-dash-condfmt.tsdiff --git a/dash/CHANGELOG.md b/dash/CHANGELOG.mdindex cc9f34d4..b08f8174 100644--- a/dash/CHANGELOG.md+++ b/dash/CHANGELOG.md@@ -58,6 +58,25 @@ The release that came out of watching somebody use 0.2.0.the relay as write access and appeared as an Editor to everyone else. Only awriter copy now does either.+- **An edit made while a save is writing is no longer marked saved.** Every+ save — ⌘S, the automatic save to the file, Save a copy, Save as new workbook+ and the in-place update — now goes through one queue that writes a snapshot+ and clears the unsaved dot only if nothing changed while it was writing.+ Before, the dot went out when the write finished, so a keystroke made in that+ second was missing from the file and nothing said so.++- **Dropping a workbook onto the window can no longer write the old one into+ it.** An automatic save that was mid-write when the file was dropped used to+ finish into the NEW file's handle. The swap now waits for it.++- **After "Update this file", this window stops saving to it.** The page is+ still the old version, and its next automatic save would have put the old+ version back. ⌘S now says to reload first.++- **Save a copy clears the unsaved dot** when the copy holds everything — it is+ the file you carry on working in — and a failed copy says so instead of+ failing silently.+- **Sheet tabs along the bottom**, where every spreadsheet has kept them sinceExcel 5. They were a list inside the left panel; that panel is gone, and thegrid is about 200px wider at every window size. Drag to reorder — and becausediff --git a/dash/src/dropopen.ts b/dash/src/dropopen.tsindex 7e41a091..e9a520d6 100644--- a/dash/src/dropopen.ts+++ b/dash/src/dropopen.ts@@ -53,6 +53,7 @@ import { importXlsx, installNames } from './xlsx.ts'import { parseDoc } from './model.ts'import { swapWorkbook, type WorkbookHost } from './recovery.ts'import { adoptFileHandle, hasFileHandle, isEncryptionActive } from '../../kernel/src/save.ts'+import { afterPendingWrites } from './saving.ts'import { toast, forkTemplate, applyDocLock } from './saveui.ts'import { t } from './i18n.ts'@@ -353,12 +354,25 @@ async function openWorkbook(host: DropHost, item: DataTransferItem | undefined,// caller in recovery.ts needs this — those restore the SAME workbook, not a// foreign one.forkTemplate(res.doc)- if (!swapWorkbook(host, res.doc)) {+ // THE SWAP AND THE HANDLE CHANGE WAIT FOR EVERY WRITE AHEAD OF THEM+ // (saving.ts). An automatic save of the workbook being replaced may be+ // mid-serialize, and it reads the held handle only after that await — so+ // adopting B's handle under it wrote A's workbook into B, the file the user+ // had just dropped. Both halves run in one continuation, before any later+ // write can start, and any write of A still queued is discarded because the+ // workbook it was for is gone.+ const swapped = await afterPendingWrites(host.store, () => {+ if (!swapWorkbook(host, res.doc)) return false+ applyDocLock(res.doc, host.store)+ if (writable) adoptFileHandle(handle as never)+ else adoptFileHandle(null as never)+ return true+ })+ if (!swapped) {host.notice(t('“{name}” has no table sheet to show, so it was not opened.', { name }))return}- applyDocLock(res.doc, host.store)- // AFTER the swap, and only on success: the handle decides where ⌘S writes,+ // THE HANDLE, adopted above AFTER the swap and only on success: it decides where ⌘S writes,// so touching it earlier would aim the next save at a file whose contents are// not what is on screen.//@@ -375,8 +389,6 @@ async function openWorkbook(host: DropHost, item: DataTransferItem | undefined,// implementation is a bare assignment. The right fix is a `releaseFileHandle()`// beside it in kernel/src/save.ts; until that exists, this is the same// assignment spelled where the reason for it is written down.- if (writable) adoptFileHandle(handle as never)- else adoptFileHandle(null as never)toast(hasFileHandle()? t('Opened “{name}” — ⌘S writes it back', { name }): t('Opened “{name}” — ⌘S will save a copy', { name }))diff --git a/dash/src/i18n/de.ts b/dash/src/i18n/de.tsindex b989b335..bfe5b894 100644--- a/dash/src/i18n/de.ts+++ b/dash/src/i18n/de.ts@@ -750,5 +750,6 @@ export const de: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "„{name}“ hat das ältere Excel-Format. In Excel öffnen und als .xlsx speichern, dann kann dash sie lesen.","…or cut at character positions": "…oder an Zeichenpositionen schneiden","+ Comment on the selected cell": "+ Kommentar zur ausgewählten Zelle",+ "This file was updated. Reload to run the new version before saving again.": "Diese Datei wurde aktualisiert. Laden Sie neu, um die neue Version zu starten, bevor Sie erneut speichern.","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "Keine Zahl — aus den Summen ausgenommen, und eine Formel, die sie liest, ergibt #VALUE!",}diff --git a/dash/src/i18n/es.ts b/dash/src/i18n/es.tsindex 965751e9..7bdf596a 100644--- a/dash/src/i18n/es.ts+++ b/dash/src/i18n/es.ts@@ -750,5 +750,6 @@ export const es: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "“{name}” tiene el formato antiguo de Excel. Ábrelo en Excel y guárdalo como .xlsx, y dash podrá leerlo.","…or cut at character positions": "…o cortar en posiciones de carácter","+ Comment on the selected cell": "+ Comentar la celda seleccionada",+ "This file was updated. Reload to run the new version before saving again.": "Este archivo se ha actualizado. Recarga para ejecutar la nueva versión antes de volver a guardar.","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "No es un número: queda fuera de los totales, y una fórmula que lo lea da #VALUE!",}diff --git a/dash/src/i18n/fr.ts b/dash/src/i18n/fr.tsindex a26488fc..071b3a82 100644--- a/dash/src/i18n/fr.ts+++ b/dash/src/i18n/fr.ts@@ -750,5 +750,6 @@ export const fr: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "« {name} » est à l’ancien format Excel. Ouvrez-le dans Excel et enregistrez-le en .xlsx, et dash pourra le lire.","…or cut at character positions": "…ou couper à des positions de caractère","+ Comment on the selected cell": "+ Commenter la cellule sélectionnée",+ "This file was updated. Reload to run the new version before saving again.": "Ce fichier a été mis à jour. Rechargez pour lancer la nouvelle version avant d’enregistrer à nouveau.","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "Pas un nombre — exclu des totaux, et une formule qui le lit donne #VALUE!",}diff --git a/dash/src/i18n/it.ts b/dash/src/i18n/it.tsindex 9bca6077..16bf93b9 100644--- a/dash/src/i18n/it.ts+++ b/dash/src/i18n/it.ts@@ -750,5 +750,6 @@ export const it: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "“{name}” è nel vecchio formato Excel. Aprilo in Excel e salvalo come .xlsx, e dash lo leggerà.","…or cut at character positions": "…oppure taglia a posizioni di carattere","+ Comment on the selected cell": "+ Commenta la cella selezionata",+ "This file was updated. Reload to run the new version before saving again.": "Questo file è stato aggiornato. Ricarica per avviare la nuova versione prima di salvare di nuovo.","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "Non è un numero — escluso dai totali, e una formula che lo legge dà #VALUE!",}diff --git a/dash/src/i18n/ja.ts b/dash/src/i18n/ja.tsindex 6b0bfca4..66b3ce06 100644--- a/dash/src/i18n/ja.ts+++ b/dash/src/i18n/ja.ts@@ -750,5 +750,6 @@ export const ja: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "「{name}」は古い形式の Excel ファイルです。Excel で開いて .xlsx で保存すれば、dash が読み取れます。","…or cut at character positions": "…または文字位置で区切る","+ Comment on the selected cell": "+ 選択したセルにコメント",+ "This file was updated. Reload to run the new version before saving again.": "このファイルは更新されました。再度保存する前に、再読み込みして新しいバージョンを起動してください。","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "数値ではありません — 合計から除外され、これを参照する数式は #VALUE! になります",}diff --git a/dash/src/i18n/packed.ts b/dash/src/i18n/packed.tsindex cf05f41d..e052ce68 100644--- a/dash/src/i18n/packed.ts+++ b/dash/src/i18n/packed.ts@@ -554,6 +554,7 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {"This file": ["このファイル","此文件","此檔案","Este archivo","Ce fichier","Diese Datei","Questo file"],"This file could not be opened as a bento/dash workbook.": ["このファイルを bento/dash のブックとして開けませんでした。","此文件无法作为 bento/dash 工作簿打开。","此檔案無法以 bento/dash 活頁簿開啟。","No se ha podido abrir este archivo como libro de bento/dash.","Ce fichier n’a pas pu être ouvert comme classeur bento/dash.","Diese Datei konnte nicht als bento/dash-Arbeitsmappe geöffnet werden.","Non è stato possibile aprire questo file come cartella di lavoro bento/dash."],"This file is encrypted.": ["このファイルは暗号化されています。","此文件已加密。","此檔案已加密。","Este archivo está cifrado.","Ce fichier est chiffré.","Diese Datei ist verschlüsselt.","Questo file è cifrato."],+ "This file was updated. Reload to run the new version before saving again.": ["このファイルは更新されました。再度保存する前に、再読み込みして新しいバージョンを起動してください。","此文件已更新。请先重新加载以运行新版本,然后再保存。","此檔案已更新。請先重新載入以執行新版本,再進行儲存。","Este archivo se ha actualizado. Recarga para ejecutar la nueva versión antes de volver a guardar.","Ce fichier a été mis à jour. Rechargez pour lancer la nouvelle version avant d’enregistrer à nouveau.","Diese Datei wurde aktualisiert. Laden Sie neu, um die neue Version zu starten, bevor Sie erneut speichern.","Questo file è stato aggiornato. Ricarica per avviare la nuova versione prima di salvare di nuovo."],"This is now a new workbook — save it under a new name": ["これは新しいブックになりました — 別の名前で保存してください","这已经是一个新工作簿 — 请用新名称保存","這現在是一份新的活頁簿 — 請以新名稱儲存","Ahora esto es un libro nuevo: guárdalo con otro nombre","C’est désormais un nouveau classeur — enregistrez-le sous un nouveau nom","Das ist jetzt eine neue Arbeitsmappe — unter einem neuen Namen speichern","Ora questa è una nuova cartella di lavoro — salvala con un nuovo nome"],"This rule came from a later build of dash. It is kept in the file and written back out unchanged, and this build paints nothing for it.": ["このルールは新しいバージョンの dash で作られたものです。ファイルの中に保持してそのまま書き出しますが、このバージョンでは何も描画しません。","该规则来自更高版本的 dash。文件中会原样保留并写回,但当前版本不会为它绘制任何内容。","這條規則來自較新版本的 dash。檔案中會原樣保留並寫回,但這個版本不會為它繪製任何內容。","Esta regla viene de una versión posterior de dash. Se conserva en el archivo y se vuelve a escribir sin cambios, y esta versión no pinta nada para ella.","Cette règle vient d’une version plus récente de dash. Elle est conservée dans le fichier et réécrite telle quelle, et cette version ne dessine rien pour elle.","Diese Regel stammt aus einer neueren Version von dash. Sie bleibt in der Datei und wird unverändert zurückgeschrieben; diese Version zeichnet nichts dafür.","Questa regola arriva da una versione più recente di dash. Resta nel file e viene riscritta invariata, e questa versione non disegna nulla per essa."],"This rule came from a spreadsheet that evaluates it. dash keeps it and writes it back out unchanged, and does not check entries against it.": ["この規則は、それを評価するスプレッドシートから読み込まれました。dash は内容をそのまま保持して書き戻しますが、入力の検証には使いません。","此规则来自一个会计算它的电子表格。dash 会原样保留并写回,但不会用它检查输入。","此規則來自會計算它的試算表。dash 會原樣保留並寫回,但不會用它檢查輸入。","Esta regla viene de una hoja de cálculo que sí la evalúa. dash la conserva y la vuelve a escribir sin cambios, pero no comprueba las entradas con ella.","Cette règle vient d’un tableur qui, lui, l’évalue. dash la conserve et la réécrit telle quelle, sans vérifier les saisies avec.","Diese Regel stammt aus einer Tabellenkalkulation, die sie auswertet. dash bewahrt sie unverändert auf und schreibt sie so wieder heraus, prüft Eingaben aber nicht damit.","Questa regola arriva da un foglio di calcolo che la valuta. dash la conserva e la riscrive invariata, ma non la usa per controllare ciò che si digita."],diff --git a/dash/src/i18n/zh-Hans.ts b/dash/src/i18n/zh-Hans.tsindex ac9417ab..d12eff27 100644--- a/dash/src/i18n/zh-Hans.ts+++ b/dash/src/i18n/zh-Hans.ts@@ -750,5 +750,6 @@ export const zhHans: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "“{name}”是旧版 Excel 格式。请在 Excel 中打开并另存为 .xlsx,dash 就能读取。","…or cut at character positions": "…或按字符位置切分","+ Comment on the selected cell": "+ 为所选单元格添加评论",+ "This file was updated. Reload to run the new version before saving again.": "此文件已更新。请先重新加载以运行新版本,然后再保存。","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "不是数字 — 未计入合计,读取它的公式会得到 #VALUE!",}diff --git a/dash/src/i18n/zh-Hant.ts b/dash/src/i18n/zh-Hant.tsindex 4529849d..46e697c7 100644--- a/dash/src/i18n/zh-Hant.ts+++ b/dash/src/i18n/zh-Hant.ts@@ -750,5 +750,6 @@ export const zhHant: Catalog = {"“{name}” is the older Excel format. Open it in Excel and save it as .xlsx, and dash will read it.": "「{name}」是舊版的 Excel 格式。請在 Excel 中開啟並另存為 .xlsx,dash 就能讀取。","…or cut at character positions": "…或按字元位置切分","+ Comment on the selected cell": "+ 為選取的儲存格加註解",+ "This file was updated. Reload to run the new version before saving again.": "此檔案已更新。請先重新載入以執行新版本,再進行儲存。","Not a number — left out of totals, and a formula that reads it gives #VALUE!": "不是數字 — 未計入合計,讀取它的公式會得到 #VALUE!",}diff --git a/dash/src/main.ts b/dash/src/main.tsindex 91208efd..fa48161b 100644--- a/dash/src/main.ts+++ b/dash/src/main.ts@@ -47,6 +47,7 @@ import { installPrint, openPrintDialog } from './print.ts'import './ask.css'import { openColumnMenu } from './filterui.ts'import { installSaveMenu, adoptOpenedDoc, toast } from './saveui.ts'+import { savingFor, saveRevision, type Acknowledge } from './saving.ts'import { dismissSplash, dismissSplashNow } from './splash.ts'import { t, i18nApi } from './i18n.ts'import {@@ -1279,9 +1280,25 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav// writes exactly what ⌘S writes. Stamping is dash's to add on both paths at// once; the dep exists in writeback.ts so that change is one line here.const writeBack = new FileWriteBack()+ const saving = savingFor(store)+ // What every write that reached the open file owes the screen. `clean` is+ // called only when the bytes written are the revision on screen — see+ // saving.ts; clearing on resolve is the race this replaced.+ const ack: Acknowledge = {+ adopt: (d) => writeBack.adopt(d),+ clean: () => { dirty = false; dirtyEl.hidden = true; dirtyEl.title = '' },+ }let wbTag: HTMLElement | null = nullasync function runWriteBack(): Promise<void> {- const { notice } = await writeBack.run(store.doc, store.readOnly)+ if (saving.superseded) return+ // Through the queue, on the snapshot. write-back's own `lastWritten`+ // records the bytes it wrote, so it adopts itself — `adopt` here would+ // also reset its failure state, which is its own to manage.+ const out = await saveRevision(store, (snap) => writeBack.run(snap, store.readOnly),+ (r) => r.outcome.kind === 'wrote' ? 'open-file' : 'nowhere',+ { adopt: () => {}, clean: ack.clean })+ if (out.kind !== 'done') return+ const { notice } = out.valueif (!notice) returnif (notice.say === 'failed') {// INTERRUPTS, unlike a success. The file on disk is now older than the@@ -1294,11 +1311,10 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav.replace('{why}', notice.why))return}- // The bytes are on disk. Clearing the dot here is the whole point: it is- // the same claim ⌘S makes, and it is now true without one.- dirty = false- dirtyEl.hidden = true- dirtyEl.title = ''+ // The bytes are on disk. Clearing the dot is the whole point — and it+ // was done above by `saveRevision`, ONLY if no edit landed while they were+ // being written. An edit that did keeps the dot on and the next cycle+ // writes it.if (notice.say === 'recovered') toast(t('Saved to the file — automatic saving is working again.'))wbTag ??= app.querySelector<HTMLElement>('.dx-wb')if (!wbTag) return@@ -1337,6 +1353,7 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', savshowingSheet: () => grid.showingId(),showSheet: (id: string) => grid.setSheet(id),onDirty: markDirty,+ ack,// so Offline mode can HANG UP an open relay socket, not merely refuse the// next connection — a switch that leaves the current one running is not onesync,@@ -1451,6 +1468,7 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', savbutton: app.querySelector<HTMLElement>('[data-act="save"]')!,store,save: doSave,+ ack,})const undoBtn = app.querySelector<HTMLButtonElement>('[data-act="undo"]')!const redoBtn = app.querySelector<HTMLButtonElement>('[data-act="redo"]')!@@ -1989,25 +2007,33 @@ function boot(doc: DashDoc, repaired: number, frozen?: 'policy' | 'version', sav// A throw was invisible too: an unhandled rejection in the console of an// app the user is not looking at the console of. A revoked permission, a// deleted file and a full disk all arrive this way.- let r: Awaited<ReturnType<typeof saveFile>>- try {- r = await saveFile(store.doc)- } catch (err) {- toast(t('Save failed — {why}').replace('{why}', err instanceof Error ? err.message : String(err)))+ if (saving.superseded) {+ toast(t('This file was updated. Reload to run the new version before saving again.'))return}- if (r === 'cancelled') return // they closed the picker; they know- dirty = false- dirtyEl.hidden = true- dirtyEl.title = ''- // These bytes ARE the file now, so write-back must not immediately rewrite- // them — and a manual save that succeeded through the same handle clears- // any standing "automatic saving failed" warning, which would otherwise sit- // there contradicting the toast that is about to appear. Not for a- // DOWNLOAD: that wrote a copy to Downloads and left the open file stale, so+ // Through the queue (saving.ts): the snapshot is what is written, and the+ // dot goes out only if it is still what is on screen when the write lands.+ // `adopt` — these bytes ARE the file now, so write-back must not rewrite+ // them, and a manual save through the same handle clears any standing+ // "automatic saving failed" warning — happens for an in-place write ONLY.+ // A DOWNLOAD wrote a copy to Downloads and left the open file stale, so// adopting it would tell the next cycle the file is current when it is the// one thing that is not.- if (r !== 'downloaded') writeBack.adopt(store.doc)+ const out = await saveRevision(store, (snap) => saveFile(snap),+ (r) => r === 'saved' || r === 'saved-as' ? 'open-file' : r === 'downloaded' ? 'download' : 'nowhere',+ ack)+ if (out.kind === 'failed') {+ const err = out.error+ toast(t('Save failed — {why}').replace('{why}', err instanceof Error ? err.message : String(err)))+ return+ }+ if (out.kind === 'superseded') {+ toast(t('This file was updated. Reload to run the new version before saving again.'))+ return+ }+ if (out.kind !== 'done') return+ const r = out.value+ if (r === 'cancelled') return // they closed the picker; they knowconst name = currentFileName()if (r === 'downloaded') {toast(t('This browser cannot write files in place, so a copy was saved to your Downloads. The file open here is unchanged.'))diff --git a/dash/src/saveui.ts b/dash/src/saveui.tsindex a51af36e..e5119b4a 100644--- a/dash/src/saveui.ts+++ b/dash/src/saveui.ts@@ -51,6 +51,7 @@// nobody honours is worse than no tier at all.import './saveui.css'+import { afterPendingWrites, saveRevision, savingFor, type Acknowledge } from './saving.ts'import {saveFile, serializeAuto, writeUpdatedFileAs, canWriteInPlace, adoptFileHandle,isEncryptionActive, setEncryptionPassword,@@ -71,6 +72,8 @@ export interface SaveMenuHost {* ⌘S does" is how the button and the keystroke drift apart.*/save: () => void | Promise<void>+ /** what a write that reached the open file owes the screen (saving.ts) */+ ack: Acknowledge}/** A uuid, with the same fallback shape starter.ts uses for old runtimes. */@@ -217,6 +220,15 @@ export function installSaveMenu(host: SaveMenuHost): void {menu.appendChild(b)}+ /** An in-place update replaced this file's shell; this page must not write it. */+ const refuseSuperseded = (): boolean => {+ if (!savingFor(store).superseded) return false+ toast(t('This file was updated. Reload to run the new version before saving again.'))+ return true+ }+ const failed = (err: unknown): void =>+ toast(t('Save failed — {why}').replace('{why}', err instanceof Error ? err.message : String(err)))+const build = () => {menu.textContent = ''@@ -226,8 +238,18 @@ export function installSaveMenu(host: SaveMenuHost): void {item(t('Save a copy…'), t('A second file you carry on working in — same workbook, same identity.'),async () => {if (!confirmBudget(store.doc)) return- const r = await saveFile(store.doc, true)- if (r !== 'cancelled') toast(t('Copy saved'))+ if (refuseSuperseded()) return+ // THE COPY BECOMES THE OPEN FILE: `saveFile(…, true)` keeps the picked+ // handle, so the next ⌘S and the next automatic save go to it. That is+ // a handle change, so it queues behind any write still in flight to+ // the old one, and it acknowledges like ⌘S — it was not acknowledged+ // at all before, so the dot stayed lit over a file that held every edit+ // and write-back rewrote the copy it had just been handed.+ const out = await saveRevision(store, (snap) => saveFile(snap, true),+ (r) => r === 'saved' || r === 'saved-as' ? 'open-file' : r === 'downloaded' ? 'elsewhere' : 'nowhere',+ host.ack)+ if (out.kind === 'failed') return failed(out.error)+ if (out.kind === 'done' && out.value !== 'cancelled') toast(t('Copy saved'))})item(t('Save as new workbook…'), t('A separate workbook — same data, new identity. Nothing links it back to this one.'),@@ -239,23 +261,36 @@ export function installSaveMenu(host: SaveMenuHost): void {// `template: true`, so forking a template gave you another template —// a file that re-mints its identity on every open, which is the exact// opposite of "a separate workbook".- const next = duplicateWorkbook(store.doc, newDocId())- store.replaceDoc(next)- const r = await saveFile(store.doc, true)- if (r === 'cancelled') {- // THE FORK IS ALREADY IN MEMORY and the picker was closed, so the- // held handle still points at the ANCESTOR — a file this document is- // no longer a version of. ⌘S would overwrite it; automatic write-back- // (writeback.ts) would do the same thing 2.5s later with no gesture at- // all, which is how the original quietly becomes the fork. Releasing- // puts both back on the picker, which is merely inconvenient.- //- // The `null` cast is the same KERNEL GAP dropopen.ts names: nothing- // needed to RELEASE a handle until a document could stop belonging to- // its file, `adoptFileHandle` types its argument non-null, and the- // implementation is a bare assignment. The fix is a- // `releaseFileHandle()` beside it in kernel/src/save.ts.+ if (refuseSuperseded()) return+ // THE SWAP WAITS FOR EVERY WRITE AHEAD OF IT. An automatic save of the+ // ancestor already in flight resolves its handle after its serializer+ // awaits; releasing the handle and switching identity under it is how+ // a fork's first save and the ancestor's last one cross. Any write of+ // the ancestor still QUEUED is discarded once the identity changes.+ //+ // The handle is released FIRST and always, not only on cancel: the+ // fork is not a version of the ancestor's file in any outcome. A+ // successful save-as adopts the new handle; a download never had one.+ //+ // The `null` cast is the same KERNEL GAP dropopen.ts names: nothing+ // needed to RELEASE a handle until a document could stop belonging to+ // its file, `adoptFileHandle` types its argument non-null, and the+ // implementation is a bare assignment. The fix is a+ // `releaseFileHandle()` beside it in kernel/src/save.ts.+ await afterPendingWrites(store, () => {adoptFileHandle(null as never)+ store.replaceDoc(duplicateWorkbook(store.doc, newDocId()))+ })+ const out = await saveRevision(store, (snap) => saveFile(snap, true),+ (r) => r === 'saved' || r === 'saved-as' ? 'open-file' : r === 'downloaded' ? 'download' : 'nowhere',+ host.ack)+ if (out.kind === 'failed') return failed(out.error)+ if (out.kind !== 'done') return+ if (out.value === 'cancelled') {+ // THE FORK IS ALREADY IN MEMORY and the picker was closed. The held+ // handle was released above, so ⌘S and write-back go back to the+ // picker rather than overwriting the ancestor — which is how the+ // original used to quietly become the fork.toast(t('This is now a new workbook — save it under a new name'))} else {toast(t('Saved as a new workbook'))diff --git a/dash/src/saving.ts b/dash/src/saving.tsnew file mode 100644index 00000000..9e668bba--- /dev/null+++ b/dash/src/saving.ts@@ -0,0 +1,143 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// Every write dash makes against the OPEN FILE goes through one queue, and the+// unsaved dot goes out only when the write that captured THIS revision lands.+//+// The race this closes was in every save path dash had. `saveFile` awaits — a+// handle reconnect, the serializer (encryption can take a second), the disk —+// and an edit made inside that window landed in the live workbook after the+// bytes were taken. The resolve then cleared the dot, so the file on disk was+// missing the edit and nothing on screen said so. The kernel's SaveQueue+// (kernel/src/savequeue.ts) serializes the writes, hands each one a DETACHED+// snapshot, and answers `isCurrent()` at acknowledgement time; this module is+// dash's side of that contract, kept out of main.ts so the rig drives the+// same code the button does (scripts/test-dash-save-revisions.ts).+//+// ONE QUEUE PER STORE, because "all writes that use or adopt the same file+// handle must share one queue": ⌘S, the toolbar button, the Save menu, the+// automatic write-back, the in-place self-update, and a dropped file adopting+// a new handle. Two queues over one handle is the race again with extra steps.+//+// Policy that stays HERE, not in the kernel: what clears the dot, which+// results put bytes into the open file, and that an in-place update ends this+// session's writing.++import { SaveQueue } from '../../kernel/src/savequeue.ts'+import type { DashDoc } from './model.ts'+import type { Store } from './store.ts'++export interface Saving {+ queue: SaveQueue<DashDoc>+ /**+ * An in-place update rewrote the open file with a NEWER shell. This page is+ * still the old one, and every write it makes serializes the old shell — so+ * the next automatic save would quietly put the previous version back. Once+ * set, nothing in this session writes the open file again; reload runs the+ * new version.+ */+ superseded: boolean+}++const all = new WeakMap<Store, Saving>()++export function savingFor(store: Store): Saving {+ let s = all.get(store)+ if (!s) {+ s = {+ queue: new SaveQueue<DashDoc>({ getDocument: () => store.doc, getRevision: () => store.revision }),+ superseded: false,+ }+ all.set(store, s)+ }+ return s+}++/** What a write did to the OPEN file — the only thing the dot is about. */+export type Landed =+ /** the open file now holds the snapshot (⌘S, Save a copy, write-back) */+ | 'open-file'+ /**+ * ⌘S on a browser with no in-place save: the snapshot went to Downloads.+ * The dot goes out — that IS saving there, and a dot that can never go out+ * would make every close a false alarm — but nothing is adopted, because+ * the open file is still stale and write-back must not believe otherwise.+ */+ | 'download'+ /** bytes went somewhere else; the open file is as stale as it was */+ | 'elsewhere'+ /** nothing was written */+ | 'nowhere'++export interface Acknowledge {+ /** the open file holds these bytes — write-back must not rewrite them */+ adopt(doc: DashDoc): void+ /** and they are the workbook on screen: the dot goes out */+ clean(): void+}++export type SaveOutcome<T> =+ /** the workbook was swapped for another while this save waited */+ | { kind: 'discarded' }+ /** an in-place update replaced the shell while this write waited */+ | { kind: 'superseded' }+ /** the write threw — nothing acknowledged, the dot stays */+ | { kind: 'failed'; error: unknown }+ | { kind: 'done'; value: T; doc: DashDoc; landed: Landed; current: boolean }++/**+ * Write through the queue and acknowledge only the revision that was written.+ *+ * `adopt` runs INSIDE the queued task, before the next write starts: the next+ * write-back cycle compares against it, and adopting after the queue moved on+ * would let that cycle see a stale baseline.+ */+export async function saveRevision<T>(+ store: Store,+ write: (snapshot: DashDoc) => Promise<T>,+ landed: (value: T) => Landed,+ ack: Acknowledge,+): Promise<SaveOutcome<T>> {+ const saving = savingFor(store)+ const SUPERSEDED = Symbol('superseded')+ let saved+ try {+ saved = await saving.queue.run(() => store.endRun(), async (snapshot) => {+ // Checked HERE, when the write is about to happen — not only when it was+ // asked for. A write queued behind an in-place update passed every+ // earlier check and would otherwise write the old shell straight back.+ if (saving.superseded) return SUPERSEDED+ const value = await write(snapshot)+ if (landed(value) === 'open-file') ack.adopt(snapshot)+ return value+ })+ } catch (error) {+ return { kind: 'failed', error }+ }+ if (!saved) return { kind: 'discarded' }+ if (saved.value === SUPERSEDED) return { kind: 'superseded' }+ const where = landed(saved.value as T)+ const current = saved.isCurrent()+ if ((where === 'open-file' || where === 'download') && current) ack.clean()+ return { kind: 'done', value: saved.value as T, doc: saved.doc, landed: where, current }+}++/**+ * Wait for every write ahead of this point, then run `swap` before the next+ * one can start. For anything that changes WHICH FILE is open — a dropped+ * workbook adopting its handle, "Save as new workbook" switching identity: an+ * automatic write already in flight resolves its handle AFTER its serializer+ * awaits, so swapping the handle under it writes the OLD workbook into the NEW+ * file. Queued writes for the old workbook are discarded by the kernel queue's+ * identity check once the swap has replaced the document.+ */+export async function afterPendingWrites<T>(store: Store, swap: () => T): Promise<T> {+ const { queue } = savingFor(store)+ // An EMPTY task, awaited, then the swap in its continuation — not the swap+ // inside the task. The queue skips a task whose workbook was replaced while+ // it waited, and a swap is exactly the thing that must never be skipped.+ // The continuation runs before the next queued task can start: that task is+ // chained on `task.catch(...)`, which settles a tick after `task` itself.+ await queue.run(() => {}, async () => undefined)+ return swap()+}diff --git a/dash/src/settings.ts b/dash/src/settings.tsindex 9266d151..939db56f 100644--- a/dash/src/settings.ts+++ b/dash/src/settings.ts@@ -21,6 +21,7 @@// 2026 opens in every later build, so "am I running the newest app" is a// question about this copy of the reader's software.+import { saveRevision, savingFor, type Acknowledge } from './saving.ts'import {APP_VERSION, applyUpdate, applyUpdateInPlace, autoCheckEnabled, canUpdateInPlace,checkForUpdates, offlineEnabled, setAutoCheck, setOffline,@@ -45,6 +46,11 @@ export interface SettingsHooks {* update half of the switch.*/sync?: SyncSession+ /**+ * What an in-place update that wrote this workbook owes the screen+ * (saving.ts). Optional so a host with no unsaved dot still updates.+ */+ ack?: Acknowledge}// --- the launch-time update check (PLATFORM §6) -------------------------------@@ -291,10 +297,30 @@ export function openSettings(hooks: SettingsHooks): void {upStatus.textContent = t('Downloading and verifying…')// Two shapes, and the difference is worth stating because one of them// leaves the file on disk untouched and the other does not.+ //+ // IN PLACE IS A WRITE TO THE OPEN FILE, so it goes through the same+ // queue as ⌘S and the automatic save (saving.ts). It did not, and an+ // automatic save landing mid-update wrote the OLD shell over the new one+ // — and after a successful update every later automatic save did the+ // same, because this page IS the old shell. So success also ends this+ // session's writing (`superseded`): the file is current, the reload runs+ // the new version, and nothing here may put the old one back.+ const inPlace = async (): Promise<string> => {+ const out = await saveRevision(store, async (snap) => {+ const ok = await applyUpdateInPlace(rel, snap)+ // INSIDE the queued write, not after it resolves: the next queued+ // write starts the moment this one settles, a tick before any code+ // awaiting it runs, and would write the old shell straight back.+ if (ok) savingFor(store).superseded = true+ return ok+ }, (ok) => ok ? 'open-file' : 'nowhere',+ { adopt: () => {}, clean: () => hooks.ack?.clean() })+ if (out.kind === 'failed') throw out.error+ if (out.kind !== 'done' || !out.value) return t('Cancelled — nothing was changed.')+ return t('Updated. A backup of the old version was downloaded beside it — reload to run {v}.', { v: rel.version })+ }const run = canUpdateInPlace()- ? applyUpdateInPlace(rel, store.doc).then((ok) => ok- ? t('Updated. A backup of the old version was downloaded beside it — reload to run {v}.', { v: rel.version })- : t('Cancelled — nothing was changed.'))+ ? inPlace(): applyUpdate(rel, store.doc).then(() =>t('Downloaded. Open the new file — this one is unchanged.'))void rundiff --git a/dash/src/store.ts b/dash/src/store.tsindex 2a6f8022..8a5435c6 100644--- a/dash/src/store.ts+++ b/dash/src/store.ts@@ -1001,7 +1001,17 @@ export class Store {return () => set.delete(fn)}+ /**+ * Advances on EVERY document change — committed, mid-run, remote, and the+ * few writes that go straight onto the doc and call `touch()` (document+ * properties, sharing credentials). The save queue compares it at+ * acknowledgement time: a write may clear the unsaved dot only if this has+ * not moved since its snapshot. View changes do not count.+ */+ revision = 0+private emit(ev: StoreEvent): void {+ if (ev === 'doc') this.revision++for (const fn of this.listeners.get(ev) ?? []) fn()}@@ -1234,6 +1244,7 @@ export class Store {/** Model changed without a new undo entry (mid-run). */touch(): void {+ this.revision++this.doc.modified = new Date().toISOString()}diff --git a/dash/src/sync/session.ts b/dash/src/sync/session.tsindex 50e543e0..7ce445b4 100644--- a/dash/src/sync/session.ts+++ b/dash/src/sync/session.ts@@ -185,7 +185,7 @@ export class SyncSession {private async ensureCollab() {if (this.store.doc.collab) returnconst creds = await mintCollab()- if (!this.store.doc.collab) this.store.doc.collab = creds+ if (!this.store.doc.collab) { this.store.doc.collab = creds; this.store.touch() }}// --- the patch tap --------------------------------------------------------diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex dd966c33..17351099 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -8125,6 +8125,37 @@ size limit must be enforced DURING decompression, never after; the declaredsize in a container header is an attacker input, and the primitive, not thecaller's preflight, must hold the ceiling.+## 2026-10-04 — dash adopts the kernel SaveQueue; the queue also orders handle swaps++Dash takes the kernel's `SaveQueue` (#579) directly, replacing #538's+app-local approach, through `dash/src/saving.ts` — the same shape spaces took in+#580. Recorded here because three of its rules are not obvious from the kernel's+contract, and the second applies to every app.++- **Every write to the open file, and every change of which file is open, goes+ through one queue per store.** ⌘S, the Save menu, automatic write-back, the+ in-place self-update, and a dropped file adopting its handle. The drop was+ the surprise: the kernel's write reads its held handle AFTER the serializer+ awaits, so a handle swap during an in-flight write sends the OLD document into+ the NEW file. `afterPendingWrites` waits for the queue, then swaps in the+ continuation, which runs before the next queued task starts (that task is+ chained on `tail.catch`, a tick later); stale writes for the old document are+ then discarded by the queue's identity check. The swap is deliberately not a+ queued task, because the queue skips tasks whose document was replaced, and a+ swap must never be skipped.+- **The revision advances on every `doc` event and on `touch()`.** `touch()`+ covers the writes that go straight onto the document without an event:+ document properties, credential minting for a new workbook, and sharing+ start/stop/rotate (which call `markUnsaved()`, itself a `touch()`, since #597).+- **An in-place update marks the session `superseded` inside the queued write.**+ This page is the old shell, so any later write would downgrade the file.+ Setting the flag after the write resolves is one tick too late: the next+ queued write has already started. The rig carries that as a control.+- A ⌘S that DOWNLOADS (no in-place save) still clears the dot, but is not+ adopted as the file's content. Exports (template, read-only copy) do not+ touch the open handle and stay outside the queue.++## 2026-09-26 — Spaces adopts the kernel menu; an anchored menu is the primitive mounted over its anchor**Every menu in bento/spaces is `createMenu` (kernel/src/ui/menu.ts), throughdiff --git a/scripts/test-dash-save-revisions.ts b/scripts/test-dash-save-revisions.tsnew file mode 100644index 00000000..3e562f85--- /dev/null+++ b/scripts/test-dash-save-revisions.ts@@ -0,0 +1,287 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/dash SAVE-RACE rig — every write to the open file goes through one+// queue, and the unsaved dot goes out only for the revision that was written.+//+// node scripts/test-dash-save-revisions.ts+//+// WHY THIS EXISTS. Every dash save path cleared the dot when its write+// RESOLVED. A write awaits (handle reconnect, serializer, disk), so an edit+// made inside that window was missing from the file and the dot said it was+// saved. Worse, a dropped file adopted its handle while an automatic write was+// mid-serialize, and that write — which reads the held handle after its await —+// put the OLD workbook into the NEW file. This rig drives dash/src/saving.ts+// with a real Store and writes held open on a gate, so each window can be+// entered on purpose rather than hoped for.++import { registerHooks } from 'node:module'+registerHooks({+ load(url, context, next) {+ if (url.endsWith('.css')) return { format: 'module', source: 'export {}', shortCircuit: true }+ return next(url, context)+ },+})++const { parseDoc } = await import('../dash/src/model.ts')+const { Store } = await import('../dash/src/store.ts')+const { savingFor, saveRevision, afterPendingWrites } = await import('../dash/src/saving.ts')+const { FileWriteBack } = await import('../dash/src/writeback.ts')+type DashDoc = import('../dash/src/model.ts').DashDoc++let checks = 0, failures = 0+const ok = (c: boolean, m: string) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }++const fresh = (docId = 'd'): DashDoc => {+ const r = parseDoc(JSON.stringify({+ format: 'bento/dash', version: 1, policy: 'bento-dash-1', docId, title: 'Book',+ sheets: [{+ id: 'sh', kind: 'table', name: 'Data', rids: [[1, 2]], nextRid: 3,+ columns: [{ id: 'v', name: 'Value', type: 'number' }],+ data: { v: { enc: 'raw', v: [1, 2] } }, steps: [],+ }],+ }))+ if (!r.ok) throw new Error('fixture')+ return r.doc+}+const valueOf = (d: DashDoc, i: number) => ((d.sheets[0] as { data: { v: { v: unknown[] } } }).data.v.v[i])+const edit = (s: InstanceType<typeof Store>, v: number) =>+ s.commit({ op: 'setCells', sheet: 'sh', col: 'v', rids: [1], v: [v] })++/** A write that does not finish until the test says so. */+function gated<T>(value: T) {+ let open!: () => void+ const gate = new Promise<void>((r) => { open = r })+ let saw: DashDoc | null = null+ let started = false+ const write = async (snap: DashDoc): Promise<T> => { started = true; saw = snap; await gate; return value }+ return { write, open, get saw() { return saw }, get started() { return started } }+}+const tick = () => new Promise((r) => setTimeout(r, 0))+const ackSpy = () => {+ const a = { cleaned: 0, adopted: [] as DashDoc[] }+ return { a, ack: { clean: () => { a.cleaned++ }, adopt: (d: DashDoc) => { a.adopted.push(d) } } }+}+const landsInFile = () => 'open-file' as const++console.log('one queue per workbook')+{+ const s = new Store(fresh())+ ok(savingFor(s) === savingFor(s), 'every path asks for the same queue — ⌘S, menu, write-back, update, drop')+ ok(savingFor(s) !== savingFor(new Store(fresh())), 'and another store gets its own')+}++console.log('\nan edit made WHILE the write is in flight keeps the dot on')+{+ const s = new Store(fresh())+ const w = gated('saved'), { a, ack } = ackSpy()+ const p = saveRevision(s, w.write, landsInFile, ack)+ await tick()+ ok(w.started, 'the write started')+ edit(s, 99)+ w.open()+ const out = await p+ ok(out.kind === 'done' && !out.current, 'the result says the file is behind the screen')+ ok(a.cleaned === 0, 'the dot is NOT cleared — this is the race')+ ok(a.adopted.length === 1 && valueOf(a.adopted[0], 0) === 1,+ 'what is adopted as "on disk" is the snapshot (1), not the live workbook (99) — write-back will still write 99')+ ok(valueOf(w.saw!, 0) === 1 && w.saw !== s.doc, 'and the write was handed a DETACHED snapshot')+}++console.log('\nno edit in the window: the dot goes out')+{+ const s = new Store(fresh())+ const w = gated('saved'), { a, ack } = ackSpy()+ const p = saveRevision(s, w.write, landsInFile, ack)+ await tick(); w.open()+ const out = await p+ ok(out.kind === 'done' && out.current && a.cleaned === 1, 'current, and cleaned once')+}++console.log('\nevery kind of change counts, not only a committed one')+for (const [what, change] of [+ ['a keystroke inside a typing run', (s: InstanceType<typeof Store>) => s.runEdit('v:1', { op: 'setCells', sheet: 'sh', col: 'v', rids: [1], v: [7] })],+ ['a collaborator\'s edit', (s: InstanceType<typeof Store>) => s.changedRemotely()],+ ['a write straight onto the doc that calls touch() (document properties, sharing credentials)', (s: InstanceType<typeof Store>) => { (s.doc as { meta?: object }).meta = { author: 'x' }; s.touch() }],+ ['undo', (s: InstanceType<typeof Store>) => s.undo()],+] as const) {+ const s = new Store(fresh())+ edit(s, 5)+ const w = gated('saved'), { a, ack } = ackSpy()+ const p = saveRevision(s, w.write, landsInFile, ack)+ await tick()+ change(s)+ w.open()+ const out = await p+ ok(out.kind === 'done' && !out.current && a.cleaned === 0, `${what} during the write keeps the dot on`)+}++console.log('\na typing run is closed before the snapshot is taken')+{+ const s = new Store(fresh())+ s.runEdit('v:1', { op: 'setCells', sheet: 'sh', col: 'v', rids: [1], v: [42] })+ const undoBefore = s.canUndo+ const w = gated('saved'), { ack } = ackSpy()+ const p = saveRevision(s, w.write, landsInFile, ack)+ await tick()+ ok(!undoBefore && s.canUndo, 'the open run became an undo step when the save began')+ ok(valueOf(w.saw!, 0) === 42, 'and the snapshot has what was typed')+ w.open(); await p+}++console.log('\nwrites are serialized: the second starts only after the first lands')+{+ const s = new Store(fresh())+ const log: string[] = []+ const w1 = gated('saved'), w2 = gated('saved'), { ack } = ackSpy()+ const p1 = saveRevision(s, async (d) => { log.push('1 start'); const r = await w1.write(d); log.push('1 end'); return r }, landsInFile, ack)+ const p2 = saveRevision(s, async (d) => { log.push('2 start'); const r = await w2.write(d); log.push('2 end'); return r }, landsInFile, ack)+ await tick(); await tick()+ ok(log.join() === '1 start', `only the first is writing — ${log.join(' | ')}`)+ w1.open(); await p1; await tick()+ ok(log.join() === '1 start,1 end,2 start', `then the second — ${log.join(' | ')}`)+ w2.open(); await p2+}++console.log('\na failed write is a failure, and does not poison the queue')+{+ const s = new Store(fresh())+ const { a, ack } = ackSpy()+ const out = await saveRevision(s, async () => { throw new Error('disk full') }, landsInFile, ack)+ ok(out.kind === 'failed' && (out.error as Error).message === 'disk full' && a.cleaned === 0, 'reported as failed, dot untouched')+ const after = await saveRevision(s, async () => 'saved', landsInFile, ack)+ ok(after.kind === 'done' && a.cleaned === 1, 'and the next save runs normally')+}++console.log('\nwhere the bytes went decides what is acknowledged')+for (const [landed, clean, adopt] of [['open-file', 1, 1], ['download', 1, 0], ['elsewhere', 0, 0], ['nowhere', 0, 0]] as const) {+ const s = new Store(fresh())+ const { a, ack } = ackSpy()+ await saveRevision(s, async () => 'x', () => landed, ack)+ ok(a.cleaned === clean && a.adopted.length === adopt,+ `${landed}: dot ${clean ? 'clears' : 'stays'}, ${adopt ? 'adopted' : 'not adopted'} as the file's content`)+}++console.log('\na write for a workbook that has been replaced is never made')+{+ const s = new Store(fresh())+ const w1 = gated('saved'), { ack } = ackSpy()+ const p1 = saveRevision(s, w1.write, landsInFile, ack)+ let ran = false+ const p2 = saveRevision(s, async () => { ran = true; return 'saved' }, landsInFile, ack)+ await tick()+ s.replaceDoc(fresh('other'))+ w1.open()+ const [o1, o2] = await Promise.all([p1, p2])+ ok(o1.kind === 'done' && !o1.current, 'the write in flight finishes, and is not current')+ ok(o2.kind === 'discarded' && !ran, 'the one queued behind it is discarded without writing')+}++console.log('\nTHE DROP RACE: a handle swap waits for the write in flight')+// The kernel's write reads its handle AFTER the serializer awaits. Model that+// exactly: `held` is the kernel's module handle, read after the gate.+for (const viaQueue of [true, false]) {+ const s = new Store(fresh('A'))+ let held = 'file-A'+ const wrote: Array<[string, unknown]> = []+ let open!: () => void+ const gate = new Promise<void>((r) => { open = r })+ const { ack } = ackSpy()+ const inflight = saveRevision(s, async (snap) => { await gate; wrote.push([held, snap.docId]); return 'saved' }, landsInFile, ack)+ await tick()+ const swap = () => { s.replaceDoc(fresh('B')); held = 'file-B' }+ let swapped: Promise<void>+ if (viaQueue) swapped = afterPendingWrites(s, swap)+ else { swap(); swapped = Promise.resolve() }+ open()+ await Promise.all([inflight, swapped])+ // a write asked for after the drop, for the new workbook+ await saveRevision(s, async (snap) => { wrote.push([held, snap.docId]); return 'saved' }, landsInFile, ack)+ const into = (f: string) => wrote.filter(([h]) => h === f).map(([, id]) => id).join(',')+ if (viaQueue) {+ ok(into('file-A') === 'A', `file A received only workbook A — ${JSON.stringify(wrote)}`)+ ok(into('file-B') === 'B', `file B received only workbook B — ${JSON.stringify(wrote)}`)+ } else {+ // the CONTROL: what happens without the queue. If this ever stops writing+ // A into B, the model above no longer reproduces the bug and proves nothing.+ ok(into('file-B').includes('A'), `CONTROL — swapping without waiting writes workbook A into file B — ${JSON.stringify(wrote)}`)+ }+}++console.log('\nthe swap runs before a write queued behind the drain can start')+{+ const s = new Store(fresh('A'))+ const log: string[] = []+ const w = gated('saved'), { ack } = ackSpy()+ const p1 = saveRevision(s, w.write, landsInFile, ack)+ const swapped = afterPendingWrites(s, () => { log.push('swap'); s.replaceDoc(fresh('A2')) })+ // queued for workbook A, behind the drain — must be discarded, not written+ const p3 = saveRevision(s, async () => { log.push('stale write'); return 'saved' }, landsInFile, ack)+ await tick(); w.open()+ const [, , o3] = await Promise.all([p1, swapped, p3])+ ok(log.join() === 'swap' && o3.kind === 'discarded', `the swap ran, the stale write never did — ${log.join(' | ')}`)+}++console.log('\nan in-place update ends this session\'s writing')+{+ const s = new Store(fresh())+ const saving = savingFor(s)+ const upd = gated(true), { ack } = ackSpy()+ // the update, exactly as settings.ts drives it: superseded is set INSIDE+ // the queued write. Setting it once the save resolves is one tick too late+ // — the next queued write has already started by then.+ const u = saveRevision(s, async (snap) => { const r = await upd.write(snap); if (r) saving.superseded = true; return r },+ (ok) => ok ? 'open-file' : 'nowhere', ack)+ await tick()+ // an automatic save asked for while the update is writing — it passed every+ // check made when it was ASKED for+ let wroteOld = false+ const wb = saveRevision(s, async () => { wroteOld = true; return 'saved' }, landsInFile, ack)+ upd.open()+ const [, w] = await Promise.all([u, wb])+ ok(saving.superseded, 'the update succeeded and marked the session superseded')+ ok(w.kind === 'superseded' && !wroteOld, 'the write queued behind it did NOT put the old shell back')+}++console.log('\nCONTROL: marking superseded after the update resolves is too late')+{+ const s = new Store(fresh())+ const saving = savingFor(s)+ const upd = gated(true), { ack } = ackSpy()+ const u = saveRevision(s, upd.write, (ok) => ok ? 'open-file' : 'nowhere', ack)+ .then((out) => { if (out.kind === 'done' && out.value) saving.superseded = true })+ await tick()+ let wroteOld = false+ const wb = saveRevision(s, async () => { wroteOld = true; return 'saved' }, landsInFile, ack)+ upd.open()+ await Promise.all([u, wb])+ ok(wroteOld, 'CONTROL — the queued write slipped in; if this stops happening the check above proves nothing')+}++console.log('\nthe automatic write-back, driven through the queue the way main.ts drives it')+{+ const s = new Store(fresh())+ let release!: () => void+ const gate = new Promise<void>((r) => { release = r })+ const disk: string[] = []+ const wb = new FileWriteBack({+ hasHandle: () => true,+ serialize: async (d) => { await gate; return JSON.stringify(valueOf(d, 0)) },+ write: async (html) => { disk.push(html) },+ })+ const { a, ack } = ackSpy()+ const run = () => saveRevision(s, (snap) => wb.run(snap, false),+ (r) => r.outcome.kind === 'wrote' ? 'open-file' : 'nowhere', { adopt: () => {}, clean: ack.clean })+ edit(s, 10)+ const p = run()+ await tick()+ edit(s, 11) // typed while the cycle was serializing+ release()+ await p+ ok(disk.join() === '10' && a.cleaned === 0, `the cycle wrote 10 and left the dot on for 11 — disk ${disk.join()}`)+ await run()+ ok(disk.join() === '10,11' && a.cleaned === 1, `the next cycle writes 11 and only then clears it — disk ${disk.join()}`)+}++console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)