fix(opencode): handle child approvals, stops, and model catalogs (#8480)
This commit is contained in:
1 parent
0009aacdf1
commit
cb49e5d720
42 files changed
+7889
-581
No files matched your search
@@ -11,6 +11,7 @@ import { beforeEach, expect } from "vite-plus/test";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
import * as OpenCodeServerOwner from "../provider/OpenCodeServerOwner.ts";
|
||||
import * as OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
|
||||
@@ -21,6 +22,8 @@ const runtimeMock = {
|
||||
promptParts: [] as ReadonlyArray<unknown>[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
closeCalls: [] as string[],
|
||||
sessionCreateCalls: 0,
|
||||
connectionError: undefined as Error | undefined,
|
||||
sessionCreateError: undefined as unknown,
|
||||
sessionResult: undefined as { data?: { id: string } } | undefined,
|
||||
promptRequestError: undefined as unknown,
|
||||
@@ -34,6 +37,8 @@ const runtimeMock = {
|
||||
this.state.promptParts.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.sessionCreateCalls = 0;
|
||||
this.state.connectionError = undefined;
|
||||
this.state.sessionCreateError = undefined;
|
||||
this.state.sessionResult = undefined;
|
||||
this.state.promptRequestError = undefined;
|
||||
@@ -42,7 +47,7 @@ const runtimeMock = {
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
startOpenCodeServerProcess: ({ binaryPath, serverPassword, environment }) =>
|
||||
Effect.gen(function* () {
|
||||
const index = runtimeMock.state.startCalls.length + 1;
|
||||
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||
@@ -54,22 +59,43 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
}),
|
||||
);
|
||||
const effectiveServerPassword = OpenCodeRuntime.resolveOpenCodeServerPassword({
|
||||
external: false,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
...(environment !== undefined ? { environment } : {}),
|
||||
});
|
||||
return {
|
||||
url,
|
||||
...(effectiveServerPassword !== undefined
|
||||
? { serverPassword: effectiveServerPassword }
|
||||
: {}),
|
||||
version: "1.14.19",
|
||||
isRunning: Effect.succeed(true),
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl, serverPassword }) =>
|
||||
runtimeMock.state.connectionError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: runtimeMock.state.connectionError.message,
|
||||
cause: runtimeMock.state.connectionError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
...(serverPassword ? { serverPassword } : {}),
|
||||
version: "1.14.19",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
}),
|
||||
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => {
|
||||
runtimeMock.state.sessionCreateCalls += 1;
|
||||
if (runtimeMock.state.sessionCreateError !== undefined) {
|
||||
throw runtimeMock.state.sessionCreateError;
|
||||
}
|
||||
@@ -163,18 +189,35 @@ const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
|
||||
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
});
|
||||
const LOCAL_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
serverPassword: "secret-password",
|
||||
});
|
||||
const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
});
|
||||
const EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
});
|
||||
|
||||
function withOpenCodeTextGeneration<A, E, R>(
|
||||
settings: OpenCodeSettings,
|
||||
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
|
||||
const serverOwner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: settings.binaryPath,
|
||||
directory: process.cwd(),
|
||||
...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
|
||||
...(environment ? { environment } : {}),
|
||||
});
|
||||
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe(
|
||||
Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
|
||||
);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
@@ -229,6 +272,49 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("passes configured authentication to a locally spawned server", () =>
|
||||
withOpenCodeTextGeneration(LOCAL_AUTH_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses an environment-only password for a locally spawned server", () =>
|
||||
withOpenCodeTextGeneration(
|
||||
DEFAULT_OPENCODE_SETTINGS,
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:environment-password")}`,
|
||||
]);
|
||||
}),
|
||||
{ OPENCODE_SERVER_PASSWORD: "environment-password" },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses settings auth when the local environment password differs", () =>
|
||||
withOpenCodeTextGeneration(
|
||||
LOCAL_AUTH_OPENCODE_SETTINGS,
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
}),
|
||||
{ OPENCODE_SERVER_PASSWORD: "environment-password" },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -460,6 +546,36 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
|
||||
"OpenCodeTextGeneration with configured server URL",
|
||||
(it) => {
|
||||
it.effect("does not send a local environment password to a configured server", () =>
|
||||
withOpenCodeTextGeneration(
|
||||
EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS,
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
expect(runtimeMock.state.authHeaders).toEqual([null]);
|
||||
}),
|
||||
{ OPENCODE_SERVER_PASSWORD: "local-secret" },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not create a session when the server version is unsupported", () =>
|
||||
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.connectionError = new Error(
|
||||
"OpenCode v1.14.18 is too old. Upgrade to v1.14.19 or newer.",
|
||||
);
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(TextGenerationError);
|
||||
expect(error.message).toContain("v1.14.18 is too old");
|
||||
expect(runtimeMock.state.sessionCreateCalls).toBe(0);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
|
||||
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
NonNegativeInt,
|
||||
@@ -31,8 +27,7 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
import * as OpenCodeServerOwner from "../provider/OpenCodeServerOwner.ts";
|
||||
|
||||
const OpenCodeTextGenerationOperation = Schema.Literals([
|
||||
"generateCommitMessage",
|
||||
@@ -175,188 +170,12 @@ function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): str
|
||||
.trim();
|
||||
}
|
||||
|
||||
interface SharedOpenCodeTextGenerationServerState {
|
||||
server: OpenCodeRuntime.OpenCodeServerProcess | null;
|
||||
/**
|
||||
* The scope that owns the shared server's lifetime. Closing this scope
|
||||
* terminates the OpenCode child process and interrupts any fibers the
|
||||
* runtime forked during startup. We don't hold a `close()` function on
|
||||
* the server handle anymore — the scope is the only lifecycle handle.
|
||||
*/
|
||||
serverScope: Scope.Closeable | null;
|
||||
binaryPath: string | null;
|
||||
activeRequests: number;
|
||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||
}
|
||||
|
||||
export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (
|
||||
openCodeSettings: OpenCodeSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const sharedServerMutex = yield* Semaphore.make(1);
|
||||
const sharedServerState: SharedOpenCodeTextGenerationServerState = {
|
||||
server: null,
|
||||
serverScope: null,
|
||||
binaryPath: null,
|
||||
activeRequests: 0,
|
||||
idleCloseFiber: null,
|
||||
};
|
||||
|
||||
const closeSharedServer = Effect.fn("closeSharedServer")(function* () {
|
||||
const scope = sharedServerState.serverScope;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.serverScope = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
if (scope !== null) {
|
||||
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
|
||||
const idleCloseFiber = sharedServerState.idleCloseFiber;
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
if (idleCloseFiber !== null) {
|
||||
yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const scheduleIdleClose = Effect.fn("scheduleIdleClose")(function* (
|
||||
server: OpenCodeRuntime.OpenCodeServerProcess,
|
||||
) {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
|
||||
Effect.andThen(
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
yield* closeSharedServer();
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.forkIn(idleFiberScope),
|
||||
);
|
||||
sharedServerState.idleCloseFiber = fiber;
|
||||
});
|
||||
|
||||
const acquireSharedServer = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
}) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
|
||||
const existingServer = sharedServerState.server;
|
||||
if (existingServer !== null) {
|
||||
if (
|
||||
sharedServerState.binaryPath !== input.binaryPath &&
|
||||
sharedServerState.activeRequests === 0
|
||||
) {
|
||||
yield* closeSharedServer();
|
||||
} else {
|
||||
if (sharedServerState.binaryPath !== input.binaryPath) {
|
||||
yield* Effect.logWarning(
|
||||
"OpenCode shared server binary path mismatch: requested " +
|
||||
input.binaryPath +
|
||||
" but active server uses " +
|
||||
sharedServerState.binaryPath +
|
||||
"; reusing existing server because there are active requests",
|
||||
);
|
||||
}
|
||||
sharedServerState.activeRequests += 1;
|
||||
return existingServer;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a fresh scope that owns this shared server. The runtime
|
||||
// will attach its child-process and fiber finalizers to this scope;
|
||||
// closing it kills the server and interrupts those fibers.
|
||||
//
|
||||
// The `Scope.make` / spawn / record-or-close transitions run inside
|
||||
// `uninterruptibleMask` so an interrupt arriving between any two
|
||||
// steps can't orphan the scope (and the child process attached to
|
||||
// it) before we either close it on failure or hand ownership to
|
||||
// `sharedServerState`. `restore` keeps the actual spawn
|
||||
// interruptible; an interrupt during the spawn is captured by
|
||||
// `Effect.exit` and drives us through the failure branch that
|
||||
// closes the fresh scope.
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const serverScope = yield* Scope.make();
|
||||
const startedExit = yield* Effect.exit(
|
||||
restore(
|
||||
openCodeRuntime
|
||||
.startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
environment: resolvedEnvironment,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, serverScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (startedExit._tag === "Failure") {
|
||||
yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
|
||||
return yield* Effect.failCause(startedExit.cause);
|
||||
}
|
||||
|
||||
const server = startedExit.value;
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.serverScope = serverScope;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const releaseSharedServer = (server: OpenCodeRuntime.OpenCodeServerProcess) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (sharedServerState.server !== server) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);
|
||||
if (sharedServerState.activeRequests === 0) {
|
||||
yield* scheduleIdleClose(server);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Module-level finalizer: on layer shutdown, cancel the idle close fiber
|
||||
// and close the shared server scope. Consumers therefore cannot leak
|
||||
// the shared OpenCode server by forgetting to call anything.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
sharedServerState.activeRequests = 0;
|
||||
yield* closeSharedServer();
|
||||
}),
|
||||
),
|
||||
);
|
||||
const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
|
||||
|
||||
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
|
||||
readonly operation: OpenCodeTextGenerationOperation;
|
||||
@@ -381,13 +200,16 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
});
|
||||
|
||||
const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
|
||||
function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
|
||||
function* (
|
||||
server: Pick<
|
||||
OpenCodeRuntime.OpenCodeServerConnection,
|
||||
"url" | "serverPassword" | "version"
|
||||
>,
|
||||
) {
|
||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
|
||||
});
|
||||
const session = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
@@ -496,17 +318,31 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
}),
|
||||
);
|
||||
|
||||
const rawOutput =
|
||||
const serverOutput =
|
||||
openCodeSettings.serverUrl.length > 0
|
||||
? yield* runAgainstServer({ url: openCodeSettings.serverUrl })
|
||||
: yield* Effect.acquireUseRelease(
|
||||
acquireSharedServer({
|
||||
? openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
directory: input.cwd,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
...(openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
})
|
||||
.pipe(Effect.flatMap(runAgainstServer), Effect.scoped)
|
||||
: serverOwner.withServer(runAgainstServer);
|
||||
const rawOutput = yield* serverOutput.pipe(
|
||||
Effect.catchTags({
|
||||
OpenCodeRuntimeError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
runAgainstServer,
|
||||
releaseSharedServer,
|
||||
);
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
|
||||
|
||||
Reference in new issue
Block a user