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(desktop): 灵动岛与侧栏工作状态复用面板人话文案产线 (#257)

Dash8c13e90dea65
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index 007ce627ac..c4cb3e688c 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { AgentEvent, InteractionRequest } from '@cindy/maker-core';
+import { DEFAULT_TOOL_ROW_WORDING } from '@cindy/maker-shared/message-presentation';
import { DEFAULT_AGENT_ISLAND_STRINGS } from '../../../shared/agentIsland.js';
import {
@@ -21,6 +22,7 @@ import {
requestAgentIslandSessionFocus,
setAgentIslandAppFocused,
setAgentIslandStrings,
+ setAgentIslandToolWording,
setAgentIslandHovered,
setAgentIslandLayoutDragActive,
setAgentIslandPointerZones,
@@ -338,7 +340,7 @@ describe('Agent Island display state', () => {
expect(afterPreviewDwell.sessions[0]?.compactDetail).toBe('我会继续看输出');
});
- it('shows the currently running shell command instead of only the tool name', () => {
+ it('humanizes intent-classified shell commands with panel wording', () => {
const state = createAgentIslandState();
applyAgentIslandEvent(
state,
@@ -358,11 +360,32 @@ describe('Agent Island display state', () => {
const display = buildAgentIslandDisplayState(state, 1_050);
expect(display.sessions[0]).toMatchObject({
- detail: '$ pnpm --dir apps/desktop test',
+ detail: '运行测试',
phase: 'running',
});
});
+ it('keeps the raw shell command when no intent rule classifies it', () => {
+ const state = createAgentIslandState();
+ applyAgentIslandEvent(
+ state,
+ { sessionId: 's1', title: 'Task', agentKind: 'codex', workingDir: '/repo/xdt-maker' },
+ {
+ type: 'tool_use',
+ source: 'codex',
+ data: {
+ toolUseId: 'tool-1',
+ toolName: 'exec',
+ // rm 系破坏性命令刻意不进意图规则表:显示原文。
+ input: { command: 'rm -rf dist', cwd: '/repo/xdt-maker' },
+ },
+ },
+ 1_000,
+ );
+
+ expect(buildAgentIslandDisplayState(state, 1_050).sessions[0]?.detail).toBe('$ rm -rf dist');
+ });
+
it('uses displayCommand for Codex command summaries when raw command is a wrapper', () => {
const state = createAgentIslandState();
applyAgentIslandEvent(
@@ -387,14 +410,15 @@ describe('Agent Island display state', () => {
const display = buildAgentIslandDisplayState(state, 1_050);
- expect(display.sessions[0]?.detail).toBe('$ pnpm build');
+ // displayCommand 解包 wrapper 后作为意图解析输入源:pnpm build → 构建。
+ expect(display.sessions[0]?.detail).toBe('构建');
});
- it('localizes task update tool detail', () => {
+ it('localizes task update tool detail through the injected wording', () => {
const state = createAgentIslandState();
- setAgentIslandStrings(state, {
- ...DEFAULT_AGENT_ISLAND_STRINGS,
- updatingTasks: '正在更新任务',
+ setAgentIslandToolWording(state, {
+ ...DEFAULT_TOOL_ROW_WORDING,
+ verb: (key) => (key === 'updateTodos' ? '正在更新任务' : DEFAULT_TOOL_ROW_WORDING.verb(key)),
});
applyAgentIslandEvent(
@@ -459,7 +483,7 @@ describe('Agent Island display state', () => {
applyAgentIslandEvent(state, { sessionId: 's1' }, toolResultEvent('tool-1'), 1_500);
applyAgentIslandEvent(state, { sessionId: 's1' }, statusEvent(true, 'Thinking'), 1_700);
- expect(buildAgentIslandDisplayState(state, 2_000).sessions[0]?.detail).toBe('$ pnpm test');
+ expect(buildAgentIslandDisplayState(state, 2_000).sessions[0]?.detail).toBe('运行测试');
expect(buildAgentIslandDisplayState(state, 3_600).sessions[0]?.detail).toBe('');
applyAgentIslandEvent(state, { sessionId: 's1' }, statusEvent(true, 'Thinking'), 3_700);
@@ -631,7 +655,7 @@ describe('Agent Island display state', () => {
start + AGENT_ISLAND_MESSAGE_PREVIEW_MIN_DWELL_MS * 2 + 200,
);
expect(afterAssistantDwell.sessions[0]?.messagePreview).toBeNull();
- expect(afterAssistantDwell.sessions[0]?.compactDetail).toBe('$ pnpm test');
+ expect(afterAssistantDwell.sessions[0]?.compactDetail).toBe('运行测试');
});
it('does not display managed dialogue workspace folders as projects', () => {
@@ -1733,14 +1757,15 @@ describe('Agent Island display state', () => {
input: { command: 'pnpm lint' },
}, 1_200);
- expect(buildAgentIslandDisplayState(state, 1_250).sessions[0]?.detail).toBe('$ pnpm test');
+ // 权限确认:人话意图作语境,真实命令保持可见。
+ expect(buildAgentIslandDisplayState(state, 1_250).sessions[0]?.detail).toBe('运行测试 · $ pnpm test');
applyAgentIslandInteractionDismissed(state, 'ask', 'r1', 1_300);
const display = buildAgentIslandDisplayState(state, 1_350);
expect(display.sessions[0]).toMatchObject({
permissionAction: { requestId: 'r2' },
- detail: '$ pnpm lint',
+ detail: '代码检查 · $ pnpm lint',
});
});
@@ -1761,7 +1786,7 @@ describe('Agent Island display state', () => {
expect(display.sessions[0]).toMatchObject({
permissionAction: { requestId: 'r2' },
- detail: '$ pnpm lint',
+ detail: '代码检查 · $ pnpm lint',
});
});
diff --git a/apps/desktop/src/main/agent-island/__tests__/toolDetail.test.ts b/apps/desktop/src/main/agent-island/__tests__/toolDetail.test.ts
new file mode 100644
index 0000000000..987a74210c
--- /dev/null
+++ b/apps/desktop/src/main/agent-island/__tests__/toolDetail.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+import { DEFAULT_TOOL_ROW_WORDING, type ToolRowWording } from '@cindy/maker-shared/message-presentation';
+
+import { formatIslandToolDetail } from '../toolDetail.js';
+
+const wording = DEFAULT_TOOL_ROW_WORDING;
+
+function detail(toolName: string, input: unknown, requireCommandVisible = false): string | null {
+ return formatIslandToolDetail(toolName, input, { wording, requireCommandVisible });
+}
+
+describe('formatIslandToolDetail', () => {
+ it('humanizes intent-classified commands into panel-style labels', () => {
+ expect(detail('Bash', { command: 'pnpm test' })).toBe('运行测试');
+ expect(detail('exec', { command: 'git status --short' })).toBe('查看工作区状态');
+ expect(detail('exec', {
+ command: 'bash -lc "pnpm build"',
+ displayCommand: 'pnpm build',
+ })).toBe('构建');
+ });
+
+ it('keeps the raw command for unclassifiable or destructive commands', () => {
+ // rm 系破坏性命令刻意不进意图规则表:原文即最诚实的展示。
+ expect(detail('Bash', { command: 'rm -rf dist' })).toBe('$ rm -rf dist');
+ const opaque = 'docker run --rm -v /repo:/w node:22 bash -lc "true"';
+ expect(detail('Bash', { command: opaque })).toBe(`$ ${opaque}`);
+ });
+
+ it('keeps model descriptions verbatim with the command as suffix', () => {
+ expect(detail('Bash', { command: 'pnpm test', description: 'Run tests' }))
+ .toBe('Run tests · $ pnpm test');
+ // 描述已含命令时不重复。
+ expect(detail('Bash', { command: 'pnpm test', description: 'Run tests: pnpm test' }))
+ .toBe('Run tests: pnpm test');
+ });
+
+ it('forces the real command to stay visible for permission prompts', () => {
+ expect(detail('Bash', { command: 'pnpm test' }, true)).toBe('运行测试 · $ pnpm test');
+ expect(detail('Bash', { command: 'rm -rf dist' }, true)).toBe('$ rm -rf dist');
+ });
+
+ it('renders non-command descriptors with shared panel wording', () => {
+ expect(detail('Read', { file_path: '/repo/src/app.ts' })).toBe('读取 app.ts');
+ expect(detail('Edit', { file_path: '/repo/src/app.ts' })).toBe('编辑 app.ts');
+ expect(detail('Grep', { pattern: 'useMemo', path: 'src/renderer' })).toBe('搜索 useMemo');
+ expect(detail('WebFetch', { url: 'https://example.com/docs' })).toBe('访问 https://example.com/docs');
+ expect(detail('TodoWrite', { todos: [] })).toBe('更新待办');
+ expect(detail('mcp__lizi_feishu__read_by_url', { url: 'https://example.com' }))
+ .toBe('调用 lizi_feishu · read by url');
+ expect(detail('file_change', {
+ changes: [
+ { path: '/repo/a.ts', kind: { type: 'update' }, diff: '-a\n+b' },
+ { path: '/repo/b.ts', kind: { type: 'add' }, diff: '+b' },
+ ],
+ })).toBe('更新 2 个文件');
+ });
+
+ it('covers the codex canonical tool shapes with the same shared pipeline', () => {
+ // codex web_search:input 是 { query, action }。
+ expect(detail('web_search', { query: 'electron notch api', action: 'search' }))
+ .toBe('搜索 electron notch api');
+ // codex update_plan 与 Claude TodoWrite 走同一个 todo 槽。
+ expect(detail('update_plan', { plan: [] })).toBe('更新待办');
+ // codex file_change 移动。
+ expect(detail('file_change', {
+ changes: [{ path: '/repo/src/old.ts', kind: { type: 'update', move_path: '/repo/src/new.ts' }, diff: '' }],
+ })).toBe('重命名 old.ts → new.ts');
+ // codex 官方 commandActions 优先于本地规则;多段 action 时取首段意图
+ // (与 mobile 行、IM 卡片的 summarizeToolUseText 单行行为一致)。
+ expect(detail('exec', {
+ command: 'rg -n useMemo src/renderer',
+ commandActions: [{ type: 'search', query: 'useMemo', path: 'src/renderer', command: 'rg' }],
+ })).toBe('搜索 useMemo');
+ });
+
+ it('surfaces informative input fields for descriptor-opaque tools (codex MCP elicitation)', () => {
+ // codex MCP elicitation 权限:toolName 只有 `mcp:server` 两段(拆不出 tool),
+ // input 里的 message / toolTitle / toolDescription 才是人话(旧岛行为)。
+ expect(detail('mcp:lizi_feishu', {
+ serverName: 'lizi_feishu',
+ message: '允许写入飞书文档《周报》?',
+ toolTitle: '写入文档',
+ }, true)).toBe('允许写入飞书文档《周报》?');
+ expect(detail('mcp:lizi_feishu', {
+ serverName: 'lizi_feishu',
+ toolTitle: '写入文档',
+ })).toBe('写入文档');
+ // codex permissions 审批:input 无人话字段,回落请求级 description(reason)。
+ expect(formatIslandToolDetail('permissions', { permissions: ['network'] }, { wording }, {
+ description: 'Needs network access to fetch docs',
+ })).toBe('Needs network access to fetch docs');
+ });
+
+ it('truncates task descriptions and generic labels to the island cap', () => {
+ const longDescription = 'x'.repeat(120);
+ const taskLabel = detail('Task', { description: longDescription, prompt: 'ignored' });
+ expect(taskLabel).not.toBeNull();
+ expect(taskLabel!.length).toBeLessThanOrEqual(80);
+ expect(detail('SomeUnknownTool', { anything: true })).toBe('调用 SomeUnknownTool');
+ // generic 但 input 有可读细节(DETAIL_KEYS)时,label 后跟细节(对齐面板行)。
+ expect(detail('SomeUnknownTool', { query: 'find usages' })).toBe('调用 SomeUnknownTool · find usages');
+ });
+
+ it('prefers codex tool-side questions over tool shape', () => {
+ expect(detail('some_tool', {
+ questions: [{ question: 'Continue?' }, { question: 'Second' }],
+ })).toBe('Continue? (+1)');
+ });
+
+ it('falls back to request metadata when input is not a record', () => {
+ expect(formatIslandToolDetail('CustomTool', undefined, { wording }, {
+ description: 'Do the thing',
+ })).toBe('Do the thing');
+ expect(formatIslandToolDetail('CustomTool', undefined, { wording }, {
+ displayName: 'Custom Tool',
+ })).toBe('Custom Tool');
+ expect(formatIslandToolDetail('CustomTool', undefined, { wording })).toBeNull();
+ });
+
+ it('routes wording through the injected implementation', () => {
+ const fake: ToolRowWording = {
+ verb: (key) => `verb:${key}`,
+ intentVerb: (action) => `intent:${action}`,
+ updateFilesLabel: (count) => `updated ${count} files`,
+ };
+ expect(formatIslandToolDetail('Bash', { command: 'pnpm test' }, { wording: fake }))
+ .toBe('intent:test');
+ expect(formatIslandToolDetail('Read', { file_path: '/repo/a.ts' }, { wording: fake }))
+ .toBe('verb:read a.ts');
+ });
+});
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 46a531820a..12b6f17a3f 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -80,9 +80,11 @@ import {
setAgentIslandMeasuredContentHeight,
setAgentIslandPointerZones,
setAgentIslandStrings,
+ setAgentIslandToolWording,
setAgentIslandVisibleSession,
type AgentIslandUserPromptRollbackToken,
} from './state.js';
+import { createLocalizedToolRowWording } from './toolWording.js';
import {
type AgentIslandLayoutPreference,
computeAgentIslandCarrierSize,
@@ -247,6 +249,8 @@ export class AgentIslandService {
private streamingPreviewPublishTimer: ReturnType<typeof setTimeout> | null = null;
constructor(private readonly deps: AgentIslandServiceDeps) {
+ // lazy t() 闭包跟随 locale 运行时切换,注入一次即可(strings 仍每次 publish 重建)。
+ setAgentIslandToolWording(this.state, createLocalizedToolRowWording());
this.layoutPreferencesByDisplayId = readAgentIslandLayoutPreferences();
this.nativeHost = deps.nativeHost ?? new MacAgentIslandNativeHost({
onPointerZones: (zones) => this.handleNativePointerZones(zones),
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index 32c1c4dd23..362a5dd90a 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -1,7 +1,10 @@
import type { AgentEvent, InteractionRequest } from '@cindy/maker-core';
+import { DEFAULT_TOOL_ROW_WORDING, type ToolRowWording } from '@cindy/maker-shared/message-presentation';
import { stripTrailingPathSeparators } from '../../shared/pathText';
+import { formatIslandToolDetail } from './toolDetail.js';
+
import {
createDefaultAgentIslandDisplayConfig,
DEFAULT_AGENT_ISLAND_STRINGS,
@@ -171,6 +174,8 @@ export interface AgentIslandState {
compactCurrentSessionId: string | null;
compactCurrentUntil: number | null;
strings: AgentIslandStrings;
+ /** 工具状态文案的措辞实现:默认共享包中文表,service 注入本地化版(lazy t())。 */
+ toolWording: ToolRowWording;
}
export function createAgentIslandState(): AgentIslandState {
@@ -202,6 +207,7 @@ export function createAgentIslandState(): AgentIslandState {
compactCurrentSessionId: null,
compactCurrentUntil: null,
strings: { ...DEFAULT_AGENT_ISLAND_STRINGS },
+ toolWording: DEFAULT_TOOL_ROW_WORDING,
};
}
@@ -234,12 +240,17 @@ export function resetAgentIslandState(state: AgentIslandState): void {
state.compactCurrentSessionId = fresh.compactCurrentSessionId;
state.compactCurrentUntil = fresh.compactCurrentUntil;
state.strings = fresh.strings;
+ // toolWording 是注入的配置(非会话状态),reset 时保留,避免退回默认中文表。
}
export function setAgentIslandStrings(state: AgentIslandState, strings: AgentIslandStrings): void {
state.strings = { ...strings };
}
+export function setAgentIslandToolWording(state: AgentIslandState, wording: ToolRowWording): void {
+ state.toolWording = wording;
+}
+
export function setAgentIslandAppFocused(state: AgentIslandState, focused: boolean, now = Date.now()): boolean {
const previousFocused = state.appFocused;
state.appFocused = focused;
@@ -516,7 +527,7 @@ export function applyAgentIslandEvent(
const toolUseId = toolUseIdsFromEvent(event)[0] ?? null;
const toolInput = data?.input;
const toolDescription = toolName
- ? formatToolDetail(toolName, toolInput, state.strings, data ?? undefined)
+ ? formatIslandToolDetail(toolName, toolInput, { wording: state.toolWording }, data ?? undefined)
: firstNonEmptyString(data?.description, data?.toolDescription);
markSessionRunning(state, session);
if (toolUseId) {
@@ -617,7 +628,7 @@ export function applyAgentIslandInteractionRequest(
applyMeta(session, meta);
session.pendingInteractionIds.add(request.requestId);
session.pendingInteractionKinds.set(request.requestId, request.kind);
- session.pendingInteractionDetails.set(request.requestId, detailForInteraction(request, state.strings));
+ session.pendingInteractionDetails.set(request.requestId, detailForInteraction(request, state.toolWording));
session.running = true;
session.completionAllowedAfterTerminalError = false;
const activateRequest = request.kind !== 'permission' || session.permissionRequestId === null;
@@ -2103,9 +2114,10 @@ function priorityRank(state: AgentIslandState, session: AgentIslandSessionState,
return 0;
}
-function detailForInteraction(request: InteractionRequest, strings: AgentIslandStrings): string {
+function detailForInteraction(request: InteractionRequest, wording: ToolRowWording): string {
if (request.kind === 'permission') {
- return formatToolDetail(request.toolName, request.input, strings, {
+ // 权限确认:requireCommandVisible 保证用户批准的真实命令始终可见。
+ return formatIslandToolDetail(request.toolName, request.input, { wording, requireCommandVisible: true }, {
description: request.description,
displayName: request.displayName,
}) || request.displayName || request.toolName || '';
@@ -2125,123 +2137,6 @@ function toolUseIdsFromEvent(event: AgentEvent): string[] {
return typeof data.id === 'string' && data.id.length > 0 ? [data.id] : [];
}
-function formatToolDetail(
- toolName: string,
- input: unknown,
- strings: AgentIslandStrings,
- fallback?: Record<string, unknown>,
-): string | null {
- const toolInput = asRecord(input);
- const normalizedToolName = normalizeToolName(toolName);
- if (toolInput) {
- switch (normalizedToolName) {
- case 'bash':
- case 'exec':
- case 'execute_command':
- return formatCommandDetail(toolInput);
- case 'read':
- case 'read_file':
- return formatFileDetail(toolInput, true);
- case 'edit':
- case 'apply_diff':
- case 'write':
- case 'write_to_file':
- return formatFileDetail(toolInput, false);
- case 'grep':
- case 'search_files': {
- const pattern = firstNonEmptyString(toolInput.pattern, toolInput.query);
- const searchPath = firstNonEmptyString(toolInput.path, toolInput.cwd);
- if (pattern && searchPath) return `${pattern} in ${lastPathSegment(searchPath)}`;
- if (pattern) return pattern;
- break;
- }
- case 'glob':
- return firstNonEmptyString(toolInput.pattern);
- case 'websearch':
- case 'web_search':
- return firstNonEmptyString(toolInput.query);
- case 'webfetch':
- case 'web_fetch': {
- const url = firstNonEmptyString(toolInput.url);
- if (!url) break;
- return hostFromUrl(url) ?? url.slice(0, 60);
- }
- case 'task':
- case 'agent':
- return firstNonEmptyString(toolInput.description, toolInput.prompt)?.slice(0, 80) ?? null;
- case 'todowrite':
- case 'update_plan':
- return strings.updatingTasks;
- default:
- break;
- }
-
- const question = permissionQuestionDetail(toolInput);
- if (question) return question;
-
- const fileValue = firstNonEmptyString(toolInput.file_path, toolInput.path);
- if (fileValue) return lastPathSegment(fileValue);
-
- return firstNonEmptyString(
- toolInput.message,
- toolInput.toolTitle,
- toolInput.toolDescription,
- toolInput.pattern,
- toolInput.query,
- toolInput.displayCommand,
- toolInput.command,
- toolInput.description,
- toolInput.prompt,
- )?.slice(0, 80) ?? null;
- }
-
- return firstNonEmptyString(fallback?.description, fallback?.toolDescription, fallback?.displayName);
-}
-
-function permissionQuestionDetail(input: Record<string, unknown>): string | null {
- const questions = input.questions;
- if (!Array.isArray(questions)) return null;
- const firstQuestion = questions.find((question): question is Record<string, unknown> => (
- Boolean(question) && typeof question === 'object' && !Array.isArray(question)
- ));
- if (!firstQuestion) return null;
- const text = firstNonEmptyString(firstQuestion.question, firstQuestion.header);
- if (!text) return null;
- const extraCount = questions.length - 1;
- return extraCount > 0 ? `${text} (+${extraCount})` : text;
-}
-
-function formatCommandDetail(input: Record<string, unknown>): string | null {
- const command = firstNonEmptyString(input.displayCommand, input.command, input.cmd);
- const description = firstNonEmptyString(input.description);
- if (description && command) {
- if (description === command || description.includes(command)) return description;
- return `${description} · $ ${command}`;
- }
- if (command) return `$ ${command}`;
- return description;
-}
-
-function formatFileDetail(input: Record<string, unknown>, includeOffset: boolean): string | null {
- const filePath = firstNonEmptyString(input.file_path, input.path);
- if (!filePath) return null;
- const fileName = lastPathSegment(filePath);
- if (!includeOffset) return fileName;
- const offset = typeof input.offset === 'number' ? input.offset : null;
- return offset === null ? fileName : `${fileName}:${offset}`;
-}
-
-function normalizeToolName(toolName: string): string {
- const direct = toolName.trim().toLowerCase();
- if (direct.startsWith('mcp__')) {
- return direct.split('__').filter(Boolean).at(-1) ?? direct;
- }
- if (direct.startsWith('mcp:')) {
- return direct.split(':').filter(Boolean).at(-1) ?? direct;
- }
- return direct;
-}
-
function firstNonEmptyString(...values: unknown[]): string | null {
for (const value of values) {
if (typeof value !== 'string') continue;
@@ -2251,14 +2146,6 @@ function firstNonEmptyString(...values: unknown[]): string | null {
return null;
}
-function hostFromUrl(rawUrl: string): string | null {
- try {
- return new URL(rawUrl).host || null;
- } catch {
- return null;
- }
-}
-
function lastPathSegment(value: string): string {
const trimmed = stripTrailingPathSeparators(value.trim());
const parts = trimmed.split(/[\\/]/).filter(Boolean);
diff --git a/apps/desktop/src/main/agent-island/toolDetail.ts b/apps/desktop/src/main/agent-island/toolDetail.ts
new file mode 100644
index 0000000000..c8119c1564
--- /dev/null
+++ b/apps/desktop/src/main/agent-island/toolDetail.ts
@@ -0,0 +1,118 @@
+/**
+ * 灵动岛单行工具状态文案:复用面板同一套共享产线
+ * (describeToolUse → formatToolRowText,措辞经 ToolRowWording 注入本地化),
+ * 在其上做岛特有的单行拼接决策。
+ *
+ * 纯模块(无 electron / i18n import),可直接单测;措辞由调用方注入
+ * (state 持有,默认共享包中文表,service 换成本地化实现)。
+ */
+import { formatToolRowText, type ToolRowWording } from '@cindy/maker-shared/message-presentation';
+import { describeToolUse, truncateToolText, type ToolUseDescriptor } from '@cindy/maker-shared/tool-use-descriptor';
+
+/** task 描述与 generic 兜底沿用旧岛的 80 字上限,防长 prompt 撑爆 pill。 */
+const ISLAND_DETAIL_MAX_CHARS = 80;
+
+export interface IslandToolDetailOptions {
+ wording: ToolRowWording;
+ /**
+ * 权限确认场景:真实命令必须保持可见(用户批准的是命令本身,不是意图摘要),
+ * 人话 label 只作语境补充(`运行测试 · $ pnpm test`)。
+ */
+ requireCommandVisible?: boolean;
+}
+
+export function formatIslandToolDetail(
+ toolName: string,
+ input: unknown,
+ options: IslandToolDetailOptions,
+ fallback?: Record<string, unknown>,
+): string | null {
+ const toolInput = asRecord(input);
+ if (!toolInput) {
+ return firstNonEmptyString(fallback?.description, fallback?.toolDescription, fallback?.displayName);
+ }
+
+ // codex 工具侧问题(input.questions)优先于工具形态展示。
+ const question = permissionQuestionDetail(toolInput);
+ if (question) return question;
+
+ const descriptor = describeToolUse(toolName, toolInput);
+ if (descriptor.kind === 'command') {
+ return formatCommandDetail(descriptor, options);
+ }
+ const label = formatToolRowText(descriptor, options.wording).label;
+ if (!label) return null;
+ if (descriptor.kind === 'generic') {
+ // 描述符解析不出形态的工具(codex MCP elicitation 的 `mcp:server`、
+ // permissions 等):input 里的人话字段与请求级 description 比「调用 X」
+ // 更有信息量,优先展示(旧岛行为);都没有时才落 label(+detail)。
+ const informative = firstNonEmptyString(
+ toolInput.message,
+ toolInput.toolTitle,
+ toolInput.toolDescription,
+ fallback?.description,
+ );
+ if (informative) return truncateToolText(informative, ISLAND_DETAIL_MAX_CHARS);
+ return truncateToolText(
+ descriptor.detail ? `${label} · ${descriptor.detail}` : label,
+ ISLAND_DETAIL_MAX_CHARS,
+ );
+ }
+ if (descriptor.kind === 'task') {
+ return truncateToolText(label, ISLAND_DETAIL_MAX_CHARS);
+ }
+ return label;
+}
+
+/**
+ * 命令类单行拼接:
+ * - 模型 description → `描述 · $ 命令`(描述已含命令时不重复);
+ * - 命令意图 → 人话 label(权限场景强制补 `· $ 命令`);
+ * - 无法分类 → 保持 `$ 命令` 原样(rm 等破坏性命令刻意不进意图规则表,
+ * 「运行命令」label 无信息量,原文即最诚实的展示)。
+ */
+function formatCommandDetail(
+ descriptor: Extract<ToolUseDescriptor, { kind: 'command' }>,
+ options: IslandToolDetailOptions,
+): string | null {
+ const command = descriptor.command.trim();
+ const description = descriptor.description?.trim() ?? '';
+ if (description) {
+ if (!command || description === command || description.includes(command)) return description;
+ return `${description} · $ ${command}`;
+ }
+ if (descriptor.intent) {
+ const label = formatToolRowText(descriptor, options.wording).label;
+ if (options.requireCommandVisible && command) return `${label} · $ ${command}`;
+ return label;
+ }
+ if (command) return `$ ${command}`;
+ return null;
+}
+
+function permissionQuestionDetail(input: Record<string, unknown>): string | null {
+ const questions = input.questions;
+ if (!Array.isArray(questions)) return null;
+ const firstQuestion = questions.find((question): question is Record<string, unknown> => (
+ Boolean(question) && typeof question === 'object' && !Array.isArray(question)
+ ));
+ if (!firstQuestion) return null;
+ const text = firstNonEmptyString(firstQuestion.question, firstQuestion.header);
+ if (!text) return null;
+ const extraCount = questions.length - 1;
+ return extraCount > 0 ? `${text} (+${extraCount})` : text;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
+}
+
+function firstNonEmptyString(...values: unknown[]): string | null {
+ for (const value of values) {
+ if (typeof value !== 'string') continue;
+ const trimmed = value.trim();
+ if (trimmed) return trimmed;
+ }
+ return null;
+}
diff --git a/apps/desktop/src/main/agent-island/toolWording.ts b/apps/desktop/src/main/agent-island/toolWording.ts
new file mode 100644
index 0000000000..6da5a945f0
--- /dev/null
+++ b/apps/desktop/src/main/agent-island/toolWording.ts
@@ -0,0 +1,27 @@
+/**
+ * 灵动岛工具措辞的本地化实现:用 main 侧 t() 解析与面板同源的 i18n key 表
+ * (src/shared/agentActionVerbKeys.ts),注入共享包的 ToolRowWording 槽位。
+ *
+ * 做成 lazy t() 闭包而非预构建数据表:locale 运行时可切(setMainLocale),
+ * 每次取词现场解析即可自动跟随,无缓存失效问题。依赖 electron(经 i18n.ts),
+ * 因此独立于纯模块 state.ts / toolDetail.ts,由 service 注入。
+ */
+import type { ToolRowWording } from '@cindy/maker-shared/message-presentation';
+
+import { t } from '../i18n.js';
+import {
+ FILE_CHANGE_FILES_I18N_KEY,
+ INTENT_ROW_VERB_KEY,
+ TOOL_ROW_VERB_I18N_KEY,
+ UPDATED_VERB_I18N_KEY,
+} from '../../shared/agentActionVerbKeys.js';
+
+export function createLocalizedToolRowWording(): ToolRowWording {
+ return {
+ verb: (key) => t(TOOL_ROW_VERB_I18N_KEY[key]),
+ intentVerb: (action) => t(INTENT_ROW_VERB_KEY[action]),
+ // main 的迷你 i18n 只支持 {{appName}} 插值,{{count}} 在调用点手动替换。
+ updateFilesLabel: (count) =>
+ `${t(UPDATED_VERB_I18N_KEY)} ${t(FILE_CHANGE_FILES_I18N_KEY).replace('{{count}}', String(count))}`,
+ };
+}
diff --git a/apps/desktop/src/renderer/__tests__/agentActionsI18n.test.ts b/apps/desktop/src/renderer/__tests__/agentActionsI18n.test.ts
index db6886c628..377972199f 100644
--- a/apps/desktop/src/renderer/__tests__/agentActionsI18n.test.ts
+++ b/apps/desktop/src/renderer/__tests__/agentActionsI18n.test.ts
@@ -15,6 +15,13 @@ import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
+import {
+ FILE_CHANGE_FILES_I18N_KEY,
+ INTENT_ROW_VERB_KEY,
+ TOOL_ROW_VERB_I18N_KEY,
+ UPDATED_VERB_I18N_KEY,
+} from '../../shared/agentActionVerbKeys';
+
const locales = ['zh-CN', 'en', 'ja', 'ko'] as const;
const VERBS = ['edited', 'created', 'ran', 'read', 'updated', 'searched', 'fetched', 'used'] as const;
@@ -75,6 +82,31 @@ describe('agent actions i18n', () => {
}
});
+ it('resolves every shared verb-key table entry in every supported locale', () => {
+ // 灵动岛(main 侧 t())与面板共用 src/shared/agentActionVerbKeys.ts;
+ // 表里的 key 是自由字符串,防手滑指向不存在的 key。
+ const lookup = (bundle: Record<string, unknown>, key: string): unknown => {
+ let cur: unknown = bundle;
+ for (const part of key.split('.')) {
+ if (typeof cur !== 'object' || cur === null) return undefined;
+ cur = (cur as Record<string, unknown>)[part];
+ }
+ return cur;
+ };
+ const allKeys = [
+ ...Object.values(INTENT_ROW_VERB_KEY),
+ ...Object.values(TOOL_ROW_VERB_I18N_KEY),
+ UPDATED_VERB_I18N_KEY,
+ FILE_CHANGE_FILES_I18N_KEY,
+ ];
+ for (const locale of locales) {
+ const bundle = readLocale(locale) as Record<string, unknown>;
+ for (const key of allKeys) {
+ expect(lookup(bundle, key), `${locale} ${key}`).toEqual(expect.any(String));
+ }
+ }
+ });
+
it('keeps aggregate summary phrases translated in every supported locale', () => {
for (const locale of locales) {
const actions = readLocale(locale).chat?.agentActions;
diff --git a/apps/desktop/src/renderer/lib/agent-actions/verbAggregator.ts b/apps/desktop/src/renderer/lib/agent-actions/verbAggregator.ts
index 6e52f1530f..5d3c8a94c0 100644
--- a/apps/desktop/src/renderer/lib/agent-actions/verbAggregator.ts
+++ b/apps/desktop/src/renderer/lib/agent-actions/verbAggregator.ts
@@ -20,14 +20,17 @@
*
* 文案 i18n(issue #450):聚合短语 / 行级动词都走 i18n key。CJK 语序与英文
* 不同,所以 key 是「整短语」粒度(如 "edited {{count}} files" / "编辑
- * {{count}} 个文件"),不拆 verb/noun 两段拼接。key 集中在下方两张映射表 —
- * i18nCompleteness 静态扫描认不出 `t(变量)`,这些 key 的 4 语言齐全性由
- * `agentActionsI18n.test.ts` 显式断言兜底。
+ * {{count}} 个文件"),不拆 verb/noun 两段拼接。聚合/行级 key 在下方映射表,
+ * command intent 的动词 key 表在 `src/shared/agentActionVerbKeys.ts`(与
+ * main 灵动岛措辞共享)— i18nCompleteness 静态扫描认不出 `t(变量)`,这些
+ * key 的 4 语言齐全性由 `agentActionsI18n.test.ts` 显式断言兜底。
*/
import type { TFunction } from 'i18next';
import type { CommandIntentAction } from '@cindy/maker-shared';
+import { INTENT_ROW_VERB_KEY } from '../../../shared/agentActionVerbKeys';
+
import type { ChatMessage } from '@/lib/makerChatStore';
export type Verb =
@@ -106,107 +109,10 @@ const ROW_VERB_KEY: Record<Verb, string> = {
};
/**
- * command intent(代码解析的命令意图,issue #450 codex 人话)→ 行级动词 key。
- * read / search / fetch 复用既有动词档,其余是本表新增 key —— 与 ROW_VERB_KEY
- * 一样属于 `t(变量)` 动态 key,4 语言齐全性由 agentActionsI18n.test.ts 钉住。
+ * command intent 的行级动词 label key;消费端自行 `t()`。key 表已下沉到
+ * `src/shared/agentActionVerbKeys.ts`(main 灵动岛措辞与面板共用同一事实源),
+ * 本函数保留为薄委托,面板消费端(AgentActionRow 等)零改动。
*/
-const INTENT_ROW_VERB_KEY: Record<CommandIntentAction, string> = {
- read: 'chat.agentActionRow.verb.read',
- list: 'chat.agentActionRow.verb.listed',
- search: 'chat.agentActionRow.verb.searched',
- inspect: 'chat.agentActionRow.verb.inspect',
- inspectRepository: 'chat.agentActionRow.verb.inspectRepository',
- inspectEnvironment: 'chat.agentActionRow.verb.inspectEnvironment',
- modifyRepository: 'chat.agentActionRow.verb.modifyRepository',
- verify: 'chat.agentActionRow.verb.verify',
- fetch: 'chat.agentActionRow.verb.fetched',
- install: 'chat.agentActionRow.verb.installedDeps',
- test: 'chat.agentActionRow.verb.ranTests',
- build: 'chat.agentActionRow.verb.built',
- lint: 'chat.agentActionRow.verb.linted',
- typecheck: 'chat.agentActionRow.verb.typechecked',
- runScript: 'chat.agentActionRow.verb.runScript',
- runNodeScript: 'chat.agentActionRow.verb.runNodeScript',
- runPythonScript: 'chat.agentActionRow.verb.runPythonScript',
- runPerlScript: 'chat.agentActionRow.verb.runPerlScript',
- runSwiftScript: 'chat.agentActionRow.verb.runSwiftScript',
- checkSyntax: 'chat.agentActionRow.verb.checkSyntax',
- showVersion: 'chat.agentActionRow.verb.showVersion',
- checkFormatting: 'chat.agentActionRow.verb.checkFormatting',
- parseJson: 'chat.agentActionRow.verb.parseJson',
- count: 'chat.agentActionRow.verb.count',
- showCurrentDirectory: 'chat.agentActionRow.verb.showCurrentDirectory',
- showDateTime: 'chat.agentActionRow.verb.showDateTime',
- locateCommand: 'chat.agentActionRow.verb.locateCommand',
- inspectProcesses: 'chat.agentActionRow.verb.inspectProcesses',
- inspectPorts: 'chat.agentActionRow.verb.inspectPorts',
- queryDatabase: 'chat.agentActionRow.verb.queryDatabase',
- gitStatus: 'chat.agentActionRow.verb.gitStatus',
- gitDiff: 'chat.agentActionRow.verb.gitDiff',
- gitLog: 'chat.agentActionRow.verb.gitLog',
- gitShow: 'chat.agentActionRow.verb.gitShow',
- gitAdd: 'chat.agentActionRow.verb.gitAdd',
- gitCommit: 'chat.agentActionRow.verb.gitCommit',
- gitFetch: 'chat.agentActionRow.verb.gitFetch',
- gitPull: 'chat.agentActionRow.verb.gitPull',
- gitPush: 'chat.agentActionRow.verb.gitPush',
- gitRebase: 'chat.agentActionRow.verb.gitRebase',
- gitMerge: 'chat.agentActionRow.verb.gitMerge',
- gitCherryPick: 'chat.agentActionRow.verb.gitCherryPick',
- gitStash: 'chat.agentActionRow.verb.gitStash',
- gitRestore: 'chat.agentActionRow.verb.gitRestore',
- gitSubmodule: 'chat.agentActionRow.verb.gitSubmodule',
- gitRemote: 'chat.agentActionRow.verb.gitRemote',
- gitRevParse: 'chat.agentActionRow.verb.gitRevParse',
- gitBranch: 'chat.agentActionRow.verb.gitBranch',
- gitGrep: 'chat.agentActionRow.verb.gitGrep',
- gitMergeBase: 'chat.agentActionRow.verb.gitMergeBase',
- gitLsFiles: 'chat.agentActionRow.verb.gitLsFiles',
- gitRevList: 'chat.agentActionRow.verb.gitRevList',
- gitLsRemote: 'chat.agentActionRow.verb.gitLsRemote',
- gitWorktreeList: 'chat.agentActionRow.verb.gitWorktreeList',
- gitWorktreeAdd: 'chat.agentActionRow.verb.gitWorktreeAdd',
- gitWorktreeRemove: 'chat.agentActionRow.verb.gitWorktreeRemove',
- gitWorktreeMove: 'chat.agentActionRow.verb.gitWorktreeMove',
- gitWorktreePrune: 'chat.agentActionRow.verb.gitWorktreePrune',
- ghPrList: 'chat.agentActionRow.verb.ghPrList',
- ghPrView: 'chat.agentActionRow.verb.ghPrView',
- ghPrChecks: 'chat.agentActionRow.verb.ghPrChecks',
- ghPrStatus: 'chat.agentActionRow.verb.ghPrStatus',
- ghPrDiff: 'chat.agentActionRow.verb.ghPrDiff',
- ghPrCreate: 'chat.agentActionRow.verb.ghPrCreate',
- ghPrEdit: 'chat.agentActionRow.verb.ghPrEdit',
- ghPrComment: 'chat.agentActionRow.verb.ghPrComment',
- ghPrReview: 'chat.agentActionRow.verb.ghPrReview',
- ghPrMerge: 'chat.agentActionRow.verb.ghPrMerge',
- ghPrClose: 'chat.agentActionRow.verb.ghPrClose',
- ghPrReopen: 'chat.agentActionRow.verb.ghPrReopen',
- ghPrCheckout: 'chat.agentActionRow.verb.ghPrCheckout',
- ghIssueList: 'chat.agentActionRow.verb.ghIssueList',
- ghIssueView: 'chat.agentActionRow.verb.ghIssueView',
- ghIssueStatus: 'chat.agentActionRow.verb.ghIssueStatus',
- ghIssueCreate: 'chat.agentActionRow.verb.ghIssueCreate',
- ghIssueEdit: 'chat.agentActionRow.verb.ghIssueEdit',
- ghIssueComment: 'chat.agentActionRow.verb.ghIssueComment',
- ghIssueClose: 'chat.agentActionRow.verb.ghIssueClose',
- ghIssueReopen: 'chat.agentActionRow.verb.ghIssueReopen',
- ghAuthStatus: 'chat.agentActionRow.verb.ghAuthStatus',
- ghAuthLogin: 'chat.agentActionRow.verb.ghAuthLogin',
- ghAuthLogout: 'chat.agentActionRow.verb.ghAuthLogout',
- ghAuthRefresh: 'chat.agentActionRow.verb.ghAuthRefresh',
- ghAuthSwitch: 'chat.agentActionRow.verb.ghAuthSwitch',
- ghRunList: 'chat.agentActionRow.verb.ghRunList',
- ghRunView: 'chat.agentActionRow.verb.ghRunView',
- ghRunWatch: 'chat.agentActionRow.verb.ghRunWatch',
- ghSearch: 'chat.agentActionRow.verb.ghSearch',
- ghRepoList: 'chat.agentActionRow.verb.ghRepoList',
- ghRepoView: 'chat.agentActionRow.verb.ghRepoView',
- ghApiQuery: 'chat.agentActionRow.verb.ghApiQuery',
- ghApiMutation: 'chat.agentActionRow.verb.ghApiMutation',
- ghApiCall: 'chat.agentActionRow.verb.ghApiCall',
-};
-
-/** command intent 的行级动词 label key;消费端自行 `t()`。 */
export function verbLabelKeyForIntent(action: CommandIntentAction): string {
return INTENT_ROW_VERB_KEY[action];
}
diff --git a/apps/desktop/src/shared/agentActionVerbKeys.ts b/apps/desktop/src/shared/agentActionVerbKeys.ts
new file mode 100644
index 0000000000..00917896c6
--- /dev/null
+++ b/apps/desktop/src/shared/agentActionVerbKeys.ts
@@ -0,0 +1,141 @@
+/**
+ * agentActionVerbKeys
+ * ---------------------------------------------------------------------------
+ * 工具动作人话动词的 i18n key 表(纯数据,main / renderer 共享)。
+ *
+ * renderer 面板(AgentActionRow 经 verbAggregator)与 main 灵动岛
+ * (agent-island/toolWording)各自用自己的 t() 解析同一批 key,让两端的
+ * "正在做什么"措辞来自同一事实源。key 的 4 语言齐全性由
+ * `renderer/__tests__/agentActionsI18n.test.ts` 显式断言兜底
+ * (i18nCompleteness 静态扫描认不出 `t(变量)`)。
+ */
+
+import type { CommandIntentAction } from '@cindy/maker-shared';
+import type { ToolRowVerbKey } from '@cindy/maker-shared/message-presentation';
+
+/**
+ * command intent(代码解析的命令意图,issue #450 codex 人话)→ 行级动词 key。
+ * read / search / fetch 复用既有动词档,其余是本表新增 key。
+ */
+export const INTENT_ROW_VERB_KEY: Record<CommandIntentAction, string> = {
+ read: 'chat.agentActionRow.verb.read',
+ list: 'chat.agentActionRow.verb.listed',
+ search: 'chat.agentActionRow.verb.searched',
+ inspect: 'chat.agentActionRow.verb.inspect',
+ inspectRepository: 'chat.agentActionRow.verb.inspectRepository',
+ inspectEnvironment: 'chat.agentActionRow.verb.inspectEnvironment',
+ modifyRepository: 'chat.agentActionRow.verb.modifyRepository',
+ verify: 'chat.agentActionRow.verb.verify',
+ fetch: 'chat.agentActionRow.verb.fetched',
+ install: 'chat.agentActionRow.verb.installedDeps',
+ test: 'chat.agentActionRow.verb.ranTests',
+ build: 'chat.agentActionRow.verb.built',
+ lint: 'chat.agentActionRow.verb.linted',
+ typecheck: 'chat.agentActionRow.verb.typechecked',
+ runScript: 'chat.agentActionRow.verb.runScript',
+ runNodeScript: 'chat.agentActionRow.verb.runNodeScript',
+ runPythonScript: 'chat.agentActionRow.verb.runPythonScript',
+ runPerlScript: 'chat.agentActionRow.verb.runPerlScript',
+ runSwiftScript: 'chat.agentActionRow.verb.runSwiftScript',
+ checkSyntax: 'chat.agentActionRow.verb.checkSyntax',
+ showVersion: 'chat.agentActionRow.verb.showVersion',
+ checkFormatting: 'chat.agentActionRow.verb.checkFormatting',
+ parseJson: 'chat.agentActionRow.verb.parseJson',
+ count: 'chat.agentActionRow.verb.count',
+ showCurrentDirectory: 'chat.agentActionRow.verb.showCurrentDirectory',
+ showDateTime: 'chat.agentActionRow.verb.showDateTime',
+ locateCommand: 'chat.agentActionRow.verb.locateCommand',
+ inspectProcesses: 'chat.agentActionRow.verb.inspectProcesses',
+ inspectPorts: 'chat.agentActionRow.verb.inspectPorts',
+ queryDatabase: 'chat.agentActionRow.verb.queryDatabase',
+ gitStatus: 'chat.agentActionRow.verb.gitStatus',
+ gitDiff: 'chat.agentActionRow.verb.gitDiff',
+ gitLog: 'chat.agentActionRow.verb.gitLog',
+ gitShow: 'chat.agentActionRow.verb.gitShow',
+ gitAdd: 'chat.agentActionRow.verb.gitAdd',
+ gitCommit: 'chat.agentActionRow.verb.gitCommit',
+ gitFetch: 'chat.agentActionRow.verb.gitFetch',
+ gitPull: 'chat.agentActionRow.verb.gitPull',
+ gitPush: 'chat.agentActionRow.verb.gitPush',
+ gitRebase: 'chat.agentActionRow.verb.gitRebase',
+ gitMerge: 'chat.agentActionRow.verb.gitMerge',
+ gitCherryPick: 'chat.agentActionRow.verb.gitCherryPick',
+ gitStash: 'chat.agentActionRow.verb.gitStash',
+ gitRestore: 'chat.agentActionRow.verb.gitRestore',
+ gitSubmodule: 'chat.agentActionRow.verb.gitSubmodule',
+ gitRemote: 'chat.agentActionRow.verb.gitRemote',
+ gitRevParse: 'chat.agentActionRow.verb.gitRevParse',
+ gitBranch: 'chat.agentActionRow.verb.gitBranch',
+ gitGrep: 'chat.agentActionRow.verb.gitGrep',
+ gitMergeBase: 'chat.agentActionRow.verb.gitMergeBase',
+ gitLsFiles: 'chat.agentActionRow.verb.gitLsFiles',
+ gitRevList: 'chat.agentActionRow.verb.gitRevList',
+ gitLsRemote: 'chat.agentActionRow.verb.gitLsRemote',
+ gitWorktreeList: 'chat.agentActionRow.verb.gitWorktreeList',
+ gitWorktreeAdd: 'chat.agentActionRow.verb.gitWorktreeAdd',
+ gitWorktreeRemove: 'chat.agentActionRow.verb.gitWorktreeRemove',
+ gitWorktreeMove: 'chat.agentActionRow.verb.gitWorktreeMove',
+ gitWorktreePrune: 'chat.agentActionRow.verb.gitWorktreePrune',
+ ghPrList: 'chat.agentActionRow.verb.ghPrList',
+ ghPrView: 'chat.agentActionRow.verb.ghPrView',
+ ghPrChecks: 'chat.agentActionRow.verb.ghPrChecks',
+ ghPrStatus: 'chat.agentActionRow.verb.ghPrStatus',
+ ghPrDiff: 'chat.agentActionRow.verb.ghPrDiff',
+ ghPrCreate: 'chat.agentActionRow.verb.ghPrCreate',
+ ghPrEdit: 'chat.agentActionRow.verb.ghPrEdit',
+ ghPrComment: 'chat.agentActionRow.verb.ghPrComment',
+ ghPrReview: 'chat.agentActionRow.verb.ghPrReview',
+ ghPrMerge: 'chat.agentActionRow.verb.ghPrMerge',
+ ghPrClose: 'chat.agentActionRow.verb.ghPrClose',
+ ghPrReopen: 'chat.agentActionRow.verb.ghPrReopen',
+ ghPrCheckout: 'chat.agentActionRow.verb.ghPrCheckout',
+ ghIssueList: 'chat.agentActionRow.verb.ghIssueList',
+ ghIssueView: 'chat.agentActionRow.verb.ghIssueView',
+ ghIssueStatus: 'chat.agentActionRow.verb.ghIssueStatus',
+ ghIssueCreate: 'chat.agentActionRow.verb.ghIssueCreate',
+ ghIssueEdit: 'chat.agentActionRow.verb.ghIssueEdit',
+ ghIssueComment: 'chat.agentActionRow.verb.ghIssueComment',
+ ghIssueClose: 'chat.agentActionRow.verb.ghIssueClose',
+ ghIssueReopen: 'chat.agentActionRow.verb.ghIssueReopen',
+ ghAuthStatus: 'chat.agentActionRow.verb.ghAuthStatus',
+ ghAuthLogin: 'chat.agentActionRow.verb.ghAuthLogin',
+ ghAuthLogout: 'chat.agentActionRow.verb.ghAuthLogout',
+ ghAuthRefresh: 'chat.agentActionRow.verb.ghAuthRefresh',
+ ghAuthSwitch: 'chat.agentActionRow.verb.ghAuthSwitch',
+ ghRunList: 'chat.agentActionRow.verb.ghRunList',
+ ghRunView: 'chat.agentActionRow.verb.ghRunView',
+ ghRunWatch: 'chat.agentActionRow.verb.ghRunWatch',
+ ghSearch: 'chat.agentActionRow.verb.ghSearch',
+ ghRepoList: 'chat.agentActionRow.verb.ghRepoList',
+ ghRepoView: 'chat.agentActionRow.verb.ghRepoView',
+ ghApiQuery: 'chat.agentActionRow.verb.ghApiQuery',
+ ghApiMutation: 'chat.agentActionRow.verb.ghApiMutation',
+ ghApiCall: 'chat.agentActionRow.verb.ghApiCall',
+};
+
+/**
+ * 共享包 ToolRowWording 的 verb 槽 → i18n key(供 main 灵动岛构建本地化措辞)。
+ * zh-CN 文案与 maker-shared 的 TOOL_ROW_VERB_ZH 默认表逐字一致。
+ *
+ * updateTodos 特例:绑到灵动岛既有的 `agentIsland.native.updatingTasks`
+ * ("正在更新任务",进行时)——岛是实况状态面,面板没有"更新待办"的 i18n key,
+ * 复用现成 4 语言 key 而不新增。
+ */
+export const TOOL_ROW_VERB_I18N_KEY: Record<ToolRowVerbKey, string> = {
+ read: 'chat.agentActionRow.verb.read',
+ edit: 'chat.agentActionRow.verb.edited',
+ create: 'chat.agentActionRow.verb.created',
+ delete: 'chat.agentActionRow.fileChange.deleted',
+ rename: 'chat.agentActionRow.fileChange.renamed',
+ update: 'chat.agentActionRow.verb.updated',
+ run: 'chat.agentActionRow.verb.ran',
+ runCommand: 'chat.agentActionRow.verb.ranCommand',
+ search: 'chat.agentActionRow.verb.searched',
+ fetch: 'chat.agentActionRow.verb.fetched',
+ use: 'chat.agentActionRow.verb.used',
+ updateTodos: 'agentIsland.native.updatingTasks',
+};
+
+/** fileChange 多文件短语的组成 key:`${t(UPDATED_VERB)} ${t(FILES).replace('{{count}}', n)}`。 */
+export const UPDATED_VERB_I18N_KEY = 'chat.agentActionRow.verb.updated';
+export const FILE_CHANGE_FILES_I18N_KEY = 'chat.agentActionRow.fileChange.files';
diff --git a/packages/maker-shared/src/__tests__/messagePresentation.test.ts b/packages/maker-shared/src/__tests__/messagePresentation.test.ts
index 6d47e5aea0..b816583bf2 100644
--- a/packages/maker-shared/src/__tests__/messagePresentation.test.ts
+++ b/packages/maker-shared/src/__tests__/messagePresentation.test.ts
@@ -10,6 +10,7 @@ import {
summarizeToolRowPresentation,
summarizeWorkGroupPresentation,
todoStatusPresentation,
+ type ToolRowWording,
} from '../messagePresentation';
import type {
MessageRenderNormalizedMessage,
@@ -345,6 +346,46 @@ describe('messagePresentation', () => {
}))).toMatchObject({ label: '更新 2 个文件' });
});
+ it('routes all wording channels through an injected ToolRowWording (island i18n)', () => {
+ // 假英文表:三个通道(verb / intentVerb / updateFilesLabel)各自可被注入方接管。
+ const wording: ToolRowWording = {
+ verb: (key) => `verb:${key}`,
+ intentVerb: (action) => `intent:${action}`,
+ updateFilesLabel: (count) => `updated ${count} files`,
+ };
+
+ // verb 通道:file 描述符。
+ expect(summarizeToolUseText('Read', { file_path: '/repo/src/app.ts' }, { wording })).toEqual({
+ label: 'verb:read app.ts',
+ detail: '/repo/src/app.ts',
+ });
+
+ // intentVerb 通道:命令意图。
+ expect(summarizeToolUseText('exec', { command: 'git status' }, { wording })).toEqual({
+ label: 'intent:gitStatus',
+ detail: 'git status',
+ });
+
+ // verb 通道:无法分类命令回退 runCommand。
+ expect(summarizeToolUseText('Bash', {
+ command: 'docker run --rm -v /repo:/w node:22 bash -lc "true"',
+ }, { wording }).label).toBe('verb:runCommand');
+
+ // updateFilesLabel 通道:fileChange 多文件。
+ expect(summarizeToolUseText('file_change', {
+ changes: [
+ { path: '/repo/a.ts', kind: { type: 'update' }, diff: '-a\n+b' },
+ { path: '/repo/b.ts', kind: { type: 'add' }, diff: '+b' },
+ ],
+ }, { wording }).label).toBe('updated 2 files');
+
+ // verb 通道:todo 槽(灵动岛绑 agentIsland.native.updatingTasks 的注入点)。
+ expect(summarizeToolUseText('TodoWrite', { todos: [] }, { wording }).label).toBe('verb:updateTodos');
+
+ // 不注入时默认中文表(mobile / IM 零变化,与上方既有用例同一事实)。
+ expect(summarizeToolUseText('TodoWrite', { todos: [] }).label).toBe('更新待办');
+ });
+
it('marks unsettled tool rows running only while the session is streaming', () => {
const pending = message('bash-pending', { toolSettled: false });
const settled = message('bash-done', { toolSettled: true });
diff --git a/packages/maker-shared/src/messagePresentation.ts b/packages/maker-shared/src/messagePresentation.ts
index f64a850194..f0bf765aa9 100644
--- a/packages/maker-shared/src/messagePresentation.ts
+++ b/packages/maker-shared/src/messagePresentation.ts
@@ -295,6 +295,29 @@ const INTENT_VERB_ZH: Record<CommandIntentAction, string> = {
ghApiCall: '调用 GitHub API',
};
+/** 行级动词槽位(TOOL_ROW_VERB_ZH 的 key 空间,供措辞注入方实现)。 */
+export type ToolRowVerbKey = keyof typeof TOOL_ROW_VERB_ZH;
+
+/**
+ * 工具行措辞注入点——默认是本文件的中文硬编码表(mobile / IM 卡片继续走默认,
+ * 字节级不变);desktop main(灵动岛)注入经 i18n 解析的本地化实现。做成函数式
+ * 接口而非数据表:locale 可运行时切换,惰性求值免缓存失效。
+ */
+export interface ToolRowWording {
+ /** 行级工具动词("读取"/"编辑"…)。 */
+ verb(key: ToolRowVerbKey): string;
+ /** 命令意图动词(CommandIntentAction 全覆盖)。 */
+ intentVerb(action: CommandIntentAction): string;
+ /** fileChange 多文件复合短语("更新 3 个文件");量词与语序语言相关,整短语粒度,count 恒 >= 2。 */
+ updateFilesLabel(count: number): string;
+}
+
+export const DEFAULT_TOOL_ROW_WORDING: ToolRowWording = {
+ verb: (key) => TOOL_ROW_VERB_ZH[key],
+ intentVerb: (action) => INTENT_VERB_ZH[action],
+ updateFilesLabel: (count) => `${TOOL_ROW_VERB_ZH.update} ${count} 个文件`,
+};
+
const TOOL_ROW_TEXT_MAX_CHARS = 60;
/** 次行命令原文的截断上限(与桌面 hover 展示完整命令的意图对齐,手机放宽到 200 字)。 */
@@ -407,13 +430,13 @@ export function summarizeToolRowPresentation<
export function summarizeToolUseText(
toolName: string,
input: unknown,
- options: Pick<ToolRowPresentationOptions, 'intentOverride'> = {},
+ options: Pick<ToolRowPresentationOptions, 'intentOverride'> & { wording?: ToolRowWording } = {},
): ToolUseTextPresentation {
const sourceDescriptor = describeToolUse(toolName, input);
const descriptor = sourceDescriptor.kind === 'command' && options.intentOverride
? { ...sourceDescriptor, intent: options.intentOverride }
: sourceDescriptor;
- return formatToolRowText(descriptor);
+ return formatToolRowText(descriptor, options.wording);
}
/**
@@ -433,13 +456,19 @@ function toolRowDescriptor(tool: MessagePresentationToolLike): ToolUseDescriptor
}
/**
- * 描述符 → 手机版中文行文案(对齐桌面 AgentActionRow 的展示决策,issue #450):
+ * 描述符 → 行级人话文案(对齐桌面 AgentActionRow 的展示决策,issue #450):
* - Bash 有模型 description → 独立成句,命令原文降为次要细节;
* - command intent(codex commandActions / 本地规则)命中 → 意图动词 + 目标;
* - MCP / dynamic / collab → `调用 server · tool`;
* - 无法分类的命令显示「运行命令」,真实命令保留在 detail;其它工具按类型回退。
+ *
+ * 措辞经 wording 注入(默认中文表);export 供灵动岛在拿到 descriptor 后按
+ * kind 决定单行拼接策略。
*/
-function formatToolRowText(descriptor: ToolUseDescriptor): ToolUseTextPresentation {
+export function formatToolRowText(
+ descriptor: ToolUseDescriptor,
+ wording: ToolRowWording = DEFAULT_TOOL_ROW_WORDING,
+): ToolUseTextPresentation {
switch (descriptor.kind) {
case 'command': {
if (descriptor.description) {
@@ -451,8 +480,8 @@ function formatToolRowText(descriptor: ToolUseDescriptor): ToolUseTextPresentati
const intent = descriptor.intent;
if (intent) {
const label = intent.target
- ? joinVerb(INTENT_VERB_ZH[intent.action], truncateToolText(intent.target, TOOL_ROW_TEXT_MAX_CHARS))
- : INTENT_VERB_ZH[intent.action];
+ ? joinVerb(wording.intentVerb(intent.action), truncateToolText(intent.target, TOOL_ROW_TEXT_MAX_CHARS))
+ : wording.intentVerb(intent.action);
return {
label,
// 友好标题负责扫读,真实命令固定留在次行负责准确性与审计。
@@ -461,16 +490,16 @@ function formatToolRowText(descriptor: ToolUseDescriptor): ToolUseTextPresentati
}
if (!descriptor.command) return { label: descriptor.toolName };
return {
- label: TOOL_ROW_VERB_ZH.runCommand,
+ label: wording.verb('runCommand'),
...commandDetail(descriptor.command),
};
}
case 'file': {
const verb = descriptor.action === 'read'
- ? TOOL_ROW_VERB_ZH.read
+ ? wording.verb('read')
: descriptor.action === 'edit'
- ? TOOL_ROW_VERB_ZH.edit
- : TOOL_ROW_VERB_ZH.create;
+ ? wording.verb('edit')
+ : wording.verb('create');
return {
label: joinVerb(verb, descriptor.fileName),
...(descriptor.filePath !== descriptor.fileName ? { detail: descriptor.filePath } : {}),
@@ -478,18 +507,18 @@ function formatToolRowText(descriptor: ToolUseDescriptor): ToolUseTextPresentati
}
case 'fileChange': {
if (descriptor.changes.length > 1) {
- return { label: `${TOOL_ROW_VERB_ZH.update} ${descriptor.changes.length} 个文件` };
+ return { label: wording.updateFilesLabel(descriptor.changes.length) };
}
const change = descriptor.changes[0];
const verb = change.action === 'add'
- ? TOOL_ROW_VERB_ZH.create
+ ? wording.verb('create')
: change.action === 'delete'
- ? TOOL_ROW_VERB_ZH.delete
+ ? wording.verb('delete')
: change.action === 'move'
- ? TOOL_ROW_VERB_ZH.rename
+ ? wording.verb('rename')
: change.action === 'update'
- ? TOOL_ROW_VERB_ZH.edit
- : TOOL_ROW_VERB_ZH.update;
+ ? wording.verb('edit')
+ : wording.verb('update');
const target = change.action === 'move' && change.moveFileName
? `${change.fileName} → ${change.moveFileName}`
: change.fileName;
@@ -503,18 +532,18 @@ function formatToolRowText(descriptor: ToolUseDescriptor): ToolUseTextPresentati
}
case 'search':
return {
- label: joinVerb(TOOL_ROW_VERB_ZH.search, truncateToolText(descriptor.pattern, TOOL_ROW_TEXT_MAX_CHARS)),
+ label: joinVerb(wording.verb('search'), truncateToolText(descriptor.pattern, TOOL_ROW_TEXT_MAX_CHARS)),
...(descriptor.path ? { detail: descriptor.path } : {}),
};
case 'web':
return {
label: joinVerb(
- descriptor.mode === 'fetch' ? TOOL_ROW_VERB_ZH.fetch : TOOL_ROW_VERB_ZH.search,
+ descriptor.mode === 'fetch' ? wording.verb('fetch') : wording.verb('search'),
truncateToolText(descriptor.target, TOOL_ROW_TEXT_MAX_CHARS),
),
};
case 'todo':
- return { label: TOOL_ROW_VERB_ZH.updateTodos };
+ return { label: wording.verb('updateTodos') };
case 'task':
return {
label: descriptor.description ?? descriptor.toolName,
@@ -522,25 +551,25 @@ function formatToolRowText(descriptor: ToolUseDescriptor): ToolUseTextPresentati
};
case 'mcp':
return {
- label: joinVerb(TOOL_ROW_VERB_ZH.use, `${descriptor.serverLabel} · ${descriptor.toolLabel}`),
+ label: joinVerb(wording.verb('use'), `${descriptor.serverLabel} · ${descriptor.toolLabel}`),
...(descriptor.detail ? { detail: descriptor.detail } : {}),
};
case 'dynamic':
return {
label: joinVerb(
- TOOL_ROW_VERB_ZH.use,
+ wording.verb('use'),
descriptor.namespace ? `${descriptor.namespace} · ${descriptor.toolLabel}` : descriptor.toolLabel,
),
...(descriptor.detail ? { detail: descriptor.detail } : {}),
};
case 'collab':
return {
- label: joinVerb(TOOL_ROW_VERB_ZH.use, descriptor.toolLabel),
+ label: joinVerb(wording.verb('use'), descriptor.toolLabel),
...(descriptor.detail ? { detail: descriptor.detail } : {}),
};
default:
return {
- label: joinVerb(TOOL_ROW_VERB_ZH.use, descriptor.toolName),
+ label: joinVerb(wording.verb('use'), descriptor.toolName),
...(descriptor.detail ? { detail: descriptor.detail } : {}),
};
}