diff --git a/Cargo.lock b/Cargo.lock index 0d4e0114..18fa511c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3956,6 +3956,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pdfmd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17859279b05a8e2b117a3ed599be6d1d5314a28029d9fdf959a14062efc4c0dd" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4080,8 +4086,9 @@ dependencies = [ [[package]] name = "plugin-std" version = "0.1.0" -source = "git+https://github.com/cppalliance/runvil-plugin-std?rev=badf32c91d9c16694758cc3cc847b2e2878d0a82#badf32c91d9c16694758cc3cc847b2e2878d0a82" +source = "git+https://github.com/cppalliance/runvil-plugin-std?rev=a0a1e3f7388ad60131d7ed35afff0cc970a25a36#a0a1e3f7388ad60131d7ed35afff0cc970a25a36" dependencies = [ + "pdfmd", "regex", "runvil-plugin-sdk", "serde", diff --git a/Cargo.toml b/Cargo.toml index eba02f2c..3f4db6af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ runvil-plugin-sdk = { version = "0.10.0", git = "https://github.com/cppalliance/ # own export of `runvil_plugin`, which `workshop-plugin-std` makes instead. # The key is `std-plugin` because that crate's own library is named # `plugin_std`, the name of the file Workshop ships. -std-plugin = { package = "plugin-std", version = "0.1.0", git = "https://github.com/cppalliance/runvil-plugin-std", rev = "badf32c91d9c16694758cc3cc847b2e2878d0a82", default-features = false } +std-plugin = { package = "plugin-std", version = "0.1.0", git = "https://github.com/cppalliance/runvil-plugin-std", rev = "a0a1e3f7388ad60131d7ed35afff0cc970a25a36", default-features = false } # The bashkit Plugin, from its own repository, pinned by commit and built # against the same contract commit. default-features off drops its own # export of `runvil_plugin`, which `workshop-plugin-bashkit` makes diff --git a/crates/workshop/server/tests/it/std_real_directory.rs b/crates/workshop/server/tests/it/std_real_directory.rs index f70be866..8758e412 100644 --- a/crates/workshop/server/tests/it/std_real_directory.rs +++ b/crates/workshop/server/tests/it/std_real_directory.rs @@ -1,10 +1,9 @@ //! The `std` file tools over a real directory, mounted with //! `RealBackend::rooted`: the acceptance flow a coding agent follows. List -//! the directory, find a word with Grep, read a window of the file, and read -//! the next window from the offset the first window's trailer names. Then -//! the tools that change files: Write makes a file under a directory that -//! is absent, StrReplace edits it, and Delete removes it, and the real -//! directory holds each change. +//! the directory, find a word with Grep, see an oversized full read refused, +//! and read a window around the line Grep found. Then the tools that change +//! files: Write makes a file under a directory that is absent, StrReplace +//! edits it, and Delete removes it, and the real directory holds each change. //! //! The tools come from the std Plugin's dynamic library, loaded from a //! Plugin directory as the server loads it, so each call crosses the C @@ -39,11 +38,6 @@ const NEEDLE_LINE: usize = 3000; /// The word only that line holds. const NEEDLE: &str = "needleword"; -/// The first line the second window starts at, which is the line after the -/// last one a 100,000-byte window of 40-byte lines with every-10th-line -/// numbers holds. -const SECOND_OFFSET: usize = 2399; - /// Counts the directories this process has made, so two tests never share /// one. static DIRECTORIES: AtomicUsize = AtomicUsize::new(0); @@ -162,36 +156,39 @@ fn list_find_read_a_window_and_read_the_next_one_by_the_trailer_offset() { assert_eq!(found.text(), format!("/{FILE}\n{expected_line}")); let path = format!("/{FILE}"); - let first = call(&*pack, &access, "read", json!({ "path": path })); - assert_eq!(first.trust(), OutputTrust::Trusted); - assert!( - first.text().starts_with(&format!("{}\n", "x".repeat(40))), - "the first window starts at line 1" - ); - let trailer = first - .text() - .lines() - .last() - .expect("a first window has a last line"); + let full = call(&*pack, &access, "read", json!({ "path": path })); + assert_eq!(full.trust(), OutputTrust::Trusted); assert!( - trailer.contains(&format!("Use offset={SECOND_OFFSET} to continue.")), - "{trailer}" + full.text().starts_with( + "Requested content exceeds maximum allowed characters (100000 characters)." + ), + "an oversized full read is refused: {}", + full.text() ); - let second = call( + let offset = NEEDLE_LINE - 5; + let slice = call( &*pack, &access, "read", - json!({ "path": path, "offset": SECOND_OFFSET }), + json!({ "path": path, "offset": offset, "limit": 10 }), + ); + assert_eq!(slice.trust(), OutputTrust::Trusted); + assert!( + slice + .text() + .starts_with(&format!("... {} lines not shown ...\n", offset - 1)), + "the slice opens with the omitted-lines marker: {}", + slice.text() ); assert!( - second.text().starts_with(&format!(" {SECOND_OFFSET}|")), - "the second window starts at the offset the trailer named: {}", - &second.text()[..20] + slice.text().contains(&format!(" {NEEDLE_LINE}|{NEEDLE}")), + "the slice holds the line Grep found" ); assert!( - second.text().contains(&format!(" {NEEDLE_LINE}|{NEEDLE}")), - "the second window holds the line Grep found" + slice.text().ends_with(" lines not shown ..."), + "the slice ends with the omitted-lines marker: {}", + slice.text() ); } diff --git a/crates/workshop/ui/src/parts/agent/AGENTS.md b/crates/workshop/ui/src/parts/agent/AGENTS.md new file mode 100644 index 00000000..1069a9bd --- /dev/null +++ b/crates/workshop/ui/src/parts/agent/AGENTS.md @@ -0,0 +1,4 @@ +# Agent Window UI + +- **Everything is inspectable**: the agent window must give the user a way to see every thinking block, every tool call, and every tool input, output, and error. Each item either expands inline to show its full contents or jumps directly to the underlying artifact (for example, clicking a successful `Read` row opens the file in the editor at the starting line of that read, while a failed `Read attempted` row expands inline to show its arguments and error text). +- **Collapsed by default and accumulated**: thinking blocks and tool calls start collapsed by default and accumulate into `Explored ...` groups with a hover-only caret, expanding only when the user clicks. diff --git a/crates/workshop/ui/src/parts/agent/agent-session-view.ts b/crates/workshop/ui/src/parts/agent/agent-session-view.ts index 33dca7f3..dfbe476d 100644 --- a/crates/workshop/ui/src/parts/agent/agent-session-view.ts +++ b/crates/workshop/ui/src/parts/agent/agent-session-view.ts @@ -46,6 +46,7 @@ import { TOAST_STACK } from "../../services/toast-service"; import { TEXT_CONTROL_SERVICE } from "@workshop/platform/text-control-service"; import { AgentToolbar } from "./agent-toolbar"; import { buildTranscript } from "./transcript/transcript-model"; +import { openPathAtLine } from "../workspace/file-actions"; import { TranscriptView } from "./transcript/transcript-view"; import { ChatBox } from "../chatbox/chat-box"; import type { ChatBoxError, ChatBoxEvent, ChatBoxProps } from "../chatbox/types"; @@ -121,6 +122,9 @@ export class AgentSessionView extends Disposable { copied: () => { getServiceOrNull(TOAST_STACK)?.show(COPIED_TOAST, "info"); }, + openFile: (path, line) => { + openPathAtLine(path, line); + }, }), ); diff --git a/crates/workshop/ui/src/parts/agent/transcript/rows.ts b/crates/workshop/ui/src/parts/agent/transcript/rows.ts index 58e5edf3..48bba309 100644 --- a/crates/workshop/ui/src/parts/agent/transcript/rows.ts +++ b/crates/workshop/ui/src/parts/agent/transcript/rows.ts @@ -191,9 +191,10 @@ export class ToolRowView implements IDisposable { readonly kind = "tool"; readonly element: HTMLElement; - private readonly line = new ToolLine(); + private readonly line: ToolLine; - constructor() { + constructor(onOpenFile?: (path: string, line: number) => void) { + this.line = new ToolLine(onOpenFile); this.element = this.line.element; } @@ -217,12 +218,12 @@ export class ToolRowView implements IDisposable { // --- Group ---------------------------------------------------------------------------- -/** A group's thinking step: an inner thinking line that opens while it streams. */ +/** A group's thinking step: collapsed by default until clicked. */ class ThinkingStepView implements KeyedComponent { readonly kind = "thought"; readonly element: HTMLElement; - private readonly line = new ThinkingLine(true, "ws-thinking-line"); + private readonly line = new ThinkingLine(false, "ws-thinking-line"); constructor() { this.element = this.line.element; @@ -246,9 +247,10 @@ class ToolStepView implements KeyedComponent { readonly kind = "tool"; readonly element: HTMLElement; - private readonly line = new ToolLine(); + private readonly line: ToolLine; - constructor() { + constructor(onOpenFile?: (path: string, line: number) => void) { + this.line = new ToolLine(onOpenFile); this.element = this.line.element; } @@ -283,9 +285,11 @@ export class GroupRowView implements IDisposable { private readonly collapsible = new Collapsible(); private readonly steps = new Map(); private readonly list: HTMLDivElement; + private readonly onOpenFile: ((path: string, line: number) => void) | undefined; private text = ""; - constructor() { + constructor(onOpenFile?: (path: string, line: number) => void) { + this.onOpenFile = onOpenFile; this.element = document.createElement("div"); this.element.className = "ws-group-row"; this.element.appendChild(this.collapsible.element); @@ -305,7 +309,7 @@ export class GroupRowView implements IDisposable { this.list, this.steps, entries, - (entry) => (entry.kind === "tool" ? new ToolStepView() : new ThinkingStepView()), + (entry) => (entry.kind === "tool" ? new ToolStepView(this.onOpenFile) : new ThinkingStepView()), (component, entry) => { if (component.kind === "tool" && entry.step.step === "tool") { component.update(entry.step); @@ -363,7 +367,11 @@ export type RowComponent = | ToolRowView; /** Builds the component for a row's kind. */ -export function createRowComponent(row: TranscriptRow, animateIn: boolean): RowComponent { +export function createRowComponent( + row: TranscriptRow, + animateIn: boolean, + onOpenFile?: (path: string, line: number) => void, +): RowComponent { let component: RowComponent; switch (row.kind) { case "human": @@ -376,10 +384,10 @@ export function createRowComponent(row: TranscriptRow, animateIn: boolean): RowC component = new ThoughtRowView(); break; case "group": - component = new GroupRowView(); + component = new GroupRowView(onOpenFile); break; case "tool": - component = new ToolRowView(); + component = new ToolRowView(onOpenFile); break; } component.element.classList.add("ws-transcript-row"); diff --git a/crates/workshop/ui/src/parts/agent/transcript/tool-labels.ts b/crates/workshop/ui/src/parts/agent/transcript/tool-labels.ts index 32d236e9..841c3839 100644 --- a/crates/workshop/ui/src/parts/agent/transcript/tool-labels.ts +++ b/crates/workshop/ui/src/parts/agent/transcript/tool-labels.ts @@ -6,9 +6,10 @@ // rather than throwing. import type { ToolCallRow } from "../../../services/agent-session"; +import { baseName } from "../../../base/paths"; /** The families of tool the transcript words differently. */ -export type ToolKind = "search" | "fetch" | "ask" | "other"; +export type ToolKind = "read" | "search" | "fetch" | "ask" | "other"; /** What a tool line reads: a verb, details after it, and the call name's span. */ export interface ToolLabel { @@ -24,8 +25,16 @@ export interface ToolLabel { readonly callName: string | null; } +/** Where a clicked `Read` line jumps in the editor. */ +export interface ReadTarget { + readonly path: string; + /** 1-based starting line of the read. */ + readonly line: number; +} + /** How many calls of each family a group holds. */ export interface ToolCounts { + readonly files: number; readonly searches: number; readonly fetches: number; readonly tools: number; @@ -47,12 +56,14 @@ export interface TurnState { /** * The family of a vendor-qualified tool name (`vendor/tool`, such as - * `runvil/web/search`). Only the fixed names of runvil's ask, search, - * and fetch tools are special, so the same tool id from another vendor's - * Pack is generic. A null name, a call without a vendor, is generic. + * `runvil/web/search`). Only the fixed names of runvil's read, ask, + * search, and fetch tools are special, so the same tool id from another + * vendor's Pack is generic. A null name, a call without a vendor, is generic. */ export function toolKind(qualified: string | null): ToolKind { switch (qualified) { + case "runvil/std/read": + return "read"; case "runvil/web/search": return "search"; case "runvil/web/fetch": @@ -86,32 +97,129 @@ export function isToolLoading(kind: ToolKind, hasResult: boolean, turn: TurnStat return turn.last && turn.generating; } -/** One string argument of a call's compact-JSON arguments, or "". */ -function stringArg(args: string, key: string): string { +/** Parses a call's compact-JSON arguments as an object, or null on any other input. */ +function parseArgs(args: string): Record | null { if (args === "") { - return ""; + return null; } let parsed: unknown; try { parsed = JSON.parse(args); } catch { - return ""; + return null; } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + return null; + } + return parsed as Record; +} + +/** One string argument of a call's compact-JSON arguments, or "". */ +function stringArg(args: string, key: string): string { + const parsed = parseArgs(args); + if (parsed === null) { return ""; } - const value = (parsed as Record)[key]; + const value = parsed[key]; return typeof value === "string" ? value : ""; } +/** One finite integer argument of a call's compact-JSON arguments, or null. */ +function intArg(args: string, key: string): number | null { + const parsed = parseArgs(args); + if (parsed === null) { + return null; + } + const value = parsed[key]; + return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) ? value : null; +} + +const TOP_OMITTED = /^\.\.\. (\d+) lines? not shown \.\.\.\n/; +const BOTTOM_OMITTED = /\n\.\.\. \d+ lines? not shown \.\.\.$/; +const NOTE_LINE = /\n\[Note: [^\n]+\]$/; +const EXCEEDS_PREFIX = "Requested content exceeds maximum allowed characters"; + +/** Whether a `Read` tool result is an error rather than file contents. */ +export function isReadFailure(result: string): boolean { + return result.startsWith("Error:") || result.startsWith("std_Read:"); +} + +/** Derives the 1-based inclusive `[first, last]` line range from a successful `Read` result. */ +function readLineRange(result: string): readonly [number, number] { + let body = result; + let first = 1; + const top = TOP_OMITTED.exec(body); + if (top !== null) { + first = Number(top[1]) + 1; + body = body.slice(top[0].length); + } + while (NOTE_LINE.test(body)) { + body = body.replace(NOTE_LINE, ""); + } + body = body.replace(BOTTOM_OMITTED, ""); + const count = body.split("\n").length; + return [first, first + count - 1]; +} + +/** + * The file path and 1-based starting line a settled, successful `Read` + * call opens in the editor when clicked, or null for failed/loading calls. + */ +export function readTarget(call: ToolCallRow, result: string | null): ReadTarget | null { + if (toolKind(qualifiedTool(call)) !== "read" || result === null || isReadFailure(result)) { + return null; + } + const path = stringArg(call.args, "path").trim(); + if (path === "") { + return null; + } + if (result === "File is empty.") { + return { path, line: 1 }; + } + if (result.startsWith(EXCEEDS_PREFIX)) { + const offset = intArg(call.args, "offset"); + return { path, line: offset !== null && offset > 0 ? offset : 1 }; + } + const [first] = readLineRange(result); + return { path, line: first }; +} + +function readLabel(call: ToolCallRow, loading: boolean, result: string | null): ToolLabel { + const path = stringArg(call.args, "path").trim(); + const name = path === "" ? "" : baseName(path); + if (loading) { + return { action: "Reading", details: name, callName: null }; + } + if (name === "" || (result !== null && isReadFailure(result))) { + return { action: "Read", details: "attempted", callName: null }; + } + if (result === null || result === "File is empty.") { + return { action: "Read", details: name, callName: null }; + } + if (result.startsWith(EXCEEDS_PREFIX)) { + const offset = intArg(call.args, "offset"); + const limit = intArg(call.args, "limit"); + if (limit !== null && limit >= 1 && (offset === null || offset >= 0)) { + const start = offset === null || offset === 0 ? 1 : offset; + return { action: "Read", details: `${name} L${start}-${start + limit - 1}`, callName: null }; + } + return { action: "Read", details: name, callName: null }; + } + const [first, last] = readLineRange(result); + return { action: "Read", details: `${name} L${first}-${last}`, callName: null }; +} + /** - * The verb and details of one tool call. runvil's `web/search` and - * `web/fetch` read their query and url arguments; runvil's ask tool has - * no details; any other tool reads ` in `, + * The verb and details of one tool call. runvil's `std/read` shows the + * file's basename and `L-` range (or `attempted` on failure); + * `web/search` and `web/fetch` read their query and url arguments; runvil's + * ask tool has no details; any other tool reads ` in `, * with the call name flagged for the verb's color. */ -export function toolLabel(call: ToolCallRow, loading: boolean): ToolLabel { +export function toolLabel(call: ToolCallRow, loading: boolean, result: string | null = null): ToolLabel { switch (toolKind(qualifiedTool(call))) { + case "read": + return readLabel(call, loading, result); case "search": return { action: loading ? "Searching web" : "Searched web", @@ -152,11 +260,14 @@ function plural(count: number, one: string, many: string): string { /** * A group's header. The verb is Exploring while the group is the last row * of a generating turn and Explored otherwise. The parts come in a fixed - * order - searches, fetches, other tools - and are joined with ", ": there - * is no "and". A family with no calls is left out. + * order - files, searches, fetches, other tools - and are joined with ", ": + * there is no "and". A family with no calls is left out. */ export function groupSummary(counts: ToolCounts, active: boolean): GroupSummary { const parts: string[] = []; + if (counts.files > 0) { + parts.push(plural(counts.files, "file", "files")); + } if (counts.searches > 0) { parts.push(plural(counts.searches, "search", "searches")); } diff --git a/crates/workshop/ui/src/parts/agent/transcript/tool-line.css b/crates/workshop/ui/src/parts/agent/transcript/tool-line.css index 31f4985b..61a7fb9d 100644 --- a/crates/workshop/ui/src/parts/agent/transcript/tool-line.css +++ b/crates/workshop/ui/src/parts/agent/transcript/tool-line.css @@ -6,6 +6,10 @@ user-select: none; } +.ws-tool-line[data-clickable="true"] > .ws-collapsible__header { + cursor: pointer; +} + /* The verb reads in the secondary tier and the details in the tertiary one; a muted scope (a group's steps) shifts both down a tier, which gives the verb 60% and the details 36%. */ diff --git a/crates/workshop/ui/src/parts/agent/transcript/tool-line.ts b/crates/workshop/ui/src/parts/agent/transcript/tool-line.ts index ea0f7166..0a6f6e04 100644 --- a/crates/workshop/ui/src/parts/agent/transcript/tool-line.ts +++ b/crates/workshop/ui/src/parts/agent/transcript/tool-line.ts @@ -1,8 +1,11 @@ -// A tool call as the transcript shows it: one line, "Ran read in fs" or -// "Searched web ", used both as a standalone tool row and as a -// step inside a group. The verb and details come from the model's tool -// label; the line adds the behavior. +// A tool call as the transcript shows it: one line, "Read read.rs L1-122", +// "Ran read in fs", or "Searched web ", used both as a standalone +// tool row and as a step inside a group. The verb and details come from +// the model's tool label; the line adds the behavior. // +// - A successful `Read` line opens the file in the editor at the starting +// line when clicked. A failed `Read attempted` line expands into its +// arguments and error text so everything remains inspectable. // - Search and fetch lines are not expandable. They open a hover card // (web-hover-card.ts) listing the result titles and URLs, disabled // while the call is loading. @@ -19,6 +22,7 @@ import "./tool-line.css"; import type { IDisposable } from "@workshop/platform/lifecycle"; import { Collapsible } from "./collapsible"; +import { readTarget, type ReadTarget } from "./tool-labels"; import type { ToolStep } from "./transcript-model"; import { WebHoverCard, webCardEntries } from "./web-hover-card"; @@ -55,10 +59,26 @@ export class ToolLine implements IDisposable { private readonly collapsible: Collapsible; private readonly pre: HTMLPreElement; private readonly card: WebHoverCard; + private readonly onOpenFile: ((path: string, line: number) => void) | undefined; + private target: ReadTarget | null = null; private text = ""; private label = ""; - constructor() { + private readonly onHeaderClick = (): void => { + if (this.target !== null) { + this.onOpenFile?.(this.target.path, this.target.line); + } + }; + + private readonly onHeaderKeydown = (event: KeyboardEvent): void => { + if (this.target !== null && (event.key === "Enter" || event.key === " ")) { + event.preventDefault(); + this.onOpenFile?.(this.target.path, this.target.line); + } + }; + + constructor(onOpenFile?: (path: string, line: number) => void) { + this.onOpenFile = onOpenFile; this.collapsible = new Collapsible(); this.element = this.collapsible.element; this.element.classList.add("ws-tool-line"); @@ -70,6 +90,9 @@ export class ToolLine implements IDisposable { block.appendChild(this.pre); this.collapsible.body.appendChild(block); + this.collapsible.header.addEventListener("click", this.onHeaderClick); + this.collapsible.header.addEventListener("keydown", this.onHeaderKeydown); + // The card hangs off the header line, not the whole element, so an // opened block never keeps it alive. this.card = new WebHoverCard(this.collapsible.header); @@ -87,6 +110,36 @@ export class ToolLine implements IDisposable { this.element.dataset["loading"] = String(step.loading); this.label = `${step.label.action} ${step.label.details}`.trim(); + if (step.toolKind === "read") { + const target = step.loading ? null : readTarget(step.call, step.result); + this.target = target; + this.card.setEntries(null); + if (target !== null) { + this.text = ""; + this.pre.textContent = ""; + this.collapsible.setExpandable(false); + this.setClickable(true); + return; + } + this.setClickable(false); + if (!step.loading && step.result !== null) { + const text = toolBlockText(step); + if (text !== this.text) { + this.text = text; + this.pre.textContent = text; + } + this.collapsible.setExpandable(text !== ""); + return; + } + this.text = ""; + this.pre.textContent = ""; + this.collapsible.setExpandable(false); + return; + } + + this.target = null; + this.setClickable(false); + if (step.toolKind === "other") { const text = toolBlockText(step); if (text !== this.text) { @@ -109,6 +162,14 @@ export class ToolLine implements IDisposable { } } + private setClickable(clickable: boolean): void { + this.element.dataset["clickable"] = String(clickable); + if (clickable) { + this.collapsible.header.setAttribute("role", "button"); + this.collapsible.header.tabIndex = 0; + } + } + /** The operator's own open or closed choice for the block, or null while they've made none. */ get operatorChoice(): boolean | null { return this.collapsible.operatorChoice; @@ -125,6 +186,8 @@ export class ToolLine implements IDisposable { } dispose(): void { + this.collapsible.header.removeEventListener("click", this.onHeaderClick); + this.collapsible.header.removeEventListener("keydown", this.onHeaderKeydown); this.card.dispose(); } } diff --git a/crates/workshop/ui/src/parts/agent/transcript/transcript-model.ts b/crates/workshop/ui/src/parts/agent/transcript/transcript-model.ts index 79b66fcc..201a41d4 100644 --- a/crates/workshop/ui/src/parts/agent/transcript/transcript-model.ts +++ b/crates/workshop/ui/src/parts/agent/transcript/transcript-model.ts @@ -422,7 +422,7 @@ function toolStep(draft: ToolDraft, state: TurnState): ToolStep { toolKind: draft.family, result: draft.result, loading, - label: toolLabel(draft.call, loading), + label: toolLabel(draft.call, loading, draft.result), }; } @@ -495,6 +495,7 @@ function finishTurn( steps, summary: groupSummary( { + files: tools.filter((step) => step.toolKind === "read").length, searches: tools.filter((step) => step.toolKind === "search").length, fetches: tools.filter((step) => step.toolKind === "fetch").length, tools: tools.filter((step) => step.toolKind === "other").length, diff --git a/crates/workshop/ui/src/parts/agent/transcript/transcript-view.ts b/crates/workshop/ui/src/parts/agent/transcript/transcript-view.ts index 70b425e9..801cb11c 100644 --- a/crates/workshop/ui/src/parts/agent/transcript/transcript-view.ts +++ b/crates/workshop/ui/src/parts/agent/transcript/transcript-view.ts @@ -40,6 +40,8 @@ import type { TranscriptModel, TranscriptTurn } from "./transcript-model"; export interface TranscriptHost { /** A turn's Copy landed: raise the confirmation. */ copied(): void; + /** Opens a file in the editor at the 1-based `line`. */ + openFile?(path: string, line: number): void; } /** One turn: its wrapper, its rows, and its footer. */ @@ -177,7 +179,9 @@ export class TranscriptView implements IDisposable { } private makeRow(row: TranscriptTurn["rows"][number]): RowComponent & KeyedComponent { - const component = createRowComponent(row, this.animateIn); + const component = createRowComponent(row, this.animateIn, (path, line) => { + this.host.openFile?.(path, line); + }); this.rowByElement.set(component.element, component); return component; } diff --git a/crates/workshop/ui/src/parts/editor/editor-panel.ts b/crates/workshop/ui/src/parts/editor/editor-panel.ts index bc30b7ea..7caa2f04 100644 --- a/crates/workshop/ui/src/parts/editor/editor-panel.ts +++ b/crates/workshop/ui/src/parts/editor/editor-panel.ts @@ -9,7 +9,8 @@ import "./editor-panel.css"; -import type { GroupPanelPartInitParameters } from "dockview"; +import type { GroupPanelPartInitParameters, PanelUpdateEvent } from "dockview"; +import { EditorSelection } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { Emitter } from "@workshop/platform/event"; @@ -60,6 +61,12 @@ function untitledSerialParam(params: Record): number | null { return typeof untitled === "number" && Number.isInteger(untitled) && untitled > 0 ? untitled : null; } +/** Reads an optional 1-based target line number out of panel params. */ +function lineParam(params: Record): number | null { + const line = params.line; + return typeof line === "number" && Number.isInteger(line) && line > 0 ? line : null; +} + const SAVE_TIMEOUT_MESSAGE = "The save timed out; the file may or may not have been written."; const didInitEmitter = new Emitter(); @@ -86,6 +93,12 @@ export class EditorPanel extends WorkshopPart { private saving = false; /** True from the unsaved-changes prompt opening until it answers. */ private closePending = false; + /** True once `load` has opened the document in the surface. */ + private loaded = false; + /** True while `load` is awaiting the workspace reader. */ + private loading = false; + /** 1-based line to jump to once `load` finishes. */ + private pendingLine: number | null = null; constructor(private readonly deps: EditorPanelDeps = {}) { super(); @@ -125,6 +138,7 @@ export class EditorPanel extends WorkshopPart { if (path !== null) { this.path = path; this.title = baseName(path); + this.pendingLine = lineParam(parameters.params); this.updateTitle(); void this.load(path) .then(() => { @@ -205,6 +219,36 @@ export class EditorPanel extends WorkshopPart { this.surface.focus(); } + /** Handles parameter updates on an already-open tab, jumping to `line` when present. */ + update(event: PanelUpdateEvent): void { + const line = lineParam(event.params); + if (line === null) { + return; + } + if (this.loaded && !this.loading) { + this.pendingLine = null; + this.revealLine(line); + } else { + this.pendingLine = line; + } + } + + /** Moves the cursor to the 1-based `line`, clamped into the document, and focuses the view. */ + revealLine(line: number): void { + const view = this.surface.editorView(); + if (view === null) { + return; + } + const clamped = Math.max(1, Math.min(line, view.state.doc.lines)); + const docLine = view.state.doc.line(clamped); + view.dispatch({ + selection: EditorSelection.cursor(docLine.from), + scrollIntoView: true, + userEvent: "select", + }); + view.focus(); + } + /** * Saves through the workspace API with the token from the last read. * A stale token means the file changed on disk: rather than overwriting @@ -418,10 +462,20 @@ export class EditorPanel extends WorkshopPart { /** Loads the document into the surface and records its conflict token. */ private async load(path: string): Promise { - const file = await this.reader()(path); - this.token = file.token; - this.tokenUnknown = false; - this.surface.open({ path, text: file.text }); + this.loading = true; + try { + const file = await this.reader()(path); + this.token = file.token; + this.tokenUnknown = false; + this.surface.open({ path, text: file.text }); + this.loaded = true; + if (this.pendingLine !== null) { + this.revealLine(this.pendingLine); + this.pendingLine = null; + } + } finally { + this.loading = false; + } } private updateTitle(): void { diff --git a/crates/workshop/ui/src/parts/layout/panel-types.ts b/crates/workshop/ui/src/parts/layout/panel-types.ts index 7c408160..a1a5d5d5 100644 --- a/crates/workshop/ui/src/parts/layout/panel-types.ts +++ b/crates/workshop/ui/src/parts/layout/panel-types.ts @@ -12,6 +12,7 @@ import type { GroupPanelPartInitParameters, IContentRenderer, ITabRenderer, + PanelUpdateEvent, } from "dockview"; import { Disposable } from "@workshop/platform/lifecycle"; @@ -44,6 +45,7 @@ class LazyPanel extends Disposable implements IContentRenderer { readonly element = document.createElement("div"); private inner: (IContentRenderer & { dispose?: () => void }) | null = null; private dimension: readonly [width: number, height: number] | null = null; + private pendingUpdate: PanelUpdateEvent | null = null; private unloaded = false; constructor(private readonly type: string) { @@ -69,6 +71,10 @@ class LazyPanel extends Disposable implements IContentRenderer { if (this.dimension !== null) { renderer.layout?.(...this.dimension); } + if (this.pendingUpdate !== null) { + renderer.update?.(this.pendingUpdate); + this.pendingUpdate = null; + } }) .catch((error: unknown) => { if (!this.unloaded) { @@ -82,6 +88,15 @@ class LazyPanel extends Disposable implements IContentRenderer { return this.inner; } + /** Forwards parameter updates to the real panel, replaying the latest once loaded. */ + update(event: PanelUpdateEvent): void { + if (this.inner !== null) { + this.inner.update?.(event); + } else { + this.pendingUpdate = event; + } + } + /** * Forwards the dock's resize to the real panel; a resize that lands * before the chunk resolves is replayed at the swap. diff --git a/crates/workshop/ui/src/parts/workspace/file-actions.ts b/crates/workshop/ui/src/parts/workspace/file-actions.ts index ddf33551..bf8b108f 100644 --- a/crates/workshop/ui/src/parts/workspace/file-actions.ts +++ b/crates/workshop/ui/src/parts/workspace/file-actions.ts @@ -118,6 +118,18 @@ export function openPath(path: string): void { openInZone("editor", { path }); } +/** + * Opens an editor on `path` and moves the cursor to the 1-based `line`, + * both for a newly opened panel and for an already-open tab. + */ +export function openPathAtLine(path: string, line: number): void { + const params = line > 0 ? { path, line } : { path }; + const panel = openInZone("editor", params); + if (line > 0) { + panel.api.updateParameters(params); + } +} + /** * vscode.openFolder: re-focus the Workshop tree on one granted root. The * root's listing is fetched and cached when missing, so the expanded row diff --git a/crates/workshop/ui/test/agent-session-view.mjs b/crates/workshop/ui/test/agent-session-view.mjs index b4f67ac8..b1aabaeb 100644 --- a/crates/workshop/ui/test/agent-session-view.mjs +++ b/crates/workshop/ui/test/agent-session-view.mjs @@ -501,12 +501,12 @@ await assertNoLeaks(lifecycle, async () => { wire.fire.delta("reasoning", "pondering", 3); let thinking = steps().find((step) => step.classList.contains("ws-thinking-line")); check( - "a streaming thinking step in a group is open by default", - thinking !== undefined && isOpen(thinking) && actionOf(thinking) === "Thinking", + "a streaming thinking step in a group is collapsed by default", + thinking !== undefined && !isOpen(thinking) && actionOf(thinking) === "Thinking", ); wire.fire.event("agent_thought", "pondering", { reply: 3 }); check( - "the same thinking step closes once settled", + "the same thinking step stays collapsed once settled", steps().find((step) => step.classList.contains("ws-thinking-line")) === thinking && !isOpen(thinking), ); headerOf(thinking)?.click(); @@ -516,9 +516,9 @@ await assertNoLeaks(lifecycle, async () => { wire.fire.delta("reasoning", "again", 5); thinking = steps().filter((step) => step.classList.contains("ws-thinking-line")).at(-1); headerOf(thinking)?.click(); - check("the operator closes a streaming thinking step", !isOpen(thinking)); + check("the operator opens a streaming thinking step on click", isOpen(thinking)); wire.fire.event("agent_thought", "again", { reply: 5 }); - check("a thinking step the operator closed stays closed through the settle", !isOpen(thinking)); + check("a thinking step the operator opened stays open through the settle", isOpen(thinking)); wire.fire.event("agent_message", "done", { reply: 6 }); wire.fire.awaiting(); diff --git a/crates/workshop/ui/test/tool-line.mjs b/crates/workshop/ui/test/tool-line.mjs index 55297bbf..919c7d60 100644 --- a/crates/workshop/ui/test/tool-line.mjs +++ b/crates/workshop/ui/test/tool-line.mjs @@ -67,7 +67,7 @@ function step({ name, tool, vendor = "runvil", args = {}, result = null, loading toolKind: toolKind(`${vendor}/${tool}`), result, loading, - label: toolLabel(call, loading), + label: toolLabel(call, loading, result), }; } @@ -339,6 +339,54 @@ function mount(initial) { dispose(); } +// --- Read lines ------------------------------------------------------------------------------- + +{ + const opened = []; + const line = new ToolLine((filePath, lineNumber) => opened.push([filePath, lineNumber])); + document.body.appendChild(line.element); + const header = line.element.querySelector(".ws-collapsible__header"); + + line.update( + step({ + name: "Read", + tool: "std/read", + args: { path: "/proj/src/read.rs", offset: 10, limit: 2 }, + result: "... 9 lines not shown ...\n 10|ten\neleven", + loading: false, + }), + ); + check( + "a successful Read line shows Read L- and is clickable, not expandable", + line.copyText() === "Read read.rs L10-11" && + line.element.dataset.clickable === "true" && + line.element.dataset.expandable === "false", + ); + header.click(); + check( + "clicking a successful Read line opens the file at the starting line", + JSON.stringify(opened) === JSON.stringify([["/proj/src/read.rs", 10]]), + ); + + line.update( + step({ + name: "Read", + tool: "std/read", + args: { path: "/missing.rs" }, + result: "Error: File not found", + loading: false, + }), + ); + check( + "a failed Read line shows Read attempted and is expandable so the error is inspectable", + line.copyText() === "Read attempted" && + line.element.dataset.clickable === "false" && + line.element.dataset.expandable === "true", + ); + line.dispose(); + line.element.remove(); +} + if (failures.length > 0) { console.error(`tool-line: ${failures.length} failure(s)`); for (const failure of failures) console.error(` - ${failure}`); diff --git a/crates/workshop/ui/test/transcript-model.mjs b/crates/workshop/ui/test/transcript-model.mjs index fd2bb5da..8c30160f 100644 --- a/crates/workshop/ui/test/transcript-model.mjs +++ b/crates/workshop/ui/test/transcript-model.mjs @@ -823,6 +823,80 @@ const keysOf = (model, turn = 0) => rowsOf(model, turn).map((row) => row.key); ); } +// --- Read tool labels and file-count summaries ----------------------------------------- + +{ + const readCall = (id, args) => call(id, "Read", "std/read", args); + check("runvil/std/read maps to toolKind read", toolKind("runvil/std/read") === "read"); + same( + "loading Read shows Reading ", + toolLabel(readCall("r1", { path: "/a/b/read.rs" }), true, null), + { action: "Reading", details: "read.rs", callName: null }, + ); + same( + "full Read shows L1-N including trailing newline line", + toolLabel(readCall("r1", { path: "/a/read.json" }), false, "a\nb\n"), + { action: "Read", details: "read.json L1-3", callName: null }, + ); + same( + "windowed Read shows L- from omitted markers", + toolLabel( + readCall("r1", { path: "/a/read.json", offset: 2, limit: 2 }), + false, + "... 1 line not shown ...\nb\nc\n... 5 lines not shown ...", + ), + { action: "Read", details: "read.json L2-3", callName: null }, + ); + same( + "single-line Read shows L-", + toolLabel( + readCall("r1", { path: "/a/read.json", offset: 22, limit: 1 }), + false, + "... 21 lines not shown ...\n}\n... 1 line not shown ...", + ), + { action: "Read", details: "read.json L22-22", callName: null }, + ); + same( + "empty file Read shows basename without range", + toolLabel(readCall("r1", { path: "/a/validate.d.ts" }), false, "File is empty."), + { action: "Read", details: "validate.d.ts", callName: null }, + ); + same( + "failed Read shows Read attempted", + toolLabel(readCall("r1", { path: "/missing.md" }), false, "Error: File not found"), + { action: "Read", details: "attempted", callName: null }, + ); + same( + "oversized Read with offset and limit shows L-", + toolLabel( + readCall("r1", { path: "/Cargo.lock", offset: 1, limit: 5000 }), + false, + "Requested content exceeds maximum allowed characters (100000 characters). The file is 203796 bytes.", + ), + { action: "Read", details: "Cargo.lock L1-5000", callName: null }, + ); + same( + "group summary puts files first before searches", + groupSummary({ files: 33, searches: 2, fetches: 0, tools: 0 }, false), + { action: "Explored", details: "33 files, 2 searches" }, + ); + const grouped = buildTranscript( + [ + user("inspect"), + batch(readCall("r1", { path: "/a.rs" }), search("s1", "foo")), + result("r1", "fn main() {}"), + result("s1", "{}"), + ], + false, + false, + ); + const groupRow = rowsOf(grouped, 0)[1]; + same("group counts std/read calls as files", groupRow.summary, { + action: "Explored", + details: "1 file, 1 search", + }); +} + if (failures.length > 0) { console.error(`transcript-model: ${failures.length} failure(s)`); for (const failure of failures) console.error(` - ${failure}`);