Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(archive): 归档绑定自动化的任务前先确认
Dash57c871e46299
diff --git a/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts b/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.tsindex b14a52563e..99a8ebd757 100644--- a/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarUpperSingleButton.test.ts@@ -112,7 +112,7 @@ describe('archive dirty-worktree warning', () => {it('only skips the archive dialog when the preflight confirms the worktree is clean', () => {// 钉的是预检顺序与放行判据,不是排版:末段用 [\s\S]*? 容忍换行。// · 菜单归档与行内 archive-now 共用 isArchiveLike 这一条无弹窗路径 ——- // 归档可逆,只有 worktree 有情况才升级到 ConfirmDialog;+ // 归档可逆,只有 worktree 有情况或绑定了 active 自动化才升级到 ConfirmDialog;// · 判据必须是 `preflight !== 'clean'`,**不能**退回布尔的「不是脏的就放行」:// 预检失败是 'unknown',塌成放行就会静默回收带未提交改动的 worktree// (greptile review);@@ -122,7 +122,7 @@ describe('archive dirty-worktree warning', () => {// 让 handleActionClick 的 useCallback deps 保持稳定,见 sessionRowRenderIsolation// 的行渲染隔离不变量。expect(sidebarSource).toMatch(- /if \(isArchiveLike\) \{[\s\S]*?resolveWorktreeRemovalPreflight\([\s\S]*?if \(preflight !== 'clean'\) \{[\s\S]*?setConfirm\(\{[\s\S]*?action: 'archive',[\s\S]*?dirtyWorktree: preflight === 'dirty',[\s\S]*?\}\);[\s\S]*?return;[\s\S]*?await runSessionAction\(sessionId, 'archive', \{[\s\S]*?activeSessionId: viewedSessionIdRef\.current,[\s\S]*?\}\);/,+ /if \(isArchiveLike\) \{[\s\S]*?resolveWorktreeRemovalPreflight\([\s\S]*?if \(preflight !== 'clean' \|\| scheduleNames\.length > 0\) \{[\s\S]*?setConfirm\(\{[\s\S]*?action: 'archive',[\s\S]*?dirtyWorktree: preflight === 'dirty',[\s\S]*?scheduleNames,[\s\S]*?\}\);[\s\S]*?return;[\s\S]*?await runSessionAction\(sessionId, 'archive', \{[\s\S]*?activeSessionId: viewedSessionIdRef\.current,[\s\S]*?\}\);/,);});@@ -136,6 +136,11 @@ describe('archive dirty-worktree warning', () => {expect(archiveBranch!.indexOf('blockedByAttachment()')).toBeLessThan(archiveBranch!.indexOf('resolveWorktreeRemovalPreflight('),);+ // 自动化绑定读本地缓存,也排在预检之前。+ expect(archiveBranch!.indexOf('loadActiveBoundScheduleNames(')).toBeGreaterThan(-1);+ expect(archiveBranch!.indexOf('loadActiveBoundScheduleNames(')).toBeLessThan(+ archiveBranch!.indexOf('resolveWorktreeRemovalPreflight('),+ );});it('keeps the delete confirm dialog — deletion is irreversible', () => {diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex ce3aeea22f..f665fdb6ad 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -308,6 +308,11 @@ import {useDeleteScheduleWithSessions,type DeletedScheduleGeneratedSessionResult,} from '@/features/scheduler/hooks/useDeleteScheduleWithSessions';+import {+ archiveConfirmDescription,+ archiveScheduleWarningMany,+ loadActiveBoundScheduleNames,+} from '@/features/scheduler/lib/archiveScheduleWarning';import { resolveDialogueDeviceTarget, type DialogueDeviceTarget } from './lib/dialogueCreateTarget';import { makeDialogueNewMakerRouteState } from './lib/newMakerRouteState';import { makeGenericNewMakerRouteState } from './lib/genericNewMakerRouteState';@@ -868,6 +873,8 @@ interface ConfirmState {action: 'delete' | 'archive';/** P1: 会话 worktree 有未提交更改 → 确认文案追加警告(打开前预检)。 */dirtyWorktree: boolean;+ /** 归档会暂停的 active 自动化名称(仅 archive;为空则不提示)。 */+ scheduleNames?: readonly string[];/** Owned shared task to close before the confirmed archive/delete. */sharedTaskId?: string;}@@ -877,6 +884,7 @@ const CONFIRM_INITIAL: ConfirmState = {sessionId: '',action: 'delete',dirtyWorktree: false,+ scheduleNames: undefined,sharedTaskId: undefined,};@@ -3094,9 +3102,9 @@ function ExpandedView({/* ---- Delete / Archive / Unarchive action handlers ----* delete 走 ConfirmDialog —— 不可逆,必须确认;* archive / archive-now 都直接执行,不弹确认框:归档可逆(菜单里就有「恢复」),- * 行内入口本身已经是两步确认,菜单入口再弹一次纯属多余摩擦。唯一例外是- * worktree 有未提交改动 —— 归档会顺带回收 worktree,这时升级到 ConfirmDialog- * 展示 dirty warning;+ * 行内入口本身已经是两步确认,菜单入口再弹一次纯属多余摩擦。例外有两个:+ * worktree 有未提交改动 —— 归档会顺带回收 worktree;任务绑定了 active 自动化+ * —— 归档后自动化会暂停。这两种情况升级到 ConfirmDialog 展示对应提醒;* unarchive 是 archive 的反向操作,无副作用,直接 patch 即可,不弹确认。** 执行序列(关子进程 / 写库 / 乐观补丁 / 释放内存 / refresh / 跳转)抽在@@ -3167,11 +3175,16 @@ function ExpandedView({};// 归档一律不弹确认框:它是可逆的(菜单里就有「恢复」),菜单入口与行内// 快捷按钮同一口径直接执行 —— 行内那个本身已经是两步确认。- // 唯一例外是 worktree 有未提交改动:归档会顺带回收 worktree,这时升级到- // 确认弹窗展示 dirty warning,不让改动被静默带走。+ // 例外:worktree 有未提交改动(归档会顺带回收 worktree)、或任务绑定了+ // active 自动化(归档后会暂停),这时升级到确认弹窗展示对应提醒。if (isArchiveLike) {// 接管拦截先结算:被接管时不该弹任何归档确认。if (await blockedByAttachment()) return;+ // 自动化绑定读本地缓存,放在 worktree 预检之前,不占用预检之后的窗口。+ const scheduleNames =+ (await loadActiveBoundScheduleNames([+ { id: sessionId, deviceLinkDeviceId: session?.deviceLinkDeviceId },+ ])).get(sessionId) ?? [];// **worktree 预检必须是最后一个前置条件**(codex review):它之后再 await// 任何东西(比如原来排在后面的接管查询),都会给「clean 结论」留一段失效// 窗口 —— 编辑器或收尾中的 agent 在那段时间写脏工作区,归档就不带警告地@@ -3193,12 +3206,13 @@ function ExpandedView({// 同样要弹确认框,否则归档会静默回收可能带着未提交改动的 worktree// (greptile review)。'unknown' 时不摆 dirty 警告文案 —— 那会谎称有改动,// 走的是普通归档确认。- if (preflight !== 'clean') {+ if (preflight !== 'clean' || scheduleNames.length > 0) {setConfirm({open: true,sessionId,action: 'archive',dirtyWorktree: preflight === 'dirty',+ scheduleNames,sharedTaskId,});return;@@ -3419,6 +3433,7 @@ function ExpandedView({return;}+ const scheduleWarning = await archiveScheduleWarningMany(t, candidates);const dirtyCount = await countDirtyWorktreesForRemoval(candidates);const skipNotes: string[] = [];@@ -3444,7 +3459,8 @@ function ExpandedView({t('ccAgent.sidebar.bulkSelection.confirmArchive.dirtyWorktreeWarning', {count: dirtyCount,})- : '');+ : '') ++ (scheduleWarning ? ' ' + scheduleWarning : '');const ok = await confirmDialog({title: t('ccAgent.sidebar.bulkSelection.confirmArchive.title'),@@ -3927,15 +3943,15 @@ function ExpandedView({: t('ccAgent.sidebar.confirmArchive.title')}description={- (confirm.action === 'delete'- ? t('ccAgent.sidebar.confirmDelete.description')- : t('ccAgent.sidebar.confirmArchive.description')) +- (confirm.dirtyWorktree- ? ' ' +- (confirm.action === 'delete'- ? t('ccAgent.sidebar.confirmDelete.dirtyWorktreeWarning')- : t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning'))- : '')+ confirm.action === 'delete'+ ? t('ccAgent.sidebar.confirmDelete.description') ++ (confirm.dirtyWorktree+ ? ' ' + t('ccAgent.sidebar.confirmDelete.dirtyWorktreeWarning')+ : '')+ : archiveConfirmDescription(t, {+ dirtyWorktree: confirm.dirtyWorktree,+ scheduleNames: confirm.scheduleNames ?? [],+ })}confirmText={confirm.action === 'delete'diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsxindex 411c5ddee2..29d7e354b7 100644--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx@@ -63,6 +63,10 @@ import { OrcaRemoteLeadBadge } from './OrcaRemoteLeadBadge';import { BotTaskOwnerChip } from '@/features/bots/BotTaskOwnerChip';import { SessionRenameInput } from './SessionRenameInput';import { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';+import {+ archiveConfirmDescription,+ loadActiveBoundScheduleNames,+} from '@/features/scheduler/lib/archiveScheduleWarning';import { ScheduleBindingBadge } from './sidebar/ScheduleBindingBadge';import { RemoteProjectIcon } from './sidebar/RemoteProjectIcon';import { VendorIcon, agentKindToVendor } from '@/components/sidebar/VendorIcon';@@ -478,6 +482,11 @@ export function SessionContentHeader({toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));return;}+ // 绑定了 active 自动化:归档后会暂停,需要确认。读本地缓存,排在 worktree 预检之前。+ const scheduleNames =+ (await loadActiveBoundScheduleNames([+ { id: session.id, deviceLinkDeviceId: session.deviceLinkDeviceId },+ ])).get(session.id) ?? [];// **worktree 预检必须是最后一个前置条件**(codex review):原来这里用 Promise.all// 一起等,dirty 先返回 clean、接管查询还在飞的那段时间就是 clean 结论的失效窗口。// 改成接管结算之后再 resolve —— clean 一律重查(见 worktreeRemovalWarning),@@ -488,14 +497,13 @@ export function SessionContentHeader({// 免确认的判据是「**确认**干净」:worktree 脏、或预检失败拿不到结论('unknown')// 都要确认 —— 归档会顺带回收 worktree,不能静默带走改动(greptile review)。// 'unknown' 只弹普通归档确认,不摆 dirty 警告文案(那会谎称有未提交改动)。- if (preflight !== 'clean') {+ if (preflight !== 'clean' || scheduleNames.length > 0) {const ok = await confirmDialog({title: t('ccAgent.sidebar.confirmArchive.title'),- description:- t('ccAgent.sidebar.confirmArchive.description') +- (preflight === 'dirty'- ? ' ' + t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning')- : ''),+ description: archiveConfirmDescription(t, {+ dirtyWorktree: preflight === 'dirty',+ scheduleNames,+ }),confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),});diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.tsindex b897baa4d4..b6e7757517 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/sharedTaskArchiveGuard.test.ts@@ -35,6 +35,7 @@ function harness(result: unknown, reject = false, sharedTaskId: string | undefintoast, t: (key: string) => key, sharedTaskErrorKey: () => 'sharedTask.retry',sessionsById: new Map([['task', session]]), sessionsByIdRef: { current: new Map([['task', session]]) },runningSessionIds: new Set(), attachedSessionIdsRef: { current: new Set() },+ loadActiveBoundScheduleNames: async () => new Map(),isRemoteSessionWriteBlocked: () => false, resolveWorktreeRemovalPreflight: preflight,archiveBlockedByRunning,viewedSessionIdRef: { current: 'other' }, viewedSessionId: 'other',@@ -125,7 +126,7 @@ describe('archive preserves the current task until preflight and confirmation fi{ name: 'hardware shortcut', file: 'lib/sessionHardwareTaskActions.ts', handler: 'archive' },];- function archiveHarness(entry: typeof entrypoints[number]) {+ function archiveHarness(entry: typeof entrypoints[number], scheduleNames: string[] = []) {const entrySource = ts.createSourceFile(entry.file, readFileSync(resolve(process.cwd(),'src/renderer/features/cc-agent', entry.file), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);const preflight = deferred<'clean' | 'dirty' | 'unknown'>();@@ -147,6 +148,9 @@ describe('archive preserves the current task until preflight and confirmation firunningSessionIds: new Set(), attachedSessionIdsRef: { current: new Set() },isRemoteSessionWriteBlocked: () => false, remoteWritesBlocked: false,resolveWorktreeRemovalPreflight: resolvePreflight,+ loadActiveBoundScheduleNames: async () =>+ new Map(scheduleNames.length > 0 ? [['task', scheduleNames]] : []),+ archiveConfirmDescription: () => 'description',viewedSessionIdRef: { current: 'task' }, viewedSessionId: 'task',resolveSessionRemovalRedirect: vi.fn(), unarchiveSession: vi.fn(),runSessionAction, setConfirm, CONFIRM_INITIAL: { open: false },@@ -224,5 +228,22 @@ describe('archive preserves the current task until preflight and confirmation fiexpect(h.selected()).toBeNull();expect(h.visible()).toBe(false);});++ it(entry.name + ' confirms a clean archive when the task has an active automation', async () => {+ const h = archiveHarness(entry, ['Daily report']);+ const pending = h.archive();+ h.preflight.resolve('clean');+ await vi.waitFor(() => {+ expect(entry.name === 'sidebar' ? h.setConfirm : h.confirmDialog).toHaveBeenCalled();+ });+ if (entry.name === 'sidebar') {+ expect(h.setConfirm).toHaveBeenCalledWith(expect.objectContaining({ scheduleNames: ['Daily report'] }));+ }+ expect(h.runSessionAction).not.toHaveBeenCalled();+ await h.finish(false);+ await pending;+ expect(h.runSessionAction).not.toHaveBeenCalled();+ expect(h.selected()).toBe('task');+ });}});diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.tsindex af5150959e..aaa918c8c4 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionGroupArchive.ts@@ -7,6 +7,7 @@ import * as sessionService from '@/lib/sessionService';import { makerChatStore } from '@/lib/makerChatStore';import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';import { countDirtyWorktreesForRemoval } from '@/lib/worktreeRemovalWarning';+import { archiveScheduleWarningMany } from '@/features/scheduler/lib/archiveScheduleWarning';import { emitRefresh } from '@/lib/sessionsBus';import { toast } from '@/lib/toast';import { createLogger } from '@/lib/logger';@@ -146,6 +147,7 @@ export function useSessionGroupArchive({return;}+ const scheduleWarning = await archiveScheduleWarningMany(t, candidates);const dirtyCount = await countDirtyWorktreesForRemoval(candidates);const skipNotes: string[] = [];@@ -168,7 +170,8 @@ export function useSessionGroupArchive({t('ccAgent.sidebar.bulkSelection.confirmArchive.dirtyWorktreeWarning', {count: dirtyCount,})- : '');+ : '') ++ (scheduleWarning ? ' ' + scheduleWarning : '');const ok = await confirmDialog({title: t('ccAgent.sidebar.archiveAll.title'),diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.tsindex e209ade335..db51392ccc 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts@@ -2,6 +2,10 @@ import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import {+ archiveConfirmDescription,+ loadActiveBoundScheduleNames,+} from '@/features/scheduler/lib/archiveScheduleWarning';import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';import type { Session } from '@/lib/ccAgent.types';import { createLogger } from '@/lib/logger';@@ -74,16 +78,19 @@ export function useSessionHardwareTaskActions({toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));return;}+ const scheduleNames =+ (await loadActiveBoundScheduleNames([{ id: sessionId, deviceLinkDeviceId }])).get(+ sessionId,+ ) ?? [];// 预检与确认期间保留当前任务,确定归档后再隐藏并跳离。const preflight = await resolveWorktreeRemovalPreflight(sessionId, deviceLinkDeviceId);- if (preflight !== 'clean') {+ if (preflight !== 'clean' || scheduleNames.length > 0) {const ok = await confirmDialog({title: t('ccAgent.sidebar.confirmArchive.title'),- description:- t('ccAgent.sidebar.confirmArchive.description') +- (preflight === 'dirty'- ? ' ' + t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning')- : ''),+ description: archiveConfirmDescription(t, {+ dirtyWorktree: preflight === 'dirty',+ scheduleNames,+ }),confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),});diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsxindex 3b550b4556..1aaa18a085 100644--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx@@ -40,6 +40,10 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { makerChatStore } from '@/lib/makerChatStore';import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';import { fetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';+import {+ archiveScheduleWarning,+ loadActiveBoundScheduleNames,+} from '@/features/scheduler/lib/archiveScheduleWarning';import * as sessionService from '@/lib/sessionService';import { getDraft, getFastModeForModel } from '@/state/newMakerDraft';import { isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';@@ -356,17 +360,23 @@ function WorkdirBrowseContent() {// resolveSession 失败不阻断后续 confirm —— 与 sidebar 单条 archive 行为一致。}+ const scheduleNames =+ (await loadActiveBoundScheduleNames([+ { id: closingId, deviceLinkDeviceId: closing?.deviceLinkDeviceId },+ ])).get(closingId) ?? [];const dirtyWorktree = await fetchDirtyWorktreeForRemoval(closingId,closing?.deviceLinkDeviceId,);const ok = await confirmDialog({title: t('ccAgent.workdirBrowse.archiveSession.title'),- description:- t('ccAgent.workdirBrowse.archiveSession.description', { title: closingTitle }) +- (dirtyWorktree- ? ' ' + t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning')- : ''),+ description: [+ t('ccAgent.workdirBrowse.archiveSession.description', { title: closingTitle }),+ dirtyWorktree ? t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning') : '',+ archiveScheduleWarning(t, scheduleNames),+ ]+ .filter(Boolean)+ .join(' '),confirmText: t('ccAgent.workdirBrowse.archiveSession.confirm'),cancelText: t('ccAgent.workdirBrowse.archiveSession.cancel'),});diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.tsnew file mode 100644index 0000000000..c10eb57e57--- /dev/null+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.ts@@ -0,0 +1,127 @@+/**+ * archiveScheduleWarning — 归档前的自动化提醒:只算 active 绑定,本机与远程分别取数。+ *+ * @vitest-environment node+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { TFunction } from 'i18next';++const mocks = vi.hoisted(() => ({+ ensure: vi.fn(),+ getSnapshot: vi.fn(),+ getSessionScheduleBindings: vi.fn(),+}));++vi.mock('../schedulesStore', () => ({+ schedulesStore: { ensure: mocks.ensure, getSnapshot: mocks.getSnapshot },+}));+vi.mock('@/features/device-link/remoteProjectsStore', () => ({+ remoteProjectsStore: { getSessionScheduleBindings: mocks.getSessionScheduleBindings },+}));++import {+ archiveConfirmDescription,+ archiveScheduleWarningMany,+ loadActiveBoundScheduleNames,+} from '../archiveScheduleWarning';+import { __resetBindingMemoForTest } from '../scheduleBindingIndex';++const t = ((key: string, options?: Record<string, unknown>) =>+ options ? `${key}${JSON.stringify(options)}` : key) as unknown as TFunction;++describe('loadActiveBoundScheduleNames', () => {+ beforeEach(() => {+ __resetBindingMemoForTest();+ mocks.ensure.mockReset();+ mocks.getSnapshot.mockReset();+ mocks.getSessionScheduleBindings.mockReset().mockReturnValue([]);+ });++ it('只返回本机任务绑定的 active 自动化', async () => {+ mocks.ensure.mockResolvedValue([+ { id: 'a', name: 'Daily', status: 'active', targetSessionId: 'task' },+ { id: 'b', name: 'Paused', status: 'paused', targetSessionId: 'task' },+ { id: 'c', name: 'Other', status: 'active', targetSessionId: 'other' },+ ]);++ const result = await loadActiveBoundScheduleNames([{ id: 'task' }, { id: 'plain' }]);++ expect([...result]).toEqual([['task', ['Daily']]]);+ });++ it('持续会话归档后会换绑新任务继续跑,不提示', async () => {+ mocks.ensure.mockResolvedValue([+ {+ id: 'p',+ name: 'Persistent',+ status: 'active',+ targetSessionId: 'task',+ persistentSession: true,+ },+ { id: 'h', name: 'Heartbeat', status: 'active', targetSessionId: 'task' },+ ]);++ const result = await loadActiveBoundScheduleNames([{ id: 'task' }]);++ expect(result.get('task')).toEqual(['Heartbeat']);+ });++ it('远程任务读远程分片,不回退到本机同 ID', async () => {+ mocks.getSessionScheduleBindings.mockReturnValue([+ { id: 'r', name: 'Remote', status: 'active', targetSessionId: 'task' },+ ]);++ const result = await loadActiveBoundScheduleNames([+ { id: 'task', deviceLinkDeviceId: 'mac-2' },+ ]);++ expect(mocks.getSessionScheduleBindings).toHaveBeenCalledWith('mac-2', 'task');+ expect(mocks.ensure).not.toHaveBeenCalled();+ expect(result.get('task')).toEqual(['Remote']);+ });++ it('本机列表加载失败时退回已有快照', async () => {+ mocks.ensure.mockRejectedValue(new Error('offline'));+ mocks.getSnapshot.mockReturnValue([+ { id: 'a', name: 'Cached', status: 'active', targetSessionId: 'task' },+ ]);++ const result = await loadActiveBoundScheduleNames([{ id: 'task' }]);++ expect(result.get('task')).toEqual(['Cached']);+ });++ it('批量提示按绑定了自动化的任务数计数', async () => {+ mocks.ensure.mockResolvedValue([+ { id: 'a', name: 'A', status: 'active', targetSessionId: 't1' },+ { id: 'b', name: 'B', status: 'active', targetSessionId: 't1' },+ { id: 'c', name: 'C', status: 'active', targetSessionId: 't2' },+ ]);++ await expect(+ archiveScheduleWarningMany(t, [{ id: 't1' }, { id: 't2' }, { id: 't3' }]),+ ).resolves.toBe('ccAgent.sidebar.confirmArchive.scheduleWarningMany{"count":2}');+ mocks.ensure.mockResolvedValue([]);+ await expect(archiveScheduleWarningMany(t, [{ id: 't3' }])).resolves.toBe('');+ });+});++describe('archiveConfirmDescription', () => {+ it('无自动化、无改动时只有基础说明', () => {+ expect(archiveConfirmDescription(t, { dirtyWorktree: false, scheduleNames: [] })).toBe(+ 'ccAgent.sidebar.confirmArchive.description',+ );+ });++ it('追加 worktree 警告与自动化提醒', () => {+ const text = archiveConfirmDescription(t, { dirtyWorktree: true, scheduleNames: ['Daily'] });+ expect(+ text.startsWith(+ 'ccAgent.sidebar.confirmArchive.description ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning ',+ ),+ ).toBe(true);+ expect(text).toContain('ccAgent.sidebar.confirmArchive.scheduleWarning{"count":1');+ });+});diff --git a/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.ts b/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.tsnew file mode 100644index 0000000000..f4ffa589e7--- /dev/null+++ b/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.ts@@ -0,0 +1,74 @@+/**+ * 归档前的自动化提醒:绑定到已归档任务的自动化在下次触发时会被调度器暂停(持续会话+ * 除外,它会换绑新任务继续跑),归档入口据此升级到确认弹窗,让用户先知道。本机读+ * schedulesStore,远程任务读 remoteProjectsStore 的绑定分片;读取失败按「无绑定」处理。+ */+import type { TFunction } from 'i18next';++import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';++import { buildBindingMap, type ScheduleBinding } from './scheduleBindingIndex';+import { schedulesStore } from './schedulesStore';++export interface ArchiveTarget {+ id: string;+ deviceLinkDeviceId?: string | null;+}++/** 每个任务归档后会停掉的自动化名称(active、非持续会话);没有的任务不出现在结果里。 */+export async function loadActiveBoundScheduleNames(+ targets: readonly ArchiveTarget[],+): Promise<Map<string, string[]>> {+ const needsLocal = targets.some((target) => !target.deviceLinkDeviceId);+ const localSchedules = needsLocal+ ? await schedulesStore.ensure().catch(() => schedulesStore.getSnapshot())+ : null;+ const localMap: ReadonlyMap<string, readonly ScheduleBinding[]> = localSchedules+ ? buildBindingMap(localSchedules)+ : new Map();+ const result = new Map<string, string[]>();+ for (const target of targets) {+ const bindings = target.deviceLinkDeviceId+ ? remoteProjectsStore.getSessionScheduleBindings(target.deviceLinkDeviceId, target.id)+ : (localMap.get(target.id) ?? []);+ const names = bindings+ .filter((schedule) => schedule.status === 'active' && !schedule.persistentSession)+ .map((schedule) => schedule.name);+ if (names.length > 0) result.set(target.id, names);+ }+ return result;+}++/** 单个任务的提醒句;无绑定时返回空串。 */+export function archiveScheduleWarning(t: TFunction, names: readonly string[]): string {+ if (names.length === 0) return '';+ return t('ccAgent.sidebar.confirmArchive.scheduleWarning', {+ count: names.length,+ names: names+ .map((name) => t('ccAgent.sidebar.confirmArchive.scheduleName', { name }))+ .join(t('ccAgent.sidebar.confirmArchive.scheduleNameSeparator')),+ });+}++/** 批量归档的提醒句:绑定了 active 自动化的任务数;为 0 时返回空串。 */+export async function archiveScheduleWarningMany(+ t: TFunction,+ targets: readonly ArchiveTarget[],+): Promise<string> {+ const count = (await loadActiveBoundScheduleNames(targets)).size;+ return count > 0 ? t('ccAgent.sidebar.confirmArchive.scheduleWarningMany', { count }) : '';+}++/** 单个任务归档确认的完整说明:基础句 + worktree 警告 + 自动化提醒。 */+export function archiveConfirmDescription(+ t: TFunction,+ { dirtyWorktree, scheduleNames }: { dirtyWorktree: boolean; scheduleNames: readonly string[] },+): string {+ return [+ t('ccAgent.sidebar.confirmArchive.description'),+ dirtyWorktree ? t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning') : '',+ archiveScheduleWarning(t, scheduleNames),+ ]+ .filter(Boolean)+ .join(' ');+}diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.tsindex fa1b20197b..33f7a73d50 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts@@ -5,7 +5,7 @@ export type ScheduleBinding = Pick<Schedule,'id' | 'name' | 'status' | 'targetSessionId' | 'cronExpr' | 'manual' | 'intervalMs'> &- Partial<Pick<Schedule, 'recurring'>>;+ Partial<Pick<Schedule, 'recurring' | 'persistentSession'>>;let lastInput: readonly ScheduleBinding[] | null = null;let lastMap: ReadonlyMap<string, ScheduleBinding[]> = new Map();@@ -61,6 +61,8 @@ export function parseScheduleBindings(raw: unknown): ScheduleBinding[] {manual: s.manual === true,recurring: s.recurring as boolean | undefined,intervalMs: s.intervalMs as number | undefined,+ // 持续会话在任务归档后会换绑新任务继续跑,归档确认据此不提示。+ ...(s.persistentSession === true ? { persistentSession: true } : {}),});}return result;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7ac59c776d..ab99c66cdd 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -12845,6 +12845,12 @@"title": "Archive session","description": "Archive this session? It will be removed from the list.","dirtyWorktreeWarning": "This session's worktree has uncommitted changes; they will be saved as a git snapshot before archiving and can be restored from the session later.",+ "scheduleWarning_one": "The automation {{names}} linked to this session will be paused after archiving.",+ "scheduleWarning_other": "The automations {{names}} linked to this session will be paused after archiving.",+ "scheduleWarningMany_one": "{{count}} of them has linked automations, which will be paused after archiving.",+ "scheduleWarningMany_other": "{{count}} of them have linked automations, which will be paused after archiving.",+ "scheduleName": "“{{name}}”",+ "scheduleNameSeparator": ", ","confirm": "Confirm","cancel": "Cancel"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d5b46edae8..b352bfb9b2 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -12797,6 +12797,12 @@"title": "セッションをアーカイブ","description": "このセッションをアーカイブしますか?アーカイブ後はリストから消えます。","dirtyWorktreeWarning": "このセッションのワークツリーには未コミットの変更があります。アーカイブ前に git スナップショットとして自動保存され、後でセッションから復元できます。",+ "scheduleWarning_one": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",+ "scheduleWarning_other": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",+ "scheduleWarningMany_one": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",+ "scheduleWarningMany_other": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",+ "scheduleName": "「{{name}}」",+ "scheduleNameSeparator": "、","confirm": "確認","cancel": "キャンセル"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex bf187a0001..c813a87a58 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -12797,6 +12797,12 @@"title": "세션 보관","description": "이 세션을 보관하시겠습니까? 보관 후 목록에서 사라집니다.","dirtyWorktreeWarning": "이 세션의 워크트리에 커밋되지 않은 변경 사항이 있습니다. 보관 전에 git 스냅샷으로 자동 저장되며 나중에 세션에서 복원할 수 있습니다.",+ "scheduleWarning_one": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",+ "scheduleWarning_other": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",+ "scheduleWarningMany_one": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",+ "scheduleWarningMany_other": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",+ "scheduleName": "\"{{name}}\"",+ "scheduleNameSeparator": ", ","confirm": "확인","cancel": "취소"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 9f18d5752f..c651f25668 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -12797,6 +12797,12 @@"title": "归档任务","description": "确定要归档这个任务吗?归档后将从列表中移除。","dirtyWorktreeWarning": "该任务的 worktree 有未提交的更改;归档前会自动保存为 git 快照,之后可在任务内一键恢复。",+ "scheduleWarning_one": "该任务绑定了自动化{{names}},归档后将暂停。",+ "scheduleWarning_other": "该任务绑定了自动化{{names}},归档后将暂停。",+ "scheduleWarningMany_one": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",+ "scheduleWarningMany_other": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",+ "scheduleName": "「{{name}}」",+ "scheduleNameSeparator": "、","confirm": "确认","cancel": "取消"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex d118579381..18b3697a36 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -12797,6 +12797,12 @@"title": "歸檔任務","description": "確定要歸檔這個任務嗎?歸檔後將從列表中移除。","dirtyWorktreeWarning": "該任務的 worktree 有未提交的更改;歸檔前會自動儲存為 git 快照,之後可在任務內一鍵恢復。",+ "scheduleWarning_one": "該任務綁定了自動化{{names}},歸檔後將暫停。",+ "scheduleWarning_other": "該任務綁定了自動化{{names}},歸檔後將暫停。",+ "scheduleWarningMany_one": "其中 {{count}} 個任務綁定了自動化,歸檔後這些自動化將暫停。",+ "scheduleWarningMany_other": "其中 {{count}} 個任務綁定了自動化,歸檔後這些自動化將暫停。",+ "scheduleName": "「{{name}}」",+ "scheduleNameSeparator": "、","confirm": "確認","cancel": "取消"},diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsxindex 6c7cb3408e..d37e95b38f 100644--- a/apps/mobile/app/devices/[deviceId].tsx+++ b/apps/mobile/app/devices/[deviceId].tsx@@ -107,6 +107,7 @@ import {loadSharedSessionScheduleIndex,} from '@/session/scheduleIndex';import { shouldSuppressRemoteListEmptyState } from '@/session/sessionEmptyState';+import { countSessionsWithActiveBoundSchedules } from '@/session/archiveScheduleConfirm';import type { RemoteSession } from '@/session/types';import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';@@ -275,6 +276,9 @@ function DeviceDetailScreenContent() {const [expandedAutomationGroups, setExpandedAutomationGroups] = useState<string[]>([]);const [bulkActionPending, setBulkActionPending] = useState<MobileSessionBulkAction | null>(null);const [bulkConfirmAction, setBulkConfirmAction] = useState<MobileSessionBulkAction | null>(null);+ // 批量归档确认里「绑定了自动化的任务数」;按请求序号丢弃过期结果。+ const [bulkScheduleCount, setBulkScheduleCount] = useState(0);+ const bulkScheduleRequestRef = useRef(0);const [bulkNotice, setBulkNotice] = useState<string | null>(null);const [scheduleIndex, setScheduleIndex] = useState<Map<string, RemoteSessionScheduleInfo>>(() => new Map(),@@ -662,8 +666,16 @@ function DeviceDetailScreenContent() {);return;}+ const scheduleRequest = ++bulkScheduleRequestRef.current;+ setBulkScheduleCount(0);+ if (action === 'archive') {+ void countSessionsWithActiveBoundSchedules(maker, summary.candidates.map((session) => session.id))+ .then((count) => {+ if (bulkScheduleRequestRef.current === scheduleRequest) setBulkScheduleCount(count);+ });+ }setBulkConfirmAction(action);- }, [bulkActionSummaries, t]);+ }, [bulkActionSummaries, maker, t]);const actionOverlays = (<>@@ -1164,6 +1176,11 @@ function DeviceDetailScreenContent() {<View style={styles.bulkConfirmCard} testID="deviceDetail.bulkConfirmCard"><Text style={styles.bulkConfirmTitle}>{bulkConfirmSummary.title}</Text><Text style={styles.bulkConfirmText}>{bulkConfirmSummary.description}</Text>+ {bulkConfirmSummary.action === 'archive' && bulkScheduleCount > 0 ? (+ <Text style={styles.bulkConfirmText}>+ {t('session.menu.archiveScheduleBulkNotice', { count: bulkScheduleCount })}+ </Text>+ ) : null}<MainWindowActionGroupprimaryActions={[{diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 2fc1db653d..e7ee7dd4b7 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -610,6 +610,7 @@ import {} from '@/session/sessionEmptyState';import { deferScheduleIndexHydration } from '@/session/scheduleIndexDefer';import { sessionMayHaveScheduleRuns } from '@/session/scheduleIndex';+import { confirmArchiveWithSchedules, loadActiveBoundScheduleNames } from '@/session/archiveScheduleConfirm';import { markSessionScheduleRunsRead, unreadRunIdFromProjection } from '@/session/scheduleRunRead';import { useRemoteScheduleEventSnapshot } from '@/scheduler/remoteScheduleEvents';import { buildSessionNativeShellLayout } from '@/session/mobileNativeShellLayout';@@ -9850,6 +9851,9 @@ function SessionScreenContent() {initialView={menuInitialView}keyboardAvoidingBehavior={nativeShellLayout.keyboardAvoidingBehavior}onArchive={() => patchSessionMeta({ status: 'archived' })}+ confirmArchive={async () => confirmArchiveWithSchedules(t, deviceId+ ? await loadActiveBoundScheduleNames({ deviceId, invoke, sessionId, source: sessionSourceForSchedule })+ : [])}onClose={() => setSettingsOpen(false)}onClosed={handleSessionMenuClosed}onDelete={() => patchSessionMeta({ status: 'deleted' })}diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.jsonindex 735834b398..e39ad3ce50 100644--- a/apps/mobile/src/i18n/locales/en/session.json+++ b/apps/mobile/src/i18n/locales/en/session.json@@ -438,6 +438,13 @@"copyFailed": "Copy failed","deleteConfirmTitle": "Delete session?","deleteConfirmBody": "This can't be undone.",+ "archiveScheduleConfirmTitle": "Archive session?",+ "archiveScheduleConfirmBody_one": "The automation {{names}} linked to this session will be paused after archiving.",+ "archiveScheduleConfirmBody_other": "The automations {{names}} linked to this session will be paused after archiving.",+ "archiveScheduleName": "“{{name}}”",+ "archiveScheduleNameSeparator": ", ",+ "archiveScheduleBulkNotice_one": "{{count}} of them has linked automations, which will be paused after archiving.",+ "archiveScheduleBulkNotice_other": "{{count}} of them have linked automations, which will be paused after archiving.","dirAlreadyAdded": "This directory is already in the list.","resetCodexTitle": "Reset Codex usage?","resetCodexBody": "This uses 1 reset for {{account}}. The quota window reopens immediately and this can't be undone.",diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.jsonindex 3cefb8823c..1f4e1e8101 100644--- a/apps/mobile/src/i18n/locales/ja/session.json+++ b/apps/mobile/src/i18n/locales/ja/session.json@@ -438,6 +438,13 @@"copyFailed": "コピーに失敗しました","deleteConfirmTitle": "セッションを削除しますか?","deleteConfirmBody": "削除すると元に戻せません。",+ "archiveScheduleConfirmTitle": "セッションをアーカイブしますか?",+ "archiveScheduleConfirmBody_one": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",+ "archiveScheduleConfirmBody_other": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",+ "archiveScheduleName": "「{{name}}」",+ "archiveScheduleNameSeparator": "、",+ "archiveScheduleBulkNotice_one": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",+ "archiveScheduleBulkNotice_other": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。","dirAlreadyAdded": "このディレクトリはすでにリストにあります。","resetCodexTitle": "Codex の使用量をリセットしますか?","resetCodexBody": "{{account}} のリセットを 1 回消費します。クォータウィンドウはすぐに再開され、この操作は取り消せません。",diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.jsonindex 078a4bcffd..47304e9f25 100644--- a/apps/mobile/src/i18n/locales/ko/session.json+++ b/apps/mobile/src/i18n/locales/ko/session.json@@ -434,6 +434,13 @@"copyFailed": "복사 실패","deleteConfirmTitle": "세션을 삭제할까요?","deleteConfirmBody": "삭제하면 되돌릴 수 없습니다.",+ "archiveScheduleConfirmTitle": "세션을 보관할까요?",+ "archiveScheduleConfirmBody_one": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",+ "archiveScheduleConfirmBody_other": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",+ "archiveScheduleName": "\"{{name}}\"",+ "archiveScheduleNameSeparator": ", ",+ "archiveScheduleBulkNotice_one": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",+ "archiveScheduleBulkNotice_other": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.","dirAlreadyAdded": "이 디렉터리는 이미 목록에 있습니다.","resetCodexTitle": "Codex 사용량을 재설정할까요?","resetCodexBody": "{{account}}에 대해 재설정 1회를 사용합니다. 사용량 창이 즉시 다시 열리며 이 작업은 취소할 수 없습니다.",diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.jsonindex 3d3277c3b8..235e076082 100644--- a/apps/mobile/src/i18n/locales/zh-CN/session.json+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json@@ -434,6 +434,13 @@"copyFailed": "复制失败","deleteConfirmTitle": "删除任务?","deleteConfirmBody": "删除后不可恢复。",+ "archiveScheduleConfirmTitle": "归档任务?",+ "archiveScheduleConfirmBody_one": "该任务绑定了自动化{{names}},归档后将暂停。",+ "archiveScheduleConfirmBody_other": "该任务绑定了自动化{{names}},归档后将暂停。",+ "archiveScheduleName": "「{{name}}」",+ "archiveScheduleNameSeparator": "、",+ "archiveScheduleBulkNotice_one": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",+ "archiveScheduleBulkNotice_other": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。","dirAlreadyAdded": "这个目录已经在列表里。","resetCodexTitle": "重置 Codex 用量?","resetCodexBody": "将为 {{account}} 消耗 1 次重置。配额窗口会立即重开,此操作不能撤销。",diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.jsonindex f1b845a4a5..42606ed2e1 100644--- a/apps/mobile/src/i18n/locales/zh-TW/session.json+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json@@ -438,6 +438,13 @@"copyFailed": "複製失敗","deleteConfirmTitle": "刪除任務?","deleteConfirmBody": "刪除後不可恢復。",+ "archiveScheduleConfirmTitle": "歸檔任務?",+ "archiveScheduleConfirmBody_one": "該任務綁定了自動化{{names}},歸檔後將暫停。",+ "archiveScheduleConfirmBody_other": "該任務綁定了自動化{{names}},歸檔後將暫停。",+ "archiveScheduleName": "「{{name}}」",+ "archiveScheduleNameSeparator": "、",+ "archiveScheduleBulkNotice_one": "其中 {{count}} 個任務綁定了自動化,歸檔後這些自動化將暫停。",+ "archiveScheduleBulkNotice_other": "其中 {{count}} 個任務綁定了自動化,歸檔後這些自動化將暫停。","dirAlreadyAdded": "這個目錄已經在列表裡。","resetCodexTitle": "重置 Codex 用量?","resetCodexBody": "將為 {{account}} 消耗 1 次重置。配額視窗會立即重開,此操作不能撤銷。",diff --git a/apps/mobile/src/session/SessionMenuSheet.tsx b/apps/mobile/src/session/SessionMenuSheet.tsxindex e016540fca..e496a7741d 100644--- a/apps/mobile/src/session/SessionMenuSheet.tsx+++ b/apps/mobile/src/session/SessionMenuSheet.tsx@@ -169,6 +169,8 @@ export interface SessionMenuSheetProps {leavingSharing?: boolean;onTogglePinned(): void;onArchive(): void;+ /** 归档前的确认(如绑定了自动化);返回 false 时保留菜单、不归档。 */+ confirmArchive?: () => Promise<boolean>;onRestore(): void;onDelete(): void;onClose(): void;@@ -210,6 +212,7 @@ export function SessionMenuSheet({leavingSharing = false,onTogglePinned,onArchive,+ confirmArchive,onRestore,onDelete,onClose,@@ -491,9 +494,17 @@ export function SessionMenuSheet({onClose();return;case 'archive':- if (session.status === 'archived') onRestore();- else onArchive();- onClose();+ if (session.status === 'archived') {+ onRestore();+ onClose();+ return;+ }+ // 与删除同序:确认弹窗在菜单仍展开时弹出,确认后再收起并归档。+ void (confirmArchive?.() ?? Promise.resolve(true)).then((ok) => {+ if (!ok) return;+ onArchive();+ onClose();+ });return;case 'delete':confirmDelete();@@ -501,7 +512,7 @@ export function SessionMenuSheet({default:return;}- }, [confirmDelete, copyValue, onArchive, onClose, onRestore, onTogglePinned, renamePrefill, session]);+ }, [confirmArchive, confirmDelete, copyValue, onArchive, onClose, onRestore, onTogglePinned, renamePrefill, session]);const currentExtraDirs = normalizeExtraDirs(session.extraDirs ?? undefined);const addExtraDir = useCallback((path: string) => {diff --git a/apps/mobile/src/session/archiveScheduleConfirm.ts b/apps/mobile/src/session/archiveScheduleConfirm.tsnew file mode 100644index 0000000000..2e19f8fbae--- /dev/null+++ b/apps/mobile/src/session/archiveScheduleConfirm.ts@@ -0,0 +1,82 @@+import { Alert } from 'react-native';+import type { TFunction } from 'i18next';+import { normalizeScheduleList } from '@/scheduler/scheduleModel';+import type { RemoteSchedule } from '@/scheduler/types';+import {+ createMobileMakerTransport,+ type MobileMakerTransport,+ type RemoteInvoke,+} from '@/device-link/mobileMakerTransport';+import { sessionMayHaveScheduleRuns } from '@/session/scheduleIndex';++/**+ * 归档前的自动化提醒:绑定到已归档任务的自动化在下次触发时会被电脑暂停(持续会话除外,+ * 它会换绑新任务继续跑),归档前先让用户知道。已知未绑定的普通任务直接放行,不额外请求;+ * 读取失败按无绑定处理。+ */+function stopsWhenTargetArchived(schedule: RemoteSchedule): boolean {+ return schedule.status === 'active' && !schedule.persistentSession && !!schedule.targetSessionId;+}++/** 批量归档:所选任务里归档后会停掉自动化的任务数(一次列表请求;失败按 0)。 */+export async function countSessionsWithActiveBoundSchedules(+ maker: Pick<MobileMakerTransport, 'schedule'>,+ sessionIds: readonly string[],+): Promise<number> {+ try {+ const ids = new Set(sessionIds);+ const bound = new Set(+ normalizeScheduleList(await maker.schedule.list())+ .filter((schedule) => stopsWhenTargetArchived(schedule) && ids.has(schedule.targetSessionId!))+ .map((schedule) => schedule.targetSessionId),+ );+ return bound.size;+ } catch {+ return 0;+ }+}++export async function loadActiveBoundScheduleNames({+ deviceId,+ invoke,+ sessionId,+ source,+}: {+ deviceId: string;+ invoke: RemoteInvoke;+ sessionId: string;+ source?: string | null;+}): Promise<string[]> {+ if (!sessionMayHaveScheduleRuns(deviceId, sessionId, source)) return [];+ try {+ const schedules = normalizeScheduleList(+ await createMobileMakerTransport({ deviceId, invoke }).schedule.list(),+ );+ return schedules+ .filter((schedule) => schedule.targetSessionId === sessionId && stopsWhenTargetArchived(schedule))+ .map((schedule) => schedule.name || schedule.id);+ } catch {+ return [];+ }+}++/** 有会停掉的自动化时弹系统确认;没有直接返回 true。 */+export function confirmArchiveWithSchedules(t: TFunction, names: readonly string[]): Promise<boolean> {+ if (names.length === 0) return Promise.resolve(true);+ return new Promise((resolve) => {+ Alert.alert(+ t('session.menu.archiveScheduleConfirmTitle'),+ t('session.menu.archiveScheduleConfirmBody', {+ count: names.length,+ names: names+ .map((name) => t('session.menu.archiveScheduleName', { name }))+ .join(t('session.menu.archiveScheduleNameSeparator')),+ }),+ [+ { style: 'cancel', text: t('devices.common.cancel'), onPress: () => resolve(false) },+ { text: t('session.menu.archive'), onPress: () => resolve(true) },+ ],+ { cancelable: true, onDismiss: () => resolve(false) },+ );+ });+}diff --git a/apps/mobile/src/session/useSessionListActions.ts b/apps/mobile/src/session/useSessionListActions.tsindex 3578bcec57..f6c857e6cf 100644--- a/apps/mobile/src/session/useSessionListActions.ts+++ b/apps/mobile/src/session/useSessionListActions.ts@@ -25,6 +25,7 @@ import {} from '@/session/swipeRowRegistry';import type { RemoteSession } from '@/session/types';import { withNewSessionCreationRemoval } from '@/session/newSessionCreation';+import { confirmArchiveWithSchedules, loadActiveBoundScheduleNames } from '@/session/archiveScheduleConfirm';/*** 首页与设备详情共用的任务行写回 / 滑动 / 选项菜单 / 重命名。@@ -133,6 +134,24 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()});}, [patchSession, swipeRegistry, t]);+ // 绑定了 active 自动化的任务归档前先确认(归档后电脑会暂停它们);普通任务直接归档。+ const archiveWithScheduleConfirm = useCallback(async (session: RemoteSession) => {+ const devices = resolveSessionWriteDevices(session.id, session);+ const names = devices+ ? await loadActiveBoundScheduleNames({+ deviceId: devices.rpcDeviceId,+ invoke,+ sessionId: session.id,+ source: session.source,+ })+ : [];+ if (!(await confirmArchiveWithSchedules(t, names))) {+ swipeRegistry.closeOpenRow();+ return;+ }+ runSwipeAction(session, 'archive');+ }, [invoke, runSwipeAction, swipeRegistry, t]);+const applySessionSheetAction = useCallback((session: RemoteSession, action: SessionSwipeAction) => {if (action === 'delete') {const title = projectDraftSessionTitle(session.title, t('session.menu.unnamedTitle')).trim()@@ -148,16 +167,20 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()setRenameSessionTarget(session);return;}+ if (action === 'archive') {+ void archiveWithScheduleConfirm(session);+ return;+ }runSwipeAction(session, action);- }, [runSwipeAction, t]);+ }, [archiveWithScheduleConfirm, runSwipeAction, t]);const handleSessionSheetAction = useCallback((action: SessionSwipeAction) => {const session = actionSheetSession;setActionSheetSession(null);if (!session) return;- if (action === 'rename' || action === 'delete') {+ if (action === 'rename' || action === 'delete' || action === 'archive') {// Android Compose BottomSheet、iOS Expo BottomSheet、系统 Alert 都不能在 Sheet- // dismiss 过程中再 present,否则会被吞掉或压在后面。+ // dismiss 过程中再 present,否则会被吞掉或压在后面。归档可能弹自动化确认,同样延后。pendingSheetActionRef.current = () => applySessionSheetAction(session, action);return;}@@ -191,8 +214,10 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()}, [runSwipeAction]);const archiveSession = useCallback((session: RemoteSession) => {- runSwipeAction(session, statusToggleAction(session.status).action);- }, [runSwipeAction]);+ const { action } = statusToggleAction(session.status);+ if (action === 'archive') void archiveWithScheduleConfirm(session);+ else runSwipeAction(session, action);+ }, [archiveWithScheduleConfirm, runSwipeAction]);const showSessionOptions = useCallback((session: RemoteSession) => {setActionSheetSession(session);diff --git a/docs/product-rules/README.md b/docs/product-rules/README.mdindex ee945f3044..ff01e6ac1d 100644--- a/docs/product-rules/README.md+++ b/docs/product-rules/README.md@@ -36,3 +36,5 @@授权、未知选项)交给主人逐步完成,值不留痕;兜底、提醒、结束判定与已知边界。- [`session-runtime-control.md`](session-runtime-control.md):Agent 调整任务模型、来源、推理强度与 Fast 的统一控制面,baseline/effective/pending 状态和自动降级边界。+- [`archive-pauses-automations.md`](archive-pauses-automations.md):归档后绑定的自动化会在+ 下次触发时被暂停(持续会话除外),用户归档这类任务前先弹确认。diff --git a/docs/product-rules/archive-pauses-automations.md b/docs/product-rules/archive-pauses-automations.mdnew file mode 100644index 0000000000..b9102f330a--- /dev/null+++ b/docs/product-rules/archive-pauses-automations.md@@ -0,0 +1,34 @@+# 归档绑定了自动化的任务前先确认++## 适用场景++任务被一个或多个**运行中**(`active`)的自动化绑定(`targetSessionId` 指向该任务),用户手动归档这个任务。++## 现有行为(不在本规则内改变)++自动化下次触发时,调度器发现绑定的任务已归档,就暂停这条自动化(本轮记为跳过);+**持续会话**(`persistentSession`)例外,它会换绑一个新任务继续运行。归档那一刻本身不改动自动化,+取消归档也不会恢复已暂停的自动化。++## 产品不变量++1. **归档前先确认**:任务绑定了归档后会停掉的自动化(运行中、非持续会话)时,用户入口先弹确认,+ 写明哪些自动化会暂停(单个任务列出名称,批量归档给出受影响的任务数)。+2. 没有这类绑定的普通任务维持「归档不弹确认」的原有体验,不增加等待。+3. 已暂停、已过期、持续会话的自动化不提示;伙伴例行任务按伙伴生命周期管理,不在此列。++## 原因++此前归档后,绑定的自动化会在下一次触发时被静默停掉,用户事先不知道,事后才发现自动化不再运行。++## 验收++- 桌面:侧栏单条 / 行内归档、批量归档、项目「全部归档」、标题栏菜单、硬件快捷键、文件浏览+ 模式关闭任务,遇到上述绑定时均出现带自动化提示的确认。+- 手机:滑动归档、选项菜单归档、任务详情菜单归档弹系统确认;设备页批量归档的确认条显示+ 受影响的任务数。++## 允许的例外++- 绑定信息读取失败(如远程电脑暂时不可达)时,入口按「无绑定」直接归档,不阻塞归档。+- Agent 工具(`archive_sessions`)与 IM 渠道的归档没有确认界面,不在本规则范围内。