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(sidebar): 自动化停用后气泡倒计时改用实时索引

Zhang Yunjin5571a4f2004e
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
index eaffe04d7d..fcd9b7d037 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
@@ -56,6 +56,17 @@ export function resetAutomationScheduleOptimisticUnreadForTests(): void {
optimisticUnreads.clear();
}
+/**
+ * 清掉已发布索引 —— 仅供测试。
+ *
+ * `publishedIndex` 是模块级状态,跨用例残留会让后一条用例继承前一条的 schedule
+ * 信息(静默的用例顺序耦合)。生产路径不调用。
+ */
+export function resetAutomationSchedulePublishedIndexForTests(): void {
+ publishedIndex = new Map();
+ for (const listener of publishedIndexListeners) listener();
+}
+
function rememberOptimisticUnread(
sessionId: string,
runId: string,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
index e025c26613..666bca611b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
@@ -16,7 +16,7 @@
import { GitPullRequest, MessageSquare } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { useEffect, useState, type ReactNode } from 'react';
+import { useEffect, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { Tooltip } from '@/components/ui/tooltip';
@@ -25,11 +25,7 @@ import { prStatusKey, MAX_STATUS_QUERIES } from '@/lib/prStatus';
import { usePrStatuses } from '@/contexts/PrRefsContext';
import { PR_STATUS_COLOR, PR_STATUS_ICON, prFailureCopyKey } from '../gitContextPrVisuals';
import { formatSidebarFutureTime } from '../lib/formatSidebarTime';
-import {
- findLatestSidebarIndexRunForSession,
- loadScheduleSidebarIndexRuns,
- type ScheduleSidebarIndexRun,
-} from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
+import { useAutomationScheduleSessionInfo } from '../hooks/useAutomationScheduleSessionIndex';
const CONTENT_SURFACE_CLASS = cn(
'bg-[var(--surface-elevated)] text-[var(--text-primary)]',
@@ -147,9 +143,13 @@ function PrTooltip({
/**
* 单独 automation-generated 会话行的 hover 浮层 —— 显示下次运行剩余时间或停止状态。
- * 数据源和 Timer chip 点击复用同一套 loadScheduleSidebarIndexRuns;tooltip 打开时才发起一次拉取
- * (与 PrTooltip 的 fetchStatusesForSession 同风格,不在密集渲染路径上常驻拉数据);
- * 拉到的 nextFireAt 用一次性 formatSidebarFutureTime 转成 "N 分钟后运行",不做秒级 tick
+ * 数据源 = 已发布的实时 schedule 索引(useAutomationScheduleSessionInfo,随 scheduler
+ * 事件刷新)。旧实现是「tooltip 首次打开时拉一次 listSidebarIndexRuns 就把
+ * 快照留在组件 state 里」,此后永不刷新:用户停用(暂停)自动化后,气泡仍拿停用前的
+ * scheduleStatus=active + nextFireAt 继续显示倒计时,直到该行重新挂载。
+ * 走实时索引后停用/恢复立刻反映,也不用在密集渲染路径上自己发 IPC。
+ * 索引未就绪 / 为空时与组头同源降级(不显示气泡),本浮层不再单独兜底拉取。
+ * nextFireAt 用一次性 formatSidebarFutureTime 转成 "N 分钟后运行",不做秒级 tick
* (tooltip 通常只停留几秒,静态文案够用)。
*/
function AutomationTooltip({
@@ -162,36 +162,19 @@ function AutomationTooltip({
children: ReactNode;
}) {
const { t } = useTranslation();
- const [open, setOpen] = useState(false);
- const effectiveOpen = controlledOpen ?? open;
- const [runs, setRuns] = useState<ScheduleSidebarIndexRun[] | null>(null);
- useEffect(() => {
- if (!effectiveOpen || runs !== null) return;
- let cancelled = false;
- loadScheduleSidebarIndexRuns()
- .then((next) => {
- if (!cancelled) setRuns(next);
- })
- .catch(() => {
- if (!cancelled) setRuns([]);
- });
- return () => {
- cancelled = true;
- };
- }, [effectiveOpen, runs]);
-
- const hit = runs ? (findLatestSidebarIndexRunForSession(runs, sessionId) ?? null) : null;
+ const scheduleInfo = useAutomationScheduleSessionInfo(sessionId);
const countdownText =
- hit && hit.scheduleStatus === 'active' && typeof hit.nextFireAt === 'number'
- ? formatSidebarFutureTime(hit.nextFireAt, t)
+ scheduleInfo?.scheduleStatus === 'active' && typeof scheduleInfo.nextFireAt === 'number'
+ ? formatSidebarFutureTime(scheduleInfo.nextFireAt, t)
: '';
- const isStopped = hit?.scheduleStatus === 'paused' || hit?.scheduleStatus === 'expired';
+ const isStopped =
+ scheduleInfo?.scheduleStatus === 'paused' || scheduleInfo?.scheduleStatus === 'expired';
const stoppedText = isStopped ? t('ccAgent.sidebar.automationGroup.stopped') : '';
const hasContent = countdownText || stoppedText;
return (
<Tooltip.Provider delayDuration={0} skipDelayDuration={0}>
- <Tooltip.Root open={controlledOpen} onOpenChange={setOpen}>
+ <Tooltip.Root open={controlledOpen}>
<Tooltip.Trigger asChild onFocus={(event) => event.preventDefault()}>
{children}
</Tooltip.Trigger>
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionTooltip.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionTooltip.test.ts
index 88d280d8f1..ca172b29c0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionTooltip.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionTooltip.test.ts
@@ -1,11 +1,16 @@
// @vitest-environment jsdom
-import { createElement, type ComponentProps } from 'react';
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { createElement, type ComponentProps, type ReactNode } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Tooltip } from '@/components/ui/tooltip';
import { SessionTooltip } from '../SessionTooltip';
+import {
+ resetAutomationSchedulePublishedIndexForTests,
+ useAutomationScheduleSessionIndex,
+} from '../../hooks/useAutomationScheduleSessionIndex';
+import type { ScheduleSidebarIndexRun } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
import type { SessionPrRef } from '@/lib/gitContext.types';
import { prStatusKey } from '@/hooks/useSessionGitContext';
@@ -15,7 +20,11 @@ const { prStatuses } = vi.hoisted(() => ({
vi.mock('react-i18next', () => ({
useTranslation: () => ({
- t: (key: string) => key,
+ t: (key: string, options?: Record<string, unknown>) => {
+ if (key === 'ccAgent.time.future.hour') return `还有 ${options?.count} 小时`;
+ if (key === 'ccAgent.sidebar.automationGroup.stopped') return '已停止';
+ return key;
+ },
}),
}));
@@ -29,6 +38,9 @@ vi.mock('@/contexts/PrRefsContext', () => ({
afterEach(() => {
cleanup();
prStatuses.clear();
+ vi.unstubAllGlobals();
+ // publishedIndex 是模块级状态,不清会让后续用例继承本条用例发布的 schedule 信息。
+ resetAutomationSchedulePublishedIndexForTests();
});
const prRef: SessionPrRef = {
@@ -160,4 +172,75 @@ describe('SessionTooltip', () => {
expect(statusLabel.classList.contains('whitespace-nowrap')).toBe(true);
}
});
+
+ it('replaces the countdown with the stopped state once the automation is paused', async () => {
+ // 停用只改 schedules.status,next_fire_at 保留旧值 —— 气泡若还拿着停用前的快照,
+ // 就会继续显示「还有 N 小时」。这里用真实索引入口(useAutomationScheduleSessionIndex
+ // + scheduler 'changed' 事件)驱动,验证气泡跟随实时状态。
+ const runs: ScheduleSidebarIndexRun[] = [
+ {
+ runId: 'run-1',
+ scheduleId: 'schedule-1',
+ scheduleName: 'PR 助手',
+ scheduleStatus: 'active',
+ status: 'success',
+ firedAt: 1,
+ sessionId: 'session-1',
+ nextFireAt: Date.now() + 2 * 60 * 60 * 1000 + 60_000,
+ },
+ ];
+ let listener: ((event: unknown, ownerStamp: unknown) => void) | undefined;
+ const listSidebarIndexRuns = vi.fn(async () => ({
+ runs,
+ inflightRunIds: [],
+ inflightPolicies: [],
+ }));
+ vi.stubGlobal('electronAPI', {
+ maker: {
+ schedule: {
+ listSidebarIndexRuns,
+ onEvent: vi.fn((callback: (event: unknown, ownerStamp: unknown) => void) => {
+ listener = callback;
+ return () => {
+ listener = undefined;
+ };
+ }),
+ },
+ },
+ });
+
+ const IndexOwner = ({ children }: { children?: ReactNode }) => {
+ useAutomationScheduleSessionIndex();
+ return children ?? null;
+ };
+
+ render(
+ createElement(
+ IndexOwner,
+ null,
+ createElement(
+ SessionTooltip,
+ {
+ sessionId: 'session-1',
+ prRefs: [],
+ isAutomationSession: true,
+ } as unknown as ComponentProps<typeof SessionTooltip>,
+ createElement('div', null, 'Session row'),
+ ),
+ ),
+ );
+
+ await waitFor(() => expect(listSidebarIndexRuns).toHaveBeenCalled());
+ fireEvent.pointerMove(screen.getByText('Session row'), { pointerType: 'mouse' });
+ expect((await screen.findByRole('tooltip')).textContent).toContain('还有 2 小时');
+
+ runs[0].scheduleStatus = 'paused';
+ await act(async () => {
+ listener?.({ type: 'changed', scheduleId: 'schedule-1' }, undefined);
+ });
+
+ const tooltip = await screen.findByRole('tooltip');
+ expect(tooltip.textContent).toContain('已停止');
+ expect(tooltip.textContent).not.toContain('还有');
+ });
});