Skip to content

Commit 19d0e71

Browse files
authored
fix(core): stabilize message queue and thinking timeout (#974)
1 parent 9f6d7c5 commit 19d0e71

5 files changed

Lines changed: 76 additions & 72 deletions

File tree

‎packages/core/src/chains/chain.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export class ChatChain {
4646
timeoutObj.autoRecallTimeout &&
4747
clearTimeout(timeoutObj.autoRecallTimeout)
4848

49+
timeoutObj.setQueueCount(0)
4950
timeoutObj.recallFunc && (await timeoutObj.recallFunc())
5051

5152
timeoutObj.timeout = null
@@ -71,11 +72,12 @@ export class ChatChain {
7172
context.recallThinkingMessage =
7273
this._createRecallThinkingMessage(context)
7374

74-
const result = await this._runMiddleware(session, context)
75-
76-
await context.recallThinkingMessage()
77-
78-
return result
75+
try {
76+
return await this._runMiddleware(session, context)
77+
} finally {
78+
await context.options.completeMessageTurn?.()
79+
await context.recallThinkingMessage()
80+
}
7981
}
8082

8183
async receiveCommand(
@@ -124,11 +126,13 @@ export class ChatChain {
124126
context.recallThinkingMessage =
125127
this._createRecallThinkingMessage(context)
126128

127-
const ok = await this._runMiddleware(session, context)
128-
129-
await context.recallThinkingMessage()
130-
131-
return { ok, context }
129+
try {
130+
const ok = await this._runMiddleware(session, context)
131+
return { ok, context }
132+
} finally {
133+
await context.options.completeMessageTurn?.()
134+
await context.recallThinkingMessage()
135+
}
132136
}
133137

134138
middleware<T extends keyof ChainMiddlewareName>(

‎packages/core/src/middlewares/chat/message_delay.ts‎

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -130,38 +130,9 @@ export function apply(ctx: Context, config: Config, chain: ChatChain) {
130130
.after('transform_chat_message')
131131
.before('lifecycle-handle_command')
132132

133-
const completeTurn = async (conversationId: string) => {
134-
const conversation = queues.get(conversationId)
135-
if (!conversation) {
136-
return
137-
}
138-
139-
const current = conversation.turns.shift()
140-
conversation.inFlight = false
141-
142-
if (current?.timeout) {
143-
current.timeout()
144-
}
145-
if (current?.starter) {
146-
current.starter.resolve(ChainMiddlewareRunStatus.STOP)
147-
current.starter = undefined
148-
}
149-
150-
if (conversation.turns.length === 0) {
151-
queues.delete(conversationId)
152-
return
153-
}
154-
155-
tryStartHeadTurn(conversationId, conversation)
156-
157-
if (current) {
158-
logger.debug(
159-
`Completing turn for ${conversationId}, remaining: ${conversation.turns.length}`
160-
)
161-
}
162-
}
163-
164-
ctx.on('chatluna/after-chat', completeTurn)
133+
ctx.on('chatluna/after-chat', (conversationId) =>
134+
completeTurn(conversationId)
135+
)
165136

166137
ctx.on('chatluna/after-chat-error', (_error, conversationId) =>
167138
completeTurn(conversationId)
@@ -209,6 +180,40 @@ export function apply(ctx: Context, config: Config, chain: ChatChain) {
209180
)
210181
}
211182

183+
async function completeTurn(conversationId: string, expected?: MessageTurn) {
184+
const conversation = queues.get(conversationId)
185+
if (
186+
!conversation ||
187+
(expected != null && conversation.turns[0] !== expected)
188+
) {
189+
return
190+
}
191+
192+
const current = conversation.turns.shift()
193+
conversation.inFlight = false
194+
195+
if (current?.timeout) {
196+
current.timeout()
197+
}
198+
if (current?.starter) {
199+
current.starter.resolve(ChainMiddlewareRunStatus.STOP)
200+
current.starter = undefined
201+
}
202+
203+
if (conversation.turns.length === 0) {
204+
queues.delete(conversationId)
205+
return
206+
}
207+
208+
tryStartHeadTurn(conversationId, conversation)
209+
210+
if (current) {
211+
logger.debug(
212+
`Completing turn for ${conversationId}, remaining: ${conversation.turns.length}`
213+
)
214+
}
215+
}
216+
212217
function awaitTurnStart(
213218
turn: MessageTurn,
214219
context: ChainMiddlewareContext
@@ -294,6 +299,8 @@ function startHeadTurn(
294299

295300
conversation.inFlight = true
296301
head.state = 'processing'
302+
starter.context.options.completeMessageTurn = () =>
303+
completeTurn(conversationId, head)
297304
starter.context.options.inputMessage = mergeMessages(
298305
head.messages
299306
.sort((a, b) => a.timestamp - b.timestamp)
@@ -363,5 +370,6 @@ declare module '../../chains/chain' {
363370

364371
interface ChainMiddlewareContextOptions {
365372
messageId?: string
373+
completeMessageTurn?: () => Promise<void>
366374
}
367375
}

‎packages/core/src/middlewares/chat/thinking_message_send.ts‎

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
import { Context, Logger } from 'koishi'
22
import { Config } from '../../config'
3-
import {
4-
ChainMiddlewareContextOptions,
5-
ChainMiddlewareRunStatus,
6-
ChatChain
7-
} from '../../chains/chain'
3+
import { ChainMiddlewareRunStatus, ChatChain } from '../../chains/chain'
84
import { createLogger } from 'koishi-plugin-chatluna/utils/logger'
5+
import { withResolver } from 'koishi-plugin-chatluna/utils/promise'
96

107
let logger: Logger
118

@@ -17,14 +14,15 @@ export function apply(ctx: Context, config: Config, chain: ChatChain) {
1714
return ChainMiddlewareRunStatus.SKIPPED
1815
}
1916

20-
const thinkingTimeoutObject: ThinkingTimeoutObject = {}
17+
const queue = withResolver<number>()
18+
const thinkingTimeoutObject: ThinkingTimeoutObject = {
19+
queueCount: queue.promise,
20+
setQueueCount: queue.resolve
21+
}
2122
context.options.thinkingTimeoutObject = thinkingTimeoutObject
2223

2324
thinkingTimeoutObject.timeout = setTimeout(async () => {
24-
const queueCount = await getQueueCount(
25-
thinkingTimeoutObject,
26-
context.options
27-
)
25+
const queueCount = await thinkingTimeoutObject.queueCount
2826

2927
if (thinkingTimeoutObject.timeout == null || queueCount < 1) {
3028
return
@@ -63,23 +61,9 @@ export function apply(ctx: Context, config: Config, chain: ChatChain) {
6361
.before('lifecycle-prepare')
6462
}
6563

66-
async function getQueueCount(
67-
obj: ThinkingTimeoutObject,
68-
options: ChainMiddlewareContextOptions
69-
) {
70-
await new Promise((resolve, reject) => {
71-
const timer = setInterval(() => {
72-
if (obj.timeout != null && options.queueCount != null) {
73-
clearInterval(timer)
74-
resolve(undefined)
75-
}
76-
})
77-
})
78-
79-
return options.queueCount
80-
}
81-
8264
export interface ThinkingTimeoutObject {
65+
queueCount: Promise<number>
66+
setQueueCount: (count: number) => void
8367
timeout?: NodeJS.Timeout
8468
recallFunc?: () => PromiseLike<void>
8569
autoRecallTimeout?: NodeJS.Timeout

‎packages/core/src/middlewares/conversation/request_conversation.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ function createChatCallbacks(
193193
await stream.write({ type: 'content', chunk })
194194
},
195195
'llm-queue-waiting': async (count: number) => {
196-
context.options.queueCount = count
196+
context.options.thinkingTimeoutObject?.setQueueCount(count)
197197
},
198198
'llm-usage': async (usage: UsageMetadata) => {
199199
if (context.options.invocation != null) {
@@ -293,6 +293,5 @@ declare module '../../chains/chain' {
293293
responseMessage?: Message
294294
finalResponseMessage?: Message
295295
inputMessage?: Message
296-
queueCount?: number
297296
}
298297
}

‎packages/core/src/services/conversation_runtime.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ export class ConversationRuntime {
8080
message,
8181
options
8282
),
83-
options.signal
83+
options.signal,
84+
options.event?.['llm-queue-waiting']
8485
)
8586
}
8687

@@ -268,7 +269,8 @@ export class ConversationRuntime {
268269
async withConversationAndPlatformLock<T>(
269270
conversation: ConversationRecord,
270271
callback: (config: ClientConfig) => Promise<T>,
271-
signal?: AbortSignal
272+
signal?: AbortSignal,
273+
onQueueWaiting?: ChatEvents['llm-queue-waiting']
272274
): Promise<T> {
273275
const requestId = randomUUID()
274276
const modelRequestId = randomUUID()
@@ -293,6 +295,13 @@ export class ConversationRuntime {
293295
this.conversationQueue.add(conversation.id, requestId),
294296
this.modelQueue.add(platform, modelRequestId)
295297
])
298+
if (onQueueWaiting != null) {
299+
const sizes = await Promise.all([
300+
this.conversationQueue.getQueueLength(conversation.id),
301+
this.modelQueue.getQueueLength(platform)
302+
])
303+
await onQueueWaiting(Math.max(...sizes))
304+
}
296305
const waiting = Promise.all([
297306
this.conversationQueue.wait(
298307
conversation.id,

0 commit comments

Comments
 (0)