@devries-cameron20 / t3code Mirror · read-only / commits / 23d75ef43d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 01:45 UTC

fix(opencode): stop cancelled text generation sessions (#10606)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Aditya Garud committed Oct 20, 2026 at 00:35 UTC 23d75ef43dab1ddd6142921a693d8a2abe6fdbd9
2 files changed +199 -16
packages/provider-opencode/src/server/textGeneration.test.ts
+162 -2
@@ -2,9 +2,14 @@ import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
2 import { OpenCodeSettings } from "../settings.ts";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { it } from "@effect/vitest";
5 +import * as Cause from "effect/Cause";
6 +import * as Deferred from "effect/Deferred";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 +import * as Exit from "effect/Exit";
10 +import * as Fiber from "effect/Fiber";
11 import * as Layer from "effect/Layer";
12 +import * as Logger from "effect/Logger";
13 import * as Schema from "effect/Schema";
14 import * as TestClock from "effect/testing/TestClock";
15 import * as NetService from "@t3tools/shared/Net";
@@ -24,6 +29,12 @@ const runtimeMock = {
29 authHeaders: [] as Array<string | null>,
30 closeCalls: [] as string[],
31 sessionCreateCalls: 0,
32 + abortCalls: [] as string[],
33 + onSessionCreate: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined,
34 + onPrompt: undefined as
35 + | ((signal?: AbortSignal) => Promise<{ data: { parts: ReadonlyArray<unknown> } }>)
36 + | undefined,
37 + onAbort: undefined as ((signal?: AbortSignal) => Promise<never>) | undefined,
38 connectionError: undefined as Error | undefined,
39 sessionCreateError: undefined as unknown,
40 sessionResult: undefined as { data?: { id: string } } | undefined,
@@ -39,6 +50,10 @@ const runtimeMock = {
50 this.state.authHeaders.length = 0;
51 this.state.closeCalls.length = 0;
52 this.state.sessionCreateCalls = 0;
53 + this.state.abortCalls.length = 0;
54 + this.state.onSessionCreate = undefined;
55 + this.state.onPrompt = undefined;
56 + this.state.onAbort = undefined;
57 this.state.connectionError = undefined;
58 this.state.sessionCreateError = undefined;
59 this.state.sessionResult = undefined;
@@ -93,19 +108,34 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
108 createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
109 ({
110 session: {
96 - create: async () => {
111 + create: async (_input: unknown, options?: { readonly signal?: AbortSignal }) => {
112 runtimeMock.state.sessionCreateCalls += 1;
113 + if (runtimeMock.state.onSessionCreate) {
114 + return runtimeMock.state.onSessionCreate(options?.signal);
115 + }
116 if (runtimeMock.state.sessionCreateError !== undefined) {
117 throw runtimeMock.state.sessionCreateError;
118 }
119 return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
120 },
103 - prompt: async (input: { readonly parts: ReadonlyArray<unknown> }) => {
121 + abort: async (
122 + input: { readonly sessionID: string },
123 + options?: { readonly signal?: AbortSignal },
124 + ) => {
125 + runtimeMock.state.abortCalls.push(input.sessionID);
126 + if (runtimeMock.state.onAbort) return runtimeMock.state.onAbort(options?.signal);
127 + return { data: true };
128 + },
129 + prompt: async (
130 + input: { readonly parts: ReadonlyArray<unknown> },
131 + options?: { readonly signal?: AbortSignal },
132 + ) => {
133 runtimeMock.state.promptUrls.push(baseUrl);
134 runtimeMock.state.promptParts.push(input.parts);
135 runtimeMock.state.authHeaders.push(
136 serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
137 );
138 + if (runtimeMock.state.onPrompt) return runtimeMock.state.onPrompt(options?.signal);
139 if (runtimeMock.state.promptRequestError !== undefined) {
140 throw runtimeMock.state.promptRequestError;
141 }
@@ -228,6 +258,136 @@ const advanceIdleClock = Effect.gen(function* () {
258 });
259
260 it.layer(layerOpenCodeTextGenerationTest)("OpenCodeTextGeneration", (it) => {
261 + it.effect("cancels an in-flight session creation before prompting", () =>
262 + withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
263 + Effect.gen(function* () {
264 + const started = yield* Deferred.make<AbortSignal | undefined>();
265 + runtimeMock.state.onSessionCreate = (signal) => {
266 + Deferred.doneUnsafe(started, Effect.succeed(signal));
267 + return new Promise<never>(() => {});
268 + };
269 + const fiber = yield* textGeneration
270 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
271 + .pipe(Effect.forkChild);
272 + const signal = yield* Deferred.await(started);
273 + yield* Fiber.interrupt(fiber);
274 +
275 + const exit = yield* Fiber.await(fiber);
276 + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
277 + expect(signal?.aborted).toBe(true);
278 + expect(runtimeMock.state.promptUrls).toEqual([]);
279 + expect(runtimeMock.state.abortCalls).toEqual([]);
280 + }),
281 + ),
282 + );
283 +
284 + it.effect("cancels only its prompt session while another generation uses the shared server", () =>
285 + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
286 + Effect.gen(function* () {
287 + const started = yield* Deferred.make<AbortSignal | undefined>();
288 + runtimeMock.state.sessionResult = { data: { id: "cancelled-session" } };
289 + runtimeMock.state.onPrompt = (signal) => {
290 + Deferred.doneUnsafe(started, Effect.succeed(signal));
291 + return new Promise<never>(() => {});
292 + };
293 + const fiber = yield* textGeneration
294 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
295 + .pipe(Effect.forkChild);
296 + const signal = yield* Deferred.await(started);
297 +
298 + const otherStarted = yield* Deferred.make<AbortSignal | undefined>();
299 + const otherReply = Promise.withResolvers<{ data: { parts: ReadonlyArray<unknown> } }>();
300 + runtimeMock.state.sessionResult = { data: { id: "other-session" } };
301 + runtimeMock.state.onPrompt = (otherSignal) => {
302 + Deferred.doneUnsafe(otherStarted, Effect.succeed(otherSignal));
303 + return otherReply.promise;
304 + };
305 + const otherFiber = yield* textGeneration
306 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
307 + .pipe(Effect.forkChild);
308 + const otherSignal = yield* Deferred.await(otherStarted);
309 + yield* Fiber.interrupt(fiber);
310 +
311 + const exit = yield* Fiber.await(fiber);
312 + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
313 + expect(signal?.aborted).toBe(true);
314 + expect(otherSignal?.aborted).toBe(false);
315 + expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
316 + expect(runtimeMock.state.closeCalls).toEqual([]);
317 +
318 + otherReply.resolve({
319 + data: {
320 + parts: [{ type: "text", text: '{"subject":"Other generation completed","body":""}' }],
321 + },
322 + });
323 + expect((yield* Fiber.join(otherFiber)).subject).toBe("Other generation completed");
324 + expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
325 + expect(runtimeMock.state.promptUrls).toEqual([
326 + "http://127.0.0.1:4301",
327 + "http://127.0.0.1:4301",
328 + ]);
329 + expect(runtimeMock.state.abortCalls).toEqual(["cancelled-session"]);
330 + expect(runtimeMock.state.closeCalls).toEqual([]);
331 + }),
332 + ),
333 + );
334 +
335 + it.effect.each(["failure", "timeout"] as const)(
336 + "preserves cancellation when the session abort ends in %s",
337 + (outcome) => {
338 + const messages: unknown[] = [];
339 + const logger = Logger.make<unknown, void>(({ message }) => {
340 + messages.push(message);
341 + });
342 + return withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
343 + Effect.gen(function* () {
344 + const promptStarted = yield* Deferred.make<AbortSignal | undefined>();
345 + const abortStarted = yield* Deferred.make<AbortSignal | undefined>();
346 + runtimeMock.state.onPrompt = (signal) => {
347 + Deferred.doneUnsafe(promptStarted, Effect.succeed(signal));
348 + return new Promise<never>(() => {});
349 + };
350 + runtimeMock.state.onAbort = (signal) => {
351 + Deferred.doneUnsafe(abortStarted, Effect.succeed(signal));
352 + return outcome === "failure"
353 + ? Promise.reject(new Error("Synthetic SDK response: confidential-value"))
354 + : new Promise<never>(() => {});
355 + };
356 + const fiber = yield* textGeneration
357 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
358 + .pipe(Effect.forkChild);
359 + const promptSignal = yield* Deferred.await(promptStarted);
360 + const cancellation = yield* Fiber.interrupt(fiber).pipe(Effect.forkChild);
361 + const abortSignal = yield* Deferred.await(abortStarted);
362 + if (outcome === "timeout") {
363 + yield* TestClock.adjust("10 seconds");
364 + }
365 + yield* Fiber.join(cancellation);
366 +
367 + const exit = yield* Fiber.await(fiber);
368 + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
369 + expect(promptSignal?.aborted).toBe(true);
370 + expect(runtimeMock.state.abortCalls).toEqual(["http://127.0.0.1:9999/session"]);
371 + expect(runtimeMock.state.startCalls).toEqual([]);
372 + expect(runtimeMock.state.closeCalls).toEqual([]);
373 + if (outcome === "timeout") expect(abortSignal?.aborted).toBe(true);
374 + expect(messages).toEqual([
375 + [
376 + "Failed to stop cancelled OpenCode text generation.",
377 + {
378 + operation: "generateCommitMessage",
379 + cwd: DEFAULT_COMMIT_MESSAGE_INPUT.cwd,
380 + sessionId: "http://127.0.0.1:9999/session",
381 + providerId: "openai",
382 + modelId: "gpt-5",
383 + },
384 + ],
385 + ]);
386 + }),
387 + ).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
388 + },
389 + );
390 +
391 it.effect("excludes generic files from thread title generation", () =>
392 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
393 Effect.gen(function* () {
packages/provider-opencode/src/server/textGeneration.ts
+37 -14
@@ -186,11 +186,14 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
186 ...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
187 });
188 const session = yield* Effect.tryPromise({
189 - try: () =>
190 - client.session.create({
191 - title: `T3 Code ${input.operation}`,
192 - permission: [{ permission: "*", pattern: "*", action: "deny" }],
193 - }),
189 + try: (signal) =>
190 + client.session.create(
191 + {
192 + title: `T3 Code ${input.operation}`,
193 + permission: [{ permission: "*", pattern: "*", action: "deny" }],
194 + },
195 + { signal },
196 + ),
197 catch: (cause) =>
198 new OpenCodeTextGenerationSessionRequestError({
199 operation: input.operation,
@@ -215,20 +218,40 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
218 };
219
220 const result = yield* Effect.tryPromise({
218 - try: () =>
219 - client.session.prompt({
220 - sessionID: session.data.id,
221 - model: parsedModel,
222 - ...(selectedAgent ? { agent: selectedAgent } : {}),
223 - ...(selectedVariant ? { variant: selectedVariant } : {}),
224 - parts: [{ type: "text", text: input.prompt }, ...fileParts],
225 - }),
221 + try: (signal) =>
222 + client.session.prompt(
223 + {
224 + sessionID: session.data.id,
225 + model: parsedModel,
226 + ...(selectedAgent ? { agent: selectedAgent } : {}),
227 + ...(selectedVariant ? { variant: selectedVariant } : {}),
228 + parts: [{ type: "text", text: input.prompt }, ...fileParts],
229 + },
230 + { signal },
231 + ),
232 catch: (cause) =>
233 new OpenCodeTextGenerationPromptRequestError({
234 ...promptContext,
235 cause,
236 }),
231 - });
237 + }).pipe(
238 + // Disconnecting the HTTP request does not stop work in a shared or external server.
239 + Effect.onInterrupt(() =>
240 + OpenCodeRuntime.runOpenCodeSdk("session.abort", (signal) =>
241 + client.session.abort({ sessionID: session.data.id }, { signal }),
242 + ).pipe(
243 + Effect.interruptible,
244 + Effect.timeout("10 seconds"),
245 + Effect.catch(() =>
246 + Effect.logWarning(
247 + "Failed to stop cancelled OpenCode text generation.",
248 + promptContext,
249 + ),
250 + ),
251 + Effect.asVoid,
252 + ),
253 + ),
254 + );
255 const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
256 if (promptFailure) {
257 return yield* new OpenCodeTextGenerationPromptResponseError({