const saveBtn = document.getElementById("saveBtn"); const saveBtnSidebar = document.getElementById("saveBtnSidebar"); const addApiConfigBtn = document.getElementById("addApiConfigBtn"); const apiConfigsContainer = document.getElementById("apiConfigs"); const addApiKeyBtn = document.getElementById("addApiKeyBtn"); const apiKeysContainer = document.getElementById("apiKeys"); const addEnvConfigBtn = document.getElementById("addEnvConfigBtn"); const envConfigsContainer = document.getElementById("envConfigs"); const addTaskBtn = document.getElementById("addTaskBtn"); const tasksContainer = document.getElementById("tasks"); const addProfileBtn = document.getElementById("addProfileBtn"); const profilesContainer = document.getElementById("profiles"); const addWorkspaceBtn = document.getElementById("addWorkspaceBtn"); const workspacesContainer = document.getElementById("workspaces"); const addSiteBtn = document.getElementById("addSiteBtn"); const sitesContainer = document.getElementById("sites"); const addPresetBtn = document.getElementById("addPresetBtn"); const presetsContainer = document.getElementById("presets"); const statusEl = document.getElementById("status"); const statusSidebarEl = document.getElementById("statusSidebar"); const sidebarErrorsEl = document.getElementById("sidebarErrors"); const themeSelect = document.getElementById("themeSelect"); const toolbarPositionSelect = document.getElementById("toolbarPositionSelect"); const OPENAI_DEFAULTS = { apiBaseUrl: "https://api.openai.com/v1", apiKeyHeader: "Authorization", apiKeyPrefix: "Bearer " }; const DEFAULT_MODEL = "gpt-4o-mini"; const DEFAULT_SYSTEM_PROMPT = "You are a precise, honest assistant. Be concise and avoid inventing details, be critical about evaluations. You should put in a small summary of all the sections at the end. You should answer in no longer than 3 sections including the summary. And remember to bold or italicize key points."; function getStorage(keys) { return new Promise((resolve) => chrome.storage.local.get(keys, resolve)); } function setStatus(message) { statusEl.textContent = message; if (statusSidebarEl) statusSidebarEl.textContent = message; if (!message) return; setTimeout(() => { if (statusEl.textContent === message) statusEl.textContent = ""; if (statusSidebarEl?.textContent === message) statusSidebarEl.textContent = ""; }, 2000); } let sidebarErrorFrame = null; function scheduleSidebarErrors() { if (!sidebarErrorsEl) return; if (sidebarErrorFrame) return; sidebarErrorFrame = requestAnimationFrame(() => { sidebarErrorFrame = null; updateSidebarErrors(); }); } function applyTheme(theme) { const value = theme || "system"; document.documentElement.dataset.theme = value; } function newTaskId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `task-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newApiKeyId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `key-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newApiConfigId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `config-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newEnvConfigId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `env-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newProfileId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `profile-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newWorkspaceId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `ws-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newSiteId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `site-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function newPresetId() { if (crypto?.randomUUID) return crypto.randomUUID(); return `preset-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; } function buildChatUrlFromBase(baseUrl) { const trimmed = (baseUrl || "").trim().replace(/\/+$/, ""); if (!trimmed) return ""; if (trimmed.endsWith("/chat/completions")) return trimmed; return `${trimmed}/chat/completions`; } function collectNames(container, selector) { if (!container) return []; return [...container.querySelectorAll(selector)] .map((input) => (input.value || "").trim()) .filter(Boolean); } function buildUniqueDefaultName(names) { const lower = new Set(names.map((name) => name.toLowerCase())); if (!lower.has("default")) return "Default"; let index = 2; while (lower.has(`default-${index}`)) { index += 1; } return `Default-${index}`; } function ensureUniqueName(desired, existingNames) { const trimmed = (desired || "").trim(); const lowerNames = existingNames.map((name) => name.toLowerCase()); if (trimmed && !lowerNames.includes(trimmed.toLowerCase())) { return trimmed; } return buildUniqueDefaultName(existingNames); } function getTopEnvId() { return collectEnvConfigs()[0]?.id || ""; } function getTopProfileId() { return collectProfiles()[0]?.id || ""; } function setApiConfigAdvanced(card, isAdvanced) { card.classList.toggle("is-advanced", isAdvanced); card.dataset.mode = isAdvanced ? "advanced" : "basic"; const basicFields = card.querySelectorAll( ".basic-only input, .basic-only textarea" ); const advancedFields = card.querySelectorAll( ".advanced-only input, .advanced-only textarea" ); basicFields.forEach((field) => { field.disabled = isAdvanced; }); advancedFields.forEach((field) => { field.disabled = !isAdvanced; }); const resetBtn = card.querySelector(".reset-openai"); if (resetBtn) resetBtn.disabled = false; const advancedBtn = card.querySelector(".advanced-toggle"); if (advancedBtn) advancedBtn.disabled = isAdvanced; } function readApiConfigFromCard(card) { const nameInput = card.querySelector(".api-config-name"); const keySelect = card.querySelector(".api-config-key-select"); const baseInput = card.querySelector(".api-config-base"); const headerInput = card.querySelector(".api-config-header"); const prefixInput = card.querySelector(".api-config-prefix"); const modelInput = card.querySelector(".api-config-model"); const urlInput = card.querySelector(".api-config-url"); const templateInput = card.querySelector(".api-config-template"); const isAdvanced = card.classList.contains("is-advanced"); return { id: card.dataset.id || newApiConfigId(), name: (nameInput?.value || "Default").trim(), apiKeyId: keySelect?.value || "", apiBaseUrl: (baseInput?.value || "").trim(), apiKeyHeader: (headerInput?.value || "").trim(), apiKeyPrefix: prefixInput?.value || "", model: (modelInput?.value || "").trim(), apiUrl: (urlInput?.value || "").trim(), requestTemplate: (templateInput?.value || "").trim(), advanced: isAdvanced }; } function buildApiConfigCard(config) { const card = document.createElement("div"); card.className = "api-config-card"; card.dataset.id = config.id || newApiConfigId(); const isAdvanced = Boolean(config.advanced); const nameField = document.createElement("div"); nameField.className = "field"; const nameLabel = document.createElement("label"); nameLabel.textContent = "Name"; const nameInput = document.createElement("input"); nameInput.type = "text"; nameInput.value = config.name || ""; nameInput.className = "api-config-name"; nameField.appendChild(nameLabel); nameField.appendChild(nameInput); const keyField = document.createElement("div"); keyField.className = "field"; const keyLabel = document.createElement("label"); keyLabel.textContent = "API Key"; const keySelect = document.createElement("select"); keySelect.className = "api-config-key-select"; keySelect.dataset.preferred = config.apiKeyId || ""; keyField.appendChild(keyLabel); keyField.appendChild(keySelect); const baseField = document.createElement("div"); baseField.className = "field basic-only"; const baseLabel = document.createElement("label"); baseLabel.textContent = "API Base URL"; const baseInput = document.createElement("input"); baseInput.type = "text"; baseInput.placeholder = OPENAI_DEFAULTS.apiBaseUrl; baseInput.value = config.apiBaseUrl || ""; baseInput.className = "api-config-base"; baseField.appendChild(baseLabel); baseField.appendChild(baseInput); const headerField = document.createElement("div"); headerField.className = "field advanced-only"; const headerLabel = document.createElement("label"); headerLabel.textContent = "API Key Header"; const headerInput = document.createElement("input"); headerInput.type = "text"; headerInput.placeholder = OPENAI_DEFAULTS.apiKeyHeader; headerInput.value = config.apiKeyHeader || ""; headerInput.className = "api-config-header"; headerField.appendChild(headerLabel); headerField.appendChild(headerInput); const prefixField = document.createElement("div"); prefixField.className = "field advanced-only"; const prefixLabel = document.createElement("label"); prefixLabel.textContent = "API Key Prefix"; const prefixInput = document.createElement("input"); prefixInput.type = "text"; prefixInput.placeholder = OPENAI_DEFAULTS.apiKeyPrefix; prefixInput.value = config.apiKeyPrefix || ""; prefixInput.className = "api-config-prefix"; prefixField.appendChild(prefixLabel); prefixField.appendChild(prefixInput); const modelField = document.createElement("div"); modelField.className = "field basic-only"; const modelLabel = document.createElement("label"); modelLabel.textContent = "Model name"; const modelInput = document.createElement("input"); modelInput.type = "text"; modelInput.placeholder = DEFAULT_MODEL; modelInput.value = config.model || ""; modelInput.className = "api-config-model"; modelField.appendChild(modelLabel); modelField.appendChild(modelInput); const urlField = document.createElement("div"); urlField.className = "field advanced-only"; const urlLabel = document.createElement("label"); urlLabel.textContent = "API URL"; const urlInput = document.createElement("input"); urlInput.type = "text"; urlInput.placeholder = "https://api.example.com/v1/chat/completions"; urlInput.value = config.apiUrl || ""; urlInput.className = "api-config-url"; urlField.appendChild(urlLabel); urlField.appendChild(urlInput); const templateField = document.createElement("div"); templateField.className = "field advanced-only"; const templateLabel = document.createElement("label"); templateLabel.textContent = "Request JSON template"; const templateInput = document.createElement("textarea"); templateInput.rows = 8; templateInput.placeholder = [ "{", " \"stream\": true,", " \"messages\": [", " { \"role\": \"system\", \"content\": \"SYSTEM_PROMPT_GOES_HERE\" },", " { \"role\": \"user\", \"content\": \"PROMPT_GOES_HERE\" }", " ],", " \"api_key\": \"API_KEY_GOES_HERE\"", "}" ].join("\n"); templateInput.value = config.requestTemplate || ""; templateInput.className = "api-config-template"; templateField.appendChild(templateLabel); templateField.appendChild(templateInput); const actions = document.createElement("div"); actions.className = "api-config-actions"; const leftActions = document.createElement("div"); leftActions.className = "api-config-actions-left"; const rightActions = document.createElement("div"); rightActions.className = "api-config-actions-right"; const moveTopBtn = document.createElement("button"); moveTopBtn.type = "button"; moveTopBtn.className = "ghost move-top"; moveTopBtn.textContent = "Top"; const moveUpBtn = document.createElement("button"); moveUpBtn.type = "button"; moveUpBtn.className = "ghost move-up"; moveUpBtn.textContent = "Up"; const moveDownBtn = document.createElement("button"); moveDownBtn.type = "button"; moveDownBtn.className = "ghost move-down"; moveDownBtn.textContent = "Down"; const addBelowBtn = document.createElement("button"); addBelowBtn.type = "button"; addBelowBtn.className = "ghost add-below"; addBelowBtn.textContent = "Add"; moveTopBtn.addEventListener("click", () => { const first = apiConfigsContainer.firstElementChild; if (!first || first === card) return; apiConfigsContainer.insertBefore(card, first); updateApiConfigControls(); updateEnvApiOptions(); }); moveUpBtn.addEventListener("click", () => { const previous = card.previousElementSibling; if (!previous) return; apiConfigsContainer.insertBefore(card, previous); updateApiConfigControls(); updateEnvApiOptions(); }); moveDownBtn.addEventListener("click", () => { const next = card.nextElementSibling; if (!next) return; apiConfigsContainer.insertBefore(card, next.nextElementSibling); updateApiConfigControls(); updateEnvApiOptions(); }); addBelowBtn.addEventListener("click", () => { const name = buildUniqueDefaultName( collectNames(apiConfigsContainer, ".api-config-name") ); const newCard = buildApiConfigCard({ id: newApiConfigId(), name, apiBaseUrl: OPENAI_DEFAULTS.apiBaseUrl, apiKeyHeader: OPENAI_DEFAULTS.apiKeyHeader, apiKeyPrefix: OPENAI_DEFAULTS.apiKeyPrefix, model: DEFAULT_MODEL, apiUrl: "", requestTemplate: "", advanced: false }); card.insertAdjacentElement("afterend", newCard); updateApiConfigKeyOptions(); updateEnvApiOptions(); updateApiConfigControls(); }); const advancedBtn = document.createElement("button"); advancedBtn.type = "button"; advancedBtn.className = "ghost advanced-toggle"; advancedBtn.textContent = "Advanced Mode"; advancedBtn.addEventListener("click", () => { if (card.classList.contains("is-advanced")) return; urlInput.value = buildChatUrlFromBase(baseInput.value); templateInput.value = [ "{", ` \"model\": \"${modelInput.value || DEFAULT_MODEL}\",`, " \"stream\": true,", " \"messages\": [", " { \"role\": \"system\", \"content\": \"SYSTEM_PROMPT_GOES_HERE\" },", " { \"role\": \"user\", \"content\": \"PROMPT_GOES_HERE\" }", " ],", " \"api_key\": \"API_KEY_GOES_HERE\"", "}" ].join("\n"); setApiConfigAdvanced(card, true); updateEnvApiOptions(); }); const duplicateBtn = document.createElement("button"); duplicateBtn.type = "button"; duplicateBtn.className = "ghost duplicate"; duplicateBtn.textContent = "Duplicate"; duplicateBtn.addEventListener("click", () => { const names = collectNames(apiConfigsContainer, ".api-config-name"); const copy = readApiConfigFromCard(card); copy.id = newApiConfigId(); copy.name = ensureUniqueName(`${copy.name || "Default"} Copy`, names); const newCard = buildApiConfigCard(copy); card.insertAdjacentElement("afterend", newCard); updateApiConfigKeyOptions(); updateEnvApiOptions(); }); const resetBtn = document.createElement("button"); resetBtn.type = "button"; resetBtn.className = "ghost reset-openai"; resetBtn.textContent = "Reset to OpenAI"; resetBtn.addEventListener("click", () => { baseInput.value = OPENAI_DEFAULTS.apiBaseUrl; headerInput.value = OPENAI_DEFAULTS.apiKeyHeader; prefixInput.value = OPENAI_DEFAULTS.apiKeyPrefix; modelInput.value = DEFAULT_MODEL; urlInput.value = ""; templateInput.value = ""; setApiConfigAdvanced(card, false); updateEnvApiOptions(); }); const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.className = "ghost delete"; deleteBtn.textContent = "Delete"; deleteBtn.addEventListener("click", () => { card.remove(); updateEnvApiOptions(); updateApiConfigControls(); }); const updateSelect = () => updateEnvApiOptions(); nameInput.addEventListener("input", updateSelect); baseInput.addEventListener("input", updateSelect); headerInput.addEventListener("input", updateSelect); prefixInput.addEventListener("input", updateSelect); modelInput.addEventListener("input", updateSelect); urlInput.addEventListener("input", updateSelect); templateInput.addEventListener("input", updateSelect); rightActions.appendChild(moveTopBtn); rightActions.appendChild(moveUpBtn); rightActions.appendChild(moveDownBtn); rightActions.appendChild(addBelowBtn); rightActions.appendChild(duplicateBtn); rightActions.appendChild(deleteBtn); leftActions.appendChild(advancedBtn); leftActions.appendChild(resetBtn); actions.appendChild(leftActions); actions.appendChild(rightActions); card.appendChild(nameField); card.appendChild(keyField); card.appendChild(baseField); card.appendChild(headerField); card.appendChild(prefixField); card.appendChild(modelField); card.appendChild(urlField); card.appendChild(templateField); card.appendChild(actions); setApiConfigAdvanced(card, isAdvanced); return card; } function collectApiConfigs() { const cards = [...apiConfigsContainer.querySelectorAll(".api-config-card")]; return cards.map((card) => readApiConfigFromCard(card)); } function updateApiConfigControls() { const cards = [...apiConfigsContainer.querySelectorAll(".api-config-card")]; cards.forEach((card, index) => { const moveTopBtn = card.querySelector(".move-top"); const moveUpBtn = card.querySelector(".move-up"); const moveDownBtn = card.querySelector(".move-down"); if (moveTopBtn) moveTopBtn.disabled = index === 0; if (moveUpBtn) moveUpBtn.disabled = index === 0; if (moveDownBtn) moveDownBtn.disabled = index === cards.length - 1; }); scheduleSidebarErrors(); } function buildApiKeyCard(entry) { const card = document.createElement("div"); card.className = "api-key-card"; card.dataset.id = entry.id || newApiKeyId(); const nameField = document.createElement("div"); nameField.className = "field"; const nameLabel = document.createElement("label"); nameLabel.textContent = "Name"; const nameInput = document.createElement("input"); nameInput.type = "text"; nameInput.value = entry.name || ""; nameInput.className = "api-key-name"; nameField.appendChild(nameLabel); nameField.appendChild(nameInput); const keyField = document.createElement("div"); keyField.className = "field"; const keyLabel = document.createElement("label"); keyLabel.textContent = "Key"; const keyInline = document.createElement("div"); keyInline.className = "inline"; const keyInput = document.createElement("input"); keyInput.type = "password"; keyInput.autocomplete = "off"; keyInput.placeholder = "sk-..."; keyInput.value = entry.key || ""; keyInput.className = "api-key-value"; const showBtn = document.createElement("button"); showBtn.type = "button"; showBtn.className = "ghost"; showBtn.textContent = "Show"; showBtn.addEventListener("click", () => { const isPassword = keyInput.type === "password"; keyInput.type = isPassword ? "text" : "password"; showBtn.textContent = isPassword ? "Hide" : "Show"; }); keyInline.appendChild(keyInput); keyInline.appendChild(showBtn); keyField.appendChild(keyLabel); keyField.appendChild(keyInline); const actions = document.createElement("div"); actions.className = "api-key-actions"; const moveTopBtn = document.createElement("button"); moveTopBtn.type = "button"; moveTopBtn.className = "ghost move-top"; moveTopBtn.textContent = "Top"; const moveUpBtn = document.createElement("button"); moveUpBtn.type = "button"; moveUpBtn.className = "ghost move-up"; moveUpBtn.textContent = "Up"; const moveDownBtn = document.createElement("button"); moveDownBtn.type = "button"; moveDownBtn.className = "ghost move-down"; moveDownBtn.textContent = "Down"; const addBelowBtn = document.createElement("button"); addBelowBtn.type = "button"; addBelowBtn.className = "ghost add-below"; addBelowBtn.textContent = "Add"; moveTopBtn.addEventListener("click", () => { const first = apiKeysContainer.firstElementChild; if (!first || first === card) return; apiKeysContainer.insertBefore(card, first); updateApiKeyControls(); updateApiConfigKeyOptions(); }); moveUpBtn.addEventListener("click", () => { const previous = card.previousElementSibling; if (!previous) return; apiKeysContainer.insertBefore(card, previous); updateApiKeyControls(); updateApiConfigKeyOptions(); }); moveDownBtn.addEventListener("click", () => { const next = card.nextElementSibling; if (!next) return; apiKeysContainer.insertBefore(card, next.nextElementSibling); updateApiKeyControls(); updateApiConfigKeyOptions(); }); addBelowBtn.addEventListener("click", () => { const name = buildUniqueDefaultName( collectNames(apiKeysContainer, ".api-key-name") ); const newCard = buildApiKeyCard({ id: newApiKeyId(), name, key: "" }); card.insertAdjacentElement("afterend", newCard); updateApiConfigKeyOptions(); updateApiKeyControls(); }); actions.appendChild(moveTopBtn); actions.appendChild(moveUpBtn); actions.appendChild(moveDownBtn); actions.appendChild(addBelowBtn); const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.className = "ghost delete"; deleteBtn.textContent = "Delete"; deleteBtn.addEventListener("click", () => { card.remove(); updateApiConfigKeyOptions(); updateApiKeyControls(); }); actions.appendChild(deleteBtn); const updateSelect = () => updateApiConfigKeyOptions(); nameInput.addEventListener("input", updateSelect); keyInput.addEventListener("input", updateSelect); card.appendChild(nameField); card.appendChild(keyField); card.appendChild(actions); return card; } function collectApiKeys() { const cards = [...apiKeysContainer.querySelectorAll(".api-key-card")]; return cards.map((card) => { const nameInput = card.querySelector(".api-key-name"); const keyInput = card.querySelector(".api-key-value"); return { id: card.dataset.id || newApiKeyId(), name: (nameInput?.value || "Default").trim(), key: (keyInput?.value || "").trim() }; }); } function updateApiKeyControls() { const cards = [...apiKeysContainer.querySelectorAll(".api-key-card")]; cards.forEach((card, index) => { const moveTopBtn = card.querySelector(".move-top"); const moveUpBtn = card.querySelector(".move-up"); const moveDownBtn = card.querySelector(".move-down"); if (moveTopBtn) moveTopBtn.disabled = index === 0; if (moveUpBtn) moveUpBtn.disabled = index === 0; if (moveDownBtn) moveDownBtn.disabled = index === cards.length - 1; }); scheduleSidebarErrors(); } function updateApiConfigKeyOptions() { const keys = collectApiKeys(); const selects = apiConfigsContainer.querySelectorAll(".api-config-key-select"); selects.forEach((select) => { const preferred = select.dataset.preferred || select.value; select.innerHTML = ""; if (!keys.length) { const option = document.createElement("option"); option.value = ""; option.textContent = "No keys configured"; select.appendChild(option); select.disabled = true; return; } select.disabled = false; for (const key of keys) { const option = document.createElement("option"); option.value = key.id; option.textContent = key.name || "Default"; select.appendChild(option); } if (preferred && keys.some((key) => key.id === preferred)) { select.value = preferred; } else { select.value = keys[0].id; } select.dataset.preferred = select.value; }); } function buildEnvConfigCard(config) { const card = document.createElement("div"); card.className = "env-config-card"; card.dataset.id = config.id || newEnvConfigId(); const nameField = document.createElement("div"); nameField.className = "field"; const nameLabel = document.createElement("label"); nameLabel.textContent = "Name"; const nameInput = document.createElement("input"); nameInput.type = "text"; nameInput.value = config.name || ""; nameInput.className = "env-config-name"; nameField.appendChild(nameLabel); nameField.appendChild(nameInput); const apiField = document.createElement("div"); apiField.className = "field"; const apiLabel = document.createElement("label"); apiLabel.textContent = "API config"; const apiSelect = document.createElement("select"); apiSelect.className = "env-config-api-select"; apiSelect.dataset.preferred = config.apiConfigId || ""; apiField.appendChild(apiLabel); apiField.appendChild(apiSelect); const promptField = document.createElement("div"); promptField.className = "field"; const promptLabel = document.createElement("label"); promptLabel.textContent = "System prompt"; const promptInput = document.createElement("textarea"); promptInput.rows = 8; promptInput.value = config.systemPrompt || ""; promptInput.className = "env-config-prompt"; promptField.appendChild(promptLabel); promptField.appendChild(promptInput); const actions = document.createElement("div"); actions.className = "env-config-actions"; const moveTopBtn = document.createElement("button"); moveTopBtn.type = "button"; moveTopBtn.className = "ghost move-top"; moveTopBtn.textContent = "Top"; const moveUpBtn = document.createElement("button"); moveUpBtn.type = "button"; moveUpBtn.className = "ghost move-up"; moveUpBtn.textContent = "Up"; const moveDownBtn = document.createElement("button"); moveDownBtn.type = "button"; moveDownBtn.className = "ghost move-down"; moveDownBtn.textContent = "Down"; const addBelowBtn = document.createElement("button"); addBelowBtn.type = "button"; addBelowBtn.className = "ghost add-below"; addBelowBtn.textContent = "Add"; moveTopBtn.addEventListener("click", () => { const first = envConfigsContainer.firstElementChild; if (!first || first === card) return; envConfigsContainer.insertBefore(card, first); updateEnvControls(); updateTaskEnvOptions(); }); moveUpBtn.addEventListener("click", () => { const previous = card.previousElementSibling; if (!previous) return; envConfigsContainer.insertBefore(card, previous); updateEnvControls(); updateTaskEnvOptions(); }); moveDownBtn.addEventListener("click", () => { const next = card.nextElementSibling; if (!next) return; envConfigsContainer.insertBefore(card, next.nextElementSibling); updateEnvControls(); updateTaskEnvOptions(); }); actions.appendChild(moveTopBtn); actions.appendChild(moveUpBtn); actions.appendChild(moveDownBtn); actions.appendChild(addBelowBtn); addBelowBtn.addEventListener("click", () => { const name = buildUniqueDefaultName( collectNames(envConfigsContainer, ".env-config-name") ); const fallbackApiConfigId = collectApiConfigs()[0]?.id || ""; const newCard = buildEnvConfigCard({ id: newEnvConfigId(), name, apiConfigId: fallbackApiConfigId, systemPrompt: DEFAULT_SYSTEM_PROMPT }); card.insertAdjacentElement("afterend", newCard); updateEnvApiOptions(); updateEnvControls(); updateTaskEnvOptions(); }); const duplicateBtn = document.createElement("button"); duplicateBtn.type = "button"; duplicateBtn.className = "ghost duplicate"; duplicateBtn.textContent = "Duplicate"; duplicateBtn.addEventListener("click", () => { const names = collectNames(envConfigsContainer, ".env-config-name"); const copy = collectEnvConfigs().find((entry) => entry.id === card.dataset.id) || { id: card.dataset.id, name: nameInput.value || "Default", apiConfigId: apiSelect.value || "", systemPrompt: promptInput.value || "" }; const newCard = buildEnvConfigCard({ id: newEnvConfigId(), name: ensureUniqueName(`${copy.name || "Default"} Copy`, names), apiConfigId: copy.apiConfigId, systemPrompt: copy.systemPrompt }); card.insertAdjacentElement("afterend", newCard); updateEnvApiOptions(); updateEnvControls(); updateTaskEnvOptions(); }); const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.className = "ghost delete"; deleteBtn.textContent = "Delete"; deleteBtn.addEventListener("click", () => { card.remove(); updateEnvControls(); updateTaskEnvOptions(); }); actions.appendChild(duplicateBtn); actions.appendChild(deleteBtn); nameInput.addEventListener("input", () => updateEnvApiOptions()); card.appendChild(nameField); card.appendChild(apiField); card.appendChild(promptField); card.appendChild(actions); return card; } function updateEnvControls() { const cards = [...envConfigsContainer.querySelectorAll(".env-config-card")]; cards.forEach((card, index) => { const moveTopBtn = card.querySelector(".move-top"); const moveUpBtn = card.querySelector(".move-up"); const moveDownBtn = card.querySelector(".move-down"); if (moveTopBtn) moveTopBtn.disabled = index === 0; if (moveUpBtn) moveUpBtn.disabled = index === 0; if (moveDownBtn) moveDownBtn.disabled = index === cards.length - 1; }); scheduleSidebarErrors(); } function updateTaskEnvOptions() { const envs = collectEnvConfigs(); const selects = tasksContainer.querySelectorAll(".task-env-select"); selects.forEach((select) => { const preferred = select.dataset.preferred || select.value; select.innerHTML = ""; if (!envs.length) { const option = document.createElement("option"); option.value = ""; option.textContent = "No environments configured"; select.appendChild(option); select.disabled = true; return; } select.disabled = false; for (const env of envs) { const option = document.createElement("option"); option.value = env.id; option.textContent = env.name || "Default"; select.appendChild(option); } if (preferred && envs.some((env) => env.id === preferred)) { select.value = preferred; } else { select.value = envs[0].id; } select.dataset.preferred = select.value; }); scheduleSidebarErrors(); } function buildProfileCard(profile, container = profilesContainer) { const card = document.createElement("div"); card.className = "profile-card"; card.dataset.id = profile.id || newProfileId(); const nameField = document.createElement("div"); nameField.className = "field"; const nameLabel = document.createElement("label"); nameLabel.textContent = "Name"; const nameInput = document.createElement("input"); nameInput.type = "text"; nameInput.value = profile.name || ""; nameInput.className = "profile-name"; nameField.appendChild(nameLabel); nameField.appendChild(nameInput); const textField = document.createElement("div"); textField.className = "field"; const textLabel = document.createElement("label"); textLabel.textContent = "Profile text"; const textArea = document.createElement("textarea"); textArea.rows = 8; textArea.value = profile.text || ""; textArea.className = "profile-text"; textField.appendChild(textLabel); textField.appendChild(textArea); const actions = document.createElement("div"); actions.className = "profile-actions"; const moveTopBtn = document.createElement("button"); moveTopBtn.type = "button"; moveTopBtn.className = "ghost move-top"; moveTopBtn.textContent = "Top"; const moveUpBtn = document.createElement("button"); moveUpBtn.type = "button"; moveUpBtn.className = "ghost move-up"; moveUpBtn.textContent = "Up"; const moveDownBtn = document.createElement("button"); moveDownBtn.type = "button"; moveDownBtn.className = "ghost move-down"; moveDownBtn.textContent = "Down"; const addBelowBtn = document.createElement("button"); addBelowBtn.type = "button"; addBelowBtn.className = "ghost add-below"; addBelowBtn.textContent = "Add"; moveTopBtn.addEventListener("click", () => { const first = container.firstElementChild; if (!first || first === card) return; container.insertBefore(card, first); updateProfileControls(container); updateTaskProfileOptions(); }); moveUpBtn.addEventListener("click", () => { const previous = card.previousElementSibling; if (!previous) return; container.insertBefore(card, previous); updateProfileControls(container); updateTaskProfileOptions(); }); moveDownBtn.addEventListener("click", () => { const next = card.nextElementSibling; if (!next) return; container.insertBefore(card, next.nextElementSibling); updateProfileControls(container); updateTaskProfileOptions(); }); addBelowBtn.addEventListener("click", () => { const name = buildUniqueDefaultName( collectNames(container, ".profile-name") ); const newCard = buildProfileCard({ id: newProfileId(), name, text: "" }, container); card.insertAdjacentElement("afterend", newCard); updateProfileControls(container); updateTaskProfileOptions(); }); const duplicateBtn = document.createElement("button"); duplicateBtn.type = "button"; duplicateBtn.className = "ghost duplicate"; duplicateBtn.textContent = "Duplicate"; duplicateBtn.addEventListener("click", () => { const names = collectNames(container, ".profile-name"); const copy = collectProfiles(container).find((entry) => entry.id === card.dataset.id) || { id: card.dataset.id, name: nameInput.value || "Default", text: textArea.value || "" }; const newCard = buildProfileCard({ id: newProfileId(), name: ensureUniqueName(`${copy.name || "Default"} Copy`, names), text: copy.text }, container); card.insertAdjacentElement("afterend", newCard); updateProfileControls(container); updateTaskProfileOptions(); }); const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.className = "ghost delete"; deleteBtn.textContent = "Delete"; deleteBtn.addEventListener("click", () => { card.remove(); updateProfileControls(container); updateTaskProfileOptions(); }); actions.appendChild(moveTopBtn); actions.appendChild(moveUpBtn); actions.appendChild(moveDownBtn); actions.appendChild(addBelowBtn); actions.appendChild(duplicateBtn); actions.appendChild(deleteBtn); nameInput.addEventListener("input", () => updateTaskProfileOptions()); card.appendChild(nameField); card.appendChild(textField); card.appendChild(actions); return card; } function collectProfiles(container = profilesContainer) { const cards = [...container.querySelectorAll(".profile-card")]; return cards.map((card) => { const nameInput = card.querySelector(".profile-name"); const textArea = card.querySelector(".profile-text"); return { id: card.dataset.id || newProfileId(), name: (nameInput?.value || "Default").trim(), text: (textArea?.value || "").trim() }; }); } function updateProfileControls(container = profilesContainer) { const cards = [...container.querySelectorAll(".profile-card")]; cards.forEach((card, index) => { const moveTopBtn = card.querySelector(".move-top"); const moveUpBtn = card.querySelector(".move-up"); const moveDownBtn = card.querySelector(".move-down"); if (moveTopBtn) moveTopBtn.disabled = index === 0; if (moveUpBtn) moveUpBtn.disabled = index === 0; if (moveDownBtn) moveDownBtn.disabled = index === cards.length - 1; }); scheduleSidebarErrors(); } function updateTaskProfileOptions() { const profiles = collectProfiles(); const selects = tasksContainer.querySelectorAll(".task-profile-select"); selects.forEach((select) => { const preferred = select.dataset.preferred || select.value; select.innerHTML = ""; if (!profiles.length) { const option = document.createElement("option"); option.value = ""; option.textContent = "No profiles configured"; select.appendChild(option); select.disabled = true; return; } select.disabled = false; for (const profile of profiles) { const option = document.createElement("option"); option.value = profile.id; option.textContent = profile.name || "Default"; select.appendChild(option); } if (preferred && profiles.some((profile) => profile.id === preferred)) { select.value = preferred; } else { select.value = profiles[0].id; } select.dataset.preferred = select.value; }); scheduleSidebarErrors(); } function updateEnvApiOptions() { const apiConfigs = collectApiConfigs(); const selects = envConfigsContainer.querySelectorAll(".env-config-api-select"); selects.forEach((select) => { const preferred = select.dataset.preferred || select.value; select.innerHTML = ""; if (!apiConfigs.length) { const option = document.createElement("option"); option.value = ""; option.textContent = "No API configs configured"; select.appendChild(option); select.disabled = true; return; } select.disabled = false; for (const config of apiConfigs) { const option = document.createElement("option"); option.value = config.id; option.textContent = config.name || "Default"; select.appendChild(option); } if (preferred && apiConfigs.some((config) => config.id === preferred)) { select.value = preferred; } else { select.value = apiConfigs[0].id; } select.dataset.preferred = select.value; }); updateTaskEnvOptions(); } function collectWorkspaces() { const cards = [...workspacesContainer.querySelectorAll(".workspace-card")]; return cards.map((card) => { const nameInput = card.querySelector(".workspace-name"); const themeSelect = card.querySelector(".workspace-theme"); // Collect nested resources const envsContainer = card.querySelector(".workspace-envs"); const profilesContainer = card.querySelector(".workspace-profiles"); const tasksContainer = card.querySelector(".workspace-tasks"); const presetsContainer = card.querySelector(".workspace-presets"); // We can reuse collect functions if they accept a container! // But collectEnvConfigs currently returns objects with flat IDs. // We'll need to ensure we don't lose the nested nature or we handle it during save. // Actually, saveSettings stores workspaces array. If we put the resources inside, it works. return { id: card.dataset.id || newWorkspaceId(), name: (nameInput?.value || "Untitled Workspace").trim(), theme: themeSelect?.value || "inherit", envConfigs: envsContainer ? collectEnvConfigs(envsContainer) : [], profiles: profilesContainer ? collectProfiles(profilesContainer) : [], tasks: tasksContainer ? collectTasks(tasksContainer) : [], presets: presetsContainer ? collectPresets(presetsContainer) : [] }; }); } function collectPresets(container = presetsContainer) { const cards = [...container.querySelectorAll(".preset-card")]; return cards.map((card) => { const nameInput = card.querySelector(".preset-name"); const envSelect = card.querySelector(".preset-env"); const profileSelect = card.querySelector(".preset-profile"); const taskSelect = card.querySelector(".preset-task"); return { id: card.dataset.id || newPresetId(), name: (nameInput?.value || "Untitled Preset").trim(), envId: envSelect?.value || "", profileId: profileSelect?.value || "", taskId: taskSelect?.value || "" }; }); } function collectEnvConfigs(container = envConfigsContainer) { const cards = [...container.querySelectorAll(".env-config-card")]; return cards.map((card) => { const nameInput = card.querySelector(".env-config-name"); const apiSelect = card.querySelector(".env-config-api-select"); const promptInput = card.querySelector(".env-config-prompt"); return { id: card.dataset.id || newEnvConfigId(), name: (nameInput?.value || "Default").trim(), apiConfigId: apiSelect?.value || "", systemPrompt: (promptInput?.value || "").trim() }; }); } function renderWorkspaceSection(title, containerClass, items, builder, newItemFactory) { const details = document.createElement("details"); details.className = "panel sub-panel"; details.style.marginTop = "10px"; details.style.border = "1px solid var(--border)"; details.style.borderRadius = "8px"; details.style.padding = "8px"; const summary = document.createElement("summary"); summary.className = "panel-summary"; summary.style.cursor = "pointer"; summary.innerHTML = `