Skip to content

Commit 7163804

Browse files
committed
fix(app): resync active sessions and approve store-synced requests
1 parent fb7f250 commit 7163804

2 files changed

Lines changed: 91 additions & 17 deletions

File tree

‎packages/app/e2e/regression/remote-session-settings.spec.ts‎

Lines changed: 69 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ test("session settings use the remote server context", async ({ page }) => {
1919
// Server A has no tab and is never visited: a pending request there proves
2020
// one toggle sweeps every connected server, not just the focused one.
2121
await mockServers(page, permissionRequests, permissionResponses, {
22-
[serverA]: [pendingPermission("permission-pending-a", sessionA.id)],
22+
pending: { [serverA]: [pendingPermission("permission-pending-a", sessionA.id)] },
2323
})
2424
await configureServers(page)
2525

@@ -163,9 +163,14 @@ test("auto-accept sweeps again after a reconnect", async ({ page }) => {
163163
const permissionResponses: PermissionResponse[] = []
164164
const pendingA: MockPermission[] = []
165165
const listFailures: Record<string, number> = {}
166+
const sessionGets: string[] = []
166167
await installSseTransport(page, { server: serverB })
167168
const transport = await installSseTransport(page, { server: serverA, retry: 20 })
168-
await mockServers(page, permissionRequests, permissionResponses, { [serverA]: pendingA }, listFailures)
169+
await mockServers(page, permissionRequests, permissionResponses, {
170+
pending: { [serverA]: pendingA },
171+
listFailures,
172+
sessionGets,
173+
})
169174
await configureServers(page, [{ type: "session", server: serverA, sessionId: sessionA.id }])
170175

171176
await page.goto(`/server/${base64Encode(serverA)}/session/${sessionA.id}`)
@@ -192,6 +197,7 @@ test("auto-accept sweeps again after a reconnect", async ({ page }) => {
192197
// deliver the reply.
193198
pendingA.push(pendingPermission("permission-offline-a", sessionA.id))
194199
listFailures[serverA] = 1
200+
const syncsBeforeReconnect = sessionGets.length
195201
await transport.disconnect()
196202
await transport.waitForConnection({ after: first.id })
197203

@@ -206,6 +212,43 @@ test("auto-accept sweeps again after a reconnect", async ({ page }) => {
206212
body: { reply: "once" },
207213
},
208214
])
215+
// The reconnect sweep must resync active sessions instead of trusting
216+
// cached locations, since another client may have moved them meanwhile.
217+
expect(sessionGets.slice(syncsBeforeReconnect)).toContain(sessionA.id)
218+
})
219+
220+
test("auto-accept approves a request discovered by opening a session", async ({ page }) => {
221+
const permissionRequests: string[] = []
222+
const permissionResponses: PermissionResponse[] = []
223+
await installSseTransport(page, { server: serverA })
224+
await installSseTransport(page, { server: serverB })
225+
// The request is only served from the per-session permission list, so it
226+
// reaches the client through the store sync when the session view opens,
227+
// never through a location sweep or an event.
228+
await mockServers(page, permissionRequests, permissionResponses, {
229+
sessionPending: { [sessionA.id]: [pendingPermission("permission-synced-a", sessionA.id)] },
230+
})
231+
await configureServers(page, [{ type: "session", server: serverA, sessionId: sessionA.id }])
232+
233+
await page.goto(`/server/${base64Encode(serverA)}/session/${sessionA.id}`)
234+
await expect(page.getByRole("heading", { name: sessionA.title, exact: true })).toBeVisible()
235+
236+
await page.keyboard.press("Control+,")
237+
const autoAccept = page.locator(".settings-dialog").locator('[data-action="settings-auto-accept-permissions"]')
238+
await autoAccept.locator('[data-slot="switch-control"]').click()
239+
await expect(autoAccept.getByRole("switch")).toBeChecked()
240+
241+
await expect
242+
.poll(() => permissionResponses)
243+
.toEqual([
244+
{
245+
origin: serverA,
246+
directory: undefined,
247+
sessionID: sessionA.id,
248+
permissionID: "permission-synced-a",
249+
body: { reply: "once" },
250+
},
251+
])
209252
})
210253

211254
type PermissionResponse = {
@@ -239,12 +282,22 @@ async function configureServers(page: Page, tabs: { type: "session"; server: str
239282
)
240283
}
241284

285+
type MockServerOptions = {
286+
// Pending requests served from /api/permission/request, keyed by origin.
287+
pending?: Record<string, MockPermission[]>
288+
// Pending requests served from /api/session/:id/permission, keyed by session ID.
289+
sessionPending?: Record<string, MockPermission[]>
290+
// Counts of /api/permission/request calls to fail with a 500, keyed by origin.
291+
listFailures?: Record<string, number>
292+
// Records /api/session/:id GETs so tests can assert session resyncs.
293+
sessionGets?: string[]
294+
}
295+
242296
async function mockServers(
243297
page: Page,
244298
permissionRequests: string[],
245299
permissionResponses: PermissionResponse[] = [],
246-
pendingPermissions: Record<string, MockPermission[]> = {},
247-
listFailures: Record<string, number> = {},
300+
options: MockServerOptions = {},
248301
) {
249302
await page.route("**/*", async (route) => {
250303
const url = new URL(route.request().url())
@@ -262,8 +315,12 @@ async function mockServers(
262315
permissionID: response[2]!,
263316
body: route.request().postDataJSON(),
264317
})
265-
return json(route, true)
318+
// The generated client requires exactly 204 for a successful reply.
319+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
266320
}
321+
const sessionPermission = url.pathname.match(/^\/api\/session\/([^/]+)\/permission$/)
322+
if (route.request().method() === "GET" && sessionPermission)
323+
return json(route, { data: options.sessionPending?.[sessionPermission[1]!] ?? [] })
267324
if (requestDirectory && requestDirectory !== directory) return json(route, { name: "InvalidDirectory" }, 500)
268325
if (url.pathname === "/api/provider")
269326
return json(route, {
@@ -281,12 +338,12 @@ async function mockServers(
281338
if (url.pathname === "/api/agent") return json(route, { location: { directory }, data: [] })
282339
if (url.pathname === "/api/permission/request") {
283340
permissionRequests.push(url.toString())
284-
const failures = listFailures[url.origin] ?? 0
341+
const failures = options.listFailures?.[url.origin] ?? 0
285342
if (failures > 0) {
286-
listFailures[url.origin] = failures - 1
343+
options.listFailures![url.origin] = failures - 1
287344
return json(route, { name: "Internal" }, 500)
288345
}
289-
return json(route, { location: { directory }, data: pendingPermissions[url.origin] ?? [] })
346+
return json(route, { location: { directory }, data: options.pending?.[url.origin] ?? [] })
290347
}
291348
if (["/api/command", "/api/reference", "/api/question/request"].includes(url.pathname))
292349
return json(route, { location: { directory }, data: [] })
@@ -311,7 +368,10 @@ async function mockServers(
311368
if (url.pathname === "/api/session/active")
312369
return json(route, { data: Object.fromEntries(sessions.map((session) => [session.id, { type: "running" }])) })
313370
const currentSessionInfo = sessions.find((session) => url.pathname === `/api/session/${session.id}`)
314-
if (currentSessionInfo) return json(route, { data: currentSession(currentSessionInfo) })
371+
if (currentSessionInfo) {
372+
options.sessionGets?.push(currentSessionInfo.id)
373+
return json(route, { data: currentSession(currentSessionInfo) })
374+
}
315375
if (sessions.some((session) => url.pathname === `/api/session/${session.id}/message`))
316376
return json(route, { data: [], cursor: {} })
317377
if (sessions.some((session) => url.pathname === `/api/session/${session.id}/inbox`))

‎packages/app/src/session/requests/auto-approve.ts‎

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,17 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
3232
void sweepWithRetry(generation, 0)
3333
})
3434

35+
// Approves pending requests that reach the local store, which is how a
36+
// previously unknown idle session's requests surface when its view opens
37+
// and syncs them. Store changes cannot re-trigger the network sweep: it
38+
// deliberately reads them after an await, outside Solid tracking.
39+
createEffect(() => {
40+
if (!enabled()) return
41+
for (const session of input.data.session.list()) {
42+
for (const request of input.data.session.permission.list(session.id) ?? []) approve(request)
43+
}
44+
})
45+
3546
// An incomplete sweep leaves pending requests hidden with no later trigger
3647
// to recover them, so retry it a bounded number of times. A newer sweep
3748
// supersedes scheduled retries.
@@ -70,15 +81,18 @@ export function createPermissionAutoApprover(input: { sdk: ServerSDK; data: Data
7081
async function sweepLocations() {
7182
const active = await input.sdk.api.session.active().catch(() => undefined)
7283
const ids = Object.keys(active ?? {})
84+
// Resync every active session rather than trusting cached info: another
85+
// client may have moved one while this client was disconnected, and the
86+
// cached location would list permissions from the old location. A failed
87+
// resync falls back to the cached location and marks the sweep incomplete.
7388
const synced = await Promise.all(
74-
ids
75-
.filter((id) => !input.data.session.get(id))
76-
.map((id) =>
77-
input.data.session.sync(id).then(
78-
() => true,
79-
() => false,
80-
),
81-
),
89+
ids.map((id) => {
90+
input.data.session.invalidate(id)
91+
return input.data.session.sync(id).then(
92+
() => true,
93+
() => false,
94+
)
95+
}),
8296
)
8397
const locations = [
8498
...ids.flatMap((id) => {

0 commit comments

Comments
 (0)