Repository navigation
fix: abort upstream requests on client disconnect, pool connections, handle assistant prefill #278
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,12 +1,15 @@ | ||||||||||||||||||||||||||||||||||||||
| import consola from "consola" | ||||||||||||||||||||||||||||||||||||||
| import { events } from "fetch-event-stream" | ||||||||||||||||||||||||||||||||||||||
| import { getGlobalDispatcher, type Dispatcher } from "undici" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| import { copilotHeaders, copilotBaseUrl } from "~/lib/api-config" | ||||||||||||||||||||||||||||||||||||||
| import { HTTPError } from "~/lib/error" | ||||||||||||||||||||||||||||||||||||||
| import { state } from "~/lib/state" | ||||||||||||||||||||||||||||||||||||||
| import { refreshCopilotToken } from "~/lib/token" | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| export const createChatCompletions = async ( | ||||||||||||||||||||||||||||||||||||||
| payload: ChatCompletionsPayload, | ||||||||||||||||||||||||||||||||||||||
| signal?: AbortSignal, | ||||||||||||||||||||||||||||||||||||||
| ) => { | ||||||||||||||||||||||||||||||||||||||
| if (!state.copilotToken) throw new Error("Copilot token not found") | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
|
|
@@ -22,25 +25,48 @@ export const createChatCompletions = async ( | |||||||||||||||||||||||||||||||||||||
| ["assistant", "tool"].includes(msg.role), | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| // Build headers and add X-Initiator | ||||||||||||||||||||||||||||||||||||||
| const headers: Record<string, string> = { | ||||||||||||||||||||||||||||||||||||||
| ...copilotHeaders(state, enableVision), | ||||||||||||||||||||||||||||||||||||||
| "X-Initiator": isAgentCall ? "agent" : "user", | ||||||||||||||||||||||||||||||||||||||
| const body = JSON.stringify(payload) | ||||||||||||||||||||||||||||||||||||||
| const send = () => { | ||||||||||||||||||||||||||||||||||||||
| // Build headers (with the current Copilot token) and add X-Initiator | ||||||||||||||||||||||||||||||||||||||
| const headers: Record<string, string> = { | ||||||||||||||||||||||||||||||||||||||
| ...copilotHeaders(state, enableVision), | ||||||||||||||||||||||||||||||||||||||
| "X-Initiator": isAgentCall ? "agent" : "user", | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| const requestInit: RequestInit & { dispatcher: Dispatcher } = { | ||||||||||||||||||||||||||||||||||||||
| method: "POST", | ||||||||||||||||||||||||||||||||||||||
| headers, | ||||||||||||||||||||||||||||||||||||||
| body, | ||||||||||||||||||||||||||||||||||||||
| signal, | ||||||||||||||||||||||||||||||||||||||
| dispatcher: getGlobalDispatcher(), | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
| return fetch(`${copilotBaseUrl(state)}/chat/completions`, requestInit) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| const response = await fetch(`${copilotBaseUrl(state)}/chat/completions`, { | ||||||||||||||||||||||||||||||||||||||
| method: "POST", | ||||||||||||||||||||||||||||||||||||||
| headers, | ||||||||||||||||||||||||||||||||||||||
| body: JSON.stringify(payload), | ||||||||||||||||||||||||||||||||||||||
| }) | ||||||||||||||||||||||||||||||||||||||
| let response = await send() | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| // The Copilot token can be revoked server-side before its scheduled | ||||||||||||||||||||||||||||||||||||||
| // refresh. On 401/403, fetch a fresh token and retry once. | ||||||||||||||||||||||||||||||||||||||
| if (response.status === 401 || response.status === 403) { | ||||||||||||||||||||||||||||||||||||||
| consola.warn( | ||||||||||||||||||||||||||||||||||||||
| `Copilot returned ${response.status}, refreshing Copilot token and retrying`, | ||||||||||||||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||||||||||
| await refreshCopilotToken() | ||||||||||||||||||||||||||||||||||||||
| await response.body?.cancel() | ||||||||||||||||||||||||||||||||||||||
| response = await send() | ||||||||||||||||||||||||||||||||||||||
| } catch (error) { | ||||||||||||||||||||||||||||||||||||||
| consola.error("Failed to refresh Copilot token:", error) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+54
to
+60
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win Limit the The
The result is that the real error (network failure or abort) is lost. The client gets a misleading 401/403 or an error-handler failure. The route handlers check for Catch only the refresh failure. If the refresh fails, keep the first response and do not cancel its body. 🐛 Proposed fix--- "a/src/services/copilot/create-chat-completions.ts"
+++ "b/src/services/copilot/create-chat-completions.ts"
@@ -51,13 +51,17 @@
consola.warn(
`Copilot returned ${response.status}, refreshing Copilot token and retrying`,
)
- try {
- await refreshCopilotToken()
- await response.body?.cancel()
- response = await send()
- } catch (error) {
- consola.error("Failed to refresh Copilot token:", error)
- }
+ let refreshed = false
+ try {
+ await refreshCopilotToken()
+ refreshed = true
+ } catch (error) {
+ consola.error("Failed to refresh Copilot token:", error)
+ }
+ if (refreshed) {
+ await response.body?.cancel()
+ response = await send()
+ }
}
if (!response.ok) {📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| if (!response.ok) { | ||||||||||||||||||||||||||||||||||||||
| consola.error("Failed to create chat completions", response) | ||||||||||||||||||||||||||||||||||||||
| throw new HTTPError("Failed to create chat completions", response) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| if (payload.stream) { | ||||||||||||||||||||||||||||||||||||||
| return events(response) | ||||||||||||||||||||||||||||||||||||||
| return events(response, signal) | ||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| return (await response.json()) as ChatCompletionResponse | ||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Resolve upstream failures before returning an SSE response. Both routes now await the Copilot request inside the
streamSSEcallback. If the token is missing or Copilot rejects the request, Hono has already returned the SSE response. Hono then writes anerrorevent instead of allowing an HTTP error response. (github.com)src/routes/chat-completions/handler.ts#L62-L62: await the upstream connection before callingstreamSSE; retain the controller for disconnect cancellation.src/routes/messages/handler.ts#L58-L61: make the same change before starting the translated SSE response.📍 Affects 2 files
src/routes/chat-completions/handler.ts#L62-L62(this comment)src/routes/messages/handler.ts#L58-L61