| @@ -1,35 +1,15 @@ | ||
| 1 | 1 | import { buildToolMessages } from '@agent/lib/tool-messages'; |
| 2 | -import { isChangeSiteDesignWorkflowAvailable, makeId } from '@agent/lib/util'; | |
| 2 | +import { makeId } from '@agent/lib/util'; | |
| 3 | 3 | import { useStatusStore } from '@agent/state/status'; |
| 4 | 4 | import apiFetch from '@wordpress/api-fetch'; |
| 5 | -import { __ } from '@wordpress/i18n'; | |
| 6 | 5 | import { create } from 'zustand'; |
| 7 | 6 | import { createJSONStorage, devtools, persist } from 'zustand/middleware'; |
| 8 | 7 | |
| 9 | 8 | const { chatHistory } = window.extAgentData; |
| 10 | 9 | |
| 11 | -const welcomeMessage = [ | |
| 12 | - { | |
| 13 | - id: 1, | |
| 14 | - type: 'message', | |
| 15 | - details: { | |
| 16 | - role: 'assistant', | |
| 17 | - // translators: this is the initial message in the agent chat, welcoming the user. Keep it short and friendly and follow the same markdown format and emoji. | |
| 18 | - content: isChangeSiteDesignWorkflowAvailable() | |
| 19 | - ? __( | |
| 20 | - '#### Your site is ready 🎉\nWant to explore other website designs?', | |
| 21 | - 'extendify-local', | |
| 22 | - ) | |
| 23 | - : __( | |
| 24 | - '#### Your site is ready 🎉\nWant to explore other site colors?', | |
| 25 | - 'extendify-local', | |
| 26 | - ), | |
| 27 | - }, | |
| 28 | - }, | |
| 29 | -]; | |
| 30 | 10 | const state = (set, get) => ({ |
| 31 | - messages: chatHistory?.length ? chatHistory.toReversed() : welcomeMessage, | |
| 11 | + messages: chatHistory?.length ? chatHistory.toReversed() : [], | |
| 32 | 12 | // API messages, back to the last finished workflow. |
| 33 | 13 | getCurrentMessages: ({ includeTools = true } = {}) => { |
| 34 | 14 | const messages = []; |
| 35 | 15 | let foundUserMessage = false; |
| @@ -124,13 +104,23 @@ | ||
| 124 | 104 | clearMessages: () => set({ messages: [] }), |
| 125 | 105 | }); |
| 126 | 106 | |
| 127 | 107 | const path = '/extendify/v1/agent/chat-events'; |
| 108 | +let lastSave = Promise.resolve(); | |
| 128 | 109 | const storage = { |
| 129 | 110 | getItem: async () => await apiFetch({ path }), |
| 130 | - setItem: async (_name, state) => | |
| 131 | - await apiFetch({ path, method: 'POST', data: { state } }), | |
| 111 | + setItem: (_name, state) => { | |
| 112 | + lastSave = apiFetch({ path, method: 'POST', data: { state } }); | |
| 113 | + return lastSave; | |
| 114 | + }, | |
| 132 | 115 | }; |
| 116 | + | |
| 117 | +// Await before navigating — an aborted in-flight save loses the newest messages. | |
| 118 | +export const flushChatStorage = (timeout = 5000) => | |
| 119 | + Promise.race([ | |
| 120 | + lastSave.catch(() => null), | |
| 121 | + new Promise((resolve) => setTimeout(resolve, timeout)), | |
| 122 | + ]); | |
| 133 | 123 | |
| 134 | 124 | export const useChatStore = create()( |
| 135 | 125 | persist(devtools(state, { name: 'Extendify Agent Chat' }), { |
| 136 | 126 | name: `extendify-agent-chat-${window.extSharedData.siteId}`, |