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): avoid stale device roster snapshot

Dante29a78fc3bfd0
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 3ae23aef6b..678d1df95b 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -945,7 +945,10 @@ function HomeScreenContent() {
if (homeAccountGenerationRef.current !== accountGenerationAtStart) {
throw new Error('Home account generation superseded');
}
- return readDeviceList();
+ // Provider connection recovery may already own an older roster request. Home's
+ // presence fence is captured above, so joining that earlier request could let its
+ // stale empty snapshot erase a desktop presence delta that will not be replayed.
+ return readDeviceList({ fresh: true });
},
{ maxAttempts: 3 },
);
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 9d192d983e..5181595316 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -6,6 +6,7 @@ import {
DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,
type DeviceLinkClient,
type DeviceLinkStatus,
+ type DeviceView,
type LinkAcceptPayload,
type PresenceSnapshot,
} from '@cindy/device-link';
@@ -17,7 +18,7 @@ const auth = vi.hoisted(() => ({
accountGeneration: 1,
user: { id: 'test-account' },
getAccessToken: vi.fn(async () => 'test-token'),
- apiFetch: vi.fn(async () => ({ devices: [] })),
+ apiFetch: vi.fn(async (..._args: unknown[]): Promise<{ devices: DeviceView[] }> => ({ devices: [] })),
}));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => auth }));
const networkEvents = vi.hoisted(() => ({
@@ -95,6 +96,11 @@ function deferredAccept() {
const promise = new Promise<LinkAcceptPayload>(done => { resolve = done; });
return { promise, resolve };
}
+function deferredRoster() {
+ let resolve!: (value: { devices: DeviceView[] }) => void;
+ const promise = new Promise<{ devices: DeviceView[] }>(done => { resolve = done; });
+ return { promise, resolve };
+}
async function readHistory() {
// Attach rejection handling immediately: lifecycle tests intentionally reject.
let result!: Promise<unknown>;
@@ -105,12 +111,51 @@ async function readHistory() {
beforeEach(async () => {
networkEvents.state = 'active';
auth.accountGeneration = 1;
+ auth.apiFetch.mockReset();
+ auth.apiFetch.mockResolvedValue({ devices: [] });
transport.clients.length = 0;
root = createRoot(document.createElement('div'));
await act(async () => render());
});
afterEach(async () => { await act(async () => root.unmount()); });
+describe('Provider device roster reads', () => {
+ it('starts a fresh snapshot when Home joins a recovery read that predates its presence fence', async () => {
+ const stale = deferredRoster();
+ const current = deferredRoster();
+ auth.apiFetch.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise);
+ const client = transport.clients[0];
+
+ await act(async () => {
+ client.status = 'online';
+ client.statusChanged('online');
+ });
+ expect(auth.apiFetch).toHaveBeenCalledTimes(1);
+
+ await act(async () => client.presenceChanged({
+ deviceId: 'desktop', deviceName: 'Desktop', platform: 'darwin', appVersion: 'test',
+ online: true, remoteControlEnabled: true, busy: false, lastSeenAt: 1,
+ }));
+ const joined = context.readDeviceList();
+ expect(auth.apiFetch).toHaveBeenCalledTimes(1);
+ const fresh = context.readDeviceList({ fresh: true });
+ expect(auth.apiFetch).toHaveBeenCalledTimes(2);
+
+ const desktop: DeviceView = {
+ deviceId: 'desktop', name: 'Desktop', platform: 'darwin', appVersion: 'test',
+ online: true, remoteControlEnabled: true, busy: false, lastSeenAt: new Date(1).toISOString(),
+ isSelf: false,
+ };
+ await act(async () => {
+ stale.resolve({ devices: [] });
+ current.resolve({ devices: [desktop] });
+ });
+
+ expect(await joined).toEqual({ devices: [] });
+ expect(await fresh).toEqual({ devices: [desktop] });
+ });
+});
+
describe('Provider network recovery priority', () => {
const wifi = { type: 'WIFI', isConnected: true, isInternetReachable: true };
it('coalesces equal hints but expedites transport changes and offline recovery', async () => {
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 36b292d82e..9693cfecc4 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -672,7 +672,7 @@ describe('mobile home desktop-first surface', () => {
// Home remains mounted across saved-account activation, so clearing the shared DeviceLink
// stores is insufficient: page-local refs/state must disappear before the next paint too.
expect(source).toContain('const { accountGeneration, deviceId: selfDeviceId, user } = auth;');
- expect(source).toContain('return readDeviceList();');
+ expect(source).toContain('return readDeviceList({ fresh: true });');
expect(source).toContain('const homeAccountGenerationRef = useRef(accountGeneration);');
expect(source).toContain('useLayoutEffect(() => {');
expect(source).toContain('syncInFlightRef.current = null;');
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index bd1727d3ce..ecffc9e868 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -163,7 +163,11 @@ export interface DeviceLinkContextValue {
lastPresenceSnapshot: PresenceSnapshot | null;
/** 当前 relay 连接代内的逐设备 availability;null = 本代尚无权威 verdict。 */
getPresenceAvailability(deviceId: string): boolean | null;
- readDeviceList(): Promise<{ devices: DeviceView[] }>;
+ /**
+ * Read the account device roster. `fresh` starts a new REST snapshot instead of
+ * joining a request that may have started before the caller's reconciliation fence.
+ */
+ readDeviceList(options?: { fresh?: boolean }): Promise<{ devices: DeviceView[] }>;
openLink(deviceId: string): Promise<LinkAcceptPayload>;
/** 丢弃已结算的开链缓存并真正重开;并发重开仍按设备单飞。 */
reopenLink(deviceId: string): Promise<LinkAcceptPayload>;
@@ -395,11 +399,11 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// Home and direct task entry share the same in-flight roster read. Evidence
// belongs to the connection that started it, not whichever one finishes it.
- const readDeviceList = useCallback((): Promise<{ devices: DeviceView[] }> => {
+ const readDeviceList = useCallback((options: { fresh?: boolean } = {}): Promise<{ devices: DeviceView[] }> => {
const client = clientRef.current;
const epoch = connectionEpochRef.current;
const pending = rosterRequestRef.current;
- if (pending?.client === client && pending.epoch === epoch) return pending.promise;
+ if (!options.fresh && pending?.client === client && pending.epoch === epoch) return pending.promise;
const apply = rosterConsumerRef.current?.();
const promise = auth.apiFetch<{ devices: DeviceView[] }>('/api/device-link/devices', {
baseUrl: DEVICE_LINK_API_BASE_URL, timeoutMs: 12_000,