@devries-cameron20 / t3code Mirror · read-only / commits / a5b3de04c7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 22:00 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Jorge Cervantes committed Oct 19, 2026 at 23:42 UTC a5b3de04c7d13dd1d0b3602cc36726f256ba5470
8 files changed +540 -38
apps/server/src/htmlRender/HtmlRender.test.ts
+55 -11
@@ -1,7 +1,8 @@
1 // @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services.
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { describe, expect, it } from "@effect/vitest";
4 -import { ThreadId } from "@t3tools/contracts";
4 +import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
5 +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
7 import {
8 HTML_RENDER_MEASURE_FONTS,
@@ -47,6 +48,7 @@ const layerHtmlRender = (
48 }),
49 ),
50 ),
51 + Layer.provideMerge(McpProviderSessions.layer),
52 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-html-render-" })),
53 Layer.provideMerge(NodeServices.layer),
54 );
@@ -196,10 +198,22 @@ describe("HtmlRender", () => {
198 const fileSystem = yield* FileSystem.FileSystem;
199 const config = yield* ServerConfig.ServerConfig;
200 const htmlRender = yield* HtmlRender.HtmlRender;
201 + const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
202 + const threadId = ThreadId.make("thread-html-render");
203 + const session = {
204 + environmentId: EnvironmentId.make("html-render-environment"),
205 + threadId,
206 + providerSessionId: "first-credential",
207 + providerInstanceId: ProviderInstanceId.make("claude"),
208 + endpoint: "http://localhost:8311/mcp",
209 + authorizationHeader: "Bearer first-token",
210 + browserToolsAvailable: false,
211 + };
212 + yield* mcpSessions.set(session);
213
214 const reference = yield* htmlRender.publish({
201 - threadId: ThreadId.make("thread-html-render"),
202 - html: "<p>Quarterly revenue</p>",
215 + threadId,
216 + html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
217 title: " Revenue ",
218 height: 9_000,
219 });
@@ -217,32 +231,62 @@ describe("HtmlRender", () => {
231 const html = yield* fileSystem.readFileString(stored ?? "");
232 expect(html).toContain('<style id="t3-theme">');
233 expect(html).toContain("<p>Quarterly revenue</p>");
234 + // Antigravity reports the call without its result, so the thread's
235 + // provider session keeps the page for one call with these arguments.
236 + const page = {
237 + html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
238 + title: " Revenue ",
239 + height: 9_000,
240 + };
241 + expect(
242 + yield* mcpSessions.takeHtmlRender(threadId, {
243 + ...page,
244 + html: page.html.replace("revenue", "expense"),
245 + }),
246 + ).toBe(undefined);
247 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reference);
248 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
249 + const reused = yield* htmlRender.publish({ threadId, ...page });
250 + yield* mcpSessions.set({ ...session, browserToolsAvailable: true });
251 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reused);
252 +
253 + yield* htmlRender.publish({ threadId, ...page });
254 + yield* mcpSessions.set({
255 + ...session,
256 + providerSessionId: "replacement-credential",
257 + providerInstanceId: ProviderInstanceId.make("antigravity"),
258 + authorizationHeader: "Bearer replacement-token",
259 + });
260 + const replacement = yield* htmlRender.publish({ threadId, ...page });
261 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(replacement);
262 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
263 + // Clearing the thread's MCP session drops the pages it kept.
264 + yield* htmlRender.publish({ threadId, ...page });
265 + yield* mcpSessions.clear(threadId);
266 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
267 }).pipe(Effect.provide(layerTest)),
268 );
269
270 it.effect("removes the page when publishing is interrupted", () =>
271 Effect.gen(function* () {
272 + const threadId = ThreadId.make("thread-html-cancel");
273 + const page = { html: "<p>x</p>", title: "X", height: 200 };
274 const measuring = yield* Deferred.make<void>();
275 yield* Effect.gen(function* () {
276 const fileSystem = yield* FileSystem.FileSystem;
277 const config = yield* ServerConfig.ServerConfig;
278 const htmlRender = yield* HtmlRender.HtmlRender;
279 + const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
280 const storedPages = fileSystem
281 .readDirectory(config.attachmentsDir, { recursive: true })
282 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
283
234 - const publishing = yield* htmlRender
235 - .publish({
236 - threadId: ThreadId.make("thread-html-cancel"),
237 - html: "<p>x</p>",
238 - title: "X",
239 - height: 200,
240 - })
241 - .pipe(Effect.forkChild);
284 + const publishing = yield* htmlRender.publish({ threadId, ...page }).pipe(Effect.forkChild);
285 yield* Deferred.await(measuring);
286 expect(yield* storedPages).toHaveLength(1);
287 yield* Fiber.interrupt(publishing);
288 expect(yield* storedPages).toEqual([]);
289 + expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
290 }).pipe(
291 Effect.provide(
292 layerHtmlRender(
apps/server/src/htmlRender/HtmlRender.ts
+28 -10
@@ -1,4 +1,5 @@
1 import type { ThreadId } from "@t3tools/contracts";
2 +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import {
5 clampHtmlRenderHeight,
@@ -310,6 +311,7 @@ const make = Effect.gen(function* () {
311 const fileSystem = yield* FileSystem.FileSystem;
312 const config = yield* ServerConfig.ServerConfig;
313 const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
314 + const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
315 const services = yield* Effect.context<
316 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
317 >();
@@ -404,19 +406,35 @@ const make = Effect.gen(function* () {
406 if (attachmentId === null || filePath === null) {
407 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
408 }
407 - const heights = yield* fileSystem.writeFileString(filePath, html).pipe(
408 - Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
409 - Effect.andThen(measure(html)),
410 - // Only the returned reference lets thread deletion find the page, so a
411 - // publish that fails or is interrupted before returning removes it.
412 - Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)),
413 - );
414 - return {
409 + const baseReference: HtmlRenderReference = {
410 attachmentId,
411 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
412 height: clampHtmlRenderHeight(input.height),
418 - ...(heights === undefined ? {} : { heights }),
419 - } satisfies HtmlRenderReference;
413 + };
414 + return yield* fileSystem.writeFileString(filePath, html).pipe(
415 + Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
416 + Effect.uninterruptible,
417 + Effect.andThen(measure(html)),
418 + Effect.andThen((heights) => {
419 + const reference: HtmlRenderReference = {
420 + ...baseReference,
421 + ...(heights === undefined ? {} : { heights }),
422 + };
423 + return mcpSessions
424 + .recordHtmlRender(input.threadId, input, reference)
425 + .pipe(Effect.as(reference));
426 + }),
427 + // An interrupted publish must leave neither an attachment nor a recoverable reference.
428 + Effect.onError(() =>
429 + Effect.all(
430 + [
431 + fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore),
432 + mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore),
433 + ],
434 + { discard: true },
435 + ),
436 + ),
437 + );
438 });
439
440 const preview = Effect.fn("HtmlRender.preview")(function* (input: {
apps/server/src/mcp/toolkits/core.test.ts
+2
@@ -18,6 +18,7 @@ import {
18 type OrchestrationV2ProjectedTurnItem,
19 type OrchestrationV2ThreadShell,
20 } from "@t3tools/contracts";
21 +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
22 import * as Deferred from "effect/Deferred";
23 import * as Effect from "effect/Effect";
24 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
293 Effect.provide(
294 McpHttpServer.layerHtmlToolkit.pipe(
295 Layer.provideMerge(McpServer.McpServer.layer),
296 + Layer.provide(McpProviderSessions.layer),
297 Layer.provide(PreviewBrowser.layer),
298 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-html-render-" })),
299 Layer.provide(NodeServices.layer),
apps/server/src/mcp/toolkits/worktree/registration.test.ts
+2
@@ -6,6 +6,7 @@ import { expect, it } from "@effect/vitest";
6 import { NodeHttpServer } from "@effect/platform-node";
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
9 +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
10 import * as Effect from "effect/Effect";
11 import * as Layer from "effect/Layer";
12 import * as Schema from "effect/Schema";
@@ -57,6 +58,7 @@ const layerStubServices = Layer.mergeAll(
58 Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}),
59 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
60 Layer.mock(ThreadSearch.ThreadSearch)({}),
61 + McpProviderSessions.layer,
62 );
63
64 const ToolsListPayload = Schema.fromJsonString(
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+282
@@ -11,6 +11,7 @@ import {
11 ThreadId,
12 } from "@t3tools/contracts";
13 import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
14 +import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
15 import * as Crypto from "effect/Crypto";
16 import * as DateTime from "effect/DateTime";
17 import * as Effect from "effect/Effect";
@@ -27,6 +28,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
28 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
29 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
30 import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
31 +import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
32 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
33 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
34 import {
@@ -510,3 +512,283 @@ describe("AntigravityAdapterV2 client file system under restrictive policies", (
512 }).pipe(Effect.provide(layerSession), Effect.scoped),
513 );
514 });
515 +
516 +describe("AntigravityAdapterV2 html_render pages", () => {
517 + it.effect("shows the page html_render published when the agent reports only a summary", () =>
518 + Effect.gen(function* () {
519 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
520 + const path = yield* Path.Path;
521 + const crypto = yield* Crypto.Crypto;
522 + const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
523 + const mockAgentPath = yield* path.fromFileUrl(
524 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
525 + );
526 + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
527 + let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
528 + const instanceId = ProviderInstanceId.make("antigravity-html-render-test");
529 + const threadId = ThreadId.make("thread-antigravity-html-render");
530 + const page = (name: string) => ({
531 + attachmentId: `${threadId}-${name}-html`,
532 + title: "Revenue",
533 + height: 240,
534 + });
535 + // Long enough that Antigravity bounds the html the adapter sees.
536 + const rows = Array.from({ length: 500 }, (_, row) => `<tr><td>Row ${row}</td></tr>`);
537 + const report = { html: `<table>${rows.join("")}</table>`, title: "Revenue", height: 240 };
538 + const failed = { ...report, html: "<p>Revenue</p>" };
539 + const errored = { ...report, html: "<p>Revenue error</p>" };
540 + const adapter = yield* makeAntigravityAdapterV2({
541 + instanceId,
542 + selfInvocation: yield* resolveSelfInvocation(),
543 + makeRuntime: (input) =>
544 + makeAntigravityAcpRuntime({
545 + ...input,
546 + childProcessSpawner,
547 + spawn: {
548 + command: process.execPath,
549 + args: [mockAgentPath],
550 + cwd: input.cwd,
551 + env: { T3_ACP_ANTIGRAVITY: "1" },
552 + },
553 + }).pipe(
554 + Effect.provideService(Crypto.Crypto, crypto),
555 + Effect.map((runtime): RuntimeService => ({
556 + ...runtime,
557 + handleSessionUpdate: (handler) =>
558 + Effect.sync(() => {
559 + sessionUpdate = handler;
560 + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
561 + // agy_acp_server 1.3/1.4 without a permission prompt: the call is
562 + // titled "Running <tool>" and completes with the step's summary
563 + // in place of the MCP result.
564 + prompt: () =>
565 + Effect.gen(function* () {
566 + const send = (update: EffectAcpSchema.SessionUpdate) =>
567 + sessionUpdate === undefined
568 + ? Effect.die("the adapter must handle session updates")
569 + : sessionUpdate(
570 + normalizeAntigravitySessionUpdate({
571 + sessionId: "mock-session-1",
572 + update,
573 + }),
574 + );
575 + const calls = [
576 + ["published", report],
577 + ["unpublished", { ...report, html: "<p>Costs</p>" }],
578 + ["failed", failed],
579 + ["error", errored],
580 + ] as const;
581 + for (const [toolCallId, rawInput] of calls) {
582 + yield* send({
583 + sessionUpdate: "tool_call",
584 + toolCallId,
585 + title: "Running html_render",
586 + kind: "other",
587 + status: "in_progress",
588 + rawInput,
589 + });
590 + }
591 + yield* mcpSessions.recordHtmlRender(threadId, report, page("report"));
592 + yield* mcpSessions.recordHtmlRender(threadId, failed, page("failed"));
593 + yield* mcpSessions.recordHtmlRender(threadId, errored, page("error"));
594 + for (const [toolCallId, status] of [
595 + ["unpublished", "completed"],
596 + ["failed", "failed"],
597 + ["published", "completed"],
598 + ["published", "completed"],
599 + ] as const) {
600 + yield* send({
601 + sessionUpdate: "tool_call_update",
602 + toolCallId,
603 + status,
604 + rawOutput: `Summary of ${toolCallId}`,
605 + });
606 + }
607 + yield* send({
608 + sessionUpdate: "tool_call_update",
609 + toolCallId: "error",
610 + status: "completed",
611 + rawOutput: { result: { isError: true, content: [] } },
612 + });
613 + for (const [name, rawInput] of [
614 + ["failed", failed],
615 + ["error", errored],
616 + ] as const) {
617 + const toolCallId = `${name}-retry`;
618 + yield* send({
619 + sessionUpdate: "tool_call",
620 + toolCallId,
621 + title: "Running html_render",
622 + kind: "other",
623 + status: "in_progress",
624 + rawInput,
625 + });
626 + yield* mcpSessions.recordHtmlRender(threadId, rawInput, page(toolCallId));
627 + yield* send({
628 + sessionUpdate: "tool_call_update",
629 + toolCallId: name,
630 + status: name === "failed" ? "failed" : "completed",
631 + rawOutput:
632 + name === "failed"
633 + ? "Summary of failed"
634 + : { result: { isError: true, content: [] } },
635 + });
636 + yield* send({
637 + sessionUpdate: "tool_call_update",
638 + toolCallId,
639 + status: "completed",
640 + rawOutput: `Summary of ${toolCallId}`,
641 + });
642 + }
643 + yield* mcpSessions.recordHtmlRender(threadId, report, page("replacement"));
644 + yield* send({
645 + sessionUpdate: "tool_call_update",
646 + toolCallId: "published",
647 + status: "completed",
648 + rawOutput: { htmlRender: page("replacement") },
649 + });
650 + yield* send({
651 + sessionUpdate: "tool_call_update",
652 + toolCallId: "published",
653 + status: "completed",
654 + rawOutput: "Summary of published",
655 + });
656 + return { stopReason: "end_turn" as const };
657 + }),
658 + })),
659 + ),
660 + withProcess: (_stop, task) => task,
661 + defaultModel: Effect.succeed(undefined),
662 + });
663 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
664 + runtimeMode: "full-access",
665 + interactionMode: "default",
666 + cwd: process.cwd(),
667 + });
668 + const modelSelection = { instanceId, model: "gemini-test-low" } as const;
669 + const session = yield* adapter.openSession({
670 + threadId,
671 + providerSessionId: ProviderSessionId.make("provider-session-antigravity-html-render"),
672 + modelSelection,
673 + runtimePolicy,
674 + });
675 + const providerThread = yield* session.ensureThread({
676 + threadId,
677 + modelSelection,
678 + runtimePolicy,
679 + });
680 + const now = yield* DateTime.now;
681 + yield* session.startTurn({
682 + appThread: {
683 + createdBy: "user",
684 + creationSource: "web",
685 + id: threadId,
686 + projectId: ProjectId.make("project-antigravity-html-render"),
687 + title: "Antigravity html_render",
688 + providerInstanceId: instanceId,
689 + modelSelection,
690 + runtimeMode: "full-access",
691 + interactionMode: "default",
692 + branch: null,
693 + worktreePath: process.cwd(),
694 + activeProviderThreadId: providerThread.id,
695 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
696 + forkedFrom: null,
697 + createdAt: now,
698 + updatedAt: now,
699 + archivedAt: null,
700 + settledOverride: null,
701 + settledAt: null,
702 + lastVisitedAt: null,
703 + deletedAt: null,
704 + },
705 + threadId,
706 + runId: RunId.make("run-antigravity-html-render"),
707 + runOrdinal: 1,
708 + providerTurnOrdinal: 1,
709 + attemptId: RunAttemptId.make("attempt-antigravity-html-render"),
710 + rootNodeId: NodeId.make("node-antigravity-html-render"),
711 + providerThread,
712 + message: {
713 + createdBy: "user",
714 + creationSource: "web",
715 + messageId: MessageId.make("message-antigravity-html-render"),
716 + text: "chart the revenue",
717 + attachments: [],
718 + },
719 + modelSelection,
720 + runtimePolicy,
721 + });
722 + const events = Array.from(
723 + yield* session.events.pipe(
724 + Stream.takeUntil((event) => event.type === "turn.terminal"),
725 + Stream.runCollect,
726 + ),
727 + );
728 + const tool = (nativeId: string) => {
729 + const event = events.findLast(
730 + (event) =>
731 + event.type === "turn_item.updated" &&
732 + event.turnItem.nativeItemRef?.nativeId === nativeId,
733 + );
734 + if (event?.type !== "turn_item.updated" || event.turnItem.type !== "dynamic_tool") {
735 + return undefined;
736 + }
737 + const item = event.turnItem;
738 + return {
739 + status: item.status,
740 + toolName: item.toolName,
741 + page: htmlRenderFromToolItem(item),
742 + output: item.output,
743 + };
744 + };
745 +
746 + assert.deepEqual(tool("published"), {
747 + status: "completed",
748 + toolName: "t3-code.html_render",
749 + page: page("replacement"),
750 + output: { htmlRender: page("replacement") },
751 + });
752 + assert.deepEqual(tool("unpublished"), {
753 + status: "completed",
754 + toolName: "t3-code.html_render",
755 + page: undefined,
756 + output: "Summary of unpublished",
757 + });
758 + assert.deepEqual(tool("failed"), {
759 + status: "failed",
760 + toolName: "t3-code.html_render",
761 + page: undefined,
762 + output: "Summary of failed",
763 + });
764 + assert.deepEqual(tool("error"), {
765 + status: "completed",
766 + toolName: "t3-code.html_render",
767 + page: undefined,
768 + output: [],
769 + });
770 + assert.deepEqual(
771 + events.flatMap((event) =>
772 + event.type === "turn_item.updated" &&
773 + event.turnItem.type === "dynamic_tool" &&
774 + event.turnItem.nativeItemRef?.nativeId === "published" &&
775 + event.turnItem.status === "completed"
776 + ? [htmlRenderFromToolItem(event.turnItem)]
777 + : [],
778 + ),
779 + [page("report"), page("report"), page("replacement"), page("replacement")],
780 + );
781 + for (const name of ["failed-retry", "error-retry"]) {
782 + assert.deepEqual(tool(name), {
783 + status: "completed",
784 + toolName: "t3-code.html_render",
785 + page: page(name),
786 + output: { htmlRender: page(name) },
787 + });
788 + }
789 + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined);
790 + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined);
791 + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined);
792 + }).pipe(Effect.provide(layerSession), Effect.scoped),
793 + );
794 +});
packages/provider-acp/src/server/adapter.ts
+46 -7
@@ -32,8 +32,11 @@ import {
32 type ThreadId,
33 } from "@t3tools/contracts";
34 import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope";
35 +import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
36 import { modelSelectionsEqual } from "@t3tools/shared/model";
37 import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
38 +import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
39 +import { compactDynamicToolOutput, htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
40 import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
41 import * as Cause from "effect/Cause";
42 import * as Crypto from "effect/Crypto";
@@ -3676,6 +3679,46 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3679 });
3680 }
3681 } else if (mcpIdentity !== undefined) {
3682 + const toolName = `${mcpIdentity.server}.${mcpIdentity.tool}`;
3683 + const input =
3684 + mcpIdentity.input ?? unknownRecord(rawInputRecord?.arguments) ?? rawInputRecord ?? {};
3685 + let output = rawOutput === undefined ? undefined : acpMcpToolCallOutput(rawOutput);
3686 + const isHtmlRender = resolveT3McpToolId(toolName) === HTML_RENDER_TOOL_NAME;
3687 + const isError =
3688 + compactDynamicToolOutput(output)?.isError === true ||
3689 + compactDynamicToolOutput(rawOutputRecord?.result)?.isError === true;
3690 + if (
3691 + isHtmlRender &&
3692 + (status === "failed" || (status === "completed" && isError)) &&
3693 + previous?.status !== "failed" &&
3694 + previous?.status !== "completed"
3695 + ) {
3696 + // A failed call may have published before the provider lost its result.
3697 + yield* mcpSessions.takeHtmlRender(
3698 + context.input.threadId,
3699 + input,
3700 + htmlRenderFromToolItem({ toolName, output }),
3701 + );
3702 + }
3703 + if (status === "completed" && isHtmlRender && !isError) {
3704 + const reportedPage = htmlRenderFromToolItem({ toolName, output });
3705 + // Antigravity replaces MCP results with summaries, including on repeated completions.
3706 + const previousPage = htmlRenderFromToolItem({
3707 + toolName,
3708 + output: acpMcpToolCallOutput(previous?.data.rawOutput ?? previous?.data.content),
3709 + });
3710 + const page = reportedPage
3711 + ? yield* mcpSessions.takeHtmlRender(context.input.threadId, input, reportedPage)
3712 + : (previousPage ??
3713 + (yield* mcpSessions.takeHtmlRender(context.input.threadId, input)));
3714 + if (reportedPage === undefined && page !== undefined) {
3715 + output = { htmlRender: page };
3716 + context.tools.set(toolCall.toolCallId, {
3717 + ...toolCall,
3718 + data: { ...toolCall.data, rawOutput: output },
3719 + });
3720 + }
3721 + }
3722 turnItem = {
3723 ...base,
3724 title: null,
@@ -3687,13 +3730,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3730 )?.source,
3731 }),
3732 type: "dynamic_tool",
3690 - toolName: `${mcpIdentity.server}.${mcpIdentity.tool}`,
3691 - input:
3692 - mcpIdentity.input ??
3693 - unknownRecord(rawInputRecord?.arguments) ??
3694 - rawInputRecord ??
3695 - {},
3696 - ...(rawOutput === undefined ? {} : { output: acpMcpToolCallOutput(rawOutput) }),
3733 + toolName,
3734 + input,
3735 + ...(output === undefined ? {} : { output }),
3736 };
3737 yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem });
3738 yield* rearmDeferredFinalize(context);
packages/provider-acp/src/server/runtimeModel.ts
+4 -8
@@ -1091,15 +1091,11 @@ const T3_MCP_TITLE_SUFFIX_CALL =
1091 /^(?<tool>[A-Za-z0-9][A-Za-z0-9_.-]*?)(?: \(t3[-_ ]?code MCP Server\)(?::|$)|[-_.]t3[-_ ]?code$)/i;
1092
1093 /**
1094 - * glm-acp-agent and Kimi CLI register injected MCP tools under their bare
1095 - * names; Kimi additionally appends ": <raw args json>". The T3 inventory gate
1096 - * alone is not enough: an agent can have its own tool of the same name (Hermes
1097 - * has a built-in `delegate_task`) and title it "<tool>: <description>", so only
1098 - * a bare name or a JSON object after the colon counts. The match stops at the
1099 - * opening brace because Kimi retitles on every streamed args chunk, so the
1100 - * JSON is often still incomplete.
1094 + * glm and Kimi use bare names; Antigravity uses "Running <tool>". Kimi appends
1095 + * streamed JSON arguments. Require a name or JSON opening brace so built-ins
1096 + * titled "<tool>: <description>" cannot impersonate an inventory entry.
1097 */
1102 -const T3_MCP_BARE_TITLE_CALL = /^(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
1098 +const T3_MCP_BARE_TITLE_CALL = /^(?:Running )?(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
1099
1100 /**
1101 * ACP has no typed MCP tool-call item, so agents surface MCP calls in agent-specific shapes:
packages/provider-core/src/server/McpProviderSessions.ts
+121 -2
@@ -1,4 +1,7 @@
1 +// @effect-diagnostics nodeBuiltinImport:off -- Pure synchronous hashing keeps page matching bounded without a runtime dependency.
2 +import * as NodeCrypto from "node:crypto";
3 import type { ThreadId } from "@t3tools/contracts";
4 +import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
5 import * as Context from "effect/Context";
6 import * as Effect from "effect/Effect";
7 import * as Layer from "effect/Layer";
@@ -6,26 +9,142 @@ import * as Ref from "effect/Ref";
9
10 import type { McpProviderSessionConfig } from "./mcpSession.ts";
11
12 +// Other providers may never consume these references.
13 +const MAX_KEPT_HTML_RENDERS = 64;
14 +
15 +// Antigravity truncates long HTML arguments to a marked tail of at most 8,000 characters.
16 +const BOUNDED_TEXT_MARKER = "[Earlier output truncated]\n\n";
17 +const KEPT_HTML_END_LENGTH = 8_000;
18 +
19 +interface KeptHtmlRender {
20 + readonly title: string;
21 + readonly height: number;
22 + readonly htmlLength: number;
23 + readonly htmlHash: string;
24 + readonly htmlEnd: string;
25 + readonly reference: HtmlRenderReference;
26 +}
27 +
28 +const hashHtml = (html: string) => NodeCrypto.createHash("sha256").update(html).digest("hex");
29 +
30 export class McpProviderSessions extends Context.Service<
31 McpProviderSessions,
32 {
33 readonly set: (config: McpProviderSessionConfig) => Effect.Effect<void>;
34 readonly read: (threadId: ThreadId) => Effect.Effect<McpProviderSessionConfig | undefined>;
35 readonly clear: (threadId: ThreadId) => Effect.Effect<void>;
36 + readonly recordHtmlRender: (
37 + threadId: ThreadId,
38 + input: { readonly html: string; readonly title: string; readonly height: number },
39 + reference: HtmlRenderReference,
40 + ) => Effect.Effect<void>;
41 + // A reported attachment consumes that exact page; otherwise only unique input matches count.
42 + readonly takeHtmlRender: (
43 + threadId: ThreadId,
44 + input: { readonly html?: unknown; readonly title?: unknown; readonly height?: unknown },
45 + reported?: HtmlRenderReference,
46 + ) => Effect.Effect<HtmlRenderReference | undefined>;
47 }
48 >()("@t3tools/provider-core/server/McpProviderSessions") {}
49
50 +const matchingPageIndex = (
51 + kept: ReadonlyArray<KeptHtmlRender>,
52 + input: { readonly html?: unknown; readonly title?: unknown; readonly height?: unknown },
53 +): number => {
54 + const html = input.html;
55 + if (typeof html !== "string" || html.length === 0) {
56 + return -1;
57 + }
58 + const height =
59 + typeof input.height === "string" && input.height.trim() !== ""
60 + ? Number(input.height)
61 + : input.height;
62 + const htmlHash = hashHtml(html);
63 + const tail = html.startsWith(BOUNDED_TEXT_MARKER)
64 + ? html.slice(BOUNDED_TEXT_MARKER.length)
65 + : undefined;
66 + const matches = kept.flatMap((page, index) =>
67 + page.title === input.title &&
68 + page.height === height &&
69 + (page.htmlHash === htmlHash ||
70 + (tail !== undefined &&
71 + tail.length > 0 &&
72 + tail.length < page.htmlLength &&
73 + page.htmlEnd.endsWith(tail)))
74 + ? [index]
75 + : [],
76 + );
77 + return matches.length === 1 ? matches[0]! : -1;
78 +};
79 +
80 const make = Effect.gen(function* () {
81 const sessions = yield* Ref.make(new Map<ThreadId, McpProviderSessionConfig>());
82 + const htmlRenders = yield* Ref.make(new Map<ThreadId, ReadonlyArray<KeptHtmlRender>>());
83 return McpProviderSessions.of({
21 - set: (config) =>
22 - Ref.update(sessions, (current) => new Map(current).set(config.threadId, config)),
84 + set: Effect.fn("McpProviderSessions.set")(function* (config) {
85 + const current = yield* Ref.get(sessions);
86 + if (current.get(config.threadId)?.providerSessionId !== config.providerSessionId) {
87 + yield* Ref.update(htmlRenders, (kept) => {
88 + const next = new Map(kept);
89 + next.delete(config.threadId);
90 + return next;
91 + });
92 + }
93 + yield* Ref.update(sessions, (current) => new Map(current).set(config.threadId, config));
94 + }),
95 read: (threadId) => Ref.get(sessions).pipe(Effect.map((current) => current.get(threadId))),
96 clear: (threadId) =>
97 Ref.update(sessions, (current) => {
98 const next = new Map(current);
99 next.delete(threadId);
100 return next;
101 + }).pipe(
102 + Effect.andThen(
103 + Ref.update(htmlRenders, (current) => {
104 + const next = new Map(current);
105 + next.delete(threadId);
106 + return next;
107 + }),
108 + ),
109 + ),
110 + recordHtmlRender: (threadId, input, reference) =>
111 + Ref.update(htmlRenders, (current) =>
112 + new Map(current).set(
113 + threadId,
114 + [
115 + ...(current.get(threadId) ?? []),
116 + {
117 + title: input.title,
118 + height: input.height,
119 + htmlLength: input.html.length,
120 + htmlHash: hashHtml(input.html),
121 + // Copy the tail so its backing storage cannot retain the entire HTML string.
122 + htmlEnd: Buffer.from(input.html.slice(-KEPT_HTML_END_LENGTH), "utf16le").toString(
123 + "utf16le",
124 + ),
125 + reference,
126 + },
127 + ].slice(-MAX_KEPT_HTML_RENDERS),
128 + ),
129 + ),
130 + takeHtmlRender: (threadId, input, reported) =>
131 + Ref.modify(htmlRenders, (current) => {
132 + const kept = current.get(threadId) ?? [];
133 + const index =
134 + reported === undefined
135 + ? matchingPageIndex(kept, input)
136 + : kept.findIndex((page) => page.reference.attachmentId === reported.attachmentId);
137 + if (index === -1) {
138 + return [undefined, current];
139 + }
140 + const rest = kept.filter((_, keptIndex) => keptIndex !== index);
141 + const next = new Map(current);
142 + if (rest.length === 0) {
143 + next.delete(threadId);
144 + } else {
145 + next.set(threadId, rest);
146 + }
147 + return [kept[index]!.reference, next];
148 }),
149 });
150 });