Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 去掉剪贴板邀请自动检测,避免无故弹出 iOS 粘贴授权
Dashe2745429ff82
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 929e65d79e..640f2671d1 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -161,8 +161,8 @@"runsOnThisDevice": "Runs on this device","inviteNotice": "Anyone holding the invitation link can join after signing in, with the same Agent access as the host.","offlineAutoClose": "Sharing ends automatically if the host computer stays offline.",- "inviteBoxHint": "Send the link to your teammate to join. On mobile, they can also copy the link and open Cindy.",- "invitationMessage": "You’re invited to join “{{title}}”\n{{link}}\nOpen the link to join. On mobile, you can also copy the link, open Cindy, and confirm to join.",+ "inviteBoxHint": "Send the link to your teammate. They can open it to join, or paste it into Join Shared Task in Cindy.",+ "invitationMessage": "You’re invited to join “{{title}}”\n{{link}}\nOpen the link to join. If Cindy doesn’t open, choose Join Shared Task in Cindy and paste this link.","membersWithLimit": "Members · {{count}} (up to 2 guests)","me": "Me","thisDevice": "This device",@@ -197,8 +197,6 @@"invitationDifferentServer": "This invitation belongs to another Cindy service. Open the link in the matching app.","managementIntro": "Manage the tasks you share and join.","returnToTasks": "Back to Tasks",- "invitationDetected": "Shared task invitation found",- "notNow": "Not Now","closeAllLabel": "Stop All Sharing","closeAllDescription": "Guests will lose access. Task history is kept."},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5b68112feb..234f59ac1b 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -161,8 +161,8 @@"runsOnThisDevice": "このパソコンで実行中","inviteNotice": "招待リンクを持つユーザーはログイン後に参加でき、所有者と同じ Agent 権限を持ちます。","offlineAutoClose": "ホストのパソコンがオフラインのままだと、共有は自動的に終了します。",- "inviteBoxHint": "リンクを送ると、相手はクリックして参加できます。モバイルではリンクをコピーして Cindy を開くこともできます。",- "invitationMessage": "「{{title}}」への招待です\n{{link}}\nリンクを開いて参加してください。モバイルではリンクをコピーして Cindy を開き、参加を確認することもできます。",+ "inviteBoxHint": "リンクを送ると、相手はクリックして参加できます。Cindy の「共有セッションに参加」にリンクを貼り付けて参加することもできます。",+ "invitationMessage": "「{{title}}」への招待です\n{{link}}\nリンクを開いて参加してください。Cindy が開かない場合は、Cindy の「共有セッションに参加」からこのリンクを貼り付けてください。","membersWithLimit": "メンバー · {{count}} 人(ゲストは最大 2 人)","me": "自分","thisDevice": "このパソコン",@@ -197,8 +197,6 @@"invitationDifferentServer": "この招待は別の Cindy サービスのものです。対応するアプリでリンクを開いてください。","managementIntro": "開始した共有と参加した共有を管理します。","returnToTasks": "タスク一覧に戻る",- "invitationDetected": "共有タスクへの招待が見つかりました",- "notNow": "今は参加しない","closeAllLabel": "すべての共有を停止","closeAllDescription": "すべてのゲストがアクセスできなくなります。タスクの履歴は保持されます。"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5e1e75aaf6..5560f726e5 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -161,8 +161,8 @@"runsOnThisDevice": "이 PC에서 실행 중","inviteNotice": "초대 링크를 가진 사용자는 로그인 후 참여할 수 있으며, 호스트와 동일한 Agent 권한을 갖습니다.","offlineAutoClose": "호스트 컴퓨터가 계속 오프라인 상태이면 공유가 자동으로 종료됩니다.",- "inviteBoxHint": "동료에게 링크를 보내면 클릭하여 참여할 수 있습니다. 모바일에서는 링크를 복사한 뒤 Cindy를 열어도 됩니다.",- "invitationMessage": "“{{title}}”에 초대합니다\n{{link}}\n링크를 열어 참여하세요. 모바일에서는 링크를 복사한 뒤 Cindy를 열고 참여를 확인할 수도 있습니다.",+ "inviteBoxHint": "동료에게 링크를 보내면 클릭하여 참여할 수 있습니다. Cindy의 ‘공유 세션 참여’에 링크를 붙여 넣어 참여할 수도 있습니다.",+ "invitationMessage": "“{{title}}”에 초대합니다\n{{link}}\n링크를 열어 참여하세요. Cindy가 열리지 않으면 Cindy에서 ‘공유 세션 참여’를 선택하고 이 링크를 붙여 넣으세요.","membersWithLimit": "멤버 · {{count}}명 (최대 게스트 2명)","me": "나","thisDevice": "이 PC",@@ -197,8 +197,6 @@"invitationDifferentServer": "다른 Cindy 서비스의 초대입니다. 해당 앱에서 링크를 여세요.","managementIntro": "시작하거나 참여한 공유를 관리합니다.","returnToTasks": "작업 목록으로 돌아가기",- "invitationDetected": "공유 작업 초대를 찾았습니다",- "notNow": "나중에","closeAllLabel": "모든 공유 중지","closeAllDescription": "모든 게스트의 접근이 차단됩니다. 작업 기록은 유지됩니다."},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 01af98dab4..54ea4ea4e3 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -161,8 +161,8 @@"runsOnThisDevice": "运行在这台电脑","inviteNotice": "持有邀请链接的用户登录后即可加入,拥有与房主相同的 Agent 使用权限。","offlineAutoClose": "房主电脑持续离线后,共享会自动结束。",- "inviteBoxHint": "将链接发送给伙伴,对方点击即可加入。手机端也可复制链接后打开 Cindy。",- "invitationMessage": "邀请你加入「{{title}}」\n{{link}}\n点击链接加入;手机端也可复制链接后打开 Cindy,确认加入。",+ "inviteBoxHint": "将链接发送给伙伴,对方点击即可加入,也可在 Cindy 中点「加入共享任务」粘贴链接。",+ "invitationMessage": "邀请你加入「{{title}}」\n{{link}}\n点击链接加入;如果没能打开 Cindy,可在 Cindy 中点「加入共享任务」并粘贴这条链接。","membersWithLimit": "成员 · {{count}} 人(最多 2 位访客)","me": "我","thisDevice": "这台电脑",@@ -197,8 +197,6 @@"invitationDifferentServer": "此邀请属于其他 Cindy 服务,请用对应的客户端打开链接","managementIntro": "管理你发起和加入的共享。","returnToTasks": "返回任务列表",- "invitationDetected": "发现共享任务邀请",- "notNow": "暂不加入","closeAllLabel": "取消全部共享","closeAllDescription": "所有访客将无法继续访问,任务记录保留。"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex a74a4f0351..1cd3f4e48e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -161,8 +161,8 @@"runsOnThisDevice": "執行在這台電腦","inviteNotice": "持有邀請連結的使用者登入後即可加入,擁有與房主相同的 Agent 使用權限。","offlineAutoClose": "房主電腦持續離線後,共享會自動結束。",- "inviteBoxHint": "將連結傳送給夥伴,對方點擊即可加入。手機端也可複製連結後開啟 Cindy。",- "invitationMessage": "邀請你加入「{{title}}」\n{{link}}\n點擊連結加入;手機端也可複製連結後開啟 Cindy,確認加入。",+ "inviteBoxHint": "將連結傳送給夥伴,對方點擊即可加入,也可在 Cindy 中點「加入共享任務」貼上連結。",+ "invitationMessage": "邀請你加入「{{title}}」\n{{link}}\n點擊連結加入;如果沒能開啟 Cindy,可在 Cindy 中點「加入共享任務」並貼上這條連結。","membersWithLimit": "成員 · {{count}} 人(最多 2 位訪客)","me": "我","thisDevice": "這台電腦",@@ -197,8 +197,6 @@"invitationDifferentServer": "此邀請屬於其他 Cindy 服務,請用對應的用戶端開啟連結","managementIntro": "管理你發起和加入的共享。","returnToTasks": "返回任務清單",- "invitationDetected": "發現共享任務邀請",- "notNow": "暫不加入","closeAllLabel": "取消全部共享","closeAllDescription": "所有訪客將無法繼續存取,任務記錄保留。"},diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 8ab0e8c0cd..2c66401a79 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -82,8 +82,7 @@ import {} from '@/session/precreatedWorktreeRecovery';import { IncomingShareBridge } from '@/session/IncomingShareBridge';import { usePendingSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';-import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';-import { ClipboardSharedTaskPrompt } from '@/session/ClipboardSharedTaskPrompt';+import { removeLegacyClipboardInvitationHistory } from '@/device-link/legacyClipboardInvitationHistory';import { HomeEntryProvider, useHomeEntrySplashRelease } from '@/session/HomeEntryProvider';import { RemoteDesktopHost } from '@/remote-desktop/RemoteDesktopHost';@@ -98,7 +97,7 @@ function NavigationGate() {const auth = useAuth();const router = useRouter();const segments = useSegments();- useClipboardSharedTaskInvitation(auth.initialized && auth.isAuthenticated, segments.join('/') === 'shared-session');+ useEffect(() => { void removeLegacyClipboardInvitationHistory(); }, []);const { mode, colors, preferenceReady } = useTheme();const { releaseSplash, splashActive } = useStartupSplash();// iOS 状态栏样式走 react-native-screens 的 VC-based 通道(Info.plist 已翻@@ -141,9 +140,9 @@ function NavigationGate() {return;}if (auth.isAuthenticated && inAuthGroup) {- if (pendingSharedTaskInvitation?.source === 'link') router.replace('/shared-session');+ if (pendingSharedTaskInvitation) router.replace('/shared-session');else router.replace('/');- } else if (auth.isAuthenticated && pendingSharedTaskInvitation?.source === 'link' && segments.join('/') !== 'shared-session') {+ } else if (auth.isAuthenticated && pendingSharedTaskInvitation && segments.join('/') !== 'shared-session') {router.replace('/shared-session');}}, [auth.initialized, auth.isAuthenticated, pendingSharedTaskInvitation, router, segments]);@@ -210,7 +209,6 @@ function NavigationGate() {</ResidentHomeListProvider></RecentMessageHistoriesProvider></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 45e3ab5291..f5f483732e 100644--- a/apps/mobile/app/shared-session.tsx+++ b/apps/mobile/app/shared-session.tsx@@ -241,7 +241,7 @@ export default function SharedSessionScreen() {if (enter) await openTask(joined.sharedTaskId, current);}, false, 'join');useEffect(() => {- if (incomingInvitation?.source !== 'link' || !isAuthenticated || sessionId || deviceId || sharedTaskId) return;+ if (!incomingInvitation || !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);diff --git a/apps/mobile/src/__tests__/accountDeletion.test.ts b/apps/mobile/src/__tests__/accountDeletion.test.tsindex a6c99cccc2..39f4d608b8 100644--- a/apps/mobile/src/__tests__/accountDeletion.test.ts+++ b/apps/mobile/src/__tests__/accountDeletion.test.ts@@ -10,20 +10,6 @@ function source(path: string): string {}describe("mobile account deletion", () => {- it('invalidates invitation history before asynchronous terminal cleanup, without clearing it on account switches', () => {- const context = source('src/auth/AuthContext.tsx');- const start = context.indexOf('const clearLocalSession = useCallback');- const body = context.slice(start, context.indexOf('const terminateSession', start));- const capture = body.indexOf('const invitationHistoryOwner = getMobileAuthOwner();');- const invalidate = body.indexOf('setMobileAuthOwner(null);');- const clear = body.indexOf('clearClipboardInvitationHistory(invitationHistoryAccountKey)');- expect(capture).toBeGreaterThan(-1);- expect(invalidate).toBeGreaterThan(capture);- expect(clear).toBeGreaterThan(invalidate);- expect(clear).toBeLessThan(body.indexOf('await unregisterPushTokenBestEffort'));- expect(body).toContain('await clearInvitationHistory;');- expect(context.slice(0, start)).not.toContain('clearClipboardInvitationHistory(');- });it("lets auth-server eligibility exclusively control settings visibility", () => {const settings = source("app/settings.tsx");const visibilityBlock = settings.slice(diff --git a/apps/mobile/src/__tests__/clipboardInvitationHistory.test.ts b/apps/mobile/src/__tests__/clipboardInvitationHistory.test.tsdeleted file mode 100644index b79a3f6cb5..0000000000--- a/apps/mobile/src/__tests__/clipboardInvitationHistory.test.ts+++ /dev/null@@ -1,285 +0,0 @@-import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import { readFileSync } from 'node:fs';-import { resolve } from 'node:path';-import { accountVaultKey, type AuthRegion } from '@cindy/auth-client';-import { getMobileAuthOwner, setMobileAuthOwner, invalidateMobileAuthOwnerForSwitch } from '@/auth/authOwnerGeneration';--const storage = vi.hoisted(() => ({ values: new Map<string, string>(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() }));-vi.mock('@react-native-async-storage/async-storage', () => ({ default: storage }));-import { __testing, clearClipboardInvitationHistory, hasSeenClipboardInvitation, invitationDigest, rememberClipboardInvitation } from '@/device-link/clipboardInvitationHistory';--const account = '["global","guest"]';-const key = __testing.storageKey(account);-const token = 'A'.repeat(43);-const digest = invitationDigest(token);-const day = 24 * 60 * 60_000;-beforeEach(() => {- vi.useFakeTimers(); vi.setSystemTime(new Date('2026-09-29T00:00:00Z'));- __testing.reset(); storage.values.clear();- storage.getItem.mockReset().mockImplementation(async (k: string) => storage.values.get(k) ?? null);- storage.setItem.mockReset().mockImplementation(async (k: string, value: string) => { storage.values.set(k, value); });- storage.removeItem.mockReset().mockImplementation(async (k: string) => { storage.values.delete(k); });-});-afterEach(async () => { await __testing.flush(); vi.useRealTimers(); });--// Execute the actual provider's synchronous logout prelude with committed-// identity refs, real owner fencing and real history storage logic. Native auth-// cleanup starts after this block and is irrelevant to choosing the owner key.-const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8');-const logoutStart = authSource.indexOf('const clearLocalSession = useCallback');-const historyStart = authSource.indexOf('const invitationHistoryOwner =', logoutStart);-const historyEnd = authSource.indexOf('setAccountGeneration(', historyStart);-if (logoutStart < 0 || historyStart < 0 || historyEnd < historyStart) throw new Error('Logout history prelude not found');-const logoutHistory = new Function(- 'getMobileAuthOwner', 'setMobileAuthOwner', 'clearClipboardInvitationHistory',- 'accountVaultKey', 'userRef', 'activeAuthRealmRef',- authSource.slice(historyStart, historyEnd) + '\nreturn clearInvitationHistory;',-);--it.each([- { realm: 'global', phase: 'active' },- { realm: 'global', phase: 'switching' },- { realm: 'cn', phase: 'switching' },- { realm: 'cn', phase: 'rollback' },- { realm: 'cn', phase: 'switched' },- { realm: 'global', phase: 'no-user' },-] as const)('terminal logout clears only the committed history ($realm / $phase)', async ({ realm, phase }) => {- const keys = [accountVaultKey('global', 'guest'), accountVaultKey('cn', 'guest'), accountVaultKey('global', 'other')];- for (const ownerKey of keys) await rememberClipboardInvitation(ownerKey, digest);- const userRef: { current: { id: string } | null } = { current: { id: 'guest' } };- const realmRef: { current: AuthRegion } = { current: realm };- setMobileAuthOwner('guest', realm);- if (phase !== 'active') invalidateMobileAuthOwnerForSwitch();- if (phase === 'rollback') setMobileAuthOwner('guest', realm);- if (phase === 'switched') {- userRef.current = { id: 'other' }; realmRef.current = 'global';- setMobileAuthOwner('other', 'global');- }- if (phase === 'no-user') userRef.current = null;- try {- // Switch invalidation, successful activation and rollback themselves retain- // all histories. Only terminal logout starts account-scoped removal.- for (const ownerKey of keys) expect(await hasSeenClipboardInvitation(ownerKey, digest)).toBe(true);- const expectedClearedKey = userRef.current ? accountVaultKey(realmRef.current, userRef.current.id) : '';- const clearing = logoutHistory(getMobileAuthOwner, setMobileAuthOwner, clearClipboardInvitationHistory, accountVaultKey, userRef, realmRef);- expect(getMobileAuthOwner().accountKey).toBe('');- expect(getMobileAuthOwner().switching).toBeUndefined();- await clearing;- __testing.reset(); // Cold start must not restore the terminated account.- for (const ownerKey of keys) {- expect(await hasSeenClipboardInvitation(ownerKey, digest)).toBe(ownerKey !== expectedClearedKey);- expect(storage.values.has(__testing.storageKey(ownerKey))).toBe(ownerKey !== expectedClearedKey);- }- } finally { setMobileAuthOwner(null); }-});--it('stores only SHA-256 digests and timestamps and reloads them after losing all memory', async () => {- await rememberClipboardInvitation(account, digest);- const raw = storage.values.get(key)!;- expect(raw).not.toContain(token);- expect(JSON.parse(raw)).toEqual({ version: 1, entries: [{ digest, seenAt: Date.now() }] });- expect(digest).toMatch(/^[a-f0-9]{64}$/);- __testing.reset();- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);- expect(await hasSeenClipboardInvitation('["cn","guest"]', digest)).toBe(false);-});--it('expires records at 30 days without extending TTL on reads', async () => {- await rememberClipboardInvitation(account, digest);- vi.setSystemTime(Date.now() + 29 * day);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);- vi.setSystemTime(Date.now() + day);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(storage.values.has(key)).toBe(false);- __testing.reset();- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- await rememberClipboardInvitation(account, invitationDigest('new'));- expect(JSON.parse(storage.values.get(key)!).entries).toHaveLength(1);-});--it('keeps only the most recent 16 distinct invitations in memory and on disk', async () => {- for (let i = 0; i < 17; i++) {- vi.setSystemTime(Date.now() + 1);- await rememberClipboardInvitation(account, invitationDigest(String(i)));- }- expect(await hasSeenClipboardInvitation(account, invitationDigest('0'))).toBe(false);- expect(JSON.parse(storage.values.get(key)!).entries).toHaveLength(16);- __testing.reset();- expect(await hasSeenClipboardInvitation(account, invitationDigest('0'))).toBe(false);- expect(await hasSeenClipboardInvitation(account, invitationDigest('16'))).toBe(true);-});--it('merges concurrent discoveries with a delayed disk read and serializes writes', async () => {- const saved = invitationDigest('saved');- let finish!: (raw: string) => void;- storage.getItem.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));- let releaseWrite!: () => void;- storage.setItem.mockImplementationOnce(async (k: string, value: string) => {- await new Promise<void>(resolve => { releaseWrite = resolve; });- storage.values.set(k, value);- });- const first = rememberClipboardInvitation(account, digest);- await vi.waitFor(() => expect(storage.getItem).toHaveBeenCalledTimes(1));- const secondDigest = invitationDigest('second');- const second = rememberClipboardInvitation(account, secondDigest);- finish(JSON.stringify({ version: 1, entries: [{ digest: saved, seenAt: Date.now() - 1 }] }));- await vi.waitFor(() => expect(storage.setItem).toHaveBeenCalledTimes(1));- const thirdDigest = invitationDigest('third');- const third = rememberClipboardInvitation(account, thirdDigest);- await Promise.resolve();- expect(storage.setItem).toHaveBeenCalledTimes(1);- releaseWrite(); await Promise.all([first, second, third]);- __testing.reset();- for (const item of [saved, digest, secondDigest, thirdDigest]) {- expect(await hasSeenClipboardInvitation(account, item)).toBe(true);- }-});--it('does not overwrite unread disk data and merges it after a read retry', async () => {- const saved = invitationDigest('saved');- const original = JSON.stringify({ version: 1, entries: [{ digest: saved, seenAt: Date.now() - 1 }] });- storage.values.set(key, original);- storage.getItem.mockRejectedValueOnce(new Error('unavailable'));- await rememberClipboardInvitation(account, digest);- expect(storage.setItem).not.toHaveBeenCalled();- expect(storage.values.get(key)).toBe(original);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);- await rememberClipboardInvitation(account, invitationDigest('new'));- __testing.reset();- expect(await hasSeenClipboardInvitation(account, saved)).toBe(true);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);-});--it('keeps failed writes in memory and allows later writes to recover', async () => {- storage.setItem.mockRejectedValueOnce(new Error('unavailable'));- await rememberClipboardInvitation(account, digest);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);- await rememberClipboardInvitation(account, invitationDigest('new'));- __testing.reset();- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);-});--it.each(['broken json', 'null', '{"version":1,"entries":[null,{}, {"digest":"plaintext","seenAt":0}]}'])(- 'ignores corrupt records: %s', async raw => {- storage.values.set(key, raw);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- await rememberClipboardInvitation(account, digest);- expect(JSON.parse(storage.values.get(key)!).entries).toEqual([{ digest, seenAt: Date.now() }]);- },-);--it('never stores an invitation before an account is known', async () => {- await rememberClipboardInvitation('', digest);- expect(await hasSeenClipboardInvitation('', digest)).toBe(false);- expect(storage.getItem).not.toHaveBeenCalled();- expect(storage.setItem).not.toHaveBeenCalled();-});--it('persists pruning on a cold read and retains only unexpired records without a new invitation', async () => {- const fresh = invitationDigest('fresh');- storage.values.set(key, JSON.stringify({ version: 1, entries: [- { digest, seenAt: Date.now() - 31 * day }, { digest: fresh, seenAt: Date.now() - day },- ] }));- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(JSON.parse(storage.values.get(key)!).entries).toEqual([{ digest: fresh, seenAt: Date.now() - day }]);- await hasSeenClipboardInvitation(account, fresh);- expect(storage.setItem).toHaveBeenCalledTimes(1);-});--it('retries failed expiry cleanup without treating expired records as seen', async () => {- await rememberClipboardInvitation(account, digest);- vi.setSystemTime(Date.now() + 30 * day);- storage.removeItem.mockRejectedValueOnce(new Error('unavailable'));- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(storage.values.has(key)).toBe(true);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(storage.values.has(key)).toBe(false);-});--it('does not overwrite a fresh invitation when TTL cleanup is queued behind an older write', async () => {- await rememberClipboardInvitation(account, digest);- let finish!: () => void;- storage.setItem.mockImplementationOnce(async (k: string, value: string) => {- await new Promise<void>(resolve => { finish = resolve; }); storage.values.set(k, value);- });- const oldWrite = rememberClipboardInvitation(account, invitationDigest('old'));- await vi.waitFor(() => expect(finish).toBeDefined());- vi.setSystemTime(Date.now() + 31 * day);- const cleanup = hasSeenClipboardInvitation(account, digest);- const fresh = invitationDigest('fresh');- const newWrite = rememberClipboardInvitation(account, fresh);- finish(); await Promise.all([oldWrite, cleanup, newWrite]);- expect(JSON.parse(storage.values.get(key)!).entries).toEqual([{ digest: fresh, seenAt: Date.now() }]);-});--it.each(['read', 'write'] as const)('clears both memory and disk after an in-flight %s without touching another account', async operation => {- await rememberClipboardInvitation('other-account', digest);- let finish!: () => void;- if (operation === 'read') {- storage.getItem.mockImplementationOnce(async () => {- await new Promise<void>(resolve => { finish = resolve; });- return JSON.stringify({ version: 1, entries: [{ digest, seenAt: Date.now() }] });- });- } else {- storage.setItem.mockImplementationOnce(async (k: string, value: string) => {- await new Promise<void>(resolve => { finish = resolve; }); storage.values.set(k, value);- });- }- const writing = rememberClipboardInvitation(account, digest);- await vi.waitFor(() => expect(finish).toBeDefined());- const clearing = clearClipboardInvitationHistory(account);- expect(clearClipboardInvitationHistory(account)).toBe(clearing);- await rememberClipboardInvitation(account, invitationDigest('late'));- finish(); await Promise.all([writing, clearing]);- expect(storage.values.has(key)).toBe(false);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(await hasSeenClipboardInvitation('other-account', digest)).toBe(true);- // A later login can record fresh offers again.- await rememberClipboardInvitation(account, digest);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);-});--it('clears an account that was never loaded and permits a failed removal to be retried', async () => {- storage.values.set(key, JSON.stringify({ version: 1, entries: [{ digest, seenAt: Date.now() }] }));- storage.removeItem.mockRejectedValueOnce(new Error('unavailable'));- await expect(clearClipboardInvitationHistory(account)).rejects.toThrow('unavailable');- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(storage.values.has(key)).toBe(false);- await rememberClipboardInvitation(account, digest);- expect(await hasSeenClipboardInvitation(account, digest)).toBe(true);-});--it('does not reload erased digests after removal fails and all process memory is lost', async () => {- await rememberClipboardInvitation(account, digest);- storage.removeItem.mockRejectedValueOnce(new Error('remove unavailable'));- await expect(clearClipboardInvitationHistory(account)).rejects.toThrow('remove unavailable');- expect(JSON.parse(storage.values.get(key)!)).toEqual({ version: 1, entries: [] });- __testing.reset(); // Cold start: retain disk only, losing the retired flag and queues.- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(storage.values.has(key)).toBe(false);- expect(storage.removeItem).toHaveBeenCalledTimes(2);-});--it('preserves durable erasure across repeated failed removal attempts and restarts', async () => {- await rememberClipboardInvitation(account, digest);- storage.removeItem.mockRejectedValue(new Error('remove unavailable'));- await expect(clearClipboardInvitationHistory(account)).rejects.toThrow('remove unavailable');- for (let i = 0; i < 2; i++) {- __testing.reset();- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(JSON.parse(storage.values.get(key)!)).toEqual({ version: 1, entries: [] });- }- storage.removeItem.mockImplementation(async (k: string) => { storage.values.delete(k); });- __testing.reset();- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);- expect(storage.values.has(key)).toBe(false);-});--it('still deletes the history when writing the empty record fails', async () => {- await rememberClipboardInvitation(account, digest);- storage.setItem.mockRejectedValueOnce(new Error('write unavailable'));- await clearClipboardInvitationHistory(account);- expect(storage.values.has(key)).toBe(false);- __testing.reset();- expect(await hasSeenClipboardInvitation(account, digest)).toBe(false);-});diff --git a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsxdeleted file mode 100644index cbfffe3909..0000000000--- a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx+++ /dev/null@@ -1,390 +0,0 @@-// @vitest-environment jsdom-import { act, createElement, useEffect, type ReactNode } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import { getMobileAuthOwner, invalidateMobileAuthOwnerForSwitch as invalidateOwner, setMobileAuthOwner as setOwner } from '@/auth/authOwnerGeneration';-import { __testing as historyTesting, invitationDigest } from '@/device-link/clipboardInvitationHistory';-import { useClipboardSharedTaskInvitation } from '@/device-link/useClipboardSharedTaskInvitation';-import { ClipboardSharedTaskPrompt } from '@/session/ClipboardSharedTaskPrompt';-import { clearSharedTaskInvitationIntent as clearIntent, confirmClipboardSharedTaskInvitation as confirmIntent, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent as receiveIntent } from '@/device-link/sharedTaskInvitationIntent';--// Store events now drive a mounted confirmation component as well as the hook.-function inAct<Args extends unknown[], Result>(operation: (...args: Args) => Result) {- return (...args: Args): Result => {- let result!: Result;- act(() => { result = operation(...args); });- return result;- };-}-const clearSharedTaskInvitationIntent = inAct(clearIntent);-const confirmClipboardSharedTaskInvitation = inAct(confirmIntent);-const receiveSharedTaskInvitationIntent = inAct(receiveIntent);-const setMobileAuthOwner = inAct(setOwner);-const invalidateMobileAuthOwnerForSwitch = inAct(invalidateOwner);--const h = vi.hoisted(() => ({ read: vi.fn(), state: 'active', listener: null as null | ((state: string) => void), autoShow: true, onShow: undefined as (() => void) | undefined }));-const storage = vi.hoisted(() => ({ values: new Map<string, string>(), getItem: vi.fn(), setItem: vi.fn() }));-vi.mock('@react-native-async-storage/async-storage', () => ({ default: storage }));-vi.mock('expo-clipboard', () => ({ getStringAsync: h.read }));-vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.test' }));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));-vi.mock('@/theme', () => ({ useThemedStyles: () => ({}) }));-vi.mock('@/components/AppText', () => ({ Text: ({ children }: { children?: ReactNode }) => createElement('span', null, children) }));-vi.mock('@/session/SharedTaskScreen', () => ({- SharedTaskAction: ({ action }: { action: { label: string; onPress(): void } }) => createElement('button', { onClick: action.onPress }, action.label),-}));-vi.mock('react-native', () => ({- Modal: ({ children, onShow }: { children?: ReactNode; onShow?(): void }) => {- useEffect(() => {- h.onShow = onShow;- if (h.autoShow) onShow?.();- }, []);- return createElement('div', { role: 'dialog' }, children);- },- Platform: { OS: 'android' },- View: ({ children }: { children?: ReactNode }) => createElement('div', null, children),- KeyboardAvoidingView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),- ScrollView: ({ children }: { children?: ReactNode }) => createElement('div', null, children),- StyleSheet: { create: (value: unknown) => value },- AppState: {- get currentState() { return h.state; },- addEventListener: (_event: string, listener: (state: string) => void) => {- h.listener = listener; return { remove: () => { if (h.listener === listener) h.listener = null; } };- },-} }));-const token = 'A'.repeat(43);-const link = 'https://relay.example.test/shared-task/join#' + token;-let root: Root;-function Harness({ enabled, joining, promptVisible }: { enabled: boolean; joining: boolean; promptVisible: boolean }) {- useClipboardSharedTaskInvitation(enabled, joining);- // Same visibility boundary as NavigationGate while its startup splash is active.- return enabled && promptVisible ? createElement(ClipboardSharedTaskPrompt) : null;-}-async function render(enabled = true, joining = false, promptVisible = true) {- await act(async () => root.render(createElement(Harness, { enabled, joining, promptVisible })));-}-async function state(next: string) { await act(async () => { h.state = next; h.listener?.(next); }); }-beforeEach(() => {- historyTesting.reset(); storage.values.clear();- h.autoShow = true; h.onShow = undefined;- storage.getItem.mockReset().mockImplementation(async (key: string) => storage.values.get(key) ?? null);- storage.setItem.mockReset().mockImplementation(async (key: string, value: string) => { storage.values.set(key, value); });- Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });- vi.useFakeTimers(); h.read.mockReset(); h.read.mockResolvedValue(link); h.state = 'active';- clearSharedTaskInvitationIntent(); setMobileAuthOwner('guest');- root = createRoot(document.createElement('div'));-});-afterEach(async () => { await act(async () => root.unmount()); clearSharedTaskInvitationIntent(); await historyTesting.flush(); vi.useRealTimers(); });--it('reads on startup and identifies the invitation as clipboard admission', async () => {- await render();- expect(h.read).toHaveBeenCalledTimes(1);- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });-});-it('recognizes an invitation message whose task title contains an ordinary URL', async () => {- h.read.mockResolvedValue(`邀请你加入「检查 https://docs.example.test/page」\n${link}\n复制后打开 Cindy`);- await render();- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });-});-it.each(['before-mount', 'before-login', 'while-running'] as const)('does not reoffer an explicit invitation from the clipboard: %s', async when => {- const intent = 'cindy://shared-session?invitation=' + token + '&server=https%3A%2F%2Frelay.example.test';- h.read.mockResolvedValue('');- if (when !== 'before-mount') await render(when !== 'before-login');- await act(async () => { receiveSharedTaskInvitationIntent(intent); });- if (when === 'before-mount') await render();- clearSharedTaskInvitationIntent(); // Explicit admission has consumed the link.- h.read.mockResolvedValue(link);- await render(); await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- // Dedupe does not block explicit retry or a newly copied invitation.- expect(receiveSharedTaskInvitationIntent(intent)).toBe(true);- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'link' });- clearSharedTaskInvitationIntent(); h.read.mockResolvedValue(link.replace(token, 'B'.repeat(43)));- await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: 'B'.repeat(43), source: 'clipboard' });-});-it('does not let a foreign-server explicit invitation suppress the current service clipboard', async () => {- receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + token + '&server=https%3A%2F%2Fother.example.test');- await render(); clearSharedTaskInvitationIntent();- await state('background'); await state('active');- 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');- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- h.read.mockResolvedValue(link.replace(token, 'B'.repeat(43)));- await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe('B'.repeat(43));- clearSharedTaskInvitationIntent(); h.read.mockResolvedValue(link);- await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()).toBeNull();-});-it.each(['hello', token, link.replace('relay.example.test', 'other.example.test'), link + '?app=unknown'])('ignores ordinary or incompatible clipboard content: %s', async text => {- h.read.mockResolvedValue(text); await render(); expect(getPendingSharedTaskInvitationIntent()).toBeNull();-});-it('does not reread after an inactive/active permission prompt', async () => {- await render(); clearSharedTaskInvitationIntent();- await state('inactive'); await state('active'); expect(h.read).toHaveBeenCalledTimes(1);-});-it('offers the first allowed clipboard invitation when the permission prompt returns to active', async () => {- let finish!: (text: string) => void;- h.read.mockImplementation(() => new Promise(resolve => { finish = resolve; }));- await render();- await state('inactive');- await act(async () => finish(link));- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- await state('active');- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: token, source: 'clipboard' });- expect(h.read).toHaveBeenCalledTimes(1);-});-it('does not offer a permission-prompt result after a link invitation replaces it', async () => {- let finish!: (text: string) => void;- h.read.mockImplementation(() => new Promise(resolve => { finish = resolve; }));- await render(); await state('inactive');- await act(async () => finish(link));- receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test');- await state('active');- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: 'B'.repeat(43), source: 'link' });- expect(h.read).toHaveBeenCalledTimes(1);-});-it('rereads for a new account after a permission prompt returns to active', async () => {- const finishes: Array<(text: string) => void> = [];- h.read.mockImplementation(() => new Promise(resolve => { finishes.push(resolve); }));- await render(); await state('inactive');- await act(async () => finishes[0](link));- await act(async () => { setMobileAuthOwner('another'); await vi.runAllTicks(); });- await state('active');- expect(h.read).toHaveBeenCalledTimes(2);- await act(async () => finishes[1](link.replace(token, 'B'.repeat(43))));- expect(getPendingSharedTaskInvitationIntent()).toMatchObject({ invitation: 'B'.repeat(43), source: 'clipboard' });-});-it('waits for login and leaves an open admission form alone', async () => {- await render(false); expect(h.read).not.toHaveBeenCalled();- await render(true, true); expect(h.read).not.toHaveBeenCalled();-});-it.each(['account', 'manual', 'link'] as const)('discards delayed clipboard results superseded by %s', async reason => {- let finish!: (text: string) => void;- h.read.mockImplementation(() => new Promise(resolve => { finish = resolve; })); await render();- if (reason === 'account') setMobileAuthOwner('another');- if (reason === 'manual') await render(true, true);- if (reason === 'link') {- receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test');- 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();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();-});--async function restart() {- await act(async () => root.unmount());- clearSharedTaskInvitationIntent();- await historyTesting.flush();- // Discard ALL history cache/hydration/queue state, retaining only simulated disk.- historyTesting.reset();- setMobileAuthOwner(null); setMobileAuthOwner('guest');- root = createRoot(document.createElement('div'));- await render();-}--it.each(['dismissed', 'joined'] as const)('does not reoffer a %s invitation after cold-start cache reset', async action => {- await render();- if (action === 'joined') confirmClipboardSharedTaskInvitation(getPendingSharedTaskInvitationIntent()!.id);- clearSharedTaskInvitationIntent(); // Dismissal, or admission consumed after joining.- await restart();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- expect(storage.getItem).toHaveBeenCalledTimes(2);- h.read.mockResolvedValue(link.replace(token, 'B'.repeat(43)));- await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe('B'.repeat(43));-});--it('deduplicates the token despite a changed title and A to B to A clipboard changes across restarts', async () => {- await render();- await restart();- h.read.mockResolvedValue(link.replace(token, 'B'.repeat(43)));- await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe('B'.repeat(43));- clearSharedTaskInvitationIntent();- h.read.mockResolvedValue(`A different title\n${link}`);- await restart();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();-});--it('offers the same token to a different account and remembers each account separately', async () => {- await render(); clearSharedTaskInvitationIntent();- await act(async () => { setMobileAuthOwner('another'); await vi.runAllTicks(); });- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe(token);- clearSharedTaskInvitationIntent();- await act(async () => { setMobileAuthOwner('guest'); await vi.runAllTicks(); });- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- await restart();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- expect(storage.values.size).toBe(2);-});--it.each(['account', 'same-account-generation', 'logout', 'link', 'manual', 'background', 'unmount'] as const)(- 'discards a history read superseded by %s without recording the stale offer', async reason => {- let finish!: (value: string | null) => void;- storage.getItem.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));- await render();- const oldKey = historyTesting.storageKey(getMobileAuthOwner().accountKey);- // Subsequent fresh reads must not offer the stale clipboard value either.- h.read.mockResolvedValue('');- if (reason === 'account') setMobileAuthOwner('another');- if (reason === 'same-account-generation') { invalidateMobileAuthOwnerForSwitch(); setMobileAuthOwner('guest'); }- if (reason === 'logout') setMobileAuthOwner(null);- if (reason === 'link') {- receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test');- clearSharedTaskInvitationIntent();- }- if (reason === 'manual') await render(true, true);- if (reason === 'background') await state('background');- if (reason === 'unmount') await act(async () => root.render(null));- await act(async () => { finish(null); await vi.runAllTicks(); });- await historyTesting.flush();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- expect(storage.values.get(oldKey) ?? '').not.toContain(invitationDigest(token));- },-);--it('persists an explicit link claimed at first login, without suppressing explicit retries', async () => {- setMobileAuthOwner(null);- await render(false);- const url = 'cindy://shared-session?invitation=' + token + '&server=https%3A%2F%2Frelay.example.test';- receiveSharedTaskInvitationIntent(url);- expect(storage.setItem).not.toHaveBeenCalled();- await act(async () => { setMobileAuthOwner('guest'); await vi.runAllTicks(); });- await render(); clearSharedTaskInvitationIntent();- await restart();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- expect(receiveSharedTaskInvitationIntent(url)).toBe(true);- expect(getPendingSharedTaskInvitationIntent()?.source).toBe('link');-});--it('does not attribute an old explicit link to the next account', async () => {- h.read.mockResolvedValue(''); await render();- receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + token + '&server=https%3A%2F%2Frelay.example.test');- await act(async () => { setMobileAuthOwner('another'); await vi.runAllTicks(); });- await historyTesting.flush();- expect(storage.values.has(historyTesting.storageKey(getMobileAuthOwner().accountKey))).toBe(false);-});--it.each(['getItem', 'setItem'] as const)('keeps admission usable when %s fails', async method => {- storage[method].mockRejectedValue(new Error('storage unavailable'));- await render();- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe(token);- clearSharedTaskInvitationIntent();- await state('background'); await state('active');- expect(getPendingSharedTaskInvitationIntent()).toBeNull();- await restart();- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe(token);-});--it('offers an unseen invitation after restart when the startup splash prevented presentation', async () => {- await render(true, false, false);- expect(getPendingSharedTaskInvitationIntent()?.source).toBe('clipboard');- expect(h.onShow).toBeUndefined();- await historyTesting.flush();- expect(storage.setItem).not.toHaveBeenCalled();- await restart();- expect(getPendingSharedTaskInvitationIntent()?.invitation).toBe(token);- expect(storage.setItem).toHaveBeenCalledTimes(1);-});--it('waits for native onShow even after mounting, then suppresses the displayed invitation after restart', async () => {- h.autoShow = false;- await render(true, false, false);- await render(); // Startup splash is released; native presentation is still pending.- expect(h.onShow).toBeDefined();- await historyTesting.flush();- expect(storage.setItem).not.toHaveBeenCalled();- await act(async () => h.onShow?.());- expect(storage.setItem).toHaveBeenCalledTimes(1);- await restart();- expect(getPendingSharedTaskInvitationIntent()).toBeNull();-});--it.each(['new-link', 'account', 'same-account-generation', 'dismiss', 'expired', 'unmount'] as const)(- 'ignores a delayed native onShow after %s', async reason => {- h.autoShow = false;- await render();- const shown = h.onShow!;- h.read.mockResolvedValue('');- await act(async () => {- if (reason === 'new-link') receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test', 'clipboard');- if (reason === 'account') setMobileAuthOwner('another');- if (reason === 'same-account-generation') { invalidateMobileAuthOwnerForSwitch(); setMobileAuthOwner('guest'); }- if (reason === 'dismiss') clearSharedTaskInvitationIntent();- if (reason === 'expired') await vi.advanceTimersByTimeAsync(15 * 60_000);- await vi.runAllTicks();- });- if (reason === 'unmount') await render(true, false, false);- await act(async () => shown());- await historyTesting.flush();- expect(storage.setItem).not.toHaveBeenCalled();- },-);--it('registers presentation for the replacement invitation independently', async () => {- h.autoShow = false;- await render();- const oldShow = h.onShow!;- await act(async () => {- receiveSharedTaskInvitationIntent('cindy://shared-session?invitation=' + 'B'.repeat(43) + '&server=https%3A%2F%2Frelay.example.test', 'clipboard');- });- const newShow = h.onShow!;- expect(newShow).not.toBe(oldShow);- await act(async () => { oldShow(); newShow(); });- await historyTesting.flush();- const raw = [...storage.values.values()].join('');- expect(raw).not.toContain(invitationDigest(token));- expect(raw).toContain(invitationDigest('B'.repeat(43)));-});diff --git a/apps/mobile/src/__tests__/legacyClipboardInvitationHistory.test.ts b/apps/mobile/src/__tests__/legacyClipboardInvitationHistory.test.tsnew file mode 100644index 0000000000..279da2f2af--- /dev/null+++ b/apps/mobile/src/__tests__/legacyClipboardInvitationHistory.test.ts@@ -0,0 +1,34 @@+import { beforeEach, expect, it, vi } from 'vitest';++const storage = vi.hoisted(() => ({+ keys: [] as string[],+ getAllKeys: vi.fn(async () => storage.keys),+ multiRemove: vi.fn(async (_keys: string[]) => undefined),+}));+vi.mock('@react-native-async-storage/async-storage', () => ({+ default: { getAllKeys: storage.getAllKeys, multiRemove: storage.multiRemove },+}));++import { removeLegacyClipboardInvitationHistory } from '@/device-link/legacyClipboardInvitationHistory';++beforeEach(() => {+ vi.clearAllMocks();+ storage.keys = [];+});++it('removes only the old per-account clipboard invitation digests', async () => {+ storage.keys = [+ 'cindy.mobile.shared-task.clipboard-history.v1.["global","a"]',+ 'cindy.mobile.shared-task.clipboard-history.v1.["cn","b"]',+ 'cindy.mobile.other',+ ];+ await removeLegacyClipboardInvitationHistory();+ expect(storage.multiRemove).toHaveBeenCalledExactlyOnceWith(storage.keys.slice(0, 2));+});++it('skips removal when nothing is left and swallows storage failures', async () => {+ await removeLegacyClipboardInvitationHistory();+ expect(storage.multiRemove).not.toHaveBeenCalled();+ storage.getAllKeys.mockRejectedValueOnce(new Error('storage unavailable'));+ await expect(removeLegacyClipboardInvitationHistory()).resolves.toBeUndefined();+});diff --git a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsxindex df14013361..08f618057b 100644--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx@@ -10,7 +10,6 @@ import { setMobileDebugSink } from '@/debug/mobileDebugLog';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,@@ -18,7 +17,7 @@ const h = vi.hoisted(() => ({link: { sharedTaskAvailable: true, invoke: vi.fn(), openLink: vi.fn(), closeLink: vi.fn(), readDeviceList: vi.fn() },api: { list: vi.fn(), get: vi.fn(), join: vi.fn(), leave: vi.fn(), close: vi.fn() },store: { getSessions: vi.fn(), removeDevice: vi.fn(), setDeviceSessions: vi.fn(), upsertDeviceSession: vi.fn() },- t: (key: string, options?: { title?: string; link?: string }) => key === 'sharedTask.invitationMessage' ? `Join “${options?.title}”\n${options?.link}\nOpen the link, or copy it and open Cindy on mobile.` : options?.title ? key + ':' + options.title : key,+ t: (key: string, options?: { title?: string; link?: string }) => key === 'sharedTask.invitationMessage' ? `Join “${options?.title}”\n${options?.link}\nOpen the link, or paste it into Join Shared Task in Cindy.` : options?.title ? key + ':' + options.title : key,}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: h.t }) }));vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async () => null), setItem: vi.fn(async () => undefined) } }));@@ -217,42 +216,9 @@ it('copies a shareable invitation message with a link accepted by automatic andconst content = vi.mocked(writeClipboardText).mock.lastCall![0];expect(content).toContain('Design review');expect(content).toContain(invitationLink);- expect(content).toContain('copy it and open Cindy on mobile');+ expect(content).toContain('paste it into Join Shared Task in Cindy');expect(parseSharedTaskInvitation(content, 'https://relay.example.test')).toEqual({ ok: true, invitation: 'A'.repeat(43) });});-it('uses an automatically detected clipboard invitation without a paste or nickname control', async () => {- receiveSharedTaskInvitationIntent(invitationIntent, 'clipboard');- 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/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 2f1bd3ebf4..81796b6238 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -121,8 +121,7 @@ import { resetAgentCapabilitiesCache } from '@/session/agentCapabilitiesCache';import { resetComposerPaletteCache } from '@/session/composerPaletteCache';import { clearRemoteResourceCache } from '@/device-link/remoteResourceCache';import { clearCachedHomeListSnapshot } from '@/session/mobileHomeListCache';-import { getMobileAuthOwner, invalidateMobileAuthOwnerForSwitch, setMobileAuthOwner } from '@/auth/authOwnerGeneration';-import { clearClipboardInvitationHistory } from '@/device-link/clipboardInvitationHistory';+import { invalidateMobileAuthOwnerForSwitch, setMobileAuthOwner } from '@/auth/authOwnerGeneration';import { updateCredentialAccessToken } from '@/remote-desktop/credentialIdentity';import { clearCachedSessionMessages } from '@/session/mobileSessionMessageCache';import { clearHistoryDisk } from '@/session/remoteHistoryDiskCache';@@ -2914,14 +2913,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {// 继续收到旧账号的任务通知。token 此刻可能已失效(账号不可用),失败静默,// 残留由 server 侧 APNs 410 回收与换账号重注册的让位逻辑兜底。// Invalidate in-flight remote creates before any async logout cleanup begins.- const invitationHistoryOwner = getMobileAuthOwner();- // Switching temporarily empties the owner fence; the committed user/realm- // still identify the session being terminated until the new owner is applied.- const invitationHistoryAccountKey = invitationHistoryOwner.accountKey || (userRef.current- ? accountVaultKey(activeAuthRealmRef.current, userRef.current.id)- : '');setMobileAuthOwner(null);- const clearInvitationHistory = clearClipboardInvitationHistory(invitationHistoryAccountKey).catch(() => undefined);setAccountGeneration((value) => value + 1);// 同步失效认证代次,必须早于第一个 await。否则推送 token 注销的网络等待窗口内,// 迟到的 canary / XD beta 探测仍会把旧账号结果写回本地。@@ -2967,7 +2959,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {await clearCachedHomeListSnapshot().catch(() => undefined);resetComposerPaletteCache();resetAgentCapabilitiesCache();- await clearInvitationHistory;await clearCanaryChannel().catch(() => undefined);// 使用统计的同意记录也随登出清除。手机端没有游客模式:登出后 NavigationGate 会// 把所有路由重定向到 /login,设置页里的统计开关从此不可达。保留同意会让用户处在diff --git a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsxindex b917eb5fa5..0e42f95c18 100644--- a/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx+++ b/apps/mobile/src/auth/__tests__/browserAuthSession.test.tsx@@ -110,7 +110,6 @@ vi.mock('@/session/agentCapabilitiesCache', () => ({ resetAgentCapabilitiesCachevi.mock('@/session/composerPaletteCache', () => ({ resetComposerPaletteCache: async () => {} }));vi.mock('@/device-link/remoteResourceCache', () => ({ clearRemoteResourceCache: async () => {} }));vi.mock('@/session/mobileHomeListCache', () => ({ clearCachedHomeListSnapshot: async () => {} }));-vi.mock('@/device-link/clipboardInvitationHistory', () => ({ clearClipboardInvitationHistory: async () => {} }));vi.mock('@/remote-desktop/credentialIdentity', () => ({ updateCredentialAccessToken() {} }));vi.mock('@/session/mobileSessionMessageCache', () => ({ clearCachedSessionMessages: async () => {} }));vi.mock('@/session/remoteHistoryDiskCache', () => ({ clearHistoryDisk: async () => {} }));diff --git a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.tsindex 75d71881ea..c46eac3328 100644--- a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts+++ b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts@@ -10,8 +10,6 @@ const secureStorage = vi.hoisted(() => ({secureStorage.value = value;}),}));-const invitationHistory = vi.hoisted(() => ({ clear: vi.fn(async (_key: string) => undefined) }));-vi.mock('@/device-link/clipboardInvitationHistory', () => ({ clearClipboardInvitationHistory: invitationHistory.clear }));vi.mock('../secureStorage', () => ({deleteSecureItem: secureStorage.delete,@@ -58,12 +56,10 @@ describe('mobile account vault', () => {secureStorage.value = null;secureStorage.readError = null;vi.clearAllMocks();- invitationHistory.clear.mockReset().mockResolvedValue(undefined);});- it('cleans every invitation history belonging to a deleted Passport, preserving another active account and realm', async () => {+ it('removes a deleted Passport and its accounts, preserving another active account and realm', async () => {const deleted = JSON.stringify(['global', metadata.membershipId]);- const memberOnly = JSON.stringify(['global', 'member-only']);const other = JSON.stringify(['global', 'other']);const cn = JSON.stringify(['cn', metadata.membershipId]);await mutateMobileAccountVault(vault => {@@ -77,25 +73,12 @@ describe('mobile account vault', () => {vault.activeAccountKey = other;});await removeMobilePassport('global', metadata.passportId);- expect(invitationHistory.clear.mock.calls.map(([key]) => key).sort()).toEqual([deleted, memberOnly].sort());const vault = parseMobileAccountVault(secureStorage.value);expect(vault.activeAccountKey).toBe(other);expect(Object.keys(vault.resources).sort()).toEqual([cn, other].sort());expect(vault.passports).toEqual({});});- it('still removes revoked credentials when invitation-history deletion fails', async () => {- const key = JSON.stringify(['global', metadata.membershipId]);- await mutateMobileAccountVault(vault => {- vault.resources[key] = { realm: 'global', refreshToken: 'fake-token', metadata, lastUsedAt: 1 };- vault.activeAccountKey = key;- });- invitationHistory.clear.mockRejectedValueOnce(new Error('storage unavailable'));- await removeMobilePassport('global', metadata.passportId);- expect(invitationHistory.clear).toHaveBeenCalledWith(key);- expect(parseMobileAccountVault(secureStorage.value).resources).toEqual({});- });-it('falls back to an empty read-only projection for malformed encrypted content', () => {expect(parseMobileAccountVault('{bad-json')).toEqual({version: 1,diff --git a/apps/mobile/src/auth/mobileAccountVault.ts b/apps/mobile/src/auth/mobileAccountVault.tsindex e8145bd4cc..a542948ed4 100644--- a/apps/mobile/src/auth/mobileAccountVault.ts+++ b/apps/mobile/src/auth/mobileAccountVault.ts@@ -651,21 +651,14 @@ export async function removeMobileSavedAccount(accountKey: string): Promise<void}export async function removeMobilePassport(realm: AuthRegion, passportId: string): Promise<void> {- const { clearClipboardInvitationHistory } = await import('../device-link/clipboardInvitationHistory');- await mutateMobileAccountVault(async (vault) => {- const passportKey = passportVaultKey(realm, passportId);- const invitationAccounts = new Set((vault.passports[passportKey]?.memberships ?? [])- .map(membership => accountVaultKey(realm, membership.membershipId)));+ await mutateMobileAccountVault((vault) => {+ delete vault.passports[passportVaultKey(realm, passportId)];for (const [key, resource] of Object.entries(vault.resources)) {if (resource.realm === realm && resource.metadata.passportId === passportId) {- invitationAccounts.add(key);delete vault.resources[key];if (vault.activeAccountKey === key) vault.activeAccountKey = null;}}- // Also runs when deletion completes after switching to another Passport.- await Promise.all([...invitationAccounts].map(key => clearClipboardInvitationHistory(key).catch(() => undefined)));- delete vault.passports[passportKey];});}diff --git a/apps/mobile/src/device-link/clipboardInvitationHistory.ts b/apps/mobile/src/device-link/clipboardInvitationHistory.tsdeleted file mode 100644index 8357797163..0000000000--- a/apps/mobile/src/device-link/clipboardInvitationHistory.ts+++ /dev/null@@ -1,143 +0,0 @@-import AsyncStorage from '@react-native-async-storage/async-storage';-import { sha256 } from '@noble/hashes/sha256';-import { bytesToHex } from '@noble/hashes/utils';--const PREFIX = 'cindy.mobile.shared-task.clipboard-history.v1.';-const LIMIT = 16;-const TTL = 30 * 24 * 60 * 60_000;-type Entry = { digest: string; seenAt: number };-type History = {- entries: Entry[];- hydrated: boolean;- hydrating: Promise<void> | null;- writes: Promise<void>;- persisted: string | null;- retired: boolean;- clearing: Promise<void> | null;-};-const histories = new Map<string, History>();--export function invitationDigest(invitation: string): string {- return bytesToHex(sha256(invitation));-}--function historyFor(accountKey: string): History {- let history = histories.get(accountKey);- if (!history) {- history = { entries: [], hydrated: false, hydrating: null, writes: Promise.resolve(), persisted: null, retired: false, clearing: null };- histories.set(accountKey, history);- }- return history;-}--function prune(entries: Entry[]): Entry[] {- const now = Date.now();- const seen = new Set<string>();- return entries.filter(entry => entry.seenAt <= now && now - entry.seenAt < TTL)- .sort((a, b) => b.seenAt - a.seenAt)- .filter(entry => {- if (seen.has(entry.digest)) return false;- seen.add(entry.digest); return true;- }).slice(0, LIMIT);-}--function parse(raw: string | null): Entry[] {- if (!raw) return [];- try {- const value = JSON.parse(raw);- if (value?.version !== 1 || !Array.isArray(value.entries)) return [];- return value.entries.filter((entry: unknown): entry is Entry => {- if (!entry || typeof entry !== 'object') return false;- const item = entry as Partial<Entry>;- return typeof item.digest === 'string' && /^[a-f0-9]{64}$/.test(item.digest)- && typeof item.seenAt === 'number' && Number.isFinite(item.seenAt);- }).map(({ digest, seenAt }: Entry) => ({ digest, seenAt }));- } catch { return []; }-}--async function hydrate(accountKey: string, history: History): Promise<void> {- if (history.hydrated || history.retired) return;- if (!history.hydrating) {- history.hydrating = AsyncStorage.getItem(PREFIX + accountKey).then(raw => {- if (history.retired) return;- // Invitations can be offered while this read is in flight. Preserve those records.- history.entries = prune([...history.entries, ...parse(raw)]);- history.hydrated = true;- history.persisted = raw;- }).catch(() => {- // Retry later; an unread history must never be overwritten by an empty cache.- }).finally(() => { history.hydrating = null; });- }- await history.hydrating;-}--/** Callers revalidate their captured auth generation after this asynchronous read. */-export async function hasSeenClipboardInvitation(accountKey: string, digest: string): Promise<boolean> {- if (!accountKey) return false;- const history = historyFor(accountKey);- if (history.retired) {- // A failed terminal cleanup must not disable deduplication for a later login.- if (!history.clearing) await clearClipboardInvitationHistory(accountKey).catch(() => undefined);- return false;- }- await hydrate(accountKey, history);- if (history.retired) return false;- history.entries = prune(history.entries);- // Persist expiry/normalization even when no new invitation is recorded.- if (history.hydrated) await persistHistory(accountKey, history);- return history.entries.some(entry => entry.digest === digest);-}--/** Remember synchronously in memory; serialize best-effort writes within the captured account. */-export function rememberClipboardInvitation(accountKey: string, digest: string): Promise<void> {- if (!accountKey) return Promise.resolve();- const history = historyFor(accountKey);- if (history.retired) return Promise.resolve();- history.entries = prune([{ digest, seenAt: Date.now() }, ...history.entries]);- return persistHistory(accountKey, history);-}--function persistHistory(accountKey: string, history: History): Promise<void> {- history.writes = history.writes.then(async () => {- await hydrate(accountKey, history);- if (!history.hydrated || history.retired) return;- history.entries = prune(history.entries);- const value = history.entries.length ? JSON.stringify({ version: 1, entries: history.entries }) : null;- if (value === history.persisted) return;- if (value === null) await AsyncStorage.removeItem(PREFIX + accountKey);- else await AsyncStorage.setItem(PREFIX + accountKey, value);- history.persisted = value;- }).catch(() => {- // Storage failure must not interrupt admission; memory still deduplicates this run.- });- return history.writes;-}--/** Invalidate synchronously, then delete after older reads/writes have settled. */-export function clearClipboardInvitationHistory(accountKey: string): Promise<void> {- if (!accountKey) return Promise.resolve();- const history = historyFor(accountKey);- if (history.clearing) return history.clearing;- history.retired = true;- history.entries = [];- const clearing = history.writes.then(async () => {- await history.hydrating;- // Erase digests durably before removing the key. If removal fails and the- // process exits, hydration sees an empty record and retries its removal.- // Still attempt removal if overwriting fails (e.g. storage is full).- await AsyncStorage.setItem(PREFIX + accountKey, JSON.stringify({ version: 1, entries: [] }))- .catch(() => undefined);- await AsyncStorage.removeItem(PREFIX + accountKey);- if (histories.get(accountKey) === history) histories.delete(accountKey);- }).finally(() => { history.clearing = null; });- history.clearing = clearing;- // Keep deletion errors visible to cleanup callers while allowing a later retry.- history.writes = clearing.catch(() => undefined);- return clearing;-}--export const __testing = {- storageKey: (accountKey: string) => PREFIX + accountKey,- reset: () => histories.clear(),- flush: () => Promise.all([...histories.values()].map(history => history.writes)),-};diff --git a/apps/mobile/src/device-link/legacyClipboardInvitationHistory.ts b/apps/mobile/src/device-link/legacyClipboardInvitationHistory.tsnew file mode 100644index 0000000000..446cc8431e--- /dev/null+++ b/apps/mobile/src/device-link/legacyClipboardInvitationHistory.ts@@ -0,0 +1,13 @@+import AsyncStorage from '@react-native-async-storage/async-storage';++const PREFIX = 'cindy.mobile.shared-task.clipboard-history.v1.';++/** Clipboard invitation detection was removed; erase its per-account digests left on disk. */+export async function removeLegacyClipboardInvitationHistory(): Promise<void> {+ try {+ const keys = (await AsyncStorage.getAllKeys()).filter(key => key.startsWith(PREFIX));+ if (keys.length) await AsyncStorage.multiRemove(keys);+ } catch {+ // Best effort; the next launch retries.+ }+}diff --git a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts b/apps/mobile/src/device-link/sharedTaskInvitationIntent.tsindex 36e6cb293b..6ea5bf4284 100644--- a/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts+++ b/apps/mobile/src/device-link/sharedTaskInvitationIntent.ts@@ -2,8 +2,7 @@ import { useSyncExternalStore } from 'react';import { parseSharedTaskInvitationIntent, type SharedTaskInvitationIntent } from '@cindy/device-link';import { getMobileAuthOwner, isMobileAuthOwnerCurrent, subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';-let pending: (SharedTaskInvitationIntent & { id: number; source: 'link' | 'clipboard'; expiresAt: number }) | null = null;-let sequence = 0;+let pending: (SharedTaskInvitationIntent & { expiresAt: number }) | null = null;let stopWatching: (() => void) | undefined;let expiry: ReturnType<typeof setTimeout> | undefined;const listeners = new Set<() => void>();@@ -17,13 +16,13 @@ export function clearSharedTaskInvitationIntent(): void {notify();}-export function receiveSharedTaskInvitationIntent(url: string, source: 'link' | 'clipboard' = 'link'): boolean {+export function receiveSharedTaskInvitationIntent(url: string): boolean {const value = parseSharedTaskInvitationIntent(url);if (!value) return false;clearSharedTaskInvitationIntent();let owner = getMobileAuthOwner();if (owner.switching) return true;- pending = { ...value, id: ++sequence, source, expiresAt: Date.now() + 15 * 60_000 };+ pending = { ...value, expiresAt: Date.now() + 15 * 60_000 };stopWatching = subscribeMobileAuthOwner(() => {const next = getMobileAuthOwner();if (next.switching || (owner.accountKey && !isMobileAuthOwnerCurrent(owner))) clearSharedTaskInvitationIntent();@@ -35,12 +34,5 @@ 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;export const subscribeSharedTaskInvitationIntent = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };export const usePendingSharedTaskInvitationIntent = () => useSyncExternalStore(subscribeSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent, getPendingSharedTaskInvitationIntent);diff --git a/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.tsdeleted file mode 100644index e9bb74d727..0000000000--- a/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts+++ /dev/null@@ -1,103 +0,0 @@-import { useEffect, useRef } from 'react';-import { AppState, type AppStateStatus } from 'react-native';-import * as Clipboard from 'expo-clipboard';-import { parseSharedTaskInvitation, sharedTaskInvitationServer } from '@cindy/device-link';-import { getMobileAuthOwner, isMobileAuthOwnerCurrent, subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';-import { DEVICE_LINK_API_BASE_URL } from '@/config/env';-import {- getPendingSharedTaskInvitationIntent, getSharedTaskInvitationIntentSequence,- receiveSharedTaskInvitationIntent, subscribeSharedTaskInvitationIntent,-} from './sharedTaskInvitationIntent';-import { hasSeenClipboardInvitation, invitationDigest, rememberClipboardInvitation } from './clipboardInvitationHistory';--/** Only account-scoped invitation digests persist; clipboard contents stay in memory. */-export function useClipboardSharedTaskInvitation(enabled: boolean, joining: boolean): void {- const joiningRef = useRef(joining);- joiningRef.current = joining;- useEffect(() => {- let disposed = false;- const rememberExplicitInvitation = () => {- if (disposed) return;- const intent = getPendingSharedTaskInvitationIntent();- const owner = getMobileAuthOwner();- if (!owner.switching && owner.accountKey && intent?.source === 'link'- && intent.server === sharedTaskInvitationServer(DEVICE_LINK_API_BASE_URL)) {- void rememberClipboardInvitation(owner.accountKey, invitationDigest(intent.invitation));- }- };- // Observe even before login enables clipboard reads, and before admission clears- // the pending intent. Explicit links remain usable; only clipboard offers dedupe.- const stopWatching = subscribeSharedTaskInvitationIntent(rememberExplicitInvitation);- // First login may claim an unsigned link without notifying intent listeners.- // Wait until the intent store has retired any previous account's invitation.- const stopWatchingOwner = subscribeMobileAuthOwner(() => queueMicrotask(rememberExplicitInvitation));- rememberExplicitInvitation();- return () => { disposed = true; stopWatching(); stopWatchingOwner(); };- }, []);- useEffect(() => {- if (!enabled) return;- let disposed = false;- let reading = false;- let started = false;- let background = false;- let activation = 0;- let deferredOffer: (() => void) | null = null;- const check = async () => {- if (reading || joiningRef.current || getPendingSharedTaskInvitationIntent()) return;- const owner = getMobileAuthOwner();- if (owner.switching || !owner.accountKey) return;- reading = true;- const captured = activation;- const sequence = getSharedTaskInvitationIntentSequence();- try {- const text = await Clipboard.getStringAsync();- if (disposed) return;- // Bare codes could be unrelated clipboard data; automatic detection accepts links only.- if (!/https?:\/\//.test(text)) return;- const parsed = parseSharedTaskInvitation(text, DEVICE_LINK_API_BASE_URL);- if (!parsed.ok) return;- const digest = invitationDigest(parsed.invitation);- if (await hasSeenClipboardInvitation(owner.accountKey, digest)) return;- const offer = () => {- if (disposed || captured !== activation || joiningRef.current || !isMobileAuthOwnerCurrent(owner)- || sequence !== getSharedTaskInvitationIntentSequence() || getPendingSharedTaskInvitationIntent()) {- return;- }- // The iOS paste permission sheet can resolve the read while the app is inactive.- // Keep that result until focus returns instead of reading the clipboard again.- if (AppState.currentState !== 'active') { deferredOffer = offer; return; }- const url = 'cindy://shared-session?invitation=' + encodeURIComponent(parsed.invitation)- + '&server=' + encodeURIComponent(DEVICE_LINK_API_BASE_URL);- // The prompt records the digest only after its native dialog is shown.- receiveSharedTaskInvitationIntent(url, 'clipboard');- };- offer();- } catch {- // Denied/unavailable clipboard access leaves the current page usable.- } finally {- reading = false;- if (!disposed && captured !== activation && AppState.currentState === 'active') void check();- }- };- const activate = (state: AppStateStatus) => {- if (state === 'background') { background = true; activation++; deferredOffer = null; }- if (state !== 'active') return;- const offer = deferredOffer;- deferredOffer = null;- offer?.();- if (started && !background) return;- started = true; background = false;- 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++; deferredOffer = null;- if (AppState.currentState !== 'active') started = false;- // 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; deferredOffer = null; subscription.remove(); stopWatchingOwner(); };- }, [enabled]);-}diff --git a/apps/mobile/src/i18n/locales/en/sharedTask.json b/apps/mobile/src/i18n/locales/en/sharedTask.jsonindex 75ea0eca01..0a03391d78 100644--- a/apps/mobile/src/i18n/locales/en/sharedTask.json+++ b/apps/mobile/src/i18n/locales/en/sharedTask.json@@ -60,8 +60,8 @@"runsOnThisDevice": "Runs on this device","inviteNotice": "Anyone holding the invitation can join after signing in, with the same Agent access as the host.","offlineAutoClose": "Sharing closes automatically when the host goes offline.",- "inviteBoxHint": "Send the link to your teammate to join. On mobile, they can also copy the link and open Cindy.",- "invitationMessage": "You’re invited to join “{{title}}”\n{{link}}\nOpen the link to join. On mobile, you can also copy the link, open Cindy, and confirm to join.",+ "inviteBoxHint": "Send the link to your teammate. They can open it to join, or paste it into Join Shared Task in Cindy.",+ "invitationMessage": "You’re invited to join “{{title}}”\n{{link}}\nOpen the link to join. If Cindy doesn’t open, choose Join Shared Task in Cindy and paste this link.","membersWithLimit": "Members · {{count}} (up to 2 guests)","me": "Me","thisDevice": "This device",@@ -102,8 +102,6 @@"cancelOperation": "Cancel","leaveShort": "Leave","returnToTasks": "Back to Tasks",- "invitationDetected": "Shared task invitation found",- "notNow": "Not Now","closeAllLabel": "Stop All Sharing","closeAllDescription": "Guests will lose access. Task history is kept.","joinedManageIntro": "Leaving removes your access. The host and other members are not affected."diff --git a/apps/mobile/src/i18n/locales/ja/sharedTask.json b/apps/mobile/src/i18n/locales/ja/sharedTask.jsonindex 98aeae8755..0405208274 100644--- a/apps/mobile/src/i18n/locales/ja/sharedTask.json+++ b/apps/mobile/src/i18n/locales/ja/sharedTask.json@@ -60,8 +60,8 @@"runsOnThisDevice": "このパソコンで実行中","inviteNotice": "招待を持つユーザーはログイン後に参加でき、所有者と同じ Agent 権限を持ちます。","offlineAutoClose": "ホストがオフラインになると、共有は自動的に終了します。",- "inviteBoxHint": "リンクを送ると、相手はクリックして参加できます。モバイルではリンクをコピーして Cindy を開くこともできます。",- "invitationMessage": "「{{title}}」への招待です\n{{link}}\nリンクを開いて参加してください。モバイルではリンクをコピーして Cindy を開き、参加を確認することもできます。",+ "inviteBoxHint": "リンクを送ると、相手はクリックして参加できます。Cindy の「共有セッションに参加」にリンクを貼り付けて参加することもできます。",+ "invitationMessage": "「{{title}}」への招待です\n{{link}}\nリンクを開いて参加してください。Cindy が開かない場合は、Cindy の「共有セッションに参加」からこのリンクを貼り付けてください。","membersWithLimit": "メンバー · {{count}} 人(ゲストは最大 2 人)","me": "自分","thisDevice": "このパソコン",@@ -102,8 +102,6 @@"cancelOperation": "キャンセル","leaveShort": "退出","returnToTasks": "タスク一覧に戻る",- "invitationDetected": "共有タスクへの招待が見つかりました",- "notNow": "今は参加しない","closeAllLabel": "すべての共有を停止","closeAllDescription": "すべてのゲストがアクセスできなくなります。タスクの履歴は保持されます。","joinedManageIntro": "退出するとこの共有にアクセスできなくなります。ホストや他のメンバーには影響しません。"diff --git a/apps/mobile/src/i18n/locales/ko/sharedTask.json b/apps/mobile/src/i18n/locales/ko/sharedTask.jsonindex 94e33808fd..210105c1cf 100644--- a/apps/mobile/src/i18n/locales/ko/sharedTask.json+++ b/apps/mobile/src/i18n/locales/ko/sharedTask.json@@ -60,8 +60,8 @@"runsOnThisDevice": "이 PC에서 실행 중","inviteNotice": "초대를 가진 사용자는 로그인 후 참여할 수 있으며, 호스트와 동일한 Agent 권한을 갖습니다.","offlineAutoClose": "호스트가 오프라인이 되면 공유는 자동으로 종료됩니다.",- "inviteBoxHint": "동료에게 링크를 보내면 클릭하여 참여할 수 있습니다. 모바일에서는 링크를 복사한 뒤 Cindy를 열어도 됩니다.",- "invitationMessage": "“{{title}}”에 초대합니다\n{{link}}\n링크를 열어 참여하세요. 모바일에서는 링크를 복사한 뒤 Cindy를 열고 참여를 확인할 수도 있습니다.",+ "inviteBoxHint": "동료에게 링크를 보내면 클릭하여 참여할 수 있습니다. Cindy의 ‘공유 세션 참여’에 링크를 붙여 넣어 참여할 수도 있습니다.",+ "invitationMessage": "“{{title}}”에 초대합니다\n{{link}}\n링크를 열어 참여하세요. Cindy가 열리지 않으면 Cindy에서 ‘공유 세션 참여’를 선택하고 이 링크를 붙여 넣으세요.","membersWithLimit": "멤버 · {{count}}명 (최대 게스트 2명)","me": "나","thisDevice": "이 PC",@@ -102,8 +102,6 @@"cancelOperation": "취소","leaveShort": "나가기","returnToTasks": "작업 목록으로 돌아가기",- "invitationDetected": "공유 작업 초대를 찾았습니다",- "notNow": "나중에","closeAllLabel": "모든 공유 중지","closeAllDescription": "모든 게스트의 접근이 차단됩니다. 작업 기록은 유지됩니다.","joinedManageIntro": "나가면 이 공유에 접근할 수 없습니다. 호스트와 다른 멤버에게는 영향이 없습니다."diff --git a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.jsonindex 20123f7104..d2d4f43be9 100644--- a/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json+++ b/apps/mobile/src/i18n/locales/zh-CN/sharedTask.json@@ -60,8 +60,8 @@"runsOnThisDevice": "运行在这台电脑","inviteNotice": "持有邀请的用户登录后即可加入,拥有与房主相同的 Agent 使用权限。","offlineAutoClose": "房主离线时,共享会自动关闭。",- "inviteBoxHint": "将链接发送给伙伴,对方点击即可加入。手机端也可复制链接后打开 Cindy。",- "invitationMessage": "邀请你加入「{{title}}」\n{{link}}\n点击链接加入;手机端也可复制链接后打开 Cindy,确认加入。",+ "inviteBoxHint": "将链接发送给伙伴,对方点击即可加入,也可在 Cindy 中点「加入共享任务」粘贴链接。",+ "invitationMessage": "邀请你加入「{{title}}」\n{{link}}\n点击链接加入;如果没能打开 Cindy,可在 Cindy 中点「加入共享任务」并粘贴这条链接。","membersWithLimit": "成员 · {{count}} 人(最多 2 位访客)","me": "我","thisDevice": "这台电脑",@@ -102,8 +102,6 @@"cancelOperation": "取消","leaveShort": "退出","returnToTasks": "返回任务列表",- "invitationDetected": "发现共享任务邀请",- "notNow": "暂不加入","closeAllLabel": "取消全部共享","closeAllDescription": "所有访客将无法继续访问,任务记录保留。","joinedManageIntro": "退出后将无法继续访问该共享;房主和其他成员不受影响。"diff --git a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.jsonindex 84d446d379..5ef398e993 100644--- a/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json+++ b/apps/mobile/src/i18n/locales/zh-TW/sharedTask.json@@ -60,8 +60,8 @@"runsOnThisDevice": "執行在這台電腦","inviteNotice": "持有邀請的使用者登入後即可加入,擁有與房主相同的 Agent 使用權限。","offlineAutoClose": "房主離線時,共享會自動關閉。",- "inviteBoxHint": "將連結傳送給夥伴,對方點擊即可加入。手機端也可複製連結後開啟 Cindy。",- "invitationMessage": "邀請你加入「{{title}}」\n{{link}}\n點擊連結加入;手機端也可複製連結後開啟 Cindy,確認加入。",+ "inviteBoxHint": "將連結傳送給夥伴,對方點擊即可加入,也可在 Cindy 中點「加入共享任務」貼上連結。",+ "invitationMessage": "邀請你加入「{{title}}」\n{{link}}\n點擊連結加入;如果沒能開啟 Cindy,可在 Cindy 中點「加入共享任務」並貼上這條連結。","membersWithLimit": "成員 · {{count}} 人(最多 2 位訪客)","me": "我","thisDevice": "這台電腦",@@ -102,8 +102,6 @@"cancelOperation": "取消","leaveShort": "退出","returnToTasks": "返回任務清單",- "invitationDetected": "發現共享任務邀請",- "notNow": "暫不加入","closeAllLabel": "取消全部共享","closeAllDescription": "所有訪客將無法繼續存取,任務記錄保留。","joinedManageIntro": "退出後將無法繼續存取此共享;房主和其他成員不受影響。"diff --git a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx b/apps/mobile/src/plugins/PluginSetupNativeForm.tsxindex d5e1ce6def..8fcf5c31e7 100644--- a/apps/mobile/src/plugins/PluginSetupNativeForm.tsx+++ b/apps/mobile/src/plugins/PluginSetupNativeForm.tsx@@ -35,6 +35,7 @@ import { type MobilePluginSetupAction } from "./pluginSetupActions";import type { authenticateMobilePluginOauth } from "./pluginOauthClient";import { openMobilePluginOauthSession } from "./pluginOauthSession";import { pluginOauthPlatformCrypto } from "./pluginOauthPlatformCrypto";+import { remotePresentation } from "../../modules/cindy-remote-presentation/src";import { runMobilePluginAuthorization } from "./pluginAuthorizationController";export default function PluginSetupNativeForm({@@ -63,7 +64,7 @@ export default function PluginSetupNativeForm({alive = useRef(true),lock = useRef(false),operation = useRef(0),- copiedCode = useRef<string | undefined>(undefined);+ copiedVersion = useRef<string | undefined>(undefined);const live = useRef({ focused, epoch: link.connectionEpoch });live.current = { focused, epoch: link.connectionEpoch };const [selected, setSelected] = useState<MobilePluginSetupAction | undefined>(@@ -82,9 +83,16 @@ export default function PluginSetupNativeForm({[],);const clearCopiedCode = async () => {- const code = copiedCode.current;- copiedCode.current = undefined;- if (code && (await Clipboard.getStringAsync().catch(() => "")) === code)+ const version = copiedVersion.current;+ copiedVersion.current = undefined;+ // Compare the change counter instead of reading the clipboard, which would+ // make iOS ask the user for paste permission.+ if (+ version &&+ (await remotePresentation+ ?.clipboardVersion?.()+ .catch(() => undefined)) === version+ )await Clipboard.setStringAsync("").catch(() => {});};const clear = () => {@@ -336,8 +344,9 @@ export default function PluginSetupNativeForm({onPress={() => {const code = browser.code!;void Clipboard.setStringAsync(code)- .then(() => {- copiedCode.current = code;+ .then(() => remotePresentation?.clipboardVersion?.())+ .then((version) => {+ copiedVersion.current = version;if (!alive.current) void clearCopiedCode();}).catch(() => {});diff --git a/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx b/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsxdeleted file mode 100644index 7164eda7cd..0000000000--- a/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { useEffect, useRef } from 'react';-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 { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';-import { invitationDigest, rememberClipboardInvitation } from '@/device-link/clipboardInvitationHistory';-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);- const owner = getMobileAuthOwner();- const mounted = useRef(true);- useEffect(() => {- mounted.current = true;- return () => { mounted.current = false; };- }, []);- if (invitation?.source !== 'clipboard') return null;- const onShow = () => {- // Native presentation can finish after a new invitation, account switch, or unmount.- if (!mounted.current || !owner.accountKey || owner.switching || !isMobileAuthOwnerCurrent(owner)- || getPendingSharedTaskInvitationIntent()?.id !== invitation.id) return;- void rememberClipboardInvitation(owner.accountKey, invitationDigest(invitation.invitation));- };- const dismiss = () => {- if (getPendingSharedTaskInvitationIntent()?.id === invitation.id) clearSharedTaskInvitationIntent();- };- return <SharedTaskAdmissionDialog key={invitation.id} title={t('sharedTask.invitationDetected')} onClose={dismiss} onShow={onShow}>- <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 },-});diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.mdindex 9a2c9ea411..2d1c12c29b 100644--- a/docs/product-rules/shared-task-mode.md+++ b/docs/product-rules/shared-task-mode.md@@ -12,7 +12,7 @@## 用户流程1. 房主在任务内点击“共享任务”,开启共享并复制邀请链接。-2. 访客点击链接,通过网页唤起已安装的客户端;登录后直接加入并进入任务。桌面也可在“加入共享任务”中粘贴链接或旧邀请码。移动端启动或回到前台时自动识别剪贴板邀请链接,打开加入页面供用户确认,无申请或批准步骤。+2. 访客点击链接,通过网页唤起已安装的客户端;登录后直接加入并进入任务。两端也可在“加入共享任务”中粘贴链接或旧邀请码,无申请或批准步骤。3. 双方进入现有任务页面,查看全部历史、工具结果、上下文和附件,向同一个 Agent 发消息。4. 房主可复制新邀请、移除访客、停止共享;访客可退出。@@ -26,10 +26,10 @@- 链接默认唤起 Cindy;发起客户端按自身构建身份在 fragment 追加 `?app=cindycn` 或 `?app=cindydev`,网页据此选择移动端已有 Scheme,不让用户选择版本。- 客户端只向当前配置的服务提交邀请。链接中的 `server` 仅用于比较,不能覆盖请求目标;不同服务的邀请显示对应提示。仍接受旧的裸邀请码,REST 和 device-link 既有入参保持兼容。- 访客加入时直接使用已登录用户的账号昵称,不再要求填写自定义昵称。昵称只作为展示信息,成员身份仍由服务端的账号与成员关系决定。-- 移动端登录后在启动或从后台回到前台时自动读取剪贴板,只识别当前服务的有效邀请链接,普通内容与裸邀请码不触发跳转。已提示过的邀请按账号持久化摘要去重,点“暂不加入”或加入后,冷启动与前后台切换均不重放仍在记录内的邀请;剪贴板结果不覆盖已打开的加入页面或更新的链接唤起,异步读取完成后须重新核验账号代次。系统粘贴权限提示引起的短暂失焦不重复读取。菜单不暴露“加入共享任务”入口,页面也不提供独立粘贴按钮。自动识别只打开加入页面,由用户点击加入;显式点击邀请链接继续直接加入并进入任务。-- 待处理邀请仍只在内存中暂存;去重仅持久化解析后邀请 token 的 SHA-256 摘要与提示时间,每个账号保留最近 16 条、有效期 30 天,内存缓存与落盘采用相同隔离、容量和时效。自动识别仅在确认弹框的原生 onShow 回调中记录摘要,并核验邀请 ID、账号代次与组件仍挂载;启动遮罩期间尚未展示的邀请不记为已提示,不等待加入成功;显式链接在账号归属确定后也记录摘要,但显式链接与设置页手动加入不受去重拦截。此规则是历史邀请去重,不承诺检测复制动作:A→B→A 或重新复制 A,在 A 记录有效时仍不自动提示;过期或容量淘汰后可再次提示。分享标题变化不算新邀请,不清空或改写剪贴板,不落盘剪贴板原文或明文邀请码。查询时淘汰的过期记录同步从磁盘清除,与新增记录共用串行写入队列;应用未运行时不承诺后台定时删除,清理失败在后续访问时重试。退出登录或终止会话清理当前账号历史,账号注销清理该身份在当前区域下的各成员历史,清理先失效内存并等待旧读写完成,再以空记录覆写后删除存储键,避免旧写入恢复记录;删除失败但覆写成功时,重启也不会恢复旧摘要,后续访问会重试移除空记录。覆写和删除均失败时只能尽力清理,不保证跨重启擦除;普通账号切换不清除去重历史。存储读取失败不阻断邀请提示,也不覆盖未读出的历史;写入失败保留本次运行的摘要去重,下次冷启动可能再次提示。链接邀请支持首次登录后继续,切换账号、关闭页面或过期后不自动沿用待处理邀请。系统拒绝剪贴板访问时保持当前页面可用,邀请链接唤起仍可使用。-- 两端“设置 → 共享任务”提供独立管理页,分为“我发起的 / 我加入的”,有共享和空状态均保留“加入共享任务”次要按钮。手动加入使用紧凑弹框,接受邀请链接和旧裸邀请码;旧裸邀请码不进入自动识别。2026-09-28 用户已确认交互 HTML 并授权实现:Desktop 设置项位于远程控制之后;Mobile 沿用实际设置分组,在语音词典与外观之间增加“共享任务 → 共享管理”。顶部、主菜单和移动端首页共享分组不提供加入入口;桌面端侧栏“共享任务”分组右侧保留“+”加入入口(2026-09-28 用户确认)。-- 自动识别邀请展示账号与加入确认,不暴露长链接或邀请输入框;手动加入和显式链接成功后进入任务。共享结束提示返回任务列表,并说明重新加入需要房主的新邀请。管理页的移除、退出、关闭当前、关闭全部使用紧凑确认;取消保留原页面、页签和滚动位置。加载失败提供重试,不当作空列表;关闭或退出成功回到对应管理列表。+- 移动端不自动读取剪贴板识别邀请(2026-10-15 移除):iOS 读取剪贴板内容会弹出系统粘贴授权,启动或回到前台时自动检测会制造与用户操作无关的弹窗。手机只通过点击链接唤起加入,或由用户在“加入共享任务”弹框里自己粘贴(系统粘贴菜单不弹授权);邀请文案同步改为“打不开时在 Cindy 中点「加入共享任务」并粘贴链接”。显式点击邀请链接继续直接加入并进入任务。+- 待处理邀请仍只在内存中暂存。旧版本按账号落盘的邀请去重摘要(`cindy.mobile.shared-task.clipboard-history.v1.*`)在应用启动时尽力删除,失败下次启动重试。链接邀请支持首次登录后继续,切换账号、关闭页面或过期后不自动沿用待处理邀请。+- 两端“设置 → 共享任务”提供独立管理页,分为“我发起的 / 我加入的”,有共享和空状态均保留“加入共享任务”次要按钮。手动加入使用紧凑弹框,接受邀请链接和旧裸邀请码。2026-09-28 用户已确认交互 HTML 并授权实现:Desktop 设置项位于远程控制之后;Mobile 沿用实际设置分组,在语音词典与外观之间增加“共享任务 → 共享管理”。顶部、主菜单和移动端首页共享分组不提供加入入口;桌面端侧栏“共享任务”分组右侧保留“+”加入入口(2026-09-28 用户确认)。+- 手动加入和显式链接成功后进入任务。共享结束提示返回任务列表,并说明重新加入需要房主的新邀请。管理页的移除、退出、关闭当前、关闭全部使用紧凑确认;取消保留原页面、页签和滚动位置。加载失败提供重试,不当作空列表;关闭或退出成功回到对应管理列表。- 本阶段不修改移动端原生配置或 runtime fingerprint;Universal Links / Android App Links 另行实施。先部署服务端页面,再发布客户端;旧客户端尚不能解析新链接,需更新。## 权限与顺序