File size: 1,575 Bytes
e6ed1f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * Backend persistence for chat history.
 *
 * Single shared store at /data/conversations.json on the backend Space.
 * Frontend hydrates on mount and writes back on changes (debounced).
 * Last-write-wins; no auth beyond the Space-level Bearer.
 */
import type { Conversation } from "./chatStore";

const PROXY = "/api/proxy/conversations";

export type RemoteConversationsPayload = {
  conversations: Record<string, Conversation>;
  activeId: string | null;
  updatedAt?: number;
  version?: number;
};

export async function loadConversations(): Promise<RemoteConversationsPayload | null> {
  try {
    const res = await fetch(PROXY, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
    if (!res.ok) {
      console.warn("[sync] load failed", res.status);
      return null;
    }
    const data = (await res.json()) as RemoteConversationsPayload;
    return data;
  } catch (err) {
    console.warn("[sync] load error", err);
    return null;
  }
}

export async function saveConversations(
  payload: RemoteConversationsPayload,
  signal?: AbortSignal
): Promise<boolean> {
  try {
    const res = await fetch(PROXY, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      signal,
    });
    if (!res.ok) {
      console.warn("[sync] save failed", res.status);
      return false;
    }
    return true;
  } catch (err) {
    if ((err as { name?: string })?.name === "AbortError") return false;
    console.warn("[sync] save error", err);
    return false;
  }
}