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.

feat(web-app): add the chat close barrier

Akarshan Biswasbd89304151a8
diff --git a/web-app/src/lib/__tests__/chatClose.test.ts b/web-app/src/lib/__tests__/chatClose.test.ts
new file mode 100644
index 000000000..7ffad3a30
--- /dev/null
+++ b/web-app/src/lib/__tests__/chatClose.test.ts
@@ -0,0 +1,137 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+import { Chat } from '@ai-sdk/react'
+import type { UIMessageChunk } from 'ai'
+import {
+ trackChat,
+ observeChatWork,
+ quiesceChats,
+ forgetChat,
+ isChatClosing,
+ __resetChatCloseForTests,
+ resumeChatsAfterPreventedClose,
+ withChatCloseDeadline,
+} from '../chatClose'
+
+// The close barrier itself, against the installed AI SDK `Chat`. Durable
+// message writes (the second half of the PR's barrier) are not part of this
+// port, so "settled" here means the stream was stopped and every pending
+// finalizer ran.
+
+const deferred = () => {
+ let resolve!: () => void
+ const promise = new Promise<void>((r) => {
+ resolve = r
+ })
+ return { promise, resolve }
+}
+
+beforeEach(() => __resetChatCloseForTests())
+
+function streamChat(finalize: () => Promise<void> = async () => {}) {
+ let controller!: ReadableStreamDefaultController<UIMessageChunk>
+ const started = deferred()
+ const pending = new Set<Promise<unknown>>()
+ const finished: string[] = []
+ const chat = new Chat({
+ transport: {
+ async sendMessages({ abortSignal }) {
+ const stream = new ReadableStream<UIMessageChunk>({
+ start(c) {
+ controller = c
+ },
+ })
+ abortSignal?.addEventListener('abort', () => {
+ controller.error(new DOMException('Stopped', 'AbortError'))
+ })
+ started.resolve()
+ return stream
+ },
+ async reconnectToStream() {
+ return null
+ },
+ },
+ onFinish: (event) =>
+ observeChatWork(pending, async () => {
+ await finalize()
+ finished.push(event.message.id)
+ }),
+ })
+ trackChat(chat, pending)
+ return {
+ chat,
+ started,
+ finished,
+ push: (chunk: UIMessageChunk) => controller.enqueue(chunk),
+ }
+}
+
+async function partial(id: string, finalize?: () => Promise<void>) {
+ const stream = streamChat(finalize)
+ const sending = stream.chat.sendMessage({ text: 'Question' })
+ await stream.started.promise
+ stream.push({ type: 'start', messageId: `${id}-answer` })
+ stream.push({ type: 'text-start', id: 'text' })
+ stream.push({ type: 'text-delta', id: 'text', delta: 'Partial survived' })
+ await new Promise((r) => setTimeout(r, 0))
+ return { ...stream, sending }
+}
+
+describe('ordinary Chat close barrier using installed SDK', () => {
+ it('a rejected public operation does not poison later closes', async () => {
+ const stream = streamChat()
+ await expect(stream.chat.regenerate({ messageId: 'missing' })).rejects.toThrow()
+ await quiesceChats()
+ })
+
+ it('waits for an async onFinish finalizer before the close resolves', async () => {
+ const finish = deferred()
+ const stream = await partial('a', () => finish.promise)
+ let closed = false
+ const closing = quiesceChats().then(() => {
+ closed = true
+ })
+ await new Promise((r) => setTimeout(r, 10))
+ expect(closed).toBe(false)
+ finish.resolve()
+ await stream.sending
+ await closing
+ expect(closed).toBe(true)
+ expect(stream.finished).toEqual(['a-answer'])
+ })
+
+ it('stops all background chats, not only the active route', async () => {
+ const a = await partial('a')
+ const b = await partial('b')
+ await quiesceChats()
+ expect(a.finished).toEqual(['a-answer'])
+ expect(b.finished).toEqual(['b-answer'])
+ })
+
+ it('refuses new operations while closing and accepts them again after a prevented close', async () => {
+ const stream = streamChat()
+ await quiesceChats()
+ expect(isChatClosing()).toBe(true)
+ await stream.chat.sendMessage({ text: 'ignored' }) // guarded: no-op
+ expect(stream.chat.messages).toHaveLength(0)
+ resumeChatsAfterPreventedClose()
+ expect(isChatClosing()).toBe(false)
+ })
+
+ it('a forgotten chat no longer participates', async () => {
+ const stream = await partial('gone')
+ forgetChat(stream.chat)
+ await quiesceChats() // must not wait on, or stop, the forgotten chat
+ expect(stream.finished).toEqual([])
+ stream.chat.stop()
+ })
+
+ it('a whole-attempt deadline fails the close and a retry still awaits the finalizer', async () => {
+ const tools = deferred()
+ const stream = await partial('tools', () => tools.promise)
+ await expect(withChatCloseDeadline(quiesceChats(), 10)).rejects.toThrow('timed out')
+ resumeChatsAfterPreventedClose()
+ tools.resolve()
+ await quiesceChats()
+ expect(stream.finished).toEqual(['tools-answer'])
+ })
+})
diff --git a/web-app/src/lib/chatClose.ts b/web-app/src/lib/chatClose.ts
new file mode 100644
index 000000000..bc78d373f
--- /dev/null
+++ b/web-app/src/lib/chatClose.ts
@@ -0,0 +1,78 @@
+import type { Chat, UIMessage } from '@ai-sdk/react'
+
+type Participant = { stop: () => void | Promise<void>; settle: () => Promise<void> }
+const finalizers = new WeakMap<Chat<UIMessage>, Set<Promise<unknown>>>()
+const participants = new Map<Chat<UIMessage>, Participant>()
+let closing = false
+export const isChatClosing = () => closing
+export function resumeChatsAfterPreventedClose() { closing = false }
+
+/** Retained Chat objects, not mounted routes, own these registrations. */
+export function trackChat(chat: Chat<UIMessage>, pending: Set<Promise<unknown>>) {
+ finalizers.set(chat, pending)
+ const stopped = chat.stop.bind(chat)
+ const settle = async () => {
+ // SDK sets ready immediately BEFORE calling onFinish. Cross a microtask
+ // before inspecting pending callbacks; status alone is not a barrier.
+ for (;;) {
+ await Promise.resolve()
+ if (pending.size) {
+ await Promise.all([...pending])
+ continue
+ }
+ if (chat.status !== 'submitted' && chat.status !== 'streaming') return
+ await new Promise<void>((resolve) => {
+ const unsubscribe = chat['~registerStatusCallback'](() => {
+ unsubscribe()
+ resolve()
+ })
+ })
+ }
+ }
+ participants.set(chat, { stop: stopped, settle })
+ const guard = <A extends unknown[]>(original: (...args: A) => Promise<void>) => (...args: A) => {
+ if (closing) return Promise.resolve()
+ const operation = original(...args)
+ pending.add(operation)
+ void operation.then(() => pending.delete(operation), () => pending.delete(operation))
+ return operation
+ }
+ chat.sendMessage = guard(chat.sendMessage.bind(chat))
+ chat.regenerate = guard(chat.regenerate.bind(chat))
+ chat.resumeStream = guard(chat.resumeStream.bind(chat))
+}
+export function observeChatWork<T>(pending: Set<Promise<unknown>>, work: () => T): T {
+ const result = work()
+ if (result && typeof (result as unknown as Promise<unknown>).then === 'function') {
+ const promise = Promise.resolve(result)
+ pending.add(promise)
+ void promise.then(() => pending.delete(promise), () => { /* Keep failed finalization fail-closed. */ })
+ }
+ return result
+}
+export function trackChatFinalization(chat: Chat<UIMessage> | undefined, completion: Promise<unknown>) {
+ const pending = chat && finalizers.get(chat)
+ if (pending) observeChatWork(pending, () => completion)
+}
+export function setChatCloseStop(chat: Chat<UIMessage>, stop: () => void | Promise<void>) {
+ const participant = participants.get(chat)
+ if (participant) participant.stop = stop
+}
+export async function quiesceChats() {
+ closing = true
+ const snapshot = [...participants.values()]
+ const stops = snapshot.map(async (p) => p.stop())
+ const results = await Promise.allSettled([...stops, ...snapshot.map((p) => p.settle())])
+ const failure = results.find((r) => r.status === 'rejected')
+ if (failure?.status === 'rejected') throw failure.reason
+}
+export function forgetChat(chat: Chat<UIMessage>) { participants.delete(chat) }
+export async function withChatCloseDeadline<T>(work: Promise<T>, timeoutMs = 10_000): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([work, new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Chat close timed out; close again to retry')), timeoutMs)
+ })])
+ } finally { if (timer) clearTimeout(timer) }
+}
+export function __resetChatCloseForTests() { participants.clear(); closing = false }