Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): fence relay availability and mobile account requests
DavidShena3a035e47c75
diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskAvailability.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskAvailability.test.tsnew file mode 100644index 0000000000..ef3abc4f31--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskAvailability.test.ts@@ -0,0 +1,29 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';++// Execute the exported predicate without starting Electron or its relay singleton.+const source = ts.createSourceFile('index.ts', readFileSync(resolve(process.cwd(), 'src/main/device-link/index.ts'), 'utf8'), ts.ScriptTarget.Latest, true);+const declaration = source.statements.find((node): node is ts.FunctionDeclaration => ts.isFunctionDeclaration(node) && node.name?.text === 'isSharedTaskAvailable');+if (!declaration?.body) throw new Error('Shared task availability predicate not found');+const compiled = ts.transpileModule('function available() ' + declaration.body.getText(source), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+const available = (status: string, capable = true, authenticated = true, tornDown = false) => {+ const client = { getStatus: () => status, hasServerCapability: vi.fn(() => capable) };+ return new Function('client', 'linkTornDown', 'authManager', 'SHARED_TASK_CAPABILITY', compiled + '; return available();')(client, tornDown, { getAuthState: () => ({ isAuthenticated: authenticated }) }, 'shared-task-v2');+};+describe('desktop shared-task availability', () => {+ it.each(['connecting', 'stopped'])('rejects cached capabilities while %s', (status) => {+ expect(available(status)).toBe(false);+ });+ it('allows sharing again once relay is online and still supports it', () => {+ expect(available('online')).toBe(true);+ expect(available('connecting')).toBe(false);+ expect(available('online')).toBe(true);+ });+ it('retains capability, login and teardown guards', () => {+ expect(available('online', false)).toBe(false);+ expect(available('online', true, false)).toBe(false);+ expect(available('online', true, true, true)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 2771798253..9fd94d5405 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -1358,7 +1358,7 @@ export function getDeviceLinkStatus(): DeviceLinkStatus {}export function isSharedTaskAvailable(): boolean {- return !linkTornDown && !!client?.hasServerCapability(SHARED_TASK_CAPABILITY) &&+ return !linkTornDown && client?.getStatus() === 'online' && client.hasServerCapability(SHARED_TASK_CAPABILITY) &&authManager.getAuthState().isAuthenticated;}diff --git a/apps/mobile/src/__tests__/sharedTaskApiAccountScope.test.ts b/apps/mobile/src/__tests__/sharedTaskApiAccountScope.test.tsnew file mode 100644index 0000000000..15718cb806--- /dev/null+++ b/apps/mobile/src/__tests__/sharedTaskApiAccountScope.test.ts@@ -0,0 +1,104 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ApiError, apiFetchRaw, registerAccountUnavailableHandler, type ApiFetchOptions } from '@/api/client';+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';+import { SharedTaskScopeChangedError } from '@cindy/device-link';+import { useSharedTaskApi } from '@/device-link/useSharedTaskApi';++type ApiFetch = <T>(path: string, opts: Omit<ApiFetchOptions, 'token'>) => Promise<T>;+const auth = vi.hoisted(() => ({ apiFetch: null as unknown as ApiFetch, accountGeneration: 1 }));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => auth }));+vi.mock('react', () => ({ useMemo: (factory: () => unknown) => factory() }));+vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://relay.example.invalid' }));++// Execute the provider callback with in-memory auth dependencies, without native+// login/storage. The shared-task hook and HTTP transport remain real.+const source = ts.createSourceFile('AuthContext.tsx', readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+let callback: ts.Expression | undefined;+let refreshable: ts.FunctionDeclaration | undefined;+function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'apiFetch' && node.initializer && ts.isCallExpression(node.initializer)) callback = node.initializer.arguments[0];+ if (ts.isFunctionDeclaration(node) && node.name?.text === 'isRefreshableUnauthorizedCode') refreshable = node;+ ts.forEachChild(node, visit);+}+visit(source);+if (!callback || !refreshable) throw new Error('AuthProvider API callback not found');+const compiled = ts.transpileModule(refreshable.getText(source) + '; const request = ' + callback.getText(source), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+const getAccessToken = vi.fn<() => Promise<string | null>>();+const refresh = vi.fn<() => Promise<string | null>>();+const terminateSession = vi.fn();+const fetchMock = vi.fn();+const closed = { sharedTaskId: 'shared-a', status: 'closed' };+const response = (status = 200, code = 'TOKEN_EXPIRED') => ({ ok: status === 200, status, json: async () => status === 200 ? closed : { code } }) as Response;+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}+beforeEach(() => {+ vi.resetAllMocks();+ setMobileAuthOwner('account-a');+ getAccessToken.mockResolvedValue('fake-token-a');+ refresh.mockResolvedValue('fake-refreshed-a');+ fetchMock.mockResolvedValue(response());+ vi.stubGlobal('fetch', fetchMock);+ auth.apiFetch = new Function('getAccessToken', 'refresh', 'terminateSession', 'userRef', 'ApiError', 'apiFetchRaw', compiled + '; return request;')(getAccessToken, refresh, terminateSession, { current: { id: 'account-a' } }, ApiError, apiFetchRaw);+});+afterEach(() => { vi.unstubAllGlobals(); setMobileAuthOwner(null); });++describe('shared-task HTTP account fence', () => {+ it('sends and refreshes once while the originating account remains current', async () => {+ fetchMock.mockResolvedValueOnce(response(401));+ await expect(useSharedTaskApi().close('shared-a')).resolves.toEqual(closed);+ expect(refresh).toHaveBeenCalledOnce();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls[1][1].headers.Authorization).toBe('Bearer fake-refreshed-a');+ });+ it('does not send after switching accounts while obtaining the token', async () => {+ const token = deferred<string>();+ getAccessToken.mockReturnValue(token.promise);+ const request = useSharedTaskApi().close('shared-a');+ setMobileAuthOwner('account-b');+ token.resolve('fake-token-b');+ await expect(request).rejects.toBeInstanceOf(SharedTaskScopeChangedError);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(refresh).not.toHaveBeenCalled();+ });+ it.each(['TOKEN_EXPIRED', 'ACCOUNT_UNAVAILABLE'])('ignores a late %s without refreshing or logging out the new account', async (code) => {+ const pending = deferred<Response>();+ const terminal = vi.fn();+ const dispose = registerAccountUnavailableHandler(terminal);+ fetchMock.mockReturnValue(pending.promise);+ try {+ const request = useSharedTaskApi().close('shared-a');+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());+ setMobileAuthOwner('account-b');+ pending.resolve(response(401, code));+ await expect(request).rejects.toBeInstanceOf(SharedTaskScopeChangedError);+ expect(refresh).not.toHaveBeenCalled();+ expect(terminateSession).not.toHaveBeenCalled();+ expect(terminal).not.toHaveBeenCalled();+ } finally { dispose(); }+ });+ it.each(['account', 'realm', 'logout', 'away-and-back'])('does not retry after %s changes during refresh', async (change) => {+ const fresh = deferred<string | null>();+ refresh.mockReturnValue(fresh.promise);+ fetchMock.mockResolvedValueOnce(response(401));+ const request = useSharedTaskApi().close('shared-a');+ await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce());+ if (change === 'realm') setMobileAuthOwner('account-a', 'cn');+ else if (change === 'logout') setMobileAuthOwner(null);+ else { setMobileAuthOwner('account-b'); if (change === 'away-and-back') setMobileAuthOwner('account-a'); }+ fresh.resolve(change === 'logout' ? null : 'fake-token-new-owner');+ await expect(request).rejects.toBeInstanceOf(SharedTaskScopeChangedError);+ expect(fetchMock).toHaveBeenCalledOnce();+ expect(terminateSession).not.toHaveBeenCalled();+ });+ it('keeps ordinary API callers without a scope guard compatible', async () => {+ fetchMock.mockResolvedValueOnce(response(401));+ await expect(auth.apiFetch('/resource', { baseUrl: 'https://relay.example.invalid' })).resolves.toEqual(closed);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/mobile/src/api/client.ts b/apps/mobile/src/api/client.tsindex 155472fef4..d446ae4fb6 100644--- a/apps/mobile/src/api/client.ts+++ b/apps/mobile/src/api/client.ts@@ -19,6 +19,8 @@ export interface ApiFetchOptions {body?: unknown;timeoutMs?: number;cache?: 'no-store';+ /** Reject stale account-scoped work before transport or auth side effects. */+ assertCurrent?: () => void;}const DEFAULT_API_TIMEOUT_MS = 20_000;@@ -43,6 +45,7 @@ export async function apiFetchRaw<T>(path: string,opts: ApiFetchOptions,): Promise<T> {+ opts.assertCurrent?.();const headers: Record<string, string> = { 'Content-Type': 'application/json' };if (opts.token) headers.Authorization = `Bearer ${opts.token}`;if (opts.cache === 'no-store') {@@ -106,6 +109,8 @@ export async function apiFetchRaw<T>(if (timeoutId) clearTimeout(timeoutId);}+ // A late old-account response must not terminate the newly active account.+ opts.assertCurrent?.();if (!response.ok) {const error = readError(data);const code = error.code ?? `HTTP_${response.status}`;diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 8e5053d30f..fd22aa3a46 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -3023,11 +3023,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {path: string,opts: Omit<ApiFetchOptions, 'token'>,): Promise<T> => {+ opts.assertCurrent?.();const token = await getAccessToken();+ opts.assertCurrent?.();if (!token) throw new Error('UNAUTHENTICATED');try {return await apiFetchRaw<T>(path, { ...opts, token });} catch (error) {+ opts.assertCurrent?.();if (!(error instanceof ApiError) || error.status !== 401) throw error;if (error.code === 'ACCOUNT_UNAVAILABLE') {if (userRef.current) {@@ -3038,6 +3041,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {if (!isRefreshableUnauthorizedCode(error.code)) throw error;const fresh = await refresh();+ opts.assertCurrent?.();if (!fresh) {if (userRef.current) await terminateSession();throw error;@@ -3045,6 +3049,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {try {return await apiFetchRaw<T>(path, { ...opts, token: fresh });} catch (retryError) {+ opts.assertCurrent?.();if (retryError instanceof ApiError &&retryError.status === 401 &&diff --git a/apps/mobile/src/device-link/useSharedTaskApi.ts b/apps/mobile/src/device-link/useSharedTaskApi.tsindex 1b0b4b7032..f7a73a3504 100644--- a/apps/mobile/src/device-link/useSharedTaskApi.ts+++ b/apps/mobile/src/device-link/useSharedTaskApi.ts@@ -14,7 +14,11 @@ export function useSharedTaskApi() {request(path, options) {if (!options.isCurrent()) throw new SharedTaskScopeChangedError();return apiFetch(path, { baseUrl: DEVICE_LINK_API_BASE_URL, method: options.method,- body: options.body, cache: 'no-store', timeoutMs: 12_000 });+ body: options.body, cache: 'no-store', timeoutMs: 12_000,+ assertCurrent() {+ if (!options.isCurrent()) throw new SharedTaskScopeChangedError();+ },+ });},}), [apiFetch, accountGeneration]);}