94 lines
2.4 KiB
Plaintext
94 lines
2.4 KiB
Plaintext
/**
|
|
* useConversations — Conversation CRUD and history list management
|
|
*
|
|
* Manages the full array of all conversations. Persisted to storage.
|
|
* Provides create, delete, update, and query operations.
|
|
*/
|
|
|
|
import type { Conversation, WorkflowId } from '@/types/index'
|
|
import { STORAGE_KEYS, generateId } from '@/constants/index'
|
|
import { useStorage } from './useStorage'
|
|
|
|
export function useConversations() {
|
|
const { loadValue, saveValue } = useStorage()
|
|
|
|
// All conversations loaded from persistence
|
|
const conversations = ref<Conversation[]>(
|
|
loadValue<Conversation[]>(STORAGE_KEYS.CONVERSATIONS, [])
|
|
)
|
|
|
|
/**
|
|
* Persist the current conversations array to storage.
|
|
*/
|
|
function persist(): void {
|
|
saveValue(STORAGE_KEYS.CONVERSATIONS, conversations.value)
|
|
}
|
|
|
|
/**
|
|
* Create a new empty conversation with the given workflow.
|
|
*/
|
|
function createConversation(workflowId: WorkflowId, title?: string): Conversation {
|
|
const now = Date.now()
|
|
const conversation: Conversation = {
|
|
id: generateId(),
|
|
title: title ?? '新对话',
|
|
workflowId: workflowId,
|
|
messages: [],
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
}
|
|
conversations.value.unshift(conversation)
|
|
persist()
|
|
return conversation
|
|
}
|
|
|
|
/**
|
|
* Delete a conversation by ID.
|
|
*/
|
|
function deleteConversation(id: string): void {
|
|
conversations.value = conversations.value.filter((c) => c.id !== id)
|
|
persist()
|
|
}
|
|
|
|
/**
|
|
* Update a conversation's title.
|
|
*/
|
|
function updateConversationTitle(id: string, title: string): void {
|
|
const conv = conversations.value.find((c) => c.id === id)
|
|
if (conv) {
|
|
conv.title = title
|
|
conv.updatedAt = Date.now()
|
|
persist()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a conversation by ID.
|
|
*/
|
|
function getConversation(id: string): Conversation | undefined {
|
|
return conversations.value.find((c) => c.id === id)
|
|
}
|
|
|
|
/**
|
|
* Update a conversation's messages and timestamp.
|
|
* Used after adding/removing messages.
|
|
*/
|
|
function saveConversation(conversation: Conversation): void {
|
|
const index = conversations.value.findIndex((c) => c.id === conversation.id)
|
|
if (index !== -1) {
|
|
conversations.value[index] = conversation
|
|
persist()
|
|
}
|
|
}
|
|
|
|
return {
|
|
conversations,
|
|
createConversation,
|
|
deleteConversation,
|
|
updateConversationTitle,
|
|
getConversation,
|
|
saveConversation,
|
|
persist,
|
|
}
|
|
}
|