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(remote): 对齐任务状态与已读确认

Dashd5eb2f05114a
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index f397103212..2cf51a95ea 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -530,9 +530,9 @@ describe('automation-generated sessions', () => {
expect(sessionViewSource).toContain('useAutomationScheduleSessionInfo(sessionId)');
expect(sessionViewSource).not.toContain('useAutomationScheduleSessionIndex()');
expect(sessionViewSource).toContain('latestUnreadFailedRunId');
- expect(sessionViewSource).toContain('markScheduleRunsReadAndSync([currentUnreadFailedRunId])');
+ expect(sessionViewSource).toContain('markScheduleRunsReadAndSync([currentUnreadFailedRunId], remoteDeviceId ?? undefined)');
expect(sessionViewSource).toContain(
- 'useReadFailedScheduleRuns(unreadFailedScheduleRunIds, viewVisible && historyLoaded)',
+ 'useReadFailedScheduleRuns(unreadFailedScheduleRunIds, viewVisible && historyLoaded, remoteDeviceId ?? undefined)',
);
expect(bannerSource).toContain("t('chat.unreadFailedScheduleBanner.text')");
expect(zh.chat.unreadFailedScheduleBanner.text).toBe('此前有定时任务未完成,可查看运行记录。');
@@ -1075,7 +1075,8 @@ describe('automation-generated sessions', () => {
expect(storageSource).toContain("eq(sessions.source, 'scheduler')");
expect(storageSource).toContain('listDirectScheduleIdsByLegacyKey');
expect(storageSource).toContain('directScheduleId && directScheduleId !== row.id');
- expect(scheduleIndexHookSource).toContain('nextFireAt: run.nextFireAt');
+ expect(scheduleIndexHookSource).toContain('projectScheduleSidebarIndex(runs)');
+ expect(readFileSync(new URL('../features/scheduler/lib/projectScheduleSidebarIndex.ts', import.meta.url), 'utf8')).toContain('nextFireAt: run.nextFireAt');
expect(preloadSource).toContain('listSidebarIndexRuns');
});
diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
index 56d7ddaf5c..d557b44241 100644
--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
@@ -735,3 +735,53 @@ describe('refreshRemoteDeviceSessions retry', () => {
expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
});
});
+
+describe('remote schedule mirror', () => {
+ const snapshot = (readAt?: number) => ({ runs: [{
+ sessionId: 'schedule-session', runId: 'run', scheduleId: 'auto', scheduleName: 'auto',
+ scheduleStatus: 'active', status: 'failed', firedAt: 1, readAt,
+ }], inflightRunIds: [], inflightPolicies: [] });
+ it('bootstraps remote unread and refreshes only metadata on read', async () => {
+ const device = did();
+ invoke.mockResolvedValueOnce([session('schedule-session')]).mockResolvedValueOnce(snapshot());
+ await refreshRemoteDeviceSessions(device, 'Remote', { scope: 'both' });
+ expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')).toMatchObject({ hasUnreadFailedRun: true });
+ invoke.mockClear().mockResolvedValue(snapshot(10));
+ await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
+ expect(invoke).toHaveBeenCalledTimes(1);
+ expect(invoke).toHaveBeenCalledWith(device, 'maker:schedule:list-sidebar-index-runs', []);
+ expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')).toMatchObject({ hasUnreadFailedRun: false });
+ });
+ it('discards a late response after disconnect and keeps the existing mirror on failure', async () => {
+ const device = did();
+ invoke.mockResolvedValueOnce([session('schedule-session')]).mockResolvedValueOnce(snapshot());
+ await refreshRemoteDeviceSessions(device, 'Remote', { scope: 'both' });
+ invoke.mockRejectedValueOnce(new Error('channel not allowed'));
+ await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule', maxAttempts: 1 });
+ expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')?.hasUnreadFailedRun).toBe(true);
+ const pending = deferred<unknown>();
+ invoke.mockReturnValueOnce(pending.promise);
+ const refresh = refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
+ remoteProjectsStore.clear();
+ pending.resolve(snapshot(10));
+ expect(await refresh).toBe('superseded');
+ expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')).toBeUndefined();
+ });
+});
+
+it('does not publish unchanged schedule snapshots or swallow revocation', async () => {
+ const device = did();
+ remoteProjectsStore.setDeviceSessions(device, 'Remote', [session('s')]);
+ const data = { runs: [{ sessionId: 's', runId: 'r', scheduleId: 'a', scheduleName: 'a', scheduleStatus: 'active', status: 'success' }] };
+ invoke.mockResolvedValue(data);
+ await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
+ const info = remoteProjectsStore.getSessionScheduleInfo('s');
+ const listener = vi.fn();
+ const off = remoteProjectsStore.subscribe(listener);
+ await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
+ expect(remoteProjectsStore.getSessionScheduleInfo('s')).toBe(info);
+ expect(listener).not.toHaveBeenCalled();
+ off();
+ invoke.mockResolvedValueOnce([session('s')]).mockRejectedValueOnce(new Error('DEVICE_LINK_ACCESS_REVOKED'));
+ expect(await refreshRemoteDeviceSessions(device, undefined, { scope: 'both' })).toBe('revoked');
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index b0cdd2ebb2..b9a6dc9b99 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1958,12 +1958,12 @@ export function CCAgentSessionView({
const scheduleSessionInfo = useAutomationScheduleSessionInfo(sessionId);
const unreadFailedScheduleRunIds =
scheduleSessionInfo?.unreadFailedRunIds ?? EMPTY_UNREAD_FAILED_RUN_IDS;
- useReadFailedScheduleRuns(unreadFailedScheduleRunIds, viewVisible && historyLoaded);
+ useReadFailedScheduleRuns(unreadFailedScheduleRunIds, viewVisible && historyLoaded, remoteDeviceId ?? undefined);
const currentUnreadFailedRunId =
scheduleSessionInfo?.latestUnreadFailedRunId ?? unreadFailedScheduleRunIds[0];
const markCurrentUnreadFailedScheduleRun = useCallback(async (): Promise<boolean> => {
if (!currentUnreadFailedRunId) return true;
- const { failed, firstError } = await markScheduleRunsReadAndSync([currentUnreadFailedRunId]);
+ const { failed, firstError } = await markScheduleRunsReadAndSync([currentUnreadFailedRunId], remoteDeviceId ?? undefined);
if (failed.length === 0) return true;
toast.error(
t('ccAgent.layout.markAllReadFailed', {
@@ -1971,7 +1971,7 @@ export function CCAgentSessionView({
}),
);
return false;
- }, [currentUnreadFailedRunId, t]);
+ }, [currentUnreadFailedRunId, remoteDeviceId, t]);
const errorTailMsg = useMemo(() => {
const last = messages.length > 0 ? messages[messages.length - 1] : undefined;
return last &&
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 7ffb7b4fbb..d99c2a7d48 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -180,7 +180,7 @@ import {
type AutomationScheduleSessionInfo,
type AutomationSessionGroup,
} from './lib/automationSidebarGrouping';
-import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
+import { getSessionDeviceId, remoteProjectsStore, useRemoteScheduleIndex } from '@/features/device-link/remoteProjectsStore';
import {
getRemoteSessionActivity,
useRemoteSessionActivity,
@@ -464,6 +464,7 @@ export function CCAgentSidebarUpper() {
const activeSessionId = orcaMatch?.params.sessionId ?? match?.params.sessionId;
const filesSessionId = filesMatch?.params.sessionId;
const scheduleSessionIndex = usePublishedAutomationScheduleSessionIndex();
+ const remoteScheduleIndex = useRemoteScheduleIndex();
// 侧栏右侧 urgent 红点的"额外"来源:定时任务未读且失败(status != 'success')。
// sessionAttentionStore 只跟踪 chat 内 attention;schedule 未读通过 sidebarNotifications
// 合并进 hasAttentionNotification,但 attentionKind 缺失导致默认走绿(见 SessionItem
@@ -471,11 +472,11 @@ export function CCAgentSidebarUpper() {
// 把它们提到 urgent 红档,避免"失败的 automation 被涂成 Completed"的误导。
const unreadFailedScheduleSessionIds = useMemo(() => {
const next = new Set<string>();
- for (const [sessionId, info] of scheduleSessionIndex) {
+ for (const [sessionId, info] of [...scheduleSessionIndex, ...remoteScheduleIndex]) {
if (info.hasUnreadFailedRun) next.add(sessionId);
}
return next;
- }, [scheduleSessionIndex]);
+ }, [scheduleSessionIndex, remoteScheduleIndex]);
const navigate = useNavigate();
// Workdir-browse mode (skillhub Market sidebar pattern). When the user
@@ -630,12 +631,12 @@ export function CCAgentSidebarUpper() {
// 完成未读(如重启后 attention store 还没填充)会丢绿点(codex review)。
const railNotifications = useMemo(() => {
const unread = new Set<string>();
- for (const [sessionId, info] of scheduleSessionIndex) {
+ for (const [sessionId, info] of [...scheduleSessionIndex, ...remoteScheduleIndex]) {
if (info.hasUnreadRun) unread.add(sessionId);
}
if (unread.size === 0) return attentionNotifications;
return new Set([...attentionNotifications, ...unread]);
- }, [attentionNotifications, scheduleSessionIndex]);
+ }, [attentionNotifications, scheduleSessionIndex, remoteScheduleIndex]);
useOrcaWorkerAttentionWatcher(sessionsHook.sessions, activeSessionId);
@@ -1074,15 +1075,16 @@ function ExpandedView({
onSessionNeedsReply: handleSessionNeedsReply,
},
);
+ const remoteScheduleIndex = useRemoteScheduleIndex();
const attentionKinds = useSessionAttentionKinds();
const urgentSet = useSessionAttentionUrgencySet();
const unreadScheduleSessionIds = useMemo(() => {
const next = new Set<string>();
- for (const [sessionId, info] of scheduleSessionIndex) {
+ for (const [sessionId, info] of [...scheduleSessionIndex, ...remoteScheduleIndex]) {
if (info.hasUnreadRun) next.add(sessionId);
}
return next;
- }, [scheduleSessionIndex]);
+ }, [scheduleSessionIndex, remoteScheduleIndex]);
const sidebarNotifications = useMemo(() => {
if (unreadScheduleSessionIds.size === 0) return notifications;
return new Set([...notifications, ...unreadScheduleSessionIds]);
@@ -1091,16 +1093,16 @@ function ExpandedView({
const markAutomationSessionRunsRead = useCallback(
(sessionId: string) => {
- const info = scheduleSessionIndex.get(sessionId);
+ const info = remoteProjectsStore.getSessionScheduleInfo(sessionId) ?? scheduleSessionIndex.get(sessionId);
// 成功进入即已读;历史失败在任务内容实际展示时确认,保留横幅、只清红点。
const successUnreadRunIds = info ? unreadSuccessScheduleRunIds(info) : [];
if (successUnreadRunIds.length === 0) return;
// …AndSync:settle 后无条件触发 renderer 本地刷新。跨实例场景下这些 runId
// 可能在 DB 里早已被另一实例标为已读(main no-op 且不广播),没有本地刷新
// 通道的话,这里的过期未读快照永远等不到事件、红点无法自愈。
- void markScheduleRunsReadAndSync(successUnreadRunIds);
+ void markScheduleRunsReadAndSync(successUnreadRunIds, getSessionDeviceId(sessionId));
},
- [scheduleSessionIndex],
+ [scheduleSessionIndex, remoteScheduleIndex],
);
const orcaLeadWorkerMap = useOrcaLeadWorkerMap(sessions);
const effectiveRunningSessionIds = useMemo(() => {
@@ -3739,6 +3741,7 @@ function CollapsedView({
const startingSessionIds = useStartingSessionIds(runningSessionIds);
// 瓷砖未读点颜色按 attention kind(done 绿 / awaiting TapTap 蓝 / error 红);组件层
// 取一次,renderItem 里查表(renderItem 非组件,不能 per-item 用 hook)。
+
const attentionKinds = useSessionAttentionKinds();
// 失败 automation urgency 集合 —— rail 瓷砖也要按此把 failed schedule 涂红,不能
// 让"失败的定时任务"落到默认绿色 done tone(否则和 SessionItem 不一致,
@@ -4022,6 +4025,7 @@ function RailPanels({
// onOpenChange —— openSection 离开 projects 就同步清掉菜单状态,否则组件常驻
// (只是 return null),下次打开面板旧菜单会按旧坐标复现并引用旧项目(review)。
// 与下方 showAllProjects 的复位同构。
+
const attentionKinds = useSessionAttentionKinds();
const urgentSet = useSessionAttentionUrgencySet();
// 项目列表「显示全部」:面板关闭后复位(与 ProjectsSection 的段收起复位同语义)。
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 8473a5de15..eaffe04d7d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import type { SchedulerEvent } from '@cindy/maker-scheduler';
+import { useRemoteSessionScheduleInfo } from '@/features/device-link/remoteProjectsStore';
import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
import { createLogger } from '@/lib/logger';
import {
@@ -28,14 +29,9 @@ import {
scheduleClearSilencedRun,
} from '@/lib/silencedSessionDoneStore';
import type { AutomationScheduleSessionInfo } from '../lib/automationSidebarGrouping';
-import {
- isFailedScheduleRun,
- isUnreadFailedScheduleRun,
- isUnreadScheduleRun,
-} from '../../scheduler/lib/runUnread';
import { loadScheduleSidebarIndexSnapshot } from '../../scheduler/lib/scheduleSidebarIndexRuns';
import { subscribeScheduleRunReadSync } from '../../scheduler/lib/scheduleRunReadSync';
-import { compareFailedScheduleRuns } from '../../scheduler/lib/failedScheduleDismissal';
+import { projectScheduleSidebarIndex } from '../../scheduler/lib/projectScheduleSidebarIndex';
const log = createLogger('AutomationScheduleSessionIndex');
@@ -130,11 +126,13 @@ export function usePublishedAutomationScheduleSessionIndex(): ReadonlyMap<
export function useAutomationScheduleSessionInfo(
sessionId: string | undefined,
): AutomationScheduleSessionInfo | undefined {
- return useSyncExternalStore(
+ const remoteInfo = useRemoteSessionScheduleInfo(sessionId ?? '');
+ const localInfo = useSyncExternalStore(
subscribePublishedIndex,
() => (sessionId ? publishedIndex.get(sessionId) : undefined),
() => (sessionId ? publishedIndex.get(sessionId) : undefined),
);
+ return remoteInfo ?? localInfo;
}
/**
@@ -209,53 +207,7 @@ export function useAutomationScheduleSessionIndex(
}, RECONCILE_RECHECK_DELAY_MS);
}
- const next = new Map<string, AutomationScheduleSessionInfo>();
- const latestUnreadFailedFiredAt = new Map<string, number>();
- for (const run of runs) {
- if (!run.sessionId) continue;
- const existing = next.get(run.sessionId);
- const unreadRunIds = existing?.unreadRunIds ? [...existing.unreadRunIds] : [];
- const unreadFailedRunIds = existing?.unreadFailedRunIds
- ? [...existing.unreadFailedRunIds]
- : [];
- // 只对未读 run 累加(与 isUnreadScheduleRun 对齐)。failed / interrupted
- // 未读 run 拉高本 session 的 urgency 让侧栏涂红而不是涂绿。
- const isRunUnread = isUnreadScheduleRun(run);
- if (isRunUnread) unreadRunIds.push(run.runId);
- let latestFailedRun = existing?.latestFailedRun;
- if (isFailedScheduleRun(run)) {
- const candidate = { runId: run.runId, firedAt: run.firedAt ?? 0 };
- if (!latestFailedRun || compareFailedScheduleRuns(candidate, latestFailedRun) > 0)
- latestFailedRun = candidate;
- }
- let latestUnreadFailedRunId = existing?.latestUnreadFailedRunId;
- if (isUnreadFailedScheduleRun(run)) {
- unreadFailedRunIds.push(run.runId);
- const firedAt = run.firedAt ?? 0;
- if (
- firedAt >= (latestUnreadFailedFiredAt.get(run.sessionId) ?? Number.NEGATIVE_INFINITY)
- ) {
- latestUnreadFailedFiredAt.set(run.sessionId, firedAt);
- latestUnreadFailedRunId = run.runId;
- }
- }
- next.set(run.sessionId, {
- scheduleId: run.scheduleId,
- scheduleName: run.scheduleName,
- scheduleStatus: run.scheduleStatus,
- scheduleSource: run.scheduleSource,
- nextFireAt: run.nextFireAt,
- workingDir: run.workingDir,
- projectConfigId: run.projectConfigId,
- unreadRunIds,
- unreadFailedRunIds,
- latestUnreadFailedRunId,
- latestFailedRun,
- hasFailedRun: Boolean(existing?.hasFailedRun || isFailedScheduleRun(run)),
- hasUnreadRun: unreadRunIds.length > 0,
- hasUnreadFailedRun: unreadFailedRunIds.length > 0,
- });
- }
+ const next = projectScheduleSidebarIndex(runs);
applyOptimisticUnreads(next);
setIndex(next);
publishIndex(next);
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 5c4df0c077..e448908bbe 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -34,7 +34,7 @@ import {
useSessionsAttentionUrgencyIdSet,
} from '../contexts/SessionAttentionUrgencyContext';
import { useSessionAttentionKind, useSessionsAttentionKindMap } from '@/lib/sessionAttentionStore';
-import { useRemoteSessionsPhaseMap } from '@/features/device-link/remoteSessionActivityStore';
+import { useRemoteSessionActivity, useRemoteSessionsPhaseMap } from '@/features/device-link/remoteSessionActivityStore';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import {
projectSidebarSessionActivity,
@@ -222,7 +222,9 @@ export const AutomationSessionGroupItem = memo(function AutomationSessionGroupIt
// 也都是"一组 id"的 primitive 快照 —— 别退回整组对象 / 整张表订阅(性能不变量)。
const latestUrgentFromSchedule = useSessionAttentionUrgency(latestSessionId ?? '');
const latestChatKind = useSessionAttentionKind(latestSessionId ?? '');
- const latestLiveActivity = useAgentIslandActivity(latestSessionId ?? '');
+ const latestLocalActivity = useAgentIslandActivity(latestSessionId ?? '');
+ const latestRemoteActivity = useRemoteSessionActivity(latestSessionId ?? '');
+ const latestLiveActivity = latestRemoteActivity ?? latestLocalActivity;
const scheduleId = group.scheduleId;
// 「已停止」= paused(用户主动暂停)+ expired(计划到期不再触发);两者对用户体验
// 而言都是「不会再自动跑」,视觉上都在 Timer chip 上叠 Pause 徽标,并在 tooltip
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index ce62a35f59..d214721ea1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -83,6 +83,7 @@ import { prefetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
import { resolveSessionCardBody } from './sessionCardPreview';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
+import { useRemoteSessionScheduleInfo } from '@/features/device-link/remoteProjectsStore';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
import {
useSessionBoundSchedules,
@@ -171,15 +172,16 @@ export const SessionCard = memo(function SessionCard({
const attentionKind = useSessionAttentionKind(session.id);
const isUrgentFromContext = useSessionAttentionUrgency(session.id);
const remoteActivity = useRemoteSessionActivity(session.id);
+ const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
const sessionActivity = projectSidebarSessionActivity({
sessionId: session.id,
title: session.title,
recordStatus: session.status,
liveActivity: remoteActivity ?? islandActivity,
attentionKind,
- isUrgentFromContext,
+ isUrgentFromContext: isUrgentFromContext || remoteSchedule?.hasUnreadFailedRun === true,
isRunning,
- hasAttentionNotification,
+ hasAttentionNotification: hasAttentionNotification || remoteSchedule?.hasUnreadRun === true,
});
const leftIconRunning = sessionActivity.currentTurnActive === true;
const rightStatusKind = resolveSidebarRightStatus(sessionActivity);
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index 0820ed34bc..34152fe31c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -93,6 +93,7 @@ import { Tip } from '@/components/ui/tooltip';
import { prefetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
+import { useRemoteSessionScheduleInfo } from '@/features/device-link/remoteProjectsStore';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import { projectSidebarSessionActivity, resolveSidebarRightStatus } from './sidebarRightStatus';
@@ -401,15 +402,16 @@ export const SessionItem = memo(function SessionItem({
// 被控端灵动岛 relay 的活动镜像驱动(remoteSessionActivityStore,按行精准订阅;本地
// 会话恒 undefined 零开销)。镜像只保留活跃态与未读终态,映射与本地五档同一张色表。
const remoteActivity = useRemoteSessionActivity(session.id);
+ const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
const sessionActivity = projectSidebarSessionActivity({
sessionId: session.id,
title: session.title,
recordStatus: session.status,
liveActivity: remoteActivity ?? islandActivity,
attentionKind,
- isUrgentFromContext,
+ isUrgentFromContext: isUrgentFromContext || remoteSchedule?.hasUnreadFailedRun === true,
isRunning,
- hasAttentionNotification,
+ hasAttentionNotification: hasAttentionNotification || remoteSchedule?.hasUnreadRun === true,
});
const leftIconRunning = sessionActivity.currentTurnActive === true;
const rightStatusKind = resolveSidebarRightStatus(sessionActivity);
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 0a8f9608de..df8e396845 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/projectCollapsedAttention.ts
@@ -1,6 +1,5 @@
import type { AttentionKind } from '@/lib/sessionAttentionStore';
import type { RemoteSessionActivityPhase } from '@/features/device-link/remoteSessionActivityStore';
-import type { SidebarRightStatusKind } from './sidebarRightStatus';
export type CollapsedAttentionTone = 'error' | 'done';
/** @deprecated 保留旧名给既有调用点;新代码用 CollapsedAttentionTone。 */
@@ -50,6 +49,10 @@ export function resolveCollapsedAttention({
const errorSessionIds: string[] = [];
for (const session of sessions) {
+ if (urgentSessionIds.has(session.id)) {
+ errorSessionIds.push(session.id);
+ continue;
+ }
const remotePhase = remotePhaseOf(session.id);
if (remotePhase) {
if (remotePhase === 'error') errorSessionIds.push(session.id);
@@ -98,20 +101,7 @@ export function resolveCollapsedProjectAttentionTone(
* 「仍在跑却看起来已完成」的错觉(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;
-}
+export { resolveCollapsedGroupRightStatus } from '@cindy/maker-shared/session-activity';
/**
* 组头点击打开哪一条。展开态仍打开最新一条;收起且整组是红时,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
index 60e7dbfbae..83558c2ae1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
@@ -5,7 +5,8 @@ import {
import type { AttentionKind } from '@/lib/sessionAttentionStore';
-export type SidebarRightStatusKind = 'error' | 'awaiting' | 'running' | 'done' | 'time';
+export { resolveSessionRightStatus as resolveSidebarRightStatus } from '@cindy/maker-shared/session-activity';
+export type { SessionRightStatus as SidebarRightStatusKind } from '@cindy/maker-shared/session-activity';
export interface SidebarRightStatusInput {
sessionId: string;
@@ -68,18 +69,3 @@ export function projectSidebarSessionActivity({
attention: liveActivity?.attention === true || hasAttentionNotification || isUrgentFromContext,
});
}
-
-/**
- * 右侧状态槽优先级:error > awaiting > running > done(完成未读)> time。
- * error / awaiting 拆成两档两色(红 / TapTap 蓝),与灵动岛 phase 色表一致;
- * 两者都压过 running spinner —— "需要你处理"永远最高。
- */
-export function resolveSidebarRightStatus(
- activity: Pick<SessionActivitySnapshot, 'phase' | 'attention'>,
-): SidebarRightStatusKind {
- if (activity.phase === 'error' && activity.attention) return 'error';
- if (activity.phase === 'needs-interaction') return 'awaiting';
- if (activity.phase === 'running') return 'running';
- if (activity.phase === 'completed' && activity.attention) return 'done';
- return 'time';
-}
diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
index aa817ea50d..a4f9755fef 100644
--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
@@ -15,6 +15,8 @@
* 重试,覆盖被控端启动窗口;对**永久**错误(被控开关关 / channel 不允许)立即放弃,不空转。
*/
+import { projectScheduleSidebarIndex } from '../scheduler/lib/projectScheduleSidebarIndex';
+import type { ScheduleSidebarIndexSnapshot } from '../scheduler/lib/scheduleSidebarIndexRuns';
import type { Session } from '@/lib/ccAgent.types';
import { createLogger } from '@/lib/logger';
import { extractIpcError } from '@/utils/ipcError';
@@ -199,6 +201,7 @@ function backoffMs(attempt: number): number {
const realSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
export interface RefreshOptions {
+ scope?: 'sessions' | 'schedule' | 'both';
/** 注入式 sleep(测试用,默认真实 setTimeout)。 */
sleep?: (ms: number) => Promise<void>;
/** 最大尝试次数(含首次),默认 DEFAULT_MAX_ATTEMPTS。 */
@@ -285,6 +288,8 @@ export async function refreshRemoteDeviceSessions(
existing.opts = {
...existing.opts,
...opts,
+ scope:
+ (existing.opts.scope ?? 'sessions') === (opts.scope ?? 'sessions') ? opts.scope : 'both',
// 显式 replace 是更强的 snapshot 覆盖要求,不能被后续 merge 降级;默认的事件型
// refresh 则保持安全的有界 merge,并通过上面的强 coalescing 语义确保补跑。
snapshotMode:
@@ -400,42 +405,77 @@ async function runRefreshRemoteDeviceSessions(
// 被一次更新的重拉取代(期间又发起了新的 refresh)→ 停手,交给那一次(也避免无谓重试)。
if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';
try {
- const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:list', [
- listLimit,
- status,
- {
- includePinned: true,
- // 周期 tick 保持单飞;created / bootstrap 等事件重拉必须绕开写前查询。
- ...(opts.coalescingMode === 'weak' ? {} : { fresh: true }),
- },
- ]);
- // 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。
- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';
- const sessions = parseRemoteSessionList(value, status);
- if ((opts.snapshotMode ?? 'merge') === 'merge') {
- const incomingIds = new Set(sessions.map((session) => session.id));
- const missingSessionIds = remoteProjectsStore
- .getDeviceSessions(deviceId, status)
- .filter((session) => !incomingIds.has(session.id))
- .map((session) => session.id);
- // archived 使用与本地侧栏一致的 1000 条产品窗口,可直接替换并清掉断线期间的
- // 删除 / 取消归档陈旧行;active 仍保持 200 条轻量窗口,满窗时有界补查缺席缓存。
- if (status === 'archived' || sessions.length < LIST_LIMIT) {
- if (status === 'active') {
- missingStatusProbeQueues.delete(deviceId);
- for (const sessionId of missingSessionIds) {
- removeRemoteSessionActivityEntry(sessionId);
+ if (opts.scope !== 'schedule') {
+ const value = await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ 'local-db:sessions:list',
+ [
+ listLimit,
+ status,
+ {
+ includePinned: true,
+ // 周期 tick 保持单飞;created / bootstrap 等事件重拉必须绕开写前查询。
+ ...(opts.coalescingMode === 'weak' ? {} : { fresh: true }),
+ },
+ ],
+ );
+ // 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。
+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status))
+ return 'superseded';
+ const sessions = parseRemoteSessionList(value, status);
+ if ((opts.snapshotMode ?? 'merge') === 'merge') {
+ const incomingIds = new Set(sessions.map((session) => session.id));
+ const missingSessionIds = remoteProjectsStore
+ .getDeviceSessions(deviceId, status)
+ .filter((session) => !incomingIds.has(session.id))
+ .map((session) => session.id);
+ // archived 使用与本地侧栏一致的 1000 条产品窗口,可直接替换并清掉断线期间的
+ // 删除 / 取消归档陈旧行;active 仍保持 200 条轻量窗口,满窗时有界补查缺席缓存。
+ if (status === 'archived' || sessions.length < LIST_LIMIT) {
+ if (status === 'active') {
+ missingStatusProbeQueues.delete(deviceId);
+ for (const sessionId of missingSessionIds) {
+ removeRemoteSessionActivityEntry(sessionId);
+ }
+ }
+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
+ } else {
+ remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions, status);
+ if (status === 'active') {
+ await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);
}
}
- remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
} else {
- remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions, status);
- if (status === 'active') {
- await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);
+ remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
+ }
+ }
+ if (opts.scope === 'schedule' || opts.scope === 'both') {
+ try {
+ const raw = await window.electronAPI.deviceLink.invoke(
+ deviceId,
+ 'maker:schedule:list-sidebar-index-runs',
+ [],
+ );
+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status))
+ return 'superseded';
+ if (
+ !raw ||
+ typeof raw !== 'object' ||
+ !Array.isArray((raw as ScheduleSidebarIndexSnapshot).runs)
+ ) {
+ throw new Error('Invalid remote schedule index');
}
+ remoteProjectsStore.setDeviceScheduleIndex(
+ deviceId,
+ projectScheduleSidebarIndex((raw as ScheduleSidebarIndexSnapshot).runs),
+ );
+ } catch (error) {
+ // Older peers may not expose this existing channel. Keep the last mirror;
+ // failure of optional schedule metadata must not hide a valid session list.
+ if (opts.scope === 'schedule' || String(error).includes(ACCESS_REVOKED_MARKER))
+ throw error;
+ log.debug('remote schedule index unavailable');
}
- } else {
- remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
}
return 'ok'; // 成功
} catch (err) {
diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
index c2185bc697..8ed2297de3 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -38,6 +38,7 @@ import { useSyncExternalStore } from 'react';
import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
import type { DeviceLinkConnectionStatus, Session } from '@/lib/ccAgent.types';
import type { ListStatusFilter } from '@/lib/sessionService';
+import type { AutomationScheduleSessionInfo } from '../cc-agent/lib/automationSidebarGrouping';
import { clearCachedMessages } from './mirrorCacheClient';
export type RemoteSessionStatus = Exclude<ListStatusFilter, 'all'>;
@@ -51,9 +52,16 @@ interface DeviceShard {
sessions: Session[];
/** 已拿到过权威列表的状态桶;空数组同样需要被记住,避免每次渲染都重复拉取。 */
loadedStatuses: Set<RemoteSessionStatus>;
+ scheduleIndex?: ReadonlyMap<string, AutomationScheduleSessionInfo>;
}
const shards = new Map<string, DeviceShard>();
+let mergedScheduleIndex: ReadonlyMap<string, AutomationScheduleSessionInfo> = new Map();
+function recomputeScheduleIndex(): void {
+ const next = new Map([...shards.values()].flatMap((shard) => [...(shard.scheduleIndex ?? [])]));
+ if (JSON.stringify([...next]) !== JSON.stringify([...mergedScheduleIndex]))
+ mergedScheduleIndex = next;
+}
const subs = new Set<() => void>();
/**
* 正在读取任务快照的设备。它与 shard 是否存在独立:重连或手动重试时可以
@@ -294,6 +302,7 @@ function withPendingTitle(session: Session): Session {
/** 重算扁平快照 + origin 注册表,然后通知订阅者。所有 mutation 走这里。 */
function recompute(): void {
+ recomputeScheduleIndex();
sessionDeviceIndex.clear();
// 先铺 origin 钉子:分片还没到的新建远程会话也必须能被判定为远程(见 pinnedOrigins)。
// 分片派生值随后覆盖同 id 的条目。
@@ -394,6 +403,21 @@ function stamp(
}
const actions = {
+ setDeviceScheduleIndex(
+ deviceId: string,
+ index: ReadonlyMap<string, AutomationScheduleSessionInfo>,
+ ): void {
+ const shard = shards.get(deviceId);
+ if (!shard || JSON.stringify([...(shard.scheduleIndex ?? [])]) === JSON.stringify([...index]))
+ return;
+ shard.scheduleIndex = index;
+ recomputeScheduleIndex();
+ subs.forEach((fn) => fn());
+ },
+ getSessionScheduleInfo(sessionId: string): AutomationScheduleSessionInfo | undefined {
+ const deviceId = sessionDeviceIndex.get(sessionId);
+ return deviceId ? shards.get(deviceId)?.scheduleIndex?.get(sessionId) : undefined;
+ },
/**
* 写入 / 覆盖某台设备的整份会话列表(bootstrap 订阅后拉一次 / reconnect 重拉 / reseed)。
* rawSessions 是被控端 local-db:sessions:list 原样返回的 Session[],本函数负责打标记。
@@ -464,6 +488,7 @@ const actions = {
deviceName,
connectionStatus,
sessions: nextSessions,
+ scheduleIndex: existing?.scheduleIndex,
loadedStatuses,
});
recompute();
@@ -1070,3 +1095,21 @@ export function getSessionDeviceId(sessionId: string): string | undefined {
export function isRemoteDeviceMarkedDisconnected(deviceId: string): boolean {
return shards.get(deviceId)?.connectionStatus === 'disconnected';
}
+
+export function useRemoteSessionScheduleInfo(
+ sessionId: string,
+): AutomationScheduleSessionInfo | undefined {
+ return useSyncExternalStore(
+ subscribe,
+ () => actions.getSessionScheduleInfo(sessionId),
+ () => undefined,
+ );
+}
+
+export function useRemoteScheduleIndex(): ReadonlyMap<string, AutomationScheduleSessionInfo> {
+ return useSyncExternalStore(
+ subscribe,
+ () => mergedScheduleIndex,
+ () => mergedScheduleIndex,
+ );
+}
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index 298eef6b1a..c9136b8c54 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -376,7 +376,7 @@ export function useDeviceLinkRemoteProjects(): void {
if (disposed || !eligible.has(deviceId)) return;
// bootstrap 期间被撤销(subscribe 成功、list 被拒)→ refreshRemoteDeviceSessions 返 'revoked'
// (而非静默 give-up)→ 这里 handleRevoked,而不是继续预取能力 / 清撤销标记无视拒绝。
- const result = await refreshRemoteDeviceSessions(deviceId, name);
+ const result = await refreshRemoteDeviceSessions(deviceId, name, { scope: 'both' });
if (result === 'revoked') return void handleRevoked(deviceId);
if (disposed || !eligible.has(deviceId)) return;
if (result === 'gave-up') {
@@ -649,9 +649,15 @@ export function useDeviceLinkRemoteProjects(): void {
// 被控端 active-catalog 变化:供应商目录与 capabilities.availableModels 必须同代刷新。
// 两套缓存订阅会把完整结果原子推给已挂载选择器,刷新期间保留旧列表避免空白跳变。
const offRemotePush = window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {
- if (disposed || push.channel !== 'maker:provider:changed' || !eligible.has(push.deviceId))
- return;
+ if (disposed || !eligible.has(push.deviceId)) return;
if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;
+ if (push.channel === 'maker:schedule:event') {
+ void refreshRemoteDeviceSessions(push.deviceId, eligible.get(push.deviceId), { scope: 'schedule' }).then((result) => {
+ if (result === 'revoked' && !disposed) handleRevoked(push.deviceId);
+ });
+ return;
+ }
+ if (push.channel !== 'maker:provider:changed') return;
evictDeviceProviders(push.deviceId);
evictDeviceCapabilities(push.deviceId);
void prefetchDeviceProviders(push.deviceId);
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts
index 5da4a88772..19083b750a 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useReadFailedScheduleRuns.ts
@@ -6,7 +6,7 @@ import { markScheduleRunsReadAndSync } from '../lib/scheduleRunReadSync';
const log = createLogger('ReadFailedScheduleRuns');
/** 打开任务即确认失败已读,与通用横幅或具体错误的显示无关。 */
-export function useReadFailedScheduleRuns(runIds: readonly string[], viewVisible: boolean) {
+export function useReadFailedScheduleRuns(runIds: readonly string[], viewVisible: boolean, deviceId?: string) {
const windowVisible = useWindowVisible(viewVisible);
// 侧栏重查会重建数组;同一批记录的刷新不应循环重试失败的已读请求。
const runIdsKey = JSON.stringify([...runIds].sort());
@@ -15,10 +15,10 @@ export function useReadFailedScheduleRuns(runIds: readonly string[], viewVisible
if (!viewVisible || !windowVisible || !isWindowVisiblyFocused() || runIdsKey === '[]') return;
const seenRunIds: string[] = JSON.parse(runIdsKey);
// 只确认当前快照;已读状态不决定错误提示是否显示。
- void markScheduleRunsReadAndSync(seenRunIds)
+ void markScheduleRunsReadAndSync(seenRunIds, deviceId)
.then(({ failed }) => {
if (failed.length > 0) log.warn('Could not mark seen runs read', { count: failed.length });
})
.catch(() => log.warn('Could not sync seen runs'));
- }, [runIdsKey, viewVisible, windowVisible]);
+ }, [runIdsKey, viewVisible, windowVisible, deviceId]);
}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleRunReadSync.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleRunReadSync.test.ts
index 8be19f0255..2876908ba5 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleRunReadSync.test.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleRunReadSync.test.ts
@@ -119,3 +119,20 @@ describe('scheduleRunReadSync', () => {
expect(listener).not.toHaveBeenCalled();
});
});
+
+it('routes remote reads and the no-op refresh to the owning device only', async () => {
+ const { markRunRead } = stubScheduleApi({});
+ const invoke = vi.fn().mockResolvedValue({ runs: [] });
+ Object.assign(window.electronAPI, { deviceLink: { invoke } });
+ const listener = vi.fn();
+ const off = subscribeScheduleRunReadSync(listener);
+ try {
+ await markScheduleRunsReadAndSync(['remote-run'], 'remote-device');
+ expect(markRunRead).not.toHaveBeenCalled();
+ expect(invoke.mock.calls).toEqual([
+ ['remote-device', 'maker:schedule:mark-run-read', ['remote-run']],
+ ['remote-device', 'maker:schedule:list-sidebar-index-runs', []],
+ ]);
+ expect(listener).not.toHaveBeenCalled();
+ } finally { off(); }
+});
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
new file mode 100644
index 0000000000..8237663537
--- /dev/null
+++ b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
@@ -0,0 +1,54 @@
+import type { AutomationScheduleSessionInfo } from '../../cc-agent/lib/automationSidebarGrouping';
+import type { ScheduleSidebarIndexRun } from './scheduleSidebarIndexRuns';
+import { isFailedScheduleRun, isUnreadFailedScheduleRun, isUnreadScheduleRun } from './runUnread';
+import { compareFailedScheduleRuns } from './failedScheduleDismissal';
+
+/** Local and remote snapshots have the same unread projection. */
+export function projectScheduleSidebarIndex(
+ runs: readonly ScheduleSidebarIndexRun[],
+): Map<string, AutomationScheduleSessionInfo> {
+ const next = new Map<string, AutomationScheduleSessionInfo>();
+ const latestUnreadFailedFiredAt = new Map<string, number>();
+ for (const run of runs) {
+ if (!run.sessionId) continue;
+ const existing = next.get(run.sessionId);
+ const unreadRunIds = existing?.unreadRunIds ? [...existing.unreadRunIds] : [];
+ const unreadFailedRunIds = existing?.unreadFailedRunIds ? [...existing.unreadFailedRunIds] : [];
+ // 只对未读 run 累加(与 isUnreadScheduleRun 对齐)。failed / interrupted
+ // 未读 run 拉高本 session 的 urgency 让侧栏涂红而不是涂绿。
+ const isRunUnread = isUnreadScheduleRun(run);
+ if (isRunUnread) unreadRunIds.push(run.runId);
+ let latestFailedRun = existing?.latestFailedRun;
+ if (isFailedScheduleRun(run)) {
+ const candidate = { runId: run.runId, firedAt: run.firedAt ?? 0 };
+ if (!latestFailedRun || compareFailedScheduleRuns(candidate, latestFailedRun) > 0)
+ latestFailedRun = candidate;
+ }
+ let latestUnreadFailedRunId = existing?.latestUnreadFailedRunId;
+ if (isUnreadFailedScheduleRun(run)) {
+ unreadFailedRunIds.push(run.runId);
+ const firedAt = run.firedAt ?? 0;
+ if (firedAt >= (latestUnreadFailedFiredAt.get(run.sessionId) ?? Number.NEGATIVE_INFINITY)) {
+ latestUnreadFailedFiredAt.set(run.sessionId, firedAt);
+ latestUnreadFailedRunId = run.runId;
+ }
+ }
+ next.set(run.sessionId, {
+ scheduleId: run.scheduleId,
+ scheduleName: run.scheduleName,
+ scheduleStatus: run.scheduleStatus,
+ scheduleSource: run.scheduleSource,
+ nextFireAt: run.nextFireAt,
+ workingDir: run.workingDir,
+ projectConfigId: run.projectConfigId,
+ unreadRunIds,
+ unreadFailedRunIds,
+ latestUnreadFailedRunId,
+ latestFailedRun,
+ hasFailedRun: Boolean(existing?.hasFailedRun || isFailedScheduleRun(run)),
+ hasUnreadRun: unreadRunIds.length > 0,
+ hasUnreadFailedRun: unreadFailedRunIds.length > 0,
+ });
+ }
+ return next;
+}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts b/apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts
index 39721e9396..b40c830b3a 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/runUnread.ts
@@ -1,18 +1 @@
-import type { ScheduleRun } from '@cindy/maker-scheduler';
-
-type RunUnreadFields = Pick<ScheduleRun, 'readAt' | 'status'>;
-
-export function isFailedScheduleRun(run: Pick<ScheduleRun, 'status'>): boolean {
- return run.status === 'failed' || run.status === 'interrupted';
-}
-
-export function isUnreadFailedScheduleRun(run: RunUnreadFields): boolean {
- return !run.readAt && isFailedScheduleRun(run);
-}
-
-export function isUnreadScheduleRun(run: RunUnreadFields): boolean {
- return (
- !run.readAt &&
- (run.status === 'success' || run.status === 'failed' || run.status === 'interrupted')
- );
-}
+export { isFailedScheduleRun, isUnreadFailedScheduleRun, isUnreadScheduleRun } from '@cindy/maker-shared/schedule-model';
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts
index 5374a5d191..f53ab9e9b7 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleRunReadSync.ts
@@ -16,6 +16,8 @@
* main 侧广播语义保持不变(仍只在真实更新时发,其他窗口/消费方照旧)。
*/
+import { refreshRemoteDeviceSessions } from '../../device-link/refreshRemoteSessions';
+
type Listener = () => void;
const listeners = new Set<Listener>();
@@ -46,13 +48,16 @@ export interface MarkScheduleRunsReadResult {
*/
export async function markScheduleRunsReadAndSync(
runIds: readonly string[],
+ deviceId?: string,
): Promise<MarkScheduleRunsReadResult> {
const processed: string[] = [];
const failed: string[] = [];
let firstError: string | undefined;
if (runIds.length > 0) {
const results = await Promise.allSettled(
- runIds.map((runId) => window.electronAPI.maker.schedule.markRunRead(runId)),
+ runIds.map((runId) => deviceId
+ ? window.electronAPI.deviceLink.invoke(deviceId, 'maker:schedule:mark-run-read', [runId])
+ : window.electronAPI.maker.schedule.markRunRead(runId)),
);
results.forEach((result, index) => {
const runId = runIds[index];
@@ -67,7 +72,8 @@ export async function markScheduleRunsReadAndSync(
}
});
}
- emit();
+ if (deviceId) await refreshRemoteDeviceSessions(deviceId, undefined, { scope: 'schedule' });
+ else emit();
return firstError === undefined ? { processed, failed } : { processed, failed, firstError };
}
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index aaec681d4e..fcd2b162fd 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -229,7 +229,7 @@ import {
replaceSessionScheduleIndexEntries,
} from '@/session/scheduleIndex';
import { createScheduleIndexDeferRegistry } from '@/session/scheduleIndexDefer';
-import { resolveMobileSessionRightStatus } from '@/session/sessionRightStatus';
+import { latestMobileSessionRow, resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
import { AutomationTimerIcon } from '@/session/AutomationTimerIcon';
import { RenameSessionModal } from '@/session/RenameSessionModal';
import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';
@@ -3795,24 +3795,21 @@ function HomeSessionRowInner({
const { colors } = useTheme();
const { t } = useTranslation();
// 运行态走订阅而非命令式读取:行已 memo 化,父层不再逐 emit 重渲染,命令式读取会 stale。
- const sessionIsRunning = useSessionRunning(item.session.id);
+ const latestItem = latestMobileSessionRow(item);
+ const sessionIsRunning = useSessionRunning(latestItem.session.id);
// 已加载消息的预览按 session 订阅。普通流式 token 只让对应的可见行更新,首页根层、
// sections 和其它任务行都保持原引用。
const loadedMessagePreview = useRemoteSessionMessagePreview(item.session.id);
- const running = sessionIsRunning || !!item.scheduleInfo?.running;
+ const running = sessionIsRunning || !!latestItem.scheduleInfo?.running;
// attention 合并 main 的 #368:liveActivity.attention 也点亮关注态(组行直开 primary 的判定沿用)。
const attention = item.pendingInteractionCount > 0
|| (item.scheduleInfo?.unreadCount ?? 0) > 0
|| item.liveActivity?.attention === true;
// 右侧状态槽(替代时间位):与桌面侧栏同一套五档优先级与色表
// (error 红 > awaiting TapTap 蓝 > running spinner > 完成未读绿 > 时间)。
- const rightStatus = resolveMobileSessionRightStatus({
- liveAttention: item.liveActivity?.attention === true,
- livePhase: item.liveActivity?.phase,
- pendingInteractionCount: item.pendingInteractionCount,
- running,
- scheduleUnreadCount: item.scheduleInfo?.unreadCount ?? 0,
- });
+ const group = onToggleAutomationGroup ? item.automationGroup : undefined;
+ const groupExpanded = !!group && !!expandedAutomationGroups?.includes(group.key);
+ const { status: rightStatus, target: statusTarget } = resolveMobileSessionRowStatus(item, sessionIsRunning, groupExpanded);
const showDraftIndicator = readBooleanField(item.session, 'hasDraft')
|| readBooleanField(item.session, 'hasPausedQueue')
|| readBooleanField(item.session, 'composerDraft');
@@ -3823,8 +3820,6 @@ function HomeSessionRowInner({
const showPinned = !!item.session.pinnedAt;
// 自动化组行:同一任务的多次运行折叠而成(共享层 groupAutomationListItems 产出)。
// 没接展开回调的调用点退化为普通行为(点击打开 primary 会话)。
- const group = onToggleAutomationGroup ? item.automationGroup : undefined;
- const groupExpanded = !!group && !!expandedAutomationGroups?.includes(group.key);
// 块模式:组行 + 展开的子行整体包在一个上下全宽线的块里;组行自身不再画缩进分割线
// (收起时块底线紧贴行底,展开时组头与子行之间保持连续无线,均与项目组语义一致)。
const blockMode = asBlock && !!group;
@@ -3846,7 +3841,7 @@ function HomeSessionRowInner({
// 无需关注内容或已展开时,点行仍是展开 / 收起。
const openGroupPrimary = () => {
if (!group) return;
- const primary = group.items.find((child) => child.session.id === group.primarySessionId) ?? group.items[0];
+ const primary = statusTarget;
if (primary) onOpenSession(primary);
};
const groupRowOpensPrimary = !!group && attention && !groupExpanded;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 6823a114e9..9c531d4e22 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -727,7 +727,7 @@ function measureViewInWindow(view: View | null): Promise<{
}
/** 会话已读回执的驻留门槛:聚焦本会话且消息已渲染后停满这段时间才算「真实看到」。 */
-const SESSION_READ_ACK_DWELL_MS = 1_200;
+const SESSION_READ_ACK_DWELL_MS = 200;
/** 旧被控端没有 update-content 通道时的降级判定(与 mobileVoiceInput 同款字符串匹配)。 */
function isChannelNotAllowedError(err: unknown): boolean {
diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
index b324bc51b1..e5038c0880 100644
--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
@@ -64,6 +64,7 @@ describe('history window backfill wiring', () => {
});
it('不变量 3:同步门槛按 session + 连接代,不用屏幕级 lastSyncedAt', () => {
+ expect(source).toContain('const SESSION_READ_ACK_DWELL_MS = 200;');
expect(source).toContain('if (readAckSyncedKey !== `${sessionId}:${connectionEpoch}`) return;');
expect(source).not.toContain('|| lastSyncedAt === null) return;');
});
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 4466d7c95f..078738e595 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -282,7 +282,7 @@ describe('mobile home desktop-first surface', () => {
expect(vendorIconSource).not.toContain('transform="translate(');
expect(vendorIconSource).toContain('Easing.inOut(Easing.ease)');
// 行运行态经订阅获取(memo 化后命令式读取会 stale,2026-07-18 重渲染风暴修复)
- expect(homeSource).toContain('const sessionIsRunning = useSessionRunning(item.session.id);');
+ expect(homeSource).toContain('const sessionIsRunning = useSessionRunning(latestItem.session.id);');
// 保鲜契约:项目/自动化折叠只订阅低频首页状态;消息预览下沉到 session 行。
// 普通流式 token 不得再通过全局 storeVersion 唤醒整棵首页列表。
expect(homeSource).not.toContain('useRemoteSessionStoreVersion();');
@@ -339,7 +339,7 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('|| item.liveActivity?.attention === true;');
// 提醒点已从行首 icon 角标移到行右侧状态槽(替代时间位),五档判定与桌面
// sidebarRightStatus 对齐:error 红 > awaiting TapTap 蓝 > running spinner > 完成绿 > 时间。
- expect(source).toContain('resolveMobileSessionRightStatus({');
+ expect(source).toContain('resolveMobileSessionRowStatus(item, sessionIsRunning, groupExpanded)');
expect(source).toContain('styles.sessionRightDot');
expect(source).toContain('<SessionRightSpinner');
expect(source).not.toContain('sessionAttentionDot');
diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.ts
index 0894467bbf..b191694fb6 100644
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@ -8,6 +8,7 @@ import {
invalidateScheduleIndexForDevice,
invalidateTransientScheduleIndexFailureFor,
invalidateTransientScheduleIndexFailures,
+ loadLightweightSessionScheduleIndex,
loadSessionScheduleIndex,
loadSessionScheduleIndexThrottled,
replaceSessionScheduleIndexEntries,
@@ -622,3 +623,16 @@ describe('loadSessionScheduleIndexThrottled (单飞 + TTL 节流)', () => {
expect(maxInFlight).toBe(1);
});
});
+
+it('a drawer status read never replaces the full home binding cache', async () => {
+ resetScheduleIndexThrottleForTesting();
+ const full = new Map<string, RemoteSessionScheduleInfo>([['bound-no-run', {
+ scheduleId: 'a', scheduleName: 'a', unreadRunIds: [], unreadCount: 0, running: false, latestRunAt: 0,
+ }]]);
+ await loadSessionScheduleIndexThrottled('device', async () => full);
+ const invoke = vi.fn().mockResolvedValue({ runs: [] });
+ expect((await loadLightweightSessionScheduleIndex('device', invoke)).size).toBe(0);
+ const reload = vi.fn(async () => new Map<string, RemoteSessionScheduleInfo>());
+ expect(await loadSessionScheduleIndexThrottled('device', reload)).toBe(full);
+ expect(reload).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/sessionList.test.ts b/apps/mobile/src/__tests__/sessionList.test.ts
index b0139aed2b..de3309a4e9 100644
--- a/apps/mobile/src/__tests__/sessionList.test.ts
+++ b/apps/mobile/src/__tests__/sessionList.test.ts
@@ -1,5 +1,6 @@
import { performance } from 'node:perf_hooks';
import { beforeAll, describe, expect, it } from 'vitest';
+import { resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
import { i18n } from '@/i18n';
import {
buildSessionMessagePreviewIndex,
@@ -682,3 +683,28 @@ function createLargeSessionFixture(count: number): RemoteSession[] {
});
});
}
+
+it('schedule unread follows desktop: failed/interrupted are urgent, aborted is read', () => {
+ const index = buildSessionScheduleIndex([schedule('auto')], new Map([['auto', [
+ run('failed', 'auto', { sessionId: 's1', status: 'failed' }),
+ run('interrupted', 'auto', { sessionId: 's2', status: 'interrupted' }),
+ run('aborted', 'auto', { sessionId: 's3', status: 'aborted' }),
+ run('seen', 'auto', { sessionId: 's4', status: 'failed', readAt: 1 }),
+ ]]]));
+ expect(index.get('s1')).toMatchObject({ unreadCount: 1, hasUnreadFailedRun: true });
+ expect(index.get('s2')).toMatchObject({ unreadCount: 1, hasUnreadFailedRun: true });
+ expect(index.get('s3')).toMatchObject({ unreadCount: 0, hasUnreadFailedRun: false });
+ expect(index.get('s4')).toMatchObject({ unreadCount: 0, hasUnreadFailedRun: false });
+});
+
+it('collapsed errors open the failed run; expanded headers mirror the latest running row', () => {
+ const older = toRemoteSessionListItem(session('older'));
+ older.liveActivity = { sessionId: 'older', phase: 'error', attention: true, compactDetail: '' };
+ const latest = toRemoteSessionListItem(session('latest', { updatedAt: '2026-01-02T00:00:00.000Z' }));
+ const group = { ...older, automationGroup: {
+ key: 'g', baseKey: 'g', title: 'g', sessionIds: ['older', 'latest'], sessionCount: 2,
+ primarySessionId: 'older', children: [], items: [older, latest],
+ } };
+ expect(resolveMobileSessionRowStatus(group, true)).toEqual({ status: 'error', target: older });
+ expect(resolveMobileSessionRowStatus(group, true, true)).toEqual({ status: 'running', target: latest });
+});
diff --git a/apps/mobile/src/__tests__/sessionListDrawer.test.ts b/apps/mobile/src/__tests__/sessionListDrawer.test.ts
index ce2adb9a7c..bb8e6b2fcd 100644
--- a/apps/mobile/src/__tests__/sessionListDrawer.test.ts
+++ b/apps/mobile/src/__tests__/sessionListDrawer.test.ts
@@ -77,7 +77,7 @@ describe('mobile session list drawer', () => {
expect(text).toContain('excludeOrcaWorkerSessions(sessions)');
expect(text).toContain('buildMobileHomePresentation({');
expect(text).toContain('buildHomeSections(home, false, false)');
- expect(text).toContain('resolveMobileSessionRightStatus({');
+ expect(text).toContain('resolveMobileSessionRowStatus(item, sessionIsRunning)');
expect(text).toMatch(/buildRemoteSessionCardPreview\((?:(?!\);)[\s\S])*?\{ running \},?\s*\)/);
expect(text).toContain('formatRemoteSessionSidebarTime(lastActivityAt)');
expect(text).toContain('conversationSearchOriginsFromDeviceModels');
diff --git a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
index e2925db816..df645ab25c 100644
--- a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
+++ b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
@@ -7,6 +7,8 @@ import { SessionListDrawer } from "@/session/SessionListDrawer";
import { remoteSessionStore } from "@/session/remoteSessionStore";
import { buildMobileHomePresentation } from "@/session/mobileHome";
import { buildRemoteSessionCardPreview } from "@/session/sessionList";
+import { clearSessionScheduleIndexCache } from "@/session/scheduleIndex";
+import { remoteScheduleEventStore } from "@/scheduler/remoteScheduleEvents";
import { i18n } from "@/i18n";
import type { HomeRow, HomeSection } from "@/session/homeSections";
import type { RemoteMessage, RemoteSession } from "@/session/types";
@@ -235,6 +237,8 @@ describe("drawer selective updates", () => {
};
beforeEach(async () => {
+ clearSessionScheduleIndexCache();
+ remoteScheduleEventStore.clearAll();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.useFakeTimers();
remoteSessionStore.clear();
@@ -351,7 +355,7 @@ describe("drawer selective updates", () => {
}
});
- it("changes an automation group primary and its click target when an older run needs attention", async () => {
+ it("keeps the latest group run for an older waiting interaction, matching desktop", async () => {
remoteSessionStore.setDeviceSessions("dev-1", "Studio", [
session("old", { source: "scheduler", title: "daily" }),
session("new", {
@@ -372,14 +376,28 @@ describe("drawer selective updates", () => {
{ request: { kind: "ask_user_question", requestId: "question" } },
]),
);
- expect(row("new")).toBeNull();
- expect(status("old", "awaiting")).not.toBeNull();
- await act(async () => (row("old") as HTMLElement).click());
- expect(onSelect.mock.calls.at(-1)?.[0].session.id).toBe("old");
+ expect(row("old")).toBeNull();
+ expect(row("new")?.textContent).toContain("newer run");
+ await act(async () => (row("new") as HTMLElement).click());
+ expect(onSelect.mock.calls.at(-1)?.[0].session.id).toBe("new");
await act(async () => remoteSessionStore.setPendingInteractions("old", []));
expect(row("new")?.textContent).toContain("newer run");
});
+ it("refreshes failed unread from the lightweight host index when read elsewhere", async () => {
+ let readAt: number | undefined;
+ native.invoke.mockImplementation(async (_device, channel) => {
+ expect(channel).toBe("maker:schedule:list-sidebar-index-runs");
+ return { runs: [{ sessionId: "s1", scheduleId: "auto", runId: "run", scheduleName: "auto", scheduleStatus: "active", status: "failed", firedAt: 1, readAt }] };
+ });
+ await render();
+ expect(status("s1", "error")).not.toBeNull();
+ readAt = 10;
+ await act(async () => remoteScheduleEventStore.apply("dev-1", { type: "read", scheduleId: "auto" }));
+ expect(status("s1", "error")).toBeNull();
+ expect(native.invoke).toHaveBeenCalledTimes(2);
+ });
+
it("refreshes device search reachability without a session-array change", async () => {
remoteSessionStore.setConversationSearchDeviceModels([
{ deviceId: "dev-1", name: "Studio", canOpen: false, state: "offline" },
@@ -387,7 +405,7 @@ describe("drawer selective updates", () => {
await render();
await act(async () => native.search.onChangeQuery("needle"));
await tick(300);
- expect(native.invoke).not.toHaveBeenCalled();
+ expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(0);
const sessions = remoteSessionStore.getSessions();
await act(async () =>
remoteSessionStore.setConversationSearchDeviceModels([
@@ -396,8 +414,8 @@ describe("drawer selective updates", () => {
);
expect(remoteSessionStore.getSessions()).toBe(sessions);
await tick(300);
- expect(native.invoke).toHaveBeenCalledTimes(1);
- expect(native.invoke.mock.calls[0].slice(0, 2)).toEqual([
+ expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(1);
+ expect(native.invoke.mock.calls.find((call) => call[1] === "local-db:conversations:search")?.slice(0, 2)).toEqual([
"dev-1",
"local-db:conversations:search",
]);
@@ -432,9 +450,9 @@ describe("drawer selective updates", () => {
expect(row("s1")?.textContent).toContain("needle");
await act(async () => delta("s1", " more"));
await tick(100);
- expect(native.invoke).toHaveBeenCalledTimes(1);
+ expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(1);
await tick(300);
- expect(native.invoke).toHaveBeenCalledTimes(1);
+ expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(1);
});
it("preserves indexed hit snippets and message focus while newer loaded messages arrive", async () => {
diff --git a/apps/mobile/src/__tests__/sessionRightStatus.test.ts b/apps/mobile/src/__tests__/sessionRightStatus.test.ts
index eab03249df..ee8dfcde26 100644
--- a/apps/mobile/src/__tests__/sessionRightStatus.test.ts
+++ b/apps/mobile/src/__tests__/sessionRightStatus.test.ts
@@ -76,3 +76,9 @@ describe('resolveMobileSessionRightStatus', () => {
expect(resolveMobileSessionRightStatus(base)).toBe('time');
});
});
+
+it('unread failed automation is red even without a live activity, and clears after read', () => {
+ expect(resolveMobileSessionRightStatus({ ...base, scheduleUnreadCount: 1, scheduleHasUnreadFailedRun: true })).toBe('error');
+ expect(resolveMobileSessionRightStatus({ ...base, scheduleUnreadCount: 1, scheduleHasUnreadFailedRun: true, running: true })).toBe('error');
+ expect(resolveMobileSessionRightStatus({ ...base, scheduleUnreadCount: 0, scheduleHasUnreadFailedRun: false })).toBe('time');
+});
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index d5a32c380f..6b9b4c365f 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -73,6 +73,7 @@ import {
type PeerRecoveryResult,
} from '@/device-link/peerRecoveryScheduler';
import {
+ clearSessionScheduleIndexCache,
invalidateOfflineScheduleIndexFailureFor,
invalidateScheduleIndexForDevice,
invalidateTransientScheduleIndexFailureFor,
@@ -383,6 +384,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const clearPerAccountDeviceLinkState = useCallback(() => {
remoteSessionStore.clear();
+ clearSessionScheduleIndexCache();
remoteScheduleEventStore.clearAll();
revokedDevicesStore.clearAll();
resetDeviceResponsivenessTracking();
diff --git a/apps/mobile/src/session/SessionListDrawer.tsx b/apps/mobile/src/session/SessionListDrawer.tsx
index 2326677b92..e39a8121b2 100644
--- a/apps/mobile/src/session/SessionListDrawer.tsx
+++ b/apps/mobile/src/session/SessionListDrawer.tsx
@@ -1,3 +1,6 @@
+import { loadLightweightSessionScheduleIndex } from './scheduleIndex';
+import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
/**
* SessionListDrawer —— 宽屏(iPad / 折叠屏展开 / 横屏手机)会话页的任务列表抽屉。
*
@@ -65,7 +68,7 @@ import {
useSessionRunning,
} from '@/session/remoteSessionStore';
import type { RemoteSessionLiveActivity } from '@/session/sessionList';
-import { resolveMobileSessionRightStatus } from '@/session/sessionRightStatus';
+import { latestMobileSessionRow, resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
import {
buildRemoteSessionCardPreview,
buildSessionMessagePreviewIndex,
@@ -304,6 +307,37 @@ export function SessionListDrawer({
sort: t(`devices.list.search.filter.sort.${indexedSearch.sortBy}`),
status: t(`devices.list.search.filter.status.${indexedSearch.statusFilter}`),
});
+ const { invoke } = useDeviceLink();
+ const [scheduleIndex, setScheduleIndex] = useState<ReadonlyMap<string, import('./sessionList').RemoteSessionScheduleInfo>>(() => new Map());
+ const scheduleDeviceIdsKey = devices.map((device) => device.deviceId).sort().join(',');
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ const perDevice = new Map<string, ReadonlyMap<string, import('./sessionList').RemoteSessionScheduleInfo>>();
+ const requestVersions = new Map<string, number>();
+ const ids = scheduleDeviceIdsKey.split(',').filter(Boolean);
+ const versions = new Map(ids.map((id) => [id, remoteScheduleEventStore.getSnapshot(id).sessionIndexVersion]));
+ const refresh = (id: string) => {
+ const request = (requestVersions.get(id) ?? 0) + 1;
+ requestVersions.set(id, request);
+ void loadLightweightSessionScheduleIndex(id, invoke).then((index) => {
+ if (cancelled || requestVersions.get(id) !== request) return;
+ perDevice.set(id, index);
+ setScheduleIndex(new Map([...perDevice.values()].flatMap((entries) => [...entries])));
+ }).catch(() => undefined);
+ };
+ ids.forEach(refresh);
+ const off = remoteScheduleEventStore.subscribe(() => {
+ for (const id of ids) {
+ const version = remoteScheduleEventStore.getSnapshot(id).sessionIndexVersion;
+ const previous = versions.get(id) ?? 0;
+ versions.set(id, version);
+ if (version <= previous) continue;
+ refresh(id);
+ }
+ });
+ return () => { cancelled = true; off(); };
+ }, [open, scheduleDeviceIdsKey, invoke]);
const sections = useMemo<HomeSection[]>(() => {
if (!mounted) return [];
if (shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status)) {
@@ -347,19 +381,15 @@ export function SessionListDrawer({
liveActivityIndex: new Map(liveActivityEntries),
messagePreviewIndex,
pendingInteractionIndex,
- // scheduleIndex **刻意不接**:它靠 1+N×listRuns RPC 水合,仓内把这条链路限制在
- // 首页/设备详情页并配 defer+30s 节流(见 scheduleIndex.ts / scheduleIndexDefer.ts,
- // issue 324:单 WS 管道被背景 listRuns 拥塞会拖慢会话打开的关键读)。抽屉是瞬态
- // 切换器:分组与名称由共享层 fallbackScheduleInfo 兜底,主选与运行态由
- // pendingInteractionIndex / liveActivity / useSessionRunning 覆盖,仅缺 schedule
- // 未读绿点这档次要徽标——不值得从会话页新开一个取数点。
+ // Visible drawer state only; the lightweight status index never replaces the home binding cache.
+ scheduleIndex,
sessions: excludeOrcaWorkerSessions(sessions),
statusFilter: 'active',
// 已解析的 i18n 文案传给共享层(共享层不出中文串;en/ja/ko 不再回退「未命名任务」)。
unnamedLabel: t('session.menu.unnamedTitle'),
});
return buildHomeSections(home, false, false);
- }, [devices, homeStatusVersion, indexedSearch.results, indexedSearch.status, messageSearchVersion, mounted, searchQuery, sessions, t]);
+ }, [scheduleIndex, devices, homeStatusVersion, indexedSearch.results, indexedSearch.status, messageSearchVersion, mounted, searchQuery, sessions, t]);
const hasRows = useMemo(
() => sections.some((section) => section.data.length > 0),
[sections],
@@ -527,21 +557,17 @@ const DrawerSessionRow = memo(function DrawerSessionRow({
const { colors } = useTheme();
const { t } = useTranslation();
// 运行态走订阅(行 memo 化后命令式读取会 stale,与首页行同一取舍)。
- const sessionIsRunning = useSessionRunning(item.session.id);
+ const latestItem = latestMobileSessionRow(item);
+ const sessionIsRunning = useSessionRunning(latestItem.session.id);
const loadedMessagePreview = useRemoteSessionMessagePreview(item.session.id);
- const running = sessionIsRunning || !!item.scheduleInfo?.running;
- const rightStatus = resolveMobileSessionRightStatus({
- liveAttention: item.liveActivity?.attention === true,
- livePhase: item.liveActivity?.phase,
- pendingInteractionCount: item.pendingInteractionCount,
- running,
- scheduleUnreadCount: item.scheduleInfo?.unreadCount ?? 0,
- });
+ const running = sessionIsRunning || !!latestItem.scheduleInfo?.running;
+ const { status: rightStatus, target: statusTarget } = resolveMobileSessionRowStatus(item, sessionIsRunning);
// 索引搜索展示命中摘要;普通行(含自动化代表行)才使用自己的最新消息预览。
+ const previewItem = item.automationGroup ? statusTarget : item;
const preview = buildRemoteSessionCardPreview(
- searchResult || loadedMessagePreview === undefined || loadedMessagePreview === item.messagePreview
- ? item
- : { ...item, messagePreview: loadedMessagePreview },
+ searchResult || loadedMessagePreview === undefined || loadedMessagePreview === previewItem.messagePreview
+ ? previewItem
+ : { ...previewItem, messagePreview: loadedMessagePreview },
{ running },
);
return (
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index 11593280e5..dff90e2666 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -235,7 +235,7 @@ export function getScheduleIndexInvalidationVersion(deviceId: string): number {
}
/** Test-only: clear cache and invalidation generations. */
-export function resetScheduleIndexThrottleForTesting(): void {
+export function clearSessionScheduleIndexCache(): void {
scheduleIndexThrottleEntries.clear();
scheduleIndexInvalidationVersions.clear();
}
@@ -294,6 +294,7 @@ function scheduleInfoEqual(a: RemoteSessionScheduleInfo, b: RemoteSessionSchedul
return a.scheduleId === b.scheduleId
&& a.scheduleName === b.scheduleName
&& a.unreadCount === b.unreadCount
+ && !!a.hasUnreadFailedRun === !!b.hasUnreadFailedRun
&& a.running === b.running
&& a.latestRunAt === b.latestRunAt
&& a.scheduleStatus === b.scheduleStatus
@@ -306,3 +307,24 @@ function stringListsEqual(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) return false;
return a.every((item, index) => item === b[index]);
}
+
+export const resetScheduleIndexThrottleForTesting = clearSessionScheduleIndexCache;
+
+/** Existing lightweight host query; never starts the schedule list + per-run scan. */
+export async function loadLightweightSessionScheduleIndex(deviceId: string, invoke: RemoteInvoke): Promise<Map<string, RemoteSessionScheduleInfo>> {
+ const raw = await invoke<{ runs?: unknown[] }>(deviceId, 'maker:schedule:list-sidebar-index-runs', []);
+ if (!raw || !Array.isArray(raw.runs)) throw new Error('Invalid schedule index');
+ const schedules = new Map<string, import('@/scheduler/types').RemoteSchedule>();
+ const runs = new Map<string, RemoteScheduleRun[]>();
+ for (const value of raw.runs) {
+ if (!value || typeof value !== 'object') throw new Error('Invalid schedule index row');
+ const row = value as Record<string, unknown>;
+ if (typeof row.scheduleId !== 'string' || typeof row.runId !== 'string' || typeof row.scheduleName !== 'string') throw new Error('Invalid schedule index row');
+ const schedule = normalizeScheduleList([{ id: row.scheduleId, name: row.scheduleName, status: row.scheduleStatus }])[0];
+ const run = normalizeScheduleRuns([{ ...row, id: row.runId }])[0];
+ if (!schedule || !run) throw new Error('Invalid schedule index row');
+ schedules.set(schedule.id, schedule);
+ runs.set(schedule.id, [...(runs.get(schedule.id) ?? []), run]);
+ }
+ return buildSessionScheduleIndex([...schedules.values()], runs);
+}
diff --git a/apps/mobile/src/session/sessionRightStatus.ts b/apps/mobile/src/session/sessionRightStatus.ts
index 378d93ec44..1b8e5d80b0 100644
--- a/apps/mobile/src/session/sessionRightStatus.ts
+++ b/apps/mobile/src/session/sessionRightStatus.ts
@@ -14,12 +14,18 @@
* 手机端只消费,不自己猜。
* - pendingInteractionCount:实时待处理交互数(ask-user / 权限 / 计划审阅)——
* 即使 liveActivity 缺失(relay 断连)也能点亮 awaiting。
- * - scheduleUnreadCount:定时任务未读运行数(schedule 索引)。注意手机端的
- * schedule 索引暂不带"失败结局"信息,失败未读会落绿档(桌面是红);
- * 等共享层补充 hasUnreadFailedRun 后在这里升红。
+ * - scheduleUnreadCount / scheduleHasUnreadFailedRun:同桌面自动化运行账本。
*/
+import { projectSessionActivity, resolveSessionRightStatus, resolveCollapsedGroupRightStatus, type SessionRightStatus } from '@cindy/maker-shared/session-activity';
-export type MobileSessionRightStatus = 'error' | 'awaiting' | 'running' | 'done' | 'time';
+type SessionRow = import('@cindy/maker-shared/session-list').RemoteSessionListItem;
+export type MobileSessionRightStatus = SessionRightStatus;
+
+export function latestMobileSessionRow(item: SessionRow): SessionRow {
+ return item.automationGroup?.items.reduce((a, b) =>
+ Date.parse(b.session.userSendAt ?? b.session.updatedAt ?? b.session.createdAt) > Date.parse(a.session.userSendAt ?? a.session.updatedAt ?? a.session.createdAt) ? b : a,
+ ) ?? item;
+}
export interface MobileSessionRightStatusInput {
/** liveActivity.phase(缺失 = 无 relay 数据)。 */
@@ -32,6 +38,7 @@ export interface MobileSessionRightStatusInput {
running: boolean;
/** 定时任务未读运行数。 */
scheduleUnreadCount: number;
+ scheduleHasUnreadFailedRun?: boolean;
}
export function resolveMobileSessionRightStatus({
@@ -40,12 +47,42 @@ export function resolveMobileSessionRightStatus({
pendingInteractionCount,
running,
scheduleUnreadCount,
+ scheduleHasUnreadFailedRun = false,
}: MobileSessionRightStatusInput): MobileSessionRightStatus {
- if (liveAttention && livePhase === 'error') return 'error';
- if (pendingInteractionCount > 0 || (liveAttention && livePhase === 'needs-interaction')) {
- return 'awaiting';
- }
- if (running) return 'running';
- if (scheduleUnreadCount > 0 || (liveAttention && livePhase === 'completed')) return 'done';
- return 'time';
+ return resolveSessionRightStatus(projectSessionActivity({
+ sessionId: '',
+ livePhase,
+ running,
+ waitingForUser: pendingInteractionCount > 0,
+ terminal: scheduleHasUnreadFailedRun ? 'error' : scheduleUnreadCount > 0 ? 'completed' : null,
+ attention: liveAttention || pendingInteractionCount > 0 || scheduleUnreadCount > 0 || scheduleHasUnreadFailedRun,
+ }));
+}
+
+/** Group header mirrors the latest run; collapsed errors remain discoverable. */
+export function resolveMobileSessionRowStatus(
+ item: import('@cindy/maker-shared/session-list').RemoteSessionListItem,
+ running: boolean,
+ expanded = false,
+): { status: MobileSessionRightStatus; target: import('@cindy/maker-shared/session-list').RemoteSessionListItem } {
+ const children = item.automationGroup?.items;
+ const latest = latestMobileSessionRow(item);
+ const statusOf = (row: typeof item, isRunning: boolean) => resolveMobileSessionRightStatus({
+ livePhase: row.liveActivity?.phase,
+ liveAttention: row.liveActivity?.attention === true,
+ pendingInteractionCount: row.pendingInteractionCount,
+ running: isRunning || row.liveActivity?.phase === 'running' || row.scheduleInfo?.running === true,
+ scheduleUnreadCount: row.scheduleInfo?.unreadCount ?? 0,
+ scheduleHasUnreadFailedRun: row.scheduleInfo?.hasUnreadFailedRun,
+ });
+ const error = children?.find((row) => statusOf(row, false) === 'error');
+ const hasDone = children?.some((row) => statusOf(row, false) === 'done');
+ return {
+ status: resolveCollapsedGroupRightStatus({
+ collapsed: !expanded,
+ latestKind: statusOf(latest, running),
+ tone: error ? 'error' : hasDone ? 'done' : null,
+ }),
+ target: !expanded && error ? error : latest,
+ };
}
diff --git a/packages/maker-shared/src/__tests__/mobileHome.test.ts b/packages/maker-shared/src/__tests__/mobileHome.test.ts
index 467dfaa4c6..52aa988316 100644
--- a/packages/maker-shared/src/__tests__/mobileHome.test.ts
+++ b/packages/maker-shared/src/__tests__/mobileHome.test.ts
@@ -521,7 +521,7 @@ describe('mobileHome', () => {
expect(home.projects[0].sessions.map((item) => [item.session.id, item.automationGroup])).toEqual([['solo-run', undefined]]);
});
- it('keeps the grouped automation row activity on the newest run even when an older unread run is primary', () => {
+ it('keeps the latest run as primary when an older successful run is unread', () => {
// 旧 run 未读(primary 选中它)+ 新 run 已读:组行与项目卡的活动时间必须跟最新一条,
// 否则该项目卡会按旧时间排到别的项目后面(P2 回归)。
const scheduleInfo = (latestRunAt: number, unread: boolean) => ({
@@ -546,15 +546,14 @@ describe('mobileHome', () => {
});
const row = home.projects[0].sessions[0];
- // primary 是未读的旧 run,但组行活动时间取最新一条(new-read)。
- expect(row.automationGroup?.primarySessionId).toBe('old-unread');
+ // 成功未读不改变组头代理,展开子行仍能看到旧运行。
+ expect(row.automationGroup?.primarySessionId).toBe('new-read');
expect(row.lastActivityAt).toBe('2026-01-01T12:00:00.000Z');
expect(home.projects[0].latestActivityAt).toBe('2026-01-01T12:00:00.000Z');
});
- it('routes the grouped automation primary to the run waiting for interaction', () => {
- // 旧 run 有待处理交互、新 run 正常:primary 必须是等用户行动的那条(点行直开它),
- // 不能落在最新一条把待确认内容藏进展开列表(P2 回归)。
+ it('keeps the latest primary when an older run waits for interaction, matching desktop', () => {
+ // 与 Desktop 一致,旧运行的待处理交互保留在展开子行。
const scheduleInfo = (latestRunAt: number) => ({
scheduleId: 'sched-1',
scheduleName: '每日巡检',
@@ -577,7 +576,7 @@ describe('mobileHome', () => {
});
const row = home.projects[0].sessions[0];
- expect(row.automationGroup?.primarySessionId).toBe('old-pending');
+ expect(row.automationGroup?.primarySessionId).toBe('new-idle');
// 组行活动时间仍取组内最新,不因 primary 是旧 run 而回退。
expect(row.lastActivityAt).toBe('2026-01-01T12:00:00.000Z');
});
diff --git a/packages/maker-shared/src/scheduleModel.ts b/packages/maker-shared/src/scheduleModel.ts
index ecd6f152e0..c3e5657018 100644
--- a/packages/maker-shared/src/scheduleModel.ts
+++ b/packages/maker-shared/src/scheduleModel.ts
@@ -562,8 +562,20 @@ function formatTimestamp(value: RemoteTimestamp, localizer?: PresentationLocaliz
return `${month}-${day} ${hour}:${minute}`;
}
+export function isFailedScheduleRun(run: { status: string }): boolean {
+ return run.status === 'failed' || run.status === 'interrupted';
+}
+
+export function isUnreadFailedScheduleRun(run: { status: string; readAt?: unknown }): boolean {
+ return !run.readAt && isFailedScheduleRun(run);
+}
+
+export function isUnreadScheduleRun(run: { status: string; readAt?: unknown }): boolean {
+ return !run.readAt && (run.status === 'success' || isFailedScheduleRun(run));
+}
+
function isUnreadRun(run: RemoteScheduleRun, now = Date.now()): boolean {
- if (run.status === 'running') return false;
+ if (!isUnreadScheduleRun(run)) return false;
const firedAt = toMillis(run.firedAt);
if (!firedAt || firedAt > now) return false;
return !toMillis(run.readAt);
diff --git a/packages/maker-shared/src/sessionActivity.ts b/packages/maker-shared/src/sessionActivity.ts
index 4d9d2e348e..17e6bb993f 100644
--- a/packages/maker-shared/src/sessionActivity.ts
+++ b/packages/maker-shared/src/sessionActivity.ts
@@ -8,6 +8,19 @@
type OpenValue<Known extends string> = Known | (string & Record<never, never>);
+export type SessionRightStatus = 'error' | 'awaiting' | 'running' | 'done' | 'time';
+
+/** Shared by local desktop and every remote controller. */
+export function resolveSessionRightStatus(
+ activity: Pick<SessionActivitySnapshot, 'phase' | 'attention'>,
+): SessionRightStatus {
+ if (activity.phase === 'error' && activity.attention) return 'error';
+ if (activity.phase === 'needs-interaction') return 'awaiting';
+ if (activity.phase === 'running') return 'running';
+ if (activity.phase === 'completed' && activity.attention) return 'done';
+ return 'time';
+}
+
export type SessionActivityPhase = OpenValue<
'idle' | 'running' | 'needs-interaction' | 'completed' | 'error'
>;
@@ -168,3 +181,18 @@ export function isSessionActivityWaitingForUser(
): boolean {
return activity.phase === 'needs-interaction';
}
+
+export function resolveCollapsedGroupRightStatus({
+ collapsed,
+ latestKind,
+ tone,
+}: {
+ collapsed: boolean;
+ latestKind: SessionRightStatus;
+ tone: 'error' | 'done' | null;
+}): SessionRightStatus {
+ if (!collapsed) return latestKind;
+ if (tone === 'error') return 'error';
+ if (tone === 'done' && latestKind === 'time') return 'done';
+ return latestKind;
+}
diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.ts
index 9f3ea12d83..8933b116f4 100644
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@ -2,8 +2,8 @@ import { messageContentToPreview } from './messageNormalize.js';
import { stripTrailingPathSeparators } from './pathText.js';
import { presentationDate, presentationText, type PresentationLocalizer } from './presentationLocalization.js';
import { isSyntheticTriggerText } from './syntheticTrigger.js';
-import type { RemoteSchedule, RemoteScheduleRun, RemoteScheduleRunStatus } from './scheduleTypes.js';
-import { toMillis } from './scheduleModel.js';
+import type { RemoteSchedule, RemoteScheduleRun } from './scheduleTypes.js';
+import { toMillis, isUnreadScheduleRun, isUnreadFailedScheduleRun } from './scheduleModel.js';
import { sessionCollaborationLabel, sessionWorktreeLabel } from './sessionIdentity.js';
import { isDefaultDraftSessionTitle } from './sessionTitle.js';
import { getSessionListCollapseView } from './sessionListCollapse.js';
@@ -112,6 +112,7 @@ export interface RemoteSessionScheduleInfo {
/** 同一会话的所有已知 schedule 绑定都已 paused / expired 时为 true;缺失按 false。 */
allSchedulesStopped?: boolean;
unreadRunIds: string[];
+ hasUnreadFailedRun?: boolean;
unreadCount: number;
running: boolean;
latestRunAt: number;
@@ -633,7 +634,7 @@ export function buildSessionScheduleIndex(
const firedAt = toMillis(run.firedAt);
const existing = index.get(run.sessionId);
const unreadRunIds = existing ? [...existing.unreadRunIds] : [];
- if (isUnreadRunStatus(run.status) && !run.readAt) unreadRunIds.push(run.id);
+ if (isUnreadScheduleRun(run)) unreadRunIds.push(run.id);
const running = (existing?.running ?? false) || run.status === 'running';
const isLatest = !existing || firedAt >= existing.latestRunAt;
index.set(run.sessionId, {
@@ -643,6 +644,7 @@ export function buildSessionScheduleIndex(
allSchedulesStopped: false,
unreadRunIds,
unreadCount: unreadRunIds.length,
+ hasUnreadFailedRun: existing?.hasUnreadFailedRun === true || isUnreadFailedScheduleRun(run),
running,
latestRunAt: Math.max(existing?.latestRunAt ?? 0, firedAt),
});
@@ -908,14 +910,12 @@ function toAutomationGroupListItem(
/**
* 组的 primary(收起组"点行直开"的目标,也是组行的图标 / 预览来源):
- * 待处理交互 > 运行中 > 有未读 > 最新。待处理交互最优先 —— 它在等用户行动才能推进,
- * 组行的红点也来自它,点行必须落在这条上,否则用户要的确认被藏进展开列表。
+ * 与桌面折叠组一致:未读失败优先,其余打开最新运行;等待交互仍在展开子行显示。
*/
function pickAutomationPrimaryItem(group: readonly RemoteSessionListItem[]): RemoteSessionListItem {
- return group.find((item) => item.pendingInteractionCount > 0)
- ?? group.find((item) => item.scheduleInfo?.running)
- ?? group.find((item) => (item.scheduleInfo?.unreadCount ?? 0) > 0)
- ?? group[0];
+ return group.find((item) => item.scheduleInfo?.hasUnreadFailedRun
+ || (item.liveActivity?.phase === 'error' && item.liveActivity.attention))
+ ?? group.reduce((a, b) => lastActivity(b.session) > lastActivity(a.session) ? b : a);
}
function mergeScheduleInfo(group: readonly RemoteSessionListItem[]): RemoteSessionScheduleInfo | null {
@@ -928,15 +928,12 @@ function mergeScheduleInfo(group: readonly RemoteSessionListItem[]): RemoteSessi
allSchedulesStopped: group.every((item) => item.scheduleInfo?.allSchedulesStopped === true),
unreadRunIds,
unreadCount: unreadRunIds.length,
+ hasUnreadFailedRun: group.some((item) => item.scheduleInfo?.hasUnreadFailedRun === true),
running: group.some((item) => item.scheduleInfo?.running),
latestRunAt: Math.max(...group.map((item) => item.scheduleInfo?.latestRunAt ?? 0)),
};
}
-function isUnreadRunStatus(status: RemoteScheduleRunStatus): boolean {
- return status === 'success' || status === 'failed' || status === 'aborted' || status === 'interrupted';
-}
-
function agentLabel(agentKind: RemoteSession['agentKind']): string {
return agentKind === 'codex' ? 'Codex' : agentKind === 'pi' ? 'Pi' : 'Claude Code';
}