✨ feat(vscode): 问 AI 和重写注释各用各的 profile,设置里加重写注释默认模型

This commit is contained in:
cruldra committed 2026-10-12 16:30:41 +11:00
1 parent 925f1ed39a
commit b83c445dd0
25 files changed
+363 -111

No files matched your search

+9 -6
View File
@@ -107,6 +107,9 @@ export interface QaMessage {
rewriteCurrent: AskRound[]
}
/** 预览里的两种对话:问 AI(ask,块下面和页面顶部)、重写注释(rewrite),各有各的记录和 profile 下拉 */
export type ChatKind = 'ask' | 'rewrite'
/**
* VS Code 的 Sticky Scroll 设置(editor.stickyScroll.enabled / editor.stickyScroll.maxLineCount):卡片的开头滚到预览顶上后面、卡片还有一部分看得见时把它钉在顶上,
* 外层的在上、里层的在下,最多钉 maxLineCount 行。
@@ -126,7 +129,7 @@ export interface StickyScrollSettings {
* occurrencesFound:id 那次 findOccurrences 的回答,语言扩展没答(或没装)就是空的
* filter:整个工作区共用的块筛选和「只看改动」开关;ready 后先于第一份文档发一次,之后任何一个预览改了都发给所有预览
* qa:这份文件的问答;ready 后发一次,问答、正在答的问题变了再发
* askProfiles:「问 AI」输入框旁边的 profile 下拉:选项和选中的那项;ready 后发一次,任何一个预览改了都发给所有预览
* profiles:kind 那种对话输入框旁边的 profile 下拉:选项和选中的那项;ready 后两种各发一次,任何一个预览改了哪种就把哪种发给所有预览
* answer:askId 那个问题的回答长了(text 是到现在为止的全文)、或换了在做的事
* answerEnd:askId 那个问题答完了:done 带最终的回答和存下的那条的 id,failed 带给人看的原因,stopped 是被叫停
* rewriteProgress:askId 那一轮重写排上队了(queued)、开始了、正文长了(text 是到现在为止写出来的)、或换了在做的事;question 是记在这一轮上的话(点按钮时是那句技能命令)
@@ -157,7 +160,7 @@ export type ExtensionToWebview
| { type: 'displayNames', version: number, names: ShownName[] }
| ({ type: 'filter' } & FilterState)
| QaMessage
| ({ type: 'askProfiles' } & ProfileChoice)
| ({ type: 'profiles', kind: ChatKind } & ProfileChoice)
| { type: 'answer', askId: string, text: string, activity?: string }
| { type: 'answerEnd', askId: string, status: 'done' | 'failed' | 'stopped', text?: string, error?: string, entryId?: string }
| { type: 'rewriteProgress', askId: string, question: string, text: string, activity?: string, queued?: true }
@@ -184,7 +187,7 @@ export type ExtensionToWebview
* findOccurrences:单击带下标的名字,问它在这份文档里出现在哪几处;id、version 同 probeDefinition
* setFilter:改块筛选(整份替换),扩展端记下后发 filter 给所有预览
* setOnlyChanges:打开 / 关掉「只看改动」,扩展端记下后发 filter 给所有预览
* ask:问 anchor 那块代码;askId 由 webview 起,回答的消息带回去;扩展端接着这块最近一次问答的会话问,用眼下选的 profile;
* ask:问 anchor 那块代码;askId 由 webview 起,回答的消息带回去;扩展端接着这块最近一次问答的会话问,用问 AI 眼下选的 profile;
* images 是贴进输入框的图片(没贴是空的),随问题发给 Claude Code,答成了跟这条一起存
* rewriteComment:按注释规范重写 anchor 那块的注释(还没有就新写一段);askId 由 webview 起,过程用 rewriteProgress / rewriteEnd 带回去。
* 没有 request 是点了按钮:发技能命令,开新会话;有 request 是在输入框里说的修改意见,接着这块最近一次重写的会话说,images 是贴的图片
@@ -193,7 +196,7 @@ export type ExtensionToWebview
* deleteRewrite:删掉 anchor 那块下面的一条重写记录
* stopAsk:叫停 askId 那个问题,这次不存
* deleteQa:删掉 anchor 那块下面的一次问答(已经理解了)
* selectAskProfile:「问 AI」换 profile(id 是 profile 名,「默认」是 ''),扩展端记下后发 askProfiles 给所有预览
* selectProfile:kind 那种对话换 profile(id 是 profile 名,「默认」是 ''),扩展端记下后把这种的 profiles 发给所有预览
* occurrenceNavigation:眼下能不能用键盘在高亮着的名字的各处出现之间跳(有高亮、页面有焦点、焦点不在输入框里),变了才发;
* 扩展端按它设 when 子句用的上下文键
* openRepoLink:点了注释里的仓库路径链接,打开 path(从仓库根算起)。symbol 是类名、函数名或「类名.成员名」,没有就只打开文件或在代码阅读侧栏的树上定位目录;
@@ -211,7 +214,7 @@ export type WebviewToExtension
| { type: 'rewriteComment', askId: string, anchor: string, request?: string, images: ClaudeImage[] }
| { type: 'stopRewrite', askId: string }
| { type: 'deleteRewrite', anchor: string, entryId: string }
| { type: 'forgetRound', kind: 'ask' | 'rewrite', anchor: string }
| { type: 'forgetRound', kind: ChatKind, anchor: string }
| { type: 'selectTranslator', id: string }
| { type: 'visibleLine', line: number }
| { type: 'probeDefinition', id: number, version: number, offset: number }
@@ -222,7 +225,7 @@ export type WebviewToExtension
| { type: 'ask', askId: string, anchor: string, question: string, images: ClaudeImage[] }
| { type: 'stopAsk', askId: string }
| { type: 'deleteQa', anchor: string, entryId: string }
| { type: 'selectAskProfile', id: string }
| { type: 'selectProfile', kind: ChatKind, id: string }
| { type: 'occurrenceNavigation', available: boolean }
| { type: 'openRepoLink', path?: string, symbol?: string }
| { type: 'checkRepoLinks', id: number, paths: string[], symbols: string[] }
@@ -1,8 +1,9 @@
import type { DiffBase, OpenedFrom } from '../diff/diffBase'
import type { ProfileChoice } from '../qa/askProfiles'
import type { RewriteRequest } from '../qa/codeQa'
import type { ExtensionToWebview, WebviewToExtension } from './messages'
import { describe, expect, it, vi } from 'vitest'
import { workspace } from 'vscode'
import { window, workspace } from 'vscode'
import { PreviewEditorProvider } from './previewEditor'
vi.mock('vscode', () => ({
@@ -49,7 +50,7 @@ function preview(rewrite: (uri: unknown, request: RewriteRequest) => Promise<str
const uri = { fsPath: '/workspace/web/a.ts', scheme: 'file', toString: () => 'file:///workspace/web/a.ts' }
const document = { uri, isDirty: dirty, lineAt: (line: number) => ({ text: SOURCE[line] }), lineCount: SOURCE.length, eol: 1 }
vi.mocked(workspace.openTextDocument).mockResolvedValue(document as never)
const qa = { imageRoot: () => undefined, onDidChange: subscribe, onDidAnswer: subscribe, onDidRewrite: subscribe, profiles: { subscribe }, rewrite: vi.fn(rewrite) }
const qa = { imageRoot: () => undefined, onDidChange: subscribe, onDidAnswer: subscribe, onDidRewrite: subscribe, profiles: { ask: { subscribe }, rewrite: { subscribe } }, rewrite: vi.fn(rewrite) }
const provider = new PreviewEditorProvider(...[
{},
{},
@@ -75,7 +76,7 @@ function preview(rewrite: (uri: unknown, request: RewriteRequest) => Promise<str
describe('预览里重写注释', () => {
it('点按钮:发技能命令、开新会话,记在这一轮上的就是这句命令;开不了时回一条带 askId 的失败,能再试', async () => {
const error = '文件问答模型不可用:official。请重新选择。'
const error = '重写注释模型不可用:official。请重新选择。'
const editor = preview(async () => error)
try {
await editor.send({ type: 'rewriteComment', askId: 'r1', anchor: 'block', images: [] })
@@ -139,8 +140,24 @@ describe('预览里重写注释', () => {
const HEAD_BASE: DiffBase = { label: '上一次提交', key: 'head:web/a.ts', read: async () => '// 改之前', missing: '' }
const OPTIONS = [{ id: 'offical', label: 'offical' }, { id: 'sonnet', label: 'sonnet' }, { id: 'dsflash', label: 'dsflash' }]
/** 一套 profile 选择:眼下选的是 selected,publish 模拟它变了、通知订阅的预览 */
function profileSet(selected: string) {
const listeners = new Set<(choice: ProfileChoice) => void>()
return {
subscribe: (listener: (choice: ProfileChoice) => void) => {
listeners.add(listener)
return { dispose: () => listeners.delete(listener) }
},
choice: async (): Promise<ProfileChoice> => ({ options: OPTIONS, selected }),
select: vi.fn(async (_id: string) => {}),
publish: (choice: ProfileChoice) => listeners.forEach(listener => listener(choice)),
}
}
/** 对比基准只认从「未提交的更改」点开的:从那儿点开的对比上一次提交,别处打开的不比 */
function opening() {
function opening(profiles = { ask: profileSet(''), rewrite: profileSet('') }) {
const subscribe = () => ({ dispose: () => {} })
const diffBase = vi.fn((_uri: unknown, from: OpenedFrom): DiffBase | undefined => from === 'uncommitted' ? HEAD_BASE : undefined)
const qa = {
@@ -148,7 +165,7 @@ function opening() {
onDidChange: subscribe,
onDidAnswer: subscribe,
onDidRewrite: subscribe,
profiles: { subscribe, choice: async () => ({ profiles: [], selected: '' }) },
profiles,
view: () => ({ type: 'qa' }),
}
const provider = new PreviewEditorProvider(...[
@@ -290,3 +307,41 @@ describe('预览对比什么看这个标签页是从哪儿打开的', () => {
expect(diffBase).not.toHaveBeenCalledWith(document.uri, 'uncommitted')
})
})
describe('问 AI 和重写注释的 profile 下拉各管各的', () => {
it('ready 后两套各发一次;哪一套变了只发哪一套', async () => {
const profiles = { ask: profileSet('sonnet'), rewrite: profileSet('dsflash') }
const { provider, document } = opening(profiles)
const page = tab()
provider.resolveCustomTextEditor(document as never, page.panel)
await page.send({ type: 'ready' })
await vi.waitFor(() => {
expect(page.posted()).toContainEqual({ type: 'profiles', kind: 'ask', options: OPTIONS, selected: 'sonnet' })
expect(page.posted()).toContainEqual({ type: 'profiles', kind: 'rewrite', options: OPTIONS, selected: 'dsflash' })
})
page.clear()
profiles.rewrite.publish({ options: OPTIONS, selected: 'offical' })
expect(page.posted()).toContainEqual({ type: 'profiles', kind: 'rewrite', options: OPTIONS, selected: 'offical' })
expect(page.posted()).not.toContainEqual(expect.objectContaining({ type: 'profiles', kind: 'ask' }))
})
it('下拉换了哪一套就只改哪一套;换不成时报错,并把那一套眼下的选择发回去', async () => {
const profiles = { ask: profileSet('sonnet'), rewrite: profileSet('dsflash') }
const { provider, document } = opening(profiles)
const page = tab()
provider.resolveCustomTextEditor(document as never, page.panel)
await page.send({ type: 'ready' })
await page.send({ type: 'selectProfile', kind: 'rewrite', id: 'offical' })
expect(profiles.rewrite.select).toHaveBeenCalledWith('offical')
expect(profiles.ask.select).not.toHaveBeenCalled()
profiles.ask.select.mockRejectedValueOnce(new Error('问答模型不可用:gone。请重新选择。'))
page.clear()
await page.send({ type: 'selectProfile', kind: 'ask', id: 'gone' })
expect(vi.mocked(window.showErrorMessage)).toHaveBeenCalledWith('问答模型不可用:gone。请重新选择。')
expect(page.posted()).toContainEqual({ type: 'profiles', kind: 'ask', options: OPTIONS, selected: 'sonnet' })
expect(page.posted()).not.toContainEqual(expect.objectContaining({ type: 'profiles', kind: 'rewrite' }))
})
})
+16 -12
View File
@@ -14,7 +14,7 @@ import type { TreeSitterRuntime } from '../runtime'
import type { ImportedName, LinkTarget, SymbolNode } from '../symbolLinks'
import type { BlockFilter } from './blockFilter'
import type { FoundLocation } from './definitions'
import type { DefinitionPeek, ExtensionToWebview, Occurrence, Reveal, WebviewToExtension } from './messages'
import type { ChatKind, DefinitionPeek, ExtensionToWebview, Occurrence, Reveal, WebviewToExtension } from './messages'
import type { TargetSpot } from './openTarget'
import type { TopSubject } from './pathPreview'
import { realpath } from 'node:fs/promises'
@@ -51,6 +51,9 @@ export const PREVIEW_VIEW_TYPE = 'superpowers.codeReader.preview'
/** 连续输入时合并成一次重新解析。 */
const REFRESH_DELAY_MS = 150
/** 预览里各有一个 profile 下拉的两种对话 */
const CHAT_KINDS: readonly ChatKind[] = ['ask', 'rewrite']
/**
* 一次打开预览带的话:这个标签页是从哪儿打开的(定对比什么);要滚到哪(从文本编辑器切过来时它顶部那一行,或跳到的定义);
* 要不要把光标放进顶部「问 AI」输入框(侧栏「问 AI」打开的)。
@@ -290,10 +293,10 @@ class Preview {
if (uris.some(uri => uri.toString() === this.subject().uri.toString()))
this.postQa()
}),
owner.qa.profiles.subscribe((choice) => {
...CHAT_KINDS.map(kind => owner.qa.profiles[kind].subscribe((choice) => {
if (this.ready)
this.post({ type: 'askProfiles', ...choice })
}),
this.post({ type: 'profiles', kind, ...choice })
})),
owner.qa.onDidAnswer((event) => {
if (event.owner !== this.subject().uri.toString() || !this.ready)
return
@@ -546,11 +549,11 @@ class Preview {
this.post({ type: 'focusPathAsk' })
}
/** profile 列表每次现读(同看板),读完页面还在才发。 */
private async postProfiles(): Promise<void> {
const choice = await this.owner.qa.profiles.choice()
/** kind 那种对话的 profile 列表每次现读(同看板),读完页面还在才发。 */
private async postProfiles(kind: ChatKind): Promise<void> {
const choice = await this.owner.qa.profiles[kind].choice()
if (this.ready)
this.post({ type: 'askProfiles', ...choice })
this.post({ type: 'profiles', kind, ...choice })
}
/**
@@ -601,7 +604,8 @@ class Preview {
this.postHoverDelay()
this.postStickyScroll()
this.postQa()
void this.postProfiles()
for (const kind of CHAT_KINDS)
void this.postProfiles(kind)
await this.push()
if (this.pendingPathFocus)
this.focusPathAsk()
@@ -609,13 +613,13 @@ class Preview {
case 'ask':
await this.ask(msg.askId, msg.anchor, msg.question, msg.images)
return
case 'selectAskProfile':
case 'selectProfile':
try {
await this.owner.qa.profiles.select(msg.id)
await this.owner.qa.profiles[msg.kind].select(msg.id)
}
catch (err) {
void window.showErrorMessage(err instanceof Error ? err.message : String(err))
await this.postProfiles()
await this.postProfiles(msg.kind)
}
return
case 'stopAsk':
+31 -18
View File
@@ -43,11 +43,24 @@ describe('profile 列表 → 下拉的选项', () => {
})
})
describe('文件问答默认模型与临时选择', () => {
describe('报错说清是哪一套', () => {
it('问答、重写注释各报各的名字,并指向设置里各自的默认模型', async () => {
const gone = `${DIR}/gone.json`
await expect(new AskProfiles('问答', () => gone, source()).current())
.rejects
.toThrow(`问答模型不可用:${gone}。请在设置的「问答默认模型」里重新选择,或在输入框旁临时切换。`)
await expect(new AskProfiles('重写注释', () => gone, source()).current())
.rejects
.toThrow(`重写注释模型不可用:${gone}。请在设置的「重写注释默认模型」里重新选择,或在输入框旁临时切换。`)
await expect(new AskProfiles('重写注释', () => '', source()).select('unknown')).rejects.toThrow('重写注释模型不可用:unknown。请重新选择。')
})
})
describe('默认模型与临时选择', () => {
it.each(['offical', 'official'])('临时选空默认后,%s.json 增加或删除都保持不带配置文件', async (officialName) => {
let available = [profile('sonnet')]
let defaultPath = DEFAULT_PATH
const profiles = new AskProfiles(() => `${DIR}/sonnet.json`, {
const profiles = new AskProfiles('问答', () => `${DIR}/sonnet.json`, {
...source(),
list: async () => available,
defaultPath: () => defaultPath,
@@ -67,7 +80,7 @@ describe('文件问答默认模型与临时选择', () => {
it('真实目录变更才清除显式空选择并恢复设置默认', async () => {
let directory = DIR
const profiles = new AskProfiles(() => `${DIR}/sonnet.json`, {
const profiles = new AskProfiles('问答', () => `${DIR}/sonnet.json`, {
...source([profile('sonnet')]),
directory: () => directory,
})
@@ -81,7 +94,7 @@ describe('文件问答默认模型与临时选择', () => {
it('仅官方文件删除改变自动默认路径时,保留失效的临时选择并阻止发问', async () => {
let available = [profile('dsflash'), profile('official')]
let defaultPath = `${DIR}/official.json`
const profiles = new AskProfiles(() => `${DIR}/dsflash.json`, {
const profiles = new AskProfiles('问答', () => `${DIR}/dsflash.json`, {
...source(),
list: async () => available,
defaultPath: () => defaultPath,
@@ -90,11 +103,11 @@ describe('文件问答默认模型与临时选择', () => {
available = [profile('dsflash')]
defaultPath = `${DIR}/offical.json`
expect((await profiles.choice()).selected).toBe(`${DIR}/official.json`)
await expect(profiles.current()).rejects.toThrow(`文件问答模型不可用:${DIR}/official.json`)
await expect(profiles.current()).rejects.toThrow(`问答模型不可用:${DIR}/official.json`)
})
it('没有官方配置文件时,可以从配置的默认模型临时切到内置默认', async () => {
const profiles = new AskProfiles(() => `${DIR}/sonnet.json`, source([profile('sonnet')]))
const profiles = new AskProfiles('问答', () => `${DIR}/sonnet.json`, source([profile('sonnet')]))
await profiles.select('')
expect((await profiles.choice()).selected).toBe('')
expect(await profiles.current()).toBeUndefined()
@@ -102,19 +115,19 @@ describe('文件问答默认模型与临时选择', () => {
it('配置默认实际用于命令行;临时切换不改默认,重新创建服务恢复配置', async () => {
const configured = `${DIR}/dsflash.json`
const profiles = new AskProfiles(() => configured, source())
const profiles = new AskProfiles('问答', () => configured, source())
expect(await profiles.current()).toEqual(profile('dsflash'))
expect(askArgs({ profilePath: (await profiles.current())?.path }).slice(0, 2)).toEqual(['--settings', configured])
await profiles.select('sonnet')
expect((await profiles.choice()).selected).toBe('sonnet')
expect(await profiles.current()).toEqual(profile('sonnet'))
expect(configured).toBe(`${DIR}/dsflash.json`)
expect(await new AskProfiles(() => configured, source()).current()).toEqual(profile('dsflash'))
expect(await new AskProfiles('问答', () => configured, source()).current()).toEqual(profile('dsflash'))
})
it('配置变更清除临时选择并通知所有预览;相同配置刷新保留临时选择', async () => {
let configured = `${DIR}/dsflash.json`
const profiles = new AskProfiles(() => configured, source())
const profiles = new AskProfiles('问答', () => configured, source())
const updates: string[] = []
profiles.subscribe(choice => updates.push(choice.selected))
await profiles.select('sonnet')
@@ -131,29 +144,29 @@ describe('文件问答默认模型与临时选择', () => {
it('配置的模型已删除时保留不可用选项并报错,不会偷偷换成官方模型', async () => {
let available = [...PROFILES]
const profiles = new AskProfiles(() => `${DIR}/sonnet.json`, { ...source(), list: async () => available })
const profiles = new AskProfiles('问答', () => `${DIR}/sonnet.json`, { ...source(), list: async () => available })
expect(await profiles.current()).toEqual(profile('sonnet'))
available = available.filter(item => item.name !== 'sonnet')
const choice = await profiles.choice()
expect(choice.options.find(item => item.id === choice.selected)?.label).toContain('不可用')
await expect(profiles.current()).rejects.toThrow('文件问答模型不可用')
await expect(profiles.current()).rejects.toThrow('问答模型不可用')
await profiles.select('dsflash')
expect(await profiles.current()).toEqual(profile('dsflash'))
})
it('临时模型被删除和无效选择都会报错,不能静默换模型', async () => {
let available = [...PROFILES]
const profiles = new AskProfiles(() => '', { ...source(), list: async () => available })
const profiles = new AskProfiles('问答', () => '', { ...source(), list: async () => available })
await profiles.select('sonnet')
available = available.filter(item => item.name !== 'sonnet')
await expect(profiles.current()).rejects.toThrow('文件问答模型不可用')
await expect(profiles.select('unknown')).rejects.toThrow('文件问答模型不可用')
await expect(profiles.current()).rejects.toThrow('问答模型不可用')
await expect(profiles.select('unknown')).rejects.toThrow('问答模型不可用')
await profiles.select('offical')
expect(await profiles.current()).toEqual(profile('offical'))
})
it('一个预览选了,所有订阅的预览都收到新的选项和选中的那项;取消订阅后不再收到', async () => {
const profiles = new AskProfiles(() => '', source())
const profiles = new AskProfiles('问答', () => '', source())
const first: ProfileChoice[] = []
const second: string[] = []
profiles.subscribe(choice => first.push(choice))
@@ -167,17 +180,17 @@ describe('文件问答默认模型与临时选择', () => {
})
it('下一个问题用选的那个 profile:命令行带它的 --settings;选「默认」时没有、不带 --settings', async () => {
const profiles = new AskProfiles(() => `${DIR}/sonnet.json`, source())
const profiles = new AskProfiles('问答', () => `${DIR}/sonnet.json`, source())
const chosen = await profiles.current()
expect(chosen).toEqual(profile('sonnet'))
expect(askArgs({ profilePath: chosen?.path }).slice(0, 2)).toEqual(['--settings', `${DIR}/sonnet.json`])
const none = await new AskProfiles(() => '', source([])).current()
const none = await new AskProfiles('问答', () => '', source([])).current()
expect(none).toBeUndefined()
expect(askArgs({ profilePath: none?.path })).not.toContain('--settings')
})
it('没选过:用插件的默认 profile(和以前问 AI 用的一样)', async () => {
expect(await new AskProfiles(() => '', source()).current()).toEqual(profile('offical'))
expect(await new AskProfiles('问答', () => '', source()).current()).toEqual(profile('offical'))
})
})
+9 -4
View File
@@ -34,13 +34,18 @@ export interface ProfileSource {
const PROFILE_SOURCE: ProfileSource = { list: listClaudeProfiles, defaultPath: getDefaultProfilePath, directory: getProfilesDir }
/** 所有预览共用临时模型选择,重新创建服务或修改默认配置后恢复设置里的默认值。 */
/**
* 一套 profile 选择:临时切换所有预览共用、不写进设置,重新创建服务或这一套的默认配置改了以后回到设置里的默认值。
*
* @param purpose 这一套给什么用(「问答」「重写注释」);报错时用它说是哪一套、该改设置里的哪一项
* @param configuredPath 读设置里这一套的默认 profile 路径
*/
export class AskProfiles {
private readonly listeners = new Set<(choice: ProfileChoice) => void>()
private temporary: string | undefined
private defaultKey: string | undefined
constructor(private readonly configuredPath: () => string, private readonly source: ProfileSource = PROFILE_SOURCE) {}
constructor(readonly purpose: string, private readonly configuredPath: () => string, private readonly source: ProfileSource = PROFILE_SOURCE) {}
async choice(): Promise<ProfileChoice> {
return (await this.read()).choice
@@ -52,7 +57,7 @@ export class AskProfiles {
this.publish(choice)
const profile = profiles.find(profile => profile.name === choice.selected)
if (choice.selected && !profile)
throw new Error(`文件问答模型不可用:${choice.selected}。请在设置中重新选择默认模型,或在输入框旁临时切换。`)
throw new Error(`${this.purpose}模型不可用:${choice.selected}。请在设置的「${this.purpose}默认模型」里重新选择,或在输入框旁临时切换。`)
return profile
}
@@ -66,7 +71,7 @@ export class AskProfiles {
const { profiles, choice } = await this.read()
const profile = profiles.find(profile => profile.name === id)
if (id ? !profile : !choice.options.some(option => option.id === ''))
throw new Error(`文件问答模型不可用:${id}。请重新选择。`)
throw new Error(`${this.purpose}模型不可用:${id}。请重新选择。`)
this.temporary = profile?.path ?? ''
await this.refresh()
}
+79 -7
View File
@@ -91,10 +91,10 @@ describe('问这个文件实际使用设置的默认模型', () => {
await saveSettings(ctx, { defaultAskProfilePath: '/p/sonnet.json' })
vi.mocked(listClaudeProfiles).mockResolvedValue(AVAILABLE.filter(item => item.name !== 'offical'))
const { qa, runner } = service(ctx)
await qa.profiles.select('')
await qa.profiles.ask.select('')
vi.mocked(listClaudeProfiles).mockResolvedValue(AVAILABLE)
const shown = vi.fn()
qa.profiles.subscribe(shown)
qa.profiles.ask.subscribe(shown)
await saveSettings(ctx, { webhookPort: 9000 })
await vi.waitFor(() => expect(shown).toHaveBeenLastCalledWith(expect.objectContaining({ selected: '' })))
await qa.askPath(uri, 'file', { askId: '1', question: '这是什么', images: [] })
@@ -114,7 +114,7 @@ describe('问这个文件实际使用设置的默认模型', () => {
await qa.askPath(uri, 'file', { askId: '1', question: '这是什么', images: [] })
expect(runner.mock.calls[0]?.[0].profilePath).toBe('/p/dsflash.json')
qa.stop('1')
await qa.profiles.select('sonnet')
await qa.profiles.ask.select('sonnet')
await qa.askPath(uri, 'file', { askId: '2', question: '这是什么', images: [] })
expect(runner.mock.calls[1]?.[0].profilePath).toBe('/p/sonnet.json')
expect(getSettings(ctx).defaultAskProfilePath).toBe('/p/dsflash.json')
@@ -126,9 +126,9 @@ describe('问这个文件实际使用设置的默认模型', () => {
it('保存新默认后所有现有预览收到新选择,下一个问题和界面使用同一个模型', async () => {
const ctx = context()
const { qa, runner } = service(ctx)
await qa.profiles.select('sonnet')
await qa.profiles.ask.select('sonnet')
const shown = vi.fn()
qa.profiles.subscribe(shown)
qa.profiles.ask.subscribe(shown)
await saveSettings(ctx, { defaultAskProfilePath: '/p/dsflash.json' })
await vi.waitFor(() => expect(shown).toHaveBeenLastCalledWith(expect.objectContaining({ selected: 'dsflash' })))
await qa.askPath(uri, 'file', { askId: '1', question: '这是什么', images: [] })
@@ -139,12 +139,84 @@ describe('问这个文件实际使用设置的默认模型', () => {
const ctx = context()
await saveSettings(ctx, { defaultAskProfilePath: '/p/deleted.json' })
const { qa, runner } = service(ctx)
expect(await qa.askPath(uri, 'file', { askId: '1', question: '这是什么', images: [] })).toContain('文件问答模型不可用')
expect(await qa.ask(uri, { askId: '2', anchor: 'a', question: '问题', prompt: '问题', followUp: '继续', images: [] })).toContain('文件问答模型不可用')
expect(await qa.askPath(uri, 'file', { askId: '1', question: '这是什么', images: [] })).toMatch(/^问答模型不可用:\/p\/deleted\.json。/)
expect(await qa.ask(uri, { askId: '2', anchor: 'a', question: '问题', prompt: '问题', followUp: '继续', images: [] })).toMatch(/^问答模型不可用:\/p\/deleted\.json。/)
expect(runner).not.toHaveBeenCalled()
})
})
describe('问 AI 和重写注释各用各的 profile', () => {
const SKILL = '/ecc:writing-code-comments a.ts:1-3'
const asking = (askId: string) => ({ askId, anchor: 'function f', question: '为什么', prompt: '完整的', followUp: '短的', images: [] })
const rewriting = (askId: string): RewriteRequest => ({ askId, anchor: 'function f', question: SKILL, prompt: SKILL, images: [], writeBack: async () => undefined })
it('各按设置里自己的默认模型起步:块下面问、顶部问、了解一块代码用问答的,重写注释用重写的', async () => {
const ctx = context()
await saveSettings(ctx, { defaultAskProfilePath: '/p/sonnet.json', defaultRewriteProfilePath: '/p/dsflash.json' })
const { qa, runner, rewriter } = service(ctx)
rewriter.mockResolvedValue({ body: '新的。', sessionId: 'r1' })
await qa.ask(uri, asking('1'))
await qa.askPath(uri, 'file', { askId: '2', question: '这是什么', images: [] })
qa.stop('2')
await qa.askTop(uri, { askId: '3', question: '用户登录', images: [] }, { prompt: '找', followUp: '接着找' }, async answer => ({ text: answer.text }))
await qa.rewrite(uri, rewriting('4'))
expect(runner.mock.calls.map(([run]) => run.profilePath)).toEqual(['/p/sonnet.json', '/p/sonnet.json', '/p/sonnet.json'])
expect(rewriter.mock.calls[0]?.[0].profilePath).toBe('/p/dsflash.json')
})
it('都没配时两套都用默认的那个', async () => {
const { qa, runner, rewriter } = service(context())
rewriter.mockResolvedValue({ body: '新的。', sessionId: 'r1' })
await qa.ask(uri, asking('1'))
await qa.rewrite(uri, rewriting('2'))
expect(runner.mock.calls[0]?.[0].profilePath).toBe('/p/offical.json')
expect(rewriter.mock.calls[0]?.[0].profilePath).toBe('/p/offical.json')
})
it('临时切换只改自己那一套、只通知自己那一套的下拉,不写进设置', async () => {
const ctx = context()
const { qa, runner, rewriter } = service(ctx)
rewriter.mockResolvedValue({ body: '新的。', sessionId: 'r1' })
const askShown = vi.fn()
const rewriteShown = vi.fn()
qa.profiles.ask.subscribe(askShown)
qa.profiles.rewrite.subscribe(rewriteShown)
await qa.profiles.rewrite.select('dsflash')
expect(rewriteShown).toHaveBeenLastCalledWith(expect.objectContaining({ selected: 'dsflash' }))
expect(askShown).not.toHaveBeenCalled()
await qa.profiles.ask.select('sonnet')
expect(askShown).toHaveBeenLastCalledWith(expect.objectContaining({ selected: 'sonnet' }))
expect(rewriteShown).toHaveBeenCalledTimes(1)
await qa.ask(uri, asking('1'))
await qa.rewrite(uri, rewriting('2'))
expect(runner.mock.calls[0]?.[0].profilePath).toBe('/p/sonnet.json')
expect(rewriter.mock.calls[0]?.[0].profilePath).toBe('/p/dsflash.json')
expect(getSettings(ctx)).toMatchObject({ defaultAskProfilePath: '', defaultRewriteProfilePath: '' })
})
it('改了重写注释的默认模型只清掉重写那一套的临时选择,问答那一套的留着', async () => {
const ctx = context()
const { qa } = service(ctx)
await qa.profiles.ask.select('sonnet')
await qa.profiles.rewrite.select('sonnet')
const rewriteShown = vi.fn()
qa.profiles.rewrite.subscribe(rewriteShown)
await saveSettings(ctx, { defaultRewriteProfilePath: '/p/dsflash.json' })
await vi.waitFor(() => expect(rewriteShown).toHaveBeenLastCalledWith(expect.objectContaining({ selected: 'dsflash' })))
expect((await qa.profiles.ask.choice()).selected).toBe('sonnet')
})
it('重写注释用的模型删掉了:报重写注释的错、不启动模型;问答照常', async () => {
const ctx = context()
await saveSettings(ctx, { defaultRewriteProfilePath: '/p/deleted.json' })
const { qa, runner, rewriter } = service(ctx)
expect(await qa.rewrite(uri, rewriting('1'))).toMatch(/^重写注释模型不可用:\/p\/deleted\.json。/)
expect(rewriter).not.toHaveBeenCalled()
expect(await qa.ask(uri, asking('2'))).toBeUndefined()
expect(runner).toHaveBeenCalledTimes(1)
})
})
describe('重写注释的记录', () => {
const SKILL = '/ecc:writing-code-comments a.ts:1-3'
+22 -17
View File
@@ -1,7 +1,7 @@
import type { Event, ExtensionContext, Memento } from 'vscode'
import type { ClaudeProfile } from '../../cc/profiles'
import type { ClaudeImage } from '../../cc/spawnClaude'
import type { QaEntryView, QaMessage } from '../editor/messages'
import type { ChatKind, QaEntryView, QaMessage } from '../editor/messages'
import type { PathSubject, TopSubject } from '../editor/pathPreview'
import type { PathLocation } from '../folderStore'
import type { AskEnd, RunningAsk } from './asks'
@@ -121,8 +121,8 @@ export class CodeQa implements Disposable {
/** 顶部问答的读写排成一队,两次同时答完不会互相盖掉 */
private pathQueue: Promise<void> = Promise.resolve()
private readonly settingsSubscription: Disposable
/** 所有预览共用当前模型,临时切换不会写入默认设置。 */
readonly profiles: AskProfiles
/** 问 AI(块下面和顶部)、重写注释各用各的一套 profile,各自的临时切换所有预览共用、不写进设置 */
readonly profiles: Readonly<Record<ChatKind, AskProfiles>>
/** 块下面的问答、重写记录或顶部的问答变了的那些文件 / 文件夹 */
readonly onDidChange: Event<Uri[]> = (listener, thisArgs, disposables) => {
const subscription = Disposable.from(
@@ -143,11 +143,16 @@ export class CodeQa implements Disposable {
runner: AskRunner = askClaude,
rewriter: (ask: CommentAsk) => Promise<CommentAnswer> = askCommentBody,
) {
this.profiles = new AskProfiles(() => getSettings(context).defaultAskProfilePath)
this.profiles = {
ask: new AskProfiles('问答', () => getSettings(context).defaultAskProfilePath),
rewrite: new AskProfiles('重写注释', () => getSettings(context).defaultRewriteProfilePath),
}
this.settingsSubscription = onDidChangeSettings(context, () => {
void this.profiles.refresh().catch((err) => {
void window.showErrorMessage(`文件问答模型刷新失败:${err instanceof Error ? err.message : String(err)}`)
})
for (const profiles of Object.values(this.profiles)) {
void profiles.refresh().catch((err) => {
void window.showErrorMessage(`${profiles.purpose}模型刷新失败:${err instanceof Error ? err.message : String(err)}`)
})
}
})
this.asks = new QaAsks(runner)
this.rewrites = new QaAsks(rewriter, REWRITE_POLICY)
@@ -188,11 +193,11 @@ export class CodeQa implements Disposable {
/**
* 开始问;问不了时返回原因(给人看的话)。在工作区文件夹里跑 claude,它读得到整个项目。
* 这块问过的就接着最近一次的会话问(收起再展开、重启 VS Code 都一样),没问过就带上代码上下文开新会话。
* 用眼下选的 profile;和那次会话开头用的不一样也照样接着问(`--resume` 和 `--settings` 能一起用)。
* 用问 AI 眼下选的 profile;和那次会话开头用的不一样也照样接着问(`--resume` 和 `--settings` 能一起用)。
* 带的图片随问题发,答成了才写进 `.spx/code-qa/`、记在这条上;没答成不留文件。
*/
async ask(uri: Uri, request: AskRequest): Promise<string | undefined> {
const ready = await this.prepare(uri, request.images, '问答')
const ready = await this.prepare(uri, request.images, 'ask')
if (typeof ready === 'string')
return ready
const { at, profile } = ready
@@ -230,12 +235,12 @@ export class CodeQa implements Disposable {
}
/**
* 重写一段注释;开不了时返回原因(给人看的话)。在工作区文件夹里跑 claude(见 askCommentBody),用眼下选的 profile。
* 重写一段注释;开不了时返回原因(给人看的话)。在工作区文件夹里跑 claude(见 [askCommentBody]),用重写注释眼下选的 profile。
* 带 followUp 时接着这块最近一次重写的会话说(和问答的会话分开),没重写过就开新会话;不带时(点按钮)总是开新会话。
* 模型答完先写回文件,再把这一轮记下:用户的话、交回的正文、没写进文件的原因、会话 id、profile、图片。Claude Code 报错、被叫停的不记,文件不动。
*/
async rewrite(uri: Uri, request: RewriteRequest): Promise<string | undefined> {
const ready = await this.prepare(uri, request.images, '重写记录')
const ready = await this.prepare(uri, request.images, 'rewrite')
if (typeof ready === 'string')
return ready
const { at, profile } = ready
@@ -295,15 +300,15 @@ export class CodeQa implements Disposable {
await this.rewriteStore.update(at.folder, map => withoutEntry(map, at.key, anchor, entryId))
}
/** 块下面开一轮前都要的:文件在工作区文件夹里(记录才有地方存)、图片格式认得、眼下选的 profile 还在;不行时返回原因。 */
private async prepare(uri: Uri, images: readonly ClaudeImage[], record: string): Promise<{ at: PathLocation, profile?: ClaudeProfile } | string> {
/** 块下面开一轮 kind 那种对话前都要的:文件在工作区文件夹里(记录才有地方存)、图片格式认得、这种对话眼下选的 profile 还在;不行时返回原因。 */
private async prepare(uri: Uri, images: readonly ClaudeImage[], kind: ChatKind): Promise<{ at: PathLocation, profile?: ClaudeProfile } | string> {
const at = locate(uri)
if (!at)
return `这个文件不在工作区文件夹里,${record}没地方存。`
return `这个文件不在工作区文件夹里,${kind === 'ask' ? '问答' : '重写记录'}没地方存。`
if (!images.every(image => isQaImageType(image.mediaType)))
return '只能带 PNG、JPEG、GIF、WebP 图片。'
try {
const profile = await this.profiles.current()
const profile = await this.profiles[kind].current()
return { at, ...(profile && { profile }) }
}
catch (err) {
@@ -322,7 +327,7 @@ export class CodeQa implements Disposable {
}
/**
* 在 subject 这一页的顶部问一轮(文件、文件夹、「了解一块代码」的功能,记在哪见 topQaLocation);问不了、进行中再问时返回给人看的原因。
* 在 subject 这一页的顶部问一轮(文件、文件夹、「了解一块代码」的功能,记在哪见 [topQaLocation]),用问 AI 眼下选的 profile;问不了、进行中再问时返回给人看的原因。
* 问过的接着最近一次的会话说 run.followUp,没问过、会话找不到了发 run.prompt;要结构化结果时带上 run.schema,别的目录要读时带上 run.addDirs。
* 答完交给 settle:它给出这一轮记下的回答,或说交回的不合格(这一轮算没答成)。答成了记在 workspaceState 里,带的图片写进 `.spx/code-qa/`;没答成不记。
*/
@@ -335,7 +340,7 @@ export class CodeQa implements Disposable {
return '只能带 PNG、JPEG、GIF、WebP 图片。'
let profile: ClaudeProfile | undefined
try {
profile = await this.profiles.current()
profile = await this.profiles.ask.current()
}
catch (err) {
return err instanceof Error ? err.message : String(err)