Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(desktop): 交互卡合成语义收敛到 im/shared/interactionCardModel 单一出处 (#1925)
Chris Zhang11d51a273f1b
diff --git a/apps/desktop/src/main/hook-control/interactions.ts b/apps/desktop/src/main/hook-control/interactions.tsindex cd827f1bd7..3070b2004e 100644--- a/apps/desktop/src/main/hook-control/interactions.ts+++ b/apps/desktop/src/main/hook-control/interactions.ts@@ -12,9 +12,10 @@* - answers 的 question 全文匹配等易碎约定(见 im/shared/cardActionHandler* 的 qKey 注释)不过网线, 单端维护。*- * 卡片合成语义对齐 im/shared/cardBuilders 的 v1 简化(同一产品能力的两个- * 渠道不该有体验分叉): ask 只渲染第一道问题、至多 6 个选项、multiSelect- * 降级单选; plan 正文截断 1500。+ * 卡片合成语义(ask 只渲染第一道问题、至多 6 个选项、multiSelect 降级单选、+ * plan 正文截断 1500、按钮->决策对象)已收进 im/shared/interactionCardModel ——+ * 与 IM 渠道同一份语义(同一产品能力的两个渠道不该有体验分叉), 本文件只做+ * hook 协议卡的渲染与挂起注册表。** 超时与收口: hook 是无人值守链路, 任何交互都必须有界 —— 注册时挂 30min* 超时(短于 session-runner 的 60min 整 turn 硬超时, 保证超时后 turn 还能@@ -28,21 +29,25 @@import type { InteractionButton, InteractionRequestPayload } from '@cindy/slack-hook-protocol';import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';-/** ask 卡渲染的最大选项数(与 im/shared/cardBuilders MAX_OPTIONS 一致)。 */-const MAX_OPTIONS = 6;-/** plan 正文截断长度(与 im/shared/cardBuilders MAX_PLAN_LEN 一致)。 */-const MAX_PLAN_LEN = 1500;-/** 按钮文案截断(Slack plain_text 上限 75, 对齐 IM 的 30)。 */-const BTN_LABEL_MAX = 30;-/** permission 卡的工具入参摘要截断(JSON 全文可能巨大, 卡片只要能看清意图)。 */-const PERM_INPUT_SUMMARY_MAX = 600;+import {+ composeInteractionModel,+ truncateInline as truncate,+ BTN_LABEL_MAX,+ HOOK_PERMISSION_INPUT_SUMMARY_MAX,+ MAX_PLAN_LEN,+} from '../im/shared/interactionCardModel.js';++/** 卡片标题截断(hook 协议卡标题一行放得下的量)。 */+const TITLE_MAX = 60;+/** 超时 / 收口自决时写进决策的 reason(系统代码, 非用户反馈)。 */+const TIMEOUT_REASON = 'hook_interaction_timeout';/** 工具入参 -> 单行 JSON 摘要(不可序列化时降级为空串, 卡片少一行而已)。 */function summarizeInput(input: Record<string, unknown>): string {try {const json = JSON.stringify(input);if (!json || json === '{}') return '';- return truncate(json, PERM_INPUT_SUMMARY_MAX);+ return truncate(json, HOOK_PERMISSION_INPUT_SUMMARY_MAX);} catch {return '';}@@ -51,11 +56,6 @@ function summarizeInput(input: Record<string, unknown>): string {/** 未决交互超时(必须短于 session-runner 的整 turn 硬超时 60min)。 */export const HOOK_INTERACTION_TIMEOUT_MS = 30 * 60_000;-function truncate(s: string, max: number): string {- if (!s) return '';- return s.length > max ? `${s.slice(0, max)}…` : s;-}-/** 合成结果: 过网线的卡片 + 留在本端的按钮->决策映射与安全默认。 */export interface ComposedInteractionCard {card: Pick<InteractionRequestPayload, 'kind' | 'title' | 'body' | 'buttons'>;@@ -75,123 +75,83 @@ export interface ComposedInteractionCard {* **拒绝**(用户显式选了收紧档, 放行才是意外)。*/export function composeInteractionCard(req: InteractionRequest): ComposedInteractionCard | null {- if (req.kind === 'ask_user_question') {- const question = req.questions[0];- if (!question) return null;- const headerText = question.header || question.question;- const options = (question.options ?? []).slice(0, MAX_OPTIONS);- const bodyExtra =- question.header && question.header !== question.question ? question.question : '';+ const model = composeInteractionModel(req);+ // ask 没有问题项 / 未来未知 kind: 不出卡+ if (!model) return null;+ if (model.kind === 'ask_user_question') {+ // buttonId 是过网线的兼容契约, 由本端从语义 choice 映射:+ // 无选项降级 -> ask:continue(空答案), 有选项 -> ask:<序号>。const decisions = new Map<string, InteractionDecision>();- const buttons: InteractionButton[] = [];- if (options.length === 0) {- // 自由问答无选项: 无人值守链路给不了自由文本, 只能"继续"(空答案) ——- // 与 IM 渠道的 noOptions 降级一致- buttons.push({ id: 'ask:continue', label: '继续', style: 'default' });- decisions.set('ask:continue', {- kind: 'ask_user_question',- // answers key 必须是 question.question 全文(SDK 按全文匹配, 见- // im/shared/cardActionHandler.decisionFromPress 的 qKey 注释)- answers: { [question.question]: '' },- });- } else {- options.forEach((opt, i) => {- const id = `ask:${i}`;- buttons.push({ id, label: truncate(opt.label, BTN_LABEL_MAX), style: 'default' });- decisions.set(id, {- kind: 'ask_user_question',- answers: { [question.question]: opt.label },- });- });- }+ const buttons: InteractionButton[] = model.choices.map((choice) => {+ const id = model.degraded ? 'ask:continue' : `ask:${choice.index}`;+ decisions.set(id, choice.decision);+ return { id, label: truncate(choice.label ?? '', BTN_LABEL_MAX), style: choice.style };+ });return {card: {- kind: req.kind,- title: `❓ ${truncate(headerText, 60)}`,- body: bodyExtra,+ kind: 'ask_user_question',+ title: `❓ ${truncate(model.headerText, TITLE_MAX)}`,+ body: model.questionBody,buttons,},decisions,- defaultDecision: { kind: 'ask_user_question', answers: {} },+ defaultDecision: model.buildDefaultDecision(TIMEOUT_REASON),fallbackReason: '等待回答超时, 任务已按“未回答”继续',};}- if (req.kind === 'plan_review') {- const decisions = new Map<string, InteractionDecision>([- ['plan:approve', { kind: 'plan_review', behavior: 'allow' }],- [- 'plan:reject',- { kind: 'plan_review', behavior: 'deny', reason: 'user_rejected', dismissed: true },- ],- ]);+ if (model.kind === 'plan_review') {+ const [approve, reject] = model.choices;return {card: {- kind: req.kind,+ kind: 'plan_review',title: '📋 计划待审阅',- body: truncate(req.plan, MAX_PLAN_LEN),+ body: truncate(model.plan, MAX_PLAN_LEN),buttons: [- { id: 'plan:approve', label: '批准执行', style: 'primary' },- { id: 'plan:reject', label: '打回', style: 'danger' },+ { id: 'plan:approve', label: '批准执行', style: approve.style },+ { id: 'plan:reject', label: '打回', style: reject.style },],},- decisions,- defaultDecision: {- kind: 'plan_review',- behavior: 'deny',- reason: 'hook_interaction_timeout',- // 系统性 dismissal: 别让 codex 把超时 reason 当用户反馈发起修订 turn- dismissed: true,- },+ decisions: new Map<string, InteractionDecision>([+ ['plan:approve', approve.decision],+ ['plan:reject', reject.decision],+ ]),+ // 超时按安全默认 deny;恒带 dismissed(系统性 dismissal, 别让 codex 把超时+ // reason 当用户反馈发起修订 turn) —— 见 interactionCardModel。+ defaultDecision: model.buildDefaultDecision(TIMEOUT_REASON),fallbackReason: '等待审阅超时, 计划未获批准',};}- if (req.kind === 'permission') {- const decisions = new Map<string, InteractionDecision>([- ['perm:allow', { kind: 'permission', behavior: 'allow' }],- [- 'perm:always',- {- kind: 'permission',- behavior: 'allow',- // 会话级 addRules: claude-code 直接消费; codex 把非空 permissionUpdates- // 视为会话级放行(见 maker-core events.ts 的 permissionUpdates 注释)- permissionUpdates: [- { type: 'addRules', rules: [{ toolName: req.toolName }], behavior: 'allow', destination: 'session' },- ],- },+ const [allowOnce, allowAlways, deny] = model.choices;+ const inputSummary = summarizeInput(model.input);+ const body = [+ model.description,+ `工具: \`${model.toolName}\``,+ inputSummary ? `\`\`\`${inputSummary}\`\`\`` : '',+ ]+ .filter((s) => s.length > 0)+ .join('\n');+ return {+ card: {+ kind: 'permission',+ title: `🔐 权限请求: ${truncate(model.displayTitle, TITLE_MAX)}`,+ body,+ buttons: [+ { id: 'perm:allow', label: '允许一次', style: allowOnce.style },+ { id: 'perm:always', label: '本任务总是允许', style: allowAlways.style },+ { id: 'perm:deny', label: '拒绝', style: deny.style },],- ['perm:deny', { kind: 'permission', behavior: 'deny', reason: 'user_denied' }],- ]);- const inputSummary = summarizeInput(req.input);- const body = [- req.description ?? '',- `工具: \`${req.toolName}\``,- inputSummary ? `\`\`\`${inputSummary}\`\`\`` : '',- ]- .filter((s) => s.length > 0)- .join('\n');- return {- card: {- kind: req.kind,- title: `🔐 权限请求: ${truncate(req.displayName ?? req.title ?? req.toolName, 60)}`,- body,- buttons: [- { id: 'perm:allow', label: '允许一次', style: 'primary' },- { id: 'perm:always', label: '本任务总是允许', style: 'default' },- { id: 'perm:deny', label: '拒绝', style: 'danger' },- ],- },- decisions,- defaultDecision: { kind: 'permission', behavior: 'deny', reason: 'hook_interaction_timeout' },- fallbackReason: '等待授权超时, 已拒绝该权限请求',- };- }-- // 未来未知 kind: 不出卡, 调用方按 kind 安全默认就地自决- return null;+ },+ decisions: new Map<string, InteractionDecision>([+ ['perm:allow', allowOnce.decision],+ ['perm:always', allowAlways.decision],+ ['perm:deny', deny.decision],+ ]),+ defaultDecision: model.buildDefaultDecision(TIMEOUT_REASON),+ fallbackReason: '等待授权超时, 已拒绝该权限请求',+ };}/** 挂起交互条目。 */diff --git a/apps/desktop/src/main/im/shared/__tests__/interactionCardModel.test.ts b/apps/desktop/src/main/im/shared/__tests__/interactionCardModel.test.tsnew file mode 100644index 0000000000..8d55de1a75--- /dev/null+++ b/apps/desktop/src/main/im/shared/__tests__/interactionCardModel.test.ts@@ -0,0 +1,311 @@+/**+ * interactionCardModel 跨实现一致性单测。+ *+ * 语义层收敛后, ask / plan / permission 三类交互卡由两个渲染侧共用同一份模型:+ * - IM 侧: im/shared/cardBuilders(+ cardActionHandler 的按压->决策映射)+ * - hook 侧: hook-control/interactions.composeInteractionCard+ * 本文件用同一组 InteractionRequest 夹具驱动两侧, 断言**选项集与决策对象**语义+ * 对齐(渲染差异 —— 按钮文案来源、标题格式、省略号样式 —— 允许不同)。+ */++import { describe, expect, it } from 'vitest';++import { SESSION_PERMISSION_DESTINATION, type InteractionRequest } from '@cindy/maker-core';++import { composeInteractionCard } from '../../../hook-control/interactions';+import { ui } from '../../feishu/uiText';+import { createCardBuilders } from '../cardBuilders';+import {+ buildAskAnswerDecision,+ buildPermissionAllowAlwaysDecision,+ buildPermissionAllowOnceDecision,+ buildPermissionDenyDecision,+ buildPlanApproveDecision,+ buildPlanDenyDecision,+ composeInteractionModel,+ BTN_LABEL_MAX,+ MAX_OPTIONS,+ MAX_PLAN_LEN,+ PERMISSION_USER_DENIED_REASON,+ PLAN_USER_REJECTED_REASON,+} from '../interactionCardModel';+import { cancelPending, registerPending } from '../pendingInteractions';++const cards = createCardBuilders(ui, () => 'high');++/** IM 侧按压 -> 决策: 与 cardActionHandler.decisionFromPress 同一张表。 */+function imDecisionFromButton(+ buttonId: string,+ payload: Record<string, unknown>,+ toolName?: string,+) {+ switch (buttonId) {+ case 'permission:allow:once':+ return buildPermissionAllowOnceDecision();+ case 'permission:allow:always':+ return toolName+ ? buildPermissionAllowAlwaysDecision(toolName)+ : buildPermissionAllowOnceDecision();+ case 'permission:deny':+ return buildPermissionDenyDecision(PERMISSION_USER_DENIED_REASON);+ case 'plan:approve':+ return buildPlanApproveDecision();+ case 'plan:reject':+ return buildPlanDenyDecision(PLAN_USER_REJECTED_REASON);+ case 'ask:pick':+ case 'ask:noop':+ return buildAskAnswerDecision(+ String(payload.questionText ?? payload.questionHeader ?? 'q'),+ String(payload.optionLabel ?? ''),+ );+ default:+ return null;+ }+}++type AskRequest = Extract<InteractionRequest, { kind: 'ask_user_question' }>;+type PlanRequest = Extract<InteractionRequest, { kind: 'plan_review' }>;+type PermissionRequest = Extract<InteractionRequest, { kind: 'permission' }>;++const LONG_LABEL = '一个非常长的选项标签'.repeat(6);++const ASK_MULTI: AskRequest = {+ kind: 'ask_user_question',+ requestId: 'req-ask-multi',+ questions: [+ {+ question: '这次用哪个方案实现?',+ header: '方案选择',+ // v1: multiSelect 降级单选+ multiSelect: true,+ options: [+ ...Array.from({ length: 8 }, (_, i) => ({ label: `方案 ${i}` })),+ { label: LONG_LABEL },+ ],+ },+ { question: '第二问在 v1 不渲染', options: [{ label: '不该出现' }] },+ ],+};++const ASK_NO_OPTIONS: AskRequest = {+ kind: 'ask_user_question',+ requestId: 'req-ask-free',+ questions: [{ question: '接下来做什么?' }],+};++const ASK_LONG_LABEL: AskRequest = {+ kind: 'ask_user_question',+ requestId: 'req-ask-long',+ // header 与 question 相同 -> question 不进正文+ questions: [{ question: '选一个', header: '选一个', options: [{ label: LONG_LABEL }] }],+};++const PLAN_LONG: PlanRequest = {+ kind: 'plan_review',+ requestId: 'req-plan',+ plan: '第一步做这个, 第二步做那个。'.repeat(300),+};++const PERMISSION_RICH: PermissionRequest = {+ kind: 'permission',+ requestId: 'req-perm',+ toolName: 'Bash',+ input: { command: `echo ${'x'.repeat(3000)}` },+ displayName: '运行命令',+ description: '在工作目录执行 shell 命令',+};++describe('composeInteractionModel — v1 规则', () => {+ it('ask: 只取第一问, 至多 MAX_OPTIONS 个选项, multiSelect 降级单选', () => {+ const model = composeInteractionModel(ASK_MULTI)!;+ expect(model.kind).toBe('ask_user_question');+ if (model.kind !== 'ask_user_question') throw new Error('unreachable');+ expect(model.question.question).toBe('这次用哪个方案实现?');+ expect(model.choices).toHaveLength(MAX_OPTIONS);+ expect(model.degraded).toBe(false);+ // 选项 label 是原文(截断长度是渲染参数, 不在语义层做)+ expect(model.choices.map((c) => c.label)).toEqual([+ '方案 0',+ '方案 1',+ '方案 2',+ '方案 3',+ '方案 4',+ '方案 5',+ ]);+ // header !== question -> question 进正文+ expect(model.headerText).toBe('方案选择');+ expect(model.questionBody).toBe('这次用哪个方案实现?');+ });++ it('ask: header 与 question 相同则正文为空; 无选项降级为单个「继续」(空答案)', () => {+ const same = composeInteractionModel(ASK_LONG_LABEL)!;+ if (same.kind !== 'ask_user_question') throw new Error('unreachable');+ expect(same.questionBody).toBe('');++ const free = composeInteractionModel(ASK_NO_OPTIONS)!;+ if (free.kind !== 'ask_user_question') throw new Error('unreachable');+ expect(free.degraded).toBe(true);+ expect(free.choices).toHaveLength(1);+ expect(free.choices[0].answerText).toBe('');+ expect(free.choices[0].decision).toEqual({+ kind: 'ask_user_question',+ answers: { '接下来做什么?': '' },+ });+ });++ it('无问题项 / 未知 kind 不出卡', () => {+ expect(+ composeInteractionModel({ kind: 'ask_user_question', requestId: 'x', questions: [] }),+ ).toBeNull();+ expect(+ composeInteractionModel({ kind: 'unknown' } as unknown as InteractionRequest),+ ).toBeNull();+ });++ it('permission 的会话级 addRules destination 与 maker-core 常量同值(防漂移)', () => {+ const decision = buildPermissionAllowAlwaysDecision('Bash');+ expect(decision).toEqual({+ kind: 'permission',+ behavior: 'allow',+ permissionUpdates: [+ {+ type: 'addRules',+ rules: [{ toolName: 'Bash' }],+ behavior: 'allow',+ destination: SESSION_PERMISSION_DESTINATION,+ },+ ],+ });+ });+});++describe('跨实现一致性 — IM cardBuilders vs hook composeInteractionCard', () => {+ it('ask(多问 / 多选 / 超长 label): 两侧选项集与决策逐项对齐', () => {+ const model = composeInteractionModel(ASK_MULTI)!;+ if (model.kind !== 'ask_user_question') throw new Error('unreachable');+ const hook = composeInteractionCard(ASK_MULTI)!;+ const im = cards.buildAskUserCard(ASK_MULTI)!;++ // 选项个数一致, 第二问一律不渲染+ expect(hook.card.buttons).toHaveLength(MAX_OPTIONS);+ expect(im.buttons).toHaveLength(MAX_OPTIONS);+ expect(JSON.stringify(hook.card)).not.toContain('不该出现');+ expect(JSON.stringify(im)).not.toContain('不该出现');++ // 决策逐项对齐: hook 查表 vs IM 从按钮 payload 还原+ const hookDecisions = hook.card.buttons.map((b) => hook.decisions.get(b.id));+ const imDecisions = im.buttons.map((b) =>+ imDecisionFromButton(b.id, b.payload as Record<string, unknown>),+ );+ expect(hookDecisions).toEqual(model.choices.map((c) => c.decision));+ expect(imDecisions).toEqual(hookDecisions);++ // 超长 label 两侧截断长度一致(省略号样式不同, 属渲染差异)+ const longOnly = composeInteractionCard(ASK_LONG_LABEL)!;+ const imLongOnly = cards.buildAskUserCard(ASK_LONG_LABEL)!;+ expect(longOnly.card.buttons[0].label.slice(0, BTN_LABEL_MAX)).toBe(+ LONG_LABEL.slice(0, BTN_LABEL_MAX),+ );+ expect(imLongOnly.buttons[0].label.slice(0, BTN_LABEL_MAX)).toBe(+ LONG_LABEL.slice(0, BTN_LABEL_MAX),+ );+ // 截断只影响按钮文案, answers 里的答案仍是原文+ expect(longOnly.decisions.get('ask:0')).toEqual({+ kind: 'ask_user_question',+ answers: { 选一个: LONG_LABEL },+ });+ expect(+ imDecisionFromButton(+ imLongOnly.buttons[0].id,+ imLongOnly.buttons[0].payload as Record<string, unknown>,+ ),+ ).toEqual(longOnly.decisions.get('ask:0'));+ });++ it('ask(无选项): 两侧都降级为单个「继续」且答案为空串', () => {+ const hook = composeInteractionCard(ASK_NO_OPTIONS)!;+ const im = cards.buildAskUserCard(ASK_NO_OPTIONS)!;+ expect(hook.card.buttons.map((b) => b.label)).toEqual(['继续']);+ expect(im.buttons.map((b) => b.label)).toEqual(['继续']);+ const expected = { kind: 'ask_user_question', answers: { '接下来做什么?': '' } };+ expect(hook.decisions.get('ask:continue')).toEqual(expected);+ expect(+ imDecisionFromButton(im.buttons[0].id, im.buttons[0].payload as Record<string, unknown>),+ ).toEqual(expected);+ });++ it('plan(超长正文): 两侧同截断上限、同决策(approve / reject 都带 dismissed)', () => {+ const hook = composeInteractionCard(PLAN_LONG)!;+ const im = cards.buildPlanReviewCard(PLAN_LONG);+ // 同一截断上限, 截断后的正文正体一致(省略号样式两侧不同)+ expect(hook.card.body.slice(0, MAX_PLAN_LEN)).toBe(im.body!.slice(0, MAX_PLAN_LEN));+ expect(hook.card.body.slice(0, MAX_PLAN_LEN)).toBe(PLAN_LONG.plan.slice(0, MAX_PLAN_LEN));++ const imDecisions = im.buttons.map((b) =>+ imDecisionFromButton(b.id, b.payload as Record<string, unknown>),+ );+ const hookDecisions = hook.card.buttons.map((b) => hook.decisions.get(b.id));+ expect(hookDecisions).toEqual([+ { kind: 'plan_review', behavior: 'allow' },+ { kind: 'plan_review', behavior: 'deny', reason: 'user_rejected', dismissed: true },+ ]);+ expect(imDecisions).toEqual(hookDecisions);+ });++ it('permission(带 description 与大 input): 两侧三选项同序同决策', () => {+ const hook = composeInteractionCard(PERMISSION_RICH)!;+ const im = cards.buildPermissionCard(PERMISSION_RICH);+ expect(hook.card.buttons.map((b) => b.style)).toEqual(['primary', 'default', 'danger']);+ expect(im.buttons.map((b) => b.type)).toEqual(['primary', 'default', 'danger']);++ // IM 的「总是允许」toolName 取自 pendingInteractions 存的原请求+ const imDecisions = im.buttons.map((b) =>+ imDecisionFromButton(b.id, b.payload as Record<string, unknown>, 'Bash'),+ );+ const hookDecisions = hook.card.buttons.map((b) => hook.decisions.get(b.id));+ expect(hookDecisions).toEqual([+ { kind: 'permission', behavior: 'allow' },+ {+ kind: 'permission',+ behavior: 'allow',+ permissionUpdates: [+ {+ type: 'addRules',+ rules: [{ toolName: 'Bash' }],+ behavior: 'allow',+ destination: SESSION_PERMISSION_DESTINATION,+ },+ ],+ },+ { kind: 'permission', behavior: 'deny', reason: 'user_denied' },+ ]);+ expect(imDecisions).toEqual(hookDecisions);++ // 两侧都渲染 toolName 与入参摘要, 但上限不同(600 单行 vs 800 pretty) —— 渲染差异+ expect(hook.card.body).toContain('Bash');+ expect(hook.card.body.length).toBeLessThan(800);+ expect(im.body).toContain('command');+ expect(im.body!.length).toBeLessThan(1000);+ });++ it('安全默认: IM cancelPending 与 hook defaultDecision 同形(只有 reason 由渠道给)', async () => {+ const reason = 'turn_closed';+ for (const req of [ASK_NO_OPTIONS, PLAN_LONG, PERMISSION_RICH]) {+ const model = composeInteractionModel(req)!;+ const p = registerPending(req.requestId, model.kind, 'msg-1');+ expect(cancelPending(req.requestId, reason)).toBe(true);+ await expect(p).resolves.toEqual(model.buildDefaultDecision(reason));+ }+ // hook 侧同一模型 + 自己的超时 reason+ const hookPerm = composeInteractionCard(PERMISSION_RICH)!;+ expect(hookPerm.defaultDecision).toEqual(+ composeInteractionModel(PERMISSION_RICH).buildDefaultDecision('hook_interaction_timeout'),+ );+ const hookPlan = composeInteractionCard(PLAN_LONG)!;+ expect(hookPlan.defaultDecision).toEqual(+ composeInteractionModel(PLAN_LONG).buildDefaultDecision('hook_interaction_timeout'),+ );+ const hookAsk = composeInteractionCard(ASK_NO_OPTIONS)!;+ expect(hookAsk.defaultDecision).toEqual({ kind: 'ask_user_question', answers: {} });+ });+});diff --git a/apps/desktop/src/main/im/shared/cardActionHandler.ts b/apps/desktop/src/main/im/shared/cardActionHandler.tsindex 86fc727a94..41d97bee69 100644--- a/apps/desktop/src/main/im/shared/cardActionHandler.ts+++ b/apps/desktop/src/main/im/shared/cardActionHandler.ts@@ -18,7 +18,6 @@ import fs from 'node:fs';import type { ChannelIM, IMCardActionEvent } from '@cindy/im';import {- createSessionPermissionUpdate,hasSessionPermissionUpdates,type AgentKind,type Effort,@@ -75,6 +74,16 @@ import {} from './sessionRepo';import { changeSessionPermissionMode } from './permissionModeControl';import type { ImCardBuilders } from './cardBuilders';+import {+ buildAskAnswerDecision,+ buildPermissionAllowAlwaysDecision,+ buildPermissionAllowOnceDecision,+ buildPermissionDenyDecision,+ buildPlanApproveDecision,+ buildPlanDenyDecision,+ PERMISSION_USER_DENIED_REASON,+ PLAN_USER_REJECTED_REASON,+} from './interactionCardModel';import type { ImTurnRunner } from './turnRunner';import type { ImChannelAdapter } from './types';@@ -1204,7 +1213,7 @@ export function createCardActionHandler(const requestId = String(p.requestId ?? '');switch (event.buttonId) {case 'permission:allow:once':- return { kind: 'permission', behavior: 'allow' };+ return buildPermissionAllowOnceDecision();case 'permission:allow:always': {// "Allow always for this session": ask the SDK to add a session-scoped// allow rule for the same toolName so subsequent calls of the same tool@@ -1215,26 +1224,16 @@ export function createCardActionHandler(if (!toolName) {// No toolName recoverable — degrade to plain allow (one-shot). User// sees the same outcome as "allow once" for this single call.- return { kind: 'permission', behavior: 'allow' };+ return buildPermissionAllowOnceDecision();}- return {- kind: 'permission',- behavior: 'allow',- permissionUpdates: [- createSessionPermissionUpdate({- type: 'addRules',- rules: [{ toolName }],- behavior: 'allow',- }),- ],- };+ return buildPermissionAllowAlwaysDecision(toolName);}case 'permission:deny':- return { kind: 'permission', behavior: 'deny', reason: 'user_denied' };+ return buildPermissionDenyDecision(PERMISSION_USER_DENIED_REASON);case 'plan:approve':- return { kind: 'plan_review', behavior: 'allow' };+ return buildPlanApproveDecision();case 'plan:reject':- return { kind: 'plan_review', behavior: 'deny', reason: 'user_rejected', dismissed: true };+ return buildPlanDenyDecision(PLAN_USER_REJECTED_REASON);case 'ask:pick':case 'ask:noop': {// answers 的 key 必须是 question.question 全文 — SDK 用全文匹配@@ -1244,7 +1243,7 @@ export function createCardActionHandler(// 历史 payload, 新卡片(cardBuilders.ts)总是带 questionText。const qKey = String(p.questionText ?? p.questionHeader ?? 'q');const label = String(p.optionLabel ?? '');- return { kind: 'ask_user_question', answers: { [qKey]: label } };+ return buildAskAnswerDecision(qKey, label);}default:return null;diff --git a/apps/desktop/src/main/im/shared/cardBuilders.ts b/apps/desktop/src/main/im/shared/cardBuilders.tsindex e1603e6a24..34782e533e 100644--- a/apps/desktop/src/main/im/shared/cardBuilders.ts+++ b/apps/desktop/src/main/im/shared/cardBuilders.ts@@ -18,7 +18,6 @@import type {InteractionRequest,AgentKind,- AskUserQuestionItem,Effort,PermissionModeDescriptor,} from '@cindy/maker-core';@@ -27,20 +26,22 @@ import type { Schedule, ScheduleRun } from '@cindy/maker-scheduler';import type { InteractiveCardSpec } from '@cindy/im';import type { ImUiTextPack } from './types';+import {+ composeInteractionModel,+ truncateBlock,+ BTN_LABEL_MAX,+ IM_PERMISSION_INPUT_PREVIEW_MAX,+ MAX_PLAN_LEN,+} from './interactionCardModel';import type { ControlProject, ControlSession, RecentControlSession } from './controlProjects';-const MAX_PLAN_LEN = 1500;-const MAX_INPUT_PREVIEW = 800;-const MAX_OPTIONS = 6;--function truncate(s: string, max: number): string {- if (!s) return '';- return s.length > max ? `${s.slice(0, max)}\n\n…(已截断)` : s;-}+/** IM 卡片文本截断(实现见 interactionCardModel.truncateBlock)。 */+const truncate = truncateBlock;+/** 工具入参 -> pretty JSON 预览(IM 卡片正文有排版空间, 与 hook 侧的单行摘要不同)。 */function previewInput(input: Record<string, unknown>): string {try {- return truncate(JSON.stringify(input, null, 2), MAX_INPUT_PREVIEW);+ return truncate(JSON.stringify(input, null, 2), IM_PERMISSION_INPUT_PREVIEW_MAX);} catch {return '<unserializable>';}@@ -114,9 +115,10 @@ export function createCardBuilders(// ── permission ──────────────────────────────────────────────────────────buildPermissionCard(req) {+ const model = composeInteractionModel(req);return {- title: ui.cards.permission.title(req.toolName),- body: `${ui.cards.permission.paramsLabel}\n\`\`\`json\n${previewInput(req.input)}\n\`\`\``,+ title: ui.cards.permission.title(model.toolName),+ body: `${ui.cards.permission.paramsLabel}\n\`\`\`json\n${previewInput(model.input)}\n\`\`\``,buttons: [{id: 'permission:allow:once',@@ -141,22 +143,17 @@ export function createCardBuilders(},// ── ask_user_question ───────────────────────────────────────────────────- // v1 simplification (mirrors legacy cardRenderer behaviour):- // - render only the FIRST question- // - max 6 options (single-select); multiSelect is downgraded to single-select+ // v1 简化(只渲染第一问 / 至多 6 个选项 / multiSelect 降级单选)已收进+ // interactionCardModel.composeInteractionModel — 这里只做渲染。buildAskUserCard(req) {- const question: AskUserQuestionItem | undefined = req.questions[0];- if (!question) return null;+ const model = composeInteractionModel(req);+ if (!model) return null;- const headerText = question.header || question.question;- const options = (question.options ?? []).slice(0, MAX_OPTIONS);- const bodyExtra =- question.header && question.header !== question.question- ? `\n${question.question}`- : '';+ const { headerText, question } = model;+ const bodyExtra = model.questionBody ? `\n${model.questionBody}` : '';- if (options.length === 0) {+ if (model.degraded) {return {title: ui.cards.ask.title(headerText),body: bodyExtra@@ -165,7 +162,7 @@ export function createCardBuilders(buttons: [{id: 'ask:noop',- label: '继续',+ label: model.choices[0].label ?? '',type: 'default',payload: {requestId: req.requestId,@@ -174,7 +171,7 @@ export function createCardBuilders(// headerText 只作卡片标题, 不参与 answers 匹配。questionText: question.question,questionHeader: headerText,- optionLabel: '',+ optionLabel: model.choices[0].answerText ?? '',},},],@@ -184,15 +181,15 @@ export function createCardBuilders(return {title: ui.cards.ask.title(headerText),body: bodyExtra || ' ',- buttons: options.map((opt) => ({+ buttons: model.choices.map((choice) => ({id: 'ask:pick',- label: truncate(opt.label, 30),+ label: truncate(choice.label ?? '', BTN_LABEL_MAX),type: 'default' as const,payload: {requestId: req.requestId,questionText: question.question,questionHeader: headerText,- optionLabel: opt.label,+ optionLabel: choice.answerText ?? '',},})),};@@ -201,9 +198,10 @@ export function createCardBuilders(// ── plan_review ─────────────────────────────────────────────────────────buildPlanReviewCard(req) {+ const model = composeInteractionModel(req);return {title: ui.cards.plan.title,- body: truncate(req.plan, MAX_PLAN_LEN),+ body: truncate(model.plan, MAX_PLAN_LEN),buttons: [{id: 'plan:approve',diff --git a/apps/desktop/src/main/im/shared/interactionCardModel.ts b/apps/desktop/src/main/im/shared/interactionCardModel.tsnew file mode 100644index 0000000000..a17918e94c--- /dev/null+++ b/apps/desktop/src/main/im/shared/interactionCardModel.ts@@ -0,0 +1,310 @@+/**+ * main/im/shared/interactionCardModel.ts+ * ---------------------------------------------------------------------------+ * ask_user_question / plan_review / permission 三类交互卡的**语义层**单一出处。+ *+ * 背景: 同一产品能力此前有两份人肉对齐的实现 —— 个人 IM 侧+ * (im/shared/cardBuilders + cardActionHandler) 与 hook 侧+ * (hook-control/interactions)。两边的 v1 简化规则(只渲染第一问、至多 6 个选项、+ * multiSelect 降级单选、plan 正文截断)与决策对象形状必须一致, 靠注释互相引用维持+ * 太脆。这里把「选项集 + 决策对象 + header/body 拆分」收进一处, 两侧只做渲染:+ * - IM 侧渲染 @cindy/im InteractiveCardSpec(按钮 payload 是历史兼容契约);+ * - hook 侧渲染 slack-hook-protocol 的按钮卡 + buttonId -> 决策映射。+ *+ * **渠道差异不在这里统一**(统一是产品决策, 不归本模块): 按钮文案(IM 走 ui 文案包 /+ * hook 走本端硬编码)、卡片标题格式、截断省略号样式、permission 入参摘要上限+ * (hook 600 单行 / IM 800 pretty)都是渲染参数, 由各自渲染侧持有, 本模块只提供+ * 截断工具与常量。+ */++// 只做 type-only 依赖: 本模块被 hook-control/interactions 复用, 那条链路刻意+// 不在运行期加载 maker-core barrel(session-runner 单测按最小面 mock 该包)。+import type {+ AskUserQuestionItem,+ InteractionDecision,+ InteractionRequest,+} from '@cindy/maker-core';++// ── 语义常量 ────────────────────────────────────────────────────────────────++/** ask 卡渲染的最大选项数(v1: 单选, 超出部分丢弃)。 */+export const MAX_OPTIONS = 6;+/** plan 正文截断长度。 */+export const MAX_PLAN_LEN = 1500;+/** 按钮文案截断(Slack plain_text 上限 75, 对齐 IM 的 30)。 */+export const BTN_LABEL_MAX = 30;+/**+ * permission 卡的工具入参摘要截断 —— 两侧**刻意不同**, 属渲染差异:+ * hook 卡是单行 JSON 摘要(卡片只要能看清意图), IM 卡是 pretty JSON 代码块。+ */+export const HOOK_PERMISSION_INPUT_SUMMARY_MAX = 600;+export const IM_PERMISSION_INPUT_PREVIEW_MAX = 800;+/** 无选项降级时唯一按钮的文案(两侧一致)。 */+export const ASK_CONTINUE_LABEL = '继续';++// ── 截断工具 ────────────────────────────────────────────────────────────────++/** IM 卡片截断: 折行后追加「…(已截断)」(卡片正文有排版空间)。 */+export function truncateBlock(s: string, max: number): string {+ if (!s) return '';+ return s.length > max ? `${s.slice(0, max)}\n\n…(已截断)` : s;+}++/** hook 卡片截断: 单行省略号(标题 / 单行摘要用)。 */+export function truncateInline(s: string, max: number): string {+ if (!s) return '';+ return s.length > max ? `${s.slice(0, max)}…` : s;+}++// ── 决策构造(唯一出处) ──────────────────────────────────────────────────────++/**+ * ask 的一条答案。+ *+ * answers 的 key 必须是 question.question 全文 — SDK 用全文匹配+ * (cc-code QuestionView.tsx:167: questionText = question.question)。+ * questionHeader 只是卡片标题 chip, 用它做 key 会让模型在 answers 里找不到+ * 自己的问题, 误判"用户没选答案"。(出处: im/shared/cardActionHandler+ * decisionFromPress 的 qKey 注释 + hook-control/interactions。)+ */+export function buildAskAnswerDecision(+ questionText: string,+ answerText: string,+): InteractionDecision {+ return { kind: 'ask_user_question', answers: { [questionText]: answerText } };+}++/** ask 的安全默认: 空 answers(超时 / turn 收口 = "未回答"继续)。 */+export function buildAskNoAnswerDecision(): InteractionDecision {+ return { kind: 'ask_user_question', answers: {} };+}++/** permission: 只允许这一次。 */+export function buildPermissionAllowOnceDecision(): InteractionDecision {+ return { kind: 'permission', behavior: 'allow' };+}++/**+ * permission: 「本任务总是允许」。+ *+ * 会话级 addRules: claude-code 直接消费(同 toolName 的后续调用跳过 canUseTool+ * 回调); codex 把非空 permissionUpdates 视为会话级放行(见 maker-core events.ts+ * 的 permissionUpdates 注释)。+ *+ * 注: 按钮文案用「任务」(产品术语, 与应用内 permissions.alwaysAllowForSession+ * 一致), 但 addRules 的作用域是技术意义上的 agent session, 两者刻意不同名。+ *+ * destination 与 maker-core 的 SESSION_PERMISSION_DESTINATION /+ * createSessionPermissionUpdate 同值, 这里就地写死只为不给 hook 链路引入+ * maker-core 运行期依赖; 漂移由本模块单测钉住(见 __tests__)。+ */+export function buildPermissionAllowAlwaysDecision(toolName: string): InteractionDecision {+ return {+ kind: 'permission',+ behavior: 'allow',+ permissionUpdates: [+ { type: 'addRules', rules: [{ toolName }], behavior: 'allow', destination: 'session' },+ ],+ };+}++/** permission 拒绝(reason 是渠道语义: 用户点拒绝 / 超时 / turn 收口)。 */+export function buildPermissionDenyDecision(reason: string): InteractionDecision {+ return { kind: 'permission', behavior: 'deny', reason };+}++/** plan: 批准执行。 */+export function buildPlanApproveDecision(): InteractionDecision {+ return { kind: 'plan_review', behavior: 'allow' };+}++/**+ * plan: 打回 / 未获批准。恒带 dismissed —— 系统性 dismissal, 别让 codex 把+ * reason 当用户反馈发起修订 turn。+ */+export function buildPlanDenyDecision(reason: string): InteractionDecision {+ return { kind: 'plan_review', behavior: 'deny', reason, dismissed: true };+}++/** 用户点「打回」的 reason(两侧一致)。 */+export const PLAN_USER_REJECTED_REASON = 'user_rejected';+/** 用户点「拒绝」的 reason(两侧一致)。 */+export const PERMISSION_USER_DENIED_REASON = 'user_denied';++// ── 语义模型 ────────────────────────────────────────────────────────────────++export type InteractionChoiceStyle = 'primary' | 'default' | 'danger';++/** 一个可按下的选项(渠道各自映射到自己的历史 buttonId, choiceId 不过网线)。 */+export interface InteractionChoice {+ /** 稳定语义 id。 */+ choiceId: string;+ /** 选项序号(hook 侧按 index 生成 buttonId)。 */+ index: number;+ /**+ * 按钮文案来自请求数据时为原文、未截断(ask 选项);来自渠道文案包时为 null+ * (permission / plan 的按钮文案是渲染侧资产)。+ */+ label: string | null;+ /** ask 专用: 写进 answers 的答案文本(无选项降级时为空串)。 */+ answerText?: string;+ style: InteractionChoiceStyle;+ /** 按下即生效的决策。 */+ decision: InteractionDecision;+}++interface BaseInteractionModel {+ choices: InteractionChoice[];+ /** 超时 / turn 收口时的安全默认决策(reason 由渠道给, 文案语义不同)。 */+ buildDefaultDecision(reason: string): InteractionDecision;+}++export interface AskInteractionModel extends BaseInteractionModel {+ kind: 'ask_user_question';+ /** v1: 只取第一问。 */+ question: AskUserQuestionItem;+ /** 卡片标题文本: header 优先, 缺省用问题全文。 */+ headerText: string;+ /** header 与 question 不同才把 question 放正文, 否则空串。 */+ questionBody: string;+ /** true = 自由问答无选项, 降级为唯一的「继续」(空答案)。 */+ degraded: boolean;+}++export interface PlanInteractionModel extends BaseInteractionModel {+ kind: 'plan_review';+ /** 正文原文(截断在渲染侧 —— 省略号样式两侧不同)。 */+ plan: string;+}++export interface PermissionInteractionModel extends BaseInteractionModel {+ kind: 'permission';+ toolName: string;+ /** hook 卡标题用的展示名: displayName > title > toolName。 */+ displayTitle: string;+ description: string;+ input: Record<string, unknown>;+}++export type InteractionModel =+ AskInteractionModel | PlanInteractionModel | PermissionInteractionModel;++/**+ * InteractionRequest -> 语义模型。返回 null = 不出卡, 调用方按 kind 安全默认+ * 就地自决(ask 没有问题项, 或未来未知 kind)。+ *+ * v1 简化(两侧共用, 同一产品能力的两个渠道不该有体验分叉):+ * - ask 只渲染第一道问题;+ * - 至多 MAX_OPTIONS 个选项, multiSelect 降级单选;+ * - 无选项时降级成单个「继续」(空答案) —— 无人值守链路给不了自由文本。+ */+export function composeInteractionModel(+ req: Extract<InteractionRequest, { kind: 'ask_user_question' }>,+): AskInteractionModel | null;+export function composeInteractionModel(+ req: Extract<InteractionRequest, { kind: 'plan_review' }>,+): PlanInteractionModel;+export function composeInteractionModel(+ req: Extract<InteractionRequest, { kind: 'permission' }>,+): PermissionInteractionModel;+export function composeInteractionModel(req: InteractionRequest): InteractionModel | null;+export function composeInteractionModel(req: InteractionRequest): InteractionModel | null {+ if (req.kind === 'ask_user_question') {+ const question = req.questions[0];+ if (!question) return null;+ const headerText = question.header || question.question;+ const options = (question.options ?? []).slice(0, MAX_OPTIONS);+ const questionBody =+ question.header && question.header !== question.question ? question.question : '';+ const choices: InteractionChoice[] =+ options.length === 0+ ? [+ {+ choiceId: 'ask:continue',+ index: 0,+ label: ASK_CONTINUE_LABEL,+ answerText: '',+ style: 'default',+ decision: buildAskAnswerDecision(question.question, ''),+ },+ ]+ : options.map((opt, index) => ({+ choiceId: `ask:option:${index}`,+ index,+ label: opt.label,+ answerText: opt.label,+ style: 'default' as const,+ decision: buildAskAnswerDecision(question.question, opt.label),+ }));+ return {+ kind: 'ask_user_question',+ question,+ headerText,+ questionBody,+ degraded: options.length === 0,+ choices,+ buildDefaultDecision: () => buildAskNoAnswerDecision(),+ };+ }++ if (req.kind === 'plan_review') {+ return {+ kind: 'plan_review',+ plan: req.plan,+ choices: [+ {+ choiceId: 'plan:approve',+ index: 0,+ label: null,+ style: 'primary',+ decision: buildPlanApproveDecision(),+ },+ {+ choiceId: 'plan:reject',+ index: 1,+ label: null,+ style: 'danger',+ decision: buildPlanDenyDecision(PLAN_USER_REJECTED_REASON),+ },+ ],+ buildDefaultDecision: (reason) => buildPlanDenyDecision(reason),+ };+ }++ if (req.kind === 'permission') {+ return {+ kind: 'permission',+ toolName: req.toolName,+ displayTitle: req.displayName ?? req.title ?? req.toolName,+ description: req.description ?? '',+ input: req.input,+ choices: [+ {+ choiceId: 'permission:allow-once',+ index: 0,+ label: null,+ style: 'primary',+ decision: buildPermissionAllowOnceDecision(),+ },+ {+ choiceId: 'permission:allow-always',+ index: 1,+ label: null,+ style: 'default',+ decision: buildPermissionAllowAlwaysDecision(req.toolName),+ },+ {+ choiceId: 'permission:deny',+ index: 2,+ label: null,+ style: 'danger',+ decision: buildPermissionDenyDecision(PERMISSION_USER_DENIED_REASON),+ },+ ],+ buildDefaultDecision: (reason) => buildPermissionDenyDecision(reason),+ };+ }++ // 未来未知 kind: 不出卡, 调用方按 kind 安全默认就地自决+ return null;+}diff --git a/apps/desktop/src/main/im/shared/pendingInteractions.ts b/apps/desktop/src/main/im/shared/pendingInteractions.tsindex bb1e826ade..7da649809c 100644--- a/apps/desktop/src/main/im/shared/pendingInteractions.ts+++ b/apps/desktop/src/main/im/shared/pendingInteractions.ts@@ -12,6 +12,12 @@import type { InteractionDecision } from '@cindy/maker-core';+import {+ buildAskNoAnswerDecision,+ buildPermissionDenyDecision,+ buildPlanDenyDecision,+} from './interactionCardModel';+interface PendingEntry {resolve: (decision: InteractionDecision) => void;reject: (err: Error) => void;@@ -88,20 +94,23 @@ export function resolvePending(return { messageId: entry.messageId };}-/** Resolve one pending card with the safe decision used when its turn ends. */+/**+ * Resolve one pending card with the safe decision used when its turn ends.+ * 安全默认与 hook 链路同源(interactionCardModel), 只有 reason 文案按渠道给。+ */export function cancelPending(requestId: string, reason: string): boolean {const entry = pending.get(requestId);if (!entry) return false;pending.delete(requestId);if (entry.kind === 'ask_user_question') {- entry.resolve({ kind: 'ask_user_question', answers: {} });+ entry.resolve(buildAskNoAnswerDecision());return true;}if (entry.kind === 'plan_review') {- entry.resolve({ kind: 'plan_review', behavior: 'deny', reason, dismissed: true });+ entry.resolve(buildPlanDenyDecision(reason));return true;}- entry.resolve({ kind: 'permission', behavior: 'deny', reason });+ entry.resolve(buildPermissionDenyDecision(reason));return true;}