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): 侧栏定时任务分组收起时露出未处理告警 (#3184)

Dash8353be1fa3b1
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index 49749745cf..ab6b07db81 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -573,6 +573,108 @@ describe('automation-generated sessions', () => {
expect(view.totalCount).toBe(7);
});
+ describe('collapsed automation group keeps unhandled alerts reachable', () => {
+ const alertGroup = (count = 7) => ({
+ id: 'schedule:sched-alert',
+ title: 'Alert',
+ sessions: Array.from({ length: count }, (_, index) =>
+ makeSession({ id: `run-${index}`, title: `RUN-${index}`, source: 'scheduler' }),
+ ),
+ attentionSessionIds: [],
+ });
+
+ it('renders nothing extra while no run holds an alert', () => {
+ const view = getAutomationGroupChildView(alertGroup(), {
+ notifications: new Set(['run-0']),
+ showAll: false,
+ collapsed: true,
+ });
+ expect(view.visibleSessions).toEqual([]);
+ expect(view.isOverflowing).toBe(false);
+ expect(view.totalCount).toBe(0);
+ });
+
+ it('lifts only the alerting runs out of a collapsed group', () => {
+ // run-3 是「组内第 3 新、turn 从未收尾」那类运行:组头代表的是 run-0,
+ // 收起态若返回空列表,项目折叠头的红点就没有任何一行能对应上。
+ const view = getAutomationGroupChildView(alertGroup(), {
+ notifications: new Set(['run-0', 'run-3']),
+ showAll: false,
+ collapsed: true,
+ alertSessionIds: new Set(['run-3']),
+ });
+ expect(view.visibleSessions.map((session) => session.id)).toEqual(['run-3']);
+ expect(view.isOverflowing).toBe(false);
+ expect(view.totalCount).toBe(1);
+ });
+
+ it('caps lifted alerts at five and counts only alerts in the overflow label', () => {
+ const alerts = ['run-0', 'run-1', 'run-2', 'run-3', 'run-4', 'run-5'];
+ const view = getAutomationGroupChildView(alertGroup(8), {
+ notifications: new Set(alerts),
+ showAll: false,
+ collapsed: true,
+ alertSessionIds: new Set(alerts),
+ });
+ expect(view.visibleSessions).toHaveLength(5);
+ expect(view.isOverflowing).toBe(true);
+ expect(view.hiddenCount).toBe(1);
+ // 「显示全部 N 个」的 N 是告警数,不是整组运行数(收起态列表语义就是告警)。
+ expect(view.totalCount).toBe(6);
+
+ const expanded = getAutomationGroupChildView(alertGroup(8), {
+ notifications: new Set(alerts),
+ showAll: true,
+ collapsed: true,
+ alertSessionIds: new Set(alerts),
+ });
+ expect(expanded.visibleSessions.map((session) => session.id)).toEqual(alerts);
+ expect(expanded.isOverflowing).toBe(false);
+ });
+
+ it('ignores a frozen expanded layout so collapsing cannot drag non-alert runs back', () => {
+ const view = getAutomationGroupChildView(alertGroup(), {
+ notifications: new Set(),
+ showAll: false,
+ collapsed: true,
+ alertSessionIds: new Set(['run-4']),
+ frozenVisibleSessionIds: ['run-0', 'run-1', 'run-2'],
+ });
+ expect(view.visibleSessions.map((session) => session.id)).toEqual(['run-4']);
+ });
+
+ it('goes back to the regular collapse cap once the group is expanded', () => {
+ const view = getAutomationGroupChildView(alertGroup(), {
+ notifications: new Set(),
+ showAll: false,
+ collapsed: false,
+ alertSessionIds: new Set(['run-6']),
+ });
+ expect(view.visibleSessions.map((session) => session.id)).toEqual([
+ 'run-0',
+ 'run-1',
+ 'run-2',
+ 'run-3',
+ 'run-4',
+ ]);
+ expect(view.totalCount).toBe(7);
+ });
+
+ it('does not let a leftover collapsed showAll dump the whole history on expand', () => {
+ // 收起态点过「显示全部」后,showAll 仍为 true;若展开分支把 collapsed 短路排在
+ // showAll 之后,会一次渲染全部历史运行。组件切折叠时会清 showAll,本断言钉住
+ // childView 自己也不依赖那次复位。
+ const view = getAutomationGroupChildView(alertGroup(), {
+ notifications: new Set(),
+ showAll: true,
+ collapsed: false,
+ alertSessionIds: new Set(['run-0', 'run-1', 'run-2', 'run-3', 'run-4', 'run-5']),
+ });
+ expect(view.visibleSessions).toHaveLength(7);
+ expect(view.totalCount).toBe(7);
+ });
+ });
+
it('keeps unread automation runs visible past the collapse cap', () => {
const sessions = Array.from({ length: 8 }, (_, index) =>
makeSession({ id: `run-${index}`, title: `RUN-${index}`, source: 'scheduler' }),
@@ -709,10 +811,15 @@ describe('automation-generated sessions', () => {
expect(source).toContain('useAutomationGroupCollapsed(');
expect(source).toContain('group.legacyId');
expect(source).toContain('toggleCollapsed()');
+ // 切折叠必须复位轴 2:showAll 被收起告警列表和展开历史列表共用。复位挂在
+ // collapsed 变化上,覆盖 chevron 与父层「收起所有分组」,不只一条点击路径。
+ expect(source).toContain('useLayoutEffect(() => {\n setShowAll(false);\n }, [collapsed]);');
expect(source).toContain('const ToggleIcon = collapsed ? ChevronRight : ChevronDown');
expect(source).toContain('aria-expanded={!collapsed}');
- // 轴 1 收起时藏掉全部子运行(只留组头)。
- expect(source).toContain('const visibleSessions = collapsed ? [] : childView.visibleSessions');
+ // 轴 1 收起时只留组头 + 被提上来的未处理告警行,取舍统一由 childView 决定
+ // (收起态曾经是硬编码的空列表,于是组内非最新一条的告警既不上组头也不成行)。
+ expect(source).toContain('const visibleSessions = childView.visibleSessions;');
+ expect(source).toMatch(/getAutomationGroupChildView\(group, \{[\s\S]*?collapsed,/);
expect(source).toContain('const hasVisibleChildren = visibleSessions.length > 0');
expect(source).toContain('{hasVisibleChildren && (');
// 侧栏侧保留「立即运行」直点,低频的编辑 / 暂停恢复 / 删除收回 More 菜单。
diff --git a/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts b/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts
index ca6f80106e..ce9db9198a 100644
--- a/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts
+++ b/apps/desktop/src/renderer/__tests__/projectCollapsedAttention.test.ts
@@ -5,7 +5,11 @@ import { describe, expect, it } from 'vitest';
import type { AttentionKind } from '@/lib/sessionAttentionStore';
import type { RemoteSessionActivityPhase } from '@/features/device-link/remoteSessionActivityStore';
-import { resolveCollapsedProjectAttentionTone } from '../features/cc-agent/sidebar/projectCollapsedAttention';
+import {
+ resolveCollapsedAttention,
+ resolveCollapsedGroupRightStatus,
+ resolveCollapsedProjectAttentionTone,
+} from '../features/cc-agent/sidebar/projectCollapsedAttention';
const sidebarDir = resolvePath(__dirname, '..', 'features', 'cc-agent', 'sidebar');
const projectNodeSource = readFileSync(
@@ -21,33 +25,47 @@ const sidebarUpperSource = readFileSync(
'utf8',
);
const sessionItemSource = readFileSync(resolvePath(sidebarDir, 'SessionItem.tsx'), 'utf8');
+const automationGroupSource = readFileSync(
+ resolvePath(sidebarDir, 'AutomationSessionGroupItem.tsx'),
+ 'utf8',
+);
const sessions = (ids: string[]) => ids.map((id) => ({ id }));
-function resolve({
- ids = ['session-1'],
- running = [],
- notifications = [],
- attentionKinds = [],
- urgent = [],
- remotePhases = [],
-}: {
+interface ResolveOptions {
ids?: string[];
running?: string[];
notifications?: string[];
attentionKinds?: [string, AttentionKind][];
urgent?: string[];
remotePhases?: [string, RemoteSessionActivityPhase][];
-} = {}) {
+}
+
+function inputFor({
+ ids = ['session-1'],
+ running = [],
+ notifications = [],
+ attentionKinds = [],
+ urgent = [],
+ remotePhases = [],
+}: ResolveOptions = {}) {
const phases = new Map(remotePhases);
- return resolveCollapsedProjectAttentionTone({
+ return {
sessions: sessions(ids),
runningSessionIds: new Set(running),
notifications: new Set(notifications),
attentionKinds: new Map(attentionKinds),
urgentSessionIds: new Set(urgent),
- remotePhaseOf: (sessionId) => phases.get(sessionId),
- });
+ remotePhaseOf: (sessionId: string) => phases.get(sessionId),
+ };
+}
+
+function resolve(options: ResolveOptions = {}) {
+ return resolveCollapsedProjectAttentionTone(inputFor(options));
+}
+
+function summarize(options: ResolveOptions = {}) {
+ return resolveCollapsedAttention(inputFor(options));
}
describe('collapsed project attention tone', () => {
@@ -111,6 +129,82 @@ describe('collapsed project attention tone', () => {
});
});
+describe('collapsed attention alert ids', () => {
+ it('names every child that contributes the red dot, across all three sources', () => {
+ const summary = summarize({
+ ids: ['local-error', 'urgent-schedule', 'remote-error', 'done-child', 'idle-child'],
+ notifications: ['local-error', 'done-child'],
+ attentionKinds: [
+ ['local-error', 'error'],
+ ['done-child', 'done'],
+ ],
+ urgent: ['urgent-schedule'],
+ remotePhases: [['remote-error', 'error']],
+ });
+ expect(summary.tone).toBe('error');
+ expect([...summary.errorSessionIds]).toEqual([
+ 'local-error',
+ 'urgent-schedule',
+ 'remote-error',
+ ]);
+ });
+
+ it('stays empty whenever the aggregate is green or absent', () => {
+ expect(summarize({ notifications: ['session-1'] })).toEqual({
+ tone: 'done',
+ errorSessionIds: [],
+ });
+ expect(summarize()).toEqual({ tone: null, errorSessionIds: [] });
+ // 蓝(等你回复)与运行态都不升格,也不算告警 —— 与 tone 口径一致。
+ expect(
+ summarize({ notifications: ['session-1'], attentionKinds: [['session-1', 'awaiting']] })
+ .errorSessionIds,
+ ).toEqual([]);
+ });
+
+ it('never reports an alert the tone would not show (remote mirror wins)', () => {
+ const summary = summarize({
+ notifications: ['session-1'],
+ attentionKinds: [['session-1', 'error']],
+ remotePhases: [['session-1', 'running']],
+ });
+ expect(summary.tone).toBeNull();
+ expect(summary.errorSessionIds).toEqual([]);
+ });
+});
+
+describe('collapsed automation group right status', () => {
+ const status = (
+ collapsed: boolean,
+ latestKind: Parameters<typeof resolveCollapsedGroupRightStatus>[0]['latestKind'],
+ tone: Parameters<typeof resolveCollapsedGroupRightStatus>[0]['tone'],
+ ) => resolveCollapsedGroupRightStatus({ collapsed, latestKind, tone });
+
+ it('keeps the latest run authoritative while the group is expanded', () => {
+ expect(status(false, 'time', 'error')).toBe('time');
+ expect(status(false, 'running', 'done')).toBe('running');
+ });
+
+ it('promotes an aggregated error over anything the latest run shows', () => {
+ expect(status(true, 'time', 'error')).toBe('error');
+ // 「等你处理」压过 spinner —— 正是此前被藏掉的那一档。
+ expect(status(true, 'running', 'error')).toBe('error');
+ expect(status(true, 'done', 'error')).toBe('error');
+ });
+
+ it('only fills green into an otherwise empty slot', () => {
+ expect(status(true, 'time', 'done')).toBe('done');
+ // 绿点绝不能盖掉 spinner:会读成「仍在跑却已完成」。
+ expect(status(true, 'running', 'done')).toBe('running');
+ expect(status(true, 'awaiting', 'done')).toBe('awaiting');
+ });
+
+ it('leaves the latest status untouched when the group has nothing to aggregate', () => {
+ expect(status(true, 'running', null)).toBe('running');
+ expect(status(true, 'time', null)).toBe('time');
+ });
+});
+
describe('collapsed project attention wiring', () => {
it('renders the aggregate status on the trailing slot while the project is collapsed', () => {
const slotChrome = 'group/slot relative ml-auto flex h-6 shrink-0 items-center justify-end';
@@ -136,6 +230,30 @@ describe('collapsed project attention wiring', () => {
expect(indicator).toBeGreaterThan(trailingSlot);
});
+ it('feeds the automation group header and its collapsed rows from the same summary', () => {
+ // 组头红点与收起态提上来的告警行必须同源 —— 判据分家就会重演「项目行有红点、
+ // 展开后哪一行都没有」。
+ expect(automationGroupSource).toContain('resolveCollapsedAttention({');
+ expect(automationGroupSource).toContain('resolveCollapsedGroupRightStatus({');
+ expect(automationGroupSource).toMatch(/tone:\s*collapsedAttention\.tone/);
+ expect(automationGroupSource).toMatch(/new Set\(collapsedAttention\.errorSessionIds\)/);
+ expect(automationGroupSource).toContain('alertSessionIds,');
+ // 收起态不再是"空列表",子行的取舍统一由 getAutomationGroupChildView 决定。
+ expect(automationGroupSource).toContain('const visibleSessions = childView.visibleSessions;');
+ expect(automationGroupSource).not.toMatch(/collapsed\s*\?\s*\[\]\s*:/);
+ });
+
+ it('aggregates the group header without falling back to whole-table subscriptions', () => {
+ // 每个项目下都挂着若干组头,整表 / 整集订阅会让任何一个任务的状态变化重画全部组头。
+ expect(automationGroupSource).not.toMatch(/useSessionAttentionKinds\s*\(/);
+ expect(automationGroupSource).not.toMatch(/useSessionAttentionSnapshot\s*\(/);
+ expect(automationGroupSource).not.toMatch(/useSessionAttentionUrgencySet\s*\(/);
+ expect(automationGroupSource).not.toMatch(/useRemoteSessionActivityRevision\s*\(/);
+ expect(automationGroupSource).toMatch(/useSessionsAttentionKindMap\(groupSessionIds\)/);
+ expect(automationGroupSource).toMatch(/useSessionsAttentionUrgencyIdSet\(groupSessionIds\)/);
+ expect(automationGroupSource).toMatch(/useRemoteSessionsPhaseMap\(groupSessionIds\)/);
+ });
+
it('feeds both regular and pinned project rows from their displayed children', () => {
expect(projectsSectionSource).toContain(
'collapsed.has(project.projectKey) ? collapsedAttentionToneFor(project.sessions) : null',
diff --git a/apps/desktop/src/renderer/features/cc-agent/contexts/SessionAttentionUrgencyContext.tsx b/apps/desktop/src/renderer/features/cc-agent/contexts/SessionAttentionUrgencyContext.tsx
index bc8e620320..e425ceaa4b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/contexts/SessionAttentionUrgencyContext.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/contexts/SessionAttentionUrgencyContext.tsx
@@ -27,6 +27,7 @@ import {
createContext,
useContext,
useEffect,
+ useMemo,
useRef,
useSyncExternalStore,
type ReactNode,
@@ -130,3 +131,27 @@ export function useSessionsAttentionUrgencyAny(sessionIds: readonly string[]): b
};
return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
}
+
+/**
+ * @returns 一组 session 里命中 urgent 的**子集** —— 折叠容器既要汇总红点、又要指出
+ * 是哪几条时用(定时任务分组头收起态把告警行提上来,见
+ * sidebar/projectCollapsedAttention.ts 的 errorSessionIds)。
+ * 快照是序列化 key(primitive),Set 由 useMemo 派生:组外成员变化、组内成员变化但
+ * 本组命中结果不变时都不重渲染 —— 不要改成直接返回新 Set(等同退回整集订阅)。
+ * 只需要布尔的场景用更省的 useSessionsAttentionUrgencyAny。
+ */
+export function useSessionsAttentionUrgencyIdSet(
+ sessionIds: readonly string[],
+): ReadonlySet<string> {
+ const store = useContext(SessionAttentionUrgencyContext);
+ const getSnapshot = () => {
+ const set = store.getSet();
+ let key = '';
+ for (const id of sessionIds) {
+ if (set.has(id)) key += `${id}|`;
+ }
+ return key;
+ };
+ const key = useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
+ return useMemo(() => new Set(key.split('|').filter(Boolean)), [key]);
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
index 7eeaabe6d8..4a25a6d950 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
@@ -193,6 +193,14 @@ export interface AutomationGroupChildViewOptions {
nowMs?: number;
/** 收起态默认展示条数,默认 5(和普通对话一致)。 */
minVisibleCount?: number;
+ /** 轴 1(文件夹开/关)的收起态。收起时只渲染 alertSessionIds 命中的运行,见下方 ⚠️。 */
+ collapsed?: boolean;
+ /**
+ * 收起态仍要保留可见的**未处理告警**运行 id,来源是
+ * `sidebar/projectCollapsedAttention.ts` 的 `resolveCollapsedAttention().errorSessionIds`
+ * —— 与组头红点、项目折叠头红点同一份判据。
+ */
+ alertSessionIds?: ReadonlySet<string>;
}
/**
@@ -204,6 +212,15 @@ export interface AutomationGroupChildViewOptions {
* 展开。**全部运行(含被组头代表的最新一条)都参与折叠并各自成行**,让最新未读也单独可见,
* 与「显示全部」一致;组头点击打开哪条由组件单独算(getAutomationGroupPrimarySession),
* 与列表行是"两个入口指向同一 session",不互斥。
+ *
+ * ⚠️ 收起态(options.collapsed)**不是空列表**:组内带未处理告警的运行会被提上来单独
+ * 成行。原因是「组头只代表最新一条」+「收起时子行整片不渲染」叠起来会藏掉告警 ——
+ * 项目折叠头按全部子任务汇总出红点,用户展开项目却在任何一行上都看不到它
+ * (实测:一条被 App 重启打断、turn 从未收尾的定时任务运行)。告警行与组头红点同源
+ * (alertSessionIds ← resolveCollapsedAttention),所以不可能出现「汇总说有、列表没有」。
+ * 这也是折叠上限里「需关注的条目始终显示」那条不变量本来就该覆盖的路径。
+ * 收起态刻意不套 24h / active 豁免:此时列表的语义是"只列要你处理的",
+ * 把非告警运行放进来会让收起形同失效。
*/
export function getAutomationGroupChildView(
group: AutomationSessionGroup,
@@ -217,6 +234,26 @@ export function getAutomationGroupChildView(
hiddenCount: 0,
});
+ // 收起:只提告警行。必须排在 frozen 之前 —— 冻结快照是展开态"前 N 条"防跳动用的,
+ // 收起态套上去会把非告警运行一起带回来。也必须排在下方的 showAll 短路之前:
+ // showAll 是两套列表共用的轴 2 状态,漏排会让收起态点过的「显示全部」把展开态
+ // 直接渲染成整组历史(见 AutomationSessionGroupItem 切折叠时的复位注释)。
+ if (options.collapsed) {
+ const alertIds = options.alertSessionIds;
+ const alertRuns = alertIds?.size ? allRuns.filter((session) => alertIds.has(session.id)) : [];
+ const limit = options.showAll
+ ? alertRuns.length
+ : Math.max(0, options.minVisibleCount ?? SESSION_LIST_COLLAPSE_MIN_VISIBLE_COUNT);
+ const visibleSessions = alertRuns.slice(0, limit);
+ return {
+ visibleSessions,
+ isOverflowing: alertRuns.length > visibleSessions.length,
+ // 收起态的「显示全部 N 个」N = 告警行总数(此时列表语义就是告警,不是整组)。
+ totalCount: alertRuns.length,
+ hiddenCount: alertRuns.length - visibleSessions.length,
+ };
+ }
+
// 展开:全量子运行。
if (options.showAll) return withoutOverflow(allRuns);
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index 92bd328169..79a667e68d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { ChevronDown, ChevronRight, EllipsisVertical, Play } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -29,13 +29,22 @@ import { scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBindi
import { hasSessionSelectionModifier, SessionItem } from './SessionItem';
import type { SessionClickHandler } from './SessionItem';
import { MENU_CONTENT_CLASS, MENU_ITEM_CLASS, MENU_SEPARATOR_CLASS } from './menuStyles';
-import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
-import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
+import {
+ useSessionAttentionUrgency,
+ useSessionsAttentionUrgencyIdSet,
+} from '../contexts/SessionAttentionUrgencyContext';
+import { useSessionAttentionKind, useSessionsAttentionKindMap } from '@/lib/sessionAttentionStore';
+import { useRemoteSessionsPhaseMap } from '@/features/device-link/remoteSessionActivityStore';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import {
projectSidebarSessionActivity,
resolveSidebarRightStatus,
+ type SidebarRightStatusKind,
} from './sidebarRightStatus';
+import {
+ resolveCollapsedAttention,
+ resolveCollapsedGroupRightStatus,
+} from './projectCollapsedAttention';
import { AutomationTimerIcon } from './AutomationTimerIcon';
import { SessionCard } from './SessionCard';
import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
@@ -122,8 +131,15 @@ export function AutomationSessionGroupItem({
}
toggleStoredCollapsed();
}, [collapsed, onCollapsedChange, toggleStoredCollapsed]);
- // 轴 2:展开后运行列表内部的「前 5 条 / 显示全部」临时态,离开自动收回。
+ // 轴 2:运行列表内部的「前 5 条 / 显示全部」临时态,离开自动收回。
+ // 收起告警列表和展开历史列表共用这一份状态,所以切折叠必须复位 —— 否则
+ // 收起态点过「显示全部」再展开会一次摊开整组历史(Codex #3184),对称地,
+ // 展开态点过「显示全部」再收起也会把整组历史带进告警列表。复位挂在
+ // collapsed 变化上,覆盖 chevron 与父层「收起所有分组」,不只一条点击路径。
const [showAll, setShowAll] = useState(false);
+ useLayoutEffect(() => {
+ setShowAll(false);
+ }, [collapsed]);
const [frozen, setFrozen] = useState<FrozenGroupState | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
const [rowTooltipOpen, setRowTooltipOpen] = useState(false);
@@ -133,6 +149,44 @@ export function AutomationSessionGroupItem({
// 变化才变,天然稳定,无需再靠 frozen 快照固定"代表会话"。
const latestSession = useMemo(() => getAutomationGroupLatestSession(group), [group]);
const latestSessionId = latestSession?.id;
+ // ── 收起态的整组汇总 ────────────────────────────────────────────────────────
+ // 组头收起时代表的是**整组**,不能只反映最新一条:组内任意一条运行留下未处理告警
+ // (典型是被 App 重启打断、turn 从未收尾的运行)时,项目折叠头会按全部子任务汇总出
+ // 红点,而此前组头只看最新一条、收起态子行又整片不渲染 —— 于是「项目行有红点、
+ // 展开后哪一行都没有」。判据复用项目折叠头那一份(resolveCollapsedAttention),
+ // 红点与被提上来的告警行同源,两者不可能再打架。
+ // 三个 hook 都是"一组 id"的 primitive 快照订阅(组外会话变化、组内不改变本组结果的
+ // 变化都不唤醒本组件),不要退回整表 / 整集订阅 —— 每个项目下都有若干组头在挂载。
+ const groupSessionIds = useMemo(
+ () => group.sessions.map((session) => session.id),
+ [group.sessions],
+ );
+ const groupAttentionKinds = useSessionsAttentionKindMap(groupSessionIds);
+ const groupUrgentSessionIds = useSessionsAttentionUrgencyIdSet(groupSessionIds);
+ const groupRemotePhases = useRemoteSessionsPhaseMap(groupSessionIds);
+ const collapsedAttention = useMemo(
+ () =>
+ resolveCollapsedAttention({
+ sessions: group.sessions,
+ runningSessionIds,
+ notifications,
+ attentionKinds: groupAttentionKinds,
+ urgentSessionIds: groupUrgentSessionIds,
+ remotePhaseOf: (sessionId) => groupRemotePhases.get(sessionId),
+ }),
+ [
+ group.sessions,
+ groupAttentionKinds,
+ groupRemotePhases,
+ groupUrgentSessionIds,
+ notifications,
+ runningSessionIds,
+ ],
+ );
+ const alertSessionIds = useMemo(
+ () => new Set(collapsedAttention.errorSessionIds),
+ [collapsedAttention],
+ );
// childView 的 24h 豁免依赖实时 now,必须每次渲染直接算,不能进 useMemo —— 否则依赖项
// 不变时时间窗口会被冻结,跨过 24h 阈值的运行不会及时移出豁免。与普通对话列表
// SessionEntryList 一致(它也是 render 内直接算 getSessionListCollapseView、不 memo);
@@ -145,20 +199,24 @@ export function AutomationSessionGroupItem({
frozenVisibleSessionIds: frozen?.visibleSessionIds ?? null,
// 实时 now:启用「最近 24h 内有活动不折叠」豁免,和普通对话列表一致。
nowMs: Date.now(),
+ collapsed,
+ alertSessionIds,
});
- // 轴 1 收起时藏掉全部子运行(只留组头);展开时才交给轴 2 的「前 5 / 显示全部」。
- const visibleSessions = collapsed ? [] : childView.visibleSessions;
- const attentionCount = group.attentionSessionIds.filter((id) => notifications.has(id)).length;
- // 组头右侧状态图标来源(全端统一 5 档色表:error 红 > awaiting TapTap 蓝 >
+ // 轴 1 收起时只留组头 + 被提上来的告警行;展开时交给轴 2 的「前 5 / 显示全部」。
+ // 两种形态都由 getAutomationGroupChildView 一处决定(见该函数的 ⚠️)。
+ const visibleSessions = childView.visibleSessions;
+ // 组头右侧状态图标的**基线**来源(全端统一 5 档色表:error 红 > awaiting TapTap 蓝 >
// running spinner > 完成未读绿 > time),两路信号都只看「最新一条」运行:
// 1. SessionAttentionUrgencyContext:该 run 是失败 schedule run(attentionKind 缺失
// 但语义等同 error)→ 红
// 2. sessionAttentionStore kind:该 run 有 chat 侧 urgent attention
// (错误终止 → 红;pending ask-user / 权限 → 蓝)
- // 组头状态 = 组内「最新一条」运行的状态(不再跨组聚合):折叠态下组头只代表最新那条,
- // 点击也打开它,状态/loading 与其保持一致。两个 hook 都按 latestSessionId 精准订阅
- // (boolean / kind primitive 快照),只有最新那条的 attention/urgency 翻转才唤醒本组件
- // (性能不变量,别退回整组 / 整张表订阅)。
+ // 组头是「最新一条运行的代理」:点击打开它,loading / vendor 呼吸与其一致。展开态右侧
+ // 状态就到此为止;**收起态**再叠一层整组汇总(上方 collapsedAttention +
+ // resolveCollapsedGroupRightStatus)—— 此时组头代表整组,组内任何一条的未处理告警都必须
+ // 露出来,否则会重演「项目折叠头有红点、展开却哪一行都没有」。
+ // 这两个 hook 仍按 latestSessionId 精准订阅(boolean / kind primitive 快照),整组那三个
+ // 也都是"一组 id"的 primitive 快照 —— 别退回整组对象 / 整张表订阅(性能不变量)。
const latestUrgentFromSchedule = useSessionAttentionUrgency(latestSessionId ?? '');
const latestChatKind = useSessionAttentionKind(latestSessionId ?? '');
const latestLiveActivity = useAgentIslandActivity(latestSessionId ?? '');
@@ -185,6 +243,8 @@ export function AutomationSessionGroupItem({
// 组头右侧状态槽复用 SessionItem 的 5 档色表(error 红 / awaiting 蓝 / running spinner /
// done 绿 / time 文字):四个 input 全部取「最新一条」运行,送进同一 resolveSidebarRightStatus,
// 于是组头右侧状态与最新 session 子行像素级一致(色号 / 图标尺寸 / 判定完全同源)。
+ // 收起态在这个基线之上叠整组汇总,见下方 groupRightStatusKind —— 色表与图标不变,
+ // 只是档位改由整组决定。
const latestHasNotification = latestSessionId != null && notifications.has(latestSessionId);
const groupActivity = projectSidebarSessionActivity({
sessionId: latestSessionId ?? '',
@@ -196,7 +256,14 @@ export function AutomationSessionGroupItem({
isRunning,
hasAttentionNotification: latestHasNotification,
});
- const groupRightStatusKind = resolveSidebarRightStatus(groupActivity);
+ // 收起态按整组汇总补足组头(展开态仍严格只看最新一条),判据见
+ // resolveCollapsedGroupRightStatus。isRunning 与 vendor / Timer 呼吸不受影响,仍跟
+ // 最新一条 —— 保住「loading 与最新 session 一致」那条既有裁决。
+ const groupRightStatusKind: SidebarRightStatusKind = resolveCollapsedGroupRightStatus({
+ collapsed,
+ latestKind: resolveSidebarRightStatus(groupActivity),
+ tone: collapsedAttention.tone,
+ });
const showRightStatus = groupRightStatusKind !== 'time';
const actionButtonToneClassName = hasActiveHidden
? 'text-sidebar-item-active-foreground hover:text-sidebar-item-active-foreground hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'
@@ -219,9 +286,13 @@ export function AutomationSessionGroupItem({
freezeCurrentLayoutRef.current = freezeCurrentLayout;
const showAllRef = useRef(showAll);
showAllRef.current = showAll;
+ // 收起态点告警行不冻结:冻结快照会把"当时可见的行"锁成布局,而收起态可见的只有
+ // 告警行 —— 之后用户展开这个组会看到被锁住的两三条告警行而不是正常的前 5 条运行。
+ const collapsedRef = useRef(collapsed);
+ collapsedRef.current = collapsed;
const handleChildSessionClick = useCallback<SessionClickHandler>(
(id, modifiers) => {
- if (!showAllRef.current && !hasSessionSelectionModifier(modifiers)) {
+ if (!collapsedRef.current && !showAllRef.current && !hasSessionSelectionModifier(modifiers)) {
freezeCurrentLayoutRef.current(id);
}
onSessionClick(id, modifiers);
@@ -461,8 +532,6 @@ export function AutomationSessionGroupItem({
// 阻止冒泡到行级 onClick(否则一次点击既切展开又打开会话)。
event.stopPropagation();
setFrozen(null);
- // 收起文件夹时顺手复位轴 2,下次展开从「前 5 条」开始,而不是停在「显示全部」。
- if (!collapsed) setShowAll(false);
toggleCollapsed();
}}
aria-expanded={!collapsed}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx
new file mode 100644
index 0000000000..0bd02fdce7
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/automationGroupCollapsedAlerts.test.tsx
@@ -0,0 +1,251 @@
+// @vitest-environment jsdom
+
+/**
+ * 定时任务分组头 —— 收起态的未处理告警必须可见(行为回归,不是源码形状断言)。
+ *
+ * 复现的线上现象:某项目折叠后行右侧亮红点,展开项目却在任何一行上都找不到它。
+ * 成因是两层折叠叠加 —— 组头此前只代表「最新一条」运行,而收起态子行整片不渲染,
+ * 于是「组内第 3 新的运行留下未处理告警」(实测是一条被 App 重启打断、turn 从未
+ * 收尾的定时任务运行)既不上组头、也不成行,而项目折叠头是按**全部**子任务汇总的。
+ *
+ * 本测试钉住修复后的两条:
+ * 1. 收起态组头按整组汇总点红(不是只看最新一条);
+ * 2. 收起态把带告警的那条运行提上来单独成行,用户能直接点开处置。
+ * 都从同一份判据(resolveCollapsedAttention)出发,所以不可能再「汇总说有、列表没有」。
+ */
+
+import { createElement, useState } from 'react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { Session } from '@/lib/ccAgent.types';
+import { addSessionAttention, clearSessionAttention } from '@/lib/sessionAttentionStore';
+
+// ── mocks:剥离与「收起态告警可见性」无关的重依赖 ─────────────────────────────
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: unknown) => (typeof fallback === 'string' ? fallback : key),
+ }),
+ initReactI18next: { type: '3rdParty' as const, init: () => {} },
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => vi.fn(),
+}));
+
+// 子行探针:只登记「哪些运行被渲染成行」,不拖进 SessionItem 的全套依赖。
+vi.mock('../SessionItem', () => ({
+ SessionItem: ({ session }: { session: { id: string } }) =>
+ createElement('div', { 'data-child-run': session.id }),
+ hasSessionSelectionModifier: () => false,
+}));
+
+vi.mock('../SessionCard', () => ({
+ SessionCard: ({ session }: { session: { id: string } }) =>
+ createElement('div', { 'data-child-run': session.id }),
+}));
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ children }: { children: React.ReactNode }) => children,
+}));
+
+vi.mock('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuContent: () => null,
+ DropdownMenuItem: () => null,
+ DropdownMenuSeparator: () => null,
+}));
+
+vi.mock('@/components/sidebar/VendorIcon', () => ({
+ VendorIcon: () => null,
+ agentKindToVendor: () => 'cc',
+}));
+
+vi.mock('../AutomationTimerIcon', () => ({
+ AutomationTimerIcon: () => null,
+}));
+
+vi.mock('@/state/agentIslandActivity', () => ({
+ useAgentIslandActivity: () => undefined,
+}));
+
+vi.mock('@/features/scheduler/lib/scheduleSessionBinding', () => ({
+ scheduleFocusPath: (id: string) => `/cc-agent/scheduled?focus=${id}`,
+}));
+
+// mock 之后再 import,确保组件拿到探针版依赖。
+import { AutomationSessionGroupItem } from '../AutomationSessionGroupItem';
+import { SessionAttentionUrgencyProvider } from '../../contexts/SessionAttentionUrgencyContext';
+
+// ── fixtures ─────────────────────────────────────────────────────────────────
+
+/** run-0 最新,序号越大越旧(sessionActivityMs 取 updatedAt / userSendAt 较新者)。 */
+function makeRun(index: number): Session {
+ const iso = new Date(Date.parse('2026-08-21T12:00:00.000Z') - index * 3_600_000).toISOString();
+ return {
+ id: `run-${index}`,
+ title: `[Schedule] 巡检 ${index}`,
+ status: 'active',
+ source: 'scheduler',
+ createdAt: iso,
+ updatedAt: iso,
+ userSendAt: iso,
+ pinnedAt: null,
+ sdkSessionId: null,
+ remoteHostId: null,
+ deviceLinkDeviceId: null,
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ _count: { messages: 5 },
+ } as unknown as Session;
+}
+
+const RUNS = [makeRun(0), makeRun(1), makeRun(2), makeRun(3)];
+const MANY_RUNS = Array.from({ length: 8 }, (_, index) => makeRun(index));
+const ALL_IDS = MANY_RUNS.map((run) => run.id);
+const noop = () => {};
+
+function GroupHarness({
+ sessions,
+ notifications,
+ urgentSessionIds,
+ initialCollapsed,
+}: {
+ sessions: Session[];
+ notifications: string[];
+ urgentSessionIds: ReadonlySet<string>;
+ initialCollapsed: boolean;
+}) {
+ const [collapsed, setCollapsed] = useState(initialCollapsed);
+ return createElement(SessionAttentionUrgencyProvider, {
+ urgentSessionIds,
+ children: createElement(AutomationSessionGroupItem, {
+ group: {
+ id: 'schedule:sched-1',
+ scheduleId: 'sched-1',
+ scheduleStatus: 'active',
+ title: '产品决策巡检',
+ sessions,
+ attentionSessionIds: notifications,
+ },
+ runningSessionIds: new Set<string>(),
+ attachedSessionIds: new Set<string>(),
+ notifications: new Set(notifications),
+ collapsed,
+ onCollapsedChange: setCollapsed,
+ onSessionClick: noop,
+ onAction: noop,
+ onRename: noop,
+ onTogglePin: noop,
+ onScheduleAction: noop,
+ }),
+ });
+}
+
+function renderGroup({
+ sessions = RUNS,
+ notifications = [],
+ urgentSessionIds = new Set<string>(),
+ collapsed = true,
+}: {
+ sessions?: Session[];
+ notifications?: string[];
+ urgentSessionIds?: ReadonlySet<string>;
+ collapsed?: boolean;
+} = {}) {
+ return render(
+ createElement(GroupHarness, {
+ sessions,
+ notifications,
+ urgentSessionIds,
+ initialCollapsed: collapsed,
+ }),
+ );
+}
+
+const childRunIds = (container: HTMLElement): string[] =>
+ [...container.querySelectorAll('[data-child-run]')].map(
+ (node) => node.getAttribute('data-child-run') ?? '',
+ );
+
+afterEach(() => {
+ cleanup();
+ for (const id of ALL_IDS) clearSessionAttention(id, { intent: 'explicit' });
+});
+
+beforeEach(() => {
+ for (const id of ALL_IDS) clearSessionAttention(id, { intent: 'explicit' });
+});
+
+describe('AutomationSessionGroupItem — 收起态的未处理告警', () => {
+ it('无告警时收起就是收起:组头不点状态、不渲染子行', () => {
+ const { container } = renderGroup();
+ expect(childRunIds(container)).toEqual([]);
+ expect(screen.queryByLabelText('Failed — click to view')).toBeNull();
+ });
+
+ it('组内非最新一条留下告警时,组头点红且该条被提上来成行', () => {
+ // run-2 = 「第 3 新、turn 从未收尾」的那条;组头代表的是 run-0。
+ addSessionAttention('run-2', 'error');
+ const { container } = renderGroup({ notifications: ['run-2'] });
+
+ expect(screen.getByLabelText('Failed — click to view')).toBeTruthy();
+ expect(childRunIds(container)).toEqual(['run-2']);
+ });
+
+ it('定时任务失败未读(attention kind 缺失)同样算告警,不被涂成完成绿', () => {
+ const { container } = renderGroup({
+ notifications: ['run-3'],
+ urgentSessionIds: new Set(['run-3']),
+ });
+
+ expect(screen.getByLabelText('Failed — click to view')).toBeTruthy();
+ expect(screen.queryByLabelText('Completed — click to view')).toBeNull();
+ expect(childRunIds(container)).toEqual(['run-3']);
+ });
+
+ it('只有完成未读时组头补绿点,但不提行(绿点不是待处理告警)', () => {
+ addSessionAttention('run-2', 'done');
+ const { container } = renderGroup({ notifications: ['run-2'] });
+
+ expect(screen.getByLabelText('Completed — click to view')).toBeTruthy();
+ expect(screen.queryByLabelText('Failed — click to view')).toBeNull();
+ expect(childRunIds(container)).toEqual([]);
+ });
+
+ it('等待回复(蓝)不升格成组头状态,也不提行', () => {
+ addSessionAttention('run-2', 'awaiting');
+ const { container } = renderGroup({ notifications: ['run-2'] });
+
+ expect(screen.queryByLabelText('Failed — click to view')).toBeNull();
+ expect(screen.queryByLabelText('Awaiting your input')).toBeNull();
+ expect(childRunIds(container)).toEqual([]);
+ });
+
+ it('收起态点过显示全部后再展开,不会把整组历史一次摊开', () => {
+ // 运行全部 >24h,展开态没有 24h 豁免;告警 6 条超过收起上限 5,所以能点「显示全部」。
+ // 收起态靠 urgent 提行,展开态既无 24h 也无未读 —— 只有残留 showAll 才会把第 8 条带出来。
+ const staleRuns = Array.from({ length: 8 }, (_, index) => {
+ const iso = new Date(
+ Date.parse('2026-08-10T12:00:00.000Z') - index * 3_600_000,
+ ).toISOString();
+ return { ...makeRun(index), createdAt: iso, updatedAt: iso, userSendAt: iso };
+ });
+ const alerts = staleRuns.slice(2).map((run) => run.id);
+ const { container } = renderGroup({
+ sessions: staleRuns,
+ urgentSessionIds: new Set(alerts),
+ });
+
+ expect(childRunIds(container)).toHaveLength(5);
+ fireEvent.click(screen.getByText(/ccAgent\.sidebar\.showAllSessions/));
+ expect(childRunIds(container)).toEqual(alerts);
+
+ fireEvent.click(screen.getByLabelText('ccAgent.sidebar.automationGroup.expand'));
+ const expandedIds = childRunIds(container);
+ expect(expandedIds).toEqual(['run-0', 'run-1', 'run-2', 'run-3', 'run-4']);
+ expect(expandedIds).not.toContain('run-7');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
index 8fea4ba2de..85f9eda0a2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
@@ -1,9 +1,12 @@
import type { AttentionKind } from '@/lib/sessionAttentionStore';
import type { RemoteSessionActivityPhase } from '@/features/device-link/remoteSessionActivityStore';
+import type { SidebarRightStatusKind } from './sidebarRightStatus';
-export type CollapsedProjectAttentionTone = 'error' | 'done';
+export type CollapsedAttentionTone = 'error' | 'done';
+/** @deprecated 保留旧名给既有调用点;新代码用 CollapsedAttentionTone。 */
+export type CollapsedProjectAttentionTone = CollapsedAttentionTone;
-interface CollapsedProjectAttentionInput {
+interface CollapsedAttentionInput {
sessions: readonly { id: string }[];
runningSessionIds: ReadonlySet<string>;
notifications: ReadonlySet<string>;
@@ -12,38 +15,100 @@ interface CollapsedProjectAttentionInput {
remotePhaseOf: (sessionId: string) => RemoteSessionActivityPhase | undefined;
}
+export interface CollapsedAttentionSummary {
+ /** 折叠容器右侧状态槽要显示的档位;两者都没有则 null(回落时间文字)。 */
+ tone: CollapsedAttentionTone | null;
+ /**
+ * 贡献红点的子任务 id —— **未处理告警**的集合。
+ *
+ * ⚠️ 这个列表存在的理由:折叠容器一旦汇总出红点,用户必须能找到那条子任务。
+ * 项目行展开后子任务各自成行,天然可达;定时任务分组收起时子行整片不渲染,
+ * 组头此前只代表「最新一条」运行,于是「组里第 3 新的运行有未处理告警」会变成
+ * 「项目折叠头亮红点、展开却哪儿都找不到」(实测:一条被 App 重启打断、turn 从未
+ * 收尾的定时任务运行)。分组收起态据此把告警行提上来,与本函数的 tone 同源,
+ * 不可能再出现「汇总说有、列表没有」。
+ */
+ errorSessionIds: readonly string[];
+}
+
/**
- * 折叠项目只汇总子任务实际可见的红/绿状态点。等待回复(蓝)与运行态不在此处
- * 升格;若红绿同时存在,错误红点优先。
+ * 折叠容器(项目行 / 定时任务分组头)汇总子任务实际可见的红/绿状态点。等待回复(蓝)
+ * 与运行态不在此处升格;若红绿同时存在,错误红点优先。
+ *
+ * 这是折叠态「什么算告警」的**唯一**判据:项目折叠头取 tone,定时任务分组头同时取
+ * tone 与 errorSessionIds(见该字段注释)。要改语义就只改这里,别在消费侧另写一份。
*/
-export function resolveCollapsedProjectAttentionTone({
+export function resolveCollapsedAttention({
sessions,
runningSessionIds,
notifications,
attentionKinds,
urgentSessionIds,
remotePhaseOf,
-}: CollapsedProjectAttentionInput): CollapsedProjectAttentionTone | null {
+}: CollapsedAttentionInput): CollapsedAttentionSummary {
let hasDone = false;
+ const errorSessionIds: string[] = [];
for (const session of sessions) {
const remotePhase = remotePhaseOf(session.id);
if (remotePhase) {
- if (remotePhase === 'error') return 'error';
- if (remotePhase === 'completed') hasDone = true;
+ if (remotePhase === 'error') errorSessionIds.push(session.id);
+ else if (remotePhase === 'completed') hasDone = true;
// 远程活动镜像是远程行右侧状态的权威来源;running / needs-interaction
// 分别显示 spinner / 蓝点,不能再被本地残留状态误汇总成红绿点。
continue;
}
- if (urgentSessionIds.has(session.id)) return 'error';
+ if (urgentSessionIds.has(session.id)) {
+ errorSessionIds.push(session.id);
+ continue;
+ }
if (!notifications.has(session.id)) continue;
const attentionKind = attentionKinds.get(session.id);
- if (attentionKind === 'error') return 'error';
+ if (attentionKind === 'error') {
+ errorSessionIds.push(session.id);
+ continue;
+ }
if (attentionKind === 'awaiting' || runningSessionIds.has(session.id)) continue;
hasDone = true;
}
- return hasDone ? 'done' : null;
+ return {
+ tone: errorSessionIds.length > 0 ? 'error' : hasDone ? 'done' : null,
+ errorSessionIds,
+ };
+}
+
+/** 只要 tone 的调用点(项目折叠头)。语义见 resolveCollapsedAttention。 */
+export function resolveCollapsedProjectAttentionTone(
+ input: CollapsedAttentionInput,
+): CollapsedAttentionTone | null {
+ return resolveCollapsedAttention(input).tone;
+}
+
+/**
+ * 定时任务分组头右侧状态槽的最终档位。
+ *
+ * 组头平时是「最新一条运行的代理」(状态 / loading / 点击目标都跟最新那条一致,
+ * 2026-08 既有裁决),展开态照此不变;收起态它代表的却是**整组**,于是按整组汇总补两档:
+ * - 汇总出 error → 强制红。压过 latest 的 running spinner,与全端色表
+ * error > awaiting > running > done 一致 ——「等你处理」永远最高。
+ * - 汇总出 done → 只在组头自身无状态可显(time)时补绿。绿点若压掉 spinner 会造成
+ * 「仍在跑却看起来已完成」的错觉(sidebarRightStatus 里有同款告警)。
+ * awaiting(蓝)刻意不升格,与项目折叠头口径一致。
+ */
+export function resolveCollapsedGroupRightStatus({
+ collapsed,
+ latestKind,
+ tone,
+}: {
+ collapsed: boolean;
+ latestKind: SidebarRightStatusKind;
+ tone: CollapsedAttentionTone | null;
+}): SidebarRightStatusKind {
+ if (!collapsed) return latestKind;
+ if (tone === 'error') return 'error';
+ if (tone === 'done' && latestKind === 'time') return 'done';
+ return latestKind;
}
diff --git a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
index 84c86bb124..2ec917bf55 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
@@ -18,7 +18,7 @@
* 按 sessionId 的稳定引用精准订阅(条目对象未替换时快照引用不变),禁止整表订阅。
*/
-import { useSyncExternalStore } from 'react';
+import { useMemo, useSyncExternalStore } from 'react';
export type RemoteSessionActivityPhase = 'running' | 'needs-interaction' | 'completed' | 'error';
@@ -82,6 +82,34 @@ export function useRemoteSessionActivity(sessionId: string): RemoteSessionActivi
);
}
+/** Hook —— 一组 sessionId 的 phase 子映射(无远程活动条目的不进结果)。
+ * 给"折叠容器按同一份判据汇总整组"的场景用(定时任务分组头,组内可能含
+ * device-link 远程运行)。快照是序列化 key(primitive),Map 由 useMemo 派生:
+ * 组外条目变化、以及组内 detail 类变化都不会触发重渲染 —— 别改成整表 revision
+ * 逐行用(会退化成整表订阅,违反文件头的性能不变量)。 */
+export function useRemoteSessionsPhaseMap(
+ sessionIds: readonly string[],
+): ReadonlyMap<string, RemoteSessionActivityPhase> {
+ const getSnapshot = (): string => {
+ let key = '';
+ for (const id of sessionIds) {
+ const phase = activityMap.get(id)?.phase;
+ if (phase) key += `${id}:${phase}|`;
+ }
+ return key;
+ };
+ const key = useSyncExternalStore(subscribeRemoteSessionActivity, getSnapshot, getSnapshot);
+ return useMemo(() => {
+ const map = new Map<string, RemoteSessionActivityPhase>();
+ for (const pair of key.split('|')) {
+ if (!pair) continue;
+ const sep = pair.lastIndexOf(':');
+ map.set(pair.slice(0, sep), pair.slice(sep + 1) as RemoteSessionActivityPhase);
+ }
+ return map;
+ }, [key]);
+}
+
function getRevision(): number {
return revision;
}
diff --git a/apps/desktop/src/renderer/lib/sessionAttentionStore.ts b/apps/desktop/src/renderer/lib/sessionAttentionStore.ts
index 5df6cc47ea..105446adcc 100644
--- a/apps/desktop/src/renderer/lib/sessionAttentionStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionAttentionStore.ts
@@ -1,4 +1,4 @@
-import { useSyncExternalStore } from 'react';
+import { useMemo, useSyncExternalStore } from 'react';
import { isTransientRemoteError, withTransientRemoteRetry } from '@cindy/maker-shared/device-link-contract';
@@ -411,6 +411,38 @@ export function useSessionsAttentionUrgentKind(
return useSyncExternalStore(subscribeSessionAttention, getSnapshot, getSnapshot);
}
+/** Hook —— 一组 session 的 sessionId → kind 子映射(组外会话不进结果)。
+ * 给"折叠容器要按同一份判据汇总整组、且需要知道**是哪几条**"的场景用
+ * (定时任务分组头:汇总红点 + 收起态把告警行提上来,见
+ * sidebar/projectCollapsedAttention.ts 的 errorSessionIds)。
+ * ⚠️ 快照必须是 primitive:内部先序列化成 key 字符串交给 useSyncExternalStore
+ * 按值比较,再由 useMemo 派生出引用稳定的 Map —— 组外会话的 attention 变化、
+ * 以及组内不改变本组 kind 的变化都不会触发重渲染。直接返回新 Map 会让**任何**
+ * 会话的 attention 变化重渲染全部消费组件,等同退回 useSessionAttentionKinds。
+ * 只回答"是什么 kind"的聚合场景仍用更省的 useSessionsAttentionUrgentKind。 */
+export function useSessionsAttentionKindMap(
+ sessionIds: readonly string[],
+): ReadonlyMap<string, AttentionKind> {
+ const getSnapshot = (): string => {
+ let key = '';
+ for (const id of sessionIds) {
+ const kind = attentionMap.get(id);
+ if (kind) key += `${id}:${kind}|`;
+ }
+ return key;
+ };
+ const key = useSyncExternalStore(subscribeSessionAttention, getSnapshot, getSnapshot);
+ return useMemo(() => {
+ const map = new Map<string, AttentionKind>();
+ for (const pair of key.split('|')) {
+ if (!pair) continue;
+ const sep = pair.lastIndexOf(':');
+ map.set(pair.slice(0, sep), pair.slice(sep + 1) as AttentionKind);
+ }
+ return map;
+ }, [key]);
+}
+
export function hasSessionAttention(sessionId: string): boolean {
return attentionMap.has(sessionId);
}