Skip to content
TypeScript

fix(acp): Antigravity html_render pages show in the thread (#19796)

Jorge Cervantesa5b3de04c7d1
diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts
index d4d3a0329d9..4a6eed34d1e 100644
--- a/apps/server/src/htmlRender/HtmlRender.test.ts
+++ b/apps/server/src/htmlRender/HtmlRender.test.ts
@@ -1,7 +1,8 @@
// @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
-import { ThreadId } from "@t3tools/contracts";
+import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as HostProcess from "@t3tools/shared/HostProcess";
import {
HTML_RENDER_MEASURE_FONTS,
@@ -47,6 +48,7 @@ const layerHtmlRender = (
}),
),
),
+ Layer.provideMerge(McpProviderSessions.layer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-html-render-" })),
Layer.provideMerge(NodeServices.layer),
);
@@ -196,10 +198,22 @@ describe("HtmlRender", () => {
const fileSystem = yield* FileSystem.FileSystem;
const config = yield* ServerConfig.ServerConfig;
const htmlRender = yield* HtmlRender.HtmlRender;
+ const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
+ const threadId = ThreadId.make("thread-html-render");
+ const session = {
+ environmentId: EnvironmentId.make("html-render-environment"),
+ threadId,
+ providerSessionId: "first-credential",
+ providerInstanceId: ProviderInstanceId.make("claude"),
+ endpoint: "http://localhost:8311/mcp",
+ authorizationHeader: "Bearer first-token",
+ browserToolsAvailable: false,
+ };
+ yield* mcpSessions.set(session);
const reference = yield* htmlRender.publish({
- threadId: ThreadId.make("thread-html-render"),
- html: "<p>Quarterly revenue</p>",
+ threadId,
+ html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
title: " Revenue ",
height: 9_000,
});
@@ -217,32 +231,62 @@ describe("HtmlRender", () => {
const html = yield* fileSystem.readFileString(stored ?? "");
expect(html).toContain('<style id="t3-theme">');
expect(html).toContain("<p>Quarterly revenue</p>");
+ // Antigravity reports the call without its result, so the thread's
+ // provider session keeps the page for one call with these arguments.
+ const page = {
+ html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
+ title: " Revenue ",
+ height: 9_000,
+ };
+ expect(
+ yield* mcpSessions.takeHtmlRender(threadId, {
+ ...page,
+ html: page.html.replace("revenue", "expense"),
+ }),
+ ).toBe(undefined);
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reference);
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
+ const reused = yield* htmlRender.publish({ threadId, ...page });
+ yield* mcpSessions.set({ ...session, browserToolsAvailable: true });
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reused);
+
+ yield* htmlRender.publish({ threadId, ...page });
+ yield* mcpSessions.set({
+ ...session,
+ providerSessionId: "replacement-credential",
+ providerInstanceId: ProviderInstanceId.make("antigravity"),
+ authorizationHeader: "Bearer replacement-token",
+ });
+ const replacement = yield* htmlRender.publish({ threadId, ...page });
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(replacement);
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
+ // Clearing the thread's MCP session drops the pages it kept.
+ yield* htmlRender.publish({ threadId, ...page });
+ yield* mcpSessions.clear(threadId);
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
}).pipe(Effect.provide(layerTest)),
);
it.effect("removes the page when publishing is interrupted", () =>
Effect.gen(function* () {
+ const threadId = ThreadId.make("thread-html-cancel");
+ const page = { html: "<p>x</p>", title: "X", height: 200 };
const measuring = yield* Deferred.make<void>();
yield* Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const config = yield* ServerConfig.ServerConfig;
const htmlRender = yield* HtmlRender.HtmlRender;
+ const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const storedPages = fileSystem
.readDirectory(config.attachmentsDir, { recursive: true })
.pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
- const publishing = yield* htmlRender
- .publish({
- threadId: ThreadId.make("thread-html-cancel"),
- html: "<p>x</p>",
- title: "X",
- height: 200,
- })
- .pipe(Effect.forkChild);
+ const publishing = yield* htmlRender.publish({ threadId, ...page }).pipe(Effect.forkChild);
yield* Deferred.await(measuring);
expect(yield* storedPages).toHaveLength(1);
yield* Fiber.interrupt(publishing);
expect(yield* storedPages).toEqual([]);
+ expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
}).pipe(
Effect.provide(
layerHtmlRender(
diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.ts
index b6a5236a858..41075df5600 100644
--- a/apps/server/src/htmlRender/HtmlRender.ts
+++ b/apps/server/src/htmlRender/HtmlRender.ts
@@ -1,4 +1,5 @@
import type { ThreadId } from "@t3tools/contracts";
+import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as HostProcess from "@t3tools/shared/HostProcess";
import {
clampHtmlRenderHeight,
@@ -310,6 +311,7 @@ const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const config = yield* ServerConfig.ServerConfig;
const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
+ const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const services = yield* Effect.context<
FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
>();
@@ -404,19 +406,35 @@ const make = Effect.gen(function* () {
if (attachmentId === null || filePath === null) {
return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
}
- const heights = yield* fileSystem.writeFileString(filePath, html).pipe(
- Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
- Effect.andThen(measure(html)),
- // Only the returned reference lets thread deletion find the page, so a
- // publish that fails or is interrupted before returning removes it.
- Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)),
- );
- return {
+ const baseReference: HtmlRenderReference = {
attachmentId,
title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
height: clampHtmlRenderHeight(input.height),
- ...(heights === undefined ? {} : { heights }),
- } satisfies HtmlRenderReference;
+ };
+ return yield* fileSystem.writeFileString(filePath, html).pipe(
+ Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
+ Effect.uninterruptible,
+ Effect.andThen(measure(html)),
+ Effect.andThen((heights) => {
+ const reference: HtmlRenderReference = {
+ ...baseReference,
+ ...(heights === undefined ? {} : { heights }),
+ };
+ return mcpSessions
+ .recordHtmlRender(input.threadId, input, reference)
+ .pipe(Effect.as(reference));
+ }),
+ // An interrupted publish must leave neither an attachment nor a recoverable reference.
+ Effect.onError(() =>
+ Effect.all(
+ [
+ fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore),
+ mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore),
+ ],
+ { discard: true },
+ ),
+ ),
+ );
});
const preview = Effect.fn("HtmlRender.preview")(function* (input: {
diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts
index aaa5b176db4..251a5592eb9 100644
--- a/apps/server/src/mcp/toolkits/core.test.ts
+++ b/apps/server/src/mcp/toolkits/core.test.ts
@@ -18,6 +18,7 @@ import {
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
+import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
@@ -292,6 +293,7 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both
Effect.provide(
McpHttpServer.layerHtmlToolkit.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
+ Layer.provide(McpProviderSessions.layer),
Layer.provide(PreviewBrowser.layer),
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-html-render-" })),
Layer.provide(NodeServices.layer),
diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts
index 1598031d50c..48c48f61996 100644
--- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts
+++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts
@@ -6,6 +6,7 @@ import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -57,6 +58,7 @@ const layerStubServices = Layer.mergeAll(
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ThreadSearch.ThreadSearch)({}),
+ McpProviderSessions.layer,
);
const ToolsListPayload = Schema.fromJsonString(
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
index 2ded59be7fc..340bdd08898 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
@@ -11,6 +11,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
+import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -27,6 +28,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
+import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import {
@@ -510,3 +512,283 @@ describe("AntigravityAdapterV2 client file system under restrictive policies", (
}).pipe(Effect.provide(layerSession), Effect.scoped),
);
});
+
+describe("AntigravityAdapterV2 html_render pages", () => {
+ it.effect("shows the page html_render published when the agent reports only a summary", () =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const path = yield* Path.Path;
+ const crypto = yield* Crypto.Crypto;
+ const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
+ const mockAgentPath = yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
+ );
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
+ const instanceId = ProviderInstanceId.make("antigravity-html-render-test");
+ const threadId = ThreadId.make("thread-antigravity-html-render");
+ const page = (name: string) => ({
+ attachmentId: `${threadId}-${name}-html`,
+ title: "Revenue",
+ height: 240,
+ });
+ // Long enough that Antigravity bounds the html the adapter sees.
+ const rows = Array.from({ length: 500 }, (_, row) => `<tr><td>Row ${row}</td></tr>`);
+ const report = { html: `<table>${rows.join("")}</table>`, title: "Revenue", height: 240 };
+ const failed = { ...report, html: "<p>Revenue</p>" };
+ const errored = { ...report, html: "<p>Revenue error</p>" };
+ const adapter = yield* makeAntigravityAdapterV2({
+ instanceId,
+ selfInvocation: yield* resolveSelfInvocation(),
+ makeRuntime: (input) =>
+ makeAntigravityAcpRuntime({
+ ...input,
+ childProcessSpawner,
+ spawn: {
+ command: process.execPath,
+ args: [mockAgentPath],
+ cwd: input.cwd,
+ env: { T3_ACP_ANTIGRAVITY: "1" },
+ },
+ }).pipe(
+ Effect.provideService(Crypto.Crypto, crypto),
+ Effect.map((runtime): RuntimeService => ({
+ ...runtime,
+ handleSessionUpdate: (handler) =>
+ Effect.sync(() => {
+ sessionUpdate = handler;
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
+ // agy_acp_server 1.3/1.4 without a permission prompt: the call is
+ // titled "Running <tool>" and completes with the step's summary
+ // in place of the MCP result.
+ prompt: () =>
+ Effect.gen(function* () {
+ const send = (update: EffectAcpSchema.SessionUpdate) =>
+ sessionUpdate === undefined
+ ? Effect.die("the adapter must handle session updates")
+ : sessionUpdate(
+ normalizeAntigravitySessionUpdate({
+ sessionId: "mock-session-1",
+ update,
+ }),
+ );
+ const calls = [
+ ["published", report],
+ ["unpublished", { ...report, html: "<p>Costs</p>" }],
+ ["failed", failed],
+ ["error", errored],
+ ] as const;
+ for (const [toolCallId, rawInput] of calls) {
+ yield* send({
+ sessionUpdate: "tool_call",
+ toolCallId,
+ title: "Running html_render",
+ kind: "other",
+ status: "in_progress",
+ rawInput,
+ });
+ }
+ yield* mcpSessions.recordHtmlRender(threadId, report, page("report"));
+ yield* mcpSessions.recordHtmlRender(threadId, failed, page("failed"));
+ yield* mcpSessions.recordHtmlRender(threadId, errored, page("error"));
+ for (const [toolCallId, status] of [
+ ["unpublished", "completed"],
+ ["failed", "failed"],
+ ["published", "completed"],
+ ["published", "completed"],
+ ] as const) {
+ yield* send({
+ sessionUpdate: "tool_call_update",
+ toolCallId,
+ status,
+ rawOutput: `Summary of ${toolCallId}`,
+ });
+ }
+ yield* send({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "error",
+ status: "completed",
+ rawOutput: { result: { isError: true, content: [] } },
+ });
+ for (const [name, rawInput] of [
+ ["failed", failed],
+ ["error", errored],
+ ] as const) {
+ const toolCallId = `${name}-retry`;
+ yield* send({
+ sessionUpdate: "tool_call",
+ toolCallId,
+ title: "Running html_render",
+ kind: "other",
+ status: "in_progress",
+ rawInput,
+ });
+ yield* mcpSessions.recordHtmlRender(threadId, rawInput, page(toolCallId));
+ yield* send({
+ sessionUpdate: "tool_call_update",
+ toolCallId: name,
+ status: name === "failed" ? "failed" : "completed",
+ rawOutput:
+ name === "failed"
+ ? "Summary of failed"
+ : { result: { isError: true, content: [] } },
+ });
+ yield* send({
+ sessionUpdate: "tool_call_update",
+ toolCallId,
+ status: "completed",
+ rawOutput: `Summary of ${toolCallId}`,
+ });
+ }
+ yield* mcpSessions.recordHtmlRender(threadId, report, page("replacement"));
+ yield* send({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "published",
+ status: "completed",
+ rawOutput: { htmlRender: page("replacement") },
+ });
+ yield* send({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "published",
+ status: "completed",
+ rawOutput: "Summary of published",
+ });
+ return { stopReason: "end_turn" as const };
+ }),
+ })),
+ ),
+ withProcess: (_stop, task) => task,
+ defaultModel: Effect.succeed(undefined),
+ });
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ });
+ const modelSelection = { instanceId, model: "gemini-test-low" } as const;
+ const session = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-antigravity-html-render"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* session.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ const now = yield* DateTime.now;
+ yield* session.startTurn({
+ appThread: {
+ createdBy: "user",
+ creationSource: "web",
+ id: threadId,
+ projectId: ProjectId.make("project-antigravity-html-render"),
+ title: "Antigravity html_render",
+ providerInstanceId: instanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ activeProviderThreadId: providerThread.id,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ threadId,
+ runId: RunId.make("run-antigravity-html-render"),
+ runOrdinal: 1,
+ providerTurnOrdinal: 1,
+ attemptId: RunAttemptId.make("attempt-antigravity-html-render"),
+ rootNodeId: NodeId.make("node-antigravity-html-render"),
+ providerThread,
+ message: {
+ createdBy: "user",
+ creationSource: "web",
+ messageId: MessageId.make("message-antigravity-html-render"),
+ text: "chart the revenue",
+ attachments: [],
+ },
+ modelSelection,
+ runtimePolicy,
+ });
+ const events = Array.from(
+ yield* session.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runCollect,
+ ),
+ );
+ const tool = (nativeId: string) => {
+ const event = events.findLast(
+ (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === nativeId,
+ );
+ if (event?.type !== "turn_item.updated" || event.turnItem.type !== "dynamic_tool") {
+ return undefined;
+ }
+ const item = event.turnItem;
+ return {
+ status: item.status,
+ toolName: item.toolName,
+ page: htmlRenderFromToolItem(item),
+ output: item.output,
+ };
+ };
+
+ assert.deepEqual(tool("published"), {
+ status: "completed",
+ toolName: "t3-code.html_render",
+ page: page("replacement"),
+ output: { htmlRender: page("replacement") },
+ });
+ assert.deepEqual(tool("unpublished"), {
+ status: "completed",
+ toolName: "t3-code.html_render",
+ page: undefined,
+ output: "Summary of unpublished",
+ });
+ assert.deepEqual(tool("failed"), {
+ status: "failed",
+ toolName: "t3-code.html_render",
+ page: undefined,
+ output: "Summary of failed",
+ });
+ assert.deepEqual(tool("error"), {
+ status: "completed",
+ toolName: "t3-code.html_render",
+ page: undefined,
+ output: [],
+ });
+ assert.deepEqual(
+ events.flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.type === "dynamic_tool" &&
+ event.turnItem.nativeItemRef?.nativeId === "published" &&
+ event.turnItem.status === "completed"
+ ? [htmlRenderFromToolItem(event.turnItem)]
+ : [],
+ ),
+ [page("report"), page("report"), page("replacement"), page("replacement")],
+ );
+ for (const name of ["failed-retry", "error-retry"]) {
+ assert.deepEqual(tool(name), {
+ status: "completed",
+ toolName: "t3-code.html_render",
+ page: page(name),
+ output: { htmlRender: page(name) },
+ });
+ }
+ assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined);
+ assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined);
+ assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined);
+ }).pipe(Effect.provide(layerSession), Effect.scoped),
+ );
+});
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 2c007db0ce0..21ecde2ef4f 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -32,8 +32,11 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope";
+import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
+import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
+import { compactDynamicToolOutput, htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
@@ -3676,6 +3679,46 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
});
}
} else if (mcpIdentity !== undefined) {
+ const toolName = `${mcpIdentity.server}.${mcpIdentity.tool}`;
+ const input =
+ mcpIdentity.input ?? unknownRecord(rawInputRecord?.arguments) ?? rawInputRecord ?? {};
+ let output = rawOutput === undefined ? undefined : acpMcpToolCallOutput(rawOutput);
+ const isHtmlRender = resolveT3McpToolId(toolName) === HTML_RENDER_TOOL_NAME;
+ const isError =
+ compactDynamicToolOutput(output)?.isError === true ||
+ compactDynamicToolOutput(rawOutputRecord?.result)?.isError === true;
+ if (
+ isHtmlRender &&
+ (status === "failed" || (status === "completed" && isError)) &&
+ previous?.status !== "failed" &&
+ previous?.status !== "completed"
+ ) {
+ // A failed call may have published before the provider lost its result.
+ yield* mcpSessions.takeHtmlRender(
+ context.input.threadId,
+ input,
+ htmlRenderFromToolItem({ toolName, output }),
+ );
+ }
+ if (status === "completed" && isHtmlRender && !isError) {
+ const reportedPage = htmlRenderFromToolItem({ toolName, output });
+ // Antigravity replaces MCP results with summaries, including on repeated completions.
+ const previousPage = htmlRenderFromToolItem({
+ toolName,
+ output: acpMcpToolCallOutput(previous?.data.rawOutput ?? previous?.data.content),
+ });
+ const page = reportedPage
+ ? yield* mcpSessions.takeHtmlRender(context.input.threadId, input, reportedPage)
+ : (previousPage ??
+ (yield* mcpSessions.takeHtmlRender(context.input.threadId, input)));
+ if (reportedPage === undefined && page !== undefined) {
+ output = { htmlRender: page };
+ context.tools.set(toolCall.toolCallId, {
+ ...toolCall,
+ data: { ...toolCall.data, rawOutput: output },
+ });
+ }
+ }
turnItem = {
...base,
title: null,
@@ -3687,13 +3730,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
)?.source,
}),
type: "dynamic_tool",
- toolName: `${mcpIdentity.server}.${mcpIdentity.tool}`,
- input:
- mcpIdentity.input ??
- unknownRecord(rawInputRecord?.arguments) ??
- rawInputRecord ??
- {},
- ...(rawOutput === undefined ? {} : { output: acpMcpToolCallOutput(rawOutput) }),
+ toolName,
+ input,
+ ...(output === undefined ? {} : { output }),
};
yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem });
yield* rearmDeferredFinalize(context);
diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts
index f7c10bdf3ad..70ce4336f55 100644
--- a/packages/provider-acp/src/server/runtimeModel.ts
+++ b/packages/provider-acp/src/server/runtimeModel.ts
@@ -1091,15 +1091,11 @@ const T3_MCP_TITLE_SUFFIX_CALL =
/^(?<tool>[A-Za-z0-9][A-Za-z0-9_.-]*?)(?: \(t3[-_ ]?code MCP Server\)(?::|$)|[-_.]t3[-_ ]?code$)/i;
/**
- * glm-acp-agent and Kimi CLI register injected MCP tools under their bare
- * names; Kimi additionally appends ": <raw args json>". The T3 inventory gate
- * alone is not enough: an agent can have its own tool of the same name (Hermes
- * has a built-in `delegate_task`) and title it "<tool>: <description>", so only
- * a bare name or a JSON object after the colon counts. The match stops at the
- * opening brace because Kimi retitles on every streamed args chunk, so the
- * JSON is often still incomplete.
+ * glm and Kimi use bare names; Antigravity uses "Running <tool>". Kimi appends
+ * streamed JSON arguments. Require a name or JSON opening brace so built-ins
+ * titled "<tool>: <description>" cannot impersonate an inventory entry.
*/
-const T3_MCP_BARE_TITLE_CALL = /^(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
+const T3_MCP_BARE_TITLE_CALL = /^(?:Running )?(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
/**
* ACP has no typed MCP tool-call item, so agents surface MCP calls in agent-specific shapes:
diff --git a/packages/provider-core/src/server/McpProviderSessions.ts b/packages/provider-core/src/server/McpProviderSessions.ts
index 7022328420a..2da992cfb85 100644
--- a/packages/provider-core/src/server/McpProviderSessions.ts
+++ b/packages/provider-core/src/server/McpProviderSessions.ts
@@ -1,4 +1,7 @@
+// @effect-diagnostics nodeBuiltinImport:off -- Pure synchronous hashing keeps page matching bounded without a runtime dependency.
+import * as NodeCrypto from "node:crypto";
import type { ThreadId } from "@t3tools/contracts";
+import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -6,26 +9,142 @@ import * as Ref from "effect/Ref";
import type { McpProviderSessionConfig } from "./mcpSession.ts";
+// Other providers may never consume these references.
+const MAX_KEPT_HTML_RENDERS = 64;
+
+// Antigravity truncates long HTML arguments to a marked tail of at most 8,000 characters.
+const BOUNDED_TEXT_MARKER = "[Earlier output truncated]\n\n";
+const KEPT_HTML_END_LENGTH = 8_000;
+
+interface KeptHtmlRender {
+ readonly title: string;
+ readonly height: number;
+ readonly htmlLength: number;
+ readonly htmlHash: string;
+ readonly htmlEnd: string;
+ readonly reference: HtmlRenderReference;
+}
+
+const hashHtml = (html: string) => NodeCrypto.createHash("sha256").update(html).digest("hex");
+
export class McpProviderSessions extends Context.Service<
McpProviderSessions,
{
readonly set: (config: McpProviderSessionConfig) => Effect.Effect<void>;
readonly read: (threadId: ThreadId) => Effect.Effect<McpProviderSessionConfig | undefined>;
readonly clear: (threadId: ThreadId) => Effect.Effect<void>;
+ readonly recordHtmlRender: (
+ threadId: ThreadId,
+ input: { readonly html: string; readonly title: string; readonly height: number },
+ reference: HtmlRenderReference,
+ ) => Effect.Effect<void>;
+ // A reported attachment consumes that exact page; otherwise only unique input matches count.
+ readonly takeHtmlRender: (
+ threadId: ThreadId,
+ input: { readonly html?: unknown; readonly title?: unknown; readonly height?: unknown },
+ reported?: HtmlRenderReference,
+ ) => Effect.Effect<HtmlRenderReference | undefined>;
}
>()("@t3tools/provider-core/server/McpProviderSessions") {}
+const matchingPageIndex = (
+ kept: ReadonlyArray<KeptHtmlRender>,
+ input: { readonly html?: unknown; readonly title?: unknown; readonly height?: unknown },
+): number => {
+ const html = input.html;
+ if (typeof html !== "string" || html.length === 0) {
+ return -1;
+ }
+ const height =
+ typeof input.height === "string" && input.height.trim() !== ""
+ ? Number(input.height)
+ : input.height;
+ const htmlHash = hashHtml(html);
+ const tail = html.startsWith(BOUNDED_TEXT_MARKER)
+ ? html.slice(BOUNDED_TEXT_MARKER.length)
+ : undefined;
+ const matches = kept.flatMap((page, index) =>
+ page.title === input.title &&
+ page.height === height &&
+ (page.htmlHash === htmlHash ||
+ (tail !== undefined &&
+ tail.length > 0 &&
+ tail.length < page.htmlLength &&
+ page.htmlEnd.endsWith(tail)))
+ ? [index]
+ : [],
+ );
+ return matches.length === 1 ? matches[0]! : -1;
+};
+
const make = Effect.gen(function* () {
const sessions = yield* Ref.make(new Map<ThreadId, McpProviderSessionConfig>());
+ const htmlRenders = yield* Ref.make(new Map<ThreadId, ReadonlyArray<KeptHtmlRender>>());
return McpProviderSessions.of({
- set: (config) =>
- Ref.update(sessions, (current) => new Map(current).set(config.threadId, config)),
+ set: Effect.fn("McpProviderSessions.set")(function* (config) {
+ const current = yield* Ref.get(sessions);
+ if (current.get(config.threadId)?.providerSessionId !== config.providerSessionId) {
+ yield* Ref.update(htmlRenders, (kept) => {
+ const next = new Map(kept);
+ next.delete(config.threadId);
+ return next;
+ });
+ }
+ yield* Ref.update(sessions, (current) => new Map(current).set(config.threadId, config));
+ }),
read: (threadId) => Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId))),
clear: (threadId) =>
Ref.update(sessions, (current) => {
const next = new Map(current);
next.delete(threadId);
return next;
+ }).pipe(
+ Effect.andThen(
+ Ref.update(htmlRenders, (current) => {
+ const next = new Map(current);
+ next.delete(threadId);
+ return next;
+ }),
+ ),
+ ),
+ recordHtmlRender: (threadId, input, reference) =>
+ Ref.update(htmlRenders, (current) =>
+ new Map(current).set(
+ threadId,
+ [
+ ...(current.get(threadId) ?? []),
+ {
+ title: input.title,
+ height: input.height,
+ htmlLength: input.html.length,
+ htmlHash: hashHtml(input.html),
+ // Copy the tail so its backing storage cannot retain the entire HTML string.
+ htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(
+ "utf16le",
+ ),
+ reference,
+ },
+ ].slice(-MAX_KEPT_HTML_RENDERS),
+ ),
+ ),
+ takeHtmlRender: (threadId, input, reported) =>
+ Ref.modify(htmlRenders, (current) => {
+ const kept = current.get(threadId) ?? [];
+ const index =
+ reported === undefined
+ ? matchingPageIndex(kept, input)
+ : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);
+ if (index === -1) {
+ return [undefined, current];
+ }
+ const rest = kept.filter((_, keptIndex) => keptIndex !== index);
+ const next = new Map(current);
+ if (rest.length === 0) {
+ next.delete(threadId);
+ } else {
+ next.set(threadId, rest);
+ }
+ return [kept[index]!.reference, next];
}),
});
});