Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): keep current page beneath invitation confirmation
DavidShenaf5700822dc1
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex e64e1dcfa7..a6f9817906 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -79,6 +79,7 @@ import {import { IncomingShareBridge } from '@/session/IncomingShareBridge';import { usePendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';+import { ClipboardSharedTaskPrompt } from '@/session/ClipboardSharedTaskPrompt';import { HomeEntryProvider, useHomeEntrySplashRelease } from '@/session/HomeEntryProvider';import { RemoteDesktopHost } from '@/remote-desktop/RemoteDesktopHost';@@ -135,9 +136,9 @@ function NavigationGate() {return;}if (auth.isAuthenticated && inAuthGroup) {- if (pendingSharedTaskInvitation) router.replace('/shared-session');+ if (pendingSharedTaskInvitation?.source === 'link') router.replace('/shared-session');else router.replace('/');- } else if (auth.isAuthenticated && pendingSharedTaskInvitation && segments.join('/') !== 'shared-session') {+ } else if (auth.isAuthenticated && pendingSharedTaskInvitation?.source === 'link' && segments.join('/') !== 'shared-session') {router.replace('/shared-session');}}, [auth.initialized, auth.isAuthenticated, pendingSharedTaskInvitation, router, segments]);@@ -201,6 +202,7 @@ function NavigationGate() {</RecentMessageHistoriesProvider></ResidentHomeListProvider></RemoteDesktopHost>+ {auth.initialized && auth.isAuthenticated && !splashActive && <ClipboardSharedTaskPrompt accountName={auth.user?.name} />}</NavigationThemeProvider>);}diff --git a/apps/mobile/app/shared-session.tsx b/apps/mobile/app/shared-session.tsxindex be28adf9a1..fe7d953e86 100644--- a/apps/mobile/app/shared-session.tsx+++ b/apps/mobile/app/shared-session.tsx@@ -48,7 +48,6 @@ export default function SharedSessionScreen() {const [joined, setJoined] = useState<SharedTaskListItem[]>([]);const [loaded, setLoaded] = useState(false);const [manualOpen, setManualOpen] = useState(false);- const [clipboardInvitation, setClipboardInvitation] = useState(false);const [guestCounts, setGuestCounts] = useState<Record<string, number>>({});const [deviceNames, setDeviceNames] = useState<Record<string, string>>({});const [tab, setTab] = useState<'current' | 'owned' | 'joined'>('current');@@ -133,7 +132,7 @@ export default function SharedSessionScreen() {useEffect(() => {mounted.current = true;epoch.current++; pending.current = false; setBusy(false);- setState(null); setOwnedTargetUnavailable(false); setOwned([]); setJoined([]); setLoaded(false); setManualOpen(false); setClipboardInvitation(false); setGuestCounts({}); setJoinedId(undefined); setEnded(false);+ setState(null); setOwnedTargetUnavailable(false); setOwned([]); setJoined([]); setLoaded(false); setManualOpen(false); setGuestCounts({}); setJoinedId(undefined); setEnded(false);setInvitation(''); setIncomingLink(null);setNotice(''); setLoadError(''); setTab(management ? 'owned' : 'current'); confirmationPending.current = null;return () => { mounted.current = false; epoch.current++; };@@ -232,19 +231,18 @@ export default function SharedSessionScreen() {const joined = await api.join(parsed.invitation, sharedTaskAccountName(user?.name));if (!current()) return;Keyboard.dismiss(); setInvitation(''); setJoinedId(joined.sharedTaskId);- setManualOpen(false); setClipboardInvitation(false);+ setManualOpen(false);if (enter) await openTask(joined.sharedTaskId, current);}, false, 'join');useEffect(() => {- if (!incomingInvitation || !isAuthenticated || sessionId || deviceId || sharedTaskId) return;+ if (incomingInvitation?.source !== 'link' || !isAuthenticated || sessionId || deviceId || sharedTaskId) return;const input = buildSharedTaskInvitationLink(incomingInvitation.invitation, incomingInvitation.server);// Claim before waiting for relay capability. Leaving this screen discards the invitation.epoch.current++; pending.current = false; setBusy(false);setJoinedId(undefined); setState(null); setEnded(false); setTab('current');- setIncomingLink(incomingInvitation.source === 'link' ? { link: input, owner: getMobileAuthOwner() } : null);+ setIncomingLink({ link: input, owner: getMobileAuthOwner() });clearSharedTaskInvitationIntent();setInvitation(input);- setClipboardInvitation(incomingInvitation.source === 'clipboard');}, [incomingInvitation, isAuthenticated, sessionId, deviceId, sharedTaskId]);useEffect(() => {if (!incomingLink || !isMobileAuthOwnerCurrent(incomingLink.owner) || !isAuthenticated || link.sharedTaskAvailable !== true || guestId || pending.current) return;@@ -346,7 +344,7 @@ export default function SharedSessionScreen() {setJoinedId(undefined); setEnded(false); setState(null); setNotice(''); setLoadError('');router.replace('/devices');}} /> : link.sharedTaskAvailable !== true ? <Text style={styles.intro}>{t(link.sharedTaskAvailable === false ? 'sharedTask.upgrade' : 'sharedTask.retry')}</Text> : <>- {!guestId && !management && !clipboardInvitation && <View style={styles.tabs}>+ {!guestId && !management && <View style={styles.tabs}><MainWindowRowButton accessibilityLabel={t(hostContext ? 'sharedTask.tabCurrent' : 'sharedTask.join')} selected={tab === 'current'} style={[styles.tab, tab === 'current' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('current'); }}><Text style={styles.small}>{t(hostContext ? 'sharedTask.tabCurrent' : 'sharedTask.join')}</Text></MainWindowRowButton><MainWindowRowButton accessibilityLabel={t('sharedTask.tabOwned')} selected={tab === 'owned'} style={[styles.tab, tab === 'owned' && styles.tabSelected]} onPress={() => { setNotice(''); setTab('owned'); }}><Text style={styles.small}>{t('sharedTask.tabOwned')}</Text><View style={styles.badge}><Text style={styles.metadata}>{owned.length}</Text></View></MainWindowRowButton></View>}@@ -397,13 +395,7 @@ export default function SharedSessionScreen() {await host({ action: 'close', sharedTaskId: detail.sharedTaskId });if (current() && mode === 'detail') goBackGuarded(router, { pathname: '/shared-session', params: { mode: 'manage' } });}) }} /></View>- </> : clipboardInvitation ? <SharedTaskAdmissionDialog title={t('sharedTask.invitationDetected')} onClose={() => { if (!pending.current) router.replace('/devices'); }}>- <Text style={styles.intro}>{t('sharedTask.joinIntro')}</Text>- <Text style={styles.taskTitle}>{sharedTaskAccountName(user?.name)}</Text>- <Text style={styles.emptyCopy}>{t('sharedTask.joinNotice')}</Text>- {!!notice && <Text accessibilityRole="alert" style={styles.noticeText}>{notice}</Text>}- <View style={styles.footer}><SharedTaskAction grow action={{ label: t('sharedTask.notNow'), disabled: busy, onPress: () => router.replace('/devices') }} /><SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', busy, onPress: () => joinInvitation(invitation, true) }} /></View>- </SharedTaskAdmissionDialog> : <>+ </> : <><Text style={styles.intro}>{t('sharedTask.joinIntro')}</Text><View style={styles.field}><Text style={styles.label}>{t('sharedTask.invitation')}</Text><TextInput accessibilityLabel={t('sharedTask.invitation')} placeholder={t('sharedTask.invitationPlaceholder')} placeholderTextColor={colors.textPlaceholder} style={[styles.input, styles.invitation]} value={invitation} onChangeText={(text) => { setIncomingLink(null); setInvitation(text); }} maxLength={8192} multiline textAlignVertical="top" autoCapitalize="none" autoCorrect={false} editable={!busy} /></View><View style={styles.noticeBox}><Users size={iconSize.sm} color={colors.textTertiary} /><Text style={[styles.smallMuted, styles.grow]}>{t('sharedTask.joinNotice')}</Text></View>diff --git a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsxindex 02e2db345e..f422fd0a1a 100644--- a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx+++ b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx@@ -4,7 +4,7 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { invalidateMobileAuthOwnerForSwitch, setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';-import { clearSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';+import { clearSharedTaskInvitationIntent, confirmClipboardSharedTaskInvitation, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';const h = vi.hoisted(() => ({ read: vi.fn(), state: 'active', listener: null as null | ((state: string) => void) }));vi.mock('expo-clipboard', () => ({ getStringAsync: h.read }));@@ -38,6 +38,18 @@ it('reads on startup and identifies the invitation as clipboard admission', asynexpect(h.read).toHaveBeenCalledTimes(1);expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });});+it.each(['account', 'new-link', 'expired'] as const)('ignores confirmation after the visible clipboard invitation is superseded by %s', async reason => {+ await render();+ const id = getPendingSharedTaskInvitationIntent()!.id;+ await act(async () => {+ if (reason === 'account') invalidateMobileAuthOwnerForSwitch();+ if (reason === 'new-link') receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test', 'clipboard');+ if (reason === 'expired') await vi.advanceTimersByTimeAsync(15 * 60_000);+ confirmClipboardSharedTaskInvitation(id);+ });+ if (reason === 'new-link') expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: 'B'.repeat(43), source: 'clipboard' });+ else expect(getPendingSharedTaskInvitationIntent()).toBeNull();+});it('reads on foreground, deduplicates consumed links, and detects a newly copied link', async () => {await render(); clearSharedTaskInvitationIntent();await state('background'); await state('active');diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsxindex 10bff18eff..1e7c764913 100644--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx@@ -8,6 +8,7 @@ import { ApiError } from '@/api/client';import { Platform } from 'react-native';import { clearSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';import SharedSessionScreen from '../../app/shared-session';+import { ClipboardSharedTaskPrompt } from '@/session/ClipboardSharedTaskPrompt';const h = vi.hoisted(() => ({params: {} as { sessionId?: string; deviceId?: string; sharedTaskId?: string; expectedOwnedSharedTaskId?: string; mode?: string }, generation: 1,@@ -95,15 +96,37 @@ const invitationLink = 'https://relay.example.test/shared-task/join#' + 'A'.repeconst invitationIntent = 'cindy://shared-session?invitation=' + 'A'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test';it('uses an automatically detected clipboard invitation without a paste or nickname control', async () => {receiveSharedTaskInvitationIntent(invitationIntent, 'clipboard');- await render();+ h.link.invoke.mockResolvedValue({ id: 'task' });+ await act(async () => root.render(createElement('div', null, 'Current task', createElement(ClipboardSharedTaskPrompt, { accountName: 'Account Guest' }))));expect(element.querySelector('textarea')).toBeNull();+ expect(element.textContent).toContain('Current task');expect(element.textContent).toContain('sharedTask.invitationDetected');expect(element.textContent).not.toContain('sharedTask.pasteInvitation');expect(h.api.join).not.toHaveBeenCalled();+ expect(h.router.replace).not.toHaveBeenCalled();await click('sharedTask.join');+ expect(getPendingSharedTaskInvitationIntent()?.source).toBe('link');+ await render();expect(h.api.join).toHaveBeenCalledExactlyOnceWith('A'.repeat(43), 'Account Guest');+ expect(h.router.replace).toHaveBeenCalledWith({ pathname: '/sessions/[sessionId]', params: { sessionId: 'task', deviceId: sharedTaskHostPeer('shared', 'desktop'), deviceName: 'Design review' } });expect(element.querySelector('[aria-label="sharedTask.joinNickname"]')).toBeNull();});+it('dismisses clipboard confirmation without navigating away from the current page', async () => {+ receiveSharedTaskInvitationIntent(invitationIntent, 'clipboard');+ await act(async () => root.render(createElement('div', null, 'Current settings', createElement(ClipboardSharedTaskPrompt, { accountName: 'Account Guest' }))));+ await click('sharedTask.notNow');+ expect(element.textContent).toBe('Current settings');+ expect(getPendingSharedTaskInvitationIntent()).toBeNull();+ expect(h.router.replace).not.toHaveBeenCalled();+ expect(h.api.join).not.toHaveBeenCalled();+});+it('does not let a mounted management screen consume an unconfirmed clipboard invitation', async () => {+ h.params = { mode: 'manage' };+ receiveSharedTaskInvitationIntent(invitationIntent, 'clipboard');+ await render();+ expect(getPendingSharedTaskInvitationIntent()?.source).toBe('clipboard');+ expect(h.api.join).not.toHaveBeenCalled();+});it('rejects an invitation from another service without joining', async () => {await render(); await fill('sharedTask.invitation', invitationLink.replace('relay.example.test', 'other.example.test'));await click('sharedTask.join');diff --git a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts b/apps/mobile/src/device-link/sharedTaskInvitationIntent.tsindex 920cc14304..b9e502a695 100644--- a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts+++ b/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts@@ -35,6 +35,12 @@ export function receiveSharedTaskInvitationIntent(url: string, source: 'link' |}export const getPendingSharedTaskInvitationIntent = () => pending;+/** Confirmation belongs to the visible invitation, never to a newer link or account. */+export function confirmClipboardSharedTaskInvitation(id: number): void {+ if (!pending || pending.id !== id || pending.source !== 'clipboard' || getMobileAuthOwner().switching) return;+ pending = { ...pending, id: ++sequence, source: 'link' };+ notify();+}export const getSharedTaskInvitationIntentSequence = () => sequence;const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };export const usePendingSharedTaskInvitationIntent = () => useSyncExternalStore(subscribe, getPendingSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent);diff --git a/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx b/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsxnew file mode 100644index 0000000000..e4408cc135--- /dev/null+++ b/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx@@ -0,0 +1,35 @@+import { StyleSheet, View } from 'react-native';+import { useTranslation } from 'react-i18next';+import { sharedTaskAccountName } from '@cindy/device-link';+import { Text } from '@/components/AppText';+import { clearSharedTaskInvitationIntent, confirmClipboardSharedTaskInvitation, getPendingSharedTaskInvitationIntent, usePendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';+import { useThemedStyles, type ThemeColors } from '@/theme';+import { fontWeight, lineHeight, spacing, typeScale } from '@/theme/tokens';+import { SharedTaskAdmissionDialog } from './SharedTaskAdmissionDialog';+import { SharedTaskAction } from './SharedTaskScreen';++/** Clipboard discovery must not replace the page underneath the confirmation. */+export function ClipboardSharedTaskPrompt({ accountName }: { accountName?: string | null }) {+ const invitation = usePendingSharedTaskInvitationIntent();+ const { t } = useTranslation();+ const styles = useThemedStyles(makeStyles);+ if (invitation?.source !== 'clipboard') return null;+ const dismiss = () => {+ if (getPendingSharedTaskInvitationIntent()?.id === invitation.id) clearSharedTaskInvitationIntent();+ };+ return <SharedTaskAdmissionDialog title={t('sharedTask.invitationDetected')} onClose={dismiss}>+ <Text style={styles.intro}>{t('sharedTask.joinIntro')}</Text>+ <Text style={styles.account}>{sharedTaskAccountName(accountName)}</Text>+ <Text style={styles.notice}>{t('sharedTask.joinNotice')}</Text>+ <View style={styles.footer}>+ <SharedTaskAction grow action={{ label: t('sharedTask.notNow'), onPress: dismiss }} />+ <SharedTaskAction grow action={{ label: t('sharedTask.join'), tone: 'primary', onPress: () => confirmClipboardSharedTaskInvitation(invitation.id) }} />+ </View>+ </SharedTaskAdmissionDialog>;+}+const makeStyles = (colors: ThemeColors) => StyleSheet.create({+ intro: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginBottom: spacing.lg },+ account: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },+ notice: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, marginTop: spacing.sm, marginBottom: spacing.lg },+ footer: { flexDirection: 'row', gap: spacing.sm, marginTop: spacing.lg },+});