storage.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // coversations is stored in localStorage
  2. // format: { [convId]: { id: string, lastModified: number, messages: [...] } }
  3. import { CONFIG_DEFAULT } from '../Config';
  4. import { Conversation, Message, TimingReport } from './types';
  5. import Dexie, { Table } from 'dexie';
  6. const event = new EventTarget();
  7. type CallbackConversationChanged = (convId: string) => void;
  8. let onConversationChangedHandlers: [
  9. CallbackConversationChanged,
  10. EventListener,
  11. ][] = [];
  12. const dispatchConversationChange = (convId: string) => {
  13. event.dispatchEvent(
  14. new CustomEvent('conversationChange', { detail: { convId } })
  15. );
  16. };
  17. const db = new Dexie('LlamacppWebui') as Dexie & {
  18. conversations: Table<Conversation>;
  19. messages: Table<Message>;
  20. };
  21. // https://dexie.org/docs/Version/Version.stores()
  22. db.version(1).stores({
  23. // Unlike SQL, you don’t need to specify all properties but only the one you wish to index.
  24. conversations: '&id, lastModified',
  25. messages: '&id, convId, [convId+id], timestamp',
  26. });
  27. // convId is a string prefixed with 'conv-'
  28. const StorageUtils = {
  29. /**
  30. * manage conversations
  31. */
  32. async getAllConversations(): Promise<Conversation[]> {
  33. await migrationLStoIDB().catch(console.error); // noop if already migrated
  34. return (await db.conversations.toArray()).sort(
  35. (a, b) => b.lastModified - a.lastModified
  36. );
  37. },
  38. /**
  39. * can return null if convId does not exist
  40. */
  41. async getOneConversation(convId: string): Promise<Conversation | null> {
  42. return (await db.conversations.where('id').equals(convId).first()) ?? null;
  43. },
  44. /**
  45. * get all message nodes in a conversation
  46. */
  47. async getMessages(convId: string): Promise<Message[]> {
  48. return await db.messages.where({ convId }).toArray();
  49. },
  50. /**
  51. * use in conjunction with getMessages to filter messages by leafNodeId
  52. * includeRoot: whether to include the root node in the result
  53. * if node with leafNodeId does not exist, return the path with the latest timestamp
  54. */
  55. filterByLeafNodeId(
  56. msgs: Readonly<Message[]>,
  57. leafNodeId: Message['id'],
  58. includeRoot: boolean
  59. ): Readonly<Message[]> {
  60. const res: Message[] = [];
  61. const nodeMap = new Map<Message['id'], Message>();
  62. for (const msg of msgs) {
  63. nodeMap.set(msg.id, msg);
  64. }
  65. let startNode: Message | undefined = nodeMap.get(leafNodeId);
  66. if (!startNode) {
  67. // if not found, we return the path with the latest timestamp
  68. let latestTime = -1;
  69. for (const msg of msgs) {
  70. if (msg.timestamp > latestTime) {
  71. startNode = msg;
  72. latestTime = msg.timestamp;
  73. }
  74. }
  75. }
  76. // traverse the path from leafNodeId to root
  77. // startNode can never be undefined here
  78. let currNode: Message | undefined = startNode;
  79. while (currNode) {
  80. if (currNode.type !== 'root' || (currNode.type === 'root' && includeRoot))
  81. res.push(currNode);
  82. currNode = nodeMap.get(currNode.parent ?? -1);
  83. }
  84. res.sort((a, b) => a.timestamp - b.timestamp);
  85. return res;
  86. },
  87. /**
  88. * create a new conversation with a default root node
  89. */
  90. async createConversation(name: string): Promise<Conversation> {
  91. const now = Date.now();
  92. const msgId = now;
  93. const conv: Conversation = {
  94. id: `conv-${now}`,
  95. lastModified: now,
  96. currNode: msgId,
  97. name,
  98. };
  99. await db.conversations.add(conv);
  100. // create a root node
  101. await db.messages.add({
  102. id: msgId,
  103. convId: conv.id,
  104. type: 'root',
  105. timestamp: now,
  106. role: 'system',
  107. content: '',
  108. parent: -1,
  109. children: [],
  110. });
  111. return conv;
  112. },
  113. /**
  114. * update the name of a conversation
  115. */
  116. async updateConversationName(convId: string, name: string): Promise<void> {
  117. await db.conversations.update(convId, {
  118. name,
  119. lastModified: Date.now(),
  120. });
  121. dispatchConversationChange(convId);
  122. },
  123. /**
  124. * if convId does not exist, throw an error
  125. */
  126. async appendMsg(
  127. msg: Exclude<Message, 'parent' | 'children'>,
  128. parentNodeId: Message['id']
  129. ): Promise<void> {
  130. if (msg.content === null) return;
  131. const { convId } = msg;
  132. await db.transaction('rw', db.conversations, db.messages, async () => {
  133. const conv = await StorageUtils.getOneConversation(convId);
  134. const parentMsg = await db.messages
  135. .where({ convId, id: parentNodeId })
  136. .first();
  137. // update the currNode of conversation
  138. if (!conv) {
  139. throw new Error(`Conversation ${convId} does not exist`);
  140. }
  141. if (!parentMsg) {
  142. throw new Error(
  143. `Parent message ID ${parentNodeId} does not exist in conversation ${convId}`
  144. );
  145. }
  146. await db.conversations.update(convId, {
  147. lastModified: Date.now(),
  148. currNode: msg.id,
  149. });
  150. // update parent
  151. await db.messages.update(parentNodeId, {
  152. children: [...parentMsg.children, msg.id],
  153. });
  154. // create message
  155. await db.messages.add({
  156. ...msg,
  157. parent: parentNodeId,
  158. children: [],
  159. });
  160. });
  161. dispatchConversationChange(convId);
  162. },
  163. /**
  164. * remove conversation by id
  165. */
  166. async remove(convId: string): Promise<void> {
  167. await db.transaction('rw', db.conversations, db.messages, async () => {
  168. await db.conversations.delete(convId);
  169. await db.messages.where({ convId }).delete();
  170. });
  171. dispatchConversationChange(convId);
  172. },
  173. // event listeners
  174. onConversationChanged(callback: CallbackConversationChanged) {
  175. const fn = (e: Event) => callback((e as CustomEvent).detail.convId);
  176. onConversationChangedHandlers.push([callback, fn]);
  177. event.addEventListener('conversationChange', fn);
  178. },
  179. offConversationChanged(callback: CallbackConversationChanged) {
  180. const fn = onConversationChangedHandlers.find(([cb, _]) => cb === callback);
  181. if (fn) {
  182. event.removeEventListener('conversationChange', fn[1]);
  183. }
  184. onConversationChangedHandlers = [];
  185. },
  186. // manage config
  187. getConfig(): typeof CONFIG_DEFAULT {
  188. const savedVal = JSON.parse(localStorage.getItem('config') || '{}');
  189. // to prevent breaking changes in the future, we always provide default value for missing keys
  190. return {
  191. ...CONFIG_DEFAULT,
  192. ...savedVal,
  193. };
  194. },
  195. setConfig(config: typeof CONFIG_DEFAULT) {
  196. localStorage.setItem('config', JSON.stringify(config));
  197. },
  198. getTheme(): string {
  199. return localStorage.getItem('theme') || 'auto';
  200. },
  201. setTheme(theme: string) {
  202. if (theme === 'auto') {
  203. localStorage.removeItem('theme');
  204. } else {
  205. localStorage.setItem('theme', theme);
  206. }
  207. },
  208. };
  209. export default StorageUtils;
  210. // Migration from localStorage to IndexedDB
  211. // these are old types, LS prefix stands for LocalStorage
  212. interface LSConversation {
  213. id: string; // format: `conv-{timestamp}`
  214. lastModified: number; // timestamp from Date.now()
  215. messages: LSMessage[];
  216. }
  217. interface LSMessage {
  218. id: number;
  219. role: 'user' | 'assistant' | 'system';
  220. content: string;
  221. timings?: TimingReport;
  222. }
  223. async function migrationLStoIDB() {
  224. if (localStorage.getItem('migratedToIDB')) return;
  225. const res: LSConversation[] = [];
  226. for (const key in localStorage) {
  227. if (key.startsWith('conv-')) {
  228. res.push(JSON.parse(localStorage.getItem(key) ?? '{}'));
  229. }
  230. }
  231. if (res.length === 0) return;
  232. await db.transaction('rw', db.conversations, db.messages, async () => {
  233. let migratedCount = 0;
  234. for (const conv of res) {
  235. const { id: convId, lastModified, messages } = conv;
  236. const firstMsg = messages[0];
  237. const lastMsg = messages.at(-1);
  238. if (messages.length < 2 || !firstMsg || !lastMsg) {
  239. console.log(
  240. `Skipping conversation ${convId} with ${messages.length} messages`
  241. );
  242. continue;
  243. }
  244. const name = firstMsg.content ?? '(no messages)';
  245. await db.conversations.add({
  246. id: convId,
  247. lastModified,
  248. currNode: lastMsg.id,
  249. name,
  250. });
  251. const rootId = messages[0].id - 2;
  252. await db.messages.add({
  253. id: rootId,
  254. convId: convId,
  255. type: 'root',
  256. timestamp: rootId,
  257. role: 'system',
  258. content: '',
  259. parent: -1,
  260. children: [firstMsg.id],
  261. });
  262. for (let i = 0; i < messages.length; i++) {
  263. const msg = messages[i];
  264. await db.messages.add({
  265. ...msg,
  266. type: 'text',
  267. convId: convId,
  268. timestamp: msg.id,
  269. parent: i === 0 ? rootId : messages[i - 1].id,
  270. children: i === messages.length - 1 ? [] : [messages[i + 1].id],
  271. });
  272. }
  273. migratedCount++;
  274. console.log(
  275. `Migrated conversation ${convId} with ${messages.length} messages`
  276. );
  277. }
  278. console.log(
  279. `Migrated ${migratedCount} conversations from localStorage to IndexedDB`
  280. );
  281. localStorage.setItem('migratedToIDB', '1');
  282. });
  283. }