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(mobile): 对齐任务内历史定时失败提示

Dashf409dfbf2ddf
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index 2cf51a95ea..d6fea06669 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -526,7 +526,8 @@ describe('automation-generated sessions', () => {
);
expect(sessionViewSource).toContain('<UnreadFailedScheduleBanner');
- expect(sessionViewSource).toContain('scheduleSessionInfo?.hasFailedRun');
+ expect(sessionViewSource).toContain('scheduleSessionInfo.hasFailedRun');
+ expect(sessionViewSource).toContain('shouldShowFailedScheduleNotice({');
expect(sessionViewSource).toContain('useAutomationScheduleSessionInfo(sessionId)');
expect(sessionViewSource).not.toContain('useAutomationScheduleSessionIndex()');
expect(sessionViewSource).toContain('latestUnreadFailedRunId');
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index b9a6dc9b99..ada041d80e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1,3 +1,4 @@
+import { shouldShowFailedScheduleNotice } from '@cindy/maker-shared/schedule-model';
/**
* CCAgentSessionView
* ---------------------------------------------------------------------------
@@ -4878,17 +4879,12 @@ export function CCAgentSessionView({
/>
)}
- {!readOnly &&
- !errorTailMsg &&
- !interruptedFromSession &&
- scheduleSessionInfo?.hasFailedRun &&
- scheduleSessionInfo.latestFailedRun &&
- !syntheticContinuationPending &&
- !error &&
- !credentialSwitchWait &&
- !isStreaming &&
- !agentStatus.isRunning &&
- sessionId && (
+ {sessionId && scheduleSessionInfo?.latestFailedRun && shouldShowFailedScheduleNotice({
+ latestFailedRun: scheduleSessionInfo.hasFailedRun ? scheduleSessionInfo.latestFailedRun : null,
+ readOnly, tailError: !!errorTailMsg, interrupted: !!interruptedFromSession,
+ continuationPending: !!syntheticContinuationPending, error: !!error,
+ credentialWait: !!credentialSwitchWait, streaming: isStreaming, running: agentStatus.isRunning,
+ }) && (
<UnreadFailedScheduleBanner
key={sessionId}
dataOwnerId={dataOwnerId}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts b/apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts
index 18e58e0b0f..32e6981e7d 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/failedScheduleDismissal.ts
@@ -1,15 +1,5 @@
-/** 与数据库最新失败查询一致的快照顺序;已读状态不参与比较。 */
-export interface FailedScheduleRunSnapshot {
- runId: string;
- firedAt: number;
-}
-
-export function compareFailedScheduleRuns(
- a: FailedScheduleRunSnapshot,
- b: FailedScheduleRunSnapshot,
-): number {
- return a.firedAt - b.firedAt || (a.runId > b.runId ? 1 : a.runId < b.runId ? -1 : 0);
-}
+import { compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
+export { compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
export function failedScheduleDismissalPrefix(ownerId: string, sessionId: string): string {
return `scheduleFailureDismissal:${JSON.stringify([ownerId, sessionId])}:`;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index c94fd71afe..d21c09d47d 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,7 @@
+import { getActiveMobileSessionRealm } from '@/config/env';
+import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';
+import { loadLightweightSessionScheduleIndex, loadSessionScheduleIndex } from '@/session/scheduleIndex';
+import { shouldShowFailedScheduleNotice, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { isInFlightDeviceLinkError } from '@cindy/device-link';
@@ -2077,26 +2081,9 @@ export default function SessionScreen() {
// 把该会话名下未读 run 在被控端标已读;host 随之广播 read 事件,首页 / 设备列表红点自动清除。
const scheduleEventSnapshot = useRemoteScheduleEventSnapshot(deviceId);
const completedRunId = unreadRunIdFromProjection(scheduleEventSnapshot.lastProjection, sessionId);
- // 开会话路径:延后一小段再拉 schedule index,把该会话未读 run 标已读。不限定 scheduler 生成的
- // 会话——显式绑定普通会话(targetSessionId)的 run 同样会在列表挂未读徽标,冷启动后无事件投影可依,
- // 只能靠 index 探测。无 schedule 的用户只多一次轻量 schedule.list;延后是避开首开关键读抢 WS 管道(#324)。
- // 瞬态失败兜底:短暂抖动走 withTransientRemoteRetry 原地重试;冷启动首开时 device-link 可能尚未
- // 就绪且失败被吞,依赖 connectionEpoch 在重连后重跑一次探测,用户停在会话里红点也能自愈。
- // unreadVersion 依赖:store 只存最近一条事件投影,completed 被紧随的事件覆盖时下面的快路径会漏;
- // 任何影响未读的事件都 bump unreadVersion(累计计数不丢),据此重跑延后探测兜底。标已读后广播回来的
- // read 事件会再触发一轮探测,发现无未读即收敛;800ms defer + effect cleanup 会把连续事件合并成一次。
- useEffect(() => {
- if (!sessionId) return;
- return deferScheduleIndexHydration(() => {
- void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId))
- .catch(() => undefined);
- });
- }, [connectionEpoch, maker, scheduleEventSnapshot.unreadVersion, sessionId]);
- // 会话开着时报告刚完成:事件投影直接给出绑定到本会话的 runId,单次标已读、免拉 index。
- useEffect(() => {
- if (!completedRunId) return;
- void maker.schedule.markRunRead(completedRunId).catch(() => undefined);
- }, [completedRunId, maker]);
+ // 同一轻量索引同时提供历史失败提示和未读记录;已读不会消除历史失败。
+ const scheduleNoticeSource = JSON.stringify([getActiveMobileSessionRealm(), auth.user?.id, deviceId, sessionId]);
+ const [scheduleFailure, setScheduleFailure] = useState<{ source: string; run?: FailedScheduleRunSnapshot } | null>(null);
// —— 会话未读「真实展示即已读」回执 ——
// 手机端打开会话且**本次连接代已完成整窗同步**后,驻留满 dwell 把被控端该会话的
// 未读态(灵动岛 / Dock 角标 / 桌面侧栏红绿点)清掉;被控端清完经 sessions relay
@@ -2139,6 +2126,32 @@ export default function SessionScreen() {
});
return () => subscription.remove();
}, []);
+ useFocusEffect(useCallback(() => {
+ if (!appStateActive || !deviceId || !sessionId || !remoteHistoryAvailable) return;
+ let active = true;
+ const isActive = () => active && messageScreenFocusedRef.current && messageAppActiveRef.current;
+ const cancel = deferScheduleIndexHydration(() => {
+ void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId, {
+ isActive,
+ // The same read supplies the notice and existing read receipts. Old
+ // Hosts retain their original query; no second schedule scan is added.
+ loadIndex: async () => {
+ try { return await loadLightweightSessionScheduleIndex(deviceId, invoke); }
+ catch (error) {
+ if (!isHistoryViewUnavailable(error)) throw error;
+ if (!isActive()) return new Map();
+ return loadSessionScheduleIndex(maker, { throwOnTransientRunListError: true });
+ }
+ },
+ onIndex: (index) => setScheduleFailure({ source: scheduleNoticeSource, run: index.get(sessionId)?.latestFailedRun }),
+ })).catch(() => undefined);
+ });
+ return () => { active = false; cancel(); };
+ }, [appStateActive, connectionEpoch, deviceId, invoke, maker, remoteHistoryAvailable, scheduleEventSnapshot.sessionIndexVersion, scheduleNoticeSource, sessionId]));
+ useFocusEffect(useCallback(() => {
+ if (!appStateActive || !remoteHistoryAvailable || !completedRunId) return;
+ void maker.schedule.markRunRead(completedRunId).catch(() => undefined);
+ }, [appStateActive, completedRunId, maker, remoteHistoryAvailable]));
useFocusEffect(
useCallback(() => {
if (!appStateActive || !deviceId || !sessionId || !hasRenderedMessages) return undefined;
@@ -9234,6 +9247,18 @@ export default function SessionScreen() {
state={tailBannerState}
/>
) : null}
+ {shouldShowFailedScheduleNotice({
+ latestFailedRun: scheduleFailure?.source === scheduleNoticeSource ? scheduleFailure.run : null,
+ readOnly: !!collaborationReadOnlyReason,
+ tailError: !!errorTailClientId || !!retryHiddenTailClientId,
+ interrupted: tailBannerState?.kind === 'interrupted',
+ continuationPending: tailContinuationInFlight,
+ error: !!inputProjection.error, credentialWait: !!inputProjection.credentialSwitchWait,
+ streaming: isSessionStreaming, running: remoteSessionRunning,
+ }) && scheduleFailure?.run ? (
+ <FailedScheduleNotice key={scheduleNoticeSource}
+ source={scheduleNoticeSource} run={scheduleFailure.run} />
+ ) : null}
{/* 队列状态横幅(错误 / 凭证等待 / 停止确认 / 暂停)。待发送气泡
不在这里,它们是消息流里的 pending_send 项。 */}
<InlineQueueSection
diff --git a/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx b/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
new file mode 100644
index 0000000000..cec02d0780
--- /dev/null
+++ b/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { FailedScheduleNotice } from '@/session/FailedScheduleNotice';
+const storage = vi.hoisted(() => new Map<string, string>());
+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {
+ getItem: vi.fn(async (key: string) => storage.get(key) ?? null),
+ setItem: vi.fn(async (key: string, value: string) => { storage.set(key, value); }),
+} }));
+vi.mock('react-native', async () => {
+ const { createElement } = await import('react');
+ const view = (tag: string) => ({ children, onPress }: { children?: ReactNode; onPress?: () => void }) => createElement(tag, { onClick: onPress }, children);
+ return { View: view('div'), Text: view('span'), Pressable: view('button'), StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 } };
+});
+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));
+vi.mock('lucide-react-native', () => ({ CircleAlert: () => null, X: () => null }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/theme', async () => {
+ const { lightColors } = await import('@/theme/tokens');
+ return { useTheme: () => ({ colors: lightColors }), useThemedStyles: (make: (colors: typeof lightColors) => unknown) => make(lightColors) };
+});
+let root: Root;
+let host: HTMLDivElement;
+const run = { runId: 'run1', firedAt: 10 };
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ storage.clear(); host = document.createElement('div'); root = createRoot(host);
+});
+afterEach(() => act(() => root.unmount()));
+async function show(source = 'owner/host/task', value = run) {
+ await act(async () => root.render(<FailedScheduleNotice key={source} source={source} run={value} />));
+}
+it('keeps dismissal local and shows a newer failed run', async () => {
+ await show(); expect(host.querySelector('button')).not.toBeNull();
+ await act(async () => host.querySelector('button')!.click());
+ expect(host.textContent).toBe('');
+ await act(async () => root.render(null)); await show(); expect(host.textContent).toBe('');
+ await show('owner/host/task', { runId: 'run2', firedAt: 11 }); expect(host.querySelector('button')).not.toBeNull();
+});
+it('does not share dismissal across accounts, devices or tasks', async () => {
+ await show(); await act(async () => host.querySelector('button')!.click());
+ for (const source of ['other/host/task', 'owner/other/task', 'owner/host/other']) {
+ await show(source); expect(host.querySelector('button')).not.toBeNull();
+ }
+});
+
+it('discards an old account preference read after switching source', async () => {
+ let finish!: (value: string) => void;
+ vi.mocked(AsyncStorage.getItem).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ await show('old/host/task');
+ expect(host.textContent).toBe('');
+ await show('new/host/task');
+ await act(async () => finish(JSON.stringify(run)));
+ expect(host.querySelector('button')).not.toBeNull();
+});
+it('can close for the current view even if preference storage fails', async () => {
+ vi.mocked(AsyncStorage.setItem).mockRejectedValueOnce(new Error('storage unavailable'));
+ await show();
+ await act(async () => host.querySelector('button')!.click());
+ expect(host.textContent).toBe('');
+});
diff --git a/apps/mobile/src/__tests__/scheduleNoticeWiring.test.ts b/apps/mobile/src/__tests__/scheduleNoticeWiring.test.ts
new file mode 100644
index 0000000000..71d885d1bc
--- /dev/null
+++ b/apps/mobile/src/__tests__/scheduleNoticeWiring.test.ts
@@ -0,0 +1,23 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { expect, it } from 'vitest';
+import { projectScheduleEvent } from '@cindy/maker-shared/schedule-events';
+it('refreshes the actual notice effect when a completed run is later bound to the task', () => {
+ const source = ts.createSourceFile('screen.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ let dependencies: string[] = [];
+ function visit(node: ts.Node) {
+ if (ts.isCallExpression(node) && node.expression.getText(source) === 'useCallback'
+ && node.arguments[0]?.getText(source).includes('setScheduleFailure') && node.arguments[1] && ts.isArrayLiteralExpression(node.arguments[1])) {
+ dependencies = node.arguments[1].elements.map((element) => element.getText(source));
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ const event = projectScheduleEvent({ type: 'session-bound', scheduleId: 'schedule', runId: 'run', sessionId: 'task' });
+ expect(event.refresh.sessionIndex).toBe(true);
+ expect(event.refresh.unreadSummary).toBe(false);
+ expect(dependencies).toContain('scheduleEventSnapshot.sessionIndexVersion');
+ expect(dependencies).toContain('remoteHistoryAvailable');
+ expect(dependencies).toContain('appStateActive');
+});
diff --git a/apps/mobile/src/__tests__/scheduleRunRead.test.ts b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
index 23b0f77043..83fbe40de0 100644
--- a/apps/mobile/src/__tests__/scheduleRunRead.test.ts
+++ b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
@@ -147,3 +147,20 @@ describe('unreadRunIdFromProjection', () => {
expect(unreadRunIdFromProjection(failedEvent, 'session-1')).toBeNull();
});
});
+
+it('shares the supplied index with the notice and ignores a late result after leaving', async () => {
+ const markRunRead = vi.fn(async () => undefined);
+ const maker = makerWith([], markRunRead);
+ const onIndex = vi.fn();
+ const index = new Map([['session-1', { scheduleId: 's', scheduleName: 's', unreadRunIds: ['r'], unreadCount: 1,
+ running: false, latestRunAt: 1, latestFailedRun: { runId: 'r', firedAt: 1 } }]]);
+ let active = true;
+ let finish!: (value: typeof index) => void;
+ const pending = markSessionScheduleRunsRead(maker, 'session-1', {
+ isActive: () => active, onIndex, loadIndex: () => new Promise((resolve) => { finish = resolve; }),
+ });
+ active = false; finish(index); await pending;
+ expect(onIndex).not.toHaveBeenCalled(); expect(markRunRead).not.toHaveBeenCalled();
+ await markSessionScheduleRunsRead(maker, 'session-1', { isActive: () => true, onIndex, loadIndex: async () => index });
+ expect(onIndex).toHaveBeenCalledWith(index); expect(markRunRead).toHaveBeenCalledWith('r');
+});
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 30baa53a26..e7c2f76248 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -1,4 +1,8 @@
{
+ "failedScheduleNotice": {
+ "text": "Some scheduled runs did not finish. Check the run history.",
+ "dismissTitle": "Dismiss past failure notice"
+ },
"common": {
"cancel": "Cancel",
"delete": "Delete",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 82af564416..b5f8a89902 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -1,4 +1,8 @@
{
+ "failedScheduleNotice": {
+ "text": "完了しなかったスケジュール実行があります。実行履歴を確認してください。",
+ "dismissTitle": "過去の失敗通知を閉じる"
+ },
"common": {
"cancel": "キャンセル",
"delete": "削除",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 62ee7056c5..72988edde9 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -1,4 +1,8 @@
{
+ "failedScheduleNotice": {
+ "text": "완료되지 않은 예약 실행이 있습니다. 실행 기록을 확인하세요.",
+ "dismissTitle": "이전 실패 알림 닫기"
+ },
"common": {
"cancel": "취소",
"delete": "삭제",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index f22423a664..84407c4225 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -1,4 +1,8 @@
{
+ "failedScheduleNotice": {
+ "text": "此前有定时任务未完成,可查看运行记录。",
+ "dismissTitle": "关闭历史失败提示"
+ },
"common": {
"cancel": "取消",
"delete": "删除",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index b2bbcd1e5f..b135f82f8a 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -1,4 +1,8 @@
{
+ "failedScheduleNotice": {
+ "text": "先前有定時任務未完成,可查看執行記錄。",
+ "dismissTitle": "關閉歷史失敗提示"
+ },
"common": {
"cancel": "取消",
"delete": "刪除",
diff --git a/apps/mobile/src/session/FailedScheduleNotice.tsx b/apps/mobile/src/session/FailedScheduleNotice.tsx
new file mode 100644
index 0000000000..68b94ad6df
--- /dev/null
+++ b/apps/mobile/src/session/FailedScheduleNotice.tsx
@@ -0,0 +1,55 @@
+import AsyncStorage from '@react-native-async-storage/async-storage';
+import { compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
+import { CircleAlert, X } from 'lucide-react-native';
+import { useEffect, useState } from 'react';
+import { Pressable, StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import { Text } from '@/components/AppText';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+
+/** Only a local display preference: never writes a run or a read receipt. */
+export function FailedScheduleNotice({ source, run }: { source: string; run: FailedScheduleRunSnapshot }) {
+ const key = `scheduleFailureDismissal:${source}`;
+ const [loaded, setLoaded] = useState(false);
+ const [dismissed, setDismissed] = useState<FailedScheduleRunSnapshot | null>(null);
+ const { t } = useTranslation();
+ const { colors } = useTheme();
+ const styles = useThemedStyles(makeStyles);
+ useEffect(() => {
+ let active = true;
+ setLoaded(false);
+ setDismissed(null);
+ void AsyncStorage.getItem(key).then((raw) => {
+ if (!active || !raw) return;
+ try {
+ const value = JSON.parse(raw);
+ if (typeof value?.runId === 'string' && typeof value.firedAt === 'number' && Number.isFinite(value.firedAt)) setDismissed(value);
+ } catch { /* Invalid preferences do not hide history. */ }
+ }).catch(() => undefined).finally(() => { if (active) setLoaded(true); });
+ return () => { active = false; };
+ }, [key]);
+ if (!loaded || (dismissed && compareFailedScheduleRuns(dismissed, run) >= 0)) return null;
+ const dismiss = () => {
+ setDismissed(run);
+ void AsyncStorage.setItem(key, JSON.stringify(run)).catch(() => undefined);
+ };
+ return (
+ <View style={styles.box} testID="session.failedScheduleNotice">
+ <CircleAlert color={colors.errorText} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ <Text style={styles.text}>{t('session.failedScheduleNotice.text')}</Text>
+ <Pressable accessibilityRole="button" accessibilityLabel={t('session.failedScheduleNotice.dismissTitle')}
+ onPress={dismiss} style={({ pressed }) => [styles.close, pressed && styles.pressed]}>
+ <X color={colors.errorText} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ </View>
+ );
+}
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ box: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginTop: spacing.sm,
+ paddingLeft: spacing.md, backgroundColor: colors.surfaceElevated, borderColor: colors.errorBorder,
+ borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.container },
+ text: { flex: 1, color: colors.errorText, fontSize: typeScale.caption, lineHeight: lineHeight.caption, paddingVertical: spacing.sm },
+ close: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center', borderRadius: radius.pill },
+ pressed: { opacity: 0.7 },
+});
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index dff90e2666..61800340ce 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -295,6 +295,8 @@ function scheduleInfoEqual(a: RemoteSessionScheduleInfo, b: RemoteSessionSchedul
&& a.scheduleName === b.scheduleName
&& a.unreadCount === b.unreadCount
&& !!a.hasUnreadFailedRun === !!b.hasUnreadFailedRun
+ && a.latestFailedRun?.runId === b.latestFailedRun?.runId
+ && a.latestFailedRun?.firedAt === b.latestFailedRun?.firedAt
&& a.running === b.running
&& a.latestRunAt === b.latestRunAt
&& a.scheduleStatus === b.scheduleStatus
diff --git a/apps/mobile/src/session/scheduleRunRead.ts b/apps/mobile/src/session/scheduleRunRead.ts
index 4f7cb2ec54..8c55be0c25 100644
--- a/apps/mobile/src/session/scheduleRunRead.ts
+++ b/apps/mobile/src/session/scheduleRunRead.ts
@@ -1,3 +1,4 @@
+import type { RemoteSessionScheduleInfo } from '@/session/sessionList';
import type { ScheduleEventProjection } from '@cindy/maker-shared/schedule-events';
import { isTransientRemoteError } from '@/device-link/remoteRetry';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
@@ -23,15 +24,22 @@ type ScheduleReadTransport = Pick<MobileMakerTransport, 'schedule'>;
export async function markSessionScheduleRunsRead(
maker: ScheduleReadTransport,
sessionId: string,
+ options: {
+ loadIndex?: () => Promise<Map<string, RemoteSessionScheduleInfo>>;
+ onIndex?: (index: Map<string, RemoteSessionScheduleInfo>) => void;
+ isActive?: () => boolean;
+ } = {},
): Promise<string[]> {
- if (!sessionId) return [];
- const index = await loadSessionScheduleIndex(maker, { throwOnTransientRunListError: true });
+ if (!sessionId || options.isActive?.() === false) return [];
+ const index = await (options.loadIndex?.() ?? loadSessionScheduleIndex(maker, { throwOnTransientRunListError: true }));
+ if (options.isActive?.() === false) return [];
+ options.onIndex?.(index);
const unreadRunIds = index.get(sessionId)?.unreadRunIds ?? [];
if (unreadRunIds.length === 0) return [];
// 单个永久失败不阻塞其它 run;瞬态失败需要抛出,让外层 retry 重新探测并补标。
// allSettled 后按原 unreadRunIds 顺序收集成功项,返回值保序。
const results = await Promise.allSettled(
- unreadRunIds.map((runId) => maker.schedule.markRunRead(runId)),
+ unreadRunIds.map((runId) => options.isActive?.() === false ? Promise.reject(new Error('READ_INACTIVE')) : maker.schedule.markRunRead(runId)),
);
const transientError = results.find(
(result): result is PromiseRejectedResult => result.status === 'rejected' && isTransientRemoteError(result.reason),
diff --git a/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts b/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts
new file mode 100644
index 0000000000..5788b0364a
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { compareFailedScheduleRuns, shouldShowFailedScheduleNotice } from '../scheduleModel';
+import { buildSessionScheduleIndex } from '../sessionList';
+import type { RemoteScheduleRun } from '../scheduleTypes';
+const run = { runId: 'b', firedAt: 10 };
+const visible = { latestFailedRun: run, readOnly: false, tailError: false, interrupted: false,
+ continuationPending: false, error: false, credentialWait: false, streaming: false, running: false };
+describe('historical schedule failure notice', () => {
+ it('uses time then run identity, independently of read state', () => {
+ expect(compareFailedScheduleRuns(run, { runId: 'a', firedAt: 10 })).toBeGreaterThan(0);
+ expect(compareFailedScheduleRuns(run, { runId: 'z', firedAt: 9 })).toBeGreaterThan(0);
+ const rows = [
+ { id: 'a', status: 'failed', firedAt: 10, readAt: 11 },
+ { id: 'b', status: 'interrupted', firedAt: 10, readAt: 11 },
+ { id: 'c', status: 'success', firedAt: 12, readAt: 13 },
+ { id: 'd', status: 'aborted', firedAt: 14 },
+ ].map((r) => ({ ...r, sessionId: 's', scheduleId: 'schedule' })) as RemoteScheduleRun[];
+ const info = buildSessionScheduleIndex([], new Map([['schedule', rows]])).get('s');
+ expect(info?.latestFailedRun).toEqual(run);
+ expect(info?.hasUnreadFailedRun).toBe(false);
+ });
+ it.each(['readOnly', 'tailError', 'interrupted', 'continuationPending', 'error', 'credentialWait', 'streaming', 'running'])(
+ 'yields to %s', (field) => {
+ expect(shouldShowFailedScheduleNotice(visible)).toBe(true);
+ expect(shouldShowFailedScheduleNotice({ ...visible, [field]: true })).toBe(false);
+ });
+ it('requires a failed run', () => expect(shouldShowFailedScheduleNotice({ ...visible, latestFailedRun: null })).toBe(false));
+});
diff --git a/packages/maker-shared/src/scheduleModel.ts b/packages/maker-shared/src/scheduleModel.ts
index c3e5657018..ce35701af4 100644
--- a/packages/maker-shared/src/scheduleModel.ts
+++ b/packages/maker-shared/src/scheduleModel.ts
@@ -596,3 +596,17 @@ function readString(value: Record<string, unknown>, key: string): string | null
const raw = value[key];
return typeof raw === 'string' && raw.length > 0 ? raw : null;
}
+
+/** Historical failure notices are independent of read receipts. */
+export interface FailedScheduleRunSnapshot { runId: string; firedAt: number }
+export function compareFailedScheduleRuns(a: FailedScheduleRunSnapshot, b: FailedScheduleRunSnapshot): number {
+ return a.firedAt - b.firedAt || (a.runId > b.runId ? 1 : a.runId < b.runId ? -1 : 0);
+}
+export function shouldShowFailedScheduleNotice(state: {
+ latestFailedRun?: FailedScheduleRunSnapshot | null;
+ readOnly: boolean; tailError: boolean; interrupted: boolean; continuationPending: boolean;
+ error: boolean; credentialWait: boolean; streaming: boolean; running: boolean;
+}): boolean {
+ return !!state.latestFailedRun && !state.readOnly && !state.tailError && !state.interrupted
+ && !state.continuationPending && !state.error && !state.credentialWait && !state.streaming && !state.running;
+}
diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.ts
index ae2db837d7..5ffc6c1c0e 100644
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@ -4,7 +4,7 @@ import { presentationDate, presentationText, type PresentationLocalizer } from '
import { isSyntheticTriggerText } from './syntheticTrigger.js';
import { hasPendingSessionInterruption, type SessionInterruptionState } from './sessionActivity.js';
import type { RemoteSchedule, RemoteScheduleRun } from './scheduleTypes.js';
-import { toMillis, isUnreadScheduleRun, isUnreadFailedScheduleRun } from './scheduleModel.js';
+import { toMillis, isUnreadScheduleRun, isUnreadFailedScheduleRun, isFailedScheduleRun, compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from './scheduleModel.js';
import { sessionCollaborationLabel, sessionWorktreeLabel } from './sessionIdentity.js';
import { isDefaultDraftSessionTitle } from './sessionTitle.js';
import { getSessionListCollapseView } from './sessionListCollapse.js';
@@ -114,6 +114,7 @@ export interface RemoteSessionScheduleInfo {
allSchedulesStopped?: boolean;
unreadRunIds: string[];
hasUnreadFailedRun?: boolean;
+ latestFailedRun?: FailedScheduleRunSnapshot;
unreadCount: number;
running: boolean;
latestRunAt: number;
@@ -640,6 +641,9 @@ export function buildSessionScheduleIndex(
const existing = index.get(run.sessionId);
const unreadRunIds = existing ? [...existing.unreadRunIds] : [];
if (isUnreadScheduleRun(run)) unreadRunIds.push(run.id);
+ const candidate = isFailedScheduleRun(run) ? { runId: run.id, firedAt } : undefined;
+ const latestFailedRun = candidate && (!existing?.latestFailedRun || compareFailedScheduleRuns(candidate, existing.latestFailedRun) > 0)
+ ? candidate : existing?.latestFailedRun;
const running = (existing?.running ?? false) || run.status === 'running';
const isLatest = !existing || firedAt >= existing.latestRunAt;
index.set(run.sessionId, {
@@ -649,6 +653,7 @@ export function buildSessionScheduleIndex(
allSchedulesStopped: false,
unreadRunIds,
unreadCount: unreadRunIds.length,
+ latestFailedRun,
hasUnreadFailedRun: existing?.hasUnreadFailedRun === true || isUnreadFailedScheduleRun(run),
running,
latestRunAt: Math.max(existing?.latestRunAt ?? 0, firedAt),