Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(chat): ignore custom SSE event types in OpenAI-compatible streams (#8392)

Akarshan Biswasd47a2d3475bd
diff --git a/web-app/src/lib/__tests__/sseEventTypeFilter.test.ts b/web-app/src/lib/__tests__/sseEventTypeFilter.test.ts
new file mode 100644
index 000000000..e816857e8
--- /dev/null
+++ b/web-app/src/lib/__tests__/sseEventTypeFilter.test.ts
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest'
+import {
+ SseEventTypeFilter,
+ filterDefaultSseEvents,
+} from '../sseEventTypeFilter'
+
+const collect = (f: SseEventTypeFilter, chunks: string[]): string => {
+ let out = ''
+ for (const c of chunks) out += f.process(c)
+ out += f.flush()
+ return out
+}
+
+describe('SseEventTypeFilter', () => {
+ it('passes plain data-only frames through unchanged', () => {
+ const f = new SseEventTypeFilter()
+ const input = 'data: {"choices":[]}\n\ndata: {"choices":[1]}\n\n'
+ expect(collect(f, [input])).toBe(input)
+ })
+
+ it('drops a named-event frame but keeps the following data frame', () => {
+ const f = new SseEventTypeFilter()
+ const named =
+ 'event: hermes.tool.progress\ndata: {"tool":"terminal","status":"running"}\n\n'
+ const chunk = 'data: {"choices":[{"delta":{"content":"Hello"}}]}\n\n'
+ expect(collect(f, [named + chunk])).toBe(chunk)
+ })
+
+ it('keeps an explicit event: message frame', () => {
+ const f = new SseEventTypeFilter()
+ const input = 'event: message\ndata: {"choices":[]}\n\n'
+ expect(collect(f, [input])).toBe(input)
+ })
+
+ it('keeps the [DONE] sentinel frame', () => {
+ const f = new SseEventTypeFilter()
+ const input = 'data: [DONE]\n\n'
+ expect(collect(f, [input])).toBe(input)
+ })
+
+ it('keeps keepalive comment frames', () => {
+ const f = new SseEventTypeFilter()
+ const input = ': ping\n\ndata: {"choices":[]}\n\n'
+ expect(collect(f, [input])).toBe(input)
+ })
+
+ it('handles a named-event frame split across chunks', () => {
+ const f = new SseEventTypeFilter()
+ const chunks = [
+ 'event: hermes.tool',
+ '.progress\ndata: {"a":1}',
+ '\n\ndata: {"choices":[]}\n\n',
+ ]
+ expect(collect(f, chunks)).toBe('data: {"choices":[]}\n\n')
+ })
+
+ it('handles CRLF frame separators', () => {
+ const f = new SseEventTypeFilter()
+ const named = 'event: custom\r\ndata: {"x":1}\r\n\r\n'
+ const kept = 'data: {"choices":[]}\r\n\r\n'
+ expect(collect(f, [named + kept])).toBe(kept)
+ })
+
+ it('emits a trailing frame with no terminating separator on flush', () => {
+ const f = new SseEventTypeFilter()
+ expect(collect(f, ['data: {"choices":[]}'])).toBe('data: {"choices":[]}')
+ })
+
+ it('drops a trailing named-event frame with no terminating separator', () => {
+ const f = new SseEventTypeFilter()
+ expect(collect(f, ['event: custom\ndata: {"x":1}'])).toBe('')
+ })
+})
+
+describe('filterDefaultSseEvents', () => {
+ const read = async (stream: ReadableStream<Uint8Array>): Promise<string> => {
+ const reader = stream.getReader()
+ const decoder = new TextDecoder()
+ let out = ''
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ out += decoder.decode(value, { stream: true })
+ }
+ out += decoder.decode()
+ return out
+ }
+
+ const streamOf = (parts: string[]): ReadableStream<Uint8Array> => {
+ const enc = new TextEncoder()
+ return new ReadableStream({
+ start(controller) {
+ for (const p of parts) controller.enqueue(enc.encode(p))
+ controller.close()
+ },
+ })
+ }
+
+ it('filters named events out of a byte stream', async () => {
+ const source = streamOf([
+ 'event: hermes.tool.progress\ndata: {"tool":"terminal"}\n\n',
+ 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n',
+ 'data: [DONE]\n\n',
+ ])
+ const out = await read(filterDefaultSseEvents(source))
+ expect(out).toBe(
+ 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\ndata: [DONE]\n\n'
+ )
+ })
+})
diff --git a/web-app/src/lib/model-factory.ts b/web-app/src/lib/model-factory.ts
index c9e49677e..62c961f58 100644
--- a/web-app/src/lib/model-factory.ts
+++ b/web-app/src/lib/model-factory.ts
@@ -61,6 +61,7 @@ import { SessionInfo } from '@janhq/core'
import { fetch as httpFetch } from '@tauri-apps/plugin-http'
import { hasAudioSentinel, splitAudioSentinels } from './audio-sentinel'
import { hasVideoSentinel, splitVideoSentinels } from './video-sentinel'
+import { filterDefaultSseEvents } from './sseEventTypeFilter'
import { isPlatformTauri } from '@/lib/platform/utils'
import { providerRemoteApiKeyChain } from '@/lib/provider-api-keys'
import {
@@ -411,7 +412,21 @@ export function createCustomFetch(
if (!friendly) throw err
throw new Error(`${friendly} (${requestUrlOf(input)})`)
}
- if (res.ok) return res
+ if (res.ok) {
+ // Servers may interleave custom named SSE events (e.g. tool-progress)
+ // with chat.completion.chunk data. The AI SDK validates every data line
+ // against the chunk schema regardless of event type, so strip non-default
+ // events before the stream reaches it.
+ const contentType = res.headers.get('content-type') || ''
+ if (res.body && contentType.includes('text/event-stream')) {
+ return new Response(filterDefaultSseEvents(res.body), {
+ status: res.status,
+ statusText: res.statusText,
+ headers: res.headers,
+ })
+ }
+ return res
+ }
const isLlamacpp500 = keepLlamacppOnly && res.status === 500
diff --git a/web-app/src/lib/sseEventTypeFilter.ts b/web-app/src/lib/sseEventTypeFilter.ts
new file mode 100644
index 000000000..23015b394
--- /dev/null
+++ b/web-app/src/lib/sseEventTypeFilter.ts
@@ -0,0 +1,84 @@
+/**
+ * W3C-compliant SSE event-type filtering for OpenAI-compatible streams.
+ *
+ * The Vercel AI SDK's `parseJsonEventStream` destructures only the `data:`
+ * field of each SSE event and discards the `event:` type, then validates every
+ * payload against the `chat.completion.chunk` schema. Servers that interleave
+ * custom named events (e.g. `event: hermes.tool.progress`) therefore trip a
+ * fatal "Type validation failed" and the whole stream aborts.
+ *
+ * Per the SSE spec an event's type defaults to "message"; a client with no
+ * handler for other types must ignore them. This filter drops every frame
+ * whose event type is not the default before the SDK ever parses it.
+ */
+
+const FRAME_SEPARATOR = /\r\n\r\n|\n\n|\r\r/
+
+/** Returns the frame's SSE event type, defaulting to "message". */
+function eventTypeOf(frame: string): string {
+ let type = 'message'
+ for (const line of frame.split(/\r\n|\n|\r/)) {
+ if (!line.startsWith('event:')) continue
+ let value = line.slice('event:'.length)
+ if (value.startsWith(' ')) value = value.slice(1)
+ // An empty event field dispatches as "message" per spec.
+ type = value === '' ? 'message' : value
+ }
+ return type
+}
+
+const isDefaultEvent = (frame: string): boolean =>
+ eventTypeOf(frame) === 'message'
+
+/**
+ * Stateful, chunk-boundary-safe filter over the raw SSE text. Feed decoded
+ * string chunks to `process()`; call `flush()` once at stream end to emit any
+ * trailing frame that never received a terminating blank line.
+ */
+export class SseEventTypeFilter {
+ private buffer = ''
+
+ process(chunk: string): string {
+ this.buffer += chunk
+ let out = ''
+ for (;;) {
+ const match = FRAME_SEPARATOR.exec(this.buffer)
+ if (!match) break
+ const end = match.index + match[0].length
+ const frame = this.buffer.slice(0, end)
+ this.buffer = this.buffer.slice(end)
+ if (isDefaultEvent(frame)) out += frame
+ }
+ return out
+ }
+
+ flush(): string {
+ if (!this.buffer) return ''
+ const frame = this.buffer
+ this.buffer = ''
+ return isDefaultEvent(frame) ? frame : ''
+ }
+}
+
+/** Wraps an SSE byte stream, dropping any non-default (named) event frames. */
+export function filterDefaultSseEvents(
+ body: ReadableStream<Uint8Array>
+): ReadableStream<Uint8Array> {
+ const filter = new SseEventTypeFilter()
+ const decoder = new TextDecoder()
+ const encoder = new TextEncoder()
+ const emit = (text: string, controller: TransformStreamDefaultController<Uint8Array>) => {
+ if (text) controller.enqueue(encoder.encode(text))
+ }
+ return body.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ transform(chunk, controller) {
+ emit(filter.process(decoder.decode(chunk, { stream: true })), controller)
+ },
+ flush(controller) {
+ emit(filter.process(decoder.decode()), controller)
+ emit(filter.flush(), controller)
+ },
+ })
+ )
+}