Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(tui): keep input responsive during agent output (#5791)
chengyongru2fb16593988b
diff --git a/tui/src/app-event-queue.test.ts b/tui/src/app-event-queue.test.tsnew file mode 100644index 000000000..62f07063d--- /dev/null+++ b/tui/src/app-event-queue.test.ts@@ -0,0 +1,167 @@+import { describe, expect, test } from "bun:test"+import type { ServerWebSocket } from "bun"+import type { TextareaRenderable } from "@opentui/core"+import { createTestRenderer, MockTreeSitterClient } from "@opentui/core/testing"++import { NanobotTui } from "./app"+import type { InboundEvent, NanobotClient } from "./protocol"++async function waitUntil(predicate: () => boolean): Promise<void> {+ const deadline = Date.now() + 2_000+ while (!predicate() && Date.now() < deadline) await Bun.sleep(5)+ expect(predicate()).toBe(true)+}++async function fixture() {+ let socket: ServerWebSocket<undefined> | undefined+ const sent: string[] = []+ const server = Bun.serve<undefined>({+ hostname: "127.0.0.1",+ port: 0,+ fetch: (request, server) => server.upgrade(request) ? undefined : new Response(null),+ websocket: {+ open(ws) {+ socket = ws+ ws.send(JSON.stringify({ event: "attached", chat_id: "chat" }))+ ws.send(JSON.stringify({ event: "goal_status", chat_id: "chat", status: "running" }))+ },+ message(_ws, message) {+ const frame = JSON.parse(String(message))+ if (frame.type === "message") sent.push(frame.content)+ },+ },+ })+ const setup = await createTestRenderer({ width: 72, height: 20 })+ const app = NanobotTui.mount(setup.renderer, {+ wsUrl: `ws://127.0.0.1:${server.port}`,+ apiUrl: "",+ apiToken: "",+ model: "test/model",+ modelPreset: "default",+ workspace: "/tmp/nanobot-workspace",+ version: "test",+ access: "workspace access",+ theme: "dark",+ }, undefined, new MockTreeSitterClient({ autoResolveTimeout: 0 }))+ const ui = app as unknown as {+ composer: TextareaRenderable+ client: NanobotClient+ ready: boolean+ activeTurn: boolean+ }+ ui.client.connect()+ await waitUntil(() => ui.ready && ui.activeTurn)+ return {+ app, ui, setup, sent,+ send(events: InboundEvent[]) {+ for (const event of events) socket!.send(JSON.stringify(event))+ },+ async close() {+ app.stop()+ await server.stop(true)+ },+ }+}++const deltas = (count: number): InboundEvent[] => Array.from({ length: count }, (_, index) => ({+ event: "delta", chat_id: "chat", text: `${index} `,+}))++describe("gateway output scheduling", () => {+ test("submits and repaints before costly queued output finishes", async () => {+ const f = await fixture()+ try {+ const animation = f.app as unknown as { shimmerTimer: ReturnType<typeof setInterval> | null }+ if (animation.shimmerTimer) clearInterval(animation.shimmerTimer)+ animation.shimmerTimer = null+ f.ui.composer.setText("你")+ await waitUntil(() => f.setup.captureCharFrame().includes("你"))++ const events = deltas(64)+ const applied: InboundEvent[] = []+ let appliedAtSend = -1+ let appliedAtPaint = -1+ const send = f.ui.client.send.bind(f.ui.client)+ f.ui.client.send = (...args) => {+ appliedAtSend = applied.length+ return send(...args)+ }+ const accept = f.app.accept.bind(f.app)+ f.app.accept = (event) => {+ accept(event)+ applied.push(event)+ if (applied.length === 1) {+ f.setup.mockInput.pressEnter()+ setTimeout(() => f.ui.composer.setText("你好"), 0)+ }+ Bun.sleepSync(5)+ }+ f.setup.renderer.on("frame", () => {+ if (appliedAtPaint >= 0 || f.ui.composer.plainText !== "") return+ const lines = f.setup.captureCharFrame().split("\n")+ const draft = lines.slice(f.ui.composer.screenY, f.ui.composer.screenY + f.ui.composer.height)+ if (lines.some((line) => /›\s*你好/u.test(line)) && draft.every((line) => !line.includes("你好"))) {+ appliedAtPaint = applied.length+ }+ })++ f.send(events)+ await waitUntil(() => f.sent.length === 1 && appliedAtPaint >= 0)+ expect(f.sent).toEqual(["你好"])+ expect(appliedAtSend).toBe(1)+ expect(appliedAtPaint).toBeLessThan(events.length)+ await waitUntil(() => applied.length === events.length)+ expect(applied).toEqual(events)+ } finally {+ await f.close()+ }+ })++ test("yields after a costly event before reaching the batch limit", async () => {+ const f = await fixture()+ try {+ let applied = 0+ let appliedAtYield = 0+ const accept = f.app.accept.bind(f.app)+ f.app.accept = (event) => {+ accept(event)+ if (++applied === 1) {+ Bun.sleepSync(5)+ setImmediate(() => { appliedAtYield = applied })+ }+ }+ f.send(deltas(64))+ await waitUntil(() => applied === 64 && appliedAtYield > 0)+ expect(appliedAtYield).toBe(1)+ } finally {+ await f.close()+ }+ })++ test("discards queued output when another session attaches", async () => {+ const f = await fixture()+ try {+ const applied: InboundEvent[] = []+ const accept = f.app.accept.bind(f.app)+ f.app.accept = (event) => {+ applied.push(event)+ accept(event)+ }+ f.setup.mockInput.pressEnter()+ f.send([+ { event: "delta", chat_id: "chat", text: "old session" },+ { event: "attached", chat_id: "next" },+ { event: "delta", chat_id: "next", text: "new session" },+ { event: "stream_end", chat_id: "next" },+ ])+ await waitUntil(() => applied.some((event) => event.event === "stream_end"))+ expect(applied).toEqual([+ { event: "attached", chat_id: "next" },+ { event: "delta", chat_id: "next", text: "new session" },+ { event: "stream_end", chat_id: "next" },+ ])+ } finally {+ await f.close()+ }+ })+})diff --git a/tui/src/app.ts b/tui/src/app.tsindex fa489e634..4a00a112f 100644--- a/tui/src/app.ts+++ b/tui/src/app.ts@@ -196,6 +196,8 @@ const IMAGE_PLACEHOLDER_STYLE = "image.placeholder"const SHIMMER_PAUSE = 16const SHIMMER_BAND = 4const SHIMMER_INTERVAL_MS = 80+const EVENT_BATCH_SIZE = 64+const EVENT_BATCH_BUDGET_MS = 4const SESSION_REFRESH_INTERVAL_MS = 1_000const LOCAL_COMMANDS: TuiCommand[] = [{@@ -525,6 +527,9 @@ export class NanobotTui {private historyLoadingOlder = falseprivate attachedOnce = falseprivate pendingEvents: InboundEvent[] | null = null+ private eventQueue: Array<InboundEvent | (() => void)> = []+ private eventDrain: ReturnType<typeof setImmediate> | null = null+ private followUpPending = falseprivate hydrationId = 0private ready = falseprivate shimmerFrame = 0@@ -665,7 +670,7 @@ export class NanobotTui {project_path: options.workspace,access_mode: options.access.toLocaleLowerCase().includes("full") ? "full" : "restricted",},- onEvent: (event) => this.accept(event),+ onEvent: (event) => this.enqueueEvent(event),onStatus: (status, detail, info) => this.handleStatus(status, detail, info),})@@ -932,8 +937,11 @@ export class NanobotTui {if (!this.submitPending || generation !== this.submitGeneration) returnthis.submitPending = falsethis.submitGeneration += 1- if (this.composer.isDestroyed) return- this.submit()+ try {+ if (!this.composer.isDestroyed) this.submit()+ } finally {+ this.scheduleEventDrain()+ }}private submit(): void {@@ -1088,6 +1096,50 @@ export class NanobotTui {}}+ private enqueueEvent(event: InboundEvent): void {+ if (this.quitting) return+ if (event.event === "attached") {+ this.clearEventQueue()+ this.accept(event)+ return+ }+ this.eventQueue.push(event)+ this.scheduleEventDrain()+ }++ private scheduleEventDrain(): void {+ if (+ this.eventDrain || this.quitting || this.submitPending+ || this.pendingEvents || !this.eventQueue.length+ ) return+ this.eventDrain = setImmediate(() => {+ this.eventDrain = null+ const started = performance.now()+ let processed = 0+ // Yield between output batches so terminal input can run. Keep queued+ // output paused until an IME-delayed submit has read the composer.+ while (!this.submitPending && !this.quitting && processed < this.eventQueue.length) {+ const event = this.eventQueue[processed++]!+ if (typeof event === "function") event()+ else this.accept(event)+ if (processed >= EVENT_BATCH_SIZE || performance.now() - started >= EVENT_BATCH_BUDGET_MS) break+ }+ this.eventQueue.splice(0, processed)+ this.scheduleEventDrain()+ if (!this.eventQueue.length && this.followUpPending) {+ this.followUpPending = false+ this.sendNextFollowUp()+ }+ })+ }++ private clearEventQueue(): void {+ if (this.eventDrain) clearImmediate(this.eventDrain)+ this.eventDrain = null+ this.eventQueue = []+ this.followUpPending = false+ }+accept(event: InboundEvent): void {if (event.event === "attached") {const switchedSession = Boolean(this.currentChatId && this.currentChatId !== event.chat_id)@@ -1380,7 +1432,8 @@ export class NanobotTui {private flushPendingEvents(): void {const events = this.pendingEventsthis.pendingEvents = null- for (const event of events || []) this.accept(event)+ if (events?.length) this.eventQueue = [...events, ...this.eventQueue]+ this.scheduleEventDrain()}private clearRecoveryState(): void {@@ -1497,6 +1550,18 @@ export class NanobotTui {// Invalid frames do not mean the transport is unavailable. Keep the last// accurate user-facing state unless the protocol supplied connection diagnostics.if (status === "error" && !info) return+ this.ready = false+ // Render already-received output before the disconnect notice, but block+ // submissions immediately when the transport becomes unavailable.+ if (this.eventQueue.length) {+ this.eventQueue.push(() => this.applyStatus(status, info))+ this.scheduleEventDrain()+ return+ }+ this.applyStatus(status, info)+ }++ private applyStatus(status: ConnectionStatus, info?: ConnectionStatusInfo): void {this.connectionMessage = connectionStatusText(status, info)if (this.options.desktopGatewayId && status === "error") {this.connectionMessage = "Desktop disconnected or incompatible · exit and run nanobot to reconnect"@@ -1596,6 +1661,11 @@ export class NanobotTui {private sendNextFollowUp(): void {if (!this.ready || this.activeTurn || this.quitting) return+ // Hydration may have queued an active-turn snapshot for this session.+ if (this.eventQueue.length) {+ this.followUpPending = true+ return+ }const prompt = this.promptQueue.takeFollowUp()if (!prompt) returnthis.syncQueuePreview()@@ -2977,6 +3047,7 @@ export class NanobotTui {private handleDestroy = (): void => {this.quitting = true+ this.clearEventQueue()this.usageRequest?.abort()this.clipboardPasteGeneration += 1if (this.shimmerTimer) clearInterval(this.shimmerTimer)