From 41ab8389340613e917b76e8d20b2ee20b5922e12 Mon Sep 17 00:00:00 2001 From: qqqys Date: Mon, 11 May 2026 15:44:52 +0800 Subject: [PATCH 1/5] feat(cli): argument hint + --auto completion for /rename MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #4047. The /rename command supports a structured --auto flag (let the fast model generate a sentence-case title from the conversation), but unlike /model — which advertises --fast via argumentHint and a completion entry — /rename's flag was undocumented inline. Users had to either run the command incorrectly or check the docs to learn about --auto. - argumentHint: '[--auto] []' so the completion menu shows the shape when the user types `/rename` and tabs. - completion: returns null on empty / free-text input (don't shadow the user typing a title) and surfaces --auto when the partial arg is a prefix of it ('-', '--', '--a', '--au', '--auto'). Same shape as /model's --fast handling. Free-text titles intentionally don't auto-complete — there's nothing meaningful to suggest, and offering --auto on every keystroke would feel like noise on `/rename my-feature`. Tests: - pins argumentHint shape - empty partial → null - '-' / '--' / '--a' / '--au' / '--auto' all return the --auto suggestion - 'my-feature' / 'fix bug' / '-x' return null (free-text path) Co-Authored-By: Qwen-Coder --- .../cli/src/ui/commands/renameCommand.test.ts | 43 +++++++++++++++++++ packages/cli/src/ui/commands/renameCommand.ts | 20 +++++++++ 2 files changed, 63 insertions(+) diff --git a/packages/cli/src/ui/commands/renameCommand.test.ts b/packages/cli/src/ui/commands/renameCommand.test.ts index 854b50d52aa..a6b6edb518c 100644 --- a/packages/cli/src/ui/commands/renameCommand.test.ts +++ b/packages/cli/src/ui/commands/renameCommand.test.ts @@ -36,6 +36,49 @@ describe('renameCommand', () => { ); }); + it('exposes an argumentHint covering --auto and ', () => { + // The completion menu reads argumentHint when the user types + // `/rename` and hovers — this is the primary discoverability + // affordance, so pin its shape. + expect(renameCommand.argumentHint).toBe('[--auto] []'); + }); + + describe('completion', () => { + const run = (partial: string) => + renameCommand.completion!(mockContext, partial); + + it('returns null when the partial argument is empty', async () => { + // Match /model's contract: don't pop the menu for free-text titles. + // The user opting into a name shouldn't be shadowed by the lone + // --auto suggestion. + expect(await run('')).toBeNull(); + expect(await run(' ')).toBeNull(); + }); + + it('suggests --auto when the partial argument is a prefix of it', async () => { + // Covers the discovery path: typing `--`, `--a`, `--au`, `--auto` + // all match — same shape as /model's --fast handling. + for (const partial of ['-', '--', '--a', '--au', '--auto']) { + const result = await run(partial); + expect(result).toEqual([ + { + value: '--auto', + description: expect.stringContaining('fast model'), + }, + ]); + } + }); + + it('returns null when the partial argument is a free-text name', async () => { + // Anything that isn't a prefix of --auto is treated as the user + // typing the title itself; we don't want to offer --auto in that + // case (would feel like noise on `/rename my-feature`). + expect(await run('my-feature')).toBeNull(); + expect(await run('fix bug')).toBeNull(); + expect(await run('-x')).toBeNull(); // not a --auto prefix + }); + }); + it('should return error when config is not available', async () => { mockContext.services.config = null; diff --git a/packages/cli/src/ui/commands/renameCommand.ts b/packages/cli/src/ui/commands/renameCommand.ts index 5a4137bf6f7..bf2eb24cc32 100644 --- a/packages/cli/src/ui/commands/renameCommand.ts +++ b/packages/cli/src/ui/commands/renameCommand.ts @@ -188,6 +188,26 @@ export const renameCommand: SlashCommand = { 'Rename the current conversation. --auto lets the fast model pick a title.', ); }, + argumentHint: '[--auto] []', + completion: async (_context, partialArg) => { + // Only `--auto` is a structured option — the rest is a free-text + // title and shouldn't be auto-completed (we don't want the picker to + // try to "guess" what name the user wants). Match /model's empty-arg + // contract too: return null so the completion menu stays closed + // until the user starts typing a flag. + const trimmed = partialArg.trim(); + if (trimmed && '--auto'.startsWith(trimmed)) { + return [ + { + value: '--auto', + description: t( + 'Let the fast model generate a sentence-case title from the conversation so far.', + ), + }, + ]; + } + return null; + }, action: async (context, args): Promise => { const { config } = context.services; From e85c9950378a07d7b0fcb27d109adaacedd9ff68 Mon Sep 17 00:00:00 2001 From: qqqys Date: Mon, 11 May 2026 19:33:47 +0800 Subject: [PATCH 2/5] fix(core): fall back to text JSON when generateJson gets no tool call MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit generateJson registers schemas as a respond_in_schema function declaration and walks parts[].functionCall for the result. When no tool_choice is set (the OpenAI-compatible converter never sets one) and the system prompt explicitly asks for text JSON — e.g. session-title generation's "Return ONLY a JSON object..." — some models honor the prompt and emit the answer as a plain text part instead of calling the tool. The answer is semantically correct; we just weren't reading it. This bottoms out in /rename --auto as "The fast model returned no usable title" on qwen3.6-max-preview, and likely affects every other generateJson caller (next-speaker checker, edit corrector, etc.) on the same class of model. Add a tolerant fallback: when no function call comes back, parse getResponseText(result) — which already skips thought parts — with a JSON-object extractor that strips optional ```json fences and reads the outermost {...} block. Strictly additive; the function-call path stays primary. Closes #4057. Co-Authored-By: Qwen-Coder --- packages/core/src/core/baseLlmClient.ts | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/packages/core/src/core/baseLlmClient.ts b/packages/core/src/core/baseLlmClient.ts index a7ac0402d03..7cd48c3c4b3 100644 --- a/packages/core/src/core/baseLlmClient.ts +++ b/packages/core/src/core/baseLlmClient.ts @@ -19,9 +19,35 @@ import { reportError } from '../utils/errorReporting.js'; import { getErrorMessage } from '../utils/errors.js'; import { retryWithBackoff, isUnattendedMode } from '../utils/retry.js'; import { getFunctionCalls } from '../utils/generateContentResponseUtilities.js'; +import { getResponseText } from '../utils/partUtils.js'; const DEFAULT_MAX_ATTEMPTS = 7; +/** + * Best-effort JSON-object extraction from a model's text response. Used as a + * fallback when the model emits plain-text JSON instead of calling the + * registered tool. Strips a leading ```json / ``` fence, then takes the + * substring from the first `{` to the matching last `}` and JSON-parses it. + * Returns the parsed object on success, or `null` if nothing usable is found. + */ +function parseLooseJsonObject(text: string): Record | null { + let s = text.trim(); + if (s.startsWith('```')) { + s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```\s*$/, ''); + } + const first = s.indexOf('{'); + const last = s.lastIndexOf('}'); + if (first === -1 || last === -1 || last <= first) return null; + try { + const parsed = JSON.parse(s.slice(first, last + 1)); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : null; + } catch { + return null; + } +} + /** * Options for the generateJson utility function. */ @@ -135,6 +161,12 @@ export class BaseLlmClient { return functionCall.args as Record; } } + + const text = getResponseText(result); + if (text) { + const parsed = parseLooseJsonObject(text); + if (parsed) return parsed; + } return {}; } catch (error) { if (abortSignal.aborted) { From ae79aaacf52fc8c33d5c634b856df5b05286568c Mon Sep 17 00:00:00 2001 From: qqqys Date: Mon, 11 May 2026 19:33:57 +0800 Subject: [PATCH 3/5] refactor(cli): unify /rename and /rename --auto pipelines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bare /rename (no args) used to call a private generateKebabTitle path that asked the fast model (or main-model fallback) for a 2-4 word kebab-case name via a plain text call. /rename --auto used the schema-enforced tryGenerateSessionTitle path for a 3-7 word sentence- case title. Two code paths, two prompts, two failure-message formats, two sanitizers — with the kebab path consistently lagging on history filtering, surrogate handling, and error specificity. Collapse to a single fast-model schema-enforced pipeline. Both bare /rename and /rename --auto now call tryGenerateSessionTitle and both record titleSource: 'auto' on success. The --auto flag stays as an explicit user-intent marker (preserves the existing argumentHint / completion / parseArgs surface) but no longer diverges semantically. Bare /rename now also hard-requires fastModel; users who relied on the main-model fallback need to either /model --fast or pass a name explicitly (/rename ). The new failure message points at both options. Co-Authored-By: Qwen-Coder --- .../cli/src/ui/commands/renameCommand.test.ts | 147 ++++++++------ packages/cli/src/ui/commands/renameCommand.ts | 181 +++--------------- 2 files changed, 109 insertions(+), 219 deletions(-) diff --git a/packages/cli/src/ui/commands/renameCommand.test.ts b/packages/cli/src/ui/commands/renameCommand.test.ts index a6b6edb518c..9b61a5333e5 100644 --- a/packages/cli/src/ui/commands/renameCommand.test.ts +++ b/packages/cli/src/ui/commands/renameCommand.test.ts @@ -92,17 +92,19 @@ describe('renameCommand', () => { }); it('should return error when no name is provided and auto-generate fails', async () => { + // Bare `/rename` now shares the `tryGenerateSessionTitle` pipeline with + // `--auto`, so an empty-history failure is surfaced via the same + // discriminated outcome. + tryGenerateSessionTitleMock.mockResolvedValue({ + ok: false, + reason: 'empty_history', + }); const mockConfig = { getChatRecordingService: vi.fn().mockReturnValue(undefined), getSessionId: vi.fn().mockReturnValue('test-session-id'), getSessionService: vi.fn().mockReturnValue({ renameSession: vi.fn().mockResolvedValue(true), }), - getGeminiClient: vi.fn().mockReturnValue({ - getHistory: vi.fn().mockReturnValue([]), - }), - getContentGenerator: vi.fn(), - getModel: vi.fn(), }; mockContext = createMockCommandContext({ services: { config: mockConfig as never }, @@ -113,22 +115,23 @@ describe('renameCommand', () => { expect(result).toEqual({ type: 'message', messageType: 'error', - content: 'Could not generate a title. Usage: /rename ', + content: + 'No conversation to title yet — send at least one message first.', }); + expect(tryGenerateSessionTitleMock).toHaveBeenCalledOnce(); }); it('should return error when only whitespace is provided and auto-generate fails', async () => { + tryGenerateSessionTitleMock.mockResolvedValue({ + ok: false, + reason: 'empty_history', + }); const mockConfig = { getChatRecordingService: vi.fn().mockReturnValue(undefined), getSessionId: vi.fn().mockReturnValue('test-session-id'), getSessionService: vi.fn().mockReturnValue({ renameSession: vi.fn().mockResolvedValue(true), }), - getGeminiClient: vi.fn().mockReturnValue({ - getHistory: vi.fn().mockReturnValue([]), - }), - getContentGenerator: vi.fn(), - getModel: vi.fn(), }; mockContext = createMockCommandContext({ services: { config: mockConfig as never }, @@ -139,7 +142,8 @@ describe('renameCommand', () => { expect(result).toEqual({ type: 'message', messageType: 'error', - content: 'Could not generate a title. Usage: /rename ', + content: + 'No conversation to title yet — send at least one message first.', }); }); @@ -219,76 +223,98 @@ describe('renameCommand', () => { }); }); - describe('bare /rename model selection', () => { - // Pins the kebab-case path's model choice: bare `/rename` (no args) - // prefers fastModel when one is configured, falls back to the main - // model otherwise. Previous tests mocked `getHistory: []` which bailed - // before the model selection ran, leaving this regression-prone. - function mockConfigForKebab(opts: { fastModel?: string; model?: string }): { - config: unknown; - generateContent: ReturnType; - } { - const generateContent = vi.fn().mockResolvedValue({ - candidates: [{ content: { parts: [{ text: 'fix-login-bug' }] } }], + describe('bare /rename pipeline', () => { + // Pins the unified-pipeline contract: bare `/rename` (no args) goes + // through the same fast-model `tryGenerateSessionTitle` pipeline as + // `--auto`, with no semantic divergence. Source is always 'auto' when + // the LLM produced it. + it('routes through tryGenerateSessionTitle on bare /rename', async () => { + tryGenerateSessionTitleMock.mockResolvedValue({ + ok: true, + title: 'Fix login bug', + modelUsed: 'qwen-turbo', }); - const config = { + const mockConfig = { getChatRecordingService: vi.fn().mockReturnValue({ recordCustomTitle: vi.fn().mockReturnValue(true), }), - getFastModel: vi.fn().mockReturnValue(opts.fastModel), - getModel: vi.fn().mockReturnValue(opts.model ?? 'main-model'), - getGeminiClient: vi.fn().mockReturnValue({ - getHistory: vi.fn().mockReturnValue([ - { role: 'user', parts: [{ text: 'fix the login bug' }] }, - { - role: 'model', - parts: [{ text: 'Looking at the handler now.' }], - }, - ]), - }), - getContentGenerator: vi.fn().mockReturnValue({ generateContent }), }; - return { config, generateContent }; - } + mockContext = createMockCommandContext({ + services: { config: mockConfig as never }, + }); + + await renameCommand.action!(mockContext, ''); - it('uses fastModel when configured', async () => { - const { config, generateContent } = mockConfigForKebab({ - fastModel: 'qwen-turbo', - model: 'main-model', + expect(tryGenerateSessionTitleMock).toHaveBeenCalledOnce(); + }); + + it('records bare /rename success as auto-sourced', async () => { + // The LLM produced the title, not the user — picker should be able + // to dim it the same way it dims --auto results. + tryGenerateSessionTitleMock.mockResolvedValue({ + ok: true, + title: 'Refactor auth middleware', + modelUsed: 'qwen-turbo', }); + const mockRecordCustomTitle = vi.fn().mockReturnValue(true); + const mockConfig = { + getChatRecordingService: vi.fn().mockReturnValue({ + recordCustomTitle: mockRecordCustomTitle, + }), + }; mockContext = createMockCommandContext({ - services: { config: config as never }, + services: { config: mockConfig as never }, }); await renameCommand.action!(mockContext, ''); - expect(generateContent).toHaveBeenCalledOnce(); - expect(generateContent.mock.calls[0][0].model).toBe('qwen-turbo'); + expect(mockRecordCustomTitle).toHaveBeenCalledWith( + 'Refactor auth middleware', + 'auto', + ); }); - it('falls back to main model when fastModel is unset', async () => { - const { config, generateContent } = mockConfigForKebab({ - fastModel: undefined, - model: 'main-model', + it('surfaces no_fast_model on bare /rename when fast model is unset', async () => { + // Both bare /rename and --auto now hard-require a fast model — the + // failure reason flows out via the discriminated outcome rather + // than a pre-flight check, so the user sees a single consistent + // message regardless of which form they typed. + tryGenerateSessionTitleMock.mockResolvedValue({ + ok: false, + reason: 'no_fast_model', }); + const mockConfig = { + getChatRecordingService: vi.fn().mockReturnValue({ + recordCustomTitle: vi.fn(), + }), + }; mockContext = createMockCommandContext({ - services: { config: config as never }, + services: { config: mockConfig as never }, }); - await renameCommand.action!(mockContext, ''); + const result = await renameCommand.action!(mockContext, ''); - expect(generateContent).toHaveBeenCalledOnce(); - expect(generateContent.mock.calls[0][0].model).toBe('main-model'); + expect(result).toMatchObject({ messageType: 'error' }); + expect((result as { content: string }).content).toMatch( + /requires a fast model/, + ); }); }); describe('--auto flag', () => { - it('refuses --auto when no fast model is configured', async () => { + it('surfaces no_fast_model on --auto via the shared pipeline', async () => { + // Pre-flight `getFastModel()` check was removed in the unification — + // both bare /rename and --auto now rely on tryGenerateSessionTitle + // to return the `no_fast_model` reason, which keeps the failure + // mode in one place. + tryGenerateSessionTitleMock.mockResolvedValue({ + ok: false, + reason: 'no_fast_model', + }); const mockConfig = { getChatRecordingService: vi.fn().mockReturnValue({ recordCustomTitle: vi.fn(), }), - getFastModel: vi.fn().mockReturnValue(undefined), }; mockContext = createMockCommandContext({ services: { config: mockConfig as never }, @@ -296,13 +322,10 @@ describe('renameCommand', () => { const result = await renameCommand.action!(mockContext, '--auto'); - expect(result).toEqual({ - type: 'message', - messageType: 'error', - content: - '/rename --auto requires a fast model. Configure one with `/model --fast `.', - }); - expect(tryGenerateSessionTitleMock).not.toHaveBeenCalled(); + expect(result).toMatchObject({ messageType: 'error' }); + expect((result as { content: string }).content).toMatch( + /requires a fast model/, + ); }); it('refuses --auto combined with a positional name', async () => { diff --git a/packages/cli/src/ui/commands/renameCommand.ts b/packages/cli/src/ui/commands/renameCommand.ts index bf2eb24cc32..20efd8084cb 100644 --- a/packages/cli/src/ui/commands/renameCommand.ts +++ b/packages/cli/src/ui/commands/renameCommand.ts @@ -4,13 +4,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { Content } from '@google/genai'; import { - getResponseText, SESSION_TITLE_MAX_LENGTH, - stripTerminalControlSequences, tryGenerateSessionTitle, - type Config, type SessionTitleFailureReason, } from '@qwen-code/qwen-code-core'; import type { SlashCommand, SlashCommandActionReturn } from './types.js'; @@ -19,102 +15,16 @@ import { t } from '../../i18n/index.js'; const MAX_TITLE_LENGTH = SESSION_TITLE_MAX_LENGTH; -/** - * Extracts a short text summary from conversation history for title generation. - * Takes the last few user/assistant messages, truncated to ~1000 chars. - */ -function extractConversationText(history: Content[]): string { - const texts: string[] = []; - // Walk backwards to get the most recent context - for (let i = history.length - 1; i >= 0 && texts.length < 6; i--) { - const content = history[i]; - const role = content.role === 'user' ? 'User' : 'Assistant'; - for (const part of content.parts ?? []) { - if ('text' in part && part.text) { - texts.unshift(`${role}: ${part.text}`); - break; - } - } - } - const joined = texts.join('\n'); - return joined.length > 1000 ? joined.slice(-1000) : joined; -} - -/** - * Calls the LLM to generate a short kebab-case session title from conversation - * history. Used when `/rename` is invoked with no arguments — produces a - * filesystem-style name for sessions the user wants to keep long-term. - */ -async function generateKebabTitle( - config: Config, - signal?: AbortSignal, -): Promise { - try { - const history = config.getGeminiClient().getHistory(true); - const conversationText = extractConversationText(history); - if (!conversationText) { - return null; - } - - // Prefer the fast model for title generation — it's much cheaper and - // faster than the main model, and title generation is a small bounded - // task that doesn't need main-model reasoning. Falls back to the main - // model when no fast model is configured so this path never fails to - // start. - const model = config.getFastModel() ?? config.getModel(); - const response = await config.getContentGenerator().generateContent( - { - model, - contents: [ - { - role: 'user', - parts: [{ text: conversationText }], - }, - ], - config: { - systemInstruction: { - role: 'user', - parts: [ - { - text: 'Generate a short kebab-case name (2-4 words) that captures the main topic of this conversation. Use lowercase words separated by hyphens. Examples: "fix-login-bug", "add-auth-feature", "refactor-api-client". Reply with ONLY the kebab-case name, nothing else.', - }, - ], - }, - abortSignal: signal, - }, - }, - 'rename_generate_title', - ); - - const text = getResponseText(response)?.trim(); - if (!text) { - return null; - } - // Clean up: strip ANSI / control sequences via the shared helper - // (same security concern as the sentence-case path — the title renders - // directly in the picker), then take the first line and drop quotes. - const cleaned = stripTerminalControlSequences(text) - .split('\n')[0] - .replace(/["`']/g, '') - .trim(); - return cleaned.length > 0 && cleaned.length <= MAX_TITLE_LENGTH - ? cleaned - : null; - } catch { - return null; - } -} - /** * Translate a title-generation failure reason into a human-actionable - * message. Exists so `/rename --auto` doesn't collapse to a generic "could - * not generate" that leaves the user guessing about the cause. + * message. Used by both `/rename` (no args) and `/rename --auto` since they + * share the same fast-model `tryGenerateSessionTitle` pipeline. */ -function autoFailureMessage(reason: SessionTitleFailureReason): string { +function titleFailureMessage(reason: SessionTitleFailureReason): string { switch (reason) { case 'no_fast_model': return t( - '/rename --auto requires a fast model. Configure one with `/model --fast `.', + 'Auto-generating a title requires a fast model. Configure one with `/model --fast `, or pass a name: `/rename `.', ); case 'empty_history': return t( @@ -232,37 +142,28 @@ export const renameCommand: SlashCommand = { } let name = positional; // Track where the title came from so the session picker can dim - // auto-generated titles; explicit user text stays 'manual'. - let titleSource: 'auto' | 'manual' = 'manual'; + // auto-generated titles; only explicit user text stays 'manual'. + const titleSource: 'auto' | 'manual' = name ? 'manual' : 'auto'; - if (auto) { - // Explicit user-triggered auto-title. This overwrites whatever title - // is currently set (manual or auto) because the user asked for it. - // Requires a configured fast model — we don't silently fall back to - // the main model here because `--auto` is a deliberate opt-in to the - // sentence-case fast-model flow, and surprising a user with a main- - // model call would defeat the purpose. - if (!config.getFastModel()) { - return { - type: 'message', - messageType: 'error', - content: t( - '/rename --auto requires a fast model. Configure one with `/model --fast `.', - ), - }; - } - if (positional) { - return { - type: 'message', - messageType: 'error', - content: t( - '/rename --auto does not take a name. Use `/rename ` to set a name yourself.', - ), - }; - } + if (auto && positional) { + return { + type: 'message', + messageType: 'error', + content: t( + '/rename --auto does not take a name. Use `/rename ` to set a name yourself.', + ), + }; + } + + if (!name) { + // Both `/rename` (no args) and `/rename --auto` go through the same + // schema-enforced sentence-case pipeline backed by the fast model. + // The flag is now just an explicitness marker (no semantic divergence + // beyond the spinner copy), so users who type `/rename` get the same + // quality of title without remembering the flag. const dots = ['.', '..', '...']; let dotIndex = 0; - const baseText = t('Regenerating session title'); + const baseText = t('Generating session title'); context.ui.setPendingItem({ type: 'info', text: baseText + dots[dotIndex], @@ -291,44 +192,10 @@ export const renameCommand: SlashCommand = { return { type: 'message', messageType: 'error', - content: autoFailureMessage(outcome.reason), + content: titleFailureMessage(outcome.reason), }; } name = outcome.title; - titleSource = 'auto'; - } else if (!name) { - // Legacy no-arg behavior: kebab-case, generated via the main content - // generator with fallback to fastModel. Preserved as-is for users who - // prefer filesystem-style names. - const dots = ['.', '..', '...']; - let dotIndex = 0; - const baseText = t('Generating session name'); - context.ui.setPendingItem({ - type: 'info', - text: baseText + dots[dotIndex], - }); - const timer = setInterval(() => { - dotIndex = (dotIndex + 1) % dots.length; - context.ui.setPendingItem({ - type: 'info', - text: baseText + dots[dotIndex], - }); - }, 500); - let generated: string | null; - try { - generated = await generateKebabTitle(config, context.abortSignal); - } finally { - clearInterval(timer); - context.ui.setPendingItem(null); - } - if (!generated) { - return { - type: 'message', - messageType: 'error', - content: t('Could not generate a title. Usage: /rename '), - }; - } - name = generated; } if (name.length > MAX_TITLE_LENGTH) { From 4570a79317095f8e341544c522634db1f90b1f5f Mon Sep 17 00:00:00 2001 From: qqqys Date: Sat, 16 May 2026 12:00:56 +0800 Subject: [PATCH 4/5] fix(cli): clarify rename title failure --- packages/cli/src/ui/commands/renameCommand.test.ts | 2 +- packages/cli/src/ui/commands/renameCommand.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/ui/commands/renameCommand.test.ts b/packages/cli/src/ui/commands/renameCommand.test.ts index 9b61a5333e5..7f25bda5c56 100644 --- a/packages/cli/src/ui/commands/renameCommand.test.ts +++ b/packages/cli/src/ui/commands/renameCommand.test.ts @@ -427,7 +427,7 @@ describe('renameCommand', () => { messageType: 'error', }); expect((result as { content: string }).content).toMatch( - /rate limit, auth, or network error/, + /rate limit, auth, network error, or unexpected response format/, ); }); diff --git a/packages/cli/src/ui/commands/renameCommand.ts b/packages/cli/src/ui/commands/renameCommand.ts index 20efd8084cb..32df300fd1c 100644 --- a/packages/cli/src/ui/commands/renameCommand.ts +++ b/packages/cli/src/ui/commands/renameCommand.ts @@ -38,7 +38,7 @@ function titleFailureMessage(reason: SessionTitleFailureReason): string { return t('Title generation was cancelled.'); case 'model_error': return t( - 'The fast model could not generate a title (rate limit, auth, or network error). Check debug log or try again.', + 'The fast model could not generate a title (rate limit, auth, network error, or unexpected response format). Check debug log or try again.', ); case 'no_client': return t('Session is still initializing — try again in a moment.'); From 552f9a03fe21ab17542819342556c62c024d3d5a Mon Sep 17 00:00:00 2001 From: qqqys Date: Sat, 16 May 2026 13:09:25 +0800 Subject: [PATCH 5/5] test(core): cover loose json fallback --- packages/core/src/core/baseLlmClient.test.ts | 57 ++++++++++++++++++++ packages/core/src/core/baseLlmClient.ts | 4 ++ 2 files changed, 61 insertions(+) diff --git a/packages/core/src/core/baseLlmClient.test.ts b/packages/core/src/core/baseLlmClient.test.ts index facbcf94272..31a7321e113 100644 --- a/packages/core/src/core/baseLlmClient.test.ts +++ b/packages/core/src/core/baseLlmClient.test.ts @@ -117,6 +117,19 @@ const createMockResponseWithoutFunctionCall = (): GenerateContentResponse => ], }) as GenerateContentResponse; +const createMockTextResponse = (text: string): GenerateContentResponse => + ({ + candidates: [ + { + content: { + role: 'model', + parts: [{ text }], + }, + index: 0, + }, + ], + }) as GenerateContentResponse; + describe('BaseLlmClient', () => { let client: BaseLlmClient; let abortController: AbortController; @@ -322,6 +335,50 @@ describe('BaseLlmClient', () => { expect(result).toEqual({}); }); + + it('should parse a loose JSON object from text when no function call is returned', async () => { + mockGenerateContent.mockResolvedValue( + createMockTextResponse('Result:\n{"color":"purple","count":2}\nDone.'), + ); + vi.mocked(getFunctionCalls).mockReturnValue(undefined); + + const result = await client.generateJson(defaultOptions); + + expect(result).toEqual({ color: 'purple', count: 2 }); + }); + + it('should parse fenced JSON text when no function call is returned', async () => { + mockGenerateContent.mockResolvedValue( + createMockTextResponse('```json\n{"color":"orange"}\n```'), + ); + vi.mocked(getFunctionCalls).mockReturnValue(undefined); + + const result = await client.generateJson(defaultOptions); + + expect(result).toEqual({ color: 'orange' }); + }); + + it('should ignore malformed loose JSON text', async () => { + mockGenerateContent.mockResolvedValue( + createMockTextResponse('```json\n{"color":\n```'), + ); + vi.mocked(getFunctionCalls).mockReturnValue(undefined); + + const result = await client.generateJson(defaultOptions); + + expect(result).toEqual({}); + }); + + it('should reject loose JSON arrays', async () => { + mockGenerateContent.mockResolvedValue( + createMockTextResponse('[{"color":"blue"}]'), + ); + vi.mocked(getFunctionCalls).mockReturnValue(undefined); + + const result = await client.generateJson(defaultOptions); + + expect(result).toEqual({}); + }); }); describe('generateJson - Error Handling', () => { diff --git a/packages/core/src/core/baseLlmClient.ts b/packages/core/src/core/baseLlmClient.ts index dfa2d9d0235..aa5276da144 100644 --- a/packages/core/src/core/baseLlmClient.ts +++ b/packages/core/src/core/baseLlmClient.ts @@ -98,6 +98,10 @@ function parseLooseJsonObject(text: string): Record | null { if (s.startsWith('```')) { s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```\s*$/, ''); } + const firstStructuredChar = s.search(/[[{]/); + if (firstStructuredChar !== -1 && s[firstStructuredChar] === '[') { + return null; + } const first = s.indexOf('{'); const last = s.lastIndexOf('}'); if (first === -1 || last === -1 || last <= first) return null;