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.

πŸ› fix(conversation): readable titles for undescribed shell commands (#23070)

YuTengjing78f1a05ed969
diff --git a/packages/shared-tool-ui/package.json b/packages/shared-tool-ui/package.json
index 205f6c6ead8..f5a8e36be7f 100644
--- a/packages/shared-tool-ui/package.json
+++ b/packages/shared-tool-ui/package.json
@@ -12,6 +12,7 @@
"./inspectors/linear-labels": "./src/Inspector/Linear/labels.ts",
"./pending-hotkeys": "./src/pendingHotkeys.ts",
"./renders": "./src/Render/index.ts",
+ "./run-command": "./src/utils/runCommand.ts",
"./secret-input": "./src/SecretInput/index.ts",
"./styles": "./src/styles.ts"
},
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 da06876c629..567d9c4e3bb 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ToolTitle.test.tsx
@@ -115,7 +115,7 @@ describe('ToolTitle', () => {
);
expect(screen.getByText('runCommand')).toBeInTheDocument();
- expect(screen.getByText('docker')).toBeInTheDocument();
+ expect(screen.getByText('docker ps')).toBeInTheDocument();
});
it('keeps the label for a latin model description (reads as a spec, not a step)', () => {
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.ts
index 7ea9a606251..50eb7b6eb95 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.test.ts
@@ -9,22 +9,30 @@ describe('extractToolKeyword', () => {
});
describe('command args', () => {
- it('skips env setup and runners to find the script being run', () => {
+ it('drops setup statements and output plumbing from the command line', () => {
expect(
extractToolKeyword({
command:
'set -a && source .env && set +a && npx tsx scripts/gross-margin/monthly.ts 2>/dev/null',
}),
- ).toBe('monthly.ts');
+ ).toBe('npx tsx scripts/gross-margin/monthly.ts');
});
- it('returns the program for a plain command', () => {
- expect(extractToolKeyword({ command: 'git status' })).toBe('git');
+ it('returns the whole command for a plain command', () => {
+ expect(extractToolKeyword({ command: 'git status' })).toBe('git status');
});
- it('skips env assignments and sudo', () => {
+ it('names a heredoc by its opener line instead of a single token', () => {
+ expect(
+ extractToolKeyword({
+ command: "cd /repo && python3 - <<'EOF'\nprint('hi')\nEOF",
+ }),
+ ).toBe("python3 - <<'EOF'");
+ });
+
+ it('keeps an inline environment prefix', () => {
expect(extractToolKeyword({ command: 'FOO=1 sudo systemctl restart nginx' })).toBe(
- 'systemctl',
+ 'FOO=1 sudo systemctl restart nginx',
);
});
@@ -34,8 +42,8 @@ describe('extractToolKeyword', () => {
).toBe('List files in current directory');
});
- it('falls back to the command program when no description exists', () => {
- expect(extractToolKeyword({ command: 'ls -la' })).toBe('ls');
+ it('falls back to the command line when no description exists', () => {
+ expect(extractToolKeyword({ command: 'ls -la' })).toBe('ls -la');
});
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts
index 3904ae218a3..cab23f812e0 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/extractToolKeyword.ts
@@ -1,3 +1,5 @@
+import { readableShellCommand } from './readableShellCommand';
+
// Arg keys checked in priority order. NAME_KEYS (model-written description /
// title) lead because they state what the step does; then query/pattern
// outranks path (Grep/Glob-style calls carry both, and the pattern is the
@@ -8,32 +10,6 @@ const QUERY_KEYS = ['query', 'q', 'pattern', 'keywords'];
const PATH_KEYS = ['file_path', 'filePath', 'path', 'filename', 'file'];
const URL_KEYS = ['url', 'urls'];
-// Shell tokens that never identify the program being run. The ones that take
-// an argument (`source .env`, `cd dir`) consume the following token too.
-const SHELL_NOISE = new Set(['env', 'exec', 'nice', 'nohup', 'set', 'sudo', 'time']);
-const SHELL_NOISE_WITH_ARG = new Set(['.', 'cd', 'source']);
-// Launchers whose next token (or a later path) is the real subject.
-const SHELL_RUNNERS = new Set([
- 'bash',
- 'bun',
- 'bunx',
- 'deno',
- 'node',
- 'npm',
- 'npx',
- 'pnpm',
- 'python',
- 'python3',
- 'run',
- 'sh',
- 'ts-node',
- 'tsx',
- 'uv',
- 'uvx',
- 'yarn',
- 'zsh',
-]);
-
const basename = (path: string): string => {
const trimmed = path.replace(/[/\\]+$/, '');
return trimmed.split(/[/\\]/).pop() || trimmed;
@@ -50,35 +26,6 @@ const pickString = (args: Record<string, unknown>, keys: string[]): string | und
return undefined;
};
-/**
- * Pull the program (or script file) actually being run out of a shell command,
- * skipping env assignments, flags, and wrapper launchers:
- * `set -a && source .env && npx tsx scripts/report/monthly.ts` β†’ `monthly.ts`.
- */
-const extractCommandKeyword = (command: string): string | undefined => {
- const tokens = command.split(/[\s;&|()]+/).filter(Boolean);
-
- let skipNext = false;
- for (const token of tokens) {
- if (skipNext) {
- skipNext = false;
- continue;
- }
- if (/^[A-Z_]\w*=/i.test(token)) continue; // env assignment
- if (/^[+-]/.test(token)) continue; // flag
- if (SHELL_NOISE_WITH_ARG.has(token)) {
- skipNext = true;
- continue;
- }
- if (SHELL_NOISE.has(token)) continue;
- if (SHELL_RUNNERS.has(token)) continue;
-
- return token.includes('/') ? basename(token) : token;
- }
-
- return tokens[0];
-};
-
const extractUrlKeyword = (url: string): string => {
try {
return new URL(url).hostname;
@@ -88,25 +35,25 @@ const extractUrlKeyword = (url: string): string => {
};
/**
- * Distill tool-call args down to the single most informative token so the
- * collapsed inspector row can read as "<action> <keyword>" instead of dumping
- * raw arguments. Returns undefined when nothing identifiable is present.
+ * Distill tool-call args down to the most informative text so the collapsed
+ * inspector row can read as "<action> <keyword>" instead of dumping raw
+ * arguments. Returns undefined when nothing identifiable is present. Long
+ * results are truncated by CSS ellipsis at the render site.
*/
export const extractToolKeyword = (args?: Record<string, unknown>): string | undefined => {
if (!args) return undefined;
// The model-written description ("恒倍登录态", "List files in current
// directory") is the clearest statement of what this step does β€” every
- // command-running tool schema asks for one, so prefer it over distilling
- // fragments (flags, session names) out of the raw command.
+ // command-running tool schema asks for one, so prefer it over the raw command.
const description = pickString(args, NAME_KEYS);
if (description) return description;
+ // Without a description, show the command itself as one readable line
+ // (setup, heredoc bodies and output plumbing dropped). Picking a single
+ // token produced titles like `<<'EOF'`, `cat` or `for` that named nothing.
const command = pickString(args, COMMAND_KEYS);
- if (command) {
- const keyword = extractCommandKeyword(command);
- if (keyword) return keyword;
- }
+ if (command) return readableShellCommand(command);
const query = pickString(args, QUERY_KEYS);
if (query) return query;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.test.ts
new file mode 100644
index 00000000000..c2d9f1710f1
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from 'vitest';
+
+import { readableShellCommand } from './readableShellCommand';
+
+describe('readableShellCommand', () => {
+ it('keeps a plain command as is', () => {
+ expect(readableShellCommand('git status')).toBe('git status');
+ });
+
+ it('drops output plumbing from every command in a chain', () => {
+ expect(
+ readableShellCommand(
+ 'npm view @scope/cli version 2>&1 | tail -1; tool --help 2>&1 | head -30; which tool 2>/dev/null',
+ ),
+ ).toBe('npm view @scope/cli version; tool --help; which tool');
+ expect(readableShellCommand('sed -n 1,80p src/a.ts 2>&1 | head -40')).toBe(
+ 'sed -n 1,80p src/a.ts',
+ );
+ });
+
+ it('keeps a filter that changes what the command shows', () => {
+ expect(readableShellCommand("gh api repos/a/b | sed -n '/^## Install/,$p'")).toBe(
+ "gh api repos/a/b | sed -n '/^## Install/,$p'",
+ );
+ expect(readableShellCommand('git log | head -n 5 | wc -l')).toBe('git log | head -n 5 | wc -l');
+ });
+
+ it('drops setup statements that only prepare the command after them', () => {
+ expect(
+ readableShellCommand(
+ 'cd /work/repo-worktrees/shared && git commit -q -a --fixup=abc1234 && git push',
+ ),
+ ).toBe('git commit -q -a --fixup=abc1234 && git push');
+ expect(
+ readableShellCommand(
+ `cd /tmp/acc; S=acc1; A="agent-browser --session $S"; $A click @e25; sleep 2; $A snapshot`,
+ ),
+ ).toBe('agent-browser --session $S click @e25; sleep 2; agent-browser --session $S snapshot');
+ expect(
+ readableShellCommand(
+ String.raw`cd ~/Library/Application\ Support/App; sqlite3 -readonly app.db ".tables"`,
+ ),
+ ).toBe('sqlite3 -readonly app.db ".tables"');
+ expect(
+ readableShellCommand('export CI=1 FORCE=1 && sleep 20; . /tmp/lib.sh; gh pr checks 14'),
+ ).toBe('gh pr checks 14');
+ expect(
+ readableShellCommand(
+ 'set -a && source .env && set +a && npx tsx scripts/gross-margin/monthly.ts 2>/dev/null',
+ ),
+ ).toBe('npx tsx scripts/gross-margin/monthly.ts');
+ expect(readableShellCommand("cd 'dir with space'\nbun run check")).toBe('bun run check');
+ });
+
+ it('keeps a setup statement that is the whole command or only an environment prefix', () => {
+ expect(readableShellCommand('cd src')).toBe('cd src');
+ expect(readableShellCommand('CI=1 bun run test')).toBe('CI=1 bun run test');
+ });
+
+ it('names a heredoc by the line that opens it, not its body', () => {
+ expect(
+ readableShellCommand(
+ "cd /work/repo && python3 - <<'EOF'\np='packages/a.ts'\ns=open(p).read()\nEOF",
+ ),
+ ).toBe("python3 - <<'EOF'");
+ expect(
+ readableShellCommand(
+ "cd /repo && mkdir -p src && cat > src/LimitReachedIcon.tsx <<'EOF'\nexport const A = 1;\nEOF",
+ ),
+ ).toBe("cat > src/LimitReachedIcon.tsx <<'EOF'");
+ expect(readableShellCommand('cat > notes.md <<-MD\n# Notes\n\tMD')).toBe(
+ 'cat > notes.md <<-MD',
+ );
+ expect(
+ readableShellCommand("python3 - <<'EOF'\nprint(1)\nEOF\nbun run check 2>&1 | tail -5"),
+ ).toBe("python3 - <<'EOF'; bun run check");
+ });
+
+ it('recognizes a heredoc delimiter that is not a plain word', () => {
+ expect(readableShellCommand('cat <<\'END-JSON\'\n{"value": 1}\nEND-JSON\ngit status')).toBe(
+ "cat <<'END-JSON'; git status",
+ );
+ expect(readableShellCommand('cat <<\'END-JSON\'\n{"value":')).toBe("cat <<'END-JSON'");
+ expect(readableShellCommand('grep -c x <<< "a b"')).toBe('grep -c x <<< "a b"');
+ expect(readableShellCommand('cat <<\\EOF\nhello\nEOF\ngit status')).toBe(
+ 'cat <<\\EOF; git status',
+ );
+ });
+
+ it('treats shell syntax inside quotes as an argument', () => {
+ expect(readableShellCommand("rg '<<EOF' src\ngit status")).toBe("rg '<<EOF' src; git status");
+ expect(readableShellCommand("printf '%s' 'hello | head -5; goodbye'")).toBe(
+ "printf '%s' 'hello | head -5; goodbye'",
+ );
+ expect(readableShellCommand('echo "a 2>&1" 2>&1')).toBe('echo "a 2>&1"');
+ expect(readableShellCommand("python3 -c '\nprint(1 << 2)\n'\ngit status")).toBe(
+ "python3 -c ' print(1 << 2) '; git status",
+ );
+ });
+
+ it('keeps the opener line while the heredoc body is still streaming', () => {
+ expect(readableShellCommand("cd /repo && python3 - <<'EOF'\nimport json\nprint(")).toBe(
+ "python3 - <<'EOF'",
+ );
+ });
+
+ it('reads a heredoc commit message by its first line', () => {
+ expect(
+ readableShellCommand(
+ `git commit -m "$(cat <<'EOF'\nfix: keep titles short\n\nBody\nEOF\n)" && git push`,
+ ),
+ ).toBe(`git commit -m 'fix: keep titles short' && git push`);
+ });
+
+ it('joins a multi-line command into one line', () => {
+ expect(readableShellCommand('for f in a.ts b.ts; do\n wc -l "$f"\ndone')).toBe(
+ 'for f in a.ts b.ts; do wc -l "$f"; done',
+ );
+ expect(readableShellCommand('bunx vitest run \\\n --silent src/a.test.ts')).toBe(
+ 'bunx vitest run --silent src/a.test.ts',
+ );
+ expect(readableShellCommand('git status\ngit diff --stat 2>&1')).toBe(
+ 'git status; git diff --stat',
+ );
+ });
+
+ it('unwraps the login-shell wrapper Codex reports', () => {
+ expect(readableShellCommand(`/bin/zsh -lc "cd /repo && rg -n \\"a|b\\" src"`)).toBe(
+ 'rg -n "a|b" src',
+ );
+ expect(readableShellCommand("bash -lc 'git diff --stat'")).toBe('git diff --stat');
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.ts
new file mode 100644
index 00000000000..c903806a98e
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/readableShellCommand.ts
@@ -0,0 +1,228 @@
+import { getRunCommandDisplayCommand } from '@lobechat/shared-tool-ui/run-command';
+
+/**
+ * Turns a raw shell command into the one-line title of a tool row that has no
+ * model-written description. The expanded row still shows the exact command.
+ *
+ * Ported from Caxri's `readableShellCommand`
+ * (`packages/protocol/src/agent/tool-rows/shell/agent-shell-title.ts`), with
+ * three additions: `set -a` / `set +a` count as setup, multi-line commands are
+ * joined into one line, and a heredoc whose body is still streaming is cut at
+ * its opener line instead of leaking the partial script into the title.
+ */
+
+/**
+ * Plumbing an agent appends only to keep its own output short (`2>&1`,
+ * `2>/dev/null`, a trailing `| head -30`) says nothing about what the command
+ * does, yet fills a one-line title. Dropped at each command boundary.
+ */
+const SHELL_TITLE_NOISE =
+ /\s*(?:\d?>&\d|&?\d?>\s*\/dev\/null|\|\s*(?:head|tail)(?:\s+-n)?(?:\s+-?\d+)?)(?=[ \t]*(?:;|&&|\|\||\n|$))/gu;
+
+/**
+ * One shell word, quotes and escapes included (`"agent-browser --session $S"`,
+ * `Application\ Support`), never crossing an unquoted `;`, `&`, or `|`.
+ */
+const SHELL_WORD = String.raw`(?:'[^']*'|"(?:[^"\\]|\\.)*"|\\.|[^\s;&|'"\\])+`;
+const SHELL_VALUE = SHELL_WORD.replace(/\+$/u, '*');
+const SHELL_ASSIGNMENTS = String.raw`[A-Za-z_]\w*=${SHELL_VALUE}(?:\s+[A-Za-z_]\w*=${SHELL_VALUE})*`;
+
+/**
+ * A statement that only prepares the command after it, ending in `&&`, `;`, or
+ * a newline: `cd <dir>`, variable assignments, `export`, `set -a`, a fixed
+ * `sleep`, `mkdir -p`, or sourcing a file (`. lib.sh`, `source .env`). A leading
+ * `cd` alone opens most undescribed agent commands, so without this every title
+ * reads as the same worktree path.
+ */
+const SHELL_TITLE_SETUP = new RegExp(
+ String.raw`^\s*(?:cd\s+${SHELL_WORD}|(?:export\s+)?${SHELL_ASSIGNMENTS}|set\s+[+-]a|sleep\s+\d+(?:\.\d+)?|mkdir\s+-p(?:\s+${SHELL_WORD})+|(?:\.|source)\s+${SHELL_WORD})[ \t]*(?:&&|;|\n)\s*`,
+ 'u',
+);
+
+const SHELL_ASSIGNMENT = new RegExp(String.raw`([A-Za-z_]\w*)=(${SHELL_WORD})?`, 'gu');
+
+/**
+ * A heredoc delimiter: any shell word, so `END-JSON` and `PY.END` count as
+ * well as `EOF`, quoted (`'EOF'`) or escaped (`\EOF`). Named groups keep it embeddable in larger patterns.
+ */
+const HEREDOC_TAG = String.raw`(?<quote>['"]?)\\?([^\s'"<>;&|()\\]+)\k<quote>`;
+
+/** A heredoc opener (`<<'EOF'`, `<<-PY`); its body is input, not the command. */
+const HEREDOC_OPENER = new RegExp(String.raw`(?<!<)<<(?!<)-?\s*${HEREDOC_TAG}`, 'u');
+
+/** A heredoc inside a command substitution: `"$(cat <<'EOF'`. */
+const HEREDOC_SUBSTITUTION = new RegExp(
+ String.raw`"?\$\(\s*cat\s+<<(?!<)-?\s*${HEREDOC_TAG}[ \t]*\n`,
+ 'u',
+);
+
+/**
+ * Quoted text on its own (`'<<EOF'`, `'a | head -5; b'`), skipping a quoted
+ * heredoc delimiter (`<<'EOF'`) so the opener still reads as one.
+ */
+const QUOTED_TEXT = new RegExp(
+ String.raw`((?<!<)<<(?!<)-?\s*${HEREDOC_TAG})|'[^']*'|"(?:[^"\\]|\\.)*"`,
+ 'gu',
+);
+
+/**
+ * Hides quoted text behind private-use placeholders, so the rules below only
+ * read real shell syntax: a `|`, `;`, or `<<` inside quotes is an argument.
+ * `restore` puts the original text back.
+ */
+const maskQuotedText = (text: string): { masked: string; restore: (value: string) => string } => {
+ const quoted: string[] = [];
+ const masked = text.replaceAll(QUOTED_TEXT, (whole, opener?: string) => {
+ if (opener) return whole;
+ quoted.push(whole);
+ return `\uE000${quoted.length - 1}\uE001`;
+ });
+ const restore = (value: string) =>
+ value.replaceAll(/\uE000(\d+)\uE001/gu, (_, index: string) => quoted[Number(index)] ?? '');
+ return { masked, restore };
+};
+
+const unquoteShellWord = (word: string): string =>
+ /^(["'])[\s\S]*\1$/u.test(word) ? word.slice(1, -1) : word;
+
+/**
+ * Replaces `"$(cat <<'EOF' … EOF\n)"` with the quoted first body line, so a
+ * commit message reads as `git commit -m 'fix: …'`. An unterminated one is left
+ * for {@link withoutHeredocBodies} to cut.
+ */
+const inlineHeredocSubstitutions = (command: string): string => {
+ let rest = command;
+ let result = '';
+ for (
+ let start = HEREDOC_SUBSTITUTION.exec(rest);
+ start;
+ start = HEREDOC_SUBSTITUTION.exec(rest)
+ ) {
+ const tag = start[2];
+ const bodyStart = start.index + start[0].length;
+ const lines = rest.slice(bodyStart).split('\n');
+ const endLine = lines.findIndex((line) => line.trim() === tag);
+ if (endLine === -1) return command;
+ const close = /^\s*\)"?/u.exec(lines.slice(endLine + 1).join('\n'));
+ if (!close) return command;
+ const firstLine = lines.slice(0, endLine).find((line) => line.trim() !== '') ?? '';
+ const consumed = lines.slice(0, endLine + 1).join('\n').length + 1 + close[0].length;
+ result += `${rest.slice(0, start.index)}'${firstLine.trim().replaceAll("'", '')}'`;
+ rest = rest.slice(bodyStart + consumed);
+ }
+ return result + rest;
+};
+
+/**
+ * Drops every heredoc body, keeping the line that opens it
+ * (`python3 - <<'EOF'`, `cat > notes.md <<'EOF'`). A heredoc whose terminator
+ * has not arrived yet (still streaming) ends the command at its opener line.
+ */
+const withoutHeredocBodies = (command: string): string => {
+ const lines = command.split('\n');
+ const kept: string[] = [];
+ // The quote a previous line left open (`python3 -c '` …), so a `<<` inside a
+ // multi-line quoted argument is not read as a heredoc.
+ let openQuote: string | undefined;
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index] ?? '';
+ kept.push(line);
+ let code = line;
+ if (openQuote) {
+ const close = line.indexOf(openQuote);
+ if (close === -1) continue;
+ code = line.slice(close + 1);
+ openQuote = undefined;
+ }
+ const masked = maskQuotedText(code).masked;
+ const stray = /['"]/u.exec(masked.replaceAll(new RegExp(HEREDOC_OPENER, 'gu'), ''));
+ if (stray) {
+ openQuote = stray[0];
+ continue;
+ }
+ const tag = HEREDOC_OPENER.exec(masked)?.[2];
+ if (!tag) continue;
+ const end = lines.findIndex((candidate, at) => at > index && candidate.trim() === tag);
+ if (end === -1) break;
+ index = end;
+ }
+ return kept.join('\n');
+};
+
+/**
+ * Strips the setup statements that open a command while a command still
+ * follows them (so `cd src` alone keeps its title), collecting the variables
+ * they assign.
+ */
+const stripShellSetup = (
+ command: string,
+ restore: (value: string) => string,
+): { rest: string; variables: Map<string, string> } => {
+ let rest = command;
+ const variables = new Map<string, string>();
+ for (let match = SHELL_TITLE_SETUP.exec(rest); match; match = SHELL_TITLE_SETUP.exec(rest)) {
+ const remaining = rest.slice(match[0].length);
+ if (remaining.trim() === '') break;
+ const statement = match[0];
+ if (!/^\s*(?:cd|set|sleep|mkdir|\.|source)\s/u.test(statement)) {
+ for (const [, name = '', value = ''] of statement.matchAll(SHELL_ASSIGNMENT))
+ variables.set(name, unquoteShellWord(restore(value)));
+ }
+ rest = remaining;
+ }
+ return { rest, variables };
+};
+
+/**
+ * An agent driving a CLI repeatedly names it once
+ * (`A="agent-browser --session $S"; $A click @e25`). With the assignment
+ * dropped, a command that starts with that variable reads as its value again;
+ * a variable used as an argument stays as written.
+ */
+const expandCommandVariables = (command: string, variables: ReadonlyMap<string, string>) => {
+ if (variables.size === 0) return command;
+ return command.replaceAll(
+ /(^|&&|[;\n|])(\s*)\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))(?![\w{])/gu,
+ (whole, separator: string, space: string, braced?: string, bare?: string) => {
+ const value = variables.get(braced ?? bare ?? '');
+ return value ? `${separator}${space}${value}` : whole;
+ },
+ );
+};
+
+/**
+ * Joins a multi-line command into one line: a line ending in an operator or a
+ * block opener (`do`, `then`, `{`, `|`, `&&`) continues on the next one,
+ * otherwise the lines are separate statements joined with `; `.
+ */
+const joinLines = (command: string): string => {
+ const lines = command
+ .replaceAll(/[ \t]*\\\n\s*/gu, ' ')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean);
+ let joined = '';
+ for (const line of lines) {
+ if (!joined) joined = line;
+ else if (/(?:[;&|{(]|\b(?:do|then|else|in))$/u.test(joined)) joined += ` ${line}`;
+ else joined += `; ${line}`;
+ }
+ return joined;
+};
+
+export const readableShellCommand = (rawCommand: string): string => {
+ const command = getRunCommandDisplayCommand(rawCommand);
+ const bodiless = withoutHeredocBodies(inlineHeredocSubstitutions(command));
+ // Every rule below reads shell syntax, so quoted arguments stay out of reach.
+ const { masked, restore } = maskQuotedText(bodiless);
+ const { rest, variables } = stripShellSetup(masked, restore);
+ let readable = expandCommandVariables(rest, variables);
+ // Stripping `| tail -1` leaves the `2>&1` before it at the end of its
+ // command, so repeat until nothing changes.
+ for (let previous = ''; previous !== readable;) {
+ previous = readable;
+ readable = readable.replaceAll(SHELL_TITLE_NOISE, '');
+ }
+ // A multi-line quoted argument still reads as one line.
+ return restore(joinLines(readable)).replaceAll(/\s*\n\s*/gu, ' ') || command.trim();
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
index a46829ac8d1..9b72fae0512 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.test.ts
@@ -223,7 +223,7 @@ describe('reasoning headline extraction', () => {
// the plugin i18n namespace is not registered in the test harness, so the
// label falls back to the apiName; the shape under test is label + keyword.
expect(state.kind).toBe('tool');
- expect((state as any).fallbackTool).toMatch(/ monthly\.ts$/);
+ expect((state as any).fallbackTool).toMatch(/ npx tsx scripts\/gross-margin\/monthly\.ts$/);
expect((state as any).fallbackTool).not.toContain('set -a');
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
index 14acae3a586..0ad347c35fd 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolDisplayNames.ts
@@ -108,7 +108,7 @@ const getToolActionLabel = (tool: ChatToolPayloadWithResult): string => {
return builtinLabel || getToolDisplayName(tool.apiName);
};
-/** The single most informative token from the args β€” never the raw args dump. */
+/** The most informative text from the args (a readable command line, query, path…) β€” never the raw args dump. */
const getToolKeywordDetail = (tool: ChatToolPayloadWithResult): string => {
try {
return extractToolKeyword(JSON.parse(tool.arguments || '{}')) ?? '';