Explorar o código

feat(paas): persist inbox read state locally

241880436@seecoder.cn hai 4 días
pai
achega
47bb3c748e

+ 41 - 0
packages/app/src/pages/paas/inbox-seen.test.ts

@@ -0,0 +1,41 @@
+import { expect, test } from "bun:test"
+import { inboxSeenKey, markInboxSeen, readInboxSeen } from "./inbox-seen"
+
+class MemoryStorage implements Storage {
+  private data = new Map<string, string>()
+  get length() {
+    return this.data.size
+  }
+  clear() {
+    this.data.clear()
+  }
+  getItem(key: string) {
+    return this.data.get(key) ?? null
+  }
+  key(index: number) {
+    return [...this.data.keys()][index] ?? null
+  }
+  removeItem(key: string) {
+    this.data.delete(key)
+  }
+  setItem(key: string, value: string) {
+    this.data.set(key, value)
+  }
+}
+
+test("seen state is isolated by scope, window and project", () => {
+  const storage = new MemoryStorage()
+  const a = inboxSeenKey("scope-a", "main", "p1")
+  const b = inboxSeenKey("scope-a", "main", "p2")
+  markInboxSeen(storage, a, "unread:run-a")
+  expect([...readInboxSeen(storage, a)]).toEqual(["unread:run-a"])
+  expect(readInboxSeen(storage, b).size).toBe(0)
+})
+
+test("corrupt seen state falls back to empty and remains writable", () => {
+  const storage = new MemoryStorage()
+  const key = inboxSeenKey("scope", "main", "p1")
+  storage.setItem(key, "{broken")
+  expect(readInboxSeen(storage, key).size).toBe(0)
+  expect([...markInboxSeen(storage, key, "unread:run-b")]).toEqual(["unread:run-b"])
+})

+ 23 - 0
packages/app/src/pages/paas/inbox-seen.ts

@@ -0,0 +1,23 @@
+export function inboxSeenKey(scope: string, windowID: string, projectID: string) {
+  return `lambda-scientist.inbox-seen.v1:${scope}:${windowID}:${projectID}`
+}
+
+export function readInboxSeen(storage: Storage, key: string) {
+  try {
+    const value = JSON.parse(storage.getItem(key) || "[]") as unknown
+    return new Set(Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [])
+  } catch {
+    return new Set<string>()
+  }
+}
+
+export function writeInboxSeen(storage: Storage, key: string, seen: Set<string>) {
+  storage.setItem(key, JSON.stringify([...seen]))
+}
+
+export function markInboxSeen(storage: Storage, key: string, id: string) {
+  const seen = readInboxSeen(storage, key)
+  seen.add(id)
+  writeInboxSeen(storage, key, seen)
+  return seen
+}