diff --git a/docs/archive/specs/2026-11-01-cloud-workspace-reset.md b/docs/archive/specs/2026-11-01-cloud-workspace-reset.md new file mode 100644 index 0000000..bda95c4 --- /dev/null +++ b/docs/archive/specs/2026-11-01-cloud-workspace-reset.md @@ -0,0 +1,180 @@ +# Cloud Workspace Reset + +Date: 2026-11-01 +Status: Implemented and locally verified +Base: `243db4cc4272e7e4772355fcc7f8e06a84976259` +Task branch: `feat/cloud-reset` + +## Outcome + +Settings offers **Reset cloud data** next to the existing device recovery action. +After a confirmed cloud commit, the current device remains authenticated and bound +to the same private Gist, with the empty business state seen after first setup. +The action affects every device connected to that Gist. + +Device reset remains a separate local operation. Cloud reset does not create or +delete a Gist, clear credentials, change Workspace identity, or erase GitHub +revision history. It does not offer browser backup/import, switching, local push, +merge, or force overwrite. + +## Scope and ownership + +Reset clears all live `nodes`, `subscriptions`, `aggregates`, `publishTargets`, +and `clientExports`. It removes existing output files only when current publication +metadata proves SubMan published them. An unowned file, an unpublished same-name +file, or a retained historical output without sufficient ownership evidence is +preserved and appears in the confirmation preview. + +`subman.json` remains the authoritative Schema V2 document. The immutable +`subman.v1.backup.json`, external files, historical tombstones, processed mutation +journal, orphan browser queues, quarantine evidence, and fencing counters remain. +Existing bootstrap cleanup rules remain owned by the coordinator. +When a stale bootstrap marker is visible in the inventory, the reset preview +lists it for cleanup rather than promising to preserve it. + +## Entry and confirmation + +1. Show a separate destructive Settings section beside **Reset this device**. +2. Require authentication, an initialized automatic V2 binding, successful cloud + loading, and no active pending, blocked, or dead-letter queue. Refuse active + dispatcher leases. Existing reload/repair resolves pending evidence first. +3. Read only the originally bound Gist. Validate the cloud document, then safely + align the local baseline using the existing compare-and-swap refresh boundary. +4. Prepare a preview containing Gist ID, revision, reset revision, counts for all + five resource collections, files to remove, files to preserve, and the complete + local snapshot/binding/active-queue expectation. + Derive deletion names from the authoritative document, without filtering them + through a separately read Gist inventory that may predate a concurrent publish. +5. Use the shared accessible Dialog. Explain the cross-device impact and retained + files; require literal `RESET`. Cancellation sends no mutation. +6. Pin the preview's local expectation and cloud revision. A changed snapshot, + binding, queue, active lease, or cloud revision rejects this attempt and requires + a fresh preview and confirmation. Reset never automatically reprepares itself + against newer data. + +## Coordinator mutation + +Add browser-only `workspace.reset` with an empty payload to the internal mutation +protocol. The public Server API does not expose reset or change its request or +response contract. + +The existing coordinator serializes the operation for `gist:`. It checks +identity, request hash, pending recovery, authorization, expected revision, and +reset boundary using the existing order and guarantees. It then: + +- Appends tombstones for every live entity, retaining all earlier tombstones. +- Clears the five business collections. +- Advances revision by one and sets `lastMutationId` and commit timestamp normally. +- Sets `resetRevision` to this committed revision. +- Produces deletions only for provably published SubMan output files. +- Journals the candidate before sending one Gist PATCH containing the new + `subman.json` and all output deletions. +- Reads back and verifies the candidate and file effects before confirming it. + +A repeated mutation ID with the same request hash returns its stored receipt +without executing reset again. Existing processed retries remain recoverable even +after later writes or resets. Unresolved pending recovery, invalid documents, +backup mismatch, and ambiguous upstream writes continue to fail closed. + +## Reset boundary and compatibility + +Schema V2 gains optional `resetRevision`; mutation envelopes gain optional +`expectedResetRevision`. Absence means zero for comparison. A new mutation is +accepted only if its observed reset revision equals the document's reset revision. +Ordinary mutations preserve the document boundary. Another reset advances it. + +This supplements revision checks and tombstones: an old queued creation can have +an ID that never reached the cloud and therefore has no tombstone. Local CAS retry, +delayed actions, or compatibility reconcile must not silently repackage that old +intent with a new reset boundary. + +- Capture the initial Workspace identity and reset boundary when accepting an + action, before asynchronous preparation. Recheck after every persistence read + and bounded ordinary CAS retry. A boundary change rejects the old intent. +- A batch import pins one boundary for the whole batch. Stop on reset or any + non-remote outcome; retain its draft instead of submitting later rows as fresh + actions in the new generation. +- Persist envelopes with their originally observed boundary; never rewrite it at + dispatch time. Remote conflicts block the complete queue for explicit repair. +- Reject old-boundary reconcile/repair and delayed resolved snapshots. Cloud reload + may replace a complete old queue only through existing explicit confirmation. +- An already-committed old mutation may acknowledge its historical receipt and + hydrate the latest cloud state; remaining old queue entries stay blocked and + are not replayed into the new generation. +- Server API adapters capture the boundary from their own cloud read and place it + in their internal envelope. Public clients need no new field. + +Keep optional fields absent in historical parsing, serialization, request hashes, +and document signatures. Do not inject zero into existing envelopes: that would +change the request hash for an original mutation ID. Include a nonzero reset +boundary in document signatures and preserve old pending-journal verification. +New documents first emit the boundary on actual reset. Older strict clients stop +on the unfamiliar field and must reload the updated application. + +## Browser durability and presentation + +Use the existing `WorkspacePersistence` root and transaction boundary. Reset's +original envelope, optimistic snapshot, and unchanged binding are committed +atomically before dispatch. Persistence also verifies the full preview expectation +and idle active queue/lease inside that transaction; a read-only preflight alone +is insufficient. + +Await the operation completion. Only `remote-committed` allows **Cloud data reset** +success wording and finalization. Pending, peer-owned, retry-scheduled, blocked, +and acknowledgement-uncertain outcomes use the shared operation presenter and +retain the operation identity. Eligible upstream retries use existing bounded +backoff and the same mutation ID. Editing remains blocked while delivery is +pending. A post-commit local read or presentation failure cannot turn cloud success +into a fresh destructive attempt. + +After confirmation, atomically settle the queue with the authoritative empty +snapshot and baseline. Keep Gist binding, authentication preference, and token. +Broadcast existing commit/state events as hints; correctness must survive missing +BroadcastChannel or Web Locks. + +## Validation and acceptance + +Add behavior tests before implementation in each affected layer: + +| Layer | Required evidence | +| --- | --- | +| Document/mutation | Optional-field compatibility; unchanged old hashes/signatures; five collections cleared; tombstones retained/appended; monotonic revision; browser-only reset; output ownership | +| Coordinator | Single PATCH; immutable backup; duplicate request; timeout after actual commit; read-back recovery; competing write/reset rejects stale preview | +| Persistence | Preview CAS including snapshot/queue; active lease; rollback before commit; durable post-commit recovery; unchanged Gist identity and token exclusion | +| Browser actions | Old intents and unseen UUID creations cannot cross reset during asynchronous preparation or CAS retry; explicit reset never retries with a newer revision | +| Delivery/repair | Old queue conflict; historical receipt recovery; remaining old queue retained and blocked; safe explicit whole-queue cloud reload | +| Server API | Empty reads after reset; fresh writes succeed; pre-reset internal envelopes conflict; public OpenAPI contract unchanged | +| UI/E2E | Cancel sends zero writes; typed confirmation; resource/file preview; cloud confirmation precedes success; token/binding retained; pending outcome; desktop and Chinese mobile flow | + +Run repository docs, unit, type, lint, build, Workers runtime, and relevant browser +checks with Bun 1.3.14. Use isolated worktree dependencies, Worker state, output, +browser state, and ports. Test GitHub through mocks, never a real user Gist. + +## Delivery boundary + +Implement and verify in the dedicated task worktree and create an atomic local +Conventional Commit. Push, PR creation, merge, Wiki publication, and production +deployment require authorization beyond this local implementation request. + +## Local verification evidence + +Verified with Bun 1.3.14 in the dedicated task worktree: + +- 758 unit tests across 74 files passed. +- 10 Workers/SQLite integration tests passed, including reset receipt recovery + and stale-preview HTTP rejection. +- All 81 browser cases passed in isolated groups (41 + 20 + 20). The seven reset + cases passed again after the final confirmation layout adjustment. +- Desktop 1280 x 720 and Chinese mobile 390 x 844 confirmation flows were inspected. + The warning initially stays visible; the confirmation input remains fully in + view while editing, with no framework overlay or unexpected console errors in + the normal preview flow. +- Documentation, Svelte/type/generated Worker type checks, lint, build, sing-box + 1.14 output validation, and deployment dry-run passed. +- Independent local review findings about first-read races, batch boundaries, + and incomplete deletion previews were reproduced and resolved with regression + tests. Removing the browser action guard in an isolated copy made all three + new guard regressions fail, confirming their effectiveness. + +GitHub calls used test fixtures and mocks. No real Gist was accessed or changed, +and these checks do not claim production deployment or live GitHub acceptance. diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index 5e5ef35..91fee38 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -8,6 +8,17 @@ production deployment and real-provider acceptance require separate evidence. ## Unreleased +### 2026-11-01 - Confirmed cloud data reset + +- Added a Settings preview and typed confirmation to clear cloud business data + while retaining the original Gist connection and authentication. +- Reset and proven published-output removal share one coordinator PATCH. External + files, immutable migration backup, tombstones, and recovery journals remain. +- Added reset revision fencing so old queues and delayed actions cannot replay + across reset; stale confirmations require a new preview. Public API shapes stay + unchanged and cloud confirmation remains the only success result. +- Recorded the [accepted implementation specification](../archive/specs/2026-11-01-cloud-workspace-reset.md). + ### 2026-11-01 - Foreground cloud operation loading - Keep saves, publication generation, and Gist refresh in a visible foreground diff --git a/docs/wiki/Changelog.zh-CN.md b/docs/wiki/Changelog.zh-CN.md index 5650472..d5d7acb 100644 --- a/docs/wiki/Changelog.zh-CN.md +++ b/docs/wiki/Changelog.zh-CN.md @@ -7,6 +7,15 @@ ## 未发布 +### 2026-11-01 - 确认后重置云端数据 + +- 设置页增加云端重置预览和输入确认,清空云端业务数据,同时保留原 Gist 连接与认证。 +- 重置文档与删除有发布证据的输出使用同一次协调器 PATCH;保留外部文件、不可变迁移备份、 + 删除标记和恢复日志。 +- 增加重置修订边界,旧队列和延迟操作不能跨重置重放,过期确认需重新预览; + 公开 API 结构不变,仍只有云端确认才能报告成功。 +- 记录[已确认的实现 SPEC](../archive/specs/2026-11-01-cloud-workspace-reset.md)。 + ### 2026-11-01 - 云端操作前台等待状态 - 保存、发布生成与 Gist 刷新统一显示前台 loading,等待期间禁止编辑背景内容或切换页面, diff --git a/docs/wiki/User-Guide.md b/docs/wiki/User-Guide.md index 9b08d08..d2036f8 100644 --- a/docs/wiki/User-Guide.md +++ b/docs/wiki/User-Guide.md @@ -28,7 +28,7 @@ empty Workspace, then recent resources and confirmed publication metadata. | Page | Purpose | | --- | --- | -| `/auth` | Connection, token, delivery status, cloud reload, device reset, migration, and diagnostics | +| `/auth` | Connection, token, delivery status, cloud reload, cloud/device reset, migration, and diagnostics | | `/nodes` | Nodes and subscriptions, tags, search, filters, and batch import | | `/aggregate` | Rule editing, preview ordering, publish targets, and publication | | `/exports` | sing-box configuration preview, copy, download, and publication | @@ -85,6 +85,25 @@ they do not export business data or credentials. There is no browser business JSON backup/restore, local overwrite/merge, manual push, or Workspace switching. For operator procedures, see [operations and repair](../workspace-v2-operations.md). +## Reset cloud data and keep your connection + +In Settings, choose **Reset cloud data** to return the original Gist to an empty +business state while keeping your token and connection. This affects every device +using that Gist. Complete or repair pending delivery first, then review the latest +resource counts and files and type `RESET` to confirm. + +Reset clears nodes, subscriptions, rules, publish targets, and client export +profiles. It removes outputs with confirmed SubMan publication metadata; the +preview lists preserved external files and migration backups. It preserves the +Gist itself and its GitHub history. Existing subscription links for removed +outputs stop serving those files; previously downloaded copies are unaffected. + +Only cloud confirmation completes reset. If delivery is pending or uncertain, +retain the original operation and use existing retry/recovery controls. If data +changes during confirmation, review a new preview. Older devices cannot replay +pre-reset changes; confirm a complete-queue cloud reload before editing again. +Older application versions may need a page refresh after reset. + ## Start again after removing your Gist Disconnect removes your token but keeps this device's Workspace binding and diff --git a/docs/wiki/User-Guide.zh-CN.md b/docs/wiki/User-Guide.zh-CN.md index 20d75a8..c21ae6e 100644 --- a/docs/wiki/User-Guide.zh-CN.md +++ b/docs/wiki/User-Guide.zh-CN.md @@ -22,7 +22,7 @@ SubMan 查找描述为 `SubMan-Data`、包含权威文档 `subman.json` 的私 | 页面 | 用途 | | --- | --- | -| `/auth` | 连接、Token、发送状态、云端重载、设备重置、迁移和诊断 | +| `/auth` | 连接、Token、发送状态、云端重载、云端/设备重置、迁移和诊断 | | `/nodes` | 节点与订阅、标签、搜索、过滤、批量导入 | | `/aggregate` | 规则编辑、预览排序、发布目标与发布 | | `/exports` | sing-box 配置预览、复制、下载和发布 | @@ -64,6 +64,20 @@ SubMan 查找描述为 `SubMan-Data`、包含权威文档 `subman.json` 的私 浏览器不提供业务 JSON 备份/恢复、本地覆盖/合并、手动推送或工作区切换。 操作人员的修复步骤见[运维与恢复](../workspace-v2-operations.zh-CN.md)。 +## 保留连接并重置云端数据 + +在设置中选择**重置云端数据**,可将原 Gist 恢复为空的业务状态,同时保留 Token 和连接。 +这会影响使用该 Gist 的所有设备。先完成或修复待发送操作,再检查最新的资源数量和文件列表, +输入 `RESET` 确认。 + +重置会清空节点、订阅、规则、发布目标和客户端导出配置,并删除存在 SubMan 发布确认记录的 +输出;确认窗口列出保留的外部文件和迁移备份。Gist 本身及其 GitHub 历史仍保留。 +被删除输出的订阅链接将不再提供这些文件,已下载到客户端的副本不受影响。 + +只有云端确认后才完成重置。发送待处理或结果不确定时,保留原操作,使用现有重试/恢复入口。 +确认期间数据发生变化时,需要查看新预览。其他设备不能重新发送重置前的变更, +应确认丢弃完整旧队列并重载云端后再编辑。旧版应用可能需要刷新页面升级。 + ## 删除 Gist 后重新开始 断开连接只清除 Token,保留此设备的工作区绑定和待确认变更。重新连接仍会读取原 Gist, diff --git a/docs/workspace-v2-operations.md b/docs/workspace-v2-operations.md index ef57658..5f2d1a6 100644 --- a/docs/workspace-v2-operations.md +++ b/docs/workspace-v2-operations.md @@ -311,6 +311,35 @@ discarded browser cache is never uploaded as business authority. Safe historical queue evidence remains in Sync recovery and is never automatically rebound or delivered. +## Cloud Data Reset With The Original Connection + +Settings **Reset cloud data** requires a ready automatic V2 binding, authentication, +an idle active queue, and no active delivery lease. It reads the original Gist, +previews resource counts and file ownership, and requires typed `RESET` confirmation. +The snapshot, binding, complete queue, and cloud revision are pinned; changed state +requires a fresh confirmation rather than automatic re-preparation. + +The internal browser-only `workspace.reset` mutation clears all five business +collections and removes only outputs with publication evidence in one coordinator +Gist PATCH. It retains the original Gist/token/binding, immutable V1 backup, +external files, earlier tombstones, processed journal, and browser recovery +evidence. Removed entities gain tombstones; revision continues increasing. + +Optional document `resetRevision` records the last reset's committed revision. +Internal envelopes carry `expectedResetRevision` from the original action's +baseline; absent fields compare as zero and retain historical hash/serialization +shape. Ordinary CAS retries, compatibility reconcile, and Server API adapters +must preserve this boundary. The coordinator rejects a mismatched boundary as +`revision_conflict`. A historical committed receipt remains recoverable without +re-executing it. Old queues require explicit complete-queue cloud reload, never +automatic rebase across reset. Older strict clients must refresh their app. + +Only `remote-committed` completes reset. Retry/uncertain results retain the +original mutation ID; cloud success followed by local acknowledgement failure +must not create a second reset. Reset does not erase GitHub history or repair +invalid documents, backup mismatch, or unresolved coordinator pending records. +See the [accepted specification](archive/specs/2026-11-01-cloud-workspace-reset.md). + ## Leases, Retry, And Upstream Failures Each Workspace dispatcher acquires a persisted lease with a random owner ID, diff --git a/docs/workspace-v2-operations.zh-CN.md b/docs/workspace-v2-operations.zh-CN.md index aa94f5a..c37d58e 100644 --- a/docs/workspace-v2-operations.zh-CN.md +++ b/docs/workspace-v2-operations.zh-CN.md @@ -204,6 +204,27 @@ domain conflict/修复证据继续阻塞;时间戳不赋予覆盖权,墓碑 或创建空的私有 bootstrap Gist 并由协调器完成初始化;已丢弃的浏览器缓存不会成为上传来源。 历史队列的安全证据仍可在“同步恢复”中查看,不会自动重绑或发送。 +## 保留原连接的云端数据重置 + +设置中的**重置云端数据**要求已认证、自动 V2 绑定已加载、当前队列空闲且无活动发送租约。 +仅读取原 Gist,预览资源数量与文件归属,输入 `RESET` 后确认。确认固定本机快照、绑定、 +完整活动队列和云端修订号;期间状态变化需重新预览,不自动按新数据重新准备重置。 + +内部浏览器操作 `workspace.reset` 在同一次协调器 Gist PATCH 中清空五类业务集合, +并删除有发布证据的输出。保留原 Gist、Token、绑定、不可变 V1 备份、外部文件、历史删除标记、 +已处理操作日志和浏览器修复证据。被清空资源补充删除标记,修订号持续递增。 + +文档可选字段 `resetRevision` 记录最近重置的提交修订号。内部 mutation 使用原操作基线的 +`expectedResetRevision`,缺字段按零比较,历史哈希与序列化形状不变。普通 CAS 重试、 +兼容 reconcile 和 Server API 内部适配都保留这个边界;协调器以 `revision_conflict` +拒绝边界不匹配。历史已提交操作仍可确认回执,但不会重新执行。旧队列必须显式完整丢弃并 +重载云端,不得跨重置自动重放。旧版严格解析客户端需刷新应用升级。 + +只有 `remote-committed` 完成重置,待重试或结果不确定时保留原操作 ID;云端成功后本机 +确认失败不能产生第二次重置。重置不擦除 GitHub 历史,也不绕过损坏文档、备份不匹配或 +未解决的协调器 pending 记录。[实现 SPEC](archive/specs/2026-11-01-cloud-workspace-reset.md) +记录协议、确认和验证边界。 + ## 租约、重试和上游故障 dispatcher 持久租约含随机 owner、单调 fencing token、到期和 heartbeat; diff --git a/e2e/workspace-cloud-reset.spec.ts b/e2e/workspace-cloud-reset.spec.ts new file mode 100644 index 0000000..7229999 --- /dev/null +++ b/e2e/workspace-cloud-reset.spec.ts @@ -0,0 +1,440 @@ +import { type BrowserContext, expect, type Page, test } from "@playwright/test"; +import type { WorkspaceDocumentV2 } from "../src/lib/workspace-document"; +import { + defaultUiData, + seedUiWorkspace, + type UiWorkspaceData, +} from "./ui-workspace-fixture"; + +const GIST_ID = "accessibility-cloud"; +const WORKSPACE_ID = `gist:${GIST_ID}`; +const NOW = "2026-10-23T10:00:00.000Z"; +type JsonRecord = Record; + +function resetData(): UiWorkspaceData { + const data = structuredClone(defaultUiData); + data.aggregates = [ + { + id: "reset-rule", + name: "Reset rule", + nodeIds: ["accessibility-node"], + subscriptionIds: [], + excludeTagIds: [], + renameMap: {}, + allowedTypes: [], + sortMode: "none", + updatedAt: NOW, + }, + ]; + const target = { + id: "published-target", + name: "Published target", + ruleId: "reset-rule", + fileName: "published.txt", + description: "", + isPublic: false, + lastPublishedAt: NOW, + lastPublishedUrl: `https://gist.githubusercontent.com/e2e/${GIST_ID}/raw/published.txt`, + lastPublishTransitionAt: null, + lastPublishTransitionFromFileName: null, + lastPublishTransitionToFileName: null, + lastPublishTransitionOutcome: null, + updatedAt: NOW, + }; + data.publishTargets = [ + target, + { + ...target, + id: "unpublished-target", + name: "Unpublished target", + fileName: "manual.txt", + lastPublishedAt: null, + lastPublishedUrl: null, + }, + ]; + return data; +} + +async function readRecord(page: Page): Promise { + return page.evaluate(async () => { + const database = await new Promise((resolve, reject) => { + const request = indexedDB.open("subman-workspace", 1); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + try { + return await new Promise((resolve, reject) => { + const transaction = database.transaction("workspace-state", "readonly"); + const request = transaction.objectStore("workspace-state").get("root"); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + } finally { + database.close(); + } + }); +} + +async function mockCloudReset( + page: Page, + context: BrowserContext, + options: { deferCommit?: boolean; conflict?: boolean; retry?: boolean } = {}, +) { + const data = resetData(); + const files: Record = { + "published.txt": "published output", + "manual.txt": "external contents without publication evidence", + "notes.txt": "operator notes", + "subman.v1.backup.json": "immutable migration backup", + }; + await seedUiWorkspace(page, context, data, files); + let document: WorkspaceDocumentV2 = { + version: 2, + schemaVersion: 2, + workspaceId: WORKSPACE_ID, + revision: 0, + updatedAt: NOW, + lastMutationId: null, + data, + tombstones: { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }, + }; + const requests: Array<{ method: string; path: string }> = []; + const mutations: JsonRecord[] = []; + let releaseCommit: () => void = () => undefined; + const commitReady = options.deferCommit + ? new Promise((resolve) => { + releaseCommit = resolve; + }) + : Promise.resolve(); + await context.route("https://api.github.com/**", async (route) => { + const request = route.request(); + const path = new URL(request.url()).pathname; + requests.push({ method: request.method(), path }); + if (request.method() !== "GET" || path !== `/gists/${GIST_ID}`) { + await route.abort("blockedbyclient"); + return; + } + await route.fulfill({ + json: { + id: GIST_ID, + owner: { login: "e2e" }, + description: "SubMan-Data", + updated_at: document.updatedAt, + html_url: `https://gist.github.com/e2e/${GIST_ID}`, + files: Object.fromEntries( + Object.entries({ + ...files, + "subman.json": JSON.stringify(document), + }).map(([filename, content]) => [ + filename, + { + filename, + content, + size: new TextEncoder().encode(content).byteLength, + raw_url: `https://gist.githubusercontent.com/e2e/${GIST_ID}/raw/${filename}`, + truncated: false, + }, + ]), + ), + }, + }); + }); + await context.route("**/api/workspaces/**/mutations", async (route) => { + const mutation = route.request().postDataJSON() as JsonRecord; + mutations.push(mutation); + await commitReady; + if (options.retry) { + await route.fulfill({ + status: 503, + headers: { "Retry-After": "120" }, + json: { + error: { + code: "gist_read_failed", + message: "GitHub is temporarily unavailable", + disposition: "retryable-upstream", + }, + }, + }); + return; + } + if (options.conflict) { + await route.fulfill({ + status: 409, + json: { + error: { + code: "revision_conflict", + message: "Cloud data changed after reset preview", + disposition: "state-conflict", + }, + revision: document.revision + 1, + document: { ...document, revision: document.revision + 1 }, + }, + }); + return; + } + document = { + ...document, + revision: Number(mutation.expectedRevision) + 1, + resetRevision: Number(mutation.expectedRevision) + 1, + lastMutationId: String(mutation.mutationId), + updatedAt: String(mutation.createdAt), + data: { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }, + }; + delete files["published.txt"]; + await route.fulfill({ + json: { + status: "committed", + mutationId: mutation.mutationId, + workspaceId: WORKSPACE_ID, + committedRevision: document.revision, + committedAt: document.updatedAt, + receipt: { kind: "workspace.reset" }, + document, + }, + }); + }); + return { mutations, requests, releaseCommit }; +} + +async function openCloudReset(page: Page) { + await page.goto("/auth"); + await expect(page.getByTestId("cloud-reset-action")).toBeEnabled(); + await page.getByTestId("cloud-reset-action").click(); + const dialog = page.getByRole("dialog", { + name: "Reset cloud data", + exact: true, + }); + await expect(dialog).toBeVisible(); + await expect(dialog).toHaveCSS("opacity", "1"); + return dialog; +} + +test("cloud reset previews its scope and cancellation sends no mutation", async ({ + page, + context, +}) => { + const browserErrors: string[] = []; + page.on("pageerror", (error) => browserErrors.push(error.message)); + page.on("console", (message) => { + if (message.type() === "error" || message.type() === "warning") + browserErrors.push(message.text()); + }); + const cloud = await mockCloudReset(page, context); + const dialog = await openCloudReset(page); + await expect(page).toHaveTitle("Settings - SubMan"); + await expect( + page.getByRole("heading", { name: "Settings", exact: true }), + ).toBeVisible(); + await expect(page.locator("vite-error-overlay")).toHaveCount(0); + await expect( + dialog.getByRole("heading", { name: "Reset cloud data", exact: true }), + ).toBeFocused(); + await expect(dialog.locator("#cloud-reset-warning")).toBeInViewport(); + await expect(dialog).toContainText(GIST_ID); + await expect(dialog).toContainText("Files to remove: 1"); + await expect(dialog).toContainText("published.txt"); + await expect(dialog).toContainText("Files to retain: 3"); + await expect(dialog).toContainText("subman.v1.backup.json"); + await expect(dialog).toContainText("manual.txt"); + await expect(page.getByTestId("cloud-reset-confirm")).toBeDisabled(); + await page.screenshot({ + path: "/tmp/subman-cloud-reset-desktop.png", + animations: "disabled", + }); + await dialog.getByLabel("Type RESET to confirm").fill("reset"); + await expect(page.getByTestId("cloud-reset-confirm")).toBeDisabled(); + await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); + expect(cloud.mutations).toEqual([]); + expect(cloud.requests.every((request) => request.method === "GET")).toBe( + true, + ); + expect((await readRecord(page)).binding).toMatchObject({ gistId: GIST_ID }); + expect(browserErrors).toEqual([]); +}); + +test("cloud reset waits for confirmation and keeps the original Gist and credentials", async ({ + page, + context, +}) => { + const cloud = await mockCloudReset(page, context, { deferCommit: true }); + const dialog = await openCloudReset(page); + await dialog.getByLabel("Type RESET to confirm").fill("RESET"); + await page.getByTestId("cloud-reset-confirm").click(); + await expect.poll(() => cloud.mutations.length).toBe(1); + await expect(page.getByTestId("cloud-reset-confirm")).toHaveText( + "Resetting cloud data...", + ); + await expect(page.getByTestId("cloud-reset-confirm")).toBeDisabled(); + expect((await readRecord(page)).binding).toMatchObject({ + gistId: GIST_ID, + revision: 0, + }); + await expect(page.getByTestId("cloud-reset-notice")).toHaveCount(0); + cloud.releaseCommit(); + await expect(dialog).toHaveCount(0); + await expect(page.getByTestId("cloud-reset-notice")).toHaveText( + "Cloud data reset. This Workspace is ready to start again.", + ); + const record = await readRecord(page); + expect(record.binding).toMatchObject({ + gistId: GIST_ID, + revision: 1, + baseline: { resetRevision: 1 }, + }); + expect(record.snapshot).toMatchObject({ + activeGistId: GIST_ID, + nodes: [], + aggregates: [], + publishTargets: [], + }); + expect(cloud.mutations[0]).toMatchObject({ + kind: "workspace.reset", + expectedRevision: 0, + expectedResetRevision: 0, + payload: {}, + }); + expect( + await page.evaluate(() => sessionStorage.getItem("subman:auth:session:v2")), + ).toContain("fixture-accessibility-token"); + await page.reload(); + await expect( + page.getByRole("button", { name: "Disconnect", exact: true }), + ).toBeVisible(); + await expect(page.getByTestId("cloud-reset-action")).toBeEnabled(); + expect(cloud.requests.every((request) => request.method === "GET")).toBe( + true, + ); +}); + +test("a concurrent browser change invalidates the cloud reset confirmation", async ({ + page, + context, +}) => { + const cloud = await mockCloudReset(page, context); + const dialog = await openCloudReset(page); + await dialog.getByLabel("Type RESET to confirm").fill("RESET"); + await page.evaluate(async () => { + const database = await new Promise((resolve, reject) => { + const request = indexedDB.open("subman-workspace", 1); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + try { + await new Promise((resolve, reject) => { + const transaction = database.transaction( + "workspace-state", + "readwrite", + ); + const store = transaction.objectStore("workspace-state"); + const read = store.get("root"); + read.onsuccess = () => { + const record = read.result; + record.snapshot.lastUpdated = "2026-11-01T12:00:00.000Z"; + store.put(record, "root"); + }; + transaction.oncomplete = () => resolve(); + transaction.onerror = () => reject(transaction.error); + }); + } finally { + database.close(); + } + }); + const before = await readRecord(page); + await page.getByTestId("cloud-reset-confirm").click(); + await expect(page.getByTestId("cloud-reset-dialog-notice")).toBeVisible(); + await expect(page.getByTestId("cloud-reset-confirm")).toBeDisabled(); + expect(cloud.mutations).toEqual([]); + expect(await readRecord(page)).toEqual(before); +}); + +test("cloud reset requires authentication while device reset remains available", async ({ + page, + context, +}) => { + const cloud = await mockCloudReset(page, context); + await page.evaluate(() => + sessionStorage.removeItem("subman:auth:session:v2"), + ); + await page.goto("/auth"); + await expect(page.getByTestId("cloud-reset-action")).toBeDisabled(); + await expect(page.getByTestId("device-reset-action")).toBeEnabled(); + expect(cloud.mutations).toEqual([]); +}); + +for (const outcome of ["retry", "conflict"] as const) { + test(`cloud reset retains its original mutation after ${outcome} and does not report success`, async ({ + page, + context, + }) => { + const cloud = await mockCloudReset(page, context, { [outcome]: true }); + const dialog = await openCloudReset(page); + await dialog.getByLabel("Type RESET to confirm").fill("RESET"); + await page.getByTestId("cloud-reset-confirm").click(); + await expect(page.getByTestId("cloud-reset-dialog-notice")).toBeVisible(); + await expect(dialog).toBeVisible(); + await expect(page.getByTestId("cloud-reset-confirm")).toBeDisabled(); + await expect(page.getByTestId("cloud-reset-notice")).not.toHaveText( + "Cloud data reset. This Workspace is ready to start again.", + ); + const record = await readRecord(page); + const queue = (record.workspaces as JsonRecord)[WORKSPACE_ID] as JsonRecord; + expect(queue.mutations).toHaveLength(1); + if (outcome === "conflict") { + expect(queue.delivery).toMatchObject({ + blocked: { disposition: "state-conflict", code: "revision_conflict" }, + }); + } + expect((queue.mutations as JsonRecord[])[0].mutationId).toBe( + cloud.mutations[0].mutationId, + ); + expect(cloud.mutations).toHaveLength(1); + expect(record.binding).toMatchObject({ gistId: GIST_ID }); + }); +} + +test("mobile Chinese cloud reset uses an explicit confirmation phrase", async ({ + page, + context, +}) => { + await page.setViewportSize({ width: 390, height: 844 }); + const cloud = await mockCloudReset(page, context); + await page.evaluate(() => localStorage.setItem("subman:locale:v1", "zh-CN")); + await page.goto("/auth"); + await expect(page.getByTestId("cloud-reset-action")).toBeEnabled(); + await page.getByTestId("cloud-reset-action").click(); + const dialog = page.getByRole("dialog", { + name: "重置云端数据", + exact: true, + }); + await expect(dialog).toBeVisible(); + await expect(dialog).toHaveCSS("opacity", "1"); + await expect(dialog).toContainText("所有已连接设备"); + await dialog.getByLabel("输入 RESET 以确认").fill("RESET"); + await expect(dialog.getByLabel("输入 RESET 以确认")).toBeInViewport({ + ratio: 1, + }); + await expect(page.getByTestId("cloud-reset-confirm")).toBeEnabled(); + await page.screenshot({ + path: "/tmp/subman-cloud-reset-mobile.png", + animations: "disabled", + }); + await dialog.getByRole("button", { name: "取消", exact: true }).click(); + expect(cloud.mutations).toEqual([]); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + ).toBe(true); +}); diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index b713cde..6a5def5 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -7,6 +7,34 @@ const STORAGE_KEY = "subman:locale:v1"; const DEFAULT_LOCALE: Locale = "en"; const zhCN: Record = { + "Reset cloud data": "重置云端数据", + "Start again with an empty Workspace in the same Gist. Your GitHub connection is kept.": + "清空当前 Gist 的工作区数据并重新开始,保留 GitHub 连接。", + "This clears cloud resources, rules, publication settings, and managed published files for every connected device. Existing subscription links may stop working.": + "此操作会清空云端资源、规则、发布设置及受管理的已发布文件,并影响所有已连接设备。现有订阅链接可能失效。", + "The original Gist, migration backup, and external files are retained. Finish pending synchronization or repair before continuing.": + "原 Gist、迁移备份和外部文件会保留。请先完成待处理的同步或修复。", + "Nodes: {nodes}, subscriptions: {subscriptions}, rules: {aggregates}, publish targets: {publishTargets}, client exports: {clientExports}": + "节点:{nodes},订阅:{subscriptions},规则:{aggregates},发布目标:{publishTargets},客户端导出:{clientExports}", + "Files to remove": "将移除的文件", + "Files to retain": "将保留的文件", + "The Gist and your GitHub connection stay in place. Only confirmed cloud reset completes this action.": + "Gist 和 GitHub 连接将保留。只有云端确认后,重置才算完成。", + "Type RESET to confirm": "输入 RESET 以确认", + "Clear cloud data and start again": "清空云端并重新开始", + "Resetting cloud data...": "正在重置云端数据...", + "Cloud data reset. This Workspace is ready to start again.": + "云端数据已重置,可以在当前工作区重新开始。", + "Cloud reset could not be prepared. Check the connection and try again.": + "无法准备云端重置。请检查连接后重试。", + "Workspace changed while cloud reset was being prepared. Review the latest cloud data and try again.": + "准备云端重置期间工作区已发生变化。请查看最新云端数据后重试。", + "Load the latest cloud data before resetting cloud data.": + "请先加载最新云端数据,再重置云端数据。", + "Cloud delivery is active. Wait for it to finish before resetting cloud data.": + "当前仍在发送云端变更,请等待发送结束后再重置云端数据。", + "Cloud Workspace was reset. Reload from Cloud before retrying this action.": + "云端工作区已重置。请从云端重新加载后再重试此操作。", "Reset this device": "重置此设备", "If the original Gist was deleted or this browser cannot reconnect, reset its Workspace connection and start setup again.": "如果原 Gist 已删除,或此浏览器无法重新连接,可重置此设备的工作区连接后重新设置。", diff --git a/src/lib/server/api/workspace.test.ts b/src/lib/server/api/workspace.test.ts index f204ce5..724d46f 100644 --- a/src/lib/server/api/workspace.test.ts +++ b/src/lib/server/api/workspace.test.ts @@ -77,6 +77,18 @@ function mutation(): WorkspaceMutation { } describe("loadServerWorkspace", () => { + it("retains the reset boundary for internal Server API mutations", async () => { + const result = await loadServerWorkspace(TOKEN, { + ensureWorkspace: async () => ({ gist: gist(), created: false }), + getFileContent: async () => + serializeWorkspaceDocumentV2({ ...document(), resetRevision: 3 }), + }); + expect(result.resetRevision).toBe(3); + const identity = createServerMutationIdentity(result); + expect(identity.expectedRevision).toBe(4); + expect(identity.expectedResetRevision).toBe(3); + }); + it("loads legacy V1 data at revision zero for coordinator migration", async () => { const state = createDefaultWorkspaceState(); state.nodes = document().data.nodes; diff --git a/src/lib/server/api/workspace.ts b/src/lib/server/api/workspace.ts index e5ef7ce..27a7d25 100644 --- a/src/lib/server/api/workspace.ts +++ b/src/lib/server/api/workspace.ts @@ -20,6 +20,7 @@ export type ServerWorkspace = { gist: GistMeta; workspaceId: string; revision: number; + resetRevision?: number; data: WorkspaceData; }; @@ -86,6 +87,10 @@ export async function loadServerWorkspace( gist, workspaceId, revision: parsed.schemaVersion === 2 ? parsed.document.revision : 0, + ...(parsed.schemaVersion === 2 && + parsed.document.resetRevision !== undefined + ? { resetRevision: parsed.document.resetRevision } + : {}), data: selectWorkspaceData(parsed.document.data), }; } catch (error) { @@ -110,12 +115,20 @@ export function createServerMutationIdentity( clock: ServerMutationClock = defaultClock, ): Pick< WorkspaceMutation, - "mutationId" | "workspaceId" | "expectedRevision" | "source" | "createdAt" + | "mutationId" + | "workspaceId" + | "expectedRevision" + | "expectedResetRevision" + | "source" + | "createdAt" > { return { mutationId: clock.id(), workspaceId: workspace.workspaceId, expectedRevision: workspace.revision, + ...(workspace.resetRevision === undefined + ? {} + : { expectedResetRevision: workspace.resetRevision }), source: "server-api", createdAt: clock.now(), }; diff --git a/src/lib/server/workspace-coordinator-core.test.ts b/src/lib/server/workspace-coordinator-core.test.ts index 69b8ce5..c8f1b9a 100644 --- a/src/lib/server/workspace-coordinator-core.test.ts +++ b/src/lib/server/workspace-coordinator-core.test.ts @@ -309,6 +309,178 @@ async function expectCode( } describe("Workspace coordinator serialization and idempotency", () => { + it("resets in one verified PATCH and preserves backup, external files, and idempotency", async () => { + const initial = document(); + initial.data.publishTargets[0] = { + ...target(), + lastPublishedAt: T0, + lastPublishedUrl: + "https://gist.githubusercontent.com/owner/gist-1/raw/aggregate.txt", + }; + const gateway = new MemoryGateway({ + "subman.json": serializeWorkspaceDocumentV2(initial), + "subman.v1.backup.json": "immutable legacy bytes", + "aggregate.txt": "published output", + "client.json": "unpublished external output", + "notes.txt": "external notes", + }); + const { core, journal } = coordinator(gateway); + const reset = mutation( + "10000000-0000-4000-8000-000000000080", + 1, + "workspace.reset", + {}, + ); + const result = await core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: reset, + }); + expect(result.document.resetRevision).toBe(2); + expect(result.document.data.nodes).toEqual([]); + expect(gateway.patches).toHaveLength(1); + expect(gateway.patches[0]?.["aggregate.txt"]).toBeNull(); + expect(gateway.files["aggregate.txt"]).toBe(undefined); + expect(gateway.files["client.json"]).toBe("unpublished external output"); + expect(gateway.files["notes.txt"]).toBe("external notes"); + expect(gateway.files["subman.v1.backup.json"]).toBe( + "immutable legacy bytes", + ); + expect(journal.processed.has(reset.mutationId)).toBe(true); + const retry = await core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: reset, + }); + expect(retry.status).toBe("already-committed"); + expect(gateway.patches).toHaveLength(1); + }); + + it("allows historical committed retries after reset but rejects uncommitted pre-reset intents", async () => { + const gateway = new MemoryGateway({ + "subman.json": serializeWorkspaceDocumentV2(document()), + }); + const { core } = coordinator(gateway); + const old = replaceNodeMutation("10000000-0000-4000-8000-000000000081"); + await core.mutate({ githubToken: TOKEN, gistId: GIST_ID, mutation: old }); + await core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: mutation( + "10000000-0000-4000-8000-000000000082", + 2, + "workspace.reset", + {}, + ), + }); + const retry = await core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: old, + }); + expect(retry.status).toBe("already-committed"); + expect(retry.document.data.nodes).toEqual([]); + const rejected = await core.mutateSettled({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: replaceNodeMutation( + "10000000-0000-4000-8000-000000000083", + 3, + "new-before-reset", + ), + }); + expect(rejected.ok).toBe(false); + if (rejected.ok) throw new Error("Expected reset boundary conflict"); + if (!(rejected.error instanceof WorkspaceCoordinatorError)) + throw new Error("Expected coordinator conflict"); + expect(rejected.error.code).toBe("revision_conflict"); + expect(rejected.error.latestDocument?.resetRevision).toBe(3); + const created = await core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: { + ...replaceNodeMutation( + "10000000-0000-4000-8000-000000000084", + 3, + "new-after-reset", + ), + expectedResetRevision: 3, + }, + }); + expect(created.document.data.nodes.map((item) => item.id)).toEqual([ + "new-after-reset", + ]); + expect(created.document.resetRevision).toBe(3); + expect(gateway.patches).toHaveLength(3); + }); + + it("does not clear concurrent changes after a stale reset preview", async () => { + const gateway = new MemoryGateway({ + "subman.json": serializeWorkspaceDocumentV2(document()), + }); + const { core } = coordinator(gateway); + await core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: replaceNodeMutation("10000000-0000-4000-8000-000000000085"), + }); + await expectCode( + core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: mutation( + "10000000-0000-4000-8000-000000000086", + 1, + "workspace.reset", + {}, + ), + }), + "revision_conflict", + ); + expect(gateway.patches).toHaveLength(1); + }); + + it("recovers a reset and its output deletions after losing the acknowledgement", async () => { + const initial = document(); + initial.data.publishTargets[0] = { + ...target(), + lastPublishedAt: T0, + lastPublishedUrl: + "https://gist.githubusercontent.com/owner/gist-1/raw/aggregate.txt", + }; + const gateway = new MemoryGateway({ + "subman.json": serializeWorkspaceDocumentV2(initial), + "aggregate.txt": "published output", + }); + const journal = new MemoryJournal(); + journal.failNextCommit = true; + const reset = mutation( + "10000000-0000-4000-8000-000000000087", + 1, + "workspace.reset", + {}, + ); + await expectCode( + coordinator(gateway, journal).core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: reset, + }), + "commit_index_failed", + ); + expect(journal.pending.has(reset.mutationId)).toBe(true); + const result = await coordinator(gateway, journal).core.mutate({ + githubToken: TOKEN, + gistId: GIST_ID, + mutation: reset, + }); + expect(result.status).toBe("already-committed"); + expect(result.document.resetRevision).toBe(2); + expect(gateway.files["aggregate.txt"]).toBe(undefined); + expect(gateway.patches).toHaveLength(1); + expect(journal.pending.size).toBe(0); + }); + it("preserves safe timeout metadata and releases the operation queue", async () => { const backing = new MemoryGateway({ "subman.json": serializeWorkspaceDocumentV2(document()), diff --git a/src/lib/server/workspace-coordinator-core.ts b/src/lib/server/workspace-coordinator-core.ts index bb78977..eec8d6c 100644 --- a/src/lib/server/workspace-coordinator-core.ts +++ b/src/lib/server/workspace-coordinator-core.ts @@ -130,6 +130,7 @@ const MUTATION_KINDS = new Set([ "client-export.publish", "output.delete", "workspace.bootstrap.cleanup", + "workspace.reset", "workspace.migrate", "workspace.reconcile", ]); diff --git a/src/lib/stores/app-browser-behavior.test.ts b/src/lib/stores/app-browser-behavior.test.ts index 87a46de..f84d4a4 100644 --- a/src/lib/stores/app-browser-behavior.test.ts +++ b/src/lib/stores/app-browser-behavior.test.ts @@ -767,3 +767,245 @@ test("a stale browser cache rebases one business intent onto the latest IndexedD expect(stored.quarantines).toEqual([]); runtime.setBrowserWorkspacePersistenceForTest(null); }); + +async function resetActionHarness() { + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: new FailingStorage(), + }); + Object.defineProperty(globalThis, "sessionStorage", { + configurable: true, + value: new FailingStorage(), + }); + Object.defineProperty(globalThis, "document", { + configurable: true, + value: { documentElement: { lang: "" } }, + }); + const [ + workspaceData, + stateModule, + persistenceModule, + runtime, + appStore, + authStore, + cloudStatus, + mutations, + ] = await Promise.all([ + import("$lib/workspace-data"), + import("$lib/workspace-v2-state"), + import("$lib/workspace-persistence"), + import("$lib/workspace-persistence-browser"), + import("$lib/stores/app"), + import("$lib/stores/auth"), + import("$lib/workspace-cloud-status"), + import("$lib/workspace-mutation"), + ]); + const baseline: WorkspaceDocumentV2 = { + version: 2, + schemaVersion: 2, + workspaceId: WORKSPACE_ID, + revision: 0, + updatedAt: NOW, + lastMutationId: null, + data: { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }, + tombstones: { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }, + }; + const record = persistenceModule.createEmptyWorkspacePersistenceRecord(); + const initial = stateModule.hydrateAppStateFromWorkspaceDocument( + workspaceData.createDefaultWorkspaceState(NOW), + baseline, + GIST_ID, + ); + record.snapshot = initial; + record.binding = stateModule.createWorkspaceV2LocalState(GIST_ID, { + baseline, + }); + const persistence = new persistenceModule.InMemoryWorkspacePersistence( + record, + ); + runtime.setBrowserWorkspacePersistenceForTest(persistence); + await appStore.initializeAppStatePersistence(); + authStore.authState.update((state) => ({ + ...state, + token: "reset-intent-fixture-token", + })); + cloudStatus.workspaceCloudStatus.set({ phase: "ready", message: null }); + const resetDocument = mutations.applyWorkspaceMutation( + baseline, + { + mutationId: "f0000000-0000-4000-8000-000000000010", + workspaceId: WORKSPACE_ID, + expectedRevision: 0, + source: "browser", + createdAt: NOW, + kind: "workspace.reset", + payload: {}, + }, + { committedAt: NOW, gist: { id: GIST_ID, files: [] } }, + ).document; + const resetSnapshot = stateModule.hydrateAppStateFromWorkspaceDocument( + initial, + resetDocument, + GIST_ID, + ); + const resetBinding = stateModule.createWorkspaceV2LocalState(GIST_ID, { + baseline: resetDocument, + }); + return { + appStore, + persistence, + persistenceModule, + runtime, + resetDocument, + applyPeerReset: () => + persistence.rebindWorkspace({ + snapshot: resetSnapshot, + binding: resetBinding, + }), + }; +} + +function unseenResetNode(id: string) { + return { + id, + name: "Never uploaded before reset", + type: "vless" as const, + raw: `vless://${id}`, + tags: [], + enabled: true, + updatedAt: NOW, + source: "single" as const, + }; +} + +for (const refreshCache of [false, true]) { + test(`accepted new-node intents cannot cross reset before serialization with a ${refreshCache ? "refreshed" : "stale"} cache`, async () => { + const harness = await resetActionHarness(); + const { appStore, persistence, runtime } = harness; + let releaseRead = () => {}; + const readGate = new Promise((resolve) => { + releaseRead = resolve; + }); + let firstReadArrived = () => {}; + const readStarted = new Promise((resolve) => { + firstReadArrived = resolve; + }); + const originalRead = persistence.read.bind(persistence); + let gateNextRead = true; + persistence.read = async () => { + if (gateNextRead) { + gateNextRead = false; + firstReadArrived(); + await readGate; + } + return originalRead(); + }; + let commitCount = 0; + const originalCommit = persistence.commitAutomaticAction.bind(persistence); + persistence.commitAutomaticAction = async (input) => { + commitCount += 1; + return originalCommit(input); + }; + let requestCount = 0; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => { + requestCount += 1; + throw new Error("Unexpected delivery of a pre-reset intent"); + }) as typeof fetch; + const actions: ReturnType[] = []; + try { + // The first accepted action holds serialization before either intent persists. + actions.push( + appStore.upsertNode( + unseenResetNode("f0000000-0000-4000-8000-000000000011"), + ), + ); + actions.push( + appStore.upsertNode( + unseenResetNode("f0000000-0000-4000-8000-000000000012"), + ), + ); + expect(actions.map((action) => action.submitted)).toEqual([true, true]); + await readStarted; + await harness.applyPeerReset(); + if (refreshCache) await runtime.refreshBrowserWorkspacePersistence(); + expect( + runtime.getBrowserWorkspaceBinding()?.baseline?.resetRevision ?? 0, + ).toBe(refreshCache ? 1 : 0); + expect(harness.resetDocument.tombstones.nodes).toEqual([]); + releaseRead(); + for (const action of actions) { + const result = await action.completion; + expect(result.status).toBe("rejected-before-durable-commit"); + expect("code" in result ? result.code : null).toBe("concurrent-update"); + } + const stored = await persistence.read(); + expect(stored.binding?.baseline?.resetRevision).toBe(1); + expect(stored.snapshot?.nodes).toEqual([]); + expect(stored.workspaces).toEqual({}); + expect(stored.quarantines).toEqual([]); + expect(commitCount).toBe(0); + expect(requestCount).toBe(0); + } finally { + releaseRead(); + await Promise.all(actions.map((action) => action.completion)); + globalThis.fetch = originalFetch; + runtime.setBrowserWorkspacePersistenceForTest(null); + } + }); +} + +test("an automatic CAS retry rejects a new-node intent when reset changes the generation", async () => { + const harness = await resetActionHarness(); + const { appStore, persistence, persistenceModule, runtime } = harness; + const originalCommit = persistence.commitAutomaticAction.bind(persistence); + let commitCount = 0; + persistence.commitAutomaticAction = async (input) => { + commitCount += 1; + if (commitCount === 1) { + await harness.applyPeerReset(); + throw new persistenceModule.WorkspaceConcurrentUpdateError(); + } + return originalCommit(input); + }; + let requestCount = 0; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => { + requestCount += 1; + throw new Error( + "Unexpected delivery after crossing reset during CAS retry", + ); + }) as typeof fetch; + try { + const action = appStore.upsertNode( + unseenResetNode("f0000000-0000-4000-8000-000000000013"), + ); + expect(action.submitted).toBe(true); + const result = await action.completion; + expect(result.status).toBe("rejected-before-durable-commit"); + expect("code" in result ? result.code : null).toBe("concurrent-update"); + const stored = await persistence.read(); + expect(stored.binding?.baseline?.resetRevision).toBe(1); + expect(stored.binding?.baseline?.tombstones.nodes).toEqual([]); + expect(stored.snapshot?.nodes).toEqual([]); + expect(stored.workspaces).toEqual({}); + expect(stored.quarantines).toEqual([]); + expect(commitCount).toBe(1); + expect(requestCount).toBe(0); + } finally { + globalThis.fetch = originalFetch; + runtime.setBrowserWorkspacePersistenceForTest(null); + } +}); diff --git a/src/lib/stores/app.ts b/src/lib/stores/app.ts index 787d43b..a95be46 100644 --- a/src/lib/stores/app.ts +++ b/src/lib/stores/app.ts @@ -86,6 +86,9 @@ function createMutationDraft( mutationId: options.mutationId ?? VALIDATION_MUTATION_ID, workspaceId: binding?.workspaceId ?? LOCAL_VALIDATION_WORKSPACE_ID, expectedRevision: binding?.revision ?? 0, + ...(binding?.baseline?.resetRevision !== undefined + ? { expectedResetRevision: binding.baseline.resetRevision } + : {}), source: "browser", createdAt: options.createdAt ?? VALIDATION_TIMESTAMP, kind, @@ -177,9 +180,13 @@ function runPreparedWorkspaceAction( createdAt: string, ) => PreparedAction, ): WorkspaceActionHandle { + let acceptedWorkspaceId: string | undefined; + let acceptedResetRevision = 0; try { const binding = getBrowserWorkspaceBinding(); requireCloudAction(binding); + acceptedWorkspaceId = binding?.workspaceId; + acceptedResetRevision = binding?.baseline?.resetRevision ?? 0; const preliminary = prepare(get(appState), binding, VALIDATION_TIMESTAMP); createMutationDraft(kind, preliminary.payload, binding); } catch (error) { @@ -197,6 +204,14 @@ function runPreparedWorkspaceAction( const current = record.snapshot ?? get(appState); if (record.snapshot) appState.set(record.snapshot); const binding = record.binding; + if ( + binding?.workspaceId !== acceptedWorkspaceId || + (binding?.baseline?.resetRevision ?? 0) !== acceptedResetRevision + ) { + throw new WorkspaceConcurrentUpdateError( + "Cloud Workspace was reset. Reload from Cloud before retrying this action.", + ); + } const token = requireCloudAction(binding); const queue = binding ? record.workspaces[binding.workspaceId] : null; if ( diff --git a/src/lib/workspace-browser-session-v2.test.ts b/src/lib/workspace-browser-session-v2.test.ts index af30373..656e345 100644 --- a/src/lib/workspace-browser-session-v2.test.ts +++ b/src/lib/workspace-browser-session-v2.test.ts @@ -46,6 +46,210 @@ const MUTATION_ID = "b0000000-0000-4000-8000-000000000001"; const MUTATION_ID_2 = "b0000000-0000-4000-8000-000000000002"; const MUTATION_ID_3 = "b0000000-0000-4000-8000-000000000003"; +describe("cloud reset submission boundaries", () => { + it("captures the action boundary before the first asynchronous persistence read", async () => { + const original = document(); + const originalBinding = createWorkspaceV2LocalState("gist-1", { + baseline: original, + }); + class ResetBeforeFirstRead extends InMemoryWorkspacePersistence { + resetOnRead = false; + override async read() { + if (this.resetOnRead) { + this.resetOnRead = false; + const reset = { ...document(2, MUTATION_ID_3, []), resetRevision: 2 }; + await this.rebindWorkspace({ + snapshot: stateFor(reset), + binding: createWorkspaceV2LocalState("gist-1", { baseline: reset }), + }); + } + return super.read(); + } + } + const persistence = new ResetBeforeFirstRead(); + let current = stateFor(original); + await seed(persistence, current, originalBinding); + persistence.resetOnRead = true; + const result = await submitBrowserWorkspaceMutation( + { + token: "test-token", + kind: "node.upsert", + payload: { operation: "replace", node: node("unseen-before-reset") }, + }, + { + persistence, + getBinding: () => originalBinding, + getState: () => current, + setState: (next) => { + current = next; + }, + fetchImpl: async () => { + throw new Error("Old intent cannot be submitted"); + }, + }, + ); + expect(result.status).toBe("rejected-before-durable-commit"); + expect((await persistence.read()).workspaces["gist:gist-1"]).toBe( + undefined, + ); + }); + it("does not roll the reset boundary back when accepting a stale cloud snapshot", async () => { + const persistence = new InMemoryWorkspacePersistence(); + const reset = { ...document(2, MUTATION_ID_3, []), resetRevision: 2 }; + let current = stateFor(reset); + await seed( + persistence, + current, + createWorkspaceV2LocalState("gist-1", { baseline: reset }), + ); + let rejected = false; + try { + await persistBrowserWorkspaceSnapshot( + { origin: "v2", document: document(), state: stateFor(document()) }, + "gist-1", + "automatic", + { + persistence, + getState: () => current, + setState: (next) => { + current = next; + }, + }, + ); + } catch (error) { + rejected = error instanceof WorkspaceConcurrentUpdateError; + } + expect(rejected).toBe(true); + expect((await persistence.read()).binding?.baseline?.resetRevision).toBe(2); + expect(current.nodes).toEqual([]); + }); + it("never automatically reprepares a reset after a local CAS conflict", async () => { + class ConflictingPersistence extends InMemoryWorkspacePersistence { + attempts = 0; + override async commitExplicitAction( + _input: Parameters< + InMemoryWorkspacePersistence["commitExplicitAction"] + >[0], + ): Promise { + this.attempts += 1; + throw new WorkspaceConcurrentUpdateError(); + } + } + const persistence = new ConflictingPersistence(); + const original = document(); + let current = stateFor(original); + await seed( + persistence, + current, + createWorkspaceV2LocalState("gist-1", { baseline: original }), + ); + const before = await persistence.read(); + const result = await submitBrowserWorkspaceMutation( + { + token: "test-token", + kind: "workspace.reset", + payload: {}, + expectedRevision: original.revision, + expectedResetRevision: 0, + expected: { + snapshot: before.snapshot, + binding: before.binding, + queue: null, + }, + }, + { + persistence, + getState: () => current, + setState: (next) => { + current = next; + }, + }, + ); + expect(result.status).toBe("rejected-before-durable-commit"); + expect(persistence.attempts).toBe(1); + }); + it("rejects an unseen old creation when CAS retry crosses a cloud reset", async () => { + class ResetDuringCommit extends InMemoryWorkspacePersistence { + attempts = 0; + override async commitExplicitAction( + input: Parameters< + InMemoryWorkspacePersistence["commitExplicitAction"] + >[0], + ) { + this.attempts += 1; + if (this.attempts === 1) { + const reset = { ...document(2, MUTATION_ID_3, []), resetRevision: 2 }; + await this.rebindWorkspace({ + snapshot: stateFor(reset), + binding: createWorkspaceV2LocalState("gist-1", { baseline: reset }), + }); + throw new WorkspaceConcurrentUpdateError(); + } + return super.commitExplicitAction(input); + } + } + const persistence = new ResetDuringCommit(); + let current = stateFor(document()); + await seed( + persistence, + current, + createWorkspaceV2LocalState("gist-1", { baseline: document() }), + ); + const result = await submitBrowserWorkspaceMutation( + { + token: "test-token", + kind: "node.upsert", + payload: { operation: "replace", node: node("never-uploaded") }, + }, + { + persistence, + getState: () => current, + setState: (next) => { + current = next; + }, + fetchImpl: async () => { + throw new Error("Old intent must not reach the network"); + }, + }, + ); + expect(result.status).toBe("rejected-before-durable-commit"); + expect(persistence.attempts).toBe(1); + expect((await persistence.read()).workspaces["gist:gist-1"]).toBe( + undefined, + ); + }); + it("includes the observed reset boundary in fresh mutations", async () => { + const persistence = new InMemoryWorkspacePersistence(); + const reset = { ...document(2, MUTATION_ID_3, []), resetRevision: 2 }; + let current = stateFor(reset); + await seed( + persistence, + current, + createWorkspaceV2LocalState("gist-1", { baseline: reset }), + ); + await submitBrowserWorkspaceMutation( + { + token: "test-token", + kind: "node.upsert", + payload: { operation: "replace", node: node("fresh") }, + }, + { + persistence, + getState: () => current, + setState: (next) => { + current = next; + }, + fetchImpl: async () => + failureResponse(503, "gist_read_failed", "retryable-upstream"), + }, + ); + expect( + (await persistence.read()).workspaces["gist:gist-1"]?.mutations[0] + ?.expectedResetRevision, + ).toBe(2); + }); +}); + function node(id: string, name = id): NodeItem { return { id, diff --git a/src/lib/workspace-browser-session-v2.ts b/src/lib/workspace-browser-session-v2.ts index 13dcb6b..9c96be9 100644 --- a/src/lib/workspace-browser-session-v2.ts +++ b/src/lib/workspace-browser-session-v2.ts @@ -33,6 +33,7 @@ import { type WorkspaceResetExpectation, } from "$lib/workspace-persistence"; import { + getBrowserWorkspaceBinding, getBrowserWorkspacePersistence, initializeBrowserWorkspacePersistence, refreshBrowserWorkspacePersistence, @@ -64,6 +65,7 @@ export type BrowserWorkspaceSnapshot = { type BrowserWorkspaceSessionDependencies = { persistence?: BrowserWorkspacePersistence; + getBinding?: () => WorkspaceV2LocalState | null; getState?: () => AppState; setState?: (state: AppState) => void; fetchImpl?: typeof fetch; @@ -378,6 +380,9 @@ function mutationDraft( : crypto.randomUUID(), workspaceId: binding.workspaceId, expectedRevision: binding.revision ?? 0, + ...(binding.baseline?.resetRevision !== undefined + ? { expectedResetRevision: binding.baseline.resetRevision } + : {}), source: "browser", createdAt: (dependencies.now ?? (() => new Date().toISOString()))(), kind, @@ -689,6 +694,14 @@ export async function persistBrowserWorkspaceSnapshot( if (record.binding && record.binding.gistId !== gistId) { throw new WorkspaceBindingLockedError(); } + if ( + record.binding?.baseline && + (snapshot.document.revision < (record.binding.revision ?? 0) || + (snapshot.document.resetRevision ?? 0) < + (record.binding.baseline.resetRevision ?? 0)) + ) { + throw new WorkspaceConcurrentUpdateError(); + } const binding = createWorkspaceV2LocalState(gistId, { baseline: snapshot.document, syncMode, @@ -747,6 +760,17 @@ async function reconcileBrowserWorkspaceInternal( if (record.binding && record.binding.workspaceId !== workspaceId) { throw new WorkspaceBindingLockedError(); } + const originalResetRevision = baseline.resetRevision ?? 0; + const localIntentBaseline = + record.binding?.conflictBaseline ?? record.binding?.baseline; + if ( + localIntentBaseline && + (localIntentBaseline.resetRevision ?? 0) !== originalResetRevision + ) { + throw new WorkspaceConcurrentUpdateError( + "Cloud Workspace was reset. Reload from Cloud before retrying this action.", + ); + } let pending = record.workspaces[workspaceId]?.mutations ?? []; if ( input.migrationMutationId && @@ -834,6 +858,11 @@ async function reconcileBrowserWorkspaceInternal( throw new Error("Committed Workspace state is unavailable"); } baseline = committed.baseline; + if ((baseline.resetRevision ?? 0) !== originalResetRevision) { + throw new WorkspaceConcurrentUpdateError( + "Cloud Workspace was reset. Reload from Cloud before retrying this action.", + ); + } pending = record.workspaces[workspaceId]?.mutations ?? []; if (pending.length > 0) { throw new Error("Pending Workspace delivery did not settle"); @@ -1025,18 +1054,37 @@ export async function submitBrowserWorkspaceMutation( token: string; kind: WorkspaceMutation["kind"]; payload: unknown; + expected?: WorkspaceResetExpectation; + expectedRevision?: number; + expectedResetRevision?: number; }, dependencies: BrowserWorkspaceSessionDependencies = {}, ): Promise { let mutationId: string | null = null; try { + const acceptedBinding = + dependencies.getBinding?.() ?? + (dependencies.persistence ? undefined : getBrowserWorkspaceBinding()); + let workspaceId: string | null = acceptedBinding?.workspaceId ?? null; + let observedResetRevision = + input.expectedResetRevision ?? + (acceptedBinding?.baseline + ? (acceptedBinding.baseline.resetRevision ?? 0) + : undefined); dependencies = await withStateAccess(dependencies); const persistence = await persistenceFor(dependencies); mutationId = dependencies.mutationId ? dependencies.mutationId() : crypto.randomUUID(); const createdAt = (dependencies.now ?? (() => new Date().toISOString()))(); - let workspaceId: string | null = null; + if ( + input.kind === "workspace.reset" && + (!input.expected || input.expectedRevision === undefined) + ) { + throw new WorkspaceConcurrentUpdateError( + "Prepare and confirm cloud reset before submitting it.", + ); + } for (let attempt = 0; attempt < 2; attempt += 1) { const record = await readPersistence(dependencies, persistence); const binding = record.binding; @@ -1047,6 +1095,18 @@ export async function submitBrowserWorkspaceMutation( ); } workspaceId ??= binding.workspaceId; + observedResetRevision ??= binding.baseline.resetRevision ?? 0; + const queue = record.workspaces[binding.workspaceId] ?? null; + if ( + (binding.baseline.resetRevision ?? 0) !== observedResetRevision || + (input.expectedRevision !== undefined && + binding.revision !== input.expectedRevision) || + (input.expected && + JSON.stringify({ snapshot: record.snapshot, binding, queue }) !== + JSON.stringify(input.expected)) + ) { + throw new WorkspaceConcurrentUpdateError(); + } if (binding.workspaceId !== workspaceId) { return rejectedWorkspaceOperation( new WorkspaceConcurrentUpdateError(), @@ -1070,6 +1130,10 @@ export async function submitBrowserWorkspaceMutation( mutationId, workspaceId: binding.workspaceId, expectedRevision: binding.revision, + ...(input.expectedResetRevision !== undefined || + binding.baseline.resetRevision !== undefined + ? { expectedResetRevision: observedResetRevision } + : {}), source: "browser", createdAt, kind: input.kind, @@ -1077,7 +1141,11 @@ export async function submitBrowserWorkspaceMutation( }); const { expectedRevision: _allocatedByPersistence, ...draft } = parsed; try { - await persistence.commitExplicitAction({ binding, mutation: draft }); + await persistence.commitExplicitAction({ + binding, + mutation: draft, + expected: input.expected, + }); } catch (error) { const recovered = await hydrateAfterDurableCommit( dependencies, @@ -1091,7 +1159,12 @@ export async function submitBrowserWorkspaceMutation( "workspace_explicit_commit_acknowledgement_failed", ); } - if (error instanceof WorkspaceConcurrentUpdateError && attempt === 0) { + if ( + error instanceof WorkspaceConcurrentUpdateError && + attempt === 0 && + input.kind !== "workspace.reset" && + !input.expected + ) { continue; } return rejectedWorkspaceOperation(error, mutationId); diff --git a/src/lib/workspace-diagnostics.ts b/src/lib/workspace-diagnostics.ts index 21abedb..5058f4e 100644 --- a/src/lib/workspace-diagnostics.ts +++ b/src/lib/workspace-diagnostics.ts @@ -28,6 +28,7 @@ const MUTATION_KINDS = new Set([ "output.delete", "workspace.bootstrap.cleanup", "workspace.migrate", + "workspace.reset", "workspace.reconcile", ]); diff --git a/src/lib/workspace-document.test.ts b/src/lib/workspace-document.test.ts index 74cc6e0..c622d3b 100644 --- a/src/lib/workspace-document.test.ts +++ b/src/lib/workspace-document.test.ts @@ -8,6 +8,7 @@ import type { } from "$lib/models"; import { getWorkspaceContentSignature, + getWorkspaceResetRevision, migrateWorkspaceDocumentV1ToV2, parseWorkspaceDocument, serializeWorkspaceDocumentV2, @@ -262,6 +263,45 @@ describe("Workspace Schema V2 migration", () => { }); }); +describe("Workspace reset revision compatibility", () => { + it("preserves historical document bytes and signatures when the boundary is absent", () => { + const legacy = document(); + const serialized = serializeWorkspaceDocumentV2(legacy); + const parsed = parseWorkspaceDocument(serialized); + if (parsed.schemaVersion !== 2) throw new Error("Expected V2"); + expect(Object.hasOwn(parsed.document, "resetRevision")).toBe(false); + expect(getWorkspaceResetRevision(parsed.document)).toBe(0); + expect(serializeWorkspaceDocumentV2(parsed.document)).toBe(serialized); + expect(getWorkspaceContentSignature(parsed.document)).toBe( + JSON.stringify({ + data: JSON.parse(serialized).data, + tombstones: JSON.parse(serialized).tombstones, + }), + ); + }); + + it("round-trips the reset revision and includes it in recovery signatures", () => { + const reset = document({ resetRevision: 6 }); + const parsed = parseWorkspaceDocument(serializeWorkspaceDocumentV2(reset)); + if (parsed.schemaVersion !== 2) throw new Error("Expected V2"); + expect(parsed.document.resetRevision).toBe(6); + expect(getWorkspaceResetRevision(parsed.document)).toBe(6); + expect(getWorkspaceContentSignature(parsed.document)).not.toBe( + getWorkspaceContentSignature(document()), + ); + }); + + it("rejects invalid or future reset revisions", () => { + for (const resetRevision of [-1, 1.5, 8, "0", null]) { + expect(() => + parseWorkspaceDocument( + JSON.stringify({ ...document(), resetRevision }), + ), + ).toThrow(); + } + }); +}); + describe("Workspace Schema V2 serialization", () => { it("is stable across object insertion order and preserves entity order", () => { const first = document(); diff --git a/src/lib/workspace-document.ts b/src/lib/workspace-document.ts index 5c397cb..4b9c446 100644 --- a/src/lib/workspace-document.ts +++ b/src/lib/workspace-document.ts @@ -122,12 +122,19 @@ export type WorkspaceDocumentV2 = { schemaVersion: 2; workspaceId: string; revision: number; + resetRevision?: number; updatedAt: string; lastMutationId: string | null; data: WorkspaceData; tombstones: WorkspaceTombstones; }; +export function getWorkspaceResetRevision( + document: Pick, +): number { + return document.resetRevision ?? 0; +} + export type WorkspaceDocumentV1 = { version: 1; exportedAt?: string; @@ -812,16 +819,21 @@ function parseV2( value: Record, expectedWorkspaceId?: string, ): WorkspaceDocumentV2 { - keys(value, "workspace", [ - "version", - "schemaVersion", - "workspaceId", - "revision", - "updatedAt", - "lastMutationId", - "data", - "tombstones", - ]); + keys( + value, + "workspace", + [ + "version", + "schemaVersion", + "workspaceId", + "revision", + "updatedAt", + "lastMutationId", + "data", + "tombstones", + ], + ["resetRevision"], + ); if (value.version !== 2) invalid("version must be 2 for Schema V2"); if (value.schemaVersion !== 2) invalid("schemaVersion must be 2"); const workspaceId = string(value.workspaceId, "workspaceId"); @@ -832,12 +844,20 @@ function parseV2( ); } const revision = integer(value.revision, "revision", { minimum: 0 }); + const resetRevision = + value.resetRevision === undefined + ? undefined + : integer(value.resetRevision, "resetRevision", { minimum: 0 }); + if (resetRevision !== undefined && resetRevision > revision) { + invalid("resetRevision cannot exceed revision"); + } const data = parseWorkspaceData(value.data); return { version: 2, schemaVersion: 2, workspaceId, revision, + ...(resetRevision === undefined ? {} : { resetRevision }), updatedAt: timestamp(value.updatedAt, "updatedAt"), lastMutationId: value.lastMutationId === null @@ -1108,6 +1128,9 @@ export function serializeWorkspaceDocumentV2( schemaVersion: 2, workspaceId: parsed.workspaceId, revision: parsed.revision, + ...(parsed.resetRevision === undefined + ? {} + : { resetRevision: parsed.resetRevision }), updatedAt: parsed.updatedAt, lastMutationId: parsed.lastMutationId, data, @@ -1134,5 +1157,8 @@ export function getWorkspaceContentSignature( parsed.revision, data, ), + ...(getWorkspaceResetRevision(parsed) === 0 + ? {} + : { resetRevision: parsed.resetRevision }), }); } diff --git a/src/lib/workspace-mutation-queue.ts b/src/lib/workspace-mutation-queue.ts index 905b5db..5e5f52a 100644 --- a/src/lib/workspace-mutation-queue.ts +++ b/src/lib/workspace-mutation-queue.ts @@ -62,6 +62,7 @@ const MUTATION_KINDS = new Set([ "output.delete", "workspace.bootstrap.cleanup", "workspace.migrate", + "workspace.reset", "workspace.reconcile", ]); diff --git a/src/lib/workspace-mutation.test.ts b/src/lib/workspace-mutation.test.ts index 069597c..a028d77 100644 --- a/src/lib/workspace-mutation.test.ts +++ b/src/lib/workspace-mutation.test.ts @@ -211,6 +211,7 @@ describe("Workspace mutation parsing", () => { }, ], ["output.delete", { fileName: "aggregate.txt" }], + ["workspace.reset", {}], ["workspace.bootstrap.cleanup", {}], ["workspace.migrate", { sourceSha256: "a".repeat(64) }], ["workspace.reconcile", { baselineRevision: 0, data: data() }], @@ -352,6 +353,193 @@ describe("Workspace mutation parsing", () => { }); }); +describe("Workspace cloud reset", () => { + it("clears all live collections, preserves tombstones, and records a reset boundary", () => { + const previous = document(); + previous.tombstones.nodes.push({ + id: "previously-deleted", + deletedAt: T0, + deletedRevision: 1, + mutationId: "20000000-0000-4000-8000-000000000001", + }); + const reset = parseWorkspaceMutation(mutation("workspace.reset", {})); + const applied = applyWorkspaceMutation(previous, reset, context); + expect(applied.document.workspaceId).toBe(WORKSPACE_ID); + expect(applied.document.revision).toBe(2); + expect(applied.document.resetRevision).toBe(2); + expect(applied.document.lastMutationId).toBe(reset.mutationId); + for (const collection of Object.keys(previous.data) as Array< + keyof WorkspaceData + >) { + expect(applied.document.data[collection]).toEqual([]); + for (const item of previous.data[collection]) { + expect( + applied.document.tombstones[collection].find( + (tombstone) => tombstone.id === item.id, + ), + ).toEqual({ + id: item.id, + deletedAt: T1, + deletedRevision: 2, + mutationId: reset.mutationId, + }); + } + } + expect(applied.document.tombstones.nodes[0]).toEqual( + previous.tombstones.nodes[0], + ); + expect(applied.receipt).toEqual({ kind: "workspace.reset", deleted: true }); + }); + + it("deletes only outputs with current publication evidence", () => { + const previous = document(); + previous.data.publishTargets[0] = { + ...target(), + lastPublishedAt: T0, + lastPublishedUrl: + "https://gist.githubusercontent.com/owner/gist-1/raw/aggregate.txt", + }; + previous.data.publishTargets.push({ + ...target("unpublished-target"), + fileName: "manual.txt", + }); + previous.data.publishTargets.push({ + ...target("renamed-target"), + fileName: "renamed.txt", + lastPublishedAt: T0, + lastPublishedUrl: + "https://gist.githubusercontent.com/owner/gist-1/raw/historical.txt", + }); + previous.data.clientExports[0] = { + ...profile(), + lastPublishedAt: T0, + lastPublishedUrl: "https://example.com/client.json", + }; + const applied = applyWorkspaceMutation( + previous, + parseWorkspaceMutation(mutation("workspace.reset", {})), + context, + ); + expect(applied.files).toEqual({ + "aggregate.txt": null, + "client.json": null, + }); + }); + + it("rejects pre-reset intents even when their revision matches the latest document", () => { + const current = document({ revision: 3, resetRevision: 2 }); + for (const expectedResetRevision of [undefined, 0, 1]) { + expectCode( + () => + applyWorkspaceMutation( + current, + parseWorkspaceMutation( + mutation( + "node.upsert", + { operation: "replace", node: node("new-before-reset") }, + { + expectedRevision: 3, + ...(expectedResetRevision === undefined + ? {} + : { expectedResetRevision }), + }, + ), + ), + context, + ), + "revision_conflict", + ); + } + const applied = applyWorkspaceMutation( + current, + parseWorkspaceMutation( + mutation( + "node.upsert", + { operation: "replace", node: node("new-after-reset") }, + { expectedRevision: 3, expectedResetRevision: 2 }, + ), + ), + context, + ); + expect(applied.document.revision).toBe(4); + expect(applied.document.resetRevision).toBe(2); + }); + + it("restricts reset to browser requests with an empty payload", () => { + expectCode( + () => + parseWorkspaceMutation( + mutation("workspace.reset", {}, { source: "server-api" }), + ), + "invalid_mutation", + ); + expectCode( + () => + parseWorkspaceMutation( + mutation("workspace.reset", { deleteEverything: true }), + ), + "invalid_mutation", + ); + for (const expectedResetRevision of [-1, 1.5, 2, "0", null]) { + expectCode( + () => + parseWorkspaceMutation( + mutation("workspace.reset", {}, { expectedResetRevision }), + ), + "invalid_mutation", + ); + } + }); + + it("keeps deleted IDs fenced after a reset-aware retry", () => { + const reset = applyWorkspaceMutation( + document(), + parseWorkspaceMutation(mutation("workspace.reset", {})), + context, + ).document; + expectCode( + () => + applyWorkspaceMutation( + reset, + parseWorkspaceMutation( + mutation( + "node.upsert", + { operation: "replace", node: node() }, + { expectedRevision: 2, expectedResetRevision: 2 }, + ), + ), + context, + ), + "entity_deleted", + ); + expectCode( + () => + applyWorkspaceMutation( + reset, + parseWorkspaceMutation( + mutation( + "workspace.reconcile", + { baselineRevision: 2, data: data() }, + { expectedRevision: 2, expectedResetRevision: 2 }, + ), + ), + context, + ), + "entity_deleted", + ); + }); + + it("keeps the legacy mutation hash stable when the reset field is absent", async () => { + const parsed = parseWorkspaceMutation( + mutation("node.delete", { id: "node-1" }), + ); + expect(Object.hasOwn(parsed, "expectedResetRevision")).toBe(false); + expect(await getWorkspaceMutationSignature(parsed)).toBe( + "37bfc7fdd177e7dba26c7bb93d2217aafb61736f0a3a88a550052dd688d9b264", + ); + }); +}); + describe("Workspace mutation domain limits", () => { it("rejects oversized node, subscription, and external-key fields", () => { expectCode( diff --git a/src/lib/workspace-mutation.ts b/src/lib/workspace-mutation.ts index 0c384ec..bb3317b 100644 --- a/src/lib/workspace-mutation.ts +++ b/src/lib/workspace-mutation.ts @@ -17,6 +17,7 @@ import { makeUniqueResourceName, } from "$lib/resource-dedupe"; import { + getWorkspaceResetRevision, serializeWorkspaceDocumentV2, validateWorkspaceAggregate, validateWorkspaceClientExport, @@ -39,6 +40,7 @@ import { findWorkspaceOutputConflicts, getConflictingOutputOwners, getWorkspaceOutputOwners, + getWorkspaceResetOutputFileNames, isCurrentClientExportOutputPublished, isCurrentPublishTargetOutputPublished, } from "$lib/workspace-output"; @@ -61,6 +63,7 @@ type MutationBase = { mutationId: string; workspaceId: string; expectedRevision: number; + expectedResetRevision?: number; source: WorkspaceMutationSource; createdAt: string; kind: Kind; @@ -119,6 +122,7 @@ export type WorkspaceMutation = > | MutationBase<"output.delete", { fileName: string }> | MutationBase<"workspace.bootstrap.cleanup", Record> + | MutationBase<"workspace.reset", Record> | MutationBase<"workspace.migrate", { sourceSha256: string }> | MutationBase< "workspace.reconcile", @@ -514,21 +518,27 @@ const MUTATION_KINDS = new Set([ "client-export.publish", "output.delete", "workspace.bootstrap.cleanup", + "workspace.reset", "workspace.migrate", "workspace.reconcile", ]); function parseWorkspaceMutationShape(inputValue: unknown): WorkspaceMutation { const input = record(inputValue, "mutation"); - exactKeys(input, "mutation", [ - "mutationId", - "workspaceId", - "expectedRevision", - "source", - "createdAt", - "kind", - "payload", - ]); + exactKeys( + input, + "mutation", + [ + "mutationId", + "workspaceId", + "expectedRevision", + "source", + "createdAt", + "kind", + "payload", + ], + ["expectedResetRevision"], + ); const mutationId = documentValue(() => validateWorkspaceUuid(input.mutationId, "mutationId"), ); @@ -537,6 +547,16 @@ function parseWorkspaceMutationShape(inputValue: unknown): WorkspaceMutation { input.expectedRevision, "expectedRevision", ); + const expectedResetRevision = + input.expectedResetRevision === undefined + ? undefined + : safeRevision(input.expectedResetRevision, "expectedResetRevision"); + if ( + expectedResetRevision !== undefined && + expectedResetRevision > expectedRevision + ) { + invalid("expectedResetRevision cannot exceed expectedRevision"); + } const sourceValue = nonempty(input.source, "source"); if (sourceValue !== "browser" && sourceValue !== "server-api") { invalid(`source is unsupported: ${sourceValue}`); @@ -558,6 +578,7 @@ function parseWorkspaceMutationShape(inputValue: unknown): WorkspaceMutation { mutationId, workspaceId, expectedRevision, + ...(expectedResetRevision === undefined ? {} : { expectedResetRevision }), source, createdAt, }; @@ -695,7 +716,8 @@ function parseWorkspaceMutationShape(inputValue: unknown): WorkspaceMutation { invalid("payload.sourceSha256 must be a SHA-256 hash"); return { ...base, kind, payload: { sourceSha256 } }; } - case "workspace.bootstrap.cleanup": { + case "workspace.bootstrap.cleanup": + case "workspace.reset": { const payload = record(input.payload, "payload"); exactKeys(payload, "payload", []); return { ...base, kind, payload: {} }; @@ -1158,6 +1180,14 @@ export function applyWorkspaceMutation( `Expected revision ${mutation.expectedRevision}, found ${current.revision}`, ); } + if ( + (mutation.expectedResetRevision ?? 0) !== getWorkspaceResetRevision(current) + ) { + fail( + "revision_conflict", + "Workspace was reset after this change was prepared", + ); + } const nextRevision = current.revision + 1; let data = current.data; let tombstones = current.tombstones; @@ -1659,6 +1689,38 @@ export function applyWorkspaceMutation( receipt = { kind: mutation.kind, deleted: true }; break; } + case "workspace.reset": { + files = Object.fromEntries( + getWorkspaceResetOutputFileNames(data).map((fileName) => [ + fileName, + null, + ]), + ); + for (const collection of Object.keys(data) as EntityCollection[]) { + // Validated documents already exclude overlapping live and deleted IDs. + tombstones = { + ...tombstones, + [collection]: [ + ...tombstones[collection], + ...data[collection].map((item) => ({ + id: item.id, + deletedAt: committedAt, + deletedRevision: nextRevision, + mutationId: mutation.mutationId, + })), + ], + }; + } + data = { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }; + receipt = { kind: mutation.kind, deleted: true }; + break; + } case "workspace.reconcile": { const requested = mutation.payload.data; const resolved: WorkspaceData = { @@ -1763,7 +1825,9 @@ export function applyWorkspaceMutation( reconcileChangedValueLimits(current.data, data); assertEntityCountGrowth(current.data, data); const nextDocument = finalize( - current, + mutation.kind === "workspace.reset" + ? { ...current, resetRevision: nextRevision } + : current, mutation, data, tombstones, diff --git a/src/lib/workspace-output.ts b/src/lib/workspace-output.ts index 42b2e83..fa4abba 100644 --- a/src/lib/workspace-output.ts +++ b/src/lib/workspace-output.ts @@ -34,6 +34,21 @@ export function isCurrentClientExportOutputPublished( return profile.lastPublishedAt !== null; } +export function getWorkspaceResetOutputFileNames( + data: Pick, +): string[] { + return [ + ...new Set([ + ...data.publishTargets + .filter(isCurrentPublishTargetOutputPublished) + .map((target) => target.fileName), + ...data.clientExports + .filter(isCurrentClientExportOutputPublished) + .map((profile) => profile.fileName), + ]), + ].sort(); +} + export function getWorkspaceOutputOwners( data: Pick, fileNameValue: string, diff --git a/src/lib/workspace-persistence.test.ts b/src/lib/workspace-persistence.test.ts index 2845cd6..43a1cbe 100644 --- a/src/lib/workspace-persistence.test.ts +++ b/src/lib/workspace-persistence.test.ts @@ -42,6 +42,94 @@ const MUTATION_ID_2 = "b0000000-0000-4000-8000-000000000002"; const MUTATION_ID_3 = "b0000000-0000-4000-8000-000000000003"; const TOKEN_CANARY = "credential-canary-do-not-persist"; +describe("cloud reset transaction", () => { + function expectation(record: WorkspacePersistenceRecord) { + return { + snapshot: record.snapshot, + binding: record.binding, + queue: record.workspaces[WORKSPACE_ID] ?? null, + }; + } + function resetDraft() { + return mutationDraft({ + mutationId: MUTATION_ID_2, + workspaceId: WORKSPACE_ID, + expectedRevision: 0, + source: "browser", + createdAt: NOW_2, + kind: "workspace.reset", + payload: {}, + }); + } + it("requires a complete confirmed expectation before journaling reset", async () => { + const persistence = automaticPersistence(); + const before = await persistence.read(); + expect( + (await captureError( + persistence.commitExplicitAction({ + binding: binding(), + mutation: resetDraft(), + }), + )) instanceof WorkspaceConcurrentUpdateError, + ).toBe(true); + expect(await persistence.read()).toEqual(before); + }); + it("rejects an active lease even when the confirmed business state is unchanged", async () => { + const persistence = automaticPersistence(() => 10); + const before = await persistence.read(); + await persistence.acquireLease({ + name: workspaceDispatcherLeaseName(WORKSPACE_ID), + ownerId: "peer", + now: 10, + ttlMs: 100, + }); + const leased = await persistence.read(); + expect( + (await captureError( + persistence.commitExplicitAction({ + binding: binding(), + mutation: resetDraft(), + expected: expectation(before), + }), + )) instanceof WorkspaceConcurrentUpdateError, + ).toBe(true); + expect(await persistence.read()).toEqual(leased); + }); + it("rejects a queue append made after confirmation without discarding it", async () => { + const persistence = automaticPersistence(); + const before = await persistence.read(); + await persistence.commitExplicitAction({ + binding: binding(), + mutation: mutationDraft(reconcileMutation()), + }); + const queued = await persistence.read(); + expect( + (await captureError( + persistence.commitExplicitAction({ + binding: binding(), + mutation: resetDraft(), + expected: expectation(before), + }), + )) instanceof WorkspaceConcurrentUpdateError, + ).toBe(true); + expect(await persistence.read()).toEqual(queued); + }); + it("journals the original reset atomically while keeping the committed baseline", async () => { + const persistence = automaticPersistence(); + const before = await persistence.read(); + const committed = await persistence.commitExplicitAction({ + binding: binding(), + mutation: resetDraft(), + expected: expectation(before), + }); + const record = await persistence.read(); + expect(committed.kind).toBe("workspace.reset"); + expect(record.binding).toEqual(before.binding); + expect(record.snapshot?.activeGistId).toBe(GIST_ID); + expect(record.workspaces[WORKSPACE_ID]?.mutations).toEqual([committed]); + }); +}); + async function captureError( promise: Promise, ): Promise { diff --git a/src/lib/workspace-persistence.ts b/src/lib/workspace-persistence.ts index 21ec5d7..59d88a8 100644 --- a/src/lib/workspace-persistence.ts +++ b/src/lib/workspace-persistence.ts @@ -236,6 +236,7 @@ export interface BrowserWorkspacePersistence { binding: WorkspaceV2LocalState; mutation: WorkspaceMutationDraft; snapshot?: AppState; + expected?: WorkspaceResetExpectation; }): Promise; commitLocalAction(input: { snapshot: AppState; @@ -574,6 +575,7 @@ const MUTATION_KINDS = new Set([ "output.delete", "workspace.bootstrap.cleanup", "workspace.migrate", + "workspace.reset", "workspace.reconcile", ]); @@ -1569,6 +1571,7 @@ export class TransactionalWorkspacePersistence binding: WorkspaceV2LocalState; mutation: WorkspaceMutationDraft; snapshot?: AppState; + expected?: WorkspaceResetExpectation; }): Promise { const binding = validatePersistenceBinding(input.binding); const snapshot = @@ -1591,6 +1594,29 @@ export class TransactionalWorkspacePersistence if (!draft.binding || !workspaceBindingsEqual(draft.binding, binding)) { throw new WorkspaceConcurrentUpdateError(); } + const activeQueue = draft.workspaces[binding.workspaceId] ?? null; + if ( + input.expected && + (!persistenceValuesEqual(draft.snapshot, input.expected.snapshot) || + !workspaceBindingsEqual(draft.binding, input.expected.binding) || + !persistenceValuesEqual(activeQueue, input.expected.queue)) + ) { + throw new WorkspaceConcurrentUpdateError(); + } + if (input.mutation.kind === "workspace.reset") { + const lease = + draft.leases[workspaceDispatcherLeaseName(binding.workspaceId)]; + if ( + !input.expected || + binding.syncMode !== "automatic" || + (activeQueue?.mutations.length ?? 0) > 0 || + activeQueue?.delivery.blocked || + (activeQueue?.delivery.deadLetters.length ?? 0) > 0 || + (lease && lease.expiresAt > this.nowMs()) + ) { + throw new WorkspaceConcurrentUpdateError(); + } + } const queue = draft.workspaces[binding.workspaceId] ?? createQueue(binding.workspaceId); @@ -2171,6 +2197,18 @@ export class TransactionalWorkspacePersistence ) { throw new WorkspaceConcurrentUpdateError(); } + const intentBaseline = + draft.binding?.conflictBaseline ?? draft.binding?.baseline; + if ( + mutations.length > 0 && + intentBaseline && + (intentBaseline.resetRevision ?? 0) !== + (binding.baseline?.resetRevision ?? 0) + ) { + throw new WorkspaceConcurrentUpdateError( + "Cloud Workspace was reset. Reload from Cloud before retrying this action.", + ); + } const previousWorkspaceId = draft.binding?.workspaceId; draft.snapshot = snapshot; checkpoint("after-snapshot"); diff --git a/src/lib/workspace-settings-controller.test.ts b/src/lib/workspace-settings-controller.test.ts index 2e9ba7e..531f05e 100644 --- a/src/lib/workspace-settings-controller.test.ts +++ b/src/lib/workspace-settings-controller.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "bun:test"; -import type { AppState, NodeItem } from "$lib/models"; +import type { AppState, GistMeta, NodeItem } from "$lib/models"; +import type { BrowserWorkspaceSnapshot } from "$lib/workspace-browser-session-v2"; import { createDefaultWorkspaceState } from "$lib/workspace-data"; import type { WorkspaceDocumentV2 } from "$lib/workspace-document"; import { parseWorkspaceMutation } from "$lib/workspace-mutation"; @@ -142,6 +143,278 @@ async function expectRejection( expect(failure instanceof Error ? failure.message : "").toBe(message); } +describe("Cloud Workspace reset", () => { + function setupCloudReset(remote = document(3, [node("cloud-node")])) { + const record = createEmptyWorkspacePersistenceRecord(); + record.snapshot = state(document(2)); + record.binding = createWorkspaceV2LocalState(GIST_ID, { + baseline: document(2), + syncMode: "automatic", + }); + const persistence = new InMemoryWorkspacePersistence(record); + let current = record.snapshot; + let reads = 0; + const gist: GistMeta = { + id: GIST_ID, + description: "SubMan-Data", + updatedAt: NOW, + url: `https://gist.github.com/${GIST_ID}`, + files: ["subman.json", "subman.v1.backup.json", "notes.txt"].map( + (filename) => ({ filename, language: null, size: 10 }), + ), + }; + let snapshot: BrowserWorkspaceSnapshot = { + origin: "v2", + document: remote, + state: state(remote), + }; + const requests: unknown[] = []; + const controller = createWorkspaceSettingsController({ + persistence, + getState: () => current, + setState: (next) => { + current = next; + }, + isCloudReady: () => true, + readCloudResetSnapshot: async () => { + reads += 1; + return { gist, snapshot }; + }, + fetchImpl: (async (_input, init) => { + const mutation = JSON.parse(String(init?.body)); + requests.push(mutation); + const committed = document(mutation.expectedRevision + 1); + committed.resetRevision = committed.revision; + committed.lastMutationId = mutation.mutationId; + return Response.json({ + status: "committed", + mutationId: mutation.mutationId, + workspaceId: WORKSPACE_ID, + committedRevision: committed.revision, + committedAt: NOW, + receipt: { kind: "workspace.reset" }, + document: committed, + }); + }) as typeof fetch, + dispatchSyncEvent: () => true, + }); + return { + controller, + persistence, + gist, + requests, + reads: () => reads, + setSnapshot: (value: BrowserWorkspaceSnapshot) => { + snapshot = value; + }, + }; + } + + it("previews the latest original cloud revision and retains external files and the V1 backup", async () => { + const setup = setupCloudReset(); + const preview = await setup.controller.prepareCloudReset("test-token"); + expect(preview.gistId).toBe(GIST_ID); + expect(preview.revision).toBe(3); + expect(preview.resetRevision).toBe(0); + expect(preview.counts.nodes).toBe(1); + expect(preview.deletedFiles).toEqual([]); + expect(preview.retainedFiles).toEqual([ + "notes.txt", + "subman.v1.backup.json", + ]); + expect(preview.expected.binding?.revision).toBe(3); + expect(setup.requests).toEqual([]); + }); + + it("previews published filenames from the latest document even when the earlier file inventory omits them", async () => { + const remote = document(3); + remote.data.aggregates = [ + { + id: "new-rule", + name: "New rule", + nodeIds: [], + subscriptionIds: [], + excludeTagIds: [], + renameMap: {}, + allowedTypes: [], + updatedAt: NOW, + }, + ]; + remote.data.publishTargets = [ + { + id: "new-target", + name: "New target", + ruleId: "new-rule", + fileName: "newly-published.txt", + description: "", + isPublic: false, + lastPublishedAt: NOW, + lastPublishedUrl: + "https://gist.githubusercontent.com/user/gist/raw/newly-published.txt", + lastPublishTransitionAt: null, + lastPublishTransitionFromFileName: null, + lastPublishTransitionToFileName: null, + lastPublishTransitionOutcome: null, + updatedAt: NOW, + }, + ]; + const setup = setupCloudReset(remote); + const preview = await setup.controller.prepareCloudReset("test-token"); + expect(preview.deletedFiles).toEqual(["newly-published.txt"]); + }); + + it("lists a stale bootstrap marker for cleanup instead of promising to retain it", async () => { + const setup = setupCloudReset(); + setup.gist.files.push({ + filename: "subman.bootstrap.json", + language: "JSON", + size: 10, + }); + const preview = await setup.controller.prepareCloudReset("test-token"); + expect(preview.deletedFiles).toEqual(["subman.bootstrap.json"]); + expect(preview.retainedFiles).toEqual([ + "notes.txt", + "subman.v1.backup.json", + ]); + }); + + it("requires an idle local queue before reading the cloud reset preview", async () => { + const persistence = queuedPersistence(); + let reads = 0; + const setup = createWorkspaceSettingsController({ + persistence, + getState: () => state(), + setState: () => undefined, + isCloudReady: () => true, + readCloudResetSnapshot: async () => { + reads += 1; + throw new Error("Must not read cloud"); + }, + }); + await expectRejection( + setup.prepareCloudReset("test-token"), + "Pending cloud changes must finish syncing before refreshing cloud data.", + ); + expect(reads).toBe(0); + }); + + it("rejects V1 reset previews without migrating or submitting a mutation", async () => { + const setup = setupCloudReset(); + const before = await setup.persistence.read(); + setup.setSnapshot({ origin: "v1", document: document(3), state: state() }); + await expectRejection( + setup.controller.prepareCloudReset("test-token"), + "Upgrade this Workspace to continue.", + ); + expect(await setup.persistence.read()).toEqual(before); + expect(setup.requests).toEqual([]); + }); + + it("rejects cloud reset while another dispatcher owns an active lease", async () => { + const setup = setupCloudReset(); + await setup.persistence.acquireLease({ + name: workspaceDispatcherLeaseName(WORKSPACE_ID), + ownerId: "peer", + now: Date.now(), + ttlMs: 60_000, + }); + await expectRejection( + setup.controller.prepareCloudReset("test-token"), + "Cloud delivery is active. Wait for it to finish before resetting cloud data.", + ); + expect(setup.reads()).toBe(0); + }); + + it("does not reprepare a confirmed preview after a concurrent local change", async () => { + const setup = setupCloudReset(); + const preview = await setup.controller.prepareCloudReset("test-token"); + if (!preview.expected.binding) throw new Error("Expected bound preview"); + await setup.persistence.commitExplicitAction({ + binding: preview.expected.binding, + mutation: { + mutationId: MUTATION_ID, + workspaceId: WORKSPACE_ID, + source: "browser", + createdAt: NOW, + kind: "node.delete", + payload: { id: "cloud-node" }, + }, + }); + const before = await setup.persistence.read(); + const result = await setup.controller.submitCloudReset( + preview, + "test-token", + ); + expect(result.status).toBe("rejected-before-durable-commit"); + expect(setup.reads()).toBe(1); + expect(setup.requests).toEqual([]); + expect(await setup.persistence.read()).toEqual(before); + }); + + it("resets through one fixed revisioned browser mutation and keeps the Gist binding", async () => { + const setup = setupCloudReset(); + const preview = await setup.controller.prepareCloudReset("test-token"); + const result = await setup.controller.submitCloudReset( + preview, + "test-token", + ); + expect(result.status).toBe("remote-committed"); + expect(setup.requests).toHaveLength(1); + const submitted = setup.requests[0] as Record; + expect(submitted.kind).toBe("workspace.reset"); + expect(submitted.expectedRevision).toBe(3); + expect(submitted.expectedResetRevision).toBe(0); + expect(submitted.payload).toEqual({}); + const stored = await setup.persistence.read(); + expect(stored.binding?.gistId).toBe(GIST_ID); + expect(stored.snapshot?.activeGistId).toBe(GIST_ID); + expect(stored.snapshot?.nodes).toEqual([]); + expect(stored.binding?.baseline?.resetRevision).toBe(4); + }); + + for (const action of [ + "bind-only", + "reconcile", + "local", + "remote", + "merge", + ] as const) { + it(`rejects ${action} recovery captured before a cloud reset`, async () => { + const remote = document(4); + remote.resetRevision = 4; + const setup = setupCloudReset(remote); + await setup.controller.prepareCloudReset("test-token"); + const stale = document(3, [node("old-node")]); + const conflict = setup.controller.createConflict(stale, GIST_ID); + const before = await setup.persistence.read(); + let operation: Promise; + if (action === "bind-only") { + operation = setup.controller.bindOnly(conflict); + } else if (action === "reconcile") { + operation = setup.controller.reconcile({ + token: "test-token", + gistId: GIST_ID, + baseline: stale, + resolvedState: state(stale), + syncMode: "automatic", + }); + } else { + operation = setup.controller.resolveConflict({ + token: "test-token", + conflict, + action, + }); + } + await expectRejection( + operation, + "Cloud Workspace was reset. Reload from Cloud before retrying this action.", + ); + expect(await setup.persistence.read()).toEqual(before); + expect(setup.requests).toEqual([]); + }); + } +}); + describe("Workspace settings controller", () => { it("returns a committed reset even when state hydration and sync presentation fail", async () => { const persistence = queuedPersistence(); diff --git a/src/lib/workspace-settings-controller.ts b/src/lib/workspace-settings-controller.ts index 2103083..46553a1 100644 --- a/src/lib/workspace-settings-controller.ts +++ b/src/lib/workspace-settings-controller.ts @@ -1,14 +1,22 @@ -import type { AppState } from "$lib/models"; +import { get } from "svelte/store"; +import { getGist } from "$lib/gist"; +import type { AppState, GistMeta } from "$lib/models"; import { getSyncStateSignature } from "$lib/serialization"; import { type BrowserWorkspaceSnapshot, migrateBrowserWorkspace, persistBrowserWorkspaceSnapshot, + readBrowserWorkspaceSnapshot, reconcileBrowserWorkspace, + submitBrowserWorkspaceMutation, } from "$lib/workspace-browser-session-v2"; +import { workspaceCloudStatus } from "$lib/workspace-cloud-status"; import { getWorkspaceBusinessData, WORKSPACE_FILE } from "$lib/workspace-data"; import { exportWorkspaceDiagnosticsFromPersistence } from "$lib/workspace-diagnostics"; -import type { WorkspaceDocumentV2 } from "$lib/workspace-document"; +import { + WORKSPACE_BOOTSTRAP_FILE_NAME, + type WorkspaceDocumentV2, +} from "$lib/workspace-document"; import { broadcastWorkspaceEvent } from "$lib/workspace-events"; import { requireWorkspaceIdentity, @@ -20,7 +28,11 @@ import { type WorkspaceMergeNotice, } from "$lib/workspace-merge"; import { parseWorkspaceMutation } from "$lib/workspace-mutation"; -import type { WorkspaceOperationResult } from "$lib/workspace-operation-result"; +import { + rejectedWorkspaceOperation, + type WorkspaceOperationResult, +} from "$lib/workspace-operation-result"; +import { getWorkspaceResetOutputFileNames } from "$lib/workspace-output"; import { type BrowserWorkspacePersistence, inspectWorkspacePersistenceRecord, @@ -29,6 +41,7 @@ import { type WorkspacePersistenceRecord, type WorkspaceQueueInspection, type WorkspaceResetExpectation, + workspaceDispatcherLeaseName, } from "$lib/workspace-persistence"; import { getBrowserWorkspacePersistence, @@ -63,6 +76,23 @@ export type WorkspaceSettingsView = { inspection: WorkspaceQueueInspection; }; +export type WorkspaceCloudResetPreview = { + gistId: string; + revision: number; + resetRevision: number; + counts: Record< + | "nodes" + | "subscriptions" + | "aggregates" + | "publishTargets" + | "clientExports", + number + >; + deletedFiles: string[]; + retainedFiles: string[]; + expected: WorkspaceResetExpectation; +}; + export type WorkspaceManualPullDecision = | { status: "already-synced" } | { status: "confirm-pull" }; @@ -83,6 +113,12 @@ type ControllerDependencies = { persistence?: BrowserWorkspacePersistence; fetchImpl?: typeof fetch; dispatchSyncEvent?: typeof dispatchWorkspaceSyncEvent; + isCloudReady?: () => boolean; + readCloudResetSnapshot?: ( + token: string, + gistId: string, + current: AppState, + ) => Promise<{ gist: GistMeta; snapshot: BrowserWorkspaceSnapshot }>; }; type ConflictResolution = @@ -155,6 +191,164 @@ export function createWorkspaceSettingsController( return resetExpectation(await readRecord()); } + function requireSameResetGeneration( + record: WorkspacePersistenceRecord, + baseline: WorkspaceDocumentV2, + ): void { + if ( + record.binding?.baseline && + (record.binding.baseline.resetRevision ?? 0) !== + (baseline.resetRevision ?? 0) + ) { + throw new WorkspaceConcurrentUpdateError( + "Cloud Workspace was reset. Reload from Cloud before retrying this action.", + ); + } + } + + function requireCloudResetReady( + record: WorkspacePersistenceRecord, + token: string, + ): asserts record is WorkspacePersistenceRecord & { + binding: WorkspaceV2LocalState; + snapshot: AppState; + } { + if (!token.trim()) { + throw new Error("Connect GitHub before changing cloud data."); + } + if ( + !( + dependencies.isCloudReady?.() ?? + get(workspaceCloudStatus).phase === "ready" + ) || + !record.binding?.baseline || + record.binding.revision === null || + record.binding.syncMode !== "automatic" || + !record.snapshot + ) { + throw new Error( + "Load the latest cloud data before resetting cloud data.", + ); + } + requireWorkspaceIdentity(record.snapshot, record.binding); + requireIdleCloudQueue(record, record.binding.gistId); + const lease = + record.leases[workspaceDispatcherLeaseName(record.binding.workspaceId)]; + if (lease && lease.expiresAt > Date.now()) { + throw new Error( + "Cloud delivery is active. Wait for it to finish before resetting cloud data.", + ); + } + } + + async function prepareCloudReset( + token: string, + ): Promise { + const current = await refresh(); + requireCloudResetReady(current.record, token); + const gistId = current.record.binding.gistId; + const currentSnapshot = current.record.snapshot; + const expected = resetExpectation(current.record); + const { gist, snapshot } = dependencies.readCloudResetSnapshot + ? await dependencies.readCloudResetSnapshot( + token, + gistId, + currentSnapshot, + ) + : await (async () => { + const gist = await getGist(token, gistId); + return { + gist, + snapshot: await readBrowserWorkspaceSnapshot( + token, + gist, + currentSnapshot, + ), + }; + })(); + if (snapshot.origin !== "v2") { + throw new Error("Upgrade this Workspace to continue."); + } + if ( + gist.id !== gistId || + snapshot.document.workspaceId !== `gist:${gistId}` + ) { + throw new WorkspaceBindingLockedError(); + } + const observed = await refresh(); + requireExpectedRecord(observed.record, expected); + requireCloudResetReady(observed.record, token); + await refreshCloud(snapshot, gistId, expected); + const prepared = await refresh(); + requireCloudResetReady(prepared.record, token); + if ( + prepared.record.binding.revision !== snapshot.document.revision || + (prepared.record.binding.baseline?.resetRevision ?? 0) !== + (snapshot.document.resetRevision ?? 0) + ) { + throw new WorkspaceConcurrentUpdateError(); + } + const managedNames = new Set( + getWorkspaceResetOutputFileNames(snapshot.document.data), + ); + const files = gist.files + .map((file) => file.filename) + .filter((name) => name !== WORKSPACE_FILE) + .sort(); + if (files.includes(WORKSPACE_BOOTSTRAP_FILE_NAME)) { + managedNames.add(WORKSPACE_BOOTSTRAP_FILE_NAME); + } + return { + gistId, + revision: snapshot.document.revision, + resetRevision: snapshot.document.resetRevision ?? 0, + counts: { + nodes: snapshot.document.data.nodes.length, + subscriptions: snapshot.document.data.subscriptions.length, + aggregates: snapshot.document.data.aggregates.length, + publishTargets: snapshot.document.data.publishTargets.length, + clientExports: snapshot.document.data.clientExports.length, + }, + deletedFiles: [...managedNames].sort(), + retainedFiles: files.filter((name) => !managedNames.has(name)), + expected: resetExpectation(prepared.record), + }; + } + + async function submitCloudReset( + preview: WorkspaceCloudResetPreview, + token: string, + ): Promise { + try { + const current = await refresh(); + requireExpectedRecord(current.record, preview.expected); + requireCloudResetReady(current.record, token); + if ( + current.record.binding.gistId !== preview.gistId || + current.record.binding.revision !== preview.revision || + (current.record.binding.baseline?.resetRevision ?? 0) !== + preview.resetRevision + ) { + throw new WorkspaceConcurrentUpdateError(); + } + const operation = await submitBrowserWorkspaceMutation( + { + token, + kind: "workspace.reset", + payload: {}, + expected: preview.expected, + expectedRevision: preview.revision, + expectedResetRevision: preview.resetRevision, + }, + sessionDependencies(), + ); + await refresh().catch(() => undefined); + return operation; + } catch (error) { + return rejectedWorkspaceOperation(error); + } + } + async function resetDevice( expected: WorkspaceResetExpectation, ): Promise { @@ -325,6 +519,7 @@ export function createWorkspaceSettingsController( syncMode: "paused-conflict", }); const current = await requireBoundWorkspace(input.gistId); + requireSameResetGeneration(current.record, input.document); const persistedQueue = current.record.workspaces[paused.workspaceId]; if ( (persistedQueue?.delivery.blocked && @@ -342,6 +537,7 @@ export function createWorkspaceSettingsController( mutationId: crypto.randomUUID(), workspaceId: paused.workspaceId, expectedRevision: input.document.revision, + expectedResetRevision: input.document.resetRevision ?? 0, source: "browser", createdAt, kind: "workspace.reconcile", @@ -484,7 +680,8 @@ export function createWorkspaceSettingsController( replacePending?: boolean; expected?: WorkspaceResetExpectation; }): Promise { - await requireBoundWorkspace(input.gistId); + const current = await requireBoundWorkspace(input.gistId); + requireSameResetGeneration(current.record, input.baseline); const result = await reconcileBrowserWorkspace( input, sessionDependencies(), @@ -559,6 +756,7 @@ export function createWorkspaceSettingsController( async function bindOnly(conflict: WorkspaceSettingsConflict): Promise { const current = await requireBoundWorkspace(conflict.gistId); + requireSameResetGeneration(current.record, conflict.remoteDocument); const nextBinding = createWorkspaceV2LocalState(conflict.gistId, { baseline: conflict.remoteDocument, syncMode: "manual", @@ -586,6 +784,7 @@ export function createWorkspaceSettingsController( mutationId: crypto.randomUUID(), workspaceId: nextBinding.workspaceId, expectedRevision: conflict.remoteDocument.revision, + expectedResetRevision: conflict.remoteDocument.resetRevision ?? 0, source: "browser", createdAt, kind: "workspace.reconcile", @@ -630,7 +829,8 @@ export function createWorkspaceSettingsController( baselineMode?: "conflict" | "current"; syncMode?: "automatic" | "manual"; }): Promise { - await requireBoundWorkspace(input.conflict.gistId); + const current = await requireBoundWorkspace(input.conflict.gistId); + requireSameResetGeneration(current.record, input.conflict.remoteDocument); if (input.action === "remote") { await persistSnapshot( { @@ -853,6 +1053,8 @@ export function createWorkspaceSettingsController( initialize, prepareDeviceReset, resetDevice, + prepareCloudReset, + submitCloudReset, refresh, currentView, binding, diff --git a/src/routes/auth/+page.svelte b/src/routes/auth/+page.svelte index cfb3375..b172f8f 100644 --- a/src/routes/auth/+page.svelte +++ b/src/routes/auth/+page.svelte @@ -1,5 +1,6 @@