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(desktop): 权限卡片写明「允许这一类」的具体范围 (#546)

Dash2421560d7b56
diff --git a/apps/desktop/src/renderer/__tests__/permissionSuggestionScope.test.ts b/apps/desktop/src/renderer/__tests__/permissionSuggestionScope.test.ts
new file mode 100644
index 0000000000..b91c8313fb
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/permissionSuggestionScope.test.ts
@@ -0,0 +1,95 @@
+/**
+ * permissionSuggestionScope.test.ts
+ * ---------------------------------------------------------------------------
+ * 权限卡片上那个按钮原本只写「本对话总是允许」,既没说允许的是哪一类,也容易被读成
+ * 「什么都允许」。范围文本由本模块从 agent 给的授权建议里提取,所以这里锁死两件事:
+ * 能描述时给出**准确**的规则原文(不意译、不放宽);只要有**任何一项**授权项描述不完整
+ * 就整体返回 null。后者是安全要求:点击会把 suggestions 里每一项都转发成
+ * updatedPermissions,文案漏掉一项(比如混进来的 setMode)就等于一边宣称「只允许这一类」、
+ * 一边顺手改了权限档位。分隔符交给调用方按语言拼,这里只返回结构化清单。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { describeSessionPermissionScope } from '../lib/permissionSuggestionScope';
+
+const sessionRule = (rules: unknown[]) => ({
+ type: 'addRules',
+ rules,
+ behavior: 'allow',
+ destination: 'session',
+});
+
+describe('describeSessionPermissionScope', () => {
+ it('带 ruleContent 的规则显示成 工具(规则)', () => {
+ expect(
+ describeSessionPermissionScope([sessionRule([{ toolName: 'Bash', ruleContent: 'curl:*' }])]),
+ ).toEqual(['Bash(curl:*)']);
+ });
+
+ it('无 ruleContent 的规则只显示工具名(MCP 工具常见)', () => {
+ expect(
+ describeSessionPermissionScope([sessionRule([{ toolName: 'mcp__feishu__call_tool' }])]),
+ ).toEqual(['mcp__feishu__call_tool']);
+ });
+
+ it('多条规则全部列出,并按原文去重', () => {
+ expect(
+ describeSessionPermissionScope([
+ sessionRule([
+ { toolName: 'Bash', ruleContent: 'curl:*' },
+ { toolName: 'Bash', ruleContent: 'git:*' },
+ ]),
+ sessionRule([{ toolName: 'Bash', ruleContent: 'curl:*' }]),
+ ]),
+ ).toEqual(['Bash(curl:*)', 'Bash(git:*)']);
+ });
+
+ // 只有「加一条放行规则」才是这个按钮的语义。其余类型拿来生成文案会说谎:
+ // removeRules 是收紧、setMode 是换档位,都不是「以后允许这一类」。
+ it('只认 addRules + allow,其它类型不描述', () => {
+ expect(describeSessionPermissionScope([
+ { type: 'removeRules', rules: [{ toolName: 'Bash' }], behavior: 'allow', destination: 'session' },
+ ])).toBeNull();
+ expect(describeSessionPermissionScope([
+ { type: 'addRules', rules: [{ toolName: 'Bash' }], behavior: 'deny', destination: 'session' },
+ ])).toBeNull();
+ expect(describeSessionPermissionScope([
+ { type: 'setMode', mode: 'bypassPermissions', destination: 'session' },
+ ])).toBeNull();
+ });
+
+ it('形状不认识时返回 null,不猜也不兜底放宽', () => {
+ expect(describeSessionPermissionScope([])).toBeNull();
+ expect(describeSessionPermissionScope([null, 'nope', 42])).toBeNull();
+ expect(describeSessionPermissionScope([sessionRule([{ ruleContent: 'curl:*' }])])).toBeNull();
+ expect(describeSessionPermissionScope([sessionRule([{ toolName: ' ' }])])).toBeNull();
+ expect(describeSessionPermissionScope([sessionRule('not-an-array' as unknown as unknown[])])).toBeNull();
+ });
+
+ // 关键安全用例:混进一项描述不出来的授权,整个范围声明必须放弃 —— 否则按钮会
+ // 宣称「只允许 Bash(curl:*)」,而点击时把那条未列出的 update 一起交出去。
+ it('任何一项描述不全 → 整体放弃,不做部分声明', () => {
+ expect(
+ describeSessionPermissionScope([
+ sessionRule([{ toolName: 'Bash', ruleContent: 'curl:*' }, { notAToolRule: true }]),
+ ]),
+ ).toBeNull();
+ expect(
+ describeSessionPermissionScope([
+ sessionRule([{ toolName: 'Bash', ruleContent: 'curl:*' }]),
+ { type: 'setMode', mode: 'bypassPermissions', destination: 'session' },
+ ]),
+ ).toBeNull();
+ expect(
+ describeSessionPermissionScope([
+ sessionRule([{ toolName: 'Bash', ruleContent: 'curl:*' }]),
+ { type: 'replaceRules', rules: [{ toolName: 'Bash' }], behavior: 'allow', destination: 'session' },
+ ]),
+ ).toBeNull();
+ });
+
+ it('rules 为空数组也算描述不出来', () => {
+ expect(describeSessionPermissionScope([sessionRule([])])).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
index b174ec0ccf..6dd73eb74f 100644
--- a/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx
@@ -17,7 +17,9 @@ import { useCallback, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
+import { Tip } from '@/components/ui/tooltip';
import type { PendingPermission } from '@/lib/makerChatStore';
+import { describeSessionPermissionScope } from '@/lib/permissionSuggestionScope';
// ---------------------------------------------------------------------------
// Props
@@ -75,6 +77,15 @@ export function PermissionPrompt({ permission, onRespond }: PermissionPromptProp
const codeContent = formatToolInput(toolName, input);
const sessionSuggestions = useMemo(() => filterSessionScopedSuggestions(suggestions), [suggestions]);
const canAlwaysAllowForSession = sessionSuggestions.length > 0;
+ // 这个按钮加的是 agent 给的一条具体规则(Bash 多为 `curl:*` 这类前缀模式),
+ // 范围远小于「总是允许」的字面。把范围写到按钮上,别让用户猜。
+ // 描述不全时返回 null(见该函数顶注:点击会转发**全部** suggestions,文案漏项就是说谎),
+ // 此时退回不声称范围的原文案。分隔符按当前语言取 —— 顿号不能漏进英文句子。
+ const scopeLabels = useMemo(
+ () => describeSessionPermissionScope(sessionSuggestions),
+ [sessionSuggestions],
+ );
+ const allowScope = scopeLabels?.join(t('newChat.permissionPrompt.ruleSeparator')) ?? null;
// ── Action handlers ──
@@ -162,8 +173,10 @@ export function PermissionPrompt({ permission, onRespond }: PermissionPromptProp
<pre className="whitespace-pre-wrap break-all">{codeContent}</pre>
</div>
- {/* Action buttons — inline text + kbd badges, right-aligned */}
- <div className="mt-4 flex items-center justify-end gap-2">
+ {/* Action buttons — inline text + kbd badges, right-aligned.
+ flex-wrap:带范围的「本对话都允许 …」按钮会比原来长,窄宽(doc rail portal)
+ 下允许整行折行,而不是把 Deny / Allow once 挤出容器。 */}
+ <div className="mt-4 flex flex-wrap items-center justify-end gap-2">
{/* Deny */}
<button
type="button"
@@ -182,24 +195,44 @@ export function PermissionPrompt({ permission, onRespond }: PermissionPromptProp
</button>
{canAlwaysAllowForSession && (
- <button
- type="button"
- onClick={handleAlwaysAllow}
- className={cn(
- 'flex items-center gap-2 rounded-[8px] border px-3 py-[7px]',
- 'border-[var(--chat-input-border)] bg-transparent',
- 'text-13 font-medium text-[var(--chat-input-text)]',
- 'transition-colors hover:bg-[var(--perm-code-bg)]',
- )}
+ // 有具体规则就把范围写进按钮(`本对话都允许 Bash(curl:*)`),没有则退回原文案。
+ // tooltip 补两件按钮里放不下的事:完整规则(长命令会被 truncate)、以及
+ // 「作用于整个对话」——用户容易把「本对话」读成「这一次来回」。
+ // 列不出范围时(Codex 的会话级放行只给一个不带规则的标记,范围由 app-server 定)
+ // 换成只讲时效的说法:一条都没列出还说「只限这里列出的范围」就是虚假安心。
+ <Tip
+ text={
+ allowScope
+ ? `${allowScope}\n${t('newChat.permissionPrompt.alwaysAllowScopedHint')}`
+ : t('newChat.permissionPrompt.alwaysAllowSessionHint')
+ }
+ side="top"
+ contentClassName="max-w-[320px] whitespace-pre-line break-all text-left"
>
- <span>{t('agentIsland.native.alwaysAllowForSession')}</span>
- <kbd className="rounded-[4px] border border-[var(--chat-input-border)] bg-[var(--perm-code-bg)] px-1.5 py-[1px] text-11 font-normal text-[var(--status-bar-meta)]">
- Ctrl
- </kbd>
- <kbd className="-ml-1 rounded-[4px] border border-[var(--chat-input-border)] bg-[var(--perm-code-bg)] px-1.5 py-[1px] text-11 font-normal text-[var(--status-bar-meta)]">
- Enter
- </kbd>
- </button>
+ <button
+ type="button"
+ onClick={handleAlwaysAllow}
+ className={cn(
+ // max-w:规则可能很长(完整命令串),截断后完整内容看 tooltip。
+ 'flex min-w-0 max-w-[460px] items-center gap-2 rounded-[8px] border px-3 py-[7px]',
+ 'border-[var(--chat-input-border)] bg-transparent',
+ 'text-13 font-medium text-[var(--chat-input-text)]',
+ 'transition-colors hover:bg-[var(--perm-code-bg)]',
+ )}
+ >
+ <span className="min-w-0 truncate">
+ {allowScope
+ ? t('newChat.permissionPrompt.alwaysAllowScoped', { scope: allowScope })
+ : t('agentIsland.native.alwaysAllowForSession')}
+ </span>
+ <kbd className="shrink-0 rounded-[4px] border border-[var(--chat-input-border)] bg-[var(--perm-code-bg)] px-1.5 py-[1px] text-11 font-normal text-[var(--status-bar-meta)]">
+ Ctrl
+ </kbd>
+ <kbd className="-ml-1 shrink-0 rounded-[4px] border border-[var(--chat-input-border)] bg-[var(--perm-code-bg)] px-1.5 py-[1px] text-11 font-normal text-[var(--status-bar-meta)]">
+ Enter
+ </kbd>
+ </button>
+ </Tip>
)}
{/* Allow once (primary) */}
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx
new file mode 100644
index 0000000000..abab135000
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/PermissionPrompt.test.tsx
@@ -0,0 +1,177 @@
+// @vitest-environment jsdom
+/**
+ * PermissionPrompt.test.tsx — 「本对话都允许」按钮的范围表达。
+ *
+ * 这个按钮加的是 agent 给的一条具体规则,范围远小于「总是允许」的字面。原文案既没说
+ * 允许的是哪一类,也容易被读成「什么都允许」。这里锁死:能描述规则时范围出现在按钮上,
+ * 描述不出来时退回原文案(而不是编一个范围),以及按钮的授权载荷一字不改地转发 agent
+ * 建议 —— 文案怎么写都不该动实际授权内容。
+ */
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { PendingPermission } from '@/lib/makerChatStore';
+
+// 仓库同款 i18n mock:t 返回 key(带参时拼上参数便于断言)。
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, args?: Record<string, unknown>) =>
+ args && Object.keys(args).length > 0 ? `${key}:${JSON.stringify(args)}` : key,
+ }),
+}));
+
+// Tip 是 Radix 浮层,这里不测浮层行为,但 text 必须落到 DOM 里 ——
+// tooltip 正文也是授权文案,漏测就等于放过「说了没依据的话」这类问题。
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ children, text }: { children: React.ReactNode; text?: string }) => (
+ <>
+ {children}
+ <span data-testid="tip-text">{text}</span>
+ </>
+ ),
+}));
+
+import { PermissionPrompt } from '../PermissionPrompt';
+
+afterEach(cleanup);
+
+const bashRule = {
+ type: 'addRules',
+ rules: [{ toolName: 'Bash', ruleContent: 'curl:*' }],
+ behavior: 'allow',
+ destination: 'session',
+};
+
+function permission(suggestions?: unknown[]): PendingPermission {
+ return {
+ requestId: 'req-1',
+ toolName: 'Bash',
+ input: { command: 'curl -s https://example.com' },
+ ...(suggestions ? { suggestions } : {}),
+ };
+}
+
+describe('PermissionPrompt 的会话级授权按钮', () => {
+ it('把规则范围写进按钮文案', () => {
+ render(<PermissionPrompt permission={permission([bashRule])} onRespond={vi.fn()} />);
+
+ expect(
+ screen.getByText('newChat.permissionPrompt.alwaysAllowScoped:{"scope":"Bash(curl:*)"}'),
+ ).toBeTruthy();
+ });
+
+ it('规则描述不出来时退回原文案,不编造范围', () => {
+ const unknownShape = { type: 'setMode', mode: 'bypassPermissions', destination: 'session' };
+ render(<PermissionPrompt permission={permission([unknownShape])} onRespond={vi.fn()} />);
+
+ expect(screen.getByText('agentIsland.native.alwaysAllowForSession')).toBeTruthy();
+ expect(screen.queryByText(/alwaysAllowScoped:/)).toBeNull();
+ });
+
+ // Codex 的会话级放行只给一个不带规则的标记(范围由 app-server 定),这条分支必然走到。
+ // 此时 tooltip 不许说「只限这里列出的范围」—— 一条都没列出,那句话是虚假安心。
+ it('列不出范围时提示只讲时效,不声称范围', () => {
+ render(
+ <PermissionPrompt
+ permission={permission([{ type: 'codexSessionApproval', destination: 'session' }])}
+ onRespond={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('tip-text').textContent).toBe(
+ 'newChat.permissionPrompt.alwaysAllowSessionHint',
+ );
+ });
+
+ // 有范围时反过来:完整规则原文进 tooltip(按钮里长命令会被 truncate)。
+ it('有范围时提示带上完整规则与范围限定', () => {
+ render(<PermissionPrompt permission={permission([bashRule])} onRespond={vi.fn()} />);
+
+ expect(screen.getByTestId('tip-text').textContent).toBe(
+ 'Bash(curl:*)\nnewChat.permissionPrompt.alwaysAllowScopedHint',
+ );
+ });
+
+ // 点击会把 suggestions 里每一项都转发出去。混进一项没写进文案的授权(这里是 setMode)
+ // 时必须退回原文案 —— 否则按钮一边宣称「只允许 Bash(curl:*)」,一边顺手改权限档位。
+ it('授权项描述不全时不做范围声明', () => {
+ render(
+ <PermissionPrompt
+ permission={permission([
+ bashRule,
+ { type: 'setMode', mode: 'bypassPermissions', destination: 'session' },
+ ])}
+ onRespond={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText('agentIsland.native.alwaysAllowForSession')).toBeTruthy();
+ expect(screen.queryByText(/alwaysAllowScoped:/)).toBeNull();
+ // tooltip 也不许替按钮把范围声明补回来。
+ expect(screen.getByTestId('tip-text').textContent).toBe(
+ 'newChat.permissionPrompt.alwaysAllowSessionHint',
+ );
+ });
+
+ // 分隔符按语言取(中日顿号 / 英韩逗号),不能把顿号漏进英文句子。
+ it('多条规则用当前语言的分隔符拼接', () => {
+ render(
+ <PermissionPrompt
+ permission={permission([
+ {
+ type: 'addRules',
+ rules: [
+ { toolName: 'Bash', ruleContent: 'curl:*' },
+ { toolName: 'Bash', ruleContent: 'git:*' },
+ ],
+ behavior: 'allow',
+ destination: 'session',
+ },
+ ])}
+ onRespond={vi.fn()}
+ />,
+ );
+
+ // i18n mock 下 ruleSeparator 返回 key 本身,断言两条规则都在、且中间是分隔符 key。
+ expect(
+ screen.getByRole('button', { name: /alwaysAllowScoped:/ }).textContent,
+ ).toContain('Bash(curl:*)newChat.permissionPrompt.ruleSeparatorBash(git:*)');
+ });
+
+ it('没有会话级建议时整个按钮不出现', () => {
+ render(<PermissionPrompt permission={permission()} onRespond={vi.fn()} />);
+
+ expect(screen.queryByText('agentIsland.native.alwaysAllowForSession')).toBeNull();
+ expect(screen.queryByText(/alwaysAllowScoped/)).toBeNull();
+ // 另两个出口照常。
+ expect(screen.getByText('agentIsland.native.allowOnce')).toBeTruthy();
+ expect(screen.getByText('agentIsland.native.deny')).toBeTruthy();
+ });
+
+ // 文案是展示层的事,授权载荷必须原样转发 agent 的建议 —— 改文案不许改语义。
+ it('点击后原样转发 agent 建议作为授权载荷', () => {
+ const onRespond = vi.fn();
+ render(<PermissionPrompt permission={permission([bashRule])} onRespond={onRespond} />);
+
+ fireEvent.click(
+ screen.getByText('newChat.permissionPrompt.alwaysAllowScoped:{"scope":"Bash(curl:*)"}'),
+ );
+
+ expect(onRespond).toHaveBeenCalledWith({
+ behavior: 'allow',
+ updatedPermissions: [bashRule],
+ decisionClassification: 'user_permanent',
+ });
+ });
+
+ it('Ctrl+Enter 与点击等价', () => {
+ const onRespond = vi.fn();
+ render(<PermissionPrompt permission={permission([bashRule])} onRespond={onRespond} />);
+
+ fireEvent.keyDown(window, { key: 'Enter', code: 'Enter', ctrlKey: true });
+
+ expect(onRespond).toHaveBeenCalledWith(
+ expect.objectContaining({ decisionClassification: 'user_permanent' }),
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8208dfa302..50e48df24a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4289,6 +4289,12 @@
"editTitle": "Edit Pasted Text",
"cancelEdit": "Cancel Editing",
"saveEdit": "Save Text"
+ },
+ "permissionPrompt": {
+ "alwaysAllowScoped": "Always Allow {{scope}} in This Session",
+ "alwaysAllowScopedHint": "Applies to the whole session, and only to what is listed here.",
+ "alwaysAllowSessionHint": "Applies to the whole session, not just this one request.",
+ "ruleSeparator": ", "
}
},
"onboarding": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 0b1022f581..637bed9657 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4288,6 +4288,12 @@
"editTitle": "貼り付けたテキストを編集",
"cancelEdit": "編集をキャンセル",
"saveEdit": "テキストを保存"
+ },
+ "permissionPrompt": {
+ "alwaysAllowScoped": "このセッションでは {{scope}} を常に許可",
+ "alwaysAllowScopedHint": "このセッション全体に適用され、ここに挙げた範囲にのみ及びます。",
+ "alwaysAllowSessionHint": "この 1 回のリクエストだけでなく、このセッション全体に適用されます。",
+ "ruleSeparator": "、"
}
},
"onboarding": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 143b7c4392..fedeb6c2e7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4288,6 +4288,12 @@
"editTitle": "붙여넣은 텍스트 편집",
"cancelEdit": "편집 취소",
"saveEdit": "텍스트 저장"
+ },
+ "permissionPrompt": {
+ "alwaysAllowScoped": "이 세션에서 {{scope}} 항상 허용",
+ "alwaysAllowScopedHint": "이 세션 전체에 적용되며, 여기에 표시된 범위에만 해당합니다.",
+ "alwaysAllowSessionHint": "이번 요청 한 번이 아니라 이 세션 전체에 적용됩니다.",
+ "ruleSeparator": ", "
}
},
"onboarding": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 9e42decbdf..de8315ced8 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4288,6 +4288,12 @@
"editTitle": "编辑粘贴的文本",
"cancelEdit": "取消编辑",
"saveEdit": "保存文本"
+ },
+ "permissionPrompt": {
+ "alwaysAllowScoped": "本对话都允许 {{scope}}",
+ "alwaysAllowScopedHint": "作用于整个对话,且只限这里列出的范围。",
+ "alwaysAllowSessionHint": "作用于整个对话,不只是这一次请求。",
+ "ruleSeparator": "、"
}
},
"onboarding": {
diff --git a/apps/desktop/src/renderer/lib/permissionSuggestionScope.ts b/apps/desktop/src/renderer/lib/permissionSuggestionScope.ts
new file mode 100644
index 0000000000..138d31420d
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/permissionSuggestionScope.ts
@@ -0,0 +1,61 @@
+/**
+ * 把权限请求携带的「会话级授权建议」翻译成一句用户能看懂的范围。
+ *
+ * 为什么需要:权限卡片上那个按钮原本只写「本对话总是允许」,既没说允许的是**哪一类**,
+ * 也容易被读成「什么都允许」。而它实际加的是 agent 给出的一条具体规则(Bash 通常是
+ * `curl:*` 这类前缀模式),范围远小于字面。Claude Code 命令行把范围写进选项文案里
+ * (`don't ask again for curl commands in …`),Cindy 之前没有 —— 这里补上。
+ *
+ * 数据形状来自 SDK 的 PermissionUpdate:
+ * { type: 'addRules', rules: [{ toolName, ruleContent? }], behavior, destination }
+ * 只认 `addRules` + `behavior: 'allow'`:其余类型(replaceRules / removeRules / setMode)
+ * 不是「放宽这一类」的语义,拿它们生成文案会误导。suggestions 已由调用方按
+ * `destination === 'session'` 过滤。
+ *
+ * 一律展示规则原文而不做二次意译:`curl:*` 就显示 `curl:*`。猜测性地美化成
+ * 「curl 命令」会在规则语法变化时悄悄说谎,而这是一条授权文案,宁可技术感强一点。
+ */
+
+/** 未知形状一律当作「无法描述」,调用方据此隐藏按钮 —— 不猜、不兜底放宽。 */
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function describeRule(rule: unknown): string | null {
+ if (!isRecord(rule)) return null;
+ const toolName = typeof rule.toolName === 'string' ? rule.toolName.trim() : '';
+ if (!toolName) return null;
+ const ruleContent = typeof rule.ruleContent === 'string' ? rule.ruleContent.trim() : '';
+ return ruleContent ? `${toolName}(${ruleContent})` : toolName;
+}
+
+/**
+ * @returns 规则清单(如 `['Bash(curl:*)']`),**只在能把全部授权项描述完整时**才返回;
+ * 否则返回 null,调用方退回不声称范围的原文案。
+ *
+ * 「描述不全就整体放弃」是安全要求,不是洁癖:点下按钮会把 suggestions 里**每一项**
+ * 都作为 updatedPermissions 转发出去。只要有一项没被写进文案(比如混进来一条 setMode
+ * 或 replaceRules),按钮就会一边宣称「只允许这一类」,一边顺手改掉权限档位或应用
+ * 未列出的规则 —— 授权文案说谎比文案笼统严重得多。
+ *
+ * 不返回拼好的字符串:分隔符是语言相关的(中日用 `、`,英韩用 `, `),硬编码会把
+ * 顿号漏进英文句子。拼接交给调用方按当前语言做(DESIGN.md 文案规范:标点不跨语言)。
+ */
+export function describeSessionPermissionScope(suggestions: readonly unknown[]): string[] | null {
+ if (!Array.isArray(suggestions)) return null;
+ const labels: string[] = [];
+ for (const suggestion of suggestions) {
+ // 任何一项无法完整描述 → 整体放弃(见顶注)。
+ if (!isRecord(suggestion)) return null;
+ if (suggestion.type !== 'addRules') return null;
+ if (suggestion.behavior !== 'allow') return null;
+ if (!Array.isArray(suggestion.rules) || suggestion.rules.length === 0) return null;
+ for (const rule of suggestion.rules) {
+ const label = describeRule(rule);
+ if (!label) return null;
+ // 同一条规则可能在多个 suggestion 里重复出现,去重后再列。
+ if (!labels.includes(label)) labels.push(label);
+ }
+ }
+ return labels.length > 0 ? labels : null;
+}