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(desktop): 归档执行前核对运行状态与当前路由

Dashb30da8f1844c
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
index 64eedcc9ae..4254420bbb 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
completeStatusTransition: vi.fn(),
rollbackStatusTransition: vi.fn(),
closeSessionQuery: vi.fn(),
+ getRunningSnapshot: vi.fn(),
purgeSession: vi.fn(),
releaseRemoteArchivedTombstone: vi.fn(),
beginPendingStatus: vi.fn(),
@@ -24,12 +25,14 @@ const mocks = vi.hoisted(() => ({
cleanupSessionLayoutPrefs: vi.fn(),
cleanupSessionImages: vi.fn(),
toastError: vi.fn(),
+ toastWarning: vi.fn(),
logInfo: vi.fn(),
logWarn: vi.fn(),
logError: vi.fn(),
}));
-vi.mock('react-router-dom', () => ({
+vi.mock('react-router-dom', async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-router-dom')>(),
useNavigate: () => mocks.navigate,
}));
@@ -38,7 +41,7 @@ vi.mock('react-i18next', () => ({
}));
vi.mock('@/lib/toast', () => ({
- toast: { error: mocks.toastError },
+ toast: { error: mocks.toastError, warning: mocks.toastWarning },
}));
vi.mock('@/lib/sessionService', () => ({
@@ -48,6 +51,7 @@ vi.mock('@/lib/sessionService', () => ({
vi.mock('@/lib/makerChatStore', () => ({
makerChatStore: {
+ getRunningSnapshot: mocks.getRunningSnapshot,
closeSessionQuery: mocks.closeSessionQuery,
purgeSession: mocks.purgeSession,
releaseRemoteArchivedTombstone: mocks.releaseRemoteArchivedTombstone,
@@ -99,9 +103,14 @@ vi.mock('@/lib/logger', () => ({
}));
import { useSessionLifecycleActions } from '../useSessionLifecycleActions';
+import { isSessionRemovalRouteCurrent } from '../../lib/sessionRemovalNavigation';
+import { clearRemoteSessionActivity, applyRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
beforeEach(() => {
vi.clearAllMocks();
+ window.history.replaceState(null, '', '#/cc-agent/session-1');
+ mocks.getRunningSnapshot.mockReturnValue(new Map());
+ clearRemoteSessionActivity();
mocks.setStatus.mockImplementation(async (id: string, status: string) => ({
id,
status,
@@ -134,6 +143,98 @@ beforeEach(() => {
});
});
+describe('archive uses current state after asynchronous checks', () => {
+ it.each(['local', 'device-link'] as const)('does not interrupt a newly running %s task', async (kind) => {
+ let finishTarget!: (target: unknown) => void;
+ mocks.resolveStatusWriteTarget.mockImplementationOnce(() => new Promise((resolve) => {
+ finishTarget = resolve;
+ }));
+ const { result } = renderHook(() => useSessionLifecycleActions());
+ let pending!: Promise<void>;
+ await act(async () => {
+ pending = result.current.runSessionAction('session-1', 'archive', { activeSessionId: 'session-1' });
+ });
+ mocks.getRunningSnapshot.mockReturnValue(new Map([['session-1', { isRunning: true }]]));
+ await act(async () => {
+ finishTarget({ kind, deviceId: 'device-1' });
+ await pending;
+ });
+ expect(mocks.toastWarning).toHaveBeenCalledWith('ccAgent.sidebar.archiveBlocked.running');
+ expect(mocks.beginStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.beginPendingStatus).not.toHaveBeenCalled();
+ expect(mocks.closeSessionQuery).not.toHaveBeenCalled();
+ expect(mocks.setStatus).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it.each(['running', 'needs-interaction'])('also blocks a remote %s activity without a local chat mirror', async (phase) => {
+ mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'device-link', deviceId: 'device-1' });
+ applyRemoteSessionActivity('device-1', { sessionId: 'session-1', phase });
+ const { result } = renderHook(() => useSessionLifecycleActions());
+ await act(async () => {
+ await result.current.runSessionAction('session-1', 'archive', { activeSessionId: 'session-1' });
+ });
+ expect(mocks.toastWarning).toHaveBeenCalledWith('ccAgent.sidebar.archiveBlocked.running');
+ expect(mocks.closeSessionQuery).not.toHaveBeenCalled();
+ expect(mocks.setStatus).not.toHaveBeenCalled();
+ expect(mocks.beginPendingStatus).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('rechecks running state after waiting for a previous local status transition', async () => {
+ mocks.beginStatusTransitionWhenReady.mockImplementationOnce(async (_id, _patch, apply) => {
+ mocks.getRunningSnapshot.mockReturnValue(new Map([['session-1', { isRunning: true }]]));
+ return apply(() => mocks.beginStatusTransition('session-1'));
+ });
+ const { result } = renderHook(() => useSessionLifecycleActions({ includeArchived: 'all' }));
+ await act(async () => {
+ await result.current.runSessionAction('session-1', 'archive', { activeSessionId: 'session-1' });
+ });
+ expect(mocks.beginStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.closeSessionQuery).not.toHaveBeenCalled();
+ expect(mocks.setStatus).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it.each(['active', 'all'] as const)('keeps the new route when the old view unmounts before archive (%s)', async (includeArchived) => {
+ mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'device-link', deviceId: 'device-1' });
+ const { result, unmount } = renderHook(() => useSessionLifecycleActions({ includeArchived }));
+ const runSessionAction = result.current.runSessionAction;
+ unmount();
+ window.history.replaceState(null, '', '#/cc-agent/other-session');
+ await act(async () => {
+ await runSessionAction('session-1', 'archive', { activeSessionId: 'session-1' });
+ });
+ expect(mocks.setStatus).toHaveBeenCalledWith('session-1', 'archived', expect.anything());
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('keeps a route changed while resolving the status write target', async () => {
+ mocks.resolveStatusWriteTarget.mockImplementationOnce(async () => {
+ window.history.replaceState(null, '', '#/settings');
+ return { kind: 'device-link', deviceId: 'device-1' };
+ });
+ const { result } = renderHook(() => useSessionLifecycleActions());
+ await act(async () => {
+ await result.current.runSessionAction('session-1', 'archive', { activeSessionId: 'session-1' });
+ });
+ expect(mocks.setStatus).toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ '/cc-agent/session-1',
+ '/cc-agent/files/session-1?path=src',
+ '/cc-agent/orca/session-1',
+ '/bots/bot/session/session-1',
+ '/bots/bot/history/session-1',
+ ])('recognizes the currently viewed task at %s', (route) => {
+ window.history.replaceState(null, '', '#' + route);
+ expect(isSessionRemovalRouteCurrent('session-1')).toBe(true);
+ expect(isSessionRemovalRouteCurrent('other-session')).toBe(false);
+ });
+});
+
describe('useSessionLifecycleActions archive optimistic ordering', () => {
it('drops the row before navigating away when the row leaves the list', async () => {
// active 桶:store 已把行就地移出,高亮随行消失 → 先让行消失,别把
@@ -313,6 +414,7 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
});
it('hides a device-link row through the remote overlay before the write and completes it', async () => {
+ window.history.replaceState(null, '', '#/cc-agent/remote-session');
mocks.resolveStatusWriteTarget.mockResolvedValueOnce({
kind: 'device-link',
deviceId: 'device-1',
@@ -421,6 +523,7 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
});
it('navigates before moving an archived remote row in the all bucket', async () => {
+ window.history.replaceState(null, '', '#/cc-agent/remote-session');
mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'device-link', deviceId: 'device-1' });
const { result } = renderHook(() => useSessionLifecycleActions({ includeArchived: 'all' }));
await act(async () => {
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
index 4165e8a654..bf94030403 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
@@ -11,8 +11,8 @@
* (sidebar 是受控 ConfirmDialog + 行内两步确认,header 是 imperative
* confirmDialog),强行收进来反而耦合。
*
- * activeSessionId 由调用方传入:sidebar 是当前路由解析出的活跃会话(可能
- * 操作非活跃行);header 操作的恒为当前打开的会话(传 session.id 即可)。
+ * activeSessionId 表示调用方原先浏览的会话;归档跳转前还会读取实时路由,
+ * 防止预检或确认期间切换任务后,旧操作把新页面带走。
*
* 远程(device-link)任务的归档 / 恢复走 remoteProjectsStore 的状态迁移叠加层,与本机
* sessionsStore 状态事务对称:行当帧换桶,写库成功后落被控端返回的行,失败回滚。
@@ -27,6 +27,7 @@
import { useCallback } from 'react';
import { flushSync } from 'react-dom';
import { useSidebarNavigate } from '../sidebar/sidebarNavigation';
+import { isSessionRemovalRouteCurrent } from '../lib/sessionRemovalNavigation';
import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
@@ -40,6 +41,10 @@ import {
remoteProjectsStore,
type RemotePendingStatusToken,
} from '@/features/device-link/remoteProjectsStore';
+import {
+ getRemoteSessionActivity,
+ isRemoteSessionActivityActive,
+} from '@/features/device-link/remoteSessionActivityStore';
import { createLogger } from '@/lib/logger';
import type { ListStatusFilter } from '@/lib/sessionService';
import type { Session, SessionStatus } from '@/lib/ccAgent.types';
@@ -106,7 +111,9 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
): RemotePendingStatusToken => {
const archivedRowStaysInList = listFilter === 'all';
const leaveArchivedSession = () => {
- if (sessionId === activeSessionId) navigate('/cc-agent/new');
+ if (sessionId === activeSessionId && isSessionRemovalRouteCurrent(sessionId)) {
+ navigate('/cc-agent/new');
+ }
};
if (archivedRowStaysInList) flushSync(leaveArchivedSession);
let token!: RemotePendingStatusToken;
@@ -132,6 +139,16 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
const targetStatus: SessionStatus = action === 'delete' ? 'deleted' : 'archived';
const statusWriteTarget = await sessionService.resolveStatusWriteTarget(sessionId);
const isDeviceLinkSession = statusWriteTarget.kind === 'device-link';
+ // Preflight/confirmation and write-target resolution may outlive the initial running check.
+ const archiveBlockedByRunning = () => {
+ const running = makerChatStore.getRunningSnapshot().get(sessionId)?.isRunning ||
+ (statusWriteTarget.kind === 'device-link' && isRemoteSessionActivityActive(
+ getRemoteSessionActivity(sessionId, statusWriteTarget.deviceId),
+ ));
+ if (running) toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));
+ return Boolean(running);
+ };
+ if (action === 'archive' && archiveBlockedByRunning()) return;
let statusTransition: SessionStatusTransitionToken | null = null;
// device-link 远程会话:status 写经隧道(setStatus 内部按来源路由 patch-meta)。归档走
// remoteProjectsStore 的状态迁移叠加层乐观换桶,写库成功即落被控端返回的行,不等
@@ -166,11 +183,10 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
// 后再用 patchLocal 从所有桶移除。
const archivedRowStaysInList = listFilter === 'all';
const leaveArchivedSession = () => {
- if (sessionId === activeSessionId) navigate('/cc-agent/new');
+ if (sessionId === activeSessionId && isSessionRemovalRouteCurrent(sessionId)) {
+ navigate('/cc-agent/new');
+ }
};
- if (archivedRowStaysInList) {
- flushSync(leaveArchivedSession);
- }
statusTransition = await sessionsStore.beginStatusTransitionWhenReady(
sessionId,
{
@@ -178,6 +194,9 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
pinnedAt: null,
},
(begin) => {
+ // A previous local status write can keep us waiting after the check above.
+ if (archiveBlockedByRunning()) return null;
+ if (archivedRowStaysInList) flushSync(leaveArchivedSession);
let transition: SessionStatusTransitionToken | null = null;
flushSync(() => {
transition = begin();
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts
index ea907ffd94..78a8f4ffc1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionRemovalNavigation.ts
@@ -1,3 +1,17 @@
+import { matchPath } from 'react-router-dom';
+
+/** Read HashRouter's current URL at navigation time, even if the initiating view unmounted. */
+export function isSessionRemovalRouteCurrent(sessionId: string): boolean {
+ const pathname = window.location.hash.slice(1).split(/[?#]/, 1)[0];
+ return [
+ '/cc-agent/:sessionId',
+ '/cc-agent/files/:sessionId',
+ '/cc-agent/orca/:sessionId',
+ '/bots/:botId/session/:sessionId',
+ '/bots/:botId/history/:sessionId',
+ ].some((path) => matchPath(path, pathname)?.params.sessionId === sessionId);
+}
+
export function getVisibleSidebarSessionIds(root?: Document | Element | null): string[] {
if (root == null && typeof document === 'undefined') return [];
const queryRoot = root ?? document;