Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 持久化共享任务邀请摘要,避免冷启动重复提示

DavidShen6a140a3dff28
diff --git a/apps/mobile/src/__tests__/clipboardInvitationHistory.test.ts b/apps/mobile/src/__tests__/clipboardInvitationHistory.test.ts
new file mode 100644
index 0000000000..882625b6af
--- /dev/null
+++ b/apps/mobile/src/__tests__/clipboardInvitationHistory.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+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 }));
+import { __testing, 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); });
+});
+afterEach(async () => { await __testing.flush(); vi.useRealTimers(); });
+
+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);
+ __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();
+});
diff --git a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
index 2a8059411a..cbfffe3909 100644
--- a/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
+++ b/apps/mobile/src/__tests__/clipboardSharedTaskInvitation.test.tsx
@@ -1,15 +1,52 @@
// @vitest-environment jsdom
-import { act, createElement } from 'react';
+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 { invalidateMobileAuthOwnerForSwitch, setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+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 { clearSharedTaskInvitationIntent, confirmClipboardSharedTaskInvitation, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent } from '@/device-link/sharedTaskInvitationIntent';
+import { ClipboardSharedTaskPrompt } from '@/session/ClipboardSharedTaskPrompt';
+import { clearSharedTaskInvitationIntent as clearIntent, confirmClipboardSharedTaskInvitation as confirmIntent, getPendingSharedTaskInvitationIntent, receiveSharedTaskInvitationIntent as receiveIntent } from '@/device-link/sharedTaskInvitationIntent';
-const h = vi.hoisted(() => ({ read: vi.fn(), state: 'active', listener: null as null | ((state: string) => void) }));
+// 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-native', () => ({ AppState: {
+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; } };
@@ -18,20 +55,26 @@ vi.mock('react-native', () => ({ AppState: {
const token = 'A'.repeat(43);
const link = 'https://relay.example.test/shared-task/join#' + token;
let root: Root;
-function Harness({ enabled, joining }: { enabled: boolean; joining: boolean }) {
- useClipboardSharedTaskInvitation(enabled, joining); return null;
+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) {
- await act(async () => root.render(createElement(Harness, { enabled, joining })));
+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(); vi.useRealTimers(); });
+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();
@@ -179,3 +222,169 @@ 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__/sharedTaskFlow.test.tsx b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
index 276f49c885..5ea2b2c573 100644
--- a/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
+++ b/apps/mobile/src/__tests__/sharedTaskFlow.test.tsx
@@ -20,6 +20,7 @@ const h = vi.hoisted(() => ({
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,
}));
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) } }));
vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.test', APP_SCHEME: 'cindy' }));
vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('lucide-react-native', () => ({ Check: () => null, Laptop: () => null, Link: () => null, Users: () => null, Clock: () => null, FileText: () => null, Square: () => null, X: () => null }));
diff --git a/apps/mobile/src/device-link/clipboardInvitationHistory.ts b/apps/mobile/src/device-link/clipboardInvitationHistory.ts
new file mode 100644
index 0000000000..b3262a7711
--- /dev/null
+++ b/apps/mobile/src/device-link/clipboardInvitationHistory.ts
@@ -0,0 +1,98 @@
+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>;
+};
+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() };
+ 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) return;
+ if (!history.hydrating) {
+ history.hydrating = AsyncStorage.getItem(PREFIX + accountKey).then(raw => {
+ // Invitations can be offered while this read is in flight. Preserve those records.
+ history.entries = prune([...history.entries, ...parse(raw)]);
+ history.hydrated = true;
+ }).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);
+ await hydrate(accountKey, history);
+ history.entries = prune(history.entries);
+ 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);
+ history.entries = prune([{ digest, seenAt: Date.now() }, ...history.entries]);
+ history.writes = history.writes.then(async () => {
+ await hydrate(accountKey, history);
+ if (!history.hydrated) return;
+ history.entries = prune(history.entries);
+ await AsyncStorage.setItem(PREFIX + accountKey, JSON.stringify({ version: 1, entries: history.entries }));
+ }).catch(() => {
+ // Storage failure must not interrupt admission; memory still deduplicates this run.
+ });
+ return history.writes;
+}
+
+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/useClipboardSharedTaskInvitation.ts b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
index 2dbfabc66f..e9bb74d727 100644
--- a/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
+++ b/apps/mobile/src/device-link/useClipboardSharedTaskInvitation.ts
@@ -8,24 +8,31 @@ import {
getPendingSharedTaskInvitationIntent, getSharedTaskInvitationIntentSequence,
receiveSharedTaskInvitationIntent, subscribeSharedTaskInvitationIntent,
} from './sharedTaskInvitationIntent';
+import { hasSeenClipboardInvitation, invitationDigest, rememberClipboardInvitation } from './clipboardInvitationHistory';
-/** Clipboard contents stay in memory. Only a valid link for this service opens admission. */
+/** 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;
- const seenInvitations = useRef(new Set<string>());
useEffect(() => {
+ let disposed = false;
const rememberExplicitInvitation = () => {
+ if (disposed) return;
const intent = getPendingSharedTaskInvitationIntent();
- if (intent?.source === 'link' && intent.server === sharedTaskInvitationServer(DEVICE_LINK_API_BASE_URL)) {
- seenInvitations.current.add(intent.invitation);
+ 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 stopWatching;
+ return () => { disposed = true; stopWatching(); stopWatchingOwner(); };
}, []);
useEffect(() => {
if (!enabled) return;
@@ -48,7 +55,9 @@ export function useClipboardSharedTaskInvitation(enabled: boolean, joining: bool
// 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 || seenInvitations.current.has(parsed.invitation)) return;
+ 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()) {
@@ -59,7 +68,8 @@ export function useClipboardSharedTaskInvitation(enabled: boolean, joining: bool
if (AppState.currentState !== 'active') { deferredOffer = offer; return; }
const url = 'cindy://shared-session?invitation=' + encodeURIComponent(parsed.invitation)
+ '&server=' + encodeURIComponent(DEVICE_LINK_API_BASE_URL);
- if (receiveSharedTaskInvitationIntent(url, 'clipboard')) seenInvitations.current.add(parsed.invitation);
+ // The prompt records the digest only after its native dialog is shown.
+ receiveSharedTaskInvitationIntent(url, 'clipboard');
};
offer();
} catch {
diff --git a/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx b/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx
index e4408cc135..7164eda7cd 100644
--- a/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx
+++ b/apps/mobile/src/session/ClipboardSharedTaskPrompt.tsx
@@ -1,8 +1,11 @@
+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';
@@ -13,11 +16,23 @@ export function ClipboardSharedTaskPrompt({ accountName }: { accountName?: strin
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 title={t('sharedTask.invitationDetected')} onClose={dismiss}>
+ 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>
diff --git a/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx b/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx
index ed9becc164..dc1ab1f9b0 100644
--- a/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx
+++ b/apps/mobile/src/session/SharedTaskAdmissionDialog.tsx
@@ -5,11 +5,11 @@ import { useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
/** Compact invitation form; the management page stays mounted behind it. */
-export function SharedTaskAdmissionDialog({ title, onClose, children }: {
- title: string; onClose(): void; children: ReactNode;
+export function SharedTaskAdmissionDialog({ title, onClose, onShow, children }: {
+ title: string; onClose(): void; onShow?(): void; children: ReactNode;
}) {
const styles = useThemedStyles(makeStyles);
- return <Modal transparent visible animationType="fade" onRequestClose={onClose}>
+ return <Modal transparent visible animationType="fade" onRequestClose={onClose} onShow={onShow}>
<KeyboardAvoidingView style={styles.backdrop} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
<View style={styles.card} accessibilityViewIsModal testID="sharedTask.admissionDialog">
<ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.content} bounces={false}>
diff --git a/docs/product-rules/shared-task-mode.md b/docs/product-rules/shared-task-mode.md
index ce8641e17f..d8e365b99c 100644
--- a/docs/product-rules/shared-task-mode.md
+++ b/docs/product-rules/shared-task-mode.md
@@ -1,6 +1,6 @@
# 共享任务:远程连接的多人版本
-> 产品裁决更新:2026-09-28。实现与验证进度见文末;本文不代表已上线。
+> 产品裁决更新:2026-09-29。实现与验证进度见文末;本文不代表已上线。
> 产品、代码、协议与存储统一使用“共享任务 / SharedTask”,开发期旧协议不保留兼容别名。
## 定位
@@ -26,8 +26,8 @@
- 链接默认唤起 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 用户确认)。
- 自动识别邀请展示账号与加入确认,不暴露长链接或邀请输入框;手动加入和显式链接成功后进入任务。共享结束提示返回任务列表,并说明重新加入需要房主的新邀请。管理页的移除、退出、关闭当前、关闭全部使用紧凑确认;取消保留原页面、页签和滚动位置。加载失败提供重试,不当作空列表;关闭或退出成功回到对应管理列表。
- 本阶段不修改移动端原生配置或 runtime fingerprint;Universal Links / Android App Links 另行实施。先部署服务端页面,再发布客户端;旧客户端尚不能解析新链接,需更新。