From 43c6c68238729037d4c13415dbf2f2ae2d7e5ecb Mon Sep 17 00:00:00 2001 From: mic Date: Thu, 22 Aug 2024 22:09:44 +0200 Subject: [PATCH 01/10] implemented a loop on exception to send a message to the tab --- mzta-background.js | 173 +++++++++++++++++++++++++++------------------ 1 file changed, 103 insertions(+), 70 deletions(-) diff --git a/mzta-background.js b/mzta-background.js index 733b0083..0a706398 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -167,23 +167,23 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ let createdTab = newWindow.tabs[0]; // Wait for tab loaded. - await new Promise(resolve => { - const tabIsLoaded = tab => { - return tab.status == "complete" && tab.url != "about:blank"; - }; - const listener = (tabId, changeInfo, updatedTab) => { - if (tabIsLoaded(updatedTab)) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - } - // Early exit if loaded already - if (tabIsLoaded(createdTab)) { - resolve(); - } else { - browser.tabs.onUpdated.addListener(listener); - } - }); + // await new Promise(resolve => { + // const tabIsLoaded = tab => { + // return tab.status == "complete" && tab.url != "about:blank"; + // }; + // const listener = (tabId, changeInfo, updatedTab) => { + // if (tabIsLoaded(updatedTab)) { + // browser.tabs.onUpdated.removeListener(listener); + // resolve(); + // } + // } + // // Early exit if loaded already + // if (tabIsLoaded(createdTab)) { + // resolve(); + // } else { + // browser.tabs.onUpdated.addListener(listener); + // } + // }); let pre_script = `let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`"; let mztaForceCompletionDesc="`+ browser.i18n.getMessage("chatgpt_force_completion") +`"; @@ -192,17 +192,28 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ let mztaPromptName="[`+ i18nConditionalGet(prompt_name) +`]"; `; - browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false }) - .then(async () => { - taLog.log("[ThunderAI] ChatGPT web interface script injected successfully"); - let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); - let mailMessageId = -1; - if(mailMessage) mailMessageId = mailMessage.id; - browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId}); - }) - .catch(err => { - console.error("[ThunderAI] ChatGPT web interface error injecting the script: ", err); - }); + let done1 = false; + + while(!done1){ + try { + browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false }) + .then(async () => { + taLog.log("[ThunderAI] ChatGPT web interface script injected successfully"); + let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); + let mailMessageId = -1; + if(mailMessage) mailMessageId = mailMessage.id; + browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId}); + }) + .catch(err => { + console.error("[ThunderAI] ChatGPT web interface error injecting the script: ", err); + }); + done1 = true; + } catch (error) { + console.error('[ThunderAI] Error sending message to ChatGPT Web Interface: ', error); + done1 = false; + } + await new Promise(resolve => setTimeout(resolve, 500)); + } break; // chatgpt_web case 'chatgpt_api': @@ -217,26 +228,26 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ createdWindowID = newWindow2.id; let createdTab2 = newWindow2.tabs[0]; - if(await isThunderbird128OrGreater()){ - // Wait for tab loaded. - await new Promise(resolve => { - const tabIsLoaded2 = tab => { - return tab.status == "complete" && tab.url != "about:blank"; - }; - const listener2 = (tabId, changeInfo, updatedTab) => { - if (tabIsLoaded2(updatedTab)) { - browser.tabs.onUpdated.removeListener(listener2); - resolve(); - } - } - // Early exit if loaded already - if (tabIsLoaded2(createdTab2)) { - resolve(); - } else { - browser.tabs.onUpdated.addListener(listener2); - } - }); - } + // if(await isThunderbird128OrGreater()){ + // // Wait for tab loaded. + // await new Promise(resolve => { + // const tabIsLoaded2 = tab => { + // return tab.status == "complete" && tab.url != "about:blank"; + // }; + // const listener2 = (tabId, changeInfo, updatedTab) => { + // if (tabIsLoaded2(updatedTab)) { + // browser.tabs.onUpdated.removeListener(listener2); + // resolve(); + // } + // } + // // Early exit if loaded already + // if (tabIsLoaded2(createdTab2)) { + // resolve(); + // } else { + // browser.tabs.onUpdated.addListener(listener2); + // } + // }); + // } let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); let mailMessageId2 = -1; @@ -252,7 +263,18 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ return; } - browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); + let done2 = false; + + while(!done2){ + try { + browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); + done2 = true; + } catch (error) { + console.error('[ThunderAI] Error sending message to OpenAI ChatGPI API: ', error); + done2 = false; + } + await new Promise(resolve => setTimeout(resolve, 500)); + } break; // chatgpt_api case 'ollama_api': @@ -267,26 +289,26 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ createdWindowID = newWindow3.id; let createdTab3 = newWindow3.tabs[0]; - if(await isThunderbird128OrGreater()){ + // if(await isThunderbird128OrGreater()){ // Wait for tab loaded. - await new Promise(resolve => { - const tabIsLoaded3 = tab => { - return tab.status == "complete" && tab.url != "about:blank"; - }; - const listener3 = (tabId, changeInfo, updatedTab) => { - if (tabIsLoaded3(updatedTab)) { - browser.tabs.onUpdated.removeListener(listener3); - resolve(); - } - } - // Early exit if loaded already - if (tabIsLoaded3(createdTab3)) { - resolve(); - } else { - browser.tabs.onUpdated.addListener(listener3); - } - }); - } + // await new Promise(resolve => { + // const tabIsLoaded3 = tab => { + // return tab.status == "complete" && tab.url != "about:blank"; + // }; + // const listener3 = (tabId, changeInfo, updatedTab) => { + // if (tabIsLoaded3(updatedTab)) { + // browser.tabs.onUpdated.removeListener(listener3); + // resolve(); + // } + // } + // // Early exit if loaded already + // if (tabIsLoaded3(createdTab3)) { + // resolve(); + // } else { + // browser.tabs.onUpdated.addListener(listener3); + // } + // }); + //} let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId); let mailMessageId3 = -1; @@ -301,8 +323,19 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_model')}); return; } - - browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); + + let done3 = false; + + while(!done3){ + try { + await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); + done3 = true; + } catch (error) { + console.error('[ThunderAI] Error sending message to Ollama API: ', error); + done3 = false; + } + await new Promise(resolve => setTimeout(resolve, 500)); + } break; // ollama_api } } From 1ab1da1b688cfa78afa222968053422e2c0bcab3 Mon Sep 17 00:00:00 2001 From: mic Date: Thu, 22 Aug 2024 22:17:02 +0200 Subject: [PATCH 02/10] fixed chatgpt web loop. see #117 --- mzta-background.js | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/mzta-background.js b/mzta-background.js index 0a706398..1e1a8af2 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -196,20 +196,15 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ while(!done1){ try { - browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false }) - .then(async () => { - taLog.log("[ThunderAI] ChatGPT web interface script injected successfully"); - let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); - let mailMessageId = -1; - if(mailMessage) mailMessageId = mailMessage.id; - browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId}); - }) - .catch(err => { - console.error("[ThunderAI] ChatGPT web interface error injecting the script: ", err); - }); + await browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false }); + let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); + let mailMessageId = -1; + if(mailMessage) mailMessageId = mailMessage.id; + browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId}); + taLog.log("[ThunderAI] ChatGPT Web script injected successfully"); done1 = true; } catch (error) { - console.error('[ThunderAI] Error sending message to ChatGPT Web Interface: ', error); + console.error('[ThunderAI] ChatGPT Web error injecting the script: ', error); done1 = false; } await new Promise(resolve => setTimeout(resolve, 500)); From 8071fe4f1612856049b34f8f68f3c71842448630 Mon Sep 17 00:00:00 2001 From: mic Date: Thu, 22 Aug 2024 22:20:32 +0200 Subject: [PATCH 03/10] error messages improved. see #117 --- mzta-background.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/mzta-background.js b/mzta-background.js index 1e1a8af2..8510a5f2 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -204,7 +204,8 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ taLog.log("[ThunderAI] ChatGPT Web script injected successfully"); done1 = true; } catch (error) { - console.error('[ThunderAI] ChatGPT Web error injecting the script: ', error); + console.error('[ThunderAI] [ChatGPT Web] Error connecting to the window chat: ', error); + console.error('[ThunderAI] [ChatGPT Web] trying again...'); done1 = false; } await new Promise(resolve => setTimeout(resolve, 500)); @@ -265,7 +266,8 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); done2 = true; } catch (error) { - console.error('[ThunderAI] Error sending message to OpenAI ChatGPI API: ', error); + console.error('[ThunderAI] [OpenAI ChatGPI API] Error connecting to the window chat: ', error); + console.error('[ThunderAI] [OpenAI ChatGPI API] trying again...'); done2 = false; } await new Promise(resolve => setTimeout(resolve, 500)); @@ -326,7 +328,8 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); done3 = true; } catch (error) { - console.error('[ThunderAI] Error sending message to Ollama API: ', error); + console.error('[ThunderAI] [Ollama API] Error connecting to the window chat: ', error); + console.error('[ThunderAI] [Ollama API] trying again...'); done3 = false; } await new Promise(resolve => setTimeout(resolve, 500)); From afa7815ebe8024ba592d7252923e85cb10dd345b Mon Sep 17 00:00:00 2001 From: mic Date: Thu, 22 Aug 2024 22:26:12 +0200 Subject: [PATCH 04/10] log messages improved. see #117 --- mzta-background.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/mzta-background.js b/mzta-background.js index 8510a5f2..aa039d1e 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -201,11 +201,12 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ let mailMessageId = -1; if(mailMessage) mailMessageId = mailMessage.id; browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId}); + taLog.log('[ChatGPT Web] Connection succeded!'); taLog.log("[ThunderAI] ChatGPT Web script injected successfully"); done1 = true; } catch (error) { - console.error('[ThunderAI] [ChatGPT Web] Error connecting to the window chat: ', error); - console.error('[ThunderAI] [ChatGPT Web] trying again...'); + taLog.warn('[ChatGPT Web] Error connecting to the window chat: ', error); + taLog.warn('[ChatGPT Web] Trying again...'); done1 = false; } await new Promise(resolve => setTimeout(resolve, 500)); @@ -264,10 +265,11 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ while(!done2){ try { browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); + taLog.log('[OpenAI ChatGPI] Connection succeded!'); done2 = true; } catch (error) { - console.error('[ThunderAI] [OpenAI ChatGPI API] Error connecting to the window chat: ', error); - console.error('[ThunderAI] [OpenAI ChatGPI API] trying again...'); + taLog.warn('[OpenAI ChatGPI API] Error connecting to the window chat: ', error); + taLog.warn('[OpenAI ChatGPI API] Trying again...'); done2 = false; } await new Promise(resolve => setTimeout(resolve, 500)); @@ -326,10 +328,11 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ while(!done3){ try { await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); + taLog.log('[Ollama API] Connection succeded!'); done3 = true; } catch (error) { - console.error('[ThunderAI] [Ollama API] Error connecting to the window chat: ', error); - console.error('[ThunderAI] [Ollama API] trying again...'); + taLog.warn('[Ollama API] Error connecting to the window chat: ', error); + taLog.warn('[Ollama API] Trying again...'); done3 = false; } await new Promise(resolve => setTimeout(resolve, 500)); From 25b84ba8b2b45f0ac2dd7da25bf2db7c0f382156 Mon Sep 17 00:00:00 2001 From: Mic Date: Fri, 23 Aug 2024 13:52:22 +0200 Subject: [PATCH 05/10] generateCallID method added --- js/mzta-utils.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/js/mzta-utils.js b/js/mzta-utils.js index 2e359c13..f3a34d3a 100644 --- a/js/mzta-utils.js +++ b/js/mzta-utils.js @@ -123,6 +123,16 @@ function compareThunderbirdVersions(v1, v2) { return 0; } +function generateCallID(length) { + const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + const charactersLength = characters.length; + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); + } + return result; +} + // The following methods are a modified version derived from https://github.com/ali-raheem/Aify/blob/13ff87583bc520fb80f555ab90a90c5c9df797a7/plugin/content_scripts/compose.js From 9698eb1d01ba9d523480d61a39cf0e4ce4a1ffd0 Mon Sep 17 00:00:00 2001 From: Mic Date: Fri, 23 Aug 2024 13:52:48 +0200 Subject: [PATCH 06/10] new internal messaging method in the ollama api call --- api_webchat/controller.js | 2 + mzta-background.js | 99 ++++++++++++++++++--------------------- 2 files changed, 47 insertions(+), 54 deletions(-) diff --git a/api_webchat/controller.js b/api_webchat/controller.js index d9b51b7d..75d73ec9 100644 --- a/api_webchat/controller.js +++ b/api_webchat/controller.js @@ -23,6 +23,7 @@ // Get the LLM to be used const urlParams = new URLSearchParams(window.location.search); const llm = urlParams.get('llm'); +const call_id = urlParams.get('call_id'); //console.log(">>>>>>>>>>> llm: " + llm); @@ -35,6 +36,7 @@ switch (llm) { worker = new Worker('model-worker-openai.js', { type: 'module' }); break; case "ollama_api": { + browser.runtime.sendMessage({command: "ollama_api_ready_"+call_id}); worker = new Worker('model-worker-ollama.js', { type: 'module' }); break; } diff --git a/mzta-background.js b/mzta-background.js index aa039d1e..999a7f86 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -20,7 +20,7 @@ import { mzta_script } from './js/mzta-chatgpt.js'; import { prefs_default } from './options/mzta-options-default.js'; import { mzta_Menus } from './js/mzta-menus.js'; import { taLogger } from './js/mzta-logger.js'; -import { getCurrentIdentity, getOriginalBody, replaceBody, setBody, i18nConditionalGet, isThunderbird128OrGreater } from './js/mzta-utils.js'; +import { getCurrentIdentity, getOriginalBody, replaceBody, setBody, i18nConditionalGet, generateCallID } from './js/mzta-utils.js'; var createdWindowID = null; var original_html = ''; @@ -278,65 +278,56 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ case 'ollama_api': // We are using the Ollama API - let newWindow3 = await browser.windows.create({ - url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type), + + taLog.log("Ollama API window opening..."); + + let rand_call_id = '_ollama_' + generateCallID(); + + await browser.windows.create({ + url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type+'&call_id='+rand_call_id), type: "popup", width: prefs.chatgpt_win_width, height: prefs.chatgpt_win_height }); - - createdWindowID = newWindow3.id; - let createdTab3 = newWindow3.tabs[0]; - - // if(await isThunderbird128OrGreater()){ - // Wait for tab loaded. - // await new Promise(resolve => { - // const tabIsLoaded3 = tab => { - // return tab.status == "complete" && tab.url != "about:blank"; - // }; - // const listener3 = (tabId, changeInfo, updatedTab) => { - // if (tabIsLoaded3(updatedTab)) { - // browser.tabs.onUpdated.removeListener(listener3); - // resolve(); - // } - // } - // // Early exit if loaded already - // if (tabIsLoaded3(createdTab3)) { - // resolve(); - // } else { - // browser.tabs.onUpdated.addListener(listener3); - // } - // }); - //} - - let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId); - let mailMessageId3 = -1; - if(mailMessage3) mailMessageId3 = mailMessage3.id; - - // check if the config is present, or give a message error - if (prefs.ollama_host == '') { - browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_host')}); - return; - } - if (prefs.ollama_model == '') { - browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_model')}); - return; - } - - let done3 = false; - while(!done3){ - try { - await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); - taLog.log('[Ollama API] Connection succeded!'); - done3 = true; - } catch (error) { - taLog.warn('[Ollama API] Error connecting to the window chat: ', error); - taLog.warn('[Ollama API] Trying again...'); - done3 = false; + browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => { + + if (message.command === "ollama_api_ready_"+rand_call_id) { + taLog.log("Ollama API window ready."); + + let newWindow = await browser.windows.get(message.window_id); + let createdTab3 = newWindow.tabs[0]; + + let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId); + let mailMessageId3 = -1; + if(mailMessage3) mailMessageId3 = mailMessage3.id; + + // check if the config is present, or give a message error + if (prefs.ollama_host == '') { + browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_host')}); + return; + } + if (prefs.ollama_model == '') { + browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_model')}); + return; + } + + let done3 = false; + + while(!done3){ + try { + await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); + taLog.log('[Ollama API] Connection succeded!'); + done3 = true; + } catch (error) { + taLog.warn('[Ollama API] Error connecting to the window chat: ', error); + taLog.warn('[Ollama API] Trying again...'); + done3 = false; + } + await new Promise(resolve => setTimeout(resolve, 500)); + } } - await new Promise(resolve => setTimeout(resolve, 500)); - } + }); break; // ollama_api } } From c104edbf9305cd190eab2fec15a5fbbd44e8f53e Mon Sep 17 00:00:00 2001 From: Mic Date: Fri, 23 Aug 2024 14:03:25 +0200 Subject: [PATCH 07/10] new internal communication system for openai api --- api_webchat/controller.js | 3 +- mzta-background.js | 98 ++++++++++++++++++--------------------- 2 files changed, 46 insertions(+), 55 deletions(-) diff --git a/api_webchat/controller.js b/api_webchat/controller.js index 75d73ec9..ea4da31a 100644 --- a/api_webchat/controller.js +++ b/api_webchat/controller.js @@ -33,10 +33,11 @@ let worker = null; switch (llm) { case "chatgpt_api": + browser.runtime.sendMessage({command: "openai_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id}); worker = new Worker('model-worker-openai.js', { type: 'module' }); break; case "ollama_api": { - browser.runtime.sendMessage({command: "ollama_api_ready_"+call_id}); + browser.runtime.sendMessage({command: "ollama_api_ready_" + call_id, window_id: (await browser.windows.getCurrent()).id}); worker = new Worker('model-worker-ollama.js', { type: 'module' }); break; } diff --git a/mzta-background.js b/mzta-background.js index 999a7f86..fc8074d1 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -215,65 +215,54 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ case 'chatgpt_api': // We are using the ChatGPT API - let newWindow2 = await browser.windows.create({ - url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type), + + let rand_call_id = '_openai_' + generateCallID(); + + await browser.windows.create({ + url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type+'&call_id='+rand_call_id), type: "popup", width: prefs.chatgpt_win_width, height: prefs.chatgpt_win_height }); - createdWindowID = newWindow2.id; - let createdTab2 = newWindow2.tabs[0]; + browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => { - // if(await isThunderbird128OrGreater()){ - // // Wait for tab loaded. - // await new Promise(resolve => { - // const tabIsLoaded2 = tab => { - // return tab.status == "complete" && tab.url != "about:blank"; - // }; - // const listener2 = (tabId, changeInfo, updatedTab) => { - // if (tabIsLoaded2(updatedTab)) { - // browser.tabs.onUpdated.removeListener(listener2); - // resolve(); - // } - // } - // // Early exit if loaded already - // if (tabIsLoaded2(createdTab2)) { - // resolve(); - // } else { - // browser.tabs.onUpdated.addListener(listener2); - // } - // }); - // } + if (message.command === "openai_api_ready_"+rand_call_id) { - let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); - let mailMessageId2 = -1; - if(mailMessage) mailMessageId2 = mailMessage.id; + let newWindow2 = await browser.windows.get(message.window_id); + let createdTab2 = newWindow2.tabs[0]; - // check if the config is present, or give a message error - if (prefs.chatgpt_api_key == '') { - browser.tabs.sendMessage(createdTab2.id, { command: "api_error", error: browser.i18n.getMessage('chatgpt_empty_apikey')}); - return; - } - if (prefs.chatgpt_model == '') { - browser.tabs.sendMessage(createdTab2.id, { command: "api_error", error: browser.i18n.getMessage('chatgpt_empty_model')}); - return; - } + let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); + let mailMessageId2 = -1; + if(mailMessage) mailMessageId2 = mailMessage.id; - let done2 = false; + // check if the config is present, or give a message error + if (prefs.chatgpt_api_key == '') { + browser.tabs.sendMessage(createdTab2.id, { command: "api_error", error: browser.i18n.getMessage('chatgpt_empty_apikey')}); + return; + } + if (prefs.chatgpt_model == '') { + browser.tabs.sendMessage(createdTab2.id, { command: "api_error", error: browser.i18n.getMessage('chatgpt_empty_model')}); + return; + } - while(!done2){ - try { - browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); - taLog.log('[OpenAI ChatGPI] Connection succeded!'); - done2 = true; - } catch (error) { - taLog.warn('[OpenAI ChatGPI API] Error connecting to the window chat: ', error); - taLog.warn('[OpenAI ChatGPI API] Trying again...'); - done2 = false; + let done2 = false; + + while(!done2){ + try { + browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); + taLog.log('[OpenAI ChatGPI] Connection succeded!'); + done2 = true; + } catch (error) { + taLog.warn('[OpenAI ChatGPI API] Error connecting to the window chat: ', error); + taLog.warn('[OpenAI ChatGPI API] Trying again...'); + done2 = false; + } + await new Promise(resolve => setTimeout(resolve, 500)); + } + browser.runtime.onMessage.removeListener(arguments.callee); } - await new Promise(resolve => setTimeout(resolve, 500)); - } + }); break; // chatgpt_api case 'ollama_api': @@ -281,10 +270,10 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ taLog.log("Ollama API window opening..."); - let rand_call_id = '_ollama_' + generateCallID(); + let rand_call_id2 = '_ollama_' + generateCallID(); await browser.windows.create({ - url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type+'&call_id='+rand_call_id), + url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type+'&call_id='+rand_call_id2), type: "popup", width: prefs.chatgpt_win_width, height: prefs.chatgpt_win_height @@ -292,15 +281,15 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => { - if (message.command === "ollama_api_ready_"+rand_call_id) { + if (message.command === "ollama_api_ready_"+rand_call_id2) { taLog.log("Ollama API window ready."); - let newWindow = await browser.windows.get(message.window_id); - let createdTab3 = newWindow.tabs[0]; + let newWindow3 = await browser.windows.get(message.window_id); + let createdTab3 = newWindow3.tabs[0]; let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId); let mailMessageId3 = -1; - if(mailMessage3) mailMessageId3 = mailMessage3.id; + if(mailMessage3) mailMessageId3 = mailMessage3.id; // check if the config is present, or give a message error if (prefs.ollama_host == '') { @@ -326,6 +315,7 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ } await new Promise(resolve => setTimeout(resolve, 500)); } + browser.runtime.onMessage.removeListener(arguments.callee); } }); break; // ollama_api From b9ad4a493709c8f7bc3e8532d002ff5f79f360fc Mon Sep 17 00:00:00 2001 From: mic Date: Fri, 23 Aug 2024 14:13:09 +0200 Subject: [PATCH 08/10] export fixed --- js/mzta-utils.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/mzta-utils.js b/js/mzta-utils.js index f3a34d3a..b3d81dfb 100644 --- a/js/mzta-utils.js +++ b/js/mzta-utils.js @@ -123,7 +123,7 @@ function compareThunderbirdVersions(v1, v2) { return 0; } -function generateCallID(length) { +export function generateCallID(length) { const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; const charactersLength = characters.length; From 687ac698a7b47526fa438be07ba4194ae9dbdd11 Mon Sep 17 00:00:00 2001 From: mic Date: Fri, 23 Aug 2024 14:29:23 +0200 Subject: [PATCH 09/10] ollama new internal messaging system fixed --- mzta-background.js | 54 +++++++++++++++------------------------------- 1 file changed, 17 insertions(+), 37 deletions(-) diff --git a/mzta-background.js b/mzta-background.js index fc8074d1..eaba461e 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -229,7 +229,7 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ if (message.command === "openai_api_ready_"+rand_call_id) { - let newWindow2 = await browser.windows.get(message.window_id); + let newWindow2 = await browser.windows.get(message.window_id, {populate: true}); let createdTab2 = newWindow2.tabs[0]; let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); @@ -246,20 +246,8 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ return; } - let done2 = false; - - while(!done2){ - try { - browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); - taLog.log('[OpenAI ChatGPI] Connection succeded!'); - done2 = true; - } catch (error) { - taLog.warn('[OpenAI ChatGPI API] Error connecting to the window chat: ', error); - taLog.warn('[OpenAI ChatGPI API] Trying again...'); - done2 = false; - } - await new Promise(resolve => setTimeout(resolve, 500)); - } + browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text}); + taLog.log('[OpenAI ChatGPI] Connection succeded!'); browser.runtime.onMessage.removeListener(arguments.callee); } }); @@ -279,45 +267,37 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ height: prefs.chatgpt_win_height }); - browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => { + const listener3 = async (message, sender, sendResponse) => { if (message.command === "ollama_api_ready_"+rand_call_id2) { taLog.log("Ollama API window ready."); - - let newWindow3 = await browser.windows.get(message.window_id); + taLog.log("message.window_id: " + message.window_id) + let newWindow3 = await browser.windows.get(message.window_id, {populate: true}); let createdTab3 = newWindow3.tabs[0]; - + taLog.log(">>>>>> createdTab3.id: " + createdTab3.id) let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId); let mailMessageId3 = -1; if(mailMessage3) mailMessageId3 = mailMessage3.id; + taLog.log(">>>>>> mailMessageId3: " + mailMessageId3) // check if the config is present, or give a message error if (prefs.ollama_host == '') { - browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_host')}); + await browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_host')}); return; } if (prefs.ollama_model == '') { - browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_model')}); + await browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_model')}); return; } - - let done3 = false; - while(!done3){ - try { - await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); - taLog.log('[Ollama API] Connection succeded!'); - done3 = true; - } catch (error) { - taLog.warn('[Ollama API] Error connecting to the window chat: ', error); - taLog.warn('[Ollama API] Trying again...'); - done3 = false; - } - await new Promise(resolve => setTimeout(resolve, 500)); - } - browser.runtime.onMessage.removeListener(arguments.callee); + await browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text}); + taLog.log('[Ollama API] Connection succeded!'); + browser.runtime.onMessage.removeListener(listener3); } - }); + } + + browser.runtime.onMessage.addListener(listener3); + break; // ollama_api } } From 47a4a8c5bce73affb6eb7005eb3b26709f95fdc3 Mon Sep 17 00:00:00 2001 From: mic Date: Fri, 23 Aug 2024 14:36:48 +0200 Subject: [PATCH 10/10] correctly closing the window --- api_webchat/messagesArea.js | 8 ++++---- js/mzta-chatgpt.js | 2 +- mzta-background.js | 27 ++++----------------------- 3 files changed, 9 insertions(+), 28 deletions(-) diff --git a/api_webchat/messagesArea.js b/api_webchat/messagesArea.js index 23707b2d..f2257f24 100644 --- a/api_webchat/messagesArea.js +++ b/api_webchat/messagesArea.js @@ -241,20 +241,20 @@ class MessagesArea extends HTMLElement { case "1": // do reply // console.log("[ThunderAI] (do reply) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment); await browser.runtime.sendMessage({command: "chatgpt_replyMessage", text: fullTextHTMLAtAssignment, tabId: promptData.tabId, mailMessageId: promptData.mailMessageId}); - browser.runtime.sendMessage({command: "chatgpt_close"}); + browser.runtime.sendMessage({command: "chatgpt_close", window_id: (await browser.windows.getCurrent()).id}); break; case "2": // replace text // console.log("[ThunderAI] (replace text) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment); await browser.runtime.sendMessage({command: "chatgpt_replaceSelectedText", text: fullTextHTMLAtAssignment, tabId: promptData.tabId, mailMessageId: promptData.mailMessageId}); - browser.runtime.sendMessage({command: "chatgpt_close"}); + browser.runtime.sendMessage({command: "chatgpt_close", window_id: (await browser.windows.getCurrent()).id}); break; } }); const closeButton = document.createElement('button'); closeButton.textContent = browser.i18n.getMessage("chatgpt_win_close"); - closeButton.addEventListener('click', () => { + closeButton.addEventListener('click', async () => { // console.log("[ThunderAI] (close) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment); - browser.runtime.sendMessage({command: "chatgpt_close"}); // close window + browser.runtime.sendMessage({command: "chatgpt_close", window_id: (await browser.windows.getCurrent()).id}); // close window }); if(promptData.action != 0) { actionButtons.appendChild(actionButton); } actionButtons.appendChild(closeButton); diff --git a/js/mzta-chatgpt.js b/js/mzta-chatgpt.js index fbe119e0..58c84fde 100644 --- a/js/mzta-chatgpt.js +++ b/js/mzta-chatgpt.js @@ -159,7 +159,7 @@ function addCustomDiv(prompt_action,tabId,mailMessageId) { case "0": // close window btn_ok.textContent = browser.i18n.getMessage("chatgpt_win_close"); btn_ok.onclick = async function() { - browser.runtime.sendMessage({command: "chatgpt_close"}); + browser.runtime.sendMessage({command: "chatgpt_close", window_id: mztaWinId}); }; break; case "1": // do reply diff --git a/mzta-background.js b/mzta-background.js index eaba461e..1a8e87cd 100644 --- a/mzta-background.js +++ b/mzta-background.js @@ -22,7 +22,6 @@ import { mzta_Menus } from './js/mzta-menus.js'; import { taLogger } from './js/mzta-logger.js'; import { getCurrentIdentity, getOriginalBody, replaceBody, setBody, i18nConditionalGet, generateCallID } from './js/mzta-utils.js'; -var createdWindowID = null; var original_html = ''; var modified_html = ''; @@ -58,7 +57,7 @@ messenger.runtime.onMessage.addListener(async (message, sender, sendResponse) => // openChatGPT(message.prompt,message.action,message.tabId); // return true; case 'chatgpt_close': - browser.windows.remove(createdWindowID).then(() => { + browser.windows.remove(message.window_id).then(() => { taLog.log("ChatGPT window closed successfully."); return true; }).catch((error) => { @@ -163,29 +162,11 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_ }); taLog.log("[ThunderAI] ChatGPT web interface script started..."); - createdWindowID = newWindow.id; let createdTab = newWindow.tabs[0]; + let newWindowId = newWindow.id; - // Wait for tab loaded. - // await new Promise(resolve => { - // const tabIsLoaded = tab => { - // return tab.status == "complete" && tab.url != "about:blank"; - // }; - // const listener = (tabId, changeInfo, updatedTab) => { - // if (tabIsLoaded(updatedTab)) { - // browser.tabs.onUpdated.removeListener(listener); - // resolve(); - // } - // } - // // Early exit if loaded already - // if (tabIsLoaded(createdTab)) { - // resolve(); - // } else { - // browser.tabs.onUpdated.addListener(listener); - // } - // }); - - let pre_script = `let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`"; + let pre_script = `let mztaWinId = `+ newWindowId +`; + let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`"; let mztaForceCompletionDesc="`+ browser.i18n.getMessage("chatgpt_force_completion") +`"; let mztaForceCompletionTitle="`+ browser.i18n.getMessage("chatgpt_force_completion_title") +`"; let mztaDoCustomText=`+ do_custom_text +`;