diff --git a/apps/desktop/e2e/code-review-diff.spec.ts b/apps/desktop/e2e/code-review-diff.spec.ts index cde9c9d5..ef654244 100644 --- a/apps/desktop/e2e/code-review-diff.spec.ts +++ b/apps/desktop/e2e/code-review-diff.spec.ts @@ -105,6 +105,33 @@ test("Viewed marks a file on this Mac for one revision, folds it, survives a rel expect(await app.evaluate(() => (globalThis as any).__diff.local)).toEqual([]); }); +test("Viewed keeps multiple session marks when storage writes fail", async () => { + await open(); + await page.evaluate(() => { + const original = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + if (key === "modex.codeReview.viewed") throw new DOMException("Quota exceeded", "QuotaExceededError"); + return original.call(this, key, value); + }; + }); + const marks = page.getByRole("checkbox", { name: /^Viewed / }); + await expect(marks).toHaveCount(4); + const asked = (await log()).length; + await marks.nth(0).check(); + await marks.nth(1).check(); + await expect(marks.nth(0)).toBeChecked(); + await expect(marks.nth(1)).toBeChecked(); + await expect(tid(page, "cr-viewed-count")).toHaveText("2 of 4 viewed"); + await marks.nth(0).uncheck(); + await marks.nth(2).check(); + await expect(marks.nth(0)).not.toBeChecked(); + await expect(marks.nth(1)).toBeChecked(); + await expect(marks.nth(2)).toBeChecked(); + await expect(tid(page, "cr-viewed-count")).toHaveText("2 of 4 viewed"); + expect((await log()).length).toBe(asked); + expect(await app.evaluate(() => (globalThis as any).__diff.local)).toEqual([]); +}); + test("keyboard: F6 moves between the areas and [ ] between files, and typing a bracket in the filter types it (F6)", async () => { await open(); await expect(tid(page, "cr-file-section")).toHaveCount(4); diff --git a/apps/desktop/src/renderer/code-review/viewed.ts b/apps/desktop/src/renderer/code-review/viewed.ts index 7b88e688..23ad1d96 100644 --- a/apps/desktop/src/renderer/code-review/viewed.ts +++ b/apps/desktop/src/renderer/code-review/viewed.ts @@ -10,12 +10,16 @@ const PRS = 200, PATHS = 3000; type Storage = { getItem(key: string): string | null; setItem(key: string, value: string): void }; interface Entry { baseSha: string; headSha: string; paths: string[] } +// Only failed writes need a session fallback. Successful writes resume ordinary storage reads. +const pending = new WeakMap>(); const ACCOUNT = /^[1-9][0-9]{0,19}$/; const SHA = /^[0-9a-f]{40}$/; const id = (key: PrKey) => `${key.repoId}#${key.number}`; function read(storage: Storage): Record { + const unsaved = pending.get(storage); + if (unsaved) return unsaved; try { const value: unknown = JSON.parse(storage.getItem(VIEWED_KEY) ?? "null"); return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; @@ -51,8 +55,12 @@ export function setViewed(storage: Storage, key: PrKey, revision: PrRevision, pa // Newest last; the oldest pull requests' marks go first when the list is full. const rest = Object.entries(mine).filter(([other]) => other !== id(key)).slice(-(PRS - 1)); const next = paths.length ? [...rest, [id(key), { baseSha: revision.baseSha, headSha: revision.headSha, paths } satisfies Entry]] : rest; + const document = { ...read(storage), [key.account]: Object.fromEntries(next) }; try { - storage.setItem(VIEWED_KEY, JSON.stringify({ ...read(storage), [key.account]: Object.fromEntries(next) })); - } catch { /* A full or blocked store keeps the mark for this session only. */ } + storage.setItem(VIEWED_KEY, JSON.stringify(document)); + pending.delete(storage); + } catch { + pending.set(storage, document); + } return paths; } diff --git a/apps/desktop/test/code-review-workspace.test.ts b/apps/desktop/test/code-review-workspace.test.ts index 9bd9ae2e..dcd211c1 100644 --- a/apps/desktop/test/code-review-workspace.test.ts +++ b/apps/desktop/test/code-review-workspace.test.ts @@ -272,6 +272,66 @@ test("viewed marks are local, per account and belong to one revision (C65)", () assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 1), at("b")), []); }); +for (const denyReads of [false, true]) { + test(`viewed marks survive successive failed writes${denyReads ? " and denied reads" : ""}`, () => { + const storage = { + getItem: () => { if (denyReads) throw new Error("blocked"); return null; }, + setItem: () => { throw new Error("quota exceeded"); }, + }; + const pr = key(ACCOUNT_A, LENDING, 73); + const revision = { baseRef: "main", baseSha: "a".repeat(40), headSha: "b".repeat(40) }; + assert.deepEqual(setViewed(storage, pr, revision, "a.ts", true), ["a.ts"]); + assert.deepEqual(setViewed(storage, pr, revision, "b.ts", true), ["a.ts", "b.ts"]); + assert.deepEqual(setViewed(storage, pr, revision, "a.ts", false), ["b.ts"]); + assert.deepEqual(setViewed(storage, pr, revision, "c.ts", true), ["b.ts", "c.ts"]); + assert.deepEqual(loadViewed(storage, pr, revision), ["b.ts", "c.ts"]); + assert.deepEqual(loadViewed({ ...storage }, pr, revision), [], "another storage object has no unsaved session"); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_B, LENDING, 73), revision), []); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, FIELD_GUIDE, 73), revision), []); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 74), revision), []); + assert.deepEqual(loadViewed(storage, pr, { ...revision, baseSha: "c".repeat(40) }), []); + assert.deepEqual(setViewed(storage, pr, { ...revision, headSha: "d".repeat(40) }, "d.ts", true), ["d.ts"]); + assert.deepEqual(loadViewed(storage, pr, revision), [], "a new revision replaces pending old marks"); + }); +} + +test("viewed unmarks do not resurrect stale storage and pending changes persist when writes recover", () => { + const pr = key(ACCOUNT_A, LENDING, 73); + const revision = { baseRef: "main", baseSha: "a".repeat(40), headSha: "b".repeat(40) }; + const document = (paths: string[]) => JSON.stringify({ [pr.account]: { [`${pr.repoId}#73`]: { ...revision, paths } } }); + let saved = document(["a.ts", "b.ts"]), blocked = true; + const storage = { getItem: () => saved, setItem: (_key: string, value: string) => { if (blocked) throw new Error("full"); saved = value; } }; + assert.deepEqual(setViewed(storage, pr, revision, "a.ts", false), ["b.ts"]); + assert.deepEqual(setViewed(storage, pr, revision, "c.ts", true), ["b.ts", "c.ts"]); + assert.deepEqual(setViewed(storage, pr, revision, "b.ts", false), ["c.ts"]); + blocked = false; + assert.deepEqual(setViewed(storage, pr, revision, "d.ts", true), ["c.ts", "d.ts"]); + assert.deepEqual(loadViewed({ ...storage }, pr, revision), ["c.ts", "d.ts"], "a fresh reader sees successfully persisted pending changes"); + saved = document(["external.ts"]); + assert.deepEqual(loadViewed(storage, pr, revision), ["external.ts"], "successful writes release fallback and ordinary external reads still work"); +}); + +test("failed Viewed writes preserve account separation and bounded eviction", () => { + const storage = { getItem: () => null, setItem: () => { throw new Error("blocked"); } }; + const revision = { baseRef: "main", baseSha: "a".repeat(40), headSha: "b".repeat(40) }; + const pr = key(ACCOUNT_A, LENDING, 73), other = key(ACCOUNT_B, LENDING, 73); + setViewed(storage, pr, revision, "mine.ts", true); + setViewed(storage, other, revision, "theirs.ts", true); + assert.deepEqual(loadViewed(storage, pr, revision), ["mine.ts"]); + assert.deepEqual(loadViewed(storage, other, revision), ["theirs.ts"]); + setViewed(storage, pr, revision, "mine.ts", false); + assert.deepEqual(loadViewed(storage, pr, revision), [], "failed removal of the final mark remains empty"); + assert.deepEqual(loadViewed(storage, other, revision), ["theirs.ts"]); + for (let n = 1; n <= 201; n++) setViewed(storage, key(ACCOUNT_A, LENDING, n), revision, "f.ts", true); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 1), revision), []); + assert.deepEqual(loadViewed(storage, key(ACCOUNT_A, LENDING, 2), revision), ["f.ts"]); + for (let n = 0; n <= 3000; n++) setViewed(storage, pr, revision, `file-${n}.ts`, true); + const paths = loadViewed(storage, pr, revision); + assert.equal(paths.length, 3000); + assert.equal(paths.includes("file-0.ts"), false); + assert.equal(paths.at(-1), "file-3000.ts"); +}); + test("the destination defaults on, keeps an explicit old off, and the saved choice wins over the old switch", () => { const storage = (value: string | null, saved?: object) => ({ getItem: (k: string) => k === LEGACY_CODE_REVIEW_SWITCH ? value : k === LAYOUT_KEY && saved ? JSON.stringify(saved) : null, setItem: () => {} }); assert.equal(loadLayout(storage(null)).codeReview, false); diff --git a/docs/reviews/2026-11-12-viewed-storage-recovery.md b/docs/reviews/2026-11-12-viewed-storage-recovery.md new file mode 100644 index 00000000..c86f9798 --- /dev/null +++ b/docs/reviews/2026-11-12-viewed-storage-recovery.md @@ -0,0 +1,17 @@ +# Viewed storage recovery + +This repairs the [reproduced #506 follow-up](https://github.com/TypeSafeAI/modex/pull/506#discussion_r4548813336) on base `e6e644ea25cd5f428b8699e0b1e9cfbaa022e49d`: when localStorage rejects writes, marking B erased the earlier session mark A, and a later toggle could resurrect a file just unmarked from persisted data. The original source always reconstructed the next state from stale storage. Existing C65 Viewed behavior is local, account/repository/PR/revision-bound and performs no GitHub mutation. + +A WeakMap now retains only failed writes per storage object. Later toggles and helper reads use the pending document; the next successful write persists accumulated changes and removes the fallback. Normal successful storage reads continue observing external updates. A fresh storage object or renderer restart has no access to unpersisted marks. Cross-window convergence while storage fails is not promised; the current renderer's pending document is authoritative until a local write succeeds. Existing 200-PR and 3000-path limits remain. + +The clean baseline passed all 18 workspace tests. Four new unit cases failed against unchanged production code with lost marks or resurrected stale marks, then all 22 workspace tests passed after the repair. They cover failed writes, denied reads, unmarking, storage recovery, ordinary external updates, account/repository/PR/revision separation, final-mark removal and eviction bounds. + +The first Electron invocation failed before the regression because the renderer had not been built: localStorage access was denied on the unloaded document. Its log and trace are preserved separately. After building the unchanged renderer, the new regression failed on the first checkbox becoming unchecked after marking the second file. After the repair, both Viewed Electron cases passed in 4.9 seconds, including existing revision/reload behavior and the new actual-controls quota failure case. Only the Viewed localStorage write is made to throw; renderer controls and production Viewed helpers remain real. The existing diff fixture synthesizes Code Review reads, so these cases do not qualify the production GitHub transport or live writes. + +An intermediate expanded-test build command returned status 1 without a compiler diagnostic; the unchanged separate build returned zero and the new units then failed at the intended state assertions. This unexplained command failure is retained. Focused reruns are recorded as reruns, not clean first attempts. + +Full build and typecheck passed. Full units passed with 2,583 passes, 36 skips and no failures/cancellations. The first canonical local E2E run failed after 23.8 minutes: 522 desktop cases passed, 17 were explicitly skipped and one existing draft/account-isolation case failed before sign-out. It expected `Private note before signing out.` but main returned that text with an unexpected `eame ` suffix. The test trace records filling the exact expected string and then status polling; it does not establish the source of the extra input. The full input guard confirmed unchanged test/production inputs. Site and web were not reached by the canonical chained command. The failure log, trace and error context were preserved before later runs. + +One unchanged focused reproduction of the failed draft case passed in 4.9 seconds. That narrow rerun does not turn the first full run green or establish a causal fix. The complete actions/diff specs then passed all 50 cases in 2.0 minutes without source changes; the separate site suite passed eight cases in 9.9 seconds and web passed four in 3.3 seconds. These additional runs are separate from the failed canonical invocation. Any published PR remains draft pending full current-head hosted qualification and the existing draft-test follow-up. No issue checkbox, release, default activation or human acceptance follows from the focused results. + +One independent read-only review checked all seven authored files and found no Critical or Important code finding. Its Minor observation was to refresh interim evidence wording; root treats accurate terminal reporting as an Important publication gate and has refreshed the completed and failed states here. The reviewer explicitly did not certify the running full E2E or protected delivery. Storage failure/restart, cross-window behavior, external mounted-view synchronization and wholly unavailable localStorage remain bounded as documented in the design; native/live/human claims remain separate. diff --git a/docs/status.md b/docs/status.md index dc8220d3..892a9746 100644 --- a/docs/status.md +++ b/docs/status.md @@ -133,7 +133,7 @@ before relying on a tick. | [#319](https://github.com/TypeSafeAI/modex/issues/319) CR tracker | 2/10 | CR-3 to CR-8 acceptance; the R1–R4 comparison is retired (2026-11-04) but its boxes still name it | Val's [one session](reviews/2026-11-02-v0.5.0-val-session.md) | | [#322](https://github.com/TypeSafeAI/modex/issues/322) CR-3 | 10/14 | Original-reference comparison (AC1; retired 2026-11-04, box still names it), keyboard/VoiceOver (AC4); clearance beside CR-6's inline section is measured on `main` (#491), but these boxes also need the person-run checks | Val runs the [CR-8 VoiceOver checklist](reviews/2026-10-22-cr8-voiceover/checklist.md) | | [#323](https://github.com/TypeSafeAI/modex/issues/323) CR-4 | 10/14 | Original R1/R2 comparison, VoiceOver; clearance beside CR-6's inline section is measured on `main` (#491), but these boxes also need the person-run checks. Avatars are settled as logins only (decision 1, 2026-11-04) | Benchmark on real pull requests replaces the retired comparison; the comparison boxes stay unticked | -| [#324](https://github.com/TypeSafeAI/modex/issues/324) CR-5 | 12/14 | Original R4 comparison (AC1), retired on 2026-11-04 but still named by the box; the Viewed toggle is decided (local, revision-bound) and not built | Build the Viewed toggle; run the benchmark | +| [#324](https://github.com/TypeSafeAI/modex/issues/324) CR-5 | 12/14 | Original R4 comparison (AC1), retired on 2026-11-04 but still named by the box; local revision-bound Viewed shipped on unreleased main in #506, with a reproduced failed-storage follow-up | Qualify and deliver the [session-state repair](reviews/2026-11-12-viewed-storage-recovery.md); run the benchmark and retain remaining acceptance gates | | [#325](https://github.com/TypeSafeAI/modex/issues/325) CR-6 | 13/14 | Authorized live native smoke (AC6) | Run the smoke once on a small open TypeSafeAI/modex PR (authorized 2026-11-04) | | [#326](https://github.com/TypeSafeAI/modex/issues/326) CR-7 | 13/14 | Live canary on a disposable repository (AC6) | Val names a disposable repository | | [#327](https://github.com/TypeSafeAI/modex/issues/327) CR-8 | 6/17 | The full fixture journey is accepted at its [named source/CI scope](https://github.com/TypeSafeAI/modex/issues/327#issuecomment-6830284937); reference comparison (retired 2026-11-04, boxes still name it), VoiceOver and the live gates. Budgets and C76 landed in #490; re-check item 18 and AC5 once Val confirms the budget numbers | Val's [one session](reviews/2026-11-02-v0.5.0-val-session.md) | diff --git a/docs/superpowers/plans/2026-11-12-viewed-storage-recovery.md b/docs/superpowers/plans/2026-11-12-viewed-storage-recovery.md new file mode 100644 index 00000000..2b0e97a2 --- /dev/null +++ b/docs/superpowers/plans/2026-11-12-viewed-storage-recovery.md @@ -0,0 +1,34 @@ +# Viewed storage recovery implementation plan + +> **For agentic workers:** Use superpowers:executing-plans to implement this one-task repair inline, with a final independent review. + +**Goal:** Preserve local Viewed session marks across failed storage writes. + +**Architecture:** Keep a pending document per storage object only after a write fails; clear it after the next successful write. Existing validation and eviction remain authoritative. + +**Tech Stack:** TypeScript, Node test runner, Electron Playwright, pnpm 10.34.5. + +**Spec:** docs/superpowers/specs/2026-11-12-viewed-storage-recovery-design.md + +## Global constraints + +Preserve local-only behavior, account/repository/PR/revision isolation, 200 PRs and 3000 paths. Do not edit owner branches, enable Code Review, run live inference or release. + +## Review focus + +Storage becoming writable again must retain pending changes and release the fallback. A different storage object must not inherit unsaved marks. Persisted marks must stay unmarked across later failed writes. Head/base changes must not resurrect old revision marks. Normal successful storage reads must still observe external changes. + +## Task 1: Retain failed Viewed writes + +- [x] Run the existing workspace tests on clean main as baseline. +- [x] Add failing production-helper tests for mark A, mark B, unmark A, later toggle, reload helper reads, denied reads, stale persisted marks, isolation and recovery. Expected: exact literal arrays; failures must show lost session state. +- [x] In apps/desktop/src/renderer/code-review/viewed.ts, preserve the existing loadViewed and setViewed signatures and store only failed writes in a WeakMap keyed by Storage. Expected: focused tests pass with existing normal-storage/eviction tests unchanged. +- [x] Add an Electron regression that makes only Viewed storage writes fail and verifies two marks and an unmark through actual controls without GitHub writes. Preserve its RED and GREEN outputs. +- [x] Run pnpm build, pnpm typecheck, pnpm test and pnpm test:e2e, retain first failures/skips and update docs/status.md plus a dated receipt. +- [ ] Make signed commits, obtain one independent final review, apply any Important/Critical corrections in one RED-to-GREEN pass, then preserve recovery and publish a reviewable PR. Protected delivery requires fresh hosted/queue checks and actual merge proof. + +**Interfaces:** Existing loadViewed(storage, key, revision): string[] and setViewed(storage, key, revision, path, viewed): string[] remain unchanged; the view continues using the same calls. + +## Validation status + +Build/typecheck and full units passed. The first canonical desktop E2E failed522/17/1 on an existing draft-input case; that first failure remains unexplained and preserved. The unchanged affected actions/diff suite subsequently passed50/50, with separate site8/web4 passes. The one independent review found no Critical/Important code issue; the interim receipt discrepancy is corrected. Publication is draft only; full current-head hosted qualification and actual protected delivery remain required. diff --git a/docs/superpowers/specs/2026-11-12-viewed-storage-recovery-design.md b/docs/superpowers/specs/2026-11-12-viewed-storage-recovery-design.md new file mode 100644 index 00000000..46b96a19 --- /dev/null +++ b/docs/superpowers/specs/2026-11-12-viewed-storage-recovery-design.md @@ -0,0 +1,7 @@ +# Viewed storage recovery + +Restore the existing C65 promise that Viewed marks survive successive toggles for the current renderer session when localStorage rejects writes. The reproduced #506 follow-up loses mark A after marking B; an unmark can also resurrect stale persisted marks. This repair follows the accepted local-only Viewed decision and does not create GitHub writes or change activation. + +A storage-object-scoped WeakMap will hold the last unsaved document after a failed write. Reads use that document until a later successful write persists accumulated changes and removes the fallback. Existing account/repository/PR/revision separation and 200-PR/3000-path bounds apply unchanged. A fresh storage object cannot see an unpersisted session; renderer restart may lose unsaved marks. Cross-window convergence during storage failure is not promised, and the next successful local toggle uses this renderer's pending state. + +Passing the current React array into every toggle is smaller but would lose the fallback on remount and duplicate revision ownership in the view. Always caching storage would hide ordinary external storage updates. Cache only failed writes, and clear after success, to preserve the normal storage read path. This is an implementation choice under the authorized repair scope, not a new product decision.