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。

feat(desktop): 多个下载合并提示并支持下拉管理

DavidShen600083ff9de9
diff --git a/apps/desktop/src/renderer/__tests__/downloadToast.test.tsx b/apps/desktop/src/renderer/__tests__/downloadToast.test.tsx
new file mode 100644
index 0000000000..c60634631e
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/downloadToast.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DownloadToast } from '../components/ui/toast/DownloadToast';
+import type { FileTransferToast } from '../lib/fileTransferToasts';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (_key: string, values: { count: number }) => `Downloads (${values.count})`,
+ }),
+}));
+afterEach(cleanup);
+
+const transfer = (id: string): FileTransferToast => ({
+ id,
+ name: `${id}.zip`,
+ message: 'Downloading… 25%',
+ variant: 'loading',
+ duration: 0,
+ createdAt: 0,
+ exiting: false,
+ action: { label: 'Cancel', onClick: vi.fn() },
+});
+
+describe('grouped download toast', () => {
+ it('shows a text cancel button for one file and a disclosure for multiple files', () => {
+ const items = ['a', 'b', 'c', 'd'].map(transfer);
+ const view = render(<DownloadToast items={[items[0]]} />);
+ expect(screen.getByText(items[0].message)).toBeTruthy();
+ expect(screen.queryByText(items[0].name)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(items[0].action!.onClick).toHaveBeenCalledOnce();
+ view.rerender(<DownloadToast items={items} />);
+ expect(screen.getAllByRole('status')).toHaveLength(1);
+ expect(screen.queryByRole('list')).toBeNull();
+ const trigger = screen.getByRole('button', { name: 'Downloads (4)' });
+ fireEvent.click(trigger);
+ expect(screen.getAllByRole('listitem')).toHaveLength(4);
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel b.zip' }));
+ expect(items[1].action!.onClick).toHaveBeenCalledOnce();
+ expect(items[2].action!.onClick).not.toHaveBeenCalled();
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.click(trigger);
+ view.rerender(<DownloadToast items={[items[3]]} />);
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.getByText(items[3].message)).toBeTruthy();
+ expect(screen.queryByText(items[3].name)).toBeNull();
+ view.rerender(<DownloadToast items={[]} />);
+ expect(screen.queryByRole('status')).toBeNull();
+ view.rerender(<DownloadToast items={items.slice(0, 2)} />);
+ expect(
+ screen.getByRole('button', { name: 'Downloads (2)' }).getAttribute('aria-expanded'),
+ ).toBe('false');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts b/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts
index 7136111ebb..19f5b3e855 100644
--- a/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { downloadRemoteChatEntry, fetchChatFileWithToasts, openRemoteChatFile } from '../lib/remoteFileOpen';
import { getToastSnapshot, toast } from '../lib/toast';
+import { getFileTransferToasts } from '../lib/fileTransferToasts';
import messages from '../i18n/locales/en/common.json';
import {
createFileTransferProgressValues,
@@ -52,7 +53,7 @@ function emit(
listener({ requestId, workdir, relPath: absPath, received, total, phase });
}
-const active = () => getToastSnapshot().filter((item) => !item.exiting);
+const active = () => [...getFileTransferToasts(), ...getToastSnapshot().filter((item) => !item.exiting)];
beforeEach(() => {
vi.useFakeTimers();
@@ -268,6 +269,31 @@ describe('remote file transfer toasts', () => {
expect(listeners.size).toBe(0);
});
+ it('keeps more than three downloads visible and cancels only the selected request', async () => {
+ const results = Array.from({ length: 4 }, () => deferred<typeof success>());
+ results.forEach((result) => chatFetch.mockReturnValueOnce(result.promise));
+ const pending = results.map((_, index) => fetchChatFileWithToasts(origin, workdir, `${workdir}/${index}.zip`));
+ await vi.advanceTimersByTimeAsync(600);
+ const shown = getFileTransferToasts();
+ expect(shown.map((item) => item.name)).toEqual(['0.zip', '1.zip', '2.zip', '3.zip']);
+ expect(getToastSnapshot().filter((item) => !item.exiting)).toEqual([]);
+ const cancelled = shown[1];
+ cancelled.action!.onClick();
+ cancelled.action!.onClick();
+ expect(chatCancel).toHaveBeenCalledExactlyOnceWith(cancelled.id);
+ emit(cancelled.id, 4096);
+ emit(shown[3].id, 3072);
+ expect(getFileTransferToasts().map((item) => item.name)).toEqual(['0.zip', '2.zip', '3.zip']);
+ expect(getFileTransferToasts()[2].message).toContain('75%');
+ results.forEach((result) => result.resolve(success));
+ expect(await Promise.all(pending)).toEqual([success.cachePath, null, success.cachePath, success.cachePath]);
+ expect(getFileTransferToasts()).toEqual([]);
+ expect(listeners.size).toBe(0);
+ // An old button reference cannot cancel a completed or later request.
+ shown[0].action!.onClick();
+ expect(chatCancel).toHaveBeenCalledTimes(1);
+ });
+
it('keeps stale-copy warnings separate from loading', async () => {
chatFetch.mockResolvedValue({ ...success, stale: true });
await fetchChatFileWithToasts(origin, workdir, absPath);
diff --git a/apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx b/apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx
new file mode 100644
index 0000000000..14da8f5ed2
--- /dev/null
+++ b/apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx
@@ -0,0 +1,82 @@
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import type { FileTransferToast } from '@/lib/fileTransferToasts';
+import { Toast } from './Toast';
+
+export function DownloadToast({ items }: { items: readonly FileTransferToast[] }) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ if (items.length < 2) setOpen(false);
+ }, [items.length]);
+ if (!items.length) return null;
+
+ const first = items[0];
+ return (
+ <div data-download-toast data-toast-id="file-transfers" className="max-w-[calc(100%_-_32px)]">
+ {items.length === 1 ? (
+ <Toast item={first} />
+ ) : (
+ <Popover open={open} onOpenChange={setOpen}>
+ <Toast
+ item={{
+ ...first,
+ message: t('chat.remoteFile.downloadsInProgress', { count: items.length }),
+ action: undefined,
+ }}
+ message={
+ <PopoverTrigger asChild>
+ <Button variant="secondary" tone="quiet" size="sm" compact className="gap-2 text-13">
+ {t('chat.remoteFile.downloadsInProgress', { count: items.length })}
+ {open ? (
+ <ChevronUp className="h-4 w-4 shrink-0" />
+ ) : (
+ <ChevronDown className="h-4 w-4 shrink-0" />
+ )}
+ </Button>
+ </PopoverTrigger>
+ }
+ />
+ <PopoverContent
+ className="pointer-events-auto z-[10101] w-[440px] max-w-[calc(100vw_-_32px)] p-2"
+ sideOffset={8}
+ aria-label={t('chat.remoteFile.downloadsInProgress', { count: items.length })}
+ >
+ <ul className="max-h-[min(360px,60vh)] overflow-y-auto">
+ {items.map((item) => (
+ <li
+ key={item.id}
+ data-download-id={item.id}
+ className="flex items-center gap-3 border-b border-[var(--border-default)] px-2 py-3 last:border-b-0"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="break-words text-13 font-medium leading-5 text-[var(--text-primary)] [overflow-wrap:anywhere]">
+ {item.name}
+ </div>
+ <div className="mt-1 text-12 leading-[18px] tabular-nums text-[var(--text-secondary)] [overflow-wrap:anywhere]">
+ {item.message}
+ </div>
+ </div>
+ <Button
+ variant="secondary"
+ size="sm"
+ compact
+ className="shrink-0"
+ aria-label={`${item.action?.label} ${item.name}`}
+ onClick={item.action?.onClick}
+ >
+ {item.action?.label}
+ </Button>
+ </li>
+ ))}
+ </ul>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/ui/toast/Toast.tsx b/apps/desktop/src/renderer/components/ui/toast/Toast.tsx
index 4746c95b17..29aeb42d6d 100644
--- a/apps/desktop/src/renderer/components/ui/toast/Toast.tsx
+++ b/apps/desktop/src/renderer/components/ui/toast/Toast.tsx
@@ -49,9 +49,11 @@ export const VARIANT_MAP: Record<ToastVariant, VariantMeta> = {
export interface ToastProps {
item: ToastItem;
+ /** Interactive content, such as a disclosure, in place of the plain message. */
+ message?: React.ReactNode;
}
-export function Toast({ item }: ToastProps) {
+export function Toast({ item, message }: ToastProps) {
const meta = VARIANT_MAP[item.variant];
const Icon = meta.icon;
const panelRef = useRef<HTMLDivElement>(null);
@@ -150,7 +152,7 @@ export function Toast({ item }: ToastProps) {
)}
{/* Preserve diagnostic newlines and allow unbroken URLs to fit. */}
- {item.message}
+ {message ?? item.message}
</span>
{item.action && (
diff --git a/apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx b/apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx
index 4b4ff43f42..230c0953f9 100644
--- a/apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx
+++ b/apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx
@@ -3,8 +3,10 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { type ToastItem, getToastSnapshot, subscribeToastStore } from '@/lib/toast';
+import { getFileTransferToasts, subscribeFileTransferToasts } from '@/lib/fileTransferToasts';
import { Toast } from './Toast';
+import { DownloadToast } from './DownloadToast';
// ────────────────────────────────────────────────────────────
// ToastFadeWrapper — 纯 opacity 淡入淡出(整块,无裁切)
@@ -49,6 +51,7 @@ function ToastFadeWrapper({
export function ToastContainer() {
const { t } = useTranslation();
const items = useSyncExternalStore(subscribeToastStore, getToastSnapshot, getToastSnapshot);
+ const transfers = useSyncExternalStore(subscribeFileTransferToasts, getFileTransferToasts, getFileTransferToasts);
const containerRef = useRef<HTMLDivElement>(null);
const prevRectsRef = useRef<Map<string, number>>(new Map());
@@ -108,6 +111,7 @@ export function ToastContainer() {
// z-[10100]: 高于所有 Radix Dialog (z-[10000]),避免 toast 被打开的对话框遮挡
className="pointer-events-none fixed inset-x-0 top-5 z-[10100] flex flex-col items-center gap-[10px]"
>
+ <DownloadToast items={transfers} />
{items.map((item) => (
<ToastFadeWrapper key={item.id} item={item} toastId={item.id}>
<Toast item={item} />
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b46cf95510..1e55115dc0 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11449,7 +11449,8 @@
"downloadUnsupported": "The remote computer can't download folders yet. Update Cindy on that computer and try again",
"downloadNoSpace": "Not enough disk space to finish the download",
"downloadSkipped": "Saved to Downloads, but some files could not be downloaded",
- "cancelTransfer": "Cancel"
+ "cancelTransfer": "Cancel",
+ "downloadsInProgress": "Downloads in progress ({{count}})"
},
"mivoAction": {
"promptPlaceholder": "Type a prompt, press Enter to send",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 368c9ed31a..521c170367 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11398,7 +11398,8 @@
"downloadUnsupported": "リモートコンピュータはまだフォルダのダウンロードに対応していません。そのコンピュータの Cindy を更新してから再試行してください",
"downloadNoSpace": "ディスクの空き容量が足りないため、ダウンロードを完了できません",
"downloadSkipped": "ダウンロードフォルダに保存しましたが、一部のファイルはダウンロードできませんでした",
- "cancelTransfer": "キャンセル"
+ "cancelTransfer": "キャンセル",
+ "downloadsInProgress": "ダウンロード中({{count}} 件)"
},
"mivoAction": {
"promptPlaceholder": "プロンプトを入力し、Enter で送信",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 4d1ff050e6..37b6caf5ca 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11398,7 +11398,8 @@
"downloadUnsupported": "원격 컴퓨터가 아직 폴더 다운로드를 지원하지 않습니다. 해당 컴퓨터의 Cindy를 업데이트한 후 다시 시도하세요",
"downloadNoSpace": "디스크 공간이 부족해 다운로드를 완료할 수 없습니다",
"downloadSkipped": "다운로드 폴더에 저장했지만 일부 파일은 다운로드하지 못했습니다",
- "cancelTransfer": "취소"
+ "cancelTransfer": "취소",
+ "downloadsInProgress": "다운로드 중 ({{count}}개)"
},
"mivoAction": {
"promptPlaceholder": "프롬프트를 입력하고 Enter로 전송",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 34eb5ad4fe..75ab7584ca 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11398,7 +11398,8 @@
"downloadUnsupported": "远程电脑暂不支持下载文件夹,请更新该电脑上的 Cindy 后重试",
"downloadNoSpace": "磁盘空间不足,无法完成下载",
"downloadSkipped": "已下载到「下载」文件夹,但有部分文件未能下载",
- "cancelTransfer": "取消"
+ "cancelTransfer": "取消",
+ "downloadsInProgress": "正在下载 {{count}} 个文件"
},
"mivoAction": {
"promptPlaceholder": "输入提示词,回车发送",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 0a56cc3ea6..6e9cc33e09 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11397,7 +11397,8 @@
"downloadUnsupported": "遠端電腦暫不支援下載資料夾,請更新該電腦上的 Cindy 後重試",
"downloadNoSpace": "磁碟空間不足,無法完成下載",
"downloadSkipped": "已下載到「下載項目」資料夾,但有部分檔案未能下載",
- "cancelTransfer": "取消"
+ "cancelTransfer": "取消",
+ "downloadsInProgress": "正在下載 {{count}} 個檔案"
},
"mivoAction": {
"promptPlaceholder": "輸入提示詞,按 Enter 傳送",
diff --git a/apps/desktop/src/renderer/lib/fileTransferProgress.ts b/apps/desktop/src/renderer/lib/fileTransferProgress.ts
index b9944ade82..922922742c 100644
--- a/apps/desktop/src/renderer/lib/fileTransferProgress.ts
+++ b/apps/desktop/src/renderer/lib/fileTransferProgress.ts
@@ -1,6 +1,6 @@
import { i18n } from '@/i18n';
import { formatBytes } from '@/features/cc-agent/workdir-browse/lib/fileMeta';
-import { toast } from './toast';
+import { addFileTransferToast, removeFileTransferToast, updateFileTransferToast } from './fileTransferToasts';
export type FileTransferProgress = {
received: number;
@@ -74,22 +74,30 @@ export function observeFileTransferProgressText(onProgress: (text: string) => vo
* Its Cancel button aborts the chatFetch / chatDownload started with `requestId`;
* callers check `cancelled` and skip the follow-up action and failure toast.
*/
-export function createFileTransferToast() {
- let id: string | null = null;
+export function createFileTransferToast(absPath: string) {
let cancelled = false;
+ let disposed = false;
let text = i18n.t('chat.remoteFile.fetching');
const progress = observeFileTransferProgressText((next) => {
text = next;
- if (id) toast.update(id, text);
+ updateFileTransferToast(progress.requestId, text);
});
const delayed = setTimeout(() => {
- id = toast.loading(text, {
+ addFileTransferToast({
+ id: progress.requestId,
+ name: absPath.split(/[\\/]/).filter(Boolean).at(-1) ?? absPath,
+ message: text,
+ variant: 'loading',
+ duration: 0,
+ createdAt: Date.now(),
+ exiting: false,
action: {
label: i18n.t('chat.remoteFile.cancelTransfer'),
onClick: () => {
- // The toast dismisses itself after the action runs.
+ if (cancelled || disposed) return;
cancelled = true;
- id = null;
+ progress.dispose();
+ removeFileTransferToast(progress.requestId);
void window.electronAPI.fileBrowser.chatCancel(progress.requestId).catch(() => {});
},
},
@@ -101,9 +109,11 @@ export function createFileTransferToast() {
return cancelled;
},
dispose() {
+ if (disposed) return;
+ disposed = true;
clearTimeout(delayed);
progress.dispose();
- if (id) toast.dismiss(id);
+ removeFileTransferToast(progress.requestId);
},
};
}
diff --git a/apps/desktop/src/renderer/lib/fileTransferToasts.ts b/apps/desktop/src/renderer/lib/fileTransferToasts.ts
new file mode 100644
index 0000000000..0442c4056e
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/fileTransferToasts.ts
@@ -0,0 +1,33 @@
+import type { ToastItem } from './toast';
+
+export type FileTransferToast = ToastItem & { name: string };
+
+// Transfers share one notification, independent of the ordinary toast queue's limit.
+let items: readonly FileTransferToast[] = [];
+const listeners = new Set<() => void>();
+
+function publish(next: readonly FileTransferToast[]) {
+ items = next;
+ for (const listener of listeners) listener();
+}
+
+export const getFileTransferToasts = () => items;
+export function subscribeFileTransferToasts(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export function addFileTransferToast(item: FileTransferToast) {
+ publish([...items, item]);
+}
+
+export function updateFileTransferToast(id: string, message: string) {
+ if (!items.some((item) => item.id === id && item.message !== message)) return;
+ publish(items.map((item) => (item.id === id ? { ...item, message } : item)));
+}
+
+export function removeFileTransferToast(id: string) {
+ if (items.some((item) => item.id === id)) publish(items.filter((item) => item.id !== id));
+}
diff --git a/apps/desktop/src/renderer/lib/remoteFileOpen.ts b/apps/desktop/src/renderer/lib/remoteFileOpen.ts
index 2b86cb37d2..31c442aad8 100644
--- a/apps/desktop/src/renderer/lib/remoteFileOpen.ts
+++ b/apps/desktop/src/renderer/lib/remoteFileOpen.ts
@@ -76,7 +76,7 @@ export async function fetchChatFileWithToasts(
workdir: string,
absPath: string,
): Promise<string | null> {
- const progress = createFileTransferToast();
+ const progress = createFileTransferToast(absPath);
try {
const res = await fetchChatFileToCache(origin, workdir, absPath, progress.requestId);
if (progress.cancelled) return null;
@@ -133,7 +133,7 @@ export async function downloadRemoteChatEntry(
workdir: string,
absPath: string,
): Promise<void> {
- const progress = createFileTransferToast();
+ const progress = createFileTransferToast(absPath);
const wireOrigin =
origin.kind === 'device'
? ({ kind: 'device', deviceId: origin.deviceId } as const)