From b9e03e9cb1a2547911ba692159c2ee767f351600 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 18 Jul 2024 16:37:12 +0000 Subject: [PATCH 01/10] Add Mistral Nemo and Codestral Mamba models --- public/index.html | 5 +++++ public/scripts/openai.js | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/public/index.html b/public/index.html index 6ac770401..3e438efa8 100644 --- a/public/index.html +++ b/public/index.html @@ -2821,15 +2821,19 @@

MistralAI Model

diff --git a/public/scripts/openai.js b/public/scripts/openai.js index c23f7a4e2..b60a6948f 100644 --- a/public/scripts/openai.js +++ b/public/scripts/openai.js @@ -125,6 +125,7 @@ const max_32k = 32767; const max_64k = 65535; const max_128k = 128 * 1000; const max_200k = 200 * 1000; +const max_256k = 256 * 1000; const max_1mil = 1000 * 1000; const scale_max = 8191; const claude_max = 9000; // We have a proper tokenizer, so theoretically could be larger (up to 9k) @@ -3992,7 +3993,7 @@ async function onModelChange() { if ($(this).is('#model_mistralai_select')) { // Upgrade old mistral models to new naming scheme // would have done this in loadOpenAISettings, but it wasn't updating on preset change? - if (value === 'mistral-medium' || value === 'mistral-small' || value === 'mistral-tiny') { + if (value === 'mistral-medium' || value === 'mistral-small') { value = value + '-latest'; } else if (value === '') { value = default_settings.mistralai_model; @@ -4139,6 +4140,10 @@ async function onModelChange() { if (oai_settings.chat_completion_source === chat_completion_sources.MISTRALAI) { if (oai_settings.max_context_unlocked) { $('#openai_max_context').attr('max', unlocked_max); + } else if (oai_settings.mistralai_model.includes('codestral-mamba')) { + $('#openai_max_context').attr('max', max_256k); + } else if (oai_settings.mistralai_model.includes('mistral-nemo')) { + $('#openai_max_context').attr('max', max_128k); } else if (oai_settings.mistralai_model.includes('mixtral-8x22b')) { $('#openai_max_context').attr('max', max_64k); } else { From e6995e40ccbb24ef006ef03a8123fac8f08cc573 Mon Sep 17 00:00:00 2001 From: Wolfsblvt Date: Thu, 18 Jul 2024 18:47:13 +0200 Subject: [PATCH 02/10] Update /qr-delete help string and add missing arg - Fixes #2527 --- .../extensions/quick-reply/src/SlashCommandHandler.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/public/scripts/extensions/quick-reply/src/SlashCommandHandler.js b/public/scripts/extensions/quick-reply/src/SlashCommandHandler.js index a2c54e9ee..0f3829e84 100644 --- a/public/scripts/extensions/quick-reply/src/SlashCommandHandler.js +++ b/public/scripts/extensions/quick-reply/src/SlashCommandHandler.js @@ -316,7 +316,14 @@ export class SlashCommandHandler { enumProvider: localEnumProviders.qrEntries, }), ], - helpString: 'Deletes a Quick Reply from the specified set. If no label is provided, the entire set is deleted.', + unnamedArgumentList: [ + SlashCommandArgument.fromProps({ + description: 'label', + typeList: [ARGUMENT_TYPE.STRING], + enumProvider: localEnumProviders.qrEntries, + }), + ], + helpString: 'Deletes a Quick Reply from the specified set. (Label must be provided via named or unnamed argument)', })); SlashCommandParser.addCommandObject(SlashCommand.fromProps({ name: 'qr-contextadd', callback: (args, name) => { From 318b6a17b93a032618d4d460806b215a55830cd2 Mon Sep 17 00:00:00 2001 From: Wolfsblvt Date: Thu, 18 Jul 2024 21:37:18 +0200 Subject: [PATCH 03/10] Add gpt-4o-mini --- public/index.html | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/public/index.html b/public/index.html index 3e438efa8..cca1fefba 100644 --- a/public/index.html +++ b/public/index.html @@ -2560,6 +2560,10 @@ + + + + From ff68956371fb0ba0b3798258e360b50945656e8a Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 18 Jul 2024 22:47:57 +0300 Subject: [PATCH 04/10] Add events to SlashCommandAbortController --- .../slash-commands/AbstractEventTarget.js | 36 +++++++++++++++++++ .../SlashCommandAbortController.js | 8 ++++- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 public/scripts/slash-commands/AbstractEventTarget.js diff --git a/public/scripts/slash-commands/AbstractEventTarget.js b/public/scripts/slash-commands/AbstractEventTarget.js new file mode 100644 index 000000000..717d1c515 --- /dev/null +++ b/public/scripts/slash-commands/AbstractEventTarget.js @@ -0,0 +1,36 @@ +/** + * @abstract + * @implements {EventTarget} + */ +export class AbstractEventTarget { + constructor() { + this.listeners = {}; + } + + addEventListener(type, callback, _options) { + if (!this.listeners[type]) { + this.listeners[type] = []; + } + this.listeners[type].push(callback); + } + + dispatchEvent(event) { + if (!this.listeners[event.type] || this.listeners[event.type].length === 0) { + return true; + } + this.listeners[event.type].forEach(listener => { + listener(event); + }); + return true; + } + + removeEventListener(type, callback, _options) { + if (!this.listeners[type]) { + return; + } + const index = this.listeners[type].indexOf(callback); + if (index !== -1) { + this.listeners[type].splice(index, 1); + } + } +} diff --git a/public/scripts/slash-commands/SlashCommandAbortController.js b/public/scripts/slash-commands/SlashCommandAbortController.js index 7ed919f8c..b55e77ae6 100644 --- a/public/scripts/slash-commands/SlashCommandAbortController.js +++ b/public/scripts/slash-commands/SlashCommandAbortController.js @@ -1,22 +1,28 @@ -export class SlashCommandAbortController { +import { AbstractEventTarget } from './AbstractEventTarget.js'; + +export class SlashCommandAbortController extends AbstractEventTarget { /**@type {SlashCommandAbortSignal}*/ signal; constructor() { + super(); this.signal = new SlashCommandAbortSignal(); } abort(reason = 'No reason.', isQuiet = false) { this.signal.isQuiet = isQuiet; this.signal.aborted = true; this.signal.reason = reason; + this.dispatchEvent(new Event('abort')); } pause(reason = 'No reason.') { this.signal.paused = true; this.signal.reason = reason; + this.dispatchEvent(new Event('pause')); } continue(reason = 'No reason.') { this.signal.paused = false; this.signal.reason = reason; + this.dispatchEvent(new Event('continue')); } } From f9e16d2225c31c2a8d27a48105f73fe6745fc3d0 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 18 Jul 2024 22:51:47 +0300 Subject: [PATCH 05/10] Add to multimodal captions --- public/scripts/extensions/caption/settings.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/public/scripts/extensions/caption/settings.html b/public/scripts/extensions/caption/settings.html index ccbdd67c0..5181e8ce1 100644 --- a/public/scripts/extensions/caption/settings.html +++ b/public/scripts/extensions/caption/settings.html @@ -35,6 +35,7 @@ + @@ -44,6 +45,7 @@ + From 4468bf5034e3ff4583cee05384e98a44db4a0461 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 18 Jul 2024 22:54:44 +0300 Subject: [PATCH 06/10] Explicitly add to image inlining list --- public/scripts/openai.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/public/scripts/openai.js b/public/scripts/openai.js index b60a6948f..d1a45727a 100644 --- a/public/scripts/openai.js +++ b/public/scripts/openai.js @@ -4633,8 +4633,10 @@ export function isImageInliningSupported() { 'gemini-1.5-pro-latest', 'gemini-pro-vision', 'claude-3', + 'claude-3-5', 'gpt-4-turbo', 'gpt-4o', + 'gpt-4o-mini', ]; switch (oai_settings.chat_completion_source) { From 1effb66fd6ee33072cc2a3fc7b9994220eedba6a Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 18 Jul 2024 23:23:33 +0300 Subject: [PATCH 07/10] Add cancelling of SD gens --- .../extensions/stable-diffusion/index.js | 88 +++++++++++++------ src/endpoints/horde.js | 11 +++ 2 files changed, 74 insertions(+), 25 deletions(-) diff --git a/public/scripts/extensions/stable-diffusion/index.js b/public/scripts/extensions/stable-diffusion/index.js index 85967f7bd..0e727a931 100644 --- a/public/scripts/extensions/stable-diffusion/index.js +++ b/public/scripts/extensions/stable-diffusion/index.js @@ -2289,24 +2289,34 @@ async function generatePicture(initiator, args, trigger, message, callback) { } const dimensions = setTypeSpecificDimensions(generationType); + const abortController = new AbortController(); let negativePromptPrefix = args?.negative || ''; let imagePath = ''; + const stopListener = () => abortController.abort('Aborted by user'); + const mesStop = document.getElementById('mes_stop'); + try { const combineNegatives = (prefix) => { negativePromptPrefix = combinePrefixes(negativePromptPrefix, prefix); }; const prompt = await getPrompt(generationType, message, trigger, quietPrompt, combineNegatives); console.log('Processed image prompt:', prompt); + mesStop?.addEventListener('click', stopListener); context.deactivateSendButtons(); hideSwipeButtons(); - imagePath = await sendGenerationRequest(generationType, prompt, negativePromptPrefix, characterName, callback, initiator); + if (typeof args?._abortController?.addEventListener === 'function') { + args._abortController.addEventListener('abort', stopListener); + } + + imagePath = await sendGenerationRequest(generationType, prompt, negativePromptPrefix, characterName, callback, initiator, abortController.signal); } catch (err) { console.trace(err); throw new Error('SD prompt text generation failed.'); } finally { restoreOriginalDimensions(dimensions); + mesStop?.removeEventListener('click', stopListener); context.activateSendButtons(); showSwipeButtons(); } @@ -2521,9 +2531,10 @@ async function generatePrompt(quietPrompt) { * @param {string} characterName Name of the character * @param {function} callback Callback function to be called after image generation * @param {string} initiator The initiator of the image generation + * @param {AbortSignal} signal Abort signal to cancel the request * @returns */ -async function sendGenerationRequest(generationType, prompt, additionalNegativePrefix, characterName, callback, initiator) { +async function sendGenerationRequest(generationType, prompt, additionalNegativePrefix, characterName, callback, initiator, signal) { const noCharPrefix = [generationMode.FREE, generationMode.BACKGROUND, generationMode.USER, generationMode.USER_MULTIMODAL, generationMode.FREE_EXTENDED]; const prefix = noCharPrefix.includes(generationType) ? extension_settings.sd.prompt_prefix @@ -2541,37 +2552,37 @@ async function sendGenerationRequest(generationType, prompt, additionalNegativeP try { switch (extension_settings.sd.source) { case sources.extras: - result = await generateExtrasImage(prefixedPrompt, negativePrompt); + result = await generateExtrasImage(prefixedPrompt, negativePrompt, signal); break; case sources.horde: - result = await generateHordeImage(prefixedPrompt, negativePrompt); + result = await generateHordeImage(prefixedPrompt, negativePrompt, signal); break; case sources.vlad: - result = await generateAutoImage(prefixedPrompt, negativePrompt); + result = await generateAutoImage(prefixedPrompt, negativePrompt, signal); break; case sources.drawthings: - result = await generateDrawthingsImage(prefixedPrompt, negativePrompt); + result = await generateDrawthingsImage(prefixedPrompt, negativePrompt, signal); break; case sources.auto: - result = await generateAutoImage(prefixedPrompt, negativePrompt); + result = await generateAutoImage(prefixedPrompt, negativePrompt, signal); break; case sources.novel: - result = await generateNovelImage(prefixedPrompt, negativePrompt); + result = await generateNovelImage(prefixedPrompt, negativePrompt, signal); break; case sources.openai: - result = await generateOpenAiImage(prefixedPrompt); + result = await generateOpenAiImage(prefixedPrompt, signal); break; case sources.comfy: - result = await generateComfyImage(prefixedPrompt, negativePrompt); + result = await generateComfyImage(prefixedPrompt, negativePrompt, signal); break; case sources.togetherai: - result = await generateTogetherAIImage(prefixedPrompt, negativePrompt); + result = await generateTogetherAIImage(prefixedPrompt, negativePrompt, signal); break; case sources.pollinations: - result = await generatePollinationsImage(prefixedPrompt, negativePrompt); + result = await generatePollinationsImage(prefixedPrompt, negativePrompt, signal); break; case sources.stability: - result = await generateStabilityImage(prefixedPrompt, negativePrompt); + result = await generateStabilityImage(prefixedPrompt, negativePrompt, signal); break; } @@ -2600,12 +2611,14 @@ async function sendGenerationRequest(generationType, prompt, additionalNegativeP * Generates an image using the TogetherAI API. * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateTogetherAIImage(prompt, negativePrompt) { +async function generateTogetherAIImage(prompt, negativePrompt, signal) { const result = await fetch('/api/sd/together/generate', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ prompt: prompt, negative_prompt: negativePrompt, @@ -2630,12 +2643,14 @@ async function generateTogetherAIImage(prompt, negativePrompt) { * Generates an image using the Pollinations API. * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generatePollinationsImage(prompt, negativePrompt) { +async function generatePollinationsImage(prompt, negativePrompt, signal) { const result = await fetch('/api/sd/pollinations/generate', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ prompt: prompt, negative_prompt: negativePrompt, @@ -2662,9 +2677,10 @@ async function generatePollinationsImage(prompt, negativePrompt) { * * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateExtrasImage(prompt, negativePrompt) { +async function generateExtrasImage(prompt, negativePrompt, signal) { const url = new URL(getApiUrl()); url.pathname = '/api/image'; const result = await doExtrasFetch(url, { @@ -2672,6 +2688,7 @@ async function generateExtrasImage(prompt, negativePrompt) { headers: { 'Content-Type': 'application/json', }, + signal: signal, body: JSON.stringify({ prompt: prompt, sampler: extension_settings.sd.sampler, @@ -2739,9 +2756,10 @@ function getClosestAspectRatio(width, height) { * Generates an image using Stability AI. * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateStabilityImage(prompt, negativePrompt) { +async function generateStabilityImage(prompt, negativePrompt, signal) { const IMAGE_FORMAT = 'png'; const PROMPT_LIMIT = 10000; @@ -2749,6 +2767,7 @@ async function generateStabilityImage(prompt, negativePrompt) { const response = await fetch('/api/sd/stability/generate', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ model: extension_settings.sd.model, payload: { @@ -2783,12 +2802,14 @@ async function generateStabilityImage(prompt, negativePrompt) { * * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateHordeImage(prompt, negativePrompt) { +async function generateHordeImage(prompt, negativePrompt, signal) { const result = await fetch('/api/horde/generate-image', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ prompt: prompt, sampler: extension_settings.sd.sampler, @@ -2821,13 +2842,15 @@ async function generateHordeImage(prompt, negativePrompt) { * * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateAutoImage(prompt, negativePrompt) { +async function generateAutoImage(prompt, negativePrompt, signal) { const isValidVae = extension_settings.sd.vae && !['N/A', placeholderVae].includes(extension_settings.sd.vae); const result = await fetch('/api/sd/generate', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ ...getSdRequestBody(), prompt: prompt, @@ -2875,12 +2898,14 @@ async function generateAutoImage(prompt, negativePrompt) { * * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateDrawthingsImage(prompt, negativePrompt) { +async function generateDrawthingsImage(prompt, negativePrompt, signal) { const result = await fetch('/api/sd/drawthings/generate', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ ...getSdRequestBody(), prompt: prompt, @@ -2914,14 +2939,16 @@ async function generateDrawthingsImage(prompt, negativePrompt) { * * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateNovelImage(prompt, negativePrompt) { +async function generateNovelImage(prompt, negativePrompt, signal) { const { steps, width, height, sm, sm_dyn } = getNovelParams(); const result = await fetch('/api/novelai/generate-image', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ prompt: prompt, model: extension_settings.sd.model, @@ -3010,7 +3037,13 @@ function getNovelParams() { return { steps, width, height, sm, sm_dyn }; } -async function generateOpenAiImage(prompt) { +/** + * Generates an image in OpenAI API using the provided prompt and configuration settings. + * @param {string} prompt - The main instruction used to guide the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. + * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. + */ +async function generateOpenAiImage(prompt, signal) { const dalle2PromptLimit = 1000; const dalle3PromptLimit = 4000; @@ -3045,6 +3078,7 @@ async function generateOpenAiImage(prompt) { const result = await fetch('/api/openai/generate-image', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ prompt: prompt, model: extension_settings.sd.model, @@ -3070,9 +3104,10 @@ async function generateOpenAiImage(prompt) { * * @param {string} prompt - The main instruction used to guide the image generation. * @param {string} negativePrompt - The instruction used to restrict the image generation. + * @param {AbortSignal} signal - An AbortSignal object that can be used to cancel the request. * @returns {Promise<{format: string, data: string}>} - A promise that resolves when the image generation and processing are complete. */ -async function generateComfyImage(prompt, negativePrompt) { +async function generateComfyImage(prompt, negativePrompt, signal) { const placeholders = [ 'model', 'vae', @@ -3133,6 +3168,7 @@ async function generateComfyImage(prompt, negativePrompt) { const promptResult = await fetch('/api/sd/comfy/generate', { method: 'POST', headers: getRequestHeaders(), + signal: signal, body: JSON.stringify({ url: extension_settings.sd.comfy_url, prompt: `{ @@ -3245,7 +3281,7 @@ async function onComfyNewWorkflowClick() { if (!name) { return; } - if (!name.toLowerCase().endsWith('.json')) { + if (!String(name).toLowerCase().endsWith('.json')) { name += '.json'; } extension_settings.sd.comfy_workflow = name; @@ -3448,8 +3484,10 @@ async function sdMessageButton(e) { const messageText = message?.mes; const hasSavedImage = message?.extra?.image && message?.extra?.title; const hasSavedNegative = message?.extra?.negative; + const abortController = new AbortController(); if ($icon.hasClass(busyClass)) { + abortController.abort(); console.log('Previous image is still being generated...'); return; } @@ -3466,7 +3504,7 @@ async function sdMessageButton(e) { const generationType = message?.extra?.generationType ?? generationMode.FREE; console.log('Regenerating an image, using existing prompt:', prompt); dimensions = setTypeSpecificDimensions(generationType); - await sendGenerationRequest(generationType, prompt, negative, characterFileName, saveGeneratedImage, initiators.action); + await sendGenerationRequest(generationType, prompt, negative, characterFileName, saveGeneratedImage, initiators.action, abortController.signal); } else { console.log('doing /sd raw last'); diff --git a/src/endpoints/horde.js b/src/endpoints/horde.js index f23eb52bf..cc8b0bce8 100644 --- a/src/endpoints/horde.js +++ b/src/endpoints/horde.js @@ -339,7 +339,18 @@ router.post('/generate-image', jsonParser, async (request, response) => { return response.sendStatus(400); } + console.log('Horde image generation request:', generation); + + const controller = new AbortController(); + request.socket.removeAllListeners('close'); + request.socket.on('close', function () { + console.log('Horde image generation request aborted.'); + controller.abort(); + if (generation.id) ai_horde.deleteImageGenerationRequest(generation.id); + }); + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + controller.signal.throwIfAborted(); await delay(CHECK_INTERVAL); const check = await ai_horde.getImageGenerationCheck(generation.id); console.log(check); From 739752ccf315134a271c83520271b0d605636505 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Thu, 18 Jul 2024 23:32:20 +0300 Subject: [PATCH 08/10] Fix aborting via hourglass --- public/scripts/extensions/stable-diffusion/index.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/public/scripts/extensions/stable-diffusion/index.js b/public/scripts/extensions/stable-diffusion/index.js index 0e727a931..d43031950 100644 --- a/public/scripts/extensions/stable-diffusion/index.js +++ b/public/scripts/extensions/stable-diffusion/index.js @@ -3467,6 +3467,7 @@ async function moduleWorker() { } setInterval(moduleWorker, UPDATE_INTERVAL); +let buttonAbortController = null; async function sdMessageButton(e) { function setBusyIcon(isBusy) { @@ -3484,15 +3485,15 @@ async function sdMessageButton(e) { const messageText = message?.mes; const hasSavedImage = message?.extra?.image && message?.extra?.title; const hasSavedNegative = message?.extra?.negative; - const abortController = new AbortController(); if ($icon.hasClass(busyClass)) { - abortController.abort(); + buttonAbortController?.abort('Aborted by user'); console.log('Previous image is still being generated...'); return; } let dimensions = null; + buttonAbortController = new AbortController(); try { setBusyIcon(true); @@ -3504,7 +3505,7 @@ async function sdMessageButton(e) { const generationType = message?.extra?.generationType ?? generationMode.FREE; console.log('Regenerating an image, using existing prompt:', prompt); dimensions = setTypeSpecificDimensions(generationType); - await sendGenerationRequest(generationType, prompt, negative, characterFileName, saveGeneratedImage, initiators.action, abortController.signal); + await sendGenerationRequest(generationType, prompt, negative, characterFileName, saveGeneratedImage, initiators.action, buttonAbortController?.signal); } else { console.log('doing /sd raw last'); From 7e4abaabff3e130ab1e50c8b16842a6b271c5a5f Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Fri, 19 Jul 2024 00:01:24 +0300 Subject: [PATCH 09/10] Interrupt AUTO1111 gens on cancel --- src/endpoints/stable-diffusion.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/endpoints/stable-diffusion.js b/src/endpoints/stable-diffusion.js index 24c393aa9..9f4a4e741 100644 --- a/src/endpoints/stable-diffusion.js +++ b/src/endpoints/stable-diffusion.js @@ -323,6 +323,17 @@ router.post('/generate', jsonParser, async (request, response) => { const url = new URL(request.body.url); url.pathname = '/sdapi/v1/txt2img'; + const controller = new AbortController(); + request.socket.removeAllListeners('close'); + request.socket.on('close', function () { + if (!response.writableEnded) { + const url = new URL(request.body.url); + url.pathname = '/sdapi/v1/interrupt'; + fetch(url, { method: 'POST', headers: { 'Authorization': getBasicAuthHeader(request.body.auth) } }); + } + controller.abort(); + }); + const result = await fetch(url, { method: 'POST', body: JSON.stringify(request.body), @@ -331,6 +342,8 @@ router.post('/generate', jsonParser, async (request, response) => { 'Authorization': getBasicAuthHeader(request.body.auth), }, timeout: 0, + // @ts-ignore + signal: controller.signal, }); if (!result.ok) { From 52497ea96ddec110091d7f3f50d72457e032f3db Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Fri, 19 Jul 2024 00:39:21 +0300 Subject: [PATCH 10/10] Interrupt Comfy gens on cancel --- src/endpoints/stable-diffusion.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/endpoints/stable-diffusion.js b/src/endpoints/stable-diffusion.js index 9f4a4e741..fe4a9604c 100644 --- a/src/endpoints/stable-diffusion.js +++ b/src/endpoints/stable-diffusion.js @@ -569,6 +569,17 @@ comfy.post('/generate', jsonParser, async (request, response) => { const url = new URL(request.body.url); url.pathname = '/prompt'; + const controller = new AbortController(); + request.socket.removeAllListeners('close'); + request.socket.on('close', function () { + if (!response.writableEnded && !item) { + const interruptUrl = new URL(request.body.url); + interruptUrl.pathname = '/interrupt'; + fetch(interruptUrl, { method: 'POST', headers: { 'Authorization': getBasicAuthHeader(request.body.auth) } }); + } + controller.abort(); + }); + const promptResult = await fetch(url, { method: 'POST', body: request.body.prompt, @@ -594,6 +605,9 @@ comfy.post('/generate', jsonParser, async (request, response) => { } await delay(100); } + if (item.status.status_str === 'error') { + throw new Error('ComfyUI generation did not succeed.'); + } const imgInfo = Object.keys(item.outputs).map(it => item.outputs[it].images).flat()[0]; const imgUrl = new URL(request.body.url); imgUrl.pathname = '/view'; @@ -605,6 +619,7 @@ comfy.post('/generate', jsonParser, async (request, response) => { const imgBuffer = await imgResponse.buffer(); return response.send(imgBuffer.toString('base64')); } catch (error) { + console.log(error); return response.sendStatus(500); } });