From 40375d878a82afec72e8983d2f9792dd2f4345e8 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:16:53 +0000 Subject: [PATCH 1/4] feat(server): show a file without reading it into context An agent had to read a file and paste it to put it on screen. show_file stats the path and returns only path, size, and type. The web client opens the existing file viewer from that result, so the file bytes stay out of the model context. Model: grok-4.7 Task: CLO-898 show a file without reading it into context Agent: magpie Lane: magpie Harness: t3/codex Model-family: Grok Model-generation: 4.7 Skills-SHA: 0540352af0d6f43bdeea39a8c4aad4660ab0ec55 Co-Authored-By: Grok 4.7 --- apps/server/src/mcp/McpHttpServer.ts | 5 + .../mcp/toolkits/showFile/handlers.test.ts | 93 +++++++++++++++++++ .../src/mcp/toolkits/showFile/handlers.ts | 64 +++++++++++++ .../server/src/mcp/toolkits/showFile/tools.ts | 58 ++++++++++++ .../src/components/chat/MessagesTimeline.tsx | 19 ++++ .../src/components/chat/shownFileOpen.test.ts | 73 +++++++++++++++ apps/web/src/components/chat/shownFileOpen.ts | 53 +++++++++++ packages/client-runtime/src/t3ToolSummary.ts | 3 + packages/shared/package.json | 4 + packages/shared/src/showFile.ts | 75 +++++++++++++++ packages/shared/src/t3McpToolPresentation.ts | 4 +- packages/shared/src/toolOutput.test.ts | 28 ++++++ packages/shared/src/toolOutput.ts | 18 ++++ 13 files changed, 496 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/toolkits/showFile/handlers.test.ts create mode 100644 apps/server/src/mcp/toolkits/showFile/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/showFile/tools.ts create mode 100644 apps/web/src/components/chat/shownFileOpen.test.ts create mode 100644 apps/web/src/components/chat/shownFileOpen.ts create mode 100644 packages/shared/src/showFile.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 9784f84303590..2b69ea9c74cce 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -88,6 +88,8 @@ import { import * as HtmlHandlers from "./toolkits/html/handlers.ts"; import { MessageToolkit } from "./toolkits/message/tools.ts"; import * as MessageHandlers from "./toolkits/message/handlers.ts"; +import * as ShowFileHandlers from "./toolkits/showFile/handlers.ts"; +import { ShowFileToolkit } from "./toolkits/showFile/tools.ts"; import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts"; import { MCP_HTTP_PATH } from "../httpCors.ts"; import { requestUrl } from "../requestUrl.ts"; @@ -1280,6 +1282,8 @@ export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandl const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); +const layerShowFileToolkit = toolkitRegistration(ShowFileToolkit, ShowFileHandlers.layer); + const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, WorktreeHandlers.layer, @@ -1371,6 +1375,7 @@ export const layerTools = Layer.mergeAll( layerDeviceToolkit, layerHtmlToolkit, layerMessageToolkit, + layerShowFileToolkit, ); const layerToolExposure = Layer.effect( diff --git a/apps/server/src/mcp/toolkits/showFile/handlers.test.ts b/apps/server/src/mcp/toolkits/showFile/handlers.test.ts new file mode 100644 index 0000000000000..9336a3db131ea --- /dev/null +++ b/apps/server/src/mcp/toolkits/showFile/handlers.test.ts @@ -0,0 +1,93 @@ +import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; + +import * as ServerConfig from "../../../config.ts"; +import * as ProjectService from "../../../project/ProjectService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { liveThreadShell } from "../../McpToolAccess.testkit.ts"; +import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as ShowFileHandlers from "./handlers.ts"; +import { ShowFileToolkit } from "./tools.ts"; + +const SENTINEL = "SECRET_FILE_BYTES_9f3a"; +const environmentId = EnvironmentId.make("environment:show-file"); +const threadId = ThreadId.make("thread:show-file"); + +it.effect("returns path, size, and type and does not put file bytes in the result", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-show-file-" }); + const filePath = path.join(directory, "answers.md"); + yield* fileSystem.writeFileString(filePath, SENTINEL); + const layer = McpToolAccess.HandlersLayer.layer(ShowFileHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId, + requestNamespace: "provider:show-file", + thread: { + threadId, + providerSessionId: "provider:show-file", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: () => + Effect.succeed({ ...liveThreadShell(threadId), worktreePath: directory }), + }), + Layer.mock(ProjectService.ProjectService)({}), + ServerConfig.layerTest(directory, { prefix: "t3-show-file-config-" }), + ), + ), + Layer.provideMerge(NodeServices.layer), + ); + const call = (params: { readonly path: string; readonly line?: number }) => + Effect.gen(function* () { + const toolkit = yield* ShowFileToolkit; + const parts = yield* toolkit + .handle("show_file", params) + .pipe(Stream.unwrap, Stream.runCollect); + return parts.at(-1)?.result; + }).pipe(Effect.provide(layer)); + + const shown = yield* call({ path: filePath, line: 4 }); + expect(shown).toEqual({ + path: filePath, + byteSize: SENTINEL.length, + mediaType: "text/markdown", + line: 4, + message: "Shown in the file viewer. Do not read or quote the file.", + }); + expect(JSON.stringify(shown)).not.toContain(SENTINEL); + expect(Object.keys(shown as object).sort()).toEqual([ + "byteSize", + "line", + "mediaType", + "message", + "path", + ]); + + const relative = yield* call({ path: "answers.md" }); + expect(relative).toMatchObject({ + path: filePath, + byteSize: SENTINEL.length, + mediaType: "text/markdown", + }); + expect(JSON.stringify(relative)).not.toContain(SENTINEL); + + const missing = yield* call({ path: path.join(directory, "missing.md") }); + expect(missing).toMatchObject({ code: "invalid_request", message: "File not found." }); + expect(JSON.stringify(missing)).not.toContain(SENTINEL); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/mcp/toolkits/showFile/handlers.ts b/apps/server/src/mcp/toolkits/showFile/handlers.ts new file mode 100644 index 0000000000000..211bb5e86d668 --- /dev/null +++ b/apps/server/src/mcp/toolkits/showFile/handlers.ts @@ -0,0 +1,64 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import { isNetworkPath } from "@t3tools/shared/path"; +import { mediaTypeForPath } from "@t3tools/shared/showFile"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { makeIsServerInternalPath } from "../../../auth/serverInternalPaths.ts"; +import { expandHomePath } from "../../../os-jank.ts"; +import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { ShowFileToolkit } from "./tools.ts"; + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); + +const showFile = Effect.fn("ShowFile.stat")(function* (input: { + readonly path: string; + readonly line?: number | undefined; +}) { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const scope = yield* McpInvocationContext.McpInvocationContext; + const expanded = yield* expandHomePath(input.path); + const workspaceRoot = + scope.thread === undefined ? undefined : yield* threadWorkspaceRoot(scope.thread.threadId); + if (!path.isAbsolute(expanded) && workspaceRoot === undefined) { + return yield* invalid("Pass an absolute path or a path in this thread's workspace."); + } + const resolved = path.isAbsolute(expanded) + ? path.resolve(expanded) + : path.resolve(workspaceRoot ?? expanded, expanded); + if (isNetworkPath(resolved)) { + return yield* invalid("That path cannot be shown."); + } + const stat = yield* fileSystem + .stat(resolved) + .pipe(Effect.mapError(() => invalid("File not found."))); + if (stat.type !== "File") { + return yield* invalid("Not a file."); + } + const isServerInternalPath = yield* makeIsServerInternalPath; + if (yield* isServerInternalPath(resolved)) { + return yield* invalid("That file cannot be shown."); + } + const byteSize = Number(stat.size); + if (!Number.isSafeInteger(byteSize) || byteSize < 0) { + return yield* invalid("That file cannot be shown."); + } + return { + path: resolved, + byteSize, + mediaType: mediaTypeForPath(resolved), + ...(input.line === undefined ? {} : { line: input.line }), + message: "Shown in the file viewer. Do not read or quote the file.", + }; +}); + +const handlers = { + show_file: McpToolAccess.actsAsCaller((input) => showFile(input)), +} satisfies McpToolAccess.Handlers; + +export const layer = McpToolAccess.toLayer(ShowFileToolkit, handlers); diff --git a/apps/server/src/mcp/toolkits/showFile/tools.ts b/apps/server/src/mcp/toolkits/showFile/tools.ts new file mode 100644 index 0000000000000..f723c6ceb53e4 --- /dev/null +++ b/apps/server/src/mcp/toolkits/showFile/tools.ts @@ -0,0 +1,58 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import { SHOW_FILE_MAX_PATH_LENGTH, SHOW_FILE_TOOL_NAME } from "@t3tools/shared/showFile"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; + +import * as ServerConfig from "../../../config.ts"; +import * as ProjectService from "../../../project/ProjectService.ts"; +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +const ShowFileTool = Tool.make(SHOW_FILE_TOOL_NAME, { + description: + "Show a file to the user in the file viewer. Pass its path. Returns only the path, byte size, and media type. Does not read the file, so its contents stay out of your context. Do not read or quote the file to show it.", + parameters: Schema.Struct({ + path: Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(SHOW_FILE_MAX_PATH_LENGTH), + ).annotate({ + description: "Absolute path, ~/ path, or a path in this thread's workspace.", + }), + line: Schema.optional( + Schema.Int.check( + Schema.isGreaterThanOrEqualTo(1), + Schema.isLessThanOrEqualTo(1_000_000), + ).annotate({ + description: "1-based line to reveal. Omit to open the start of the file.", + }), + ), + }), + success: Schema.Struct({ + path: Schema.String, + byteSize: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + mediaType: Schema.String, + line: Schema.optional(Schema.Int), + message: Schema.String, + }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ProjectService.ProjectService, + FileSystem.FileSystem, + Path.Path, + ServerConfig.ServerConfig, + ], +}) + .annotate(Tool.Title, "Show a file") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients) + .annotate(Tool.Meta, { "anthropic/alwaysLoad": true }); + +export const ShowFileToolkit = Toolkit.make(ShowFileTool); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index e381e295d7e1c..fcb5081caf6df 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -20,6 +20,8 @@ import { ThreadId, } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; +import { useRightPanelStore } from "../../rightPanelStore"; +import { shownFileKey, shownFileTargets, shownFilesToOpen } from "./shownFileOpen"; import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; @@ -483,6 +485,23 @@ const ConversationTimeline = memo(function ConversationTimeline({ setExpandedAttemptIds(paintedExpandedAttemptIds); } const citationThreadRef = parseScopedThreadKey(routeThreadKey); + const shownFiles = shownFileTargets(timelineEntries); + const shownFileSignature = shownFileKey(shownFiles); + const shownFileBaseline = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a show_file completion opens the existing file viewer with a panel state update; the viewer reads the file after paint, and files already on screen stay put + useEffect(() => { + const plan = shownFilesToOpen({ + threadKey: routeThreadKey, + previous: shownFileBaseline.current, + nextKey: shownFileSignature, + files: shownFiles, + }); + shownFileBaseline.current = plan.baseline; + if (citationThreadRef === null) return; + for (const file of plan.open) { + useRightPanelStore.getState().openFile(citationThreadRef, file.path, file.line); + } + }, [citationThreadRef, routeThreadKey, shownFileSignature, shownFiles]); const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined); const [minimapStripMap] = useState(() => new Map()); const normalizedFindQuery = findQuery.trim(); diff --git a/apps/web/src/components/chat/shownFileOpen.test.ts b/apps/web/src/components/chat/shownFileOpen.test.ts new file mode 100644 index 0000000000000..458cb25644a93 --- /dev/null +++ b/apps/web/src/components/chat/shownFileOpen.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { shownFileTargets, shownFilesToOpen, type ShownFileTarget } from "./shownFileOpen"; + +const SECRET = "SECRET_FILE_BYTES_9f3a"; + +describe("shownFileTargets", () => { + it("opens from path, size, and type and drops file bytes", () => { + const targets = shownFileTargets([ + { + id: "show-1", + kind: "work", + createdAt: "2026-01-01T00:00:00.000Z", + entry: { + id: "show-1", + createdAt: "2026-01-01T00:00:00.000Z", + label: "Show a file", + tone: "tool", + structuredPayload: { + type: "dynamic_tool", + status: "completed", + toolName: "show_file", + output: { + path: "/tmp/answers.md", + byteSize: 12, + mediaType: "text/markdown", + line: 3, + contents: SECRET, + message: "Shown in the file viewer. Do not read or quote the file.", + }, + }, + }, + } as never, + ]); + expect(targets).toEqual([{ id: "show-1", path: "/tmp/answers.md", line: 3 }]); + expect(JSON.stringify(targets)).not.toContain(SECRET); + }); +}); + +describe("shownFilesToOpen", () => { + const files: ReadonlyArray = [ + { id: "show-1", path: "/tmp/answers.md" }, + { id: "show-2", path: "/tmp/notes.md", line: 2 }, + ]; + const nextKey = "show-1\t/tmp/answers.md\t\nshow-2\t/tmp/notes.md\t2"; + + it("does not open files already on screen, including after a thread change", () => { + expect( + shownFilesToOpen({ threadKey: "env/thread", previous: null, nextKey, files }).open, + ).toEqual([]); + const baseline = shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey, + files, + }).baseline; + expect( + shownFilesToOpen({ threadKey: "env/other", previous: baseline, nextKey, files }).open, + ).toEqual([]); + }); + + it("opens only a file that completed after the thread was on screen", () => { + const previous = shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey: "show-1\t/tmp/answers.md\t", + files: files.slice(0, 1), + }).baseline; + expect(shownFilesToOpen({ threadKey: "env/thread", previous, nextKey, files }).open).toEqual([ + { id: "show-2", path: "/tmp/notes.md", line: 2 }, + ]); + }); +}); diff --git a/apps/web/src/components/chat/shownFileOpen.ts b/apps/web/src/components/chat/shownFileOpen.ts new file mode 100644 index 0000000000000..a738241eca4cc --- /dev/null +++ b/apps/web/src/components/chat/shownFileOpen.ts @@ -0,0 +1,53 @@ +import { showFileFromToolItem } from "@t3tools/shared/toolOutput"; + +import type { TimelineEntry } from "../../session-logic"; + +export interface ShownFileTarget { + readonly id: string; + readonly path: string; + readonly line?: number; +} + +export function shownFileTargets( + entries: ReadonlyArray, +): ReadonlyArray { + const targets: ShownFileTarget[] = []; + for (const entry of entries) { + if (entry.kind !== "work") continue; + const item = entry.entry.structuredPayload; + if (item?.type !== "dynamic_tool" || item.status !== "completed") continue; + const shown = showFileFromToolItem(item); + if (shown === undefined) continue; + targets.push({ + id: entry.id, + path: shown.path, + ...(shown.line === undefined ? {} : { line: shown.line }), + }); + } + return targets; +} + +export function shownFileKey(files: ReadonlyArray): string { + return files.map((file) => `${file.id}\t${file.path}\t${file.line ?? ""}`).join("\n"); +} + +export function shownFilesToOpen(input: { + readonly threadKey: string; + readonly previous: string | null; + readonly nextKey: string; + readonly files: ReadonlyArray; +}): { readonly baseline: string; readonly open: ReadonlyArray } { + const baseline = `${input.threadKey}\n${input.nextKey}`; + if (input.previous === null || !input.previous.startsWith(`${input.threadKey}\n`)) { + return { baseline, open: [] }; + } + if (input.previous === baseline) return { baseline, open: [] }; + const seen = new Set( + input.previous + .slice(input.threadKey.length + 1) + .split("\n") + .filter((row) => row.length > 0) + .map((row) => row.slice(0, row.indexOf("\t"))), + ); + return { baseline, open: input.files.filter((file) => !seen.has(file.id)) }; +} diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 107b0bc652555..3cec41a44476a 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -481,6 +481,9 @@ export function summarizeT3ToolCalls( case "send-to-user": label = phrase("Sent", "send", quantity(selected.length, "message")); break; + case "show-file": + label = phrase("Showed", "show", quantity(selected.length, "file")); + break; case "capabilities": label = phrase("Checked", "check", `orchestration capabilities ${times}`); break; diff --git a/packages/shared/package.json b/packages/shared/package.json index 601e520bd24af..d0be9afb21d53 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -159,6 +159,10 @@ "types": "./src/htmlRender.ts", "import": "./src/htmlRender.ts" }, + "./showFile": { + "types": "./src/showFile.ts", + "import": "./src/showFile.ts" + }, "./favicon": { "types": "./src/favicon.ts", "import": "./src/favicon.ts" diff --git a/packages/shared/src/showFile.ts b/packages/shared/src/showFile.ts new file mode 100644 index 0000000000000..8407d07a700f3 --- /dev/null +++ b/packages/shared/src/showFile.ts @@ -0,0 +1,75 @@ +import { hostPreviewMimeTypeFromExtension } from "./filePreview.ts"; + +export const SHOW_FILE_TOOL_NAME = "show_file"; +export const SHOW_FILE_MAX_PATH_LENGTH = 4096; + +export interface ShowFileReference { + readonly path: string; + readonly byteSize: number; + readonly mediaType: string; + readonly line?: number; +} + +const TEXT_MEDIA_TYPE_BY_EXTENSION: Readonly> = { + css: "text/css", + csv: "text/csv", + go: "text/x-go", + js: "text/javascript", + jsx: "text/jsx", + json: "application/json", + markdown: "text/markdown", + md: "text/markdown", + py: "text/x-python", + rs: "text/rust", + sh: "text/x-shellscript", + toml: "application/toml", + ts: "text/typescript", + tsx: "text/tsx", + tsv: "text/tab-separated-values", + txt: "text/plain", + xml: "text/xml", + yaml: "text/yaml", + yml: "text/yaml", +}; + +const MEDIA_TYPE = /^[\w.+-]+\/[\w.+-]+$/; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +export function mediaTypeForPath(path: string): string { + const base = path.split(/[/\\]/).pop() ?? path; + const dot = base.lastIndexOf("."); + if (dot <= 0) return "application/octet-stream"; + const extension = base.slice(dot).toLowerCase(); + return ( + hostPreviewMimeTypeFromExtension(extension) ?? + TEXT_MEDIA_TYPE_BY_EXTENSION[extension.slice(1)] ?? + "application/octet-stream" + ); +} + +export function readShowFileReference(value: unknown): ShowFileReference | undefined { + if (!isRecord(value)) return undefined; + const source = isRecord(value.showFile) ? value.showFile : value; + const { path, byteSize, mediaType, line } = source; + if ( + typeof path !== "string" || + path.length === 0 || + path.length > SHOW_FILE_MAX_PATH_LENGTH || + path.includes("\0") || + /[\r\n]/.test(path) || + typeof byteSize !== "number" || + !Number.isSafeInteger(byteSize) || + byteSize < 0 || + typeof mediaType !== "string" || + !MEDIA_TYPE.test(mediaType) + ) { + return undefined; + } + const reference: ShowFileReference = { path, byteSize, mediaType }; + return typeof line === "number" && Number.isSafeInteger(line) && line >= 1 && line <= 1_000_000 + ? { ...reference, line } + : reference; +} diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index a813585b27a6e..f1c95a9fee408 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -71,7 +71,8 @@ export type T3McpToolSummaryAction = | "device" | "html-preview" | "html-render" - | "send-to-user"; + | "send-to-user" + | "show-file"; export interface T3McpToolDefinition { readonly displayName: string; @@ -378,6 +379,7 @@ const T3_MCP_TOOLS: Readonly> = { html_preview: tool(["Preview", "Previewing", "Previewed", "an HTML page"], "html-preview"), html_render: tool(["Render", "Rendering", "Rendered", "an HTML page"], "html-render"), send_to_user: tool(["Send", "Sending", "Sent", "a message"], "send-to-user"), + show_file: tool(["Show", "Showing", "Showed", "a file"], "show-file"), }; export const T3_MCP_TOOL_NAMES: ReadonlySet = new Set(Object.keys(T3_MCP_TOOLS)); diff --git a/packages/shared/src/toolOutput.test.ts b/packages/shared/src/toolOutput.test.ts index 7a5f736624da7..0afa9c0cab6fd 100644 --- a/packages/shared/src/toolOutput.test.ts +++ b/packages/shared/src/toolOutput.test.ts @@ -6,6 +6,7 @@ import { mcpToolResultOutput, SEND_TO_USER_MAX_LENGTH, sentMessageFromToolItem, + showFileFromToolItem, toolOutputImages, toolOutputIndicatesFailure, } from "./toolOutput.ts"; @@ -25,6 +26,33 @@ describe("compactDynamicToolOutput", () => { } }); + it("keeps a shown file's path, size, and type and drops its bytes", () => { + const secret = "SECRET_FILE_BYTES_9f3a"; + const output = { + path: "/tmp/answers.md", + byteSize: secret.length, + mediaType: "text/markdown", + line: 3, + contents: secret, + message: "Shown in the file viewer. Do not read or quote the file.", + }; + expect(compactDynamicToolOutput(output)).toEqual({ + showFile: { + path: "/tmp/answers.md", + byteSize: secret.length, + mediaType: "text/markdown", + line: 3, + }, + }); + expect(JSON.stringify(compactDynamicToolOutput(output))).not.toContain(secret); + expect(showFileFromToolItem({ toolName: "show_file", output })).toEqual({ + path: "/tmp/answers.md", + byteSize: secret.length, + mediaType: "text/markdown", + line: 3, + }); + expect(showFileFromToolItem({ toolName: "read_file", output })).toBeUndefined(); + }); it("keeps a send_to_user message up to its limit, even in 3-byte characters", () => { const longest = "界".repeat(SEND_TO_USER_MAX_LENGTH); for (const sentMessage of ["Draft:\n\n> Hi Sam,", longest]) { diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.ts index 0c8d7c4a33492..cf5d18b6c1612 100644 --- a/packages/shared/src/toolOutput.ts +++ b/packages/shared/src/toolOutput.ts @@ -9,6 +9,7 @@ import { readHtmlRenderReference, type HtmlRenderReference, } from "./htmlRender.ts"; +import { readShowFileReference, SHOW_FILE_TOOL_NAME, type ShowFileReference } from "./showFile.ts"; import { claudeMcpToolName, MCP_APP_OUTPUT_KEY, @@ -49,6 +50,7 @@ interface CompactToolOutput { scheduledTaskId?: string; status?: "rolled_back"; htmlRender?: HtmlRenderReference; + showFile?: ShowFileReference; [MCP_APP_OUTPUT_KEY]?: McpAppReference; thread?: { threadId: string }; threads?: Array<{ threadId?: string; status?: "rolled_back" }>; @@ -148,6 +150,8 @@ export function compactDynamicToolOutput(value: unknown): CompactToolOutput | un } const htmlRender = readHtmlRenderReference(data.htmlRender); if (htmlRender !== undefined) output.htmlRender = htmlRender; + const showFile = readShowFileReference(data); + if (showFile !== undefined) output.showFile = showFile; const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]); if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp; const nestedThreadId = Predicate.isObject(data.thread) @@ -217,6 +221,20 @@ export function htmlRenderFromToolItem(item: { } /** The text `send_to_user` showed the user, which clients render as the agent's own words. */ +export function showFileFromToolItem(item: { + readonly toolName: string | null | undefined; + readonly output?: unknown; +}): ShowFileReference | undefined { + if ( + item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME && + resolveT3McpToolId(item.toolName) !== SHOW_FILE_TOOL_NAME + ) { + return undefined; + } + const output = compactDynamicToolOutput(item.output); + return output?.isError ? undefined : output?.showFile; +} + export function sentMessageFromToolItem(item: { readonly toolName: string | null | undefined; readonly output?: unknown; From 1fae232d515318905e4d050baf3dc7bbc5b4d0c0 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:40:18 +0000 Subject: [PATCH 2/4] fix(web): open a shown file only when it just completed History loading, an older page, and an expanded work group looked like new show_file results, so old files took the panel. A completion now opens only when it is newer than what is already on screen. show_file stays in the live window, Claude's read-only sandbox can call it, and the result is a showFile object so another tool's path and size cannot open the viewer. Model: grok-4.7 Task: CLO-898 show a file without reading it into context Agent: magpie Lane: magpie Harness: t3/codex Model-family: Grok Model-generation: 4.7 Skills-SHA: 0540352af0d6f43bdeea39a8c4aad4660ab0ec55 Co-Authored-By: Grok 4.7 --- .../mcp/toolkits/showFile/handlers.test.ts | 22 ++-- .../src/mcp/toolkits/showFile/handlers.ts | 10 +- .../server/src/mcp/toolkits/showFile/tools.ts | 10 +- .../Adapters/ClaudeAdapterV2.test.ts | 2 + .../Adapters/ClaudeAdapterV2.ts | 1 + .../orchestration-v2/ProjectionStore.test.ts | 1 + .../src/orchestration-v2/ProjectionStore.ts | 2 +- .../src/provider/AgentContextBudget.test.ts | 3 +- .../src/provider/agentContextBudget.json | 2 +- .../src/components/chat/MessagesTimeline.tsx | 39 ++++-- .../src/components/chat/shownFileOpen.test.ts | 119 +++++++++++++++--- apps/web/src/components/chat/shownFileOpen.ts | 40 ++++-- packages/shared/src/showFile.ts | 4 +- packages/shared/src/toolOutput.test.ts | 19 ++- packages/shared/src/toolOutput.ts | 2 +- 15 files changed, 219 insertions(+), 57 deletions(-) diff --git a/apps/server/src/mcp/toolkits/showFile/handlers.test.ts b/apps/server/src/mcp/toolkits/showFile/handlers.test.ts index 9336a3db131ea..a266c2e466ac6 100644 --- a/apps/server/src/mcp/toolkits/showFile/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/showFile/handlers.test.ts @@ -63,26 +63,30 @@ it.effect("returns path, size, and type and does not put file bytes in the resul const shown = yield* call({ path: filePath, line: 4 }); expect(shown).toEqual({ - path: filePath, - byteSize: SENTINEL.length, - mediaType: "text/markdown", - line: 4, + showFile: { + path: filePath, + byteSize: SENTINEL.length, + mediaType: "text/markdown", + line: 4, + }, message: "Shown in the file viewer. Do not read or quote the file.", }); expect(JSON.stringify(shown)).not.toContain(SENTINEL); - expect(Object.keys(shown as object).sort()).toEqual([ + expect(Object.keys(shown as object).sort()).toEqual(["message", "showFile"]); + expect(Object.keys((shown as { showFile: object }).showFile).sort()).toEqual([ "byteSize", "line", "mediaType", - "message", "path", ]); const relative = yield* call({ path: "answers.md" }); expect(relative).toMatchObject({ - path: filePath, - byteSize: SENTINEL.length, - mediaType: "text/markdown", + showFile: { + path: filePath, + byteSize: SENTINEL.length, + mediaType: "text/markdown", + }, }); expect(JSON.stringify(relative)).not.toContain(SENTINEL); diff --git a/apps/server/src/mcp/toolkits/showFile/handlers.ts b/apps/server/src/mcp/toolkits/showFile/handlers.ts index 211bb5e86d668..989fb14e5449c 100644 --- a/apps/server/src/mcp/toolkits/showFile/handlers.ts +++ b/apps/server/src/mcp/toolkits/showFile/handlers.ts @@ -49,10 +49,12 @@ const showFile = Effect.fn("ShowFile.stat")(function* (input: { return yield* invalid("That file cannot be shown."); } return { - path: resolved, - byteSize, - mediaType: mediaTypeForPath(resolved), - ...(input.line === undefined ? {} : { line: input.line }), + showFile: { + path: resolved, + byteSize, + mediaType: mediaTypeForPath(resolved), + ...(input.line === undefined ? {} : { line: input.line }), + }, message: "Shown in the file viewer. Do not read or quote the file.", }; }); diff --git a/apps/server/src/mcp/toolkits/showFile/tools.ts b/apps/server/src/mcp/toolkits/showFile/tools.ts index f723c6ceb53e4..04b7281cb5d36 100644 --- a/apps/server/src/mcp/toolkits/showFile/tools.ts +++ b/apps/server/src/mcp/toolkits/showFile/tools.ts @@ -30,10 +30,12 @@ const ShowFileTool = Tool.make(SHOW_FILE_TOOL_NAME, { ), }), success: Schema.Struct({ - path: Schema.String, - byteSize: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), - mediaType: Schema.String, - line: Schema.optional(Schema.Int), + showFile: Schema.Struct({ + path: Schema.String, + byteSize: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + mediaType: Schema.String, + line: Schema.optional(Schema.Int), + }), message: Schema.String, }), failure: OrchestratorMcpFailure, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index fda061b665d4f..6b86813237373 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -92,6 +92,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts"; import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts"; import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts"; +import { ShowFileToolkit } from "../../mcp/toolkits/showFile/tools.ts"; import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts"; import { ThemeToolkit } from "../../mcp/toolkits/theme/tools.ts"; import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts"; @@ -794,6 +795,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { ...Object.values(PreviewControlsToolkit.tools), ...Object.values(HtmlToolkit.tools), ...Object.values(MessageToolkit.tools), + ...Object.values(ShowFileToolkit.tools), ] .filter((tool) => Context.get(tool.annotations, Tool.Readonly)) .map((tool) => `mcp__t3-code__${tool.name}`) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 0f9fc2e828457..ea50da26ff39f 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2543,6 +2543,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__html_preview", "mcp__t3-code__html_render", "mcp__t3-code__send_to_user", + "mcp__t3-code__show_file", ]; // request_secret can wait an hour; exceed Claude's default 60 s timeout. diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 7d02761ed644e..617769a4f899d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -4702,6 +4702,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { { toolName: "view_image", viewedImagePath: "/repo/screenshot.png" }, { toolName: "mcp__docs__chart", output: { [MCP_APP_OUTPUT_KEY]: { uri: "ui://chart" } } }, { toolName: "mcp__t3-code__send_to_user" }, + { toolName: "mcp__t3-code__show_file" }, // OpenCode Code Mode reports a nested send_to_user call as one `execute` item. { toolName: "execute", output: JSON.stringify({ sentMessage: "Draft" }) }, ]) { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 8402be3e50058..06ff339bac6b5 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -2251,7 +2251,7 @@ const INLINE_WORK_OUTPUT = new RegExp( "i", ); const TOOL_NAME_PREFIX = /"toolName":"/i; -const INLINE_TOOL_NAME = /(?:delegate.task|send.to.user)"/is; +const INLINE_TOOL_NAME = /(?:delegate.task|send.to.user|show.file)"/is; const isInlineWorkOutput = (payloadJson: string) => { if (INLINE_WORK_OUTPUT.test(payloadJson)) return true; diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index ae5c4bc635a45..2d47283dac50a 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -120,7 +120,7 @@ const layerAdvertisedTools = McpHttpServer.layerTools.pipe( ); // Claude Code loads these tools up front instead of behind ToolSearch, outside this budget. -it.effect("only request_secret and send_to_user ask Claude Code to load them up front", () => +it.effect("request_secret, send_to_user, and show_file ask Claude Code to load them up front", () => Effect.gen(function* () { const mcp = yield* McpServer.McpServer; const alwaysLoad = mcp.tools @@ -129,6 +129,7 @@ it.effect("only request_secret and send_to_user ask Claude Code to load them up expect(alwaysLoad).toEqual([ ["request_secret", { "anthropic/alwaysLoad": true }], ["send_to_user", { "anthropic/alwaysLoad": true }], + ["show_file", { "anthropic/alwaysLoad": true }], ]); }).pipe(Effect.provide(layerAdvertisedTools)), ); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index ee70abac0767d..c2084d57162bb 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 55240 + "mcpToolListJsonBytes": 55827 } diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index fcb5081caf6df..15b3d5e79b6a8 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -21,7 +21,12 @@ import { } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { useRightPanelStore } from "../../rightPanelStore"; -import { shownFileKey, shownFileTargets, shownFilesToOpen } from "./shownFileOpen"; +import { + latestTimelineCreatedAt, + shownFileKey, + shownFileTargets, + shownFilesToOpen, +} from "./shownFileOpen"; import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; @@ -42,6 +47,7 @@ import { useLayoutEffect, useEffect, useEffectEvent, + useMemo, useRef, useState, type ReactNode, @@ -485,23 +491,40 @@ const ConversationTimeline = memo(function ConversationTimeline({ setExpandedAttemptIds(paintedExpandedAttemptIds); } const citationThreadRef = parseScopedThreadKey(routeThreadKey); - const shownFiles = shownFileTargets(timelineEntries); - const shownFileSignature = shownFileKey(shownFiles); + const shownFilePlan = useMemo(() => { + const files = shownFileTargets(timelineEntries); + return { + files, + signature: shownFileKey(files), + latestCreatedAt: latestTimelineCreatedAt(timelineEntries), + entryCount: timelineEntries.length, + }; + }, [timelineEntries]); + const shownFilesRef = useRef(shownFilePlan.files); + shownFilesRef.current = shownFilePlan.files; const shownFileBaseline = useRef(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a show_file completion opens the existing file viewer with a panel state update; the viewer reads the file after paint, and files already on screen stay put useEffect(() => { const plan = shownFilesToOpen({ threadKey: routeThreadKey, previous: shownFileBaseline.current, - nextKey: shownFileSignature, - files: shownFiles, + nextKey: shownFilePlan.signature, + files: shownFilesRef.current, + entryCount: shownFilePlan.entryCount, + latestCreatedAt: shownFilePlan.latestCreatedAt, }); shownFileBaseline.current = plan.baseline; - if (citationThreadRef === null) return; + const threadRef = parseScopedThreadKey(routeThreadKey); + if (threadRef === null) return; for (const file of plan.open) { - useRightPanelStore.getState().openFile(citationThreadRef, file.path, file.line); + useRightPanelStore.getState().openFile(threadRef, file.path, file.line); } - }, [citationThreadRef, routeThreadKey, shownFileSignature, shownFiles]); + }, [ + routeThreadKey, + shownFilePlan.entryCount, + shownFilePlan.latestCreatedAt, + shownFilePlan.signature, + ]); const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined); const [minimapStripMap] = useState(() => new Map()); const normalizedFindQuery = findQuery.trim(); diff --git a/apps/web/src/components/chat/shownFileOpen.test.ts b/apps/web/src/components/chat/shownFileOpen.test.ts index 458cb25644a93..183d187fdc8d9 100644 --- a/apps/web/src/components/chat/shownFileOpen.test.ts +++ b/apps/web/src/components/chat/shownFileOpen.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vite-plus/test"; -import { shownFileTargets, shownFilesToOpen, type ShownFileTarget } from "./shownFileOpen"; +import { + shownFileKey, + shownFileTargets, + shownFilesToOpen, + type ShownFileTarget, +} from "./shownFileOpen"; const SECRET = "SECRET_FILE_BYTES_9f3a"; @@ -21,53 +26,131 @@ describe("shownFileTargets", () => { status: "completed", toolName: "show_file", output: { - path: "/tmp/answers.md", - byteSize: 12, - mediaType: "text/markdown", - line: 3, - contents: SECRET, + showFile: { + path: "/tmp/answers.md", + byteSize: 12, + mediaType: "text/markdown", + line: 3, + contents: SECRET, + }, message: "Shown in the file viewer. Do not read or quote the file.", }, }, }, } as never, ]); - expect(targets).toEqual([{ id: "show-1", path: "/tmp/answers.md", line: 3 }]); + expect(targets).toEqual([ + { id: "show-1", path: "/tmp/answers.md", createdAt: "2026-01-01T00:00:00.000Z", line: 3 }, + ]); expect(JSON.stringify(targets)).not.toContain(SECRET); }); }); describe("shownFilesToOpen", () => { const files: ReadonlyArray = [ - { id: "show-1", path: "/tmp/answers.md" }, - { id: "show-2", path: "/tmp/notes.md", line: 2 }, + { id: "show-1", path: "/tmp/answers.md", createdAt: "2026-01-02T00:00:00.000Z" }, + { id: "show-2", path: "/tmp/notes.md", createdAt: "2026-01-03T00:00:00.000Z", line: 2 }, ]; - const nextKey = "show-1\t/tmp/answers.md\t\nshow-2\t/tmp/notes.md\t2"; + const nextKey = shownFileKey(files); it("does not open files already on screen, including after a thread change", () => { expect( - shownFilesToOpen({ threadKey: "env/thread", previous: null, nextKey, files }).open, + shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey, + files, + entryCount: 2, + latestCreatedAt: "2026-01-03T00:00:00.000Z", + }).open, ).toEqual([]); const baseline = shownFilesToOpen({ threadKey: "env/thread", previous: null, nextKey, files, + entryCount: 2, + latestCreatedAt: "2026-01-03T00:00:00.000Z", }).baseline; expect( - shownFilesToOpen({ threadKey: "env/other", previous: baseline, nextKey, files }).open, + shownFilesToOpen({ + threadKey: "env/other", + previous: baseline, + nextKey, + files, + entryCount: 2, + latestCreatedAt: "2026-01-03T00:00:00.000Z", + }).open, ).toEqual([]); }); - it("opens only a file that completed after the thread was on screen", () => { + it("does not open history that arrives after an empty timeline", () => { + const pending = shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey: "", + files: [], + entryCount: 0, + latestCreatedAt: "", + }).baseline; + expect( + shownFilesToOpen({ + threadKey: "env/thread", + previous: pending, + nextKey, + files, + entryCount: 2, + latestCreatedAt: "2026-01-03T00:00:00.000Z", + }).open, + ).toEqual([]); + }); + + it("does not open an older file that shows up after the thread is open", () => { + const first = files.slice(0, 1); const previous = shownFilesToOpen({ threadKey: "env/thread", previous: null, - nextKey: "show-1\t/tmp/answers.md\t", - files: files.slice(0, 1), + nextKey: shownFileKey(first), + files: first, + entryCount: 1, + latestCreatedAt: "2026-01-02T00:00:00.000Z", }).baseline; - expect(shownFilesToOpen({ threadKey: "env/thread", previous, nextKey, files }).open).toEqual([ - { id: "show-2", path: "/tmp/notes.md", line: 2 }, - ]); + const older: ShownFileTarget = { + id: "show-old", + path: "/tmp/old.md", + createdAt: "2026-01-01T00:00:00.000Z", + }; + expect( + shownFilesToOpen({ + threadKey: "env/thread", + previous, + nextKey: shownFileKey([older, ...first]), + files: [older, ...first], + entryCount: 2, + latestCreatedAt: "2026-01-02T00:00:00.000Z", + }).open, + ).toEqual([]); + }); + + it("opens only a file that completed after the newest item already on screen", () => { + const first = files.slice(0, 1); + const previous = shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey: shownFileKey(first), + files: first, + entryCount: 1, + latestCreatedAt: "2026-01-02T00:00:00.000Z", + }).baseline; + expect( + shownFilesToOpen({ + threadKey: "env/thread", + previous, + nextKey, + files, + entryCount: 2, + latestCreatedAt: "2026-01-03T00:00:00.000Z", + }).open, + ).toEqual([files[1]]); }); }); diff --git a/apps/web/src/components/chat/shownFileOpen.ts b/apps/web/src/components/chat/shownFileOpen.ts index a738241eca4cc..12e9a72327ad5 100644 --- a/apps/web/src/components/chat/shownFileOpen.ts +++ b/apps/web/src/components/chat/shownFileOpen.ts @@ -5,6 +5,7 @@ import type { TimelineEntry } from "../../session-logic"; export interface ShownFileTarget { readonly id: string; readonly path: string; + readonly createdAt: string; readonly line?: number; } @@ -21,14 +22,25 @@ export function shownFileTargets( targets.push({ id: entry.id, path: shown.path, + createdAt: entry.createdAt, ...(shown.line === undefined ? {} : { line: shown.line }), }); } return targets; } +export function latestTimelineCreatedAt(entries: ReadonlyArray<{ createdAt: string }>): string { + let latest = ""; + for (const entry of entries) { + if (entry.createdAt > latest) latest = entry.createdAt; + } + return latest; +} + export function shownFileKey(files: ReadonlyArray): string { - return files.map((file) => `${file.id}\t${file.path}\t${file.line ?? ""}`).join("\n"); + return files + .map((file) => `${file.id}\t${file.path}\t${file.line ?? ""}\t${file.createdAt}`) + .join("\n"); } export function shownFilesToOpen(input: { @@ -36,18 +48,32 @@ export function shownFilesToOpen(input: { readonly previous: string | null; readonly nextKey: string; readonly files: ReadonlyArray; + readonly entryCount: number; + readonly latestCreatedAt: string; }): { readonly baseline: string; readonly open: ReadonlyArray } { - const baseline = `${input.threadKey}\n${input.nextKey}`; - if (input.previous === null || !input.previous.startsWith(`${input.threadKey}\n`)) { - return { baseline, open: [] }; + const pending = `${input.threadKey}\n`; + if (input.entryCount === 0) return { baseline: pending, open: [] }; + const ready = `${input.threadKey}\n${input.latestCreatedAt}\n${input.nextKey}`; + if ( + input.previous === null || + input.previous === pending || + !input.previous.startsWith(`${input.threadKey}\n`) + ) { + return { baseline: ready, open: [] }; } - if (input.previous === baseline) return { baseline, open: [] }; + const first = input.threadKey.length; + const second = input.previous.indexOf("\n", first + 1); + if (second === -1) return { baseline: ready, open: [] }; + const watermark = input.previous.slice(first + 1, second); const seen = new Set( input.previous - .slice(input.threadKey.length + 1) + .slice(second + 1) .split("\n") .filter((row) => row.length > 0) .map((row) => row.slice(0, row.indexOf("\t"))), ); - return { baseline, open: input.files.filter((file) => !seen.has(file.id)) }; + return { + baseline: ready, + open: input.files.filter((file) => !seen.has(file.id) && file.createdAt > watermark), + }; } diff --git a/packages/shared/src/showFile.ts b/packages/shared/src/showFile.ts index 8407d07a700f3..307a45f4e6657 100644 --- a/packages/shared/src/showFile.ts +++ b/packages/shared/src/showFile.ts @@ -51,8 +51,8 @@ export function mediaTypeForPath(path: string): string { } export function readShowFileReference(value: unknown): ShowFileReference | undefined { - if (!isRecord(value)) return undefined; - const source = isRecord(value.showFile) ? value.showFile : value; + if (!isRecord(value) || !isRecord(value.showFile)) return undefined; + const source = value.showFile; const { path, byteSize, mediaType, line } = source; if ( typeof path !== "string" || diff --git a/packages/shared/src/toolOutput.test.ts b/packages/shared/src/toolOutput.test.ts index 0afa9c0cab6fd..660916a8f9578 100644 --- a/packages/shared/src/toolOutput.test.ts +++ b/packages/shared/src/toolOutput.test.ts @@ -28,12 +28,16 @@ describe("compactDynamicToolOutput", () => { it("keeps a shown file's path, size, and type and drops its bytes", () => { const secret = "SECRET_FILE_BYTES_9f3a"; - const output = { + const showFile = { path: "/tmp/answers.md", byteSize: secret.length, mediaType: "text/markdown", line: 3, contents: secret, + }; + const output = { + showFile, + contents: secret, message: "Shown in the file viewer. Do not read or quote the file.", }; expect(compactDynamicToolOutput(output)).toEqual({ @@ -45,12 +49,25 @@ describe("compactDynamicToolOutput", () => { }, }); expect(JSON.stringify(compactDynamicToolOutput(output))).not.toContain(secret); + expect(compactDynamicToolOutput({ ...showFile, contents: secret })).toBeUndefined(); expect(showFileFromToolItem({ toolName: "show_file", output })).toEqual({ path: "/tmp/answers.md", byteSize: secret.length, mediaType: "text/markdown", line: 3, }); + expect(showFileFromToolItem({ toolName: "execute", output })).toEqual({ + path: "/tmp/answers.md", + byteSize: secret.length, + mediaType: "text/markdown", + line: 3, + }); + expect( + showFileFromToolItem({ + toolName: "execute", + output: { path: "/tmp/answers.md", byteSize: 1, mediaType: "text/plain", contents: secret }, + }), + ).toBeUndefined(); expect(showFileFromToolItem({ toolName: "read_file", output })).toBeUndefined(); }); it("keeps a send_to_user message up to its limit, even in 3-byte characters", () => { diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.ts index cf5d18b6c1612..812eb3b8f397d 100644 --- a/packages/shared/src/toolOutput.ts +++ b/packages/shared/src/toolOutput.ts @@ -220,7 +220,6 @@ export function htmlRenderFromToolItem(item: { return output?.isError ? undefined : output?.htmlRender; } -/** The text `send_to_user` showed the user, which clients render as the agent's own words. */ export function showFileFromToolItem(item: { readonly toolName: string | null | undefined; readonly output?: unknown; @@ -235,6 +234,7 @@ export function showFileFromToolItem(item: { return output?.isError ? undefined : output?.showFile; } +/** The text `send_to_user` showed the user, which clients render as the agent's own words. */ export function sentMessageFromToolItem(item: { readonly toolName: string | null | undefined; readonly output?: unknown; From 13c1b15d57746347c3b9309956ed881d2d78e26d Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:07:47 +0000 Subject: [PATCH 3/4] fix(web): open a file shown in the same millisecond it started A tool row's createdAt is its startedAt and never moves when the tool finishes, so a show_file that starts in the same millisecond as something already painted completed with createdAt equal to the watermark and the viewer never opened. The open check now uses the completion time. Co-Authored-By: Claude Fable 5.2 --- .../src/components/chat/shownFileOpen.test.ts | 34 +++++++++++++++++++ apps/web/src/components/chat/shownFileOpen.ts | 6 +++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/shownFileOpen.test.ts b/apps/web/src/components/chat/shownFileOpen.test.ts index 183d187fdc8d9..ba42a64fa6c1c 100644 --- a/apps/web/src/components/chat/shownFileOpen.test.ts +++ b/apps/web/src/components/chat/shownFileOpen.test.ts @@ -1,3 +1,4 @@ +import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import { @@ -24,6 +25,7 @@ describe("shownFileTargets", () => { structuredPayload: { type: "dynamic_tool", status: "completed", + completedAt: DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"), toolName: "show_file", output: { showFile: { @@ -132,6 +134,38 @@ describe("shownFilesToOpen", () => { ).toEqual([]); }); + it("opens a file that completes in the same millisecond it started", () => { + const sameTick = "2026-01-02T00:00:00.000Z"; + const running: ShownFileTarget = { + id: "reasoning-1", + path: "/tmp/unused.md", + createdAt: sameTick, + }; + const previous = shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey: shownFileKey([running]), + files: [], + entryCount: 1, + latestCreatedAt: sameTick, + }).baseline; + const completed: ShownFileTarget = { + id: "show-1", + path: "/tmp/answers.md", + createdAt: "2026-01-02T00:00:00.001Z", + }; + expect( + shownFilesToOpen({ + threadKey: "env/thread", + previous, + nextKey: shownFileKey([completed]), + files: [completed], + entryCount: 1, + latestCreatedAt: sameTick, + }).open, + ).toEqual([completed]); + }); + it("opens only a file that completed after the newest item already on screen", () => { const first = files.slice(0, 1); const previous = shownFilesToOpen({ diff --git a/apps/web/src/components/chat/shownFileOpen.ts b/apps/web/src/components/chat/shownFileOpen.ts index 12e9a72327ad5..25cf2a4b28dfd 100644 --- a/apps/web/src/components/chat/shownFileOpen.ts +++ b/apps/web/src/components/chat/shownFileOpen.ts @@ -1,3 +1,4 @@ +import * as DateTime from "effect/DateTime"; import { showFileFromToolItem } from "@t3tools/shared/toolOutput"; import type { TimelineEntry } from "../../session-logic"; @@ -22,7 +23,10 @@ export function shownFileTargets( targets.push({ id: entry.id, path: shown.path, - createdAt: entry.createdAt, + createdAt: + item.completedAt === null || item.completedAt === undefined + ? entry.createdAt + : DateTime.formatIso(item.completedAt), ...(shown.line === undefined ? {} : { line: shown.line }), }); } From cd35b71e76e8822ea37f073bfc7962000b92d309 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:21:46 +0000 Subject: [PATCH 4/4] fix(web): open a slow show_file that finishes behind a newer row The watermark was the newest timeline start time, so a show_file that started before a later row never opened when it completed earlier than that row's start. The watermark is now the newest completion. Co-Authored-By: Claude Fable 5.2 --- .../src/components/chat/MessagesTimeline.tsx | 4 +-- .../src/components/chat/shownFileOpen.test.ts | 28 +++++++++++++++++++ apps/web/src/components/chat/shownFileOpen.ts | 7 +++-- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 15b3d5e79b6a8..edc197e9e1590 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -22,7 +22,7 @@ import { import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { useRightPanelStore } from "../../rightPanelStore"; import { - latestTimelineCreatedAt, + latestShownFileCreatedAt, shownFileKey, shownFileTargets, shownFilesToOpen, @@ -496,7 +496,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ return { files, signature: shownFileKey(files), - latestCreatedAt: latestTimelineCreatedAt(timelineEntries), + latestCreatedAt: latestShownFileCreatedAt(files), entryCount: timelineEntries.length, }; }, [timelineEntries]); diff --git a/apps/web/src/components/chat/shownFileOpen.test.ts b/apps/web/src/components/chat/shownFileOpen.test.ts index ba42a64fa6c1c..2fab446043ddb 100644 --- a/apps/web/src/components/chat/shownFileOpen.test.ts +++ b/apps/web/src/components/chat/shownFileOpen.test.ts @@ -166,6 +166,34 @@ describe("shownFilesToOpen", () => { ).toEqual([completed]); }); + it("opens a file that finishes after one which completed earlier, even though a row started later", () => { + const first = files[0]!; + const previous = shownFilesToOpen({ + threadKey: "env/thread", + previous: null, + nextKey: shownFileKey([first]), + files: [first], + entryCount: 2, + latestCreatedAt: first.createdAt, + }).baseline; + const slow: ShownFileTarget = { + id: "show-slow", + path: "/tmp/slow.md", + createdAt: "2026-01-02T00:00:00.500Z", + }; + expect(slow.createdAt > first.createdAt).toBe(true); + expect( + shownFilesToOpen({ + threadKey: "env/thread", + previous, + nextKey: shownFileKey([first, slow]), + files: [first, slow], + entryCount: 3, + latestCreatedAt: slow.createdAt, + }).open, + ).toEqual([slow]); + }); + it("opens only a file that completed after the newest item already on screen", () => { const first = files.slice(0, 1); const previous = shownFilesToOpen({ diff --git a/apps/web/src/components/chat/shownFileOpen.ts b/apps/web/src/components/chat/shownFileOpen.ts index 25cf2a4b28dfd..e192e6a169402 100644 --- a/apps/web/src/components/chat/shownFileOpen.ts +++ b/apps/web/src/components/chat/shownFileOpen.ts @@ -33,10 +33,11 @@ export function shownFileTargets( return targets; } -export function latestTimelineCreatedAt(entries: ReadonlyArray<{ createdAt: string }>): string { +/** Newest completion, so a slow tool is not hidden behind a row that started later. */ +export function latestShownFileCreatedAt(files: ReadonlyArray<{ createdAt: string }>): string { let latest = ""; - for (const entry of entries) { - if (entry.createdAt > latest) latest = entry.createdAt; + for (const file of files) { + if (file.createdAt > latest) latest = file.createdAt; } return latest; }