Merge pull request #592 from micz/api_at_prompt_level

API settings at prompt level
This commit is contained in:
Mic 2026-01-01 21:44:13 +01:00 committed by GitHub
commit df95e56ebb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 435 additions and 120 deletions

View file

@ -93,7 +93,7 @@ export class Anthropic {
let claude_body = { let claude_body = {
model: this.model, model: this.model,
max_tokens: this.max_tokens, max_tokens: parseInt(this.max_tokens),
system: this.system_prompt, system: this.system_prompt,
messages: messages, messages: messages,
stream: this.stream, stream: this.stream,

View file

@ -19,7 +19,10 @@
// Some original methods are derived from https://github.com/ali-raheem/Aify/blob/cfadf52f576b7be3720b5b73af7c8d3129c054da/plugin/html/actions.js // Some original methods are derived from https://github.com/ali-raheem/Aify/blob/cfadf52f576b7be3720b5b73af7c8d3129c054da/plugin/html/actions.js
import { getPrompts } from './mzta-prompts.js'; import { getPrompts } from './mzta-prompts.js';
import { prefs_default } from '../options/mzta-options-default.js'; import {
prefs_default,
getDynamicSettingsDefaults
} from '../options/mzta-options-default.js';
import { import {
getLanguageDisplayName, getLanguageDisplayName,
getMenuContextCompose, getMenuContextCompose,
@ -222,7 +225,8 @@ export class mzta_Menus {
prompt: fullPrompt, prompt: fullPrompt,
llm: def_conntype, llm: def_conntype,
custom_model: curr_prompt.model ? curr_prompt.model : '', custom_model: curr_prompt.model ? curr_prompt.model : '',
do_debug: prefs_at.do_debug do_debug: prefs_at.do_debug,
config: curr_prompt
}); });
await cmd_addTags.initWorker(); await cmd_addTags.initWorker();
try{ try{
@ -258,9 +262,11 @@ export class mzta_Menus {
connection_type: prefs_default.connection_type, connection_type: prefs_default.connection_type,
calendar_enforce_timezone: prefs_default.calendar_enforce_timezone, calendar_enforce_timezone: prefs_default.calendar_enforce_timezone,
calendar_timezone: prefs_default.calendar_timezone, calendar_timezone: prefs_default.calendar_timezone,
...getDynamicSettingsDefaults(['use_specific_integration', 'connection_type'])
}); });
if((prefs_at.connection_type === '')||(prefs_at.connection_type === null)||(prefs_at.connection_type === undefined)||(prefs_at.connection_type === 'chatgpt_web')){ let def_conntype = getConnectionType(prefs_at, curr_prompt, 'get_calendar_event');
console.error("[ThunderAI | GetCalendarEvent] Invalid connection type: " + prefs_at.connection_type); if((def_conntype === '')||(def_conntype === null)||(def_conntype === undefined)||(def_conntype === 'chatgpt_web')){
console.error("[ThunderAI | GetCalendarEvent] Invalid connection type: " + def_conntype);
taWorkingStatus.stopWorking(); taWorkingStatus.stopWorking();
return {ok:'0'}; return {ok:'0'};
} }
@ -277,8 +283,9 @@ export class mzta_Menus {
this.logger.log("fullPrompt: " + fullPrompt); this.logger.log("fullPrompt: " + fullPrompt);
let cmd_GetCalendarEvent = new mzta_specialCommand({ let cmd_GetCalendarEvent = new mzta_specialCommand({
prompt: fullPrompt, prompt: fullPrompt,
llm: prefs_at.connection_type, llm: def_conntype,
do_debug: true do_debug: true,
config: curr_prompt
}); });
await cmd_GetCalendarEvent.initWorker(); await cmd_GetCalendarEvent.initWorker();
try{ try{
@ -333,9 +340,14 @@ export class mzta_Menus {
} }
case 'prompt_get_task': { // Get a task info case 'prompt_get_task': { // Get a task info
let task_data = ''; let task_data = '';
let prefs_at = await browser.storage.sync.get({connection_type: '', calendar_enforce_timezone: false, calendar_timezone: '',}); let prefs_at = await browser.storage.sync.get({
if((prefs_at.connection_type === '')||(prefs_at.connection_type === null)||(prefs_at.connection_type === undefined)||(prefs_at.connection_type === 'chatgpt_web')){ connection_type: '',
console.error("[ThunderAI | GetTask] Invalid connection type: " + prefs_at.connection_type); calendar_enforce_timezone: false,
calendar_timezone: '',
...getDynamicSettingsDefaults(['use_specific_integration', 'connection_type'])});
let def_conntype = getConnectionType(prefs_at, curr_prompt, 'get_task');
if((def_conntype === '')||(def_conntype === null)||(def_conntype === undefined)||(def_conntype === 'chatgpt_web')){
console.error("[ThunderAI | GetTask] Invalid connection type: " + def_conntype);
taWorkingStatus.stopWorking(); taWorkingStatus.stopWorking();
return {ok:'0'}; return {ok:'0'};
} }
@ -349,8 +361,9 @@ export class mzta_Menus {
this.logger.log("fullPrompt: " + fullPrompt); this.logger.log("fullPrompt: " + fullPrompt);
let cmd_GetTask = new mzta_specialCommand({ let cmd_GetTask = new mzta_specialCommand({
prompt: fullPrompt, prompt: fullPrompt,
llm: prefs_at.connection_type, llm: def_conntype,
do_debug: true do_debug: true,
config: curr_prompt
}); });
await cmd_GetTask.initWorker(); await cmd_GetTask.initWorker();
try{ try{

View file

@ -29,17 +29,20 @@
full_message = ""; full_message = "";
logger = null; logger = null;
do_debug = false; do_debug = false;
config = {};
constructor(args = {}) { constructor(args = {}) {
let { let {
prompt = '', prompt = '',
llm = '', llm = '',
custom_model = '', custom_model = '',
do_debug = false do_debug = false,
config = {}
} = args; } = args;
this.prompt = prompt; this.prompt = prompt;
this.llm = llm; this.llm = llm;
this.custom_model = custom_model; this.custom_model = custom_model;
this.config = config;
this.logger = new taLogger('mzta_specialCommand', do_debug); this.logger = new taLogger('mzta_specialCommand', do_debug);
this.do_debug = do_debug; this.do_debug = do_debug;
switch (this.llm) { switch (this.llm) {
@ -73,6 +76,11 @@
chatgpt_model: prefs_default.chatgpt_model, chatgpt_model: prefs_default.chatgpt_model,
chatgpt_developer_messages: prefs_default.chatgpt_developer_messages, chatgpt_developer_messages: prefs_default.chatgpt_developer_messages,
}); });
if (this.config.chatgpt_api_key) prefs_api.chatgpt_api_key = this.config.chatgpt_api_key;
if (this.config.chatgpt_model) prefs_api.chatgpt_model = this.config.chatgpt_model;
if (this.config.chatgpt_developer_messages) prefs_api.chatgpt_developer_messages = this.config.chatgpt_developer_messages;
this.worker.postMessage({ this.worker.postMessage({
type: 'init', type: 'init',
chatgpt_api_key: prefs_api.chatgpt_api_key, chatgpt_api_key: prefs_api.chatgpt_api_key,
@ -90,6 +98,12 @@
google_gemini_system_instruction: prefs_default.google_gemini_system_instruction, google_gemini_system_instruction: prefs_default.google_gemini_system_instruction,
google_gemini_thinking_budget: prefs_default.google_gemini_thinking_budget, google_gemini_thinking_budget: prefs_default.google_gemini_thinking_budget,
}); });
if (this.config.google_gemini_api_key) prefs_api.google_gemini_api_key = this.config.google_gemini_api_key;
if (this.config.google_gemini_model) prefs_api.google_gemini_model = this.config.google_gemini_model;
if (this.config.google_gemini_system_instruction) prefs_api.google_gemini_system_instruction = this.config.google_gemini_system_instruction;
if (this.config.google_gemini_thinking_budget) prefs_api.google_gemini_thinking_budget = this.config.google_gemini_thinking_budget;
this.worker.postMessage({ this.worker.postMessage({
type: 'init', type: 'init',
google_gemini_api_key: prefs_api.google_gemini_api_key, google_gemini_api_key: prefs_api.google_gemini_api_key,
@ -106,6 +120,10 @@
ollama_host: prefs_default.ollama_host, ollama_host: prefs_default.ollama_host,
ollama_model: prefs_default.ollama_model, ollama_model: prefs_default.ollama_model,
}); });
if (this.config.ollama_host) prefs_api.ollama_host = this.config.ollama_host;
if (this.config.ollama_model) prefs_api.ollama_model = this.config.ollama_model;
this.worker.postMessage({ this.worker.postMessage({
type: 'init', type: 'init',
ollama_host: prefs_api.ollama_host, ollama_host: prefs_api.ollama_host,
@ -124,6 +142,13 @@
openai_comp_chat_name: prefs_default.openai_comp_chat_name, openai_comp_chat_name: prefs_default.openai_comp_chat_name,
do_debug: prefs_default.do_debug, do_debug: prefs_default.do_debug,
}); });
if (this.config.openai_comp_host) prefs_api.openai_comp_host = this.config.openai_comp_host;
if (this.config.openai_comp_model) prefs_api.openai_comp_model = this.config.openai_comp_model;
if (this.config.openai_comp_api_key) prefs_api.openai_comp_api_key = this.config.openai_comp_api_key;
if (this.config.openai_comp_use_v1 !== undefined) prefs_api.openai_comp_use_v1 = this.config.openai_comp_use_v1;
if (this.config.openai_comp_chat_name) prefs_api.openai_comp_chat_name = this.config.openai_comp_chat_name;
this.worker.postMessage({ this.worker.postMessage({
type: 'init', type: 'init',
openai_comp_host: prefs_api.openai_comp_host, openai_comp_host: prefs_api.openai_comp_host,
@ -142,6 +167,12 @@
anthropic_version: prefs_default.anthropic_version, anthropic_version: prefs_default.anthropic_version,
anthropic_max_tokens: prefs_default.anthropic_max_tokens, anthropic_max_tokens: prefs_default.anthropic_max_tokens,
}); });
if (this.config.anthropic_api_key) prefs_api.anthropic_api_key = this.config.anthropic_api_key;
if (this.config.anthropic_model) prefs_api.anthropic_model = this.config.anthropic_model;
if (this.config.anthropic_version) prefs_api.anthropic_version = this.config.anthropic_version;
if (this.config.anthropic_max_tokens) prefs_api.anthropic_max_tokens = this.config.anthropic_max_tokens;
this.worker.postMessage({ this.worker.postMessage({
type: 'init', type: 'init',
anthropic_api_key: prefs_api.anthropic_api_key, anthropic_api_key: prefs_api.anthropic_api_key,

View file

@ -1084,7 +1084,8 @@ async function processEmails(messages, addTagsAuto, spamFilter) {
prompt: specialFullPrompt_add_tags, prompt: specialFullPrompt_add_tags,
llm: getConnectionType(prefs_aats, curr_prompt_add_tags, 'add_tags'), llm: getConnectionType(prefs_aats, curr_prompt_add_tags, 'add_tags'),
custom_model: curr_prompt_add_tags.model ? curr_prompt_add_tags.model : '', custom_model: curr_prompt_add_tags.model ? curr_prompt_add_tags.model : '',
do_debug: prefs_aats.do_debug do_debug: prefs_aats.do_debug,
config: curr_prompt_add_tags
}); });
await cmd_addTags.initWorker(); await cmd_addTags.initWorker();
let tags_current_email = []; let tags_current_email = [];
@ -1123,7 +1124,8 @@ async function processEmails(messages, addTagsAuto, spamFilter) {
prompt: specialFullPrompt_spamfilter, prompt: specialFullPrompt_spamfilter,
llm: getConnectionType(prefs_aats, curr_prompt_spamfilter, 'spamfilter'), llm: getConnectionType(prefs_aats, curr_prompt_spamfilter, 'spamfilter'),
custom_model: curr_prompt_spamfilter.model ? curr_prompt_spamfilter.model : '', custom_model: curr_prompt_spamfilter.model ? curr_prompt_spamfilter.model : '',
do_debug: prefs_aats.do_debug do_debug: prefs_aats.do_debug,
config: curr_prompt_spamfilter
}); });
await cmd_spamfilter.initWorker(); await cmd_spamfilter.initWorker();
let spamfilter_result = ''; let spamfilter_result = '';

View file

@ -63,9 +63,11 @@ const integration_settings_template = {
connection_type: 'chatgpt_api', connection_type: 'chatgpt_api',
}; };
const global_integration_settings = { ...integration_settings_template };
for (const [integration, options] of Object.entries(integration_options_config)) { for (const [integration, options] of Object.entries(integration_options_config)) {
for (const [key, value] of Object.entries(options)) { for (const [key, value] of Object.entries(options)) {
integration_settings_template[`${integration}_${key}`] = value; global_integration_settings[`${integration}_${key}`] = value;
} }
} }
@ -93,7 +95,7 @@ export function getDynamicSettingValue(prefs, prefix, settingName) {
} }
export const prefs_default = { export const prefs_default = {
...integration_settings_template, ...global_integration_settings,
do_debug: false, do_debug: false,
chatgpt_win_height: 800, chatgpt_win_height: 800,
chatgpt_win_width: 700, chatgpt_win_width: 700,

View file

@ -16,7 +16,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
import { prefs_default, integration_options_config } from '../../options/mzta-options-default.js'; import {
prefs_default,
integration_options_config
} from '../../options/mzta-options-default.js';
import { OpenAI } from '../../js/api/openai_responses.js'; import { OpenAI } from '../../js/api/openai_responses.js';
import { Ollama } from '../../js/api/ollama.js'; import { Ollama } from '../../js/api/ollama.js';
import { OpenAIComp } from '../../js/api/openai_comp.js' import { OpenAIComp } from '../../js/api/openai_comp.js'
@ -50,6 +53,19 @@ export async function injectConnectionUI({
return null; return null;
} }
// Inject CSS if not present
if (!document.getElementById('mzta-connection-ui-style')) {
const style = document.createElement('style');
style.id = 'mzta-connection-ui-style';
style.textContent = `
.api_key-container { position: relative; display: flex; align-items: center; }
.toggle-icon { cursor: pointer; margin-left: 5px; }
.toggle-icon img { width: 16px; height: 16px; vertical-align: middle; }
.option-input { flex-grow: 1; }
`;
document.head.appendChild(style);
}
let tpl = ` let tpl = `
<tr id="${selectId}_tr"${tr_class ? ` class="${tr_class}"` : ''}> <tr id="${selectId}_tr"${tr_class ? ` class="${tr_class}"` : ''}>
<td> <td>
@ -140,7 +156,7 @@ export async function injectConnectionUI({
<label> <label>
<input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_api_key" class="option-input"/> <input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_api_key" class="option-input"/>
</label> </label>
<span class="toggle-icon" id="toggle_chatgpt_api_key"><img src="/images/pwd-show.png" id="pwd-icon_chatgpt_api_key"></span> <span class="toggle-icon" id="${modelId_prefix ? `${modelId_prefix}` : ''}toggle_chatgpt_api_key"><img src="/images/pwd-show.png" id="${modelId_prefix ? `${modelId_prefix}` : ''}pwd-icon_chatgpt_api_key"></span>
</div> </div>
</td> </td>
</tr> </tr>
@ -151,7 +167,7 @@ export async function injectConnectionUI({
</label> </label>
</td> </td>
<td> <td>
<button id="btnUpdateChatGPTModels">__MSG_ChatGPT_Models_Fetch__</button> <span id="chatgpt_model_fetch_loading">__MSG_Loading__</span><br> <button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnUpdateChatGPTModels">__MSG_ChatGPT_Models_Fetch__</button> <span id="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_model_fetch_loading" style="display:none">__MSG_Loading__</span><br>
<label> <label>
<select id="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_model" class="option-input"></select> <select id="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}chatgpt_model" class="option-input"></select>
</label> </label>
@ -205,7 +221,7 @@ export async function injectConnectionUI({
<label> <label>
<input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_api_key" class="option-input"/> <input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_api_key" class="option-input"/>
</label> </label>
<span class="toggle-icon" id="toggle_google_gemini_api_key"><img src="/images/pwd-show.png" id="pwd-icon_google_gemini_api_key"></span> <span class="toggle-icon" id="${modelId_prefix ? `${modelId_prefix}` : ''}toggle_google_gemini_api_key"><img src="/images/pwd-show.png" id="${modelId_prefix ? `${modelId_prefix}` : ''}pwd-icon_google_gemini_api_key"></span>
</div> </div>
</td> </td>
</tr> </tr>
@ -216,7 +232,7 @@ export async function injectConnectionUI({
</label> </label>
</td> </td>
<td> <td>
<button id="btnUpdateGoogleGeminiModels">__MSG_GoogleGemini_Models_Fetch__</button> <span id="google_gemini_model_fetch_loading">__MSG_Loading__</span><br> <button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnUpdateGoogleGeminiModels">__MSG_GoogleGemini_Models_Fetch__</button> <span id="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_model_fetch_loading" style="display:none">__MSG_Loading__</span><br>
<label> <label>
<select id="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_model" class="option-input"></select> <select id="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}google_gemini_model" class="option-input"></select>
</label> </label>
@ -273,12 +289,12 @@ export async function injectConnectionUI({
</label> </label>
</td> </td>
</tr> </tr>
<tr class="conntype_ollama_api${tr_class ? ` ${tr_class}` : ''}" id="ollama_api_cors_warning"> <tr class="conntype_ollama_api${tr_class ? ` ${tr_class}` : ''}" id="${modelId_prefix ? `${modelId_prefix}` : ''}ollama_api_cors_warning">
<td colspan="2" style="text-align:center;"> <td colspan="2" style="text-align:center;">
__MSG_remember_CORS__ [<a href="https://micz.it/thunderbird-addon-thunderai/ollama-cors-information/">__MSG_more_info_string__</a>] __MSG_remember_CORS__ [<a href="https://micz.it/thunderbird-addon-thunderai/ollama-cors-information/">__MSG_more_info_string__</a>]
<br><br><b>__MSG_CORS_alternative_1__</b> <br><br><b>__MSG_CORS_alternative_1__</b>
<br>__MSG_CORS_alternative_2__ <br>__MSG_CORS_alternative_2__
<br><br><button id="btnGiveAllUrlsPermission_ollama_api">__MSG_CORS_give_allurls_perm__</button> <br><br><button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnGiveAllUrlsPermission_ollama_api">__MSG_CORS_give_allurls_perm__</button>
</td> </td>
</tr> </tr>
<tr class="conntype_ollama_api${tr_class ? ` ${tr_class}` : ''}"> <tr class="conntype_ollama_api${tr_class ? ` ${tr_class}` : ''}">
@ -288,7 +304,7 @@ export async function injectConnectionUI({
</label> </label>
</td> </td>
<td> <td>
<button id="btnUpdateOllamaModels">__MSG_Ollama_Models_Fetch__</button> <span id="ollama_model_fetch_loading">__MSG_Loading__</span><br> <button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnUpdateOllamaModels">__MSG_Ollama_Models_Fetch__</button> <span id="${modelId_prefix ? `${modelId_prefix}` : ''}ollama_model_fetch_loading" style="display:none">__MSG_Loading__</span><br>
<label> <label>
<select id="${modelId_prefix ? `${modelId_prefix}` : ''}ollama_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}ollama_model" class="option-input"></select> <select id="${modelId_prefix ? `${modelId_prefix}` : ''}ollama_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}ollama_model" class="option-input"></select>
</label> </label>
@ -335,7 +351,7 @@ export async function injectConnectionUI({
</label></td> </label></td>
<td> <td>
<label> <label>
<select id="openai_comp_services_shortcut"></select> <select id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_services_shortcut"></select>
<br>__MSG_prefs_OpenAIComp_AvailableServices_Info__ <br>__MSG_prefs_OpenAIComp_AvailableServices_Info__
</label> </label>
</td> </td>
@ -352,12 +368,12 @@ export async function injectConnectionUI({
</label> </label>
</td> </td>
</tr> </tr>
<tr class="conntype_openai_comp_api${tr_class ? ` ${tr_class}` : ''}" id="openai_comp_api_cors_warning"> <tr class="conntype_openai_comp_api${tr_class ? ` ${tr_class}` : ''}" id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_api_cors_warning">
<td colspan="2" style="text-align:center;"> <td colspan="2" style="text-align:center;">
__MSG_maybe_CORS_openai_comp__ [<a href="https://micz.it/thunderbird-addon-thunderai/ollama-cors-information/">__MSG_more_info_string__</a>] __MSG_maybe_CORS_openai_comp__ [<a href="https://micz.it/thunderbird-addon-thunderai/ollama-cors-information/">__MSG_more_info_string__</a>]
<br><br><b>__MSG_CORS_alternative_1__</b> <br><br><b>__MSG_CORS_alternative_1__</b>
<br>__MSG_CORS_alternative_2__ <br>__MSG_CORS_alternative_2__
<br><br><button id="btnGiveAllUrlsPermission_openai_comp_api">__MSG_CORS_give_allurls_perm__</button> <br><br><button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnGiveAllUrlsPermission_openai_comp_api">__MSG_CORS_give_allurls_perm__</button>
</td> </td>
</tr> </tr>
<tr class="conntype_openai_comp_api${tr_class ? ` ${tr_class}` : ''}"> <tr class="conntype_openai_comp_api${tr_class ? ` ${tr_class}` : ''}">
@ -381,7 +397,7 @@ export async function injectConnectionUI({
<label> <label>
<input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_api_key" class="option-input"/> <input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_api_key" class="option-input"/>
</label> </label>
<span class="toggle-icon" id="toggle_openai_comp_api_key"><img src="/images/pwd-show.png" id="pwd-icon_openai_comp_api_key"></span> <span class="toggle-icon" id="${modelId_prefix ? `${modelId_prefix}` : ''}toggle_openai_comp_api_key"><img src="/images/pwd-show.png" id="${modelId_prefix ? `${modelId_prefix}` : ''}pwd-icon_openai_comp_api_key"></span>
</div> </div>
</td> </td>
</tr> </tr>
@ -389,12 +405,12 @@ export async function injectConnectionUI({
<td> <td>
<label> <label>
<span class="opt_title">__MSG_OpenAIComp_Models__</span> <span class="opt_title">__MSG_OpenAIComp_Models__</span>
<br><button id="btnOpenAICompForceModel" class="btn_small">__MSG_prefs_OpenAIComp_ForceModel__</button> <br><button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnOpenAICompForceModel" class="btn_small">__MSG_prefs_OpenAIComp_ForceModel__</button>
<br><button id="btnOpenAICompClearModelsList" class="btn_small">__MSG_prefs_OpenAIComp_ClearModelsList__</button></td> <br><button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnOpenAICompClearModelsList" class="btn_small">__MSG_prefs_OpenAIComp_ClearModelsList__</button></td>
</label> </label>
</td> </td>
<td> <td>
<button id="btnUpdateOpenAICompModels">__MSG_OpenAIComp_Models_Fetch__</button> <span id="openai_comp_model_fetch_loading">__MSG_Loading__</span><br> <button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnUpdateOpenAICompModels">__MSG_OpenAIComp_Models_Fetch__</button> <span id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_model_fetch_loading" style="display:none">__MSG_Loading__</span><br>
<label> <label>
<select id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_model" class="option-input"></select> <select id="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}openai_comp_model" class="option-input"></select>
</label> </label>
@ -433,7 +449,7 @@ export async function injectConnectionUI({
<label> <label>
<input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_api_key" class="option-input"/> <input type="password" id="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_api_key" name="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_api_key" class="option-input"/>
</label> </label>
<span class="toggle-icon" id="toggle_anthropic_api_key"><img src="/images/pwd-show.png" id="pwd-icon_anthropic_api_key"></span> <span class="toggle-icon" id="${modelId_prefix ? `${modelId_prefix}` : ''}toggle_anthropic_api_key"><img src="/images/pwd-show.png" id="${modelId_prefix ? `${modelId_prefix}` : ''}pwd-icon_anthropic_api_key"></span>
</div> </div>
</td> </td>
</tr> </tr>
@ -444,7 +460,7 @@ export async function injectConnectionUI({
</label> </label>
</td> </td>
<td> <td>
<button id="btnUpdateAnthropicModels">__MSG_Anthropic_Models_Fetch__</button> <span id="anthropic_model_fetch_loading">__MSG_Loading__</span><br> <button id="${modelId_prefix ? `${modelId_prefix}` : ''}btnUpdateAnthropicModels">__MSG_Anthropic_Models_Fetch__</button> <span id="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_model_fetch_loading" style="display:none">__MSG_Loading__</span><br>
<label> <label>
<select id="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_model" class="option-input"></select> <select id="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_model" name="${modelId_prefix ? `${modelId_prefix}` : ''}anthropic_model" class="option-input"></select>
</label> </label>
@ -549,7 +565,7 @@ export async function injectConnectionUI({
document.getElementById(getPrefixedId("openai_comp_use_v1")).addEventListener("input", () => resetOpenAICompConfigs(modelId_prefix)); document.getElementById(getPrefixedId("openai_comp_use_v1")).addEventListener("input", () => resetOpenAICompConfigs(modelId_prefix));
showConnectionOptions(conntype_select); showConnectionOptions(conntype_select);
loadOpenAICompConfigs(); loadOpenAICompConfigs(modelId_prefix);
warn_ChatGPT_APIKeyEmpty(modelId_prefix); warn_ChatGPT_APIKeyEmpty(modelId_prefix);
warn_Ollama_HostEmpty(modelId_prefix); warn_Ollama_HostEmpty(modelId_prefix);
warn_OpenAIComp_HostEmpty(modelId_prefix); warn_OpenAIComp_HostEmpty(modelId_prefix);
@ -558,8 +574,8 @@ export async function injectConnectionUI({
warn_Anthropic_VersionEmpty(modelId_prefix); warn_Anthropic_VersionEmpty(modelId_prefix);
const passwordField_chatgpt_api_key = document.getElementById(getPrefixedId('chatgpt_api_key')); const passwordField_chatgpt_api_key = document.getElementById(getPrefixedId('chatgpt_api_key'));
const toggleIcon_chatgpt_api_key = document.getElementById('toggle_chatgpt_api_key'); const toggleIcon_chatgpt_api_key = document.getElementById(getPrefixedId('toggle_chatgpt_api_key'));
const icon_img_chatgpt_api_key = document.getElementById('pwd-icon_chatgpt_api_key'); const icon_img_chatgpt_api_key = document.getElementById(getPrefixedId('pwd-icon_chatgpt_api_key'));
toggleIcon_chatgpt_api_key.addEventListener('click', () => { toggleIcon_chatgpt_api_key.addEventListener('click', () => {
const type = passwordField_chatgpt_api_key.getAttribute('type') === 'password' ? 'text' : 'password'; const type = passwordField_chatgpt_api_key.getAttribute('type') === 'password' ? 'text' : 'password';
@ -569,8 +585,8 @@ export async function injectConnectionUI({
}); });
const passwordField_google_gemini_api_key = document.getElementById(getPrefixedId('google_gemini_api_key')); const passwordField_google_gemini_api_key = document.getElementById(getPrefixedId('google_gemini_api_key'));
const toggleIcon_google_gemini_api_key = document.getElementById('toggle_google_gemini_api_key'); const toggleIcon_google_gemini_api_key = document.getElementById(getPrefixedId('toggle_google_gemini_api_key'));
const icon_img_google_gemini_api_key = document.getElementById('pwd-icon_google_gemini_api_key'); const icon_img_google_gemini_api_key = document.getElementById(getPrefixedId('pwd-icon_google_gemini_api_key'));
toggleIcon_google_gemini_api_key.addEventListener('click', () => { toggleIcon_google_gemini_api_key.addEventListener('click', () => {
const type = passwordField_google_gemini_api_key.getAttribute('type') === 'password' ? 'text' : 'password'; const type = passwordField_google_gemini_api_key.getAttribute('type') === 'password' ? 'text' : 'password';
@ -580,8 +596,8 @@ export async function injectConnectionUI({
}); });
const passwordField_openai_comp_api_key = document.getElementById(getPrefixedId('openai_comp_api_key')); const passwordField_openai_comp_api_key = document.getElementById(getPrefixedId('openai_comp_api_key'));
const toggleIcon_openai_comp_api_key = document.getElementById('toggle_openai_comp_api_key'); const toggleIcon_openai_comp_api_key = document.getElementById(getPrefixedId('toggle_openai_comp_api_key'));
const icon_img_openai_comp_api_key = document.getElementById('pwd-icon_openai_comp_api_key'); const icon_img_openai_comp_api_key = document.getElementById(getPrefixedId('pwd-icon_openai_comp_api_key'));
toggleIcon_openai_comp_api_key.addEventListener('click', () => { toggleIcon_openai_comp_api_key.addEventListener('click', () => {
const type = passwordField_openai_comp_api_key.getAttribute('type') === 'password' ? 'text' : 'password'; const type = passwordField_openai_comp_api_key.getAttribute('type') === 'password' ? 'text' : 'password';
@ -591,8 +607,8 @@ export async function injectConnectionUI({
}); });
const passwordField_anthropic_api_key = document.getElementById(getPrefixedId('anthropic_api_key')); const passwordField_anthropic_api_key = document.getElementById(getPrefixedId('anthropic_api_key'));
const toggleIcon_anthropic_api_key = document.getElementById('toggle_anthropic_api_key'); const toggleIcon_anthropic_api_key = document.getElementById(getPrefixedId('toggle_anthropic_api_key'));
const icon_img_anthropic_api_key = document.getElementById('pwd-icon_anthropic_api_key'); const icon_img_anthropic_api_key = document.getElementById(getPrefixedId('pwd-icon_anthropic_api_key'));
toggleIcon_anthropic_api_key.addEventListener('click', () => { toggleIcon_anthropic_api_key.addEventListener('click', () => {
const type = passwordField_anthropic_api_key.getAttribute('type') === 'password' ? 'text' : 'password'; const type = passwordField_anthropic_api_key.getAttribute('type') === 'password' ? 'text' : 'password';
@ -626,7 +642,7 @@ export async function injectConnectionUI({
browser.tabs.create({ url: base_url + model_opt }); browser.tabs.create({ url: base_url + model_opt });
}); });
let select_openai_comp_services_shortcut = document.getElementById('openai_comp_services_shortcut'); let select_openai_comp_services_shortcut = document.getElementById(getPrefixedId('openai_comp_services_shortcut'));
select_openai_comp_services_shortcut.addEventListener("change", () => { select_openai_comp_services_shortcut.addEventListener("change", () => {
let selectedOption = select_openai_comp_services_shortcut.options[select_openai_comp_services_shortcut.selectedIndex]; let selectedOption = select_openai_comp_services_shortcut.options[select_openai_comp_services_shortcut.selectedIndex];
const config = openAICompConfigs.find(cfg => cfg.id === selectedOption.value); const config = openAICompConfigs.find(cfg => cfg.id === selectedOption.value);
@ -661,14 +677,14 @@ export async function injectConnectionUI({
select_chatgpt_model.appendChild(chatgpt_option); select_chatgpt_model.appendChild(chatgpt_option);
select_chatgpt_model.addEventListener("change", () => warn_ChatGPT_APIKeyEmpty(modelId_prefix)); select_chatgpt_model.addEventListener("change", () => warn_ChatGPT_APIKeyEmpty(modelId_prefix));
document.getElementById('btnUpdateChatGPTModels').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnUpdateChatGPTModels')).addEventListener('click', async () => {
document.getElementById('chatgpt_model_fetch_loading').style.display = 'inline'; document.getElementById(getPrefixedId('chatgpt_model_fetch_loading')).style.display = 'inline';
let openai = new OpenAI({ let openai = new OpenAI({
apiKey: document.getElementById(getPrefixedId("chatgpt_api_key")).value, apiKey: document.getElementById(getPrefixedId("chatgpt_api_key")).value,
}); });
let granted = await messenger.permissions.request({ origins: ["https://*.openai.com/*"] }); let granted = await messenger.permissions.request({ origins: ["https://*.openai.com/*"] });
if(!granted){ if(!granted){
document.getElementById('chatgpt_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('chatgpt_model_fetch_loading')).style.display = 'none';
taLog.log("OpenAI API permission denied"); taLog.log("OpenAI API permission denied");
alert(browser.i18n.getMessage("Optional_Permission_Denied_Model_Fetching")); alert(browser.i18n.getMessage("Optional_Permission_Denied_Model_Fetching"));
return; return;
@ -682,7 +698,7 @@ export async function injectConnectionUI({
} catch (e) { } catch (e) {
errorDetail = data.error; errorDetail = data.error;
} }
document.getElementById('chatgpt_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('chatgpt_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("ChatGPT_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("ChatGPT_Models_Error_fetching"));
alert(browser.i18n.getMessage("ChatGPT_Models_Error_fetching")+": " + errorDetail); alert(browser.i18n.getMessage("ChatGPT_Models_Error_fetching")+": " + errorDetail);
return; return;
@ -696,7 +712,7 @@ export async function injectConnectionUI({
select_chatgpt_model.appendChild(option); select_chatgpt_model.appendChild(option);
} }
}); });
document.getElementById('chatgpt_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('chatgpt_model_fetch_loading')).style.display = 'none';
}); });
warn_ChatGPT_APIKeyEmpty(modelId_prefix); warn_ChatGPT_APIKeyEmpty(modelId_prefix);
@ -710,8 +726,8 @@ export async function injectConnectionUI({
select_google_gemini_model.appendChild(google_gemini_option); select_google_gemini_model.appendChild(google_gemini_option);
select_google_gemini_model.addEventListener("change", () => warn_GoogleGemini_APIKeyEmpty(modelId_prefix)); select_google_gemini_model.addEventListener("change", () => warn_GoogleGemini_APIKeyEmpty(modelId_prefix));
document.getElementById('btnUpdateGoogleGeminiModels').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnUpdateGoogleGeminiModels')).addEventListener('click', async () => {
document.getElementById('google_gemini_model_fetch_loading').style.display = 'inline'; document.getElementById(getPrefixedId('google_gemini_model_fetch_loading')).style.display = 'inline';
let google_gemini = new GoogleGemini({ let google_gemini = new GoogleGemini({
apiKey: document.getElementById(getPrefixedId("google_gemini_api_key")).value, apiKey: document.getElementById(getPrefixedId("google_gemini_api_key")).value,
}); });
@ -724,7 +740,7 @@ export async function injectConnectionUI({
} catch (e) { } catch (e) {
errorDetail = data.error; errorDetail = data.error;
} }
document.getElementById('google_gemini_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('google_gemini_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("GoogleGemini_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("GoogleGemini_Models_Error_fetching"));
alert(browser.i18n.getMessage("GoogleGemini_Models_Error_fetching")+": " + errorDetail); alert(browser.i18n.getMessage("GoogleGemini_Models_Error_fetching")+": " + errorDetail);
return; return;
@ -738,7 +754,7 @@ export async function injectConnectionUI({
select_google_gemini_model.appendChild(option); select_google_gemini_model.appendChild(option);
} }
}); });
document.getElementById('google_gemini_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('google_gemini_model_fetch_loading')).style.display = 'none';
}); });
warn_GoogleGemini_APIKeyEmpty(modelId_prefix); warn_GoogleGemini_APIKeyEmpty(modelId_prefix);
@ -752,15 +768,15 @@ export async function injectConnectionUI({
select_ollama_model.appendChild(ollama_option); select_ollama_model.appendChild(ollama_option);
select_ollama_model.addEventListener("change", () => warn_Ollama_HostEmpty(modelId_prefix)); select_ollama_model.addEventListener("change", () => warn_Ollama_HostEmpty(modelId_prefix));
document.getElementById('btnUpdateOllamaModels').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnUpdateOllamaModels')).addEventListener('click', async () => {
document.getElementById('ollama_model_fetch_loading').style.display = 'inline'; document.getElementById(getPrefixedId('ollama_model_fetch_loading')).style.display = 'inline';
let ollama = new Ollama({ let ollama = new Ollama({
host: document.getElementById(getPrefixedId("ollama_host")).value, host: document.getElementById(getPrefixedId("ollama_host")).value,
}); });
try { try {
let data = await ollama.fetchModels(); let data = await ollama.fetchModels();
if(!data){ if(!data){
document.getElementById('ollama_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('ollama_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("Ollama_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("Ollama_Models_Error_fetching"));
alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")); alert(browser.i18n.getMessage("Ollama_Models_Error_fetching"));
return; return;
@ -773,13 +789,13 @@ export async function injectConnectionUI({
} catch (e) { } catch (e) {
errorDetail = data.error; errorDetail = data.error;
} }
document.getElementById('ollama_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('ollama_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("Ollama_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("Ollama_Models_Error_fetching"));
alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")+": " + errorDetail); alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")+": " + errorDetail);
return; return;
} }
if(data.response.models.length == 0){ if(data.response.models.length == 0){
document.getElementById('ollama_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('ollama_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("Ollama_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("Ollama_Models_Error_fetching"));
alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")+": " + browser.i18n.getMessage("API_Models_Error_NoModels")); alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")+": " + browser.i18n.getMessage("API_Models_Error_NoModels"));
return; return;
@ -793,9 +809,9 @@ export async function injectConnectionUI({
select_ollama_model.appendChild(option); select_ollama_model.appendChild(option);
} }
}); });
document.getElementById('ollama_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('ollama_model_fetch_loading')).style.display = 'none';
} catch (error) { } catch (error) {
document.getElementById('ollama_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('ollama_model_fetch_loading')).style.display = 'none';
taLog.error(browser.i18n.getMessage("Ollama_Models_Error_fetching")); taLog.error(browser.i18n.getMessage("Ollama_Models_Error_fetching"));
alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")+": " + error.message); alert(browser.i18n.getMessage("Ollama_Models_Error_fetching")+": " + error.message);
} }
@ -811,8 +827,8 @@ export async function injectConnectionUI({
select_openai_comp_model.appendChild(openai_comp_option); select_openai_comp_model.appendChild(openai_comp_option);
select_openai_comp_model.addEventListener("change", () => warn_OpenAIComp_HostEmpty(modelId_prefix)); select_openai_comp_model.addEventListener("change", () => warn_OpenAIComp_HostEmpty(modelId_prefix));
document.getElementById('btnUpdateOpenAICompModels').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnUpdateOpenAICompModels')).addEventListener('click', async () => {
document.getElementById('openai_comp_model_fetch_loading').style.display = 'inline'; document.getElementById(getPrefixedId('openai_comp_model_fetch_loading')).style.display = 'inline';
let openai_comp = new OpenAIComp({ let openai_comp = new OpenAIComp({
host: document.getElementById(getPrefixedId("openai_comp_host")).value, host: document.getElementById(getPrefixedId("openai_comp_host")).value,
apiKey: document.getElementById(getPrefixedId("openai_comp_api_key")).value, apiKey: document.getElementById(getPrefixedId("openai_comp_api_key")).value,
@ -827,7 +843,7 @@ export async function injectConnectionUI({
} catch (e) { } catch (e) {
errorDetail = data.error; errorDetail = data.error;
} }
document.getElementById('openai_comp_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('openai_comp_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("OpenAIComp_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("OpenAIComp_Models_Error_fetching"));
alert(browser.i18n.getMessage("OpenAIComp_Models_Error_fetching")+": " + errorDetail); alert(browser.i18n.getMessage("OpenAIComp_Models_Error_fetching")+": " + errorDetail);
return; return;
@ -841,7 +857,7 @@ export async function injectConnectionUI({
select_openai_comp_model.appendChild(option); select_openai_comp_model.appendChild(option);
} }
}); });
document.getElementById('openai_comp_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('openai_comp_model_fetch_loading')).style.display = 'none';
}); });
warn_OpenAIComp_HostEmpty(modelId_prefix); warn_OpenAIComp_HostEmpty(modelId_prefix);
@ -856,15 +872,15 @@ export async function injectConnectionUI({
select_anthropic_model.addEventListener("change", () => warn_Anthropic_APIKeyEmpty(modelId_prefix)); select_anthropic_model.addEventListener("change", () => warn_Anthropic_APIKeyEmpty(modelId_prefix));
select_anthropic_model.addEventListener("change", () => warn_Anthropic_VersionEmpty(modelId_prefix)); select_anthropic_model.addEventListener("change", () => warn_Anthropic_VersionEmpty(modelId_prefix));
document.getElementById('btnUpdateAnthropicModels').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnUpdateAnthropicModels')).addEventListener('click', async () => {
document.getElementById('anthropic_model_fetch_loading').style.display = 'inline'; document.getElementById(getPrefixedId('anthropic_model_fetch_loading')).style.display = 'inline';
let anthropic = new Anthropic({ let anthropic = new Anthropic({
apiKey: document.getElementById(getPrefixedId("anthropic_api_key")).value, apiKey: document.getElementById(getPrefixedId("anthropic_api_key")).value,
version: document.getElementById(getPrefixedId("anthropic_version")).value, version: document.getElementById(getPrefixedId("anthropic_version")).value,
}); });
let granted = await messenger.permissions.request({ origins: ["https://*.anthropic.com/*"] }); let granted = await messenger.permissions.request({ origins: ["https://*.anthropic.com/*"] });
if(!granted){ if(!granted){
document.getElementById('anthropic_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('anthropic_model_fetch_loading')).style.display = 'none';
taLog.warn("Claude API web permission denied"); taLog.warn("Claude API web permission denied");
alert(browser.i18n.getMessage("Optional_Permission_Denied_Model_Fetching")); alert(browser.i18n.getMessage("Optional_Permission_Denied_Model_Fetching"));
return; return;
@ -878,7 +894,7 @@ export async function injectConnectionUI({
} catch (e) { } catch (e) {
errorDetail = data.error; errorDetail = data.error;
} }
document.getElementById('anthropic_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('anthropic_model_fetch_loading')).style.display = 'none';
console.error("[ThunderAI] " + browser.i18n.getMessage("Anthropic_Models_Error_fetching")); console.error("[ThunderAI] " + browser.i18n.getMessage("Anthropic_Models_Error_fetching"));
alert(browser.i18n.getMessage("Anthropic_Models_Error_fetching")+": " + errorDetail); alert(browser.i18n.getMessage("Anthropic_Models_Error_fetching")+": " + errorDetail);
return; return;
@ -895,13 +911,13 @@ export async function injectConnectionUI({
select_anthropic_model.appendChild(option); select_anthropic_model.appendChild(option);
} }
}); });
document.getElementById('anthropic_model_fetch_loading').style.display = 'none'; document.getElementById(getPrefixedId('anthropic_model_fetch_loading')).style.display = 'none';
}); });
warn_Anthropic_APIKeyEmpty(modelId_prefix); warn_Anthropic_APIKeyEmpty(modelId_prefix);
}); });
document.getElementById('btnOpenAICompForceModel').addEventListener('click', () => { document.getElementById(getPrefixedId('btnOpenAICompForceModel')).addEventListener('click', () => {
let modelName = prompt(browser.i18n.getMessage('OpenAIComp_force_model_ask')).trim(); let modelName = prompt(browser.i18n.getMessage('OpenAIComp_force_model_ask')).trim();
if ((modelName !== null) && (modelName !== undefined) && (modelName !== '')) { if ((modelName !== null) && (modelName !== undefined) && (modelName !== '')) {
let select_openai_comp_model = getModelEl('openai_comp_model', modelId_prefix); let select_openai_comp_model = getModelEl('openai_comp_model', modelId_prefix);
@ -914,7 +930,7 @@ export async function injectConnectionUI({
} }
}); });
document.getElementById('btnOpenAICompClearModelsList').addEventListener('click', () => { document.getElementById(getPrefixedId('btnOpenAICompClearModelsList')).addEventListener('click', () => {
if (!confirm(browser.i18n.getMessage('OpenAIComp_ClearModelsList_Confirm'))) { if (!confirm(browser.i18n.getMessage('OpenAIComp_ClearModelsList_Confirm'))) {
return; return;
} }
@ -926,11 +942,11 @@ export async function injectConnectionUI({
select_openai_comp_model.dispatchEvent(new Event('change', { bubbles: true })); select_openai_comp_model.dispatchEvent(new Event('change', { bubbles: true }));
}); });
document.getElementById('btnGiveAllUrlsPermission_ollama_api').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnGiveAllUrlsPermission_ollama_api')).addEventListener('click', async () => {
varConnectionUI.permission_all_urls = await messenger.permissions.request({ origins: ["<all_urls>"] }); varConnectionUI.permission_all_urls = await messenger.permissions.request({ origins: ["<all_urls>"] });
}); });
document.getElementById('btnGiveAllUrlsPermission_openai_comp_api').addEventListener('click', async () => { document.getElementById(getPrefixedId('btnGiveAllUrlsPermission_openai_comp_api')).addEventListener('click', async () => {
varConnectionUI.permission_all_urls = await messenger.permissions.request({ origins: ["<all_urls>"] }); varConnectionUI.permission_all_urls = await messenger.permissions.request({ origins: ["<all_urls>"] });
}); });
@ -989,19 +1005,19 @@ export async function initializeSpecificIntegrationUI({
// Helper to update prompt // Helper to update prompt
const _updatePrompt = async () => { const _updatePrompt = async () => {
let conntype = conntype_el.value; let conntype = conntype_el.value;
let integration = conntype.replace('_api', '');
let prompt = await loadPrompt(promptId); let prompt = await loadPrompt(promptId);
if(!prompt) return; if(!prompt) return;
prompt.api = conntype; prompt.api = conntype;
if (integration_options_config[integration]) { for (const [integration, options] of Object.entries(integration_options_config)) {
for (const key of Object.keys(integration_options_config[integration])) { for (const key of Object.keys(options)) {
let elementId = `${model_prefix}${integration}_${key}`; let propName = `${integration}_${key}`;
let elementId = `${model_prefix}${propName}`;
let element = document.getElementById(elementId); let element = document.getElementById(elementId);
if (element) { if (element) {
prompt[key] = (element.type === 'checkbox') ? element.checked : element.value; prompt[propName] = (element.type === 'checkbox') ? element.checked : element.value;
} }
} }
} }
@ -1077,7 +1093,7 @@ export function changeConnTypeRowColor(conntype_row, conntype_select) {
conntype_row.classList.toggle("conntype_anthropic_api", (conntype_select.value === "anthropic_api")); conntype_row.classList.toggle("conntype_anthropic_api", (conntype_select.value === "anthropic_api"));
} }
export function showConnectionOptions(conntype_select) { export function showConnectionOptions(conntype_select, modelId_prefix = '') {
let chatgpt_web_display = 'table-row'; let chatgpt_web_display = 'table-row';
let chatgpt_api_display = 'none'; let chatgpt_api_display = 'none';
let ollama_api_display = 'none'; let ollama_api_display = 'none';
@ -1135,8 +1151,10 @@ export function showConnectionOptions(conntype_select) {
element.style.display = anthropic_api_display; element.style.display = anthropic_api_display;
}); });
if (varConnectionUI.permission_all_urls) { if (varConnectionUI.permission_all_urls) {
document.getElementById('openai_comp_api_cors_warning').style.display = 'none'; const openaiCompWarning = document.getElementById((modelId_prefix ? modelId_prefix : '') + 'openai_comp_api_cors_warning');
document.getElementById('ollama_api_cors_warning').style.display = 'none'; if (openaiCompWarning) openaiCompWarning.style.display = 'none';
const ollamaWarning = document.getElementById((modelId_prefix ? modelId_prefix : '') + 'ollama_api_cors_warning');
if (ollamaWarning) ollamaWarning.style.display = 'none';
} }
} }
@ -1190,7 +1208,7 @@ function warn_InvalidNumber(event){
function warn_ChatGPT_APIKeyEmpty(modelId_prefix) { function warn_ChatGPT_APIKeyEmpty(modelId_prefix) {
const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`; const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`;
let apiKeyInput = document.getElementById(getPrefixedId('chatgpt_api_key')); let apiKeyInput = document.getElementById(getPrefixedId('chatgpt_api_key'));
let btnFetchChatGPTModels = document.getElementById('btnUpdateChatGPTModels'); let btnFetchChatGPTModels = document.getElementById(getPrefixedId('btnUpdateChatGPTModels'));
let modelChatGPT = getModelEl('chatgpt_model', modelId_prefix); let modelChatGPT = getModelEl('chatgpt_model', modelId_prefix);
if(apiKeyInput.value === ''){ if(apiKeyInput.value === ''){
apiKeyInput.style.border = '2px solid red'; apiKeyInput.style.border = '2px solid red';
@ -1213,7 +1231,7 @@ function warn_ChatGPT_APIKeyEmpty(modelId_prefix) {
function warn_GoogleGemini_APIKeyEmpty(modelId_prefix) { function warn_GoogleGemini_APIKeyEmpty(modelId_prefix) {
const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`; const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`;
let apiKeyInput = document.getElementById(getPrefixedId('google_gemini_api_key')); let apiKeyInput = document.getElementById(getPrefixedId('google_gemini_api_key'));
let btnFetchGoogleGeminiModels = document.getElementById('btnUpdateGoogleGeminiModels'); let btnFetchGoogleGeminiModels = document.getElementById(getPrefixedId('btnUpdateGoogleGeminiModels'));
let modelGoogleGemini = getModelEl('google_gemini_model', modelId_prefix); let modelGoogleGemini = getModelEl('google_gemini_model', modelId_prefix);
if(apiKeyInput.value === ''){ if(apiKeyInput.value === ''){
apiKeyInput.style.border = '2px solid red'; apiKeyInput.style.border = '2px solid red';
@ -1236,7 +1254,7 @@ function warn_GoogleGemini_APIKeyEmpty(modelId_prefix) {
function warn_Ollama_HostEmpty(modelId_prefix) { function warn_Ollama_HostEmpty(modelId_prefix) {
const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`; const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`;
let hostInput = document.getElementById(getPrefixedId('ollama_host')); let hostInput = document.getElementById(getPrefixedId('ollama_host'));
let btnFetchOllamaModels = document.getElementById('btnUpdateOllamaModels'); let btnFetchOllamaModels = document.getElementById(getPrefixedId('btnUpdateOllamaModels'));
let modelOllama = getModelEl('ollama_model', modelId_prefix); let modelOllama = getModelEl('ollama_model', modelId_prefix);
if(hostInput.value === ''){ if(hostInput.value === ''){
hostInput.style.border = '2px solid red'; hostInput.style.border = '2px solid red';
@ -1259,7 +1277,7 @@ function warn_Ollama_HostEmpty(modelId_prefix) {
function warn_OpenAIComp_HostEmpty(modelId_prefix) { function warn_OpenAIComp_HostEmpty(modelId_prefix) {
const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`; const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`;
let hostInput = document.getElementById(getPrefixedId('openai_comp_host')); let hostInput = document.getElementById(getPrefixedId('openai_comp_host'));
let btnUpdateOpenAICompModels = document.getElementById('btnUpdateOpenAICompModels'); let btnUpdateOpenAICompModels = document.getElementById(getPrefixedId('btnUpdateOpenAICompModels'));
let modelOpenAIComp = getModelEl('openai_comp_model', modelId_prefix); let modelOpenAIComp = getModelEl('openai_comp_model', modelId_prefix);
if(hostInput.value === ''){ if(hostInput.value === ''){
hostInput.style.border = '2px solid red'; hostInput.style.border = '2px solid red';
@ -1282,7 +1300,7 @@ function warn_OpenAIComp_HostEmpty(modelId_prefix) {
function warn_Anthropic_APIKeyEmpty(modelId_prefix) { function warn_Anthropic_APIKeyEmpty(modelId_prefix) {
const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`; const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`;
let apiKeyInput = document.getElementById(getPrefixedId('anthropic_api_key')); let apiKeyInput = document.getElementById(getPrefixedId('anthropic_api_key'));
let btnFetchAnthropicModels = document.getElementById('btnUpdateAnthropicModels'); let btnFetchAnthropicModels = document.getElementById(getPrefixedId('btnUpdateAnthropicModels'));
let modelAnthropic = getModelEl('anthropic_model', modelId_prefix); let modelAnthropic = getModelEl('anthropic_model', modelId_prefix);
if(apiKeyInput.value === ''){ if(apiKeyInput.value === ''){
apiKeyInput.style.border = '2px solid red'; apiKeyInput.style.border = '2px solid red';
@ -1305,7 +1323,7 @@ function warn_Anthropic_APIKeyEmpty(modelId_prefix) {
function warn_Anthropic_VersionEmpty(modelId_prefix) { function warn_Anthropic_VersionEmpty(modelId_prefix) {
const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`; const getPrefixedId = (id) => `${modelId_prefix ? `${modelId_prefix}` : ''}${id}`;
let versionInput = document.getElementById(getPrefixedId('anthropic_version')); let versionInput = document.getElementById(getPrefixedId('anthropic_version'));
let btnFetchAnthropicModels = document.getElementById('btnUpdateAnthropicModels'); let btnFetchAnthropicModels = document.getElementById(getPrefixedId('btnUpdateAnthropicModels'));
let modelAnthropic = getModelEl('anthropic_model', modelId_prefix); let modelAnthropic = getModelEl('anthropic_model', modelId_prefix);
if(versionInput.value === ''){ if(versionInput.value === ''){
versionInput.style.border = '2px solid red'; versionInput.style.border = '2px solid red';
@ -1325,13 +1343,13 @@ function warn_Anthropic_VersionEmpty(modelId_prefix) {
} }
} }
function resetOpenAICompConfigs(){ function resetOpenAICompConfigs(modelId_prefix = ''){
let select_openai_comp_model = document.getElementById('openai_comp_services_shortcut'); let select_openai_comp_model = document.getElementById((modelId_prefix ? modelId_prefix : '') + 'openai_comp_services_shortcut');
select_openai_comp_model.value = 'custom'; select_openai_comp_model.value = 'custom';
} }
function loadOpenAICompConfigs(){ function loadOpenAICompConfigs(modelId_prefix = ''){
let select_openai_comp_model = document.getElementById('openai_comp_services_shortcut'); let select_openai_comp_model = document.getElementById((modelId_prefix ? modelId_prefix : '') + 'openai_comp_services_shortcut');
openAICompConfigs.forEach(config => { openAICompConfigs.forEach(config => {
const option = document.createElement('option'); const option = document.createElement('option');
option.value = config.id; option.value = config.id;

View file

@ -339,5 +339,23 @@ async function restoreOptions() {
} }
let getting = await browser.storage.sync.get(prefs_default); let getting = await browser.storage.sync.get(prefs_default);
let specialPrompts = await getSpecialPrompts();
let addtags_prompt = specialPrompts.find(prompt => prompt.id === 'prompt_add_tags');
if (addtags_prompt) {
if (addtags_prompt.api && addtags_prompt.api !== '') {
getting['add_tags_connection_type'] = addtags_prompt.api;
}
for (const [integration, options] of Object.entries(integration_options_config)) {
for (const key of Object.keys(options)) {
const propName = `${integration}_${key}`;
if (addtags_prompt[propName] !== undefined) {
getting[`add_tags_${propName}`] = addtags_prompt[propName];
}
}
}
}
setCurrentChoice(getting); setCurrentChoice(getting);
} }

View file

@ -16,9 +16,30 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
import { prefs_default } from "../../options/mzta-options-default.js"; import {
import { getPrompts, setDefaultPromptsProperties, setCustomPrompts, preparePromptsForExport, preparePromptsForImport } from "../../js/mzta-prompts.js"; prefs_default,
import { ChatGPTWeb_models, isThunderbird128OrGreater, getLocalStorageUsedSpace, sanitizeHtml, validateCustomData_ChatGPTWeb, getChatGPTWebModelsList_HTML, openTab } from "../../js/mzta-utils.js"; integration_options_config
} from "../../options/mzta-options-default.js";
import {
getPrompts,
setDefaultPromptsProperties,
setCustomPrompts,
preparePromptsForExport,
preparePromptsForImport
} from "../../js/mzta-prompts.js";
import {
injectConnectionUI,
showConnectionOptions
} from "../../pages/_lib/connection-ui.js";
import {
ChatGPTWeb_models,
isThunderbird128OrGreater,
getLocalStorageUsedSpace,
sanitizeHtml,
validateCustomData_ChatGPTWeb,
getChatGPTWebModelsList_HTML,
openTab
} from "../../js/mzta-utils.js";
import { taLogger } from "../../js/mzta-logger.js"; import { taLogger } from "../../js/mzta-logger.js";
import { import {
getPlaceholders, getPlaceholders,
@ -106,6 +127,59 @@ document.addEventListener('DOMContentLoaded', async () => {
i18n.updateDocument(); i18n.updateDocument();
// Inject API Configuration UI for New Prompt
const webToggle = document.getElementById('chatgpt_web_additional_info_toggle');
const apiSettingsToggle = document.createElement('tr');
apiSettingsToggle.id = 'api_additional_info_toggle';
apiSettingsToggle.className = 'small_info';
apiSettingsToggle.style.cursor = 'pointer';
apiSettingsToggle.innerHTML = '<td colspan="5"><span>' + browser.i18n.getMessage('customPrompts_show_additional_info') + ' [API]</span></td>';
const apiSettingsRow = document.createElement('tr');
apiSettingsRow.id = 'api_additional_info';
apiSettingsRow.style.display = 'none';
apiSettingsRow.innerHTML = '<td colspan="5" id="api_ui_container"></td>';
webToggle.parentNode.insertBefore(apiSettingsToggle, webToggle.nextSibling);
webToggle.parentNode.insertBefore(apiSettingsRow, apiSettingsToggle.nextSibling);
apiSettingsToggle.addEventListener('click', (e) => {
e.preventDefault();
if (apiSettingsRow.style.display === 'none') {
apiSettingsRow.style.display = 'table-row';
apiSettingsToggle.querySelector('span').innerText = browser.i18n.getMessage('customPrompts_hide_additional_info') + ' [API]';
} else {
apiSettingsRow.style.display = 'none';
apiSettingsToggle.querySelector('span').innerText = browser.i18n.getMessage('customPrompts_show_additional_info') + ' [API]';
}
});
const apiTable = document.createElement('table');
apiTable.style.width = "100%";
apiTable.innerHTML = '<tr id="api_ui_anchor"><td class="w30">' + browser.i18n.getMessage('prefs_Connection_type') + ':</td><td><select id="new_prompt_api_type" class="input_new"><option value="">-- ' + browser.i18n.getMessage('Custom') + ' --</option></select></td></tr>';
document.getElementById('api_ui_container').appendChild(apiTable);
await injectConnectionUI({
afterTrId: 'api_ui_anchor',
selectId: 'new_prompt_api_type',
no_chatgpt_web: true,
taLog: taLog
});
const apiSelect = document.getElementById('new_prompt_api_type');
// Remove chatgpt_web
// for (let i = 0; i < apiSelect.options.length; i++) {
// if (apiSelect.options[i].value === 'chatgpt_web') {
// apiSelect.remove(i);
// break;
// }
// }
apiSelect.addEventListener('change', () => {
showConnectionOptions(apiSelect);
});
showConnectionOptions(apiSelect);
switch(prefs.connection_type) { switch(prefs.connection_type) {
case 'chatgpt_web': { case 'chatgpt_web': {
// for the new item form // for the new item form
@ -120,7 +194,7 @@ document.addEventListener('DOMContentLoaded', async () => {
e.target.innerText = browser.i18n.getMessage('customPrompts_hide_additional_info'); e.target.innerText = browser.i18n.getMessage('customPrompts_hide_additional_info');
} else { } else {
additionalInfoRow.style.display = 'none'; additionalInfoRow.style.display = 'none';
e.target.innerText = browser.i18n.getMessage('customPrompts_show_additional_info'); e.target.innerText = browser.i18n.getMessage('customPrompts_show_additional_info') + ' [ChatGPT Web]';
} }
}); });
}); });
@ -132,6 +206,24 @@ document.addEventListener('DOMContentLoaded', async () => {
}); });
break; break;
} }
}
// for the edit list items form [API]
document.querySelectorAll('.api_additional_info_toggle').forEach(element => {
element.addEventListener('click', (e) => {
e.preventDefault();
let additionalInfoRow = e.target.closest('td').querySelector('.api_additional_info');
if (additionalInfoRow.style.display === 'none' || additionalInfoRow.style.display === '') {
additionalInfoRow.style.display = 'block';
e.target.innerText = browser.i18n.getMessage('customPrompts_hide_additional_info') + ' [API]';
} else {
additionalInfoRow.style.display = 'none';
e.target.innerText = browser.i18n.getMessage('customPrompts_show_additional_info') + ' [API]';
}
});
});
switch(prefs.connection_type) {
// case 'chatgpt_api': // case 'chatgpt_api':
// document.getElementById('chatgpt_api').style.display = 'block'; // document.getElementById('chatgpt_api').style.display = 'block';
// break; // break;
@ -214,6 +306,7 @@ document.addEventListener('DOMContentLoaded', async () => {
position_display: positionMax_display + 1, position_display: positionMax_display + 1,
is_default: 0, is_default: 0,
idnum: idnumMax + 1, idnum: idnumMax + 1,
api_type: document.getElementById('new_prompt_api_type').value
}; };
switch(prefs.connection_type) { switch(prefs.connection_type) {
@ -236,6 +329,9 @@ document.addEventListener('DOMContentLoaded', async () => {
// break; // break;
} }
const apiValues = getAPIValuesFromUI();
Object.assign(newItemData, apiValues);
let newItem = promptsList.add(newItemData); let newItem = promptsList.add(newItemData);
idnumMax++; idnumMax++;
let curr_idnum = newItem[0].values().idnum; let curr_idnum = newItem[0].values().idnum;
@ -348,6 +444,10 @@ document.addEventListener('DOMContentLoaded', async () => {
document.querySelectorAll('.chatgpt_web_additional_info_show').forEach(element => { document.querySelectorAll('.chatgpt_web_additional_info_show').forEach(element => {
toggleAdditionalPropertiesShow(element.closest('tr')); toggleAdditionalPropertiesShow(element.closest('tr'));
}); });
document.querySelectorAll('.api_additional_info_show').forEach(element => {
toggleApiPropertiesShow(element.closest('tr'));
});
getChatGPTWebModelsList_HTML(ChatGPTWeb_models, 'chatgpt_web_models_list'); getChatGPTWebModelsList_HTML(ChatGPTWeb_models, 'chatgpt_web_models_list');
let formNewWebModelList = document.getElementById('chatgpt_web_models_list'); let formNewWebModelList = document.getElementById('chatgpt_web_models_list');
@ -381,6 +481,28 @@ document.getElementById('btnManageCustomDataPH').addEventListener('click', () =>
function handleEditClick(e) { function handleEditClick(e) {
e.preventDefault(); e.preventDefault();
const tr = e.target.parentNode.parentNode; const tr = e.target.parentNode.parentNode;
const id = tr.querySelector('.id_output').value;
// Inject Connection UI if needed
const anchorId = `api_ui_anchor_${id}`;
const selectId = `api_type_${id}`;
const prefix = `prompt_${id}_`;
if (!document.getElementById(selectId)) {
injectConnectionUI({
afterTrId: anchorId,
selectId: selectId,
modelId_prefix: prefix,
no_chatgpt_web: true,
taLog: taLog
}).then(() => {
populateConnectionUI(tr, id, prefix, selectId);
});
} else {
populateConnectionUI(tr, id, prefix, selectId);
}
// Show/Hide buttons
//console.log('>>>>>>>> tr: ' + tr.getAttribute('data-idnum')); //console.log('>>>>>>>> tr: ' + tr.getAttribute('data-idnum'));
e.target.style.display = 'none'; // Edit btn e.target.style.display = 'none'; // Edit btn
tr.querySelector('.btnConfirmItem').style.display = 'inline'; // Save btn tr.querySelector('.btnConfirmItem').style.display = 'inline'; // Save btn
@ -391,6 +513,29 @@ function handleEditClick(e) {
toggleDiffviewer(e); toggleDiffviewer(e);
} }
function populateConnectionUI(tr, id, prefix, selectId) {
const item = promptsList.get('id', id)[0];
const itemValues = item.values();
const selectEl = document.getElementById(selectId);
if (selectEl) {
selectEl.value = itemValues.api_type || '';
showConnectionOptions(selectEl);
}
for (const [integration, options] of Object.entries(integration_options_config)) {
for (const key of Object.keys(options)) {
const propName = `${integration}_${key}`;
const inputId = `${prefix}${propName}`;
const inputEl = document.getElementById(inputId);
if (inputEl) {
inputEl.type === 'checkbox' ? inputEl.checked = (itemValues[propName] === true || itemValues[propName] === 'true') : inputEl.value = itemValues[propName] || '';
}
}
}
i18n.updateDocument();
}
function showItemRowEditor(tr) { function showItemRowEditor(tr) {
tr.querySelector('.id_output').style.display = 'inline'; tr.querySelector('.id_output').style.display = 'inline';
tr.querySelector('.id_show').style.display = 'none'; tr.querySelector('.id_show').style.display = 'none';
@ -402,6 +547,7 @@ function showItemRowEditor(tr) {
tr.querySelector('.text_show').style.display = 'none'; tr.querySelector('.text_show').style.display = 'none';
toggleAdditionalPropertiesEditor(tr); toggleAdditionalPropertiesEditor(tr);
tr.querySelector('.chatgpt_web_additional_info_show').style.display = 'none'; tr.querySelector('.chatgpt_web_additional_info_show').style.display = 'none';
tr.querySelector('.api_additional_info_show').style.display = 'none';
tr.querySelector('.type_output').style.display = 'inline'; tr.querySelector('.type_output').style.display = 'inline';
tr.querySelector('.type_show').style.display = 'none'; tr.querySelector('.type_show').style.display = 'none';
const action_output = tr.querySelector('.action_output') const action_output = tr.querySelector('.action_output')
@ -424,6 +570,8 @@ function hideItemRowEditor(tr) {
tr.querySelector('.text_show').style.display = 'inline'; tr.querySelector('.text_show').style.display = 'inline';
tr.querySelector('.chatgpt_web_additional_info_toggle').style.display = 'none'; tr.querySelector('.chatgpt_web_additional_info_toggle').style.display = 'none';
tr.querySelector('.chatgpt_web_additional_info').style.display = 'none'; tr.querySelector('.chatgpt_web_additional_info').style.display = 'none';
tr.querySelector('.api_additional_info_toggle').style.display = 'none';
tr.querySelector('.api_additional_info').style.display = 'none';
toggleAdditionalPropertiesShow(tr); toggleAdditionalPropertiesShow(tr);
tr.querySelector('.type_output').style.display = 'none'; tr.querySelector('.type_output').style.display = 'none';
tr.querySelector('.type_show').style.display = 'inline'; tr.querySelector('.type_show').style.display = 'inline';
@ -486,6 +634,23 @@ function toggleAdditionalPropertiesShow(tr) {
} }
} }
function toggleApiPropertiesShow(tr) {
let element = tr.querySelector('.api_additional_info_show');
let api_type_show = tr.querySelector('.api_type_show');
if (api_type_show.innerText !== '' && api_type_show.innerText !== 'undefined') {
element.style.display = 'flex';
} else {
element.style.display = 'none';
}
if(api_type_show.innerText === '' || api_type_show.innerText === 'undefined') {
api_type_show.parentNode.style.display = 'none';
} else {
api_type_show.parentNode.style.display = 'inline';
}
}
function toggleAdditionalPropertiesEditor(tr) { function toggleAdditionalPropertiesEditor(tr) {
switch(prefs.connection_type) { switch(prefs.connection_type) {
case 'chatgpt_web': { case 'chatgpt_web': {
@ -515,6 +680,14 @@ function toggleAdditionalPropertiesEditor(tr) {
// document.getElementById('google_gemini_api').style.display = 'block'; // document.getElementById('google_gemini_api').style.display = 'block';
// break; // break;
} }
let api_info_toggle = tr.querySelector('.api_additional_info_toggle');
api_info_toggle.style.display = 'block';
let api_type_show = tr.querySelector('.api_type_show').innerText;
if (api_type_show !== '' && api_type_show !== 'undefined') {
api_info_toggle.click();
}
} }
function toggleDiffviewer(e) { function toggleDiffviewer(e) {
@ -574,17 +747,41 @@ function handleConfirmClick(e) {
e.preventDefault(); e.preventDefault();
const tr = e.target.parentNode.parentNode; const tr = e.target.parentNode.parentNode;
e.target.style.display = 'none'; // Ok btn e.target.style.display = 'none'; // Ok btn
const oldId = tr.querySelector('.id_show').innerText;
const prefix = `prompt_${oldId}_`;
const selectId = `api_type_${oldId}`;
let newValues = {};
// Standard fields
newValues.id = tr.querySelector('.id_output').value.trim().toLowerCase();
newValues.name = tr.querySelector('.name_output').value.trim();
newValues.text = tr.querySelector('.text_output').value;
newValues.type = tr.querySelector('.type_output').value;
newValues.action = tr.querySelector('.action_output').value;
newValues.need_selected = tr.querySelector('.need_selected').checked ? 1 : 0;
newValues.need_signature = tr.querySelector('.need_signature').checked ? 1 : 0;
newValues.need_custom_text = tr.querySelector('.need_custom_text').checked ? 1 : 0;
newValues.define_response_lang = tr.querySelector('.define_response_lang').checked ? 1 : 0;
newValues.use_diff_viewer = tr.querySelector('.use_diff_viewer').checked ? 1 : 0;
newValues.enabled = tr.querySelector('.enabled').checked ? 1 : 0;
newValues.chatgpt_web_model = tr.querySelector('.chatgpt_web_model_output').value.trim();
newValues.chatgpt_web_project = tr.querySelector('.chatgpt_web_project_output').value.trim();
newValues.chatgpt_web_custom_gpt = tr.querySelector('.chatgpt_web_custom_gpt_output').value.trim();
const selectEl = document.getElementById(selectId);
if(selectEl) newValues.api_type = selectEl.value;
const apiValues = getAPIValuesFromUI(prefix);
Object.assign(newValues, apiValues);
promptsList.get('id', oldId)[0].values(newValues);
// tr.querySelector('.btnConfirmItem').style.display = 'none'; // Ok btn // tr.querySelector('.btnConfirmItem').style.display = 'none'; // Ok btn
tr.querySelector('.btnCancelItem').style.display = 'none'; // Cancel btn tr.querySelector('.btnCancelItem').style.display = 'none'; // Cancel btn
tr.querySelector('.btnEditItem').style.display = 'inline'; // Edit btn tr.querySelector('.btnEditItem').style.display = 'inline'; // Edit btn
tr.querySelector('.btnDeleteItem').style.display = 'inline'; // Delete btn tr.querySelector('.btnDeleteItem').style.display = 'inline'; // Delete btn
// Update item data // Update item data
tr.querySelector('.id_show').innerText = String(tr.querySelector('.id_output').value).toLocaleLowerCase();
tr.querySelector('.name_show').innerText = tr.querySelector('.name_output').value;
tr.querySelector('.text_show').innerText = tr.querySelector('.text_output').value;
tr.querySelector('.chatgpt_web_model_show').innerText = tr.querySelector('.chatgpt_web_model_output').value;
tr.querySelector('.chatgpt_web_project_show').innerText = tr.querySelector('.chatgpt_web_project_output').value;
tr.querySelector('.chatgpt_web_custom_gpt_show').innerText = tr.querySelector('.chatgpt_web_custom_gpt_output').value;
tr.querySelector('.type').innerText = tr.querySelector('.type_output').value; tr.querySelector('.type').innerText = tr.querySelector('.type_output').value;
tr.querySelector('.type_show').innerText = tr.querySelector('.type_output').selectedOptions[0].text; tr.querySelector('.type_show').innerText = tr.querySelector('.type_output').selectedOptions[0].text;
tr.querySelector('.action').innerText = tr.querySelector('.action_output').value; tr.querySelector('.action').innerText = tr.querySelector('.action_output').value;
@ -617,8 +814,15 @@ function handleInputChange(e) {
function loadPromptsList(values){ function loadPromptsList(values){
// console.log('>>>>>>>> loadPromptsList values: ' + JSON.stringify(values)); // console.log('>>>>>>>> loadPromptsList values: ' + JSON.stringify(values));
let api_fields = [];
for (const [integration, options] of Object.entries(integration_options_config)) {
for (const key of Object.keys(options)) {
api_fields.push(`${integration}_${key}`);
}
}
let options = { let options = {
valueNames: [ { data: ['idnum'] }, 'is_default', 'id', 'name', 'text', 'type', 'action', 'position_compose', 'position_display', { name: 'need_selected', attr: 'checked_val'}, { name: 'need_signature', attr: 'checked_val'}, { name: 'need_custom_text', attr: 'checked_val'}, { name: 'define_response_lang', attr: 'checked_val'}, { name: 'use_diff_viewer', attr: 'checked_val'}, { name: 'enabled', attr: 'checked_val'} ], valueNames: [ { data: ['idnum'] }, 'is_default', 'id', 'name', 'text', 'type', 'action', 'position_compose', 'position_display', { name: 'need_selected', attr: 'checked_val'}, { name: 'need_signature', attr: 'checked_val'}, { name: 'need_custom_text', attr: 'checked_val'}, { name: 'define_response_lang', attr: 'checked_val'}, { name: 'use_diff_viewer', attr: 'checked_val'}, { name: 'enabled', attr: 'checked_val'}, 'api_type', ...api_fields ],
item: function(values) { item: function(values) {
let type_output = ''; let type_output = '';
switch(String(values.type)){ switch(String(values.type)){
@ -676,6 +880,14 @@ function loadPromptsList(values){
<br>__MSG_prefs_OptionText_chatgpt_web_custom_data_info2__ <br>__MSG_prefs_OptionText_chatgpt_web_custom_data_info2__
<br>__MSG_prefs_OptionText_CustomGPT_Warn__</i> <br>__MSG_prefs_OptionText_CustomGPT_Warn__</i>
</div> </div>
<div class="api_additional_info_toggle small_info">__MSG_customPrompts_show_additional_info__ [API]</div>
<div class="api_additional_info">
<table style="width:100%">
<tbody id="api_ui_container_` + values.id + `">
<tr id="api_ui_anchor_` + values.id + `"><td style="display:none"></td></tr>
</tbody>
</table>
</div>
</td> </td>
<td class="w08"><span class="field_title_s">__MSG_customPrompts_add_to_menu__:</span> <td class="w08"><span class="field_title_s">__MSG_customPrompts_add_to_menu__:</span>
<br> <br>
@ -711,11 +923,14 @@ function loadPromptsList(values){
<span class="is_default hiddendata"></span> <span class="is_default hiddendata"></span>
<span class="position_compose hiddendata"></span> <span class="position_compose hiddendata"></span>
<span class="position_display hiddendata"></span> <span class="position_display hiddendata"></span>
<div class="chatgpt_web_additional_info_show small_info"><span class="chatgpt_web_additional_info_row field_title"><i>__MSG_customPrompts_show_additional_info_show__</i></span> <div class="chatgpt_web_additional_info_show small_info"><span class="chatgpt_web_additional_info_row field_title"><i>__MSG_customPrompts_show_additional_info_show__ [ChatGPT Web]</i></span>
<div class="chatgpt_web_additional_info_row"><span class="field_title">__MSG_prefs_OptionText_chatgpt_web_model__:</span><span class="chatgpt_web_model chatgpt_web_model_show">` + values.chatgpt_web_model + `</span></div> <div class="chatgpt_web_additional_info_row"><span class="field_title">__MSG_prefs_OptionText_chatgpt_web_model__:</span><span class="chatgpt_web_model chatgpt_web_model_show">` + values.chatgpt_web_model + `</span></div>
<div class="chatgpt_web_additional_info_row"><span class="field_title">__MSG_prefs_OptionText_chatgpt_web_project__:</span><span class="chatgpt_web_project chatgpt_web_project_show">` + values.chatgpt_web_project + `</span></div> <div class="chatgpt_web_additional_info_row"><span class="field_title">__MSG_prefs_OptionText_chatgpt_web_project__:</span><span class="chatgpt_web_project chatgpt_web_project_show">` + values.chatgpt_web_project + `</span></div>
<div class="chatgpt_web_additional_info_row"><span class="field_title">__MSG_prefs_OptionText_chatgpt_web_custom_gpt__:</span><span class="chatgpt_web_custom_gpt chatgpt_web_custom_gpt_show">` + values.chatgpt_web_custom_gpt + `</span></div> <div class="chatgpt_web_additional_info_row"><span class="field_title">__MSG_prefs_OptionText_chatgpt_web_custom_gpt__:</span><span class="chatgpt_web_custom_gpt chatgpt_web_custom_gpt_show">` + values.chatgpt_web_custom_gpt + `</span></div>
</div> </div>
<div class="api_additional_info_show small_info"><span class="api_additional_info_row field_title"><i>__MSG_customPrompts_show_additional_info_show__ [API]</i></span>
<div class="api_additional_info_row"><span class="field_title">__MSG_prefs_Connection_type__:</span><span class="api_type api_type_show">` + values.api_type + `</span></div>
</div>
</td> </td>
<td> <td>
<button class="btnEditItem"` + ((values.is_default == 1) ? ' disabled':'') + `>__MSG_customPrompts_btnEdit__</button> <button class="btnEditItem"` + ((values.is_default == 1) ? ' disabled':'') + `>__MSG_customPrompts_btnEdit__</button>
@ -840,6 +1055,21 @@ function clearFields() {
document.getElementById('formNew').style.display = 'none'; document.getElementById('formNew').style.display = 'none';
} }
function getAPIValuesFromUI(prefix = '') {
let values = {};
for (const [integration, options] of Object.entries(integration_options_config)) {
for (const key of Object.keys(options)) {
const propName = `${integration}_${key}`;
const inputId = `${prefix}${propName}`;
const inputEl = document.getElementById(inputId);
if (inputEl) {
values[propName] = (inputEl.type === 'checkbox') ? inputEl.checked : inputEl.value;
}
}
}
return values;
}
function inputSetError(input) { function inputSetError(input) {
document.getElementById(input).style.borderColor = 'red'; document.getElementById(input).style.borderColor = 'red';
} }
@ -897,8 +1127,6 @@ async function saveAll() {
setMessage(browser.i18n.getMessage('customPrompts_start_saving')); setMessage(browser.i18n.getMessage('customPrompts_start_saving'));
setNothingChanged(); setNothingChanged();
if(promptsList != null) { if(promptsList != null) {
setMessage(browser.i18n.getMessage('customPrompts_reindexing_list'));
promptsList.reIndex();
let newPrompts = promptsList.items.map(item => { let newPrompts = promptsList.items.map(item => {
// For each item in the array, return only the '_values' part // For each item in the array, return only the '_values' part
// console.log(">>>>>>>>>>>>>>>> item: " + JSON.stringify(item)) // console.log(">>>>>>>>>>>>>>>> item: " + JSON.stringify(item))

View file

@ -42,21 +42,6 @@ document.addEventListener('DOMContentLoaded', async () => {
let specialPrompts = await getSpecialPrompts(); let specialPrompts = await getSpecialPrompts();
let spamfilter_prompt = specialPrompts.find(prompt => prompt.id === 'prompt_spamfilter'); let spamfilter_prompt = specialPrompts.find(prompt => prompt.id === 'prompt_spamfilter');
if (spamfilter_prompt && spamfilter_prompt.api && spamfilter_prompt.api !== '') {
let update_prefs = {};
update_prefs['spamfilter_connection_type'] = spamfilter_prompt.api;
let integration = spamfilter_prompt.api.replace('_api', '');
if (integration_options_config && integration_options_config[integration]) {
for (const key of Object.keys(integration_options_config[integration])) {
if (spamfilter_prompt[key] !== undefined) {
update_prefs[`spamfilter_${integration}_${key}`] = spamfilter_prompt[key];
}
}
}
await browser.storage.sync.set(update_prefs);
}
await initializeSpecificIntegrationUI({ await initializeSpecificIntegrationUI({
prefix: 'spamfilter', prefix: 'spamfilter',
promptId: 'prompt_spamfilter', promptId: 'prompt_spamfilter',
@ -323,5 +308,23 @@ async function restoreOptions() {
} }
let getting = await browser.storage.sync.get(prefs_default); let getting = await browser.storage.sync.get(prefs_default);
let specialPrompts = await getSpecialPrompts();
let spamfilter_prompt = specialPrompts.find(prompt => prompt.id === 'prompt_spamfilter');
if (spamfilter_prompt) {
if (spamfilter_prompt.api && spamfilter_prompt.api !== '') {
getting['spamfilter_connection_type'] = spamfilter_prompt.api;
}
for (const [integration, options] of Object.entries(integration_options_config)) {
for (const key of Object.keys(options)) {
const propName = `${integration}_${key}`;
if (spamfilter_prompt[propName] !== undefined) {
getting[`spamfilter_${propName}`] = spamfilter_prompt[propName];
}
}
}
}
setCurrentChoice(getting); setCurrentChoice(getting);
} }