Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(chat): 重试刷新主进程缓存并确认手机路径类型

Dashb8b55a5580e8
diff --git a/apps/desktop/scripts/fixtures/explicit-file-links/fixture.tsx b/apps/desktop/scripts/fixtures/explicit-file-links/fixture.tsx
index 9ccf28782f..193167ce7e 100644
--- a/apps/desktop/scripts/fixtures/explicit-file-links/fixture.tsx
+++ b/apps/desktop/scripts/fixtures/explicit-file-links/fixture.tsx
@@ -11,9 +11,9 @@ const content = '[查看报告](/fixture/report.html)\n\n[下载 PDF](/fixture/r
mountPage({
route: '/sessions/fixture',
host: ctx => ({
- resolvePath: ctx.case === 'remote' ? forbid('resolvePath on remote file') : async ({ href }: { href: string }) => ({
- status: restored && href.endsWith('.pdf') ? 'unique' : 'none',
- candidates: restored && href.endsWith('.pdf') ? [href] : [],
+ resolvePath: ctx.case === 'remote' ? forbid('resolvePath on remote file') : async ({ href, refresh }: { href: string; refresh?: boolean }) => ({
+ status: refresh && restored && href.endsWith('.pdf') ? 'unique' : 'none',
+ candidates: refresh && restored && href.endsWith('.pdf') ? [href] : [],
kind: 'file',
}),
openPath: async (path: string) => {
diff --git a/apps/desktop/scripts/fixtures/explicit-file-links/ui-page.mjs b/apps/desktop/scripts/fixtures/explicit-file-links/ui-page.mjs
index 6eb156af78..ecffa3d5a5 100644
--- a/apps/desktop/scripts/fixtures/explicit-file-links/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/explicit-file-links/ui-page.mjs
@@ -7,7 +7,7 @@ export default {
real: 'MarkdownRenderer, path classification, click-time resolution, link context menu and error toast',
notCovered: 'Real filesystem, remote transport and OS opening; mobile native rendering.',
cases: {
- default: { about: 'Missing authored link remains clickable, explains failure, copies destination and retries after restoration' },
+ default: { about: 'Missing authored link remains clickable, explains failure, offers a copy menu and requests a fresh lookup after restoration' },
remote: { about: 'Missing remote link remains clickable without local filesystem access' },
untrusted: { about: 'Content without privileged file access stays inert' },
},
diff --git a/apps/desktop/src/main/__tests__/pathResolver.test.ts b/apps/desktop/src/main/__tests__/pathResolver.test.ts
index e983675499..ddd2ab1c5f 100644
--- a/apps/desktop/src/main/__tests__/pathResolver.test.ts
+++ b/apps/desktop/src/main/__tests__/pathResolver.test.ts
@@ -299,6 +299,19 @@ describe('resolveWorkspacePath', () => {
});
describe('resolveWorkspacePathCached', () => {
+ // #7303: renderer retries used to hit the same main-process negative cache.
+ // Exercise real batch-cache → file restoration → explicit refresh, no timers.
+ it('refreshes a restored file immediately despite a batch-cached miss', async () => {
+ const href = 'report.pdf';
+ expect((await resolveWorkspacePathBatchCached([href], workspace))[href].status).toBe('none');
+ const target = write(href, 'restored');
+ expect((await resolveWorkspacePathCached(href, workspace)).status).toBe('none');
+ expect(await resolveWorkspacePathCached(href, workspace, { refresh: true })).toEqual({
+ status: 'unique', candidates: [target], kind: 'file',
+ });
+ expect((await resolveWorkspacePathBatchCached([href], workspace))[href].candidates).toEqual([target]);
+ });
+
it('returns the same result on repeated calls (cache hit)', async () => {
const target = write('apps/desktop/src/App.tsx');
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index ff84acb352..2ad4cd1651 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -7529,7 +7529,7 @@ const registerIpcHandlers = () => {
'fs:resolve-path',
async (
_event: Electron.IpcMainInvokeEvent,
- params: { href: string; workingDir: string },
+ params: { href: string; workingDir: string; refresh?: boolean },
): Promise<{
status: 'unique' | 'multiple' | 'none';
candidates: string[];
@@ -7538,6 +7538,7 @@ const registerIpcHandlers = () => {
try {
return await resolveWorkspacePathCached(params.href, params.workingDir, {
isPathAllowed,
+ refresh: params.refresh === true,
});
} catch (err) {
console.error('[fs:resolve-path] failed:', err);
diff --git a/apps/desktop/src/main/pathResolver.ts b/apps/desktop/src/main/pathResolver.ts
index 9fba343926..9cbd930391 100644
--- a/apps/desktop/src/main/pathResolver.ts
+++ b/apps/desktop/src/main/pathResolver.ts
@@ -37,6 +37,8 @@ export interface ResolvePathResult {
}
export interface ResolveOptions {
+ /** Explicit user retry: bypass the shared TTL entry and replace it with a fresh result. */
+ refresh?: boolean;
/** Optional path-allowlist guard, applied to every candidate. */
isPathAllowed?: (absPath: string) => boolean;
/** Stop BFS after this many file matches. Default 10. */
@@ -274,7 +276,7 @@ export async function resolveWorkspacePathCached(
const key = makeCacheKey(workingDir, href);
const now = Date.now();
const hit = cache.get(key);
- if (hit && hit.expireAt > now) return hit.result;
+ if (!options.refresh && hit && hit.expireAt > now) return hit.result;
if (hit) cache.delete(key);
const result = await resolveWorkspacePath(href, workingDir, options);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 85fda34bc1..67edd7d1c7 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4436,6 +4436,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
resolvePath: (params: {
href: string;
workingDir: string;
+ /** User retry bypasses the host's shared render-time cache. */
+ refresh?: boolean;
}): Promise<{
status: 'unique' | 'multiple' | 'none';
candidates: string[];
diff --git a/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts b/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts
index 837f9ee79a..92e24c4c24 100644
--- a/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts
+++ b/apps/desktop/src/renderer/__tests__/localPathResolver.test.ts
@@ -247,6 +247,15 @@ describe('resolveToolFilePath (agent tool-input path absolutizer)', () => {
});
describe('resolveLocalPathSmart', () => {
+ // #7303: an explicit retry must reach the host's refresh option, not just
+ // bypass this module's render cache (the real cache regression lives in main).
+ it('passes explicit refresh through the existing resolution IPC', async () => {
+ const resolvePath = vi.fn().mockResolvedValue({ status: 'none', candidates: [] });
+ vi.stubGlobal('window', { electronAPI: { resolvePath } });
+ await resolveLocalPathSmart('report.pdf', '/repo', { refresh: true });
+ expect(resolvePath).toHaveBeenCalledWith({ href: 'report.pdf', workingDir: '/repo', refresh: true });
+ });
+
it('passes decoded native paths to the main-process resolver for file URLs', async () => {
const resolvePath = vi.fn().mockResolvedValue({
status: 'unique',
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index 6308e3a673..63536f4d9f 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -1551,7 +1551,7 @@ function MarkdownTargetLink({
// cached copy or explain the connection failure. Never open locally.
result = { status: 'unique', absPath, kind: verdict === 'directory' ? 'directory' : 'file' };
} else {
- result = await resolveLocalPathSmart(target.href, workingDir);
+ result = await resolveLocalPathSmart(target.href, workingDir, { refresh: true });
}
if (result.status === 'multiple') {
toast.error(t('chat.markdownRenderer.duplicateFiles', { count: result.candidates.length }));
diff --git a/apps/desktop/src/renderer/lib/localPathResolver.ts b/apps/desktop/src/renderer/lib/localPathResolver.ts
index dd218c2aa3..aa9f463e3a 100644
--- a/apps/desktop/src/renderer/lib/localPathResolver.ts
+++ b/apps/desktop/src/renderer/lib/localPathResolver.ts
@@ -329,6 +329,7 @@ export type SmartResolveResult =
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
@@ -343,7 +344,7 @@ export async function resolveLocalPathSmart(
return { status: 'none', fallbackAbsPath: fallback };
}
try {
- const r = await api.resolvePath({ href: lookupHref, workingDir });
+ const r = await api.resolvePath({ href: lookupHref, workingDir, ...(options.refresh ? { refresh: true } : {}) });
if (r.status === 'unique' && r.candidates[0]) {
return { status: 'unique', absPath: r.candidates[0], ...(r.kind ? { kind: r.kind } : {}) };
}
diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
index d01fc8bee5..836f716556 100644
--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
@@ -57,9 +57,9 @@ vi.mock('react-native', async () => {
children?: ReactNode; onPress?: () => void; disabled?: boolean; testID?: string; accessibilityState?: { busy?: boolean }; accessibilityLabel?: string; style?: unknown;
}) => createElement(tag, { onClick: onPress, disabled, 'data-testid': testID, 'data-native-style': JSON.stringify(style), 'aria-busy': accessibilityState?.busy, 'aria-label': accessibilityLabel }, children);
// Text keeps its onTextLayout so a test can report how many lines a label took.
- const Text = ({ children, onTextLayout, onPress, testID }: { children?: ReactNode; onTextLayout?: (event: { nativeEvent: { lines: unknown[] } }) => void; onPress?: () => void; testID?: string }) => {
+ const Text = ({ children, onTextLayout, onPress, onLongPress, testID }: { children?: ReactNode; onTextLayout?: (event: { nativeEvent: { lines: unknown[] } }) => void; onPress?: () => void; onLongPress?: () => void; testID?: string }) => {
if (onTextLayout) textLayouts.set(String(children), onTextLayout);
- return createElement('span', { onClick: onPress, 'data-testid': testID }, children);
+ return createElement('span', { onClick: onPress, onContextMenu: onLongPress, 'data-testid': testID }, children);
};
return { View: view('div'), Text, Pressable: view('button'), Linking: { openURL: evidence.openURL },
ScrollView: view('div'), Image: () => null, ActivityIndicator: () => null,
@@ -513,6 +513,41 @@ it.each([true, false])('keeps missing file links actionable only when authored:
}
});
+// #7303: an authored directory without a trailing slash can be tapped before
+// background stat completes. Wait for its actual kind before choosing a route.
+it.each(['open', 'menu', 'unmounted', 'outside'] as const)('waits for an authored directory kind before acting: %s', async (mode) => {
+ const onOpenPath = vi.fn();
+ const onLongPressPath = vi.fn();
+ let finishStat!: (value: { kind: 'dir'; resolvedPath: string }) => void;
+ const pending = new Promise<{ kind: 'dir'; resolvedPath: string }>((resolve) => { finishStat = resolve; });
+ const fileContext: ChatFilePathContextValue = {
+ deviceId: 'd1', sessionId: 's1', workdir: '/repo', onOpenPath, onLongPressPath,
+ statPath: vi.fn(() => pending),
+ };
+ await act(async () => root.render(
+ <ChatFilePathContext.Provider value={fileContext}>
+ <ChatPathChipSpan candidate={classifyChatPathLinkTarget(mode === 'outside' ? '/other/components' : 'src/components')} explicitLink
+ display="目录" SpanText={Text} chipStyle={{}} plainStyle={{}} usePathState={useState} />
+ </ChatFilePathContext.Provider>,
+ ));
+ const link = host.querySelector<HTMLElement>('[data-testid="message.markdownPathChip"]')!;
+ await act(async () => mode === 'menu'
+ ? link.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }))
+ : link.click());
+ expect(onOpenPath).not.toHaveBeenCalled();
+ expect(onLongPressPath).not.toHaveBeenCalled();
+ if (mode === 'unmounted') await act(async () => root.render(null));
+ await act(async () => finishStat({ kind: 'dir', resolvedPath: '/repo/src/components' }));
+ if (mode === 'unmounted' || mode === 'outside') {
+ expect(onOpenPath).not.toHaveBeenCalled();
+ expect(onLongPressPath).not.toHaveBeenCalled();
+ return;
+ }
+ expect(mode === 'menu' ? onLongPressPath : onOpenPath).toHaveBeenCalledExactlyOnceWith({
+ kind: 'directory', absPath: '/repo/src/components', relPath: 'src/components',
+ });
+});
+
it.each(['push-first', 'receipt-first', 'lost-receipt', 'other-client'] as const)(
'finalizes retained answers without stale snapshot resurrection: %s',
async (order) => {
diff --git a/apps/mobile/src/__tests__/chatPathCandidate.test.ts b/apps/mobile/src/__tests__/chatPathCandidate.test.ts
index 72250e5c61..007ccde056 100644
--- a/apps/mobile/src/__tests__/chatPathCandidate.test.ts
+++ b/apps/mobile/src/__tests__/chatPathCandidate.test.ts
@@ -17,7 +17,7 @@ const pathContext = React.createContext<any>(null);
const verdictListeners = new Set<(key: string) => void>();
const verifyPath = vi.fn(async () => undefined);
const pathBindings = {
- React, useContext: React.useContext, useCallback: React.useCallback, useEffect: React.useEffect, useMemo: React.useMemo,
+ React, useContext: React.useContext, useCallback: React.useCallback, useEffect: React.useEffect, useMemo: React.useMemo, useRef: React.useRef,
useRecyclingState: React.useState, ChatFilePathContext: pathContext,
resolveChatAbsPath, toWorkdirRel, canOpenChatPathChip, classifyChatPathLinkTarget, chatPathLabelReadsAsFileReference,
StyleSheet: { flatten: flattenStyle },
diff --git a/apps/mobile/src/session/ChatPathChipSpan.tsx b/apps/mobile/src/session/ChatPathChipSpan.tsx
index fe2f355d03..ce269337f0 100644
--- a/apps/mobile/src/session/ChatPathChipSpan.tsx
+++ b/apps/mobile/src/session/ChatPathChipSpan.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useContext, useEffect, useMemo, type Dispatch, type SetStateAction } from 'react';
+import { useCallback, useContext, useEffect, useMemo, useRef, type Dispatch, type SetStateAction } from 'react';
import type { StyleProp, TextStyle } from 'react-native';
import { useRecyclingState } from '@legendapp/list/react-native';
import { Text } from '@/components/AppText';
@@ -48,6 +48,11 @@ export function ChatPathChipSpan({
const absPath = resolveChatAbsPath(candidate.href, ctx.workdir);
return { absPath, relPath: toWorkdirRel(ctx.workdir, absPath) };
}, [candidate, ctx]);
+ const actionScope = useRef<{ ctx: typeof ctx; target: typeof target } | null>(null);
+ useEffect(() => {
+ actionScope.current = { ctx, target };
+ return () => { actionScope.current = null; };
+ }, [ctx, target]);
// verdict 是**缓存的纯派生**,chip 不自己存结论:ForRender 版会把 TTL 未过期的负缓存
// 回成 'unknown',于是断链期间的乐观点亮也来自缓存。自存一份的话收不到缓存变化 ——
// 同一路径出现在多个 chip 上时,A 按 unknown 点亮、B 拿到确定的 nonfile,A 会一直
@@ -117,16 +122,34 @@ export function ChatPathChipSpan({
if (!canOpenChatPathChip(kind, target.relPath)) {
return <SpanText style={plainStyle}>{display}</SpanText>;
}
- const chipTarget: ChatFilePathTarget = {
- kind,
- relPath: target.relPath,
- absPath: target.absPath,
- ...(kind === 'file' && candidate.line !== undefined ? { line: candidate.line } : {}),
+ const activate = async (action: (value: ChatFilePathTarget) => void) => {
+ let actionKind = kind;
+ if (explicitLink) {
+ // A visible authored link may be tapped before background verification,
+ // or after a cached miss. Resolve the kind before opening or building its
+ // menu; a directory without a trailing slash must not enter file preview.
+ try {
+ const stat = await ctx.statPath(target.absPath);
+ if (stat.kind === 'dir') actionKind = 'directory';
+ else if (stat.kind === 'file') actionKind = 'file';
+ } catch {
+ // Preserve the existing preview/browser failure UX and copy menu when
+ // the host is unavailable; no local lookup or connection reset.
+ }
+ if (actionScope.current?.ctx !== ctx || actionScope.current.target?.absPath !== target.absPath) return;
+ }
+ if (!canOpenChatPathChip(actionKind, target.relPath)) return;
+ action({
+ kind: actionKind,
+ relPath: target.relPath,
+ absPath: target.absPath,
+ ...(actionKind === 'file' && candidate.line !== undefined ? { line: candidate.line } : {}),
+ });
};
return (
<SpanText
- onLongPress={ctx.onLongPressPath ? () => ctx.onLongPressPath?.(chipTarget) : undefined}
- onPress={() => ctx.onOpenPath(chipTarget)}
+ onLongPress={ctx.onLongPressPath ? () => { void activate(ctx.onLongPressPath!); } : undefined}
+ onPress={() => { void activate(ctx.onOpenPath); }}
style={chipStyle}
testID="message.markdownPathChip"
>