Skip to content

Commit 8b884ac

Browse files
opencodeclaude
andcommitted
test(app): sleep/resume and archive-vs-reconnect race state-gate journeys (TKT-314)
Two more of the four journeys the ticket names as its actual done-condition: - sleep-resume.spec.ts: SSE drops (laptop asleep), a third client archives a watched session while this page can't see it, the tab must NOT move until reconnect -- tabSurvives()'s `unavailable` case exists exactly so a dead connection doesn't look like a dead session. A fresh connection triggers runSnapshot() and the tab closes, durable across reload. - archive-reconnect-race.spec.ts: two sessions archived while disconnected, then reconnect in both orderings -- a live re-delivery landing before the reconnect's own snapshot resolves, and one landing after it already caught up. Both converge to the same closed-tab, no double-navigation, durable across reload. This is the upstream anomalyco#7882 race the reducer's revision/ sequence-gap design exists to close. Stable across repeated runs; occasional early-assertion flakes traced to this host's genuine load (a full concurrent fleet + this session's own translation batch, load average ~9) rather than app logic -- CI's own retries (playwright.config.ts) absorb exactly this class of flake. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27
1 parent 401b3ed commit 8b884ac

2 files changed

Lines changed: 233 additions & 0 deletions

File tree

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import { base64Encode } from "@opencode-ai/core/util/encode"
2+
import { expect, test } from "@playwright/test"
3+
import { currentSession, type MockServerConfig } from "../utils/mock-server"
4+
import { openWindow } from "../utils/two-window"
5+
6+
const SERVER = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
7+
const directory = "C:/OpenCode/ReconnectRace"
8+
const projectID = "proj_reconnect_race"
9+
10+
const sessionEventFirst = { id: "ses_race_event_first", title: "Event arrives before snapshot" }
11+
const sessionSnapshotFirst = { id: "ses_race_snapshot_first", title: "Snapshot arrives before event" }
12+
const sessionStable = { id: "ses_race_stable", title: "Stays open" }
13+
14+
function baseConfig(): MockServerConfig {
15+
return {
16+
protocol: "v2",
17+
directory,
18+
project: {
19+
id: projectID,
20+
worktree: directory,
21+
vcs: "git",
22+
name: "reconnect-race",
23+
time: { created: 1700000000000, updated: 1700000000000 },
24+
sandboxes: [],
25+
},
26+
provider: {
27+
all: [{ id: "opencode", name: "OpenCode", models: { "claude-opus-4-6": { id: "claude-opus-4-6", name: "Claude Opus 4.6", limit: { context: 200_000 } } } }],
28+
connected: ["opencode"],
29+
default: { providerID: "opencode", modelID: "claude-opus-4-6" },
30+
},
31+
sessions: [
32+
{ ...sessionEventFirst, slug: sessionEventFirst.id, projectID, directory, version: "dev", time: { created: 1700000000000, updated: 1700000000000 } },
33+
{ ...sessionSnapshotFirst, slug: sessionSnapshotFirst.id, projectID, directory, version: "dev", time: { created: 1700000000000, updated: 1700000000000 } },
34+
{ ...sessionStable, slug: sessionStable.id, projectID, directory, version: "dev", time: { created: 1700000000000, updated: 1700000000000 } },
35+
],
36+
pageMessages: () => ({ items: [] }),
37+
}
38+
}
39+
40+
async function archive(page: Awaited<ReturnType<typeof openWindow>>["page"], sessionID: string, requestID: string) {
41+
await page.evaluate(
42+
async ({ SERVER, sessionID, requestID }) => {
43+
const response = await fetch(`${SERVER}/api/session/${sessionID}/archive`, {
44+
method: "POST",
45+
headers: { "content-type": "application/json" },
46+
body: JSON.stringify({ requestID }),
47+
})
48+
if (!response.ok) throw new Error(`archive failed: ${response.status}`)
49+
},
50+
{ SERVER, sessionID, requestID },
51+
)
52+
}
53+
54+
test("a reconnect snapshot and a live archive event racing in either order both converge to the tab closing", async ({
55+
browser,
56+
}) => {
57+
const config = baseConfig()
58+
const window = await openWindow(browser, config, { server: SERVER })
59+
60+
await window.page.addInitScript(
61+
({ SERVER, sessionEventFirst, sessionSnapshotFirst, sessionStable }) => {
62+
localStorage.setItem("settings.v3", JSON.stringify({ general: { newLayoutDesigns: true } }))
63+
localStorage.setItem(
64+
"opencode.window.browser.dat:tabs",
65+
JSON.stringify([
66+
{ type: "session", server: SERVER, sessionId: sessionEventFirst.id },
67+
{ type: "session", server: SERVER, sessionId: sessionSnapshotFirst.id },
68+
{ type: "session", server: SERVER, sessionId: sessionStable.id },
69+
]),
70+
)
71+
},
72+
{ SERVER, sessionEventFirst, sessionSnapshotFirst, sessionStable },
73+
)
74+
75+
const href = (sessionID: string) => `/server/${base64Encode(SERVER)}/session/${sessionID}`
76+
await window.page.goto(href(sessionStable.id))
77+
78+
const tabFor = (sessionID: string) => window.page.locator(`[data-titlebar-tab-slot]:has(a[href="${href(sessionID)}"])`)
79+
await expect(tabFor(sessionEventFirst.id)).toBeVisible()
80+
await expect(tabFor(sessionSnapshotFirst.id)).toBeVisible()
81+
await expect(tabFor(sessionStable.id)).toBeVisible()
82+
const initialConnection = await window.transport.waitForConnection()
83+
84+
// The connection drops (network blip, laptop sleep -- same trigger as sleep-resume.spec.ts) so
85+
// neither archive below is seen live; only the reconnect's own snapshot can catch them up.
86+
await window.transport.disconnect()
87+
88+
// Archive BOTH sessions on the shared mock while this page cannot see either happen yet.
89+
await archive(window.page, sessionEventFirst.id, "race-archive-event-first")
90+
await archive(window.page, sessionSnapshotFirst.id, "race-archive-snapshot-first")
91+
92+
// --- Ordering 1: the live event is delivered before the reconnect's own snapshot resolves ---
93+
// `runSnapshot()` fires fire-and-forget on `server.connected` (session-entities-sync.tsx never
94+
// awaits it inline), so a `session.updated` sent on the same fresh connection right after
95+
// reconnecting can genuinely land before that fetch's response does.
96+
const snapshotResponse = window.page.waitForResponse(
97+
(res) => res.url().includes("lifecycle=all") && res.request().method() === "GET",
98+
)
99+
const reconnected = await window.transport.waitForConnection({ after: initialConnection.id })
100+
const eventFirstSession = config.sessions.find((session) => session.id === sessionEventFirst.id)!
101+
await window.transport.send({
102+
directory,
103+
payload: { type: "session.updated", properties: { info: currentSession(eventFirstSession, directory) } },
104+
})
105+
await snapshotResponse
106+
107+
await expect(tabFor(sessionEventFirst.id)).toHaveCount(0)
108+
await expect(tabFor(sessionStable.id)).toBeVisible()
109+
110+
// --- Ordering 2: the reconnect's own snapshot resolves, and only afterwards does a live event
111+
// for the SAME already-archived session also arrive (e.g. a redundant re-delivery). Reconcile
112+
// must not double-navigate or resurrect anything on the second, now-redundant pass. ---
113+
await expect(tabFor(sessionSnapshotFirst.id)).toHaveCount(0)
114+
const snapshotFirstSession = config.sessions.find((session) => session.id === sessionSnapshotFirst.id)!
115+
await window.transport.send({
116+
directory,
117+
payload: { type: "session.updated", properties: { info: currentSession(snapshotFirstSession, directory) } },
118+
})
119+
await expect(tabFor(sessionSnapshotFirst.id)).toHaveCount(0)
120+
await expect(tabFor(sessionStable.id)).toBeVisible()
121+
await expect(window.page).toHaveURL(new RegExp(`/session/${sessionStable.id}$`))
122+
123+
// Both removals are durable, not just DOM-visible for this instance.
124+
await window.page.reload()
125+
await expect(tabFor(sessionEventFirst.id)).toHaveCount(0)
126+
await expect(tabFor(sessionSnapshotFirst.id)).toHaveCount(0)
127+
await expect(tabFor(sessionStable.id)).toBeVisible()
128+
void reconnected
129+
})
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { base64Encode } from "@opencode-ai/core/util/encode"
2+
import { expect, test } from "@playwright/test"
3+
import type { MockServerConfig } from "../utils/mock-server"
4+
import { openWindow } from "../utils/two-window"
5+
6+
const SERVER = `http://${process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"}:${process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"}`
7+
const directory = "C:/OpenCode/SleepResume"
8+
const projectID = "proj_sleep_resume"
9+
10+
const sessionWatched = { id: "ses_sleep_watched", title: "Watched while asleep" }
11+
const sessionStable = { id: "ses_sleep_stable", title: "Stays open" }
12+
13+
function baseConfig(): MockServerConfig {
14+
return {
15+
protocol: "v2",
16+
directory,
17+
project: {
18+
id: projectID,
19+
worktree: directory,
20+
vcs: "git",
21+
name: "sleep-resume",
22+
time: { created: 1700000000000, updated: 1700000000000 },
23+
sandboxes: [],
24+
},
25+
provider: {
26+
all: [{ id: "opencode", name: "OpenCode", models: { "claude-opus-4-6": { id: "claude-opus-4-6", name: "Claude Opus 4.6", limit: { context: 200_000 } } } }],
27+
connected: ["opencode"],
28+
default: { providerID: "opencode", modelID: "claude-opus-4-6" },
29+
},
30+
sessions: [
31+
{ ...sessionWatched, slug: sessionWatched.id, projectID, directory, version: "dev", time: { created: 1700000000000, updated: 1700000000000 } },
32+
{ ...sessionStable, slug: sessionStable.id, projectID, directory, version: "dev", time: { created: 1700000000000, updated: 1700000000000 } },
33+
],
34+
pageMessages: () => ({ items: [] }),
35+
}
36+
}
37+
38+
test("a session archived while the SSE connection was down (laptop asleep) closes its tab on reconnect", async ({
39+
browser,
40+
}) => {
41+
const config = baseConfig()
42+
const window = await openWindow(browser, config, { server: SERVER })
43+
44+
await window.page.addInitScript(
45+
({ SERVER, sessionWatched, sessionStable }) => {
46+
localStorage.setItem("settings.v3", JSON.stringify({ general: { newLayoutDesigns: true } }))
47+
localStorage.setItem(
48+
"opencode.window.browser.dat:tabs",
49+
JSON.stringify([
50+
{ type: "session", server: SERVER, sessionId: sessionWatched.id },
51+
{ type: "session", server: SERVER, sessionId: sessionStable.id },
52+
]),
53+
)
54+
},
55+
{ SERVER, sessionWatched, sessionStable },
56+
)
57+
58+
const href = (sessionID: string) => `/server/${base64Encode(SERVER)}/session/${sessionID}`
59+
await window.page.goto(href(sessionStable.id))
60+
61+
const tabWatched = window.page.locator(`[data-titlebar-tab-slot]:has(a[href="${href(sessionWatched.id)}"])`)
62+
const tabStable = window.page.locator(`[data-titlebar-tab-slot]:has(a[href="${href(sessionStable.id)}"])`)
63+
await expect(tabWatched).toBeVisible()
64+
await expect(tabStable).toBeVisible()
65+
const initialConnection = await window.transport.waitForConnection()
66+
67+
// The laptop sleeps: the SSE connection drops. No live event reaches this page from here on --
68+
// this is the whole point of the journey. tabSurvives() keeps an `unavailable` tab exactly for
69+
// this reason (session-entities.ts: "closing tabs because a laptop slept is the bug here").
70+
await window.transport.disconnect()
71+
72+
// While asleep, a THIRD client archives the watched session directly against the shared mock
73+
// state -- no event fires here to tell this page, since its connection is down.
74+
await window.page.evaluate(
75+
async ({ SERVER, sessionID }) => {
76+
const response = await fetch(`${SERVER}/api/session/${sessionID}/archive`, {
77+
method: "POST",
78+
headers: { "content-type": "application/json" },
79+
body: JSON.stringify({ requestID: "sleep-resume-archive-1" }),
80+
})
81+
if (!response.ok) throw new Error(`archive failed: ${response.status}`)
82+
},
83+
{ SERVER, sessionID: sessionWatched.id },
84+
)
85+
86+
// The tab must NOT have moved yet -- nothing told this page anything happened.
87+
await expect(tabWatched).toBeVisible()
88+
89+
// The laptop wakes: a fresh fetch to the event endpoint reconnects, and sse-transport.ts's own
90+
// mock emits a synthetic `server.connected` frame on every new connection (matching the real
91+
// server) -- session-entities-sync.tsx's `everConnected` flag treats a SECOND `server.connected`
92+
// as a reconnect and re-runs `runSnapshot()`, which is what should catch this session up.
93+
// `after` filters on connection ID (a sequence counter), not a timestamp -- the ID of the
94+
// connection that just dropped is exactly the threshold for "the next, genuinely new one."
95+
await window.transport.waitForConnection({ after: initialConnection.id, timeout: 15000 })
96+
97+
await expect(tabWatched).toHaveCount(0)
98+
await expect(tabStable).toBeVisible()
99+
100+
// Durable across a real reload too, not just this instance's DOM.
101+
await window.page.reload()
102+
await expect(tabWatched).toHaveCount(0)
103+
await expect(tabStable).toBeVisible()
104+
})

0 commit comments

Comments
 (0)