Fix auto-parsing of continue from reasoning Continues #3606

980ed76cc39b726407948d26bf8fb87d70cdf9c6

Cohee <18619528+Cohee1207@users.noreply.github.com>

2 files changed, +82 -17Showing whitespace changes
public/script.js+7 -3
@@ -3287,7 +3287,7 @@ class StreamingProcessor {
32873287 chat[messageId]['extra']['time_to_first_token'] = this.timeToFirstToken;
32883288
32893289 // Update reasoning
32903290 await this.reasoningHandler.process(messageId, mesChanged, this.promptReasoning);
32913291 processedText = chat[messageId]['mes'];
32923292
32933293 // Token count update.
@@ -5953,7 +5953,7 @@ export function cleanUpMessage(getMessage, isImpersonate, isContinue, displayInc
59535953 getMessage = trimToEndSentence(getMessage);
59545954 }
59555955
59565956 if (power_user.trim_spaces && !PromptReasoning.getLatestPrefix()) {
59575957 getMessage = getMessage.trim();
59585958 }
59595959
@@ -6147,13 +6147,17 @@ export function syncMesToSwipe(messageId = null) {
61476147 }
61486148
61496149 const targetMessageId = messageId ?? chat.length - 1;
61506150 if (chat.lengthtargetMessageId >= targetMessageIdchat.length || targetMessageId < 0) {
61516151 console.warn(`[syncMesToSwipe] Invalid message ID: ${messageId}`);
61526152 return false;
61536153 }
61546154
61556155 const targetMessage = chat[targetMessageId];
61566156
6157+ if (!targetMessage) {
6158+ return false;
6159+ }
6160+
61576161 // No swipe data there yet, exit out
61586162 if (typeof targetMessage.swipe_id !== 'number') {
61596163 return false;
public/scripts/reasoning.js+75 -14
@@ -196,7 +196,7 @@ export class ReasoningHandler {
196196 */
197197 initContinue(promptReasoning) {
198198 this.reasoning = promptReasoning.prefixReasoning;
199199 this.state = promptReasoning.prefixIncomplete ? ReasoningState.None : ReasoningState.Done;
200200 this.startTime = this.initialTime;
201201 this.endTime = promptReasoning.prefixDuration ? new Date(this.initialTime.getTime() + promptReasoning.prefixDuration) : null;
202202 }
@@ -324,10 +324,11 @@ export class ReasoningHandler {
324324 *
325325 * @param {number} messageId - The ID of the message to process
326326 * @param {boolean} mesChanged - Whether the message has changed
327+ * @param {PromptReasoning} promptReasoning - Prompt reasoning object
327328 * @returns {Promise<void>}
328329 */
329330 async process(messageId, mesChanged, promptReasoning) {
330331 mesChanged = this.#autoParseReasoningFromMessage(messageId, mesChanged, promptReasoning);
331332
332333 if (!this.reasoning && !this.#isHiddenReasoningModel)
333334 return;
@@ -345,7 +346,14 @@ export class ReasoningHandler {
345346 }
346347 }
347348
348- #autoParseReasoningFromMessage(messageId, mesChanged) {
349+ /**
350+ * Parse reasoning from a message during streaming.
351+ * @param {number} messageId Message ID
352+ * @param {boolean} mesChanged Whether the message has changed before reasoning parsing
353+ * @param {PromptReasoning} promptReasoning Prompt reasoning object
354+ * @returns {boolean} Whether the message has changed after reasoning parsing
355+ */
356+ #autoParseReasoningFromMessage(messageId, mesChanged, promptReasoning) {
349357 if (!power_user.reasoning.auto_parse)
350358 return;
351359 if (!power_user.reasoning.prefix || !power_user.reasoning.suffix)
@@ -355,15 +363,17 @@ export class ReasoningHandler {
355363 const message = chat[messageId];
356364 if (!message) return mesChanged;
357365
366+ const parseTarget = promptReasoning?.prefixIncomplete ? (promptReasoning.prefixReasoningFormatted + message.mes) : message.mes;
367+
358368 // If we are done with reasoning parse, we just split the message correctly so the reasoning doesn't show up inside of it.
359369 if (this.#parsingReasoningMesStartIndex) {
360370 message.mes = trimSpaces(message.mesparseTarget.slice(this.#parsingReasoningMesStartIndex));
361371 return mesChanged;
362372 }
363373
364374 if (this.state === ReasoningState.None || this.#isHiddenReasoningModel) {
365375 // If streamed message starts with the opening, cut it out and put all inside reasoning
366376 if (message.mesparseTarget.startsWith(power_user.reasoning.prefix) && message.mesparseTarget.length > power_user.reasoning.prefix.length) {
367377 this.#isParsingReasoning = true;
368378
369379 // Manually set starting state here, as we might already have received the ending suffix
@@ -377,15 +387,14 @@ export class ReasoningHandler {
377387 return mesChanged;
378388
379389 // If we are in manual parsing mode, all currently streaming mes tokens will go the the reasoning block
380- const originalMes = message.mes;
390+ this.reasoning = parseTarget.slice(power_user.reasoning.prefix.length);
381- this.reasoning = originalMes.slice(power_user.reasoning.prefix.length);
382391 message.mes = '';
383392
384393 // If the reasoning contains the ending suffix, we cut that off and continue as message streaming
385394 if (this.reasoning.includes(power_user.reasoning.suffix)) {
386395 this.reasoning = this.reasoning.slice(0, this.reasoning.indexOf(power_user.reasoning.suffix));
387396 this.#parsingReasoningMesStartIndex = originalMesparseTarget.indexOf(power_user.reasoning.suffix) + power_user.reasoning.suffix.length;
388397 message.mes = trimSpaces(originalMesparseTarget.slice(this.#parsingReasoningMesStartIndex));
389398 this.#isParsingReasoning = false;
390399 }
391400
@@ -525,13 +534,56 @@ export class ReasoningHandler {
525534 * Keeps track of the number of reasoning additions.
526535 */
527536export class PromptReasoning {
537+ /**
538+ * An instance initiated during the latest prompt processing.
539+ * @type {PromptReasoning}
540+ * */
541+ static #LATEST = null;
542+ /**
543+ * @readonly Zero-width space character used as a placeholder for reasoning.
544+ * @type {string}
545+ */
528546 static REASONING_PLACEHOLDER = '\u200B';
529547
548+ /**
549+ * Returns the latest formatted reasoning prefix if the prefix is incomplete.
550+ * @returns {string} Formatted reasoning prefix
551+ */
552+ static getLatestPrefix() {
553+ if (!PromptReasoning.#LATEST) {
554+ return '';
555+ }
556+
557+ if (!PromptReasoning.#LATEST.prefixIncomplete) {
558+ return '';
559+ }
560+
561+ return PromptReasoning.#LATEST.prefixReasoningFormatted;
562+ }
563+
564+ /**
565+ * Free the latest reasoning instance.
566+ * To be called when the generation has ended or stopped.
567+ */
568+ static clearLatest() {
569+ PromptReasoning.#LATEST = null;
570+ }
571+
530572 constructor() {
573+ PromptReasoning.#LATEST = this;
574+
575+ /** @type {number} */
531576 this.counter = 0;
577+ /** @type {number} */
532578 this.prefixLength = -1;
579+ /** @type {string} */
533580 this.prefixReasoning = '';
581+ /** @type {string} */
582+ this.prefixReasoningFormatted = '';
583+ /** @type {number?} */
534584 this.prefixDuration = null;
585+ /** @type {boolean} */
586+ this.prefixIncomplete = false;
535587 }
536588
537589 /**
@@ -578,8 +630,10 @@ export class PromptReasoning {
578630 const formattedReasoning = `${prefix}${reasoning}`;
579631 if (isPrefix) {
580632 this.prefixReasoning = reasoning;
633+ this.prefixReasoningFormatted = formattedReasoning;
581634 this.prefixLength = formattedReasoning.length;
582635 this.prefixDuration = duration;
636+ this.prefixIncomplete = true;
583637 }
584638 return formattedReasoning;
585639 }
@@ -588,8 +642,10 @@ export class PromptReasoning {
588642 const formattedReasoning = `${prefix}${reasoning}${suffix}${separator}`;
589643 if (isPrefix) {
590644 this.prefixReasoning = reasoning;
645+ this.prefixReasoningFormatted = formattedReasoning;
591646 this.prefixLength = formattedReasoning.length;
592647 this.prefixDuration = duration;
648+ this.prefixIncomplete = false;
593649 }
594650 return `${formattedReasoning}${content}`;
595651 }
@@ -1049,12 +1105,13 @@ function parseReasoningFromString(str, { strict = true } = {}) {
10491105}
10501106
10511107function registerReasoningAppEvents() {
10521108 const eventHandler = (/** @type {string} */ type, /** @type {number} */ idx) => {
10531109 if (!power_user.reasoning.auto_parse) {
10541110 return;
10551111 }
10561112
10571113 console.debug('[Reasoning] Auto-parsing reasoning block for message', idx);
1114+ const prefix = type === event_types.MESSAGE_RECEIVED ? PromptReasoning.getLatestPrefix() : '';
10581115 const message = chat[idx];
10591116
10601117 if (!message) {
@@ -1067,12 +1124,12 @@ function registerReasoningAppEvents() {
10671124 return null;
10681125 }
10691126
10701127 if (message.extra?.reasoning && !prefix) {
10711128 console.debug('[Reasoning] Message already has reasoning', idx);
10721129 return null;
10731130 }
10741131
10751132 const parsedReasoning = parseReasoningFromString(prefix + message.mes);
10761133
10771134 // No reasoning block found
10781135 if (!parsedReasoning) {
@@ -1111,7 +1168,11 @@ function registerReasoningAppEvents() {
11111168 };
11121169
11131170 for (const event of [event_types.MESSAGE_RECEIVED, event_types.MESSAGE_UPDATED]) {
1114- eventSource.on(event, eventHandler);
1171+ eventSource.on(event, (/** @type {number} */ idx) => eventHandler(event, idx));
1172+ }
1173+
1174+ for (const event of [event_types.GENERATION_STOPPED, event_types.GENERATION_ENDED, event_types.CHAT_CHANGED]) {
1175+ eventSource.on(event, () => PromptReasoning.clearLatest());
11151176 }
11161177}
11171178