mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(app): recover missing session locations through location.get
This commit is contained in:
parent
bf50894f4c
commit
8f749fe5f6
13 changed files with 239 additions and 157 deletions
|
|
@ -29,14 +29,6 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
|
|||
if (recover && requests > 1) return route.fallback()
|
||||
return route.fulfill({ status: 500, body: "", headers: { "access-control-allow-origin": "*" } })
|
||||
})
|
||||
await page.route("**/api/location/probe?**", (route) =>
|
||||
route.fulfill({
|
||||
status: 500,
|
||||
json: { _tag: "ServiceUnavailableError", message: "Probe failed" },
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
}),
|
||||
)
|
||||
const probe = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/location/probe")
|
||||
const failure = page.waitForResponse(
|
||||
(response) => new URL(response.url()).pathname === endpoint && response.status() === 500,
|
||||
)
|
||||
|
|
@ -45,11 +37,10 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
|
|||
return (
|
||||
url.pathname === endpoint &&
|
||||
url.searchParams.get("location[directory]") === directory &&
|
||||
(recover ? response.ok() : requests === 3 && response.status() === 500)
|
||||
(recover ? response.ok() : requests >= 3 && response.status() === 500)
|
||||
)
|
||||
})
|
||||
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
|
||||
expect((await probe).status()).toBe(500)
|
||||
await failure
|
||||
await expect(page.getByText("Keep working in this worktree", { exact: true })).toBeVisible()
|
||||
const prompt = page.getByRole("textbox", { name: "Prompt", exact: true })
|
||||
|
|
@ -59,7 +50,7 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
|
|||
await settled
|
||||
await expect(prompt).toBeEditable()
|
||||
await expect(prompt).toHaveText("Continue after reconnecting")
|
||||
expect(requests).toBe(recover ? 2 : 3)
|
||||
expect(requests).toBeGreaterThanOrEqual(recover ? 2 : 3)
|
||||
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole("button", { name: "Choose directory", exact: true })).toHaveCount(0)
|
||||
expect(recovery).toEqual([])
|
||||
|
|
@ -68,6 +59,50 @@ for (const endpoint of ["/api/location", "/api/agent"]) {
|
|||
}
|
||||
}
|
||||
|
||||
for (const error of [
|
||||
{ _tag: "FileNotFoundError", path: "/projects/current", message: "Unrelated file" },
|
||||
{ _tag: "LocationNotFoundError", directory: "/projects/other", message: "Other location" },
|
||||
]) {
|
||||
test(`does not recover from an unrelated 404 (${error._tag}, ${"directory" in error ? error.directory : error.path})`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const recovery = recoveryRequests(page)
|
||||
const directory = "/projects/current"
|
||||
const sessionID = "ses_location_unrelated_404"
|
||||
await mockOpenCodeServer(page, {
|
||||
directory: fixture.directory,
|
||||
project: fixture.project,
|
||||
provider: fixture.provider,
|
||||
sessions: [{ id: sessionID, projectID: fixture.project.id, directory, title: "Unrelated error" }],
|
||||
fileList: () => [],
|
||||
pageMessages: () => ({
|
||||
items: [{ id: "msg_saved", type: "user", text: "Continue in the current worktree", time: { created: 1 } }],
|
||||
}),
|
||||
})
|
||||
await page.route("**/api/location?**", (route) => {
|
||||
if (new URL(route.request().url()).searchParams.get("location[directory]") !== directory) return route.fallback()
|
||||
return route.fulfill({ status: 404, json: error, headers: { "access-control-allow-origin": "*" } })
|
||||
})
|
||||
const failure = page.waitForResponse((response) => {
|
||||
const url = new URL(response.url())
|
||||
return (
|
||||
url.pathname === "/api/location" &&
|
||||
url.searchParams.get("location[directory]") === directory &&
|
||||
response.status() === 404
|
||||
)
|
||||
})
|
||||
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
|
||||
await failure
|
||||
await expect(page.getByText("Continue in the current worktree", { exact: true })).toBeVisible()
|
||||
const prompt = page.getByRole("textbox", { name: "Prompt", exact: true })
|
||||
await expect(prompt).toBeEditable()
|
||||
await prompt.fill("Keep this draft")
|
||||
await expect(prompt).toHaveText("Keep this draft")
|
||||
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
|
||||
expect(recovery).toEqual([])
|
||||
})
|
||||
}
|
||||
|
||||
test("follows a live session move while the agent catalog is still loading", async ({ page }) => {
|
||||
const recovery = recoveryRequests(page)
|
||||
const directory = "/projects/old-tree"
|
||||
|
|
@ -226,7 +261,7 @@ test("ignores an old failed location read after reconnecting", async ({ page })
|
|||
await expect(prompt).toHaveText("Keep typing here")
|
||||
await expect(page.getByText("Session location unavailable", { exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole("button", { name: "Choose directory", exact: true })).toHaveCount(0)
|
||||
expect(requests).toBe(2)
|
||||
expect(requests).toBeGreaterThanOrEqual(2)
|
||||
expect(recovery).toEqual([])
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -22,9 +22,13 @@ test("keeps a session in a removed worktree readable and movable", async ({ page
|
|||
})
|
||||
await page.route("**/api/**", (route) => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.pathname === "/api/location/probe" && url.searchParams.get("directory") === missing)
|
||||
return route.fulfill({ json: { exists: false }, headers: { "access-control-allow-origin": "*" } })
|
||||
if (url.searchParams.get("location[directory]") !== missing) return route.fallback()
|
||||
if (url.pathname === "/api/location")
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
json: { _tag: "LocationNotFoundError", directory: missing, message: `Location not found: ${missing}` },
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
})
|
||||
if (!["/api/location", "/api/agent", "/api/provider", "/api/model", "/api/model/default"].includes(url.pathname))
|
||||
return route.fallback()
|
||||
return route.fulfill({
|
||||
|
|
@ -75,7 +79,7 @@ test("preserves a draft when a worktree disappears and resumes after choosing a
|
|||
const sessionID = "ses_draft_recovery"
|
||||
const session = { id: sessionID, projectID: fixture.project.id, directory: source, title: "Draft recovery" }
|
||||
const transport = await installSseTransport(page, { server: fixture.serverKey })
|
||||
let exists = true
|
||||
let missing = false
|
||||
await mockOpenCodeServer(page, {
|
||||
directory: destination,
|
||||
project: { ...fixture.project, worktree: destination },
|
||||
|
|
@ -86,9 +90,15 @@ test("preserves a draft when a worktree disappears and resumes after choosing a
|
|||
items: [{ id: "msg_draft", type: "user", text: "Saved draft history", time: { created: 1 } }],
|
||||
}),
|
||||
})
|
||||
await page.route("**/api/location/probe?**", (route) =>
|
||||
route.fulfill({ json: { exists }, headers: { "access-control-allow-origin": "*" } }),
|
||||
)
|
||||
await page.route("**/api/location?**", (route) => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.searchParams.get("location[directory]") !== source || !missing) return route.fallback()
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
})
|
||||
})
|
||||
let moves = 0
|
||||
await page.route(`**/api/session/${sessionID}/move`, (route) => {
|
||||
moves++
|
||||
|
|
@ -106,14 +116,18 @@ test("preserves a draft when a worktree disappears and resumes after choosing a
|
|||
await expect(prompt).toBeEditable()
|
||||
await prompt.fill("A draft to keep after moving")
|
||||
const connection = await transport.waitForConnection()
|
||||
const missing = page.waitForResponse((response) => {
|
||||
const missingResponse = page.waitForResponse((response) => {
|
||||
const url = new URL(response.url())
|
||||
return url.pathname === "/api/location/probe" && url.searchParams.get("directory") === source && response.ok()
|
||||
return (
|
||||
url.pathname === "/api/location" &&
|
||||
url.searchParams.get("location[directory]") === source &&
|
||||
response.status() === 404
|
||||
)
|
||||
})
|
||||
exists = false
|
||||
missing = true
|
||||
await transport.close()
|
||||
await transport.waitForConnection({ after: connection.id })
|
||||
await missing
|
||||
await missingResponse
|
||||
await expect(page.getByRole("status")).toContainText("Session location unavailable")
|
||||
await expect(prompt).toHaveCount(0)
|
||||
await expect(page.getByText("Saved draft history", { exact: true })).toBeVisible()
|
||||
|
|
@ -146,7 +160,7 @@ test("preserves a draft when a worktree disappears and resumes after choosing a
|
|||
expect((await secondMove).postDataJSON()).toEqual({ directory: destination })
|
||||
expect(moves).toBe(2)
|
||||
session.directory = destination
|
||||
exists = true
|
||||
missing = false
|
||||
await transport.send({
|
||||
id: "evt_draft_recovery_moved",
|
||||
type: "session.moved",
|
||||
|
|
@ -162,7 +176,7 @@ test("preserves a draft when a worktree disappears and resumes after choosing a
|
|||
test("ignores a stale missing result after the session moves", async ({ page }) => {
|
||||
const source = "/projects/old-worktree"
|
||||
const destination = "/projects/new-worktree"
|
||||
const sessionID = "ses_stale_probe"
|
||||
const sessionID = "ses_stale_location_read"
|
||||
const session = { id: sessionID, projectID: fixture.project.id, directory: source, title: "Moving session" }
|
||||
const requested = Promise.withResolvers<void>()
|
||||
const release = Promise.withResolvers<void>()
|
||||
|
|
@ -174,13 +188,17 @@ test("ignores a stale missing result after the session moves", async ({ page })
|
|||
sessions: [session],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
await page.route("**/api/location/probe?**", async (route) => {
|
||||
if (new URL(route.request().url()).searchParams.get("directory") === source) {
|
||||
await page.route("**/api/location?**", async (route) => {
|
||||
if (new URL(route.request().url()).searchParams.get("location[directory]") === source) {
|
||||
requested.resolve()
|
||||
await release.promise
|
||||
return route.fulfill({ json: { exists: false }, headers: { "access-control-allow-origin": "*" } })
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
})
|
||||
}
|
||||
return route.fulfill({ json: { exists: true }, headers: { "access-control-allow-origin": "*" } })
|
||||
return route.fallback()
|
||||
})
|
||||
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
|
||||
await requested.promise
|
||||
|
|
@ -190,7 +208,9 @@ test("ignores a stale missing result after the session moves", async ({ page })
|
|||
await transport.waitForConnection()
|
||||
const next = page.waitForResponse((response) => {
|
||||
const url = new URL(response.url())
|
||||
return url.pathname === "/api/location/probe" && url.searchParams.get("directory") === destination && response.ok()
|
||||
return (
|
||||
url.pathname === "/api/location" && url.searchParams.get("location[directory]") === destination && response.ok()
|
||||
)
|
||||
})
|
||||
session.directory = destination
|
||||
await transport.send({
|
||||
|
|
@ -203,7 +223,11 @@ test("ignores a stale missing result after the session moves", async ({ page })
|
|||
await next
|
||||
const old = page.waitForResponse((response) => {
|
||||
const url = new URL(response.url())
|
||||
return url.pathname === "/api/location/probe" && url.searchParams.get("directory") === source && response.ok()
|
||||
return (
|
||||
url.pathname === "/api/location" &&
|
||||
url.searchParams.get("location[directory]") === source &&
|
||||
response.status() === 404
|
||||
)
|
||||
})
|
||||
release.resolve()
|
||||
await old
|
||||
|
|
@ -225,12 +249,14 @@ test("moves a removed-worktree session into an existing worktree", async ({ page
|
|||
sessions: [session],
|
||||
pageMessages: () => ({ items: [] }),
|
||||
})
|
||||
await page.route("**/api/location/probe?**", (route) =>
|
||||
route.fulfill({
|
||||
json: { exists: new URL(route.request().url()).searchParams.get("directory") !== source },
|
||||
await page.route("**/api/location?**", (route) => {
|
||||
if (new URL(route.request().url()).searchParams.get("location[directory]") !== source) return route.fallback()
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
json: { _tag: "LocationNotFoundError", directory: source, message: `Location not found: ${source}` },
|
||||
headers: { "access-control-allow-origin": "*" },
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
await page.route(`**/api/session/${sessionID}/move`, (route) => route.fulfill({ status: 204, body: "" }))
|
||||
await page.goto(`/server/${base64Encode(fixture.serverKey)}/session/${sessionID}`)
|
||||
await expect(page.getByRole("status")).toContainText("Session location unavailable")
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { createStore } from "solid-js/store"
|
|||
import { useParams } from "@solidjs/router"
|
||||
import { DataProvider } from "@opencode/session-ui/context"
|
||||
import { SessionUserMessage } from "@opencode/session-ui/message"
|
||||
import { isLocationNotFoundError } from "@opencode/client/promise"
|
||||
import { TextShimmer } from "@opencode/ui/text-shimmer"
|
||||
import { CommentsProvider } from "@/composer/comments"
|
||||
import { readPromptPresentation } from "@/composer/comment-note"
|
||||
|
|
@ -48,12 +49,12 @@ export function TargetSessionRouteContent() {
|
|||
onCleanup(() => {
|
||||
stale = true
|
||||
})
|
||||
void server.ctx.sdk.api.location.probe({ directory }).then(
|
||||
(result) => {
|
||||
if (!stale && !result.exists)
|
||||
void server.ctx.sdk.api.location.get({ location: { directory } }).then(
|
||||
() => undefined,
|
||||
(error) => {
|
||||
if (!stale && isLocationNotFoundError(error) && error.directory === directory)
|
||||
setLocationState("missing", { sessionID: session.id, projectID: project.id, directory })
|
||||
},
|
||||
() => undefined,
|
||||
)
|
||||
})
|
||||
const missing = createMemo(() => {
|
||||
|
|
|
|||
|
|
@ -60,10 +60,6 @@ export interface ServerApi<E = never> {
|
|||
readonly connect: ServerConnectOperation<E>
|
||||
}
|
||||
|
||||
export type LocationProbeInput = { readonly directory: string }
|
||||
export type LocationProbeOutput = { readonly exists: boolean }
|
||||
export type LocationProbeOperation<E = never> = (input: LocationProbeInput) => Effect.Effect<LocationProbeOutput, E>
|
||||
|
||||
export type LocationGetInput = { readonly location?: { readonly directory?: string | undefined } | undefined }
|
||||
export type LocationGetOutput = Location.PublicInfo
|
||||
export type LocationGetOperation<E = never> = (input?: LocationGetInput) => Effect.Effect<LocationGetOutput, E>
|
||||
|
|
@ -72,7 +68,6 @@ export type LocationReloadOutput = void
|
|||
export type LocationReloadOperation<E = never> = () => Effect.Effect<LocationReloadOutput, E>
|
||||
|
||||
export interface LocationApi<E = never> {
|
||||
readonly probe: LocationProbeOperation<E>
|
||||
readonly get: LocationGetOperation<E>
|
||||
readonly reload: LocationReloadOperation<E>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,6 @@ import type {
|
|||
ServerPairOutput,
|
||||
ServerConnectInput,
|
||||
ServerConnectOutput,
|
||||
LocationProbeInput,
|
||||
LocationProbeOutput,
|
||||
LocationGetInput,
|
||||
LocationGetOutput,
|
||||
LocationReloadOutput,
|
||||
|
|
@ -303,11 +301,6 @@ const adaptGroupServer = (raw: RawClient["server.server"]) => ({
|
|||
connect: EndpointServerConnect(raw),
|
||||
})
|
||||
|
||||
const EndpointLocationProbe = (raw: RawClient["server.location"]) => (input: LocationProbeInput) =>
|
||||
preserveEffect<LocationProbeOutput>()(
|
||||
raw["location.probe"]({ query: { directory: input["directory"] } }).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const EndpointLocationGet = (raw: RawClient["server.location"]) => (input?: LocationGetInput) =>
|
||||
preserveEffect<LocationGetOutput>()(
|
||||
raw["location.get"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)),
|
||||
|
|
@ -317,7 +310,6 @@ const EndpointLocationReload = (raw: RawClient["server.location"]) => () =>
|
|||
preserveEffect<LocationReloadOutput>()(raw["location.reload"]({}).pipe(Effect.mapError(mapClientError)))
|
||||
|
||||
const adaptGroupLocation = (raw: RawClient["server.location"]) => ({
|
||||
probe: EndpointLocationProbe(raw),
|
||||
get: EndpointLocationGet(raw),
|
||||
reload: EndpointLocationReload(raw),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,8 +3,6 @@ import type {
|
|||
ServerPairOutput,
|
||||
ServerConnectInput,
|
||||
ServerConnectOutput,
|
||||
LocationProbeInput,
|
||||
LocationProbeOutput,
|
||||
LocationGetInput,
|
||||
LocationGetOutput,
|
||||
LocationReloadOutput,
|
||||
|
|
@ -442,18 +440,6 @@ export function make(options: ClientOptions) {
|
|||
),
|
||||
},
|
||||
location: {
|
||||
probe: (input: LocationProbeInput, requestOptions?: RequestOptions) =>
|
||||
request<LocationProbeOutput>(
|
||||
{
|
||||
method: "GET",
|
||||
path: `/api/location/probe`,
|
||||
query: { directory: input["directory"] },
|
||||
successStatus: 200,
|
||||
declaredStatuses: [400, 401],
|
||||
empty: false,
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
get: (input?: LocationGetInput, requestOptions?: RequestOptions) =>
|
||||
request<LocationGetOutput>(
|
||||
{
|
||||
|
|
@ -461,7 +447,7 @@ export function make(options: ClientOptions) {
|
|||
path: `/api/location`,
|
||||
query: { location: input?.["location"] },
|
||||
successStatus: 200,
|
||||
declaredStatuses: [400, 401],
|
||||
declaredStatuses: [400, 401, 404],
|
||||
empty: false,
|
||||
},
|
||||
requestOptions,
|
||||
|
|
|
|||
|
|
@ -2518,6 +2518,14 @@ export type UnauthorizedError = { readonly _tag: "UnauthorizedError"; readonly m
|
|||
export const isUnauthorizedError = (value: unknown): value is UnauthorizedError =>
|
||||
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "UnauthorizedError"
|
||||
|
||||
export type LocationNotFoundError = {
|
||||
readonly _tag: "LocationNotFoundError"
|
||||
readonly directory: string
|
||||
readonly message: string
|
||||
}
|
||||
export const isLocationNotFoundError = (value: unknown): value is LocationNotFoundError =>
|
||||
typeof value === "object" && value !== null && "_tag" in value && value["_tag"] === "LocationNotFoundError"
|
||||
|
||||
export type ServiceUnavailableError = {
|
||||
readonly _tag: "ServiceUnavailableError"
|
||||
readonly message: string
|
||||
|
|
@ -2742,10 +2750,6 @@ export type ServerConnectInput = { readonly code: { readonly code: string }["cod
|
|||
|
||||
export type ServerConnectOutput = PairingSession
|
||||
|
||||
export type LocationProbeInput = { readonly directory: { readonly directory: string }["directory"] }
|
||||
|
||||
export type LocationProbeOutput = { exists: boolean }
|
||||
|
||||
export type LocationGetInput = {
|
||||
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,9 +66,7 @@ type FormGroups<LocationId extends HttpApiMiddleware.AnyId, LocationService> = R
|
|||
typeof makeFormGroup<LocationId, LocationService>
|
||||
>
|
||||
|
||||
type LocationGroup<LocationId extends HttpApiMiddleware.AnyId, LocationService> = ReturnType<
|
||||
typeof makeLocationGroup<LocationId, LocationService>
|
||||
>
|
||||
type LocationGroup = ReturnType<typeof makeLocationGroup>
|
||||
|
||||
type MixedMiddlewareGroups<
|
||||
LocationId extends HttpApiMiddleware.AnyId,
|
||||
|
|
@ -94,7 +92,7 @@ type ApiGroups<
|
|||
| typeof PersistentPtyGroup
|
||||
| typeof CredentialGroup
|
||||
| LocationGroups<LocationId>
|
||||
| LocationGroup<LocationId, LocationService>
|
||||
| LocationGroup
|
||||
| FormGroups<LocationId, LocationService>
|
||||
| SessionGroups<SessionLocationId, SessionLocationService, FormLocationId, FormLocationService>
|
||||
| MixedMiddlewareGroups<LocationId, LocationService, SessionLocationId, SessionLocationService>
|
||||
|
|
@ -154,7 +152,7 @@ const makeApiFromGroup = <
|
|||
> =>
|
||||
HttpApi.make("server")
|
||||
.add(ServerGroup)
|
||||
.add(makeLocationGroup(locationMiddleware))
|
||||
.add(makeLocationGroup())
|
||||
.add(AgentGroup.middleware(locationMiddleware))
|
||||
.add(PluginGroup.middleware(locationMiddleware))
|
||||
.add(makeSessionGroup(sessionLocationMiddleware, formLocationMiddleware))
|
||||
|
|
|
|||
|
|
@ -129,6 +129,15 @@ export class FileNotFoundError extends Schema.TaggedError<FileNotFoundError>()(
|
|||
{ httpApiStatus: 404 },
|
||||
) {}
|
||||
|
||||
export class LocationNotFoundError extends Schema.TaggedError<LocationNotFoundError>()(
|
||||
"LocationNotFoundError",
|
||||
{
|
||||
directory: Schema.String,
|
||||
message: Schema.String,
|
||||
},
|
||||
{ httpApiStatus: 404 },
|
||||
) {}
|
||||
|
||||
export class AgentNotFoundError extends Schema.TaggedError<AgentNotFoundError>()(
|
||||
"AgentNotFoundError",
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Location } from "@opencode/schema/location"
|
||||
import { Context, Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
||||
import { ServiceUnavailableError } from "../errors.js"
|
||||
import { Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
||||
import { LocationNotFoundError, ServiceUnavailableError } from "../errors.js"
|
||||
|
||||
export const LocationQuery = Schema.Struct({
|
||||
location: Schema.optional(
|
||||
|
|
@ -11,10 +11,6 @@ export const LocationQuery = Schema.Struct({
|
|||
),
|
||||
}).annotate({ identifier: "LocationQuery" })
|
||||
|
||||
const ProbeQuery = Schema.Struct({
|
||||
directory: Schema.String,
|
||||
}).annotate({ identifier: "LocationProbeQuery" })
|
||||
|
||||
export const locationQueryOpenApi = OpenApi.annotations({
|
||||
transform: (operation) => {
|
||||
const parameters = operation.parameters
|
||||
|
|
@ -30,31 +26,16 @@ export const locationQueryOpenApi = OpenApi.annotations({
|
|||
},
|
||||
})
|
||||
|
||||
// Middleware is applied per endpoint: reload acts on every loaded location and
|
||||
// must not boot the caller's location first.
|
||||
export const makeLocationGroup = <LocationId extends HttpApiMiddleware.AnyId, LocationService>(
|
||||
locationMiddleware: Context.Key<LocationId, LocationService>,
|
||||
) =>
|
||||
// Get checks the path before entering the location scope; reload acts on all
|
||||
// loaded locations and must not boot the caller's location first.
|
||||
export const makeLocationGroup = () =>
|
||||
HttpApiGroup.make("server.location")
|
||||
.add(
|
||||
HttpApiEndpoint.get("location.probe", "/api/location/probe", {
|
||||
query: ProbeQuery,
|
||||
success: Schema.Struct({ exists: Schema.Boolean }),
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "location.probe",
|
||||
summary: "Probe location path",
|
||||
description:
|
||||
"Check if an explicit path exists without loading its location. Only filesystem NotFound returns false; other filesystem failures do not imply absence.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.get("location.get", "/api/location", {
|
||||
query: LocationQuery,
|
||||
success: Location.PublicInfo,
|
||||
error: LocationNotFoundError,
|
||||
})
|
||||
.middleware(locationMiddleware)
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
|
|
|
|||
|
|
@ -1,31 +1,41 @@
|
|||
import { Location } from "@opencode/core/location"
|
||||
import { LocationServiceMap } from "@opencode/core/location-service-map"
|
||||
import { ServiceUnavailableError } from "@opencode/protocol/errors"
|
||||
import { LocationNotFoundError, ServiceUnavailableError } from "@opencode/protocol/errors"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { Cause, Effect } from "effect"
|
||||
import { HttpApiBuilder } from "effect/unstable/httpapi"
|
||||
import { Api } from "../api"
|
||||
import { requestRef } from "../location"
|
||||
|
||||
export const LocationHandler = HttpApiBuilder.group(Api, "server.location", (handlers) =>
|
||||
Effect.gen(function* () {
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const fs = yield* FSUtil.Service
|
||||
return handlers
|
||||
.handle("location.probe", (ctx) =>
|
||||
fs.stat(ctx.query.directory).pipe(
|
||||
Effect.as({ exists: true }),
|
||||
Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed({ exists: false })),
|
||||
Effect.orDie,
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"location.get",
|
||||
Effect.fn(function* () {
|
||||
const location = yield* Location.Service
|
||||
return new Location.Info({
|
||||
directory: location.directory,
|
||||
project: location.project,
|
||||
})
|
||||
Effect.fn(function* (ctx) {
|
||||
const ref = requestRef(ctx.request)
|
||||
const missing = () =>
|
||||
new LocationNotFoundError({ directory: ref.directory, message: `Location not found: ${ref.directory}` })
|
||||
const stat = yield* fs.stat(ref.directory).pipe(
|
||||
Effect.catchTag("PlatformError", (error) => {
|
||||
if (error.reason._tag === "NotFound") return missing()
|
||||
if (
|
||||
error.reason._tag === "BadResource" &&
|
||||
error.reason.cause instanceof Error &&
|
||||
"code" in error.reason.cause &&
|
||||
error.reason.cause.code === "ENOTDIR"
|
||||
)
|
||||
return missing()
|
||||
return Effect.die(error)
|
||||
}),
|
||||
)
|
||||
if (stat.type !== "Directory") return yield* missing()
|
||||
return yield* Effect.gen(function* () {
|
||||
const location = yield* Location.Service
|
||||
return new Location.Info({ directory: location.directory, project: location.project })
|
||||
}).pipe(Effect.provide(locations.get(ref)))
|
||||
}),
|
||||
)
|
||||
.handle("location.reload", () =>
|
||||
|
|
|
|||
86
packages/server/test/location-get.test.ts
Normal file
86
packages/server/test/location-get.test.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
||||
import { it } from "../../core/test/lib/effect"
|
||||
import { startServer } from "./fixture/server"
|
||||
|
||||
it.live("reads an existing directory through the existing location endpoint", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* tmpdirScoped()
|
||||
const existing = path.join(tmp.path, "existing")
|
||||
yield* Effect.promise(() => fs.mkdir(existing))
|
||||
const server = yield* startServer(tmp.path)
|
||||
const url = new URL("/api/location", server.base)
|
||||
url.searchParams.set("location[directory]", existing)
|
||||
const response = yield* Effect.promise(() => fetch(url, { headers: server.headers }))
|
||||
expect(response.status).toBe(200)
|
||||
expect((yield* Effect.promise(() => response.json())).directory).toBe(existing)
|
||||
|
||||
const header = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/location", server.base), {
|
||||
headers: { ...server.headers, "x-opencode-directory": encodeURIComponent(existing) },
|
||||
}),
|
||||
)
|
||||
expect((yield* Effect.promise(() => header.json())).directory).toBe(existing)
|
||||
|
||||
const precedence = yield* Effect.promise(() =>
|
||||
fetch(url, {
|
||||
headers: { ...server.headers, "x-opencode-directory": encodeURIComponent(path.join(tmp.path, "removed")) },
|
||||
}),
|
||||
)
|
||||
expect((yield* Effect.promise(() => precedence.json())).directory).toBe(existing)
|
||||
|
||||
const defaultLocation = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/location", server.base), { headers: server.headers }),
|
||||
)
|
||||
expect(defaultLocation.status).toBe(200)
|
||||
expect((yield* Effect.promise(() => defaultLocation.json())).directory).toBe(process.cwd())
|
||||
|
||||
yield* Effect.promise(() => fs.rmdir(existing))
|
||||
const removed = yield* Effect.promise(() => fetch(url, { headers: server.headers }))
|
||||
expect(removed.status).toBe(404)
|
||||
expect(yield* Effect.promise(() => removed.json())).toMatchObject({
|
||||
_tag: "LocationNotFoundError",
|
||||
directory: existing,
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("reports only a missing or non-directory location as a typed 404 before booting", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* tmpdirScoped()
|
||||
const missing = path.join(tmp.path, "removed")
|
||||
const file = path.join(tmp.path, "file")
|
||||
const loop = path.join(tmp.path, "loop")
|
||||
yield* Effect.promise(async () => {
|
||||
await fs.writeFile(file, "content")
|
||||
await fs.symlink(loop, loop)
|
||||
})
|
||||
const server = yield* startServer(tmp.path)
|
||||
const get = (directory: string) =>
|
||||
Effect.promise(async () => {
|
||||
const url = new URL("/api/location", server.base)
|
||||
url.searchParams.set("location[directory]", directory)
|
||||
const response = await fetch(url, { headers: server.headers })
|
||||
return { status: response.status, body: await response.json() }
|
||||
})
|
||||
|
||||
for (const directory of [missing, file, path.join(file, "child")]) {
|
||||
expect(yield* get(directory)).toMatchObject({
|
||||
status: 404,
|
||||
body: { _tag: "LocationNotFoundError", directory },
|
||||
})
|
||||
}
|
||||
expect((yield* get(loop)).status).toBe(500)
|
||||
const probe = yield* Effect.promise(() =>
|
||||
fetch(new URL("/api/location/probe", server.base), { headers: server.headers }),
|
||||
)
|
||||
expect(probe.status).toBe(404)
|
||||
const loaded = yield* Effect.promise(async () =>
|
||||
(await fetch(new URL("/api/debug/location", server.base), { headers: server.headers })).json(),
|
||||
)
|
||||
expect(loaded).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
||||
import { it } from "../../core/test/lib/effect"
|
||||
import { startServer } from "./fixture/server"
|
||||
|
||||
it.live("probes a directory without booting its location or masking a missing path", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* tmpdirScoped()
|
||||
const existing = path.join(tmp.path, "existing")
|
||||
const missing = path.join(tmp.path, "removed")
|
||||
const file = path.join(tmp.path, "file")
|
||||
const loop = path.join(tmp.path, "loop")
|
||||
yield* Effect.promise(async () => {
|
||||
await fs.mkdir(existing)
|
||||
await fs.writeFile(file, "content")
|
||||
await fs.symlink(loop, loop)
|
||||
})
|
||||
const server = yield* startServer(tmp.path)
|
||||
const probe = (directory?: string) =>
|
||||
Effect.promise(async () => {
|
||||
const url = new URL("/api/location/probe", server.base)
|
||||
if (directory !== undefined) url.searchParams.set("directory", directory)
|
||||
const response = await fetch(url, { headers: server.headers })
|
||||
return { status: response.status, body: await response.json() }
|
||||
})
|
||||
|
||||
expect(yield* probe(existing)).toEqual({ status: 200, body: { exists: true } })
|
||||
expect(yield* probe(missing)).toEqual({ status: 200, body: { exists: false } })
|
||||
expect(yield* probe(file)).toEqual({ status: 200, body: { exists: true } })
|
||||
expect((yield* probe(path.join(file, "child"))).status).toBe(500)
|
||||
expect((yield* probe(loop)).status).toBe(500)
|
||||
expect((yield* probe()).status).toBe(400)
|
||||
const loaded = yield* Effect.promise(async () =>
|
||||
(await fetch(new URL("/api/debug/location", server.base), { headers: server.headers })).json(),
|
||||
)
|
||||
expect(loaded).toEqual([])
|
||||
}),
|
||||
)
|
||||
Loading…
Add table
Reference in a new issue