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(task-copy): 复制进行中可取消或转后台,进度条改用统一样式 (#5324)

Dashe7660fda1d4a
diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
index 35db37fc14..e4a4f7340a 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -576,6 +576,26 @@ describe('resumable cross-computer copy', () => {
expect(state.uploadedProgress).toHaveBeenCalled();
expect(result.progress).toBeUndefined();
});
+ it('cancels a running upload before the target receives it and removes source staging', async () => {
+ let cancel: Promise<Awaited<ReturnType<typeof requestTaskMigration>>> | undefined;
+ state.uploadedProgress.mockImplementation(async () => {
+ cancel ??= requestTaskMigration({ action: 'cancel', sessionId: 'fork' });
+ });
+ expect((await start()).cancellable).toBe(true);
+ const status = await settled();
+ expect(await cancel).toMatchObject({ running: true, cancelling: true });
+ expect(status.stage).toBe('cancelled');
+ expect(status.error).toBeUndefined();
+ expect(state.imports).not.toHaveBeenCalled();
+ expect(state.remove.mock.calls.map(([key]) => key)).toEqual([...state.files.keys()]);
+ await expect(
+ fs.stat(path.join(state.root, 'A', 'task-copies', 'outgoing', status.targetSessionId!)),
+ ).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(await fs.readFile(path.join(state.root, 'shared', 'draft'), 'utf8')).toBe('original');
+ state.uploadedProgress.mockReset();
+ await start();
+ expect((await settled()).stage).toBe('complete');
+ });
it('closing a failed transfer removes source staging without deleting an already committed target', async () => {
state.loseReply = 'receive';
await start();
@@ -761,6 +781,19 @@ describe('resumable cross-computer copy', () => {
expect((await settled()).stage).toBe('complete');
expect(state.imports).toHaveBeenCalledTimes(1);
});
+ it('refuses to cancel a resumed transfer before its receipt rules out a target import', async () => {
+ state.loseReply = 'receive';
+ await start();
+ expect((await settled()).stage).toBe('transferring');
+ const retry = await requestTaskMigration({ action: 'retry', sessionId: 'fork' });
+ expect(retry.running).toBe(true);
+ expect(retry.cancellable).toBeUndefined();
+ await expect(requestTaskMigration({ action: 'cancel', sessionId: 'fork' })).rejects.toThrow(
+ 'MIGRATION_CANNOT_CANCEL',
+ );
+ expect((await settled()).stage).toBe('complete');
+ expect(state.imports).toHaveBeenCalledTimes(1);
+ });
it('allows another independent copy after completion', async () => {
await start();
const first = await settled();
@@ -882,7 +915,10 @@ describe('resumable cross-computer copy', () => {
it('stops copying when source media exists but could not be packaged', async () => {
state.exportMedia = { mediaMissing: 1, mediaDropped: 1 };
await start();
- expect(await settled()).toMatchObject({ stage: 'preparing', error: 'MIGRATION_INCOMPLETE_CONTEXT' });
+ expect(await settled()).toMatchObject({
+ stage: 'preparing',
+ error: 'MIGRATION_INCOMPLETE_CONTEXT',
+ });
expect(state.imports).not.toHaveBeenCalled();
});
it('discards a snapshot when a new turn finishes during preparation', async () => {
diff --git a/apps/desktop/src/main/task-migration/handoff.ts b/apps/desktop/src/main/task-migration/handoff.ts
index 68c0720efe..45e6b6358f 100644
--- a/apps/desktop/src/main/task-migration/handoff.ts
+++ b/apps/desktop/src/main/task-migration/handoff.ts
@@ -47,6 +47,6 @@ export async function advanceHandoff(
export function canCancelHandoff(record: MigrationHandoff): boolean {
// Abandon only source staging. Never roll back a target that may have committed.
- // The service rejects cancellation while a local transfer is still running.
+ // A running copy is cancelled only before the target starts receiving it.
return record.stage === 'preparing' || record.stage === 'transferring';
}
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index 225b5be5fc..902a4db1f1 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -72,7 +72,13 @@ type MoveProject = (
// Bootstrap supplies the existing business handler; importing maker IPC here creates a cycle.
let moveProjectOnHost: MoveProject | undefined;
let sourceBoundary: { isBusy(sessionId: string): boolean; drain(): Promise<void> } | undefined;
-const running = new Map<string, { progress?: TaskMigrationView['progress'] }>();
+interface RunningCopy {
+ progress?: TaskMigrationView['progress'];
+ /** The target may commit from here on; cancelling would orphan its copy. */
+ committing?: boolean;
+ cancelRequested?: boolean;
+}
+const running = new Map<string, RunningCopy>();
const errorCode = (error: unknown): string => {
if ((error as NodeJS.ErrnoException)?.code === 'ENOSPC') return 'MIGRATION_NO_SPACE';
const message = error instanceof Error ? error.message : '';
@@ -156,14 +162,20 @@ async function invoke(
return result;
}
function view(scope: Scope, record: MigrationRecord | null): TaskMigrationView {
+ const live = record ? running.get(`${scope.root}:${record.sessionId}`) : undefined;
return {
supported: true,
deviceId: selfId(),
...(record
? {
stage: record.stage,
- running: running.has(`${scope.root}:${record.sessionId}`),
- progress: running.get(`${scope.root}:${record.sessionId}`)?.progress,
+ running: !!live,
+ progress: live?.progress,
+ ...(live?.cancelRequested
+ ? { cancelling: true as const }
+ : live && !live.committing && record.kind === 'outgoing'
+ ? { cancellable: true as const }
+ : {}),
...(record.kind === 'outgoing'
? {
targetDeviceId: record.targetDeviceId,
@@ -417,10 +429,11 @@ async function sendPart(
}
onProgress?.(0); // OSS fallback starts this part again, not a second completed part.
const result = await uploadLocalFile(file, { maxBytes: (await fs.stat(file)).size, onProgress });
- scope.assertCurrent();
+ // Record the upload before the checkpoint so a cancelled copy still deletes it.
const keysFile = path.join(artifacts, 'transfer-keys.json');
const keys = JSON.parse(readAtomicFileSync(keysFile) ?? '[]') as string[];
atomicWriteFileSync(keysFile, JSON.stringify([...keys, result.key]));
+ scope.assertCurrent();
return {
ref: buildAttachmentOssRef({ ossKey: result.key, size: result.size, sha256: result.sha256 }),
size: result.size,
@@ -493,12 +506,17 @@ async function checkTargetResources(
scope.assertCurrent();
}
async function transfer(scope: Scope, record: MigrationHandoff) {
+ const live = running.get(`${scope.root}:${record.sessionId}`)!;
+ // A retried transfer may follow a lost receive reply; until the target proves it has
+ // no receipt for this copy, it may be importing or already committed.
+ live.committing = true;
const existing = await invoke(
record.targetDeviceId,
{ action: 'receipt', id: record.id, sourceSessionId: record.sessionId },
scope,
);
if (existing.stage === 'active') return;
+ if (!existing.stage) live.committing = false;
const directory = path.join(scope.root, 'outgoing', record.id);
const workspace = JSON.parse(
readAtomicFileSync(path.join(directory, 'workspace.json')) ?? 'null',
@@ -517,7 +535,6 @@ async function transfer(scope: Scope, record: MigrationHandoff) {
}
scope.assertCurrent();
const resources = await preflight(scope, record, workspace, directory);
- const live = running.get(`${scope.root}:${record.sessionId}`)!;
const startedAt = Date.now();
let completed = 0;
live.progress = {
@@ -564,6 +581,8 @@ async function transfer(scope: Scope, record: MigrationHandoff) {
}
}
live.progress = { ...live.progress!, phase: 'finishing', bytesPerSecond: 0 };
+ // A cancel accepted before this point still aborts in invoke's preSend check.
+ live.committing = true;
const result = await invoke(
record.targetDeviceId,
{
@@ -595,7 +614,17 @@ async function cleanupOutgoing(scope: Scope, record: MigrationHandoff) {
function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {
const key = `${scope.root}:${record.sessionId}`;
if (running.has(key)) return;
- running.set(key, {});
+ // See transfer(): a resumed transfer stays non-cancellable until its receipt is checked.
+ const live: RunningCopy = { committing: record.stage !== 'preparing' };
+ running.set(key, live);
+ // Every existing checkpoint doubles as a cancellation point for this copy.
+ const copyScope: Scope = {
+ ...scope,
+ assertCurrent: () => {
+ scope.assertCurrent();
+ if (live.cancelRequested) throw new Error('MIGRATION_CANCELLED');
+ },
+ };
void withCrossProcessLock(
path.join(scope.root, `source-${record.sessionId}.lock`),
{ label: 'task-migration', waitMs: 0 },
@@ -603,13 +632,24 @@ function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {
if (!lock.held) return;
const current = scope.read(record.sessionId);
if (!current || current.kind !== 'outgoing' || current.id !== record.id) return;
- await advanceHandoff(current, {
- assertCurrent: scope.assertCurrent,
- save: async (next) => scope.save({ ...next, kind: 'outgoing' }),
- prepare: (r) => prepare(scope, r),
- import: (r) => transfer(scope, r),
- cleanup: (r) => cleanupOutgoing(scope, r),
- });
+ try {
+ await advanceHandoff(current, {
+ assertCurrent: copyScope.assertCurrent,
+ save: async (next) => scope.save({ ...next, kind: 'outgoing' }),
+ prepare: (r) => prepare(copyScope, r),
+ import: (r) => transfer(copyScope, r),
+ cleanup: (r) => cleanupOutgoing(copyScope, r),
+ });
+ } catch (error) {
+ if (!live.cancelRequested) throw error;
+ // Same cleanup as cancelling a stopped copy, still under this copy's lock.
+ scope.assertCurrent();
+ const latest = scope.read(record.sessionId);
+ if (latest?.kind !== 'outgoing' || latest.id !== record.id) return;
+ await cleanupOutgoing(scope, latest);
+ scope.assertCurrent();
+ scope.save({ ...latest, stage: 'cancelled', error: undefined });
+ }
},
)
.catch((error) => {
@@ -976,6 +1016,15 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationV
throw new Error('MIGRATION_INVALID_REQUEST');
}
if (request.action === 'status') return view(scope, scope.read(request.sessionId));
+ if (request.action === 'cancel') {
+ // A running copy holds the source lock; signal it instead of waiting for the lock.
+ const live = running.get(`${scope.root}:${request.sessionId}`);
+ if (live) {
+ if (live.committing) throw new Error('MIGRATION_CANNOT_CANCEL');
+ live.cancelRequested = true;
+ return view(scope, scope.read(request.sessionId));
+ }
+ }
await fs.mkdir(scope.root, { recursive: true, mode: 0o700 });
scope.assertCurrent();
const initialMembers =
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
index ab7c2f5e36..89e6082271 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx
@@ -10,6 +10,7 @@ import {
import type { Session } from '@/lib/ccAgent.types';
import type { TaskMoveDestination } from './TaskMoveSubmenu';
import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
import { Select } from '@/components/ui/select';
import { FormField } from '@/components/ui/form-field';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
@@ -242,9 +243,21 @@ export function TaskMigrationDialog({
? destination.deviceName
: t('taskMigration.selectedComputer')));
const closeCancels = started && !status?.running;
+ const cancelling = copying && !!status?.cancelling;
+ const cancelRequested = useRef(false);
+ const cancelCopy = () => {
+ cancelRequested.current = true;
+ void act({ action: 'cancel', sessionId: session.id });
+ };
+ useEffect(() => {
+ // The running copy unwinds asynchronously; close once it has fully stopped.
+ if (cancelRequested.current && status?.stage === 'cancelled' && !status.running) onDismiss();
+ }, [status?.stage, status?.running]);
const dismiss = () => {
- if (pending.current || copying) return;
- if (closeCancels) void act({ action: 'cancel', sessionId: session.id }, true);
+ if (pending.current) return;
+ // Closing never stops a running copy; the source task header reopens this view.
+ if (copying) onDismiss();
+ else if (closeCancels) void act({ action: 'cancel', sessionId: session.id }, true);
else onDismiss();
};
const progress = status?.progress;
@@ -383,21 +396,36 @@ export function TaskMigrationDialog({
)}
{copying && (
<div className="mt-4 space-y-2">
- <p className="text-sm text-[var(--confirm-title)]" role="status">
+ <p
+ className="flex items-center gap-2 text-sm text-[var(--confirm-title)]"
+ role="status"
+ >
+ <Spinner size={14} className="shrink-0 text-[var(--confirm-desc)]" />
{t(
- progress?.phase === 'finishing'
- ? 'taskMigration.finishing'
- : `taskMigration.stages.${status?.stage ?? 'preparing'}`,
+ cancelling
+ ? 'taskMigration.cancelling'
+ : progress?.phase === 'finishing'
+ ? 'taskMigration.finishing'
+ : `taskMigration.stages.${status?.stage ?? 'preparing'}`,
{ name: computerName },
)}
</p>
- <progress
- className="w-full accent-[var(--confirm-title)]"
+ <div
+ role="progressbar"
aria-label={t('taskMigration.copyingTitle', { name: computerName })}
- max={100}
- value={percent}
- />
- {progress?.phase === 'sending' && (
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={percent}
+ className="h-1.5 overflow-hidden rounded-full bg-[var(--surface-chip)]"
+ >
+ {percent !== undefined && (
+ <div
+ className="h-full rounded-full bg-[var(--accent-cta-bg)] transition-[width] duration-[var(--motion-base)] ease-[var(--motion-ease-move)]"
+ style={{ width: `${percent}%` }}
+ />
+ )}
+ </div>
+ {progress?.phase === 'sending' && !cancelling && (
<p className="text-sm tabular-nums text-[var(--confirm-desc)]">
{t('taskMigration.transferProgress', {
sent: bytes(progress.sentBytes),
@@ -414,7 +442,18 @@ export function TaskMigrationDialog({
</p>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
- {!copying && (
+ {copying ? (
+ <>
+ {status?.cancellable && (
+ <Button variant="secondary" disabled={busy} onClick={cancelCopy}>
+ {t('taskMigration.cancelCopy')}
+ </Button>
+ )}
+ <Button variant="secondary" disabled={busy} onClick={dismiss}>
+ {t('taskMigration.runInBackground')}
+ </Button>
+ </>
+ ) : (
<Button variant="secondary" disabled={busy} onClick={dismiss}>
{t(confirming ? 'taskMigration.cancel' : 'taskMigration.close')}
</Button>
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx
index 390139a1c5..1fd5e39bd4 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx
@@ -253,10 +253,13 @@ it('keeps transfer progress in the dialog until the target completes, including
);
mount();
await screen.findByRole('progressbar');
- expect(screen.getByRole('progressbar').hasAttribute('value')).toBe(false);
+ expect(screen.getByRole('progressbar').hasAttribute('aria-valuenow')).toBe(false);
expect(screen.queryByRole('button', { name: 'taskMigration.close' })).toBeNull();
+ // Older hosts do not report cancellable, so only the background option is offered.
+ expect(screen.queryByRole('button', { name: 'taskMigration.cancelCopy' })).toBeNull();
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
- expect(state.dismiss).not.toHaveBeenCalled();
+ expect(state.dismiss).toHaveBeenCalledOnce();
+ expect(state.request.mock.calls.some(([, command]) => command.action === 'cancel')).toBe(false);
snapshot = {
stage: 'transferring',
running: true,
@@ -267,9 +270,10 @@ it('keeps transfer progress in the dialog until the target completes, including
bytesPerSecond: 10,
},
};
- await waitFor(() => expect(screen.getByRole('progressbar').getAttribute('value')).toBe('25'), {
- timeout: 2500,
- });
+ await waitFor(
+ () => expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('25'),
+ { timeout: 2500 },
+ );
expect(screen.getByText('taskMigration.transferProgress')).toBeTruthy();
snapshot = {
stage: 'transferring',
@@ -290,6 +294,31 @@ it('keeps transfer progress in the dialog until the target completes, including
expect(screen.getAllByRole('button')).toHaveLength(2);
});
+it('cancels a running copy and closes once the source has stopped it', async () => {
+ let snapshot: Record<string, unknown> = {
+ stage: 'transferring',
+ running: true,
+ cancellable: true,
+ };
+ state.request.mockImplementation(async (_device, command) => {
+ if (command.action === 'cancel')
+ snapshot = { stage: 'transferring', running: true, cancelling: true };
+ return command.action === 'status' || command.action === 'cancel'
+ ? snapshot
+ : { deviceId: 'local', projects: [] };
+ });
+ mount();
+ fireEvent.click(await screen.findByRole('button', { name: 'taskMigration.cancelCopy' }));
+ await waitFor(() =>
+ expect(state.request).toHaveBeenCalledWith('A', { action: 'cancel', sessionId: 'task' }),
+ );
+ await screen.findByText('taskMigration.cancelling');
+ expect(screen.queryByRole('button', { name: 'taskMigration.cancelCopy' })).toBeNull();
+ expect(state.dismiss).not.toHaveBeenCalled();
+ snapshot = { stage: 'cancelled', running: false };
+ await waitFor(() => expect(state.dismiss).toHaveBeenCalledOnce(), { timeout: 2500 });
+});
+
it('a new destination selection does not reopen the previous copy success screen', async () => {
state.request.mockImplementation(async (_device, command) =>
command.action === 'status'
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 235eb1fc3c..b83296b09b 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -46,12 +46,16 @@
"MIGRATION_UNSUPPORTED": "Update both computers to a version that supports task copy.",
"MIGRATION_TASK_QUEUED": "This task has queued messages. Finish or remove them before copying it.",
"MIGRATION_SOURCE_CHANGED": "The source task changed during preparation. Retry the copy.",
- "MIGRATION_TIMEOUT": "The source computer did not respond in time. Try again later."
+ "MIGRATION_TIMEOUT": "The source computer did not respond in time. Try again later.",
+ "MIGRATION_CANNOT_CANCEL": "The target computer has started creating the task. The copy can no longer be cancelled."
},
"successTitle": "Copy successful",
"successDescription": "Copied to {{name}}.",
"copyingTitle": "Copying to {{name}}",
- "keepOpen": "Copying to {{name}}. Please wait until it finishes.",
+ "keepOpen": "Copying to {{name}}. Closing this window won't stop the copy; check progress at the top of the original task.",
+ "runInBackground": "Continue in background",
+ "cancelCopy": "Cancel copy",
+ "cancelling": "Cancelling. Stops after the current file finishes sending…",
"failureTitle": "Copy failed",
"failureDescription": "Close this window and start a new copy from the task menu.",
"finishing": "{{name}} is receiving, checking and creating the task…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c3f7931f0b..1b7ed1e9bf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -46,12 +46,16 @@
"MIGRATION_UNSUPPORTED": "両方のコンピューターをタスクのコピーに対応したバージョンに更新してください。",
"MIGRATION_TASK_QUEUED": "このタスクには待機中のメッセージがあります。処理または削除してからコピーしてください。",
"MIGRATION_SOURCE_CHANGED": "準備中に元のタスクが変更されました。コピーを再試行してください。",
- "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。"
+ "MIGRATION_TIMEOUT": "コピー元のコンピューターが時間内に応答しませんでした。しばらくしてから再試行してください。",
+ "MIGRATION_CANNOT_CANCEL": "移行先のコンピューターでタスクの作成が始まったため、キャンセルできません。"
},
"successTitle": "コピー完了",
"successDescription": "{{name}}にコピーしました。",
"copyingTitle": "{{name}}にコピー中",
- "keepOpen": "{{name}}にコピーしています。完了までお待ちください。",
+ "keepOpen": "{{name}}にコピーしています。このウィンドウを閉じてもコピーは続行され、元のタスク上部で進捗を確認できます。",
+ "runInBackground": "バックグラウンドで続行",
+ "cancelCopy": "コピーをキャンセル",
+ "cancelling": "キャンセルしています。現在のファイルの送信が終わると停止します…",
"failureTitle": "コピー失敗",
"failureDescription": "閉じた後、タスクメニューから新しくコピーできます。",
"finishing": "{{name}}で受信・検証し、タスクを作成中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 5281daf8e1..8d6cd7fe2e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -46,12 +46,16 @@
"MIGRATION_UNSUPPORTED": "두 컴퓨터 모두 작업 복사을 지원하는 버전으로 업데이트하세요.",
"MIGRATION_TASK_QUEUED": "이 작업에 대기 중인 메시지가 있습니다. 처리하거나 삭제한 후 복사하세요.",
"MIGRATION_SOURCE_CHANGED": "준비 중 원본 작업이 변경되었습니다. 복사를 다시 시도하세요.",
- "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요."
+ "MIGRATION_TIMEOUT": "원본 컴퓨터가 제한 시간 내에 응답하지 않았습니다. 잠시 후 다시 시도하세요.",
+ "MIGRATION_CANNOT_CANCEL": "대상 컴퓨터에서 작업 생성이 시작되어 더 이상 취소할 수 없습니다."
},
"successTitle": "복사 완료",
"successDescription": "{{name}}에 복사했습니다.",
"copyingTitle": "{{name}}로 복사 중",
- "keepOpen": "{{name}}로 복사 중입니다. 완료될 때까지 기다려 주세요.",
+ "keepOpen": "{{name}}로 복사 중입니다. 창을 닫아도 복사는 계속되며, 원본 작업 상단에서 진행 상황을 확인할 수 있습니다.",
+ "runInBackground": "백그라운드에서 계속",
+ "cancelCopy": "복사 취소",
+ "cancelling": "취소하는 중입니다. 현재 파일 전송이 끝나면 중지됩니다…",
"failureTitle": "복사 실패",
"failureDescription": "창을 닫은 후 작업 메뉴에서 새로 복사할 수 있습니다.",
"finishing": "{{name}}에서 수신, 검증 및 작업 생성 중…",
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 b15d043951..d5c41d3762 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -46,12 +46,16 @@
"MIGRATION_UNSUPPORTED": "请将两台电脑更新至支持任务复制的版本。",
"MIGRATION_TASK_QUEUED": "此任务有排队中的消息,请先完成或移除这些消息再复制。",
"MIGRATION_SOURCE_CHANGED": "准备期间源任务发生变化,请重试复制。",
- "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。"
+ "MIGRATION_TIMEOUT": "任务所在电脑响应超时,请稍后重试。",
+ "MIGRATION_CANNOT_CANCEL": "目标电脑已开始创建任务,无法再取消。"
},
"successTitle": "复制成功",
"successDescription": "已复制到{{name}}。",
"copyingTitle": "正在复制到{{name}}",
- "keepOpen": "正在复制到{{name}},请等待完成。",
+ "keepOpen": "正在复制到{{name}}。关闭窗口不会中断复制,可在原任务顶部查看进度。",
+ "runInBackground": "后台继续",
+ "cancelCopy": "取消复制",
+ "cancelling": "正在取消,当前文件发送完后停止…",
"failureTitle": "复制失败",
"failureDescription": "关闭后可从任务菜单重新发起复制。",
"finishing": "{{name}}正在接收、校验并创建任务…",
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 4c20bb734e..590cb06913 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -46,12 +46,16 @@
"MIGRATION_UNSUPPORTED": "請將兩台電腦更新至支援任務複製的版本。",
"MIGRATION_TASK_QUEUED": "此任務有排隊中的訊息,請先完成或移除這些訊息再複製。",
"MIGRATION_SOURCE_CHANGED": "準備期間來源任務發生變更,請重試複製。",
- "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。"
+ "MIGRATION_TIMEOUT": "任務所在電腦回應逾時,請稍後重試。",
+ "MIGRATION_CANNOT_CANCEL": "目標電腦已開始建立任務,無法再取消。"
},
"successTitle": "複製成功",
"successDescription": "已複製到{{name}}。",
"copyingTitle": "正在複製到{{name}}",
- "keepOpen": "正在複製到{{name}},請等待完成。",
+ "keepOpen": "正在複製到{{name}}。關閉視窗不會中斷複製,可在原任務頂部查看進度。",
+ "runInBackground": "背景繼續",
+ "cancelCopy": "取消複製",
+ "cancelling": "正在取消,目前檔案傳送完後停止…",
"failureTitle": "複製失敗",
"failureDescription": "關閉後可從任務選單重新發起複製。",
"finishing": "{{name}}正在接收、驗證並建立任務…",
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 386aef1d00..bae4de93d2 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -50,6 +50,7 @@ warn/warning 状态检查项、等待或处理中的检查项和 warning issue
整组 Orca 沿用可选 `teamMigration: true` 能力声明,缺省不支持;
`receive.files.additionalWorkspaces` 沿用同一文件描述,manifest 记录成员到目录的映射。
双方必须支持复制通道;收到整组能力声明才发送团队,不尝试部分导入。
+运行中取消由源端状态的可选 `cancellable` / `cancelling` 声明,旧源端缺省时控制端不提供取消。
范围、恢复与源目录保护见 [同机移动与跨电脑复制任务](../product-rules/task-device-migration.md)。
设备互联生成文件沿用远端文件服务的 stat 与修改时间,控制端按被控端消息时间窗校验命令产物;
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index 57f3c1cb44..a7adbc9559 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -30,13 +30,18 @@
`copyEstimate` 能力存在时才调用 `estimate`;旧源端无法统计时明确提示连接/版本检查,不开始复制。
统计在任务所在电脑上按 3 分钟截止(本机任务同样适用;文件系统调用本身卡住时无法中断,属已知边界),超时时提示项目文件过多,不提示连接/版本;项目文件超过 50 万个时提前停止统计,
提示改为复制文件更少的项目,不开始复制。该上限只是确认页的准入检查,复制本身仍不设总量上限。
-6. 复制全程保留弹窗,不提供隐藏到后台的入口;准备阶段显示不定进度,发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。
+6. 复制进行中的弹窗可通过「后台继续」或 Esc 关闭,关闭不中断复制,之后从原任务顶部的复制状态重新查看进度
+ (2026-10-01 用户要求,替代此前“全程保留弹窗、不提供隐藏到后台入口”的口径)。准备阶段显示 Spinner 与空进度条,
+ 发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。
+ 源端声明 `cancellable` 时提供「取消复制」:在目标开始接收前,于既有检查点中止(正在发送的文件发完后生效),
+ 清理已上传的 OSS 对象及本地暂存并记为已取消,弹窗显示 `cancelling` 直到停稳后关闭;目标开始接收后拒绝取消
+ (`MIGRATION_CANNOT_CANCEL`),不回滚目标;重试中的复制在回执确认目标没有这次复制的接收记录前同样不可取消。旧源端不声明 `cancellable`,只提供后台继续。
OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。
文件发送结束后显示目标端接收、校验与创建任务阶段,只有目标完成且源端清理结束后才显示“复制成功”。
成功页只提供关闭和“打开新复制的任务”。失败页只提供关闭,关闭会复用完成路径清理已上传的 OSS 对象及本地暂存,结束本次源端复制;目标端可能已提交的副本不会回滚。
再次复制从任务菜单发起。宿主异常退出后的既有幂等恢复协议保留,不自动重试。
-源端仅记录 `preparing → transferring → complete`(停止运行后可结束本次复制);目标记录接收与完成。
+源端仅记录 `preparing → transferring → complete`(运行中在目标接收前、或停止运行后可结束为 `cancelled`);目标记录接收与完成。
开始、取消和后台复制复用同一个源任务标识的既有跨进程锁,防止多实例覆盖同一进度。
进度日志不用于限制源任务的输入、改名、标签、Goal、共享或团队操作,不扫描其它任务日志。
旧交接日志不会让任务只读。新副本不复制调度、渠道和共享授权绑定;原绑定继续使用原任务。
diff --git a/packages/device-link/src/taskMigration.ts b/packages/device-link/src/taskMigration.ts
index 41f55133c1..79d560c8a6 100644
--- a/packages/device-link/src/taskMigration.ts
+++ b/packages/device-link/src/taskMigration.ts
@@ -71,6 +71,10 @@ export interface TaskMigrationView {
estimate?: { fileCount: number; bytes: number };
copyEstimate?: true;
running?: boolean;
+ /** A running copy accepts `cancel` (source staging only). Absent on older hosts. */
+ cancellable?: true;
+ /** `cancel` was accepted; the running copy is unwinding. Absent on older hosts. */
+ cancelling?: true;
/** Optional live source-side upload telemetry; absent on older hosts. Never persisted. */
progress?: {
phase: "sending" | "finishing";