diff --git a/CHANGELOG.md b/CHANGELOG.md index ed5aa4ab0..068c79aed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [v1.0.13] - 2026-11-09 + +- fix(ui): 全屏查看器在 iOS 状态栏下让开 safe-area (94b15f3d) +- fix(models): 模型列表未使用模型按名称首字母排序 (4f55ed0a) +- fix(slash-command): 斜杠命令匹配改为打分式模糊排序 (0deb01cb) +- fix(attachment): 路径引用在时间线可见,文本/图片预览修复 (f1bc065c) +- feat(attachment): 按类型和大小分流,二进制只给路径 (0aceff7a) +- feat(mention): @ 菜单兼容反斜杠路径 (b4147a97) +- fix(attachment): @ 提及回到 files[],对齐官方 file/path 两种部件 (f6e902f0) +- fix(sidebar): 连接状态点改用服务器健康状态,与设置页同源 (08cb1f71) + ## [v1.0.12] - 2026-11-07 - perf(react): 稳定 useSyncExternalStore 订阅引用,避免每次渲染重绑 (64a77cd7) diff --git a/package-lock.json b/package-lock.json index e6f393d02..0c59e1f59 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencodeui", - "version": "1.0.12", + "version": "1.0.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencodeui", - "version": "1.0.12", + "version": "1.0.13", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index 746570927..946706806 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencodeui", - "version": "1.0.12", + "version": "1.0.13", "description": "A third-party web frontend for OpenCode", "license": "GPL-3.0-only", "type": "module", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 39e1c4970..0070e65a7 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2725,7 +2725,7 @@ dependencies = [ [[package]] name = "opencodeui" -version = "1.0.12" +version = "1.0.13" dependencies = [ "futures-util", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 90e1fe6c7..fe157c395 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodeui" -version = "1.0.12" +version = "1.0.13" description = "OpenCode UI - Tauri Mobile App" authors = ["lehhair"] license = "GPL-3.0-only" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 14851a2b0..4be04a009 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "OpenCode", - "version": "1.0.12", + "version": "1.0.13", "identifier": "com.opencodeui.app", "build": { "frontendDist": "../dist", diff --git a/src/api/events.ts b/src/api/events.ts index a8ce4fcf7..3faaf9ab2 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -161,11 +161,15 @@ function getOrCreateConnection(serverId: string): ServerConnection { function updateConnectionState(serverId: string, update: Partial): void { const conn = connections.get(serverId) if (!conn) return - const becameConnected = update.state === 'connected' && conn.info.state !== 'connected' + const wasConnected = conn.info.state === 'connected' + const becameConnected = update.state === 'connected' && !wasConnected conn.info = { ...conn.info, ...update } // 设置页的健康灯和侧边栏的 SSE 状态必须收敛:连上了就把健康快照提升为 // 在线,否则启动期失败的探测结果会一直红着(健康轮询已跳过已连接服务器) if (becameConnected) serverStore.noteServerConnected(serverId) + else if (wasConnected && update.state !== undefined && update.state !== 'connected') { + serverStore.noteServerDisconnected(serverId) + } connectionListeners.get(serverId)?.forEach(fn => { fn(conn.info) }) @@ -946,28 +950,6 @@ export function subscribeToServerConnectionState(serverId: string, fn: (info: Co } } -/** - * 订阅活动服务器的连接状态变化(兼容旧 API)。 - * 跟随 active server:切换服务器时自动迁移订阅, - * 否则状态栏会一直显示旧服务器的连接状态。 - */ -export function subscribeToConnectionState(fn: (info: ConnectionInfo) => void): () => void { - let currentServerId = serverStore.getActiveServerId() - let unsubscribe = subscribeToServerConnectionState(currentServerId, fn) - - const offServerChange = serverStore.onServerChange(newServerId => { - if (newServerId === currentServerId) return - unsubscribe() - currentServerId = newServerId - unsubscribe = subscribeToServerConnectionState(currentServerId, fn) - }) - - return () => { - offServerChange() - unsubscribe() - } -} - /** * 订阅指定服务器的事件(每服务器独立连接)。 */ diff --git a/src/api/message.test.ts b/src/api/message.test.ts index 8c56fd6c2..37be30e62 100644 --- a/src/api/message.test.ts +++ b/src/api/message.test.ts @@ -150,8 +150,10 @@ describe('sendMessage — prompt 载荷(官方 request.ts + submit.ts:395-411 }) it('mention 区间随 files/agents 一起发出', async () => { + const text = '看下 @foo.ts 用 @build 跑' await sendMessage({ ...baseParams(), + text, attachments: [ { id: 'a1', @@ -171,15 +173,24 @@ describe('sendMessage — prompt 载荷(官方 request.ts + submit.ts:395-411 }) const payload = lastPromptPayload() + const fileStart = text.indexOf('@foo.ts') expect(payload.files).toEqual([ - { uri: 'file:///proj/src/foo.ts', name: 'foo.ts', mention: { start: 5, end: 12, text: '@foo.ts' } }, + { + uri: 'file:///proj/src/foo.ts', + name: 'foo.ts', + mention: { start: fileStart, end: fileStart + '@foo.ts'.length, text: '@foo.ts' }, + }, + ]) + const agentStart = text.indexOf('@build') + expect(payload.agents).toEqual([ + { name: 'build', mention: { start: agentStart, end: agentStart + '@build'.length, text: '@build' } }, ]) - expect(payload.agents).toEqual([{ name: 'build', mention: { start: 20, end: 26, text: '@build' } }]) }) it('skill 附件进 skills 数组(id + mention)', async () => { await sendMessage({ ...baseParams(), + text: '@commit 提交', attachments: [ { id: 's1', @@ -279,7 +290,7 @@ describe('sendMessage — 路径型附件的文本引用', () => { expect(payload.metadata?.attachments).toHaveLength(1) }) - it('带 mention 的附件(@ 引用)不额外注入路径', async () => { + it('带 mention 的附件(@ 引用)进 files[],不额外注入路径', async () => { await sendMessage({ ...baseParams(), text: '@src/foo.ts 看下', @@ -295,10 +306,38 @@ describe('sendMessage — 路径型附件的文本引用', () => { }) const payload = lastPromptPayload() + expect(payload.files).toEqual([ + { + uri: 'file:///proj/src/foo.ts', + name: 'foo.ts', + mention: { start: 0, end: 11, text: '@src/foo.ts' }, + }, + ]) expect(payload.text).toBe('@src/foo.ts 看下') expect(payload.metadata?.attachments).toBeUndefined() }) + it('提及前面改过字后,mention 区间按当前文本重新定位', async () => { + await sendMessage({ + ...baseParams(), + text: '先加一句 @src/foo.ts 看下', + attachments: [ + { + id: 'a1', + type: 'file', + displayName: 'foo.ts', + url: 'file:///proj/src/foo.ts', + // 插入时记下的旧偏移(在开头),用户后来在前面补了字 + textRange: { value: '@src/foo.ts', start: 0, end: 11 }, + }, + ] as never, + }) + + const payload = lastPromptPayload() + const start = '先加一句 '.length + expect(payload.files?.[0].mention).toEqual({ start, end: start + 11, text: '@src/foo.ts' }) + }) + it('带 mention 的附件被从文本删掉后仍补路径(pathOnly 只能靠文本可见)', async () => { await sendMessage({ ...baseParams(), @@ -320,6 +359,34 @@ describe('sendMessage — 路径型附件的文本引用', () => { expect(payload.text).toBe('看下这个\nAttached file: `/proj/src/foo.ts`') }) + it('二进制的 path 引用即使正文里有 @path 也补绝对路径(官方 path 部件无条件补)', async () => { + await sendMessage({ + ...baseParams(), + text: '@E:/Downloads/tool.exe 看下', + attachments: [ + { + id: 'a1', + type: 'file', + displayName: 'tool.exe', + url: 'file:///E:/Downloads/tool.exe', + mime: 'application/x-msdownload', + pathOnly: true, + // 拖入时插入的芯片文本仍在正文里 + textRange: { value: '@E:/Downloads/tool.exe', start: 0, end: 22 }, + }, + ] as never, + }) + + const payload = lastPromptPayload() + // 不进 files[],不受服务端 20MB 读取上限影响 + expect(payload.files).toBeUndefined() + // 但绝对路径必须给到模型(@ 相对路径不能保证模型读得到) + expect(payload.text).toBe('@E:/Downloads/tool.exe 看下\nAttached file: `E:/Downloads/tool.exe`') + expect(payload.metadata?.attachments).toEqual([ + { name: 'tool.exe', mime: 'application/x-msdownload', path: 'E:/Downloads/tool.exe' }, + ]) + }) + it('revert 回填的文本里已有同一引用时不重复追加', async () => { const path = '/tmp/opencode/uploads/u1/report.zip' await sendMessage({ @@ -403,6 +470,56 @@ describe('extractUserMessageContent — 路径附件回填', () => { }) }) + it('@ 提及文件回填 mention 区间,再次发送仍按附件处理', async () => { + const { extractUserMessageContent } = await import('./message') + const restored = extractUserMessageContent( + userMessage({ + files: [ + { + data: 'QQ==', + mime: 'text/plain', + source: { type: 'uri', uri: 'file:///repo/a.ts' }, + name: 'a.ts', + mention: { start: 3, end: 9, text: '@a.ts' }, + }, + ], + }), + ) + + expect(restored.attachments[0]).toMatchObject({ + type: 'file', + displayName: 'a.ts', + url: 'file:///repo/a.ts', + mime: 'text/plain', + textRange: { value: '@a.ts', start: 3, end: 9 }, + }) + expect(restored.attachments[0]?.pathOnly).toBeUndefined() + }) + + it('inline 附件从 data 还原成 data URL,回退重发不丢内容', async () => { + const { extractUserMessageContent } = await import('./message') + const restored = extractUserMessageContent( + userMessage({ + metadata: undefined, + files: [ + { + data: 'aW1n', + mime: 'image/png', + source: { type: 'inline' }, + name: 'shot.png', + }, + ], + }), + ) + + expect(restored.attachments[0]).toMatchObject({ + type: 'file', + displayName: 'shot.png', + url: 'data:image/png;base64,aW1n', + mime: 'image/png', + }) + }) + it('已在 files[] 里的附件不会因为 metadata 再重复一次', async () => { const { extractUserMessageContent } = await import('./message') const restored = extractUserMessageContent( diff --git a/src/api/message.ts b/src/api/message.ts index 5492ce1e2..b01012233 100644 --- a/src/api/message.ts +++ b/src/api/message.ts @@ -114,38 +114,47 @@ export function extractUserMessageContent(message: UserMessage): RevertedMessage for (const file of message.files ?? []) { const source = file.source const uri = source?.type === 'uri' ? source.uri : '' + // inline 附件(图片/pdf 等原生媒体)的字节在 data 里,回填成 data URL + // 才能再次发送;之前 url 为空,回退/重发时附件会静默丢失。 + const inlineUrl = uri ? '' : file.data ? `data:${file.mime};base64,${file.data}` : '' + const url = uri || inlineUrl const displayName = file.name || uri || file.mime || 'attachment' - if (uri) seenPaths.add(uri) + if (url) seenPaths.add(url) attachments.push({ id: crypto.randomUUID(), - type: 'file', + type: file.mime === 'application/x-directory' ? 'folder' : 'file', displayName, - // inline 附件没有可回填的路径,只在有 uri 时带上 - url: uri, + url, + mime: file.mime, relativePath: uri || displayName, + // @ 提及的文件回填 mention 区间:再次发送时仍走 files[] + mention, + // 不会被当成普通路径附件重复注入一条 Attached file 文本(官方 promptFromMessage 同款)。 + ...(file.mention + ? { + textRange: { + value: file.mention.text, + start: file.mention.start, + end: file.mention.end, + }, + } + : {}), }) } - // 只作路径引用的附件(超 20MB 未进 files[])不在 message.files 里, + // 只作路径引用的附件(二进制 / 超 20MB / 拖入的本机文件)不在 message.files 里, // 只能从 metadata.attachments 还原——否则回填后模型拿不到这个文件。 - const metadata = message.metadata as Record | undefined - const references = Array.isArray(metadata?.['attachments']) ? metadata['attachments'] : [] - for (const reference of references) { - if (!reference || typeof reference !== 'object') continue - const { name, mime, path } = reference as { name?: unknown; mime?: unknown; path?: unknown } - if (typeof path !== 'string' || !path) continue - - const url = absolutePathToFileUrl(path) + for (const reference of readPromptAttachments(message.metadata)) { + const url = absolutePathToFileUrl(reference.path) if (seenPaths.has(url)) continue seenPaths.add(url) attachments.push({ id: crypto.randomUUID(), - type: 'file', - displayName: typeof name === 'string' && name ? name : fileBaseName(path), + type: reference.mime === 'application/x-directory' ? 'folder' : 'file', + displayName: reference.name, url, - mime: typeof mime === 'string' ? mime : undefined, - relativePath: path, + mime: reference.mime, + relativePath: reference.path, pathOnly: true, }) } @@ -161,6 +170,7 @@ export function extractUserMessageContent(message: UserMessage): RevertedMessage // 回填用户原始输入(不含我们追加的路径引用行):再次发送时由 // applyAttachmentReferences 依据附件重新生成,不会丢也不会重复。 + const metadata = message.metadata as Record | undefined const displayText = metadata?.['displayText'] const text = typeof displayText === 'string' ? displayText : message.text ?? '' @@ -175,7 +185,10 @@ export function extractUserMessageContent(message: UserMessage): RevertedMessage * 附件 → prompt 的 files/agents/skills 部件(buildPromptInput 的组装段, * 队列编辑确认(editedPromptInput)与正常发送共用)。 */ -export function buildPromptParts(attachments: Attachment[]): { +export function buildPromptParts( + attachments: Attachment[], + text?: string, +): { files: Array<{ uri: string; name?: string; mention?: { start: number; end: number; text: string } }> agents: Array<{ name: string; mention?: { start: number; end: number; text: string } }> skills: Array<{ id: string; mention?: { start: number; end: number; text: string } }> @@ -184,10 +197,24 @@ export function buildPromptParts(attachments: Attachment[]): { const agents: Array<{ name: string; mention?: { start: number; end: number; text: string } }> = [] const skills: Array<{ id: string; mention?: { start: number; end: number; text: string } }> = [] - const mention = (attachment: Attachment) => - attachment.textRange - ? { start: attachment.textRange.start, end: attachment.textRange.end, text: attachment.textRange.value } - : undefined + /** + * 解析 mention 区间。 + * + * textarea 的 textRange 是插入时记下的静态偏移,用户在提及前面改过字就会过期。 + * 位置仍然对得上时沿用原区间(能区分重复出现的同名提及);对不上就按 + * 当前文本重新定位。官方编辑器的区间是实时维护的,这里用等价的后处理兜住。 + */ + const mention = (attachment: Attachment) => { + const range = attachment.textRange + if (!range) return undefined + if (!text) return { start: range.start, end: range.end, text: range.value } + if (text.slice(range.start, range.end) === range.value) { + return { start: range.start, end: range.end, text: range.value } + } + const index = text.indexOf(range.value) + if (index < 0) return undefined + return { start: index, end: index + range.value.length, text: range.value } + } for (const attachment of attachments) { if (attachment.type === 'agent') { @@ -272,18 +299,45 @@ export function fileUrlToAbsolutePath(url: string): string | undefined { } } +/** + * 从消息 metadata 里读路径引用。 + * + * 这些附件不进 `files[]`(二进制 / 超 20MB / 拖入的本机文件),模型看到的是 + * prompt 文本里的 `Attached file:` 行;用户消息气泡靠这份数据还原胶囊。 + * 之前只有 revert 回填在读它,气泡完全没渲染。 + */ +export function readPromptAttachments(metadata: unknown): PromptAttachmentReference[] { + const record = metadata as Record | undefined + const raw = record?.['attachments'] + if (!Array.isArray(raw)) return [] + + const result: PromptAttachmentReference[] = [] + for (const item of raw) { + if (!item || typeof item !== 'object') continue + const { name, mime, path } = item as { name?: unknown; mime?: unknown; path?: unknown } + if (typeof path !== 'string' || !path) continue + result.push({ + name: typeof name === 'string' && name ? name : fileBaseName(path), + mime: typeof mime === 'string' && mime ? mime : 'text/plain', + path, + }) + } + return result +} + /** * 路径型附件:`file://` 引用。 * - * 带 mention 的附件(`@` 提及、拖入)路径已经在文本里,不再补一行引用 - * ——官方也是这么区分的(path 部件 vs file 部件)。 + * pathOnly 附件不会进 `prompt.files[]`,文本是模型看到它的唯一途径。 + * 官方对 path 部件**无条件**补一行绝对路径,即使正文里已经有 `@path` + *(`@` 是相对路径,模型不一定知道绝对位置)。 * - * 但 pathOnly 附件不会进 `prompt.files[]`,文本是模型看到它的唯一途径。 - * 如果用户把 `@path` 那段删掉了(chip 还在),这里必须补回去, - * 否则模型完全看不到这个附件。 + * 非 pathOnly 的附件走 `files[]`,路径已经随 attachment 交给服务端, + * 不再补行(官方 FileAttachmentPart 同款)。 */ export function isPathReferenceAttachment(attachment: Attachment, text?: string): boolean { - if (attachment.type !== 'file') return false + if (attachment.type !== 'file' && attachment.type !== 'folder') return false + if (attachment.pathOnly) return true if (attachment.textRange) { return text !== undefined && !text.includes(attachment.textRange.value) } @@ -390,7 +444,7 @@ function buildPromptInput( skills?: Array<{ id: string; mention?: { start: number; end: number; text: string } }> metadata?: Record } { - const { files, agents, skills } = buildPromptParts(params.attachments) + const { files, agents, skills } = buildPromptParts(params.attachments, params.text) // 路径型附件额外把绝对路径写进文本(官方 request.ts:173-182 同款): // files[].uri 只让服务端读到字节,模型能否看到取决于 mime(见文件顶部说明)。 const attachmentReferences = buildAttachmentReferences(params.attachments, params.text) diff --git a/src/api/queue.test.ts b/src/api/queue.test.ts index 625c04f4a..64468b87f 100644 --- a/src/api/queue.test.ts +++ b/src/api/queue.test.ts @@ -76,7 +76,7 @@ describe('rewriteQueueOrder(官方 queue.rewrite 同款:后缀重写保序 }) describe('buildEditedPromptInput(官方 editedPromptInput 同款)', () => { - it('保留原文件/agent/skill 提及(文本仍含 mention 时),合并新请求', () => { + it('保留仍被提及的文件(uri 原样保留),mention 被编辑删掉的丢弃', () => { const original = queuedItem('q1', '看下 @agent-x 和 @skill-y', { files: [ { @@ -92,9 +92,10 @@ describe('buildEditedPromptInput(官方 editedPromptInput 同款)', () => { metadata: { displayText: '看下 @agent-x 和 @skill-y' }, }) + const text = '再看下 @agent-x 和 @a.ts 就行' const result = buildEditedPromptInput({ sessionId: 'ses-1', - text: '再看下 @agent-x 就行', + text, attachments: [], original, delivery: 'queue', @@ -102,13 +103,26 @@ describe('buildEditedPromptInput(官方 editedPromptInput 同款)', () => { }) // agent-x 仍被提及 → 保留且区间重定位;skill-y 不再被提及 → 丢弃 - expect(result.agents).toEqual([{ name: 'agent-x', mention: { text: '@agent-x', start: 4, end: 12 } }]) + expect(result.agents).toEqual([ + { name: 'agent-x', mention: { text: '@agent-x', start: 4, end: 12 } }, + ]) expect(result.skills).toEqual([]) - // 文件全部保留(非 composer 附件),区间重定位;不存在则 undefined - expect(result.files?.[0].uri).toBe('data:text/plain;base64,QQ==') - expect(result.files?.[0].mention).toBeUndefined() - expect(result.metadata?.displayText).toBe('再看下 @agent-x 就行') + // 文件仍被提及:uri 原样保留(不能拼成 data URL),mention 区间重定位 + expect(result.files?.[0].uri).toBe('file:///repo/a.ts') + expect(result.files?.[0].mention).toEqual({ text: '@a.ts', start: 15, end: 20 }) + expect(result.metadata?.displayText).toBe(text) expect(result.resume).toBe(false) + + // 编辑把 mention 删掉 → 这条文件不再发送(官方 editedPromptInput 同款) + const dropped = buildEditedPromptInput({ + sessionId: 'ses-1', + text: '再看下 @agent-x 就行', + attachments: [], + original, + delivery: 'queue', + request: { files: [], agents: [], skills: [] }, + }) + expect(dropped.files).toEqual([]) }) it('model 可见文本后缀(notes)接回 text 尾部', () => { diff --git a/src/api/queue.ts b/src/api/queue.ts index fa27c1253..f6625baea 100644 --- a/src/api/queue.ts +++ b/src/api/queue.ts @@ -14,12 +14,10 @@ import { getSDKClient } from './sdk' import { resolveSessionTarget } from '../utils/sessionKey' import { cancelInboxItem } from './session' import { createMessageId } from '../utils/identifier' -import { fileBaseName } from '../utils/pathUtils' import { applyAttachmentReferences, buildAttachmentReferences, dedupeAttachmentReferences, - fileUrlToAbsolutePath, } from './message' import type { QueuedUserPrompt } from '../store/inboxStore' import type { Attachment } from './types' @@ -148,26 +146,24 @@ export function buildEditedPromptInput(params: { return { text: value.text, start, end: start + value.text.length } } - // 非 composer 附件(带 mention 或非 inline 的文件)全部保留 + // 非 composer 附件(mention / 上下文文件)保留;mention 被编辑删掉就丢弃 + //(官方 editedPromptInput 同款)。uri 型文件必须原样保留 uri——之前统一 + // 拼成 data URL,会把 @ 引用的 file:// 变成空 data,等于附件丢失。 + const requestFiles = params.request.files ?? [] const preservedFiles = (payload.files ?? []) - .filter(file => file.mention || file.source.type !== 'inline') + .filter(file => !!file.mention || file.source.type !== 'inline') + .filter(file => !file.mention || params.text.includes(file.mention.text)) .map(file => ({ - uri: `data:${file.mime};base64,${file.data}`, + uri: file.source.type === 'uri' ? file.source.uri : `data:${file.mime};base64,${file.data}`, name: file.name, description: file.description, mention: mention(file.mention), })) + .filter(file => !requestFiles.some(entry => entry.uri === file.uri)) - // 路径引用(Issue #182):原条目里 uri 型文件的路径 + 编辑器当前的路径型附件。 - // 两者都要重新注入文本——编辑确认会重写 text,旧的那一行可能在 notes 里, - // 也可能被新文本顶掉;applyAttachmentReferences 会按路径去重,不会重复。 - const preservedReferences = (payload.files ?? []).flatMap(file => { - if (file.source.type !== 'uri') return [] - const path = fileUrlToAbsolutePath(file.source.uri) ?? file.source.uri - return [{ name: file.name ?? fileBaseName(path), mime: file.mime, path }] - }) - // 旧的 composer 路径附件形态是「无 url、有 relativePath」(queue 回填的条目), - // 保留兼容;新的上传附件带 file:// url,由 buildAttachmentReferences 收集。 + // 路径引用(Issue #182):原条目的路径引用由 queuedPromptAttachments 回填到 + // 编辑器(无 url、有 relativePath),这里统一从编辑器附件收集;不再把 + // payload.files 里的普通 uri 文件误当成路径引用重复注入文本。 const composerReferences = [ ...params.attachments .filter(attachment => attachment.type === 'file' && !attachment.url && attachment.relativePath) @@ -178,7 +174,7 @@ export function buildEditedPromptInput(params: { })), ...buildAttachmentReferences(params.attachments), ] - const references = dedupeAttachmentReferences([...preservedReferences, ...composerReferences]) + const references = dedupeAttachmentReferences(composerReferences) const requestAgents = params.request.agents ?? [] const agents = [ diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index e5238cd83..eaebb79c1 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -30,6 +30,7 @@ import { detectSlashTrigger, ensureFileMime, getMimeFromPath, + isModelReadableMime, readFileAsDataUrl, routeAttachment, } from './input/inputUtils' @@ -81,6 +82,8 @@ interface DraggedFileInfo { path: string absolute: string name: string + /** 只写路径、不进 files[](二进制 / 超 20MB);缺省时按类型临时判断 */ + pathOnly?: boolean } const TEXTAREA_MIN_HEIGHT = 24 @@ -1058,10 +1061,11 @@ function InputBoxComponent({ return } case 'ArrowLeft': { - // 返回上一级 - if (mentionQuery.includes('/')) { + // 返回上一级(反斜杠路径先规范成 `/`) + const normalizedQuery = normalizePath(mentionQuery) + if (normalizedQuery.includes('/')) { e.preventDefault() - const parts = mentionQuery.replace(/\/$/, '').split('/') + const parts = normalizedQuery.replace(/\/$/, '').split('/') // 记住当前目录名,返回后定位到它 const folderName = parts[parts.length - 1] if (folderName) { @@ -1237,18 +1241,25 @@ function InputBoxComponent({ // 裸绝对路径 `E:/...` 会被解析成 `e:` 协议直接 400——侧边栏拖入走 toFileUrl 所以没事, // 这里对齐官方 request.ts:109 的 `file://${encodeFilePath(path)}`) const attachType = item.type === 'reference' ? 'folder' : item.type + // 类型决定发送形态:模型能直接读的(文本 / 图片 / PDF / 目录)进 files[]; + // 可执行文件、压缩包、二进制只给路径,服务端不读内容、也不会撞 20MB 上限。 + const mime = + attachType === 'folder' + ? 'application/x-directory' + : attachType === 'file' + ? getMimeFromPath(item.value) + : undefined + const pathOnly = attachType === 'file' && !isModelReadableMime(mime ?? '') const attachment: Attachment = { id: crypto.randomUUID(), type: attachType, displayName: item.displayName, relativePath: item.type === 'reference' ? item.value : item.relativePath, url: item.type !== 'agent' && item.type !== 'skill' ? toFileUrl(item.value) : undefined, - mime: item.type === 'reference' ? 'application/x-directory' : item.type !== 'agent' ? 'text/plain' : undefined, + mime, agentName: item.type === 'agent' ? item.displayName : undefined, skillId: item.type === 'skill' ? item.value : undefined, - // 物理路径引用只写路径(官方 composer 的 path 部件):`@path` 已在文本里, - // 进 prompt.files[] 只会让服务端把整份文件读进内存,还撞 20MB 上限。 - ...(attachType === 'file' || attachType === 'folder' ? { pathOnly: true } : {}), + ...(pathOnly ? { pathOnly: true } : {}), textRange: { value: mentionText, start: mentionStartIndex, @@ -1478,14 +1489,13 @@ function InputBoxComponent({ }, []) /** - * 将拖入的文件信息插入为 @mention 附件。 + * 将拖入的文件信息插入为 `@path` 芯片。 * - * `pathOnly`:只把路径写进 prompt 文本,不进 `prompt.files[]`。外部拖入的本机 - * 文件走这条(对齐官方 composer 的 `path` 部件):服务端不必把整份文件读进内存、 - * 也不会撞上 20MB 上限,模型按需用工具读。侧边栏内部拖拽仍传 files[]。 + * `pathOnly` 由每个文件自己决定(`DraggedFileInfo.pathOnly`):二进制 / + * 超 20MB 只写路径、不进 `files[]`;模型能直接读的类型进 `files[]`。 */ const insertDraggedFiles = useCallback( - (fileInfos: DraggedFileInfo[], options: { pathOnly?: boolean } = {}) => { + (fileInfos: DraggedFileInfo[]) => { if (fileInfos.length === 0) return const currentText = textareaRef.current?.value ?? text @@ -1516,8 +1526,8 @@ function InputBoxComponent({ displayName: fileInfo.name, relativePath, url: toFileUrl(fileInfo.absolute), - mime: fileInfo.type === 'file' ? 'text/plain' : undefined, - ...(options.pathOnly ? { pathOnly: true } : {}), + mime: fileInfo.type === 'file' ? getMimeFromPath(fileInfo.absolute) : 'application/x-directory', + ...(fileInfo.pathOnly ? { pathOnly: true } : {}), textRange: { value: mentionText, start, @@ -1539,7 +1549,15 @@ function InputBoxComponent({ [text], ) - const insertDraggedFile = useCallback((fileInfo: DraggedFileInfo) => insertDraggedFiles([fileInfo]), [insertDraggedFiles]) + const insertDraggedFile = useCallback( + (fileInfo: DraggedFileInfo) => { + const mime = fileInfo.type === 'file' ? getMimeFromPath(fileInfo.absolute) : 'application/x-directory' + insertDraggedFiles([ + { ...fileInfo, pathOnly: fileInfo.type === 'file' && !isModelReadableMime(mime) }, + ]) + }, + [insertDraggedFiles], + ) useEffect(() => { const updateInternalFileDragState = () => { @@ -1564,12 +1582,17 @@ function InputBoxComponent({ }, [insertDraggedFile]) const buildDraggedFileInfo = useCallback( - (fileInfo: DroppedPathInfo): DraggedFileInfo => ({ - type: fileInfo.type, - path: getMentionPathForDroppedPath(fileInfo.path, rootPath), - absolute: fileInfo.path, - name: fileInfo.name || getFileName(fileInfo.path), - }), + (fileInfo: DroppedPathInfo): DraggedFileInfo => { + const mime = fileInfo.type === 'file' ? getMimeFromPath(fileInfo.path) : 'application/x-directory' + return { + type: fileInfo.type, + path: getMentionPathForDroppedPath(fileInfo.path, rootPath), + absolute: fileInfo.path, + name: fileInfo.name || getFileName(fileInfo.path), + // 默认按类型判断;走判定链时调用方会用真实大小覆盖 + pathOnly: fileInfo.type === 'file' && !isModelReadableMime(mime), + } + }, [rootPath], ) @@ -1581,7 +1604,9 @@ function InputBoxComponent({ * data URL 内联;其余 → 上传到服务端临时目录后作路径附件(Issue #182)。 */ const createUploadAttachmentFromDroppedPath = useCallback( - async (fileInfo: DroppedPathInfo): Promise => { + async ( + fileInfo: DroppedPathInfo, + ): Promise => { if (fileInfo.type !== 'file') return null const name = fileInfo.name || getFileName(fileInfo.path) @@ -1646,8 +1671,8 @@ function InputBoxComponent({ if (size >= 0) { const route = await resolveRoute(size) - // 'mention' = 服务端读得到这个本机路径 → 交回调用方退化成 @ 引用(原行为) - if (route.kind === 'mention') return null + // 'mention' = 服务端读得到这个本机路径 → 交回调用方退化成 @ 引用 + if (route.kind === 'mention') return { mention: true, pathOnly: route.pathOnly } if (route.kind === 'reject') return rejectTooLarge() if (route.kind === 'inline') return inlineAttachment(await readFile(fileInfo.path), size) } @@ -1656,7 +1681,7 @@ function InputBoxComponent({ size = size >= 0 ? size : bytes.byteLength const route = await resolveRoute(size) - if (route.kind === 'mention') return null + if (route.kind === 'mention') return { mention: true, pathOnly: route.pathOnly } if (route.kind === 'reject') return rejectTooLarge() if (route.kind === 'inline') return inlineAttachment(bytes, size) @@ -1718,6 +1743,11 @@ function InputBoxComponent({ // (服务端在远端时那个本机路径读不到) continue } + if (result && 'mention' in result) { + // 服务端读得到本机路径:沿用 @ 引用;pathOnly 由类型 + 大小决定 + mentionFiles.push({ ...buildDraggedFileInfo(info), pathOnly: result.pathOnly }) + continue + } if (result) { uploadAttachments.push(result) } else if (info.type === "folder") { @@ -1747,10 +1777,8 @@ function InputBoxComponent({ setAttachments(prev => [...prev, ...uploadAttachments]) } - // 外部拖入的本机文件只作路径引用(官方 composer 的 `path` 部件): - // 路径已经在 prompt 文本里,再进 files[] 会让服务端把整份文件读进内存, - // 超过 20MB 还会让整条 prompt 以 AttachmentError 失败。 - insertDraggedFiles(mentionFiles, { pathOnly: true }) + // 每个文件的 pathOnly 已经由类型 + 大小算好,这里只负责插入芯片。 + insertDraggedFiles(mentionFiles) } catch (err) { console.warn('[InputBox] Failed to process dropped paths:', err) } diff --git a/src/features/chat/input/attachmentUpload.test.ts b/src/features/chat/input/attachmentUpload.test.ts index 6e5f66198..1bde09fe0 100644 --- a/src/features/chat/input/attachmentUpload.test.ts +++ b/src/features/chat/input/attachmentUpload.test.ts @@ -25,7 +25,7 @@ describe('decideNativeFileRoute', () => { ).toEqual({ kind: 'inline' }) }) - it('同机 + 白名单外(zip)→ 走原有的 @ 引用,不上传', () => { + it('同机 + 白名单外(zip)→ 走 @ 引用,但只给路径(二进制不进上下文)', () => { expect( decideNativeFileRoute({ mime: 'application/zip', @@ -34,10 +34,22 @@ describe('decideNativeFileRoute', () => { serverIsLocal: true, nativePath: 'C:/dl/piui-source.zip', }), - ).toEqual({ kind: 'mention' }) + ).toEqual({ kind: 'mention', pathOnly: true }) }) - it('同机 + 原生媒体但超过内联上限 → 也是 @ 引用(不上传)', () => { + it('同机 + 小文本文件 → @ 引用且进 files[](模型能直接读)', () => { + expect( + decideNativeFileRoute({ + mime: 'text/plain', + size: 1024, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/proj/notes.txt', + }), + ).toEqual({ kind: 'mention', pathOnly: false }) + }) + + it('同机 + 原生媒体但超过内联上限 → 只给路径(不进 files[])', () => { expect( decideNativeFileRoute({ mime: 'image/png', @@ -46,7 +58,7 @@ describe('decideNativeFileRoute', () => { serverIsLocal: true, nativePath: 'C:/pics/huge.png', }), - ).toEqual({ kind: 'mention' }) + ).toEqual({ kind: 'mention', pathOnly: true }) }) it('同机 + 超大文件也不拒绝(根本不上传,没有上限问题)', () => { @@ -58,10 +70,10 @@ describe('decideNativeFileRoute', () => { serverIsLocal: true, nativePath: 'C:/dl/huge.zip', }), - ).toEqual({ kind: 'mention' }) + ).toEqual({ kind: 'mention', pathOnly: true }) }) - it('远端 + 白名单外 → 上传', () => { + it('远端 + 白名单外 → 上传,但只作路径引用', () => { expect( decideNativeFileRoute({ mime: 'application/zip', @@ -70,7 +82,7 @@ describe('decideNativeFileRoute', () => { serverIsLocal: false, nativePath: 'C:/dl/piui-source.zip', }), - ).toEqual({ kind: 'upload', pathOnly: false }) + ).toEqual({ kind: 'upload', pathOnly: true }) }) it('远端 + 超过 20MB → 上传但只作路径引用', () => { diff --git a/src/features/chat/input/attachmentUpload.ts b/src/features/chat/input/attachmentUpload.ts index bbf57aa8c..de753b56d 100644 --- a/src/features/chat/input/attachmentUpload.ts +++ b/src/features/chat/input/attachmentUpload.ts @@ -87,8 +87,11 @@ export function buildPathAttachment(input: { export type NativeFileDecision = /** 原生媒体:读本机字节内联成 data URL(浏览器/桌面都走这条) */ | { kind: 'inline' } - /** 服务端同机:交给原有的 `@` 引用,**不上传**(需求二) */ - | { kind: 'mention' } + /** + * 服务端同机:交给原有的 `@` 引用,**不上传**(需求二)。 + * `pathOnly` 为 true 时只给路径(二进制 / 超 20MB),不进 `files[]`。 + */ + | { kind: 'mention'; pathOnly: boolean } /** 服务端在远端:必须上传 */ | { kind: 'upload'; pathOnly: boolean } /** 超过上传上限 */ @@ -114,7 +117,7 @@ export function decideNativeFileRoute(input: { case 'inline': return { kind: 'inline' } case 'reference': - return { kind: 'mention' } + return { kind: 'mention', pathOnly: route.pathOnly } case 'reject': return { kind: 'reject' } default: diff --git a/src/features/chat/input/inputUtils.attachmentRouting.test.ts b/src/features/chat/input/inputUtils.attachmentRouting.test.ts index d457fe8f3..4d4d388ce 100644 --- a/src/features/chat/input/inputUtils.attachmentRouting.test.ts +++ b/src/features/chat/input/inputUtils.attachmentRouting.test.ts @@ -23,9 +23,15 @@ describe('routeAttachment', () => { ) }) - it('白名单外(zip 等)→ 上传,且不是 pathOnly', () => { + it('白名单外(zip 等)→ 上传,且只作路径引用(二进制不进上下文)', () => { expect( routeAttachment({ mime: 'application/zip', size: 1024, caps: allCaps, serverIsLocal: false }), + ).toEqual({ kind: 'upload', pathOnly: true }) + }) + + it('文本小文件 → 上传,可以进 files[](模型能直接读)', () => { + expect( + routeAttachment({ mime: 'text/plain', size: 1024, caps: allCaps, serverIsLocal: false }), ).toEqual({ kind: 'upload', pathOnly: false }) }) @@ -49,7 +55,7 @@ describe('routeAttachment', () => { ).toEqual({ kind: 'reject', reason: 'too-large' }) }) - it('服务端同机 + 有原生路径 → 直引(需求二),超限时同样只作路径引用', () => { + it('服务端同机 + 有原生路径 → 直引(需求二);二进制或超限只作路径引用', () => { expect( routeAttachment({ mime: 'application/zip', @@ -58,7 +64,17 @@ describe('routeAttachment', () => { serverIsLocal: true, nativePath: 'C:/data/report.zip', }), - ).toEqual({ kind: 'reference', path: 'C:/data/report.zip', pathOnly: false }) + ).toEqual({ kind: 'reference', path: 'C:/data/report.zip', pathOnly: true }) + + expect( + routeAttachment({ + mime: 'text/plain', + size: 1024, + caps: allCaps, + serverIsLocal: true, + nativePath: 'C:/data/notes.txt', + }), + ).toEqual({ kind: 'reference', path: 'C:/data/notes.txt', pathOnly: false }) expect( routeAttachment({ @@ -80,6 +96,6 @@ describe('routeAttachment', () => { serverIsLocal: false, nativePath: 'C:/data/report.zip', }), - ).toEqual({ kind: 'upload', pathOnly: false }) + ).toEqual({ kind: 'upload', pathOnly: true }) }) }) diff --git a/src/features/chat/input/inputUtils.ts b/src/features/chat/input/inputUtils.ts index 3ead28d7c..7a934ac21 100644 --- a/src/features/chat/input/inputUtils.ts +++ b/src/features/chat/input/inputUtils.ts @@ -68,6 +68,29 @@ export function getMimeFromPath(path: string): string { return extToMime(ext) } +/** + * 模型能直接消费的 mime。 + * + * 服务端 `to-llm-message` 只把 `text/plain`、图片、PDF、目录转进上下文, + * 其余(可执行文件、压缩包、二进制)整段丢弃。这类文件进 `files[]` + * 既占内存又可能撞服务端 20MB 读取上限,不如直接走路径引用。 + * + * 注意:服务端对 `file://` 文件会按内容 `Mime.detect`,所以源码/配置等 + * 文本类型最终都会变成 `text/plain`。客户端按扩展名先把它们划进可读, + * 二进制类直接排除。 + */ +export function isModelReadableMime(mime: string): boolean { + if (!mime) return false + if (mime.startsWith('text/')) return true + if (mime.startsWith('image/')) return true + if (mime === 'application/pdf') return true + if (mime === 'application/x-directory') return true + // 结构化文本:服务端嗅探后就是 text/plain + if (mime === 'application/json') return true + if (mime === 'application/xml' || mime === 'application/xhtml+xml') return true + return false +} + export function bytesToDataUrl(bytes: Uint8Array, mime: string): string { const chunkSize = 0x8000 let binary = '' @@ -149,13 +172,17 @@ export function routeAttachment(input: { return { kind: 'inline' } } + // 模型读不了的类型(可执行文件、压缩包、二进制)或超过服务端读取上限: + // 只给路径,不进 files[]。文件引用本来就没必要把整份内容塞进上下文。 + const pathOnly = !isModelReadableMime(input.mime) || input.size > MAX_INLINE_BYTES + if (input.nativePath && input.serverIsLocal) { - return { kind: 'reference', path: input.nativePath, pathOnly: input.size > MAX_INLINE_BYTES } + return { kind: 'reference', path: input.nativePath, pathOnly } } if (input.size > MAX_UPLOAD_BYTES) { return { kind: 'reject', reason: 'too-large' } } - return { kind: 'upload', pathOnly: input.size > MAX_INLINE_BYTES } + return { kind: 'upload', pathOnly } } diff --git a/src/features/chat/sidebar/MultiServerFolderList.tsx b/src/features/chat/sidebar/MultiServerFolderList.tsx index 526e42278..39afd1db6 100644 --- a/src/features/chat/sidebar/MultiServerFolderList.tsx +++ b/src/features/chat/sidebar/MultiServerFolderList.tsx @@ -17,7 +17,7 @@ import { useServerStore } from '../../../hooks/useServerStore' import { serverStore } from '../../../store/serverStore' import { multiServerStore } from '../../../store/multiServerStore' import { reorderSubscribedServers } from './serverOrdering' -import { subscribeToServerConnectionState, getServerConnectionInfo, type ConnectionInfo } from '../../../api/events' +import { healthToConnectionDisplay, type ConnectionDisplayState } from '../../../utils/connectionDisplay' import { ExpandableSection } from '../../../components/ui' import { GripVerticalIcon } from '../../../components/Icons' import { subscribePerServerStorageVersion, getStorageVersion } from '../../../utils/perServerStorage' @@ -53,17 +53,7 @@ interface MultiServerFolderListProps { onSelectChildSession?: (session: ApiSession) => void } -function useServerConnectionState(serverId: string): ConnectionInfo { - const subscribe = useCallback( - (onStoreChange: () => void) => - serverId ? subscribeToServerConnectionState(serverId, onStoreChange) : () => {}, - [serverId], - ) - const getSnapshot = useCallback(() => getServerConnectionInfo(serverId), [serverId]) - return useSyncExternalStore(subscribe, getSnapshot, getSnapshot) -} - -function statusDotClass(state: ConnectionInfo['state']): string { +function statusDotClass(state: ConnectionDisplayState): string { switch (state) { case 'connected': return 'bg-success-100' @@ -118,7 +108,7 @@ const ServerFolderGroup = memo(function ServerFolderGroup({ const { getHealth } = useServerStore() const server = serverStore.getServer(serverId) const health = getHealth(serverId) - const connectionState = useServerConnectionState(serverId) + const displayState = healthToConnectionDisplay(health) const [expandedProjectIds, setExpandedProjectIds] = useState([]) // 该服务器的工作区 = 该服务器 per-server storage 的 saved-directories(与单服务器模式同一套存储) @@ -209,10 +199,10 @@ const ServerFolderGroup = memo(function ServerFolderGroup({ > {/* size-5 图标位 → 连接状态点 */} - - {connectionState.state === 'connected' && ( + + {displayState === 'connected' && ( )} diff --git a/src/features/chat/sidebar/SearchResults.tsx b/src/features/chat/sidebar/SearchResults.tsx index 9902c69c5..d1c98574f 100644 --- a/src/features/chat/sidebar/SearchResults.tsx +++ b/src/features/chat/sidebar/SearchResults.tsx @@ -9,7 +9,7 @@ // 文件夹模式和多服务器模式共用侧栏提供的服务器范围。 // ============================================ -import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { useTranslation } from 'react-i18next' import { getSessions, type ApiSession } from '../../../api' import { makeSessionKey } from '../../../utils/sessionKey' @@ -19,11 +19,11 @@ import { multiServerStore } from '../../../store/multiServerStore' import { useDirectory } from '../../../contexts/useDirectory' import { readServerWorkspaces } from '../../../utils/serverWorkspaces' import { getStorageVersion, subscribePerServerStorageVersion } from '../../../utils/perServerStorage' -import { subscribeToServerConnectionState, getServerConnectionInfo, type ConnectionInfo } from '../../../api/events' +import { healthToConnectionDisplay, type ConnectionDisplayState } from '../../../utils/connectionDisplay' import { ChevronDownIcon, FolderIcon, MessageSquareIcon } from '../../../components/Icons' import { useServerStore } from '../../../hooks/useServerStore' -function statusDotClass(state: ConnectionInfo['state']): string { +function statusDotClass(state: ConnectionDisplayState): string { switch (state) { case 'connected': return 'bg-success-100' @@ -45,16 +45,6 @@ function splitTerms(search: string): string[] { .filter(Boolean) } -function useServerConnectionState(serverId: string): ConnectionInfo { - const subscribe = useCallback( - (onStoreChange: () => void) => - serverId ? subscribeToServerConnectionState(serverId, onStoreChange) : () => {}, - [serverId], - ) - const getSnapshot = useCallback(() => getServerConnectionInfo(serverId), [serverId]) - return useSyncExternalStore(subscribe, getSnapshot, getSnapshot) -} - interface ServerSearchGroupProps { serverId: string search: string @@ -76,7 +66,7 @@ function ServerSearchGroup({ const server = serverStore.getServer(serverId) const { getHealth } = useServerStore() const health = getHealth(serverId) - const connectionState = useServerConnectionState(serverId) + const displayState = healthToConnectionDisplay(health) const [expanded, setExpanded] = useState(true) // 工作区列表(本地;storage 写入时刷新) @@ -230,7 +220,7 @@ function ServerSearchGroup({ title={server?.url ?? serverId} > - + {displayName} diff --git a/src/features/chat/sidebar/SidePanel.tsx b/src/features/chat/sidebar/SidePanel.tsx index 631f7d9a0..e03d8cb41 100644 --- a/src/features/chat/sidebar/SidePanel.tsx +++ b/src/features/chat/sidebar/SidePanel.tsx @@ -8,6 +8,7 @@ import { SessionShellsSlot } from './SessionShellsSlot' import { shellInventoryStore, useShellActiveSessionIds } from '../../../store/shellInventoryStore' import { multiServerStore } from '../../../store/multiServerStore' import { useSidebarServerScope } from './useSidebarServerScope' +import { useServerStore } from '../../../hooks/useServerStore' import { getProjectGroupIdentity } from './projectGrouping' import { ConfirmDialog } from '../../../components/ui/ConfirmDialog' import { ActiveSessionItem } from './ActiveSessionItem' @@ -45,11 +46,10 @@ import { updateSession, deleteSession as apiDeleteSession, getSession, - subscribeToConnectionState, type ApiSession, - type ConnectionInfo, } from '../../../api' import { getDirectoryName, isSameDirectory, normalizeToForwardSlash } from '../../../utils' +import { healthToConnectionDisplay } from '../../../utils/connectionDisplay' import { createSessionPlaceholder } from '../../../utils/sessionPlaceholder' import { makeSessionKey, splitSessionKey } from '../../../utils/sessionKey' import { uiErrorHandler } from '../../../utils' @@ -123,6 +123,7 @@ export function SidePanel({ } = useDirectory() const { multiServerConfig, activeServer, serverIds } = useSidebarServerScope() // 多服务器模式:Git/路径信息跟随「焦点服务器」(焦点缺省 = 活动服务器) + const { getHealth } = useServerStore() const catalogServerId = multiServerConfig.enabled ? (multiServerConfig.focusedServerId ?? activeServer?.id) : undefined @@ -148,7 +149,6 @@ export function SidePanel({ () => (currentDirectory ? normalizeToForwardSlash(currentDirectory) : undefined), [currentDirectory], ) - const [connectionState, setConnectionState] = useState(null) const [projectDeleteConfirm, setProjectDeleteConfirm] = useState<{ isOpen: boolean; projectId: string | null }>({ isOpen: false, projectId: null, @@ -303,9 +303,20 @@ export function SidePanel({ const notifications = useNotifications() const unreadNotificationCount = useUnreadNotificationCount() + // 状态点与设置页同源:直接读目标服务器的健康状态(/api/info),不看 SSE。 + // 目标服务器优先取焦点会话所属服务器——切到别的服务器的会话时也能对上, + // 不会再去盯 active server 那条不相关的连接。 + const footerServerId = selectedSessionId + ? splitSessionKey(selectedSessionId).serverId + : serverStore.getActiveServerId() + const footerHealth = getHealth(footerServerId) + const connectionDisplay = healthToConnectionDisplay(footerHealth) + + // 第一次进入时健康状态可能还没查过:补一次,避免一直停在过渡态 useEffect(() => { - return subscribeToConnectionState(setConnectionState) - }, []) + if (footerHealth) return + void serverStore.checkHealth(footerServerId).catch(() => {}) + }, [footerHealth, footerServerId]) const { sessions, isLoading, isLoadingMore, hasMore, search, setSearch, loadMore, deleteSession, refresh } = useSessionContext() @@ -1635,7 +1646,7 @@ export function SidePanel({ {/* ===== Footer ===== */} diff --git a/src/features/mention/MentionMenu.test.tsx b/src/features/mention/MentionMenu.test.tsx index 88ef85ba7..7a1e783ae 100644 --- a/src/features/mention/MentionMenu.test.tsx +++ b/src/features/mention/MentionMenu.test.tsx @@ -165,4 +165,26 @@ describe('MentionMenu', () => { fireEvent.click(screen.getByTitle('Go back')) expect(onNavigate).toHaveBeenCalledWith('src/') }) + + it('反斜杠路径先规范成 `/` 再解析(Windows 手输/粘贴)', async () => { + render( +
+ +
, + ) + + await act(async () => { + vi.advanceTimersByTime(32) + await Promise.resolve() + }) + + expect(listDirectory).toHaveBeenCalledWith('src/components', '/workspace/project') + }) }) diff --git a/src/features/mention/MentionMenu.tsx b/src/features/mention/MentionMenu.tsx index 4f2de6556..f427193a8 100644 --- a/src/features/mention/MentionMenu.tsx +++ b/src/features/mention/MentionMenu.tsx @@ -94,8 +94,9 @@ export const MentionMenu = forwardRef(funct }, [isOpen, rootPath]) const [dynamicMaxHeight, setDynamicMaxHeight] = useState(undefined) const currentPath = useMemo(() => { - const lastSlashIndex = query.lastIndexOf('/') - return lastSlashIndex >= 0 ? query.slice(0, lastSlashIndex) || '.' : '.' + const normalizedQuery = normalizePath(query) + const lastSlashIndex = normalizedQuery.lastIndexOf('/') + return lastSlashIndex >= 0 ? normalizedQuery.slice(0, lastSlashIndex) || '.' : '.' }, [query]) // 动态计算菜单最大高度,防止在小屏幕上被 header 遮挡 @@ -298,16 +299,18 @@ export const MentionMenu = forwardRef(funct if (!isOpen) return const frameId = requestAnimationFrame(() => { - const lastSlashIndex = query.lastIndexOf('/') + // 反斜杠路径(Windows 直接粘贴/手输 `E:\dir\file`)先规范成 `/` 再解析 + const normalizedQuery = normalizePath(query) + const lastSlashIndex = normalizedQuery.lastIndexOf('/') if (lastSlashIndex >= 0) { - const dirPath = query.slice(0, lastSlashIndex) || '.' - const filter = query.slice(lastSlashIndex + 1) + const dirPath = normalizedQuery.slice(0, lastSlashIndex) || '.' + const filter = normalizedQuery.slice(lastSlashIndex + 1) loadDirectory(dirPath, filter) return } - if (query === '') { + if (normalizedQuery === '') { loadDirectory('.', '') return } @@ -315,7 +318,7 @@ export const MentionMenu = forwardRef(funct const requestId = ++requestIdRef.current setLoading(true) - searchFiles(query, { limit: 20, directory: rootPath }) + searchFiles(normalizedQuery, { limit: 20, directory: rootPath }) .then(paths => { if (requestId !== requestIdRef.current) return diff --git a/src/features/message/MessageRenderer.test.tsx b/src/features/message/MessageRenderer.test.tsx index d5a78b9a7..81e897951 100644 --- a/src/features/message/MessageRenderer.test.tsx +++ b/src/features/message/MessageRenderer.test.tsx @@ -75,6 +75,9 @@ vi.mock('./parts', () => ({ ), AgentPartView: ({ agent }: { agent: { name: string } }) =>
{agent.name}
, SkillPartView: ({ skill }: { skill: { name: string } }) =>
{skill.name}
, + PathReferencePartView: ({ reference }: { reference: { name: string } }) => ( +
{reference.name}
+ ), StepFinishPartView: () => null, RetryPartView: () => null, CompactionPartView: ({ message }: { message: { status?: string } }) => @@ -175,6 +178,19 @@ describe('MessageRenderer assistant fork', () => { expect(screen.getByTestId('file-part')).toHaveTextContent('notes.txt') }) + it('renders path references from metadata.attachments (dropped local files)', () => { + const message: UserMessage = { + ...createUserTextMessage('@E:/Downloads/tool.exe 看下'), + metadata: { + attachments: [{ name: 'tool.exe', mime: 'application/x-msdownload', path: 'E:/Downloads/tool.exe' }], + } as never, + } + + render() + + expect(screen.getByTestId('path-part')).toHaveTextContent('tool.exe') + }) + it('renders agent mentions from the native agents array', () => { const message: UserMessage = { ...createUserTextMessage('ping agent'), agents: [{ name: 'explore' }] } diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index 8b1d165f0..64893fc48 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -22,6 +22,7 @@ import { FilePartView, AgentPartView, SkillPartView, + PathReferencePartView, StepFinishPartView, RetryPartView, CompactionPartView, @@ -38,6 +39,7 @@ import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from './ import { MSG_SPACING } from './messageSpacing' import { MessageExpandPanel, useMessageExpandRender } from './messageExpand' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' +import { readPromptAttachments } from '../../api/message' import type { JsonValue } from '@opencode/client/promise' import { contentEntries, hasVisibleText, idleMessageError, userMessageText, type ContentEntry } from '../../types/api/message' import { currentToolFailed } from '../../types/api/toolState' @@ -572,6 +574,9 @@ const UserMessageView = memo(function UserMessageView({ const files = message.files ?? [] const agents = message.agents ?? [] const skills = message.skills ?? [] + // 路径引用(二进制 / 超 20MB / 拖入的本机文件)不在 files[] 里,只存在 + // metadata.attachments。不渲染的话就是「输入框有胶囊、发出去没了」。 + const pathReferences = useMemo(() => readPromptAttachments(message.metadata), [message.metadata]) const hasUserHtmlArtifact = renderUserMarkdown && USER_HTML_ARTIFACT_PATTERN.test(messageText) return ( @@ -592,11 +597,14 @@ const UserMessageView = memo(function UserMessageView({ )} {/* 用户附件 */} - {(files.length > 0 || agents.length > 0 || skills.length > 0) && ( + {(files.length > 0 || agents.length > 0 || skills.length > 0 || pathReferences.length > 0) && (
{files.map((file, index) => ( ))} + {pathReferences.map((reference, index) => ( + + ))} {agents.map((agent, index) => ( ))} diff --git a/src/features/message/parts/AttachmentPartViews.tsx b/src/features/message/parts/AttachmentPartViews.tsx index 725e8c48a..8234d60b0 100644 --- a/src/features/message/parts/AttachmentPartViews.tsx +++ b/src/features/message/parts/AttachmentPartViews.tsx @@ -1,5 +1,7 @@ -import { memo } from 'react' +import { memo, useMemo } from 'react' import { AttachmentItem } from '../../attachment' +import { absolutePathToFileUrl } from '../../../utils/pathUtils' +import { fileUrlToAbsolutePath, type PromptAttachmentReference } from '../../../api/message' import type { PromptAgentAttachment, PromptFileAttachment, PromptSkillAttachment } from '../../../types/api/message' // ============================================ // v2 用户消息附件 → 统一 Attachment @@ -10,21 +12,60 @@ import type { PromptAgentAttachment, PromptFileAttachment, PromptSkillAttachment // 不经过任何 part 形状。 // ============================================ -/** `PromptFileAttachment.source` → 可用的 url(inline 走 data:) */ +/** `PromptFileAttachment.source` → 可用的 url(图片优先用读回的字节) */ function attachmentUrl(file: PromptFileAttachment): string { + // Tauri webview 默认不允许直接加载 file:// 资源,图片预览会 onError。 + // 服务端已经把字节读回来了(data 是 base64),直接用 data URL。 + if (file.mime.startsWith('image/') && file.data) { + return `data:${file.mime};base64,${file.data}` + } if (file.source?.type === 'uri') return file.source.uri - return `data:${file.mime};base64,${file.data}` + return file.data ? `data:${file.mime};base64,${file.data}` : '' +} + +/** + * 服务端读回来的文本内容。 + * + * `files[]` 里的文本附件带着 base64 `data`,之前完全没用上——胶囊展开只能 + * 看到「引用路径 / 类型」,看着像被降级成了路径引用。这里解码给 + * `AttachmentItem`,展开就能预览正文(组件内部会截断到 5000 字)。 + */ +function fileTextContent(file: PromptFileAttachment): string | undefined { + if (!file.data || !file.mime?.startsWith('text/')) return undefined + try { + const binary = atob(file.data) + const bytes = Uint8Array.from(binary, char => char.charCodeAt(0)) + return new TextDecoder().decode(bytes) + } catch { + return undefined + } } function fileDisplayName(file: PromptFileAttachment): string { if (file.name) return file.name if (file.source?.type === 'uri') { - const segments = file.source.uri.split(/[?#]/)[0].split('/').filter(Boolean) + // source.uri 是 percent-encoding 过的,先解码再取文件名 + const decoded = fileUrlToAbsolutePath(file.source.uri) ?? safeDecodeUri(file.source.uri) + const segments = decoded.split(/[?#]/)[0].split(/[/\\]/).filter(Boolean) if (segments.length > 0) return segments[segments.length - 1] } return file.mime || 'attachment' } +function safeDecodeUri(uri: string): string { + try { + return decodeURIComponent(uri) + } catch { + return uri + } +} + +/** 文件来源路径(解码后的绝对路径,用于展示) */ +function fileSourcePath(file: PromptFileAttachment): string | undefined { + if (file.source?.type !== 'uri') return file.name + return fileUrlToAbsolutePath(file.source.uri) ?? safeDecodeUri(file.source.uri) +} + /** 文件提及在正文里的位置(用于高亮/回溯),v2 的 mention 就是 {start,end,text} */ function mentionRange(mention: { start: number; end: number; text: string } | undefined) { if (!mention) return undefined @@ -42,6 +83,7 @@ interface FilePartViewProps { } export const FilePartView = memo(function FilePartView({ file, index }: FilePartViewProps) { + const content = useMemo(() => fileTextContent(file), [file]) return ( + ) +}) + // ============================================ // Agent Attachment View // ============================================ diff --git a/src/features/message/parts/index.ts b/src/features/message/parts/index.ts index 0bfc9247b..4deb265bb 100644 --- a/src/features/message/parts/index.ts +++ b/src/features/message/parts/index.ts @@ -1,7 +1,7 @@ export { TextPartView } from './TextPartView' export { ReasoningPartView } from './ReasoningPartView' export { ToolPartView } from './ToolPartView' -export { FilePartView, AgentPartView, SkillPartView } from './AttachmentPartViews' +export { FilePartView, AgentPartView, SkillPartView, PathReferencePartView } from './AttachmentPartViews' export { StepFinishPartView } from './StepFinishPartView' export type { StepFinishInfo } from './StepFinishPartView' export { RetryPartView, CompactionPartView } from './SystemPartViews' diff --git a/src/features/slash-command/SlashCommandMenu.tsx b/src/features/slash-command/SlashCommandMenu.tsx index 640f7a58e..1e57aad21 100644 --- a/src/features/slash-command/SlashCommandMenu.tsx +++ b/src/features/slash-command/SlashCommandMenu.tsx @@ -6,6 +6,7 @@ import { useState, useEffect, useLayoutEffect, useRef, useImperativeHandle, forwardRef, useMemo } from 'react' import { useTranslation } from 'react-i18next' import { getCommands, type Command } from '../../api/command' +import { fuzzyScore } from '../../utils/fuzzyMatch' import { apiErrorHandler } from '../../utils' import { scrollItemIntoView } from '../../utils/scrollUtils' @@ -49,10 +50,14 @@ export const SlashCommandMenu = forwardRef { if (!isOpen) return [] - const lowerQuery = query.toLowerCase() - return commands.filter( - cmd => cmd.name.toLowerCase().includes(lowerQuery) || cmd.description?.toLowerCase().includes(lowerQuery), - ) + // 打分式模糊匹配:名字命中(全等>前缀>词边界>子串>缩写)永远压过描述命中, + // 按相关度排序,避免「描述里碰巧有这个词的 skill」把正主挤到后面 + if (!query.trim()) return commands + return commands + .map(cmd => ({ cmd, score: fuzzyScore(query, cmd.name, cmd.description) })) + .filter(({ score }) => score > 0) + .sort((a, b) => b.score - a.score) + .map(({ cmd }) => cmd) }, [commands, isOpen, query]) const commandColumnWidth = useMemo(() => { const maxCommandLength = commands.reduce((max, cmd) => Math.max(max, cmd.name.length + 1), 0) diff --git a/src/hooks/useChatSession.ts b/src/hooks/useChatSession.ts index d19b0a4e6..c0ae6f52a 100644 --- a/src/hooks/useChatSession.ts +++ b/src/hooks/useChatSession.ts @@ -1083,7 +1083,7 @@ export function useChatSession({ attachments, original, delivery: original.delivery, - request: buildPromptParts(attachments), + request: buildPromptParts(attachments, content), }) await confirmQueueEdit({ sessionId: routeSessionId, diff --git a/src/index.css b/src/index.css index 799ed04e6..efe424945 100644 --- a/src/index.css +++ b/src/index.css @@ -163,6 +163,15 @@ body, top: calc(var(--desktop-titlebar-height, 0px) + var(--app-safe-top, 0px) + var(--safe-area-inset-top, 0px)); } +/* 同样的原因:全屏查看器(ModalShell)也 portal 到 body。 + * `--app-safe-top` 只在 `.tauri-app` 下有值,浏览器/PWA 下是 0, + * 内容区会从视口顶部开始 —— 标题栏被 iOS 状态栏盖住。 + * 非 Tauri 场景显式让开 safe-area,Tauri 仍走 --app-safe-top / 原生 padding。 */ +:root:not(.tauri-app) .modal-shell-safe-content { + height: calc(100% - var(--safe-area-inset-top, 0px)); + margin-top: var(--safe-area-inset-top, 0px); +} + .settings-search-highlight { border-radius: 0.5rem; animation: settings-search-highlight 1.8s ease-out; diff --git a/src/store/serverStore.test.ts b/src/store/serverStore.test.ts index 948002650..d61e482e8 100644 --- a/src/store/serverStore.test.ts +++ b/src/store/serverStore.test.ts @@ -745,6 +745,37 @@ describe('serverStore SSE 连接与健康状态收敛', () => { expect(serverStore.getHealth('local')?.status).toBe('online') }) + it('SSE 连着时,失败的探测不能把状态降级成灰色', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockRejectedValue(new TypeError('fetch failed')), + ) + const { serverStore } = await import('./serverStore') + + // 对话正常(SSE 连着),但 HTTP 探测瞬时失败 / 走了旧地址 + serverStore.noteServerConnected('local') + expect(serverStore.getHealth('local')?.status).toBe('online') + + const health = await serverStore.checkHealth('local') + expect(health.status).toBe('offline') + // 状态点仍以「服务器实际可用」为准 + expect(serverStore.getHealth('local')?.status).toBe('online') + }) + + it('SSE 断开后才允许健康探测把状态判为离线', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockRejectedValue(new TypeError('fetch failed')), + ) + const { serverStore } = await import('./serverStore') + + serverStore.noteServerConnected('local') + serverStore.noteServerDisconnected('local') + await serverStore.checkHealth('local') + + expect(serverStore.getHealth('local')?.status).toBe('offline') + }) + it('已经在线时不再重复通知订阅方', async () => { vi.stubGlobal( 'fetch', diff --git a/src/store/serverStore.ts b/src/store/serverStore.ts index 985b2e9da..78eb015ae 100644 --- a/src/store/serverStore.ts +++ b/src/store/serverStore.ts @@ -347,6 +347,8 @@ class ServerStore { private activeServerId: string | null = null private healthMap = new Map() private healthCheckSeqMap = new Map() + /** 当前 SSE 已连上的服务器:连上期间不允许健康探测把状态降级(见 commitHealth) */ + private sseConnected = new Set() private clockCalibrationMap = new Map() /** 上次用服务端事件时间戳校准的本地单调时刻(calibrateFromServerTimestamp 节流用) */ private lastClockCalibrationAt = new Map() @@ -1113,6 +1115,7 @@ class ServerStore { * 只升不降:SSE 瞬断(休眠/切网)不立刻判死,交给断连后的健康轮询。 */ noteServerConnected(serverId: string): void { + this.sseConnected.add(serverId) const previous = this.healthMap.get(serverId) if (previous?.status === 'online') return this.healthMap.set(serverId, { @@ -1124,6 +1127,11 @@ class ServerStore { this.notify() } + /** SSE 断开:解除「连上期间不降级」的保护,交给健康轮询判定 */ + noteServerDisconnected(serverId: string): void { + this.sseConnected.delete(serverId) + } + /** * 检查服务器健康状态 * @@ -1151,11 +1159,22 @@ class ServerStore { const commitHealth = (health: ServerHealth) => { if (this.healthCheckSeqMap.get(serverId) === checkSeq) { + // SSE 正常连着 = 服务端现在确实可达,比一次 HTTP 探测更权威。 + // 移动端/代理环境下探测可能瞬时失败或还在用旧地址,不能因此把 + // 状态点打灰(用户看到的是「消息正常在流、状态点却是灰的」)。 + const effective: ServerHealth = + this.sseConnected.has(serverId) && health.status !== 'online' + ? { + status: 'online', + lastCheck: health.lastCheck, + ...(health.latency !== undefined ? { latency: health.latency } : {}), + } + : health const previous = this.healthMap.get(serverId) - this.healthMap.set(serverId, health) + this.healthMap.set(serverId, effective) // 静默体检只有「状态/版本/错误」变了才值得通知;延迟数字的变化 // 下次真实通知时自然带出去 - if (!options.silent || !sameHealth(previous, health)) this.notify() + if (!options.silent || !sameHealth(previous, effective)) this.notify() } return health } diff --git a/src/utils/connectionDisplay.test.ts b/src/utils/connectionDisplay.test.ts new file mode 100644 index 000000000..a24602627 --- /dev/null +++ b/src/utils/connectionDisplay.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { healthToConnectionDisplay } from './connectionDisplay' +import type { ServerHealth } from '../store/serverStore' + +function health(status: ServerHealth['status']): ServerHealth { + return { status } +} + +describe('healthToConnectionDisplay', () => { + it('在线 → 绿色', () => { + expect(healthToConnectionDisplay(health('online'))).toBe('connected') + }) + + it('检查中 → 过渡态', () => { + expect(healthToConnectionDisplay(health('checking'))).toBe('connecting') + }) + + it('离线 → 灰色', () => { + expect(healthToConnectionDisplay(health('offline'))).toBe('disconnected') + }) + + it('凭据错误 / 探测错误 → 红色', () => { + expect(healthToConnectionDisplay(health('unauthorized'))).toBe('error') + expect(healthToConnectionDisplay(health('error'))).toBe('error') + }) + + it('还没查过 → 过渡态(随后会发起检查)', () => { + expect(healthToConnectionDisplay(undefined)).toBe('connecting') + expect(healthToConnectionDisplay(null)).toBe('connecting') + }) +}) diff --git a/src/utils/connectionDisplay.ts b/src/utils/connectionDisplay.ts new file mode 100644 index 000000000..eebfe75d9 --- /dev/null +++ b/src/utils/connectionDisplay.ts @@ -0,0 +1,31 @@ +// ============================================ +// 侧边栏连接状态点的显示口径 +// +// 状态点表达「服务器是否可用」,直接复用设置页的服务器健康状态 +// (serverStore.healthMap,来自 GET /api/info),不再看 SSE 长连接状态。 +// +// 原因:移动端切后台、Wi-Fi ↔ 蜂窝切换、系统省电都会让长连接比 HTTP +// 断得频繁,但服务端通常是好的。之前会出现「消息正常在流、状态点却是灰的」, +// 而且 footer 只盯 active server,切到别的服务器的会话时会盯错对象。 +// ============================================ + +import type { ServerHealth } from '../store/serverStore' + +export type ConnectionDisplayState = 'connected' | 'connecting' | 'disconnected' | 'error' + +export function healthToConnectionDisplay(health: ServerHealth | null | undefined): ConnectionDisplayState { + switch (health?.status) { + case 'online': + return 'connected' + case 'checking': + return 'connecting' + case 'unauthorized': + case 'error': + return 'error' + case 'offline': + return 'disconnected' + default: + // 还没查过:先按过渡态显示,发起检查后很快会落到 online/offline + return 'connecting' + } +} diff --git a/src/utils/fuzzyMatch.test.ts b/src/utils/fuzzyMatch.test.ts new file mode 100644 index 000000000..93f8db713 --- /dev/null +++ b/src/utils/fuzzyMatch.test.ts @@ -0,0 +1,94 @@ +// ============================================ +// fuzzyMatch 核心契约测试 +// ============================================ + +import { describe, expect, it } from 'vitest' +import { fuzzyScore } from './fuzzyMatch' + +describe('fuzzyScore 分级语义', () => { + it('名字全等得分最高', () => { + const exact = fuzzyScore('compact', 'compact', 'some description containing compact') + const other = fuzzyScore('compact', 'other-cmd', 'some description containing compact') + expect(exact).toBeGreaterThan(other) + }) + + it('名字前缀命中压过描述命中 —— /goa 必须让 goal 排第一', () => { + const goal = fuzzyScore('goa', 'goal', 'Set, show goals') + const reviewWork = fuzzyScore('goa', 'review-work', 'check the goal of post-implementation') + expect(goal).toBeGreaterThan(reviewWork) + expect(reviewWork).toBeGreaterThan(0) // 描述命中仍然可见,但排后面 + }) + + it('名字子串命中压过描述命中 —— /comp 必须让 compact 压过一堆 skill', () => { + const compact = fuzzyScore('comp', 'compact', '通过总结对话历史压缩上下文') + const skillWithCompInDesc = fuzzyScore('comp', 'agent-lane-orchestrator', 'compare components and compose reports') + expect(compact).toBeGreaterThan(skillWithCompInDesc) + }) + + it('词边界命中:stats 能搜到 session-stats', () => { + const score = fuzzyScore('stats', 'session-stats') + expect(score).toBeGreaterThan(0) + const substringOnly = fuzzyScore('stats', 'statistician') + expect(score).toBeGreaterThan(substringOnly) + }) + + it('缩写(子序列)命中:cmp 能搜到 compact —— 打不完整也能找到', () => { + const score = fuzzyScore('cmp', 'compact') + expect(score).toBeGreaterThan(0) + // 更紧凑的匹配得分更高:compact 比 c-o-m-p 分散的词得分高 + const tighter = fuzzyScore('cmp', 'cmp') + expect(tighter).toBeGreaterThan(score) + }) + + it('子序列必须保持字符顺序,乱序不匹配', () => { + expect(fuzzyScore('pmc', 'compact')).toBe(0) + }) + + it('完全无关的内容不匹配', () => { + expect(fuzzyScore('xyz', 'compact')).toBe(0) + expect(fuzzyScore('xyz', 'compact', '关于对话历史的总结')).toBe(0) + }) + + it('空 query 返回 0 分(调用方应视为「全部可见」)', () => { + expect(fuzzyScore('', 'compact')).toBe(0) + expect(fuzzyScore(' ', 'compact')).toBe(0) + }) + + it('描述子序列兜底需要 query 至少 2 个字符', () => { + expect(fuzzyScore('c', 'review-work', 'check components')).toBe(0) + expect(fuzzyScore('co', 'review-work', 'check components')).toBeGreaterThan(0) + }) +}) + +describe('fuzzyScore 排序契约(模拟真实命令面板)', () => { + interface Cmd { + name: string + description?: string + } + + function rank(query: string, cmds: Cmd[]): string[] { + return cmds + .map(c => ({ name: c.name, score: fuzzyScore(query, c.name, c.description) })) + .filter(x => x.score > 0) + .sort((a, b) => b.score - a.score) + .map(x => x.name) + } + + it('场景还原:输入 comp 时 compact 排第一,描述里碰巧有 comp 的 skill 靠后', () => { + const ranked = rank('comp', [ + { name: 'agent-lane-orchestrator', description: 'compare components and reports' }, + { name: 'compact', description: '通过总结对话历史压缩上下文' }, + { name: 'review-work', description: 'post implementation review' }, + ]) + expect(ranked[0]).toBe('compact') + expect(ranked).toContain('agent-lane-orchestrator') + }) + + it('场景还原:输入 goa 时 goal 排在 review-work 前面', () => { + const ranked = rank('goa', [ + { name: 'review-work', description: 'Post-implementation review of the goal' }, + { name: 'goal', description: 'Set, show goals' }, + ]) + expect(ranked[0]).toBe('goal') + }) +}) diff --git a/src/utils/fuzzyMatch.ts b/src/utils/fuzzyMatch.ts new file mode 100644 index 000000000..db5824ff2 --- /dev/null +++ b/src/utils/fuzzyMatch.ts @@ -0,0 +1,122 @@ +// ============================================ +// fuzzyMatch - 打分式模糊匹配器 +// ============================================ +// 用于命令面板这类「少量条目、需要相关度排序」的场景。 +// 设计参考 VS Code Quick Open / fzf 的分级打分语义: +// 名字命中永远压过描述命中,同级内按打分排序。 + +/** + * 匹配等级(数值越大越相关)。 + * 注意:等级之间的差距设计为远大于同级内的细项加分, + * 保证「名字子串命中」永远排在「描述命中」前面。 + */ +const SCORE_EXACT = 10_000 // 名字全等 +const SCORE_PREFIX = 8_000 // 名字前缀命中 +const SCORE_WORD_BOUNDARY = 6_000 // 名字词边界命中(如 session-stats 中的 "stats") +const SCORE_SUBSTRING = 4_000 // 名字普通子串命中 +const SCORE_SUBSEQUENCE = 2_000 // 名字缩写命中(按序命中所有字符,如 cmp → compact) +const SCORE_DESCRIPTION = 100 // 仅描述命中(名字完全不沾边) + +// 同级内的细项加分,累计上限不会跨级 +const BONUS_PREFIX_START = 300 // query 从名字第一个字符开始(天然前缀) +const BONUS_SHORTER_NAME = 200 // 名字越短越精确(每短一个字符 +2,封顶 200) +const BONUS_CONSECUTIVE = 15 // 子序列匹配时,连续命中的字符越多越相关 +const BONUS_WORD_START = 50 // query 命中在词边界上(- _ . / 空格 后的首字符) +const PENALTY_SUBSEQUENCE_GAP = -5 // 缩写匹配时字符间隔越大越扣分 + +/** 词边界字符:这些字符后的字母视为「词首」 */ +const WORD_SEPARATORS = new Set(['-', '_', '.', '/', ' ', '@', ':']) + +/** + * 计算子序列匹配的得分:query 的每个字符按顺序出现在 target 中。 + * 返回 null 表示不是子序列匹配。 + * + * 统计连续命中数和间隔惩罚,让 "cmp" 对 "compact" 的得分 + * 高于对 "ca...m...p" 这类松散匹配。 + */ +function scoreSubsequence(query: string, target: string): { score: number } | null { + let qi = 0 + let consecutive = 0 + let maxConsecutive = 0 + let gaps = 0 + let prevMatchIndex = -2 + + for (let ti = 0; ti < target.length && qi < query.length; ti++) { + if (target[ti] === query[qi]) { + if (prevMatchIndex === ti - 1) { + consecutive++ + } else { + gaps += prevMatchIndex >= 0 ? ti - prevMatchIndex - 1 : 0 + consecutive = 1 + } + maxConsecutive = Math.max(maxConsecutive, consecutive) + prevMatchIndex = ti + qi++ + } + } + + // 有字符没按序命中 → 匹配失败 + if (qi < query.length) return null + + return { + score: BONUS_CONSECUTIVE * maxConsecutive + PENALTY_SUBSEQUENCE_GAP * gaps, + } +} + +/** + * 纯函数:query 与一个名字/描述对的相关度打分。 + * 返回总分(0 = 无匹配),分数只用于同一次查询内的排序,无绝对含义。 + */ +export function fuzzyScore(query: string, name: string, description?: string): number { + const q = query.toLowerCase().trim() + if (!q) return 0 + + const n = name.toLowerCase() + + // —— 名字匹配(高等级)—— + let nameScore = 0 + + if (n === q) { + nameScore = SCORE_EXACT + } else if (n.startsWith(q)) { + nameScore = SCORE_PREFIX + BONUS_PREFIX_START + // 名字越短,前缀命中越精确 + nameScore += Math.max(0, BONUS_SHORTER_NAME - (n.length - q.length) * 2) + } else { + // 词边界命中:query 出现在某个分隔符之后(如 "stats" → "session-stats") + let wordBoundaryOffset = -1 + for (let i = 1; i <= n.length - q.length; i++) { + if (n.startsWith(q, i) && WORD_SEPARATORS.has(n[i - 1])) { + wordBoundaryOffset = i + break + } + } + + if (wordBoundaryOffset >= 0) { + nameScore = SCORE_WORD_BOUNDARY + BONUS_WORD_START + } else if (n.includes(q)) { + // 普通子串命中:位置越靠前越相关 + nameScore = SCORE_SUBSTRING + Math.max(0, 60 - n.indexOf(q) * 3) + } else { + const sub = scoreSubsequence(q, n) + if (sub) { + nameScore = SCORE_SUBSEQUENCE + sub.score + } + } + } + + if (nameScore > 0) return nameScore + + // —— 描述匹配(最低等级,永远压不过名字命中)—— + // 单字符 query 不走描述匹配:会在所有含该字母的描述里到处命中,噪音太大 + if (description && q.length >= 2) { + const d = description.toLowerCase() + if (d.includes(q)) return SCORE_DESCRIPTION + // 描述子序列兜底,分数略高于纯 includes 以区分强度 + if (scoreSubsequence(q, d)) { + return SCORE_DESCRIPTION + Math.min(50, q.length * 5) + } + } + + return 0 +} diff --git a/src/utils/modelUtils.test.ts b/src/utils/modelUtils.test.ts new file mode 100644 index 000000000..101f46f6c --- /dev/null +++ b/src/utils/modelUtils.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Model } from '../api' + +const { storage } = vi.hoisted(() => ({ storage: new Map() })) + +vi.mock('./perServerStorage', () => ({ + serverStorage: { + get: (key: string) => storage.get(key) ?? null, + set: (key: string, value: string) => { + storage.set(key, value) + }, + remove: (key: string) => { + storage.delete(key) + }, + }, +})) + +import { groupModelsByProvider, sortModelsByFrequency } from './modelUtils' + +function model(id: string, name: string, providerID = 'p1'): Model { + return { id, name, providerID } as unknown as Model +} + +function setUsageStats(stats: Record) { + storage.set('model-usage-stats', JSON.stringify(stats)) +} + +describe('sortModelsByFrequency', () => { + beforeEach(() => { + storage.clear() + }) + + it('sorts unused models by model name', () => { + const models = [model('c', 'Zeta'), model('a', 'Alpha'), model('b', 'Beta')] + + expect(sortModelsByFrequency(models).map(m => m.name)).toEqual(['Alpha', 'Beta', 'Zeta']) + }) + + it('puts used models before unused ones, with unused sorted by name', () => { + setUsageStats({ 'p1:zulu': { count: 1, lastUsed: 100 } }) + const models = [model('zulu', 'Zulu'), model('beta', 'Beta'), model('alpha', 'Alpha')] + + expect(sortModelsByFrequency(models).map(m => m.name)).toEqual(['Zulu', 'Alpha', 'Beta']) + }) + + it('sorts used models by count desc, then lastUsed desc, then name', () => { + setUsageStats({ + 'p1:a': { count: 2, lastUsed: 100 }, + 'p1:b': { count: 2, lastUsed: 200 }, + 'p1:c': { count: 5, lastUsed: 1 }, + 'p1:d': { count: 2, lastUsed: 200 }, + }) + const models = [model('a', 'Alpha'), model('b', 'Beta'), model('c', 'Gamma'), model('d', 'Delta')] + + expect(sortModelsByFrequency(models).map(m => m.name)).toEqual(['Gamma', 'Beta', 'Delta', 'Alpha']) + }) +}) + +describe('groupModelsByProvider', () => { + beforeEach(() => { + storage.clear() + }) + + it('keeps provider groups by total usage and sorts unused models by name within groups', () => { + setUsageStats({ 'p2:x': { count: 3, lastUsed: 100 } }) + const models = [ + model('y', 'Yellow', 'p2'), + model('z', 'Zeta', 'p1'), + model('x', 'Xray', 'p2'), + model('a', 'Alpha', 'p1'), + ] + + const groups = groupModelsByProvider(models) + + expect(groups.map(group => group.providerName)).toEqual(['p2', 'p1']) + expect(groups[0].models.map(m => m.name)).toEqual(['Xray', 'Yellow']) + expect(groups[1].models.map(m => m.name)).toEqual(['Alpha', 'Zeta']) + }) +}) diff --git a/src/utils/modelUtils.ts b/src/utils/modelUtils.ts index 956db8c59..1794d2e24 100644 --- a/src/utils/modelUtils.ts +++ b/src/utils/modelUtils.ts @@ -191,7 +191,7 @@ export type ModelSortMode = 'frequency' | 'alphabetical' | 'provider' * 根据使用频率排序模型 * - 最近使用的优先 * - 使用次数多的优先 - * - 未使用过的按原始顺序 + * - 未使用过的按模型 name 首字母排序 */ export function sortModelsByFrequency(models: Model[]): Model[] { const stats = getModelUsageStats() @@ -202,18 +202,22 @@ export function sortModelsByFrequency(models: Model[]): Model[] { const statsA = stats[keyA] const statsB = stats[keyB] - // 都没使用过,保持原始顺序 - if (!statsA && !statsB) return 0 + // 都没使用过,按模型 name 首字母排序 + if (!statsA && !statsB) return a.name.localeCompare(b.name) // 只有一个使用过,使用过的排前面 if (!statsA) return 1 if (!statsB) return -1 - // 都使用过,按使用次数排序,次数相同按最近使用时间 + // 都使用过,按使用次数排序,次数相同按最近使用时间, + // 再相同则按模型 name 首字母排序以保证顺序稳定 if (statsA.count !== statsB.count) { return statsB.count - statsA.count } - return statsB.lastUsed - statsA.lastUsed + if (statsA.lastUsed !== statsB.lastUsed) { + return statsB.lastUsed - statsA.lastUsed + } + return a.name.localeCompare(b.name) }) }