Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(conversation): title undescribed shell commands by what they do (#23124)

YuTengjing3223d77e4b14
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 65556e6e6b3..71f3c4e9be5 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -710,6 +710,59 @@
"builtins.lobe-web-onboarding.updateDocument.hunkMode.insertAt": "Insert at line",
"builtins.lobe-web-onboarding.updateDocument.hunkMode.replace": "Replace",
"builtins.lobe-web-onboarding.updateDocument.hunkMode.replaceLines": "Replace lines",
+ "builtins.shellCommand.acceptance.feedback": "Read acceptance feedback",
+ "builtins.shellCommand.acceptance.ingest": "Publish acceptance round",
+ "builtins.shellCommand.acceptance.linkPr": "Link PR to acceptance",
+ "builtins.shellCommand.acceptance.list": "List acceptances",
+ "builtins.shellCommand.acceptance.preflight": "Check acceptance setup",
+ "builtins.shellCommand.acceptance.publish": "Publish acceptance",
+ "builtins.shellCommand.acceptance.view": "View acceptance",
+ "builtins.shellCommand.ci.cancel": "Cancel CI run",
+ "builtins.shellCommand.ci.list": "List CI runs",
+ "builtins.shellCommand.ci.logs": "Read CI logs",
+ "builtins.shellCommand.ci.rerun": "Rerun CI",
+ "builtins.shellCommand.ci.view": "Check CI run",
+ "builtins.shellCommand.ci.workflowRun": "Start workflow",
+ "builtins.shellCommand.commit": "Commit",
+ "builtins.shellCommand.commitAndPush": "Commit and push",
+ "builtins.shellCommand.findFiles": "Find files",
+ "builtins.shellCommand.githubApi": "Call GitHub API",
+ "builtins.shellCommand.issue.close": "Close issue",
+ "builtins.shellCommand.issue.comment": "Comment on issue",
+ "builtins.shellCommand.issue.create": "Open issue",
+ "builtins.shellCommand.issue.edit": "Update issue",
+ "builtins.shellCommand.issue.list": "List issues",
+ "builtins.shellCommand.issue.reopen": "Reopen issue",
+ "builtins.shellCommand.issue.view": "View issue",
+ "builtins.shellCommand.list": "List",
+ "builtins.shellCommand.listFiles": "List files",
+ "builtins.shellCommand.pr.check": "Check PR",
+ "builtins.shellCommand.pr.close": "Close PR",
+ "builtins.shellCommand.pr.comment": "Comment on PR",
+ "builtins.shellCommand.pr.create": "Open PR",
+ "builtins.shellCommand.pr.edit": "Update PR",
+ "builtins.shellCommand.pr.list": "List PRs",
+ "builtins.shellCommand.pr.merge": "Merge PR",
+ "builtins.shellCommand.push": "Push",
+ "builtins.shellCommand.read": "Read",
+ "builtins.shellCommand.runScript.bun": "Run Bun script",
+ "builtins.shellCommand.runScript.node": "Run Node.js script",
+ "builtins.shellCommand.runScript.perl": "Run Perl script",
+ "builtins.shellCommand.runScript.python": "Run Python script",
+ "builtins.shellCommand.runScript.ruby": "Run Ruby script",
+ "builtins.shellCommand.runScript.shell": "Run shell script",
+ "builtins.shellCommand.runTests": "Run tests",
+ "builtins.shellCommand.search": "Search",
+ "builtins.shellCommand.useSkill": "Use skill",
+ "builtins.shellCommand.vercel.deploy": "Deploy",
+ "builtins.shellCommand.vercel.envList": "List env vars",
+ "builtins.shellCommand.vercel.envPull": "Pull env vars",
+ "builtins.shellCommand.vercel.inspect": "Inspect deployment",
+ "builtins.shellCommand.vercel.list": "List deployments",
+ "builtins.shellCommand.vercel.logs": "Read deployment logs",
+ "builtins.shellCommand.vercel.promote": "Promote deployment",
+ "builtins.shellCommand.vercel.redeploy": "Redeploy",
+ "builtins.shellCommand.write": "Write",
"confirm": "Confirm",
"debug.arguments": "Arguments",
"debug.error": "Error log",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 7e93d5e2fea..71ec554f788 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -710,6 +710,59 @@
"builtins.lobe-web-onboarding.updateDocument.hunkMode.insertAt": "在指定行插入",
"builtins.lobe-web-onboarding.updateDocument.hunkMode.replace": "替换",
"builtins.lobe-web-onboarding.updateDocument.hunkMode.replaceLines": "替换行",
+ "builtins.shellCommand.acceptance.feedback": "查看验收反馈",
+ "builtins.shellCommand.acceptance.ingest": "发布验收轮次",
+ "builtins.shellCommand.acceptance.linkPr": "关联 PR 到验收",
+ "builtins.shellCommand.acceptance.list": "列出验收",
+ "builtins.shellCommand.acceptance.preflight": "检查验收环境",
+ "builtins.shellCommand.acceptance.publish": "发布验收",
+ "builtins.shellCommand.acceptance.view": "查看验收",
+ "builtins.shellCommand.ci.cancel": "取消 CI 运行",
+ "builtins.shellCommand.ci.list": "列出 CI 运行",
+ "builtins.shellCommand.ci.logs": "查看 CI 日志",
+ "builtins.shellCommand.ci.rerun": "重跑 CI",
+ "builtins.shellCommand.ci.view": "查看 CI 运行",
+ "builtins.shellCommand.ci.workflowRun": "触发工作流",
+ "builtins.shellCommand.commit": "提交",
+ "builtins.shellCommand.commitAndPush": "提交并推送",
+ "builtins.shellCommand.findFiles": "查找文件",
+ "builtins.shellCommand.githubApi": "调用 GitHub API",
+ "builtins.shellCommand.issue.close": "关闭 issue",
+ "builtins.shellCommand.issue.comment": "评论 issue",
+ "builtins.shellCommand.issue.create": "创建 issue",
+ "builtins.shellCommand.issue.edit": "更新 issue",
+ "builtins.shellCommand.issue.list": "列出 issue",
+ "builtins.shellCommand.issue.reopen": "重新打开 issue",
+ "builtins.shellCommand.issue.view": "查看 issue",
+ "builtins.shellCommand.list": "列出",
+ "builtins.shellCommand.listFiles": "列出文件",
+ "builtins.shellCommand.pr.check": "查看 PR",
+ "builtins.shellCommand.pr.close": "关闭 PR",
+ "builtins.shellCommand.pr.comment": "评论 PR",
+ "builtins.shellCommand.pr.create": "创建 PR",
+ "builtins.shellCommand.pr.edit": "更新 PR",
+ "builtins.shellCommand.pr.list": "列出 PR",
+ "builtins.shellCommand.pr.merge": "合并 PR",
+ "builtins.shellCommand.push": "推送",
+ "builtins.shellCommand.read": "读取",
+ "builtins.shellCommand.runScript.bun": "运行 Bun 脚本",
+ "builtins.shellCommand.runScript.node": "运行 Node.js 脚本",
+ "builtins.shellCommand.runScript.perl": "运行 Perl 脚本",
+ "builtins.shellCommand.runScript.python": "运行 Python 脚本",
+ "builtins.shellCommand.runScript.ruby": "运行 Ruby 脚本",
+ "builtins.shellCommand.runScript.shell": "运行 Shell 脚本",
+ "builtins.shellCommand.runTests": "运行测试",
+ "builtins.shellCommand.search": "搜索",
+ "builtins.shellCommand.useSkill": "使用技能",
+ "builtins.shellCommand.vercel.deploy": "部署",
+ "builtins.shellCommand.vercel.envList": "列出环境变量",
+ "builtins.shellCommand.vercel.envPull": "拉取环境变量",
+ "builtins.shellCommand.vercel.inspect": "查看部署",
+ "builtins.shellCommand.vercel.list": "列出部署",
+ "builtins.shellCommand.vercel.logs": "查看部署日志",
+ "builtins.shellCommand.vercel.promote": "提升部署",
+ "builtins.shellCommand.vercel.redeploy": "重新部署",
+ "builtins.shellCommand.write": "写入",
"confirm": "确认",
"debug.arguments": "调用参数",
"debug.error": "错误日志",
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 5da688c106b..c8267201444 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -218,6 +218,59 @@ export default {
'builtins.goalCommand.plan.completed': 'Goal plan submitted',
'builtins.goalCommand.plan.failed': "Couldn't submit goal plan",
'builtins.goalCommand.plan.loading': 'Planning goal tasks',
+ 'builtins.shellCommand.acceptance.feedback': 'Read acceptance feedback',
+ 'builtins.shellCommand.acceptance.ingest': 'Publish acceptance round',
+ 'builtins.shellCommand.acceptance.linkPr': 'Link PR to acceptance',
+ 'builtins.shellCommand.acceptance.list': 'List acceptances',
+ 'builtins.shellCommand.acceptance.preflight': 'Check acceptance setup',
+ 'builtins.shellCommand.acceptance.publish': 'Publish acceptance',
+ 'builtins.shellCommand.acceptance.view': 'View acceptance',
+ 'builtins.shellCommand.ci.cancel': 'Cancel CI run',
+ 'builtins.shellCommand.ci.list': 'List CI runs',
+ 'builtins.shellCommand.ci.logs': 'Read CI logs',
+ 'builtins.shellCommand.ci.rerun': 'Rerun CI',
+ 'builtins.shellCommand.ci.view': 'Check CI run',
+ 'builtins.shellCommand.ci.workflowRun': 'Start workflow',
+ 'builtins.shellCommand.commit': 'Commit',
+ 'builtins.shellCommand.commitAndPush': 'Commit and push',
+ 'builtins.shellCommand.findFiles': 'Find files',
+ 'builtins.shellCommand.githubApi': 'Call GitHub API',
+ 'builtins.shellCommand.issue.close': 'Close issue',
+ 'builtins.shellCommand.issue.comment': 'Comment on issue',
+ 'builtins.shellCommand.issue.create': 'Open issue',
+ 'builtins.shellCommand.issue.edit': 'Update issue',
+ 'builtins.shellCommand.issue.list': 'List issues',
+ 'builtins.shellCommand.issue.reopen': 'Reopen issue',
+ 'builtins.shellCommand.issue.view': 'View issue',
+ 'builtins.shellCommand.list': 'List',
+ 'builtins.shellCommand.listFiles': 'List files',
+ 'builtins.shellCommand.pr.check': 'Check PR',
+ 'builtins.shellCommand.pr.close': 'Close PR',
+ 'builtins.shellCommand.pr.comment': 'Comment on PR',
+ 'builtins.shellCommand.pr.create': 'Open PR',
+ 'builtins.shellCommand.pr.edit': 'Update PR',
+ 'builtins.shellCommand.pr.list': 'List PRs',
+ 'builtins.shellCommand.pr.merge': 'Merge PR',
+ 'builtins.shellCommand.push': 'Push',
+ 'builtins.shellCommand.read': 'Read',
+ 'builtins.shellCommand.runScript.bun': 'Run Bun script',
+ 'builtins.shellCommand.runScript.node': 'Run Node.js script',
+ 'builtins.shellCommand.runScript.perl': 'Run Perl script',
+ 'builtins.shellCommand.runScript.python': 'Run Python script',
+ 'builtins.shellCommand.runScript.ruby': 'Run Ruby script',
+ 'builtins.shellCommand.runScript.shell': 'Run shell script',
+ 'builtins.shellCommand.runTests': 'Run tests',
+ 'builtins.shellCommand.search': 'Search',
+ 'builtins.shellCommand.useSkill': 'Use skill',
+ 'builtins.shellCommand.vercel.deploy': 'Deploy',
+ 'builtins.shellCommand.vercel.envList': 'List env vars',
+ 'builtins.shellCommand.vercel.envPull': 'Pull env vars',
+ 'builtins.shellCommand.vercel.inspect': 'Inspect deployment',
+ 'builtins.shellCommand.vercel.list': 'List deployments',
+ 'builtins.shellCommand.vercel.logs': 'Read deployment logs',
+ 'builtins.shellCommand.vercel.promote': 'Promote deployment',
+ 'builtins.shellCommand.vercel.redeploy': 'Redeploy',
+ 'builtins.shellCommand.write': 'Write',
'builtins.codex.agentBrowser.click': 'Clicked element',
'builtins.codex.agentBrowser.eval': 'Evaluated page',
'builtins.codex.agentBrowser.fill': 'Filled input',
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx
index 567d9c4e3bb..cd7c0ec4b9c 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx
@@ -131,4 +131,59 @@ describe('ToolTitle', () => {
expect(screen.getByText('docker-compose.yaml')).toBeInTheDocument();
});
});
+
+ describe('undescribed shell commands', () => {
+ // The mocked `t` echoes the last key segment: `builtins.shellCommand.read` → `read`.
+ it.each([
+ ['sed -n 1,80p src/a.ts 2>&1 | head -40', 'read', 'a.ts'],
+ ['rg -n "TODO" src', 'search', 'TODO in src'],
+ ["bunx vitest run --silent='passed-only' src/foo.test.ts", 'runTests', 'foo.test.ts'],
+ ['/bin/zsh -lc "cat docs/a.md"', 'read', 'a.md'],
+ ])('titles `%s` by what it does', (command, label, subject) => {
+ render(<ToolTitle apiName={'Bash'} args={{ command }} identifier={'claude-code'} />);
+
+ expect(screen.getByText(label)).toBeInTheDocument();
+ expect(screen.getByText(subject)).toBeInTheDocument();
+ expect(screen.queryByText('Bash')).toBeNull();
+ });
+
+ it('names an inline script by its language, without its code', () => {
+ const { container } = render(
+ <ToolTitle
+ apiName={'Bash'}
+ args={{ command: "cd /repo && python3 - <<'EOF'\nprint(1)\nEOF" }}
+ identifier={'claude-code'}
+ />,
+ );
+
+ expect(screen.getByText('python')).toBeInTheDocument();
+ expect(container.textContent).not.toContain('EOF');
+ });
+
+ it('keeps "<label> <command line>" for a command no action describes', () => {
+ render(
+ <ToolTitle
+ apiName={'Bash'}
+ args={{ command: 'cd /repo && bun run build' }}
+ identifier={'claude-code'}
+ />,
+ );
+
+ expect(screen.getByText('Bash')).toBeInTheDocument();
+ expect(screen.getByText('bun run build')).toBeInTheDocument();
+ });
+
+ it('leaves a described command on its description', () => {
+ render(
+ <ToolTitle
+ apiName={LocalSystemApiName.runCommand}
+ args={{ command: 'sed -n 1,80p src/a.ts', description: '查看文件开头' }}
+ identifier={LocalSystemIdentifier}
+ />,
+ );
+
+ expect(screen.getByText('查看文件开头')).toBeInTheDocument();
+ expect(screen.queryByText('read')).toBeNull();
+ });
+ });
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
index 8de0a06f503..391f4fe673f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.tsx
@@ -13,7 +13,7 @@ import { shinyTextStyles } from '@/styles';
import { sx } from '@/styles/sx';
import { getToolDisplayName } from '../../toolDisplayNames';
-import { extractToolKeyword } from './extractToolKeyword';
+import { extractToolKeyword, getShellCommandTitle } from './extractToolKeyword';
export const styles = stylex.create({
aborted: { color: cssVar.colorTextQuaternary },
@@ -84,6 +84,7 @@ const ToolTitle = memo<ToolTitleProps>(
const effectiveArgs = args ?? partialArgs;
const keyword = useMemo(() => extractToolKeyword(effectiveArgs), [effectiveArgs]);
+ const commandTitle = useMemo(() => getShellCommandTitle(effectiveArgs), [effectiveArgs]);
// Only command step descriptions can replace the action. Resource titles,
// queries, and paths can also contain CJK text but do not say what the tool
@@ -122,6 +123,22 @@ const ToolTitle = memo<ToolTitleProps>(
);
}
+ // An undescribed shell command reads as what it does ("读取 app.ts"); the
+ // exact command line stays one click away in the expanded row.
+ if (commandTitle) {
+ const { action, isProse, subject } = commandTitle;
+ return (
+ <div {...stylex.props(styles.root, isAborted && styles.aborted)}>
+ <span {...sx(styles.label, isLoading ? shinyTextStyles.shinyText : undefined)}>
+ {t(`builtins.shellCommand.${action}`)}
+ </span>
+ {subject && (
+ <span {...stylex.props(isProse ? styles.standalone : styles.keyword)}>{subject}</span>
+ )}
+ </div>
+ );
+ }
+
return (
<div {...stylex.props(styles.root, isAborted && styles.aborted)}>
{isStandaloneDescription ? (
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts
index cab23f812e0..cce0ef246d2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts
@@ -1,4 +1,6 @@
-import { readableShellCommand } from './readableShellCommand';
+import { describeShellCommandTitle } from './shellCommand/describeShellCommandTitle';
+import { readableShellCommand } from './shellCommand/readableShellCommand';
+import type { ShellCommandTitle } from './shellCommand/types';
// Arg keys checked in priority order. NAME_KEYS (model-written description /
// title) lead because they state what the step does; then query/pattern
@@ -66,3 +68,18 @@ export const extractToolKeyword = (args?: Record<string, unknown>): string | und
return undefined;
};
+
+/**
+ * What an undescribed shell command does ("读取 app.ts", "运行测试 a.test.ts"),
+ * to replace the generic "执行命令 <command line>" title. `undefined` when the
+ * call has a model-written description (which already says what it does) or
+ * when no action describes the command.
+ */
+export const getShellCommandTitle = (
+ args?: Record<string, unknown>,
+): ShellCommandTitle | undefined => {
+ if (!args || pickString(args, NAME_KEYS)) return undefined;
+ // `script` is left out: it can hold source code for a non-shell runtime.
+ const command = pickString(args, ['command', 'cmd']);
+ return command ? describeShellCommandTitle(command) : undefined;
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/cliStep.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/cliStep.ts
new file mode 100644
index 00000000000..6615c94e6c1
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/cliStep.ts
@@ -0,0 +1,339 @@
+import type { ShellCommandAction, ShellCommandTitle } from './types';
+
+/**
+ * Steps of the CLIs an agent drives every day: GitHub's `gh`, Vercel's `vc`,
+ * and LobeHub's `lh`. Their command lines are long
+ * (`cd ~/code/app && gh api repos/owner/app/pulls/12/comments --jq ...`) while
+ * what they did fits in a few words ("调用 GitHub API owner/app/pulls/12/comments").
+ *
+ * Ported from Caxri (`packages/protocol/src/agent/tool-rows/shell/agent-shell-cli.ts`).
+ */
+
+/**
+ * Options of `gh`, `vc`, and `lh` whose value is the next word, so
+ * `gh issue view -R owner/app 12` names `12`, not `owner/app`. Short options
+ * that are booleans on some subcommands (`gh pr view -w`) are left out; a value
+ * they mis-skip only costs the subject, never a wrong one.
+ */
+const VALUE_OPTIONS = new Set([
+ '-R',
+ '--repo',
+ '-t',
+ '--title',
+ '-b',
+ '--body',
+ '-F',
+ '--body-file',
+ '-l',
+ '--label',
+ '-a',
+ '--assignee',
+ '-A',
+ '--author',
+ '-S',
+ '--search',
+ '-s',
+ '--state',
+ '-L',
+ '--limit',
+ '--json',
+ '-q',
+ '--jq',
+ '--template',
+ '-B',
+ '--base',
+ '-H',
+ '--head',
+ '--header',
+ '-m',
+ '--milestone',
+ '-p',
+ '--project',
+ '--workflow',
+ '-u',
+ '--user',
+ '-e',
+ '--event',
+ '-j',
+ '--job',
+ '--branch',
+ '-X',
+ '--method',
+ '-f',
+ '--raw-field',
+ '--field',
+ '--input',
+ '--hostname',
+ '--cache',
+ '--preview',
+ '-r',
+ '--reviewer',
+ '--add-label',
+ '--remove-label',
+ '--add-assignee',
+ '--remove-assignee',
+ '--scope',
+ '--token',
+ '--env',
+ '--environment',
+ '--cwd',
+ '--target',
+ '--meta',
+ '--output',
+]);
+
+/** The value of the first of `options` in `words`, as `-m "message"` or `--message=message`. */
+export const optionValue = (
+ words: readonly string[],
+ options: readonly string[],
+): string | undefined => {
+ const exact = new Set(options);
+ for (let index = 0; index < words.length; index += 1) {
+ const word = words[index] ?? '';
+ if (exact.has(word)) return words[index + 1];
+ const option = options.find((candidate) => word.startsWith(`${candidate}=`));
+ if (option) return word.slice(option.length + 1);
+ }
+ return undefined;
+};
+
+/** The words that are not options or option values. */
+const positionals = (words: readonly string[]): string[] => {
+ const values: string[] = [];
+ for (let index = 0; index < words.length; index += 1) {
+ const word = words[index] ?? '';
+ if (word === '--') {
+ values.push(...words.slice(index + 1));
+ break;
+ }
+ if (word !== '-' && word.startsWith('-')) {
+ if (VALUE_OPTIONS.has(word)) index += 1;
+ continue;
+ }
+ values.push(word);
+ }
+ return values;
+};
+
+/** `#12` for an issue, pull request, or run named by number (`12`, `#12`) or URL (`.../issues/12`). */
+const numberReference = (word: string | undefined): string | undefined => {
+ const match = /^#?(\d+)$|\/(?:issues|pull|runs)\/(\d+)/u.exec(word ?? '');
+ const digits = match?.slice(1).find(Boolean);
+ return digits && `#${digits}`;
+};
+
+const step = (action: ShellCommandAction, subject?: string, isProse = false): ShellCommandTitle => {
+ const trimmed = subject?.trim();
+ if (!trimmed) return { action };
+ return isProse ? { action, isProse, subject: trimmed } : { action, subject: trimmed };
+};
+
+const PULL_REQUEST_ACTIONS: Readonly<Record<string, ShellCommandAction | undefined>> = {
+ checks: 'pr.check',
+ close: 'pr.close',
+ comment: 'pr.comment',
+ create: 'pr.create',
+ diff: 'pr.check',
+ edit: 'pr.edit',
+ list: 'pr.list',
+ merge: 'pr.merge',
+ ready: 'pr.edit',
+ review: 'pr.comment',
+ status: 'pr.check',
+ view: 'pr.check',
+};
+
+const pullRequestStep = (arguments_: readonly string[]): ShellCommandTitle | null => {
+ const [verb = '', ...rest] = arguments_;
+ const action = PULL_REQUEST_ACTIONS[verb];
+ if (!action) return null;
+ if (action === 'pr.create') return step(action, optionValue(rest, ['--title', '-t']), true);
+ if (action === 'pr.list') {
+ const search = optionValue(rest, ['--search', '-S']);
+ return search ? step(action, search, true) : step(action, optionValue(rest, ['--head', '-H']));
+ }
+ return step(action, numberReference(positionals(rest).at(0)));
+};
+
+const ISSUE_ACTIONS: Readonly<Record<string, ShellCommandAction | undefined>> = {
+ close: 'issue.close',
+ comment: 'issue.comment',
+ edit: 'issue.edit',
+ reopen: 'issue.reopen',
+ view: 'issue.view',
+};
+
+const issueStep = (arguments_: readonly string[]): ShellCommandTitle | null => {
+ const [verb = '', ...rest] = arguments_;
+ if (verb === 'create') return step('issue.create', optionValue(rest, ['--title', '-t']), true);
+ if (verb === 'list') {
+ const search = optionValue(rest, ['--search', '-S']);
+ if (search) return step('issue.list', search, true);
+ const label = optionValue(rest, ['--label', '-l']);
+ return step('issue.list', label && `label: ${label}`);
+ }
+ const action = ISSUE_ACTIONS[verb];
+ return action ? step(action, numberReference(positionals(rest).at(0))) : null;
+};
+
+const runStep = (arguments_: readonly string[]): ShellCommandTitle | null => {
+ const [verb = '', ...rest] = arguments_;
+ const run = numberReference(positionals(rest).at(0))?.slice(1);
+ switch (verb) {
+ case 'view':
+ case 'watch': {
+ const isLog = rest.some((word) => word === '--log' || word === '--log-failed');
+ return step(isLog ? 'ci.logs' : 'ci.view', run);
+ }
+ case 'list': {
+ return step(
+ 'ci.list',
+ optionValue(rest, ['--branch', '-b']) ?? optionValue(rest, ['--workflow', '-w']),
+ );
+ }
+ case 'rerun': {
+ return step('ci.rerun', run);
+ }
+ case 'cancel': {
+ return step('ci.cancel', run);
+ }
+ default: {
+ return null;
+ }
+ }
+};
+
+/** A REST endpoint as the resource it names: `repos/owner/app/pulls/12?per_page=100` reads `owner/app/pulls/12`. */
+const apiEndpoint = (arguments_: readonly string[]): string | undefined => {
+ const endpoint = positionals(arguments_).at(0);
+ if (!endpoint) return undefined;
+ if (endpoint === 'graphql') return 'GraphQL';
+ return endpoint
+ .replace(/^\//u, '')
+ .replace(/^repos\//u, '')
+ .replace(/\?.*$/u, '');
+};
+
+const ghStep = (arguments_: readonly string[]): ShellCommandTitle | null => {
+ const [group = '', ...rest] = arguments_;
+ switch (group) {
+ case 'pr': {
+ return pullRequestStep(rest);
+ }
+ case 'issue': {
+ return issueStep(rest);
+ }
+ case 'run': {
+ return runStep(rest);
+ }
+ case 'workflow': {
+ return rest[0] === 'run' ? step('ci.workflowRun', positionals(rest.slice(1)).at(0)) : null;
+ }
+ case 'api': {
+ return step('githubApi', apiEndpoint(rest));
+ }
+ default: {
+ return null;
+ }
+ }
+};
+
+/** A deployment named by URL reads as its host; a deployment ID (`dpl_...`) or project name as written. */
+const deploymentName = (word: string | undefined): string | undefined => {
+ if (!word) return undefined;
+ try {
+ // `new URL('mailto:x')` parses with an empty host.
+ const { host } = new URL(word);
+ if (host) return host;
+ } catch {
+ // not a URL
+ }
+ return word;
+};
+
+const vercelStep = (arguments_: readonly string[]): ShellCommandTitle | null => {
+ const [verb = '', ...rest] = positionals(arguments_);
+ const target = deploymentName(rest.at(0));
+ switch (verb) {
+ case 'inspect': {
+ return step(arguments_.includes('--logs') ? 'vercel.logs' : 'vercel.inspect', target);
+ }
+ case 'logs': {
+ return step('vercel.logs', target);
+ }
+ case 'ls':
+ case 'list': {
+ return step('vercel.list', rest.at(0));
+ }
+ case 'env': {
+ if (rest[0] === 'ls' || rest[0] === 'list') return step('vercel.envList', rest.at(1));
+ if (rest[0] === 'pull') return step('vercel.envPull');
+ return null;
+ }
+ case 'redeploy': {
+ return step('vercel.redeploy', target);
+ }
+ case 'deploy': {
+ return step('vercel.deploy', arguments_.includes('--prod') ? 'production' : undefined);
+ }
+ case 'promote': {
+ return step('vercel.promote', target);
+ }
+ default: {
+ return null;
+ }
+ }
+};
+
+const lobeHubStep = (arguments_: readonly string[]): ShellCommandTitle | null => {
+ const [group = '', verb = '', ...rest] = positionals(arguments_);
+ if (group !== 'acceptance') return null;
+ switch (verb) {
+ case 'preflight': {
+ return step('acceptance.preflight');
+ }
+ case 'view':
+ case 'get': {
+ return step('acceptance.view', rest.at(0));
+ }
+ case 'feedback': {
+ return step('acceptance.feedback', rest.at(0));
+ }
+ case 'list': {
+ return step('acceptance.list');
+ }
+ case 'publish': {
+ return step('acceptance.publish');
+ }
+ case 'run': {
+ return rest[0] === 'ingest' ? step('acceptance.ingest') : null;
+ }
+ case 'link-pr': {
+ return step('acceptance.linkPr', numberReference(rest.at(1)) ?? rest.at(1));
+ }
+ default: {
+ return null;
+ }
+ }
+};
+
+const CLI_STEPS: Readonly<
+ Record<string, ((arguments_: readonly string[]) => ShellCommandTitle | null) | undefined>
+> = {
+ gh: ghStep,
+ lh: lobeHubStep,
+ vc: vercelStep,
+ vercel: vercelStep,
+};
+
+/**
+ * Reads one unwrapped command of `gh`, `vc`, or `lh`. `'other'` for a
+ * subcommand this module does not name, which still titles as the command
+ * line; `null` for anything else.
+ */
+export const describeCliStep = (words: readonly string[]): ShellCommandTitle | 'other' | null => {
+ const [name = '', ...arguments_] = words;
+ const read = CLI_STEPS[name];
+ if (!read) return null;
+ return read(arguments_) ?? 'other';
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/commandAction.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/commandAction.ts
new file mode 100644
index 00000000000..87d765af821
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/commandAction.ts
@@ -0,0 +1,650 @@
+import { describeCliStep, optionValue } from './cliStep';
+import { inlineHeredocSubstitutions } from './readableShellCommand';
+import type { SearchPatternDialect } from './searchPattern';
+import { searchPatternTerms } from './searchPattern';
+import type { ShellCommandTitle } from './types';
+
+/**
+ * What a shell command did, when it is one of the file reads, searches, or
+ * listings an agent runs to explore a project, or a test run, commit, push, or
+ * `gh` / `vc` / `lh` step. The Codex app reads `sed -n '1,40p' src/app.ts` as
+ * `Read app.ts`, not as a command line, so a run of exploration reads as what
+ * the agent looked at.
+ *
+ * Ported from Caxri (`packages/protocol/src/agent/agent-shell-command.ts`).
+ */
+export type ShellCommandAction =
+ | { kind: 'read'; paths: string[] }
+ | {
+ /** `isFileNames` when the pattern filters a file listing (`rg --files src | rg '\.test\.ts$'`). */
+ isFileNames?: boolean;
+ kind: 'search';
+ path?: string;
+ pattern: string;
+ /** What the pattern looks for, as a person reads it; see `searchPatternTerms`. */
+ terms: string[];
+ }
+ | { kind: 'list'; path?: string }
+ /** `targets` are the test files or directories the run names; `command` is the run without wrappers. */
+ | { command: string; kind: 'test'; targets: string[] }
+ | { isPushed: boolean; kind: 'commit'; message?: string }
+ | { branch?: string; kind: 'push' }
+ | { kind: 'cli'; title: ShellCommandTitle }
+ /** A `gh`, `vc`, or `lh` subcommand with no dedicated title. */
+ | { kind: 'other' };
+
+type ExploreAction = Extract<ShellCommandAction, { kind: 'list' | 'read' | 'search' }>;
+type StepAction = Exclude<ShellCommandAction, ExploreAction>;
+
+const READ_COMMANDS = new Set(['cat', 'head', 'tail', 'nl', 'bat', 'less', 'more']);
+const SEARCH_COMMANDS = new Set(['rg', 'grep', 'egrep', 'ag', 'ack']);
+const LIST_COMMANDS = new Set(['ls', 'find', 'fd', 'tree', 'eza']);
+
+/** `find` actions that delete or run commands on what it finds, so it no longer only lists. */
+const FIND_ACTIONS = new Set(['-delete', '-exec', '-execdir', '-ok', '-okdir']);
+
+/** `fd` options that run a command on each result. */
+const FD_ACTIONS = new Set(['-x', '--exec', '-X', '--exec-batch']);
+
+/** Commands that only reshape what an earlier pipeline stage printed, so `cat app.ts | head -40` is still a read. */
+const FILTER_COMMANDS = new Set([
+ 'head',
+ 'tail',
+ 'nl',
+ 'wc',
+ 'sort',
+ 'uniq',
+ 'cut',
+ 'tr',
+ 'sed',
+ 'jq',
+]);
+
+/** Options whose value is the next word, per command, so `head -n 40 app.ts` names `app.ts`, not `40`. */
+const VALUE_OPTIONS: Partial<Record<string, ReadonlySet<string>>> = {
+ find: new Set(['-name', '-iname', '-path', '-type', '-maxdepth', '-mindepth', '-newer', '-size']),
+ grep: new Set([
+ '-A',
+ '-B',
+ '-C',
+ '-m',
+ '-e',
+ '-f',
+ '--regexp',
+ '--file',
+ '--include',
+ '--exclude',
+ ]),
+ head: new Set(['-n', '-c']),
+ rg: new Set([
+ '-g',
+ '-t',
+ '-T',
+ '-A',
+ '-B',
+ '-C',
+ '-m',
+ '-e',
+ '-f',
+ '--regexp',
+ '--file',
+ '--glob',
+ '--type',
+ '--type-not',
+ '--max-count',
+ '--context',
+ '--after-context',
+ '--before-context',
+ ]),
+ sed: new Set(['-e', '-f']),
+ tail: new Set(['-n', '-c']),
+};
+
+/**
+ * Splits one simple command into words, honoring single and double quotes and
+ * backslash escapes (`Release\ Notes.md`). Returns `null` for anything a word
+ * split cannot read faithfully: a redirection, a substitution, or a variable.
+ */
+const splitWords = (command: string): string[] | null => {
+ const words: string[] = [];
+ let word = '';
+ let hasWord = false;
+ let quote: '"' | "'" | undefined;
+ let isEscaped = false;
+ for (const char of command) {
+ if (isEscaped) {
+ isEscaped = false;
+ // A backslash before a newline continues the line; the shell drops both.
+ if (char === '\n') continue;
+ // Inside double quotes a backslash escapes only `"`, `\`, `$`, and a backtick.
+ if (quote === '"' && !/["$\\`]/u.test(char)) word += '\\';
+ word += char;
+ hasWord = true;
+ continue;
+ }
+ if (char === '\\' && quote !== "'") {
+ isEscaped = true;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = undefined;
+ else word += char;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ hasWord = true;
+ continue;
+ }
+ if (/[<>`$(){}]/u.test(char)) return null;
+ if (/\s/u.test(char)) {
+ if (hasWord) words.push(word);
+ word = '';
+ hasWord = false;
+ continue;
+ }
+ word += char;
+ hasWord = true;
+ }
+ if (quote || isEscaped) return null;
+ if (hasWord) words.push(word);
+ return words;
+};
+
+/**
+ * Splits on unquoted list operators (`&&`, `;`, a newline) into commands, and
+ * each command on unquoted pipes into its stages. Returns `null` for `||` and
+ * for an empty command, which no single action describes.
+ */
+const splitList = (command: string): string[][] | null => {
+ const commands: string[][] = [];
+ let stages: string[] = [];
+ let current = '';
+ let quote: '"' | "'" | undefined;
+ let index = 0;
+ const didEnd = (isCommandEnd: boolean): boolean => {
+ stages.push(current.trim());
+ current = '';
+ if (stages.includes('')) return false;
+ if (isCommandEnd) {
+ commands.push(stages);
+ stages = [];
+ }
+ return true;
+ };
+ while (index < command.length) {
+ const char = command[index] ?? '';
+ // A backslash keeps the next character from closing a quote or ending a command.
+ if (char === '\\' && quote !== "'") {
+ current += command.slice(index, index + 2);
+ index += 2;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = undefined;
+ current += char;
+ index += 1;
+ continue;
+ }
+ if (char === '"' || char === "'") quote = char;
+ if (command.startsWith('||', index)) return null;
+ const operator = ['&&', ';', '\n', '|'].find((op) => command.startsWith(op, index));
+ if (operator && !quote) {
+ // A trailing `;` or newline ends the last command without starting another.
+ if (operator !== '|' && current.trim() === '' && stages.length === 0) {
+ index += operator.length;
+ continue;
+ }
+ if (!didEnd(operator !== '|')) return null;
+ index += operator.length;
+ continue;
+ }
+ current += char;
+ index += 1;
+ }
+ if (quote) return null;
+ if ((current.trim() !== '' || stages.length > 0) && !didEnd(true)) return null;
+ return commands.length > 0 ? commands : null;
+};
+
+/** A heredoc fed to a command's standard input, ending its line: `git commit -q -F - <<'EOF'`. */
+const HEREDOC_INPUT = /(\s-F\s+-|\s--file[ =]-)?\s+<<-?\s*(["']?)(\w+)\2[\t ]*\n/u;
+
+/**
+ * A heredoc fed to a command (`git commit -F - <<'EOF'`) is the command's
+ * input, not part of what it does, so it is dropped with its body; `-F -` reads
+ * its first line as the commit message (`-m '<first line>'`). An unterminated
+ * heredoc leaves the command unchanged.
+ */
+const inlineHeredocInputs = (command: string): string => {
+ let rest = command;
+ let result = '';
+ for (let start = HEREDOC_INPUT.exec(rest); start; start = HEREDOC_INPUT.exec(rest)) {
+ const [opener, fileOption, , tag] = start;
+ const lines = rest.slice(start.index + opener.length).split('\n');
+ const endLine = lines.findIndex((line) => line.trim() === tag);
+ if (endLine === -1) return command;
+ const firstLine = lines.slice(0, endLine).find((line) => line.trim() !== '') ?? '';
+ result += rest.slice(0, start.index);
+ if (fileOption) result += ` -m '${firstLine.trim().replaceAll("'", '')}'`;
+ rest = `\n${lines.slice(endLine + 1).join('\n')}`;
+ }
+ return result + rest;
+};
+
+/**
+ * Redirections an agent adds only to merge or silence output (`2>&1`,
+ * `2>/dev/null`); any other redirection still makes the command unreadable to
+ * {@link splitWords}.
+ */
+const OUTPUT_PLUMBING = /\s+(?:\d?>&\d|&?\d?>\s*\/dev\/null)(?=\s|$|[;|]|&&)/gu;
+
+/** A command's standard output sent to a file it names: `> ci.log`, `>> ci.log`, `&> ci.log`. */
+const OUTPUT_CAPTURE = /^(.*\S)\s+[&1]?>>?\s*(\S+)$/su;
+
+/** A command that only prints a file (`tail -15 ci.log`), with the file as its last word. */
+const CAPTURE_READ = /^(?:cat|head|tail)(?:\s.*)?\s(\S+)$/su;
+
+/**
+ * A background command often writes its output to a file and prints that file
+ * once it ends (`gh pr checks 31 --watch > ci.log 2>&1; tail -15 ci.log`). That
+ * pair does what the command does, so the redirection and the reads of its file
+ * are dropped. Any other redirection, or a read of a different file, is kept.
+ */
+const withoutCapturedOutput = (commands: readonly string[][]): readonly string[][] => {
+ for (let index = 0; index < commands.length - 1; index += 1) {
+ const stages = commands[index] ?? [];
+ const [, command = '', file = ''] = OUTPUT_CAPTURE.exec(stages.at(-1) ?? '') ?? [];
+ if (!command || file.startsWith('&')) continue;
+ const isReadBack = commands
+ .slice(index + 1)
+ .every(
+ (later) => later.length === 1 && CAPTURE_READ.exec(later[0]?.trim() ?? '')?.[1] === file,
+ );
+ if (isReadBack) return [...commands.slice(0, index), [...stages.slice(0, -1), command]];
+ }
+ return commands;
+};
+
+/**
+ * Drops what only changes how a command runs, not what it does: environment
+ * assignments, `env`, `time`, and the `rtk` output compressor.
+ */
+const WRAPPERS = new Set(['command', 'env', 'rtk', 'time']);
+
+const withoutWrappers = (words: readonly string[]): string[] => {
+ let rest = [...words];
+ for (;;) {
+ const [first = ''] = rest;
+ if (!WRAPPERS.has(first) && !/^[A-Z_]\w*=/iu.test(first)) return rest;
+ rest = rest.slice(1);
+ }
+};
+
+/**
+ * The positional words after the command name, skipping options and the values
+ * they take. Patterns given as options (`-e TODO -e FIXME`, `--regexp=TODO`)
+ * are collected in order; `hasPatternFile` marks patterns read from a file
+ * (`-f patterns.txt`), which the command line cannot name.
+ */
+const positionals = (
+ name: string,
+ arguments_: readonly string[],
+): { hasPatternFile: boolean; patterns: string[]; values: string[] } => {
+ const valueOptions = VALUE_OPTIONS[name];
+ const values: string[] = [];
+ const patterns: string[] = [];
+ let hasPatternFile = false;
+ for (let index = 0; index < arguments_.length; index += 1) {
+ const argument = arguments_[index] ?? '';
+ if (argument === '--') {
+ values.push(...arguments_.slice(index + 1));
+ break;
+ }
+ if (argument !== '-' && argument.startsWith('-')) {
+ if (argument.startsWith('--regexp=')) patterns.push(argument.slice('--regexp='.length));
+ if (argument.startsWith('--file=')) hasPatternFile = true;
+ if (valueOptions?.has(argument)) {
+ const value = arguments_.at(index + 1);
+ if ((argument === '-e' || argument === '--regexp') && value !== undefined) {
+ patterns.push(value);
+ }
+ if (argument === '-f' || argument === '--file') hasPatternFile = true;
+ index += 1;
+ }
+ continue;
+ }
+ values.push(argument);
+ }
+ return { hasPatternFile, patterns, values };
+};
+
+/** Which regular expression syntax a search command reads its pattern in. Short flags may be clustered (`grep -rnE`). */
+const searchDialect = (name: string, arguments_: readonly string[]): SearchPatternDialect => {
+ const hasFlag = (short: string, long: readonly string[]): boolean =>
+ arguments_.some(
+ (argument) =>
+ long.includes(argument) || (/^-[A-Z]+$/iu.test(argument) && argument.includes(short)),
+ );
+ if (name === 'ag' || name === 'ack') return hasFlag('Q', ['--literal']) ? 'fixed' : 'extended';
+ if (hasFlag('F', ['--fixed-strings'])) return 'fixed';
+ if (name !== 'grep') return 'extended';
+ return hasFlag('E', ['--extended-regexp']) || hasFlag('P', ['--perl-regexp'])
+ ? 'extended'
+ : 'basic';
+};
+
+/**
+ * `sed -i`, `-i.bak`, `-ni`, `--in-place`, and `--in-place=.bak` all rewrite the
+ * file, so the command is not a read even with `-n`.
+ */
+const isSedInPlace = (word: string): boolean =>
+ word === '--in-place' || word.startsWith('--in-place=') || /^-[A-Za-z]*i/u.test(word);
+
+/**
+ * A sed script that writes a file (`w out`, `s/a/b/w out`) or runs a command
+ * (`e`, `s/a/b/e`). Matches loosely: a false match only costs the action title.
+ */
+const SED_WRITE_SCRIPT = /(?:^|[;{}\s\d$])[wWe](?:\s|$)|\/[gpiImM\d]*[we](?:\s|;|$)/u;
+
+/** Whether a stage that otherwise reads or filters also writes a file or runs a command. */
+const writesFiles = (name: string, arguments_: readonly string[]): boolean => {
+ switch (name) {
+ case 'sed': {
+ return arguments_.some(
+ (word) => isSedInPlace(word) || (!word.startsWith('-') && SED_WRITE_SCRIPT.test(word)),
+ );
+ }
+ case 'sort': {
+ // `-o FILE`, `--output=FILE`, and clusters like `-uo FILE` write the sorted result.
+ return arguments_.some((word) => word.startsWith('--output') || /^-[A-Za-z]*o/u.test(word));
+ }
+ case 'uniq': {
+ // `uniq in out` writes its second operand.
+ return arguments_.filter((word) => word === '-' || !word.startsWith('-')).length > 1;
+ }
+ default: {
+ return false;
+ }
+ }
+};
+
+const describeStage = (words: readonly string[]): ExploreAction | null => {
+ const [name = '', ...arguments_] = words;
+ const { hasPatternFile, patterns, values } = positionals(name, arguments_);
+ const hasOptionScript = hasPatternFile || patterns.length > 0;
+ if (READ_COMMANDS.has(name)) return values.length > 0 ? { kind: 'read', paths: values } : null;
+ if (name === 'sed') {
+ // Only `sed -n '1,40p' file` prints a file; any other script edits or transforms it.
+ if (!arguments_.includes('-n') || writesFiles(name, arguments_)) return null;
+ const paths = hasOptionScript ? values : values.slice(1);
+ return paths.length > 0 ? { kind: 'read', paths } : null;
+ }
+ if (SEARCH_COMMANDS.has(name)) {
+ if (name === 'rg' && arguments_.includes('--files')) {
+ const path = values.at(0);
+ return path === undefined ? { kind: 'list' } : { kind: 'list', path };
+ }
+ // Patterns read from a file have no name to show.
+ if (hasPatternFile) return null;
+ const optionPatterns = patterns.length > 0 ? patterns : undefined;
+ const searched = optionPatterns ?? values.slice(0, 1);
+ if (searched.length === 0) return null;
+ const dialect = searchDialect(name, arguments_);
+ const terms = searched.flatMap((pattern) => searchPatternTerms(pattern, dialect));
+ const pattern = searched.join(' ');
+ const path = values.at(optionPatterns ? 0 : 1);
+ return path === undefined
+ ? { kind: 'search', pattern, terms }
+ : { kind: 'search', path, pattern, terms };
+ }
+ if (name === 'find' && arguments_.some((argument) => FIND_ACTIONS.has(argument))) return null;
+ if (
+ name === 'fd' &&
+ arguments_.some((argument) => FD_ACTIONS.has(argument.replace(/=.*$/su, '')))
+ ) {
+ return null;
+ }
+ if (LIST_COMMANDS.has(name)) {
+ const path = values.at(0);
+ return path === undefined ? { kind: 'list' } : { kind: 'list', path };
+ }
+ return null;
+};
+
+/**
+ * One pipeline that explores: its first stage reads, searches, or lists, and
+ * every later stage only filters what it printed. A search over a file listing
+ * (`rg --files src | rg test`) finds files by name.
+ */
+const describeExplorePipeline = (stages: readonly string[][]): ExploreAction | null => {
+ const [first = [], ...rest] = stages;
+ const action = describeStage(first);
+ if (!action) return null;
+ let filtered: ExploreAction = action;
+ for (const words of rest) {
+ const [name = '', ...arguments_] = words;
+ if (FILTER_COMMANDS.has(name)) {
+ if (writesFiles(name, arguments_)) return null;
+ continue;
+ }
+ if (!SEARCH_COMMANDS.has(name)) return null;
+ const filter = describeStage(words);
+ if (filter?.kind !== 'search' || filtered.kind !== 'list') return null;
+ filtered = {
+ isFileNames: true,
+ kind: 'search',
+ pattern: filter.pattern,
+ terms: filter.terms,
+ ...(filtered.path !== undefined && { path: filtered.path }),
+ };
+ }
+ return filtered;
+};
+
+/**
+ * Several explorations chained with `&&` or `;` read as one when they do the
+ * same thing: reads list every file, and searches or listings keep the first.
+ */
+const mergeExplorations = (actions: readonly ExploreAction[]): ExploreAction | null => {
+ const first = actions.at(0);
+ if (!first || actions.some((action) => action.kind !== first.kind)) return null;
+ if (first.kind !== 'read') return first;
+ const paths = actions.flatMap((action) => (action.kind === 'read' ? action.paths : []));
+ return { kind: 'read', paths: [...new Set(paths)] };
+};
+
+/** Package runners that only fetch or locate the tool they start: `bunx vitest`, `npx jest`. */
+const RUNNER_PREFIXES = new Set(['bunx', 'npx', 'pnpx']);
+
+/** Tools that start another tool after one subcommand (`pnpm exec`, `uv run`, `python -m`). */
+const RUNNER_SUBCOMMANDS: Readonly<Record<string, readonly string[] | undefined>> = {
+ bun: ['x'],
+ pnpm: ['exec', 'dlx'],
+ poetry: ['run'],
+ python: ['-m'],
+ python3: ['-m'],
+ uv: ['run'],
+ yarn: ['exec', 'dlx'],
+};
+
+const withoutRunner = (words: readonly string[]): string[] => {
+ const [name = '', second = ''] = words;
+ let rest: string[];
+ if (RUNNER_PREFIXES.has(name)) rest = words.slice(1);
+ else if (RUNNER_SUBCOMMANDS[name]?.includes(second)) rest = words.slice(2);
+ else return [...words];
+ // The runner's own flags (`bunx --bun`, `npx -y`) come before the tool.
+ while (rest[0]?.startsWith('-')) rest = rest.slice(1);
+ return rest;
+};
+
+/** Test runners started by name, and the subcommand that must follow when the tool does more than test. */
+const TEST_RUNNERS: Readonly<Record<string, string | undefined>> = {
+ ava: undefined,
+ cargo: 'test',
+ deno: 'test',
+ dotnet: 'test',
+ go: 'test',
+ jest: undefined,
+ mix: 'test',
+ mocha: undefined,
+ phpunit: undefined,
+ playwright: 'test',
+ pytest: undefined,
+ rspec: undefined,
+ swift: 'test',
+ vitest: undefined,
+};
+
+/** Options of a test run whose value is the next word and never a test file (`-c vitest.config.ts`). */
+const TEST_VALUE_OPTIONS = new Set([
+ '-c',
+ '--config',
+ '-t',
+ '--testNamePattern',
+ '-g',
+ '--grep',
+ '--project',
+ '--reporter',
+ '--shard',
+ '-k',
+ '-m',
+]);
+
+const PACKAGE_MANAGERS = new Set(['bun', 'npm', 'pnpm', 'yarn']);
+
+/**
+ * The words after the runner when `words` runs tests: a test runner
+ * (`vitest run`, `go test`), or a package script named `test` or `test:*`
+ * (`bun run test`, `pnpm test:unit`). `undefined` for anything else.
+ */
+const testArguments = (words: readonly string[]): string[] | undefined => {
+ const [name = '', second = '', third = ''] = words;
+ if (PACKAGE_MANAGERS.has(name)) {
+ const isRun = second === 'run' || second === 'run-script';
+ const script = isRun ? third : second;
+ // `bun test` is Bun's own runner and `npm t` npm's alias; both pass the rest on like a `test` script.
+ if (/^test(?::|$)/u.test(script) || (name === 'npm' && script === 't'))
+ return words.slice(isRun ? 3 : 2);
+ // `pnpm vitest` and `bun run vitest` start the project's own runner binary.
+ const rest = words.slice(isRun ? 2 : 1);
+ return Object.hasOwn(TEST_RUNNERS, script) ? testArguments(rest) : undefined;
+ }
+ if (!Object.hasOwn(TEST_RUNNERS, name)) return undefined;
+ const subcommand = TEST_RUNNERS[name];
+ if (subcommand !== undefined) return second === subcommand ? words.slice(2) : undefined;
+ if (name === 'vitest' && (second === 'bench' || second === 'init')) return undefined;
+ return words.slice(1).filter((word) => word !== 'run' && word !== 'watch');
+};
+
+/**
+ * The test files or directories a test run names, skipping options and their
+ * values. A bare word that is not a path (a test name filter) is left out.
+ */
+const testTargets = (arguments_: readonly string[]): string[] => {
+ const targets: string[] = [];
+ for (let index = 0; index < arguments_.length; index += 1) {
+ const argument = arguments_[index] ?? '';
+ if (argument.startsWith('-')) {
+ if (TEST_VALUE_OPTIONS.has(argument)) index += 1;
+ continue;
+ }
+ if (/[/\\]|\.[a-z]+$/iu.test(argument)) targets.push(argument);
+ }
+ return targets;
+};
+
+/** Git subcommands that only look at or stage the work, so `git add -A && git commit -m x` still reads as a commit. */
+const GIT_SETUP_COMMANDS = new Set(['add', 'status', 'diff', 'log', 'fetch', 'show', 'stash']);
+
+/**
+ * What one command (its first pipeline stage) does among tests, Git, and CLI
+ * steps: `setup` for a step such as `cd` or `git add` that only prepares the
+ * action next to it.
+ */
+const describeStep = (words: readonly string[], text: string): StepAction | 'setup' | null => {
+ const [name = ''] = words;
+ if (name === 'cd') return 'setup';
+ if (name === 'git') {
+ let rest = words.slice(1);
+ // Global options before the subcommand (`git -C apps/server commit`).
+ while (rest[0] === '-C' || rest[0] === '-c') rest = rest.slice(2);
+ const [subcommand = '', ...arguments_] = rest;
+ if (GIT_SETUP_COMMANDS.has(subcommand)) return 'setup';
+ if (subcommand === 'commit') {
+ const message = optionValue(arguments_, ['-m', '--message', '-am']);
+ return {
+ isPushed: false,
+ kind: 'commit',
+ ...(message?.trim() && { message: message.trim() }),
+ };
+ }
+ if (subcommand === 'push') {
+ const [, branch] = arguments_.filter((word) => !word.startsWith('-'));
+ return branch ? { branch, kind: 'push' } : { kind: 'push' };
+ }
+ return null;
+ }
+ const cliStep = describeCliStep(words);
+ if (cliStep === 'other') return { kind: 'other' };
+ if (cliStep) return { kind: 'cli', title: cliStep };
+ const arguments_ = testArguments(withoutRunner(words));
+ if (arguments_ === undefined) return null;
+ return { command: text, kind: 'test', targets: testTargets(arguments_) };
+};
+
+/**
+ * Steps chained together read as one when they are one action with its
+ * preparation (`git add -A && git commit`), or the same action repeated: test
+ * runs list every target, and a commit followed by a push reads as both.
+ */
+const mergeSteps = (steps: readonly StepAction[]): StepAction | null => {
+ const first = steps.at(0);
+ if (!first) return null;
+ if (first.kind === 'test' && steps.every((step) => step.kind === 'test'))
+ return {
+ ...first,
+ targets: [...new Set(steps.flatMap((step) => (step.kind === 'test' ? step.targets : [])))],
+ };
+ if (first.kind === 'commit' && steps.slice(1).every((step) => step.kind === 'push'))
+ return { ...first, isPushed: steps.length > 1 };
+ return steps.length === 1 ? first : null;
+};
+
+/**
+ * Reads an unwrapped shell command as the action it performs; anything else
+ * returns `null`. Within each command only the first pipeline stage acts, and
+ * every later stage must be a filter such as `head`. A leading `cd <dir>` only
+ * moves where the rest runs.
+ */
+export const describeShellCommand = (command: string): ShellCommandAction | null => {
+ const inlined = inlineHeredocInputs(inlineHeredocSubstitutions(command.trim()));
+ const listed = splitList(inlined.replaceAll(OUTPUT_PLUMBING, ''));
+ if (!listed) return null;
+ const parsed: Array<{ stages: string[][]; text: string }> = [];
+ for (const stages of withoutCapturedOutput(listed)) {
+ const words = stages.map((stage) => splitWords(stage));
+ if (words.some((stage) => !stage?.[0])) return null;
+ const [first = [], ...rest] = words as string[][];
+ const unwrapped = withoutWrappers(first);
+ if (unwrapped.length === 0) return null;
+ parsed.push({
+ stages: [unwrapped, ...rest.map((stage) => withoutWrappers(stage))],
+ text: unwrapped.join(' '),
+ });
+ }
+ const body = parsed.filter(({ stages }, index) => index > 0 || stages[0]?.[0] !== 'cd');
+ const explorations = body.map(({ stages }) => describeExplorePipeline(stages));
+ if (explorations.length > 0 && explorations.every(Boolean))
+ return mergeExplorations(explorations as ExploreAction[]);
+ const steps: StepAction[] = [];
+ for (const { stages, text } of body) {
+ const [first = [], ...rest] = stages;
+ if (rest.some(([name = '']) => !FILTER_COMMANDS.has(name))) return null;
+ const step = describeStep(first, text);
+ if (step === null) return null;
+ if (step !== 'setup') steps.push(step);
+ }
+ return mergeSteps(steps);
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/describeShellCommandTitle.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/describeShellCommandTitle.test.ts
new file mode 100644
index 00000000000..5e9a7fd9157
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/describeShellCommandTitle.test.ts
@@ -0,0 +1,406 @@
+import { describe, expect, it } from 'vitest';
+
+import { describeShellCommandTitle as title } from './describeShellCommandTitle';
+
+describe('describeShellCommandTitle', () => {
+ describe('exploration', () => {
+ it('reads a file read as the files it reads', () => {
+ expect(title("sed -n '1,40p' src/app.ts")).toEqual({ action: 'read', subject: 'app.ts' });
+ expect(title('sed -n 1,80p src/a.ts 2>&1 | head -40')).toEqual({
+ action: 'read',
+ subject: 'a.ts',
+ });
+ expect(title('/bin/zsh -lc "cat docs/a.md docs/b.md"')).toEqual({
+ action: 'read',
+ subject: 'a.md, b.md',
+ });
+ expect(title('head -n 40 src/app.ts')).toMatchObject({ subject: 'app.ts' });
+ expect(title('cd apps && nl -ba src/app.ts | sed -n 1,20p')).toEqual({
+ action: 'read',
+ subject: 'app.ts',
+ });
+ expect(title("sed -n '1,230p' src/config.ts && sed -n '1,220p' src/rotate.ts")).toMatchObject(
+ { action: 'read', subject: 'config.ts, rotate.ts' },
+ );
+ expect(title('cat a.ts; cat a.ts')).toMatchObject({ action: 'read', subject: 'a.ts' });
+ });
+
+ it('names the skill when a SKILL.md is read', () => {
+ expect(title('cat .agents/skills/review/SKILL.md')).toEqual({
+ action: 'useSkill',
+ subject: 'review',
+ });
+ expect(title('cat SKILL.md')).toMatchObject({ action: 'read' });
+ });
+
+ it('reads a search as its terms and where it looks', () => {
+ expect(title("rg -n -g '*.ts' POLICY_VERSION src/hooks")).toEqual({
+ action: 'search',
+ subject: 'POLICY_VERSION in hooks',
+ });
+ expect(title('rg -n "TODO" src')).toEqual({ action: 'search', subject: 'TODO in src' });
+ expect(title('grep -rn "foo bar"')).toEqual({ action: 'search', subject: 'foo bar' });
+ expect(title(String.raw`grep -n "退回原批次\|APPROVAL_DEV" docs/schema.md`)).toMatchObject({
+ subject: '退回原批次, APPROVAL_DEV in schema.md',
+ });
+ expect(title("rg -n 'useState|useEffect' src")).toMatchObject({
+ subject: 'useState, useEffect in src',
+ });
+ expect(title(String.raw`grep -F 'a\|b' x.ts`)).toMatchObject({
+ subject: String.raw`a\|b in x.ts`,
+ });
+ expect(title('rtk rg -n TODO src')).toMatchObject({ subject: 'TODO in src' });
+ expect(title(String.raw`rg --files scripts/rotation | rg '\.test\.ts'"$"''`)).toEqual({
+ action: 'findFiles',
+ subject: '.test.ts$ in rotation',
+ });
+ });
+
+ it('reads a listing as the folder it lists', () => {
+ expect(title('rg --files src')).toEqual({ action: 'list', subject: 'src' });
+ expect(title('ls')).toEqual({ action: 'listFiles' });
+ expect(title('find . -name "*.ts"')).toEqual({ action: 'listFiles' });
+ });
+
+ it('keeps an in-place sed a plain command', () => {
+ // `-i.bak` and `--in-place` used to read as "读取 app.ts" while rewriting it.
+ expect(title("sed -n -i 's/a/b/p' app.ts")).toBeUndefined();
+ expect(title("sed -n -i.bak 's/a/b/p' app.ts")).toBeUndefined();
+ expect(title("sed -ni 's/a/b/p' app.ts")).toBeUndefined();
+ expect(title("sed -n --in-place 's/a/b/p' app.ts")).toBeUndefined();
+ expect(title("sed -n --in-place=.bak 's/a/b/p' app.ts")).toBeUndefined();
+ });
+
+ it('keeps a read whose sed script writes or runs a command a plain command', () => {
+ expect(title("sed -n 'w out.ts' app.ts")).toBeUndefined();
+ expect(title("sed -n 's/a/b/w out.ts' app.ts")).toBeUndefined();
+ expect(title("sed -n '1e date' app.ts")).toBeUndefined();
+ });
+
+ it('keeps a pipeline whose filter writes a file a plain command', () => {
+ // `sort -o` used to read as "读取 a.ts" while overwriting b.ts.
+ expect(title('cat src/a.ts | sort -o src/b.ts')).toBeUndefined();
+ expect(title('cat src/a.ts | sort --output=src/b.ts')).toBeUndefined();
+ expect(title('cat src/a.ts | sort -uo src/b.ts')).toBeUndefined();
+ expect(title('cat src/a.ts | uniq - src/b.ts')).toBeUndefined();
+ expect(title("cat src/a.ts | sed -i 's/a/b/' src/b.ts")).toBeUndefined();
+ expect(title("cat src/a.ts | sed 's/a/b/w src/b.ts'")).toBeUndefined();
+ // Pure filters still read.
+ expect(title("cat src/a.ts | sort -u | uniq -c | sed 's/a/b/g' | head -5")).toEqual({
+ action: 'read',
+ subject: 'a.ts',
+ });
+ });
+
+ it('keeps a find or fd that deletes or runs commands a plain command', () => {
+ // `find -delete` used to read as "列出文件" while it removed files.
+ expect(title('find . -name "*.tmp" -delete')).toBeUndefined();
+ expect(title('find . -name "*.ts" -exec wc -l +')).toBeUndefined();
+ expect(title('fd -e tmp -x rm')).toBeUndefined();
+ expect(title('fd -e tmp --exec-batch=rm')).toBeUndefined();
+ });
+
+ it('reads backslash-escaped spaces as part of one word', () => {
+ // Used to split into "Release, Notes.md".
+ expect(title(String.raw`cat docs/Release\ Notes.md`)).toEqual({
+ action: 'read',
+ subject: 'Release Notes.md',
+ });
+ expect(title(String.raw`rg -n foo\ bar src`)).toEqual({
+ action: 'search',
+ subject: 'foo bar in src',
+ });
+ expect(title(String.raw`cat "docs/a\"b.md"`)).toMatchObject({ subject: 'a"b.md' });
+ // A line continuation is not a word: this used to read "\n in TODO".
+ expect(title('rg \\\n -n TODO src')).toEqual({ action: 'search', subject: 'TODO in src' });
+ });
+
+ it('reads every pattern given as an option, and none read from a file', () => {
+ // Only the last `-e` used to be kept.
+ expect(title('rg -n -e TODO -e FIXME src')).toEqual({
+ action: 'search',
+ subject: 'TODO, FIXME in src',
+ });
+ expect(title('rg -n --regexp=TODO src')).toEqual({
+ action: 'search',
+ subject: 'TODO in src',
+ });
+ expect(title('grep -rn --regexp TODO src')).toEqual({
+ action: 'search',
+ subject: 'TODO in src',
+ });
+ // `-f` used to make `src` read as the pattern.
+ expect(title('rg -n -f patterns.txt src')).toBeUndefined();
+ expect(title('grep -rn --file=patterns.txt src')).toBeUndefined();
+ });
+
+ it('keeps different explorations chained together a plain command', () => {
+ expect(title('cat a.ts && rg TODO')).toBeUndefined();
+ });
+ });
+
+ describe('test runs', () => {
+ it('reads a test run by its targets, through rtk and package runners', () => {
+ expect(title('rtk vitest run src/a.test.ts src/b.test.ts')).toEqual({
+ action: 'runTests',
+ subject: 'a.test.ts, b.test.ts',
+ });
+ expect(title("bunx vitest run --silent='passed-only' src/foo.test.ts")).toEqual({
+ action: 'runTests',
+ subject: 'foo.test.ts',
+ });
+ expect(title('bunx vitest run -t "parses" -c vitest.config.ts src/a.test.ts')).toMatchObject({
+ subject: 'a.test.ts',
+ });
+ expect(title('CI=1 pnpm test:unit')).toEqual({
+ action: 'runTests',
+ subject: 'pnpm test:unit',
+ });
+ for (const command of [
+ 'bun run test',
+ 'npm test',
+ 'bun test',
+ 'pnpm vitest',
+ 'uv run pytest tests/unit',
+ 'python -m pytest -k slow',
+ 'go test ./...',
+ 'cargo test',
+ 'bunx playwright test e2e/app.e2e.ts',
+ 'cd apps/server && rtk vitest run src/a.test.ts 2>&1 | tail -20',
+ ])
+ expect(title(command), command).toMatchObject({ action: 'runTests' });
+ expect(title('go test ./internal/...')).toMatchObject({ subject: './internal/...' });
+ });
+
+ it('keeps a command that only looks like a test run', () => {
+ for (const command of ['vitest bench', 'playwright install', 'bun scripts/test.ts'])
+ expect(title(command), command).toBeUndefined();
+ });
+ });
+
+ describe('Git', () => {
+ it('reads a commit or push with its message or branch', () => {
+ expect(title('git add -A && rtk git commit -m "fix(chat): stop waiting"')).toEqual({
+ action: 'commit',
+ isProse: true,
+ subject: 'fix(chat): stop waiting',
+ });
+ expect(
+ title(
+ 'git commit -m "$(cat <<\'EOF\'\nfeat: steer while waiting\n\nBody text.\nEOF\n)" && git push',
+ ),
+ ).toMatchObject({ action: 'commitAndPush', subject: 'feat: steer while waiting' });
+ expect(title('rtk git push -u origin feat/wait-steer')).toEqual({
+ action: 'push',
+ subject: 'feat/wait-steer',
+ });
+ expect(
+ title("git add -A && git commit -q -F - <<'EOF'\nfix: keep titles short\n\nBody\nEOF"),
+ ).toMatchObject({ action: 'commit', subject: 'fix: keep titles short' });
+ });
+
+ it('keeps other Git commands a plain command', () => {
+ for (const command of ['git status', 'git commit --amend && rm -rf out'])
+ expect(title(command), command).toBeUndefined();
+ });
+ });
+
+ describe('gh, vc and lh', () => {
+ it('names pull request steps', () => {
+ expect(
+ title('gh pr create --base main --title "Steer while waiting" --body-file /tmp/body.md'),
+ ).toEqual({ action: 'pr.create', isProse: true, subject: 'Steer while waiting' });
+ expect(title('rtk gh pr merge 2383 --squash')).toEqual({
+ action: 'pr.merge',
+ subject: '#2383',
+ });
+ expect(title('gh pr checks https://github.com/owner/project/pull/12 --watch')).toEqual({
+ action: 'pr.check',
+ subject: '#12',
+ });
+ expect(title('gh pr list --search "tool rows"')).toMatchObject({
+ action: 'pr.list',
+ subject: 'tool rows',
+ });
+ });
+
+ it('reads a command whose captured output is read back as that command', () => {
+ for (const command of [
+ 'cd /work/app && gh pr checks 31 --watch > /tmp/ci.log 2>&1; tail -15 /tmp/ci.log',
+ 'gh pr checks 31 --watch --interval 20 &> ci.log && cat ci.log',
+ ])
+ expect(title(command), command).toEqual({ action: 'pr.check', subject: '#31' });
+ for (const command of [
+ 'gh pr checks 31 --watch > /tmp/ci.log',
+ 'gh pr checks 31 --watch > /tmp/ci.log; tail -15 /tmp/other.log',
+ ])
+ expect(title(command), command).toBeUndefined();
+ });
+
+ it('names issue, CI, API, deployment and acceptance steps', () => {
+ const cases: Array<[string, { action: string; subject?: string }]> = [
+ ['cd ~/code/app && gh issue view 12 --comments', { action: 'issue.view', subject: '#12' }],
+ [
+ 'gh issue view https://github.com/owner/app/issues/34',
+ { action: 'issue.view', subject: '#34' },
+ ],
+ [
+ 'gh issue list --repo owner/app --search "login loop" --limit 10',
+ { action: 'issue.list', subject: 'login loop' },
+ ],
+ [
+ 'gh issue create --title "Fix the login loop" --body-file /tmp/b.md',
+ { action: 'issue.create', subject: 'Fix the login loop' },
+ ],
+ ['gh issue comment 5 --body-file /tmp/c.md', { action: 'issue.comment', subject: '#5' }],
+ ['gh run view 123456 --log-failed', { action: 'ci.logs', subject: '123456' }],
+ ['rtk gh run watch 123456', { action: 'ci.view', subject: '123456' }],
+ ['gh run list --branch feat/x --limit 5', { action: 'ci.list', subject: 'feat/x' }],
+ ['gh run rerun 99 --failed', { action: 'ci.rerun', subject: '99' }],
+ [
+ "gh api repos/owner/app/pulls/12/comments --jq '.[].body' | jq length",
+ { action: 'githubApi', subject: 'owner/app/pulls/12/comments' },
+ ],
+ [
+ "gh api graphql -f query='query { viewer { login } }'",
+ { action: 'githubApi', subject: 'GraphQL' },
+ ],
+ [
+ 'vc inspect https://example.vercel.app --scope team',
+ { action: 'vercel.inspect', subject: 'example.vercel.app' },
+ ],
+ ['vc logs dpl_123', { action: 'vercel.logs', subject: 'dpl_123' }],
+ ['vc env ls production', { action: 'vercel.envList', subject: 'production' }],
+ ['lh acceptance preflight --json', { action: 'acceptance.preflight' }],
+ ['lh acceptance view acc_1 --json', { action: 'acceptance.view', subject: 'acc_1' }],
+ [
+ 'cd ~/code/app && lh acceptance run ingest --dir .records/x',
+ { action: 'acceptance.ingest' },
+ ],
+ ];
+ for (const [command, expected] of cases)
+ expect(title(command), command).toMatchObject(expected);
+ });
+
+ it('keeps a subcommand with no dedicated title a plain command', () => {
+ expect(title('cd ~/code/app && gh label list --repo owner/app')).toBeUndefined();
+ });
+ });
+
+ describe('inline scripts', () => {
+ it('names the language of a heredoc script instead of its code', () => {
+ expect(title("cd /work/repo && python3 - <<'EOF'\nprint(1)\nEOF")).toEqual({
+ action: 'runScript.python',
+ });
+ expect(title("python3 -I - <<'PY'\nprint(1)\nPY")).toEqual({ action: 'runScript.python' });
+ expect(title("uv run --with rich python - <<'EOF'\nprint(1)\nEOF")).toEqual({
+ action: 'runScript.python',
+ });
+ expect(title("node <<'JS'\nconsole.log(1)\nJS")).toEqual({ action: 'runScript.node' });
+ expect(title("bash <<'SH'\nls\nSH")).toEqual({ action: 'runScript.shell' });
+ expect(title("python3 - <<'END-JSON'\nprint(1)\nEND-JSON")).toEqual({
+ action: 'runScript.python',
+ });
+ });
+
+ it('names a script passed as one argument', () => {
+ expect(title(`python3 -c "import json; print(json.load(open('a.json')))"`)).toEqual({
+ action: 'runScript.python',
+ });
+ expect(title(`perl -0pi -e 's/a/b/g' src/app.ts`)).toEqual({ action: 'runScript.perl' });
+ expect(title(`bun -e 'console.log(1)'`)).toEqual({ action: 'runScript.bun' });
+ });
+
+ it('keeps a shell -c wrapper and a script file as the command line', () => {
+ expect(title(`zsh -i -c 'echo $PATH'`)).toBeUndefined();
+ expect(title('python3 tools/report.py --json')).toBeUndefined();
+ });
+
+ it('shows the comment a script opens with', () => {
+ expect(title("python3 - <<'EOF'\n# Count rows per session\nprint(1)\nEOF")).toEqual({
+ action: 'runScript.python',
+ isProse: true,
+ subject: 'Count rows per session',
+ });
+ });
+
+ it('shows what runs after the script', () => {
+ expect(title("python3 - <<'EOF'\nprint(1)\nEOF\nbun run check")).toEqual({
+ action: 'runScript.python',
+ subject: '→ bun run check',
+ });
+ expect(title(`python3 -c 'print(1)' && git diff --stat`)).toMatchObject({
+ subject: '→ git diff --stat',
+ });
+ expect(title("python3 - <<'EOF' && echo ok\nprint(1)\nEOF\nls")).toMatchObject({
+ subject: '→ ls',
+ });
+ });
+
+ it('reads repeated scripts as one and drops progress echoes', () => {
+ expect(
+ title("python3 - <<'A'\nprint(1)\nA\npython3 - <<'B'\nprint(2)\nB\ncat types.ts"),
+ ).toMatchObject({ action: 'runScript.python', subject: '→ cat types.ts' });
+ expect(title("python3 - <<'EOF'\nprint(1)\nEOF\necho done")).toEqual({
+ action: 'runScript.python',
+ });
+ });
+
+ it('waits for a streaming heredoc to finish before naming it', () => {
+ expect(title("python3 - <<'EOF'\nprint(1)")).toBeUndefined();
+ });
+ });
+
+ describe('heredoc file writes', () => {
+ it('reads as a write of that file', () => {
+ expect(title("cat > a.md <<'EOF'\n# Title\nEOF")).toEqual({
+ action: 'write',
+ subject: 'a.md',
+ });
+ expect(title("cat >> /tmp/run/ledger.md <<'EOF'\nrow\nEOF")).toMatchObject({
+ subject: 'ledger.md',
+ });
+ expect(title('cat <<\'EOF\' > "notes/plan.md"\nx\nEOF')).toMatchObject({
+ subject: 'plan.md',
+ });
+ expect(title("tee -a out.log >/dev/null <<'EOF'\nx\nEOF")).toMatchObject({
+ subject: 'out.log',
+ });
+ expect(
+ title(
+ "cd /repo && mkdir -p src/components && cat > src/components/LimitReachedIcon.tsx <<'EOF'\nexport {}\nEOF",
+ ),
+ ).toEqual({ action: 'write', subject: 'LimitReachedIcon.tsx' });
+ });
+
+ it('reads a file written for the next command as that command', () => {
+ expect(
+ title(
+ "cat > /tmp/body.md <<'EOF'\nBody\nEOF\ngh issue create --title 'Fix login' --body-file /tmp/body.md",
+ ),
+ ).toMatchObject({ action: 'issue.create', subject: 'Fix login' });
+ });
+
+ it('shows a command it cannot name after the file', () => {
+ expect(title("cat >> a.md <<'EOF'\nx\nEOF\ntail -5 a.md | wc -l")).toEqual({
+ action: 'write',
+ subject: 'a.md → tail -5 a.md | wc -l',
+ });
+ });
+ });
+
+ it('keeps any other command a plain command', () => {
+ for (const command of [
+ 'bun run build',
+ 'cat a.ts > b.ts',
+ "sed -i 's/a/b/' app.ts",
+ 'sed s/a/b/ app.ts',
+ 'cat app.ts | bun run format',
+ 'ls && rm -rf build',
+ 'cat $FILE',
+ 'cat',
+ 'for f in a.ts b.ts; do wc -l "$f"; done',
+ ])
+ expect(title(command), command).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/describeShellCommandTitle.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/describeShellCommandTitle.ts
new file mode 100644
index 00000000000..331d53ac769
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/describeShellCommandTitle.ts
@@ -0,0 +1,118 @@
+import { getRunCommandDisplayCommand } from '@lobechat/shared-tool-ui/run-command';
+
+import { describeShellCommand } from './commandAction';
+import { readableShellCommand } from './readableShellCommand';
+import { describeShellScript } from './scriptStep';
+import type { ShellCommandAction, ShellCommandTitle } from './types';
+
+const EXPLORE_ACTIONS: ReadonlySet<ShellCommandAction> = new Set([
+ 'findFiles',
+ 'list',
+ 'listFiles',
+ 'read',
+ 'search',
+]);
+
+const basename = (path: string): string => {
+ const trimmed = path.replace(/[/\\]+$/, '');
+ return trimmed.split(/[/\\]/).pop() || trimmed;
+};
+
+/**
+ * Reading a skill's `skills/<name>/SKILL.md` is how Codex uses a skill, so the
+ * row names the skill instead of `SKILL.md`. A `SKILL.md` outside a `skills`
+ * folder is an ordinary read.
+ */
+const skillName = (path: string | undefined): string | undefined => {
+ const [folder, name, file] = (path ?? '').split(/[/\\]+/u).slice(-3);
+ return file === 'SKILL.md' && folder === 'skills' && name ? name : undefined;
+};
+
+const describeAction = (command: string): ShellCommandTitle | undefined | null => {
+ const action = describeShellCommand(command);
+ switch (action?.kind) {
+ case 'read': {
+ const skill = action.paths.length === 1 ? skillName(action.paths[0]) : undefined;
+ if (skill) return { action: 'useSkill', subject: skill };
+ return { action: 'read', subject: action.paths.map(basename).join(', ') };
+ }
+ case 'search': {
+ const terms = action.terms.join(', ');
+ return {
+ action: action.isFileNames ? 'findFiles' : 'search',
+ subject: action.path ? `${terms} in ${basename(action.path)}` : terms,
+ };
+ }
+ case 'list': {
+ const path = action.path === '.' ? undefined : action.path;
+ return path ? { action: 'list', subject: basename(path) } : { action: 'listFiles' };
+ }
+ case 'test': {
+ // Go's `./...` pattern names a package tree; its last segment alone would read `...`.
+ const targets = action.targets.map((target) =>
+ target.endsWith('...') ? target : basename(target),
+ );
+ return {
+ action: 'runTests',
+ subject: targets.length > 0 ? targets.join(', ') : readableShellCommand(action.command),
+ };
+ }
+ case 'commit': {
+ const action_ = action.isPushed ? 'commitAndPush' : 'commit';
+ return action.message
+ ? { action: action_, isProse: true, subject: action.message }
+ : { action: action_ };
+ }
+ case 'push': {
+ return action.branch ? { action: 'push', subject: action.branch } : { action: 'push' };
+ }
+ case 'cli': {
+ return action.title;
+ }
+ // A `gh` / `vc` / `lh` subcommand with no dedicated title reads as the command.
+ case 'other': {
+ return undefined;
+ }
+ case undefined: {
+ return null;
+ }
+ }
+};
+
+const describe = (command: string): ShellCommandTitle | undefined => {
+ const action = describeAction(command);
+ if (action !== null) return action;
+ const step = describeShellScript(command);
+ if (!step) return undefined;
+ const rest = step.rest === undefined ? undefined : describe(step.rest);
+ // A file written for the command after it (an issue body for
+ // `gh issue create --body-file`) is that step's input. A read, search, or
+ // listing after it only checks the result, so the write stays the title.
+ if (step.kind === 'write' && rest && !EXPLORE_ACTIONS.has(rest.action)) return rest;
+ // Two scripts in a row (`python3 - <<'EOF'` twice) read as one.
+ if (step.kind === 'script' && rest?.action === step.action) return rest;
+ const then = step.rest === undefined ? undefined : `→ ${readableShellCommand(step.rest)}`;
+ if (step.kind === 'write') {
+ const name = basename(step.path);
+ return { action: 'write', subject: then ? `${name} ${then}` : name };
+ }
+ if (then) return { action: step.action, subject: then };
+ return step.note === undefined
+ ? { action: step.action }
+ : { action: step.action, isProse: true, subject: step.note };
+};
+
+/**
+ * The collapsed title of a shell command that has no model-written
+ * description: what it does ("读取 app.ts", "运行 Python 脚本") rather than the
+ * command line. `undefined` when no action describes the command, so the row
+ * keeps "执行命令 <readable command line>". The expanded row still shows the
+ * exact command.
+ *
+ * Ported from Caxri's `describeShellRow`
+ * (`packages/protocol/src/agent/tool-rows/shell/agent-shell-rows.ts`).
+ */
+export const describeShellCommandTitle = (rawCommand: string): ShellCommandTitle | undefined => {
+ const command = getRunCommandDisplayCommand(rawCommand);
+ return command ? describe(command) : undefined;
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/readableShellCommand.test.ts
similarity index 100%
rename from src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.test.ts
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/readableShellCommand.test.ts
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/readableShellCommand.ts
similarity index 94%
rename from src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.ts
rename to src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/readableShellCommand.ts
index c903806a98e..db3a4fdd886 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/readableShellCommand.ts
@@ -90,7 +90,7 @@ const unquoteShellWord = (word: string): string =>
* commit message reads as `git commit -m 'fix: …'`. An unterminated one is left
* for {@link withoutHeredocBodies} to cut.
*/
-const inlineHeredocSubstitutions = (command: string): string => {
+export const inlineHeredocSubstitutions = (command: string): string => {
let rest = command;
let result = '';
for (
@@ -226,3 +226,14 @@ export const readableShellCommand = (rawCommand: string): string => {
// A multi-line quoted argument still reads as one line.
return restore(joinLines(readable)).replaceAll(/\s*\n\s*/gu, ' ') || command.trim();
};
+
+/**
+ * The command after the setup statements that open it, heredoc bodies kept,
+ * for a reader that classifies what the first real statement does
+ * (`python3 - <<'EOF'` after `cd /work/repo &&`).
+ */
+export const withoutShellSetup = (rawCommand: string): string => {
+ const command = inlineHeredocSubstitutions(getRunCommandDisplayCommand(rawCommand));
+ const { masked, restore } = maskQuotedText(command);
+ return restore(stripShellSetup(masked, restore).rest);
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/scriptStep.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/scriptStep.ts
new file mode 100644
index 00000000000..6ec6da2b267
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/scriptStep.ts
@@ -0,0 +1,155 @@
+import { withoutShellSetup } from './readableShellCommand';
+import type { ShellCommandAction } from './types';
+
+type ScriptAction = Extract<ShellCommandAction, `runScript.${string}`>;
+
+/**
+ * What the first statement of a command does when it is a script the agent
+ * wrote inline (`python3 - <<'EOF'`, `node -e '...'`) or a file it writes from
+ * a heredoc (`cat > notes.md <<'EOF'`). `rest` is whatever follows that
+ * statement; `note` is the comment that opens a script, when it has one.
+ *
+ * Ported from Caxri (`packages/protocol/src/agent/tool-rows/shell/agent-shell-script.ts`).
+ */
+export type ShellScriptStep =
+ | { action: ScriptAction; kind: 'script'; note?: string; rest?: string }
+ | { kind: 'write'; path: string; rest?: string };
+
+const INTERPRETER_ACTIONS: Readonly<Partial<Record<string, ScriptAction>>> = {
+ bash: 'runScript.shell',
+ bun: 'runScript.bun',
+ node: 'runScript.node',
+ perl: 'runScript.perl',
+ python: 'runScript.python',
+ ruby: 'runScript.ruby',
+ sh: 'runScript.shell',
+ zsh: 'runScript.shell',
+};
+
+/**
+ * An interpreter, optionally by path or behind `uv run` and its options:
+ * `python3`, `/usr/bin/python3.12`, `uv run --with rich python`.
+ */
+const INTERPRETER = String.raw`(?:uv\s+run\s+(?:-[\w-]+(?:[= ][^\s;&|<>-]\S*)?\s+)*)?(?:\S*\/)?(?<name>python|python3(?:\.\d+)?|node|bun|ruby|perl|bash|sh|zsh)`;
+
+/** One argument word that cannot start a redirection or end the statement (`-I`, `-`, `"$f"`). */
+const ARGUMENT = String.raw`(?:'[^']*'|"[^"]*"|[^\s;&|<>'"]+)`;
+
+/**
+ * A heredoc opener and the rest of its line. The delimiter is any shell word
+ * (`EOF`, `END-JSON`, `\EOF`), so the classifier agrees with the title cleaner
+ * about where a heredoc ends.
+ */
+const HEREDOC = String.raw`<<-?\s*(?<quote>['"]?)\\?(?<tag>[^\s'"<>;&|()\\]+)\k<quote>(?<after>[^\n]*)\n`;
+
+const SCRIPT_HEREDOC = new RegExp(String.raw`^${INTERPRETER}(?:\s+${ARGUMENT})*\s*${HEREDOC}`, 'u');
+
+/**
+ * A script passed as one quoted argument: `python3 -c '...'`, `node -e "..."`.
+ * A shell's `-c` only wraps another command, so `bash -c` is not a script here.
+ */
+const SCRIPT_INLINE = new RegExp(
+ String.raw`^${INTERPRETER}(?:\s+-[\w-]+)*\s+-[ce]\s+(?:'[^']*'|"(?:[^"\\]|\\.)*")`,
+ 'u',
+);
+
+const WRITE_PATH = String.raw`(?<path>'[^']*'|"[^"]*"|[^\s;&|<>'"]+)`;
+
+/** A heredoc written to a file: `cat > notes.md <<'EOF'`, `cat <<EOF >> log.md`, `tee -a notes.md <<EOF`. */
+const WRITE_HEREDOCS = [
+ new RegExp(String.raw`^cat\s*>>?\s*${WRITE_PATH}\s*${HEREDOC}`, 'u'),
+ new RegExp(
+ String.raw`^cat\s*<<-?\s*(?<quote>['"]?)\\?(?<tag>[^\s'"<>;&|()\\]+)\k<quote>\s*>>?\s*${WRITE_PATH}(?<after>(?:[\s;&|<>][^\n]*)?)\n`,
+ 'u',
+ ),
+ new RegExp(String.raw`^tee\s+(?:-a\s+)?${WRITE_PATH}(?:\s*>\s*\/dev\/null)?\s*${HEREDOC}`, 'u'),
+];
+
+/**
+ * The text after a statement, without the `&&`, `;`, or newline that separates
+ * it, or `undefined` when nothing follows. An `echo` that only marks progress
+ * (`echo done`, `echo ---`) is not worth a title either.
+ */
+const restAfter = (text: string): string | undefined => {
+ const rest = text
+ .replace(/^\s*(?:&&|;)?\s*/u, '')
+ .replace(/^(?:echo\s+(?:[^\s$&;<>`|][^\n$&;<>`|]*)?(?:&&|;|\n)\s*)+/u, '')
+ .trim();
+ if (rest === '') return undefined;
+ const isOnlyEchoes = rest
+ .split(/&&|;|\n/u)
+ .every((statement) => /^\s*(?:echo\s[^$<>`|]*)?$/u.test(statement));
+ return isOnlyEchoes ? undefined : rest;
+};
+
+/**
+ * A heredoc's body and what follows its terminator line, with anything after
+ * the opener that chains another command (`<<'EOF' && echo ok`) kept in front.
+ * A pipe or redirection after the opener only shapes the output and is dropped.
+ * An unterminated (still streaming) heredoc yields `undefined`.
+ */
+const heredocParts = (
+ text: string,
+ match: RegExpExecArray,
+): { body: string[]; rest?: string } | undefined => {
+ const { tag = '', after = '' } = match.groups ?? {};
+ const lines = text.slice(match[0].length).split('\n');
+ const end = lines.findIndex((line) => line.trim() === tag);
+ if (end === -1) return undefined;
+ const chained = /^\s*(?:&&|;)/u.test(after) ? `${after}\n` : '';
+ const rest = restAfter(`${chained}${lines.slice(end + 1).join('\n')}`);
+ return { body: lines.slice(0, end), ...(rest !== undefined && { rest }) };
+};
+
+/** The comment a script opens with (`# Count the rows per session`), which says what it does better than its language. */
+const scriptNote = (body: readonly string[]): string | undefined => {
+ const first = body.find((line) => line.trim() !== '')?.trim() ?? '';
+ const note = /^(?:#(?!!)|\/\/)\s*(?<text>\S.*)$/u.exec(first)?.groups?.text.trim();
+ return note || undefined;
+};
+
+const unquoted = (word: string): string =>
+ /^(["'])[\s\S]*\1$/u.test(word) ? word.slice(1, -1) : word;
+
+const interpreterAction = (name: string | undefined): ScriptAction | undefined =>
+ INTERPRETER_ACTIONS[(name ?? '').replace(/3(?:\.\d+)?$/u, '')];
+
+/**
+ * Reads the first real statement of a command (after setup such as `cd`) as an
+ * inline script or a heredoc file write. Anything else, including a script file
+ * run by path (`python3 tool.py`), returns `null`.
+ */
+export const describeShellScript = (command: string): ShellScriptStep | null => {
+ const text = withoutShellSetup(command);
+ const heredoc = SCRIPT_HEREDOC.exec(text);
+ if (heredoc) {
+ const action = interpreterAction(heredoc.groups?.name);
+ const parts = action && heredocParts(text, heredoc);
+ if (!action || !parts) return null;
+ const note = scriptNote(parts.body);
+ return {
+ action,
+ kind: 'script',
+ ...(note !== undefined && { note }),
+ ...(parts.rest !== undefined && { rest: parts.rest }),
+ };
+ }
+ const inline = SCRIPT_INLINE.exec(text);
+ const inlineName = inline?.groups?.name ?? '';
+ if (inline && !['bash', 'sh', 'zsh'].includes(inlineName)) {
+ const action = interpreterAction(inlineName);
+ if (!action) return null;
+ // Arguments, pipes, and redirections after the script stay part of its statement.
+ const separator = /^[^\n"&';]*(?:&&|;|\n)/u.exec(text.slice(inline[0].length));
+ const rest = separator && restAfter(text.slice(inline[0].length + separator[0].length));
+ return { action, kind: 'script', ...(rest && { rest }) };
+ }
+ for (const pattern of WRITE_HEREDOCS) {
+ const write = pattern.exec(text);
+ const parts = write && heredocParts(text, write);
+ if (!write || !parts) continue;
+ const path = unquoted(write.groups?.path ?? '');
+ return { kind: 'write', path, ...(parts.rest !== undefined && { rest: parts.rest }) };
+ }
+ return null;
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/searchPattern.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/searchPattern.ts
new file mode 100644
index 00000000000..a99e5361cdf
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/searchPattern.ts
@@ -0,0 +1,69 @@
+/**
+ * How a search command reads its pattern. `basic` is POSIX grep's default,
+ * where `\|` and `\(` are operators and a bare `|` is a literal; `extended` is
+ * `grep -E`, `rg`, `ag`, and `ack`, where `|` and `(` are operators; `fixed` is
+ * a literal string (`grep -F`, `rg -F`).
+ */
+export type SearchPatternDialect = 'basic' | 'extended' | 'fixed';
+
+/**
+ * Backslash escapes that only make punctuation literal (`\.`, `\$`, `\-`).
+ * Letter escapes such as `\b` or `\d` mean something, so they stay as written.
+ */
+const LITERAL_ESCAPE = /^[^\dA-Z]$/iu;
+
+/**
+ * The terms a search pattern looks for, as a person reads them:
+ * `grep "foo\|bar\.ts"` searches `foo` and `bar.ts`. Top-level alternation
+ * splits into terms; alternation inside a group or a bracket expression stays
+ * in its term. A pattern that yields no term reads as written.
+ *
+ * Ported from Caxri (`packages/protocol/src/agent/tool-rows/shell/agent-shell-search-pattern.ts`).
+ */
+export const searchPatternTerms = (pattern: string, dialect: SearchPatternDialect): string[] => {
+ if (dialect === 'fixed') return [pattern];
+ const terms: string[] = [];
+ let current = '';
+ let depth = 0;
+ let isInBracket = false;
+ for (let index = 0; index < pattern.length; index += 1) {
+ const char = pattern.charAt(index);
+ if (isInBracket) {
+ current += char;
+ if (char === ']') isInBracket = false;
+ continue;
+ }
+ if (char === '[') {
+ isInBracket = true;
+ current += char;
+ continue;
+ }
+ if (char === '\\') {
+ const next = pattern.at(index + 1);
+ index += 1;
+ if (next === undefined) {
+ current += char;
+ } else if (dialect === 'basic' && next === '|' && depth === 0) {
+ terms.push(current);
+ current = '';
+ } else if (dialect === 'basic' && (next === '(' || next === ')')) {
+ depth = Math.max(0, depth + (next === '(' ? 1 : -1));
+ current += next;
+ } else {
+ current += LITERAL_ESCAPE.test(next) ? next : `${char}${next}`;
+ }
+ continue;
+ }
+ if (dialect === 'extended' && char === '|' && depth === 0) {
+ terms.push(current);
+ current = '';
+ continue;
+ }
+ if (dialect === 'extended' && (char === '(' || char === ')'))
+ depth = Math.max(0, depth + (char === '(' ? 1 : -1));
+ current += char;
+ }
+ terms.push(current);
+ const readable = terms.map((term) => term.trim()).filter(Boolean);
+ return readable.length > 0 ? [...new Set(readable)] : [pattern];
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/types.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/types.ts
new file mode 100644
index 00000000000..5359e6bc086
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/shellCommand/types.ts
@@ -0,0 +1,78 @@
+/**
+ * What an undescribed shell command does, as the action half of its collapsed
+ * title. Each value is the suffix of a `builtins.shellCommand.<action>` key in
+ * the `plugin` namespace.
+ */
+export type ShellCommandAction =
+ // Exploration
+ | 'read'
+ | 'search'
+ | 'findFiles'
+ | 'list'
+ | 'listFiles'
+ | 'useSkill'
+ // Tests, Git and inline scripts
+ | 'runTests'
+ | 'commit'
+ | 'commitAndPush'
+ | 'push'
+ | 'write'
+ | 'runScript.bun'
+ | 'runScript.node'
+ | 'runScript.perl'
+ | 'runScript.python'
+ | 'runScript.ruby'
+ | 'runScript.shell'
+ // GitHub CLI
+ | 'pr.check'
+ | 'pr.close'
+ | 'pr.comment'
+ | 'pr.create'
+ | 'pr.edit'
+ | 'pr.list'
+ | 'pr.merge'
+ | 'issue.close'
+ | 'issue.comment'
+ | 'issue.create'
+ | 'issue.edit'
+ | 'issue.list'
+ | 'issue.reopen'
+ | 'issue.view'
+ | 'ci.cancel'
+ | 'ci.list'
+ | 'ci.logs'
+ | 'ci.rerun'
+ | 'ci.view'
+ | 'ci.workflowRun'
+ | 'githubApi'
+ // Vercel CLI
+ | 'vercel.deploy'
+ | 'vercel.envList'
+ | 'vercel.envPull'
+ | 'vercel.inspect'
+ | 'vercel.list'
+ | 'vercel.logs'
+ | 'vercel.promote'
+ | 'vercel.redeploy'
+ // LobeHub CLI
+ | 'acceptance.feedback'
+ | 'acceptance.ingest'
+ | 'acceptance.linkPr'
+ | 'acceptance.list'
+ | 'acceptance.preflight'
+ | 'acceptance.publish'
+ | 'acceptance.view';
+
+/**
+ * The collapsed title of a shell command no description explains:
+ * "读取 app.ts", "搜索 TODO in src", "运行测试 a.test.ts".
+ */
+export interface ShellCommandTitle {
+ action: ShellCommandAction;
+ /**
+ * Prose (a commit message, an issue title) rather than a path, command or
+ * identifier, so it renders in the body font instead of the code font.
+ */
+ isProse?: boolean;
+ subject?: string;
+}
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
index 9b72fae0512..4c861435d81 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
@@ -227,6 +227,28 @@ describe('reasoning headline extraction', () => {
expect((state as any).fallbackTool).not.toContain('set -a');
});
+ it('renders a running undescribed shell command as what it does', () => {
+ const state = getWorkflowStreamingHeadlineState([
+ blk({
+ id: '0',
+ tools: [
+ {
+ apiName: 'Bash',
+ arguments: JSON.stringify({ command: 'cd /repo && rg -n "TODO" src' }),
+ id: 't1',
+ identifier: 'claude-code',
+ } as any,
+ ],
+ }),
+ ]);
+
+ // The plugin namespace is not loaded here, so the label resolves to its key.
+ expect(state).toMatchObject({
+ fallbackTool: 'builtins.shellCommand.search TODO in src',
+ kind: 'tool',
+ });
+ });
+
it('uses prose state when the trailing block is prose', () => {
const state = getWorkflowStreamingHeadlineState([
blk({
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
index 0ad347c35fd..923717db21f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
@@ -23,7 +23,7 @@ import {
WORKFLOW_PROSE_SOURCE_MIN_CHARS,
WORKFLOW_TRUNCATE_WORD_BOUNDARY_MIN_RATIO,
} from './constants';
-import { extractToolKeyword } from './Tool/Inspector/extractToolKeyword';
+import { extractToolKeyword, getShellCommandTitle } from './Tool/Inspector/extractToolKeyword';
export const areWorkflowToolsComplete = (tools: ChatToolPayloadWithResult[]): boolean => {
const collapsible = tools.filter((t) => t.intervention?.status !== 'pending');
@@ -108,16 +108,27 @@ const getToolActionLabel = (tool: ChatToolPayloadWithResult): string => {
return builtinLabel || getToolDisplayName(tool.apiName);
};
-/** The most informative text from the args (a readable command line, query, path…) — never the raw args dump. */
-const getToolKeywordDetail = (tool: ChatToolPayloadWithResult): string => {
+const parseToolArgs = (tool: ChatToolPayloadWithResult): Record<string, unknown> | undefined => {
try {
- return extractToolKeyword(JSON.parse(tool.arguments || '{}')) ?? '';
+ return JSON.parse(tool.arguments || '{}');
} catch {
// arguments still streaming or invalid
- return '';
+ return undefined;
}
};
+/** The most informative text from the args (a readable command line, query, path…) — never the raw args dump. */
+const getToolKeywordDetail = (tool: ChatToolPayloadWithResult): string =>
+ extractToolKeyword(parseToolArgs(tool)) ?? '';
+
+/** An undescribed shell command as what it does ("读取 app.ts"), same as the collapsed inspector row. */
+const getShellCommandHeadlineLine = (tool: ChatToolPayloadWithResult): string => {
+ const title = getShellCommandTitle(parseToolArgs(tool));
+ if (!title) return '';
+ const label = t(`builtins.shellCommand.${title.action}`, { ns: 'plugin' });
+ return title.subject ? `${label} ${title.subject}` : label;
+};
+
/** Optional progress line from tool-runtime state (pluginState → result.state) or metadata */
interface WorkflowHeadlinePayload {
metadata?: { workflow?: { stepMessage?: string } };
@@ -183,6 +194,9 @@ export const getToolFallbackHeadlineLine = (tool: ChatToolPayloadWithResult): st
const goalHeadline = getGoalCommandHeadlineLine(tool);
if (goalHeadline) return goalHeadline;
+ const commandHeadline = getShellCommandHeadlineLine(tool);
+ if (commandHeadline) return commandHeadline;
+
const label = getToolActionLabel(tool);
const keyword = getToolKeywordDetail(tool);
return keyword ? `${label} ${keyword}` : label;