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。

feat(mobile): support attachments in direct server groups

liuliuyaod3032376cdd4
diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.ts
index 92b845d78b..969719cd87 100644
--- a/apps/mobile/src/__tests__/chatServerClient.test.ts
+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts
@@ -441,6 +441,17 @@ describe('direct Chat Server client', () => {
expect(request.mock.calls.at(-1)).toEqual(posted);
expect(request.mock.calls.filter(([, method]) => method !== 'POST')).toHaveLength(2);
});
+ it.each(['', 'with files'])('sends sealed attachment IDs with text=%s and preserves the retry body', async text => {
+ const request = vi.fn().mockResolvedValue({ id: id(9) });
+ const client = createChatServerClient(request);
+ const input = { text, clientId: 'same-media-message', mentions: { all: false, botIds: [] },
+ attachments: [{ id: id(2), name: 'report.pdf', category: 'file' as const, path: '', ext: 'pdf', mimeType: 'application/pdf', size: 42 }] };
+ await client.send(id(1), input); await client.send(id(1), input);
+ expect(request.mock.calls[0][2]).toEqual({ operationId: 'same-media-message', mentions: [],
+ content: [...(text ? [{ type: 'text', text }] : []), { type: 'media', mediaId: id(2), caption: 'report.pdf' }] });
+ expect(request.mock.calls[0]).toEqual(request.mock.calls[1]);
+ expect(chatGroupView({ snapshot: snapshot(), messages: [], before: null }, id(10)).supportsAttachments).toBe(true);
+ });
it('reauthorizes and replaces loaded older history on refresh instead of retaining deleted text', async () => {
const recent = Array.from({ length: 100 }, (_, n) => message(200 - n));
const request = vi.fn().mockResolvedValueOnce(snapshot()).mockResolvedValueOnce(recent)
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
index 8f7e8ab1cc..5526cfea2e 100644
--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -11,6 +11,7 @@ const h = vi.hoisted(() => ({
disk: new Map<string, string>(),
history: new Map<string, string>(),
foreground: new Set<(state: string) => void>(),
+ put: vi.fn(async (..._args: unknown[]) => {}),
}));
vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({
read: async (key: string) => h.history.get(key) ?? null,
@@ -25,6 +26,7 @@ vi.mock('@/session/mobileDurableOutbox', async () => {
return { mobileDurableOutbox: createDurableOutbox(storage) };
});
vi.mock('expo-crypto', () => ({ randomUUID: () => 'fixture-operation-id' }));
+vi.mock('@/session/mobileAttachmentUpload', () => ({ putMobileAttachmentUploadFromFile: (...args: unknown[]) => h.put(...args) }));
vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: (_: string, fn: (state: string) => void) => { h.foreground.add(fn); return { remove: () => h.foreground.delete(fn) }; } } }));
vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (fn: any) => useEffect(fn, [fn]) }; });
vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));
@@ -73,6 +75,7 @@ beforeEach(async () => {
await mobileDurableOutbox.activate(''); h.disk.clear(); h.history.clear(); setMobileAuthOwner('owner');
await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
vi.clearAllMocks(); h.foreground.clear(); showChat = false; h.auth.accountGeneration = 1; h.legacy.items = []; h.targets = []; h.legacy.isOnline.mockReturnValue(false);
+ h.put.mockImplementation(async () => {});
vi.stubGlobal('WebSocket', class { close() {} });
h.auth.apiFetch.mockImplementation(async (path: string, options: any) => {
options.assertCurrent();
@@ -173,6 +176,54 @@ it('keeps the account owner label when quoting from a direct phone entry', async
mentions: [botId], content: [expect.objectContaining({ data: expect.objectContaining({ authorName: 'Companion X (Account B)' }) }), { type: 'text', text: 'Agreed' }],
}) }));
});
+it.each(['', 'look at this'])('uploads and sends direct media with all computers offline, text=%s', async text => {
+ const mediaId = '00000000-0000-4000-8000-000000000003';
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/media')) return { id: mediaId, uploadUrl: 'https://upload.example.invalid/signed' };
+ if (path.endsWith('/complete')) return {};
+ return original(path, options);
+ });
+ showChat = true; await render();
+ expect(chat.state).toMatchObject({ kind: 'ready', group: { supportsAttachments: true } });
+ const attachment = await chat.uploadAttachment!({ name: 'photo.jpg', mimeType: 'image/jpeg', size: 42 }, 'file:///photo', { token: 'fixture' });
+ const input = { clientId: 'same-media-send', text, mentions: { all: false, botIds: [] }, attachments: [attachment] };
+ await act(async () => { await send(input); });
+ const posts = h.auth.apiFetch.mock.calls.filter(([path]) => path.endsWith('/messages'));
+ expect(posts).toHaveLength(1);
+ expect(posts[0][1].body).toEqual({ operationId: 'same-media-send', mentions: [],
+ content: [...(text ? [{ type: 'text', text }] : []), { type: 'media', mediaId, caption: 'photo.jpg' }] });
+ expect(h.put).toHaveBeenCalledWith('https://upload.example.invalid/signed', 'file:///photo', 'image/jpeg', {},
+ { signal: undefined, signedHeaders: { 'Content-Type': 'image/jpeg' } });
+ expect(h.link.invoke).not.toHaveBeenCalled(); expect(h.link.openLink).not.toHaveBeenCalled();
+});
+
+it('clears a group when the upload prepare rejects its membership', async () => {
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => {
+ if (path.endsWith('/media')) throw Object.assign(new Error('NOT_MEMBER'), { status: 403 });
+ return original(path, options);
+ });
+ showChat = true; await render();
+ await act(async () => {
+ await expect(chat.uploadAttachment!({ name: 'a.pdf', size: 42 }, 'file:///picked', { token: 'fixture' })).rejects.toMatchObject({ status: 403 });
+ });
+ expect(chat.state.kind).toBe('missing');
+ expect(h.put).not.toHaveBeenCalled();
+});
+
+it('refuses a late PUT result after account changes before media completion', async () => {
+ const original = h.auth.apiFetch.getMockImplementation()!;
+ h.auth.apiFetch.mockImplementation(async (path, options) => path.endsWith('/media')
+ ? { id: self, uploadUrl: 'https://upload.example.invalid/signed' } : original(path, options));
+ h.put.mockImplementation(async () => { h.auth.accountGeneration++; await render(); });
+ showChat = true; await render();
+ const upload = chat.uploadAttachment!;
+ await expect(upload({ name: 'a.pdf', size: 42 }, 'file:///picked', { token: 'fixture' })).rejects.toThrow('OWNER_CHANGED');
+ expect(h.auth.apiFetch.mock.calls.some(([path]) => path.endsWith('/complete'))).toBe(false);
+ expect(h.auth.apiFetch.mock.calls.some(([path]) => path.endsWith('/messages'))).toBe(false);
+});
+
it('never includes the current human actor in explicit or everyone server mentions', async () => {
const other = '00000000-0000-4000-8000-000000000003';
const original = h.auth.apiFetch.getMockImplementation()!;
@@ -678,12 +729,13 @@ it.each(['missing', 'empty', 'read-error'] as const)('keeps initial loading corr
// Integration: the actual ledger and HTTP adapter survive a process restart after
// a committed POST loses its response. Existing direct-send tests cannot cover it.
-it('persists the exact uncertain send across restart and never rebuilds its recipients', async () => {
+it.each([false, true])('persists the exact uncertain send across restart and never rebuilds its recipients (media=%s)', async withMedia => {
const storage = { getAllKeys: async () => [...h.disk.keys()], getItem: async (key: string) => h.disk.get(key) ?? null,
setItem: async (key: string, value: string) => { h.disk.set(key, value); }, removeItem: async (key: string) => { h.disk.delete(key); } };
const account = getMobileAuthOwner().accountKey;
let store = createDurableOutbox(storage); await store.activate(account);
- await enqueueChatMessage(store, account, id, { clientId: 'lost-response', text: 'saved offline', mentions: { all: true, botIds: [] } }, 1);
+ const attachments = withMedia ? [{ id, name: 'report.pdf', path: '', ext: 'pdf', size: 42, mimeType: 'application/pdf', category: 'file' as const }] : [];
+ await enqueueChatMessage(store, account, id, { clientId: 'lost-response', text: 'saved offline', mentions: { all: true, botIds: [] }, attachments }, 1);
expect(store.getSnapshot()[0]).toMatchObject({ state: 'queued', item: { text: 'saved offline' } });
const posted: unknown[] = [];
let memberReads = 0;
@@ -696,7 +748,9 @@ it('persists the exact uncertain send across restart and never rebuilds its reci
const delivery = () => createChatOutboxDelivery({ store, client, current: () => true, canRun: () => true, accessLost: async () => {} });
await delivery().run();
expect(store.getSnapshot()[0]).toMatchObject({ state: 'queued', enqueueStarted: true, chat: { body: { operationId: 'lost-response', mentions: [id] } } });
+ expect(posted[0]).toMatchObject({ content: [{ type: 'text', text: 'saved offline' }, ...(withMedia ? [{ type: 'media', mediaId: id, caption: 'report.pdf' }] : [])] });
store = createDurableOutbox(storage); await store.activate(account);
+ expect(store.getSnapshot()[0].chat?.input.attachments).toEqual(attachments);
await delivery().run();
expect(posted).toHaveLength(2); expect(posted[1]).toEqual(posted[0]); expect(memberReads).toBe(1);
expect(store.getSnapshot()[0]).toMatchObject({ state: 'confirming', chat: { messageId: self } });
diff --git a/apps/mobile/src/__tests__/chatServerUpload.test.ts b/apps/mobile/src/__tests__/chatServerUpload.test.ts
new file mode 100644
index 0000000000..f25663d802
--- /dev/null
+++ b/apps/mobile/src/__tests__/chatServerUpload.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createChatServerUpload } from '@/chat/chatServerUpload';
+
+const room = '00000000-0000-4000-8000-000000000001';
+const media = '00000000-0000-4000-8000-000000000002';
+const file = { name: 'report.pdf', size: 42, mimeType: 'application/pdf' };
+function fixture() {
+ let current = true;
+ const request = vi.fn().mockResolvedValue({ id: media, uploadUrl: 'https://upload.example.invalid/signed' });
+ const put = vi.fn(async () => {});
+ const upload = createChatServerUpload({ request, put, current: () => current, operationId: () => 'upload-operation' });
+ return { request, put, upload, invalidate: () => { current = false; } };
+}
+
+describe('mobile direct private media upload', () => {
+ it.each(['application/pdf', 'image/jpeg'])('prepares, uploads and seals %s without exposing the signed URL in the draft', async mimeType => {
+ const f = fixture();
+ const result = await f.upload(room, { ...file, mimeType }, 'file:///picked');
+ expect(f.request.mock.calls).toEqual([
+ [`/conversations/${room}/media`, 'POST', { operationId: 'media:upload-operation', name: file.name, type: mimeType, size: 42 }],
+ [`/conversations/${room}/media/${media}/complete`, 'POST', { operationId: `seal:${media}` }],
+ ]);
+ expect(f.put).toHaveBeenCalledWith('https://upload.example.invalid/signed', 'file:///picked', mimeType, undefined);
+ expect(result).toMatchObject({ id: media, name: file.name, path: '', category: mimeType.startsWith('image/') ? 'image' : 'file' });
+ expect(JSON.stringify(result)).not.toContain('https:');
+ });
+ it('does not seal or send after a failed PUT', async () => {
+ const f = fixture(); f.put.mockRejectedValue(new Error('NETWORK'));
+ await expect(f.upload(room, file, 'file:///picked')).rejects.toThrow('NETWORK');
+ expect(f.request).toHaveBeenCalledTimes(1);
+ });
+ it.each(['prepare', 'put', 'complete'])('rejects a late result after owner changes during %s', async stage => {
+ const f = fixture();
+ if (stage === 'put') f.put.mockImplementation(async () => { f.invalidate(); });
+ else f.request.mockImplementation(async path => {
+ if ((stage === 'prepare' && path.endsWith('/media')) || path.endsWith('/complete')) f.invalidate();
+ return { id: media, uploadUrl: 'https://upload.example.invalid/signed' };
+ });
+ await expect(f.upload(room, file, 'file:///picked')).rejects.toThrow('OWNER_CHANGED');
+ expect(f.request).toHaveBeenCalledTimes(stage === 'complete' ? 2 : 1);
+ if (stage === 'prepare') expect(f.put).not.toHaveBeenCalled();
+ });
+ it('does not seal an upload cancelled while PUT is completing', async () => {
+ const f = fixture(); const controller = new AbortController();
+ f.put.mockImplementation(async () => { controller.abort(); });
+ await expect(f.upload(room, file, 'file:///picked', controller.signal)).rejects.toThrow('UPLOAD_CANCELLED');
+ expect(f.request).toHaveBeenCalledTimes(1);
+ });
+ it.each(['file:///private/file', 'http://upload.example.invalid/file', 'https://user:[email protected]/file'])('rejects an unsafe signed target %s', async uploadUrl => {
+ const f = fixture(); f.request.mockResolvedValue({ id: media, uploadUrl });
+ await expect(f.upload(room, file, 'file:///picked')).rejects.toThrow('INVALID_CHAT_URL');
+ expect(f.put).not.toHaveBeenCalled();
+ });
+ it.each([0, -1, Number.NaN, 100 * 1024 * 1024 + 1])('rejects invalid or oversized bytes before prepare: %s', async size => {
+ const f = fixture();
+ await expect(f.upload(room, { ...file, size }, 'file:///picked')).rejects.toThrow(size > 0 ? 'ATTACHMENT_TOO_LARGE' : 'ATTACHMENT_UNAVAILABLE');
+ expect(f.request).not.toHaveBeenCalled();
+ });
+ it('propagates revoked membership without uploading bytes', async () => {
+ const f = fixture(); f.request.mockRejectedValue(Object.assign(new Error('NOT_MEMBER'), { status: 403 }));
+ await expect(f.upload(room, file, 'file:///picked')).rejects.toMatchObject({ status: 403 });
+ expect(f.put).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
index 0d7d4715ca..d18678e189 100644
--- a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
@@ -281,6 +281,19 @@ describe('mobileAttachmentUpload', () => {
}, { signal: expect.any(AbortSignal), onProgress: expect.any(Function) });
});
+ // Unit regression: real direct-chat PUT returned SignatureDoesNotMatch because the
+ // device-link uploader added an ACL header absent from the Chat Server signature.
+ // Existing native upload coverage checks only the device-link header contract.
+ it('uploads a Chat Server file without adding unsigned OSS headers', async () => {
+ const uploadFile = vi.fn(async (_url: string, _uri: string, headers: Record<string, string>) =>
+ Object.keys(headers).length === 1 && headers['Content-Type'] === 'image/png'
+ ? { status: 200 }
+ : { status: 403, body: '<Error><Code>SignatureDoesNotMatch</Code></Error>' });
+ await expect(putMobileAttachmentUploadFromFile('https://chat-upload.example/signed', 'file:///photo.png', 'image/png',
+ { uploadFile }, { signedHeaders: { 'Content-Type': 'image/png' } })).resolves.toBeUndefined();
+ expect(uploadFile).toHaveBeenCalledOnce();
+ });
+
it('returns an OSS-ref attachment after successful native file upload', async () => {
const apiFetch = vi.fn(async () => ({
putUrl: 'https://oss.example/upload',
diff --git a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
index 17405620f0..d99c8e7785 100644
--- a/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
+++ b/apps/mobile/src/__tests__/useMobileLocalAttachmentsAbandon.test.tsx
@@ -75,8 +75,9 @@ beforeEach(() => {
});
afterEach(() => act(() => root.unmount()));
-function mount(scopeKey: string) {
+function mount(scopeKey: string, upload?: UseMobileLocalAttachmentsOptions['upload']) {
const options: UseMobileLocalAttachmentsOptions = {
+ upload,
attachmentScopeKey: scopeKey,
getAccessToken: async () => 'token',
getAttachmentCount: () => 0,
@@ -249,6 +250,19 @@ describe('useMobileLocalAttachments abandonment on scope change', () => {
expect(runtime.uploads).toHaveLength(0);
});
+ it('uses a supplied direct transport while retaining the same picker queue and delivery', async () => {
+ const attachment = { id: 'server-media', name: 'report.pdf', path: '', ext: 'pdf', size: 1000,
+ category: 'file' as const, mimeType: 'application/pdf' };
+ const upload = vi.fn(async () => attachment);
+ const harness = mount('direct-group', upload);
+ act(() => harness.first.enqueueUploads([{ kind: 'file', uri: 'file:///picked', name: 'report.pdf', size: 1000,
+ mimeType: 'application/pdf' }], { token: 'token' }));
+ await act(async () => { await flush(); });
+ expect(upload).toHaveBeenCalledWith(expect.objectContaining({ name: 'report.pdf', size: 1000 }),
+ 'file:///picked', expect.objectContaining({ token: 'token', signal: expect.any(AbortSignal) }));
+ expect(runtime.uploads).toHaveLength(0);
+ expect(harness.options.onUploaded).toHaveBeenCalledWith(attachment, expect.any(Object), expect.any(String));
+ });
it('abandons a candidate enqueued from a stale scope without starting an upload', async () => {
const harness = mount('session-a');
act(() => harness.first.discardAllPendingUploadsForScopeChange());
diff --git a/apps/mobile/src/chat/chatOutbox.ts b/apps/mobile/src/chat/chatOutbox.ts
index 64e76e0a12..8a76948706 100644
--- a/apps/mobile/src/chat/chatOutbox.ts
+++ b/apps/mobile/src/chat/chatOutbox.ts
@@ -10,7 +10,7 @@ export async function enqueueChatMessage(store: DurableOutboxStore, accountId: s
await store.add({ version: 1, accountId, deviceId: '', createdAt: Date.now(), state: 'queued', uploads: [],
enqueueStarted: false, chat: { roomId, input, after, afterServerSequence, ...(quote ? { quote } : {}) },
item: buildOutboxItem({ clientId: input.clientId, sessionId: roomId, text: input.text,
- permissionModeAtSend: 'default', readyAttachments: [], claimedUploads: [] }) });
+ permissionModeAtSend: 'default', readyAttachments: [...(input.attachments ?? [])], claimedUploads: [] }) });
}
export function pendingChatMessage(record: DurableOutboxRecord): BotGroupMessageView {
@@ -18,7 +18,9 @@ export function pendingChatMessage(record: DurableOutboxRecord): BotGroupMessage
authorKind: 'user', authorBotId: null, authorName: '', isSelf: true,
content: record.chat!.input.text, mentions: record.chat!.input.mentions,
quote: record.chat!.quote, threadRootId: record.chat!.input.threadRootId,
- noticeCode: null, planId: null, files: [], attachments: [], createdAt: record.createdAt };
+ noticeCode: null, planId: null, files: [], attachments: (record.chat!.input.attachments ?? []).map(attachment => ({
+ id: attachment.id, name: attachment.name, size: attachment.size ?? 0, mimeType: attachment.mimeType ?? 'application/octet-stream', category: attachment.category, url: null, path: null,
+ })), createdAt: record.createdAt };
}
/** Remove a receipt only after its canonical message is durable on this phone. */
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
index d636156be2..3ca9ada175 100644
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -8,6 +8,7 @@ import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';
import i18next from 'i18next';
import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from '@/i18n/locale';
import { mobileMarkdownPreviewText } from '@/session/messageMarkdown';
+import type { RemoteSerializedAttachment } from '@/session/types';
export interface ChatRoom {
id: string; name: string; state?: string; kind: string; archived: boolean; dissolved_at?: string | null;
@@ -56,6 +57,7 @@ export interface ChatSendInput {
conversationKind?: 'direct';
clientId: string; text: string; mentions: { all: boolean; botIds: string[] };
quote?: { messageId: string }; threadRootId?: string;
+ attachments?: readonly RemoteSerializedAttachment[];
}
export interface ChatSendBody {
operationId: string; content: ChatMessage['content']; mentions: string[]; threadRootId?: string;
@@ -256,7 +258,7 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly C
createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),
lastMessage: last ? { authorKind: last.authorKind, authorName: last.authorName, preview: mobileMarkdownPreviewText(botGroupMessageSummaryText(last)).slice(0, 80), createdAt: last.createdAt } : null,
speakingBotIds: speakers.map(speaker => speaker.botId), planningBotId: null, openPlan: null, plans: [], messages: projectBotGroupExecutionFailures(messages, failures),
- hasMoreBefore: page.before !== null, round: { status: speakers.length ? 'running' : 'idle', speakers, canContinue: false }, supportsAttachments: false };
+ hasMoreBefore: page.before !== null, round: { status: speakers.length ? 'running' : 'idle', speakers, canContinue: false }, supportsAttachments: true };
}
export function createChatServerClient(request: ChatRequest, personalList = createConversationListState(),
@@ -569,9 +571,12 @@ export function createChatServerClient(request: ChatRequest, personalList = crea
save(body: ChatSendBody): Promise<void>;
}) {
if (durable?.body) return request<ChatMessage>(`/conversations/${chatId(roomId)}/messages`, 'POST', durable.body);
- const key = JSON.stringify([roomId, input.clientId, input.text, input.mentions, input.quote?.messageId, input.threadRootId]);
+ const key = JSON.stringify([roomId, input.clientId, input.text, input.mentions, input.quote?.messageId, input.threadRootId, input.attachments]);
const known = input.quote ? postedQuotes.get(key) : undefined;
- const content: ChatMessage['content'] = known?.content ?? [{ type: 'text', text: input.text }];
+ const content: ChatMessage['content'] = known?.content ?? [
+ ...(input.text ? [{ type: 'text', text: input.text }] : []),
+ ...(input.attachments ?? []).map(attachment => ({ type: 'media', mediaId: chatId(attachment.id), caption: attachment.name })),
+ ];
const mentions = new Set(known?.mentions ?? input.mentions.botIds.map(chatId));
if (input.quote && !known) {
const [original, members] = await Promise.all([
diff --git a/apps/mobile/src/chat/chatServerUpload.ts b/apps/mobile/src/chat/chatServerUpload.ts
new file mode 100644
index 0000000000..419f786248
--- /dev/null
+++ b/apps/mobile/src/chat/chatServerUpload.ts
@@ -0,0 +1,36 @@
+import type { RemoteSerializedAttachment } from '@/session/types';
+import type { ChatRequest } from './chatServerClient';
+import { chatHttpsUrl, chatId } from './chatServerClient';
+
+/** Existing Chat Server media contract. Signed URLs stay in memory and receive no account token. */
+export function createChatServerUpload(deps: {
+ request: ChatRequest;
+ current(): boolean;
+ operationId(): string;
+ put(url: string, uri: string, mimeType: string, signal?: AbortSignal): Promise<void>;
+}) {
+ return async (roomId: string, candidate: { name: string; size: number; mimeType?: string }, uri: string,
+ signal?: AbortSignal): Promise<RemoteSerializedAttachment> => {
+ const check = () => {
+ if (!deps.current()) throw new Error('OWNER_CHANGED');
+ if (signal?.aborted) throw new Error('UPLOAD_CANCELLED');
+ };
+ check();
+ if (!Number.isSafeInteger(candidate.size) || candidate.size <= 0) throw new Error('ATTACHMENT_UNAVAILABLE');
+ if (candidate.size > 100 * 1024 * 1024) throw new Error('ATTACHMENT_TOO_LARGE');
+ const room = chatId(roomId);
+ const type = candidate.mimeType?.trim() || 'application/octet-stream';
+ const upload = await deps.request<{ id: string; uploadUrl: string }>(`/conversations/${room}/media`, 'POST', {
+ operationId: `media:${deps.operationId()}`, name: candidate.name, type, size: candidate.size,
+ });
+ check();
+ const id = chatId(upload.id);
+ await deps.put(chatHttpsUrl(upload.uploadUrl), uri, type, signal);
+ check();
+ await deps.request(`/conversations/${room}/media/${id}/complete`, 'POST', { operationId: `seal:${id}` });
+ check();
+ // No computer/relay reference: abandoned media follows the server's media lifecycle.
+ return { id, name: candidate.name, category: type.startsWith('image/') ? 'image' : 'file',
+ mimeType: type, size: candidate.size, path: '', ext: candidate.name.includes('.') ? candidate.name.split('.').pop()! : '' };
+ };
+}
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
index 304d45f75c..74dbea2606 100644
--- a/apps/mobile/src/chat/useChatServer.ts
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -18,6 +18,10 @@ import { subscribeChatServer } from './chatServerSubscription';
import { createChatHistory } from '@cindy/maker-shared/chat-history';
import { createMobileChatHistoryStore } from './chatHistoryStore';
import { cacheChatMessages, forgetChatMessages, peekChatMessages, readChatMessages, subscribeChatInvalidation } from './chatMessageCache';
+import { createChatServerUpload } from './chatServerUpload';
+import type { MobileLocalAttachmentUploadDeps } from '@/session/mobileLocalAttachmentUpload';
+import type { RemoteSerializedAttachment } from '@/session/types';
+import { useTranslation } from 'react-i18next';
// Shared only within the current authenticated account generation and realm.
let listOwner = '';
@@ -73,7 +77,15 @@ export function useChatClient() {
return createChatHistory({ api: request, current, newGeneration: randomUUID,
store: createMobileChatHistoryStore(auth.user!.id, realm, url, human, current) });
});
- return { owner, realm, userId: auth.user?.id ?? '', current, baseUrl, endpoint, request, client,
+ const upload = createChatServerUpload({ request, current,
+ operationId: () => `${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ put: async (url, uri, type, signal) => {
+ const { putMobileAttachmentUploadFromFile } = await import('@/session/mobileAttachmentUpload');
+ check();
+ await putMobileAttachmentUploadFromFile(url, uri, type, {}, { signal, signedHeaders: { 'Content-Type': type } });
+ },
+ });
+ return { owner, realm, userId: auth.user?.id ?? '', current, baseUrl, endpoint, request, client, upload,
token: async () => { check(); await client.me(); const token = await deps.current.getAccessToken(); check(); return token; }, enabled: !!auth.user };
}, [owner, !!auth.user]);
}
@@ -215,6 +227,7 @@ export function useChatServerRoster(enabled: boolean) {
/** Reads and sends use the account's Chat Server identity, never its computer identity. */
export function useChatServerGroup(groupId: string, enabled: boolean, threadRootId?: string) {
const api = useChatClient();
+ const { t } = useTranslation();
const identity = `${api.owner}:${groupId}:${threadRootId ?? 'main'}`;
const active = useRef(identity); active.current = identity;
const ledger = useSyncExternalStore(mobileDurableOutbox.subscribe, mobileDurableOutbox.getSnapshot);
@@ -369,7 +382,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
}
return { effects: [] };
}
- if (action !== 'send' || !input || input.division || (Array.isArray(input.attachments) && input.attachments.length)) throw new Error('UNSUPPORTED_CHAT_ACTION');
+ if (action !== 'send' || !input || input.division) throw new Error('UNSUPPORTED_CHAT_ACTION');
const latest = page.current;
if (!latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');
const owner = getMobileAuthOwner();
@@ -381,6 +394,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
await enqueueChatMessage(mobileDurableOutbox, owner.accountKey, groupId, {
...(latest.page.snapshot.room.kind === 'direct' ? { conversationKind: 'direct' as const } : {}),
clientId: String(input.clientId), text: String(input.text), threadRootId,
+ attachments: input.attachments as RemoteSerializedAttachment[] | undefined,
...(input.quote && typeof input.quote === 'object' && 'messageId' in input.quote
? { quote: { messageId: String(input.quote.messageId) } } : {}),
mentions: { all: mentions.all, botIds: [...new Set(recipients)] },
@@ -389,6 +403,23 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
if (!isMobileAuthOwnerCurrent(owner)) throw new Error('OWNER_CHANGED');
return { effects: [] };
};
+ const uploadAttachment: MobileLocalAttachmentUploadDeps['upload'] = async (candidate, uri, options) => {
+ const generation = accessGeneration.current;
+ if (!enabled || !valid() || page.current?.identity !== identity) throw new Error('OWNER_CHANGED');
+ try {
+ const attachment = await api.upload(groupId, candidate, uri, options.signal);
+ if (!valid() || generation !== accessGeneration.current) throw new Error('OWNER_CHANGED');
+ return attachment;
+ } catch (error) {
+ if (valid() && generation === accessGeneration.current && chatAccessLost(error)) loseAccess();
+ if (error instanceof Error && error.message === 'ATTACHMENT_TOO_LARGE') {
+ throw new Error(t('groupChat.server.attachmentTooLarge', { size: 100 }));
+ }
+ if (error instanceof Error && error.message === 'ATTACHMENT_UNAVAILABLE') throw new Error(t('composer.upload.noFileRead'));
+ if (error instanceof Error && error.message === 'UPLOAD_CANCELLED') throw new Error(t('composer.upload.cancelled'));
+ throw error;
+ }
+ };
const media = async (mediaId: string, signal?: AbortSignal): Promise<BotGroupAttachment> => {
const generation = accessGeneration.current;
try {
@@ -432,5 +463,5 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
listHidden: api.current() && api.client.personalList.hidden(groupId),
online: state.identity === identity && state.online, reload, act, pending, pendingAction,
canQueue: enabled && api.enabled && state.identity === identity && state.value.kind === 'ready' && !api.client.personalList.hidden(groupId),
- acceptListState, isListHidden: () => api.client.personalList.hidden(groupId), loadOlder, loadingOlder: state.loadingOlder, media, markRead };
+ acceptListState, isListHidden: () => api.client.personalList.hidden(groupId), loadOlder, loadingOlder: state.loadingOlder, media, markRead, uploadAttachment };
}
diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.json
index 2011ad4db0..8b04872ebe 100644
--- a/apps/mobile/src/i18n/locales/en/groupChat.json
+++ b/apps/mobile/src/i18n/locales/en/groupChat.json
@@ -291,6 +291,7 @@
"failedStep": "Step {{step}} didn't finish"
},
"server": {
+ "attachmentTooLarge": "Group attachments must be {{size}} MB or smaller. Choose a smaller file.",
"offline": "Can’t connect to group chat. Try again.",
"loadFailed": "Can’t load this group chat right now. Try again.",
"loadOlder": "Load Earlier Messages",
diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.json
index 01b74cfda3..28d2f32d0a 100644
--- a/apps/mobile/src/i18n/locales/ja/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json
@@ -291,6 +291,7 @@
"failedStep": "ステップ {{step}} は完了できませんでした"
},
"server": {
+ "attachmentTooLarge": "グループの添付ファイルは {{size}} MB 以下にしてください。小さいファイルを選んでください。",
"offline": "グループチャットに接続できません。もう一度お試しください。",
"loadFailed": "グループチャットを読み込めません。もう一度お試しください。",
"loadOlder": "以前のメッセージを読み込む",
diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.json
index 9eb43f15bb..424ef6ff59 100644
--- a/apps/mobile/src/i18n/locales/ko/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json
@@ -291,6 +291,7 @@
"failedStep": "{{step}}단계를 끝내지 못했어요"
},
"server": {
+ "attachmentTooLarge": "그룹 첨부 파일은 {{size}} MB 이하여야 합니다. 더 작은 파일을 선택하세요.",
"offline": "그룹 채팅에 연결할 수 없습니다. 다시 시도해 주세요.",
"loadFailed": "그룹 채팅을 불러올 수 없습니다. 다시 시도해 주세요.",
"loadOlder": "이전 메시지 불러오기",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
index ee09209846..86b6b2ba92 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
@@ -291,6 +291,7 @@
"failedStep": "第 {{step}} 步没做完"
},
"server": {
+ "attachmentTooLarge": "群聊附件不能超过 {{size}} MB,请选择较小的文件。",
"offline": "暂时无法连接群聊,请重试。",
"loadFailed": "暂时无法读取群聊,请重试。",
"loadOlder": "加载更早的消息",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
index 2419d44378..8f3a784bc3 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
@@ -291,6 +291,7 @@
"failedStep": "第 {{step}} 步沒做完"
},
"server": {
+ "attachmentTooLarge": "群聊附件不能超過 {{size}} MB,請選擇較小的檔案。",
"offline": "暫時無法連線群聊,請重試。",
"loadFailed": "暫時無法讀取群聊,請重試。",
"loadOlder": "載入更早的訊息",
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index cadd91e102..09bb8f45ed 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -353,7 +353,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
clientId: input.clientId,
...(quote ? { quote: { messageId: quote.messageId } } : {}),
...(input.division ? { division: true } : {}),
- // Only a computer that declared `supportsAttachments` is offered any (see the composer).
+ // The active server/computer path declares attachment support (see the composer).
...(input.attachments.length > 0 ? { attachments: input.attachments } : {}),
});
if (quote) setReplyTo(current => current?.messageId === quote.messageId ? null : current);
@@ -497,7 +497,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
<BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={(chat.online || !!chat.canQueue) && !group.archived && !group.dissolvedAt}
quoteMessageId={replyTo?.messageId} focusRequest={replyFocusRequest}
running={group.round.status === 'running'} planState={botGroupComposerPlanState(openBotGroupPlan(group), group.replyMode)}
- divisionSupported={!chat.server && (!group.singleSpeaker || group.supportsDivision === true)} attachmentsSupported={group.supportsAttachments === true} onSend={send} onStop={stop} />
+ divisionSupported={!chat.server && (!group.singleSpeaker || group.supportsDivision === true)} attachmentsSupported={group.supportsAttachments === true} uploadAttachment={chat.uploadAttachment} onSend={send} onStop={stop} />
</KeyboardAvoidingView>;
}
diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsx
index 2039dfb5bd..3aeced5cce 100644
--- a/apps/mobile/src/session/BotGroupComposer.tsx
+++ b/apps/mobile/src/session/BotGroupComposer.tsx
@@ -54,6 +54,7 @@ import { nextBotGroupSendAttempt, type BotGroupSendAttempt } from './botGroupRem
import { canBrowsePhotoLibraryDirectly } from './photoLibraryPolicy';
import type { RemoteSerializedAttachment } from './types';
import { useBotGroupComposerAttachments } from './useBotGroupComposerAttachments';
+import type { UseMobileLocalAttachmentsOptions } from './useMobileLocalAttachments';
const CONTROL_SIZE = 34;
const CONTROL_HIT_SLOP = { top: 8, bottom: 8, left: 8, right: 8 } as const;
@@ -75,7 +76,7 @@ type MentionOption =
| { kind: 'member'; label: string; member: BotGroupMemberView };
export function BotGroupComposer({
- members, identityFor, deviceId, online, running, planState, attachmentsSupported, divisionSupported = true, quoteMessageId, focusRequest, onSend, onStop,
+ members, identityFor, deviceId, online, running, planState, attachmentsSupported, divisionSupported = true, uploadAttachment, quoteMessageId, focusRequest, onSend, onStop,
}: {
members: readonly BotGroupMemberView[];
identityFor: BotGroupIdentityLookup;
@@ -83,8 +84,9 @@ export function BotGroupComposer({
online: boolean;
running: boolean;
planState: BotGroupComposerPlanState | null;
- /** The computer takes attachments on `send` (`BotGroupRemoteChatData.supportsAttachments`). */
+ /** The active server/computer path takes attachments on send. */
attachmentsSupported: boolean;
+ uploadAttachment?: UseMobileLocalAttachmentsOptions['upload'];
divisionSupported?: boolean;
/** The message being replied to; part of the send intent. */
quoteMessageId?: string;
@@ -126,6 +128,7 @@ export function BotGroupComposer({
const focusInput = () => requestAnimationFrame(() => inputRef.current?.focus());
const tray = useBotGroupComposerAttachments({
deviceId,
+ upload: uploadAttachment,
onPicked: () => { setSheetOpen(false); focusInput(); },
});
const pendingImagePreview = useComposerPendingImagePreview(tray);
diff --git a/apps/mobile/src/session/ComposerFrame.ios.tsx b/apps/mobile/src/session/ComposerFrame.ios.tsx
index 9c83f922f2..de003e4566 100644
--- a/apps/mobile/src/session/ComposerFrame.ios.tsx
+++ b/apps/mobile/src/session/ComposerFrame.ios.tsx
@@ -12,24 +12,31 @@ const MorphTarget = requireOptionalNativeModule('CindyComposerMorph') ? requireN
export const nativeComposerFrameAvailable = isLiquidGlassAvailable();
-/** UIKit glass contains the controls directly, preserving UITextView touch/focus routing. */
+/** Keep controls in the React Native hit-test tree; glass is only the backdrop. */
export function ComposerFrame({ expanded: _expanded, unframed, style, children, entryTransitionId, onEntryTransitionComplete, expandToken, ...contentProps }: ComposerFrameProps) {
const { mode } = useTheme();
if (unframed || !nativeComposerFrameAvailable) return <View {...contentProps} style={style}>{children}</View>;
- return (
- <GlassView
- {...contentProps}
- colorScheme={mode}
- glassEffectStyle="regular"
- isInteractive={false}
- // Native glass geometry matches the existing expanded composer contour.
- style={[style, { borderRadius: composerGeometry.cornerRadius }]}
- >
+ // The native morph module requires target -> glass contentView -> effectView.
+ // Preserve that hierarchy for animated task composers.
+ if (entryTransitionId || expandToken != null) return (
+ <GlassView {...contentProps} colorScheme={mode} glassEffectStyle="regular" isInteractive={false}
+ style={[style, { borderRadius: composerGeometry.cornerRadius }]}>
{children}
- {(entryTransitionId || expandToken != null) && MorphTarget ? <MorphTarget transitionId={entryTransitionId ?? ''}
- expandToken={expandToken ?? ''}
- cornerRadius={composerGeometry.cornerRadius}
- onComplete={() => onEntryTransitionComplete?.()} pointerEvents="none" style={StyleSheet.absoluteFill} /> : null}
+ {MorphTarget ? <MorphTarget transitionId={entryTransitionId ?? ''} expandToken={expandToken ?? ''}
+ cornerRadius={composerGeometry.cornerRadius} onComplete={() => onEntryTransitionComplete?.()}
+ pointerEvents="none" style={StyleSheet.absoluteFill} /> : null}
</GlassView>
);
+ return (
+ <View {...contentProps} style={style}>
+ <GlassView
+ pointerEvents="none"
+ colorScheme={mode}
+ glassEffectStyle="regular"
+ isInteractive={false}
+ style={[StyleSheet.absoluteFill, { borderRadius: composerGeometry.cornerRadius }]}
+ />
+ {children}
+ </View>
+ );
}
diff --git a/apps/mobile/src/session/mobileAttachmentUpload.ts b/apps/mobile/src/session/mobileAttachmentUpload.ts
index 6e4eaabc16..dbb1da1178 100644
--- a/apps/mobile/src/session/mobileAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileAttachmentUpload.ts
@@ -276,10 +276,12 @@ export async function putMobileAttachmentUploadFromFile(
fileUri: string,
mimeType: string | undefined,
deps: UploadDeps = {},
- opts: UploadRecoveryOptions = {},
+ opts: UploadRecoveryOptions & { signedHeaders?: Readonly<Record<string, string>> } = {},
): Promise<void> {
const uploadFile = deps.uploadFile ?? uploadFileNative;
- const headers = buildMobileAttachmentUploadHeaders(mimeType);
+ // Chat Server signs a different header set from device-link. Never add OSS
+ // headers to an already signed request; preserve the device-link default.
+ const headers = opts.signedHeaders ? { ...opts.signedHeaders } : buildMobileAttachmentUploadHeaders(mimeType);
await putAttachmentWithRecovery((signal, onProgress) => uploadFile(putUrl, fileUri, headers, { signal, onProgress }), opts, true);
}
diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.ts
index 332f8e7fb8..2990419a6a 100644
--- a/apps/mobile/src/session/useBotGroupChat.ts
+++ b/apps/mobile/src/session/useBotGroupChat.ts
@@ -195,5 +195,5 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,
// Unknown presence still allows actions; the host answers or the link reports offline.
const online = status === 'online' && !!host.deviceId && getPresenceAvailability(host.deviceId) !== false;
return !host.deviceId ? { ...server, server: true } : { state: value, reload, act, online, server: false, listHidden: server.listHidden, loadOlder: undefined, loadingOlder: false, media: undefined, markRead,
- pending: [], pendingAction: undefined, canQueue: false };
+ uploadAttachment: undefined, pending: [], pendingAction: undefined, canQueue: false };
}
diff --git a/apps/mobile/src/session/useBotGroupComposerAttachments.ts b/apps/mobile/src/session/useBotGroupComposerAttachments.ts
index ad2278110c..d2ca7f3b7e 100644
--- a/apps/mobile/src/session/useBotGroupComposerAttachments.ts
+++ b/apps/mobile/src/session/useBotGroupComposerAttachments.ts
@@ -4,6 +4,7 @@
* 与任务输入框同一条本机附件管线:`useMobileLocalAttachments` 负责相册 / 拍照 / 文件 /
* 粘贴的拉起与乐观上传(传 deviceId,能直传时直传给这台电脑),这里只持有已上传的附件、
* 托盘缩略图与「最近照片」的勾选映射,写法对照会话页与新建页。
+ * 服务器直连群注入 upload,复用选择/预处理/托盘而不创建电脑中转对象。
*
* - 附件只在发出成功后才离开托盘(电脑取走上传后自己回收中转对象);发失败原样保留,
* 重发沿用同一条消息。
@@ -21,10 +22,11 @@ import { buildMobileImageAttachmentCandidate } from './mobileImageAttachment';
import { isComposerPastedImageUri } from './pastedImageAttachment';
import type { RemoteSerializedAttachment } from './types';
import { resolveContextSheetMediaAssetForUpload, type ContextSheetMediaAsset } from './useContextSheetMediaAssets';
-import { useMobileLocalAttachments } from './useMobileLocalAttachments';
+import { useMobileLocalAttachments, type UseMobileLocalAttachmentsOptions } from './useMobileLocalAttachments';
-export function useBotGroupComposerAttachments({ deviceId, onPicked }: {
+export function useBotGroupComposerAttachments({ deviceId, upload, onPicked }: {
deviceId: string;
+ upload?: UseMobileLocalAttachmentsOptions['upload'];
/** A picker returned (or a recent photo was tapped): close the sheet and go back to typing. */
onPicked(): void;
}) {
@@ -47,6 +49,7 @@ export function useBotGroupComposerAttachments({ deviceId, onPicked }: {
const local = useMobileLocalAttachments({
deviceId,
+ upload,
getAccessToken: () => getAccessTokenRef.current(),
getAttachmentCount: () => attachmentsRef.current.length,
onUploaded: (attachment, candidate) => {
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index 51b381b538..be66bddacc 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -35,6 +35,7 @@ import {
isCameraUnavailableOnSimulator,
type MobileLocalAttachmentUploadCandidate,
type MobileLocalAttachmentUploadController,
+ type MobileLocalAttachmentUploadDeps,
type PendingLocalAttachmentUpload,
} from '@/session/mobileLocalAttachmentUpload';
import {
@@ -55,6 +56,8 @@ import {
import type { RemoteSerializedAttachment } from '@/session/types';
export interface UseMobileLocalAttachmentsOptions {
+ /** Fixed for this composer's lifetime; defaults to the existing computer upload. */
+ upload?: MobileLocalAttachmentUploadDeps['upload'];
/**
* composer 附件作用域。已建任务页传 sessionId;作用域换代后,旧 picker / 粘贴 /
* 标注异步入口与上传完成结果不得写入新作用域。省略时保持旧的单作用域行为。
@@ -288,7 +291,7 @@ export function useMobileLocalAttachments(
if (candidate.kind === 'image') assertMobileImageSize(size);
else assertMobileDocumentSize(size);
},
- upload: (candidate, fileUri, opts) => uploadMobileAttachmentFromFile(candidate, fileUri, { ...opts, sharedTaskId: candidate.sharedTaskId, deviceId: candidate.deviceId }),
+ upload: options.upload ?? ((candidate, fileUri, opts) => uploadMobileAttachmentFromFile(candidate, fileUri, { ...opts, sharedTaskId: candidate.sharedTaskId, deviceId: candidate.deviceId })),
discard: (attachment, token) => discardMobileUploadedAttachment(attachment, {
getToken: () => token === undefined ? optionsRef.current.getAccessToken() : Promise.resolve(token),
}),
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 289a35ac58..f9810331f0 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -522,7 +522,13 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下
群主可归档服务器群,离群/解散/个人移除保持既有直连路径;电脑离线不影响人际聊天与群管理。
项目文件夹属于执行电脑,直连云端设置不展示虚假的空目录,也不为读取它连接电脑;原电脑入口保留目录展示。
仅实际请求伙伴回答或执行时,执行服务检查相关伙伴的可用性,失败只影响该次执行。
-- 直连页暂不提供新建群、上传附件、分工编排/审批、Thread 与表情操作;
+- 直连页复用手机现有相册、拍照、文件、最近照片与粘贴图片输入,支持只发附件和文字加附件。
+ 预处理后按既有 Chat Server `media` → 签名 PUT → `complete` 接口直传,消息只提交媒体 ID,
+ 不要求电脑在线。PUT 不携带账号 token,签名地址不写入草稿或消息;单件沿用服务器 100 MiB 上限。
+ 上传失败保留托盘重试,消息发送失败保留已上传附件及原发送标识;移除/退页取消在途上传,
+ 不将服务器媒体交给电脑中转对象回收接口,不改变服务器媒体生命周期或新增删除接口。
+ 账号/群聊换代后不接收旧结果;服务器撤权沿用群页清空行为。附件阅读仍沿用点击时核权的既有展示。
+- 直连页暂不提供新建群、分工编排/审批、Thread 与表情操作;
卡片保留服务器可读 fallback。原电脑兼容入口保留既有操作,不能把两条入口的能力混为一谈。
同账号另一台 Desktop 已经通过自身 Chat Server 适配器访问群,不应依赖远程伙伴列表再聚合一遍。
- 本次仅改 Mobile JS,无原生 fingerprint 或服务端 schema 变更。客户端代码接通不代表服务器部署与真机验收;
diff --git a/docs/work-notes/assets/mobile-direct-attachments/dark-panel.jpg b/docs/work-notes/assets/mobile-direct-attachments/dark-panel.jpg
new file mode 100644
index 0000000000..031e91b9a1
Binary files /dev/null and b/docs/work-notes/assets/mobile-direct-attachments/dark-panel.jpg differ
diff --git a/docs/work-notes/assets/mobile-direct-attachments/light-result.jpg b/docs/work-notes/assets/mobile-direct-attachments/light-result.jpg
new file mode 100644
index 0000000000..96ef965c9a
Binary files /dev/null and b/docs/work-notes/assets/mobile-direct-attachments/light-result.jpg differ