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(shared-task): preserve invitation retries and load remote tasks

DavidShencecd21fed128
diff --git a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
index a4e8eaa8ab..cffa271b7c 100644
--- a/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
+++ b/apps/desktop/src/renderer/features/device-link/SharedTaskDialog.tsx
@@ -275,6 +275,11 @@ export function SharedTaskDialog({ open, onOpenChange, session, returnFocus, ini
if (!item.local) {
await window.electronAPI.deviceLink.openLink(item.hostDeviceId);
if (!current()) return;
+ const readIsCurrent = remoteProjectsStore.captureSessionRead(item.hostDeviceId, item.sessionId);
+ const remoteSession = await window.electronAPI.deviceLink.invoke(item.hostDeviceId, 'local-db:sessions:get', [item.sessionId]) as Session | null;
+ if (!current()) return;
+ if (!readIsCurrent() || remoteSession?.id !== item.sessionId) throw new Error('Remote session is unavailable');
+ remoteProjectsStore.mergeDeviceSessions(item.hostDeviceId, deviceName(item), [readIsCurrent.mergeActivity(remoteSession)]);
remoteProjectsStore.pinSessionOrigin(item.hostDeviceId, item.sessionId);
}
if (current()) { navigate('/cc-agent/' + encodeURIComponent(item.sessionId)); onOpenChange(false); }
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx b/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx
index d0263b3bdd..2d89644dc6 100644
--- a/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/JoinSharedTaskDialog.test.tsx
@@ -8,11 +8,11 @@ import { SharedTaskDialog } from '../SharedTaskDialog';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import { toast } from '@/lib/toast';
-const state = vi.hoisted(() => ({ account: vi.fn(), host: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), invoke: vi.fn(), setSessions: vi.fn(), removeDevice: vi.fn(), getSessions: vi.fn(), bind: vi.fn(), reset: vi.fn() }));
+const state = vi.hoisted(() => ({ account: vi.fn(), host: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), invoke: vi.fn(), setSessions: vi.fn(), mergeSessions: vi.fn(), pin: vi.fn(), captureRead: vi.fn(), removeDevice: vi.fn(), getSessions: vi.fn(), bind: vi.fn(), reset: vi.fn() }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, args?: { title?: string }) => key + (args?.title ? ':' + args.title : '') }) }));
vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'guest', isAuthenticated: true, user: { name: 'Account Guest' } }) }));
vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
-vi.mock('../remoteProjectsStore', () => ({ remoteProjectsStore: { getDeviceName: () => undefined, setDeviceSessions: state.setSessions, removeDevice: state.removeDevice, getMergedRemoteSessions: state.getSessions }, isRemoteDeviceMarkedDisconnected: () => false }));
+vi.mock('../remoteProjectsStore', () => ({ remoteProjectsStore: { getDeviceName: () => undefined, setDeviceSessions: state.setSessions, mergeDeviceSessions: state.mergeSessions, pinSessionOrigin: state.pin, captureSessionRead: state.captureRead, removeDevice: state.removeDevice, getMergedRemoteSessions: state.getSessions }, isRemoteDeviceMarkedDisconnected: () => false }));
vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ bindSharedTaskPushOwner: state.bind, resetRemoteDataOwnerPushFence: state.reset }));
const owned = [
{ sharedTaskId: 'own-1', sessionId: 'local-task', ownerAccountId: 'guest', hostDeviceId: 'pc', revision: 1, title: 'First owned task', local: true },
@@ -32,6 +32,7 @@ beforeEach(() => {
if (action === 'close') { ownedItems = ownedItems.filter(item => item.sharedTaskId !== sharedTaskId); return { closed: [sharedTaskId], failed: [] }; }
});
state.getSessions.mockReturnValue([]);
+ state.captureRead.mockReturnValue(Object.assign(() => true, { mergeActivity: (value: unknown) => value }));
state.invoke.mockImplementation(async (_device, channel, [command]) => {
if (channel === 'maker:shared-task' && command.action === 'close') {
ownedItems = ownedItems.filter(item => item.sharedTaskId !== command.sharedTaskId);
@@ -101,6 +102,38 @@ it('keeps settings tabs keyboard accessible when switching between owned and joi
expect(document.activeElement).toBe(ownerTab);
await act(async () => {});
});
+it('loads an owned remote task before navigation without replacing the device list', async () => {
+ let finish!: (value: unknown) => void;
+ state.invoke.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const close = vi.fn();
+ render(<MemoryRouter><SharedTaskDialog open presentation="settings" onOpenChange={close} /></MemoryRouter>);
+ fireEvent.click(await screen.findByRole('button', { name: owned[1].title }));
+ await waitFor(() => expect(state.invoke).toHaveBeenCalledWith('other-pc', 'local-db:sessions:get', ['other-task']));
+ expect(close).not.toHaveBeenCalled(); expect(state.pin).not.toHaveBeenCalled();
+ const session = { id: 'other-task', title: 'Remote task contents' };
+ await act(async () => finish(session));
+ expect(state.mergeSessions).toHaveBeenCalledWith('other-pc', expect.any(String), [session]);
+ expect(state.setSessions).not.toHaveBeenCalled();
+ expect(state.pin).toHaveBeenCalledWith('other-pc', 'other-task');
+ expect(close).toHaveBeenCalledWith(false);
+ expect(state.mergeSessions.mock.invocationCallOrder[0]).toBeLessThan(close.mock.invocationCallOrder[0]);
+});
+it.each(['missing', 'wrong-task', 'stale-read', 'account-change'] as const)('does not navigate or publish an owned remote task after %s', async reason => {
+ let finish!: (value: unknown) => void;
+ state.invoke.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ if (reason === 'stale-read') state.captureRead.mockReturnValue(Object.assign(() => false, { mergeActivity: (value: unknown) => value }));
+ const close = vi.fn();
+ render(<MemoryRouter><SharedTaskDialog open presentation="settings" onOpenChange={close} /></MemoryRouter>);
+ fireEvent.click(await screen.findByRole('button', { name: owned[1].title }));
+ await waitFor(() => expect(state.invoke).toHaveBeenCalled());
+ await act(async () => {
+ if (reason === 'account-change') setDataOwnerGeneration('another-account');
+ finish(reason === 'missing' ? null : { id: reason === 'wrong-task' ? 'wrong' : 'other-task' });
+ });
+ expect(state.mergeSessions).not.toHaveBeenCalled(); expect(state.pin).not.toHaveBeenCalled();
+ expect(close).not.toHaveBeenCalled();
+ if (reason !== 'account-change') expect(toast.error).toHaveBeenCalled();
+});
async function closeAll() { tab('owned'); await screen.findByRole('button', { name: 'sharedTask.closeAll' }); click('closeAll'); }
it.each(['A'.repeat(43), 'https://relay.example.test/shared-task/join#' + 'A'.repeat(43)])('enters directly through the compact sidebar admission for %s', async invitation => {
diff --git a/apps/mobile/app/+native-intent.ts b/apps/mobile/app/+native-intent.ts
index 42b1591e78..58e6e614f6 100644
--- a/apps/mobile/app/+native-intent.ts
+++ b/apps/mobile/app/+native-intent.ts
@@ -27,7 +27,7 @@ export function redirectSystemPath({ path, initial }: { path: string; initial: b
appId: WECHAT_APP_ID,
universalLink: WECHAT_UNIVERSAL_LINK,
})) return '/';
- const invitationUrl = path.startsWith('/shared-session?') ? `cindy:/${path}` : path;
+ const invitationUrl = /^\/(?:shared-session|shared-task\/join)\?/.test(path) ? `cindy:/${path}` : path;
if (receiveSharedTaskInvitationIntent(invitationUrl)) return '/shared-session';
// path 可能是完整 URL('cindycn://auth?code=...')或路径('/auth?code=...'),统一取出 pathname。
const noScheme = path.replace(/^[a-zA-Z][\w+.-]*:\/\//, '/');
diff --git a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
index e0c46c3fe2..02e2db345e 100644
--- a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
+++ b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
@@ -2,7 +2,7 @@
import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { invalidateMobileAuthOwnerForSwitch, setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';
import { clearSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
@@ -70,6 +70,38 @@ it.each(['account', 'manual', 'link'] as const)('discards delayed clipboard resu
clearSharedTaskInvitationIntent();
}
await act(async () => finish(link)); expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ // The superseded result must not consume this invitation. A fresh read can offer it.
+ if (reason === 'account') {
+ expect(h.read).toHaveBeenCalledTimes(2);
+ await act(async () => finish(link));
+ } else {
+ h.read.mockResolvedValue(link);
+ await render(true, false);
+ await state('background'); await state('active');
+ }
+ expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });
+});
+it('checks again when an account switch settles in the foreground', async () => {
+ invalidateMobileAuthOwnerForSwitch();
+ await render(); expect(h.read).not.toHaveBeenCalled();
+ await act(async () => { setMobileAuthOwner('another'); await vi.runAllTicks(); });
+ expect(h.read).toHaveBeenCalledTimes(1);
+ expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });
+});
+it('lets the old pending invitation clear before reading for the new account', async () => {
+ await render();
+ const next = 'B'.repeat(43);
+ h.read.mockResolvedValue(link.replace(token, next));
+ await act(async () => { setMobileAuthOwner('another'); await vi.runAllTicks(); });
+ expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: next, source: 'clipboard' });
+});
+it('does not read on logout or after unmounting the owner subscription', async () => {
+ await render();
+ await act(async () => { setMobileAuthOwner(null); await vi.runAllTicks(); });
+ expect(h.read).toHaveBeenCalledTimes(1);
+ await act(async () => root.render(null));
+ await act(async () => { setMobileAuthOwner('another'); await vi.runAllTicks(); });
+ expect(h.read).toHaveBeenCalledTimes(1);
});
it('ignores clipboard denial without interrupting the app', async () => {
h.read.mockRejectedValue(new Error('Clipboard unavailable')); await render();
diff --git a/apps/mobile/src/__tests__/nativeIntent.test.ts b/apps/mobile/src/__tests__/nativeIntent.test.ts
index 4201756311..0bcf3c1cfe 100644
--- a/apps/mobile/src/__tests__/nativeIntent.test.ts
+++ b/apps/mobile/src/__tests__/nativeIntent.test.ts
@@ -29,6 +29,15 @@ describe('mobile native deep-link redirects', () => {
vi.advanceTimersByTime(15 * 60_000);
expect(getPendingSharedTaskInvitationIntent()).toBeNull();
});
+ it.each([true, false])('normalizes both relative invitation routes without retaining secrets (initial=%s)', initial => {
+ for (const route of ['/shared-session', '/shared-task/join']) {
+ const path = route + incoming.slice(incoming.indexOf('?'));
+ expect(redirectSystemPath({ path, initial })).toBe('/shared-session');
+ expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation, server: 'https://relay.example.test' });
+ expect(redirectSystemPath({ path: path + '&invitation=bad', initial })).toBe('/shared-session');
+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();
+ }
+ });
it('drops an earlier pending invitation when a malformed one arrives', () => {
redirectSystemPath({ path: incoming, initial: false });
expect(redirectSystemPath({ path: incoming + '&invitation=bad', initial: false })).toBe('/shared-session');
diff --git a/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
index 835537e63b..ea175a728a 100644
--- a/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
+++ b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
@@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react';
import { AppState, type AppStateStatus } from 'react-native';
import * as Clipboard from 'expo-clipboard';
import { parseSharedTaskInvitation } from '@cindy/device-link';
-import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent, subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
import {
getPendingSharedTaskInvitationIntent, getSharedTaskInvitationIntentSequence,
@@ -24,7 +24,7 @@ export function useClipboardSharedTaskInvitation(enabled: boolean, joining: bool
const check = async () => {
if (reading || joiningRef.current || getPendingSharedTaskInvitationIntent()) return;
const owner = getMobileAuthOwner();
- if (owner.switching) return;
+ if (owner.switching || !owner.accountKey) return;
reading = true;
const captured = activation;
const sequence = getSharedTaskInvitationIntentSequence();
@@ -37,14 +37,12 @@ export function useClipboardSharedTaskInvitation(enabled: boolean, joining: bool
if (!parsed.ok || seenInvitations.current.has(parsed.invitation)) return;
if (joiningRef.current || !isMobileAuthOwnerCurrent(owner)
|| sequence !== getSharedTaskInvitationIntentSequence() || getPendingSharedTaskInvitationIntent()) {
- seenInvitations.current.add(parsed.invitation);
return;
}
if (captured !== activation || AppState.currentState !== 'active') return;
- seenInvitations.current.add(parsed.invitation);
const url = 'cindy://shared-session?invitation=' + encodeURIComponent(parsed.invitation)
+ '&server=' + encodeURIComponent(DEVICE_LINK_API_BASE_URL);
- receiveSharedTaskInvitationIntent(url, 'clipboard');
+ if (receiveSharedTaskInvitationIntent(url, 'clipboard')) seenInvitations.current.add(parsed.invitation);
} catch {
// Denied/unavailable clipboard access leaves the current page usable.
} finally {
@@ -59,7 +57,13 @@ export function useClipboardSharedTaskInvitation(enabled: boolean, joining: bool
void check();
};
const subscription = AppState.addEventListener('change', activate);
+ const stopWatchingOwner = subscribeMobileAuthOwner(() => {
+ // Cancel the old owner's read; a fresh read belongs to the settled account.
+ activation++;
+ // Let the intent store retire the old owner's pending link first.
+ queueMicrotask(() => { if (!disposed && AppState.currentState === 'active') void check(); });
+ });
activate(AppState.currentState);
- return () => { disposed = true; subscription.remove(); };
+ return () => { disposed = true; subscription.remove(); stopWatchingOwner(); };
}, [enabled]);
}