Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 6 additions & 49 deletions apps/server/src/git/Layers/CursorTextGeneration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ import {
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle } from "../Utils.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
Expand All @@ -25,54 +30,6 @@ import { ServerSettingsService } from "../../serverSettings.ts";

const CURSOR_TIMEOUT_MS = 180_000;

function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}

const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}

let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}

if (char === '"') {
inString = true;
continue;
}

if (char === "{") {
depth += 1;
continue;
}

if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}

return trimmed.slice(start);
}

function mapCursorAcpError(
operation:
| "generateCommitMessage"
Expand Down
81 changes: 73 additions & 8 deletions apps/server/src/git/Layers/OpenCodeTextGeneration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ const runtimeMock = vi.hoisted(() => {
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
promptResult: undefined as { data?: { info?: { structured?: unknown } } } | undefined,
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
};

return {
Expand Down Expand Up @@ -63,12 +65,15 @@ vi.mock("../../provider/opencodeRuntime.ts", async () => {
return (
runtimeMock.state.promptResult ?? {
data: {
info: {
structured: {
subject: "Improve OpenCode reuse",
body: "Reuse one server for the full action.",
parts: [
{
type: "text",
text: JSON.stringify({
subject: "Improve OpenCode reuse",
body: "Reuse one server for the full action.",
}),
},
},
],
},
}
);
Expand Down Expand Up @@ -198,7 +203,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) =>
}).pipe(Effect.provide(TestClock.layer())),
);

it.effect("returns a typed missing-output error when OpenCode omits info.structured", () =>
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = { data: {} };
const textGeneration = yield* TextGeneration;
Expand All @@ -213,7 +218,67 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) =>
})
.pipe(Effect.flip);

expect(error.message).toContain("OpenCode returned no structured output.");
expect(error.message).toContain("OpenCode returned empty output.");
}),
);

it.effect("parses JSON returned as plain text output", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [
{
type: "text",
text: 'Here is the result:\n{"subject":"Tighten OpenCode parsing","body":"Handle JSON text output locally."}',
},
],
},
};
const textGeneration = yield* TextGeneration;

const result = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});

expect(result).toEqual({
subject: "Tighten OpenCode parsing",
body: "Handle JSON text output locally.",
});
}),
);

it.effect("surfaces the upstream OpenCode structured-output error message", () =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
info: {
error: {
name: "StructuredOutputError",
data: {
message: "Model did not produce structured output",
retries: 2,
},
},
},
},
};
const textGeneration = yield* TextGeneration;

const error = yield* textGeneration
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);

expect(error.message).toContain("Model did not produce structured output");
}),
);
});
Expand Down
68 changes: 57 additions & 11 deletions apps/server/src/git/Layers/OpenCodeTextGeneration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ import {
} from "../Prompts.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import {
createOpenCodeSdkClient,
Expand All @@ -35,6 +35,49 @@ import {

const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;

function getOpenCodePromptErrorMessage(error: unknown): string | null {
if (!error || typeof error !== "object") {
return null;
}

const message =
"data" in error &&
error.data &&
typeof error.data === "object" &&
"message" in error.data &&
typeof error.data.message === "string"
? error.data.message.trim()
: "";
if (message.length > 0) {
return message;
}

if ("name" in error && typeof error.name === "string") {
const name = error.name.trim();
return name.length > 0 ? name : null;
}

return null;
}

function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
return (parts ?? [])
.flatMap((part) => {
if (!part || typeof part !== "object") {
return [];
}
if (!("type" in part) || part.type !== "text") {
return [];
}
if (!("text" in part) || typeof part.text !== "string") {
return [];
}
return [part.text];
})
.join("")
.trim();
}

interface SharedOpenCodeTextGenerationServerState {
server: OpenCodeServerProcess | null;
binaryPath: string | null;
Expand Down Expand Up @@ -245,17 +288,18 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
...(input.modelSelection.options?.variant
? { variant: input.modelSelection.options.variant }
: {}),
format: {
type: "json_schema",
schema: toJsonSchemaObject(input.outputSchemaJson) as Record<string, unknown>,
},
Comment on lines -248 to -251
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @nexxeln is your structured data not reliable?

parts: [{ type: "text", text: input.prompt }, ...fileParts],
});
const structured = result.data?.info?.structured;
if (structured === undefined) {
throw new Error("OpenCode returned no structured output.");
const info = result.data?.info;
const errorMessage = getOpenCodePromptErrorMessage(info?.error);
if (errorMessage) {
throw new Error(errorMessage);
}
const rawText = getOpenCodeTextResponse(result.data?.parts);
if (rawText.length === 0) {
throw new Error("OpenCode returned empty output.");
}
return structured;
return rawText;
},
catch: (cause) =>
new TextGenerationError({
Expand All @@ -266,7 +310,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
}),
});

const structuredOutput =
const rawOutput =
settings.serverUrl.length > 0
? yield* runAgainstServer({ url: settings.serverUrl })
: yield* Effect.acquireUseRelease(
Expand All @@ -278,7 +322,9 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
releaseSharedServer,
);

return yield* Schema.decodeUnknownEffect(input.outputSchemaJson)(structuredOutput).pipe(
return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
extractJsonObject(rawOutput),
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
Expand Down
48 changes: 48 additions & 0 deletions apps/server/src/git/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,54 @@ export function limitSection(value: string, maxChars: number): string {
return `${truncated}\n\n[truncated]`;
}

export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}

const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}

let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}

if (char === '"') {
inString = true;
continue;
}

if (char === "{") {
depth += 1;
continue;
}

if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}

return trimmed.slice(start);
}

/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
Expand Down
Loading