Files
kilocode/packages/opencode/test/server/httpapi-cors.test.ts
T
Marius a1ad65e522 fix(cli): stabilize Windows CI tests and rebalance slow shards (#12723)
* fix(cli): stabilize Windows CI tests and rebalance slow shards

Three Windows-only instabilities in the CLI unit suite:

1. httpapi-instance-route-auth.test.ts failed with an uncaught
   "Invalid handle" error. The test's ConfigProvider.layer(
   fromUnknown(...)) replaced the ambient config provider, blinding
   KILO_EXPERIMENTAL_DISABLE_FILEWATCHER=true that CI/preload sets. With
   the flag hidden, the @parcel/watcher Windows backend subscribed on the
   temp repo's .git; the tmpdir fixture then deleted that directory while
   the never-disposed per-test runtime still held the subscription, and
   CreateFileW failed with the hardcoded "Invalid handle" (napi rejection
   with no JS stack). Add the disable-filewatcher flag to every test
   config map that boots instances via the HttpApi app (instance-route-auth,
   cors, ui, exercise backend, kilo-edit, memory).

2. config-overlay.test.ts intermittently returned HTTP 500 on Windows.
   Filesystem.write's atomic temp-file+rename had no retry for Windows
   transient locked-file errors (EPERM/EACCES/EBUSY) from Defender/indexer
   and the detached background plugin install racing the rename in the same
   tmpdir. Mirror the proven cleanup.ts locked-error retry pattern with a
   short backoff, Windows-only.

3. Windows shards were badly imbalanced: the sharder weighted files by
   byte size, which concentrated every slow spawn/FS/lock-heavy file
   (snapshot, prompt, provider, run-process, instance-bootstrap,
   httpapi-session) into one shard (~612s vs ~356s siblings), and the
   resulting contention forced whole-file retries that doubled cost. Add
   TestShard.timedWeight and a committed test-timings.json seeded from CI
   junit data so shards balance by measured runtime (spread collapses from
   ~200s to ~18s) and contention-prone files spread across shards.
   Platforms without manifest entries fall back to size weighting.

* fix(cli): skip stale manifest entries in timed shard weighting

Bun.file().size returns 0 (never throws) for missing paths, so the
try/catch in timedWeight was dead code and stale/renamed manifest entries
added their time to the scale numerator with zero size, inflating the
size-to-time ratio that estimates unknown files. Skip entries with a
non-positive on-disk size instead of catching a throw that never happens.

* revert(cli): drop hardcoded test-timings manifest

The committed test-timings.json (482 entries) was a maintenance burden:
it goes stale as tests are added/renamed and no size-based heuristic can
replace it (slow subprocess outliers like run-process.test.ts are 7kb but
112s, 10x the runtime-per-byte of other files). Revert the timing-weighted
sharding to the prior size-based LPT. The Windows reliability fixes
(ConfigProvider filewatcher flag + Filesystem.write locked-file retry)
remain and are what eliminate the failures and the ~360s of retry overhead
that dominated the 12m50s shard. A maintainable runtime-based rebalance
(self-updating CI cache fed from the junit artifacts CI already uploads)
is a separate follow-up.
2026-07-31 13:27:34 +02:00

132 lines
4.7 KiB
TypeScript

import { NodeHttpServer, NodeServices } from "@effect/platform-node"
import { Flag } from "@opencode-ai/core/flag/flag"
import { describe, expect } from "bun:test"
import { Config, ConfigProvider, Effect, Layer } from "effect"
import { HttpClient, HttpClientRequest, HttpRouter, HttpServer } from "effect/unstable/http"
import * as Socket from "effect/unstable/socket/Socket"
import { Server } from "../../src/server/server"
import { InstancePaths } from "../../src/server/routes/instance/httpapi/groups/instance"
import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server"
import { resetDatabase } from "../fixture/db"
import { testEffect } from "../lib/effect"
const testStateLayer = Layer.effectDiscard(
Effect.gen(function* () {
const original = {
KILO_SERVER_PASSWORD: Flag.KILO_SERVER_PASSWORD,
}
Flag.KILO_SERVER_PASSWORD = "secret"
yield* Effect.promise(() => resetDatabase())
yield* Effect.addFinalizer(() =>
Effect.promise(async () => {
Flag.KILO_SERVER_PASSWORD = original.KILO_SERVER_PASSWORD
await resetDatabase()
}),
)
}),
)
const servedRoutes: Layer.Layer<never, Config.ConfigError, HttpServer.HttpServer> = HttpRouter.serve(
HttpApiApp.routes,
{ disableListenLog: true, disableLogger: true },
)
const it = testEffect(
Layer.mergeAll(
testStateLayer,
servedRoutes.pipe(
Layer.provide(Socket.layerWebSocketConstructorGlobal),
Layer.provideMerge(NodeHttpServer.layerTest),
Layer.provideMerge(NodeServices.layer),
),
),
)
describe("HttpApi CORS", () => {
it.live("allows browser preflight requests without credentials", () =>
Effect.gen(function* () {
const response = yield* HttpClientRequest.options(InstancePaths.path).pipe(
HttpClientRequest.setHeaders({
origin: "http://localhost:3000",
"access-control-request-method": "GET",
"access-control-request-headers": "authorization",
}),
HttpClient.execute,
)
expect(response.status).toBe(204)
expect(response.headers["access-control-allow-origin"]).toBe("http://localhost:3000")
expect(response.headers["access-control-allow-headers"]).toBe("authorization")
}),
)
it.live("adds CORS headers to unauthorized responses", () =>
Effect.gen(function* () {
const handler = HttpRouter.toWebHandler(
HttpApiApp.createRoutes().pipe(
// kilocode_change start - keep the filewatcher-disable flag visible (see httpapi-instance-route-auth.test.ts)
Layer.provide(
ConfigProvider.layer(
ConfigProvider.fromUnknown({
KILO_SERVER_PASSWORD: "secret",
KILO_EXPERIMENTAL_DISABLE_FILEWATCHER: process.env.KILO_EXPERIMENTAL_DISABLE_FILEWATCHER ?? "true",
}),
),
),
// kilocode_change end
),
{ disableLogger: true },
).handler
const response = yield* Effect.promise(() =>
handler(
new Request(new URL("/global/config", "http://localhost"), {
headers: { origin: "https://app.opencode.ai" },
}),
HttpApiApp.context,
),
)
expect(response.status).toBe(401)
expect(response.headers.get("access-control-allow-origin")).toBe("https://app.opencode.ai")
}),
)
it.live("uses custom CORS origins passed to the server", () =>
Effect.gen(function* () {
const listener = yield* Effect.acquireRelease(
Effect.promise(() => Server.listen({ hostname: "127.0.0.1", port: 0, cors: ["https://custom.example"] })),
(listener) => Effect.promise(() => listener.stop(true)),
)
const response = yield* Effect.promise(() =>
fetch(new URL(InstancePaths.path, listener.url), {
method: "OPTIONS",
headers: {
origin: "https://custom.example",
"access-control-request-method": "GET",
"access-control-request-headers": "authorization",
},
}),
)
expect(response.status).toBe(204)
expect(response.headers.get("access-control-allow-origin")).toBe("https://custom.example")
expect(response.headers.get("access-control-allow-headers")).toBe("authorization")
const rejected = yield* Effect.promise(() =>
fetch(new URL(InstancePaths.path, listener.url), {
method: "OPTIONS",
headers: {
origin: "https://evil.example",
"access-control-request-method": "GET",
"access-control-request-headers": "authorization",
},
}),
)
expect(rejected.status).toBe(204)
expect(rejected.headers.get("access-control-allow-origin")).not.toBe("https://evil.example")
}),
)
})