Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 8be6ffa755 feat(agents): fold shell commands that only read or search into exploration runs
Agents such as Claude Code and Codex read and search through shell commands (grep, sed -n, git diff…), so with only read/search/fetch tool calls folding, almost nothing in their conversations folded. A command whose every segment only reads or searches now joins the run with reasoning and counts in its summary as a read or a search; commands that may change something (builds, tests, writes, redirects, command substitution, unknown programs) still show on their own row. The leading cd parsing moves to the same module.
2026-11-25 20:28:03 +08:00
6 змінених файлів з 272 додано та 16 видалено

No files matched your search

+25 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { AgentEntry } from "@/bindings";
import { foldedTurns } from "../timeline";
import { foldedTurns, summarizeWork } from "../timeline";
import { conversationRows, foldTurnRows, rowEntries, sameRow } from "./conversationRows";
const user = (text: string): AgentEntry => ({
@@ -47,6 +47,30 @@ describe("conversationRows", () => {
expect(rows[4]!.kind === "process" ? rows[4]!.entries.length : 0).toBe(2);
});
it("groups shell commands that only read or search, and keeps the others separate", () => {
const run = (id: string, title: string): AgentEntry => ({
...(tool(id, "execute") as Extract<AgentEntry, { type: "tool" }>),
title,
});
const entries: AgentEntry[] = [
user("a"),
{ type: "thought", text: "look around" },
run("c1", "cd /repo && git grep -n foo -- src"),
run("c2", "sed -n 1,40p src/a.ts"),
{ type: "thought", text: "now test" },
run("c3", "pnpm test"),
run("c4", "git diff --stat"),
run("c5", "cat a.ts | head"),
agent("done"),
];
const rows = conversationRows(entries, 0);
expect(rows.map((row) => row.kind)).toEqual(["entry", "process", "entry", "process", "entry"]);
expect(rows[1]!.kind === "process" ? rows[1]!.entries.map((e) => e.index) : []).toEqual([1, 2, 3, 4]);
expect(rows[3]!.kind === "process" ? rows[3]!.entries.map((e) => e.index) : []).toEqual([6, 7]);
const work = summarizeWork(rowEntries(rows[1]!));
expect([work.search, work.read, work.run]).toEqual([1, 1, 0]);
});
it("flattens grouped runs inside a folded turn to avoid nested folds", () => {
const entries: AgentEntry[] = [
user("a"),
+9 -5
Переглянути файл
@@ -1,5 +1,5 @@
import type { AgentEntry } from "@/bindings";
import { type FoldedTurn } from "../timeline";
import { exploringCommand, type FoldedTurn } from "../timeline";
export type ToolEntryData = Extract<AgentEntry, { type: "tool" }>;
@@ -23,12 +23,16 @@ export const liveTool = (entry: AgentEntry) =>
const EXPLORATION_KINDS = new Set(["read", "search", "fetch", "think"]);
/**
* Reasoning and read-only exploration tool calls fold together, running ones included: the run
* keeps its place while a call finishes, and its summary line says what is running. Edits,
* commands and other side-effecting calls stay visible as their own rows.
* Reasoning and read-only exploration fold together, running calls included: the run keeps its
* place while a call finishes, and its summary line says what is running. Exploration is a
* read, search or fetch, or a shell command that only reads or searches (`grep`, `sed -n`,
* `git diff`); edits and other commands stay visible as their own rows.
*/
export const isProcessEntry = (entry: AgentEntry) =>
entry.type === "thought" || (entry.type === "tool" && EXPLORATION_KINDS.has(entry.kind) && entry.diffs.length === 0);
entry.type === "thought" ||
(entry.type === "tool" &&
entry.diffs.length === 0 &&
(EXPLORATION_KINDS.has(entry.kind) || exploringCommand(entry) !== null));
/**
* The conversation's rows from `from`: a run of reasoning and finished tool calls becomes
+3 -8
Переглянути файл
@@ -1,5 +1,6 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import { useEffect, useState } from "react";
import { splitLeadingCd } from "../shellCommand";
import { useAgents } from "../store";
export function providerName(id: string) {
@@ -21,19 +22,13 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Agent-written titles with the task's own folder dropped from paths. */
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
/** A leading `cd <dir> &&` (or `;`), with the directory quoted or bare. */
const LEADING_CD = /^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)\s*/;
/**
* A command's title without the `cd <dir> &&` agents put before every call, and the folder it
* moved to when that is not the task's own: the command is what tells calls apart.
*/
export function commandTitle(task: AgentTask, title: string): { title: string; dir: string | null } {
const match = LEADING_CD.exec(title);
if (!match || match[0].length === title.length) return { title: shortTitle(task, title), dir: null };
const dir = match[1]!.replace(/^(["'])(.*)\1$/, "$2").replace(/\/+$/, "");
const rest = shortTitle(task, title.slice(match[0].length));
return { title: rest, dir: dir === task.cwd || dir === "." ? null : dir };
const { command, dir } = splitLeadingCd(title);
return { title: shortTitle(task, command), dir: dir === task.cwd || dir === "." ? null : dir };
}
/**
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { readOnlyCommand, splitLeadingCd } from "./shellCommand";
describe("splitLeadingCd", () => {
it("takes the folder off the front", () => {
expect(splitLeadingCd("cd /repo && git status")).toEqual({ command: "git status", dir: "/repo" });
expect(splitLeadingCd(`cd "/my repo/" ; ls`)).toEqual({ command: "ls", dir: "/my repo" });
expect(splitLeadingCd("cd /tmp")).toEqual({ command: "cd /tmp", dir: null });
});
});
describe("readOnlyCommand", () => {
it.each([
["git grep -n foo -- src", "search"],
["cd /repo && rg -n 'a|b' src | head -20", "search"],
["grep -rn foo src 2>/dev/null | wc -l", "search"],
["find . -name '*.ts' -not -path './node_modules/*'", "search"],
["sed -n 1,40p src/a.ts", "read"],
["cat a.ts; echo ---; head -5 b.ts", "read"],
["git diff --stat origin/main...HEAD", "read"],
["git -C ../other log --oneline -3", "read"],
["ls -la src && wc -l src/*.ts", "read"],
["git branch --show-current", "read"],
["git worktree list | head; grep -n x LICENSE | head", "search"],
["pgrep -fl openidea | head", "read"],
["FOO=1 cat a.ts 2>&1 | sort | uniq -c", "read"],
])("%s → %s", (command, kind) => {
expect(readOnlyCommand(command)).toBe(kind);
});
it.each([
"pnpm test",
"cargo build",
"git commit -m 'x'",
"git branch -D old",
"git worktree add ../x",
"git stash -q",
"git remote add up url",
"sed -i '' 's/a/b/' a.ts",
"sed -n 1p a.ts > out.txt",
"grep foo a.ts >> log",
"find . -name '*.tmp' -delete",
"find . -exec rm {} ;",
"cat a.ts | xargs rm",
"echo $(rm -rf x)",
"cat <<'EOF' > a.ts",
"sort -o a.txt a.txt",
"sleep 10 &",
"rm -rf build",
"",
])("%s may change something", (command) => {
expect(readOnlyCommand(command)).toBeNull();
});
it("does not split on operators inside quotes", () => {
expect(readOnlyCommand(`grep -n "a && rm -rf /" src`)).toBe("search");
expect(readOnlyCommand(`echo 'x' ; rm a`)).toBeNull();
});
});
+159
Переглянути файл
@@ -0,0 +1,159 @@
/** Reading what an agent's shell command does, from its text alone. */
/** A leading `cd <dir> &&` (or `;`), with the directory quoted or bare. */
const LEADING_CD = /^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)\s*/;
/** `command` without the `cd <dir> &&` agents put before it, and that folder; `null` when there is none. */
export function splitLeadingCd(command: string): { command: string; dir: string | null } {
const match = LEADING_CD.exec(command);
if (!match || match[0].length === command.length) return { command, dir: null };
const dir = match[1]!.replace(/^(["'])(.*)\1$/, "$2").replace(/\/+$/, "");
return { command: command.slice(match[0].length), dir };
}
/** Programs that look for something. */
const SEARCH = new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "find", "fd", "mdfind", "locate"]);
/** Programs that only print what is there. */
const READ = new Set([
"cat",
"head",
"tail",
"sed",
"awk",
"nl",
"wc",
"ls",
"tree",
"stat",
"file",
"pwd",
"echo",
"printf",
"jq",
"sort",
"uniq",
"cut",
"tr",
"column",
"diff",
"cmp",
"which",
"type",
"realpath",
"readlink",
"basename",
"dirname",
"du",
"df",
"true",
"cd",
"ps",
"pgrep",
"lsof",
"date",
"uname",
"whoami",
]);
/** Git subcommands that only read the repository. */
const GIT_READ = new Set([
"status",
"diff",
"log",
"show",
"blame",
"ls-files",
"ls-tree",
"rev-parse",
"merge-base",
"describe",
"cat-file",
"shortlog",
"reflog",
]);
/** Splits on `&&`, `||`, `;` and `|` outside quotes; `null` when the text has what this can't read safely. */
function segments(command: string): string[] | null {
const out: string[] = [];
let current = "";
let quote: string | null = null;
for (let i = 0; i < command.length; i++) {
const c = command[i]!;
if (quote) {
if (c === quote) quote = null;
else if (c === "\\" && quote === '"') current += command[i++] ?? "";
current += c;
continue;
}
if (c === "'" || c === '"') quote = c;
else if (c === "`" || c === "\n" || (c === "$" && command[i + 1] === "(")) return null;
else if (c === "<" && command[i + 1] === "<") return null;
else if (c === ">") {
// Only output thrown away (`>/dev/null`, `2>&1`) leaves the disk as it was.
const target = /^>?\s*(\/dev\/null\b|&\d)/.exec(command.slice(i + 1));
if (!target) return null;
i += target[0].length;
continue;
} else if (c === ";" || c === "|" || (c === "&" && command[i + 1] === "&")) {
out.push(current);
current = "";
if (command[i + 1] === c) i++;
continue;
} else if (c === "&") return null;
current += c;
}
if (quote) return null;
out.push(current);
return out.map((s) => s.trim()).filter(Boolean);
}
const words = (segment: string) => segment.match(/"[^"]*"|'[^']*'|\S+/g) ?? [];
/** What one segment does: `"search"`, `"read"`, or `null` when it may change something. */
function segmentKind(segment: string): "search" | "read" | null {
const args = words(segment).filter(
(w, i, all) => !(/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) && all.slice(0, i).every((p) => /=/.test(p))),
);
const [program, ...rest] = args;
if (!program) return null;
const name = program.replace(/^.*\//, "");
if (name === "git") {
// Global options before the subcommand, some taking a value (`git -C <dir> log`).
let at = 0;
while (at < rest.length && rest[at]!.startsWith("-"))
at += /^(-C|-c|--git-dir|--work-tree|--namespace)$/.test(rest[at]!) ? 2 : 1;
const sub = rest[at];
if (sub === "grep") return "search";
const next = rest[at + 1];
if (sub === "worktree" || sub === "stash")
return next === "list" || (sub === "stash" && next === "show") ? "read" : null;
if (sub === "remote") return next === undefined || next === "-v" || next === "show" ? "read" : null;
if (sub === "branch") return rest.some((a) => /^-(d|D|m|M|c|C|-delete|-move|-copy)$/.test(a)) ? null : "read";
return sub && GIT_READ.has(sub) ? "read" : null;
}
if (name === "sed" && rest.some((a) => /^-[a-zA-Z]*i|^--in-place/.test(a))) return null;
if (name === "awk" && rest.some((a) => /inplace/.test(a))) return null;
if (name === "sort" && rest.some((a) => /^-[a-zA-Z]*o|^--output/.test(a))) return null;
if (name === "find" && rest.some((a) => /^-(delete|exec|execdir|ok|okdir|fprint|fprintf|fls)$/.test(a))) return null;
if (name === "fd" && rest.some((a) => /^(-x|-X|--exec|--exec-batch)$/.test(a))) return null;
if (SEARCH.has(name)) return "search";
return READ.has(name) ? "read" : null;
}
/**
* Whether a shell command only looks at the workspace, and how: `"search"` when it looks for
* something (`grep`, `rg`, `find`, `git grep`), `"read"` when it prints files or state (`cat`,
* `sed -n`, `ls`, `git diff`); `null` when it may change something or can't be told.
*/
export function readOnlyCommand(command: string): "search" | "read" | null {
const parts = segments(splitLeadingCd(command).command);
if (!parts?.length) return null;
let kind: "search" | "read" = "read";
for (const part of parts) {
const k = segmentKind(part);
if (!k) return null;
if (k === "search") kind = "search";
}
return kind;
}
+17 -2
Переглянути файл
@@ -3,6 +3,7 @@
* the conversation renders the rows these describe.
*/
import type { AgentEntry } from "@/bindings";
import { readOnlyCommand } from "./shellCommand";
type ToolEntry = Extract<AgentEntry, { type: "tool" }>;
@@ -56,9 +57,14 @@ function countTool(s: WorkSummary, e: ToolEntry, edited: Set<string>) {
case "search":
s.search++;
break;
case "execute":
s.run++;
case "execute": {
// A command that only reads or searches counts as what it did.
const kind = exploringCommand(e);
if (kind === "search") s.search++;
else if (kind === "read") s.read++;
else s.run++;
break;
}
case "fetch":
s.fetch++;
break;
@@ -148,6 +154,15 @@ export interface ToolRun {
}
/** Splits an `execute` tool's text into its command, output and exit code, where it names them. */
/**
* How a shell command call only looks at the workspace (`"search"`, `"read"`), from the command
* it ran; `null` for any other call, or a command that may change something.
*/
export function exploringCommand(entry: ToolEntry): "search" | "read" | null {
if (entry.kind !== "execute" || entry.diffs.length) return null;
return readOnlyCommand(toolRun(entry).command ?? entry.title);
}
export function toolRun(entry: ToolEntry): ToolRun {
const text = entry.output ?? "";
const command = /^\$ (.+)$/m.exec(text)?.[1] ?? null;