Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/_locales/de/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@
"Clear Conversation": "Konversation löschen",
"Retry": "Erneut versuchen",
"Exceeded maximum context length": "Maximale Kontextlänge überschritten, bitte Konversation löschen und erneut versuchen",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude hat das Antwort-Token-Limit erreicht. Erhöhen Sie die maximale Antwort-Token-Länge und versuchen Sie es erneut.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude hat das Kontextfenster des Modells ausgeschöpft. Löschen Sie die Konversation und versuchen Sie es erneut.",
"Claude declined to respond to this request.": "Claude hat die Antwort auf diese Anfrage abgelehnt.",
"Claude response stream ended before completion.": "Der Claude-Antwortstream wurde vorzeitig beendet.",
"Regenerate the answer after switching model": "Antwort nach dem Wechseln des Modells neu generieren",
"Pin": "Anheften",
"Unpin": "Loslösen",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@
"Clear Conversation": "Clear Conversation",
"Retry": "Retry",
"Exceeded maximum context length": "Exceeded maximum context length, please clear the conversation and try again",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude reached the response token limit. Increase Max Response Token Length and try again.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude reached the model context window limit. Clear the conversation and try again.",
"Claude declined to respond to this request.": "Claude declined to respond to this request.",
"Claude response stream ended before completion.": "Claude response stream ended before completion.",
Comment on lines +97 to +100

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.

Informational

1. Locale json lines exceed 100 📘 Rule violation ⚙ Maintainability

New localization entries add very long single-line JSON mappings that exceed the 100-character
line-length limit. This reduces readability and violates the project’s max line length requirement.
Agent Prompt
## Issue description
New locale entries are written as single-line JSON key/value pairs whose physical line length exceeds 100 characters.

## Issue Context
These keys/values are full sentences (often duplicated as key and value), which makes each JSON line very long in multiple `src/_locales/*/main.json` files.

## Fix Focus Areas
- src/_locales/en/main.json[97-99]
- src/_locales/de/main.json[90-92]

Potential approaches:
- Reformat JSON entries so the key and value are on separate lines (only helps if each individual string stays <= 100 chars).
- Shorten the user-facing strings (and keep them consistent with any code that matches on these messages).
- If long translations are expected, add an explicit repo-wide exemption for `src/_locales/**/main.json` in the relevant line-length/linting configuration.

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

"Regenerate the answer after switching model": "Regenerate the answer after switching model",
"Pin": "Pin",
"Unpin": "Unpin",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/es/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "Borrar conversación",
"Retry": "Reintentar",
"Exceeded maximum context length": "Se superó la longitud máxima del contexto, borre la conversación y vuelva a intentarlo",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude alcanzó el límite de tokens de respuesta. Aumente la longitud máxima de tokens de respuesta e inténtelo de nuevo.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude alcanzó el límite de la ventana de contexto del modelo. Borre la conversación e inténtelo de nuevo.",
"Claude declined to respond to this request.": "Claude se negó a responder a esta solicitud.",
"Claude response stream ended before completion.": "El flujo de respuesta de Claude terminó antes de completarse.",
"Regenerate the answer after switching model": "Regenerar la respuesta después de cambiar el modelo",
"Pin": "Fijar",
"Unpin": "Desfijar",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/fr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "Effacer la conversation",
"Retry": "Réessayer",
"Exceeded maximum context length": "Dépassement de la longueur maximale de contexte, veuillez effacer la conversation et réessayer",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude a atteint la limite de jetons de réponse. Augmentez la longueur maximale des jetons de réponse, puis réessayez.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude a atteint la limite de la fenêtre de contexte du modèle. Effacez la conversation, puis réessayez.",
"Claude declined to respond to this request.": "Claude a refusé de répondre à cette requête.",
"Claude response stream ended before completion.": "Le flux de réponse de Claude s’est terminé avant la fin.",
"Regenerate the answer after switching model": "Régénérer la réponse après avoir changé de modèle",
"Pin": "Épingler",
"Unpin": "Détacher",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/in/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "Bersihkan Percakapan",
"Retry": "Coba Lagi",
"Exceeded maximum context length": "Melampaui batas maksimum panjang konteks, harap bersihkan percakapan dan coba lagi",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude mencapai batas token respons. Tingkatkan panjang token respons maksimum lalu coba lagi.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude mencapai batas jendela konteks model. Hapus percakapan lalu coba lagi.",
"Claude declined to respond to this request.": "Claude menolak menanggapi permintaan ini.",
"Claude response stream ended before completion.": "Aliran respons Claude berakhir sebelum selesai.",
"Regenerate the answer after switching model": "Hasilkan kembali jawaban setelah beralih ke model lain",
"Pin": "Sematkan",
"Unpin": "Lepas Sematan",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/it/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "Pulisci la conversazione",
"Retry": "Riprova",
"Exceeded maximum context length": "Lunghezza massima del contesto superata, si prega di pulire la conversazione e riprovare",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude ha raggiunto il limite di token della risposta. Aumenta la lunghezza massima dei token della risposta e riprova.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude ha raggiunto il limite della finestra di contesto del modello. Cancella la conversazione e riprova.",
"Claude declined to respond to this request.": "Claude ha rifiutato di rispondere a questa richiesta.",
"Claude response stream ended before completion.": "Il flusso di risposta di Claude è terminato prima del completamento.",
"Regenerate the answer after switching model": "Rigenerare la risposta dopo aver cambiato il modello",
"Pin": "Fissa",
"Unpin": "Sblocca",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/ja/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "会話をクリア",
"Retry": "再試行",
"Exceeded maximum context length": "最大コンテキスト長を超えました。会話をクリアして再試行してください",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude が応答トークンの上限に達しました。最大応答トークン長を増やして、もう一度お試しください。",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude がモデルのコンテキストウィンドウ上限に達しました。会話をクリアして、もう一度お試しください。",
"Claude declined to respond to this request.": "Claude はこのリクエストへの応答を拒否しました。",
"Claude response stream ended before completion.": "Claude の応答ストリームが完了前に終了しました。",
"Regenerate the answer after switching model": "モデルを切り替えた後に回答を再生成",
"Pin": "ピン留め",
"Unpin": "ピン留め解除",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/ko/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "대화 내용 지우기",
"Retry": "재시도",
"Exceeded maximum context length": "최대 컨텍스트 길이를 초과하였습니다. 대화 내용을 지우고 다시 시도해주세요.",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude가 응답 토큰 한도에 도달했습니다. 최대 응답 토큰 길이를 늘린 후 다시 시도하세요.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude가 모델의 컨텍스트 창 한도에 도달했습니다. 대화 내용을 지운 후 다시 시도하세요.",
"Claude declined to respond to this request.": "Claude가 이 요청에 대한 응답을 거부했습니다.",
"Claude response stream ended before completion.": "Claude 응답 스트림이 완료되기 전에 종료되었습니다.",
"Regenerate the answer after switching model": "모델 전환 후 대답 다시 생성",
"Pin": "고정",
"Unpin": "고정 해제",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/pt/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "Limpar Conversa",
"Retry": "Tentar novamente",
"Exceeded maximum context length": "Ultrapassou o comprimento máximo do contexto. Limpe a conversa e tente novamente",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "O Claude atingiu o limite de tokens da resposta. Aumente o comprimento máximo dos tokens da resposta e tente novamente.",
"Claude reached the model context window limit. Clear the conversation and try again.": "O Claude atingiu o limite da janela de contexto do modelo. Limpe a conversa e tente novamente.",
"Claude declined to respond to this request.": "O Claude recusou responder a este pedido.",
"Claude response stream ended before completion.": "O fluxo de resposta do Claude terminou antes de ser concluído.",
"Regenerate the answer after switching model": "Regenerar a resposta após trocar o modelo",
"Pin": "Fixar",
"Unpin": "Desafixar",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/ru/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@
"Clear Conversation": "Очистить беседу",
"Retry": "Повторить",
"Exceeded maximum context length": "Превышена максимальная длина контекста, очистите беседу и повторите попытку",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude достиг лимита токенов ответа. Увеличьте максимальную длину ответа в токенах и повторите попытку.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude достиг лимита контекстного окна модели. Очистите беседу и повторите попытку.",
"Claude declined to respond to this request.": "Claude отказался отвечать на этот запрос.",
"Claude response stream ended before completion.": "Поток ответа Claude завершился до окончания ответа.",
"Regenerate the answer after switching model": "Генерировать ответ после смены модели",
"Pin": "Закрепить",
"Unpin": "Открепить",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/tr/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@
"Clear Conversation": "Konuşmayı Temizle",
"Retry": "Tekrar Dene",
"Exceeded maximum context length": "Maksimum bağlam uzunluğu aşıldı",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude yanıt belirteci sınırına ulaştı. Maksimum yanıt belirteci uzunluğunu artırıp yeniden deneyin.",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude modelin bağlam penceresi sınırına ulaştı. Konuşmayı temizleyip yeniden deneyin.",
"Claude declined to respond to this request.": "Claude bu isteğe yanıt vermeyi reddetti.",
"Claude response stream ended before completion.": "Claude yanıt akışı tamamlanmadan sona erdi.",
"Regenerate the answer after switching model": "Modeli değiştirdikten sonra cevabı yeniden oluştur",
"Pin": "Sabitle",
"Unpin": "Sabitlemeyi Kaldır",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/zh-hans/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@
"Clear Conversation": "清理对话",
"Retry": "重试",
"Exceeded maximum context length": "超出最大上下文长度, 请清理对话并重试",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude 已达到响应 token 上限。请增大最大响应 token 长度,然后重试。",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude 已达到模型上下文窗口上限。请清理对话,然后重试。",
"Claude declined to respond to this request.": "Claude 拒绝响应此请求。",
"Claude response stream ended before completion.": "Claude 响应流在完成前已结束。",
"Regenerate the answer after switching model": "快捷切换模型时自动重新生成回答",
"Pin": "固定侧边",
"Unpin": "收缩侧边",
Expand Down
4 changes: 4 additions & 0 deletions src/_locales/zh-hant/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@
"Clear Conversation": "清除對話",
"Retry": "重試",
"Exceeded maximum context length": "超出最大上下文長度,請清除對話並重試",
"Claude reached the response token limit. Increase Max Response Token Length and try again.": "Claude 已達回應 token 上限。請提高 [回應的最大 token 長度],然後再試一次。",
"Claude reached the model context window limit. Clear the conversation and try again.": "Claude 已達模型的上下文視窗上限。請清除對話後再試一次。",
"Claude declined to respond to this request.": "Claude 拒絕回應這項要求。",
"Claude response stream ended before completion.": "Claude 回應串流尚未完成便已結束。",
"Regenerate the answer after switching model": "切換模型後自動重新產生回答",
"Pin": "固定側邊",
"Unpin": "取消固定側邊",
Expand Down
59 changes: 52 additions & 7 deletions src/services/apis/claude-api.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getUserConfig } from '../../config/index.mjs'
import { pushRecord, setAbortController } from './shared.mjs'
import { fetchSSE } from '../../utils/fetch-sse.mjs'
import { FETCH_RESPONSE_STREAM_FAILED, fetchSSE } from '../../utils/fetch-sse.mjs'
import { isEmpty } from 'lodash-es'
import { getConversationPairs } from '../../utils/get-conversation-pairs.mjs'
import { getModelValue } from '../../utils/model-name-convert.mjs'
Expand Down Expand Up @@ -49,7 +49,11 @@ export async function generateAnswersWithClaudeApi(port, question, session) {
}

let answer = ''
await fetchSSE(`${apiUrl}/v1/messages`, {
let stopReason = ''
let completionError
let wasAborted = false
let completedSuccessfully = false
const streamError = await fetchSSE(`${apiUrl}/v1/messages`, {
method: 'POST',
signal: controller.signal,
headers: {
Expand All @@ -69,10 +73,42 @@ export async function generateAnswersWithClaudeApi(port, question, session) {
console.debug('json error', error)
return
}
if (data?.type === 'error') {
controller.abort()
const error = new Error(JSON.stringify(data))
if (completedSuccessfully) error.code = FETCH_RESPONSE_STREAM_FAILED
throw error
}
if (completedSuccessfully) return
if (data?.type === 'message_delta') {
stopReason = data?.delta?.stop_reason || stopReason
return
}
if (data?.type === 'message_stop') {
if (stopReason === 'max_tokens') {
completionError = new Error(
'Claude reached the response token limit. Increase Max Response Token Length 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.

Informational

1. Claude strings exceed 100 columns 📘 Rule violation ⚙ Maintainability

The new Claude error string and SSE fixtures contain physical lines longer than 100 characters.
These additions violate the source line-length limit.
Agent Prompt
## Issue description
New Claude error and test fixture strings exceed the 100-character physical line limit.

## Issue Context
Preserve the exact runtime string values by wrapping them with concatenation or another formatting approach that does not introduce whitespace.

## Fix Focus Areas
- src/services/apis/claude-api.mjs[83-83]
- tests/unit/services/apis/claude-api.test.mjs[234-253]

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

)
}
if (stopReason === 'model_context_window_exceeded') {
completionError = new Error(
'Claude reached the model context window limit. Clear the conversation and try again.',
)
}
if (stopReason === 'refusal') {
completionError = new Error('Claude declined to respond to this request.')
}
if (!completionError && !['end_turn', 'stop_sequence'].includes(stopReason)) {
completionError = new Error('Claude response stream ended before completion.')
}
if (completionError) {
controller.abort()
throw completionError
}
Comment on lines +98 to +107

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 Reject nonterminal Claude stop reasons

When Anthropic returns another non-final stop reason such as pause_turn, this blacklist falls through at message_stop, saves the partial answer, and reports success. A paused turn must be continued rather than committed as a completed response, so success should be limited to terminal reasons such as end_turn and stop_sequence, with pause_turn handled explicitly.

Useful? React with 👍 / 👎.

pushRecord(session, question, answer)
console.debug('conversation history', { content: session.conversationRecords })
port.postMessage({ answer: null, done: true, session: session })
completedSuccessfully = true
return
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

Expand All @@ -84,12 +120,10 @@ export async function generateAnswersWithClaudeApi(port, question, session) {
},
async onStart() {},
async onEnd(aborted) {
wasAborted = aborted
try {
if (!aborted) {
port.postMessage({ done: true })
}
} finally {
port.onMessage.removeListener(messageListener)
} finally {
port.onDisconnect.removeListener(disconnectListener)
}
},
Expand All @@ -100,5 +134,16 @@ export async function generateAnswersWithClaudeApi(port, question, session) {
const error = await resp.json().catch(() => ({}))
throw new Error(!isEmpty(error) ? JSON.stringify(error) : `${resp.status} ${resp.statusText}`)
},
})
}).catch((error) => error)
if (wasAborted) return
if (completionError) throw completionError
if (
streamError &&
(!completedSuccessfully || streamError.code !== FETCH_RESPONSE_STREAM_FAILED)
) {
throw streamError
}
if (!completedSuccessfully) {
throw new Error('Claude response stream ended before completion.')
Comment on lines +146 to +147

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 Preserve Anthropic SSE error details

When Anthropic accepts the request but later emits an SSE error event, such as overloaded_error, onMessage ignores that event and this fallback reports only “Claude response stream ended before completion.” This masks the provider's actionable error type/message during overloads and other mid-stream failures; capture data.error and surface it before applying the generic EOF fallback.

Useful? React with 👍 / 👎.

}
}
Loading