Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 167 additions & 0 deletions packages/app/src/context/global-sync/bootstrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,173 @@ describe("bootstrapDirectory", () => {
}
})

test("skips pending interaction entries when warm session lookup returns 404", async () => {
const directory = "/tmp/project"
const queryClient = new QueryClient()
const [store, setStore] = createStore(createState())
setStore("permission", "ses_missing", [
{
id: "perm_old",
sessionID: "ses_missing",
permission: "edit",
patterns: ["/tmp/old.txt"],
metadata: {},
always: ["/tmp/old.txt"],
} as any,
])
setStore("question", "ses_missing", [
{
id: "que_old",
sessionID: "ses_missing",
questions: [{ question: "Old?", header: "Old", options: [{ label: "Old", description: "old" }] }],
} as any,
])
setStore("blocker", "ses_missing", [
{
kind: "question",
status: "awaiting_user",
sessionID: "ses_missing",
requestID: "que_old",
request: {
id: "que_old",
sessionID: "ses_missing",
questions: [{ question: "Old?", header: "Old", options: [{ label: "Old", description: "old" }] }],
},
armedAt: 1,
updatedAt: 1,
} as any,
])

const notFound = { name: "NotFoundError", response: { status: 404 } }
const validSession = {
id: "ses_valid",
title: "Valid session",
directory,
version: "test",
time: { created: 1, updated: 1 },
}
const sdk = {
app: { agents: async () => ({ data: [] }) },
config: { get: async () => ({ data: {} as Config }) },
session: {
status: async () => ({ data: {} }),
get: async ({ sessionID }: { sessionID: string }) => {
if (sessionID === "ses_missing") throw notFound
return { data: validSession }
},
},
project: { current: async () => ({ data: { id: "project-1" } }) },
path: { get: async () => ({ data: { state: "", config: "", worktree: "", directory, home: "" } as Path }) },
vcs: { get: async () => ({ data: undefined }) },
command: { list: async () => ({ data: [] }) },
permission: {
list: async () => ({
data: [
{
id: "perm_missing",
sessionID: "ses_missing",
permission: "edit",
patterns: ["/tmp/missing.txt"],
metadata: {},
always: ["/tmp/missing.txt"],
},
{
id: "perm_valid",
sessionID: "ses_valid",
permission: "edit",
patterns: ["/tmp/valid.txt"],
metadata: {},
always: ["/tmp/valid.txt"],
},
],
}),
},
question: {
list: async () => ({
data: [
{
id: "que_missing",
sessionID: "ses_missing",
questions: [
{ question: "Missing?", header: "Missing", options: [{ label: "No", description: "missing" }] },
],
},
{
id: "que_valid",
sessionID: "ses_valid",
questions: [{ question: "Valid?", header: "Valid", options: [{ label: "Yes", description: "valid" }] }],
},
],
}),
},
blocker: {
list: async () => ({
data: [
{
kind: "question",
status: "awaiting_user",
sessionID: "ses_missing",
requestID: "que_missing",
request: {
id: "que_missing",
sessionID: "ses_missing",
questions: [
{ question: "Missing?", header: "Missing", options: [{ label: "No", description: "missing" }] },
],
},
armedAt: 1,
updatedAt: 1,
},
{
kind: "question",
status: "awaiting_user",
sessionID: "ses_valid",
requestID: "que_valid",
request: {
id: "que_valid",
sessionID: "ses_valid",
questions: [{ question: "Valid?", header: "Valid", options: [{ label: "Yes", description: "valid" }] }],
},
armedAt: 2,
updatedAt: 2,
},
],
}),
},
mcp: { status: async () => ({ data: {} }) },
provider: { list: async () => ({ data: { all: [], connected: [], default: {} } }) },
} as any

await bootstrapDirectory({
directory,
sdk,
store,
setStore,
vcsCache: createVcsCache(),
loadSessions: () => undefined,
translate: (key) => key,
global: {
config: {} as Config,
path: { state: "", config: "", worktree: "", directory: "", home: "" } as Path,
project: [] as Project[],
provider: { all: [], connected: [], default: {} },
},
queryClient,
})

await waitFor(() => store.session.some((session) => session.id === "ses_valid"))
await waitFor(() => store.permission.ses_valid?.length === 1)
await waitFor(() => store.question.ses_valid?.length === 1)
await waitFor(() => store.blocker.ses_valid?.length === 1)

expect(store.permission.ses_missing ?? []).toEqual([])
expect(store.question.ses_missing ?? []).toEqual([])
expect(store.blocker.ses_missing ?? []).toEqual([])
expect(store.permission.ses_valid?.map((entry) => entry.id)).toEqual(["perm_valid"])
expect(store.question.ses_valid?.map((entry) => entry.id)).toEqual(["que_valid"])
expect(store.blocker.ses_valid?.map((entry) => entry.requestID)).toEqual(["que_valid"])
})

test("keeps active status events that arrive before the status snapshot resolves", async () => {
const directory = "/tmp/project"
const queryClient = new QueryClient()
Expand Down
87 changes: 60 additions & 27 deletions packages/app/src/context/global-sync/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import type {
Config,
OpencodeClient,
Expand Down Expand Up @@ -60,6 +60,14 @@
return list.filter((item): item is PromiseRejectedResult => item.status === "rejected").map((item) => item.reason)
}

function isNotFoundError(error: unknown) {
if (!error || typeof error !== "object") return false
const value = error as { name?: unknown; status?: unknown; statusCode?: unknown; response?: { status?: unknown } }
if (value.name === "NotFoundError") return true
if (value.status === 404 || value.statusCode === 404) return true
return value.response?.status === 404
}

const providerRev = new Map<string, number>()

export function clearProviderRev(directory: string) {
Expand Down Expand Up @@ -179,7 +187,10 @@
)
}

function sameSessionStatus(a: State["session_status"][string] | undefined, b: State["session_status"][string] | undefined) {
function sameSessionStatus(
a: State["session_status"][string] | undefined,
b: State["session_status"][string] | undefined,
) {
return JSON.stringify(a) === JSON.stringify(b)
}

Expand All @@ -206,16 +217,30 @@
}) {
const known = new Set(input.store.session.map((item) => item.id))
const ids = [...new Set(input.ids)].filter((id) => !!id && !known.has(id))
if (ids.length === 0) return Promise.resolve()
const warmed = new Set(input.store.session.map((item) => item.id))
const missing = new Set<string>()
if (ids.length === 0) return Promise.resolve({ warmed, missing })
return Promise.all(
ids.map((sessionID) =>
retry(() => input.sdk.session.get({ sessionID })).then((x) => {
const session = x.data
if (!session?.id) return
mergeSession(input.setStore, session)
}),
retry(() => input.sdk.session.get({ sessionID }))
.then((x) => {
const session = x.data
if (!session?.id) return
warmed.add(session.id)
mergeSession(input.setStore, session)
})
.catch((err) => {
if (!isNotFoundError(err)) throw err
missing.add(sessionID)
}),
),
).then(() => undefined)
).then(() => ({ warmed, missing }))
}

function filterGroupedByWarmSessions<T>(grouped: Record<string, T[]>, result: { missing: Set<string> }) {
const filtered = { ...grouped }
for (const sessionID of result.missing) delete filtered[sessionID]
return filtered
}

const inactiveQueryFn = async () => null
Expand Down Expand Up @@ -373,11 +398,14 @@
retry(() =>
input.sdk.permission.list().then((x) => {
const ids = (x.data ?? []).map((perm) => perm?.sessionID).filter((id): id is string => !!id)
const grouped = groupBySession(
(x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID),
)
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then(() =>
batch(() => {
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then((warm) => {
const grouped = filterGroupedByWarmSessions(
groupBySession(
(x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID),
),
warm,
)
return batch(() => {
for (const sessionID of Object.keys(input.store.permission)) {
if (grouped[sessionID]) continue
input.setStore("permission", sessionID, [])
Expand All @@ -392,17 +420,20 @@
),
)
}
}),
)
})
})
}),
),
() =>
retry(() =>
input.sdk.question.list().then((x) => {
const ids = (x.data ?? []).map((question) => question?.sessionID).filter((id): id is string => !!id)
const grouped = groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID))
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then(() =>
batch(() => {
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then((warm) => {
const grouped = filterGroupedByWarmSessions(
groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID)),
warm,
)
return batch(() => {
for (const sessionID of Object.keys(input.store.question)) {
if (grouped[sessionID]) continue
input.setStore("question", sessionID, [])
Expand All @@ -417,17 +448,17 @@
),
)
}
}),
)
})
})
}),
),
() =>
retry(() =>
input.sdk.blocker.list().then((x) => {
const ids = (x.data ?? []).map((blocker) => blocker?.sessionID).filter((id): id is string => !!id)
const grouped = groupBlockersBySession(x.data ?? [])
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then(() =>
batch(() => {
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then((warm) => {
const grouped = filterGroupedByWarmSessions(groupBlockersBySession(x.data ?? []), warm)
return batch(() => {
for (const sessionID of Object.keys(input.store.blocker)) {
if (grouped[sessionID]) continue
input.setStore("blocker", sessionID, [])
Expand All @@ -436,11 +467,14 @@
input.setStore(
"blocker",
sessionID,
reconcile(blockers.sort((a, b) => cmp(a.requestID, b.requestID)), { key: "requestID" }),
reconcile(
blockers.sort((a, b) => cmp(a.requestID, b.requestID)),
{ key: "requestID" },
),
)
}
}),
)
})
})
}),
),
() => Promise.resolve(input.loadSessions(input.directory)),
Expand All @@ -466,6 +500,5 @@
}

if (loading && errs.length === 0 && slowErrs.length === 0) input.setStore("status", "complete")

})()
}
23 changes: 22 additions & 1 deletion packages/opencode/src/permission/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ export namespace Permission {
export interface Interface {
readonly ask: (input: z.infer<typeof AskInput>) => Effect.Effect<void, Error>
readonly reply: (input: z.infer<typeof ReplyInput>) => Effect.Effect<void>
readonly clearSession: (
sessionID: SessionID,
reason: "session_deleted" | "session_archived" | "dangling_session",
) => Effect.Effect<void>
readonly list: () => Effect.Effect<Request[]>
}

Expand Down Expand Up @@ -285,12 +289,29 @@ export namespace Permission {
}
})

const clearSession = Effect.fn("Permission.clearSession")(function* (
sessionID: SessionID,
_reason: "session_deleted" | "session_archived" | "dangling_session",
) {
const { pending } = yield* InstanceState.get(state)
for (const [id, item] of Array.from(pending.entries())) {
if (item.info.sessionID !== sessionID) continue
pending.delete(id)
yield* bus.publish(Event.Replied, {
sessionID: item.info.sessionID,
requestID: item.info.id,
reply: "reject",
})
yield* Deferred.fail(item.deferred, new RejectedError())
}
})

const list = Effect.fn("Permission.list")(function* () {
const pending = (yield* InstanceState.get(state)).pending
return Array.from(pending.values(), (item) => item.info)
})

return Service.of({ ask, reply, list })
return Service.of({ ask, reply, clearSession, list })
}),
)

Expand Down
Loading
Loading