Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 正确处理附件链接中的特殊字符
321sssrt-bit72495a3d8cf8
diff --git a/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts b/apps/desktop/src/renderer/__tests__/localPathResolver.test.tsindex 92e24c4c24..dc79d341ad 100644--- a/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts+++ b/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts@@ -10,6 +10,15 @@*/import { afterEach, describe, it, expect, vi } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import {+ resolveWorkspacePath,+ resolveWorkspacePathBatch,+ safeDecodeHrefForLookup,+} from '../../main/pathResolver';import {_clearSmartResolveCache,@@ -274,6 +283,64 @@ describe('resolveLocalPathSmart', () => {});});+describe('file URL decoding across renderer and main', () => {+ afterEach(() => {+ _clearSmartResolveCache();+ });++ // F3: both IPC paths reach the production host decoder after file URL conversion.+ it.each([+ ['file:///C:/project/a%2520b.pdf', 'C:/project/a%20b.pdf'],+ ['file:///project/a%2520b.pdf', '/project/a%20b.pdf'],+ ['file:///project/report%23final.pdf', '/project/report#final.pdf'],+ ])('preserves the literal target of %s for direct and batched lookup', async (href, expected) => {+ const resolvePath = vi.fn().mockResolvedValue({ status: 'none', candidates: [] });+ const resolvePathBatch = vi.fn().mockResolvedValue({});+ vi.stubGlobal('window', { electronAPI: { resolvePath, resolvePathBatch } });++ await resolveLocalPathSmart(href, '/project', { refresh: true });+ await resolveLocalPathSmartCached(href, '/project');++ expect([+ safeDecodeHrefForLookup(resolvePath.mock.calls[0][0].href),+ safeDecodeHrefForLookup(resolvePathBatch.mock.calls[0][0].hrefs[0]),+ ]).toEqual([expected, expected]);+ });++ it('resolves a literal percent filename through the renderer and main production entry points', async () => {+ let root: string | undefined;++ try {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-renderer-path-'));+ const target = path.join(root, 'a%20b.pdf');+ fs.writeFileSync(target, '%PDF');+ const href = toFileUrl(target);++ const resolvePath = vi.fn(({ href: lookupHref, workingDir }: { href: string; workingDir: string }) =>+ resolveWorkspacePath(lookupHref, workingDir));+ const resolvePathBatch = vi.fn(({ hrefs, workingDir }: { hrefs: string[]; workingDir: string }) =>+ resolveWorkspacePathBatch(hrefs, workingDir));+ vi.stubGlobal('window', { electronAPI: { resolvePath, resolvePathBatch } });++ const direct = await resolveLocalPathSmart(href, root, { refresh: true });+ expect(direct.status).toBe('unique');+ if (direct.status === 'unique') {+ expect(direct.kind).toBe('file');+ expect(path.normalize(direct.absPath)).toBe(path.normalize(target));+ }++ const batch = await resolveLocalPathSmartCached(href, root);+ expect(batch.status).toBe('unique');+ if (batch.status === 'unique') {+ expect(batch.kind).toBe('file');+ expect(path.normalize(batch.absPath)).toBe(path.normalize(target));+ }+ } finally {+ if (root) fs.rmSync(root, { recursive: true, force: true });+ }+ });+});+describe('resolveLocalPathSmartCached + peekResolveLocalPathSmart (renderer cache + batch)', () => {afterEach(() => {_clearSmartResolveCache();diff --git a/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts b/apps/desktop/src/renderer/__tests__/markdownTarget.test.tsindex ee3cc8b41d..6852300bed 100644--- a/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts+++ b/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts@@ -201,6 +201,22 @@ describe('classifyMarkdownLinkTarget', () => {});});+ // F3: compare decoded hrefs with literal attachment names.+ it.each(['report#final.pdf', 'a%20b.pdf', '报告 1.pdf'])(+ 'resolves the encoded link to literal attachment %s outside the workspace', (name) => {+ const path = `/uploads/${name}`;+ expect(classifyMarkdownLinkTarget(encodeURIComponent(name), [{ name, path }]))+ .toMatchObject({ kind: 'resolved-local', absPath: path });+ },+ );++ it('does not choose between duplicate literal attachment names', () => {+ expect(classifyMarkdownLinkTarget('report%23final.pdf', [+ { name: 'report#final.pdf', path: '/one/report#final.pdf' },+ { name: 'report#final.pdf', path: '/two/report#final.pdf' },+ ])).toMatchObject({ kind: 'local-candidate' });+ });+// F2: a same-name attachment must not replace an explicit destination.it.each(['C:\\project\\report.pdf', 'C:/project/report.pdf', '/project/report.pdf',@@ -213,6 +229,15 @@ describe('classifyMarkdownLinkTarget', () => {])).toMatchObject({ kind: 'local-candidate', href });});+ // F2 + F3: URL-decoding an explicit path must not make its literal+ // percent-encoded basename eligible for attachment substitution.+ it('keeps an encoded explicit path beside a same-name literal attachment', () => {+ const href = 'file:///C:/project/a%2520b.pdf';+ expect(classifyMarkdownLinkTarget(href, [+ { name: 'a%20b.pdf', path: 'C:\\uploads\\a%20b.pdf' },+ ])).toMatchObject({ kind: 'local-candidate', href });+ });+it('does not render unsupported schemes or directories as clickable links', () => {expect(classifyMarkdownLinkTarget('mailto:[email protected]')).toEqual({kind: 'plain-text',diff --git a/apps/desktop/src/renderer/lib/localPathResolver.ts b/apps/desktop/src/renderer/lib/localPathResolver.tsindex 1714e6e69e..73d2444dd6 100644--- a/apps/desktop/src/renderer/lib/localPathResolver.ts+++ b/apps/desktop/src/renderer/lib/localPathResolver.ts@@ -192,12 +192,6 @@ function basenameFromPathLike(value: string): string {return slash >= 0 ? value.slice(slash + 1) : value;}-function normalizeKnownFileHref(href: string): string {- const strippedScheme = href.startsWith('file://') ? href.slice(7) : href;- const decoded = safeDecodeURIComponent(stripQueryAndHash(strippedScheme.trim()));- return basenameFromPathLike(decoded);-}-/*** Resolve a model-authored markdown link against files the user attached in* this chat session. LLMs often cite an uploaded document as@@ -223,12 +217,13 @@ export function resolveKnownLocalFileHref(if (!href || !files || files.length === 0) return null;const decoded = safeDecodeURIComponent(stripQueryAndHash(href.trim()));if (/^(?:file:\/\/|[\\/]|[a-z]:[\\/]|~[\\/])/i.test(decoded)) return null;- const wanted = normalizeKnownFileHref(href).toLowerCase();+ const wanted = basenameFromPathLike(decoded).toLowerCase();if (!wanted) return null;const matches = files.filter((file) => {- const name = normalizeKnownFileHref(file.name).toLowerCase();- const pathName = normalizeKnownFileHref(file.path).toLowerCase();+ // Attachment metadata is literal filesystem text, not URL syntax.+ const name = basenameFromPathLike(file.name).toLowerCase();+ const pathName = basenameFromPathLike(file.path).toLowerCase();return wanted === name || wanted === pathName;});@@ -328,17 +323,19 @@ export type SmartResolveResult =| { status: 'multiple'; candidates: string[] }| { status: 'none'; fallbackAbsPath: string };+function toMainLookupHref(href: string, workingDir: string): string {+ if (!href.startsWith('file://')) return href;+ // File URL conversion yields literal text; main still decodes its href input.+ return resolveLocalPath(href, workingDir).replace(/%/g, '%25');+}+export async function resolveLocalPathSmart(href: string,workingDir: string,options: { refresh?: boolean } = {},): Promise<SmartResolveResult> {const fallback = resolveLocalPath(href, workingDir);- // Main-process resolver expects a native absolute/relative path, not a- // file:// URL. Keep the public API accepting file:// because markdown links- // frequently use that form; resolveLocalPath already handles the cross-- // platform decoding rules.- const lookupHref = href.startsWith('file://') ? fallback : href;+ const lookupHref = toMainLookupHref(href, workingDir);const api = (typeof window !== 'undefined' ? window.electronAPI : undefined) as| { resolvePath?: typeof window.electronAPI.resolvePath }| undefined;@@ -467,11 +464,10 @@ async function runBatchForDir(return;}- // Main resolver wants a native path, not a file:// URL — same rule as- // `resolveLocalPathSmart`. Map each href to the lookup form it sends.+ // Use the same URL decoding boundary for direct and batched lookups.const lookupOf = new Map<string, string>();for (const href of hrefs) {- lookupOf.set(href, href.startsWith('file://') ? resolveLocalPath(href, workingDir) : href);+ lookupOf.set(href, toMainLookupHref(href, workingDir));}const lookups = [...new Set(lookupOf.values())];