@devries-cameron20 / t3code Mirror · read-only / commits / 8c1605b383
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 24, 21:30 UTC

[codex] Structure OpenCode text generation failures (#3472)

Co-authored-by: codex <codex@users.noreply.github.com>

Julius Marminge committed Jun 20, 2026 at 20:20 UTC 8c1605b38327176bae94c33bbc6de86e8b09fe02
2 files changed +353 -88
apps/server/src/textGeneration/OpenCodeTextGeneration.test.ts
+124 -21
@@ -1,4 +1,4 @@
1 -import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
1 +import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { it } from "@effect/vitest";
4 import * as Duration from "effect/Duration";
@@ -11,8 +11,8 @@ import { beforeEach, expect } from "vite-plus/test";
11
12 import * as ServerConfig from "../config.ts";
13 import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
14 +import * as OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
15 import * as TextGeneration from "./TextGeneration.ts";
15 -import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
16
17 const runtimeMock = {
18 state: {
@@ -20,8 +20,11 @@ const runtimeMock = {
20 promptUrls: [] as string[],
21 authHeaders: [] as Array<string | null>,
22 closeCalls: [] as string[],
23 + sessionCreateError: undefined as unknown,
24 + sessionResult: undefined as { data?: { id: string } } | undefined,
25 + promptRequestError: undefined as unknown,
26 promptResult: undefined as
24 - | { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
27 + | { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
28 | undefined,
29 },
30 reset() {
@@ -29,6 +32,9 @@ const runtimeMock = {
32 this.state.promptUrls.length = 0;
33 this.state.authHeaders.length = 0;
34 this.state.closeCalls.length = 0;
35 + this.state.sessionCreateError = undefined;
36 + this.state.sessionResult = undefined;
37 + this.state.promptRequestError = undefined;
38 this.state.promptResult = undefined;
39 },
40 };
@@ -61,12 +67,20 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
67 createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
68 ({
69 session: {
64 - create: async () => ({ data: { id: `${baseUrl}/session` } }),
70 + create: async () => {
71 + if (runtimeMock.state.sessionCreateError !== undefined) {
72 + throw runtimeMock.state.sessionCreateError;
73 + }
74 + return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
75 + },
76 prompt: async () => {
77 runtimeMock.state.promptUrls.push(baseUrl);
78 runtimeMock.state.authHeaders.push(
79 serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
80 );
81 + if (runtimeMock.state.promptRequestError !== undefined) {
82 + throw runtimeMock.state.promptRequestError;
83 + }
84 return (
85 runtimeMock.state.promptResult ?? {
86 data: {
@@ -99,6 +113,13 @@ const DEFAULT_TEST_MODEL_SELECTION = {
113 instanceId: ProviderInstanceId.make("opencode"),
114 model: "openai/gpt-5",
115 };
116 +const DEFAULT_COMMIT_MESSAGE_INPUT = {
117 + cwd: process.cwd(),
118 + branch: "feature/opencode-reuse",
119 + stagedSummary: "M README.md",
120 + stagedPatch: "diff --git a/README.md b/README.md",
121 + modelSelection: DEFAULT_TEST_MODEL_SELECTION,
122 +};
123
124 const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
125
@@ -142,7 +163,7 @@ function withOpenCodeTextGeneration<A, E, R>(
163 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
164 ) {
165 return Effect.gen(function* () {
145 - const textGeneration = yield* makeOpenCodeTextGeneration(settings);
166 + const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
167 return yield* effectFn(textGeneration);
168 }).pipe(Effect.scoped);
169 }
@@ -221,22 +242,99 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
242 ).pipe(Effect.provide(TestClock.layer())),
243 );
244
224 - it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
245 + it.effect("preserves the SDK cause when session creation fails", () =>
246 withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
247 Effect.gen(function* () {
227 - runtimeMock.state.promptResult = { data: {} };
248 + const sdkCause = new Error("session endpoint unavailable");
249 + runtimeMock.state.sessionCreateError = sdkCause;
250
251 const error = yield* textGeneration
230 - .generateCommitMessage({
231 - cwd: process.cwd(),
232 - branch: "feature/opencode-reuse",
233 - stagedSummary: "M README.md",
234 - stagedPatch: "diff --git a/README.md b/README.md",
235 - modelSelection: DEFAULT_TEST_MODEL_SELECTION,
236 - })
252 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
253 + .pipe(Effect.flip);
254 +
255 + expect(error).toBeInstanceOf(TextGenerationError);
256 + expect(error.message).toContain("OpenCode session.create request failed.");
257 + expect(error.cause).toMatchObject({
258 + _tag: "OpenCodeTextGenerationSessionRequestError",
259 + operation: "generateCommitMessage",
260 + cwd: process.cwd(),
261 + cause: sdkCause,
262 + });
263 + expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
264 + }),
265 + ),
266 + );
267 +
268 + it.effect("reports a missing session payload without manufacturing a cause", () =>
269 + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
270 + Effect.gen(function* () {
271 + runtimeMock.state.sessionResult = {};
272 +
273 + const error = yield* textGeneration
274 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
275 + .pipe(Effect.flip);
276 +
277 + expect(error.message).toContain("OpenCode session.create returned no session payload.");
278 + expect(error.cause).toMatchObject({
279 + _tag: "OpenCodeTextGenerationSessionPayloadError",
280 + operation: "generateCommitMessage",
281 + cwd: process.cwd(),
282 + });
283 + expect(error.cause).not.toHaveProperty("cause");
284 + }),
285 + ),
286 + );
287 +
288 + it.effect("preserves the SDK cause and request context when prompting fails", () =>
289 + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
290 + Effect.gen(function* () {
291 + const sdkCause = new Error("prompt endpoint unavailable");
292 + runtimeMock.state.promptRequestError = sdkCause;
293 +
294 + const error = yield* textGeneration
295 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
296 + .pipe(Effect.flip);
297 +
298 + expect(error.message).toContain("OpenCode session.prompt request failed.");
299 + expect(error.cause).toMatchObject({
300 + _tag: "OpenCodeTextGenerationPromptRequestError",
301 + operation: "generateCommitMessage",
302 + cwd: process.cwd(),
303 + sessionId: "http://127.0.0.1:4301/session",
304 + providerId: "openai",
305 + modelId: "gpt-5",
306 + cause: sdkCause,
307 + });
308 + expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
309 + }),
310 + ),
311 + );
312 +
313 + it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
314 + withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
315 + Effect.gen(function* () {
316 + runtimeMock.state.promptResult = {
317 + data: {
318 + parts: [null, { type: "tool" }, { type: "text", text: " " }],
319 + },
320 + };
321 +
322 + const error = yield* textGeneration
323 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
324 .pipe(Effect.flip);
325
326 expect(error.message).toContain("OpenCode returned empty output.");
327 + expect(error.cause).toMatchObject({
328 + _tag: "OpenCodeTextGenerationEmptyOutputError",
329 + operation: "generateCommitMessage",
330 + cwd: process.cwd(),
331 + sessionId: "http://127.0.0.1:4301/session",
332 + providerId: "openai",
333 + modelId: "gpt-5",
334 + responsePartCount: 3,
335 + textPartCount: 1,
336 + });
337 + expect(error.cause).not.toHaveProperty("cause");
338 }),
339 ),
340 );
@@ -289,16 +387,21 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
387 };
388
389 const error = yield* textGeneration
292 - .generateCommitMessage({
293 - cwd: process.cwd(),
294 - branch: "feature/opencode-reuse",
295 - stagedSummary: "M README.md",
296 - stagedPatch: "diff --git a/README.md b/README.md",
297 - modelSelection: DEFAULT_TEST_MODEL_SELECTION,
298 - })
390 + .generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
391 .pipe(Effect.flip);
392
393 expect(error.message).toContain("Model did not produce structured output");
394 + expect(error.cause).toMatchObject({
395 + _tag: "OpenCodeTextGenerationPromptResponseError",
396 + operation: "generateCommitMessage",
397 + cwd: process.cwd(),
398 + sessionId: "http://127.0.0.1:4301/session",
399 + providerId: "openai",
400 + modelId: "gpt-5",
401 + providerErrorName: "StructuredOutputError",
402 + providerMessage: "Model did not produce structured output",
403 + });
404 + expect(error.cause).not.toHaveProperty("cause");
405 }),
406 ),
407 );
apps/server/src/textGeneration/OpenCodeTextGeneration.ts
+229 -67
@@ -6,6 +6,7 @@ import * as Scope from "effect/Scope";
6 import * as Semaphore from "effect/Semaphore";
7
8 import {
9 + NonNegativeInt,
10 TextGenerationError,
11 type ChatAttachment,
12 type ModelSelection,
@@ -33,11 +34,106 @@ import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
34
35 const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
36
36 -function getOpenCodePromptErrorMessage(error: unknown): string | null {
37 +const OpenCodeTextGenerationOperation = Schema.Literals([
38 + "generateCommitMessage",
39 + "generatePrContent",
40 + "generateBranchName",
41 + "generateThreadTitle",
42 +]);
43 +
44 +type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
45 +
46 +const openCodeTextGenerationErrorContext = {
47 + operation: OpenCodeTextGenerationOperation,
48 + cwd: Schema.String,
49 +};
50 +
51 +export class OpenCodeTextGenerationSessionRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionRequestError>()(
52 + "OpenCodeTextGenerationSessionRequestError",
53 + {
54 + ...openCodeTextGenerationErrorContext,
55 + cause: Schema.Defect(),
56 + },
57 +) {
58 + override get message(): string {
59 + return `OpenCode session creation request failed for ${this.operation} in ${this.cwd}.`;
60 + }
61 +}
62 +
63 +export class OpenCodeTextGenerationSessionPayloadError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionPayloadError>()(
64 + "OpenCodeTextGenerationSessionPayloadError",
65 + openCodeTextGenerationErrorContext,
66 +) {
67 + override get message(): string {
68 + return `OpenCode session.create returned no session payload for ${this.operation} in ${this.cwd}.`;
69 + }
70 +}
71 +
72 +const openCodePromptErrorContext = {
73 + ...openCodeTextGenerationErrorContext,
74 + sessionId: Schema.String,
75 + providerId: Schema.String,
76 + modelId: Schema.String,
77 +};
78 +
79 +export class OpenCodeTextGenerationPromptRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptRequestError>()(
80 + "OpenCodeTextGenerationPromptRequestError",
81 + {
82 + ...openCodePromptErrorContext,
83 + cause: Schema.Defect(),
84 + },
85 +) {
86 + override get message(): string {
87 + return `OpenCode prompt request failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}).`;
88 + }
89 +}
90 +
91 +export class OpenCodeTextGenerationPromptResponseError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptResponseError>()(
92 + "OpenCodeTextGenerationPromptResponseError",
93 + {
94 + ...openCodePromptErrorContext,
95 + providerErrorName: Schema.optional(Schema.String),
96 + providerMessage: Schema.String,
97 + },
98 +) {
99 + override get message(): string {
100 + const providerError = this.providerErrorName ? ` ${this.providerErrorName}` : "";
101 + return `OpenCode prompt${providerError} failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}): ${this.providerMessage}`;
102 + }
103 +}
104 +
105 +export class OpenCodeTextGenerationEmptyOutputError extends Schema.TaggedErrorClass<OpenCodeTextGenerationEmptyOutputError>()(
106 + "OpenCodeTextGenerationEmptyOutputError",
107 + {
108 + ...openCodePromptErrorContext,
109 + responsePartCount: NonNegativeInt,
110 + textPartCount: NonNegativeInt,
111 + },
112 +) {
113 + override get message(): string {
114 + return `OpenCode returned empty output for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}, ${this.responsePartCount} response parts, ${this.textPartCount} text parts).`;
115 + }
116 +}
117 +
118 +interface OpenCodePromptFailure {
119 + readonly name?: string;
120 + readonly message: string;
121 +}
122 +
123 +interface OpenCodeTextPart {
124 + readonly type: "text";
125 + readonly text: string;
126 +}
127 +
128 +function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null {
129 if (!error || typeof error !== "object") {
130 return null;
131 }
132
133 + const name =
134 + "name" in error && typeof error.name === "string" && error.name.trim().length > 0
135 + ? error.name.trim()
136 + : undefined;
137 const message =
138 "data" in error &&
139 error.data &&
@@ -47,31 +143,34 @@ function getOpenCodePromptErrorMessage(error: unknown): string | null {
143 ? error.data.message.trim()
144 : "";
145 if (message.length > 0) {
50 - return message;
146 + return {
147 + ...(name ? { name } : {}),
148 + message,
149 + };
150 }
151
53 - if ("name" in error && typeof error.name === "string") {
54 - const name = error.name.trim();
55 - return name.length > 0 ? name : null;
152 + if (name) {
153 + return { name, message: name };
154 }
155
156 return null;
157 }
158
159 +function isOpenCodeTextPart(part: unknown): part is OpenCodeTextPart {
160 + return (
161 + part !== null &&
162 + typeof part === "object" &&
163 + "type" in part &&
164 + part.type === "text" &&
165 + "text" in part &&
166 + typeof part.text === "string"
167 + );
168 +}
169 +
170 function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
171 return (parts ?? [])
63 - .flatMap((part) => {
64 - if (!part || typeof part !== "object") {
65 - return [];
66 - }
67 - if (!("type" in part) || part.type !== "text") {
68 - return [];
69 - }
70 - if (!("text" in part) || typeof part.text !== "string") {
71 - return [];
72 - }
73 - return [part.text];
74 - })
172 + .filter(isOpenCodeTextPart)
173 + .map((part) => part.text)
174 .join("")
175 .trim();
176 }
@@ -260,11 +359,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
359 );
360
361 const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
263 - readonly operation:
264 - | "generateCommitMessage"
265 - | "generatePrContent"
266 - | "generateBranchName"
267 - | "generateThreadTitle";
362 + readonly operation: OpenCodeTextGenerationOperation;
363 readonly cwd: string;
364 readonly prompt: string;
365 readonly outputSchemaJson: S;
@@ -285,54 +380,121 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
380 resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
381 });
382
288 - const runAgainstServer = (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) =>
289 - Effect.tryPromise({
290 - try: async () => {
291 - const client = openCodeRuntime.createOpenCodeSdkClient({
292 - baseUrl: server.url,
293 - directory: input.cwd,
294 - ...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
295 - ? { serverPassword: openCodeSettings.serverPassword }
296 - : {}),
383 + const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
384 + function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
385 + const client = openCodeRuntime.createOpenCodeSdkClient({
386 + baseUrl: server.url,
387 + directory: input.cwd,
388 + ...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
389 + ? { serverPassword: openCodeSettings.serverPassword }
390 + : {}),
391 + });
392 + const session = yield* Effect.tryPromise({
393 + try: () =>
394 + client.session.create({
395 + title: `T3 Code ${input.operation}`,
396 + permission: [{ permission: "*", pattern: "*", action: "deny" }],
397 + }),
398 + catch: (cause) =>
399 + new OpenCodeTextGenerationSessionRequestError({
400 + operation: input.operation,
401 + cwd: input.cwd,
402 + cause,
403 + }),
404 + });
405 + if (!session.data) {
406 + return yield* new OpenCodeTextGenerationSessionPayloadError({
407 + operation: input.operation,
408 + cwd: input.cwd,
409 });
298 - const session = await client.session.create({
299 - title: `T3 Code ${input.operation}`,
300 - permission: [{ permission: "*", pattern: "*", action: "deny" }],
410 + }
411 + const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
412 + const selectedVariant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
413 + const promptContext = {
414 + operation: input.operation,
415 + cwd: input.cwd,
416 + sessionId: session.data.id,
417 + providerId: parsedModel.providerID,
418 + modelId: parsedModel.modelID,
419 + };
420 +
421 + const result = yield* Effect.tryPromise({
422 + try: () =>
423 + client.session.prompt({
424 + sessionID: session.data.id,
425 + model: parsedModel,
426 + ...(selectedAgent ? { agent: selectedAgent } : {}),
427 + ...(selectedVariant ? { variant: selectedVariant } : {}),
428 + parts: [{ type: "text", text: input.prompt }, ...fileParts],
429 + }),
430 + catch: (cause) =>
431 + new OpenCodeTextGenerationPromptRequestError({
432 + ...promptContext,
433 + cause,
434 + }),
435 + });
436 + const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
437 + if (promptFailure) {
438 + return yield* new OpenCodeTextGenerationPromptResponseError({
439 + ...promptContext,
440 + ...(promptFailure.name ? { providerErrorName: promptFailure.name } : {}),
441 + providerMessage: promptFailure.message,
442 });
302 - if (!session.data) {
303 - throw new Error("OpenCode session.create returned no session payload.");
304 - }
305 - const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
306 - const selectedVariant = getModelSelectionStringOptionValue(
307 - input.modelSelection,
308 - "variant",
309 - );
310 -
311 - const result = await client.session.prompt({
312 - sessionID: session.data.id,
313 - model: parsedModel,
314 - ...(selectedAgent ? { agent: selectedAgent } : {}),
315 - ...(selectedVariant ? { variant: selectedVariant } : {}),
316 - parts: [{ type: "text", text: input.prompt }, ...fileParts],
443 + }
444 + const responseParts = result.data?.parts ?? [];
445 + const rawText = getOpenCodeTextResponse(responseParts);
446 + if (rawText.length === 0) {
447 + return yield* new OpenCodeTextGenerationEmptyOutputError({
448 + ...promptContext,
449 + responsePartCount: responseParts.length,
450 + textPartCount: responseParts.filter(isOpenCodeTextPart).length,
451 });
318 - const info = result.data?.info;
319 - const errorMessage = getOpenCodePromptErrorMessage(info?.error);
320 - if (errorMessage) {
321 - throw new Error(errorMessage);
322 - }
323 - const rawText = getOpenCodeTextResponse(result.data?.parts);
324 - if (rawText.length === 0) {
325 - throw new Error("OpenCode returned empty output.");
326 - }
327 - return rawText;
328 - },
329 - catch: (cause) =>
330 - new TextGenerationError({
331 - operation: input.operation,
332 - detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
333 - cause,
334 - }),
335 - });
452 + }
453 + return rawText;
454 + },
455 + Effect.catchTags({
456 + OpenCodeTextGenerationSessionRequestError: (cause) =>
457 + Effect.fail(
458 + new TextGenerationError({
459 + operation: cause.operation,
460 + detail: "OpenCode session.create request failed.",
461 + cause,
462 + }),
463 + ),
464 + OpenCodeTextGenerationSessionPayloadError: (cause) =>
465 + Effect.fail(
466 + new TextGenerationError({
467 + operation: cause.operation,
468 + detail: "OpenCode session.create returned no session payload.",
469 + cause,
470 + }),
471 + ),
472 + OpenCodeTextGenerationPromptRequestError: (cause) =>
473 + Effect.fail(
474 + new TextGenerationError({
475 + operation: cause.operation,
476 + detail: "OpenCode session.prompt request failed.",
477 + cause,
478 + }),
479 + ),
480 + OpenCodeTextGenerationPromptResponseError: (cause) =>
481 + Effect.fail(
482 + new TextGenerationError({
483 + operation: cause.operation,
484 + detail: cause.providerMessage,
485 + cause,
486 + }),
487 + ),
488 + OpenCodeTextGenerationEmptyOutputError: (cause) =>
489 + Effect.fail(
490 + new TextGenerationError({
491 + operation: cause.operation,
492 + detail: "OpenCode returned empty output.",
493 + cause,
494 + }),
495 + ),
496 + }),
497 + );
498
499 const rawOutput =
500 openCodeSettings.serverUrl.length > 0