storage.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. * if convId does not exist, throw an error
  115. */
  116. async appendMsg(
  117. msg: Exclude<Message, 'parent' | 'children'>,
  118. parentNodeId: Message['id']
  119. ): Promise<void> {
  120. if (msg.content === null) return;
  121. const { convId } = msg;
  122. await db.transaction('rw', db.conversations, db.messages, async () => {
  123. const conv = await StorageUtils.getOneConversation(convId);
  124. const parentMsg = await db.messages
  125. .where({ convId, id: parentNodeId })
  126. .first();
  127. // update the currNode of conversation
  128. if (!conv) {
  129. throw new Error(`Conversation ${convId} does not exist`);
  130. }
  131. if (!parentMsg) {
  132. throw new Error(
  133. `Parent message ID ${parentNodeId} does not exist in conversation ${convId}`
  134. );
  135. }
  136. await db.conversations.update(convId, {
  137. lastModified: Date.now(),
  138. currNode: msg.id,
  139. });
  140. // update parent
  141. await db.messages.update(parentNodeId, {
  142. children: [...parentMsg.children, msg.id],
  143. });
  144. // create message
  145. await db.messages.add({
  146. ...msg,
  147. parent: parentNodeId,
  148. children: [],
  149. });
  150. });
  151. dispatchConversationChange(convId);
  152. },
  153. /**
  154. * remove conversation by id
  155. */
  156. async remove(convId: string): Promise<void> {
  157. await db.transaction('rw', db.conversations, db.messages, async () => {
  158. await db.conversations.delete(convId);
  159. await db.messages.where({ convId }).delete();
  160. });
  161. dispatchConversationChange(convId);
  162. },
  163. // event listeners
  164. onConversationChanged(callback: CallbackConversationChanged) {
  165. const fn = (e: Event) => callback((e as CustomEvent).detail.convId);
  166. onConversationChangedHandlers.push([callback, fn]);
  167. event.addEventListener('conversationChange', fn);
  168. },
  169. offConversationChanged(callback: CallbackConversationChanged) {
  170. const fn = onConversationChangedHandlers.find(([cb, _]) => cb === callback);
  171. if (fn) {
  172. event.removeEventListener('conversationChange', fn[1]);
  173. }
  174. onConversationChangedHandlers = [];
  175. },
  176. // manage config
  177. getConfig(): typeof CONFIG_DEFAULT {
  178. const savedVal = JSON.parse(localStorage.getItem('config') || '{}');
  179. // to prevent breaking changes in the future, we always provide default value for missing keys
  180. return {
  181. ...CONFIG_DEFAULT,
  182. ...savedVal,
  183. };
  184. },
  185. setConfig(config: typeof CONFIG_DEFAULT) {
  186. localStorage.setItem('config', JSON.stringify(config));
  187. },
  188. getTheme(): string {
  189. return localStorage.getItem('theme') || 'auto';
  190. },
  191. setTheme(theme: string) {
  192. if (theme === 'auto') {
  193. localStorage.removeItem('theme');
  194. } else {
  195. localStorage.setItem('theme', theme);
  196. }
  197. },
  198. };
  199. export default StorageUtils;
  200. // Migration from localStorage to IndexedDB
  201. // these are old types, LS prefix stands for LocalStorage
  202. interface LSConversation {
  203. id: string; // format: `conv-{timestamp}`
  204. lastModified: number; // timestamp from Date.now()
  205. messages: LSMessage[];
  206. }
  207. interface LSMessage {
  208. id: number;
  209. role: 'user' | 'assistant' | 'system';
  210. content: string;
  211. timings?: TimingReport;
  212. }
  213. async function migrationLStoIDB() {
  214. if (localStorage.getItem('migratedToIDB')) return;
  215. const res: LSConversation[] = [];
  216. for (const key in localStorage) {
  217. if (key.startsWith('conv-')) {
  218. res.push(JSON.parse(localStorage.getItem(key) ?? '{}'));
  219. }
  220. }
  221. if (res.length === 0) return;
  222. await db.transaction('rw', db.conversations, db.messages, async () => {
  223. let migratedCount = 0;
  224. for (const conv of res) {
  225. const { id: convId, lastModified, messages } = conv;
  226. const firstMsg = messages[0];
  227. const lastMsg = messages.at(-1);
  228. if (messages.length < 2 || !firstMsg || !lastMsg) {
  229. console.log(
  230. `Skipping conversation ${convId} with ${messages.length} messages`
  231. );
  232. continue;
  233. }
  234. const name = firstMsg.content ?? '(no messages)';
  235. await db.conversations.add({
  236. id: convId,
  237. lastModified,
  238. currNode: lastMsg.id,
  239. name,
  240. });
  241. const rootId = messages[0].id - 2;
  242. await db.messages.add({
  243. id: rootId,
  244. convId: convId,
  245. type: 'root',
  246. timestamp: rootId,
  247. role: 'system',
  248. content: '',
  249. parent: -1,
  250. children: [firstMsg.id],
  251. });
  252. for (let i = 0; i < messages.length; i++) {
  253. const msg = messages[i];
  254. await db.messages.add({
  255. ...msg,
  256. type: 'text',
  257. convId: convId,
  258. timestamp: msg.id,
  259. parent: i === 0 ? rootId : messages[i - 1].id,
  260. children: i === messages.length - 1 ? [] : [messages[i + 1].id],
  261. });
  262. }
  263. migratedCount++;
  264. console.log(
  265. `Migrated conversation ${convId} with ${messages.length} messages`
  266. );
  267. }
  268. console.log(
  269. `Migrated ${migratedCount} conversations from localStorage to IndexedDB`
  270. );
  271. localStorage.setItem('migratedToIDB', '1');
  272. });
  273. }