From bb86663d755dbcbee46d2aa354706fd334233ca4 Mon Sep 17 00:00:00 2001 From: ilovepixelart Date: Tue, 17 Nov 2026 15:46:20 +0100 Subject: [PATCH 1/2] Resolve behaviour-neutral SonarCloud code smells - Replace nested ternaries with if/else in question.ts (row color, reserved text-field width), background-shells.ts (completion wording) and hooks/config.ts (manifest hook entries). - Split nested template literals into named locals in question.ts and skills.ts. - Hoist unconfirmedText, confirm and followEdits out of the askViaOverlay closure; none of them reads closure state. - Strip dashes from random IDs with replaceAll('-', '') instead of a global regex in monitor.ts and background-bash.ts. Output strings, IDs and control flow are unchanged. --- extensions/background-bash.ts | 2 +- extensions/hooks/config.ts | 5 +- extensions/internal/background-shells.ts | 4 +- extensions/monitor.ts | 2 +- extensions/question.ts | 59 +++++++++++++++--------- extensions/skills.ts | 6 ++- 6 files changed, 49 insertions(+), 29 deletions(-) diff --git a/extensions/background-bash.ts b/extensions/background-bash.ts index 24580171..ad169bb1 100644 --- a/extensions/background-bash.ts +++ b/extensions/background-bash.ts @@ -147,7 +147,7 @@ export default function backgroundBashExtension(pi: ExtensionAPI, limits: { maxO /** Run `command` as a task that may move to the background: immediately when * `background` is set, otherwise once `limitMs` passes without it finishing. */ async function runTask(toolCallId: string, params: BashParams, limitMs: number, signal: AbortSignal | undefined, onUpdate: ((update: ToolResult) => void) | undefined, ctx: ExtensionToolContext): Promise { - const id = `b${randomUUID().replace(/-/g, '').slice(0, 8)}` + const id = `b${randomUUID().replaceAll('-', '').slice(0, 8)}` const { outputFile, log, closed } = openOutputFile(id) // The process gets its own abort signal: the tool call's ends with the call, and a diff --git a/extensions/hooks/config.ts b/extensions/hooks/config.ts index 0b138183..2e611024 100644 --- a/extensions/hooks/config.ts +++ b/extensions/hooks/config.ts @@ -291,8 +291,11 @@ function withoutUserConfigShellCommands(raw: string, source: string): string { export function loadPluginHooks(config: HooksConfig, plugins: InstalledPlugin[], sources?: Map): void { for (const plugin of plugins) { const declared = plugin.manifest.hooks + let declaredEntries: unknown[] = [] + if (Array.isArray(declared)) declaredEntries = declared + else if (declared !== undefined && declared !== null) declaredEntries = [declared] // Claude merges the manifest's paths and inline objects into hooks/hooks.json, which loads first. - const entries = [path.join('hooks', 'hooks.json'), ...(declared === undefined || declared === null ? [] : Array.isArray(declared) ? declared : [declared])] + const entries = [path.join('hooks', 'hooks.json'), ...declaredEntries] const loadedFiles = new Set() for (const entry of entries) loadPluginHooksEntry(config, plugin, entry, loadedFiles, sources) } diff --git a/extensions/internal/background-shells.ts b/extensions/internal/background-shells.ts index 69e92cf4..b49a9227 100644 --- a/extensions/internal/background-shells.ts +++ b/extensions/internal/background-shells.ts @@ -217,6 +217,8 @@ export function shellsStatusText(shells: ReadonlyArray): string /** What the model is told when a background command finishes. */ export function shellCompletionText(shell: Pick): string { const stopped = shell.stopReason ? `was stopped: ${shell.stopReason}` : 'was stopped' - const how = shell.state === 'completed' ? 'completed (exit code 0)' : shell.state === 'killed' ? stopped : `failed (exit code ${shell.exitCode ?? '?'})` + let how = `failed (exit code ${shell.exitCode ?? '?'})` + if (shell.state === 'completed') how = 'completed (exit code 0)' + else if (shell.state === 'killed') how = stopped return `Background command ${shell.id} ("${commandPreview(shell.command)}") ${how}. Output: ${shell.outputFile}` } diff --git a/extensions/monitor.ts b/extensions/monitor.ts index 94ba7c0e..d10e8730 100644 --- a/extensions/monitor.ts +++ b/extensions/monitor.ts @@ -355,7 +355,7 @@ export default function monitorExtension(pi: ExtensionAPI, limits: MonitorLimits } function start({ description, command, limitMs }: Watch, ctx: ExtensionToolContext): BackgroundShell { - const id = `m${randomUUID().replace(/-/g, '').slice(0, 8)}` + const id = `m${randomUUID().replaceAll('-', '').slice(0, 8)}` const outputFile = path.join(shellOutputDir(), `${id}.output`) const log = fs.createWriteStream(outputFile, { mode: 0o600 }) // A full disk or a removed directory must not take pi down from a stream event. diff --git a/extensions/question.ts b/extensions/question.ts index 37d16724..ab96b5df 100644 --- a/extensions/question.ts +++ b/extensions/question.ts @@ -139,7 +139,9 @@ function checkbox(checked: boolean, theme: Theme): string { type RowMarks = { field?: string; box?: string; confirmed?: boolean; width?: number } function optionLine(label: string, index: number, selected: boolean, theme: Theme, { field = '', box = '', confirmed = false, width }: RowMarks = {}): string { - const color = confirmed ? 'success' : selected ? 'accent' : 'text' + let color: 'success' | 'accent' | 'text' = 'text' + if (confirmed) color = 'success' + else if (selected) color = 'accent' const tick = confirmed ? theme.fg('success', ' ✔') : '' const body = (selected ? theme.fg('accent', '❯ ') : ' ') + theme.fg(color, `${index + 1}. `) + box + theme.fg(color, label) + field // As in Claude Code, a long label is cut short and the tick stays in view. @@ -176,6 +178,26 @@ function multiAnswer(checked: boolean[], text = ''): MultiAnswer { return { kind: 'multi', indices: checked.flatMap((on, index) => (on ? [index] : [])), ...(text ? { text } : {}) } } +/** Text in the field under the highlight that Enter has not confirmed as it stands. */ +function unconfirmedText(state: QuestionState | undefined): boolean { + const text = state?.draft.getValue().trim() + if (!state?.typing || !text) return false + return state.mode === 'multi' || state.confirmed?.kind !== 'text' || state.confirmed.text !== text +} + +/** Confirms an answer that matches the question's mode. */ +function confirm(state: QuestionState, answer: Answer): void { + if (state.mode === 'multi') { + if (answer.kind === 'multi') state.confirmed = answer + } else if (answer.kind !== 'multi') state.confirmed = answer +} + +/** A confirmed multiSelect follows every toggle and keystroke. As in Claude Code, a confirmed + * single-select text answer changes only when Enter confirms the edited text. */ +function followEdits(state: QuestionState): void { + if (state.mode === 'multi' && state.confirmed) state.confirmed = multiAnswer(state.checked, state.draft.getValue().trim()) +} + function answerText(spec: QuestionSpec, answer: Answer): string { switch (answer.kind) { case 'option': @@ -299,7 +321,8 @@ function renderOptions(args: Partial, theme: Theme): string { if (!opts.length) return '' const labels = opts.map((o: OptionWithDesc) => o.label) const numbered = [...labels, 'Type something.'].map((o, i) => `${i + 1}. ${o}`) - return `\n${theme.fg('dim', ` Options${multi ? ' (multi)' : ''}: ${numbered.join(', ')}`)}` + const line = ` Options${multi ? ' (multi)' : ''}: ${numbered.join(', ')}` + return `\n${theme.fg('dim', line)}` } function renderBatchCall(specs: Array | null>, theme: Theme): Text { @@ -370,7 +393,8 @@ export default function question(pi: ExtensionAPI) { details.questions .map((detail) => { const rendered = detail.answer === null ? theme.fg('warning', 'Cancelled') : renderAnswered(detail, detail.answer, theme) - return `${detail.header ? `[${detail.header}] ` : ''}${detail.question}\n${rendered}` + const prefix = detail.header ? `[${detail.header}] ` : '' + return `${prefix}${detail.question}\n${rendered}` }) .join('\n\n'), 0, @@ -562,7 +586,8 @@ function overlayResult(specs: QuestionSpec[], result: FormResult | null | undefi function chatResult(specs: QuestionSpec[], answers: Array): QuestionResult { const asked = specs.map((spec, index) => { const answer = answers[index] - return `- "${spec.question}"\n ${answer ? `Answer: ${answerText(spec, answer)}` : '(No answer provided)'}` + const given = answer ? `Answer: ${answerText(spec, answer)}` : '(No answer provided)' + return `- "${spec.question}"\n ${given}` }) const text = `The user wants to clarify these questions. This means they may have additional information, context or questions for you. @@ -713,12 +738,6 @@ export async function askViaOverlay(specs: QuestionSpec[], ctx: ExtensionContext const text = settledText(state) return state.checked.some(Boolean) || text ? multiAnswer(state.checked, text) : undefined } - /** Text in the field under the highlight that Enter has not confirmed as it stands. */ - function unconfirmedText(state: QuestionState | undefined): boolean { - const text = state?.draft.getValue().trim() - if (!state?.typing || !text) return false - return state.mode === 'multi' || state.confirmed?.kind !== 'text' || state.confirmed.text !== text - } function answers(): Array { return states.map(draftAnswer) } @@ -728,12 +747,6 @@ export async function askViaOverlay(specs: QuestionSpec[], ctx: ExtensionContext if (confirmed) return confirmed return state.mode === 'multi' ? { kind: 'timedOut', selected: multiAnswer(state.checked, state.draft.getValue().trim()) } : { kind: 'timedOut' } } - /** Confirms an answer that matches the question's mode. */ - function confirm(state: QuestionState, answer: Answer): void { - if (state.mode === 'multi') { - if (answer.kind === 'multi') state.confirmed = answer - } else if (answer.kind !== 'multi') state.confirmed = answer - } function restoreRemoteAnswer(index: number, value: Answer): void { const state = states[index] confirm(state, value) @@ -845,11 +858,6 @@ export async function askViaOverlay(specs: QuestionSpec[], ctx: ExtensionContext state.checked[row.index] = !state.checked[row.index] followEdits(state) } - /** A confirmed multiSelect follows every toggle and keystroke. As in Claude Code, a confirmed - * single-select text answer changes only when Enter confirms the edited text. */ - function followEdits(state: QuestionState): void { - if (state.mode === 'multi' && state.confirmed) state.confirmed = multiAnswer(state.checked, state.draft.getValue().trim()) - } function handleTypingInput(state: QuestionState, data: string): void { if (matchesKey(data, Key.escape)) finish(null) else if (matchesKey(data, Key.enter)) { @@ -899,12 +907,17 @@ export async function askViaOverlay(specs: QuestionSpec[], ctx: ExtensionContext const draft = state.draft.getValue() state.draft.focused = state.typing // The row's prefix and number take five columns, a checkbox four more, a confirmed tick two. - const reserved = state.mode === 'multi' ? 9 : state.confirmed?.kind === 'text' ? 7 : 5 + let reserved = 5 + if (state.mode === 'multi') reserved = 9 + else if (state.confirmed?.kind === 'text') reserved = 7 if (state.typing) return state.draft.render(Math.max(1, width - reserved))[0].trimEnd() return draft ? theme.fg('text', draft) : theme.fg('dim', textRowLabel(state.mode === 'multi')) } function renderTabs(width: number, saved: Array): string { - const tabs = specs.map((spec, index) => ` ${saved[index] ? '☒' : '☐'} ${spec.header ?? `Q${index + 1}`} `) + const tabs = specs.map((spec, index) => { + const name = spec.header ?? `Q${index + 1}` + return ` ${saved[index] ? '☒' : '☐'} ${name} ` + }) tabs.push(' ✔ Submit ') const widths = tabs.map((tab) => visibleWidth(tab)) const arrows = widths[active] + 4 <= width diff --git a/extensions/skills.ts b/extensions/skills.ts index 0f496622..0c27ff63 100644 --- a/extensions/skills.ts +++ b/extensions/skills.ts @@ -236,7 +236,8 @@ function registerPluginSkillCommand(pi: ExtensionAPI, skill: PluginSkill, parsed pi.registerCommand(skill.name, { description: parsed.argumentHint ? `${parsed.description} ${parsed.argumentHint}` : parsed.description, handler: async (args, commandCtx) => { - const outcome = await expandSkillInvocation(pi, `/${skill.name}${args.trim() ? ` ${args}` : ''}`, commandCtx) + const typed = args.trim() ? `/${skill.name} ${args}` : `/${skill.name}` + const outcome = await expandSkillInvocation(pi, typed, commandCtx) if (!outcome || outcome.action === 'handled') return pi.sendUserMessage(outcome.text, commandCtx.isIdle() ? {} : { deliverAs: 'followUp' }) }, @@ -501,7 +502,8 @@ function refusedForUser(name: string, ctx: ExtensionContext): { action: 'handled function bareFormRefusal(typed: string, found: ResolvedSkill, ctx: ExtensionContext): { action: 'handled' } | undefined { if (!found.plugin || typed.includes(':')) return undefined if (found.ambiguous) { - notice(ctx, `/skill:${typed} matches more than one plugin skill and was not run. Use a qualified name: ${found.ambiguous.map((name) => `/${name}`).join(', ')}.`, 'warning') + const qualified = found.ambiguous.map((name) => `/${name}`).join(', ') + notice(ctx, `/skill:${typed} matches more than one plugin skill and was not run. Use a qualified name: ${qualified}.`, 'warning') return { action: 'handled' } } warnOnce(`/skill:${typed} is deprecated for plugin skills and will be removed in the next major version. Use /${found.name} instead.`, (message) => notice(ctx, message, 'warning')) From bc253d993a78995dda09667e4cfa7fd91d98d02e Mon Sep 17 00:00:00 2001 From: ilovepixelart Date: Tue, 17 Nov 2026 15:53:06 +0100 Subject: [PATCH 2/2] Hoist toggleChecked out of the askViaOverlay closure It reads only its argument and followEdits, which is now module-level. --- extensions/question.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/extensions/question.ts b/extensions/question.ts index ab96b5df..1561ccdc 100644 --- a/extensions/question.ts +++ b/extensions/question.ts @@ -198,6 +198,13 @@ function followEdits(state: QuestionState): void { if (state.mode === 'multi' && state.confirmed) state.confirmed = multiAnswer(state.checked, state.draft.getValue().trim()) } +function toggleChecked(state: QuestionState): void { + const row = state.rows[state.cursor] + if (state.mode !== 'multi' || row.kind !== 'option') return + state.checked[row.index] = !state.checked[row.index] + followEdits(state) +} + function answerText(spec: QuestionSpec, answer: Answer): string { switch (answer.kind) { case 'option': @@ -852,12 +859,6 @@ export async function askViaOverlay(specs: QuestionSpec[], ctx: ExtensionContext refresh() return true } - function toggleChecked(state: QuestionState): void { - const row = state.rows[state.cursor] - if (state.mode !== 'multi' || row.kind !== 'option') return - state.checked[row.index] = !state.checked[row.index] - followEdits(state) - } function handleTypingInput(state: QuestionState, data: string): void { if (matchesKey(data, Key.escape)) finish(null) else if (matchesKey(data, Key.enter)) {