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): recover cold notification task entry after connection startup

Chriscadbf7e13daf
diff --git a/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx b/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
index 63aef3a8b6..641fab0ef7 100644
--- a/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
+++ b/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { act, createElement, useEffect, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
+import { sharedTaskHostPeer } from '@cindy/device-link';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CindyMakeSessionGate, SESSION_ENTRY_LOOKUP_TIMEOUT_MS } from '@/session/CindyMakeSessionGate';
import type { NewSessionCreationTask } from '@/session/newSessionCreation';
@@ -13,6 +14,11 @@ const state = vi.hoisted(() => ({
openLink: vi.fn(),
unsubscribe: vi.fn(),
connectionEpoch: 0,
+ status: 'online',
+ presence: null as boolean | null,
+ focused: true,
+ appState: 'active',
+ appListeners: new Set<(value: string) => void>(),
accountGeneration: 1,
task: null as NewSessionCreationTask | null,
router: { canGoBack: vi.fn(() => true), back: vi.fn(), replace: vi.fn() },
@@ -26,6 +32,13 @@ vi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }), useThemedStyles: (
vi.mock('react-native', () => ({
View: ({ children }: { children?: ReactNode }) => createElement('div', {}, children),
ScrollView: ({ children }: { children?: ReactNode }) => createElement('div', {}, children),
+ AppState: {
+ get currentState() { return state.appState; },
+ addEventListener: (_event: string, listener: (value: string) => void) => {
+ state.appListeners.add(listener);
+ return { remove: () => state.appListeners.delete(listener) };
+ },
+ },
ActivityIndicator: () => createElement('span', { role: 'progressbar' }),
StyleSheet: { create: (styles: unknown) => styles },
}));
@@ -48,9 +61,12 @@ vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({
openLink: state.openLink,
unsubscribe: state.unsubscribe,
connectionEpoch: state.connectionEpoch,
+ status: state.status,
+ getPresenceAvailability: () => state.presence,
}) }));
vi.mock('@/device-link/useMobileMakerTransport', () => ({ useMobileMakerTransport: () => state.maker }));
vi.mock('expo-router', () => ({
+ useIsFocused: () => state.focused,
Redirect: ({ href }: { href: string }) => createElement('span', {}, `redirect:${href}`),
useRouter: () => state.router,
}));
@@ -67,6 +83,11 @@ beforeEach(() => {
state.openLink.mockReset().mockResolvedValue(undefined);
state.unsubscribe.mockReset().mockResolvedValue(undefined);
state.connectionEpoch = 0;
+ state.status = 'online';
+ state.presence = null;
+ state.focused = true;
+ state.appState = 'active';
+ state.appListeners.clear();
state.accountGeneration = 1;
state.task = null;
state.router.canGoBack.mockReset().mockReturnValue(true);
@@ -101,6 +122,117 @@ describe('mobile Cindy Make links', () => {
permissionMode: 'auto', workingDir: '', providerId: 'openai', fastMode: false, firstMessage: 'Keep my draft' },
});
+ // Cold notification regression: the gate used to read before relay startup and
+ // permanently fail on a transient peer/metadata error. Existing tests only
+ // covered a ready relay and retries after a new connection epoch. Unit tier.
+ it('waits for cold startup and recovers a transient metadata read in the same connection', async () => {
+ vi.useFakeTimers();
+ state.status = 'stopped';
+ state.openLink.mockRejectedValueOnce(Object.assign(new Error('not ready'), { code: 'NOT_CONNECTED' }))
+ .mockResolvedValue(undefined);
+ state.maker.getSession.mockRejectedValueOnce(Object.assign(new Error('cold database'), { code: 'NOT_CONNECTED' }))
+ .mockResolvedValue({ id: 'new-task', source: 'desktop' });
+ await renderGate();
+ expect(container.textContent).toContain('session.entry.loading');
+ expect(state.openLink).not.toHaveBeenCalled();
+ state.status = 'connecting';
+ await renderGate();
+ expect(state.openLink).not.toHaveBeenCalled();
+ state.status = 'online';
+ await renderGate();
+ expect(container.textContent).toContain('session.entry.loading');
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+ expect(container.textContent).toBe('Composer');
+ expect(state.connectionEpoch).toBe(0);
+ });
+
+ it('waits for the target host and resumes after a timed out startup without manual retry', async () => {
+ vi.useFakeTimers();
+ state.presence = false;
+ await renderGate();
+ expect(state.openLink).not.toHaveBeenCalled();
+ await act(async () => vi.advanceTimersByTimeAsync(SESSION_ENTRY_LOOKUP_TIMEOUT_MS));
+ expect(container.textContent).toContain('session.entry.timedOut');
+ state.presence = true;
+ state.maker.getSession.mockResolvedValue({ id: 'new-task', source: 'desktop' });
+ await renderGate();
+ expect(container.textContent).toBe('Composer');
+ });
+
+ it('opens an authorized shared-task link before its readiness becomes available', async () => {
+ state.presence = false;
+ state.maker.getSession.mockResolvedValue({ id: 'new-task', source: 'desktop' });
+ const peer = sharedTaskHostPeer('shared-task', 'device-a');
+ await act(async () => root.render(
+ <CindyMakeSessionGate sessionId="new-task" deviceId={peer}><Content /></CindyMakeSessionGate>,
+ ));
+ expect(state.openLink).toHaveBeenCalledExactlyOnceWith(peer);
+ expect(container.textContent).toBe('Composer');
+ });
+
+ it('bounds repeated transient errors and preserves the manual recovery action', async () => {
+ vi.useFakeTimers();
+ state.openLink.mockRejectedValue(Object.assign(new Error('not ready'), { code: 'NOT_CONNECTED' }));
+ await renderGate();
+ await act(async () => vi.advanceTimersByTimeAsync(SESSION_ENTRY_LOOKUP_TIMEOUT_MS));
+ expect(container.textContent).toContain('session.entry.failed');
+ const attempts = state.openLink.mock.calls.length;
+ await act(async () => vi.advanceTimersByTimeAsync(SESSION_ENTRY_LOOKUP_TIMEOUT_MS));
+ expect(state.openLink).toHaveBeenCalledTimes(attempts);
+ state.openLink.mockResolvedValue(undefined);
+ state.maker.getSession.mockResolvedValue({ id: 'new-task', source: 'desktop' });
+ await click('session.entryRetry');
+ expect(container.textContent).toBe('Composer');
+ });
+
+ it.each(['background', 'blur', 'unmount'])('stops cold entry work on %s and fences a late link accept', async change => {
+ let accept!: () => void;
+ state.openLink.mockReturnValueOnce(new Promise<void>(resolve => { accept = resolve; }));
+ await renderGate();
+ if (change === 'background') {
+ await act(async () => {
+ state.appState = 'background';
+ state.appListeners.forEach(listener => listener('background'));
+ });
+ } else if (change === 'blur') {
+ state.focused = false;
+ await renderGate();
+ } else await act(async () => root.render(null));
+ await act(async () => accept());
+ expect(state.maker.getSession).not.toHaveBeenCalled();
+ state.maker.getSession.mockResolvedValue({ id: 'new-task', source: 'desktop' });
+ state.focused = true;
+ await act(async () => {
+ state.appState = 'active';
+ state.appListeners.forEach(listener => listener('active'));
+ });
+ await renderGate();
+ expect(container.textContent).toBe('Composer');
+ });
+
+ it('cancels pending transient retry when the account changes', async () => {
+ vi.useFakeTimers();
+ state.openLink.mockRejectedValueOnce(Object.assign(new Error('not ready'), { code: 'NOT_CONNECTED' }));
+ await renderGate();
+ state.accountGeneration += 1;
+ state.maker.getSession.mockResolvedValue({ id: 'new-task', source: 'cindy-make' });
+ await renderGate();
+ await act(async () => vi.advanceTimersByTimeAsync(SESSION_ENTRY_LOOKUP_TIMEOUT_MS));
+ expect(container.textContent).toBe('redirect:/');
+ expect(state.openLink).toHaveBeenCalledTimes(2);
+ expect(state.maker.getSession).toHaveBeenCalledOnce();
+ });
+
+ it.each(['ACCESS_REVOKED', 'REMOTE_DISABLED', 'CHANNEL_NOT_ALLOWED'])('does not retry permanent %s errors', async code => {
+ vi.useFakeTimers();
+ state.openLink.mockRejectedValue(Object.assign(new Error(code), { code }));
+ await renderGate();
+ await act(async () => vi.advanceTimersByTimeAsync(SESSION_ENTRY_LOOKUP_TIMEOUT_MS));
+ expect(container.textContent).toContain('session.entry.failed');
+ expect(state.openLink).toHaveBeenCalledOnce();
+ expect(state.maker.getSession).not.toHaveBeenCalled();
+ });
+
it.each(['running', 'create-failed'] as const)('releases pipeline subscriptions when leaving the %s recovery page', async status => {
state.task = { ...failedCreation(), status };
await renderGate();
diff --git a/apps/mobile/src/session/CindyMakeSessionGate.tsx b/apps/mobile/src/session/CindyMakeSessionGate.tsx
index b1621279b2..39fcdc55b9 100644
--- a/apps/mobile/src/session/CindyMakeSessionGate.tsx
+++ b/apps/mobile/src/session/CindyMakeSessionGate.tsx
@@ -1,9 +1,12 @@
import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react';
-import { Redirect } from 'expo-router';
+import { Redirect, useIsFocused } from 'expo-router';
+import { AppState } from 'react-native';
import { useTranslation } from 'react-i18next';
+import { isSharedTaskPeer } from '@cindy/device-link';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';
import { useAuth } from '@/auth/AuthContext';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { retryRemoteSyncRead } from '@/device-link/remoteSyncTask';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import { remoteSessionStore } from './remoteSessionStore';
import { MainWindowActionButton } from '@/components/MobilePrimitives';
@@ -23,10 +26,17 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
}) {
const { t } = useTranslation();
const { accountGeneration } = useAuth();
- const { openLink, connectionEpoch, unsubscribe } = useDeviceLink();
+ const { openLink, connectionEpoch, unsubscribe, status: relayStatus, getPresenceAvailability } = useDeviceLink();
+ const focused = useIsFocused();
+ const [foreground, setForeground] = useState(AppState.currentState === 'active');
+ useEffect(() => {
+ const subscription = AppState.addEventListener('change', state => setForeground(state === 'active'));
+ return () => subscription.remove();
+ }, []);
const sessions = useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getSessions);
const deviceId = routeDeviceId ?? remoteSessionStore.getSessionDeviceId(sessionId) ?? '';
const maker = useMobileMakerTransport(deviceId);
+ const presence = getPresenceAvailability(deviceId);
// The creation pipeline registers this owner before navigating here. The gate
// owns its lifetime even when source lookup keeps the task content unmounted.
useEffect(() => () => {
@@ -42,7 +52,7 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
const creationBlocked = localCreation !== null;
const [attempt, setAttempt] = useState(0);
const scope = JSON.stringify([sessionId, deviceId, accountGeneration]);
- const key = JSON.stringify([sessionId, deviceId, accountGeneration, connectionEpoch, attempt]);
+ const key = JSON.stringify([sessionId, deviceId, accountGeneration, connectionEpoch, relayStatus, presence, focused, foreground, attempt]);
const [lookup, setLookup] = useState<Lookup | null>(null);
// Reconnecting must not unmount content whose source was already confirmed for this owner.
const [loaded, setLoaded] = useState<{ scope: string; source: string | null } | null>(null);
@@ -55,31 +65,44 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
setLoaded({ scope, source: knownSource });
return;
}
- if (creationBlocked) return;
+ if (creationBlocked || !focused || !foreground) return;
if (!sessionId || !deviceId) {
setLookup({ key, status: 'failed' });
return;
}
- let cancelled = false;
+ const controller = new AbortController();
+ const cancelled = () => controller.signal.aborted;
setLookup({ key, status: 'loading' });
// This deadline only closes this read attempt; it never tears down the shared link.
const timeout = setTimeout(() => {
- cancelled = true;
+ controller.abort();
setLookup({ key, status: 'timedOut' });
}, SESSION_ENTRY_LOOKUP_TIMEOUT_MS);
- void openLink(deviceId)
- .then(() => cancelled ? null : maker.getSession(sessionId))
+ // Login restoration can route a notification before DeviceLinkProvider has
+ // started. Wait for transport evidence, not an arbitrary startup delay.
+ // Presence changes also resume this lookup without a relay reconnect.
+ // Shared-task peers report link readiness instead of host presence: their
+ // first open must still run, or waiting for availability would deadlock.
+ if (relayStatus !== 'online' || (presence === false && !isSharedTaskPeer(deviceId))) {
+ return () => { controller.abort(); clearTimeout(timeout); };
+ }
+ void retryRemoteSyncRead({ signal: controller.signal, isStale: cancelled }, async () => {
+ await openLink(deviceId);
+ // Do not issue metadata reads after a late accept for an abandoned route.
+ if (cancelled()) return null;
+ return maker.getSession(sessionId);
+ })
.then(session => {
- if (cancelled) return;
+ if (cancelled()) return;
if (session?.id === sessionId) setLoaded({ scope, source: session.source ?? null });
setLookup(session?.id === sessionId
? { key, status: 'loaded' }
: { key, status: 'missing' });
})
- .catch(() => { if (!cancelled) setLookup({ key, status: 'failed' }); })
+ .catch(() => { if (!cancelled()) setLookup({ key, status: 'failed' }); })
.finally(() => clearTimeout(timeout));
- return () => { cancelled = true; clearTimeout(timeout); };
- }, [key, scope, sessionId, deviceId, knownSource, maker, openLink, creationBlocked]);
+ return () => { controller.abort(); clearTimeout(timeout); };
+ }, [key, scope, sessionId, deviceId, knownSource, maker, openLink, creationBlocked, focused, foreground, relayStatus, presence]);
const source = knownSource !== undefined ? knownSource : (
loaded?.scope === scope ? loaded.source : undefined
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 4b564ec5d9..a562c3c6b9 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -121,7 +121,11 @@ iOS 的系统选图器在确认后立即把选中项交给现有附件队列。
### 任务入口与创建失败恢复
- 非本机发起的任务来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或
- 超时允许手动重读当前任务,不重置共享设备连接。账号或设备切换后忽略旧读取结果。
+ 超时允许手动重读当前任务,不重置共享设备连接。冷启动入口等待 relay 上线,
+ 普通设备已知离线时等待 presence 恢复;共享任务的未建链状态不作为离线门禁。
+ 建链和元数据读取复用有界瞬时错误重试,连接或目标设备状态恢复后自动重读。
+ 离页、退后台、账号或设备切换会取消本地等待与后续重试,迟到结果不回填;
+ 回到页面/前台重新读取。真实缺失和永久错误仍保留手动重读与返回入口。
- 新建页与普通任务页始终保留底部活动提示行的位置(沿用活动行的 44pt 最小高度),
慢发送、思考中和运行结束只改变行内内容,不因提示出现或消失改变消息列表与输入区的位置。
- 本地新建任务立即显示乐观消息与输入框,不因远端来源尚未返回而显示整页等待卡。