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): cancel inactive group preview requests

xdae8b39fefa0a
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 24a812d1ef..931715a5f1 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -13,6 +13,8 @@ const h = vi.hoisted(() => ({
confirm: vi.fn(),
leave: vi.fn(),
focused: true,
+ appState: 'active',
+ appStateListeners: new Set<(state: string) => void>(),
closeSettings: null as null | (() => void),
row: null as any,
inputs: {} as Record<string, any>,
@@ -54,7 +56,9 @@ vi.mock('react-native', () => {
Platform: { get OS() { return h.platform.OS; }, select: (value: any) => value[h.platform.OS] },
Alert: { alert: h.alert },
useWindowDimensions: () => ({ width: 390, height: 844 }),
- AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
+ AppState: { get currentState() { return h.appState; }, addEventListener: (_event: string, listener: (state: string) => void) => {
+ h.appStateListeners.add(listener); return { remove: () => h.appStateListeners.delete(listener) };
+ } },
Keyboard: { dismiss: () => {} },
Animated: { View: box('div'), Value: class { setValue() {} interpolate() { return this; } }, timing: () => ({ start() {}, stop() {} }),
loop: () => ({ start() {}, stop() {} }), sequence: () => ({}) },
@@ -285,6 +289,7 @@ beforeEach(() => {
h.management = null;
vi.clearAllMocks();
h.uuid = 0; h.inputs = {}; h.teammateQuery = ''; h.teammates = { rows: [], loading: false, failed: false };
+ h.appState = 'active'; h.appStateListeners.clear();
h.platform.OS = 'ios'; h.focused = true; h.keyboardAvoidingView = null; h.headerBlur = []; h.headerFade = [];
h.chat = { reload: vi.fn(), act: vi.fn(async () => ({ effects: [] })), online: true };
h.discarded = []; h.deleted = []; h.leaveGuard = []; h.leaveDecision = async () => false;
@@ -1375,6 +1380,38 @@ describe('direct server group presentation', () => {
expect(byId('botGroup.settings.delete')?.disabled).toBe(true);
expect(byId('botGroup.settings.replyMode.mentioned')?.disabled).toBe(true);
});
+ // PR #7145 r4371434691: a pushed task leaves the group mounted. Unit,
+ // real page + native layout/focus/AppState events; old tests only scrolled rows.
+ it.each(['ios', 'android'])('suspends previews on blur/background and restores the viewport (%s)', async platform => {
+ h.platform.OS = platform;
+ const attachment = (id: string) => ({ id, name: `${id}.png`, category: 'file' as const, mimeType: '', size: 0, url: null, path: null });
+ const media = vi.fn(async (id: string) => ({ ...attachment(id), category: 'image' as const, url: `https://media.example.invalid/${id}` }));
+ h.chat = { ...h.chat, server: true, media };
+ const data = (count: number) => group({ messages: Array.from({ length: count }, (_, n) => message(`m${n}`, n + 1,
+ { authorKind: 'user', isSelf: false, attachments: [attachment(`image-${n}`)] })), plans: [], openPlan: null });
+ const show = async (count: number) => {
+ await render(data(count));
+ await act(async () => {
+ h.scroll.onLayout({ nativeEvent: { layout: { height: 500 } } });
+ for (const strip of node.querySelectorAll('[data-testid="attachmentStrip"]')) {
+ let row = strip as HTMLElement & { nativeLayout?: (event: unknown) => void };
+ while (!row.nativeLayout) row = row.parentElement as typeof row;
+ row.nativeLayout!({ nativeEvent: { layout: { y: 0, height: 100 } } });
+ }
+ });
+ };
+ await show(1); expect(media).toHaveBeenCalledTimes(1);
+ h.focused = false;
+ await show(2); expect(media).toHaveBeenCalledTimes(1);
+ h.focused = true;
+ await show(2); expect(media).toHaveBeenCalledTimes(2);
+ await act(async () => { h.appState = 'background'; h.appStateListeners.forEach(listener => listener(h.appState)); });
+ await show(3); expect(media).toHaveBeenCalledTimes(2);
+ await act(async () => { h.appState = 'active'; h.appStateListeners.forEach(listener => listener(h.appState)); });
+ expect(media).toHaveBeenCalledTimes(3);
+ expect(byId('attachment.image')?.getAttribute('data-uri')).toBe('https://media.example.invalid/image-0');
+ });
+
it.each([undefined, 'thread-root'])('gates server previews by the viewport and reauthorizes on tap (thread=%s)', async (threadRootId) => {
const attachment = { id: 'media', name: 'picture.png', mimeType: 'image/png', size: 10, category: 'image' as const, url: 'https://media.example.invalid/one-use', path: null };
h.chat = { ...h.chat, server: true, media: vi.fn(async () => attachment) };
@@ -1390,7 +1427,7 @@ describe('direct server group presentation', () => {
await act(async () => h.scroll.onScroll({ nativeEvent: {
contentOffset: { y: 700 }, contentSize: { height: 1000 }, layoutMeasurement: { height: 500 },
} }));
- expect(h.chat.media).toHaveBeenCalledExactlyOnceWith('media');
+ expect(h.chat.media).toHaveBeenCalledExactlyOnceWith('media', expect.any(AbortSignal));
expect(byId('attachment.image')?.getAttribute('data-uri')).toBe(attachment.url);
await click('attachment.image'); expect(h.chat.media).toHaveBeenCalledTimes(2);
expect(byId('lightbox')?.getAttribute('data-url')).toBe(attachment.url);
diff --git a/apps/mobile/src/__tests__/apiClient.test.ts b/apps/mobile/src/__tests__/apiClient.test.ts
index 6538c26c92..4754e5be02 100644
--- a/apps/mobile/src/__tests__/apiClient.test.ts
+++ b/apps/mobile/src/__tests__/apiClient.test.ts
@@ -132,6 +132,52 @@ describe('apiFetchRaw', () => {
);
});
+ // PR #7145 r4371434693: caller cancellation must reach native fetch and
+ // settle promptly even if transport ignores abort; existing tests only timed out.
+ it.each([0, 100])('aborts caller-owned requests without a timeout/auth side effect (timeout=%s)', async timeoutMs => {
+ vi.useFakeTimers();
+ let nativeSignal: AbortSignal | null | undefined;
+ let finish!: (response: Response) => void;
+ vi.stubGlobal('fetch', vi.fn((_url: string, init: RequestInit) => {
+ nativeSignal = init.signal; return new Promise<Response>(resolve => { finish = resolve; });
+ }));
+ const terminal = vi.fn(); const dispose = registerAccountUnavailableHandler(terminal);
+ const controller = new AbortController();
+ const request = apiFetchRaw('/v1/media', { baseUrl: 'https://chat.example.invalid', signal: controller.signal, timeoutMs });
+ void request.catch(() => {});
+ try {
+ controller.abort();
+ expect(nativeSignal?.aborted).toBe(true);
+ await expect(request).rejects.toMatchObject({ name: 'AbortError' });
+ finish(new Response(JSON.stringify({ error: { code: 'ACCOUNT_UNAVAILABLE' } }), { status: 401 }));
+ await Promise.resolve(); await Promise.resolve();
+ expect(terminal).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0);
+ } finally { dispose(); finish(new Response('{}')); }
+ });
+
+ it('cancels while the response body is still pending', async () => {
+ vi.useFakeTimers();
+ let startedBody!: () => void;
+ const bodyStarted = new Promise<void>(resolve => { startedBody = resolve; });
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: () => {
+ startedBody(); return new Promise(() => {});
+ } })));
+ const controller = new AbortController();
+ const request = apiFetchRaw('/v1/media', { baseUrl: 'https://chat.example.invalid', signal: controller.signal });
+ await bodyStarted; controller.abort();
+ await expect(request).rejects.toMatchObject({ name: 'AbortError' });
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not start a fetch after its caller already cancelled', async () => {
+ vi.useFakeTimers();
+ const fetch = vi.fn(() => new Promise<Response>(() => {})); vi.stubGlobal('fetch', fetch);
+ const controller = new AbortController(); controller.abort();
+ const request = apiFetchRaw('/v1/media', { baseUrl: 'https://chat.example.invalid', signal: controller.signal }).catch(error => error);
+ expect(fetch).not.toHaveBeenCalled();
+ await expect(request).resolves.toMatchObject({ name: 'AbortError' });
+ });
+
it('aborts hung requests instead of leaving the UI in a connecting state', async () => {
vi.useFakeTimers();
const fetchMock = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
diff --git a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
index 089647e8b4..7ebe0c8788 100644
--- a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
+++ b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
@@ -15,6 +15,7 @@ vi.mock('expo-modules-core', () => ({ requireOptionalNativeModule: () => null })
// conversion and the viewer are production code; only native surfaces and unrelated views are replaced.
const runtime = vi.hoisted(() => ({
alerts: [] as unknown[][],
+ accountGeneration: 1,
imageEvents: new Map<string, { onLoad?: (event: unknown) => void; onError?: () => void }>(),
}));
const openBrowserAsync = vi.hoisted(() => vi.fn(async (_url: string) => ({})));
@@ -77,7 +78,7 @@ vi.mock('@/theme', async () => {
return { ...tokens, monoFont: 'monospace', useTheme: () => ({ colors, mode: 'light' }), useThemedStyles: (make: any) => make(colors) };
});
vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text, MAX_FONT_SIZE_MULTIPLIER: 2 }));
-vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: runtime.accountGeneration }) }));
vi.mock('@/session/usePluginResultCard', () => ({ usePluginResultCard: () => ({}), useSessionPluginResource: () => ({ title: 'Art' }) }));
vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({ downloadRemoteMediaShareTemp: vi.fn() }));
vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
@@ -126,7 +127,7 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
let host: HTMLDivElement | undefined;
afterEach(() => { act(() => root?.unmount()); root = undefined; host?.remove(); host = undefined; });
-beforeEach(() => { runtime.alerts = []; runtime.imageEvents.clear(); openBrowserAsync.mockClear(); });
+beforeEach(() => { runtime.accountGeneration = 1; runtime.alerts = []; runtime.imageEvents.clear(); openBrowserAsync.mockClear(); });
// Placeholder for a short-lived authorized address; never a real signed URL.
const signedImageUrl = 'https://chat.example.invalid/media/group-picture.png?signature=placeholder';
@@ -297,6 +298,27 @@ describe('Chat Server group image attachments (#5875)', () => {
expect(container.querySelector(`img[src="${neighbourUrl}"]`)).toBe(loadedNeighbour);
});
+ it('does not abort a neighbouring pending authorization when retrying one failed image', async () => {
+ let finishNeighbour!: (value: BotGroupAttachment) => void;
+ let neighbourSignal: AbortSignal | undefined;
+ const resolveServerMedia = vi.fn(async (id: string, signal?: AbortSignal) => {
+ if (id === 'neighbour') {
+ neighbourSignal = signal;
+ return new Promise<BotGroupAttachment>(resolve => { finishNeighbour = resolve; });
+ }
+ return { ...serverAttachment, category: 'image' as const, url: signedImageUrl };
+ });
+ const container = await render({ resolveServerMedia, attachments: [serverAttachment, { ...serverAttachment, id: 'neighbour' }] });
+ try {
+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());
+ expect(neighbourSignal?.aborted).toBe(false);
+ expect(resolveServerMedia.mock.calls.map(([id]) => id)).toEqual(['media-1', 'neighbour', 'media-1']);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
+ } finally {
+ await act(async () => finishNeighbour({ ...serverAttachment, id: 'neighbour', category: 'image', url: `${signedImageUrl}&neighbour=1` }));
+ }
+ });
+
// CloudCompanionScreen selects this policy even if its row is visible.
it('keeps cloud transcript media tap-only, including after returning from the viewer', async () => {
const resolveServerMedia = vi.fn(async () => ({ ...serverAttachment, category: 'image' as const, url: signedImageUrl }));
@@ -348,6 +370,35 @@ describe('Chat Server group image attachments (#5875)', () => {
expect(container.querySelector('img')).toBeNull();
});
+ // PR #7145 r4371434693: three stalled requests must not block another page
+ // until their 20s timeout. Unit through the real strip; old tests settled them first.
+ it.each(['message', 'account'])('aborts old preview jobs and frees slots before stale requests settle (%s)', async change => {
+ const signals: Array<AbortSignal | undefined> = [];
+ const finishes: Array<(value: BotGroupAttachment) => void> = [];
+ const oldResolver = vi.fn((_id: string, signal?: AbortSignal) => {
+ signals.push(signal); return new Promise<BotGroupAttachment>(resolve => finishes.push(resolve));
+ });
+ const container = await render({ resolveServerMedia: oldResolver,
+ attachments: Array.from({ length: 4 }, (_, n) => ({ ...serverAttachment, id: `old-${n}` })) });
+ expect(oldResolver).toHaveBeenCalledTimes(3);
+ const nextUrl = `${signedImageUrl}&next=1`;
+ const nextResolver = vi.fn(async () => ({ ...serverAttachment, category: 'image' as const, url: nextUrl }));
+ if (change === 'account') runtime.accountGeneration++;
+ await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
+ messageId: change === 'message' ? 'next-message' : 'message-1', align: 'right',
+ attachments: [serverAttachment], onResolveRemoteMedia: vi.fn(), resolveServerMedia: nextResolver,
+ })));
+ try {
+ expect(signals.every(signal => signal?.aborted)).toBe(true);
+ expect(nextResolver).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(nextUrl);
+ } finally {
+ await act(async () => finishes.forEach(finish => finish({ ...serverAttachment, category: 'image', url: signedImageUrl })));
+ }
+ expect(oldResolver).toHaveBeenCalledTimes(3);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(nextUrl);
+ });
+
it('bounds preview authorization and ignores late results when the message changes', async () => {
const pending: Array<(value: BotGroupAttachment) => void> = [];
const resolveServerMedia = vi.fn((id: string) => new Promise<BotGroupAttachment>(resolve => {
diff --git a/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx b/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx
index 0ddcef794b..4964ae82c6 100644
--- a/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerEndpointDiscovery.test.tsx
@@ -37,6 +37,7 @@ function Probe() { roster = hooks.useChatServerRoster(true); group = hooks.useCh
async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
beforeEach(() => {
+ // reset-modules: each case reconstructs process-owned endpoint/realm startup caches.
vi.resetModules(); vi.clearAllMocks(); h.storage.clear(); h.sockets = [];
vi.stubGlobal('__DEV__', false);
vi.stubEnv('EXPO_PUBLIC_CINDY_AUTH_REGION', 'global');
@@ -84,6 +85,13 @@ it.each(['cn', 'global'] as const)('release %s discovery feeds HTTP, WS and the
await act(async () => { await group.act('send', { text: 'fixture', clientId: 'fixture-operation', mentions: { all: false, botIds: [] } }); });
const sent = h.auth.apiFetch.mock.calls.find(([path, options]) => path.endsWith('/messages') && options.method === 'POST')!;
expect(sent[1].body).toEqual({ operationId: 'fixture-operation', content: [{ type: 'text', text: 'fixture' }], mentions: [] });
+ // PR #7145: exercise the real group hook/client/HTTP adapter, not only a fake resolver.
+ const controller = new AbortController();
+ h.auth.apiFetch.mockImplementationOnce(async (_path, options) => {
+ expect(options.signal).toBe(controller.signal);
+ return { name: 'image.png', type: 'image/png', size: 1, url: 'https://media.example.invalid/image.png' };
+ });
+ await expect(group.media(self, controller.signal)).resolves.toMatchObject({ category: 'image', url: 'https://media.example.invalid/image.png' });
const oldSockets = [...h.sockets];
const other = region === 'cn' ? 'global' : 'cn';
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, text: async () => texts[other] })));
diff --git a/apps/mobile/src/api/client.ts b/apps/mobile/src/api/client.ts
index c981812f5e..9d8a120bed 100644
--- a/apps/mobile/src/api/client.ts
+++ b/apps/mobile/src/api/client.ts
@@ -26,6 +26,8 @@ export interface ApiFetchOptions {
assertCurrent?: () => void;
/** Extra request headers (e.g. Chat Server's X-Chat-Actor); never overrides auth or content type. */
headers?: Record<string, string>;
+ /** Cancels this request, including body parsing, without terminating account auth. */
+ signal?: AbortSignal;
}
const DEFAULT_API_TIMEOUT_MS = 20_000;
@@ -51,6 +53,7 @@ export async function apiFetchRaw<T>(
opts: ApiFetchOptions,
): Promise<T> {
opts.assertCurrent?.();
+ if (opts.signal?.aborted) throw requestAborted();
const headers: Record<string, string> = { ...opts.headers, 'Content-Type': 'application/json' };
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
if (opts.cache === 'no-store') {
@@ -64,19 +67,25 @@ export async function apiFetchRaw<T>(
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const timeoutMs = opts.timeoutMs ?? DEFAULT_API_TIMEOUT_MS;
const controller = timeoutMs > 0 ? new AbortController() : null;
+ let cancelRequest: (() => void) | undefined;
try {
+ const cancellation = opts.signal ? new Promise<never>((_resolve, reject) => {
+ cancelRequest = () => { controller?.abort(); reject(requestAborted()); };
+ opts.signal!.addEventListener('abort', cancelRequest, { once: true });
+ }) : null;
const requestPromise = (async (): Promise<{ response: Response; data: unknown }> => {
const nextResponse = await fetch(opts.baseUrl + path, {
method: opts.method ?? 'GET',
headers,
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
- signal: controller?.signal,
+ signal: controller?.signal ?? opts.signal,
...(opts.cache ? { cache: opts.cache } : {}),
});
let nextData: unknown = null;
try {
nextData = await nextResponse.json();
} catch (error) {
+ if (opts.signal?.aborted) throw requestAborted();
if (nextResponse.status === 204 || nextResponse.status === 205) {
return { response: nextResponse, data: null };
}
@@ -90,21 +99,21 @@ export async function apiFetchRaw<T>(
}
return { response: nextResponse, data: nextData };
})();
- const result = timeoutMs > 0
- ? await Promise.race([
- requestPromise,
- new Promise<never>((_, reject) => {
- timeoutId = setTimeout(() => {
- void requestPromise.catch(() => undefined);
- reject(new ApiError('REQUEST_TIMEOUT', 0, i18n.t('apiErrors.requestTimeout')));
- controller?.abort();
- }, timeoutMs);
- }),
- ])
- : await requestPromise;
+ const pending = [requestPromise];
+ if (cancellation) pending.push(cancellation);
+ if (timeoutMs > 0) pending.push(new Promise<never>((_, reject) => {
+ timeoutId = setTimeout(() => {
+ void requestPromise.catch(() => undefined);
+ reject(new ApiError('REQUEST_TIMEOUT', 0, i18n.t('apiErrors.requestTimeout')));
+ controller?.abort();
+ }, timeoutMs);
+ }));
+ const result = await Promise.race(pending);
response = result.response;
data = result.data;
} catch (err) {
+ // Explicit cancellation is not a timeout, network failure, or auth boundary.
+ if (opts.signal?.aborted) throw requestAborted();
if (!(err instanceof ApiError) || err.code === 'REQUEST_TIMEOUT') {
mobileDebugLog('warn', 'network', 'request failed', err);
}
@@ -124,10 +133,12 @@ export async function apiFetchRaw<T>(
throw err;
} finally {
if (timeoutId) clearTimeout(timeoutId);
+ if (cancelRequest) opts.signal?.removeEventListener('abort', cancelRequest);
}
// A late old-account response must not terminate the newly active account.
opts.assertCurrent?.();
+ if (opts.signal?.aborted) throw requestAborted();
if (!response.ok) {
const error = readError(data);
const code = error.code ?? `HTTP_${response.status}`;
@@ -144,6 +155,10 @@ export async function apiFetchRaw<T>(
return data as T;
}
+function requestAborted(): Error {
+ return Object.assign(new Error('Request cancelled'), { name: 'AbortError' });
+}
+
function isAbortError(err: unknown): boolean {
return !!err && typeof err === 'object' && 'name' in err && err.name === 'AbortError';
}
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
index d5d0532e02..680b9467c0 100644
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -31,7 +31,7 @@ export interface ChatExecutionFailure {
}
export interface ChatPage { threadRootId?: string; snapshot: ChatSnapshot; messages: ChatMessage[]; before: string | null; failures?: ChatExecutionFailure[] }
/** `actorId` acts as one of the account's own actors (Chat Server `X-Chat-Actor`). */
-export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST' | 'PATCH', body?: unknown, actorId?: string) => Promise<T>;
+export type ChatRequest = <T>(path: string, method?: 'GET' | 'POST' | 'PATCH', body?: unknown, actorId?: string, signal?: AbortSignal) => Promise<T>;
/** An actor the account owns; a companion's `externalId` is its bot id on every computer. */
export interface ChatActor { id: string; kind: string; externalId: string; name: string; avatar: string | null; homeDeviceId: string | null }
export interface ChatCapabilities { companionHome: boolean }
@@ -397,8 +397,8 @@ export function createChatServerClient(request: ChatRequest, personalList = crea
return { ...page, messages: loaded, failures: await failures(roomId, loaded),
before: messages.length === 100 ? chatCursor(messages.at(-1)!.seq) : null };
},
- async media(roomId: string, mediaId: string): Promise<BotGroupAttachment> {
- const media = await request<{ name: string; type: string; size: string | number; url: string }>(`/conversations/${chatId(roomId)}/media/${chatId(mediaId)}`);
+ async media(roomId: string, mediaId: string, signal?: AbortSignal): Promise<BotGroupAttachment> {
+ const media = await request<{ name: string; type: string; size: string | number; url: string }>(`/conversations/${chatId(roomId)}/media/${chatId(mediaId)}`, 'GET', undefined, undefined, signal);
const size = Number(media.size);
if (!Number.isSafeInteger(size) || size < 0) throw new Error('INVALID_MEDIA_SIZE');
return { id: mediaId, name: media.name, mimeType: media.type, size, category: media.type.startsWith('image/') ? 'image' : 'file',
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
index 0fa385f7bb..41aea2b605 100644
--- a/apps/mobile/src/chat/useChatServer.ts
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -46,11 +46,11 @@ export function useChatClient() {
.finally(() => { discovering = undefined; });
return discovering;
};
- const request: ChatRequest = async <T,>(path: string, method: 'GET' | 'POST' | 'PATCH' = 'GET', body?: unknown, actorId?: string) => {
+ const request: ChatRequest = async <T,>(path: string, method: 'GET' | 'POST' | 'PATCH' = 'GET', body?: unknown, actorId?: string, signal?: AbortSignal) => {
check();
const url = await endpoint(); check();
const result = await deps.current.apiFetch<T>(`/v1${path}`, { baseUrl: url, method, cache: 'no-store', ...(body !== undefined ? { body } : {}),
- ...(actorId ? { headers: { 'X-Chat-Actor': actorId } } : {}), assertCurrent: check });
+ ...(actorId ? { headers: { 'X-Chat-Actor': actorId } } : {}), ...(signal ? { signal } : {}), assertCurrent: check });
check(); return result;
};
const client = createChatServerClient(request, listFor(owner));
@@ -315,10 +315,10 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
throw error;
}
};
- const media = async (mediaId: string): Promise<BotGroupAttachment> => {
+ const media = async (mediaId: string, signal?: AbortSignal): Promise<BotGroupAttachment> => {
const generation = accessGeneration.current;
try {
- const attachment = await api.client.media(groupId, mediaId);
+ const attachment = await api.client.media(groupId, mediaId, signal);
if (!valid() || generation !== accessGeneration.current) throw new Error('OWNER_CHANGED');
return attachment;
} catch (error) {
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index 57c47ac85e..dff980bf66 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -149,11 +149,13 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
const jumpAttempts = useRef(0);
const messagePositions = useRef(new Map<string, number>());
const group = chat.state.kind === 'ready' ? chat.state.group : null;
+ const focused = useIsFocused();
+ const [foreground, setForeground] = useState(() => AppState.currentState === 'active');
const previewVisibility = useScrollViewMessageVisibility(
`${accountGeneration}:${deviceId}:${groupId}:${threadRootId ?? ''}`,
useMemo(() => group?.messages.map(message => message.id) ?? [], [group?.messages]),
+ focused && foreground,
);
- const focused = useIsFocused();
const viewportOwner = `${user?.id ?? ''}:${accountGeneration}:${deviceId}:${groupId}:${threadRootId ?? 'main'}`;
const [seen, setSeen] = useState<{ owner: string; sequence: string } | null>(null);
const latestSequence = group?.messages.reduce((latest, message) => {
@@ -200,7 +202,10 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
}, [focused, group, user?.id, deviceId, groupId, viewportOwner, latestSequence, chat.server, chat.markRead]);
useEffect(() => {
const frame = requestAnimationFrame(acknowledge);
- const subscription = AppState.addEventListener('change', state => { if (state === 'active') acknowledge(); });
+ const subscription = AppState.addEventListener('change', state => {
+ setForeground(state === 'active');
+ if (state === 'active') acknowledge();
+ });
return () => { cancelAnimationFrame(frame); subscription.remove(); };
}, [acknowledge]);
// The list row seeds the header while the first read is in flight (display only).
@@ -519,7 +524,7 @@ export function BotGroupTimeline({
identityFor: BotGroupIdentityLookup;
/** Reads a picture attached to a message from the computer. */
resolveMedia: ResolveRemoteMediaFn;
- resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
+ resolveServerMedia?: (id: string, signal?: AbortSignal) => Promise<BotGroupAttachment>;
loadOlder?: () => void;
loadingOlder?: boolean;
continuing: boolean;
@@ -618,7 +623,7 @@ function BotGroupTimelineItem({
identityFor: BotGroupIdentityLookup;
mentionLabels: readonly string[];
resolveMedia: ResolveRemoteMediaFn;
- resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
+ resolveServerMedia?: (id: string, signal?: AbortSignal) => Promise<BotGroupAttachment>;
canContinue: boolean;
continuing: boolean;
onContinue(): void;
diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
index 51916b849c..c8a276d7b1 100644
--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx
+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
@@ -49,7 +49,7 @@ export function BotGroupMessageAttachments({ messageId, attachments, align, onRe
attachments: readonly BotGroupAttachment[];
align: 'left' | 'right';
onResolveRemoteMedia: ResolveRemoteMediaFn;
- resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
+ resolveServerMedia?: (id: string, signal?: AbortSignal) => Promise<BotGroupAttachment>;
/** Cloud transcripts keep the tap-only contract in cloud-companions.md §3.1. */
previewServerImages?: boolean;
}) {
@@ -126,17 +126,40 @@ function PendingAttachment({ attachment, align, layout }: {
}
// Bound passive authorization across mounted messages; no account data or URLs are cached here.
-const previewJobs: Array<() => Promise<void>> = [];
+type PreviewJob = {
+ run(signal: AbortSignal): Promise<void>;
+ controller: AbortController;
+ active: boolean;
+ finished: boolean;
+};
+const previewJobs: PreviewJob[] = [];
let activePreviews = 0;
-function authorizePreview(job: () => Promise<void>) {
+function finishPreview(job: PreviewJob) {
+ if (job.finished) return;
+ job.finished = true;
+ if (job.active) activePreviews--;
+ else {
+ const index = previewJobs.indexOf(job);
+ if (index >= 0) previewJobs.splice(index, 1);
+ }
+ drainPreviews();
+}
+function authorizePreview(run: PreviewJob['run']): () => void {
+ const job: PreviewJob = { run, controller: new AbortController(), active: false, finished: false };
previewJobs.push(job);
drainPreviews();
+ return () => {
+ if (job.finished) return;
+ job.controller.abort();
+ finishPreview(job);
+ };
}
function drainPreviews() {
while (activePreviews < 3 && previewJobs.length) {
const job = previewJobs.shift()!;
+ job.active = true;
activePreviews++;
- void job().finally(() => { activePreviews--; drainPreviews(); });
+ void job.run(job.controller.signal).then(() => finishPreview(job), () => finishPreview(job));
}
}
@@ -146,14 +169,14 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {
align: 'left' | 'right';
runs: ReturnType<typeof botGroupAttachmentRuns>;
layout: ReturnType<typeof buildMessageContentLayout>;
- resolve(id: string): Promise<BotGroupAttachment>;
+ resolve(id: string, signal?: AbortSignal): Promise<BotGroupAttachment>;
}) {
const { t } = useTranslation();
const { colors } = useTheme();
const [previews, setPreviews] = useState<Record<string, BotGroupAttachment>>({});
const failedPreviewIds = useRef(new Set<string>());
const retriedPreviewIds = useRef(new Set<string>());
- const [retryRequest, setRetryRequest] = useState(0);
+ const retryPreview = useRef<((id: string) => void) | null>(null);
const [previewVersions, setPreviewVersions] = useState<Record<string, number>>({});
const resolveRef = useRef(resolve); resolveRef.current = resolve;
const previewsRef = useRef(previews); previewsRef.current = previews;
@@ -161,15 +184,16 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {
useEffect(() => {
let cancelled = false;
if (!visible) return;
- for (const id of JSON.parse(previewIds) as string[]) {
- authorizePreview(async () => {
+ const cancelJobs: Array<() => void> = [];
+ const schedule = (id: string) => {
+ cancelJobs.push(authorizePreview(async signal => {
if (cancelled || (previewsRef.current[id] && !failedPreviewIds.current.has(id))) return;
const refreshing = failedPreviewIds.current.has(id);
const previousPreview = previewsRef.current[id];
try {
- const value = await resolveRef.current(id);
+ const value = await resolveRef.current(id, signal);
const preview = value.category === 'image' ? value : { ...value, url: null };
- if (!cancelled && previewsRef.current[id] === previousPreview) {
+ if (!cancelled && !signal.aborted && previewsRef.current[id] === previousPreview) {
previewsRef.current = { ...previewsRef.current, [id]: preview };
setPreviews(previewsRef.current);
failedPreviewIds.current.delete(id);
@@ -181,10 +205,16 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {
if (!cancelled) failedPreviewIds.current.delete(id);
// Keep the chip / fallback available for an explicit retry on tap.
}
- });
- }
- return () => { cancelled = true; };
- }, [previewIds, visible, retryRequest]);
+ }));
+ };
+ retryPreview.current = schedule;
+ for (const id of JSON.parse(previewIds) as string[]) schedule(id);
+ return () => {
+ cancelled = true;
+ retryPreview.current = null;
+ cancelJobs.forEach(cancel => cancel());
+ };
+ }, [previewIds, visible]);
const displayRuns = botGroupAttachmentRuns(runs.flatMap(run => run.kind === 'pending'
? [run.attachment] : run.attachments.map(item => previews[item.id] ?? { ...item, url: null })));
const [image, setImage] = useState<BotGroupAttachment | null>(null);
@@ -233,7 +263,7 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {
|| previewsRef.current[attachment.id]?.url !== attachment.url) return;
retriedPreviewIds.current.add(attachment.id);
failedPreviewIds.current.add(attachment.id);
- setRetryRequest(request => request + 1);
+ retryPreview.current?.(attachment.id);
}}
onOpenFile={index => { void open(run.attachments[index]!.id); }} usePreviewState={useState} />
{run.attachments.some(attachment => busy === attachment.id)
diff --git a/apps/mobile/src/session/messageListVisibility.ts b/apps/mobile/src/session/messageListVisibility.ts
index 54e14034b7..e46d02bd2b 100644
--- a/apps/mobile/src/session/messageListVisibility.ts
+++ b/apps/mobile/src/session/messageListVisibility.ts
@@ -1,4 +1,4 @@
-import { createContext, useCallback, useContext, useEffect, useMemo, useSyncExternalStore } from 'react';
+import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from 'react';
/** One store per LegendList lifetime; only rows whose visibility changes are notified. */
export class MessageListVisibility {
@@ -52,6 +52,12 @@ export class ScrollViewMessageVisibility extends MessageListVisibility {
private layouts = new Map<string, { y: number; height: number }>();
private offsetY = 0;
private height = 0;
+ private active = true;
+
+ setActive(active: boolean): void {
+ this.active = active;
+ this.refresh();
+ }
setViewport(offsetY: number, height: number): void {
this.offsetY = offsetY;
@@ -78,14 +84,18 @@ export class ScrollViewMessageVisibility extends MessageListVisibility {
private refresh(): void {
this.update([...this.layouts].map(([key, layout]) => ({
key,
- isViewable: this.height > 0 && layout.height > 0
+ isViewable: this.active && this.height > 0 && layout.height > 0
&& layout.y < this.offsetY + this.height && layout.y + layout.height > this.offsetY,
})));
}
}
-export function useScrollViewMessageVisibility(scope: string, keys: readonly string[]): ScrollViewMessageVisibility {
+export function useScrollViewMessageVisibility(scope: string, keys: readonly string[], active = true): ScrollViewMessageVisibility {
const store = useMemo(() => new ScrollViewMessageVisibility(), [scope]);
+ useLayoutEffect(() => {
+ store.setActive(active);
+ return () => store.setActive(false);
+ }, [store, active]);
useEffect(() => store.retain(keys), [store, keys]);
return store;
}