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..a266c2e466ac6 --- /dev/null +++ b/apps/server/src/mcp/toolkits/showFile/handlers.test.ts @@ -0,0 +1,97 @@ +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({ + 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(["message", "showFile"]); + expect(Object.keys((shown as { showFile: object }).showFile).sort()).toEqual([ + "byteSize", + "line", + "mediaType", + "path", + ]); + + const relative = yield* call({ path: "answers.md" }); + expect(relative).toMatchObject({ + showFile: { + 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..989fb14e5449c --- /dev/null +++ b/apps/server/src/mcp/toolkits/showFile/handlers.ts @@ -0,0 +1,66 @@ +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 { + 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.", + }; +}); + +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..04b7281cb5d36 --- /dev/null +++ b/apps/server/src/mcp/toolkits/showFile/tools.ts @@ -0,0 +1,60 @@ +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({ + 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, + 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/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 e381e295d7e1c..edc197e9e1590 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -20,6 +20,13 @@ import { ThreadId, } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; +import { useRightPanelStore } from "../../rightPanelStore"; +import { + latestShownFileCreatedAt, + 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"; @@ -40,6 +47,7 @@ import { useLayoutEffect, useEffect, useEffectEvent, + useMemo, useRef, useState, type ReactNode, @@ -483,6 +491,40 @@ const ConversationTimeline = memo(function ConversationTimeline({ setExpandedAttemptIds(paintedExpandedAttemptIds); } const citationThreadRef = parseScopedThreadKey(routeThreadKey); + const shownFilePlan = useMemo(() => { + const files = shownFileTargets(timelineEntries); + return { + files, + signature: shownFileKey(files), + latestCreatedAt: latestShownFileCreatedAt(files), + 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: shownFilePlan.signature, + files: shownFilesRef.current, + entryCount: shownFilePlan.entryCount, + latestCreatedAt: shownFilePlan.latestCreatedAt, + }); + shownFileBaseline.current = plan.baseline; + const threadRef = parseScopedThreadKey(routeThreadKey); + if (threadRef === null) return; + for (const file of plan.open) { + useRightPanelStore.getState().openFile(threadRef, file.path, file.line); + } + }, [ + 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 new file mode 100644 index 0000000000000..2fab446043ddb --- /dev/null +++ b/apps/web/src/components/chat/shownFileOpen.test.ts @@ -0,0 +1,218 @@ +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import { + shownFileKey, + 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", + completedAt: DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"), + toolName: "show_file", + output: { + 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", 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", 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 = shownFileKey(files); + + it("does not open files already on screen, including after a thread change", () => { + expect( + 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, + entryCount: 2, + latestCreatedAt: "2026-01-03T00:00:00.000Z", + }).open, + ).toEqual([]); + }); + + 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: shownFileKey(first), + files: first, + entryCount: 1, + latestCreatedAt: "2026-01-02T00:00:00.000Z", + }).baseline; + 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 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 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({ + 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 new file mode 100644 index 0000000000000..e192e6a169402 --- /dev/null +++ b/apps/web/src/components/chat/shownFileOpen.ts @@ -0,0 +1,84 @@ +import * as DateTime from "effect/DateTime"; +import { showFileFromToolItem } from "@t3tools/shared/toolOutput"; + +import type { TimelineEntry } from "../../session-logic"; + +export interface ShownFileTarget { + readonly id: string; + readonly path: string; + readonly createdAt: 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, + createdAt: + item.completedAt === null || item.completedAt === undefined + ? entry.createdAt + : DateTime.formatIso(item.completedAt), + ...(shown.line === undefined ? {} : { line: shown.line }), + }); + } + return targets; +} + +/** 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 file of files) { + if (file.createdAt > latest) latest = file.createdAt; + } + return latest; +} + +export function shownFileKey(files: ReadonlyArray): string { + return files + .map((file) => `${file.id}\t${file.path}\t${file.line ?? ""}\t${file.createdAt}`) + .join("\n"); +} + +export function shownFilesToOpen(input: { + readonly threadKey: string; + readonly previous: string | null; + readonly nextKey: string; + readonly files: ReadonlyArray; + readonly entryCount: number; + readonly latestCreatedAt: string; +}): { readonly baseline: string; readonly open: ReadonlyArray } { + 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: [] }; + } + 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(second + 1) + .split("\n") + .filter((row) => row.length > 0) + .map((row) => row.slice(0, row.indexOf("\t"))), + ); + return { + baseline: ready, + open: input.files.filter((file) => !seen.has(file.id) && file.createdAt > watermark), + }; +} 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..307a45f4e6657 --- /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) || !isRecord(value.showFile)) return undefined; + const source = value.showFile; + 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..660916a8f9578 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,50 @@ describe("compactDynamicToolOutput", () => { } }); + it("keeps a shown file's path, size, and type and drops its bytes", () => { + const secret = "SECRET_FILE_BYTES_9f3a"; + 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({ + showFile: { + path: "/tmp/answers.md", + byteSize: secret.length, + mediaType: "text/markdown", + line: 3, + }, + }); + 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", () => { 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..812eb3b8f397d 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) @@ -216,6 +220,20 @@ export function htmlRenderFromToolItem(item: { return output?.isError ? undefined : output?.htmlRender; } +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; +} + /** 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;