Skip to content
TypeScript

fix(server): handle JSON-wrapped titles and verbose Claude output (#10446)

Jono Kemball52b2bf77a941
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
index fe95c8649ea..361dcb35fb1 100644
--- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
@@ -394,6 +394,100 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
}),
);
+ for (const verbose of [false, true]) {
+ it.effect(`unwraps a JSON title in ${verbose ? "verbose" : "normal"} Claude output`, () => {
+ const result = {
+ type: "result",
+ structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
+ };
+ return withFakeClaudeEnv(
+ { output: JSON.stringify(verbose ? [result] : result) },
+ (textGeneration) =>
+ Effect.gen(function* () {
+ const generated = yield* textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Refresh ev-stg APP ASG instances",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
+ },
+ });
+
+ expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
+ }),
+ );
+ });
+ }
+
+ for (const previousTitle of [undefined, "Old thread title"]) {
+ it.effect(
+ `reads the result from verbose Claude output when ${previousTitle ? "regenerating" : "generating"} a title`,
+ () =>
+ withFakeClaudeEnv(
+ {
+ output: JSON.stringify([
+ { type: "system", subtype: "init" },
+ { type: "assistant", message: { content: [] } },
+ { type: "user", message: { content: [] } },
+ { type: "rate_limit_event" },
+ {
+ type: "result",
+ subtype: "success",
+ result: '{"title":"Refresh ev-stg APP ASG Instances"}',
+ structured_output: { title: "Refresh ev-stg APP ASG Instances" },
+ },
+ ]),
+ },
+ (textGeneration) =>
+ Effect.gen(function* () {
+ const generated = yield* textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Refresh ev-stg APP ASG instances",
+ previousTitle,
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
+ },
+ });
+
+ expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
+ }),
+ ),
+ );
+ }
+
+ for (const [name, output] of [
+ ["empty message array", []],
+ ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
+ ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
+ [
+ "final result without structured output",
+ [
+ { type: "result", structured_output: { title: "Earlier result" } },
+ { type: "result", subtype: "error_max_structured_output_retries" },
+ ],
+ ],
+ ] as const) {
+ it.effect(`rejects verbose Claude output with ${name}`, () =>
+ withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(
+ textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Name this thread",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
+ },
+ }),
+ );
+
+ expect(error._tag).toBe("TextGenerationError");
+ }),
+ ),
+ );
+ }
+
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
index e5b13b70f1b..1d068e8b998 100644
--- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts
+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
@@ -53,14 +53,21 @@ const CLAUDE_TIMEOUT_MS = 180_000;
/**
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
- * We only care about `structured_output`.
+ * Verbose mode wraps the result in an array of conversation messages.
*/
const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
+const ClaudeOutputMessage = Schema.Struct({
+ type: Schema.String,
+ structured_output: Schema.optionalKey(Schema.Unknown),
+});
+const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
-const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
+const decodeClaudeOutput = Schema.decodeEffect(
+ Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
+);
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
claudeSettings: ClaudeSettings,
@@ -254,7 +261,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
),
);
- const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(
+ const output = yield* decodeClaudeOutput(rawStdout).pipe(
Effect.catchTags({
SchemaError: (cause) =>
Effect.fail(
@@ -266,9 +273,12 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
),
}),
);
+ const envelope = isClaudeOutputEnvelope(output)
+ ? output
+ : output.findLast((message) => message.type === "result");
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
- return yield* decodeOutput(envelope.structured_output).pipe(
+ return yield* decodeOutput(envelope?.structured_output).pipe(
Effect.catchTags({
SchemaError: (cause) =>
Effect.fail(
diff --git a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts
index 05f45b4cb3b..ea178401b6e 100644
--- a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts
+++ b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts
@@ -216,6 +216,35 @@ describe("buildThreadTitlePrompt", () => {
});
describe("sanitizeThreadTitle", () => {
+ it.each([
+ '{"title": "Refresh ev-stg APP ASG instances"}',
+ '{\n "title": "Refresh ev-stg APP ASG instances"\n}',
+ ])("unwraps a JSON title before normalizing: %s", (raw) => {
+ expect(sanitizeThreadTitle(raw)).toBe("Refresh ev-stg APP ASG instances");
+ });
+
+ it.each([
+ "Rolling ES Refresh ev-stg",
+ "Fix {title} interpolation",
+ '{"title": 42}',
+ '{"subject": "Fix parsing"}',
+ '{"title": "unfinished}',
+ ])("preserves text that is not a JSON title: %s", (raw) => {
+ expect(sanitizeThreadTitle(raw)).toBe(raw);
+ });
+
+ it("normalizes the extracted title", () => {
+ expect(sanitizeThreadTitle('{"title": " Fix reconnect failures "}')).toBe(
+ "Fix reconnect failures",
+ );
+ expect(sanitizeThreadTitle('{"title": " "}')).toBe("New thread");
+ expect(
+ sanitizeThreadTitle(
+ '{"title": "Reconnect failures after restart because the session state does not recover"}',
+ ),
+ ).toBe("Reconnect failures after restart because the se...");
+ });
+
it("truncates long titles with the shared sidebar-safe limit", () => {
expect(
sanitizeThreadTitle(
diff --git a/apps/server/src/textGeneration/TextGenerationUtils.ts b/apps/server/src/textGeneration/TextGenerationUtils.ts
index ad2911c20f7..7c2f0f28414 100644
--- a/apps/server/src/textGeneration/TextGenerationUtils.ts
+++ b/apps/server/src/textGeneration/TextGenerationUtils.ts
@@ -1,7 +1,11 @@
import { TextGenerationError } from "@t3tools/contracts";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
const isTextGenerationError = Schema.is(TextGenerationError);
+const decodeJsonThreadTitle = Schema.decodeOption(
+ Schema.fromJsonString(Schema.Struct({ title: Schema.String })),
+);
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
@@ -44,7 +48,10 @@ export function sanitizePrTitle(raw: string): string {
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
- const normalized = raw
+ // Unwrap a JSON-formatted title before truncation can cut off the closing brace.
+ const decoded = decodeJsonThreadTitle(raw);
+ const title = Option.isSome(decoded) ? decoded.value.title : raw;
+ const normalized = title
.trim()
.split(/\r?\n/g)[0]
?.trim()
diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md
index b43b58e5262..6d3ee3b1630 100644
--- a/docs/user/providers-claude.md
+++ b/docs/user/providers-claude.md
@@ -37,6 +37,10 @@ state. Claude does not have Codex's shared-home and shadow-home arrangement.
For presets that differ only in API keys or endpoints, use the instance's
**Environment variables**. Variable assignments do not belong in **Launch arguments**.
+Claude Code's verbose mode can stay enabled when you use Claude for text generation, including
+thread titles, branch names, commit messages, and pull request descriptions. On a remote connection,
+T3 Code uses the Claude configuration on the connected server.
+
## Compact long conversations
Set **Auto-compact after** in the Claude provider settings to an integer between