Merge pull request #120 from micz/new_internal_msg_system

New internal msg system between the background script and the chat windows
This commit is contained in:
Mic 2024-08-23 14:39:22 +02:00 committed by GitHub
commit eabb4b1370
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 101 additions and 112 deletions

View file

@ -23,6 +23,7 @@
// Get the LLM to be used // Get the LLM to be used
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const llm = urlParams.get('llm'); const llm = urlParams.get('llm');
const call_id = urlParams.get('call_id');
//console.log(">>>>>>>>>>> llm: " + llm); //console.log(">>>>>>>>>>> llm: " + llm);
@ -32,9 +33,11 @@ let worker = null;
switch (llm) { switch (llm) {
case "chatgpt_api": 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' }); worker = new Worker('model-worker-openai.js', { type: 'module' });
break; break;
case "ollama_api": { case "ollama_api": {
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' }); worker = new Worker('model-worker-ollama.js', { type: 'module' });
break; break;
} }

View file

@ -241,20 +241,20 @@ class MessagesArea extends HTMLElement {
case "1": // do reply case "1": // do reply
// console.log("[ThunderAI] (do reply) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment); // console.log("[ThunderAI] (do reply) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment);
await browser.runtime.sendMessage({command: "chatgpt_replyMessage", text: fullTextHTMLAtAssignment, tabId: promptData.tabId, mailMessageId: promptData.mailMessageId}); 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; break;
case "2": // replace text case "2": // replace text
// console.log("[ThunderAI] (replace text) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment); // console.log("[ThunderAI] (replace text) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment);
await browser.runtime.sendMessage({command: "chatgpt_replaceSelectedText", text: fullTextHTMLAtAssignment, tabId: promptData.tabId, mailMessageId: promptData.mailMessageId}); 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; break;
} }
}); });
const closeButton = document.createElement('button'); const closeButton = document.createElement('button');
closeButton.textContent = browser.i18n.getMessage("chatgpt_win_close"); closeButton.textContent = browser.i18n.getMessage("chatgpt_win_close");
closeButton.addEventListener('click', () => { closeButton.addEventListener('click', async () => {
// console.log("[ThunderAI] (close) fullTextHTMLAtAssignment: " + fullTextHTMLAtAssignment); // 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); } if(promptData.action != 0) { actionButtons.appendChild(actionButton); }
actionButtons.appendChild(closeButton); actionButtons.appendChild(closeButton);

View file

@ -159,7 +159,7 @@ function addCustomDiv(prompt_action,tabId,mailMessageId) {
case "0": // close window case "0": // close window
btn_ok.textContent = browser.i18n.getMessage("chatgpt_win_close"); btn_ok.textContent = browser.i18n.getMessage("chatgpt_win_close");
btn_ok.onclick = async function() { btn_ok.onclick = async function() {
browser.runtime.sendMessage({command: "chatgpt_close"}); browser.runtime.sendMessage({command: "chatgpt_close", window_id: mztaWinId});
}; };
break; break;
case "1": // do reply case "1": // do reply

View file

@ -123,6 +123,16 @@ function compareThunderbirdVersions(v1, v2) {
return 0; return 0;
} }
export 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 // The following methods are a modified version derived from https://github.com/ali-raheem/Aify/blob/13ff87583bc520fb80f555ab90a90c5c9df797a7/plugin/content_scripts/compose.js

View file

@ -20,9 +20,8 @@ import { mzta_script } from './js/mzta-chatgpt.js';
import { prefs_default } from './options/mzta-options-default.js'; import { prefs_default } from './options/mzta-options-default.js';
import { mzta_Menus } from './js/mzta-menus.js'; import { mzta_Menus } from './js/mzta-menus.js';
import { taLogger } from './js/mzta-logger.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 = ''; var original_html = '';
var modified_html = ''; var modified_html = '';
@ -58,7 +57,7 @@ messenger.runtime.onMessage.addListener(async (message, sender, sendResponse) =>
// openChatGPT(message.prompt,message.action,message.tabId); // openChatGPT(message.prompt,message.action,message.tabId);
// return true; // return true;
case 'chatgpt_close': case 'chatgpt_close':
browser.windows.remove(createdWindowID).then(() => { browser.windows.remove(message.window_id).then(() => {
taLog.log("ChatGPT window closed successfully."); taLog.log("ChatGPT window closed successfully.");
return true; return true;
}).catch((error) => { }).catch((error) => {
@ -163,146 +162,123 @@ async function openChatGPT(promptText, action, curr_tabId, prompt_name = '', do_
}); });
taLog.log("[ThunderAI] ChatGPT web interface script started..."); taLog.log("[ThunderAI] ChatGPT web interface script started...");
createdWindowID = newWindow.id;
let createdTab = newWindow.tabs[0]; let createdTab = newWindow.tabs[0];
let newWindowId = newWindow.id;
// Wait for tab loaded. let pre_script = `let mztaWinId = `+ newWindowId +`;
await new Promise(resolve => { let mztaStatusPageDesc="`+ browser.i18n.getMessage("prefs_status_page") +`";
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") +`"; let mztaForceCompletionDesc="`+ browser.i18n.getMessage("chatgpt_force_completion") +`";
let mztaForceCompletionTitle="`+ browser.i18n.getMessage("chatgpt_force_completion_title") +`"; let mztaForceCompletionTitle="`+ browser.i18n.getMessage("chatgpt_force_completion_title") +`";
let mztaDoCustomText=`+ do_custom_text +`; let mztaDoCustomText=`+ do_custom_text +`;
let mztaPromptName="[`+ i18nConditionalGet(prompt_name) +`]"; let mztaPromptName="[`+ i18nConditionalGet(prompt_name) +`]";
`; `;
browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false }) let done1 = false;
.then(async () => {
taLog.log("[ThunderAI] ChatGPT web interface script injected successfully"); while(!done1){
try {
await browser.tabs.executeScript(createdTab.id, { code: pre_script + mzta_script, matchAboutBlank: false });
let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId);
let mailMessageId = -1; let mailMessageId = -1;
if(mailMessage) mailMessageId = mailMessage.id; if(mailMessage) mailMessageId = mailMessage.id;
browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId}); browser.tabs.sendMessage(createdTab.id, { command: "chatgpt_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId});
}) taLog.log('[ChatGPT Web] Connection succeded!');
.catch(err => { taLog.log("[ThunderAI] ChatGPT Web script injected successfully");
console.error("[ThunderAI] ChatGPT web interface error injecting the script: ", err); done1 = true;
}); } catch (error) {
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));
}
break; // chatgpt_web break; // chatgpt_web
case 'chatgpt_api': case 'chatgpt_api':
// We are using the 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", type: "popup",
width: prefs.chatgpt_win_width, width: prefs.chatgpt_win_width,
height: prefs.chatgpt_win_height height: prefs.chatgpt_win_height
}); });
createdWindowID = newWindow2.id; browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
let createdTab2 = newWindow2.tabs[0];
if(await isThunderbird128OrGreater()){ if (message.command === "openai_api_ready_"+rand_call_id) {
// Wait for tab loaded.
await new Promise(resolve => { let newWindow2 = await browser.windows.get(message.window_id, {populate: true});
const tabIsLoaded2 = tab => { let createdTab2 = newWindow2.tabs[0];
return tab.status == "complete" && tab.url != "about:blank";
}; let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId);
const listener2 = (tabId, changeInfo, updatedTab) => { let mailMessageId2 = -1;
if (tabIsLoaded2(updatedTab)) { if(mailMessage) mailMessageId2 = mailMessage.id;
browser.tabs.onUpdated.removeListener(listener2);
resolve(); // 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;
} }
// Early exit if loaded already if (prefs.chatgpt_model == '') {
if (tabIsLoaded2(createdTab2)) { browser.tabs.sendMessage(createdTab2.id, { command: "api_error", error: browser.i18n.getMessage('chatgpt_empty_model')});
resolve(); return;
} else {
browser.tabs.onUpdated.addListener(listener2);
} }
});
}
let mailMessage = await browser.messageDisplay.getDisplayedMessage(curr_tabId); browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text});
let mailMessageId2 = -1; taLog.log('[OpenAI ChatGPI] Connection succeded!');
if(mailMessage) mailMessageId2 = mailMessage.id; browser.runtime.onMessage.removeListener(arguments.callee);
}
// 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;
}
browser.tabs.sendMessage(createdTab2.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId2, do_custom_text: do_custom_text});
break; // chatgpt_api break; // chatgpt_api
case 'ollama_api': case 'ollama_api':
// We are using the 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_id2 = '_ollama_' + generateCallID();
await browser.windows.create({
url: browser.runtime.getURL('api_webchat/index.html?llm='+prefs.connection_type+'&call_id='+rand_call_id2),
type: "popup", type: "popup",
width: prefs.chatgpt_win_width, width: prefs.chatgpt_win_width,
height: prefs.chatgpt_win_height height: prefs.chatgpt_win_height
}); });
createdWindowID = newWindow3.id; const listener3 = async (message, sender, sendResponse) => {
let createdTab3 = newWindow3.tabs[0];
if (message.command === "ollama_api_ready_"+rand_call_id2) {
if(await isThunderbird128OrGreater()){ taLog.log("Ollama API window ready.");
// Wait for tab loaded. taLog.log("message.window_id: " + message.window_id)
await new Promise(resolve => { let newWindow3 = await browser.windows.get(message.window_id, {populate: true});
const tabIsLoaded3 = tab => { let createdTab3 = newWindow3.tabs[0];
return tab.status == "complete" && tab.url != "about:blank"; taLog.log(">>>>>> createdTab3.id: " + createdTab3.id)
}; let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId);
const listener3 = (tabId, changeInfo, updatedTab) => { let mailMessageId3 = -1;
if (tabIsLoaded3(updatedTab)) { if(mailMessage3) mailMessageId3 = mailMessage3.id;
browser.tabs.onUpdated.removeListener(listener3); taLog.log(">>>>>> mailMessageId3: " + mailMessageId3)
resolve();
} // check if the config is present, or give a message error
if (prefs.ollama_host == '') {
await browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_host')});
return;
} }
// Early exit if loaded already if (prefs.ollama_model == '') {
if (tabIsLoaded3(createdTab3)) { await browser.tabs.sendMessage(createdTab3.id, { command: "api_error", error: browser.i18n.getMessage('ollama_empty_model')});
resolve(); return;
} else {
browser.tabs.onUpdated.addListener(listener3);
} }
});
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);
}
} }
let mailMessage3 = await browser.messageDisplay.getDisplayedMessage(curr_tabId); browser.runtime.onMessage.addListener(listener3);
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;
}
browser.tabs.sendMessage(createdTab3.id, { command: "api_send", prompt: promptText, action: action, tabId: curr_tabId, mailMessageId: mailMessageId3, do_custom_text: do_custom_text});
break; // ollama_api break; // ollama_api
} }
} }