Skip to content

Commit f248c5a

Browse files
committed
fix(es-app): avoid duplicate initial session snapshot (anomalyco#147)
1 parent 849a6b4 commit f248c5a

4 files changed

Lines changed: 155 additions & 3 deletions

File tree

‎packages/es-app/src/live-session.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,43 @@ test("concurrent loads share one snapshot request", async () => {
404404
expect(fetchSpy).toHaveBeenCalledTimes(3)
405405
})
406406

407+
test("initial stream open during a snapshot does not fetch messages again", async () => {
408+
const gate = Promise.withResolvers<void>()
409+
fetchSpy.mockImplementation(async (input) => {
410+
if (String(input).includes("/message?")) await gate.promise
411+
return response(input)
412+
})
413+
const live = start()
414+
const loading = live.load()
415+
SessionEvents.current.onopen?.()
416+
gate.resolve()
417+
await loading
418+
await Promise.resolve()
419+
await Promise.resolve()
420+
expect(fetchSpy.mock.calls.filter(([input]) => String(input).includes("/message?"))).toHaveLength(1)
421+
})
422+
423+
test("a lost stream reopening during a snapshot still repairs the missed gap", async () => {
424+
const gate = Promise.withResolvers<void>()
425+
const started = Promise.withResolvers<void>()
426+
fetchSpy.mockImplementation(async (input) => {
427+
if (String(input).includes("/message?")) started.resolve()
428+
await gate.promise
429+
return response(input)
430+
})
431+
const live = start()
432+
const loading = live.load()
433+
SessionEvents.current.onerror?.()
434+
await started.promise
435+
snapshot = [{ info: user(), parts: [] }]
436+
SessionEvents.current.onopen?.()
437+
gate.resolve()
438+
await loading
439+
await live.load()
440+
expect(fetchSpy.mock.calls.filter(([input]) => String(input).includes("/message?"))).toHaveLength(2)
441+
expect(live.data.message.ses_current?.map((message) => message.id)).toEqual(["msg_001"])
442+
})
443+
407444
test("automatic reconnect load failures reach reactive accessors without an explicit caller", async () => {
408445
const live = start()
409446
await live.load()
@@ -635,12 +672,16 @@ test("a full part repairs ambiguous text without another snapshot", async () =>
635672
test("SSE opening during a stale snapshot schedules recovery of the subscription gap", async () => {
636673
const live = start()
637674
const gate = Promise.withResolvers<void>()
675+
const started = Promise.withResolvers<void>()
638676
fetchSpy.mockImplementation(async (input) => {
639677
const result = response(input)
678+
if (String(input).includes("/message?")) started.resolve()
640679
await gate.promise
641680
return result
642681
})
643682
const loading = live.load()
683+
SessionEvents.current.onerror?.()
684+
await started.promise
644685
snapshot = [{ info: user("msg_003"), parts: [] }]
645686
SessionEvents.current.onopen?.()
646687
fetchSpy.mockImplementation(async (input) => response(input))

‎packages/es-app/src/live-session.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ export function createLiveSession(
108108
let activeLoad: Promise<void> | undefined
109109
let duringLoad: LiveEvent[] | undefined
110110
let refreshAfterLoad = false
111+
let snapshotStarted = false
112+
let streamOpened = false
113+
let releaseInitial: (() => void) | undefined
111114
const uncertainParts = new Set<string>()
112115

113116
const load = (): Promise<void> => {
@@ -116,6 +119,20 @@ export function createLiveSession(
116119
setLoading(true)
117120
duringLoad = []
118121
activeLoad = (async () => {
122+
if (!snapshotStarted && !streamOpened && source) {
123+
// Subscribe before the first snapshot so its one GET cannot miss events
124+
// between server capture and stream admission. Do not block offline loads.
125+
await new Promise<void>((resolve) => {
126+
const timeout = setTimeout(resolve, 200)
127+
releaseInitial = () => {
128+
clearTimeout(timeout)
129+
resolve()
130+
}
131+
})
132+
releaseInitial = undefined
133+
}
134+
if (disposed) return
135+
snapshotStarted = true
119136
const [session, messages, status] = await Promise.all([
120137
oc.session(sessionID, directory, controller.signal),
121138
oc.messages(sessionID, directory, controller.signal),
@@ -314,10 +331,13 @@ export function createLiveSession(
314331
source.onopen = () => {
315332
if (disposed) return
316333
setConnection("stream", "")
317-
refresh()
334+
streamOpened = true
335+
releaseInitial?.()
336+
if (!activeLoad || snapshotStarted) refresh()
318337
}
319338
source.onerror = () => {
320339
if (disposed) return
340+
releaseInitial?.()
321341
batch(() => {
322342
setConnection("stream", "Session connection lost. Reconnecting...")
323343
stopOnFailure()

‎packages/es-app/test/composer-fixture.mjs‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ export const createFixture = async () => {
4646
receipts: [],
4747
messages: undefined,
4848
messagesB: [],
49+
holdMessages: new Map(),
50+
messageReplies: [],
51+
abortedMessages: [],
4952
children: new Map(),
5053
permissions: undefined,
5154
questions: [],
@@ -279,7 +282,7 @@ export const createFixture = async () => {
279282
if (action === "/message") {
280283
const limit = url.searchParams.get("limit")
281284
const slice = (list) => limit ? list.slice(-Number(limit)) : list
282-
return json(slice(
285+
const messages = slice(
283286
id === "ses_a"
284287
? (fixture.messages ?? [
285288
{
@@ -312,7 +315,15 @@ export const createFixture = async () => {
312315
},
313316
])
314317
: fixture.messagesB,
315-
))
318+
)
319+
if (fixture.holdMessages.has(id)) {
320+
response.on("close", () => {
321+
if (!response.writableEnded) fixture.abortedMessages.push(id)
322+
})
323+
fixture.messageReplies.push(() => json(messages))
324+
return
325+
}
326+
return json(messages)
316327
}
317328
if (action === "/prompt_async" && request.method === "POST") {
318329
if (fixture.rejectImages && body.parts.some((part) => part.type === "file"))
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { createRequire } from "node:module"
2+
import { execFileSync } from "node:child_process"
3+
import { fileURLToPath } from "node:url"
4+
import { mkdtemp, rm } from "node:fs/promises"
5+
import { tmpdir } from "node:os"
6+
import path from "node:path"
7+
import { startPanelPreview } from "./composer-panel-preview.mjs"
8+
import { directory } from "./composer-fixture.mjs"
9+
10+
const { chromium, _electron, expect } = createRequire(new URL("../../app/package.json", import.meta.url))("@playwright/test")
11+
const baseline = process.argv.includes("--baseline")
12+
const native = !!process.env.ES_DESKTOP_EXECUTABLE
13+
if (baseline && native) throw new Error("The baseline override runs only in the dev browser")
14+
const root = fileURLToPath(new URL("../../..", import.meta.url))
15+
const prior = baseline ? execFileSync("jj", ["file", "show", "-r", "849a6b4238ff", "packages/es-app/src/live-session.ts"],
16+
{ cwd: root, encoding: "utf8" }) : undefined
17+
const preview = await startPanelPreview(prior ? [{ name: "baseline-snapshot", enforce: "pre",
18+
transform(_code, id) { return id.endsWith("/src/live-session.ts") ? prior : undefined } }] : [])
19+
const fixture = preview.fixture
20+
fixture.messages = Array.from({ length: 12 }, (_, index) => ({
21+
info: { id: `msg_${String(index).padStart(6, "0")}`, sessionID: "ses_a", role: "user", agent: "build",
22+
model: { providerID: "fixture", modelID: "test" }, time: { created: index + 1 } },
23+
parts: [{ id: `prt_${index}`, messageID: `msg_${String(index).padStart(6, "0")}`, sessionID: "ses_a", type: "text",
24+
text: `${index}: ${"synthetic transcript text ".repeat(7000)} ${index === 11 ? "LATEST-SENTINEL" : ""}` }],
25+
}))
26+
fixture.messagesB = [{ info: { id: "msg_b", sessionID: "ses_b", role: "user", agent: "build",
27+
model: { providerID: "fixture", modelID: "test" }, time: { created: 1 } },
28+
parts: [{ id: "prt_b", messageID: "msg_b", sessionID: "ses_b", type: "text", text: "SECOND-SESSION-SENTINEL" }] }]
29+
const profile = native ? await mkdtemp(path.join(tmpdir(), "single-snapshot-native-")) : undefined
30+
const app = native ? await _electron.launch({ executablePath: process.env.ES_DESKTOP_EXECUTABLE,
31+
env: { ...process.env, ELECTRON_RUN_AS_NODE: "", ES_DESKTOP_USER_DATA: profile, ES_DESKTOP_RENDERER: "",
32+
OPENCODE_URL: fixture.url, ES_DASHBOARD_URL: fixture.url, OPENCODE_SERVER_PASSWORD: "" } }) : undefined
33+
const browser = app ? undefined : await chromium.launch({ channel: "chrome", headless: true })
34+
const page = app ? await app.firstWindow() : await browser.newPage()
35+
if (app) {
36+
await page.waitForURL("http://127.0.0.1:*/")
37+
preview.origin = new URL(page.url()).origin
38+
preview.url = `${preview.origin}/session/ses_a?directory=${encodeURIComponent(directory)}`
39+
}
40+
const reads = () => fixture.calls.filter((call) => call.method === "GET" && call.path === "/session/ses_a/message").length
41+
try {
42+
await page.goto(`${preview.origin}/session/ses_b?directory=${encodeURIComponent(directory)}`)
43+
await expect(page.locator(".transcript")).toContainText("SECOND-SESSION-SENTINEL")
44+
const started = Date.now()
45+
await page.locator('.sidebar a[href*="/session/ses_a"]').first().click()
46+
await expect(page.locator(".transcript")).toContainText("LATEST-SENTINEL", { timeout: 30_000 })
47+
await page.waitForTimeout(1000)
48+
const first = reads()
49+
const painted = Date.now() - started
50+
const bytes = Buffer.byteLength(JSON.stringify(fixture.messages))
51+
console.log(JSON.stringify({ phase: "initial", mode: native ? "packaged-native" : "browser", baseline,
52+
messages_get: first, response_bytes: bytes, estimated_message_bytes: bytes * first, paint_check_ms: painted }))
53+
expect(first).toBe(1)
54+
55+
fixture.disconnect()
56+
fixture.messages.at(-1).parts[0].text += "\nRECOVERED-SENTINEL"
57+
await expect.poll(reads, { timeout: 20_000 }).toBe(2)
58+
await expect(page.locator(".transcript")).toContainText("RECOVERED-SENTINEL")
59+
await page.waitForTimeout(1200)
60+
expect(reads()).toBe(2)
61+
console.log(JSON.stringify({ phase: "reconnected", mode: native ? "packaged-native" : "browser", added_message_get: reads() - first }))
62+
63+
fixture.holdMessages.set("ses_a", true)
64+
await page.locator('.sidebar a[href*="/session/ses_b"]').first().click()
65+
await expect(page.locator(".transcript")).toContainText("SECOND-SESSION-SENTINEL")
66+
await page.locator('.sidebar a[href*="/session/ses_a"]').first().click()
67+
await expect.poll(() => fixture.messageReplies.length).toBe(1)
68+
await page.locator('.sidebar a[href*="/session/ses_b"]').first().click()
69+
await expect(page.locator(".transcript")).toContainText("SECOND-SESSION-SENTINEL")
70+
fixture.messageReplies.splice(0).forEach((release) => release())
71+
await expect.poll(() => fixture.abortedMessages).toContain("ses_a")
72+
await expect(page.locator(".transcript")).not.toContainText("LATEST-SENTINEL")
73+
expect(fixture.calls.filter((call) => !["GET", "HEAD", "OPTIONS"].includes(call.method))).toEqual([])
74+
console.log(JSON.stringify({ phase: "switch", mode: native ? "packaged-native" : "browser", stale_aborted: true, writes: 0 }))
75+
} finally {
76+
await app?.close()
77+
await browser?.close()
78+
await preview.close()
79+
if (profile) await rm(profile, { recursive: true, force: true })
80+
}

0 commit comments

Comments
 (0)