From 9f2bada8031b33d216c21bcb8539d5c94c0be809 Mon Sep 17 00:00:00 2001 From: adityagarud Date: Mon, 7 Sep 2026 23:01:18 +0000 Subject: [PATCH 1/2] fix(opencode): stop cancelled text generation sessions --- .../OpenCodeTextGeneration.test.ts | 125 +++++++++++++++++- .../textGeneration/OpenCodeTextGeneration.ts | 51 +++++-- 2 files changed, 160 insertions(+), 16 deletions(-) diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts index 688bf4bca3527..9c76df14a96e7 100644 --- a/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts @@ -1,8 +1,11 @@ import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; @@ -23,6 +26,10 @@ const runtimeMock = { authHeaders: [] as Array, closeCalls: [] as string[], sessionCreateCalls: 0, + abortCalls: [] as string[], + onSessionCreate: undefined as ((signal?: AbortSignal) => Promise) | undefined, + onPrompt: undefined as ((signal?: AbortSignal) => Promise) | undefined, + onAbort: undefined as ((signal?: AbortSignal) => Promise) | undefined, connectionError: undefined as Error | undefined, sessionCreateError: undefined as unknown, sessionResult: undefined as { data?: { id: string } } | undefined, @@ -38,6 +45,10 @@ const runtimeMock = { this.state.authHeaders.length = 0; this.state.closeCalls.length = 0; this.state.sessionCreateCalls = 0; + this.state.abortCalls.length = 0; + this.state.onSessionCreate = undefined; + this.state.onPrompt = undefined; + this.state.onAbort = undefined; this.state.connectionError = undefined; this.state.sessionCreateError = undefined; this.state.sessionResult = undefined; @@ -94,19 +105,34 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = { createOpenCodeSdkClient: ({ baseUrl, serverPassword }) => ({ session: { - create: async () => { + create: async (_input: unknown, options?: { readonly signal?: AbortSignal }) => { runtimeMock.state.sessionCreateCalls += 1; + if (runtimeMock.state.onSessionCreate) { + return runtimeMock.state.onSessionCreate(options?.signal); + } if (runtimeMock.state.sessionCreateError !== undefined) { throw runtimeMock.state.sessionCreateError; } return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } }; }, - prompt: async (input: { readonly parts: ReadonlyArray }) => { + abort: async ( + input: { readonly sessionID: string }, + options?: { readonly signal?: AbortSignal }, + ) => { + runtimeMock.state.abortCalls.push(input.sessionID); + if (runtimeMock.state.onAbort) return runtimeMock.state.onAbort(options?.signal); + return { data: true }; + }, + prompt: async ( + input: { readonly parts: ReadonlyArray }, + options?: { readonly signal?: AbortSignal }, + ) => { runtimeMock.state.promptUrls.push(baseUrl); runtimeMock.state.promptParts.push(input.parts); runtimeMock.state.authHeaders.push( serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null, ); + if (runtimeMock.state.onPrompt) return runtimeMock.state.onPrompt(options?.signal); if (runtimeMock.state.promptRequestError !== undefined) { throw runtimeMock.state.promptRequestError; } @@ -235,6 +261,101 @@ const advanceIdleClock = Effect.gen(function* () { }); it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => { + it.effect.each(["local", "external"] as const)( + "cancels an in-flight session creation on the %s server", + (server) => + withOpenCodeTextGeneration( + server === "local" ? DEFAULT_OPENCODE_SETTINGS : EXISTING_SERVER_OPENCODE_SETTINGS, + (textGeneration) => + Effect.gen(function* () { + const started = Promise.withResolvers(); + runtimeMock.state.onSessionCreate = (signal) => { + started.resolve(signal); + return new Promise(() => {}); + }; + const fiber = yield* textGeneration + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) + .pipe(Effect.forkChild); + const signal = yield* Effect.promise(() => started.promise); + yield* Fiber.interrupt(fiber); + + expect(signal?.aborted).toBe(true); + expect(runtimeMock.state.promptUrls).toEqual([]); + expect(runtimeMock.state.abortCalls).toEqual([]); + }), + ), + ); + + it.effect.each(["local", "external"] as const)( + "cancels the prompt and stops only its session on the %s server", + (server) => + withOpenCodeTextGeneration( + server === "local" ? DEFAULT_OPENCODE_SETTINGS : EXISTING_SERVER_OPENCODE_SETTINGS, + (textGeneration) => + Effect.gen(function* () { + const started = Promise.withResolvers(); + runtimeMock.state.onPrompt = (signal) => { + started.resolve(signal); + return new Promise(() => {}); + }; + const fiber = yield* textGeneration + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) + .pipe(Effect.forkChild); + const signal = yield* Effect.promise(() => started.promise); + yield* Fiber.interrupt(fiber); + + expect(signal?.aborted).toBe(true); + expect(runtimeMock.state.abortCalls).toEqual([ + `${runtimeMock.state.promptUrls[0]}/session`, + ]); + expect(runtimeMock.state.closeCalls).toEqual([]); + + runtimeMock.state.onPrompt = undefined; + const result = yield* textGeneration.generateCommitMessage( + DEFAULT_COMMIT_MESSAGE_INPUT, + ); + expect(result.subject).toBe("Improve OpenCode reuse"); + expect(runtimeMock.state.abortCalls).toHaveLength(1); + }), + ), + ); + + it.effect.each(["failure", "timeout"] as const)( + "preserves cancellation when the session abort ends in %s", + (outcome) => + withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + const promptStarted = Promise.withResolvers(); + const abortStarted = Promise.withResolvers(); + runtimeMock.state.onPrompt = () => { + promptStarted.resolve(); + return new Promise(() => {}); + }; + runtimeMock.state.onAbort = (signal) => { + abortStarted.resolve(signal); + return outcome === "failure" + ? Promise.reject(new Error("Server disconnected")) + : new Promise(() => {}); + }; + const fiber = yield* textGeneration + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) + .pipe(Effect.forkChild); + yield* Effect.promise(() => promptStarted.promise); + const cancellation = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild); + const abortSignal = yield* Effect.promise(() => abortStarted.promise); + if (outcome === "timeout") { + yield* TestClock.adjust("10 seconds"); + } + yield* Fiber.join(cancellation); + + const exit = yield* Fiber.await(fiber); + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); + expect(runtimeMock.state.abortCalls).toEqual(["http://127.0.0.1:9999/session"]); + if (outcome === "timeout") expect(abortSignal?.aborted).toBe(true); + }), + ), + ); + it.effect("excludes generic files from thread title generation", () => withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => Effect.gen(function* () { diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts index e0e960422b18e..94db038e0d7b4 100644 --- a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts +++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts @@ -212,11 +212,14 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration" ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}), }); const session = yield* Effect.tryPromise({ - try: () => - client.session.create({ - title: `T3 Code ${input.operation}`, - permission: [{ permission: "*", pattern: "*", action: "deny" }], - }), + try: (signal) => + client.session.create( + { + title: `T3 Code ${input.operation}`, + permission: [{ permission: "*", pattern: "*", action: "deny" }], + }, + { signal }, + ), catch: (cause) => new OpenCodeTextGenerationSessionRequestError({ operation: input.operation, @@ -241,20 +244,40 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration" }; const result = yield* Effect.tryPromise({ - try: () => - client.session.prompt({ - sessionID: session.data.id, - model: parsedModel, - ...(selectedAgent ? { agent: selectedAgent } : {}), - ...(selectedVariant ? { variant: selectedVariant } : {}), - parts: [{ type: "text", text: input.prompt }, ...fileParts], - }), + try: (signal) => + client.session.prompt( + { + sessionID: session.data.id, + model: parsedModel, + ...(selectedAgent ? { agent: selectedAgent } : {}), + ...(selectedVariant ? { variant: selectedVariant } : {}), + parts: [{ type: "text", text: input.prompt }, ...fileParts], + }, + { signal }, + ), catch: (cause) => new OpenCodeTextGenerationPromptRequestError({ ...promptContext, cause, }), - }); + }).pipe( + // Disconnecting the HTTP request does not stop work in a shared or external server. + Effect.onInterrupt(() => + OpenCodeRuntime.runOpenCodeSdk("session.abort", (signal) => + client.session.abort({ sessionID: session.data.id }, { signal }), + ).pipe( + Effect.interruptible, + Effect.timeout("10 seconds"), + Effect.catch((cause) => + Effect.logWarning("Failed to stop cancelled OpenCode text generation.", { + ...promptContext, + cause, + }), + ), + Effect.asVoid, + ), + ), + ); const promptFailure = getOpenCodePromptFailure(result.data?.info?.error); if (promptFailure) { return yield* new OpenCodeTextGenerationPromptResponseError({ From 508e7229158790b6120470897c7f09d036de8b1d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 19 Oct 2026 03:06:19 +0000 Subject: [PATCH 2/2] test(opencode): focus cancellation isolation regressions --- .../src/server/textGeneration.test.ts | 153 ++++++++++-------- 1 file changed, 87 insertions(+), 66 deletions(-) diff --git a/packages/provider-opencode/src/server/textGeneration.test.ts b/packages/provider-opencode/src/server/textGeneration.test.ts index c68654a89ea6b..daa5de57bac31 100644 --- a/packages/provider-opencode/src/server/textGeneration.test.ts +++ b/packages/provider-opencode/src/server/textGeneration.test.ts @@ -3,6 +3,7 @@ import { OpenCodeSettings } from "../settings.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -30,7 +31,9 @@ const runtimeMock = { sessionCreateCalls: 0, abortCalls: [] as string[], onSessionCreate: undefined as ((signal?: AbortSignal) => Promise) | undefined, - onPrompt: undefined as ((signal?: AbortSignal) => Promise) | undefined, + onPrompt: undefined as + | ((signal?: AbortSignal) => Promise<{ data: { parts: ReadonlyArray } }>) + | undefined, onAbort: undefined as ((signal?: AbortSignal) => Promise) | undefined, connectionError: undefined as Error | undefined, sessionCreateError: undefined as unknown, @@ -255,63 +258,78 @@ const advanceIdleClock = Effect.gen(function* () { }); it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => { - it.effect.each(["local", "external"] as const)( - "cancels an in-flight session creation on the %s server", - (server) => - withOpenCodeTextGeneration( - server === "local" ? DEFAULT_OPENCODE_SETTINGS : EXISTING_SERVER_OPENCODE_SETTINGS, - (textGeneration) => - Effect.gen(function* () { - const started = Promise.withResolvers(); - runtimeMock.state.onSessionCreate = (signal) => { - started.resolve(signal); - return new Promise(() => {}); - }; - const fiber = yield* textGeneration - .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) - .pipe(Effect.forkChild); - const signal = yield* Effect.promise(() => started.promise); - yield* Fiber.interrupt(fiber); - - expect(signal?.aborted).toBe(true); - expect(runtimeMock.state.promptUrls).toEqual([]); - expect(runtimeMock.state.abortCalls).toEqual([]); - }), - ), + it.effect("cancels an in-flight session creation before prompting", () => + withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + runtimeMock.state.onSessionCreate = (signal) => { + Deferred.doneUnsafe(started, Effect.succeed(signal)); + return new Promise(() => {}); + }; + const fiber = yield* textGeneration + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) + .pipe(Effect.forkChild); + const signal = yield* Deferred.await(started); + yield* Fiber.interrupt(fiber); + + const exit = yield* Fiber.await(fiber); + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); + expect(signal?.aborted).toBe(true); + expect(runtimeMock.state.promptUrls).toEqual([]); + expect(runtimeMock.state.abortCalls).toEqual([]); + }), + ), ); - it.effect.each(["local", "external"] as const)( - "cancels the prompt and stops only its session on the %s server", - (server) => - withOpenCodeTextGeneration( - server === "local" ? DEFAULT_OPENCODE_SETTINGS : EXISTING_SERVER_OPENCODE_SETTINGS, - (textGeneration) => - Effect.gen(function* () { - const started = Promise.withResolvers(); - runtimeMock.state.onPrompt = (signal) => { - started.resolve(signal); - return new Promise(() => {}); - }; - const fiber = yield* textGeneration - .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) - .pipe(Effect.forkChild); - const signal = yield* Effect.promise(() => started.promise); - yield* Fiber.interrupt(fiber); - - expect(signal?.aborted).toBe(true); - expect(runtimeMock.state.abortCalls).toEqual([ - `${runtimeMock.state.promptUrls[0]}/session`, - ]); - expect(runtimeMock.state.closeCalls).toEqual([]); - - runtimeMock.state.onPrompt = undefined; - const result = yield* textGeneration.generateCommitMessage( - DEFAULT_COMMIT_MESSAGE_INPUT, - ); - expect(result.subject).toBe("Improve OpenCode reuse"); - expect(runtimeMock.state.abortCalls).toHaveLength(1); - }), - ), + it.effect("cancels only its prompt session while another generation uses the shared server", () => + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + runtimeMock.state.sessionResult = { data: { id: "cancelled-session" } }; + runtimeMock.state.onPrompt = (signal) => { + Deferred.doneUnsafe(started, Effect.succeed(signal)); + return new Promise(() => {}); + }; + const fiber = yield* textGeneration + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) + .pipe(Effect.forkChild); + const signal = yield* Deferred.await(started); + + const otherStarted = yield* Deferred.make(); + const otherReply = Promise.withResolvers<{ data: { parts: ReadonlyArray } }>(); + runtimeMock.state.sessionResult = { data: { id: "other-session" } }; + runtimeMock.state.onPrompt = (otherSignal) => { + Deferred.doneUnsafe(otherStarted, Effect.succeed(otherSignal)); + return otherReply.promise; + }; + const otherFiber = yield* textGeneration + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) + .pipe(Effect.forkChild); + const otherSignal = yield* Deferred.await(otherStarted); + yield* Fiber.interrupt(fiber); + + const exit = yield* Fiber.await(fiber); + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); + expect(signal?.aborted).toBe(true); + expect(otherSignal?.aborted).toBe(false); + expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]); + expect(runtimeMock.state.closeCalls).toEqual([]); + + otherReply.resolve({ + data: { + parts: [{ type: "text", text: '{"subject":"Other generation completed","body":""}' }], + }, + }); + expect((yield* Fiber.join(otherFiber)).subject).toBe("Other generation completed"); + expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]); + expect(runtimeMock.state.promptUrls).toEqual([ + "http://127.0.0.1:4301", + "http://127.0.0.1:4301", + ]); + expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]); + expect(runtimeMock.state.closeCalls).toEqual([]); + }), + ), ); it.effect.each(["failure", "timeout"] as const)( @@ -323,14 +341,14 @@ it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => { }); return withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) => Effect.gen(function* () { - const promptStarted = Promise.withResolvers(); - const abortStarted = Promise.withResolvers(); - runtimeMock.state.onPrompt = () => { - promptStarted.resolve(); + const promptStarted = yield* Deferred.make(); + const abortStarted = yield* Deferred.make(); + runtimeMock.state.onPrompt = (signal) => { + Deferred.doneUnsafe(promptStarted, Effect.succeed(signal)); return new Promise(() => {}); }; runtimeMock.state.onAbort = (signal) => { - abortStarted.resolve(signal); + Deferred.doneUnsafe(abortStarted, Effect.succeed(signal)); return outcome === "failure" ? Promise.reject(new Error("Synthetic SDK response: confidential-value")) : new Promise(() => {}); @@ -338,9 +356,9 @@ it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => { const fiber = yield* textGeneration .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT) .pipe(Effect.forkChild); - yield* Effect.promise(() => promptStarted.promise); + const promptSignal = yield* Deferred.await(promptStarted); const cancellation = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild); - const abortSignal = yield* Effect.promise(() => abortStarted.promise); + const abortSignal = yield* Deferred.await(abortStarted); if (outcome === "timeout") { yield* TestClock.adjust("10 seconds"); } @@ -348,17 +366,20 @@ it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => { const exit = yield* Fiber.await(fiber); expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); + expect(promptSignal?.aborted).toBe(true); expect(runtimeMock.state.abortCalls).toEqual(["http://127.0.0.1:9999/session"]); + expect(runtimeMock.state.startCalls).toEqual([]); + expect(runtimeMock.state.closeCalls).toEqual([]); if (outcome === "timeout") expect(abortSignal?.aborted).toBe(true); expect(messages).toEqual([ [ "Failed to stop cancelled OpenCode text generation.", { - operation: expect.any(String), + operation: "generateCommitMessage", cwd: DEFAULT_COMMIT_MESSAGE_INPUT.cwd, sessionId: "http://127.0.0.1:9999/session", - providerId: expect.any(String), - modelId: expect.any(String), + providerId: "openai", + modelId: "gpt-5", }, ], ]);