File size: 7,098 Bytes
ca51841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c43b369
 
 
 
 
 
 
 
 
ca51841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// LocalStorage keys
const KEYS = {
  SETTINGS: 'lw_settings',
  CONVERSATIONS: 'lw_conversations',
  CURRENT_CONV: 'lw_current_conv',
  MODEL_CAPS: 'lw_model_caps',
  AVAILABLE_MODELS: 'lw_available_models',
  MODEL_SELECTIONS: 'lw_model_selections',
};

const DEFAULT_SETTINGS = {
  apiKey: '',
  baseUrl: 'http://127.0.0.1:8000',
  theme: 'dark',
  contextLimitTokens: 4096,
  contextResetThresholdPercent: 85,
};

export function normalizeBaseUrl(baseUrl) {
  const raw = String(baseUrl || '').trim();
  if (!raw) return DEFAULT_SETTINGS.baseUrl;
  return raw.replace(/\/+$/, '');
}

function isCapabilityRecord(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
  return ['text', 'image', 'audio'].some((key) => key in value);
}

function isLegacyCapabilityMap(value) {
  if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
  const entries = Object.values(value);
  return entries.length > 0 && entries.every(isCapabilityRecord);
}

function normalizeSettings(settings = {}) {
  const merged = { ...DEFAULT_SETTINGS, ...settings };
  const contextLimitTokens = Number(merged.contextLimitTokens);
  const contextResetThresholdPercent = Number(merged.contextResetThresholdPercent);

  merged.baseUrl = normalizeBaseUrl(merged.baseUrl);
  merged.contextLimitTokens = Number.isFinite(contextLimitTokens) && contextLimitTokens >= 1024
    ? Math.round(contextLimitTokens)
    : DEFAULT_SETTINGS.contextLimitTokens;

  merged.contextResetThresholdPercent = Number.isFinite(contextResetThresholdPercent)
    ? Math.min(95, Math.max(50, Math.round(contextResetThresholdPercent)))
    : DEFAULT_SETTINGS.contextResetThresholdPercent;

  return merged;
}

function load(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    return raw ? JSON.parse(raw) : fallback;
  } catch {
    return fallback;
  }
}

function save(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (e) {
    if (e?.name === 'QuotaExceededError' || e?.code === 22) {
      console.warn('[store] localStorage quota exceeded — conversation not persisted');
    } else {
      throw e;
    }
  }
}

function uuid() {
  return crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2) + Date.now().toString(36);
}

export const store = {
  getSettings() {
    return normalizeSettings(load(KEYS.SETTINGS, {}));
  },

  saveSettings(settings) {
    save(KEYS.SETTINGS, normalizeSettings(settings));
  },

  getConversations() {
    return load(KEYS.CONVERSATIONS, []);
  },

  saveConversations(conversations) {
    save(KEYS.CONVERSATIONS, conversations);
  },

  getCurrentConversationId() {
    return localStorage.getItem(KEYS.CURRENT_CONV) || null;
  },

  setCurrentConversationId(id) {
    if (id) {
      localStorage.setItem(KEYS.CURRENT_CONV, id);
    } else {
      localStorage.removeItem(KEYS.CURRENT_CONV);
    }
  },

  getCurrentConversation() {
    const id = this.getCurrentConversationId();
    if (!id) return null;
    const convs = this.getConversations();
    return convs.find(c => c.id === id) || null;
  },

  getAvailableModels(baseUrl = this.getSettings().baseUrl) {
    const catalogs = load(KEYS.AVAILABLE_MODELS, {});
    const list = catalogs[normalizeBaseUrl(baseUrl)];
    return Array.isArray(list) ? [...new Set(list.filter(Boolean))].sort() : [];
  },

  saveAvailableModels(baseUrl, models) {
    const catalogs = load(KEYS.AVAILABLE_MODELS, {});
    catalogs[normalizeBaseUrl(baseUrl)] = Array.isArray(models)
      ? [...new Set(models.filter(Boolean))].sort()
      : [];
    save(KEYS.AVAILABLE_MODELS, catalogs);
  },

  getCurrentModel(baseUrl = this.getSettings().baseUrl) {
    const selections = load(KEYS.MODEL_SELECTIONS, {});
    const selected = selections[normalizeBaseUrl(baseUrl)];
    return typeof selected === 'string' ? selected : '';
  },

  setCurrentModel(baseUrl, modelId) {
    const selections = load(KEYS.MODEL_SELECTIONS, {});
    const normalizedUrl = normalizeBaseUrl(baseUrl);
    if (modelId) {
      selections[normalizedUrl] = modelId;
    } else {
      delete selections[normalizedUrl];
    }
    save(KEYS.MODEL_SELECTIONS, selections);
  },

  getModelCapabilities(baseUrl = this.getSettings().baseUrl) {
    const raw = load(KEYS.MODEL_CAPS, {});
    if (isLegacyCapabilityMap(raw)) return raw;

    const caps = raw[normalizeBaseUrl(baseUrl)];
    return caps && typeof caps === 'object' && !Array.isArray(caps) ? caps : {};
  },

  saveModelCapabilities(baseUrlOrCaps, maybeCaps) {
    if (maybeCaps === undefined) {
      save(KEYS.MODEL_CAPS, baseUrlOrCaps);
      return;
    }

    const raw = load(KEYS.MODEL_CAPS, {});
    const nested = isLegacyCapabilityMap(raw) ? {} : raw;
    nested[normalizeBaseUrl(baseUrlOrCaps)] = maybeCaps;
    save(KEYS.MODEL_CAPS, nested);
  },

  createConversation(model) {
    const conv = {
      id: uuid(),
      title: 'New Chat',
      model: model || '',
      messages: [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    const convs = this.getConversations();
    convs.unshift(conv);
    this.saveConversations(convs);
    return conv;
  },

  addMessage(convId, message) {
    const convs = this.getConversations();
    const idx = convs.findIndex(c => c.id === convId);
    if (idx === -1) return;
    convs[idx].messages.push(message);
    convs[idx].updatedAt = new Date().toISOString();
    this.saveConversations(convs);
  },

  updateLastAssistantMessage(convId, content) {
    const convs = this.getConversations();
    const idx = convs.findIndex(c => c.id === convId);
    if (idx === -1) return;
    const msgs = convs[idx].messages;
    // Find last assistant message
    for (let i = msgs.length - 1; i >= 0; i--) {
      if (msgs[i].role === 'assistant') {
        msgs[i].content = content;
        msgs[i].timestamp = new Date().toISOString();
        break;
      }
    }
    convs[idx].updatedAt = new Date().toISOString();
    this.saveConversations(convs);
  },

  clearMessages(convId) {
    const convs = this.getConversations();
    const idx = convs.findIndex(c => c.id === convId);
    if (idx === -1) return;
    convs[idx].messages = [];
    convs[idx].updatedAt = new Date().toISOString();
    this.saveConversations(convs);
  },

  deleteConversation(convId) {
    let convs = this.getConversations();
    convs = convs.filter(c => c.id !== convId);
    this.saveConversations(convs);
    if (this.getCurrentConversationId() === convId) {
      this.setCurrentConversationId(convs[0]?.id || null);
    }
  },

  updateConversationTitle(convId, title) {
    const convs = this.getConversations();
    const idx = convs.findIndex(c => c.id === convId);
    if (idx === -1) return;
    convs[idx].title = title;
    this.saveConversations(convs);
  },

  updateConversationModel(convId, model) {
    const convs = this.getConversations();
    const idx = convs.findIndex(c => c.id === convId);
    if (idx === -1) return;
    convs[idx].model = model;
    this.saveConversations(convs);
  },
};