forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.ts
More file actions
398 lines (331 loc) · 10.1 KB
/
Copy pathstorage.ts
File metadata and controls
398 lines (331 loc) · 10.1 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { MESSAGE_STATUS, STORAGE_KEYS } from '../../constants'
import type { PlaygroundConfig, ParameterEnabled, Message } from '../../types'
import {
finalizeMessage,
isAssistantMessagePending,
sanitizeMessagesOnLoad,
} from '../message/message-streaming-utils'
import { completeAssistantTiming } from '../message/message-timing-utils'
import { hasMessageContent } from '../message/message-utils'
import {
MAX_LOADED_MESSAGE_CHARS,
MAX_LOADED_MESSAGES_CHARS,
MAX_STORED_MESSAGES,
MAX_STORED_MESSAGES_BYTES,
STORAGE_VERSION,
messagesSchema,
parameterEnabledSchema,
playgroundConfigSchema,
} from './storage-schema'
type StoredEnvelope<T> = {
version: number
data: T
}
const TRUNCATED_CONTENT_SUFFIX = '\n\n[...]'
const MIN_PREFIX_COLLAPSE_LENGTH = 2000
const MIN_REPEATED_SECTION_COUNT = 3
const SECTION_HEADING_LINE_PATTERN = /^#{2,6}\s+\d+\.\s+.+$/gm
function readStoredValue(key: string): unknown | null {
const saved = localStorage.getItem(key)
if (!saved) return null
return JSON.parse(saved) as unknown
}
function readStoredMessagesValue(): unknown | null {
const saved = localStorage.getItem(STORAGE_KEYS.MESSAGES)
if (!saved) return null
if (saved.length > MAX_STORED_MESSAGES_BYTES) {
localStorage.removeItem(STORAGE_KEYS.MESSAGES)
return null
}
return JSON.parse(saved) as unknown
}
function unwrapStoredValue(value: unknown): unknown {
if (!value || typeof value !== 'object') {
return value
}
if ('version' in value && 'data' in value) {
return (value as StoredEnvelope<unknown>).data
}
return value
}
function writeStoredValue<T>(key: string, data: T): void {
const payload: StoredEnvelope<T> = {
version: STORAGE_VERSION,
data,
}
localStorage.setItem(key, JSON.stringify(payload))
}
function trimMessages(messages: Message[]): Message[] {
if (messages.length <= MAX_STORED_MESSAGES) {
return messages
}
return messages.slice(-MAX_STORED_MESSAGES)
}
function getMessageSize(message: Message): number {
const versionsSize = message.versions.reduce(
(total, version) => total + version.content.length,
0
)
const reasoningSize = message.reasoning?.content.length ?? 0
return versionsSize + reasoningSize
}
function truncateText(text: string, maxLength: number): string {
if (text.length <= maxLength) {
return text
}
if (maxLength <= TRUNCATED_CONTENT_SUFFIX.length) {
return text.slice(0, maxLength)
}
return `${text.slice(0, maxLength - TRUNCATED_CONTENT_SUFFIX.length)}${TRUNCATED_CONTENT_SUFFIX}`
}
type SectionOccurrence = {
heading: string
index: number
}
function getSectionOccurrences(text: string): SectionOccurrence[] {
const occurrences: SectionOccurrence[] = []
const matches = text.matchAll(SECTION_HEADING_LINE_PATTERN)
for (const match of matches) {
const index = match.index
if (index === undefined) {
continue
}
occurrences.push({
heading: match[0],
index,
})
}
return occurrences
}
function getHeadingCounts(
occurrences: SectionOccurrence[]
): Map<string, number> {
const counts = new Map<string, number>()
for (const occurrence of occurrences) {
counts.set(occurrence.heading, (counts.get(occurrence.heading) ?? 0) + 1)
}
return counts
}
function findLastRepeatedSectionRunStart(text: string): number {
const occurrences = getSectionOccurrences(text)
const headingCounts = getHeadingCounts(occurrences)
const lastRepeatedIndexes: number[] = []
const seenHeadings = new Set<string>()
for (let index = occurrences.length - 1; index >= 0; index--) {
const occurrence = occurrences[index]
const count = headingCounts.get(occurrence.heading) ?? 0
if (
count < MIN_REPEATED_SECTION_COUNT ||
seenHeadings.has(occurrence.heading)
) {
continue
}
seenHeadings.add(occurrence.heading)
lastRepeatedIndexes.push(occurrence.index)
}
if (lastRepeatedIndexes.length === 0) {
return -1
}
return Math.min(...lastRepeatedIndexes)
}
function collapseRepeatedSectionSnapshots(text: string): string {
if (text.length < MIN_PREFIX_COLLAPSE_LENGTH) {
return text
}
const lastRepeatedRunStart = findLastRepeatedSectionRunStart(text)
if (lastRepeatedRunStart === -1) {
return text
}
return text.slice(lastRepeatedRunStart)
}
function normalizeStoredMessageForLoad(message: Message): Message {
let changed = false
const versions = message.versions.map((version) => {
const collapsedContent = collapseRepeatedSectionSnapshots(version.content)
const content = truncateText(collapsedContent, MAX_LOADED_MESSAGE_CHARS)
if (content === version.content && collapsedContent === version.content) {
return version
}
changed = true
return {
...version,
content,
}
})
const reasoning = message.reasoning
? {
...message.reasoning,
content: truncateText(
message.reasoning.content,
MAX_LOADED_MESSAGE_CHARS
),
}
: undefined
if (reasoning?.content !== message.reasoning?.content) {
changed = true
}
const normalized = changed ? { ...message, versions, reasoning } : message
if (!isAssistantMessagePending(normalized)) {
return normalized
}
const hasContent = hasMessageContent(normalized)
const hasReasoning = normalized.reasoning?.content.trim()
if (!hasContent && !hasReasoning) {
return normalized
}
const completedAt =
normalized.completedAt ??
normalized.reasoning?.completedAt ??
normalized.startedAt ??
normalized.createdAt ??
Date.now()
return completeAssistantTiming(
{
...finalizeMessage(normalized),
status: MESSAGE_STATUS.COMPLETE,
isReasoningStreaming: false,
},
completedAt
)
}
function trimMessagesByContentSize(messages: Message[]): Message[] {
let totalSize = 0
const result: Message[] = []
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index]
const messageSize = getMessageSize(message)
if (
result.length > 0 &&
totalSize + messageSize > MAX_LOADED_MESSAGES_CHARS
) {
break
}
totalSize += messageSize
result.push(message)
}
return result.reverse()
}
/**
* Load playground config from localStorage
*/
export function loadConfig(): Partial<PlaygroundConfig> {
try {
const saved = readStoredValue(STORAGE_KEYS.CONFIG)
if (!saved) return {}
return playgroundConfigSchema.parse(unwrapStoredValue(saved))
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load config:', error)
}
return {}
}
/**
* Save playground config to localStorage
*/
export function saveConfig(config: Partial<PlaygroundConfig>): void {
try {
const parsed = playgroundConfigSchema.parse(config)
writeStoredValue(STORAGE_KEYS.CONFIG, parsed)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save config:', error)
}
}
/**
* Load parameter enabled state from localStorage
*/
export function loadParameterEnabled(): Partial<ParameterEnabled> {
try {
const saved = readStoredValue(STORAGE_KEYS.PARAMETER_ENABLED)
if (!saved) return {}
return parameterEnabledSchema.parse(unwrapStoredValue(saved))
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load parameter enabled:', error)
}
return {}
}
/**
* Save parameter enabled state to localStorage
*/
export function saveParameterEnabled(
parameterEnabled: Partial<ParameterEnabled>
): void {
try {
const parsed = parameterEnabledSchema.parse(parameterEnabled)
writeStoredValue(STORAGE_KEYS.PARAMETER_ENABLED, parsed)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save parameter enabled:', error)
}
}
/**
* Load messages from localStorage
*/
export function loadMessages(): Message[] | null {
try {
const saved = readStoredMessagesValue()
if (!saved) return null
const parsed = messagesSchema.parse(unwrapStoredValue(saved)) as Message[]
const normalized = parsed.map(normalizeStoredMessageForLoad)
const normalizedChanged = normalized.some(
(message, index) => message !== parsed[index]
)
const trimmed = trimMessages(normalized)
const sizeTrimmed = trimMessagesByContentSize(trimmed)
const sanitized = sanitizeMessagesOnLoad(sizeTrimmed)
if (
normalizedChanged ||
trimmed !== normalized ||
sizeTrimmed !== trimmed ||
sanitized !== sizeTrimmed
) {
saveMessages(sanitized)
}
return sanitized
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to load messages:', error)
}
return null
}
/**
* Save messages to localStorage
*/
export function saveMessages(messages: Message[]): void {
try {
const trimmed = trimMessages(messages)
const parsed = messagesSchema.parse(trimmed) as Message[]
writeStoredValue(STORAGE_KEYS.MESSAGES, parsed)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to save messages:', error)
}
}
/**
* Clear all playground data
*/
export function clearPlaygroundData(): void {
try {
localStorage.removeItem(STORAGE_KEYS.CONFIG)
localStorage.removeItem(STORAGE_KEYS.PARAMETER_ENABLED)
localStorage.removeItem(STORAGE_KEYS.MESSAGES)
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to clear playground data:', error)
}
}