mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(app): recover child session permissions after reconnect (#65120)
This commit is contained in:
committed by
GitHub
Unverified
parent
10e26d9d6c
commit
f0df6070f9
@@ -551,6 +551,98 @@ test("loads a running subagent's question without polling idle subagents on ever
|
||||
expect(forms.toSorted()).toEqual([`/api/session/${runningID}/form`, `/api/session/${sessionID}/form`].toSorted())
|
||||
})
|
||||
|
||||
test("recovers a running child session's permission on load and across reconnects without polling idle subagents", async ({
|
||||
page,
|
||||
}) => {
|
||||
const childID = "ses_request_running_child"
|
||||
const idleIDs = Array.from({ length: 5 }, (_, index) => `ses_request_idle_perm_${index}`)
|
||||
const replies: { sessionID: string; permissionID: string; body: unknown }[] = []
|
||||
const child = { idle: false }
|
||||
|
||||
const childPermission = (id: string, command: string) => ({
|
||||
id,
|
||||
sessionID: childID,
|
||||
action: "shell",
|
||||
resources: [command],
|
||||
metadata: {},
|
||||
save: [],
|
||||
})
|
||||
|
||||
const childPermissions = [childPermission("perm_child_initial", "git status")]
|
||||
|
||||
const sessionPermissions = {
|
||||
[sessionID]: [],
|
||||
[childID]: childPermissions,
|
||||
}
|
||||
|
||||
const transport = await installSseTransport(page, { server: SERVER, retry: 20 })
|
||||
await mockWorkspace(page, {
|
||||
name: "RequestDocks",
|
||||
directory,
|
||||
sessions: [
|
||||
{ id: sessionID, title },
|
||||
{ id: childID, title: "Running child", parentID: sessionID },
|
||||
...idleIDs.map((id) => ({ id, title: id, parentID: sessionID })),
|
||||
],
|
||||
seed: { tabs: [sessionID] },
|
||||
sessionStatus: () => ({ [childID]: { type: child.idle ? "idle" : "running" } }),
|
||||
sessionPermissions,
|
||||
onPermissionReply: (reply) => replies.push(reply),
|
||||
})
|
||||
|
||||
// Idle subagents whose worktrees were deleted must not be polled for permissions.
|
||||
await page.route(/\/api\/session\/ses_request_idle_perm_\d+\/permission$/, (route) =>
|
||||
route.fulfill({ status: 404, json: { message: "Location not found" } }),
|
||||
)
|
||||
|
||||
const permissionGets: string[] = []
|
||||
page.on("request", (request) => {
|
||||
const path = new URL(request.url()).pathname
|
||||
|
||||
if (request.method() === "GET" && path.startsWith("/api/session/") && path.endsWith("/permission"))
|
||||
permissionGets.push(path)
|
||||
})
|
||||
|
||||
await page.goto(sessionHref(sessionID))
|
||||
const first = await transport.waitForConnection()
|
||||
await expectSessionTitle(page, title)
|
||||
|
||||
const permission = page.locator('[data-component="dock-prompt"][data-kind="permission"]')
|
||||
const composer = page.locator('[data-component="composer"]')
|
||||
await expect(permission).toBeVisible()
|
||||
await expect(permission.getByText("git status")).toBeVisible()
|
||||
await expect(composer).toHaveCount(0)
|
||||
|
||||
// Resolved while offline and the child finished: reconnect must clear the cached request.
|
||||
childPermissions.length = 0
|
||||
child.idle = true
|
||||
await transport.disconnect()
|
||||
const second = await transport.waitForConnection({ after: first.id })
|
||||
await expect(permission).toHaveCount(0)
|
||||
await expect(composer).toBeVisible()
|
||||
|
||||
// Asked while offline with no `permission.asked` event: reconnect must recover it for the child.
|
||||
child.idle = false
|
||||
childPermissions.push(childPermission("perm_child_reconnect", "git diff"))
|
||||
await transport.disconnect()
|
||||
await transport.waitForConnection({ after: second.id })
|
||||
await expect(permission).toBeVisible()
|
||||
await expect(permission.getByText("git diff")).toBeVisible()
|
||||
|
||||
const reply = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === `/api/session/${childID}/permission/perm_child_reconnect/reply`,
|
||||
)
|
||||
|
||||
await permission.getByRole("button", { name: "Allow once" }).click()
|
||||
expect((await reply).status()).toBe(204)
|
||||
expect(replies).toEqual([{ sessionID: childID, permissionID: "perm_child_reconnect", body: { decision: "once" } }])
|
||||
await expect(permission).toHaveCount(0)
|
||||
await expect(composer).toBeVisible()
|
||||
expect(permissionGets.filter((path) => path.includes("ses_request_idle_perm_"))).toEqual([])
|
||||
})
|
||||
|
||||
test("restores the draft caret before typing after a request dock closes", async ({ page }) => {
|
||||
const transport = await installSseTransport(page, { server: SERVER, retry: 20 })
|
||||
await mockServer(page, { forms: [] })
|
||||
|
||||
@@ -12,7 +12,12 @@ import { useServerSDK } from "@/runtime/server/client"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { projectSettingsKey, useSettings } from "@/settings/model"
|
||||
import { useWorkspaceLocation } from "@/workspaces/location"
|
||||
import { sessionPermissionRequest, sessionFormRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
import {
|
||||
sessionFormRequest,
|
||||
sessionMayHoldRequests,
|
||||
sessionPermissionRequest,
|
||||
sessionTreeIDs,
|
||||
} from "@/session/requests/session-request-tree"
|
||||
import { createWebSearchRequest } from "./websearch"
|
||||
import { createSessionBackground, mergeJobList } from "@/session/requests/background"
|
||||
import { createSteerBackground } from "@/session/requests/steer-background"
|
||||
@@ -51,20 +56,16 @@ export function createSessionRequestModel() {
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
const id = params.id
|
||||
|
||||
if (!id || serverSDK.connection.status() !== "connected") return
|
||||
void Promise.all([data.shell.sync({ directory: sdk().directory }), data.session.permission.sync(id)]).catch(
|
||||
() => undefined,
|
||||
)
|
||||
if (!params.id || serverSDK.connection.status() !== "connected") return
|
||||
void data.shell.sync({ directory: sdk().directory }).catch(() => undefined)
|
||||
})
|
||||
|
||||
// Only a running Session can hold a pending form, and events keep loaded forms current. Comparing by value
|
||||
// keeps every session update in a large subagent tree from re-requesting forms.
|
||||
const formSessions = createMemo(
|
||||
// Permissions and forms are per Session, so each one in the tree that may hold a request is read. Comparing by value
|
||||
// keeps every session update in a large subagent tree from re-requesting them.
|
||||
const requestSessions = createMemo(
|
||||
() =>
|
||||
sessionTreeIDs(data.session.list(), params.id).filter(
|
||||
(id) => id === params.id || data.session.status(id) === "running",
|
||||
(id) => id === params.id || sessionMayHoldRequests(data, id),
|
||||
),
|
||||
[],
|
||||
{ equals: (a, b) => a.join() === b.join() },
|
||||
@@ -72,7 +73,12 @@ export function createSessionRequestModel() {
|
||||
|
||||
createEffect(() => {
|
||||
if (serverSDK.connection.status() !== "connected") return
|
||||
void Promise.all(formSessions().map((sessionID) => data.session.form.sync(sessionID))).catch(() => undefined)
|
||||
void Promise.all(
|
||||
requestSessions().flatMap((sessionID) => [
|
||||
data.session.permission.sync(sessionID),
|
||||
data.session.form.sync(sessionID),
|
||||
]),
|
||||
).catch(() => undefined)
|
||||
})
|
||||
|
||||
const formRequest = createMemo((): FormInfo | undefined => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { FormInfo, PermissionRequest, SessionInfo } from "@opencode/client/promise"
|
||||
import type { Data } from "@opencode/client/solid"
|
||||
|
||||
function sessionTreeRequest<T>(
|
||||
session: SessionInfo[],
|
||||
@@ -49,6 +50,17 @@ export function sessionTreeIDs(session: SessionInfo[], sessionID?: string) {
|
||||
return ids
|
||||
}
|
||||
|
||||
// Only a running Session can hold a pending permission or form, and events keep loaded requests current, so idle
|
||||
// subagents are never read. One that still has cached requests is read too, so a reconnect clears requests answered
|
||||
// while the client was offline.
|
||||
export function sessionMayHoldRequests(data: Data, sessionID: string) {
|
||||
return (
|
||||
data.session.status(sessionID) === "running" ||
|
||||
!!data.session.permission.list(sessionID)?.length ||
|
||||
!!data.session.form.list(sessionID)?.length
|
||||
)
|
||||
}
|
||||
|
||||
export function sessionPermissionRequest(
|
||||
session: SessionInfo[],
|
||||
request: Record<string, PermissionRequest[] | undefined> | ((sessionID: string) => PermissionRequest[] | undefined),
|
||||
|
||||
@@ -14,7 +14,12 @@ import { pathKey } from "@/workspaces/path-key"
|
||||
import { parseHomeSessionIndex } from "@/home/sessions/index"
|
||||
import { rawTime } from "@/runtime/server/data"
|
||||
import { mergeRootSessionIndex } from "@/runtime/server/session-index"
|
||||
import { sessionFormRequest, sessionPermissionRequest, sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
import {
|
||||
sessionFormRequest,
|
||||
sessionMayHoldRequests,
|
||||
sessionPermissionRequest,
|
||||
sessionTreeIDs,
|
||||
} from "@/session/requests/session-request-tree"
|
||||
import { notifySessionTabsRemoved } from "./session-events"
|
||||
import { errorMessage } from "@/shell/layout/helpers"
|
||||
import { showToast } from "@/shell/notifications/toast"
|
||||
@@ -270,14 +275,16 @@ export function createSessionInbox(options: { archived?: boolean } = {}) {
|
||||
|
||||
const entry = byKey().get(effect.key)
|
||||
|
||||
void Promise.allSettled(
|
||||
entry
|
||||
? [
|
||||
Promise.try(() => entry.ctx.data.session.permission.sync(entry.session.id)),
|
||||
Promise.try(() => entry.ctx.data.session.form.sync(entry.session.id)),
|
||||
]
|
||||
: [],
|
||||
).then(() => dispatchSettle({ type: "requests.settled", key: effect.key }))
|
||||
const requests = entry
|
||||
? [...new Set([entry.session.id, ...entry.ctx.data.session.family(entry.session.id)])]
|
||||
.filter((id) => id === entry.session.id || sessionMayHoldRequests(entry.ctx.data, id))
|
||||
.flatMap((id) => [
|
||||
Promise.try(() => entry.ctx.data.session.permission.sync(id)),
|
||||
Promise.try(() => entry.ctx.data.session.form.sync(id)),
|
||||
])
|
||||
: []
|
||||
|
||||
void Promise.allSettled(requests).then(() => dispatchSettle({ type: "requests.settled", key: effect.key }))
|
||||
}
|
||||
|
||||
// Synchronous, so a warm cache settles before the first paint without flashing the loader. A server that never
|
||||
|
||||
@@ -34,7 +34,7 @@ import { adjacentTabKey, mergeVisibleTabOrder } from "./tab-order"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { Dialog, DialogFooter, DialogHeader, DialogTitleGroup } from "@opencode/ui/dialog"
|
||||
import { sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
import { sessionMayHoldRequests, sessionTreeIDs } from "@/session/requests/session-request-tree"
|
||||
import { sessionTitle } from "@/session/title"
|
||||
import { errorMessage } from "@/shell/layout/helpers"
|
||||
import { notifySessionTabsRemoved } from "./session-events"
|
||||
@@ -513,16 +513,19 @@ export function createSessionRowNavigation(input: {
|
||||
|
||||
/** Loads what an unselected session row shows: metadata, and the inbox and requests that keep it busy or waiting. */
|
||||
export function syncInactiveSession(ctx: ServerCtx, id: string) {
|
||||
const running = [id, ...ctx.data.session.family(id)].some(
|
||||
(sessionID) => ctx.data.session.status(sessionID) === "running",
|
||||
const requestIDs = [...new Set([id, ...ctx.data.session.family(id)])].filter((sessionID) =>
|
||||
sessionMayHoldRequests(ctx.data, sessionID),
|
||||
)
|
||||
|
||||
void Promise.allSettled([
|
||||
ctx.data.session.sync(id, { children: true }),
|
||||
// The selected timeline loads the transcript; inactive tabs need metadata and the inbox,
|
||||
// whose waiting work keeps the tab busy. Only a running session can wait on a permission
|
||||
// or form, and reading either boots the session's location on the server.
|
||||
...(running ? [ctx.data.session.permission.sync(id), ctx.data.session.form.sync(id)] : []),
|
||||
// whose waiting work keeps the tab busy. Reading a permission or form boots the session's
|
||||
// location on the server, so only sessions that may hold one are read.
|
||||
...requestIDs.flatMap((sessionID) => [
|
||||
ctx.data.session.permission.sync(sessionID),
|
||||
ctx.data.session.form.sync(sessionID),
|
||||
]),
|
||||
ctx.data.session.pending.sync(id),
|
||||
])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user