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): 发送气泡先上屏实色,状态放左侧图标与下方状态行

zqchrisb18c62c2c104
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 5c4f40a8ed..ad8599ddc9 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -413,7 +413,9 @@ import {
buildPendingSendItems,
pendingSendItemKey,
type MobilePendingSendActions,
+ type MobilePendingSendWaitingFor,
} from '@/session/pendingSendItems';
+import { noteLocalSend } from '@/session/localSendMotion';
import { isSourceDeviceRemoved } from '@/session/messageSourceLabels';
import {
appendOptimisticUserMessage,
@@ -2293,6 +2295,12 @@ function SessionScreenContent() {
const outboxConnectionDispatchBlocked = shouldHoldOutboxDispatchForConnection(
outboxConnectionState,
);
+ // 待发气泡写「等…后发送」只看真正断开:同步中、自动恢复中几秒就过去,不提示。
+ const outboxWaitingFor: MobilePendingSendWaitingFor | null = !outboxConnectionState.relayOnline
+ ? 'network'
+ : outboxConnectionState.targetAvailable === false || outboxConnectionState.deviceUnresponsive
+ ? 'computer'
+ : null;
// 弱网普通断线也要有可见信号(消息流静默停更没有任何提示),经防闪延迟后显示
const connectionRecoveryError = companionEntry.error ?? activeOutboxTransportError ?? connectionError;
const bannerError = connectionRecoveryError ?? historyError;
@@ -6121,6 +6129,7 @@ function SessionScreenContent() {
steeringClientIds: new Set(inputProjection.steeringQueueClientIds),
presentationByClientId,
getImagePreview: getSentImagePreview,
+ outboxWaitingFor,
});
},
[
@@ -6132,6 +6141,7 @@ function SessionScreenContent() {
livePendingSendClientIds,
outboxItems,
outboxDisplayItems,
+ outboxWaitingFor,
queueBusy,
queueEditing?.clientId,
queueHiddenClientIds,
@@ -6697,6 +6707,7 @@ function SessionScreenContent() {
record.uploads.push(await retainOutboxFile(record, item.slotByLocalId[localId]!, source));
}
if (!sendScopeStillAlive() || !isMobileAuthOwnerCurrent(ownerAtSend)) return;
+ noteLocalSend(record.item.clientId);
await mobileDurableOutbox.add(record);
committed = true;
handoff.release(true);
@@ -7037,6 +7048,7 @@ function SessionScreenContent() {
// previews / mediaAssetAttachments 映射保留到成功后再清:它们不入消息体,失败
// 恢复 attachments 时缩略图能原样回来。
const projectionBeforeSend = remoteSessionStore.getInputProjection(sessionId);
+ noteLocalSend(queued.clientId);
markQueueItemSending(queued);
remoteSessionStore.setInputProjectionOptimistically(sessionId, {
...projectionBeforeSend,
diff --git a/apps/mobile/docs/mobile-design-guide.md b/apps/mobile/docs/mobile-design-guide.md
index 85d41b68a1..edd823ad83 100644
--- a/apps/mobile/docs/mobile-design-guide.md
+++ b/apps/mobile/docs/mobile-design-guide.md
@@ -288,6 +288,16 @@ iOS 新增与改造界面遵循 [iOS 原生界面规范](../../../docs/design-ru
- **动效**:新消息与卡片用 `CompanionEntering` / `CompanionFadeIn`(RN `Animated`,原生驱动,只动 opacity /
transform,系统减弱动效时静止);工作中用 `CompanionPresenceRing` + `ThinkingDots`,不另写循环动画。
+### 待发送气泡(2026-10-21 定稿,任务与伙伴私聊共用)
+
+`PendingSendBubble` 是自己刚发出、还没被确认的消息。稿件:`Designs/cindy/send-bubble`(选定 B 方案)。
+
+- **一直是实色**:点发送当帧上屏,与正式气泡同款;网络往返、排队、等电脑都不变灰。只有「正在下方输入框编辑」时淡化。
+- **状态只放两处**:气泡左侧图标(转圈 = 发送中 / 上传中,队列图标 = 排队中,时钟 = 等电脑或网络,红色感叹号 `statusError` = 失败),以及气泡下方那一行。送达后正式消息的「复制 / …」占的就是这一行,所以前后行高不变、列表不跳。
+- **本机刚发出的消息**:0.6 秒内不出任何状态,慢了才淡入转圈;入场上浮一次,确认时不重播。
+- **下方那一行**:排队中「排队中 | 插话 编辑 取消」;失败「未发送 | 重试 删除」,有具体原因时原因写在下面;等待「等电脑连上后发送 | 取消」。文字 13/18,按钮命中区补到 44。报错文字保持黑白(`errorText`),只有左侧图标是红色。
+- **带图**:每张图自己转圈;只有那张没传上去的图上显示重传按钮。
+
## 5. 间距 / 圆角 / 触控 / 安全区
- **间距 `spacing`**:`xs 4 · sm 8 · md 12 · lg 16 · xl 24 · xxl 32`(基数 4)。避免 `2 / 6 / 13 / 17` 这类裸数字;1-2pt 的微调若实在需要,集中、少量、写注释。
diff --git a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
index af905a089b..e24f4d481d 100644
--- a/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
+++ b/apps/mobile/src/__tests__/PendingSendBubble.touch.test.tsx
@@ -19,14 +19,18 @@ vi.mock('react-native', async () => {
if (props.testID) handlers.set(String(props.testID), props);
return createElement(tag, { 'data-testid': props.testID, onClick: props.disabled ? undefined : props.onPress }, props.children);
};
+ class AnimatedValue { setValue() {} interpolate() { return 0; } }
return { View: view('div'), Text: view('span'), Pressable: view('button'), ActivityIndicator: () => null,
- StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 } };
+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
+ Animated: { View: view('div'), Value: AnimatedValue, timing: () => ({ start() {}, stop() {} }) },
+ Easing: { bezier: () => (value: number) => value },
+ AccessibilityInfo: { isReduceMotionEnabled: () => Promise.resolve(true), addEventListener: () => ({ remove() {} }) } };
});
vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));
vi.mock('lucide-react-native', () => ({ Check: () => null, AlertCircle: () => null, ArrowUp: () => null,
ListEnd: () => null, Paperclip: () => null, Pencil: () => null, RotateCcw: () => null, Trash2: () => null,
Bot: () => null, Ghost: () => null, Send: () => null, Timer: () => null,
- Monitor: () => null, Smartphone: () => null }));
+ Monitor: () => null, Smartphone: () => null, Clock: () => null }));
vi.mock('@/session/SentInlineAtomBody', () => ({ SentInlineAtomBody: () => null }));
vi.mock('@/session/sentAttachmentThumbStore', () => ({ getSentAttachmentThumbUri: (ref: string) => durableThumbs.get(ref) ?? null,
useSentAttachmentThumbsVersion: () => 0 }));
@@ -45,6 +49,7 @@ const select = vi.fn();
const openLink = vi.fn();
const openImage = vi.fn();
const removeOutbox = vi.fn();
+const retryOutbox = vi.fn();
const item: MobilePendingSendItem = {
type: 'pending_send', key: 'message-a', clientId: 'a', phase: 'queued', text: 'hello',
queueIndex: 1, sentInlineTokens: [], thumbs: [], fileCount: 0, attachmentCount: 0, uploadedCount: 0,
@@ -71,7 +76,7 @@ function show(
) {
handlers.clear();
const actions: PendingSendBubbleActions = { selectedClientId, onSelect: select, onRemove: vi.fn(),
- onBeginEdit: vi.fn(), onSteer: vi.fn(), onRetryOutbox: vi.fn(), onRemoveOutbox: removeOutbox };
+ onBeginEdit: vi.fn(), onSteer: vi.fn(), onRetryOutbox: retryOutbox, onRemoveOutbox: removeOutbox };
act(() => root.render(<PendingSendBubble item={{ ...item, ...overrides }} actions={actions} viewerDeviceId={viewerDeviceId}
onOpenImage={openImage}
renderImage={() => null} renderFile={() => null}
@@ -113,6 +118,19 @@ it('lets an in-flight local outbox message open its cancel action', () => {
act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.outboxRemove.a"]')!.click());
expect(removeOutbox).toHaveBeenCalledWith('a');
});
+it('offers retry and delete on a failed send without opening it first, and re-uploads only the failed image', () => {
+ show({ actions: null, phase: 'failed', queueIndex: null, attachmentCount: 2, thumbs: [
+ { key: 'a-slot-0', uri: 'file:///ok.jpg', ossRef: 'cindy-oss-attach://ok', uploading: false },
+ { key: 'a-slot-1', uri: 'file:///bad.jpg', ossRef: null, uploading: false, failed: true },
+ ] });
+ expect(host.querySelector('[data-testid="pendingSend.imageRetry.a-slot-0"]')).toBeNull();
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.imageRetry.a-slot-1"]')!.click());
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.outboxRetry.a"]')!.click());
+ expect(retryOutbox.mock.calls).toEqual([['a'], ['a']]);
+ act(() => host.querySelector<HTMLElement>('[data-testid="pendingSend.outboxRemove.a"]')!.click());
+ expect(removeOutbox).toHaveBeenCalledWith('a');
+ expect(select).not.toHaveBeenCalled();
+});
it('lets a real body link consume the pending tap before the frame commits', () => {
show(); touch('Start'); touch('End');
act(() => host.querySelector<HTMLElement>('[data-testid="link"]')!.click());
diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.ts
index 64c0d5de37..3bfe5fe5db 100644
--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts
+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts
@@ -350,6 +350,22 @@ describe('buildPendingSendItems', () => {
expect(items[2].actions).toBeNull();
});
+ it('holds a ready local send as waiting while disconnected, but keeps uploads and failures as they are', () => {
+ const [ready, uploading, failed] = build({
+ outboxWaitingFor: 'computer',
+ outbox: [
+ outboxItem('ready'),
+ outboxItem('uploading', { attachmentCount: 1, uploadedCount: 0 }),
+ outboxItem('failed', { failed: true }),
+ ],
+ });
+ expect(ready).toMatchObject({ phase: 'waiting', waitingFor: 'computer' });
+ expect(isPendingSendItemSelected(ready, 'ready')).toBe(true);
+ expect(uploading.phase).toBe('uploading');
+ expect(failed.phase).toBe('failed');
+ expect(build({ outbox: [outboxItem('ready')] })[0].phase).toBe('sending');
+ });
+
it('keeps a first-message creation row non-interactive until creation recovery is available', () => {
const [item] = build({ outbox: [outboxItem('first', { canCancel: false })] });
expect(item.canCancel).toBe(false);
diff --git a/apps/mobile/src/__tests__/sessionOutbox.test.ts b/apps/mobile/src/__tests__/sessionOutbox.test.ts
index 1540b0e871..dfaeebe540 100644
--- a/apps/mobile/src/__tests__/sessionOutbox.test.ts
+++ b/apps/mobile/src/__tests__/sessionOutbox.test.ts
@@ -475,6 +475,20 @@ describe('outboxDisplayItem', () => {
expect(enqueueFailed.errorText).toBe('RPC boom');
});
+ it('只把没传上去的那张图标成失败,其余图与上传中的图不受影响', () => {
+ const item = outboxItemWithUploadFailure(buildOutboxItem({
+ clientId: 'c-1', sessionId: 's-1', text: 'hi', permissionModeAtSend: 'ask', readyAttachments: [],
+ claimedUploads: [
+ { localId: 'u-a', failed: false, kind: 'image', previewUri: 'file:///tmp/a.jpg' },
+ { localId: 'u-b', failed: false, kind: 'image', previewUri: 'file:///tmp/b.jpg' },
+ ],
+ }), 'u-b');
+ expect(outboxDisplayItem(item).thumbnails).toEqual([
+ { key: 'c-1-slot-0', uri: 'file:///tmp/a.jpg', ossRef: null, uploading: true },
+ { key: 'c-1-slot-1', uri: 'file:///tmp/b.jpg', ossRef: null, uploading: false, failed: true },
+ ]);
+ });
+
it('图片槽出缩略格(本地预览 / 落定 ossRef / 上传中态),文件槽走计数行', () => {
let item = buildOutboxItem({
clientId: 'c-1',
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 5e3ffa1cae..b3ac07f05f 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -240,7 +240,15 @@
"sendingMessage": "Sending message: {{text}}",
"uploadingAttachments": "Uploading attachments {{uploaded}}/{{total}}",
"delete": "Delete",
- "retry": "Retry"
+ "retry": "Retry",
+ "notSent": "Not sent",
+ "imagesNotUploaded_one": "{{count}} image didn't upload",
+ "imagesNotUploaded_other": "{{count}} images didn't upload",
+ "waitingForComputer": "Sends when your computer is back",
+ "waitingForNetwork": "Sends when you’re back online",
+ "queued": "Queued",
+ "retryImage": "Upload this image again",
+ "waitingMessage": "Waiting to send: {{text}}"
},
"systemCard": {
"contextRebuild": {
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index d2b53c996b..095d3f1f8d 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -240,7 +240,14 @@
"sendingMessage": "送信中のメッセージ:{{text}}",
"uploadingAttachments": "添付ファイルをアップロード中 {{uploaded}}/{{total}}",
"delete": "削除",
- "retry": "再試行"
+ "retry": "再試行",
+ "notSent": "未送信",
+ "imagesNotUploaded": "{{count}} 枚の画像を送れませんでした",
+ "waitingForComputer": "パソコンにつながったら送信",
+ "waitingForNetwork": "ネットワークが戻ったら送信",
+ "queued": "順番待ち",
+ "retryImage": "この画像を再アップロード",
+ "waitingMessage": "送信待ちのメッセージ:{{text}}"
},
"systemCard": {
"contextRebuild": {
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 0c2fec6a4f..8c1ff7bd0d 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -240,7 +240,14 @@
"sendingMessage": "전송 중인 메시지:{{text}}",
"uploadingAttachments": "첨부파일 업로드 중 {{uploaded}}/{{total}}",
"delete": "삭제",
- "retry": "재시도"
+ "retry": "재시도",
+ "notSent": "전송 안 됨",
+ "imagesNotUploaded": "이미지 {{count}}장을 올리지 못했어요",
+ "waitingForComputer": "컴퓨터가 연결되면 전송",
+ "waitingForNetwork": "네트워크가 돌아오면 전송",
+ "queued": "대기 중",
+ "retryImage": "이 이미지 다시 올리기",
+ "waitingMessage": "전송 대기 중인 메시지:{{text}}"
},
"systemCard": {
"contextRebuild": {
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index d5b9968db4..2359107d27 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -240,7 +240,14 @@
"sendingMessage": "发送中的消息:{{text}}",
"uploadingAttachments": "附件上传中 {{uploaded}}/{{total}}",
"delete": "删除",
- "retry": "重试"
+ "retry": "重试",
+ "notSent": "未发送",
+ "imagesNotUploaded": "{{count}} 张图片没传上去",
+ "waitingForComputer": "等电脑连上后发送",
+ "waitingForNetwork": "等网络恢复后发送",
+ "queued": "排队中",
+ "retryImage": "重新上传这张图片",
+ "waitingMessage": "等待发送的消息:{{text}}"
},
"systemCard": {
"contextRebuild": {
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index d2677c9653..fce476e267 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -240,7 +240,14 @@
"sendingMessage": "傳送中的訊息:{{text}}",
"uploadingAttachments": "附件上傳中 {{uploaded}}/{{total}}",
"delete": "刪除",
- "retry": "重試"
+ "retry": "重試",
+ "notSent": "未傳送",
+ "imagesNotUploaded": "{{count}} 張圖片沒傳上去",
+ "waitingForComputer": "等電腦連上後傳送",
+ "waitingForNetwork": "等網路恢復後傳送",
+ "queued": "排隊中",
+ "retryImage": "重新上傳這張圖片",
+ "waitingMessage": "等待傳送的訊息:{{text}}"
},
"systemCard": {
"contextRebuild": {
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index c28e2e9717..e4beb96e65 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -25,9 +25,10 @@ import { downloadRemoteMediaShareTemp } from './remoteMediaDiskCacheExpo';
import { usePluginResultCard } from './usePluginResultCard';
import { extractPayloadToolResultMedia, managedToolMediaKind } from '@cindy/maker-shared/payload-summary';
import { AuthorizationMessageCard } from './AuthorizationMessageCard';
-import { collectBotMessageTimeGroups, formatBotMessageGroupTime } from '@cindy/maker-shared/botTimeline';
+import { collectBotMessageTimeGroups, formatBotMessageGroupTime, type BotTimelineMessage } from '@cindy/maker-shared/botTimeline';
import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { CompanionEntering } from '@/session/CompanionEntering';
+import { LOCAL_SEND_FRESH_MS, localSendStartedAt } from '@/session/localSendMotion';
import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';
import { createScrollDebugSampler } from '@/debug/scrollDebugSampler';
import { errorText, resolvedUrlKind } from '@/debug/fileDiagnostics';
@@ -1747,9 +1748,15 @@ export function MessageRenderer({
}, []);
const companionPluginWork = useMemo(() => companion ? companionPluginWorkEntries(items, companionPluginInvocations) : undefined, [companion, items, companionPluginInvocations]);
// Desktop MessageStream groups the visible teammate conversation (not hidden work) into five-minute stamps.
- const companionTimeGroups = useMemo(() => companion ? collectBotMessageTimeGroups(items.flatMap((item) =>
- item.type === 'message' && (item.message.kind === 'user' || item.message.kind === 'assistant' || item.message.companion)
- ? [{ clientId: item.key, createdAt: item.message.createdAt }] : [])) : undefined, [companion, items]);
+ // A local send joins at its send time, so its stamp is in place before the echo arrives.
+ const companionTimeGroups = useMemo(() => companion ? collectBotMessageTimeGroups(items.flatMap((item): BotTimelineMessage[] => {
+ if (item.type === 'pending_send') {
+ const sentAt = localSendStartedAt(item.key);
+ return sentAt === null ? [] : [{ clientId: item.key, createdAt: sentAt }];
+ }
+ return item.type === 'message' && (item.message.kind === 'user' || item.message.kind === 'assistant' || item.message.companion)
+ ? [{ clientId: item.key, createdAt: item.message.createdAt }] : [];
+ })) : undefined, [companion, items]);
const actions: MessageActions & { firstUserMessageClientId?: string } = useMemo(() => ({
companion,
companionWorkingLabel,
@@ -1930,6 +1937,25 @@ export function MessageRenderer({
scrollToEndProgrammatically(true, 'explicit');
}, [cancelHistoryPrependTransaction, scrollToEndProgrammatically]);
+ // The send-time follow runs before the local bubble exists, so the bubble would then land through
+ // the instant tail correction. Follow once more, animated, the moment it is in the list: the list
+ // carries the bubble up while it eases in.
+ const followedLocalSendKeysRef = useRef(new Set<string>());
+ useLayoutEffect(() => {
+ if (!historyActive) return;
+ const now = Date.now();
+ for (let index = listData.length - 1; index >= Math.max(0, listData.length - 3); index--) {
+ const item = listData[index];
+ if (item.type !== 'pending_send' && item.type !== 'message') continue;
+ const sentAt = localSendStartedAt(item.key);
+ if (sentAt === null || now - sentAt >= LOCAL_SEND_FRESH_MS) continue;
+ if (followedLocalSendKeysRef.current.has(item.key)) return;
+ followedLocalSendKeysRef.current.add(item.key);
+ scrollToBottom();
+ return;
+ }
+ }, [historyActive, listData, scrollToBottom]);
+
// A retained list must not replay requests issued while another task was active.
const followRequestWasActiveRef = useRef(historyActive);
// Sending and the jump button share the same explicit follow action.
@@ -3032,14 +3058,20 @@ const RenderItemView = memo(function RenderItemView({
logUnhandledRenderItem(item);
break;
}
- const groupTimestamp = actions.companion && item.type === 'message'
+ const groupTimestamp = actions.companion && (item.type === 'message' || item.type === 'pending_send')
? actions.companionTimeGroups?.get(item.key) : undefined;
// Cards and work groups share the reply text column, leaving the avatar slot empty.
const alignWithReplies = !!actions.companionAvatar && actions.companion
&& (item.type === 'work_group' || (item.type === 'message' && !!item.message.companion));
const aligned = alignWithReplies ? <View style={styles.companionAvatarInset}>{node}</View> : node;
- // Companion chats: a new message or finished reply eases in once (M4 / M5); everything else stays still.
- const entering = actions.companion && item.type === 'message' && !item.message.systemCardType
+ // Your own send eases in once, as its local bubble (both chats). Its echo keeps the same key and
+ // wrapper, so it neither remounts nor replays. Companion chats also ease in a new message or
+ // finished reply (M4 / M5).
+ const localSendAt = item.type === 'pending_send' || item.type === 'message'
+ ? localSendStartedAt(item.key) : null;
+ const entering = localSendAt !== null
+ ? <CompanionEntering key={item.key} id={item.key} createdAt={localSendAt} kind="send">{aligned}</CompanionEntering>
+ : actions.companion && item.type === 'message' && !item.message.systemCardType
&& (item.message.kind === 'user' || item.message.kind === 'assistant')
? <CompanionEntering key={item.key} id={item.key} createdAt={item.message.createdAt} kind={item.message.kind === 'user' ? 'send' : 'reply'}>{aligned}</CompanionEntering>
: aligned;
diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsx
index 9bbc87ac4c..5beb156638 100644
--- a/apps/mobile/src/session/PendingSendBubble.tsx
+++ b/apps/mobile/src/session/PendingSendBubble.tsx
@@ -1,18 +1,24 @@
/**
* 待发送消息气泡(渲染在消息流里,不再是列表 footer)。
*
- * 形态与已发送用户气泡同款(右对齐、surfaceElevated + border)但整体半透明——
- * 「这就是你的消息,只是还没生效」;落定时提高不透明度,回流后同一个列表位置换成正式
- * 消息,原地变实。徽标语义:
+ * 形态与已发送用户气泡同款(右对齐、surfaceElevated + border),从第一帧起一直是实色:内容已经
+ * 确定,网络往返、排队、等电脑都不是把它变灰的理由;回流后同一个列表位置换成正式消息,外观不变。
+ * 状态只放两处(设计稿 Designs/cindy/send-bubble r1 · B):气泡左侧图标,以及气泡下方那一行——
+ * 送达后正式消息的「复制 / …」占的就是这一行,所以前后行高不变。本机刚发出的条目图标延后出现,
+ * 多数发送在延迟内落定,不闪转圈。左侧图标语义:
* - 转圈 = 还没有「已被收下」这个事实(enqueue 在途 / 已出队待回流 / 附件上传中);
* - 「排入队尾 list-end」= 已确认入队,顺序由排列先后表达,不标数字;
+ * - 时钟 = 电脑离线,消息留在手机上,连上后自动发出(不算失败);
* - ✎ = 正在底部 composer 编辑这一条;
* - ⚠ = 失败,可重试 / 删除。
* 「排入队尾」是个事实断言,未确认时画它就是谎报,所以未确认一律转圈。
*/
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { ActivityIndicator, Pressable, StyleSheet, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
+import { ActivityIndicator, Animated, Easing, Pressable, StyleSheet, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
+import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { CompanionFadeIn } from '@/session/CompanionEntering';
+import { LOCAL_SEND_STATUS_DELAY_MS, localSendStartedAt } from '@/session/localSendMotion';
import { Text } from '@/components/AppText';
import { buildMessageContentLayout } from '@/session/messageContentLayout';
import { summarizeMessageBubblePresentation } from '@/session/messagePresentation';
@@ -23,8 +29,8 @@ import { MessageBodyTapBoundary } from '@/session/ShareMessageCheckbox';
import { shareSelectionTapMoved, shouldCommitShareSelectionTap, type ShareSelectionTapPoint } from '@/session/shareSelectionTap';
import {
AlertCircle,
- ArrowUp,
Bot,
+ Clock,
Ghost,
ListEnd,
Monitor,
@@ -34,7 +40,6 @@ import {
Send,
Smartphone,
Timer,
- Trash2,
type LucideIcon,
} from 'lucide-react-native';
import { shouldShowSourceDevice } from '@cindy/maker-shared/message-source';
@@ -63,6 +68,8 @@ import {
iconSize,
iconStroke,
lineHeight,
+ motionDuration,
+ motionEasing,
useTheme,
useThemedStyles,
type ThemeColors,
@@ -163,15 +170,18 @@ function ThumbCell({
resolveRemoteMedia,
renderImage,
onOpenImage,
+ onRetry,
}: {
renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;
thumb: MobileOutboxThumb;
slot: number;
+ onRetry?: () => void;
resolveRemoteMedia?: ResolveRemoteMediaFn;
onOpenImage?: (payload: MessagePayload) => void;
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
+ const { t } = useTranslation();
const [failedUris, setFailedUris] = useState<readonly string[]>([]);
const uri = useThumbCellUri(thumb, resolveRemoteMedia, failedUris);
const image = pendingSendGalleryImage(thumb, uri, slot);
@@ -196,6 +206,21 @@ function ThumbCell({
<View pointerEvents="none" style={styles.thumbUploadingOverlay}>
<ActivityIndicator color={colors.ctaText} size="small" />
</View>
+ ) : thumb.failed ? (
+ // 只有这张没传上去:原图照常显示,上面一个重传按钮;正文与其它图不受影响。
+ <View pointerEvents="box-none" style={styles.thumbUploadingOverlay}>
+ <Pressable
+ accessibilityLabel={t('message.queue.retryImage')}
+ accessibilityRole="button"
+ disabled={!onRetry}
+ hitSlop={spacing.xs}
+ onPress={(event) => { event.stopPropagation(); onRetry?.(); }}
+ style={({ pressed }) => [styles.thumbRetry, pressed && styles.pressed]}
+ testID={`pendingSend.imageRetry.${thumb.key}`}
+ >
+ <RotateCcw color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ </View>
) : null}
</Pressable>
);
@@ -207,9 +232,11 @@ function AttachmentThumbStrip({
renderImage,
gap,
onOpenImage,
+ onRetry,
}: {
renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;
gap: number;
+ onRetry?: () => void;
thumbs: readonly MobileOutboxThumb[];
resolveRemoteMedia?: ResolveRemoteMediaFn;
onOpenImage?: (payload: MessagePayload) => void;
@@ -221,12 +248,48 @@ function AttachmentThumbStrip({
<View style={[styles.thumbStrip, { gap }]} testID="pendingSend.thumbStrip">
{thumbs.map((thumb, slot) => (
<ThumbCell renderImage={renderImage} key={thumb.key} resolveRemoteMedia={resolveRemoteMedia}
- thumb={thumb} slot={slot} onOpenImage={onOpenImage} />
+ thumb={thumb} slot={slot} onOpenImage={onOpenImage} onRetry={onRetry} />
))}
</View>
);
}
+/**
+ * 本机刚发出的条目延后 LOCAL_SEND_STATUS_DELAY_MS 才显示状态:false = 还在延迟内,
+ * 'revealed' = 延迟后才出现(淡入),true = 一开始就该显示(别处来的条目 / 早已过了延迟)。
+ */
+function useLocalSendStatusShown(key: string): boolean | 'revealed' {
+ const sentAt = localSendStartedAt(key);
+ const remaining = sentAt === null ? 0 : sentAt + LOCAL_SEND_STATUS_DELAY_MS - Date.now();
+ const waiting = remaining > 0;
+ const [revealedKey, setRevealedKey] = useState<string | null>(null);
+ useEffect(() => {
+ if (!waiting || sentAt === null) return undefined;
+ const timer = setTimeout(() => setRevealedKey(key), Math.max(0, sentAt + LOCAL_SEND_STATUS_DELAY_MS - Date.now()));
+ return () => clearTimeout(timer);
+ }, [key, sentAt, waiting]);
+ if (revealedKey === key) return 'revealed';
+ return !waiting;
+}
+
+/** 进出「正在下方输入框编辑」时气泡透明度渐变,系统减弱动效时直接切换。 */
+function useAnimatedOpacity(target: number): Animated.Value {
+ const reduceMotion = useReduceMotionEnabled();
+ const value = useRef(new Animated.Value(target)).current;
+ useEffect(() => {
+ if (reduceMotion !== false) {
+ value.setValue(target);
+ return undefined;
+ }
+ const timing = Animated.timing(value, {
+ toValue: target, duration: motionDuration.fast, easing: Easing.bezier(...motionEasing.out), useNativeDriver: true,
+ });
+ timing.start();
+ return () => timing.stop();
+ }, [reduceMotion, target, value]);
+ return value;
+}
+
export function PendingSendBubble({
item,
actions,
@@ -267,6 +330,11 @@ export function PendingSendBubble({
const selected = isPendingSendItemSelected(item, actions.selectedClientId);
const bubbleLabel = item.text || t('message.queue.attachmentMessage');
const uploadsPending = item.phase === 'uploading';
+ const statusShown = useLocalSendStatusShown(item.key);
+ const waiting = item.phase === 'waiting';
+ const failedImages = item.thumbs.filter((thumb) => thumb.failed).length;
+ // 只有「正在下方输入框编辑」时淡化:那一刻气泡确实在被改写。
+ const contentOpacity = useAnimatedOpacity(editing ? 0.38 : 1);
const layout = buildMessageContentLayout({ screenWidth });
const rendersSentInlineBody = item.sentInlineTokens.some((token) => token.kind !== 'text');
const displayBody = rendersSentInlineBody ? sentInlineTokensDisplayText(item.sentInlineTokens) : item.text;
@@ -331,6 +399,8 @@ export function PendingSendBubble({
? { left: badgeAnchor.left } : { right: 0 };
const statusLabel = failed
? t('message.queue.sendFailedMessage', { text: bubbleLabel })
+ : waiting
+ ? t('message.queue.waitingMessage', { text: bubbleLabel })
: spinning
? t('message.queue.sendingMessage', { text: bubbleLabel })
: item.queueIndex !== null
@@ -410,23 +480,24 @@ export function PendingSendBubble({
testID={`pendingSend.badge.${item.phase}`}
>
{failed ? (
- <AlertCircle color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- ) : spinning ? (
- <ActivityIndicator color={colors.textTertiary} size="small" />
+ <AlertCircle color={colors.statusError} size={iconSize.sm} strokeWidth={iconStroke.regular} />
) : editing ? (
<Pencil color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- ) : (
- // 暂停态不换 ⏸:组顶横幅已表达暂停,逐条再换会重复;行内恒用排队 icon。
- <ListEnd color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ ) : waiting ? (
+ <Clock color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ ) : !statusShown ? null : (
+ <CompanionFadeIn distance={0} duration={motionDuration.fast} play={statusShown === 'revealed'}>
+ {spinning ? (
+ <ActivityIndicator color={colors.textTertiary} size="small" />
+ ) : (
+ // 暂停态不换 ⏸:组顶横幅已表达暂停,逐条再换会重复;行内恒用排队 icon。
+ <ListEnd color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ )}
+ </CompanionFadeIn>
)}
</Pressable>
- <View
- style={[
- styles.content,
- item.phase === 'settling' && styles.bubbleSettling,
- selected && styles.bubbleSelected,
- editing && styles.bubbleEditing,
- ]}
+ <Animated.View
+ style={[styles.content, { opacity: contentOpacity }]}
testID={`pendingSend.bubble.${item.clientId}`}
>
{hasAttachments ? (
@@ -434,6 +505,7 @@ export function PendingSendBubble({
<AttachmentThumbStrip
gap={layout.attachmentGap}
onOpenImage={onOpenImage}
+ onRetry={failed ? () => actions.onRetryOutbox(item.clientId) : undefined}
renderImage={renderImage}
resolveRemoteMedia={resolveRemoteMedia}
thumbs={item.thumbs}
@@ -502,7 +574,8 @@ export function PendingSendBubble({
</View>
</MessageBodyTapBoundary>
) : null}
- {(item.fileCount > 0 && !item.fileNames?.length) || uploadsPending ? (
+ {/* 图片各自带上传转圈;只有非图片附件在传时才需要这一行。 */}
+ {(item.fileCount > 0 && !item.fileNames?.length) || (uploadsPending && item.thumbs.length === 0) ? (
<View style={styles.attachmentLine}>
<Paperclip color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
<Text style={styles.attachmentLineText}>
@@ -520,93 +593,90 @@ export function PendingSendBubble({
{t('message.queue.editingInComposer')}
</Text>
) : null}
- {item.errorText ? (
- <Text style={styles.errorText} testID={`pendingSend.error.${item.clientId}`}>
- {item.errorText}
+ </Animated.View>
+ </View>
+ {/* 气泡下方这一行:送达后正式消息的「复制 / …」也占这一行,状态与操作都放这里,前后行高不变。 */}
+ <View style={styles.statusRow} testID={`pendingSend.statusRow.${item.clientId}`}>
+ {failed ? (
+ <>
+ <Text numberOfLines={1} style={styles.statusError}>
+ {failedImages > 0 ? t('message.queue.imagesNotUploaded', { count: failedImages }) : t('message.queue.notSent')}
</Text>
- ) : null}
- </View>
+ <View style={styles.statusDivider} />
+ <StatusAction busy={actions.busy} label={t('message.queue.retry')} primary
+ onPress={() => actions.onRetryOutbox(item.clientId)} testID={`pendingSend.outboxRetry.${item.clientId}`} />
+ {item.canCancel !== false ? (
+ <StatusAction busy={actions.busy} label={t('message.queue.delete')}
+ onPress={() => actions.onRemoveOutbox(item.clientId)} testID={`pendingSend.outboxRemove.${item.clientId}`} />
+ ) : null}
+ </>
+ ) : waiting ? (
+ <>
+ <Text numberOfLines={1} style={styles.statusText}>
+ {t(item.waitingFor === 'network' ? 'message.queue.waitingForNetwork' : 'message.queue.waitingForComputer')}
+ </Text>
+ {outbox && item.canCancel !== false ? (
+ <>
+ <View style={styles.statusDivider} />
+ <StatusAction busy={actions.busy} label={t('message.queue.cancel')}
+ onPress={() => actions.onRemoveOutbox(item.clientId)} testID={`pendingSend.outboxRemove.${item.clientId}`} />
+ </>
+ ) : null}
+ </>
+ ) : item.actions && item.phase === 'queued' && statusShown ? (
+ <View style={styles.statusActions} testID={`pendingSend.actions.${item.clientId}`}>
+ <Text numberOfLines={1} style={styles.statusText}>{t('message.queue.queued')}</Text>
+ <View style={styles.statusDivider} />
+ <StatusAction busy={actions.busy} disabled={item.actions.steer.disabled}
+ disabledReason={item.actions.steer.disabledReason} label={t('message.queue.steer')}
+ onPress={() => actions.onSteer(item.clientId)} testID={`pendingSend.steer.${item.clientId}`} />
+ <StatusAction busy={actions.busy} disabled={item.actions.edit.disabled}
+ disabledReason={item.actions.edit.disabledReason} label={t('message.queue.edit')}
+ onPress={() => actions.onBeginEdit(item.clientId)} testID={`pendingSend.edit.${item.clientId}`} />
+ <StatusAction busy={actions.busy} disabled={item.actions.remove.disabled}
+ disabledReason={item.actions.remove.disabledReason} label={t('message.queue.cancel')}
+ onPress={() => actions.onRemove(item.clientId)} testID={`pendingSend.remove.${item.clientId}`} />
+ </View>
+ ) : selected && outbox && item.canCancel !== false ? (
+ // 还在上传 / 发出途中:轻点气泡才露出「取消」,平时这一行留空,只有左侧图标。
+ <View style={styles.statusActions} testID={`pendingSend.outboxActions.${item.clientId}`}>
+ <StatusAction busy={actions.busy} label={t('message.queue.cancel')}
+ onPress={() => actions.onRemoveOutbox(item.clientId)} testID={`pendingSend.outboxRemove.${item.clientId}`} />
+ </View>
+ ) : null}
</View>
+ {/* 有具体原因的失败(比如模型不支持图片)直接写出来,用户才知道该怎么处理;图片没传上去的
+ 通用提示由那张图上的重传按钮表达,轻点气泡才看。 */}
+ {item.errorText && (failedImages === 0 || selected) ? (
+ <Text style={styles.rowHint} testID={`pendingSend.error.${item.clientId}`}>{item.errorText}</Text>
+ ) : null}
+ {/* 轻点气泡看排队操作为什么不可用。 */}
{selected && item.hint ? (
<Text style={styles.rowHint} testID={`pendingSend.hint.${item.clientId}`}>{item.hint}</Text>
) : null}
- {selected && item.actions ? (
- <View style={styles.actionRow} testID={`pendingSend.actions.${item.clientId}`}>
- <ActionPill
- busy={actions.busy}
- disabled={item.actions.remove.disabled}
- disabledReason={item.actions.remove.disabledReason}
- icon={Trash2}
- label={t('message.queue.cancel')}
- onPress={() => actions.onRemove(item.clientId)}
- testID={`pendingSend.remove.${item.clientId}`}
- />
- <ActionPill
- busy={actions.busy}
- disabled={item.actions.edit.disabled}
- disabledReason={item.actions.edit.disabledReason}
- icon={Pencil}
- label={t('message.queue.edit')}
- onPress={() => actions.onBeginEdit(item.clientId)}
- testID={`pendingSend.edit.${item.clientId}`}
- />
- <ActionPill
- busy={actions.busy}
- cta
- disabled={item.actions.steer.disabled}
- disabledReason={item.actions.steer.disabledReason}
- icon={ArrowUp}
- label={t('message.queue.steer')}
- onPress={() => actions.onSteer(item.clientId)}
- testID={`pendingSend.steer.${item.clientId}`}
- />
- </View>
- ) : null}
- {selected && outbox ? (
- <View style={styles.actionRow} testID={`pendingSend.outboxActions.${item.clientId}`}>
- <ActionPill
- busy={actions.busy}
- icon={Trash2}
- label={t(failed ? 'message.queue.delete' : 'message.queue.cancel')}
- onPress={() => actions.onRemoveOutbox(item.clientId)}
- testID={`pendingSend.outboxRemove.${item.clientId}`}
- />
- {failed ? <ActionPill
- busy={actions.busy}
- cta
- icon={RotateCcw}
- label={t('message.queue.retry')}
- onPress={() => actions.onRetryOutbox(item.clientId)}
- testID={`pendingSend.outboxRetry.${item.clientId}`}
- /> : null}
- </View>
- ) : null}
</View>
);
}
-function ActionPill({
+/** 状态行里的文字按钮:13/18 medium,可见高度跟着这一行,命中区用 hitSlop 补到 44。 */
+function StatusAction({
busy,
- cta,
disabled,
disabledReason,
- icon: Icon,
label,
onPress,
+ primary,
testID,
}: {
busy?: boolean;
- cta?: boolean;
disabled?: boolean;
disabledReason?: string | null;
- icon?: LucideIcon;
label: string;
onPress(): void;
+ primary?: boolean;
testID?: string;
}) {
const styles = useThemedStyles(makeStyles);
- const { colors } = useTheme();
- const iconColor = cta ? colors.ctaText : colors.textSecondary;
return (
<Pressable
accessibilityHint={disabledReason ?? undefined}
@@ -614,17 +684,14 @@ function ActionPill({
accessibilityRole="button"
accessibilityState={{ busy: busy || undefined, disabled }}
disabled={disabled}
+ hitSlop={{ top: spacing.sm, bottom: spacing.sm, left: spacing.xs, right: spacing.xs }}
onPress={disabled ? undefined : onPress}
- style={({ pressed }) => [
- styles.actionPill,
- cta && styles.actionPillCta,
- pressed && styles.pressed,
- disabled && styles.disabled,
- ]}
+ style={({ pressed }) => [styles.statusAction, pressed && styles.pressed]}
testID={testID}
>
- {Icon ? <Icon color={iconColor} size={iconSize.sm} strokeWidth={iconStroke.regular} /> : null}
- <Text style={[styles.actionPillText, cta && styles.actionPillTextCta]}>{label}</Text>
+ <Text style={[styles.statusActionText, primary && styles.statusActionTextPrimary, disabled && styles.statusActionTextDisabled]}>
+ {label}
+ </Text>
</Pressable>
);
}
@@ -643,9 +710,9 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
width: '100%',
},
badge: { alignItems: 'center', justifyContent: 'center', width: 28, minHeight: 44, position: 'absolute', top: 0, zIndex: 1 },
- // 与已发送用户气泡同款,但整体半透明:「这就是你的消息,只是还没生效」。
+ // 与已发送用户气泡同款,始终实色。
textChunk: { flexBasis: '100%', flexShrink: 1, maxWidth: '100%' },
- content: { alignItems: 'flex-end', gap: 2, width: '100%', opacity: 0.62 },
+ content: { alignItems: 'flex-end', gap: 2, width: '100%' },
bubbleCompact: { gap: 6, paddingVertical: spacing.sm },
bubbleRich: { gap: spacing.sm },
bubble: {
@@ -661,10 +728,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
},
collapseMeasureWrap: { left: spacing.md, right: spacing.md, top: 0, opacity: 0, position: 'absolute' },
collapseToggleText: { alignSelf: 'flex-start', color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, paddingVertical: spacing.xs },
- bubbleSelected: { opacity: 1 },
- bubbleEditing: { opacity: 0.38 },
- // 落定中:即将变实,透明度介于排队(0.62)与已发送(1)之间。
- bubbleSettling: { opacity: 0.85 },
bubbleText: {
color: colors.textPrimary,
fontSize: typeScale.bodyLarge,
@@ -685,30 +748,33 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
right: 0,
top: 0,
},
- editingHint: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
- errorText: { color: colors.errorText, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
- rowHint: {
- color: colors.textTertiary,
- fontSize: typeScale.footnote,
- lineHeight: lineHeight.caption,
- textAlign: 'right',
- },
- actionRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm, justifyContent: 'flex-end' },
- actionPill: {
+ thumbRetry: {
alignItems: 'center',
backgroundColor: colors.surfaceElevated,
borderColor: colors.border,
borderRadius: radius.pill,
borderWidth: StyleSheet.hairlineWidth,
- flexDirection: 'row',
- gap: 6,
+ height: 32,
justifyContent: 'center',
- minHeight: 44,
- paddingHorizontal: spacing.md,
+ width: 32,
+ },
+ editingHint: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ rowHint: {
+ color: colors.textTertiary,
+ fontSize: typeScale.footnote,
+ lineHeight: lineHeight.caption,
+ textAlign: 'right',
},
- actionPillCta: { backgroundColor: colors.cta, borderColor: colors.cta },
- actionPillText: { color: colors.textPrimary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.medium },
- actionPillTextCta: { color: colors.ctaText },
+ // 正式用户消息的操作行高 44(触控高度)+ 2 间距 = 46;本行前已有 rowWrap 的 8 间距,补 38。
+ statusRow: { alignItems: 'center', flexDirection: 'row', gap: spacing.sm, height: 38, justifyContent: 'flex-end', maxWidth: '100%' },
+ statusActions: { alignItems: 'center', flexDirection: 'row', gap: spacing.sm },
+ // 说明 / 报错是成句的话:13/18,二级色;失败用报错色。
+ statusText: { color: colors.textSecondary, flexShrink: 1, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ statusError: { color: colors.errorText, flexShrink: 1, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ statusDivider: { backgroundColor: colors.border, height: spacing.md, width: StyleSheet.hairlineWidth },
+ statusAction: { justifyContent: 'center', minHeight: 28 },
+ statusActionText: { color: colors.textSecondary, fontSize: typeScale.footnote, fontWeight: fontWeight.medium, lineHeight: lineHeight.caption },
+ statusActionTextPrimary: { color: colors.textPrimary },
+ statusActionTextDisabled: { color: colors.textTertiary, fontWeight: fontWeight.regular },
pressed: { opacity: 0.72 },
- disabled: { opacity: 0.42 },
});
diff --git a/apps/mobile/src/session/localSendMotion.ts b/apps/mobile/src/session/localSendMotion.ts
new file mode 100644
index 0000000000..09cda41a67
--- /dev/null
+++ b/apps/mobile/src/session/localSendMotion.ts
@@ -0,0 +1,26 @@
+import { pendingSendItemKey } from '@/session/pendingSendItems';
+
+/**
+ * Sends started from this phone's composer in this app run, by list key (the local bubble and its
+ * echo share it). Only these rows enter with motion, pull the list along and hold back their status;
+ * queue rows from other devices, relaunch recovery and history keep their still presentation.
+ */
+const MAX_REMEMBERED = 50;
+/** Most sends land before this; a slower one then reveals its spinner instead of flashing it. */
+export const LOCAL_SEND_STATUS_DELAY_MS = 600;
+/** A local send stays "just sent" this long: later mounts (scrolling back, remounts) stay still. */
+export const LOCAL_SEND_FRESH_MS = 15_000;
+
+const startedAt = new Map<string, number>();
+
+export function noteLocalSend(clientId: string, now = Date.now()): void {
+ const key = pendingSendItemKey(clientId);
+ startedAt.delete(key);
+ startedAt.set(key, now);
+ if (startedAt.size > MAX_REMEMBERED) startedAt.delete(startedAt.keys().next().value!);
+}
+
+/** When this phone sent the row with this list key, or null when it did not. */
+export function localSendStartedAt(key: string): number | null {
+ return startedAt.get(key) ?? null;
+}
diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.ts
index a905cfac40..b733c0a237 100644
--- a/apps/mobile/src/session/pendingSendItems.ts
+++ b/apps/mobile/src/session/pendingSendItems.ts
@@ -55,6 +55,8 @@ export type MobilePendingSendPhase =
| 'settling'
/** 本地 outbox:附件还在上传 / 等轮到队首。 */
| 'uploading'
+ /** 本地 outbox:电脑离线,消息留在手机上,连上后自动发出(不算失败)。 */
+ | 'waiting'
/** 上传或 enqueue 失败,气泡保留待用户重试 / 删除。 */
| 'failed'
/** 正在底部 composer 里编辑这一条。 */
@@ -107,6 +109,8 @@ export interface MobilePendingSendItem {
source?: MobilePendingSendSource | null;
/** 手机 / 另一台电脑发来的排队消息的设备来源(气泡按查看设备决定是否显示,与已发送消息同一规则)。 */
sourceDevice?: MessageSourceDevice;
+ /** phase 为 waiting 时在等什么。 */
+ waitingFor?: MobilePendingSendWaitingFor;
}
export interface MobileMessageListExtraData {
@@ -140,7 +144,7 @@ export function isPendingSendItemInteractive(
return item.actions !== null
|| (item.canCancel !== false && (item.phase === 'uploading'
|| item.phase === 'failed'
- || (item.phase === 'sending' && item.queueIndex === null)));
+ || ((item.phase === 'sending' || item.phase === 'waiting') && item.queueIndex === null)));
}
export function pendingSendItemKey(clientId: string): string {
@@ -371,8 +375,15 @@ export interface BuildPendingSendItemsInput {
*/
previewByOssRef?: ReadonlyMap<string, string>;
getImagePreview?: GetSentMessageImagePreview;
+ /**
+ * 本地待发条目为什么暂时发不出去:手机没网,或电脑离线 / 无响应。只在真正断开时给,
+ * 同步中、自动恢复中这类几秒内就过去的状态不算,避免一闪而过的「等待」。
+ */
+ outboxWaitingFor?: MobilePendingSendWaitingFor | null;
}
+export type MobilePendingSendWaitingFor = 'network' | 'computer';
+
/**
* 组装消息流末尾的待发送气泡项。
*
@@ -438,13 +449,16 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobile
if (seen.has(item.clientId) || input.hiddenClientIds.has(item.clientId)) continue;
seen.add(item.clientId);
const uploadsPending = item.attachmentCount > 0 && item.uploadedCount < item.attachmentCount;
+ // 上传走云端,不依赖电脑:传完了才进入「等连上」。
+ const waitingFor = !item.failed && !uploadsPending ? input.outboxWaitingFor ?? null : null;
items.push({
type: 'pending_send',
key: pendingSendItemKey(item.clientId),
clientId: item.clientId,
text: item.quotesEncoded ? stripChatQuoteMarkerLines(item.text) : item.text,
sentInlineTokens: buildPendingSentInlineTokens(item),
- phase: item.failed ? 'failed' : uploadsPending ? 'uploading' : 'sending',
+ phase: item.failed ? 'failed' : uploadsPending ? 'uploading' : waitingFor ? 'waiting' : 'sending',
+ ...(waitingFor ? { waitingFor } : {}),
queueIndex: null,
thumbs: item.thumbnails,
fileCount: item.fileCount,
diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.ts
index 4f3dc9479b..14bdee3ad6 100644
--- a/apps/mobile/src/session/sessionOutbox.ts
+++ b/apps/mobile/src/session/sessionOutbox.ts
@@ -185,6 +185,8 @@ export interface MobileOutboxThumb {
previewRef?: string;
/** 对应上传任务尚未落定(渲染转圈遮罩)。 */
uploading: boolean;
+ /** 这张图上传失败:只在它上面放重传按钮,其余图与正文保持原样。 */
+ failed?: boolean;
}
/** InlineQueueSection 渲染 outbox 行所需的最小视图数据。 */
@@ -466,6 +468,7 @@ export function outboxDisplayItem(item: MobileOutboxItem): MobileOutboxDisplayIt
const thumbnails: MobileOutboxThumb[] = [];
let fileCount = 0;
const fileNames: string[] = [];
+ const failedSlots = new Set(item.failedIds.map((localId) => item.slotByLocalId[localId]));
item.attachmentSlots.forEach((slot, index) => {
const meta = item.slotMeta[index];
if (meta?.kind !== 'image') {
@@ -477,7 +480,8 @@ export function outboxDisplayItem(item: MobileOutboxItem): MobileOutboxDisplayIt
key: `${item.clientId}-slot-${index}`,
uri: meta.previewUri,
ossRef: slot ? (slot.url ?? slot.path) : null,
- uploading: slot === null,
+ uploading: slot === null && !failedSlots.has(index),
+ ...(slot === null && failedSlots.has(index) ? { failed: true } : {}),
});
});
return {