Skip to content

Open source CapCut alternative.

TypeScript

fix(site): show a shared project's chat threads

David Led2210aeb9c83
diff --git a/site/src/app/cut/s/[token]/SharedProjectView.tsx b/site/src/app/cut/s/[token]/SharedProjectView.tsx
index 1ea839ac..29247473 100644
--- a/site/src/app/cut/s/[token]/SharedProjectView.tsx
+++ b/site/src/app/cut/s/[token]/SharedProjectView.tsx
@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";
import { Editor } from "@/cut/components/Editor";
import { bindCutMode } from "@/cut/lib/backend";
import { bindSharedBackend } from "@/cut/lib/backend/shared";
+import { holdThreadsInMemory } from "@/cut/lib/chatThreads";
import { useEditor } from "@/cut/lib/store";
import type { ShareFeatures } from "@/cut/lib/types";
import { authClient } from "@/lib/auth-client";
@@ -42,6 +43,7 @@ export function SharedProject() {
const meta = (await res.json()) as { projectId: string; features: ShareFeatures };
bindSharedBackend(token);
bindCutMode("shared");
+ holdThreadsInMemory();
useEditor.getState().setSharedView(meta.features);
setGate({ state: "ready", projectId: meta.projectId });
})
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index 9bc157bc..01bb6ddf 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -46,7 +46,12 @@ import { useCutCaps } from "@/cut/lib/backend/hooks";
import { buildAiContext } from "@/cut/lib/aiContext";
import { runAiTool } from "@/cut/lib/aiTools";
import { setAssetDragData } from "@/cut/lib/assetDrag";
-import { activeChatKey, threadsKey } from "@/cut/lib/chatThreads";
+import {
+ readActiveChat,
+ readRawThreads,
+ writeActiveChat,
+ writeRawThreads,
+} from "@/cut/lib/chatThreads";
import {
deleteCloudThread,
ensureCloudThreads,
@@ -117,14 +122,7 @@ interface ChatThread {
const THREAD_LIMIT = 30;
function readThreads(projectId: string): ChatThread[] {
- try {
- const v = JSON.parse(
- localStorage.getItem(threadsKey(projectId)) ?? "[]",
- ) as unknown;
- return Array.isArray(v) ? (v as ChatThread[]) : [];
- } catch {
- return [];
- }
+ return readRawThreads(projectId) as ChatThread[];
}
/** Persisted copies drop frame payloads (data URLs) from tool outputs — one
@@ -195,14 +193,7 @@ function writeThreads(projectId: string, list: ChatThread[]) {
deleteCloudThread(projectId, t.id);
}
}
- try {
- localStorage.setItem(
- threadsKey(projectId),
- JSON.stringify(slimForStorage(kept)),
- );
- } catch {
- // Storage full/blocked — history just won't persist.
- }
+ writeRawThreads(projectId, slimForStorage(kept));
}
const MODEL_KEY = "cut-ai-model";
@@ -259,10 +250,10 @@ export function AiPanel({
const [activeChat, setActiveChat] = useState<string>(() =>
typeof window === "undefined"
? crypto.randomUUID()
- : (localStorage.getItem(activeChatKey(projectId)) ?? crypto.randomUUID()),
+ : (readActiveChat(projectId) ?? crypto.randomUUID()),
);
useEffect(() => {
- localStorage.setItem(activeChatKey(projectId), activeChat);
+ writeActiveChat(projectId, activeChat);
}, [activeChat, projectId]);
const [historyOpen, setHistoryOpen] = useState(false);
const [threads, setThreads] = useState<ChatThread[]>([]);
diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.ts
index d1c1193d..66ddb8ab 100644
--- a/site/src/cut/lib/chatCloud.ts
+++ b/site/src/cut/lib/chatCloud.ts
@@ -3,7 +3,8 @@
// /projects/:id/chats routes so the history follows the account across
// devices. Threads stay opaque here — the module reads only id and updatedAt
// to merge, and ships the same slimmed payload the panel writes to storage.
-import { apiFetch, cutMode, getBackend, type CutBackend } from "./backend";
+import { cutMode, getBackend, type CutBackend } from "./backend";
+import { cloudBackend } from "./backend/cloud";
import {
isStoredThread,
mergeThreads,
@@ -21,7 +22,9 @@ export async function fetchCloudThreads(
backend: CutBackend,
projectId: string
): Promise<StoredThread[]> {
- if (backend.kind !== "cloud") return [];
+ // The shared backend rewrites this path onto the viewer surface, which
+ // serves the owner's threads when the share includes chat.
+ if (backend.kind === "local") return [];
// Throws on a failed read rather than reading as "no threads": the seed memo
// and a project copy both have to tell an empty history from a lost one.
const res = await backend.fetch(`/api/cut/projects/${projectId}/chats`);
@@ -46,17 +49,21 @@ export async function putCloudThread(
if (!res.ok) throw new Error("Could not save a chat thread.");
}
-/** Merge the server's copy of a cloud project's threads into localStorage —
- * per thread, the newer updatedAt wins. Resolves immediately for local
- * projects; memoized per project, but a network failure clears the memo so
- * the next panel mount retries. */
+/** Bring a cloud project's chat history and the server's copy into agreement,
+ * per thread the newer updatedAt winning, and push back whatever the server is
+ * missing or trailing on. The push is what makes the mirror hold: a save that
+ * never landed — offline, a request that failed, a thread written before this
+ * project moved to the cloud — would otherwise stay local forever, and a share
+ * link would show a project with no chat at all. Resolves immediately for local
+ * projects; memoized per project, but a failure clears the memo so the next
+ * panel mount retries. */
export function ensureCloudThreads(projectId: string): Promise<void> {
- // Shared viewers seed too (read-only); saves and deletes below stay
- // cloud-only, so a viewer never writes back.
+ // Shared viewers sync too, read-only: syncThreads pushes nothing back, and
+ // the saves and deletes below are cloud-only.
if (cutMode() === "local") return Promise.resolve();
let p = seeded.get(projectId);
if (!p) {
- p = seedThreads(projectId).catch(() => {
+ p = syncThreads(projectId).catch(() => {
seeded.delete(projectId);
});
seeded.set(projectId, p);
@@ -64,10 +71,21 @@ export function ensureCloudThreads(projectId: string): Promise<void> {
return p;
}
-async function seedThreads(projectId: string): Promise<void> {
- const remote = await fetchCloudThreads(getBackend(), projectId);
- if (remote.length === 0) return;
- writeProjectThreads(projectId, mergeThreads(remote, readProjectThreads(projectId)));
+async function syncThreads(projectId: string): Promise<void> {
+ const backend = getBackend();
+ const remote = await fetchCloudThreads(backend, projectId);
+ // A viewer's list is the owner's list — there is nothing of their own to
+ // merge, so the share's threads stand alone (in memory, per chatThreads).
+ if (backend.kind === "shared") {
+ writeProjectThreads(projectId, remote);
+ return;
+ }
+ const merged = mergeThreads(remote, readProjectThreads(projectId));
+ writeProjectThreads(projectId, merged);
+ const stored = new Map(remote.map((t) => [t.id, t.updatedAt ?? 0]));
+ const behind = merged.filter((t) => (stored.get(t.id) ?? -1) < (t.updatedAt ?? 0));
+ // One at a time: a full history can be a few megabytes of transcript.
+ for (const thread of behind) await putCloudThread(backend, projectId, thread);
}
// Saves debounce per thread: while a turn streams, the panel re-saves on every
@@ -110,14 +128,18 @@ async function flushOne(key: string, keepalive = false): Promise<void> {
pending.delete(key);
clearTimeout(entry.timer);
try {
- await apiFetch(`/api/cut/projects/${entry.projectId}/chats/${entry.threadId}`, {
+ // The cloud backend by name, not the ambient one: this save was queued for
+ // a cloud project, and by the time the debounce fires the user may have
+ // closed it — with the Mac app running, the ambient backend is then the
+ // engine, which has no chats route and no copy of this project.
+ await cloudBackend.fetch(`/api/cut/projects/${entry.projectId}/chats/${entry.threadId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(entry.data),
keepalive,
});
} catch {
- // The thread is still in localStorage; its next change re-queues it.
+ // The thread is still in localStorage; the next sync pushes it up.
}
}
@@ -134,7 +156,7 @@ export function deleteCloudThread(projectId: string, threadId: string): void {
clearTimeout(entry.timer);
pending.delete(saveKey(projectId, threadId));
}
- void apiFetch(`/api/cut/projects/${projectId}/chats/${threadId}`, {
+ void cloudBackend.fetch(`/api/cut/projects/${projectId}/chats/${threadId}`, {
method: "DELETE",
}).catch(() => {
// Offline delete — the copy resurfaces on the next merge; the user can
diff --git a/site/src/cut/lib/chatThreads.ts b/site/src/cut/lib/chatThreads.ts
index fc25e265..8694c432 100644
--- a/site/src/cut/lib/chatThreads.ts
+++ b/site/src/cut/lib/chatThreads.ts
@@ -1,7 +1,7 @@
-// Chat history is per project, stored in localStorage. The keys and a couple of
-// raw readers live in this leaf module (importing nothing app-specific) so both
-// the AI panel — which owns the history — and the generate store — which must
-// refuse to resume a render whose thread the user deleted — can reach it without
+// Chat history is per project. The keys and a couple of raw readers live in
+// this leaf module (importing nothing app-specific) so both the AI panel —
+// which owns the history — and the generate store — which must refuse to
+// resume a render whose thread the user deleted — can reach it without
// importing each other.
// The keys derive from the route's project id, never the editor store's
@@ -11,6 +11,17 @@ export const threadsKey = (projectId: string) => `cut-ai-threads-${projectId}`;
// The open chat survives hiding the panel — only the + button starts a new one.
export const activeChatKey = (projectId: string) => `cut-ai-active-${projectId}`;
+// Where the threads live. An owner's are durable in localStorage; a shared
+// viewer holds the owner's copy in memory for the tab, so reading someone
+// else's project leaves nothing in this browser — and an owner opening their
+// own share link keeps their stored history untouched.
+let memory: { threads: Map<string, unknown[]>; active: Map<string, string> } | null = null;
+
+/** Bound by the shared viewer page before the editor mounts. */
+export function holdThreadsInMemory(): void {
+ memory ??= { threads: new Map(), active: new Map() };
+}
+
/** A saved thread as this module handles it: an opaque record read only for its
* id and modified time, so history, the cloud mirror, and project copies can
* move threads around without knowing the panel's payload. */
@@ -19,22 +30,60 @@ export type StoredThread = { id: string; updatedAt?: number };
export const isStoredThread = (v: unknown): v is StoredThread =>
!!v && typeof v === "object" && typeof (v as StoredThread).id === "string";
-/** Every saved thread in a project, as stored. */
-export function readProjectThreads(projectId: string): StoredThread[] {
+/** A project's thread list exactly as written. The AI panel owns the payload;
+ * this module owns where it lives. */
+export function readRawThreads(projectId: string): unknown[] {
+ if (memory) return memory.threads.get(projectId) ?? [];
try {
const v = JSON.parse(localStorage.getItem(threadsKey(projectId)) ?? "[]") as unknown;
- return Array.isArray(v) ? v.filter(isStoredThread) : [];
+ return Array.isArray(v) ? v : [];
} catch {
return [];
}
}
+/** Replace a project's thread list, payload untouched. */
+export function writeRawThreads(projectId: string, list: unknown[]): void {
+ if (memory) {
+ memory.threads.set(projectId, list);
+ return;
+ }
+ try {
+ localStorage.setItem(threadsKey(projectId), JSON.stringify(list));
+ } catch {
+ // Storage full/blocked — history just won't persist.
+ }
+}
+
+/** Every saved thread in a project, as stored. */
+export function readProjectThreads(projectId: string): StoredThread[] {
+ return readRawThreads(projectId).filter(isStoredThread);
+}
+
/** Replace a project's stored thread list. */
export function writeProjectThreads(projectId: string, threads: StoredThread[]): void {
+ writeRawThreads(projectId, threads);
+}
+
+/** The chat the panel reopens on, per project. */
+export function readActiveChat(projectId: string): string | null {
+ if (memory) return memory.active.get(projectId) ?? null;
try {
- localStorage.setItem(threadsKey(projectId), JSON.stringify(threads));
+ return localStorage.getItem(activeChatKey(projectId));
} catch {
- // Storage full/blocked — history just won't persist.
+ return null;
+ }
+}
+
+export function writeActiveChat(projectId: string, threadId: string): void {
+ if (memory) {
+ memory.active.set(projectId, threadId);
+ return;
+ }
+ try {
+ localStorage.setItem(activeChatKey(projectId), threadId);
+ } catch {
+ // Storage full/blocked — the open chat just won't be remembered.
}
}
@@ -59,6 +108,11 @@ export function readThreadIds(projectId: string): Set<string> {
/** Drop a project's chat history and active-thread pointer — called when the
* project itself is deleted, so no stale thread or its renders survive it. */
export function clearProjectThreads(projectId: string): void {
+ if (memory) {
+ memory.threads.delete(projectId);
+ memory.active.delete(projectId);
+ return;
+ }
try {
localStorage.removeItem(threadsKey(projectId));
localStorage.removeItem(activeChatKey(projectId));
diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.ts
index 41877e24..74152f99 100644
--- a/site/src/cut/server/cloud/sharedView.ts
+++ b/site/src/cut/server/cloud/sharedView.ts
@@ -51,6 +51,17 @@ async function ownerProject(share: ShareRow) {
return prisma.cutProject.findFirst({ where: { id: share.projectId, userId: share.userId } });
}
+/** What the share offers a viewer. Chat drops out when the owner's project has
+ * no threads: there is nothing to open, so the viewer gets no chat button and
+ * no panel rather than an empty conversation. */
+async function offeredFeatures(view: ShareView): Promise<ShareFeatures> {
+ if (!view.features.chat) return view.features;
+ const threads = await prisma.cutChatThread.count({
+ where: { userId: view.share.userId, projectId: view.share.projectId },
+ });
+ return threads > 0 ? view.features : { ...view.features, chat: false };
+}
+
/** The asset set a viewer may see: everything playback needs (referenced by a
* clip), plus each optional surface's assets when that surface is shared.
* Untagged assets belong to the Media panel; origin-tagged ones to the
@@ -106,7 +117,7 @@ export const sharedView = {
projectId: view.share.projectId,
name: row.name,
access: view.share.access,
- features: view.features,
+ features: await offeredFeatures(view),
},
{ headers: shareCacheHeaders(view.share, row.updatedAt, { meta: true }) }
);