-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathai-assistant-state.tsx
More file actions
653 lines (566 loc) · 20.1 KB
/
Copy pathai-assistant-state.tsx
File metadata and controls
653 lines (566 loc) · 20.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
import { Chat, type UIMessage as MessageType } from '@ai-sdk/react'
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from 'ai'
import { DBSchema, IDBPDatabase, openDB } from 'idb'
import { debounce } from 'lodash'
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
import { v4 as uuidv4 } from 'uuid'
import { proxy, ref, snapshot, subscribe, useSnapshot } from 'valtio'
import { constructHeaders } from 'data/fetchers'
import { prepareMessagesForAPI } from 'lib/ai/message-utils'
import { BASE_PATH, IS_PLATFORM } from 'lib/constants'
import { LOCAL_STORAGE_KEYS } from 'common'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
type SuggestionsType = {
title: string
prompts?: { label: string; description: string }[]
}
export type AssistantMessageType = MessageType
export type SqlSnippet = string | { label: string; content: string }
export type AssistantModel = 'gpt-5.3-codex' | 'gpt-5.4-nano'
type ChatSession = {
id: string
name: string
messages: AssistantMessageType[]
createdAt: Date
updatedAt: Date
}
export type AiAssistantContext = {
projectRef?: string
orgSlug?: string
connectionString?: string
}
type AiAssistantData = {
initialInput: string
sqlSnippets?: SqlSnippet[]
suggestions?: SuggestionsType
tables: { schema: string; name: string }[]
chats: Record<string, ChatSession>
activeChatId?: string
model: AssistantModel
context: AiAssistantContext
}
// Data structure stored in IndexedDB
type StoredAiAssistantState = {
projectRef: string
activeChatId?: string
chats: Record<string, ChatSession>
model?: AssistantModel
}
const INITIAL_AI_ASSISTANT: AiAssistantData = {
initialInput: '',
sqlSnippets: undefined,
suggestions: undefined,
tables: [],
chats: {},
activeChatId: undefined,
model: 'gpt-5.3-codex',
context: {},
}
const DB_NAME = 'ai-assistant-db'
const DB_VERSION = 1
const STORE_NAME = 'assistantState'
interface AiAssistantDB extends DBSchema {
[STORE_NAME]: {
key: string
value: StoredAiAssistantState
}
}
async function openAiDb(): Promise<IDBPDatabase<AiAssistantDB>> {
return openDB<AiAssistantDB>(DB_NAME, DB_VERSION, {
upgrade(db) {
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'projectRef' })
}
},
})
}
async function getAiState(projectRef: string): Promise<StoredAiAssistantState | undefined> {
if (!projectRef) return undefined
try {
const db = await openAiDb()
return await db.get(STORE_NAME, projectRef)
} catch (error) {
console.error('Failed to get AI state from IndexedDB:', error)
return undefined
}
}
async function saveAiState(state: StoredAiAssistantState): Promise<void> {
if (!state.projectRef) return
try {
const db = await openAiDb()
await db.put(STORE_NAME, state)
} catch (error) {
console.error('Failed to save AI state to IndexedDB:', error)
}
}
async function clearStorage(): Promise<void> {
try {
const db = await openAiDb()
await db.clear(STORE_NAME)
} catch (error) {
console.error('Failed to clear AI state from IndexedDB:', error)
}
}
// Helper function to sanitize objects to ensure they're cloneable
// Issue due to addToolResult
function sanitizeForCloning(obj: any): any {
if (obj === null || obj === undefined) return obj
if (typeof obj !== 'object') return obj
return JSON.parse(JSON.stringify(obj))
}
// Helper function to load state from IndexedDB
async function loadFromIndexedDB(projectRef: string): Promise<StoredAiAssistantState | null> {
try {
const persistedState = await getAiState(projectRef)
if (persistedState) {
// Revive dates and sanitize message data
Object.values(persistedState.chats).forEach((chat: ChatSession) => {
if (chat && typeof chat === 'object') {
chat.createdAt = new Date(chat.createdAt)
chat.updatedAt = new Date(chat.updatedAt)
// Sanitize message parts to remove proxy objects
if (chat.messages) {
chat.messages.forEach((message: any) => {
if (message.parts) {
message.parts = message.parts.map((part: any) => sanitizeForCloning(part))
}
})
}
}
})
return persistedState
}
} catch (error) {
console.error('Error loading AI state from IndexedDB:', error)
}
return null
}
// Helper function to attempt migration from localStorage
async function tryMigrateFromLocalStorage(
projectRef: string
): Promise<StoredAiAssistantState | null> {
const stored = localStorage.getItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE(projectRef))
if (!stored) {
return null
}
let migratedState: StoredAiAssistantState | null = null
try {
const parsedFromLocalStorage = JSON.parse(stored, (key, value) => {
if ((key === 'createdAt' || key === 'updatedAt') && value) {
return new Date(value)
}
return value
})
if (parsedFromLocalStorage && typeof parsedFromLocalStorage.chats === 'object') {
migratedState = {
projectRef: projectRef,
activeChatId: parsedFromLocalStorage.activeChatId,
chats: parsedFromLocalStorage.chats,
model: parsedFromLocalStorage.model ?? INITIAL_AI_ASSISTANT.model,
}
} else {
console.warn('Data in localStorage is not in the expected format, ignoring.')
// Clean up invalid data
localStorage.removeItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE(projectRef))
}
} catch (error) {
console.error('Failed to parse state from localStorage:', error)
// Clear potentially corrupted data
localStorage.removeItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE(projectRef))
}
if (migratedState) {
try {
await saveAiState(migratedState)
localStorage.removeItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE(projectRef))
return migratedState
} catch (saveError) {
console.error('Failed to save migrated state to IndexedDB:', saveError)
return null
}
}
return null
}
// Helper function to ensure an active chat exists or initialize a new one
function ensureActiveChatOrInitialize(state: AiAssistantState) {
// Ensure an active chat exists after loading/migration
if (!state.activeChatId || !state.chats[state.activeChatId]) {
const chatIds = Object.keys(state.chats)
if (chatIds.length > 0) {
// Select the most recently updated chat
state.activeChatId = chatIds.sort(
(a, b) =>
(state.chats[b].updatedAt?.getTime() || 0) - (state.chats[a].updatedAt?.getTime() || 0)
)[0]
} else {
// If loaded/migrated state had no chats, create a new one
state.newChat()
}
}
}
function createChatInstance(
state: AiAssistantState,
options: { id: string; initialMessages: MessageType[] }
) {
return new Chat<MessageType>({
id: options.id,
messages: options.initialMessages.map((message) => sanitizeForCloning(message)),
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
transport: new DefaultChatTransport({
api: `${BASE_PATH}/api/ai/sql/generate-v4`,
fetch: async (url, init) => {
const response = await globalThis.fetch(url as RequestInfo, init)
const spanId = response.headers.get('x-braintrust-span-id')
if (spanId) {
state.pendingSpanIds[options.id] = spanId
}
return response
},
async prepareSendMessagesRequest({ messages, ...opts }) {
const cleanedMessages = prepareMessagesForAPI(messages)
const headerData = await constructHeaders()
const authorizationHeader = headerData.get('Authorization')
// Get the chat specific to this request to ensure we have the correct name
const chat = state.chats[options.id]
return {
...opts,
body: {
messages: cleanedMessages,
projectRef: state.context.projectRef,
connectionString: state.context.connectionString,
chatId: options.id,
chatName: chat?.name,
orgSlug: state.context.orgSlug,
context: state.context,
model: state.model,
...opts.body,
},
...(IS_PLATFORM ? { headers: { Authorization: authorizationHeader ?? '' } } : {}),
}
},
}),
async onToolCall({ toolCall }) {
if (toolCall.dynamic) {
return
}
if (toolCall.toolName === 'rename_chat') {
const { newName } = toolCall.input as { newName: string }
if (options.id && newName?.trim()) {
state.renameChat(options.id, newName.trim())
}
}
},
onFinish(result) {
// Sync messages back to state
const chatInstance = state.chatInstances[options.id]
if (chatInstance) {
const messages = chatInstance.messages
const chat = state.chats[options.id]
if (chat) {
chat.messages = messages as AssistantMessageType[]
chat.updatedAt = new Date()
}
// Associate pending span ID with the last assistant message
const pendingSpanId = state.pendingSpanIds[options.id]
if (pendingSpanId) {
const lastAssistantMsg = [...messages].reverse().find((m) => m.role === 'assistant')
if (lastAssistantMsg) {
state.messageSpanIds[lastAssistantMsg.id] = pendingSpanId
}
delete state.pendingSpanIds[options.id]
}
}
},
})
}
export const createAiAssistantState = (): AiAssistantState => {
// Initialize with defaults, loading happens asynchronously in the provider
const initialState = { ...INITIAL_AI_ASSISTANT }
const state: AiAssistantState = proxy({
...initialState, // Spread initial values directly
chatInstances: {},
pendingSpanIds: {},
messageSpanIds: {},
setContext: (context: Partial<AiAssistantContext>) => {
state.context = { ...state.context, ...context }
},
resetAiAssistantPanel: () => {
Object.assign(state, INITIAL_AI_ASSISTANT)
},
setModel: (model: AssistantModel) => {
state.model = model
},
// Chat management
get activeChat(): ChatSession | undefined {
return state.activeChatId ? state.chats[state.activeChatId] : undefined
},
newChat: (
options?: { name?: string; initialMessage?: string } & Partial<
Pick<AiAssistantData, 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>
>
) => {
const chatId = uuidv4()
const newChat: ChatSession = {
id: chatId,
name: options?.name ?? 'New chat',
messages: [],
createdAt: new Date(),
updatedAt: new Date(),
}
state.chats = {
...state.chats,
[chatId]: newChat,
}
state.activeChatId = chatId
// Create new chat instance
const chatInstance = createChatInstance(state, { id: chatId, initialMessages: [] })
state.chatInstances[chatId] = ref(chatInstance)
// If initialMessage is provided, append it to the chat instance
if (options?.initialMessage) {
chatInstance.sendMessage({
text: options.initialMessage,
})
}
// Update non-chat related state based on options, falling back to current state, then initial
state.initialInput = options?.initialInput ?? INITIAL_AI_ASSISTANT.initialInput
state.sqlSnippets = options?.sqlSnippets ?? INITIAL_AI_ASSISTANT.sqlSnippets
state.suggestions = options?.suggestions ?? INITIAL_AI_ASSISTANT.suggestions
state.tables = options?.tables ?? INITIAL_AI_ASSISTANT.tables
return chatId
},
selectChat: (id: string) => {
if (id !== state.activeChatId) {
state.activeChatId = id
const chat = state.chats[id]
if (chat) {
if (!state.chatInstances[id]) {
state.chatInstances[id] = ref(
createChatInstance(state, { id, initialMessages: chat.messages })
)
}
}
}
},
deleteChat: (id: string) => {
const { [id]: _, ...remainingChats } = state.chats
state.chats = remainingChats
if (id === state.activeChatId) {
const remainingChatIds = Object.keys(remainingChats)
state.activeChatId = remainingChatIds.length > 0 ? remainingChatIds[0] : undefined
if (state.activeChatId) {
const chat = state.chats[state.activeChatId]
if (!state.chatInstances[state.activeChatId]) {
state.chatInstances[state.activeChatId] = ref(
createChatInstance(state, { id: state.activeChatId, initialMessages: chat.messages })
)
}
}
}
},
renameChat: (id: string, name: string) => {
const chat = state.chats[id]
if (chat && chat.name !== name) {
chat.name = name
chat.updatedAt = new Date()
}
},
clearMessages: () => {
const chat = state.activeChat
if (chat) {
chat.messages = []
chat.updatedAt = new Date()
state.suggestions = undefined
state.sqlSnippets = []
state.initialInput = ''
}
},
deleteMessagesAfter: (id: string, { includeSelf = true } = {}) => {
const chat = state.activeChat
if (!chat) return
const messageIndex = chat.messages.findIndex((msg) => msg.id === id)
if (messageIndex === -1) return
// Delete all messages from the target message (optionally including) to the end
const startIndex = includeSelf ? messageIndex : messageIndex + 1
chat.messages.splice(startIndex)
chat.updatedAt = new Date()
},
saveMessage: (message: MessageType | MessageType[]) => {
const chat = state.activeChat
if (!chat) return
const incomingMessages = Array.isArray(message) ? message : [message]
const messagesToAdd: AssistantMessageType[] = []
incomingMessages.forEach((msg) => {
const index = chat.messages.findIndex((existing) => existing.id === msg.id)
if (index !== -1) {
state.updateMessage(msg)
} else {
messagesToAdd.push(msg as AssistantMessageType)
}
})
if (messagesToAdd.length > 0) {
chat.messages.push(...messagesToAdd)
chat.updatedAt = new Date()
}
},
updateMessage: (updatedMessage: MessageType) => {
const chat = state.activeChat
if (!chat) return
const messageIndex = chat.messages.findIndex((msg) => msg.id === updatedMessage.id)
if (messageIndex !== -1) {
chat.messages[messageIndex] = updatedMessage as AssistantMessageType
chat.updatedAt = new Date()
}
},
setSqlSnippets: (snippets: SqlSnippet[]) => {
state.sqlSnippets = snippets
},
clearSqlSnippets: () => {
state.sqlSnippets = undefined
state.suggestions = undefined
},
// --- New function to load persisted state ---
loadPersistedState: (persistedState: StoredAiAssistantState) => {
state.chats = persistedState.chats
state.activeChatId = persistedState.activeChatId
state.model = persistedState.model ?? INITIAL_AI_ASSISTANT.model
// Ensure an active chat exists after loading
if (!state.activeChat) {
const chatIds = Object.keys(state.chats)
if (chatIds.length > 0) {
// Select the most recently updated chat
state.activeChatId = chatIds.sort(
(a, b) =>
(state.chats[b].updatedAt?.getTime() || 0) -
(state.chats[a].updatedAt?.getTime() || 0)
)[0]
} else {
// If loaded state had no chats, create a new one
state.newChat()
}
}
// Initialize chat instance for the active chat
if (
state.activeChatId &&
state.chats[state.activeChatId] &&
!state.chatInstances[state.activeChatId]
) {
state.chatInstances[state.activeChatId] = ref(
createChatInstance(state, {
id: state.activeChatId,
initialMessages: state.chats[state.activeChatId].messages,
})
)
}
},
clearStorage: async () => {
await clearStorage()
},
})
return state
}
export type AiAssistantState = AiAssistantData & {
resetAiAssistantPanel: () => void
activeChat: ChatSession | undefined
chatInstances: Record<string, Chat<MessageType>>
pendingSpanIds: Record<string, string>
messageSpanIds: Record<string, string>
setContext: (context: Partial<AiAssistantContext>) => void
setModel: (model: AssistantModel) => void
newChat: (
options?: { name?: string; initialMessage?: string } & Partial<
Pick<AiAssistantData, 'initialInput' | 'sqlSnippets' | 'suggestions' | 'tables'>
>
) => string
selectChat: (id: string) => void
deleteChat: (id: string) => void
renameChat: (id: string, name: string) => void
clearMessages: () => void
deleteMessagesAfter: (id: string, options?: { includeSelf?: boolean }) => void
saveMessage: (message: MessageType | MessageType[]) => void
updateMessage: (message: MessageType) => void
setSqlSnippets: (snippets: SqlSnippet[]) => void
clearSqlSnippets: () => void
loadPersistedState: (persistedState: StoredAiAssistantState) => void
clearStorage: () => Promise<void>
}
export const AiAssistantStateContext = createContext<AiAssistantState>(createAiAssistantState())
export const AiAssistantStateContextProvider = ({ children }: PropsWithChildren) => {
const { data: project } = useSelectedProjectQuery()
// Initialize state. createAiAssistantState now just sets defaults.
const [state] = useState(() => createAiAssistantState())
// Effect to load state from IndexedDB on mount or projectRef change
useEffect(() => {
let isMounted = true
async function loadAndInitializeState() {
if (!project?.ref || typeof window === 'undefined') {
if (project?.ref === undefined) {
state.resetAiAssistantPanel()
}
return // Don't load if no projectRef or not in browser
}
let loadedState: StoredAiAssistantState | null = null
// 1. Try loading from IndexedDB
loadedState = await loadFromIndexedDB(project?.ref)
// 2. If not in IndexedDB, try migrating from localStorage
if (!loadedState) {
loadedState = await tryMigrateFromLocalStorage(project?.ref)
}
if (!isMounted) return // Component unmounted during async operations
// 3. If state was loaded or migrated, update the valtio state
if (loadedState) {
state.loadPersistedState(loadedState)
}
// 4. Ensure an active chat exists and handle URL overrides
ensureActiveChatOrInitialize(state)
}
loadAndInitializeState()
return () => {
isMounted = false
}
}, [project?.ref, state])
// Effect to save state to IndexedDB on changes
useEffect(() => {
if (typeof window !== 'undefined' && project?.ref) {
// Create a debounced version of saveAiState
const debouncedSaveAiState = debounce(saveAiState, 500)
const unsubscribe = subscribe(state, () => {
const snap = snapshot(state)
// Prepare state for IndexedDB
const stateToSave: StoredAiAssistantState = {
projectRef: project?.ref,
activeChatId: snap.activeChatId,
model: snap.model,
chats: snap.chats
? Object.entries(snap.chats).reduce((acc, [chatId, chat]) => {
// Limit messages before saving
return {
...acc,
[chatId]: {
...chat,
messages: chat.messages?.slice(-20) || [],
},
}
}, {})
: {},
}
debouncedSaveAiState(stateToSave)
})
// Clean up subscription and cancel any pending saves on unmount or projectRef change
return () => {
debouncedSaveAiState.cancel()
unsubscribe()
}
}
return undefined
}, [state, project?.ref])
return (
<AiAssistantStateContext.Provider value={state}>{children}</AiAssistantStateContext.Provider>
)
}
export const useAiAssistantStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) => {
const state = useContext(AiAssistantStateContext)
return useSnapshot(state, options)
}
export const useAiAssistantState = () => {
const state = useContext(AiAssistantStateContext)
return state
}