Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix: stop MLX model inference when client aborts chat/completions
Louis05f65cf326eb
diff --git a/mlx-server/Sources/MLXServer/ModelRunner.swift b/mlx-server/Sources/MLXServer/ModelRunner.swiftindex f438b3dc0..dc996218d 100644--- a/mlx-server/Sources/MLXServer/ModelRunner.swift+++ b/mlx-server/Sources/MLXServer/ModelRunner.swift@@ -385,6 +385,9 @@ actor ModelRunner {for await generation in try MLXLMCommon.generate(input: lmInput, cache: cache?.cache, parameters: generateParameters, context: context) {+ // Check if the task was cancelled (client disconnected)+ try Task.checkCancellation()+switch generation {case .chunk(let chunk):output += chunk@@ -395,8 +398,8 @@ actor ModelRunner {// Note: info.promptTokenCount is the tokens processed in this call (may be less due to caching)// We report the full promptTokenCount in usage for accurate trackinglog("[mlx] Generation info: \(info.promptTokenCount) processed prompt tokens, \(info.generationTokenCount) generated tokens")- log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")- log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")+ log("[mlx] Prompt: \(String(format: "%.1f", info.promptTokensPerSecond)) tokens/sec")+ log("[mlx] Generation: \(String(format: "%.1f", info.tokensPerSecond)) tokens/sec")case .toolCall(let toolCall):let argsData = try JSONSerialization.data(@@ -416,6 +419,9 @@ actor ModelRunner {log("[mlx] Tool call: \(toolCall.function.name)(\(argsString))")}}+ } catch is CancellationError {+ log("[mlx] Generation cancelled by client")+ throw CancellationError()} catch {log("[mlx] Error during generation: \(error.localizedDescription)")throw error@@ -455,7 +461,7 @@ actor ModelRunner {tools: [AnyCodable]? = nil) -> AsyncThrowingStream<StreamEvent, Error> {AsyncThrowingStream { continuation in- Task {+ let task = Task {guard let container = self.container else {log("[mlx] Error: generateStream() called but no model is loaded")continuation.finish(throwing: MLXServerError.modelNotLoaded)@@ -501,6 +507,12 @@ actor ModelRunner {for await generation in try MLXLMCommon.generate(input: lmInput, cache: cache?.cache, parameters: generateParameters, context: context) {+ // Check if the task was cancelled (client disconnected)+ if Task.isCancelled {+ log("[mlx] Stream generation cancelled by client")+ break+ }+switch generation {case .chunk(let chunk):accumulated += chunk@@ -548,20 +560,32 @@ actor ModelRunner {}}} catch {- log("[mlx] Error during stream generation: \(error.localizedDescription)")- throw error+ if Task.isCancelled {+ log("[mlx] Stream generation cancelled by client")+ } else {+ log("[mlx] Error during stream generation: \(error.localizedDescription)")+ throw error+ }}- // If no .info was received, send done with fallback usage- // The .info case already yields .done, so only send if we haven'tlog("[mlx] Stream complete: \(accumulated.count) chars")continuation.finish()}} catch {- log("[mlx] Error in stream: \(error.localizedDescription)")- continuation.finish(throwing: error)+ if Task.isCancelled {+ log("[mlx] Stream cancelled by client")+ continuation.finish()+ } else {+ log("[mlx] Error in stream: \(error.localizedDescription)")+ continuation.finish(throwing: error)+ }}}++ // Cancel the generation task when the stream consumer stops (client disconnect)+ continuation.onTermination = { @Sendable _ in+ task.cancel()+ }}}}diff --git a/mlx-server/Sources/MLXServer/Server.swift b/mlx-server/Sources/MLXServer/Server.swiftindex 8e690f10a..35d16c1af 100644--- a/mlx-server/Sources/MLXServer/Server.swift+++ b/mlx-server/Sources/MLXServer/Server.swift@@ -1,29 +1,56 @@import Foundationimport Hummingbird+/// Tracks active generation tasks for external cancellation (e.g., /cancel endpoint)+actor ActiveGenerations {+ private var tasks: [String: Task<Void, Never>] = [:]++ func register(_ id: String, task: Task<Void, Never>) {+ tasks[id] = task+ }++ func cancel(_ id: String) -> Bool {+ guard let task = tasks.removeValue(forKey: id) else { return false }+ task.cancel()+ return true+ }++ func cancelAll() -> Int {+ let count = tasks.count+ tasks.values.forEach { $0.cancel() }+ tasks.removeAll()+ return count+ }++ func remove(_ id: String) {+ tasks.removeValue(forKey: id)+ }+}+/// HTTP server that exposes an OpenAI-compatible API backed by MLXstruct MLXHTTPServer {let modelRunner: ModelRunnerlet modelId: Stringlet apiKey: Stringlet batchingConfig: BatchingConfig?+ let activeGenerations = ActiveGenerations()private var batchProcessor: BatchProcessor?-+init(modelRunner: ModelRunner, modelId: String, apiKey: String, batchingConfig: BatchingConfig? = nil) {self.modelRunner = modelRunnerself.modelId = modelIdself.apiKey = apiKeyself.batchingConfig = batchingConfig-+// Initialize batch processor if batching is enabledif let config = batchingConfig, config.maxBatchSize > 0 {self.batchProcessor = BatchProcessor(modelRunner: modelRunner, config: config)}}-+func buildRouter() -> Router<BasicRequestContext> {let router = Router()-+// Health checkrouter.get("/health") { _, _ inlet batchingStatus: String@@ -38,7 +65,7 @@ struct MLXHTTPServer {)return try encodeJSON(response)}-+// Metrics endpointrouter.get("/metrics") { _, _ inlet metrics: [String: Any]@@ -61,24 +88,24 @@ struct MLXHTTPServer {"batching": "disabled",]}-+// Build JSON responsevar jsonString = "{\n"for (key, value) in metrics {jsonString += " \"\(key)\": \(value),\n"}jsonString += "}"-+var buffer = ByteBufferAllocator().buffer(capacity: jsonString.count)buffer.writeString(jsonString)-+return Response(status: .ok,headers: [.contentType: "application/json"],body: .init(byteBuffer: buffer))}-+// List modelsrouter.get("/v1/models") { _, _ inlet response = ModelsResponse(@@ -94,7 +121,7 @@ struct MLXHTTPServer {)return try encodeJSON(response)}-+// Chat completionsrouter.post("/v1/chat/completions") { request, context in// Validate API key if set@@ -118,12 +145,12 @@ struct MLXHTTPServer {return response}}-+// Parse request bodydo {let body = try await request.body.collect(upTo: 10 * 1024 * 1024) // 10MB maxlet chatRequest = try JSONDecoder().decode(ChatCompletionRequest.self, from: body)-+let temperature = chatRequest.temperature ?? 0.7let topP = chatRequest.top_p ?? 1.0let maxTokens = chatRequest.max_tokens ?? chatRequest.n_predict ?? 2048@@ -131,9 +158,9 @@ struct MLXHTTPServer {let stop = chatRequest.stop ?? []let isStreaming = chatRequest.stream ?? falselet tools = chatRequest.tools-+log("[mlx] Request: model=\(chatRequest.model), messages=\(chatRequest.messages.count), stream=\(isStreaming), tools=\(tools?.count ?? 0)")-+if isStreaming {return try await self.handleStreamingRequest(chatRequest: chatRequest,@@ -171,10 +198,35 @@ struct MLXHTTPServer {)}}-++ // Cancel active generation+ router.post("/v1/cancel") { _, _ in+ let cancelled = await self.activeGenerations.cancelAll()+ log("[mlx] Cancel requested: \(cancelled) active generation(s) cancelled")++ let response: [String: Any] = [+ "status": cancelled > 0 ? "cancelled" : "no_active_generation",+ "cancelled_count": cancelled,+ ]++ var jsonString = "{"+ jsonString += "\"status\":\"\(response["status"]!)\","+ jsonString += "\"cancelled_count\":\(response["cancelled_count"]!)"+ jsonString += "}"++ var buffer = ByteBufferAllocator().buffer(capacity: jsonString.count)+ buffer.writeString(jsonString)++ return Response(+ status: .ok,+ headers: [.contentType: "application/json"],+ body: .init(byteBuffer: buffer)+ )+ }+return router}-+private func handleNonStreamingRequest(chatRequest: ChatCompletionRequest,temperature: Float,@@ -193,14 +245,14 @@ struct MLXHTTPServer {stop: stop,tools: tools)-+let finishReason = toolCalls.isEmpty ? "stop" : "tool_calls"let message = ChatMessage(role: "assistant",content: .string(text.isEmpty && !toolCalls.isEmpty ? "" : text),tool_calls: toolCalls.isEmpty ? nil : toolCalls)-+let response = ChatCompletionResponse(id: generateResponseId(),object: "chat.completion",@@ -215,16 +267,16 @@ struct MLXHTTPServer {],usage: usage)-+log("[mlx] Response: \(text.count) chars, \(toolCalls.count) tool call(s), finish=\(finishReason)")-+return try Response(status: .ok,headers: [.contentType: "application/json"],body: .init(byteBuffer: encodeJSONBuffer(response)))}-+private func handleStreamingRequest(chatRequest: ChatCompletionRequest,temperature: Float,@@ -237,7 +289,7 @@ struct MLXHTTPServer {let responseId = generateResponseId()let created = currentTimestamp()let model = chatRequest.model-+let stream = await modelRunner.generateStream(messages: chatRequest.messages,temperature: temperature,@@ -247,125 +299,148 @@ struct MLXHTTPServer {stop: stop,tools: tools)-- // Build SSE response body- let responseStream = AsyncStream<ByteBuffer> { continuation in- Task {- // Send initial role chunk- let initialChunk = ChatCompletionChunk(- id: responseId,- object: "chat.completion.chunk",- created: created,- model: model,- choices: [- ChatChunkChoice(- index: 0,- delta: ChatDelta(role: "assistant", content: nil),- finish_reason: nil++ // Use makeStream so we can create the task externally and register it for cancellation+ let (responseStream, continuation) = AsyncStream<ByteBuffer>.makeStream()+ let activeGenerations = self.activeGenerations++ let task = Task {+ defer {+ continuation.finish()+ Task { await activeGenerations.remove(responseId) }+ }++ // Send initial role chunk+ let initialChunk = ChatCompletionChunk(+ id: responseId,+ object: "chat.completion.chunk",+ created: created,+ model: model,+ choices: [+ ChatChunkChoice(+ index: 0,+ delta: ChatDelta(role: "assistant", content: nil),+ finish_reason: nil+ )+ ]+ )+ if let data = try? encodeJSONData(initialChunk) {+ continuation.yield(buildSSEFrame(data))+ } else {+ log("[mlx] Warning: Failed to encode initial chunk")+ }++ do {+ for try await event in stream {+ // Stop sending if client disconnected or cancelled+ if Task.isCancelled {+ log("[mlx] SSE stream cancelled by client")+ break+ }++ switch event {+ case .chunk(let token):+ let chunk = ChatCompletionChunk(+ id: responseId,+ object: "chat.completion.chunk",+ created: created,+ model: model,+ choices: [+ ChatChunkChoice(+ index: 0,+ delta: ChatDelta(role: nil, content: token),+ finish_reason: nil+ )+ ])- ]- )- if let data = try? encodeJSONData(initialChunk) {- continuation.yield(buildSSEFrame(data))- } else {- log("[mlx] Warning: Failed to encode initial chunk")- }-- do {- for try await event in stream {- switch event {- case .chunk(let token):- let chunk = ChatCompletionChunk(- id: responseId,- object: "chat.completion.chunk",- created: created,- model: model,- choices: [- ChatChunkChoice(- index: 0,- delta: ChatDelta(role: nil, content: token),- finish_reason: nil- )- ]- )- if let data = try? encodeJSONData(chunk) {- continuation.yield(buildSSEFrame(data))- }-- case .toolCall(let toolCallInfo):- let chunk = ChatCompletionChunk(- id: responseId,- object: "chat.completion.chunk",- created: created,- model: model,- choices: [- ChatChunkChoice(- index: 0,- delta: ChatDelta(- role: nil,- content: nil,- tool_calls: [- ToolCallDelta(- index: 0,- id: toolCallInfo.id,- type: toolCallInfo.type,- function: FunctionCallDelta(- name: toolCallInfo.function.name,- arguments: toolCallInfo.function.arguments- )+ if let data = try? encodeJSONData(chunk) {+ continuation.yield(buildSSEFrame(data))+ }++ case .toolCall(let toolCallInfo):+ let chunk = ChatCompletionChunk(+ id: responseId,+ object: "chat.completion.chunk",+ created: created,+ model: model,+ choices: [+ ChatChunkChoice(+ index: 0,+ delta: ChatDelta(+ role: nil,+ content: nil,+ tool_calls: [+ ToolCallDelta(+ index: 0,+ id: toolCallInfo.id,+ type: toolCallInfo.type,+ function: FunctionCallDelta(+ name: toolCallInfo.function.name,+ arguments: toolCallInfo.function.arguments)- ]- ),- finish_reason: nil- )- ]- )- if let data = try? encodeJSONData(chunk) {- continuation.yield(buildSSEFrame(data))- }-- case .done(let usage, let timings, let hasToolCalls):-- let finishReason = hasToolCalls ? "tool_calls" : "stop"- // Final chunk with finish_reason- let finalChunk = ChatCompletionChunk(- id: responseId,- object: "chat.completion.chunk",- created: created,- model: model,- choices: [- ChatChunkChoice(- index: 0,- delta: ChatDelta(role: nil, content: nil),- finish_reason: finishReason- )- ],- usage: usage,- timings: timings- )- if let data = try? encodeJSONData(finalChunk) {- continuation.yield(buildSSEFrame(data))- }-- // Send [DONE]- var doneBuffer = ByteBufferAllocator().buffer(capacity: 16)- doneBuffer.writeString("data: [DONE]\n\n")- continuation.yield(doneBuffer)+ )+ ]+ ),+ finish_reason: nil+ )+ ]+ )+ if let data = try? encodeJSONData(chunk) {+ continuation.yield(buildSSEFrame(data))+ }++ case .done(let usage, let timings, let hasToolCalls):++ let finishReason = hasToolCalls ? "tool_calls" : "stop"+ // Final chunk with finish_reason+ let finalChunk = ChatCompletionChunk(+ id: responseId,+ object: "chat.completion.chunk",+ created: created,+ model: model,+ choices: [+ ChatChunkChoice(+ index: 0,+ delta: ChatDelta(role: nil, content: nil),+ finish_reason: finishReason+ )+ ],+ usage: usage,+ timings: timings+ )+ if let data = try? encodeJSONData(finalChunk) {+ continuation.yield(buildSSEFrame(data))}++ // Send [DONE]+ var doneBuffer = ByteBufferAllocator().buffer(capacity: 16)+ doneBuffer.writeString("data: [DONE]\n\n")+ continuation.yield(doneBuffer)}- } catch {+ }+ } catch {+ if !Task.isCancelled {log("[mlx] Error in SSE stream: \(error.localizedDescription)")// Send error as SSE eventvar buffer = ByteBufferAllocator().buffer(capacity: 256)buffer.writeString("error: {\"message\":\"\(error.localizedDescription)\"}\n\n")continuation.yield(buffer)+ } else {+ log("[mlx] SSE stream cancelled by client")}-- continuation.finish()}}-++ // Cancel the generation task when the stream consumer stops (client disconnect)+ continuation.onTermination = { @Sendable _ in+ log("[mlx] SSE continuation terminated, cancelling task")+ task.cancel()+ }++ // Register for external cancellation via /cancel endpoint+ await activeGenerations.register(responseId, task: task)+return Response(status: .ok,headers: [diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.tsindex 082afc28d..a67616f0b 100644--- a/web-app/src/lib/model-factory.ts+++ b/web-app/src/lib/model-factory.ts@@ -281,16 +281,45 @@ export class ModelFactory {throw new Error(`No running MLX session found for model: ${modelId}`)}- const customFetch = createCustomFetch(httpFetch, parameters)+ const baseUrl = `http://localhost:${sessionInfo.port}`+ const authHeaders = {+ Authorization: `Bearer ${sessionInfo.api_key}`,+ Origin: 'tauri://localhost',+ }++ // Custom fetch that merges parameters and calls /cancel on abort+ const customFetch: typeof httpFetch = async (+ input: RequestInfo | URL,+ init?: RequestInit+ ): Promise<Response> => {+ if (init?.method === 'POST' || !init?.method) {+ const body = init?.body ? JSON.parse(init.body as string) : {}+ const mergedBody = { ...body, ...parameters }+ init = { ...init, body: JSON.stringify(mergedBody) }+ }++ // When the request is aborted, also call the server's /cancel endpoint+ // to stop MLX inference immediately+ if (init?.signal) {+ init.signal.addEventListener('abort', () => {+ httpFetch(`${baseUrl}/v1/cancel`, {+ method: 'POST',+ headers: { ...authHeaders, 'Content-Type': 'application/json' },+ body: JSON.stringify({}),+ }).catch(() => {+ // Ignore cancel request errors+ })+ })+ }++ return httpFetch(input, init)+ }const model = new OpenAICompatibleChatLanguageModel(modelId, {provider: 'mlx',- headers: () => ({- Authorization: `Bearer ${sessionInfo.api_key}`,- Origin: 'tauri://localhost',- }),+ headers: () => authHeaders,url: ({ path }) => {- const url = new URL(`http://localhost:${sessionInfo.port}/v1${path}`)+ const url = new URL(`${baseUrl}/v1${path}`)return url.toString()},fetch: customFetch,diff --git a/web-app/tsconfig.json b/web-app/tsconfig.jsonindex ab1a13f13..e4eef7bdc 100644--- a/web-app/tsconfig.json+++ b/web-app/tsconfig.json@@ -5,7 +5,6 @@{ "path": "./tsconfig.node.json" }],"compilerOptions": {- "baseUrl": ".","paths": {"@/*": ["./src/*"],"@janhq/conversational-extension": ["../extensions/conversational-extension/src/index.ts"]