Skip to content

Reject token-length-truncated OpenAI-compatible answers - #1151

Open
sanketpatel32 wants to merge 4 commits into
ChatGPTBox-dev:masterfrom
sanketpatel32:devin/1796177544-finish-length-error
Open

sanketpatel32 wants to merge 4 commits into
ChatGPTBox-dev:masterfrom
sanketpatel32:devin/1796177544-finish-length-error

Conversation

@sanketpatel32

@sanketpatel32 sanketpatel32 commented Dec 2, 2026 •

Copy link
Copy Markdown

Fixes #1148

Summary

OpenAI-compatible and Azure OpenAI streams now treat finish_reason === 'length' as a terminal error instead of a completed answer. The partial text already streamed to the card remains visible, but the request is aborted and the truncated turn is not written with pushRecord() or reported as done; other finish reasons keep the existing completion behavior.

The error uses one shared localization key with a {{maxTokens}} interpolation placeholder, translations in every locale, and handlePortError() interpolation before display, so users see the configured response-token limit in their selected language.

Added regression coverage for both providers showing that a length-limited partial answer rejects, is not saved to conversationRecords, and does not post a successful completion. Also added handlePortError() coverage for interpolated translation.

Validation

  • npm run pretty — passed
  • npm run lint — passed
  • npm test — 1125 passed
  • npm run build — passed; expected Chromium build artifacts verified
  • Manual browser smoke tests skipped: no live provider credentials are available in this environment.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T02:26:45.258892Z 4b7b6a1 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The OpenAI-compatible and Azure OpenAI handlers now reject responses that end because they reached the configured response token limit. The error includes the limit and is translated for display. Tests verify that partial answers remain posted, no completion message or conversation record is added, and port listeners are cleaned up.

Changes: Length-limited responses

Layer / File(s) Summary
Define and translate the token-limit error
src/services/apis/shared.mjs, src/services/wrappers.mjs, tests/unit/services/handle-port-error.test.mjs, src/_locales/*/main.json
A shared error factory sets the translation key and configured token limit. The port error handler translates errors that have a translation key. Locale files add the corresponding message in 13 languages.
Handle length-limited completions
src/services/apis/openai-compatible-core.mjs, src/services/apis/azure-openai-api.mjs, tests/unit/services/apis/openai-api-compat.test.mjs, tests/unit/services/apis/azure-openai-api.test.mjs
Both handlers abort and throw the token-limit error when the finish reason is length. Tests check the partial answer, the absence of a completion message and conversation record, and listener cleanup.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: peterdavehello

Merge Risk: Minimal · up to be6be

Answers cut off by the response token limit now show an error with the configured limit instead of being saved as complete. Partial text stays visible. No concrete merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Reject token-length-truncated OpenAI-compatible answers" matches the main change. The PR makes OpenAI-compatible and Azure OpenAI streams treat finish_reason 'length' as an error. The chang…
Linked Issues check Passed [#1148] requires that answers stopped at the response token limit (finish_reason 'length') are not saved or reported as complete. The partial text must stay visible, and other finish reasons must keep…
Out of Scope Changes check Passed The production changes are limited to the two stream handlers named in #1148, plus the shared error helper and its message delivery. The helper is src/services/apis/shared.mjs, and the delivery change…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title "Reject token-length-truncated OpenAI-compatible answers" matches the main change. The PR makes OpenAI-compatible and Azure OpenAI streams treat finish_reason 'length' as an error. The change aborts the request, throws a max-response-token error, and skips saving the record or posting completion. The title is specific, concise, and free of noise. It omits Azure OpenAI, but the wording still covers the main point.

Full details: Linked Issues check

Explanation

[#1148] requires that answers stopped at the response token limit (finish_reason 'length') are not saved or reported as complete. The partial text must stay visible, and other finish reasons must keep their behavior.

The whole-PR summary shows the same length check in both stream handlers. src/services/apis/openai-compatible-core.mjs aborts the controller and throws createMaxResponseTokenLengthError(...) when finish_reason is 'length'. src/services/apis/azure-openai-api.mjs applies the same check before its existing finish branch. Because the throw happens before finish(), pushRecord() and done are not reached for this case. Other finish reasons still reach the existing completion path.

The error carries MAX_RESPONSE_TOKEN_LENGTH_ERROR_KEY, which is added in src/services/apis/shared.mjs. src/services/wrappers.mjs (handlePortError) posts the translated error when translationKey is present. This follows the Claude-style error path that the issue asks to mirror.

Regression tests in tests/unit/services/apis/openai-api-compat.test.mjs and tests/unit/services/apis/azure-openai-api.test.mjs cover rejection, the token-limit message, no conversation record, no completion message, and listener cleanup. I did not read the test files. This verdict relies on the PR summary for the tests.

The optional default-limit tuning in the issue is not a requirement. No coding requirement from #1148 is unmet in the reviewed evidence.

Full details: Out of Scope Changes check

Explanation

The production changes are limited to the two stream handlers named in #1148, plus the shared error helper and its message delivery. The helper is src/services/apis/shared.mjs, and the delivery change is in src/services/wrappers.mjs. These changes support a localized token-limit error that the issue requests.

The locale files (src/_locales/*/main.json) add one translation string each for the new message. This supports the new error text and does not change other behavior.

The test changes in azure-openai-api.test.mjs, openai-api-compat.test.mjs, and handle-port-error.test.mjs support the stated objective. The summary shows no unrelated file or behavior change.

I did not inspect the full whole-PR diff. This verdict relies on the PR summary and the file-level change summaries.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 97303163-0a37-46fe-b675-c739966c8c01
Commits

Reviewing files that changed from the base of the PR and between 4b7b6a1 and be6beb2.

Files selected for processing: 20

  • src/_locales/de/main.json
  • src/_locales/en/main.json
  • src/_locales/es/main.json
  • src/_locales/fr/main.json
  • src/_locales/id/main.json
  • src/_locales/it/main.json
  • src/_locales/ja/main.json
  • src/_locales/ko/main.json
  • src/_locales/pt/main.json
  • src/_locales/ru/main.json
  • src/_locales/tr/main.json
  • src/_locales/zh-hans/main.json
  • src/_locales/zh-hant/main.json
  • src/services/apis/azure-openai-api.mjs
  • src/services/apis/openai-compatible-core.mjs
  • src/services/apis/shared.mjs
  • src/services/wrappers.mjs
  • tests/unit/services/apis/azure-openai-api.test.mjs
  • tests/unit/services/apis/openai-api-compat.test.mjs
  • tests/unit/services/handle-port-error.test.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@qodo-code-review

qodo-code-review Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Reject token-length-truncated OpenAI-compatible answers

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• OpenAI-compatible and Azure OpenAI streams treat finish_reason: 'length' as a terminal error,
 not a completed answer.
• Truncated turns abort the request, throw a "Max Response Token Length" error, and skip
 pushRecord() and the done message.
• Regression tests for both providers verify the partial answer rejects, is not saved, and posts no
 completion.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 2 capabilities

  • 2 affected capabilities span independent functional scopes: Azure OpenAI integration, OpenAI-compatible provider integration.
  • The changed path is the Azure-specific end-to-end request and streaming response integration.
  • Its propagation path terminates at Azure OpenAI answer generation, with no evidence that this branch changes unrelated providers.
  • The shared core implements the end-to-end streaming response behavior for the generic OpenAI-compatible provider family.
  • The changed branch is in the shared response callback, so it applies across that bounded integration, while Azure uses a separate implementation and scope.
Behavioral complexity 🟡 Medium 🧩 Interacting branches

  • Before, any finish reason entered the record-and-complete path after streaming the delta.
  • After, finish_reason='length' aborts and throws before recording, while other finish reasons still complete.
  • New correctness condition: the length branch must occur after the partial delta is delivered but before pushRecord and done=true, while cleanup remains effective.
  • This adds a small interaction between stream termination, abort handling, error propagation, and conversation-record state; no new algorithm or concurrency protocol is introduced.
Sources

src/services/apis/azure-openai-api.mjs[63-74]

          port.postMessage({ answer: answer, done: false, session: null })
        }

        const finishReason = data.choices?.[0]?.finish_reason
        if (finishReason === 'length') {
          controller.abort()
          throw new Error(
            `The answer reached Max Response Token Length (${config.maxResponseTokenLength}). Increase it in Advanced settings and try again.`,
          )
        }
        if (finishReason) {
          pushRecord(session, question, answer)
Potential damage 🟡 Medium 🩹 Temporary loss

  • A token-limited Azure response is surfaced as an error and its partial answer is not committed to conversation history.
  • The user can retry or increase the configured limit; reverting restores the prior handling.
  • The partial streamed display may already have been shown, but no persistent record or external side effect is created by this branch.
  • Reverting restores the previous behavior.
  • Under the new behavior, retrying with a higher response limit is supported by the emitted error message; no stored-state repair or external compensation is required.
Sources

src/services/apis/azure-openai-api.mjs[63-74]

          port.postMessage({ answer: answer, done: false, session: null })
        }

        const finishReason = data.choices?.[0]?.finish_reason
        if (finishReason === 'length') {
          controller.abort()
          throw new Error(
            `The answer reached Max Response Token Length (${config.maxResponseTokenLength}). Increase it in Advanced settings and try again.`,
          )
        }
        if (finishReason) {
          pushRecord(session, question, answer)
Assessed commit 4b7b6a1
Diagram

graph TD
  A["SSE stream chunk"] --> B{"finish_reason?"}
  B -->|"length"| C["Abort and throw error"]
  B -->|"other reason"| D["pushRecord and done"]
  B -->|"none"| E["Keep streaming"]
Loading
High-Level Assessment

Rejecting the turn with an error is the right approach. It keeps the partial text visible on the card, which is useful context, while stopping a truncated answer from being saved to conversation history or treated as complete. The alternative of treating 'length' as a normal completion would silently store incomplete answers, and a warning-only approach would still leave the record in history. The change is local to each stream handler, and it matches the existing finish handling pattern, so no broader refactor is needed.

Files changed (4) +101 / -1

Bug fix (2) +15 / -1
azure-openai-api.mjsThrow on length finish_reason in Azure OpenAI stream handler +8/-1

Throw on length finish_reason in Azure OpenAI stream handler

• Reads finish_reason once from the first choice. When it equals 'length', the handler aborts the controller and throws the max-response-token error before the record is saved. Other finish reasons still call pushRecord and post done.

src/services/apis/azure-openai-api.mjs

openai-compatible-core.mjsThrow on length finish_reason in OpenAI-compatible core +7/-0

Throw on length finish_reason in OpenAI-compatible core

• After posting each partial answer, the handler checks for finish_reason 'length'. It then aborts the request and throws the max-response-token error, which prevents the finish() call that would record and complete the turn.

src/services/apis/openai-compatible-core.mjs

Tests (2) +86 / -0
azure-openai-api.test.mjsAdd Azure length-truncation rejection regression test +41/-0

Add Azure length-truncation rejection regression test

• Mocks an SSE stream with a single 'Part' delta and finish_reason 'length'. It asserts the call rejects with the token-limit message, the partial answer was posted, no done message was sent, conversationRecords stays empty, and listeners are cleaned up.

tests/unit/services/apis/azure-openai-api.test.mjs

openai-api-compat.test.mjsAdd OpenAI-compatible length-truncation rejection regression test +45/-0

Add OpenAI-compatible length-truncation rejection regression test

• Mirrors the Azure test for generateAnswersWithOpenAiApiCompat. It verifies the rejection message, that the partial answer is streamed, that no done message is posted, that no record is saved, and that listeners are removed.

tests/unit/services/apis/openai-api-compat.test.mjs

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 4 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

View guided diff | Re-trigger cubic

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No blocking issues — one non-blocking finding below.

Approach: sound — it mirrors the existing Claude token-limit path (controller.abort() + throw from onMessage), so the partial text stays on the card while the turn is neither recorded nor reported as done.

Reviewed changes

  • openai-compatible-core — treats finish_reason: 'length' as terminal in the shared chat/completion stream, aborting and throwing before finish() can pushRecord/post done.
  • Azure OpenAI — same check in generateAnswersWithAzureOpenaiApi, replacing the bare truthiness test with an explicit finishReason === 'length' branch.
  • Tests — one regression test per adapter asserting the rejection message, that the partial answer was streamed, that no done/record was produced, and that port listeners are cleaned up.

Non-blocking

  • The new token-limit error is a hardcoded interpolated English string, so it skips the localization and plain-text formatting the Claude equivalent gets. handlePortError runs the message through formatErrorMessage, whose richErrorTextPattern matches the parentheses around the count, so ConversationCard renders the whole message as a diagnostic code fence and getDisplayErrorText returns it untranslated — unlike Claude reached the response token limit..., a static key present in all 13 locales and rendered as plain localized text (core, azure). A static key (dropping the count) or a code routed through handlePortError's existing %s interpolation would fix both and de-duplicate the two copies.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Long error lines break the width rule 📘 Rule violation ⚙ Maintainability
Description
The added throw new Error(...) template literal in generateAnswersWithAzureOpenaiApi sits on one
physical line of roughly 140 characters, well past the 100-character limit. The same overlong line
appears in openai-compatible-core.mjs (line 152, about 135 characters), and the new test titles
and regex assertions in both test files also exceed 100 columns. A formatter cannot wrap a template
literal, so the message has to be split with string concatenation to conform.
Code

src/services/apis/azure-openai-api.mjs[70]

+            `The answer reached Max Response Token Length (${config.maxResponseTokenLength}). Increase it in Advanced settings and try again.`,
Evidence
Added line 70 is 12 spaces of indentation plus a backtick-quoted template literal of about 129
characters, exceeding the 100-character maximum. The OpenAI-compatible core line 152 follows the
same pattern, so the violation is not confined to one file.

Rule 2262946: Limit source line length to 100 characters
src/services/apis/azure-openai-api.mjs[70-70]
src/services/apis/openai-compatible-core.mjs[152-152]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The added error message in the Azure OpenAI stream handler is a single template literal on one physical line of roughly 140 characters, exceeding the 100-character source line limit. The same issue appears in the OpenAI-compatible core handler and in the new test titles and regex assertions.

## Fix Focus Areas
- src/services/apis/azure-openai-api.mjs[66-72]
- src/services/apis/openai-compatible-core.mjs[148-154]
- tests/unit/services/apis/azure-openai-api.test.mjs[231-231]
- tests/unit/services/apis/openai-api-compat.test.mjs[491-491]

## Recommended Fix
Split each long template literal into two or more shorter literals joined with `+`, for example `'The answer reached Max Response Token Length (' + config.maxResponseTokenLength + '). Increase it in Advanced settings and try again.'`, keeping each physical line at 100 characters or fewer. Apply the same wrapping to the overlong `test(...)` titles and the regex assertion lines in the two new regression tests.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


Grey Divider

Context sources
❌ Tickets: failed to load — Ticket collection could not establish complete evidence
✅ Compliance rules (platform): 6 rules
Review mode: Auto: ⚖️ Balanced: Localized streaming error behavior still merits a careful complete review.

Grey Divider

Tip of the day
💡 Did you know, you can see how risky a PR is at a glance with blast radius labels

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/services/apis/azure-openai-api.mjs Outdated
if (finishReason === 'length') {
controller.abort()
throw new Error(
`The answer reached Max Response Token Length (${config.maxResponseTokenLength}). Increase it in Advanced settings and try again.`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

1. Long error lines break the width rule 📘 Rule violation ⚙ Maintainability

The added throw new Error(...) template literal in generateAnswersWithAzureOpenaiApi sits on one
physical line of roughly 140 characters, well past the 100-character limit. The same overlong line
appears in openai-compatible-core.mjs (line 152, about 135 characters), and the new test titles
and regex assertions in both test files also exceed 100 columns. A formatter cannot wrap a template
literal, so the message has to be split with string concatenation to conform.
Agent Prompt
## Issue description
The added error message in the Azure OpenAI stream handler is a single template literal on one physical line of roughly 140 characters, exceeding the 100-character source line limit. The same issue appears in the OpenAI-compatible core handler and in the new test titles and regex assertions.

## Fix Focus Areas
- src/services/apis/azure-openai-api.mjs[66-72]
- src/services/apis/openai-compatible-core.mjs[148-154]
- tests/unit/services/apis/azure-openai-api.test.mjs[231-231]
- tests/unit/services/apis/openai-api-compat.test.mjs[491-491]

## Recommended Fix
Split each long template literal into two or more shorter literals joined with `+`, for example `'The answer reached Max Response Token Length (' + config.maxResponseTokenLength + '). Increase it in Advanced settings and try again.'`, keeping each physical line at 100 characters or fewer. Apply the same wrapping to the overlong `test(...)` titles and the regex assertion lines in the two new regression tests.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

@greptile-apps

greptile-apps Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; the previous localization issue is fixed.

Summary

OpenAI-compatible and Azure OpenAI answers that hit the token limit remain visible but are not saved as completed answers.

  • Length-limited answers stay visible but no longer count as finished.

Reviews (2) · Last reviewed commit: "Use localized token-limit error in OpenA..." · Reviewed by Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4b7b6a189d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (finishReason === 'length') {
controller.abort()
throw new Error(
`The answer reached Max Response Token Length (${config.maxResponseTokenLength}). Increase it in Advanced settings and try again.`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Localize the interpolated token-limit error

When the UI language is non-English and this branch (or the duplicate Azure branch) receives finish_reason: "length", the fully interpolated sentence is passed to getDisplayErrorText(..., t), but no stable key for it exists in src/_locales/en/main.json or the translated resources; because the numeric value is part of the lookup key, i18next falls back to displaying this English text. Use a localization key with interpolation (and add it to the locale resources) so this newly user-facing failure is translated like the existing Claude token-limit error.

AGENTS.md reference: AGENTS.md:L211-L212

Useful? React with 👍 / 👎.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed the two commits pushed since the prior pullfrog review (3d010a1, be6beb2), which replace the hardcoded token-limit string with a localized, interpolated error.

  • Localized token-limit error — shared.mjs now exports MAX_RESPONSE_TOKEN_LENGTH_ERROR_KEY plus createMaxResponseTokenLengthError(maxTokens), which attaches translationKey/translationParams to the thrown error.
  • Translation at the port boundary — handlePortError posts translate(err.translationKey, err.translationParams) for keyed errors, so the message renders as plain localized text instead of a diagnostic code fence.
  • All 13 locales — the {{maxTokens}} template key was added to every locale in resources.mjs; interpolation resolves in each one.
  • Tests — adapter regressions now assert the shared key and { maxTokens } params, and a new handlePortError test covers the keyed-error branch.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@sanketpatel32

Copy link
Copy Markdown
Author

Thanks for the feedback. In be6beb2, the token-limit error now uses a shared i18n key with {{maxTokens}} interpolation and translations in every locale file, handlePortError() applies the interpolation before display, and the new source and test lines stay within the 100-column limit. npm run lint and npm test pass (1125 tests); npm run build also passes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OpenAI-compatible answers cut off at Max Response Token Length are saved and shown as complete

1 participant