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): plugin_setup 改为完整只读状态卡 (#540)

Dash8bb72510002a
diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.ts
index 995202045a..b2b3e344fb 100644
--- a/apps/mobile/src/__tests__/interactionModel.test.ts
+++ b/apps/mobile/src/__tests__/interactionModel.test.ts
@@ -26,6 +26,9 @@ import {
normalizeAskQuestions,
pendingInteractionsBlockRemoteComposer,
remoteInteractionHandling,
+ REMOTE_PLUGIN_SETUP_ACTION_KINDS,
+ REMOTE_PLUGIN_SETUP_ERROR_CODES,
+ REMOTE_PLUGIN_SETUP_PHASES,
permissionRiskSummary,
permissionTitle,
selectActivePendingInteraction,
@@ -214,9 +217,9 @@ describe('interactionModel', () => {
// 取消出口:没有出口 + 卡接管输入框 = 会话锁死(线上已复现)。
expect(interactionPanelSource).toContain("if (kind === 'plugin_setup')");
expect(interactionPanelSource).toContain('buildPluginSetupCancelDecision(item.request)');
- expect(interactionPanelSource).toContain("t('interaction.panel.pluginSetupDesktopOnly')");
expect(interactionPanelSource).toContain('interaction.unsupported.cancelButton');
- // 摘要合并成一段再限行:每行各自 numberOfLines 会把总高度放大成 6 × 行数。
+ // 未知 kind 仍回退到 UnsupportedCard 的合并摘要:每行各自 numberOfLines 会把
+ // 总高度放大成 6 × 行数。
expect(interactionPanelSource).toContain("const summaryText = (summaryLines ?? [contentToPreview(request)])");
expect(interactionPanelSource).not.toContain('lines.map((line, index)');
// 取消由被控端按 expectedRevision 裁决,不能乐观撤卡(撤了可能其实没取消);
@@ -239,6 +242,61 @@ describe('interactionModel', () => {
})).toBe(true);
});
+ it('renders plugin setup as a full read-only status card, not a flat summary', () => {
+ const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');
+
+ // 手机端做不了配置动作,这张卡的全部价值在「看懂」:哪个插件、卡在哪一步、
+ // 为什么失败、回电脑端要做什么。退回扁平摘要就等于把这些信息又丢了。
+ expect(interactionPanelSource).toContain('function PluginSetupCard(');
+ expect(interactionPanelSource).toContain('buildRemotePluginSetupPresentation(item.request)');
+ expect(interactionPanelSource).not.toContain('pluginSetupSummaryLines');
+ expect(interactionPanelSource).toContain('interaction.pluginSetup.phase.${step.phase}');
+ expect(interactionPanelSource).toContain('interaction.pluginSetup.error.${step.errorCode}');
+ expect(interactionPanelSource).toContain('interaction.pluginSetup.action.${step.actionKind}');
+ // any_of 组要提示「任选其一」,否则用户以为每一步都得做。
+ expect(interactionPanelSource).toContain("t('interaction.pluginSetup.chooseOne')");
+ // 已 settle 的收尾帧不该再引导用户「去电脑端完成」。
+ expect(interactionPanelSource).toContain('presentation.terminal ? null');
+ // 状态色只用两个语义色 + 灰阶(mobile-design-guide §1)。
+ expect(interactionPanelSource).toContain('colors.statusReady');
+ expect(interactionPanelSource).toContain('colors.statusAccent');
+ });
+
+ it('keeps every plugin setup phase, error code and action kind translated in all locales', async () => {
+ const previous = i18n.language;
+ try {
+ for (const locale of ['zh-CN', 'en', 'ja', 'ko']) {
+ await i18n.changeLanguage(locale);
+ for (const phase of REMOTE_PLUGIN_SETUP_PHASES) {
+ const key = `interaction.pluginSetup.phase.${phase}`;
+ expect(i18n.t(key), `${locale} ${key}`).not.toBe(key);
+ }
+ for (const code of REMOTE_PLUGIN_SETUP_ERROR_CODES) {
+ const key = `interaction.pluginSetup.error.${code}`;
+ expect(i18n.t(key), `${locale} ${key}`).not.toBe(key);
+ }
+ for (const kind of REMOTE_PLUGIN_SETUP_ACTION_KINDS) {
+ // inline_form 走带字段名的专属文案,不在 action 目录里。
+ if (kind === 'inline_form') continue;
+ const key = `interaction.pluginSetup.action.${kind}`;
+ expect(i18n.t(key), `${locale} ${key}`).not.toBe(key);
+ }
+ for (const key of [
+ 'interaction.pluginSetup.completeOnDesktop',
+ 'interaction.pluginSetup.chooseOne',
+ 'interaction.pluginSetup.progress',
+ 'interaction.pluginSetup.desktopActionHint',
+ 'interaction.pluginSetup.inlineFormAction',
+ 'interaction.pluginSetup.inlineFormActionGeneric',
+ ]) {
+ expect(i18n.t(key), `${locale} ${key}`).not.toBe(key);
+ }
+ }
+ } finally {
+ await i18n.changeLanguage(previous);
+ }
+ });
+
it('localizes queue titles and kind labels instead of rendering the shared Chinese defaults', () => {
const interactionPanelSource = readFileSync(resolve(process.cwd(), 'src/session/InteractionPanel.tsx'), 'utf8');
diff --git a/apps/mobile/src/i18n/locales/en/interaction.json b/apps/mobile/src/i18n/locales/en/interaction.json
index abcacab601..3353028f1b 100644
--- a/apps/mobile/src/i18n/locales/en/interaction.json
+++ b/apps/mobile/src/i18n/locales/en/interaction.json
@@ -40,7 +40,6 @@
"unsupportedType": "This remote interaction type isn't supported on mobile yet.",
"unsupportedKind": "Unsupported",
"desktopOnlyKind": "On Computer",
- "pluginSetupDesktopOnly": "This plugin setup has to be completed on your computer.",
"cancelRequest": "Cancel This Request",
"cancelRequestAccessibility": "Cancel this remote request",
"awaitingAnswer": "Awaiting answer",
@@ -179,5 +178,42 @@
"enable": "Turn on",
"icloudTimeout": "The photo is still downloading from iCloud and timed out. Check your network and retry.",
"photoNotReadable": "This photo can't be read right now (it may not have finished downloading from iCloud). Try again later."
+ },
+ "pluginSetup": {
+ "completeOnDesktop": "Complete this setup on the controlled desktop. This card will update automatically.",
+ "chooseOne": "Choose one setup method",
+ "stepsHeading": "Setup steps",
+ "progress": "{{satisfied}}/{{total}} completed",
+ "desktopActionHint": "On your computer: {{action}}",
+ "phase": {
+ "pending": "Pending",
+ "action_running": "In progress…",
+ "waiting_external": "Waiting for authorization…",
+ "verifying": "Verifying…",
+ "satisfied": "Completed",
+ "failed": "Failed",
+ "cancelled": "Cancelled"
+ },
+ "error": {
+ "ACTION_FAILED": "Couldn't complete this setup action. Try again.",
+ "ACTION_STALE": "This setup changed. Choose the setup action again.",
+ "AUTH_CANCELLED": "Authorization was cancelled. Authorize the account again when ready.",
+ "AUTH_FAILED": "Couldn't authorize the account. Try again.",
+ "INLINE_INVALID": "This configuration is invalid. Check it and try again.",
+ "INLINE_UNAVAILABLE": "This Cindy version can't save this configuration in chat. Update Cindy and try again.",
+ "SAVE_FAILED": "Couldn't save this configuration. Try again.",
+ "WINDOW_CLOSED": "The window that started setup was closed. Return to the session and try again.",
+ "TARGET_UNAVAILABLE": "This plugin is disabled, uninstalled, or unavailable. Check the plugin and try again.",
+ "ASSESSMENT_FAILED": "Couldn't refresh the setup status. Try again.",
+ "TIMEOUT": "Setup timed out. Try again."
+ },
+ "action": {
+ "oauth_connect": "Authorize",
+ "open_plugin_settings": "Open settings",
+ "manage_connection": "Manage connections",
+ "open_client_settings": "Open model settings"
+ },
+ "inlineFormAction": "Enter {{label}} on your computer",
+ "inlineFormActionGeneric": "Enter one setting on your computer"
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/interaction.json b/apps/mobile/src/i18n/locales/ja/interaction.json
index 509e62e3be..72494a76c8 100644
--- a/apps/mobile/src/i18n/locales/ja/interaction.json
+++ b/apps/mobile/src/i18n/locales/ja/interaction.json
@@ -40,7 +40,6 @@
"unsupportedType": "このリモート操作タイプはモバイルではまだ対応していません。",
"unsupportedKind": "未対応",
"desktopOnlyKind": "パソコンで処理",
- "pluginSetupDesktopOnly": "このプラグインの設定はパソコンで行う必要があります。",
"cancelRequest": "このリクエストをキャンセル",
"cancelRequestAccessibility": "このリモートリクエストをキャンセル",
"awaitingAnswer": "回答待ち",
@@ -179,5 +178,42 @@
"enable": "オンにする",
"icloudTimeout": "写真がまだ iCloud からダウンロード中で、タイムアウトしました。ネットワークを確認して再試行してください。",
"photoNotReadable": "この写真は現在読み込めません(iCloud からのダウンロードが未完了の可能性があります)。後でもう一度お試しください。"
+ },
+ "pluginSetup": {
+ "completeOnDesktop": "操作対象のデスクトップで設定を完了してください。このカードは自動的に更新されます。",
+ "chooseOne": "設定方法を1つ選択してください",
+ "stepsHeading": "設定手順",
+ "progress": "{{satisfied}}/{{total}} 完了",
+ "desktopActionHint": "パソコンで{{action}}",
+ "phase": {
+ "pending": "設定待ち",
+ "action_running": "処理中…",
+ "waiting_external": "認証待ち…",
+ "verifying": "検証中…",
+ "satisfied": "完了",
+ "failed": "失敗",
+ "cancelled": "キャンセル済み"
+ },
+ "error": {
+ "ACTION_FAILED": "設定操作を完了できませんでした。もう一度お試しください。",
+ "ACTION_STALE": "設定内容が更新されました。設定操作を選び直してください。",
+ "AUTH_CANCELLED": "認証がキャンセルされました。必要に応じてもう一度認証してください。",
+ "AUTH_FAILED": "認証を完了できませんでした。もう一度お試しください。",
+ "INLINE_INVALID": "設定内容が無効です。内容を確認してもう一度お試しください。",
+ "INLINE_UNAVAILABLE": "このバージョンの Cindy ではチャット内でこの設定を保存できません。Cindy を更新してもう一度お試しください。",
+ "SAVE_FAILED": "設定を保存できませんでした。もう一度お試しください。",
+ "WINDOW_CLOSED": "設定を開始したウィンドウが閉じられました。セッションに戻ってもう一度お試しください。",
+ "TARGET_UNAVAILABLE": "プラグインが無効、アンインストール済み、または利用できません。プラグインの状態を確認してもう一度お試しください。",
+ "ASSESSMENT_FAILED": "設定状況を更新できませんでした。もう一度お試しください。",
+ "TIMEOUT": "設定の待機時間を超えました。もう一度お試しください。"
+ },
+ "action": {
+ "oauth_connect": "認証",
+ "open_plugin_settings": "設定を開く",
+ "manage_connection": "接続を管理",
+ "open_client_settings": "モデル設定を開く"
+ },
+ "inlineFormAction": "パソコンで{{label}}を入力",
+ "inlineFormActionGeneric": "パソコンで設定を入力"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/interaction.json b/apps/mobile/src/i18n/locales/ko/interaction.json
index 46374d0fbe..105d42cddb 100644
--- a/apps/mobile/src/i18n/locales/ko/interaction.json
+++ b/apps/mobile/src/i18n/locales/ko/interaction.json
@@ -40,7 +40,6 @@
"unsupportedType": "이 원격 상호작용 유형은 모바일에서 아직 지원되지 않습니다.",
"unsupportedKind": "미지원",
"desktopOnlyKind": "컴퓨터에서 처리",
- "pluginSetupDesktopOnly": "이 플러그인 설정은 컴퓨터에서 완료해야 합니다.",
"cancelRequest": "이 요청 취소",
"cancelRequestAccessibility": "이 원격 요청 취소",
"awaitingAnswer": "답변 대기",
@@ -179,5 +178,42 @@
"enable": "켜기",
"icloudTimeout": "사진이 아직 iCloud에서 다운로드 중이며 시간이 초과되었습니다. 네트워크를 확인하고 다시 시도하세요.",
"photoNotReadable": "이 사진은 지금 읽을 수 없습니다(iCloud에서 다운로드가 완료되지 않았을 수 있습니다). 나중에 다시 시도하세요."
+ },
+ "pluginSetup": {
+ "completeOnDesktop": "제어 중인 데스크톱에서 설정을 완료하세요. 이 카드는 자동으로 업데이트됩니다.",
+ "chooseOne": "설정 방법을 하나 선택하세요",
+ "stepsHeading": "설정 단계",
+ "progress": "{{satisfied}}/{{total}} 완료",
+ "desktopActionHint": "컴퓨터에서 {{action}}",
+ "phase": {
+ "pending": "설정 대기",
+ "action_running": "진행 중…",
+ "waiting_external": "인증 대기 중…",
+ "verifying": "검증 중…",
+ "satisfied": "완료",
+ "failed": "실패",
+ "cancelled": "취소됨"
+ },
+ "error": {
+ "ACTION_FAILED": "설정 작업을 완료할 수 없습니다. 다시 시도하세요.",
+ "ACTION_STALE": "설정 내용이 변경되었습니다. 설정 작업을 다시 선택하세요.",
+ "AUTH_CANCELLED": "인증이 취소되었습니다. 필요한 경우 다시 인증하세요.",
+ "AUTH_FAILED": "인증을 완료할 수 없습니다. 다시 시도하세요.",
+ "INLINE_INVALID": "설정 내용이 올바르지 않습니다. 확인한 후 다시 시도하세요.",
+ "INLINE_UNAVAILABLE": "이 Cindy 버전에서는 채팅에서 이 설정을 저장할 수 없습니다. Cindy를 업데이트한 후 다시 시도하세요.",
+ "SAVE_FAILED": "설정을 저장할 수 없습니다. 다시 시도하세요.",
+ "WINDOW_CLOSED": "설정을 시작한 창이 닫혔습니다. 세션으로 돌아가 다시 시도하세요.",
+ "TARGET_UNAVAILABLE": "플러그인이 비활성화되었거나 제거되었거나 사용할 수 없습니다. 플러그인 상태를 확인한 후 다시 시도하세요.",
+ "ASSESSMENT_FAILED": "설정 상태를 새로 고칠 수 없습니다. 다시 시도하세요.",
+ "TIMEOUT": "설정 대기 시간이 초과되었습니다. 다시 시도하세요."
+ },
+ "action": {
+ "oauth_connect": "인증",
+ "open_plugin_settings": "설정 열기",
+ "manage_connection": "연결 관리",
+ "open_client_settings": "모델 설정 열기"
+ },
+ "inlineFormAction": "컴퓨터에서 {{label}} 입력",
+ "inlineFormActionGeneric": "컴퓨터에서 설정 입력"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/interaction.json b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
index 347b8a345c..4f5f0f26d9 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/interaction.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/interaction.json
@@ -40,7 +40,6 @@
"unsupportedType": "手机版暂不支持这个远程交互类型。",
"unsupportedKind": "暂不支持",
"desktopOnlyKind": "电脑端处理",
- "pluginSetupDesktopOnly": "这个插件配置要在电脑端完成。",
"cancelRequest": "取消这次请求",
"cancelRequestAccessibility": "取消这次远程请求",
"awaitingAnswer": "等待回答",
@@ -179,5 +178,42 @@
"enable": "去开启",
"icloudTimeout": "照片还在从 iCloud 下载,等待超时了。请检查网络,稍后重试。",
"photoNotReadable": "这张照片暂时无法读取(可能还没从 iCloud 下载完成),请稍后重试。"
+ },
+ "pluginSetup": {
+ "completeOnDesktop": "请在被控桌面完成设置,本卡片会自动更新状态。",
+ "chooseOne": "选择一种配置方式",
+ "stepsHeading": "配置步骤",
+ "progress": "{{satisfied}}/{{total}} 已完成",
+ "desktopActionHint": "在电脑端{{action}}",
+ "phase": {
+ "pending": "待设置",
+ "action_running": "进行中…",
+ "waiting_external": "等待授权…",
+ "verifying": "验证中…",
+ "satisfied": "已完成",
+ "failed": "失败",
+ "cancelled": "已取消"
+ },
+ "error": {
+ "ACTION_FAILED": "设置操作未完成,请重试。",
+ "ACTION_STALE": "设置已更新,请重新选择配置操作。",
+ "AUTH_CANCELLED": "授权已取消,您可以重新授权。",
+ "AUTH_FAILED": "未能完成授权,请重试。",
+ "INLINE_INVALID": "配置内容无效,请检查后重试。",
+ "INLINE_UNAVAILABLE": "当前版本无法在对话中保存此配置,请更新 Cindy 后重试。",
+ "SAVE_FAILED": "未能保存配置,请重试。",
+ "WINDOW_CLOSED": "发起设置的窗口已关闭,请回到该对话重试。",
+ "TARGET_UNAVAILABLE": "插件已停用、卸载或不可用,请检查插件状态后重试。",
+ "ASSESSMENT_FAILED": "暂时无法刷新配置状态,请重试。",
+ "TIMEOUT": "等待设置超时,请重试。"
+ },
+ "action": {
+ "oauth_connect": "授权",
+ "open_plugin_settings": "打开设置",
+ "manage_connection": "管理连接",
+ "open_client_settings": "打开模型设置"
+ },
+ "inlineFormAction": "在电脑端填写{{label}}",
+ "inlineFormActionGeneric": "在电脑端填写一项配置"
}
}
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index d73d0af05d..400ff89f49 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -11,6 +11,7 @@ import {
Square,
} from 'lucide-react-native';
import {
+ Image,
Pressable,
ScrollView,
StyleSheet,
@@ -34,7 +35,7 @@ import {
buildInteractionResolveActionPresentation,
buildPluginSetupCancelDecision,
buildPlanReviewDecision,
- buildRemotePluginSetupSummary,
+ buildRemotePluginSetupPresentation,
canStartInteractionResolve,
encodeMultiSelectAnswer,
resolveInteractionResilient,
@@ -51,6 +52,8 @@ import {
type AskQuestion,
type PermissionReviewPresentation,
type PlanReviewEvidencePresentation,
+ type RemotePluginSetupPhase,
+ type RemotePluginSetupStep,
} from '@/session/interactionModel';
import {
clearAskUserDraft,
@@ -465,7 +468,7 @@ function InteractionItem({
? buildPluginSetupCancelDecision(item.request)
: null;
return (
- <UnsupportedCard
+ <PluginSetupCard
busy={busy}
cancel={cancelDecision
? {
@@ -477,13 +480,8 @@ function InteractionItem({
}),
}
: null}
- kind={kind}
- // 不是「暂不支持」:手机能看懂、能取消,只是配置动作必须回电脑端做完。
- kindLabel={t('interaction.panel.desktopOnlyKind')}
- message={t('interaction.panel.pluginSetupDesktopOnly')}
- request={item.request}
+ item={item}
requestId={requestId}
- summaryLines={pluginSetupSummaryLines(item.request)}
touchLayout={touchLayout}
/>
);
@@ -1338,10 +1336,154 @@ function PlanReviewCard({
);
}
-function pluginSetupSummaryLines(request: PendingInteraction['request']): string[] {
- const summary = buildRemotePluginSetupSummary(request);
- return [summary.ghostName, summary.intro, ...summary.stepTitles]
- .filter((line): line is string => typeof line === 'string' && line.length > 0);
+/**
+ * plugin_setup 的**只读**状态卡。
+ *
+ * 手机端做不了配置动作(Secret 输入与 OAuth 必须留在被控端,见
+ * docs/dev-rules/plugin-security-and-authoring.md §4 与 desktop 的
+ * interactionResolveOrigin),所以这张卡的价值全在「看懂」:哪个插件、卡在哪一步、
+ * 为什么失败、回电脑端要做什么。动作只有取消。
+ */
+function PluginSetupCard({
+ busy,
+ cancel,
+ item,
+ requestId,
+ touchLayout,
+}: {
+ busy: boolean;
+ cancel: { accessibilityLabel: string; label: string; onPress(): void } | null;
+ item: PendingInteraction;
+ requestId: string | null;
+ touchLayout: InteractionTouchLayout;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const { t } = useTranslation();
+ const presentation = useMemo(
+ () => buildRemotePluginSetupPresentation(item.request),
+ [item.request],
+ );
+ const title = presentation.ghostName ?? t('interaction.kinds.plugin_setup.title');
+ return (
+ <View style={cardStyle(styles, touchLayout)} testID="interaction.pluginSetup.card">
+ <View style={styles.compactCardHeader}>
+ {presentation.iconDataUrl ? (
+ <Image
+ accessibilityIgnoresInvertColors
+ // 纯装饰:插件名紧跟其后,读屏再念一次图标只是噪音。
+ accessibilityElementsHidden
+ importantForAccessibility="no"
+ source={{ uri: presentation.iconDataUrl }}
+ style={styles.pluginSetupIcon}
+ testID="interaction.pluginSetup.icon"
+ />
+ ) : null}
+ <View style={styles.compactCardTitleWrap}>
+ <Text style={styles.kind}>{t('interaction.panel.desktopOnlyKind')}</Text>
+ <Text numberOfLines={1} style={styles.compactCardTitle}>{title}</Text>
+ </View>
+ {presentation.stepCount > 0 ? (
+ <Text style={styles.pageText} testID="interaction.pluginSetup.progress">
+ {t('interaction.pluginSetup.progress', {
+ satisfied: presentation.satisfiedCount,
+ total: presentation.stepCount,
+ })}
+ </Text>
+ ) : null}
+ </View>
+ {presentation.intro ? (
+ <Text style={styles.body} numberOfLines={3}>{presentation.intro}</Text>
+ ) : null}
+ {presentation.groups.map((group) => (
+ <View key={group.id} style={styles.pluginSetupGroup}>
+ {group.anyOf ? (
+ <Text style={styles.pluginSetupGroupHint}>{t('interaction.pluginSetup.chooseOne')}</Text>
+ ) : null}
+ {group.steps.map((step) => (
+ <PluginSetupStepRow key={step.id} step={step} />
+ ))}
+ </View>
+ ))}
+ {/* 收尾帧已经 settle,再让用户「去电脑端完成」是错的引导。 */}
+ {presentation.terminal ? null : (
+ <Text style={styles.pluginSetupFootnote}>{t('interaction.pluginSetup.completeOnDesktop')}</Text>
+ )}
+ {cancel ? (
+ <View style={actionsStyle(styles, touchLayout)}>
+ <ResolveButton
+ accessibilityLabel={cancel.accessibilityLabel}
+ busy={busy}
+ label={cancel.label}
+ onPress={cancel.onPress}
+ requestId={requestId}
+ touchStyle={resolveButtonLayoutStyle(touchLayout, 'secondary')}
+ testID="interaction.unsupported.cancelButton"
+ variant="secondary"
+ />
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+/** 运行中的步骤:与桌面同语义,用 Heart Orange 表示「正在进行」。 */
+const PLUGIN_SETUP_RUNNING_PHASES: ReadonlySet<RemotePluginSetupPhase> = new Set([
+ 'action_running',
+ 'waiting_external',
+ 'verifying',
+]);
+
+function PluginSetupStepRow({ step }: { step: RemotePluginSetupStep }) {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const phaseColor = step.phase === 'satisfied'
+ ? colors.statusReady
+ : step.phase && PLUGIN_SETUP_RUNNING_PHASES.has(step.phase)
+ ? colors.statusAccent
+ : colors.textTertiary;
+ const phaseText = step.phase ? t(`interaction.pluginSetup.phase.${step.phase}`) : null;
+ const actionHint = step.actionKind === 'inline_form'
+ ? (step.inlineFieldLabel
+ ? t('interaction.pluginSetup.inlineFormAction', { label: step.inlineFieldLabel })
+ : t('interaction.pluginSetup.inlineFormActionGeneric'))
+ : step.actionKind
+ ? t('interaction.pluginSetup.desktopActionHint', {
+ action: t(`interaction.pluginSetup.action.${step.actionKind}`),
+ })
+ : null;
+ // 已完成的步骤不再提示「回电脑端做什么」——那是下一步该做的事。
+ const visibleActionHint = actionHint && step.phase !== 'satisfied' ? actionHint : null;
+ const errorText = step.errorCode ? t(`interaction.pluginSetup.error.${step.errorCode}`) : null;
+ return (
+ <View
+ // 聚合成一个读屏单元:标题 / 状态 / 待办 / 错误分开念会把一步拆成四条碎片。
+ accessible
+ accessibilityLabel={[step.title, phaseText, step.description, visibleActionHint, errorText]
+ .filter((part): part is string => !!part)
+ .join(',')}
+ style={styles.pluginSetupStep}
+ testID="interaction.pluginSetup.step"
+ >
+ <View style={styles.pluginSetupStepHeader}>
+ <Text numberOfLines={2} style={styles.pluginSetupStepTitle}>{step.title}</Text>
+ {phaseText ? (
+ <Text style={[styles.pluginSetupPhase, { color: phaseColor }]}>{phaseText}</Text>
+ ) : null}
+ </View>
+ {step.description ? (
+ <Text numberOfLines={2} style={styles.pluginSetupStepBody}>{step.description}</Text>
+ ) : null}
+ {visibleActionHint ? (
+ <Text style={styles.pluginSetupStepAction}>{visibleActionHint}</Text>
+ ) : null}
+ {errorText ? (
+ <Text style={styles.pluginSetupStepError} testID="interaction.pluginSetup.stepError">
+ {errorText}
+ </Text>
+ ) : null}
+ </View>
+ );
}
function UnsupportedCard({
@@ -1668,6 +1810,63 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
fontSize: typeScale.caption,
lineHeight: lineHeight.caption,
},
+ pluginSetupIcon: {
+ borderRadius: radius.container,
+ flexShrink: 0,
+ height: iconSize.xxl,
+ width: iconSize.xxl,
+ },
+ pluginSetupGroup: {
+ gap: spacing.sm,
+ },
+ pluginSetupGroupHint: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.caption,
+ },
+ pluginSetupStep: {
+ gap: spacing.xs,
+ },
+ pluginSetupStepHeader: {
+ alignItems: 'baseline',
+ flexDirection: 'row',
+ gap: spacing.sm,
+ },
+ pluginSetupStepTitle: {
+ color: colors.textPrimary,
+ flex: 1,
+ fontSize: typeScale.footnote,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.caption,
+ minWidth: 0,
+ },
+ pluginSetupPhase: {
+ // 颜色随 phase 内联(已完成 statusReady / 进行中 statusAccent / 其余 textTertiary)。
+ flexShrink: 0,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ },
+ pluginSetupStepBody: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ },
+ pluginSetupStepAction: {
+ color: colors.textSecondary,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ },
+ pluginSetupStepError: {
+ color: colors.errorText,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ },
+ pluginSetupFootnote: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ lineHeight: lineHeight.caption,
+ },
askHeaderKind: {
color: colors.textTertiary,
flex: 1,
diff --git a/apps/mobile/src/session/interactionModel.ts b/apps/mobile/src/session/interactionModel.ts
index 3717f6c0c2..31d1802447 100644
--- a/apps/mobile/src/session/interactionModel.ts
+++ b/apps/mobile/src/session/interactionModel.ts
@@ -20,7 +20,7 @@ export {
buildPlanReviewDecisionSummary,
buildPlanReviewEvidencePresentation,
buildPluginSetupCancelDecision,
- buildRemotePluginSetupSummary,
+ buildRemotePluginSetupPresentation,
canStartInteractionResolve,
encodeMultiSelectAnswer,
extractPlanOutline,
@@ -35,6 +35,9 @@ export {
planReviewPlan,
readRequestId,
remoteInteractionHandling,
+ REMOTE_PLUGIN_SETUP_ACTION_KINDS,
+ REMOTE_PLUGIN_SETUP_ERROR_CODES,
+ REMOTE_PLUGIN_SETUP_PHASES,
selectActivePendingInteraction,
selectionFromAnswer,
sessionScopedPermissionSuggestions,
@@ -43,6 +46,10 @@ export {
type AskQuestionReviewPresentation,
type PermissionReviewPresentation,
type PlanReviewEvidencePresentation,
+ type RemotePluginSetupGroup,
+ type RemotePluginSetupPhase,
+ type RemotePluginSetupPresentation,
+ type RemotePluginSetupStep,
} from '@cindy/maker-shared/interaction';
export type MobilePermissionDecisionAction = 'allow-once' | 'always-allow';
diff --git a/packages/maker-shared/src/__tests__/interaction.test.ts b/packages/maker-shared/src/__tests__/interaction.test.ts
index ec85393143..2a10a546f2 100644
--- a/packages/maker-shared/src/__tests__/interaction.test.ts
+++ b/packages/maker-shared/src/__tests__/interaction.test.ts
@@ -15,7 +15,7 @@ import {
buildPlanReviewDecisionSummary,
buildPlanReviewEvidencePresentation,
buildPluginSetupCancelDecision,
- buildRemotePluginSetupSummary,
+ buildRemotePluginSetupPresentation,
canStartInteractionResolve,
encodeMultiSelectAnswer,
extractPlanOutline,
@@ -581,37 +581,155 @@ describe('interaction shared model', () => {
expect(buildPluginSetupCancelDecision({ kind: 'plugin_setup', requestId: 's1', revision: -1 })).toBeNull();
expect(buildPluginSetupCancelDecision({ kind: 'permission', requestId: 'p1', revision: 1 })).toBeNull();
- expect(buildRemotePluginSetupSummary({
+ });
+
+ it('projects a full read-only plugin setup status card for controllers', () => {
+ const presentation = buildRemotePluginSetupPresentation({
kind: 'plugin_setup',
requestId: 's1',
- revision: 1,
- ghost: { id: 'cindy-web-search', name: 'Cindy Web Search' },
+ revision: 2,
+ ghost: {
+ id: 'cindy-web-search',
+ name: ' Cindy Web Search ',
+ iconDataUrl: 'data:image/png;base64,AAAA',
+ },
intro: ' 需要一个搜索 API key ',
steps: [
- { id: 'brave', title: ' 配置 Brave key ' },
- { id: 'tavily', title: 'Tavily key' },
- { id: 'blank', title: ' ' },
- 'not-a-step',
+ {
+ id: 'brave',
+ groupId: 'search-key',
+ groupMode: 'any_of',
+ title: ' Brave key ',
+ description: ' 用 Brave 的搜索 API ',
+ phase: 'failed',
+ errorCode: 'SAVE_FAILED',
+ action: {
+ id: 'inline:opaque',
+ kind: 'inline_form',
+ form: { fields: [{ id: 'value', type: 'secret', label: ' Brave API key ' }] },
+ },
+ },
+ {
+ id: 'tavily',
+ groupId: 'search-key',
+ groupMode: 'any_of',
+ title: 'Tavily key',
+ phase: 'pending',
+ action: { id: 'oauth:opaque', kind: 'oauth_connect' },
+ },
+ {
+ id: 'model',
+ groupId: 'model',
+ groupMode: 'any_of',
+ title: '连接模型服务',
+ phase: 'satisfied',
+ },
],
- })).toEqual({
+ });
+
+ expect(presentation).toEqual({
ghostName: 'Cindy Web Search',
+ iconDataUrl: 'data:image/png;base64,AAAA',
intro: '需要一个搜索 API key',
- stepTitles: ['配置 Brave key', 'Tavily key'],
+ satisfiedCount: 1,
+ stepCount: 3,
+ terminal: false,
+ groups: [
+ {
+ id: 'search-key',
+ // 组内两项 → 「任选其一」
+ anyOf: true,
+ steps: [
+ {
+ id: 'brave',
+ title: 'Brave key',
+ description: '用 Brave 的搜索 API',
+ phase: 'failed',
+ errorCode: 'SAVE_FAILED',
+ actionKind: 'inline_form',
+ inlineFieldLabel: 'Brave API key',
+ },
+ {
+ id: 'tavily',
+ title: 'Tavily key',
+ description: null,
+ phase: 'pending',
+ errorCode: null,
+ actionKind: 'oauth_connect',
+ inlineFieldLabel: null,
+ },
+ ],
+ },
+ {
+ id: 'model',
+ // 单项组没有「任选其一」语义,提示只会让用户困惑
+ anyOf: false,
+ steps: [{
+ id: 'model',
+ title: '连接模型服务',
+ description: null,
+ phase: 'satisfied',
+ errorCode: null,
+ actionKind: null,
+ inlineFieldLabel: null,
+ }],
+ },
+ ],
});
+ });
- expect(buildRemotePluginSetupSummary({ kind: 'plugin_setup', requestId: 's1' })).toEqual({
- ghostName: null,
- intro: null,
- stepTitles: [],
+ it('collapses unknown plugin setup enums instead of passing them through to copy lookups', () => {
+ const presentation = buildRemotePluginSetupPresentation({
+ kind: 'plugin_setup',
+ requestId: 's1',
+ revision: 1,
+ terminal: true,
+ steps: [
+ // 被控端新版本引入的值:降级为 null,少一个徽标而不是查表查出 key 字面量
+ { id: 'a', title: 'A', phase: 'teleporting', errorCode: 'NOT_A_CODE', action: { id: 'x', kind: 'mind_control' } },
+ { id: 'b', title: ' ' },
+ 'not-a-step',
+ ],
});
- // 换个 kind 传进来必须返回空摘要,而不是从任意 request 上刮字段让误用「看起来正常」。
- expect(buildRemotePluginSetupSummary({
+ expect(presentation.terminal).toBe(true);
+ expect(presentation.stepCount).toBe(1);
+ expect(presentation.groups).toEqual([{
+ id: 'a-group',
+ anyOf: false,
+ steps: [{
+ id: 'a',
+ title: 'A',
+ description: null,
+ phase: null,
+ errorCode: null,
+ actionKind: null,
+ inlineFieldLabel: null,
+ }],
+ }]);
+
+ // 远程 URL 图标一律丢弃:只接受内联 data:image/。
+ expect(buildRemotePluginSetupPresentation({
+ kind: 'plugin_setup',
+ requestId: 's1',
+ ghost: { id: 'g', name: 'G', iconDataUrl: 'https://example.com/icon.png' },
+ }).iconDataUrl).toBeNull();
+
+ // 换个 kind 传进来必须返回空投影,而不是从任意 request 上刮字段让误用「看起来正常」。
+ expect(buildRemotePluginSetupPresentation({
kind: 'permission',
requestId: 'p1',
ghost: { id: 'x', name: 'Not a plugin setup' },
intro: 'nope',
steps: [{ id: 's', title: 'nope' }],
- })).toEqual({ ghostName: null, intro: null, stepTitles: [] });
+ })).toEqual({
+ ghostName: null,
+ iconDataUrl: null,
+ intro: null,
+ groups: [],
+ satisfiedCount: 0,
+ stepCount: 0,
+ terminal: false,
+ });
});
});
diff --git a/packages/maker-shared/src/interaction.ts b/packages/maker-shared/src/interaction.ts
index f5af45fca2..2e447f5041 100644
--- a/packages/maker-shared/src/interaction.ts
+++ b/packages/maker-shared/src/interaction.ts
@@ -466,27 +466,186 @@ function pluginSetupCancelRevision(request: InteractionRequestLike): number | nu
}
/**
- * plugin_setup 卡在控制端的只读摘要:插件名 + 引导语 + 各步骤标题。
+ * 被控端 setup 步骤的稳定枚举。
*
- * 控制端不渲染表单(Secret 输入与 OAuth 都在被控端),但也不该把 raw JSON 摔给
- * 用户——至少要能看懂「哪个插件、要配什么」再决定是取消还是回电脑端处理。
+ * 这里是**副本**,不是从 Desktop import 的(packages 不得依赖 apps)。正本在
+ * `apps/desktop/src/shared/ghost.ts`(`GhostSetupStepPhase` /
+ * `GHOST_SETUP_ERROR_CODES` / `GhostSetupActionKind`),两端由跨端契约绑定:
+ * 正本增删值时必须同步这里,否则控制端会把新值当未知丢弃(降级展示,不会崩)。
*/
-export function buildRemotePluginSetupSummary(request: InteractionRequestLike): {
+export const REMOTE_PLUGIN_SETUP_PHASES = [
+ 'pending',
+ 'action_running',
+ 'waiting_external',
+ 'verifying',
+ 'satisfied',
+ 'failed',
+ 'cancelled',
+] as const;
+export type RemotePluginSetupPhase = (typeof REMOTE_PLUGIN_SETUP_PHASES)[number];
+
+export const REMOTE_PLUGIN_SETUP_ERROR_CODES = [
+ 'ACTION_FAILED',
+ 'ACTION_STALE',
+ 'AUTH_CANCELLED',
+ 'AUTH_FAILED',
+ 'INLINE_INVALID',
+ 'INLINE_UNAVAILABLE',
+ 'SAVE_FAILED',
+ 'WINDOW_CLOSED',
+ 'TARGET_UNAVAILABLE',
+ 'ASSESSMENT_FAILED',
+ 'TIMEOUT',
+] as const;
+export type RemotePluginSetupErrorCode = (typeof REMOTE_PLUGIN_SETUP_ERROR_CODES)[number];
+
+export const REMOTE_PLUGIN_SETUP_ACTION_KINDS = [
+ 'oauth_connect',
+ 'open_plugin_settings',
+ 'manage_connection',
+ 'open_client_settings',
+ 'inline_form',
+] as const;
+export type RemotePluginSetupActionKind = (typeof REMOTE_PLUGIN_SETUP_ACTION_KINDS)[number];
+
+export interface RemotePluginSetupStep {
+ id: string;
+ title: string;
+ description: string | null;
+ /** 非白名单值(被控端更新引入的新 phase)降级为 null,只是少显示一个徽标。 */
+ phase: RemotePluginSetupPhase | null;
+ errorCode: RemotePluginSetupErrorCode | null;
+ actionKind: RemotePluginSetupActionKind | null;
+ /**
+ * inline_form 字段的**标签**,用于说明「电脑端要填什么」。
+ * 只有 label,永远没有值:Secret 不进 interaction snapshot(见
+ * `docs/dev-rules/plugin-security-and-authoring.md` §4)。
+ */
+ inlineFieldLabel: string | null;
+}
+
+export interface RemotePluginSetupGroup {
+ id: string;
+ /** any_of 且组内不止一项 → UI 要提示「选择一种配置方式」,别让用户以为要全做。 */
+ anyOf: boolean;
+ steps: RemotePluginSetupStep[];
+}
+
+export interface RemotePluginSetupPresentation {
ghostName: string | null;
+ /** 只接受 data:image/ 的内联图标;其它形态(远程 URL 等)一律丢弃。 */
+ iconDataUrl: string | null;
intro: string | null;
- stepTitles: string[];
-} {
- // 作为导出的 shared API 显式挡住误用:换个 kind 传进来时返回空摘要,而不是
+ groups: RemotePluginSetupGroup[];
+ satisfiedCount: number;
+ stepCount: number;
+ /** 被控端已 settle 的收尾帧:不再 actionable,UI 不给可点动作。 */
+ terminal: boolean;
+}
+
+/**
+ * plugin_setup 卡在控制端的**只读**投影。
+ *
+ * 控制端不渲染表单、也不触发动作(Secret 输入与 OAuth 都必须留在被控端,见
+ * plugin-security-and-authoring.md §4 与 desktop 的 interactionResolveOrigin),
+ * 但被控端下发的状态信息足以让用户看懂「哪个插件、卡在哪一步、为什么失败、
+ * 回电脑端要做什么」,再决定是去电脑端处理还是取消。
+ *
+ * 入参来自远端 payload,一律按白名单收敛:未知 phase / errorCode / action kind
+ * 降级为 null 而不是原样透传,避免把被控端新版本的值直接喂给文案查表。
+ */
+export function buildRemotePluginSetupPresentation(
+ request: InteractionRequestLike,
+): RemotePluginSetupPresentation {
+ const empty: RemotePluginSetupPresentation = {
+ ghostName: null,
+ iconDataUrl: null,
+ intro: null,
+ groups: [],
+ satisfiedCount: 0,
+ stepCount: 0,
+ terminal: false,
+ };
+ // 作为导出的 shared API 显式挡住误用:换个 kind 传进来时返回空投影,而不是
// 从任意 request 上刮字段、让调用错误看起来「正常返回」。
- if (request.kind !== 'plugin_setup') return { ghostName: null, intro: null, stepTitles: [] };
+ if (request.kind !== 'plugin_setup') return empty;
+
const ghost = isPlainRecord(request.ghost) ? request.ghost : null;
- const ghostName = typeof ghost?.name === 'string' && ghost.name.trim() ? ghost.name.trim() : null;
- const intro = typeof request.intro === 'string' && request.intro.trim() ? request.intro.trim() : null;
- const steps = Array.isArray(request.steps) ? request.steps : [];
- const stepTitles = steps
- .map((step) => (isPlainRecord(step) && typeof step.title === 'string' ? step.title.trim() : ''))
- .filter((title) => title.length > 0);
- return { ghostName, intro, stepTitles };
+ const rawSteps = Array.isArray(request.steps) ? request.steps : [];
+ const groups: RemotePluginSetupGroup[] = [];
+ const groupsById = new Map<string, RemotePluginSetupGroup>();
+ let satisfiedCount = 0;
+ let stepCount = 0;
+
+ rawSteps.forEach((rawStep, index) => {
+ if (!isPlainRecord(rawStep)) return;
+ const title = trimmedOrNull(rawStep.title);
+ if (!title) return;
+ const phase = pickFromAllowlist(rawStep.phase, REMOTE_PLUGIN_SETUP_PHASES);
+ const action = isPlainRecord(rawStep.action) ? rawStep.action : null;
+ const actionKind = pickFromAllowlist(action?.kind, REMOTE_PLUGIN_SETUP_ACTION_KINDS);
+ const step: RemotePluginSetupStep = {
+ id: trimmedOrNull(rawStep.id) ?? `step-${index}`,
+ title,
+ description: trimmedOrNull(rawStep.description),
+ phase,
+ errorCode: pickFromAllowlist(rawStep.errorCode, REMOTE_PLUGIN_SETUP_ERROR_CODES),
+ actionKind,
+ inlineFieldLabel: actionKind === 'inline_form' ? inlineSecretFieldLabel(action) : null,
+ };
+ stepCount += 1;
+ if (phase === 'satisfied') satisfiedCount += 1;
+
+ // 分组按首次出现顺序保留;groupId 缺失的步骤各自成组,不并进同一个「空组」。
+ const groupId = trimmedOrNull(rawStep.groupId) ?? `${step.id}-group`;
+ const existing = groupsById.get(groupId);
+ if (existing) {
+ existing.steps.push(step);
+ if (rawStep.groupMode === 'any_of') existing.anyOf = true;
+ return;
+ }
+ const group: RemotePluginSetupGroup = {
+ id: groupId,
+ anyOf: rawStep.groupMode === 'any_of',
+ steps: [step],
+ };
+ groupsById.set(groupId, group);
+ groups.push(group);
+ });
+
+ return {
+ ghostName: trimmedOrNull(ghost?.name),
+ iconDataUrl: inlineImageDataUrl(ghost?.iconDataUrl),
+ intro: trimmedOrNull(request.intro),
+ // 单项组没有「任选其一」的语义,提示只会让用户困惑。
+ groups: groups.map((group) => ({ ...group, anyOf: group.anyOf && group.steps.length > 1 })),
+ satisfiedCount,
+ stepCount,
+ terminal: request.terminal === true,
+ };
+}
+
+function trimmedOrNull(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function pickFromAllowlist<T extends string>(value: unknown, allowed: readonly T[]): T | null {
+ return typeof value === 'string' && (allowed as readonly string[]).includes(value)
+ ? (value as T)
+ : null;
+}
+
+function inlineSecretFieldLabel(action: Record<string, unknown> | null): string | null {
+ const form = isPlainRecord(action?.form) ? action.form : null;
+ const fields = Array.isArray(form?.fields) ? form.fields : [];
+ const first = fields.length > 0 && isPlainRecord(fields[0]) ? fields[0] : null;
+ return trimmedOrNull(first?.label);
+}
+
+function inlineImageDataUrl(value: unknown): string | null {
+ return typeof value === 'string' && value.startsWith('data:image/') ? value : null;
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {