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): 统一压缩与目标记录为轻量分隔提示 (#3944)

Dash7e0ff7132755
diff --git a/apps/mobile/src/__tests__/MobileBoundaryNotice.test.tsx b/apps/mobile/src/__tests__/MobileBoundaryNotice.test.tsx
new file mode 100644
index 0000000000..203ff7ebe8
--- /dev/null
+++ b/apps/mobile/src/__tests__/MobileBoundaryNotice.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MobileBoundaryNotice } from '@/session/MobileBoundaryNotice';
+import { i18n } from '@/i18n';
+
+vi.mock('react-native', async () => {
+ const { createElement } = await import('react');
+ type Props = { children?: ReactNode; onPress?: () => void; accessibilityLabel?: string; accessibilityState?: { expanded?: boolean }; selectable?: boolean };
+ const view = (tag: string) => ({ children, onPress, accessibilityLabel, accessibilityState, selectable }: Props) =>
+ createElement(tag, { onClick: onPress, 'aria-label': accessibilityLabel, 'aria-expanded': accessibilityState?.expanded, 'data-selectable': selectable }, children);
+ return { View: view('div'), Pressable: view('button'), Text: view('span'), StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 } };
+});
+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text }));
+vi.mock('lucide-react-native', () => ({ ChevronDown: () => null, ChevronRight: () => null, Layers: () => null, RefreshCw: () => null, Target: () => null }));
+vi.mock('@legendapp/list/react-native', async () => ({ useRecyclingState: (await import('react')).useState }));
+vi.mock('@/theme', async () => {
+ const { lightColors } = await import('@/theme/tokens');
+ return { useTheme: () => ({ colors: lightColors }), useThemedStyles: (make: (colors: typeof lightColors) => unknown) => make(lightColors) };
+});
+
+let root: Root;
+let host: HTMLDivElement;
+beforeEach(async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ await i18n.changeLanguage('zh-CN');
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+});
+
+describe('MobileBoundaryNotice', () => {
+ it.each(['goal-complete', 'context-rebuild'] as const)('keeps %s details selectable and available on demand', (type) => {
+ const detail = '完整原因或交接正文\n第二行也必须保留';
+ act(() => root.render(<MobileBoundaryNotice type={type} data={{ reason: detail, handoff: detail, turnsUsed: 3, elapsedMs: 65000 }} />));
+ const button = host.querySelector('button')!;
+ expect(button).not.toBeNull();
+ expect(button.getAttribute('aria-expanded')).toBe('false');
+ expect(host.textContent).not.toContain(detail);
+ act(() => button.click());
+ expect(button.getAttribute('aria-expanded')).toBe('true');
+ expect(host.querySelector('[data-selectable="true"]')?.textContent).toBe(detail);
+ act(() => button.click());
+ expect(host.textContent).not.toContain(detail);
+ });
+
+ it.each(['compact', 'goal-complete', 'goal-resumed', 'context-rebuild'] as const)('does not offer an empty expander for %s', (type) => {
+ act(() => root.render(<MobileBoundaryNotice type={type} />));
+ expect(host.querySelector('button')).toBeNull();
+ expect(host.textContent).not.toBe('');
+ });
+});
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 1e9099ff0c..74ec780ad7 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -7,6 +7,7 @@ import {
import { composerDocumentFromSerializedMessage } from '@/session/composerDocument';
import { buildMobileMessageCopyText } from '@/session/messageActions';
import { normalizeRemoteMessages } from '@/session/messageNormalize';
+import { buildMobileMessageRenderItems } from '@/session/messageRenderModel';
import {
MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES,
projectLargeSettledToolInputs,
@@ -1261,6 +1262,39 @@ describe('normalizeRemoteMessages', () => {
});
});
+describe('context rebuild boundaries', () => {
+ it.each(['context-overflow', 'pi-prompt-timeout', 'codex-history-strip'])('restores %s as a visible standalone boundary', (reason) => {
+ const rows = [
+ message({ id: 'before', role: 'assistant', content: 'Before' }),
+ message({ id: 'rebuild', role: 'assistant', content: '', agentMeta: { contextRebuild: { reason, handoff: 'Private handoff' } } }),
+ message({ id: 'after', role: 'assistant', content: 'After' }),
+ ];
+ const items = buildMobileMessageRenderItems(rows);
+ const boundary = items.find((item) => item.type === 'message' && item.message.systemCardType === 'context-rebuild');
+ expect(boundary).toMatchObject({ type: 'message', message: {
+ kind: 'system', body: '', systemCardData: { reason, handoff: 'Private handoff' },
+ } });
+ // Intermediate assistant work can be folded; the following answer stays outside the marker.
+ expect(items.at(-1)).toMatchObject({ type: 'message', message: { body: 'After' } });
+ });
+
+ it('accepts projected cards and defaults incomplete persisted metadata', () => {
+ expect(normalizeRemoteMessages([
+ message({ id: 'projected', role: 'assistant', content: '', systemCardType: 'context-rebuild', systemCardData: { handoff: 'Summary' } }),
+ message({ id: 'legacy', role: 'assistant', content: '', agentMeta: { contextRebuild: { reason: 12, handoff: false } } }),
+ ])).toMatchObject([
+ { systemCardType: 'context-rebuild', systemCardData: { handoff: 'Summary' } },
+ { systemCardType: 'context-rebuild', systemCardData: { reason: 'context-overflow', handoff: '' } },
+ ]);
+ });
+
+ it.each([null, 'invalid', []])('keeps ordinary assistant text when metadata is invalid: %j', (contextRebuild) => {
+ const [item] = normalizeRemoteMessages([message({ id: 'ordinary', role: 'assistant', content: 'Keep this text', agentMeta: { contextRebuild } })]);
+ expect(item.body).toBe('Keep this text');
+ expect(item.systemCardType).toBeUndefined();
+ });
+});
+
describe('normalizeRemoteMessages — /goal 持久记录与 plan_review 状态', () => {
it('renders goal completion records as goal-complete system cards instead of empty assistant bubbles', () => {
const items = normalizeRemoteMessages([
diff --git a/apps/mobile/src/__tests__/systemCard.test.ts b/apps/mobile/src/__tests__/systemCard.test.ts
index 10e9c37c9d..fca34109d1 100644
--- a/apps/mobile/src/__tests__/systemCard.test.ts
+++ b/apps/mobile/src/__tests__/systemCard.test.ts
@@ -105,9 +105,8 @@ describe('systemCard', () => {
expect(formatMobileSystemCard('compact', {
detail: 'Compacted 20 messages',
})).toEqual({
- title: 'Compact',
+ title: i18n.t('message.systemCard.compact.auto'),
rows: [],
- body: 'Compacted 20 messages',
});
expect(formatMobileSystemCard('cmd', {
@@ -141,6 +140,47 @@ describe('formatMobileSystemCard — goal 续跑卡按原因分说法', () => {
});
});
+describe('compact and context-rebuild notices', () => {
+ it('only reports savings when both token counts are known', () => {
+ for (const postTokens of [undefined, NaN, Infinity, -1, '1000']) {
+ expect(formatMobileSystemCard('compact', { preTokens: 25000, postTokens }).title)
+ .toBe(i18n.t('message.systemCard.compact.auto'));
+ }
+ expect(formatMobileSystemCard('compact', {
+ trigger: 'manual', preTokens: 25000, postTokens: 1000, durationMs: 2400,
+ }).title).toBe([
+ i18n.t('message.systemCard.compact.manual'),
+ i18n.t('message.systemCard.compact.savedTokens', { tokens: '24.0k' }),
+ '2.4s',
+ ].join(' · '));
+ });
+
+ it.each([
+ ['context-overflow', 'labelOverflow'],
+ ['pi-prompt-timeout', 'labelTimeout'],
+ ['codex-history-strip', 'labelStrip'],
+ ['future-reason', 'labelOverflow'],
+ ])('preserves the reason for %s without exposing a handoff as message body', (reason, key) => {
+ expect(formatMobileSystemCard('context-rebuild', { reason, handoff: ' ' })).toEqual({
+ title: i18n.t(`message.systemCard.contextRebuild.${key}`), rows: [],
+ });
+ });
+
+ it('preserves the handoff and only labels English when its terminal marker matches', () => {
+ const marker = "; the user's new message follows ==";
+ for (const [handoff, key] of [
+ ['旧交接正文', 'handoffTitle'],
+ [`Quoted ${marker}\n旧交接结尾`, 'handoffTitle'],
+ [`Summary ${marker}\n`, 'handoffTitleEnglishSource'],
+ ]) {
+ expect(formatMobileSystemCard('context-rebuild', { handoff })).toMatchObject({
+ body: handoff,
+ subtitle: i18n.t(`message.systemCard.contextRebuild.${key}`),
+ });
+ }
+ });
+});
+
describe('formatMobileSystemCard — 中断自动重连状态', () => {
const info = { error: 'socket hang up', attempt: 2, maxAttempts: 5, sessionTotal: 3 };
it('shows live progress, reason, current attempt, and session total', () => {
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 286c894bb5..21ca3998b1 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -179,6 +179,19 @@
"retry": "Retry"
},
"systemCard": {
+ "contextRebuild": {
+ "labelOverflow": "Context reorganized, continuing",
+ "labelTimeout": "Last turn didn't respond; context reorganized to continue",
+ "labelStrip": "Oversized images removed, continuing",
+ "handoffTitle": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)",
+ "handoffTitleEnglishSource": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)"
+ },
+ "compact": {
+ "savedTokens": "saved {{tokens}} tokens",
+ "manual": "Manual compact",
+ "auto": "Auto compact",
+ "aria": "Chat compacted"
+ },
"goalComplete": "Goal reached · {{turns}} turns · took {{duration}}",
"goalResumed": "Usage restored, continuing the goal",
"goalCapacityRetry": "Model service was busy — retrying the goal",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 6dcb9a3dfd..d3aa78056b 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -179,6 +179,19 @@
"retry": "再試行"
},
"systemCard": {
+ "contextRebuild": {
+ "labelOverflow": "コンテキストを整理して続行しました",
+ "labelTimeout": "直前の応答がなかったため、整理して続行しました",
+ "labelStrip": "大きな画像を除いて続行しました",
+ "handoffTitle": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",
+ "handoffTitleEnglishSource": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)"
+ },
+ "compact": {
+ "savedTokens": "{{tokens}} トークンを節約",
+ "manual": "手動圧縮",
+ "auto": "自動圧縮",
+ "aria": "会話を圧縮しました"
+ },
"goalComplete": "目標を達成 · {{turns}} 回 · 所要 {{duration}}",
"goalResumed": "使用量が回復、目標を継続",
"goalCapacityRetry": "モデルサービスが混雑していました。目標を再試行します",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 8412489233..2e57143763 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -179,6 +179,19 @@
"retry": "재시도"
},
"systemCard": {
+ "contextRebuild": {
+ "labelOverflow": "컨텍스트를 정리하고 계속합니다",
+ "labelTimeout": "직전 응답이 없어 정리한 뒤 계속합니다",
+ "labelStrip": "큰 이미지를 빼고 계속합니다",
+ "handoffTitle": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",
+ "handoffTitleEnglishSource": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)"
+ },
+ "compact": {
+ "savedTokens": "{{tokens}} 토큰 절약",
+ "manual": "수동 압축",
+ "auto": "자동 압축",
+ "aria": "대화가 압축되었습니다"
+ },
"goalComplete": "목표 달성 · {{turns}}회 · 소요 {{duration}}",
"goalResumed": "사용량이 회복되어 목표를 계속합니다",
"goalCapacityRetry": "모델 서비스가 혼잡했습니다. 목표를 다시 시도합니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index e76d09dbb5..d05c4343b5 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -179,6 +179,19 @@
"retry": "重试"
},
"systemCard": {
+ "contextRebuild": {
+ "labelOverflow": "已整理上下文并继续",
+ "labelTimeout": "上一轮没有响应,已整理后继续",
+ "labelStrip": "已去掉过大图片并继续",
+ "handoffTitle": "交接内容——整理后发送给后续对话的上下文摘要(不计入对话记录,仅在此展示)",
+ "handoffTitleEnglishSource": "交接内容——整理后发送给后续对话的上下文摘要,原文为英文(不计入对话记录,仅在此展示)"
+ },
+ "compact": {
+ "savedTokens": "节省 {{tokens}} tokens",
+ "manual": "手动压缩",
+ "auto": "自动压缩",
+ "aria": "对话已压缩"
+ },
"goalComplete": "目标已达成 · {{turns}} 轮 · 耗时 {{duration}}",
"goalResumed": "用量已恢复,继续目标",
"goalCapacityRetry": "模型服务繁忙,正在重试目标",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index ff3b6b1f4b..f0bdb7f71a 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -179,6 +179,19 @@
"retry": "重試"
},
"systemCard": {
+ "contextRebuild": {
+ "labelOverflow": "已整理上下文並繼續",
+ "labelTimeout": "上一輪沒有回應,已整理後繼續",
+ "labelStrip": "已去掉過大圖片並繼續",
+ "handoffTitle": "交接內容——整理後傳送給後續對話的上下文摘要(不計入對話記錄,僅在此展示)",
+ "handoffTitleEnglishSource": "交接內容——整理後傳送給後續對話的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)"
+ },
+ "compact": {
+ "savedTokens": "節省 {{tokens}} tokens",
+ "manual": "手動壓縮",
+ "auto": "自動壓縮",
+ "aria": "對話已壓縮"
+ },
"goalComplete": "目標已達成 · {{turns}} 輪 · 耗時 {{duration}}",
"goalResumed": "用量已恢復,繼續目標",
"goalCapacityRetry": "模型服務繁忙,正在重試目標",
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 46bc3836de..48ec0ea8f4 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -303,6 +303,7 @@ import type {
MobileMediaPlayerStatus,
} from '@/session/mediaPlayerWebViewHtml';
import { formatMobileSystemCard } from '@/session/systemCard';
+import { MobileBoundaryNotice } from '@/session/MobileBoundaryNotice';
import {
getMobileAutoResumePresentation,
isMobileAutoResumeRowInFlight,
@@ -4779,6 +4780,9 @@ function MobileSystemCard({
type: NonNullable<NormalizedRemoteMessage['systemCardType']>;
}) {
const styles = useThemedStyles(makeStyles);
+ if (type === 'compact' || type === 'goal-complete' || type === 'goal-resumed' || type === 'context-rebuild') {
+ return <MobileBoundaryNotice type={type} data={data} />;
+ }
// agent-switch 走专用「分隔线 + 药丸」渲染(对齐桌面),不落通用盒子卡片。
if (type === 'agent-switch') return <MobileAgentSwitchCard data={data} />;
// auto-resume 复用桌面 AgentActionRow 的单行状态布局:默认只显示当前状态和压缩后的
diff --git a/apps/mobile/src/session/MobileBoundaryNotice.tsx b/apps/mobile/src/session/MobileBoundaryNotice.tsx
new file mode 100644
index 0000000000..7bce6cf01a
--- /dev/null
+++ b/apps/mobile/src/session/MobileBoundaryNotice.tsx
@@ -0,0 +1,102 @@
+import { useTranslation } from 'react-i18next';
+import { Pressable, StyleSheet, View } from 'react-native';
+import { ChevronDown, ChevronRight, Layers, RefreshCw, Target } from 'lucide-react-native';
+import { useRecyclingState } from '@legendapp/list/react-native';
+import { Text } from '@/components/AppText';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
+import { formatMobileSystemCard } from '@/session/systemCard';
+
+export type MobileBoundaryNoticeType = 'compact' | 'goal-complete' | 'goal-resumed' | 'context-rebuild';
+
+/** Quiet transcript markers; long reasons and handoffs stay available on demand. */
+export function MobileBoundaryNotice({ type, data }: {
+ type: MobileBoundaryNoticeType;
+ data?: Record<string, unknown>;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useRecyclingState(false);
+ const card = formatMobileSystemCard(type, data);
+ const hasDetail = !!card.body?.trim();
+ const Icon = type === 'compact' ? Layers : type === 'context-rebuild' ? RefreshCw : Target;
+ const label = type === 'compact'
+ ? `${t('message.systemCard.compact.aria')} · ${card.title}`
+ : card.title;
+ const content = (
+ <>
+ <Icon color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
+ <Text style={styles.label} numberOfLines={1}>{card.title}</Text>
+ {hasDetail && (expanded
+ ? <ChevronDown color={colors.textTertiary} size={iconSize.xs} />
+ : <ChevronRight color={colors.textTertiary} size={iconSize.xs} />)}
+ </>
+ );
+
+ return (
+ <View style={styles.container} testID={`message.systemCard.${type}`}>
+ <View style={[styles.row, hasDetail && styles.interactiveRow]}>
+ <View style={styles.divider} />
+ {hasDetail ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t(expanded ? 'message.renderer.collapseRow' : 'message.renderer.expandRow', { label })}
+ accessibilityState={{ expanded }}
+ hitSlop={{ top: spacing.sm + spacing.xs, bottom: spacing.sm + spacing.xs }}
+ onPress={() => setExpanded((value) => !value)}
+ style={styles.pill}
+ >{content}</Pressable>
+ ) : (
+ <View accessible accessibilityLabel={label} style={styles.pill}>{content}</View>
+ )}
+ <View style={styles.divider} />
+ </View>
+ {expanded && hasDetail ? (
+ <View style={styles.detail}>
+ {card.subtitle ? <Text style={styles.detailTitle}>{card.subtitle}</Text> : null}
+ <Text selectable style={styles.detailBody}>{card.body}</Text>
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ container: { paddingVertical: spacing.xs },
+ row: { alignItems: 'center', flexDirection: 'row', gap: spacing.md },
+ // Native hitSlop cannot extend beyond the parent; leave room around the small pill.
+ interactiveRow: { minHeight: 44 },
+ divider: { backgroundColor: colors.border, flex: 1, height: StyleSheet.hairlineWidth },
+ pill: {
+ alignItems: 'center',
+ borderColor: colors.border,
+ borderRadius: radius.pill,
+ borderWidth: StyleSheet.hairlineWidth,
+ flexDirection: 'row',
+ flexShrink: 1,
+ gap: spacing.xs,
+ minWidth: 0,
+ paddingHorizontal: spacing.sm,
+ paddingVertical: spacing.xs,
+ },
+ label: {
+ color: colors.textTertiary,
+ flexShrink: 1,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.caption,
+ fontVariant: ['tabular-nums'],
+ },
+ detail: {
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ borderRadius: radius.control,
+ borderWidth: StyleSheet.hairlineWidth,
+ gap: spacing.xs,
+ marginTop: spacing.sm,
+ padding: spacing.md,
+ },
+ detailTitle: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
+ detailBody: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.body },
+});
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index fa73d076c4..72f5ca32cc 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -282,6 +282,29 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor
continue;
}
+ // Desktop persists context rebuilds as empty assistant rows with metadata.
+ if (message.role === 'assistant') {
+ const rebuild = readRecord(message.agentMeta?.contextRebuild);
+ if (rebuild) {
+ result.push({
+ key: messageNormalizeKey(message),
+ source: message,
+ kind: 'system',
+ role: message.role,
+ label: 'system:context-rebuild',
+ body: '',
+ systemCardType: 'context-rebuild',
+ systemCardData: {
+ reason: typeof rebuild.reason === 'string' ? rebuild.reason : 'context-overflow',
+ handoff: typeof rebuild.handoff === 'string' ? rebuild.handoff : '',
+ },
+ align: 'agent',
+ createdAt: message.createdAt,
+ });
+ continue;
+ }
+ }
+
// /goal 持久记录(桌面 goal-host 落库:role 'assistant' + 空 content + agentMeta 标记)
// → goal 系统卡。不加分支会 fall through 到通用 assistant 处理,渲染成空白气泡。
if (message.role === 'assistant') {
@@ -786,6 +809,7 @@ function normalizeSystemCardType(value: unknown): MobileSystemCardType | null {
|| value === 'pwd'
|| value === 'status'
|| value === 'compact'
+ || value === 'context-rebuild'
|| value === 'cmd'
|| value === 'learn'
? value
diff --git a/apps/mobile/src/session/systemCard.ts b/apps/mobile/src/session/systemCard.ts
index ad4ba6a61a..b9dd5ebcc2 100644
--- a/apps/mobile/src/session/systemCard.ts
+++ b/apps/mobile/src/session/systemCard.ts
@@ -11,6 +11,7 @@ import {
} from '@cindy/maker-shared/system-card';
import { i18n } from '@/i18n';
import { mobileAgentLabelFromUnknown } from '@/session/sessionAgentSwitch';
+import { formatCompactTokens } from '@cindy/maker-shared/usage-format';
/**
* 手机端系统卡类型 = 共享 slash 命令卡 + goal 持久记录卡 + silent-stop 自动续跑卡。
@@ -25,6 +26,7 @@ export type MobileSystemCardType =
| SystemCardType
| 'goal-complete'
| 'goal-resumed'
+ | 'context-rebuild'
| 'auto-resume'
| 'learn'
// session-agent-switch 边界卡(desktop 落库 role='agent_switch',读侧派生)。
@@ -100,7 +102,7 @@ export function buildMobileSystemCardData(
): Record<string, unknown> {
// goal / auto-resume / agent-switch 卡的数据由桌面落库行派生,learn 卡的数据由
// 发送侧 buildLearnCardData 直接组装,都不走本地 slash 命令的数据组装。
- if (type === 'goal-complete' || type === 'goal-resumed' || type === 'auto-resume' || type === 'learn' || type === 'agent-switch') return {};
+ if (type === 'goal-complete' || type === 'goal-resumed' || type === 'context-rebuild' || type === 'auto-resume' || type === 'learn' || type === 'agent-switch') return {};
return buildSystemCardData(type, {
...options,
localCommands: MOBILE_LOCAL_SYSTEM_COMMANDS,
@@ -112,6 +114,8 @@ export function formatMobileSystemCard(
type: MobileSystemCardType,
data: Record<string, unknown> | undefined,
): MobileSystemCardPresentation {
+ if (type === 'compact') return formatCompactCard(data);
+ if (type === 'context-rebuild') return formatContextRebuildCard(data);
if (type === 'goal-complete') return formatGoalCompleteCard(data);
if (type === 'goal-resumed') {
// 两种续跑原因共用这张卡, 但说法必须分开(与桌面 GoalResumedCard 同口径):
@@ -131,6 +135,41 @@ export function formatMobileSystemCard(
return formatSystemCard(type, data);
}
+function formatCompactCard(data: Record<string, unknown> | undefined): SystemCardPresentation {
+ const nonNegativeNumber = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
+ const preTokens = nonNegativeNumber(data?.preTokens);
+ const postTokens = nonNegativeNumber(data?.postTokens);
+ const durationMs = nonNegativeNumber(data?.durationMs);
+ const parts = [i18n.t(data?.trigger === 'manual'
+ ? 'message.systemCard.compact.manual'
+ : 'message.systemCard.compact.auto')];
+ if (preTokens !== undefined && postTokens !== undefined && preTokens > postTokens) {
+ parts.push(i18n.t('message.systemCard.compact.savedTokens', { tokens: formatCompactTokens(preTokens - postTokens) }));
+ }
+ if (durationMs) parts.push(`${(durationMs / 1000).toFixed(1)}s`);
+ return { title: parts.join(' · '), rows: [] };
+}
+
+function formatContextRebuildCard(data: Record<string, unknown> | undefined): SystemCardPresentation {
+ const handoff = typeof data?.handoff === 'string' ? data.handoff : '';
+ const titleKey = data?.reason === 'pi-prompt-timeout'
+ ? 'labelTimeout'
+ : data?.reason === 'codex-history-strip' ? 'labelStrip' : 'labelOverflow';
+ // Same terminal marker as desktop: old Chinese handoffs must not be labelled English.
+ const englishSource = handoff.trimEnd().endsWith("; the user's new message follows ==");
+ return {
+ title: i18n.t(`message.systemCard.contextRebuild.${titleKey}`),
+ ...(handoff.trim() ? {
+ subtitle: i18n.t(englishSource
+ ? 'message.systemCard.contextRebuild.handoffTitleEnglishSource'
+ : 'message.systemCard.contextRebuild.handoffTitle'),
+ body: handoff,
+ } : {}),
+ rows: [],
+ };
+}
+
function formatAutoResumeCard(data: Record<string, unknown> | undefined): SystemCardPresentation {
const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
const error = typeof data?.error === 'string' && data.error.trim() ? data.error : undefined;
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index 084bb6da1f..c6146939d0 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -118,7 +118,7 @@ export interface RemoteMessage {
/** Large settled tool input released from the transcript mirror and recoverable by message id. */
mobileToolInputProjection?: MobileToolInputProjection;
systemCardData?: Record<string, unknown>;
- systemCardType?: 'help' | 'context' | 'cost' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'auto-resume' | 'learn' | 'agent-switch';
+ systemCardType?: 'help' | 'context' | 'cost' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'context-rebuild' | 'auto-resume' | 'learn' | 'agent-switch';
}
export type RemoteAttachmentCategory = 'image' | 'pdf' | 'text' | 'office';