Skip to content

Commit e978913

Browse files
fix(local-webui): replay a period until its chat is saved; keep its opening; message_composer bounds (#563)
* fix(local-webui): replay a period until its chat is saved; no doubled replies; message_composer bounds The non-blocking findings of the web-1 review (1-3) and the web-2 review (1-2), R5 of the pre-0.14 polish. web-1 #1, a replay without its opening turn duplicated the reply: - chat.ts buffers consecutive text deltas as one event under the last one's id (kiro-cli sends one per chunk), so MAX_BUFFERED_EVENTS (2000) drops a period's beginning much later. `bufferedAfter` gives a Last-Event-ID inside a merged run only the text after it. - useChatStream: a replay whose first message or output comes before any prompt turn cuts the history with `cutHistory(null)`; cutLocalAtPrompt(null) keeps the messages through the last user message. Cloud's cut returns undefined for null (unchanged behaviour). web-1 #2, delivered before saved: - The stream's end only records `endWritten`; the period is delivered (`markDelivered`) when the page's save after the stream's end reaches /api/agent/chat with `delivered: <session>` and `.chat.json` was written (saveChatToDeck now returns whether it wrote). Until then /api/agent/stream replays it. onSendComplete passes the session id the run streamed. web-1 #3, a failed /stream settled running tasks: - resumeLocalAgent rejects unless the answer is SSE or a JSON `{running: false}`; resumeLocal maps a failure to undefined, so settleStaleTasks runs only on the server's "nothing runs". web-2 #1, message_composer relayed past the tool's checks: - compose-run routes only input within the tool's bounds (group >= 1, text 1..10 000 code points); out-of-bounds input sends nothing, shows the tool's own refusal as an error and sends no <message_composer_error>. web-2 #2, finish() read isDropped before dropped() set it: - finish({dropped: true}): a drop ends the task cancelled, also after the 60-minute timeout. CHANGELOG [Unreleased] / Fixed: two entries. Checks run (worktree, this commit's tree): - web-ui: npx eslint src/ e2e/ --quiet: ok; npx tsc --noEmit: ok; npm test: 111 files / 1350 tests passed; npm run build:cloud: ok; npx playwright test: 28 passed; en/ja key parity: OK; package-lock.json unchanged - make lint: ok - make test: 2813 passed, 18 skipped, 1 failed: tests/test_html_assemble.py:: test_svg_icon_is_inlined_with_prefixed_ids ("asset not found: assets:aws/ Arch_AWS-Lambda_48"), from this machine's installed asset catalog; this commit changes no Python, test or asset file - ash scan --mode local --fail-on-findings: exit 0 - New tests fail on the old code (compose-run bounds and drop-after-timeout checked by stashing compose-run.ts) * fix(local-webui): keep a period's opening in the replay buffer; route coerced message_composer input as not delivered Review of 66e51de2 (review.json, CHANGES_REQUESTED), findings 1-4. 1. message_composer input the tool accepts but toolUse does not route (blocker): messageEnded shows the tool's own result as an error only when the tool refused (end.status "error" or result.status "error"). Other out-of-bounds input, such as a numeric-string group the tool coerces and answers "Sent", goes down the not-delivered path again: an error card and a <message_composer_error>, as on main. 2. A prompt-less replay dropped the saved head of a reply or still duplicated it. Chosen outcome: chat.ts never drops a period's opening (its events through the first turn, Period.opening). Past MAX_BUFFERED_EVENTS the oldest event after the opening goes, so a Local replay always starts with its prompt and the page cuts its history there. A saved reply or steer is never shown twice. What the buffer dropped is not replayed, so the reopened chat shows that reply from the oldest part kept. The cutHistory(null) path (HistoryCut, cutWithoutPrompt, cutLocalAtPrompt(null)) is removed because nothing reaches it now. 3. Style chat periods were never delivered: a stream that writes the end of a period of a chat no deck holds (savedDecks empty) delivers it at once, since no page can reopen it. 4. CHANGELOG: names only the empty and over-long text cases as delivered; describes the buffer outcome. Tests: compose-run case {group: "1", text: "x"} with a success result asserts the <message_composer_error>; chat.test pins the opening past the cap; useChatStream test pins a truncated replay against a saved full reply and a saved steer (no copy, head gone); acp-process case for a deck-less chat's delivery; the replay-until-saved cases bind a deck. The three new server-side tests fail on 66e51de2's code. Checks run (worktree, this commit's tree): - web-ui: npx eslint src/ e2e/ --quiet: ok; npx tsc --noEmit: ok; npm test: 111 files / 1351 tests passed; npm run build:cloud: ok (after removing a stale gitignored build/dev from an earlier dev server); npx playwright test: 28 passed; en/ja key parity: OK; package-lock.json unchanged - make lint: ok - make test: 2813 passed, 18 skipped, 1 failed: tests/test_html_assemble.py:: test_svg_icon_is_inlined_with_prefixed_ids ("asset not found: assets:aws/ Arch_AWS-Lambda_48"), from this machine's asset catalog; no Python, test or asset file changed - ash scan --mode local --fail-on-findings: exit 0
1 parent 3498291 commit e978913

20 files changed

Lines changed: 462 additions & 92 deletions

‎CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,21 @@ Under an Upgrading section, the bullets after **Local installs (`sdpm update`).*
3333
CLI `init_deck_workspace` without `-o`) now returns an error saying the name is a folder
3434
name without a path, and creates nothing; decks always go to `<deck root>/<timestamp>-<name>`.
3535
`make test` no longer leaves such folders in `~/Documents/SDPM-Presentations`.
36+
- **Local Web UI: a reopened deck no longer loses or doubles a reply.** A reply that ended
37+
just before a reload or a closed tab, before the page saved the chat, used to be gone on
38+
reopen; the server now replays a finished work period until the page has saved the chat
39+
after reading it. A long reply could show twice after a reopen, because the 2,000-event
40+
replay buffer dropped the period's prompt; the buffer now keeps a run of streamed text as
41+
one event and never drops the period's prompt. A period with more than 2,000 other events
42+
(tool calls, compose progress) is replayed from its prompt without its oldest events, so the
43+
reopened chat shows that reply from the oldest part kept. A failed reconnect no longer shows
44+
a running compose task as stopped.
45+
- **Local Web UI compose: `message_composer` input the tool refuses is not sent.** An empty
46+
text or a text over 10,000 characters used to reach the composer while the orchestrator read
47+
an error; the card now shows the tool's error and nothing is sent. A task
48+
whose 60-minute timeout came before a Stop its composers did not answer ends cancelled, as
49+
Stop does, instead of failed.
50+
3651
### Added
3752

3853
- `sdpm open <deck>` opens a deck in the browser Web UI and starts the Web UI if it is not

‎web-ui/src/app/api/agent/chat/route.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
22
// SPDX-License-Identifier: MIT-0
3-
/** Local Chat Save/Load — persists chat messages to deck's .chat.json. */
4-
import { saveChatToDeck, readChatFromDeck } from "@/lib/local/acp-process"
3+
/**
4+
* Local Chat Save/Load — persists chat messages to deck's .chat.json. A save with `delivered` (the
5+
* session id whose stream the page read to its end) delivers that work period once the messages
6+
* are written (acp-process.ts `markDelivered`): /api/agent/stream no longer replays it.
7+
*/
8+
import { markDelivered, saveChatToDeck, readChatFromDeck } from "@/lib/local/acp-process"
59
import { rejectCrossSite } from "@/lib/local/requestGuard"
610

711
export async function POST(req: Request) {
812
const refused = rejectCrossSite(req)
913
if (refused) return refused
10-
const { deckId, messages } = await req.json()
14+
const { deckId, messages, delivered } = await req.json()
1115
if (!deckId || !messages) return Response.json({ error: "deckId and messages required" }, { status: 400 })
12-
saveChatToDeck(deckId, messages)
16+
if (saveChatToDeck(deckId, messages) && typeof delivered === "string" && delivered) markDelivered(delivered)
1317
return Response.json({ ok: true })
1418
}
1519

‎web-ui/src/app/api/agent/invoke/route.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,9 @@ export async function POST(req: Request) {
144144
}
145145
const { subscribe, send, replayFrom, onEnd } = prompted
146146

147-
// The period's events from this turn on (its notice among them), then the live ones; a stream
148-
// that writes the period's end has delivered it (a closed tab's period is replayed by /stream).
147+
// The period's events from this turn on (its notice among them), then the live ones. A stream
148+
// that writes the period's end records it; the page's save after it delivers the period
149+
// (/api/agent/chat), until then /stream replays it (a tab closed before it saved).
149150
const stream = createSSEStream({ subscribe, replay: getBufferedEvents(clientSessionId, replayFrom - 1), onEnd })
150151

151152
send()

‎web-ui/src/app/api/agent/stream/route.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
/**
44
* Local ACP Stream — SSE endpoint with Last-Event-ID resume support (lib/local/acp-process.ts
55
* `openStream`). A busy chat's work period is replayed after the given id (the whole period when
6-
* the header is not a non-negative integer), then streamed live; a finished period no stream
7-
* delivered (its tab was closed) is replayed to its end once, also after its chat was released.
6+
* the header is not a non-negative integer), then streamed live; a finished period not delivered
7+
* yet (its tab was closed before it saved the chat) is replayed to its end, also after its chat
8+
* was released, until a page saves the chat after reading it (/api/agent/chat `delivered`).
89
* `{running: false}` when there is nothing to stream.
910
*/
1011
import { openStream } from "@/lib/local/acp-process"

‎web-ui/src/components/chat/ChatPanel.local.test.tsx‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66
* back from `.chat.json`. A deck follows its chat's work period after `.chat.json` loads
77
* (resumeLocalAgent, no EventSource): the replay rebuilds the period from its prompt, the Stop
88
* button and the background line show while it runs, and the chat is saved on a task's start
9-
* and end and on a turn's end. A task still running in the history while nothing runs shows
10-
* stopped. A history load of an earlier session id that answers late does not put the saved
9+
* and end and on a turn's end; the save after the stream's end reports the period delivered. A
10+
* task still running in the history while nothing runs shows stopped, and stays running when the
11+
* stream request fails. A history load of an earlier session id that answers late does not put the saved
1112
* history over the replay.
1213
*/
1314

@@ -146,6 +147,20 @@ describe("ChatPanel resume (Local)", () => {
146147
expect(screen.queryByText("2 slides in production")).toBeNull()
147148
})
148149

150+
it("keeps a task the history has running when the stream request fails", async () => {
151+
const tool = { toolUseId: "c1", name: "compose_slides", task: { id: "k1", state: "running" }, input: {} }
152+
getChatHistory.mockResolvedValue({
153+
messages: [...HISTORY.slice(0, 3), { role: "assistant", content: "Composing.", toolUses: [tool], blocks: [{ type: "text", text: "Composing." }, { type: "tool", tool }] }],
154+
truncated: false,
155+
})
156+
resumeLocalAgent.mockImplementationOnce(async () => { throw new Error("Local stream error: 500") })
157+
const error = vi.spyOn(console, "error").mockImplementation(() => {})
158+
renderWithIntl(<ChatPanel deckId="d1" chatSessionId="S1" />)
159+
await waitFor(() => expect(error).toHaveBeenCalledWith("Resume failed:", expect.any(Error)))
160+
expect(screen.queryByText("Stopped")).toBeNull()
161+
error.mockRestore()
162+
})
163+
149164
it("shows the background line and saves the chat on a task's start and end and a turn's end", async () => {
150165
getChatHistory.mockResolvedValue({ messages: HISTORY, truncated: false })
151166
const live = workingResume()
@@ -186,11 +201,13 @@ describe("ChatPanel resume (Local)", () => {
186201
expect(await screen.findByText("All done")).toBeTruthy()
187202
await waitFor(() => expect(saveLocalChat).toHaveBeenCalled())
188203
// Every save holds the replayed reply (none of the messages before the replay rendered).
189-
const saves = saveLocalChat.mock.calls as unknown as [string, { content: string }[]][]
204+
const saves = saveLocalChat.mock.calls as unknown as [string, { content: string }[], string | undefined][]
190205
for (const [deckId, messages] of saves) {
191206
expect(deckId).toBe("d1")
192207
expect(messages.map((m) => m.content)).toEqual(["earlier", "earlier reply", "make it", "All done"])
193208
}
209+
// The save after the stream's end reports the period delivered (the server stops replaying it).
210+
await waitFor(() => expect(saves.some(([, , delivered]) => delivered === "S1")).toBe(true))
194211
})
195212
})
196213

‎web-ui/src/components/chat/ChatPanel.tsx‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -175,11 +175,11 @@ export const ChatPanel = forwardRef<ChatPanelHandle, ChatPanelProps>(function Ch
175175
const reviewRef = useRef(review)
176176
useEffect(() => { reviewRef.current = review })
177177

178-
/** Persist chat messages to disk (Local mode only). */
179-
const saveLocalChat = useCallback((overrideDeckId?: string) => {
178+
/** Persist chat messages to disk (Local mode only); `delivered`: the session whose stream ended before this save. */
179+
const saveLocalChat = useCallback((overrideDeckId?: string, delivered?: string) => {
180180
const did = overrideDeckId || currentDeckId.current
181181
if (!IS_LOCAL || !did) return
182-
localService.saveLocalChat(did, stream.messagesRef.current).catch((err) => notifyError(t("errorSaveHistory"), err))
182+
localService.saveLocalChat(did, stream.messagesRef.current, delivered).catch((err) => notifyError(t("errorSaveHistory"), err))
183183
// eslint-disable-next-line react-hooks/exhaustive-deps
184184
}, [])
185185

@@ -225,10 +225,21 @@ export const ChatPanel = forwardRef<ChatPanelHandle, ChatPanelProps>(function Ch
225225
// --- useChatStream ---
226226
// A send's or a replay's end, and a turn's end, save the chat once the render that holds their
227227
// messages is committed (saveLocalChat reads messagesRef, which follows the render): a replayed
228-
// period arrives in one chunk, so its messages are not rendered yet when its stream ends.
228+
// period arrives in one chunk, so its messages are not rendered yet when its stream ends. The
229+
// save after a stream's end reports its session delivered: until then the server replays it.
229230
const [saveRequest, setSaveRequest] = useState(0)
230-
useEffect(() => { if (saveRequest) saveLocalChat() }, [saveRequest, saveLocalChat])
231-
const requestSave = useCallback(() => { if (IS_LOCAL) setSaveRequest((n) => n + 1) }, [])
231+
const deliveredRef = useRef<string | undefined>(undefined)
232+
useEffect(() => {
233+
if (!saveRequest) return
234+
const delivered = deliveredRef.current
235+
deliveredRef.current = undefined
236+
saveLocalChat(undefined, delivered)
237+
}, [saveRequest, saveLocalChat])
238+
const requestSave = useCallback((delivered?: string) => {
239+
if (!IS_LOCAL) return
240+
if (delivered) deliveredRef.current = delivered
241+
setSaveRequest((n) => n + 1)
242+
}, [])
232243
const mode = agentMode === "vibe" ? "vibe" : "spec"
233244
const stream = useChatStream({
234245
sessionId,
@@ -361,7 +372,7 @@ export const ChatPanel = forwardRef<ChatPanelHandle, ChatPanelProps>(function Ch
361372
// The session may be working (reload, wake, reopened deck): follow it once the agent
362373
// config is loaded. The replay rebuilds the work from its opening prompt on. Cloud: when
363374
// it was working as this page last saw it. Local: always (the server also replays a
364-
// period that ended while no page followed it).
375+
// period that ended before a page saved it).
365376
if (IS_LOCAL && deckId && deckId !== "new") {
366377
if (superseded) return
367378
setResumeCut({ cut: (prompt: string) => cutLocalAtPrompt(loaded, prompt) })

‎web-ui/src/hooks/useChatStream.test.tsx‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ vi.mock("@/services/agentCoreService", () => ({ invokeAgentCore, resumeLocalAgen
2626
vi.mock("@/services/localService", () => ({ stopLocalAgent, steerLocalAgent }))
2727
vi.mock("@/lib/errors", () => ({ notifyError }))
2828

29+
import { cutLocalAtPrompt } from "@/components/chat/chatHistory"
2930
import { useChatStream, type Message } from "./useChatStream"
3031

3132
beforeEach(() => {
@@ -259,6 +260,46 @@ describe("useChatStream resume (local)", () => {
259260
await act(async () => { run.finish!(); await done })
260261
})
261262

263+
it("a replay whose middle the server dropped rebuilds from its prompt: no copy of a saved reply or steer, the dropped part is gone", async () => {
264+
// .chat.json holds the whole period: the reply, a steer and the reply after it.
265+
const saved: Message[] = [
266+
...history.slice(0, 3),
267+
{ role: "assistant", content: "head and tail", toolUses: [] },
268+
{ role: "user", content: "also this", toolUses: [], steerId: "s1", steerState: "delivered" },
269+
{ role: "assistant", content: "More", toolUses: [] },
270+
]
271+
const run = captureResume()
272+
const { result } = render()
273+
act(() => { result.current.setMessages(saved) })
274+
const cut = vi.fn((prompt: string) => cutLocalAtPrompt(saved, prompt))
275+
let done: Promise<boolean | undefined> | undefined
276+
act(() => { done = result.current.resume(cut) })
277+
// The buffer kept the period's opening (work, its prompt) and lost the reply's head.
278+
act(() => {
279+
run.handlers!.onResumeAck({ working: true })
280+
run.handlers!.onSession.onEvent({ work: { state: "busy" } }, { own: false })
281+
run.handlers!.onSession.onEvent({ turn: { id: "t1", why: "prompt", text: "make it" } }, { own: false })
282+
run.handlers!.onStreamUpdate("tail")
283+
run.handlers!.onSession.onEvent({ steer: { id: "s1", text: "also this", state: "accepted" } }, { own: false })
284+
run.handlers!.onStreamUpdate("tailMore")
285+
})
286+
expect(cut).toHaveBeenCalledTimes(1)
287+
expect(cut).toHaveBeenCalledWith("make it")
288+
expect(roles(result.current.messages)).toEqual(["user:earlier", "assistant:earlier reply", "user:make it", "assistant:tail", "user:also this", "assistant:More"])
289+
await act(async () => { run.finish!(); await done })
290+
})
291+
292+
it("resolves undefined when the stream request fails", async () => {
293+
resumeLocalAgent.mockImplementationOnce(async () => { throw new Error("Local stream error: 500") })
294+
const error = vi.spyOn(console, "error").mockImplementation(() => {})
295+
const { result } = render()
296+
let resolved: boolean | undefined = false
297+
await act(async () => { resolved = await result.current.resume(() => []) })
298+
expect(resolved).toBeUndefined()
299+
expect(result.current.isLoading).toBe(false)
300+
error.mockRestore()
301+
})
302+
262303
it("turns a send during the followed period into a steer, and a send after it into an invoke", async () => {
263304
const run = captureResume()
264305
const onSendComplete = vi.fn()
@@ -276,6 +317,7 @@ describe("useChatStream resume (local)", () => {
276317
expect(resolved).toBe(true)
277318
expect(result.current.isLoading).toBe(false)
278319
expect(onSendComplete).toHaveBeenCalledTimes(1)
320+
expect(onSendComplete).toHaveBeenCalledWith("K1")
279321
invokeAgentCore.mockResolvedValueOnce("")
280322
await act(async () => { await result.current.sendMessage("next") })
281323
expect(invokeAgentCore).toHaveBeenCalledTimes(1)

‎web-ui/src/hooks/useChatStream.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,12 @@ export interface UseChatStreamOptions {
103103
deckId?: string
104104
/** Called on every tool event (start, complete, stream). Panel handles side effects. */
105105
onToolEvent?: (toolName: string, data: ToolUseCallbackData | undefined) => void
106-
/** Called after each send completes (success or abort). */
107-
onSendComplete?: () => void
106+
/**
107+
* Called after each send completes (success or abort), and after a resume that followed work.
108+
* Local: with the session id whose stream the run read, which the panel's next save reports
109+
* delivered (the server stops replaying that period once the chat holding it is saved).
110+
*/
111+
onSendComplete?: (streamed?: string) => void
108112
/** Called when a turn ends (`turnEnd`), while the work may go on. */
109113
onTurnEnd?: () => void
110114
}
@@ -118,10 +122,12 @@ export interface UseChatStreamReturn {
118122
stopGeneration: () => void
119123
/**
120124
* Follow the session if it is working (after a reload or on a reopened deck; Local: also a
121-
* period that ended while no page followed it). `cutHistory(prompt)` returns the messages
122-
* before the prompt that opened the work, which the replay then rebuilds. Local resolves
123-
* `true` when it followed a period, `false` when nothing ran (or the request failed), and
124-
* `undefined` when it did not run or a newer resume or Stop ended it; Cloud resolves `undefined`.
125+
* period that ended before a page saved it). `cutHistory(prompt)` returns the messages
126+
* before the prompt that opened the work, which the replay then rebuilds (Local's replay always
127+
* starts with that prompt: chat.ts never drops a period's opening events). Local resolves
128+
* `true` when it followed a period, `false` when the server said nothing runs, and `undefined`
129+
* when it did not run, the request failed, or a newer resume or Stop ended it; Cloud resolves
130+
* `undefined`.
125131
*/
126132
resume: (cutHistory: (prompt: string) => Message[]) => Promise<boolean | undefined>
127133
/** Cloud: the connection dropped while the session works and is being restored. */
@@ -669,7 +675,7 @@ export function useChatStream({ sessionId, mode, deckId, onToolEvent, onSendComp
669675
setIsLoading(false)
670676
setTurnActiveState(false)
671677
setReconnecting(false)
672-
onSendComplete?.()
678+
onSendComplete?.(IS_LOCAL ? runSessionId : undefined)
673679
}
674680
return ok
675681
}, [sessionId, mode, deckId, isLoading, auth.user?.access_token, auth.user?.profile?.sub, onToolEvent, onSendComplete, onTurnEnd, t, translateError])
@@ -726,12 +732,10 @@ export function useChatStream({ sessionId, mode, deckId, onToolEvent, onSendComp
726732
}, { signal: controller.signal })
727733
result = working
728734
} catch (err) {
729-
// A newer resume, Stop or unmount ended it (AbortError): nothing failed.
730-
if (err instanceof DOMException && err.name === "AbortError") result = undefined
731-
else {
732-
console.error("Resume failed:", err)
733-
result = false
734-
}
735+
// A newer resume, Stop or unmount ended it (AbortError): nothing failed. A failed request
736+
// says nothing about the session's work either.
737+
if (!(err instanceof DOMException && err.name === "AbortError")) console.error("Resume failed:", err)
738+
result = undefined
735739
} finally {
736740
if (resumeRunRef.current === token) {
737741
resumeControllerRef.current = null
@@ -743,7 +747,7 @@ export function useChatStream({ sessionId, mode, deckId, onToolEvent, onSendComp
743747
isLoadingRef.current = false
744748
setIsLoading(false)
745749
setTurnActiveState(false)
746-
onSendComplete?.()
750+
onSendComplete?.(sessionId)
747751
}
748752
}
749753
if (resumeGateRef.current === gate) resumeGateRef.current = null

‎web-ui/src/lib/local/acp-contract.test.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -293,15 +293,28 @@ describe("kiro-cli 3.0.0 V2, a turn that delegates to the composer", () => {
293293
expect(composeResults(events)).toEqual(["success"])
294294
})
295295

296-
it("numbers the stream's events as the buffer does, so a reconnect replays nothing twice", async () => {
296+
it("numbers the stream's events as the buffer does, so a reconnect after any of them replays nothing twice", async () => {
297297
const { second } = await runCompose()
298298
const ids = second.map((b) => b.id)
299299
expect(ids).toEqual(ids.map((_, i) => i + 1))
300-
// The turn's end is buffered after the last written event.
301-
expect(acp.getBufferedEvents("C1").map((e) => e.id)).toEqual([...ids, ids.length + 1])
302-
const lastSeen = ids[4]
303-
const reconnect = await readBlocks(bridge.createSSEStream({ subscribe: () => () => {}, replay: acp.getBufferedEvents("C1", lastSeen) }))
304-
expect([...second.slice(0, 5), ...reconnect]).toEqual(second)
300+
// Consecutive text deltas are buffered as one event under the last one's id; the turn's end
301+
// is buffered after the last written event.
302+
const buffered = acp.getBufferedEvents("C1").map((e) => e.id)
303+
expect(buffered.length).toBeLessThan(ids.length + 1)
304+
expect(buffered.at(-1)).toBe(ids.length + 1)
305+
expect(buffered.slice(0, -1).every((id) => ids.includes(id))).toBe(true)
306+
/** The payloads with consecutive text deltas joined (what the chat shows). */
307+
const shown = (blocks: { data: Line }[]) => blocks.reduce<Line[]>((out, { data }) => {
308+
const text = (data.event as { contentBlockDelta?: { delta: { text: string } } } | undefined)?.contentBlockDelta?.delta.text
309+
const last = out.at(-1)?.event as { contentBlockDelta?: { delta: { text: string } } } | undefined
310+
if (text !== undefined && last?.contentBlockDelta) out[out.length - 1] = { event: { contentBlockDelta: { delta: { text: last.contentBlockDelta.delta.text + text } } } }
311+
else out.push(data)
312+
return out
313+
}, [])
314+
for (const lastSeen of ids) {
315+
const reconnect = await readBlocks(bridge.createSSEStream({ subscribe: () => () => {}, replay: acp.getBufferedEvents("C1", lastSeen) }))
316+
expect(shown([...second.slice(0, lastSeen), ...reconnect]), `after ${lastSeen}`).toEqual(shown(second))
317+
}
305318
})
306319

307320
it("keeps the composer session's MCP state apart from the main session's", async () => {

0 commit comments

Comments
 (0)