Skip to content

Open source CapCut alternative.

TypeScript

fix(cut): keep chat history through full storage and sign-ins

David Lef31fdf65277d
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 24c5766c..a7f474f4 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -14,6 +14,7 @@ import { EmbeddedSignInFallback } from "@/cut/components/EmbeddedSignInFallback"
import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
import {
+ confirmEngineUser,
forgetRememberedEngineUser,
rememberedEngineUser,
setEngineUser,
@@ -78,7 +79,7 @@ export function RequireSession({ children }: { children: ReactNode }) {
// Bound in an effect so the render stays free of side effects; SessionGate
// subscribes to it, so the surfaces redraw the moment the id lands.
useEffect(() => {
- if (userId) setEngineUser(userId);
+ if (userId) confirmEngineUser(userId);
}, [userId]);
useEffect(() => {
diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.ts
index 1e6bdce7..b9fa49d8 100644
--- a/site/src/cut/lib/api.ts
+++ b/site/src/cut/lib/api.ts
@@ -243,6 +243,30 @@ export function currentEngineUser(): string | null {
return engineUser;
}
+// The account the resolved session named. The remembered id binds first so
+// cached shelves paint, but only a confirmed id decides whose data is whose.
+let confirmedUser: string | null = null;
+const confirmations = new Set<() => void>();
+
+/** Bind the account the live session resolved to. */
+export function confirmEngineUser(id: string) {
+ setEngineUser(id);
+ if (confirmedUser === id) return;
+ confirmedUser = id;
+ for (const fn of confirmations) fn();
+}
+
+/** The bound account once the live session confirmed it, else null. */
+export function confirmedEngineUser(): string | null {
+ return confirmedUser === engineUser ? confirmedUser : null;
+}
+
+/** Called when the live session confirms an account. */
+export function onEngineUserConfirmed(fn: () => void): () => void {
+ confirmations.add(fn);
+ return () => confirmations.delete(fn);
+}
+
/** Called when the bound account changes; returns its own unsubscribe. */
export function subscribeEngineUser(fn: () => void): () => void {
listeners.add(fn);
diff --git a/site/src/cut/lib/chatThreads.test.ts b/site/src/cut/lib/chatThreads.test.ts
index fdaf1659..5b8e9a62 100644
--- a/site/src/cut/lib/chatThreads.test.ts
+++ b/site/src/cut/lib/chatThreads.test.ts
@@ -43,7 +43,7 @@ beforeEach(() => {
/** IndexedDB as the thread store sees it: one list per project, and a quota
* that refuses a write past it the way the browser does. */
-function memoryStore(quota = Infinity, pressure?: number) {
+function memoryStore(quota = Infinity) {
const lists = new Map<string, unknown[]>();
const size = () => [...lists.values()].reduce((n, list) => n + JSON.stringify(list).length, 0);
const threadStore: ThreadStore = {
@@ -58,7 +58,6 @@ function memoryStore(quota = Infinity, pressure?: number) {
},
remove: async (projectId) => { lists.delete(projectId); },
projects: async () => [...lists.keys()],
- pressure: async () => pressure,
};
return { threadStore, lists, size };
}
@@ -254,39 +253,50 @@ describe("where threads are kept", () => {
lists.set("elsewhere", [{ id: "b" }]);
lists.set("deleted", [{ id: "c" }]);
useThreadStore(threadStore);
+ // The account listed all three once, which makes their threads its own.
+ await sweepGoneProjectThreads(new Set(["kept", "elsewhere", "deleted"]), "me", async () => true);
const asked: string[] = [];
- await sweepGoneProjectThreads(new Set(["kept"]), async (id) => { asked.push(id); return id === "deleted"; });
+ await sweepGoneProjectThreads(new Set(["kept"]), "me", async (id) => { asked.push(id); return id === "deleted"; });
expect(asked.sort()).toEqual(["deleted", "elsewhere"]);
expect([...lists.keys()].sort()).toEqual(["elsewhere", "kept"]);
// Each project is asked about once per page.
- await sweepGoneProjectThreads(new Set(["kept"]), async (id) => { asked.push(id); return false; });
+ await sweepGoneProjectThreads(new Set(["kept"]), "me", async (id) => { asked.push(id); return false; });
expect(asked).toHaveLength(2);
});
- test("a full store makes room from other projects' oldest threads first", async () => {
- const { threadStore, lists } = memoryStore(1_000_000);
- lists.set("old", [big("o1", 1, 300_000), big("o2", 5, 300_000)]);
- lists.set("older", [big("o0", 0, 300_000)]);
+ test("another account's threads survive this account's sweep", async () => {
+ const { threadStore, lists } = memoryStore();
+ lists.set("theirs", [{ id: "a" }]);
+ lists.set("unlisted", [{ id: "b" }]);
useThreadStore(threadStore);
- await loadProjectThreads("p");
- writeProjectThreads("p", [big("mine", 9, 200_000)]);
- await flushThreadSaves();
- expect(threadSaveFailure()).toBeNull();
- expect((lists.get("p") as { id: string }[]).map((t) => t.id)).toEqual(["mine"]);
- // The oldest thread went; the newer one of another project stayed.
- expect(lists.has("older")).toBe(false);
- expect((lists.get("old") as { id: string }[]).map((t) => t.id)).toEqual(["o1", "o2"]);
+ await sweepGoneProjectThreads(new Set(["theirs"]), "them", async () => true);
+ // Every backend answers 404 for a project this account doesn't own, so a
+ // miss proves nothing about a project it never listed.
+ useThreadStore(threadStore);
+ const asked: string[] = [];
+ await sweepGoneProjectThreads(new Set(), "me", async (id) => { asked.push(id); return true; });
+ expect(asked).toEqual([]);
+ expect([...lists.keys()].sort()).toEqual(["theirs", "unlisted"]);
});
- test("a store near its quota prunes before it writes", async () => {
- const { threadStore, lists } = memoryStore(Infinity, 0.95);
- lists.set("other", [big("o1", 1, 1000), big("o2", 2, 1000)]);
+ test("a full store keeps every other project's threads and says the save failed", async () => {
+ const { threadStore, lists } = memoryStore(1_000_000);
+ lists.set("old", [big("o1", 1, 300_000), big("o2", 5, 300_000)]);
+ lists.set("older", [big("o0", 0, 300_000)]);
useThreadStore(threadStore);
- await loadProjectThreads("p");
- writeProjectThreads("p", [big("mine", 9, 500)]);
- await flushThreadSaves();
- expect((lists.get("other") as { id: string }[]).map((t) => t.id)).toEqual(["o2"]);
- expect(lists.has("p")).toBe(true);
+ const warn = spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ await loadProjectThreads("p");
+ writeProjectThreads("p", [big("mine", 9, 200_000)]);
+ await flushThreadSaves();
+ expect(threadSaveFailure()).toContain("storage is full");
+ expect((lists.get("old") as { id: string }[]).map((t) => t.id)).toEqual(["o1", "o2"]);
+ expect((lists.get("older") as { id: string }[]).map((t) => t.id)).toEqual(["o0"]);
+ // The open chat is still on screen for the page to show.
+ expect(readProjectThreads("p").map((t) => t.id)).toEqual(["mine"]);
+ } finally {
+ warn.mockRestore();
+ }
});
test("a save that still fails is reported once, and clears when a save lands", async () => {
diff --git a/site/src/cut/lib/chatThreads.ts b/site/src/cut/lib/chatThreads.ts
index c41adea9..ca24cdef 100644
--- a/site/src/cut/lib/chatThreads.ts
+++ b/site/src/cut/lib/chatThreads.ts
@@ -14,6 +14,10 @@ export const activeChatKey = (projectId: string) => `cut-ai-active-${projectId}`
export const queueKey = (projectId: string, threadId: string) => `cut-ai-queue-${projectId}-${threadId}`;
// Which background replies the user has seen, per project.
export const seenRepliesKey = (projectId: string) => `cut-ai-seen-replies-${projectId}`;
+// The account whose listing last held a project this browser keeps threads
+// for. Every backend answers 404 for another account's project, so only the
+// owner's sweep may read a miss as deleted.
+const ownerKey = (projectId: string) => `cut-ai-owner-${projectId}`;
const changes = new Set<(projectId: string) => void>();
const notify = (projectId: string) => { for (const onChange of changes) onChange(projectId); };
@@ -59,8 +63,6 @@ export interface ThreadStore {
write(projectId: string, list: unknown[]): Promise<void>;
remove(projectId: string): Promise<void>;
projects(): Promise<string[]>;
- /** How full the origin's storage is, 0–1, when the browser says. */
- pressure(): Promise<number | undefined>;
}
async function chatStore<T>(mode: IDBTransactionMode, op: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
@@ -81,10 +83,6 @@ const indexedDbStore: ThreadStore = {
write: (projectId, list) => chatStore("readwrite", (s) => s.put(list, projectId)).then(() => undefined),
remove: (projectId) => chatStore("readwrite", (s) => s.delete(projectId)).then(() => undefined),
projects: () => chatStore("readonly", (s) => s.getAllKeys()).then((keys) => keys.map(String)),
- pressure: async () => {
- const estimate = await navigator.storage?.estimate?.().catch(() => undefined);
- return estimate?.quota ? (estimate.usage ?? 0) / estimate.quota : undefined;
- },
};
// The thread store in use: undefined until first needed, null when there is
@@ -104,7 +102,6 @@ const dirty = new Set<string>();
let migration: Promise<void> | null = null;
let queue: Promise<void> = Promise.resolve();
let flushScheduled = false;
-const persistedSize = new Map<string, number>();
// How long a load waits on the store (another tab can hold the database on an
// older version) before this tab falls back to localStorage.
const LOAD_TIMEOUT_MS = 5000;
@@ -117,7 +114,6 @@ export function useThreadStore(store: ThreadStore | null): void {
loads.clear();
loaded.clear();
dirty.clear();
- persistedSize.clear();
migration = null;
queue = Promise.resolve();
flushScheduled = false;
@@ -137,7 +133,6 @@ function readLegacy(projectId: string): unknown[] {
}
const merged = (...lists: unknown[][]) => mergeThreads(...lists.map((l) => l.filter(isStoredThread)));
-const sizeOf = (list: unknown[]) => JSON.stringify(list).length;
/** Move every project's localStorage history into the store, once per page,
* then free the keys. A key whose write fails stays put for the next try. */
@@ -187,7 +182,6 @@ export function loadProjectThreads(projectId: string): Promise<void> {
await migrateLegacyThreads(store);
const stored = (await store.read(projectId)) ?? [];
if (backing !== store) return;
- persistedSize.set(projectId, sizeOf(stored));
// Anything written before the load finished joins what was stored, as
// does a localStorage copy the migration couldn't move.
const early = [...readLegacy(projectId), ...(cache.get(projectId) ?? [])];
@@ -282,24 +276,12 @@ async function persistDirty(): Promise<void> {
const isQuotaError = (err: unknown) =>
!!err && typeof err === "object" && ((err as Error).name === "QuotaExceededError" || (err as { code?: number }).code === 22);
+// A save never deletes history to fit. Local and browser projects keep their
+// chat only here, and project media fills the origin's quota far faster than
+// chat does, so a full browser says the save failed and keeps every thread.
async function persist(store: ThreadStore, projectId: string, list: unknown[]): Promise<void> {
- const size = sizeOf(list);
- const growth = size - (persistedSize.get(projectId) ?? 0);
try {
- const pressure = await store.pressure().catch(() => undefined);
- if (pressure !== undefined && pressure > PRESSURE) await makeRoom(store, projectId, growth);
- for (let attempt = 0; ; attempt++) {
- try {
- await store.write(projectId, list);
- break;
- } catch (err) {
- // The browser doesn't say how far over it is: free what this save
- // adds, then twice that, and so on.
- if (!isQuotaError(err) || attempt >= 4) throw err;
- if ((await makeRoom(store, projectId, Math.max(growth, 1024) * 2 ** attempt)) === 0) throw err;
- }
- }
- persistedSize.set(projectId, size);
+ await store.write(projectId, list);
removeLocal(threadsKey(projectId));
setSaveFailure(null);
broadcast(projectId);
@@ -308,45 +290,6 @@ async function persist(store: ThreadStore, projectId: string, list: unknown[]):
}
}
-/** Above this share of the origin's quota, a save first clears room. */
-const PRESSURE = 0.9;
-
-/** Free at least `bytes` by dropping the oldest threads of other projects —
- * the open project's history is the last thing to lose. Returns the bytes freed. */
-async function makeRoom(store: ThreadStore, keep: string, bytes: number): Promise<number> {
- if (bytes <= 0) return 0;
- const lists = new Map<string, unknown[]>();
- for (const projectId of await store.projects()) {
- if (projectId === keep) continue;
- lists.set(projectId, (loaded.has(projectId) ? cache.get(projectId) : await store.read(projectId)) ?? []);
- }
- const candidates = [...lists].flatMap(([projectId, list]) =>
- list.filter(isStoredThread).filter((t) => !t.deleted).map((thread) => ({ projectId, thread })),
- );
- candidates.sort((a, b) => (a.thread.updatedAt ?? 0) - (b.thread.updatedAt ?? 0));
- let freed = 0;
- const dropped = new Map<string, Set<string>>();
- for (const { projectId, thread } of candidates) {
- if (freed >= bytes) break;
- freed += JSON.stringify(thread).length;
- if (!dropped.has(projectId)) dropped.set(projectId, new Set());
- dropped.get(projectId)!.add(thread.id);
- }
- for (const [projectId, ids] of dropped) {
- const rest = lists.get(projectId)!.filter((t) => !isStoredThread(t) || !ids.has(t.id));
- if (rest.some((t) => isStoredThread(t) && !t.deleted)) await store.write(projectId, rest);
- else await store.remove(projectId);
- persistedSize.set(projectId, sizeOf(rest));
- if (cache.has(projectId)) cache.set(projectId, rest);
- for (const id of ids) removeLocal(queueKey(projectId, id));
- notify(projectId);
- broadcast(projectId);
- }
- const count = [...dropped.values()].reduce((n, ids) => n + ids.size, 0);
- if (count) console.warn(`[chat] browser storage nearly full; dropped the ${count} oldest chat thread(s) of other projects`);
- return freed;
-}
-
/** Wait until every write so far has reached the store. */
export async function flushThreadSaves(): Promise<void> {
for (let i = 0; i < 10; i++) {
@@ -428,7 +371,6 @@ function listenAcrossTabs(): void {
void store.read(projectId).then((list) => {
if (backing !== store || dirty.has(projectId)) return;
cache.set(projectId, list ?? []);
- persistedSize.set(projectId, sizeOf(list ?? []));
notify(projectId);
}, () => {});
});
@@ -506,7 +448,6 @@ export function clearProjectThreads(projectId: string): void {
cache.set(projectId, []);
loaded.add(projectId);
dirty.delete(projectId);
- persistedSize.delete(projectId);
void enqueue(async () => {
try {
await store.remove(projectId);
@@ -530,16 +471,38 @@ export function clearProjectThreads(projectId: string): void {
removeLocal(threadsKey(projectId));
removeLocal(activeChatKey(projectId));
removeLocal(seenRepliesKey(projectId));
+ removeLocal(ownerKey(projectId));
notify(projectId);
}
// Projects already asked about this page: a listing refetch doesn't re-ask.
const goneChecked = new Set<string>();
-/** Clear the history of projects this browser holds threads for but no
- * listing shows, once `gone` confirms each is deleted (not merely on a
- * backend this page can't reach right now). */
-export async function sweepGoneProjectThreads(listed: Set<string>, gone: (projectId: string) => Promise<boolean>): Promise<void> {
+function readOwner(projectId: string): string | null {
+ try {
+ return localStorage.getItem(ownerKey(projectId));
+ } catch {
+ return null;
+ }
+}
+
+function writeOwner(projectId: string, account: string): void {
+ try {
+ if (localStorage.getItem(ownerKey(projectId)) !== account) localStorage.setItem(ownerKey(projectId), account);
+ } catch {
+ // Storage full/blocked: the project is never swept, so its threads stay.
+ }
+}
+
+/** Clear the history of projects `account` once listed but no listing shows
+ * now, once `gone` confirms each is deleted (not merely on a backend this page
+ * can't reach right now). Threads of a project this account never listed
+ * belong to another account in this browser and are left alone. */
+export async function sweepGoneProjectThreads(
+ listed: Set<string>,
+ account: string,
+ gone: (projectId: string) => Promise<boolean>,
+): Promise<void> {
if (memory) return;
const store = threadStore();
let held: string[] = [];
@@ -557,7 +520,11 @@ export async function sweepGoneProjectThreads(listed: Set<string>, gone: (projec
return;
}
for (const projectId of held) {
- if (listed.has(projectId) || goneChecked.has(projectId)) continue;
+ if (listed.has(projectId)) {
+ writeOwner(projectId, account);
+ continue;
+ }
+ if (goneChecked.has(projectId) || readOwner(projectId) !== account) continue;
goneChecked.add(projectId);
if (await gone(projectId).catch(() => false)) clearProjectThreads(projectId);
}
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
index 07fe0f80..0cb385e0 100644
--- a/site/src/cut/lib/queries.ts
+++ b/site/src/cut/lib/queries.ts
@@ -19,7 +19,7 @@
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
-import { engineLost } from "./api";
+import { confirmedEngineUser, currentEngineUser, engineLost, onEngineUserConfirmed } from "./api";
import { cutMode } from "./backend";
import { useCutMode } from "./backend/hooks";
import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";
@@ -36,6 +36,7 @@ import {
type Residency,
} from "./residency";
import { sweepGoneProjectThreads } from "./chatThreads";
+import { listingSweeper } from "./threadSweep";
import type { ProjectFolder, ProjectSummary } from "./types";
export { backendFor };
@@ -78,12 +79,14 @@ function seedFromSnapshot<T>(client: QueryClient, queryKey: readonly unknown[],
// answered, chat history this browser holds for a project none of them lists
// is checked against its backends and dropped if the project is gone —
// deleted from another tab, another device, or with its folder.
-const listings = new Map<Residency, Set<string>>();
-function noteListing(r: Residency, data: ProjectsSection): void {
- listings.set(r, new Set(data.projects.map((p) => p.id)));
- if (!availableResidencies().every((x) => listings.has(x))) return;
- const listed = new Set([...listings.values()].flatMap((ids) => [...ids]));
- void sweepGoneProjectThreads(listed, projectGone);
+const sweeper = listingSweeper({
+ residencies: availableResidencies,
+ confirmed: confirmedEngineUser,
+ sweep: (listed, account) => sweepGoneProjectThreads(listed, account, projectGone),
+});
+onEngineUserConfirmed(sweeper.retry);
+function noteListing(r: Residency, data: ProjectsSection, as: string | null): void {
+ sweeper.note(r, new Set(data.projects.map((p) => p.id)), as);
}
async function fetchProjectsSection(r: Residency): Promise<ProjectsSection> {
@@ -121,9 +124,10 @@ export function useProjectsSection(r: Residency, { list, live }: { list: boolean
queryKey: projectsKey(r),
queryFn: async () => {
try {
+ const as = currentEngineUser();
const data = await fetchProjectsSection(r);
writeSnapshot(projectsSnapshotKey(r), data);
- noteListing(r, data);
+ noteListing(r, data, as);
return data;
} catch (err) {
if (r === "local" && cutMode() === "local") {
diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.ts
index b7c11bb2..36a55474 100644
--- a/site/src/cut/lib/residency.ts
+++ b/site/src/cut/lib/residency.ts
@@ -197,7 +197,8 @@ export async function resolveProjectPlacement(projectId: string): Promise<Projec
* doesn't hold it, a reachable engine answers 404, and the cloud answers 404.
* Anything that can't answer — an engine this browser has used but that isn't
* running, a signed-out cloud, a network error — keeps it, so a closed app
- * never costs a project its chat history.
+ * never costs a project its chat history. Every backend also answers 404 for
+ * another account's project, so ask only about projects this account listed.
*/
export async function projectGone(projectId: string): Promise<boolean> {
if (await browserHasProject(projectId).catch(() => true)) return false;
diff --git a/site/src/cut/lib/threadSweep.test.ts b/site/src/cut/lib/threadSweep.test.ts
new file mode 100644
index 00000000..f1003e29
--- /dev/null
+++ b/site/src/cut/lib/threadSweep.test.ts
@@ -0,0 +1,95 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+
+import { sweepGoneProjectThreads, useThreadStore, type ThreadStore } from "./chatThreads";
+import { listingSweeper } from "./threadSweep";
+
+// Bun's test runtime has no localStorage; the chat module reads it per call.
+const local = new Map<string, string>();
+beforeEach(() => {
+ local.clear();
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (k: string) => local.get(k) ?? null,
+ setItem: (k: string, v: string) => void local.set(k, v),
+ removeItem: (k: string) => void local.delete(k),
+ get length() { return local.size; },
+ key: (i: number) => [...local.keys()][i] ?? null,
+ };
+});
+
+function heldThreads(...projectIds: string[]) {
+ const lists = new Map<string, unknown[]>(projectIds.map((id) => [id, [{ id: `t-${id}` }]]));
+ const store: ThreadStore = {
+ read: async (projectId) => lists.get(projectId),
+ write: async (projectId, list) => void lists.set(projectId, list),
+ remove: async (projectId) => void lists.delete(projectId),
+ projects: async () => [...lists.keys()],
+ };
+ return { lists, store };
+}
+
+describe("the listing sweep", () => {
+ test("a listing that arrives before the session confirms the account marks and clears nothing", async () => {
+ const { lists, store } = heldThreads("listed", "gone");
+ useThreadStore(store);
+ let confirmed: string | null = null;
+ const swept: Promise<void>[] = [];
+ const sweeper = listingSweeper({
+ residencies: () => ["cloud"],
+ confirmed: () => confirmed,
+ sweep: (listed, account) => {
+ const run = sweepGoneProjectThreads(listed, account, async () => true);
+ swept.push(run);
+ return run;
+ },
+ });
+
+ // The remembered last account is bound, and the listing comes back under it.
+ sweeper.note("cloud", new Set(["listed"]), "remembered");
+ await Promise.all(swept);
+ expect(swept).toHaveLength(0);
+ expect([...local.keys()]).toEqual([]);
+
+ // The live session names someone else: that listing was another account's.
+ confirmed = "signed-in";
+ sweeper.retry();
+ await Promise.all(swept);
+ expect(swept).toHaveLength(0);
+ expect([...lists.keys()].sort()).toEqual(["gone", "listed"]);
+
+ // A listing fetched as the confirmed account sweeps.
+ sweeper.note("cloud", new Set(["listed"]), "signed-in");
+ await Promise.all(swept);
+ expect(swept).toHaveLength(1);
+ expect(local.get("cut-ai-owner-listed")).toBe("signed-in");
+ });
+
+ test("a listing fetched as the remembered account sweeps once the session confirms that account", async () => {
+ useThreadStore(heldThreads("listed").store);
+ let confirmed: string | null = null;
+ const calls: string[] = [];
+ const sweeper = listingSweeper({
+ residencies: () => ["cloud", "browser"],
+ confirmed: () => confirmed,
+ sweep: async (_listed, account) => void calls.push(account),
+ });
+ sweeper.note("cloud", new Set(["listed"]), "me");
+ sweeper.note("browser", new Set(), "me");
+ expect(calls).toEqual([]);
+ confirmed = "me";
+ sweeper.retry();
+ expect(calls).toEqual(["me"]);
+ });
+
+ test("every live residency has to have listed before anything sweeps", () => {
+ const calls: string[] = [];
+ const sweeper = listingSweeper({
+ residencies: () => ["cloud", "browser"],
+ confirmed: () => "me",
+ sweep: async (_listed, account) => void calls.push(account),
+ });
+ sweeper.note("cloud", new Set(), "me");
+ expect(calls).toEqual([]);
+ sweeper.note("browser", new Set(), "me");
+ expect(calls).toEqual(["me"]);
+ });
+});
diff --git a/site/src/cut/lib/threadSweep.ts b/site/src/cut/lib/threadSweep.ts
new file mode 100644
index 00000000..81881688
--- /dev/null
+++ b/site/src/cut/lib/threadSweep.ts
@@ -0,0 +1,36 @@
+// Chat history a deleted project left in this browser is swept once every live
+// residency has listed for the account the session confirmed. A listing
+// fetched under the remembered last account, before the session resolves,
+// can be another account's shelf (the browser store and the engine read by
+// the bound id), so it never decides which threads are whose.
+import type { Residency } from "./residency";
+
+type SweepDeps = {
+ residencies: () => Residency[];
+ /** The account the live session named; null until it resolves. */
+ confirmed: () => string | null;
+ sweep: (listed: Set<string>, account: string) => Promise<void>;
+};
+
+export function listingSweeper({ residencies, confirmed, sweep }: SweepDeps) {
+ // Each residency's latest listing and the account bound when it was fetched.
+ const listings = new Map<Residency, { ids: Set<string>; as: string | null }>();
+
+ // Sweep only when every live residency listed as the confirmed account.
+ const retry = () => {
+ const account = confirmed();
+ if (!account) return;
+ const live = residencies();
+ if (!live.every((r) => listings.get(r)?.as === account)) return;
+ const listed = new Set(live.flatMap((r) => [...listings.get(r)!.ids]));
+ void sweep(listed, account);
+ };
+
+ return {
+ note(r: Residency, ids: Set<string>, as: string | null) {
+ listings.set(r, { ids, as });
+ retry();
+ },
+ retry,
+ };
+}