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): 待处理请求可收起,先看 agent 输出再决策 (#1493)

Chris Zhang8af9690c833e
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 6ddad7fa6d..9f0c89f92e 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -104,11 +104,17 @@ import {
import type { SessionMenuView } from '@/session/sessionMenu';
import {
interactionKind,
+ isPendingInteractionCollapsed,
pendingInteractionsBlockRemoteComposer,
readRequestId,
selectPendingInteractionByRequestId,
shouldUseFullHeightPendingInteractionSurface,
} from '@/session/interactionModel';
+import {
+ prunePendingInteractionCollapse,
+ togglePendingInteractionCollapse,
+ useCollapsedPendingRequestIds,
+} from '@/session/pendingInteractionCollapseStore';
import {
buildSessionRuntimeOptions,
normalizeMobileAgentCapabilities,
@@ -437,6 +443,7 @@ import {
useSessionInputProjection,
useSessionMessages,
useSessionPendingInteractions,
+ useSessionPendingInteractionsAuthoritative,
useSessionRunStatus,
useSessionMakerTurnRunning,
useSessionRunning,
@@ -772,6 +779,8 @@ export default function SessionScreen() {
const sessions = useRemoteSessions();
const messages = useSessionMessages(sessionId, deviceId);
const pending = useSessionPendingInteractions(sessionId);
+ // pending 列表是否已被被控端的全量快照确认过(空列表能不能当「都处理完了」用)。
+ const pendingInteractionsAuthoritative = useSessionPendingInteractionsAuthoritative(sessionId);
const inputProjection = useSessionInputProjection(sessionId);
const remoteSessionRunning = useSessionRunning(sessionId);
const makerTurnRunning = useSessionMakerTurnRunning(sessionId);
@@ -1048,6 +1057,14 @@ export default function SessionScreen() {
const [locallyRemovedQueueClientIds, setLocallyRemovedQueueClientIds] = useState<ReadonlySet<string>>(new Set());
const [pendingHistoryExpanded, setPendingHistoryExpanded] = useState(false);
const [pendingInteractionActiveRequestId, setPendingInteractionActiveRequestId] = useState<string | null>(null);
+ /**
+ * 用户主动收起的待处理请求(按 requestId),来自模块级 store。
+ *
+ * 不能是本组件的 state:契约是「只有该请求被回答 / 撤销才失效」,而离开任务会卸载本页,
+ * 组件 state 随之丢失——再进来同一条仍在 pending 的请求又会展开占满屏(#1493 review)。
+ * store 按 sessionId 隔离,切换会话不串状态。
+ */
+ const collapsedPendingRequestIds = useCollapsedPendingRequestIds(sessionId);
const [pendingPlanViewerState, setPendingPlanViewerState] = useState<MobilePlanViewerState>('half');
const [searchQuery, setSearchQuery] = useState('');
const [activeSearchIndex, setActiveSearchIndex] = useState(-1);
@@ -1507,10 +1524,24 @@ export default function SessionScreen() {
const activePendingKind = activePendingInteraction
? interactionKind(activePendingInteraction)
: null;
+ const activePendingCollapsed = isPendingInteractionCollapsed(
+ collapsedPendingRequestIds,
+ activePendingRequestId,
+ );
const pendingInteractionFullHeight = shouldUseFullHeightPendingInteractionSurface({
activeKind: activePendingKind,
+ collapsed: activePendingCollapsed,
planViewerState: pendingPlanViewerState,
});
+ const toggleCollapsedPendingRequest = useCallback((requestId: string) => {
+ togglePendingInteractionCollapse(sessionId, requestId);
+ }, [sessionId]);
+ // 状态与回调成对下发:Panel 的 collapse prop 是整组给或整组不给,只给一半会得到
+ // 「显示为收起但点不开」的死界面(#1493 review)。
+ const pendingInteractionCollapse = useMemo(
+ () => ({ requestIds: collapsedPendingRequestIds, onToggle: toggleCollapsedPendingRequest }),
+ [collapsedPendingRequestIds, toggleCollapsedPendingRequest],
+ );
const hasActivePendingInteraction = activePendingInteraction !== null;
// 只有手机能终结的卡才允许接管输入框。plugin_setup 这类必须回电脑端完成的
// 请求若也顶掉 composer,用户既处理不了卡、又发不出消息,会话在手机上被彻底
@@ -1562,6 +1593,14 @@ export default function SessionScreen() {
setPendingInteractionActiveRequestId(null);
}
}, [pending, pendingInteractionActiveRequestId]);
+ // 卡被回答 / 被撤后清掉它的收起记录,否则同一 requestId 万一复现会直接以收起态出现。
+ // 只在 pending 列表**权威**时清:短暂离线会按设计清空这份投影(markDeviceOffline),
+ // 那种空列表不代表请求已终结(#1493 review)。prune 无变化时返回原数组,不会自触发。
+ useEffect(() => {
+ prunePendingInteractionCollapse(sessionId, pending, {
+ authoritative: pendingInteractionsAuthoritative,
+ });
+ }, [pending, pendingInteractionsAuthoritative, sessionId]);
useEffect(() => {
if (
sessionOperationLayout.composerSlot !== 'pending-interaction'
@@ -8197,6 +8236,9 @@ export default function SessionScreen() {
nestedScrollEnabled
testID="interaction.aboveComposerScroll"
>
+ {/* 这张卡本来就只占 palette 量级高度、且手机上答不了(只能取消 / 回电脑端),
+ 不给收起入口:收起态的文案与 a11y 都是「先不答、稍后回答」,套在它身上是
+ 错的语义。 */}
<InteractionPanel
deviceId={deviceId}
sessionId={sessionId}
@@ -8233,6 +8275,7 @@ export default function SessionScreen() {
>
<InteractionPanel
safeAreaBottomInset={insets.bottom}
+ collapse={pendingInteractionCollapse}
deviceId={deviceId}
fillAvailableHeight
sessionId={sessionId}
@@ -8253,6 +8296,7 @@ export default function SessionScreen() {
>
<InteractionPanel
safeAreaBottomInset={insets.bottom}
+ collapse={pendingInteractionCollapse}
deviceId={deviceId}
sessionId={sessionId}
interactions={pending}
diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.ts
index 4990977ee1..d26271aafe 100644
--- a/apps/mobile/src/__tests__/interactionModel.test.ts
+++ b/apps/mobile/src/__tests__/interactionModel.test.ts
@@ -7,6 +7,7 @@ import {
buildAskQuestionProgressSummary,
buildAskQuestionReviewPresentation,
buildAskUserQuestionDecision,
+ buildCollapsedPendingInteractionPresentation,
buildInteractionResolveActionPresentation,
buildMobilePermissionCardState,
buildPendingInteractionQueuePresentation,
@@ -16,15 +17,19 @@ import {
buildPlanReviewDecision,
buildPlanReviewDecisionSummary,
buildPlanReviewEvidencePresentation,
+ canCollapsePendingInteraction,
canStartInteractionResolve,
encodeMultiSelectAnswer,
extractPlanOutline,
formatPermissionInput,
+ isPendingInteractionCollapsed,
isPlanReviewResolveBusy,
interactionBlocksRemoteComposer,
interactionKind,
normalizeAskQuestions,
+ pendingInteractionSummaryText,
pendingInteractionsBlockRemoteComposer,
+ prunePendingInteractionCollapsed,
remoteInteractionHandling,
REMOTE_PLUGIN_SETUP_ACTION_KINDS,
REMOTE_PLUGIN_SETUP_ERROR_CODES,
@@ -37,9 +42,15 @@ import {
sessionScopedPermissionSuggestions,
shouldUseFullHeightPendingInteractionSurface,
sortPendingInteractions,
+ togglePendingInteractionCollapsed,
} from '@/session/interactionModel';
+import { clearAskUserDraft, saveAskUserDraft } from '@/session/interactionDraftStore';
import type { PendingInteraction } from '@/session/types';
+/** prune 的权威性开关:全量快照到手 = 权威;离线清空投影 = 非权威。 */
+const AUTHORITATIVE = { authoritative: true } as const;
+const NOT_AUTHORITATIVE = { authoritative: false } as const;
+
// buildMobilePermissionCardState 已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦
// (全局 mock 默认 en-US)。共享层(@cindy/maker-shared/interaction)的中文直出不受影响。
beforeAll(async () => {
@@ -468,6 +479,269 @@ describe('interactionModel', () => {
activeKind: selectedPlan ? interactionKind(selectedPlan) : null,
planViewerState: 'half',
})).toBe(false);
+ // 收起时固定高度必须失效:否则「收起」只是换了张空 bar,surface 照样占满屏。
+ expect(shouldUseFullHeightPendingInteractionSurface({
+ activeKind: selectedPlan ? interactionKind(selectedPlan) : null,
+ collapsed: true,
+ planViewerState: 'expanded',
+ })).toBe(false);
+ });
+
+ it('keeps the pending collapse intent per request and survives list churn', () => {
+ const pending = [
+ { request: { kind: 'ask_user_question', requestId: 'ask-1', questions: [{ question: '按哪种方式做?' }] } },
+ { request: { kind: 'permission', requestId: 'perm-1', toolName: 'Bash' } },
+ ] as unknown as PendingInteraction[];
+
+ expect(isPendingInteractionCollapsed([], 'ask-1')).toBe(false);
+ // 没有 requestId 的卡不可能被收起(收起态以 requestId 为键)。
+ expect(isPendingInteractionCollapsed(['ask-1'], null)).toBe(false);
+
+ const collapsed = togglePendingInteractionCollapsed([], 'ask-1');
+ expect(collapsed).toEqual(['ask-1']);
+ expect(isPendingInteractionCollapsed(collapsed, 'ask-1')).toBe(true);
+ expect(isPendingInteractionCollapsed(collapsed, 'perm-1')).toBe(false);
+ expect(togglePendingInteractionCollapsed(collapsed, 'ask-1')).toEqual([]);
+
+ // 队列刷新(同一批卡再来一遍)不得清掉收起意图 —— 这正是旧卡内 state 的病根。
+ expect(prunePendingInteractionCollapsed(collapsed, pending, AUTHORITATIVE)).toBe(collapsed);
+ // 卡被回答 / 被撤后收起记录要清掉,免得同 requestId 复现时直接以收起态出现。
+ expect(prunePendingInteractionCollapsed(collapsed, [pending[1]!], AUTHORITATIVE)).toEqual([]);
+ // 空集合走 identity 返回:effect 里 setState 每帧换引用会无限重入。
+ const empty: readonly string[] = [];
+ expect(prunePendingInteractionCollapsed(empty, [], AUTHORITATIVE)).toBe(empty);
+ });
+
+ it('prunes the collapse intent only under an authoritative pending snapshot', () => {
+ const collapsed = ['ask-1', 'perm-1'];
+
+ // 非权威的空(markDeviceOffline 按设计清掉了这份依赖实时连接的投影):不能清,
+ // 否则重连后同一张卡以展开态灌回来占满屏 —— 本 PR 要治的病换条路径复发。
+ expect(prunePendingInteractionCollapsed(collapsed, [], NOT_AUTHORITATIVE)).toBe(collapsed);
+ // 权威的空(被控端确认全都处理完了):要清,否则最后一条收起记录永远留着。
+ expect(prunePendingInteractionCollapsed(collapsed, [], AUTHORITATIVE)).toEqual([]);
+
+ const restored = [
+ { request: { kind: 'ask_user_question', requestId: 'ask-1', questions: [{ question: '还在等回答' }] } },
+ ] as unknown as PendingInteraction[];
+ // 重连后的权威非空快照:ask-1 还在 → 保留收起;perm-1 已终结 → 清掉。
+ expect(prunePendingInteractionCollapsed(collapsed, restored, AUTHORITATIVE)).toEqual(['ask-1']);
+ // 非权威的非空同样不清:重连后可能先到一条 push 增量、全量快照还没来,那份列表
+ // 只含增量那张卡,按它过滤会把 perm-1 的收起记录误清 —— 与离线空列表同一类误判。
+ expect(prunePendingInteractionCollapsed(collapsed, restored, NOT_AUTHORITATIVE)).toBe(collapsed);
+
+ // 非权威窗口里不清,集合仍要有界:上限截断最旧的。
+ const many = Array.from({ length: 12 }, (_, i) => `req-${i}`);
+ const bounded = prunePendingInteractionCollapsed(many, [], NOT_AUTHORITATIVE);
+ expect(bounded).toHaveLength(8);
+ expect(bounded[0]).toBe('req-4');
+ expect(bounded[7]).toBe('req-11');
+ });
+
+ it('keeps the collapsed bar screen-reader label on the question the user is actually on', () => {
+ const item = {
+ request: {
+ kind: 'ask_user_question',
+ requestId: 'ask-label-1',
+ questions: [{ question: '第一问是什么' }, { question: '第二问是什么' }],
+ },
+ } as unknown as PendingInteraction;
+
+ // 还没翻页:标签用第一问。
+ const first = buildCollapsedPendingInteractionPresentation({
+ item,
+ queueTitle: '等待回答',
+ requestId: 'ask-label-1',
+ });
+ expect(first.summaryText).toBe('第一问是什么');
+ expect(first.accessibilityLabel).toContain('第一问是什么');
+
+ // 进入第二问后,读屏念的必须是第二问 —— 这条钉的就是 label 本身,不是渲染代码文本。
+ saveAskUserDraft('ask-label-1', {
+ answers: {},
+ currentIndex: 1,
+ customInput: '',
+ selectedLabels: [],
+ showCustomInput: false,
+ });
+ const second = buildCollapsedPendingInteractionPresentation({
+ item,
+ queueTitle: '等待回答',
+ requestId: 'ask-label-1',
+ });
+ expect(second.summaryText).toBe('第二问是什么');
+ expect(second.accessibilityLabel).toContain('第二问是什么');
+ expect(second.accessibilityLabel).not.toContain('第一问是什么');
+ clearAskUserDraft('ask-label-1');
+
+ // 没有专属摘要的卡(手机端答不了的那类)退回队列标题,标签不留空。
+ const fallback = buildCollapsedPendingInteractionPresentation({
+ item: { request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 } } as unknown as PendingInteraction,
+ queueTitle: '电脑端处理',
+ requestId: 'setup-1',
+ });
+ expect(fallback.summaryText).toBeNull();
+ expect(fallback.accessibilityLabel).toContain('电脑端处理');
+ });
+
+ it('offers the collapse affordance only for requests the phone can actually resolve', () => {
+ // 队列混着 plugin_setup 时用户能从队列头切过去,那张卡答不了(只能取消 / 回电脑端),
+ // 给它挂「点开回答」既是错的语义,也绕过了 above-composer 放置点不给收起的保护。
+ expect(canCollapsePendingInteraction({
+ request: { kind: 'ask_user_question', requestId: 'ask-1', questions: [{ question: 'q' }] },
+ } as unknown as PendingInteraction)).toBe(true);
+ expect(canCollapsePendingInteraction({
+ request: { kind: 'permission', requestId: 'perm-1', toolName: 'Bash' },
+ } as unknown as PendingInteraction)).toBe(true);
+ expect(canCollapsePendingInteraction({
+ request: { kind: 'plan_review', requestId: 'plan-1', plan: 'x' },
+ } as unknown as PendingInteraction)).toBe(true);
+ expect(canCollapsePendingInteraction({
+ request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 },
+ } as unknown as PendingInteraction)).toBe(false);
+ expect(canCollapsePendingInteraction({
+ request: { kind: 'issue_confirm', requestId: 'issue-1' },
+ } as unknown as PendingInteraction)).toBe(false);
+ expect(canCollapsePendingInteraction(null)).toBe(false);
+ });
+
+ it('summarizes what each pending kind is waiting on, without shared Chinese defaults', () => {
+ expect(pendingInteractionSummaryText({
+ request: {
+ kind: 'ask_user_question',
+ requestId: 'ask-1',
+ questions: [{ question: '手机来源提示这一条,按哪种方式做?' }, { question: '第二问' }],
+ },
+ } as unknown as PendingInteraction)).toBe('手机来源提示这一条,按哪种方式做?');
+ // 多问卡按当前进度取问题:收起条写第一问、展开后停在第二问就是错位(#1493 review)。
+ expect(pendingInteractionSummaryText({
+ request: {
+ kind: 'ask_user_question',
+ requestId: 'ask-1b',
+ questions: [{ question: '第一问' }, { question: '第二问' }, { question: '第三问' }],
+ },
+ } as unknown as PendingInteraction, 2)).toBe('第三问');
+ // 越界 / 非法索引夹回有效范围,不渲染 undefined。
+ expect(pendingInteractionSummaryText({
+ request: {
+ kind: 'ask_user_question',
+ requestId: 'ask-1c',
+ questions: [{ question: '第一问' }, { question: '第二问' }],
+ },
+ } as unknown as PendingInteraction, 9)).toBe('第二问');
+ expect(pendingInteractionSummaryText({
+ request: {
+ kind: 'ask_user_question',
+ requestId: 'ask-1d',
+ questions: [{ question: '第一问' }, { question: '第二问' }],
+ },
+ } as unknown as PendingInteraction, Number.NaN)).toBe('第一问');
+ // permission 用工具名而非 permissionTitle:后者是共享层中文直出(「允许使用 X?」),
+ // 直接渲染会让 en / ja / ko 下的收起条念混语。
+ expect(pendingInteractionSummaryText({
+ request: { kind: 'permission', requestId: 'perm-1', toolName: 'Bash', title: '允许使用 Bash?' },
+ } as unknown as PendingInteraction)).toBe('Bash');
+ // 计划卡取正文首行并剥掉 markdown 标题标记。
+ expect(pendingInteractionSummaryText({
+ request: { kind: 'plan_review', requestId: 'plan-1', plan: '\n## 重构 InteractionPanel\n- 第一步' },
+ } as unknown as PendingInteraction)).toBe('重构 InteractionPanel');
+ // 正文为空时退到文件路径,仍然给得出「在等什么」。
+ expect(pendingInteractionSummaryText({
+ request: { kind: 'plan_review', requestId: 'plan-2', plan: ' ', planFilePath: 'docs/plan.md' },
+ } as unknown as PendingInteraction)).toBe('docs/plan.md');
+ // 超长首行截断,收起条永远是一行。
+ const long = pendingInteractionSummaryText({
+ request: { kind: 'ask_user_question', requestId: 'ask-2', questions: [{ question: 'x'.repeat(200) }] },
+ } as unknown as PendingInteraction);
+ expect(long).toHaveLength(80);
+ expect(long?.endsWith('…')).toBe(true);
+ // 手机端终结不了的卡没有专属摘要,收起条退回队列标题。
+ expect(pendingInteractionSummaryText({
+ request: { kind: 'plugin_setup', requestId: 'setup-1', revision: 1 },
+ } as unknown as PendingInteraction)).toBeNull();
+ });
+
+ it('drives the pending collapse from session-level props, not card-local state', () => {
+ const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');
+ const sessionScreenSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+
+ // 收起入口在队列头,三类卡通用;卡内不得再自持一份 collapsed(两套状态时页面级
+ // 那份会被卡片 key 变化冲掉,用户刚收起就弹回来)。
+ expect(interactionPanelSource).toContain('testID="interaction.panel.collapseButton"');
+ expect(interactionPanelSource).toContain('testID="interaction.panel.collapsedBar"');
+ expect(interactionPanelSource).not.toContain('setCollapsed(');
+ expect(interactionPanelSource).not.toContain('interaction.ask.collapseButton');
+ // 按钮要带可见文字:此前是个没有标签的「—」图标,用户看不出那是「先不答」的出口。
+ expect(interactionPanelSource).toContain("t('interaction.panel.collapse')");
+ // 收起态只留一条 bar:仍渲染 PendingTaskHeader 就还是两层结构,消息流照样看不到几行。
+ const collapsedStart = interactionPanelSource.indexOf('if (collapsed) {');
+ const collapsedEnd = interactionPanelSource.indexOf('return (', interactionPanelSource.indexOf('}', collapsedStart));
+ expect(collapsedStart).toBeGreaterThan(0);
+ expect(interactionPanelSource.slice(collapsedStart, collapsedEnd)).not.toContain('<PendingTaskHeader');
+ // 状态与回调必须成对:只给一半会得到「显示为收起但点不开」的死界面(#1493 review),
+ // 所以 collapse 是一个对象 prop,且 collapsed 的判定挂在 canToggleCollapsed 上。
+ expect(interactionPanelSource).toContain('collapse?: {');
+ expect(interactionPanelSource).toContain('const collapsed = canToggleCollapsed && isPendingInteractionCollapsed(');
+ expect(interactionPanelSource).not.toContain('collapsedRequestIds?:');
+ expect(interactionPanelSource).not.toContain('onToggleCollapsed?(');
+ // 收起条的摘要与读屏标签都走可断言的 helper(进度从草稿现取)。
+ expect(interactionPanelSource).toContain('buildCollapsedPendingInteractionPresentation({');
+ expect(interactionPanelSource).toContain('accessibilityLabel={collapsedBarLabel}');
+ // 收起入口只给本端能终结的卡,否则队列头切到 plugin_setup 也会冒出「点开回答」。
+ expect(interactionPanelSource).toContain('canCollapsePendingInteraction(activeInteraction)');
+
+ expect(sessionScreenSource).toContain('collapse={pendingInteractionCollapse}');
+ expect(sessionScreenSource).not.toContain('collapsedRequestIds={');
+ expect(sessionScreenSource).toContain('collapsed: activePendingCollapsed');
+ // 清理必须挂在权威快照上:离线空列表不算「都处理完了」。
+ expect(sessionScreenSource).toContain('authoritative: pendingInteractionsAuthoritative');
+ expect(sessionScreenSource).toContain('useSessionPendingInteractionsAuthoritative(sessionId)');
+ });
+
+ it('models pending authority in the store instead of inferring it from relay status', () => {
+ const storeSource = readFileSync(resolve(process.cwd(), 'src/session/remoteSessionStore.ts'), 'utf8');
+
+ // 权威性是显式状态:全量快照置位,离线 / 设备移除 / clear 复位。
+ expect(storeSource).toContain('const pendingInteractionsAuthoritative = new Set<string>();');
+ expect(storeSource).toContain('pendingInteractionsAuthoritative.add(sessionId);');
+ expect(storeSource).toContain('hasAuthoritativePendingInteractions(sessionId: string): boolean');
+ expect(storeSource).toContain('export function useSessionPendingInteractionsAuthoritative(');
+ // markDeviceOffline 与 removeDevice 都要撤销权威,否则离线期的空列表会被当权威用。
+ const offlineStart = storeSource.indexOf('markDeviceOffline(deviceId: string): void {');
+ const offlineEnd = storeSource.indexOf('removeDevice(deviceId: string): void {');
+ expect(offlineStart).toBeGreaterThan(0);
+ expect(storeSource.slice(offlineStart, offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');
+ expect(storeSource.slice(offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');
+ // []→[] 的权威快照必须能通知出去,否则消费方永远等不到清理时机。
+ expect(storeSource).toContain('if (streamingChanged || authorityChanged) emit();');
+ });
+
+ it('translates the collapse affordances in every locale', async () => {
+ const previous = i18n.language;
+ try {
+ for (const locale of ['zh-CN', 'en', 'ja', 'ko']) {
+ await i18n.changeLanguage(locale);
+ for (const key of [
+ 'interaction.panel.collapse',
+ 'interaction.panel.collapsePendingCard',
+ 'interaction.panel.collapsedHint',
+ ]) {
+ expect(i18n.t(key), `${locale} ${key}`).not.toBe(key);
+ }
+ const expanded = i18n.t('interaction.panel.expandPendingCard', { title: 'Fixture question' });
+ expect(expanded, `${locale} expandPendingCard`).toContain('Fixture question');
+ }
+ } finally {
+ await i18n.changeLanguage(previous);
+ }
+
+ for (const lang of ['zh-CN', 'en', 'ja', 'ko']) {
+ const bundle = JSON.parse(readFileSync(resolve(process.cwd(), `src/i18n/locales/${lang}/interaction.json`), 'utf8'));
+ expect(bundle.panel?.expandPendingCard, `${lang}/panel.expandPendingCard`).toContain('{{title}}');
+ // 旧的问题卡专属文案随卡内收起一起下线,不留悬空 key。
+ expect(bundle.panel?.collapseQuestionCard, `${lang}/panel.collapseQuestionCard`).toBeUndefined();
+ expect(bundle.panel?.expandQuestionCard, `${lang}/panel.expandQuestionCard`).toBeUndefined();
+ }
});
it('serializes permission allow-once, deny, and session scoped suggestions', () => {
diff --git a/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.ts b/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.ts
new file mode 100644
index 0000000000..f2bab2dac1
--- /dev/null
+++ b/apps/mobile/src/__tests__/pendingInteractionCollapseStore.test.ts
@@ -0,0 +1,104 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ clearAllPendingInteractionCollapse,
+ getCollapsedPendingRequestIds,
+ prunePendingInteractionCollapse,
+ subscribeCollapsedPendingRequestIds,
+ togglePendingInteractionCollapse,
+} from '@/session/pendingInteractionCollapseStore';
+import type { PendingInteraction } from '@/session/types';
+
+const askCard = (requestId: string) => ({
+ request: { kind: 'ask_user_question', requestId, questions: [{ question: '还在等回答' }] },
+} as unknown as PendingInteraction);
+
+const AUTHORITATIVE = { authoritative: true } as const;
+const NOT_AUTHORITATIVE = { authoritative: false } as const;
+
+afterEach(() => {
+ clearAllPendingInteractionCollapse();
+});
+
+describe('pendingInteractionCollapseStore', () => {
+ it('keeps the collapse intent across page unmount and remount', () => {
+ // 「收起 → 离开任务(页面卸载) → 再进来」在 store 层就是「写入 → 重新读取」:
+ // 契约要求同一条仍在 pending 的请求依旧是收起的,不能因为页面重挂载又展开占满屏。
+ togglePendingInteractionCollapse('session-1', 'ask-1');
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual(['ask-1']);
+
+ // 重挂载后 pending 里这条还在(权威快照),prune 不得把它清掉。
+ prunePendingInteractionCollapse('session-1', [askCard('ask-1')], AUTHORITATIVE);
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual(['ask-1']);
+ });
+
+ it('drops the intent once an authoritative snapshot says the request is gone', () => {
+ togglePendingInteractionCollapse('session-1', 'ask-1');
+
+ // 非权威的空快照(离线清空投影 / 全量快照未到)不算终结,收起意图必须留着。
+ prunePendingInteractionCollapse('session-1', [], NOT_AUTHORITATIVE);
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual(['ask-1']);
+
+ // 权威快照确认已回答 / 撤销 → 清掉;此后重挂载不再是收起态。
+ prunePendingInteractionCollapse('session-1', [], AUTHORITATIVE);
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual([]);
+ // 清空后 key 应被回收,空快照走共享引用(useSyncExternalStore 用 Object.is 比较)。
+ expect(getCollapsedPendingRequestIds('session-1')).toBe(getCollapsedPendingRequestIds('session-2'));
+ });
+
+ it('isolates sessions so switching tasks never leaks the intent', () => {
+ togglePendingInteractionCollapse('session-1', 'ask-1');
+ expect(getCollapsedPendingRequestIds('session-2')).toEqual([]);
+
+ togglePendingInteractionCollapse('session-2', 'perm-2');
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual(['ask-1']);
+ expect(getCollapsedPendingRequestIds('session-2')).toEqual(['perm-2']);
+
+ // 一个会话的权威回收不得动到另一个会话。
+ prunePendingInteractionCollapse('session-1', [], AUTHORITATIVE);
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual([]);
+ expect(getCollapsedPendingRequestIds('session-2')).toEqual(['perm-2']);
+ });
+
+ it('toggles back and notifies subscribers only on real changes', () => {
+ let notifications = 0;
+ const unsubscribe = subscribeCollapsedPendingRequestIds(() => { notifications += 1; });
+ try {
+ togglePendingInteractionCollapse('session-1', 'ask-1');
+ expect(notifications).toBe(1);
+ // 再点一次 = 展开,记录移除。
+ togglePendingInteractionCollapse('session-1', 'ask-1');
+ expect(getCollapsedPendingRequestIds('session-1')).toEqual([]);
+ expect(notifications).toBe(2);
+
+ // 空集合上跑 prune 不产生写入,也就不该通知(否则 effect 每帧重入)。
+ prunePendingInteractionCollapse('session-1', [], AUTHORITATIVE);
+ expect(notifications).toBe(2);
+ // 无变化的 prune(该条仍在权威快照里)同样不通知。
+ togglePendingInteractionCollapse('session-1', 'ask-1');
+ expect(notifications).toBe(3);
+ prunePendingInteractionCollapse('session-1', [askCard('ask-1')], AUTHORITATIVE);
+ expect(notifications).toBe(3);
+ } finally {
+ unsubscribe();
+ }
+ });
+
+ it('bounds the number of tracked sessions', () => {
+ for (let i = 0; i < 40; i++) togglePendingInteractionCollapse(`session-${i}`, `ask-${i}`);
+ // 最旧的按插入序被淘汰,最近的保留 —— Map 不能随会话数无界增长。
+ expect(getCollapsedPendingRequestIds('session-0')).toEqual([]);
+ expect(getCollapsedPendingRequestIds('session-39')).toEqual(['ask-39']);
+ });
+
+ it('is owned by the store, not by session page component state', () => {
+ const sessionScreenSource = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+
+ // 页面组件不得再自持收起态:它会随「离开任务」卸载一起丢(#1493 review)。
+ expect(sessionScreenSource).toContain('useCollapsedPendingRequestIds(sessionId)');
+ expect(sessionScreenSource).toContain('prunePendingInteractionCollapse(sessionId, pending, {');
+ expect(sessionScreenSource).not.toContain('setCollapsedPendingRequestIds');
+ expect(sessionScreenSource).not.toContain('useState<readonly string[]>([])');
+ });
+});
diff --git a/apps/mobile/src/i18n/locales/en/interaction.json b/apps/mobile/src/i18n/locales/en/interaction.json
index 44e47c1e44..0cd624e64f 100644
--- a/apps/mobile/src/i18n/locales/en/interaction.json
+++ b/apps/mobile/src/i18n/locales/en/interaction.json
@@ -50,8 +50,10 @@
"askModeMulti": "Multi-select",
"askModeSingle": "Single select",
"askMetaCaption": "{{options}} · {{mode}} · Other answers allowed",
- "expandQuestionCard": "Expand question card",
- "collapseQuestionCard": "Collapse question card",
+ "collapse": "Collapse",
+ "collapsePendingCard": "Collapse the pending request to read your computer's output first",
+ "expandPendingCard": "Expand the pending request to answer: {{title}}",
+ "collapsedHint": "Tap to answer",
"selectAnswer": "Select answer {{label}}",
"submittingHint": "Sending the decision to your computer. Don't submit again.",
"customAnswerInputAccessibility": "Enter a custom answer",
diff --git a/apps/mobile/src/i18n/locales/ja/interaction.json b/apps/mobile/src/i18n/locales/ja/interaction.json
index da2f87da63..c6b837d439 100644
--- a/apps/mobile/src/i18n/locales/ja/interaction.json
+++ b/apps/mobile/src/i18n/locales/ja/interaction.json
@@ -50,8 +50,10 @@
"askModeMulti": "複数選択",
"askModeSingle": "単一選択",
"askMetaCaption": "{{options}} · {{mode}} · その他の回答も可",
- "expandQuestionCard": "質問カードを展開",
- "collapseQuestionCard": "質問カードを折りたたむ",
+ "collapse": "折りたたむ",
+ "collapsePendingCard": "保留中のリクエストを折りたたみ、先にパソコンの出力を確認",
+ "expandPendingCard": "保留中のリクエストを展開して回答:{{title}}",
+ "collapsedHint": "タップして回答",
"selectAnswer": "回答 {{label}} を選択",
"submittingHint": "決定をパソコンに送信中です。重複して送信しないでください。",
"customAnswerInputAccessibility": "カスタム回答を入力",
diff --git a/apps/mobile/src/i18n/locales/ko/interaction.json b/apps/mobile/src/i18n/locales/ko/interaction.json
index e8aaf26ac2..979debdaf3 100644
--- a/apps/mobile/src/i18n/locales/ko/interaction.json
+++ b/apps/mobile/src/i18n/locales/ko/interaction.json
@@ -50,8 +50,10 @@
"askModeMulti": "다중 선택",
"askModeSingle": "단일 선택",
"askMetaCaption": "{{options}} · {{mode}} · 다른 답변 가능",
- "expandQuestionCard": "질문 카드 펼치기",
- "collapseQuestionCard": "질문 카드 접기",
+ "collapse": "접기",
+ "collapsePendingCard": "대기 중인 요청을 접고 컴퓨터의 출력을 먼저 확인",
+ "expandPendingCard": "대기 중인 요청을 펼쳐 답변하기: {{title}}",
+ "collapsedHint": "탭하여 답변",
"selectAnswer": "답변 {{label}} 선택",
"submittingHint": "결정을 컴퓨터로 전송 중입니다. 중복 제출하지 마세요.",
"customAnswerInputAccessibility": "사용자 지정 답변 입력",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/interaction.json b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
index 9b9f6a6e5c..01ac968f2c 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/interaction.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
@@ -50,8 +50,10 @@
"askModeMulti": "多选",
"askModeSingle": "单选",
"askMetaCaption": "{{options}} · {{mode}} · 支持其他回答",
- "expandQuestionCard": "展开问题卡片",
- "collapseQuestionCard": "收起问题卡片",
+ "collapse": "收起",
+ "collapsePendingCard": "收起待处理请求,先查看电脑端的输出",
+ "expandPendingCard": "展开待处理请求继续回答:{{title}}",
+ "collapsedHint": "点开回答",
"selectAnswer": "选择回答 {{label}}",
"submittingHint": "正在把决定回传到电脑端,请不要重复提交。",
"customAnswerInputAccessibility": "输入自定义回答",
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index d647f0ccc9..c8e827ef4c 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -35,9 +35,12 @@ import {
buildPluginSetupCancelDecision,
buildPlanReviewDecision,
buildRemotePluginSetupPresentation,
+ buildCollapsedPendingInteractionPresentation,
+ canCollapsePendingInteraction,
canStartInteractionResolve,
encodeMultiSelectAnswer,
resolveInteractionResilient,
+ isPendingInteractionCollapsed,
isPlanReviewResolveBusy,
interactionKind,
normalizeAskQuestions,
@@ -74,6 +77,9 @@ import { contentToPreview } from '@/utils/contentPreview';
const PLAN_PREVIEW_LINE_HEIGHT = 20;
+/** 未受控(没接会话页收起态)时的空集合,常量化避免每帧换引用。 */
+const EMPTY_COLLAPSED_REQUEST_IDS: readonly string[] = [];
+
/**
* 有本地化文案的 interaction kind 白名单(与 interaction.json 的 `kinds` 键一一对应)。
*
@@ -98,6 +104,7 @@ type RestorablePlanViewerState = Exclude<MobilePlanViewerState, 'minimized'>;
export function InteractionPanel({
safeAreaBottomInset = 0,
+ collapse,
deviceId,
fillAvailableHeight = false,
sessionId,
@@ -110,6 +117,18 @@ export function InteractionPanel({
readOnlyReason,
}: {
safeAreaBottomInset?: number;
+ /**
+ * 收起能力:整组给或整组不给。
+ *
+ * 合成一个对象而不是两个可选 prop —— 只传状态不传回调会得到一个「显示为收起但点不开」
+ * 的死界面,类型上就该表达不出来(#1493 review)。不传 = 该放置点不提供收起(如贴在
+ * 输入框上方的 plugin_setup 卡)。
+ */
+ collapse?: {
+ /** 已收起的 requestId(会话页持有,见 interactionModel 的收起态注释)。 */
+ requestIds: readonly string[];
+ onToggle(requestId: string): void;
+ };
deviceId: string;
fillAvailableHeight?: boolean;
sessionId: string;
@@ -122,6 +141,7 @@ export function InteractionPanel({
onError(message: string | null): void;
}) {
const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
const { t } = useTranslation();
const sortedInteractions = useMemo(
() => sortPendingInteractions(interactions),
@@ -217,9 +237,62 @@ export function InteractionPanel({
</View>
);
}
+ // 收起 = 「这条我先不答,让我看电脑端的输出」。整块 surface 只留一条 bar:再留着
+ // 队列头就还是两层结构,消息流照样看不到几行。
+ // 收起入口只给本端能终结的卡:队列里混着 plugin_setup / issue_confirm 时用户能切过去,
+ // 那类卡答不了,挂「点开回答」是错的语义(#1493 review)。
+ const canToggleCollapsed = !!collapse
+ && !!activeRequestIdForPresentation
+ && canCollapsePendingInteraction(activeInteraction);
+ const collapsed = canToggleCollapsed && isPendingInteractionCollapsed(
+ collapse?.requestIds ?? EMPTY_COLLAPSED_REQUEST_IDS,
+ activeRequestIdForPresentation,
+ );
+ const toggleCollapsed = () => {
+ if (!activeRequestIdForPresentation) return;
+ collapse?.onToggle(activeRequestIdForPresentation);
+ };
+ // 摘要与读屏标签都跟随用户翻到的那一问(进度从 askUserDraft 现取),由纯函数产出
+ // 以便直接断言读屏行为。
+ const { accessibilityLabel: collapsedBarLabel, summaryText } = buildCollapsedPendingInteractionPresentation({
+ item: activeInteraction,
+ queueTitle: activeQueuePresentation.title,
+ requestId: activeRequestIdForPresentation,
+ });
+ if (collapsed) {
+ return (
+ <View style={[styles.root, rootLayoutStyle]} testID="interaction.panel">
+ <InteractionTouchButton
+ accessibilityLabel={collapsedBarLabel}
+ onPress={toggleCollapsed}
+ style={[styles.card, styles.collapsedInteractionBar, { paddingHorizontal: touchLayout.cardPadding }]}
+ testID="interaction.panel.collapsedBar"
+ >
+ <View style={styles.collapsedInteractionText}>
+ <Text style={styles.collapsedInteractionLabel}>{activeQueuePresentation.title}</Text>
+ {summaryText ? (
+ <Text numberOfLines={1} style={styles.collapsedInteractionTitle}>{summaryText}</Text>
+ ) : null}
+ </View>
+ <View style={styles.compactHeaderActions}>
+ {activeQueuePresentation.totalCount > 1 ? (
+ <Text style={styles.collapsedInteractionMeta} testID="interaction.panel.collapsedCount">
+ {Math.max(0, selectedQueueIndex) + 1}/{activeQueuePresentation.totalCount}
+ </Text>
+ ) : null}
+ <Text style={styles.collapsedInteractionMeta}>{t('interaction.panel.collapsedHint')}</Text>
+ <View style={styles.iconControl}>
+ <Plus color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </View>
+ </View>
+ </InteractionTouchButton>
+ </View>
+ );
+ }
return (
<View style={[styles.root, fillAvailableHeight && styles.rootFill, rootLayoutStyle]} testID="interaction.panel">
<PendingTaskHeader
+ onCollapse={canToggleCollapsed ? toggleCollapsed : undefined}
onSelectRequest={setActiveRequestId}
presentation={activeQueuePresentation}
touchLayout={touchLayout}
@@ -277,15 +350,18 @@ function resolveButtonLayoutStyle(
}
function PendingTaskHeader({
+ onCollapse,
onSelectRequest,
presentation,
touchLayout,
}: {
+ onCollapse?(): void;
onSelectRequest(requestId: string | null): void;
presentation: ReturnType<typeof buildPendingInteractionQueuePresentation>;
touchLayout: InteractionTouchLayout;
}) {
const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
const { t } = useTranslation();
const activeIndex = Math.max(0, presentation.items.findIndex((item) => item.active));
const nextItem = presentation.items.length > 1
@@ -319,6 +395,22 @@ function PendingTaskHeader({
</Text>
</InteractionTouchButton>
) : null}
+ {/*
+ 收起入口带可见文字:此前它是卡片里一个没有标签的「—」图标,用户看不出那是
+ 「先不答、让我看输出」的出口(线上反馈)。放在队列头则三类卡通用,不再各自
+ 实现一套收起。
+ */}
+ {onCollapse ? (
+ <InteractionTouchButton
+ accessibilityLabel={t('interaction.panel.collapsePendingCard')}
+ onPress={onCollapse}
+ style={[styles.taskCollapseButton, { minHeight: touchLayout.taskCountPillMinHeight }]}
+ testID="interaction.panel.collapseButton"
+ >
+ <Minus color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ <Text style={styles.taskCollapseText}>{t('interaction.panel.collapse')}</Text>
+ </InteractionTouchButton>
+ ) : null}
</View>
</View>
);
@@ -653,7 +745,6 @@ function AskUserQuestionCard({
const [selectedLabels, setSelectedLabels] = useState<Set<string>>(new Set());
const [customInput, setCustomInput] = useState('');
const [showCustomInput, setShowCustomInput] = useState(false);
- const [collapsed, setCollapsed] = useState(false);
const presentation = useMemo(() => buildAskQuestionReviewPresentation({
currentIndex,
questions,
@@ -669,7 +760,6 @@ function AskUserQuestionCard({
setSelectedLabels(new Set(draft?.selectedLabels ?? []));
setCustomInput(draft?.customInput ?? '');
setShowCustomInput(draft?.showCustomInput ?? false);
- setCollapsed(false);
}, [questions.length, requestId]);
useEffect(() => {
@@ -786,47 +876,14 @@ function AskUserQuestionCard({
});
};
- if (collapsed) {
- return (
- <InteractionTouchButton
- accessibilityLabel={t('interaction.panel.expandQuestionCard')}
- onPress={() => setCollapsed(false)}
- style={[cardStyle(styles, touchLayout), styles.collapsedInteractionBar]}
- testID="interaction.ask.collapsedCard"
- >
- <View style={styles.collapsedInteractionText}>
- <Text style={styles.collapsedInteractionLabel}>{t('interaction.panel.awaitingAnswer')}</Text>
- <Text numberOfLines={1} style={styles.collapsedInteractionTitle}>{presentation.title}</Text>
- </View>
- <View style={styles.compactHeaderActions}>
- {questions.length > 1 ? (
- <Text style={styles.collapsedInteractionMeta}>
- {currentIndex + 1} / {questions.length}
- </Text>
- ) : null}
- <View style={styles.iconControl}>
- <Plus color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- </View>
- </View>
- </InteractionTouchButton>
- );
- }
-
return (
<View style={cardStyle(styles, touchLayout)} testID="interaction.ask.card">
+ {/* 收起入口统一在队列头(PendingTaskHeader),卡内不再自持一份 collapsed state:
+ 两套状态时页面级那份被卡片 key 变化冲掉,收起会自己弹回来。 */}
<View style={styles.compactCardHeader}>
<Text style={styles.askHeaderKind}>{t('interaction.panel.awaitingAnswer')}</Text>
<View style={styles.compactHeaderActions}>
<Text style={styles.pageText}>{presentation.pageLabel}</Text>
- <InteractionTouchButton
- accessibilityLabel={t('interaction.panel.collapseQuestionCard')}
- busy={busy}
- onPress={() => setCollapsed(true)}
- style={styles.iconControl}
- testID="interaction.ask.collapseButton"
- >
- <Minus color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- </InteractionTouchButton>
</View>
</View>
<Text style={styles.askQuestion} testID="interaction.ask.question">{presentation.title}</Text>
@@ -1682,6 +1739,23 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
fontSize: typeScale.caption,
fontWeight: fontWeight.medium,
},
+ taskCollapseButton: {
+ alignItems: 'center',
+ borderColor: colors.border,
+ borderRadius: radius.pill,
+ borderWidth: StyleSheet.hairlineWidth,
+ flexDirection: 'row',
+ flexShrink: 0,
+ gap: spacing.xs,
+ justifyContent: 'center',
+ minHeight: 44,
+ paddingHorizontal: spacing.md,
+ },
+ taskCollapseText: {
+ color: colors.textSecondary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ },
card: {
backgroundColor: colors.surfaceElevated,
borderColor: colors.border,
diff --git a/apps/mobile/src/session/interactionModel.ts b/apps/mobile/src/session/interactionModel.ts
index 9f6c072cc0..072bec0816 100644
--- a/apps/mobile/src/session/interactionModel.ts
+++ b/apps/mobile/src/session/interactionModel.ts
@@ -1,10 +1,17 @@
import {
+ interactionKind as sharedInteractionKind,
+ normalizeAskQuestions as sharedNormalizeAskQuestions,
+ permissionToolName as sharedPermissionToolName,
+ planReviewFilePath as sharedPlanReviewFilePath,
+ planReviewPlan as sharedPlanReviewPlan,
readRequestId as sharedReadRequestId,
+ remoteInteractionHandling as sharedRemoteInteractionHandling,
selectActivePendingInteraction as sharedSelectActivePendingInteraction,
type PendingInteractionLike,
type PermissionReviewPresentation,
} from '@cindy/maker-shared/interaction';
import { i18n } from '@/i18n';
+import { readAskUserDraft } from '@/session/interactionDraftStore';
export {
answerKey,
@@ -86,12 +93,164 @@ export function selectPendingInteractionByRequestId<T extends PendingInteraction
export function shouldUseFullHeightPendingInteractionSurface(input: {
activeKind: string | null;
+ collapsed?: boolean;
planViewerState: string;
}): boolean {
+ // 收起时不能再吃固定高度:那正是「收起后仍然霸屏」的成因,收起的全部意义就是把
+ // 屏幕还给消息流。
+ if (input.collapsed) return false;
return input.activeKind === 'plan_review'
&& (input.planViewerState === 'expanded' || input.planViewerState === 'edit');
}
+// ─── 待处理卡收起态 ──────────────────────────────────────────────────────────
+
+/**
+ * 收起态按 requestId 记录、且必须由**会话页**持有。
+ *
+ * 曾经它是 AskUserQuestionCard 内部的 useState:卡片 key 变化(队列刷新 / 切卡)、
+ * 页面重挂载都会把状态冲掉,用户刚收起来看输出、下一帧卡又弹回来占满屏。状态提到
+ * 页面级后,收起是「这条请求我先不答」的稳定意图,只有该请求被终结才失效。
+ */
+export function isPendingInteractionCollapsed(
+ collapsedRequestIds: readonly string[],
+ requestId: string | null | undefined,
+): boolean {
+ if (!requestId) return false;
+ return collapsedRequestIds.includes(requestId);
+}
+
+export function togglePendingInteractionCollapsed(
+ collapsedRequestIds: readonly string[],
+ requestId: string,
+): string[] {
+ if (collapsedRequestIds.includes(requestId)) {
+ return collapsedRequestIds.filter((id) => id !== requestId);
+ }
+ return [...collapsedRequestIds, requestId];
+}
+
+/** 收起记录的保留上限:非权威窗口里不清时靠它保持有界(见下方 prune 注释)。 */
+const COLLAPSED_REQUEST_ID_LIMIT = 8;
+
+/**
+ * 丢掉已经不在 pending 集合里的 requestId(卡被回答 / 被撤)。
+ *
+ * **清理的前提是这份 pending 列表权威**(`authoritative`,来自被控端的一次全量快照,
+ * 见 remoteSessionStore 的 pendingInteractionsAuthoritative)。空列表有两种来源:
+ * - 权威的空 = 被控端确认全都处理完了 → **要清**,否则最后一条收起记录永远留着;
+ * - 非权威的空 = `markDeviceOffline` 按设计清掉了这份投影(它依赖实时连接),切网 /
+ * 进地铁都会让 pending 瞬时归零 → **不能清**,否则重连后被控端把同一张卡灌回来,
+ * 它又以展开态占满屏,正是本 PR 要治的病换条路径复发(#1493 review)。
+ *
+ * 判据只能是这个显式状态,不能退化成看全局 relay status:目标设备 offline 时 relay
+ * 仍可能 online。
+ *
+ * 非权威窗口里不清,集合靠 COLLAPSED_REQUEST_ID_LIMIT 截断最旧的保持有界;权威快照
+ * 一到就会收敛掉真正已终结的条目。
+ *
+ * 无变化时**返回原数组**:调用方在 effect 里按 pending 变化 prune,返回新数组会
+ * 让 setState 每帧都换引用 → 依赖它的 effect 无限重入。
+ */
+export function prunePendingInteractionCollapsed<T extends PendingInteractionLike>(
+ collapsedRequestIds: readonly string[],
+ pending: readonly T[],
+ options: { authoritative: boolean },
+): readonly string[] {
+ if (collapsedRequestIds.length === 0) return collapsedRequestIds;
+ const alive = new Set(
+ pending.map((item) => sharedReadRequestId(item)).filter((id): id is string => !!id),
+ );
+ // 非权威时**一律不清**,连非空列表也不清:重连后可能先到一条 push 增量
+ //(applyInteractionRequest)、全量快照还没来,那份列表只含增量那张卡,按它过滤会把
+ // 其它仍在等待的请求的收起记录误清 —— 与离线空列表是同一类误判。
+ const next = options.authoritative
+ ? collapsedRequestIds.filter((id) => alive.has(id))
+ : collapsedRequestIds;
+ const bounded = next.length > COLLAPSED_REQUEST_ID_LIMIT
+ ? next.slice(next.length - COLLAPSED_REQUEST_ID_LIMIT)
+ : next;
+ return bounded.length === collapsedRequestIds.length ? collapsedRequestIds : bounded;
+}
+
+/**
+ * 收起条上那行「具体在等什么」。语言无关(用户内容 / 工具名),不引入共享层中文直出。
+ *
+ * `questionIndex` 是多问提问卡当前翻到第几问(来自 askUserDraft)。缺省 0;传当前进度
+ * 才不会出现「收起条写第一问、展开后停在第三问」的错位(#1493 review)。
+ */
+export function pendingInteractionSummaryText(
+ item: PendingInteractionLike,
+ questionIndex = 0,
+): string | null {
+ const kind = sharedInteractionKind(item);
+ if (kind === 'ask_user_question') {
+ const questions = sharedNormalizeAskQuestions(item.request.questions);
+ if (questions.length === 0) return null;
+ const index = Number.isInteger(questionIndex)
+ ? Math.min(Math.max(questionIndex, 0), questions.length - 1)
+ : 0;
+ return firstLinePreview(questions[index]?.question);
+ }
+ if (kind === 'permission') {
+ return firstLinePreview(sharedPermissionToolName(item.request));
+ }
+ if (kind === 'plan_review') {
+ return firstLinePreview(sharedPlanReviewPlan(item.request))
+ ?? firstLinePreview(sharedPlanReviewFilePath(item.request));
+ }
+ return null;
+}
+
+/**
+ * 收起条的呈现(摘要 + 读屏标签)。
+ *
+ * 做成一个纯函数是为了让读屏行为可被直接断言:标签必须跟随用户翻到的那一问,而
+ * 「进入第二问后 label 用第二问」这件事光看渲染代码断言不出来(#1493 review)。
+ * 进度从 askUserDraft 现取(卡内翻页时同步保存),所以传 requestId 即可。
+ */
+export function buildCollapsedPendingInteractionPresentation(input: {
+ item: PendingInteractionLike;
+ queueTitle: string;
+ requestId: string | null | undefined;
+}): { accessibilityLabel: string; summaryText: string | null } {
+ const questionIndex = input.requestId
+ ? readAskUserDraft(input.requestId)?.currentIndex ?? 0
+ : 0;
+ const summaryText = pendingInteractionSummaryText(input.item, questionIndex);
+ return {
+ accessibilityLabel: i18n.t('interaction.panel.expandPendingCard', {
+ title: summaryText ?? input.queueTitle,
+ }),
+ summaryText,
+ };
+}
+
+/**
+ * 这张卡能不能给收起入口。
+ *
+ * 只有本端能终结的卡才可以:队列里混着 plugin_setup / issue_confirm 时,用户能从队列头
+ * 切过去,那类卡在手机上答不了(只能取消或回电脑端)。给它挂上「点开回答」的收起条,
+ * 既是错的语义,也绕过了「贴输入框上方那种放置点不给收起」的保护(#1493 review)。
+ */
+export function canCollapsePendingInteraction(item: PendingInteractionLike | null | undefined): boolean {
+ return !!item && sharedRemoteInteractionHandling(item) === 'resolvable';
+}
+
+const SUMMARY_PREVIEW_MAX_LENGTH = 80;
+
+function firstLinePreview(value: string | null | undefined): string | null {
+ if (typeof value !== 'string') return null;
+ const line = value
+ .split('\n')
+ .map((entry) => entry.replace(/^\s*#{1,6}\s*/, '').trim())
+ .find((entry) => entry.length > 0);
+ if (!line) return null;
+ return line.length > SUMMARY_PREVIEW_MAX_LENGTH
+ ? `${line.slice(0, SUMMARY_PREVIEW_MAX_LENGTH - 1)}…`
+ : line;
+}
+
export function isPlanReviewResolveBusy(input: { busy: boolean }): boolean {
return input.busy;
}
diff --git a/apps/mobile/src/session/pendingInteractionCollapseStore.ts b/apps/mobile/src/session/pendingInteractionCollapseStore.ts
new file mode 100644
index 0000000000..ffe5aeb8ee
--- /dev/null
+++ b/apps/mobile/src/session/pendingInteractionCollapseStore.ts
@@ -0,0 +1,108 @@
+import { useSyncExternalStore } from 'react';
+import type { PendingInteractionLike } from '@cindy/maker-shared/interaction';
+import {
+ prunePendingInteractionCollapsed,
+ togglePendingInteractionCollapsed,
+} from '@/session/interactionModel';
+
+/**
+ * 「这条待处理请求我先不答」的收起意图,按 sessionId 存,活在模块级。
+ *
+ * 为什么不是页面组件的 useState:契约是「只有该请求被回答 / 撤销才失效」。放在页面里
+ * 时,离开任务导致页面卸载、再进来同一条仍在 pending 的请求会重新展开占满屏
+ * (#1493 review)——这与最早那版「卡片内部 useState 被 key 变化冲掉」是同一个病,
+ * 只是作用域大了一层。
+ *
+ * 也不放进 remoteSessionStore:那是被控端会话的镜像(远端事实),收起是本端的 UI 意图,
+ * 混进去会让「快照回收」之类的语义互相牵连。
+ *
+ * store 是唯一真相源、消费方直接 useSyncExternalStore 订阅,不做 useState 镜像:镜像
+ * 需要「切 session 时重新装载 + 变化时写回」两个 effect,而它们同帧执行会用新 sessionId
+ * 写回旧 state,把上一个会话的收起意图串到新会话。
+ */
+const collapsedBySession = new Map<string, readonly string[]>();
+const listeners = new Set<() => void>();
+
+/**
+ * 空快照必须是同一个引用:useSyncExternalStore 用 Object.is 比较,每次新建 []
+ * 会让所有订阅者每帧重渲染。
+ */
+const EMPTY: readonly string[] = [];
+
+/**
+ * 最多保留多少个会话的收起意图。
+ *
+ * 绝大多数会话的卡最终会被回答 → 权威快照 prune 到空 → key 自然删除(见 write)。
+ * 只有「收起后一直不答、又离开会话」会留下残条,这里按插入序淘汰最旧的,保证 Map 有界。
+ */
+const MAX_TRACKED_SESSIONS = 32;
+
+export function getCollapsedPendingRequestIds(sessionId: string): readonly string[] {
+ if (!sessionId) return EMPTY;
+ return collapsedBySession.get(sessionId) ?? EMPTY;
+}
+
+export function subscribeCollapsedPendingRequestIds(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export function useCollapsedPendingRequestIds(sessionId: string): readonly string[] {
+ return useSyncExternalStore(
+ subscribeCollapsedPendingRequestIds,
+ () => getCollapsedPendingRequestIds(sessionId),
+ );
+}
+
+/** 切换这条请求的收起态。 */
+export function togglePendingInteractionCollapse(sessionId: string, requestId: string): void {
+ if (!sessionId || !requestId) return;
+ write(sessionId, togglePendingInteractionCollapsed(getCollapsedPendingRequestIds(sessionId), requestId));
+}
+
+/**
+ * 按 pending 快照回收收起记录。`authoritative` 的含义见
+ * prunePendingInteractionCollapsed:非权威快照(离线清空投影 / 全量快照未到)不清任何东西。
+ */
+export function prunePendingInteractionCollapse<T extends PendingInteractionLike>(
+ sessionId: string,
+ pending: readonly T[],
+ options: { authoritative: boolean },
+): void {
+ if (!sessionId) return;
+ const current = getCollapsedPendingRequestIds(sessionId);
+ if (current.length === 0) return;
+ write(sessionId, prunePendingInteractionCollapsed(current, pending, options));
+}
+
+/** 仅测试用:清空全部会话的收起意图。 */
+export function clearAllPendingInteractionCollapse(): void {
+ if (collapsedBySession.size === 0) return;
+ collapsedBySession.clear();
+ emit();
+}
+
+function write(sessionId: string, next: readonly string[]): void {
+ const current = collapsedBySession.get(sessionId) ?? EMPTY;
+ if (current === next) return;
+ if (next.length === 0) {
+ if (!collapsedBySession.delete(sessionId)) return;
+ emit();
+ return;
+ }
+ collapsedBySession.set(sessionId, next);
+ // 插入序淘汰:Map 的迭代顺序就是插入顺序,重写同一个 key 不会把它移到末尾,所以
+ // 这里淘汰的是「最久没有新增收起记录」的会话。
+ while (collapsedBySession.size > MAX_TRACKED_SESSIONS) {
+ const oldest = collapsedBySession.keys().next();
+ if (oldest.done) break;
+ collapsedBySession.delete(oldest.value);
+ }
+ emit();
+}
+
+function emit(): void {
+ for (const listener of [...listeners]) listener();
+}
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 30a8130f26..2b5b0b535d 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -122,6 +122,18 @@ const messages = new Map<string, RemoteMessage[]>();
// overwrite a newer live state with the first stale 0/N snapshot.
const livePlanSnapshots = new Map<string, Map<string, LivePlanSnapshot>>();
const pendingInteractions = new Map<string, PendingInteraction[]>();
+/**
+ * 这个会话的 pending 列表当前是不是**权威**的(来自被控端的一次全量快照)。
+ *
+ * 空列表有两种来源,消费方光看 `getPendingInteractions()` 分辨不了:
+ * - 权威的空:被控端确认所有请求都已回答 / 撤销;
+ * - 非权威的空:`markDeviceOffline` / `removeDevice` 按设计清掉了这份投影(它依赖
+ * 实时连接),此刻我们其实不知道被控端还在等什么。
+ *
+ * 凡是「空快照才能做的清理」都必须先问这里,否则短暂离线会被误判成「都处理完了」。
+ * 不能退化成看全局 relay status:目标设备 offline 时 relay 仍可能 online(#1493 review)。
+ */
+const pendingInteractionsAuthoritative = new Set<string>();
/**
* 乐观 resolve 在途抑制集合:交互卡批准 / 拒绝已在本地乐观撤卡、被控端还没有
* 确认的 requestId。这个窗口里权威流(全量快照 setPendingInteractions / push
@@ -1788,8 +1800,13 @@ export const remoteSessionStore = {
const streamingChanged = options.finalizeStreaming === true && next.length > 0
? flushAndFinalizeRemoteStreamingMessages(sessionId)
: false;
+ // 权威性先落:哪怕内容一字未变(典型是重连后的 [] → []),消费方也必须知道
+ // 「这份空列表已经被被控端确认过」——否则离线期收起态的清理永远等不到时机
+ // (#1493 review)。因此 authority 的翻转本身就是一次需要通知的变化。
+ const authorityChanged = !pendingInteractionsAuthoritative.has(sessionId);
+ pendingInteractionsAuthoritative.add(sessionId);
if (deepValueEqual(pendingInteractions.get(sessionId) ?? emptyPendingInteractions, next)) {
- if (streamingChanged) emit();
+ if (streamingChanged || authorityChanged) emit();
return;
}
pendingInteractions.set(sessionId, next);
@@ -2489,6 +2506,8 @@ export const remoteSessionStore = {
changed = livePlanSnapshots.delete(sessionId) || changed;
changed = pendingRefreshSessions.delete(sessionId) || changed;
changed = pendingInteractions.delete(sessionId) || changed;
+ // 投影没了,这份(空)列表就不再权威:重连拿到全量快照前不许据此做清理。
+ changed = pendingInteractionsAuthoritative.delete(sessionId) || changed;
changed = inputProjections.delete(sessionId) || changed;
changed = sessionLiveActivity.delete(sessionId) || changed;
changed = sessionGoalStatus.delete(sessionId) || changed;
@@ -2516,6 +2535,7 @@ export const remoteSessionStore = {
messages.delete(sessionId);
livePlanSnapshots.delete(sessionId);
pendingInteractions.delete(sessionId);
+ pendingInteractionsAuthoritative.delete(sessionId);
inputProjections.delete(sessionId);
sessionLiveActivity.delete(sessionId);
sessionRunning.delete(sessionId);
@@ -2554,6 +2574,7 @@ export const remoteSessionStore = {
messages.clear();
livePlanSnapshots.clear();
pendingInteractions.clear();
+ pendingInteractionsAuthoritative.clear();
inFlightInteractionResolves.clear();
confirmedInteractionDismissals.clear();
interactionRevisionFloors.clear();
@@ -2646,6 +2667,14 @@ export const remoteSessionStore = {
return pendingInteractions.get(sessionId) ?? emptyPendingInteractions;
},
+ /**
+ * pending 列表当前是否权威(见 pendingInteractionsAuthoritative 的注释)。
+ * 空列表要用来做清理判断时必须先问这里。
+ */
+ hasAuthoritativePendingInteractions(sessionId: string): boolean {
+ return pendingInteractionsAuthoritative.has(sessionId);
+ },
+
getInputProjection(sessionId: string): InputProjection {
return inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION;
},
@@ -3058,6 +3087,13 @@ export function useSessionPendingInteractions(sessionId: string): PendingInterac
);
}
+export function useSessionPendingInteractionsAuthoritative(sessionId: string): boolean {
+ return useSyncExternalStore(
+ remoteSessionStore.subscribe,
+ () => remoteSessionStore.hasAuthoritativePendingInteractions(sessionId),
+ );
+}
+
export function useSessionInputProjection(sessionId: string): InputProjection {
return useSyncExternalStore(
remoteSessionStore.subscribe,