23
import * as Fiber from "effect/Fiber";
24
import * as Layer from "effect/Layer";
25
import * as Path from "effect/Path";
26
+import * as Queue from "effect/Queue";
27
import * as Ref from "effect/Ref";
28
import * as Stream from "effect/Stream";
29
import { ChildProcessSpawner } from "effect/process";
30
+import * as TestClock from "effect/testing/TestClock";
31
import type * as EffectAcpSchema from "effect-acp/compat";
32
import * as EffectAcpErrors from "effect-acp/errors";
33
40
import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts";
41
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
42
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
43
+import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
44
import {
45
makeAntigravityAcpAdapterFlavor,
46
makeAntigravityAdapterV2,
617
const report = { html: `<table>${rows.join("")}</table>`, title: "Revenue", height: 240 };
618
const failed = { ...report, html: "<p>Revenue</p>" };
619
const errored = { ...report, html: "<p>Revenue error</p>" };
620
+ const telemetry = {
621
+ html: `<ul>${rows.join("").replaceAll("tr", "li")}</ul>`,
622
+ title: "Telemetry",
623
+ height: 411,
624
+ };
625
const adapter = yield* makeAntigravityAdapterV2({
626
instanceId,
627
selfInvocation: yield* resolveSelfInvocation(),
738
status: "completed",
739
rawOutput: "Summary of published",
740
});
741
+ // agy 1.5.8 titles the call with its MCP name and completes without any output.
742
+ yield* send({
743
+ sessionUpdate: "tool_call",
744
+ toolCallId: "agy-1.5.8",
745
+ title: "Run mcp_t3-code_html_render",
746
+ kind: "other",
747
+ status: "in_progress",
748
+ rawInput: { ...telemetry, toolSummary: "Render telemetry" },
749
+ });
750
+ yield* mcpSessions.recordHtmlRender(threadId, telemetry, page("agy-1.5.8"));
751
+ yield* send({
752
+ sessionUpdate: "tool_call_update",
753
+ toolCallId: "agy-1.5.8",
754
+ status: "completed",
755
+ });
756
return { stopReason: "end_turn" as const };
757
}),
758
})),
878
),
879
[page("report"), page("report"), page("replacement"), page("replacement")],
880
);
858
- for (const name of ["failed-retry", "error-retry"]) {
881
+ for (const name of ["failed-retry", "error-retry", "agy-1.5.8"]) {
882
assert.deepEqual(tool(name), {
883
status: "completed",
884
toolName: "t3-code.html_render",
889
assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined);
890
assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined);
891
assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined);
892
+ assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined);
893
+ }).pipe(Effect.provide(layerSession)),
894
+ );
895
+});
896
+
897
+describe("AntigravityAdapterV2 work after the prompt ends", () => {
898
+ // Frames as agy 1.5.11 sent them for `run_command` with `WaitMsBeforeAsync`: the prompt returns
899
+ // end_turn, the command finishes later, and the agent replies with no prompt open.
900
+ it.effect("continues in one run when a finished background command wakes the agent", () =>
901
+ Effect.gen(function* () {
902
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
903
+ const path = yield* Path.Path;
904
+ const crypto = yield* SecureRandom.SecureRandom;
905
+ const mockAgentPath = yield* path.fromFileUrl(
906
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
907
+ );
908
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
909
+ let sessionUpdate: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
910
+ let requestPermission: Parameters<RuntimeService["handleRequestPermission"]>[0] | undefined;
911
+ const send = (update: EffectAcpSchema.SessionUpdate) =>
912
+ sessionUpdate === undefined
913
+ ? Effect.die("the adapter must handle session updates")
914
+ : sessionUpdate(
915
+ normalizeAntigravitySessionUpdate({ sessionId: "mock-session-1", update }),
916
+ );
917
+ const command = {
918
+ toolCallId: "call_fetch",
919
+ kind: "execute",
920
+ title: "node fetch_throughput.mjs",
921
+ rawInput: { CommandLine: "node fetch_throughput.mjs", WaitMsBeforeAsync: 10000 },
922
+ } as const;
923
+ const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const;
924
+ const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
925
+ const instanceId = ProviderInstanceId.make("antigravity-wake-test");
926
+ const threadId = ThreadId.make("thread-antigravity-wake");
927
+ const adapter = yield* makeAntigravityAdapterV2({
928
+ instanceId,
929
+ selfInvocation: yield* resolveSelfInvocation(),
930
+ continuationRequests: { offer: (request) => Effect.sync(() => void offers.push(request)) },
931
+ makeRuntime: (input) =>
932
+ makeAntigravityAcpRuntime({
933
+ ...input,
934
+ childProcessSpawner,
935
+ spawn: {
936
+ command: process.execPath,
937
+ args: [mockAgentPath],
938
+ cwd: input.cwd,
939
+ env: { T3_ACP_ANTIGRAVITY: "1" },
940
+ },
941
+ }).pipe(
942
+ Effect.provideService(SecureRandom.SecureRandom, crypto),
943
+ Effect.map((runtime): RuntimeService => ({
944
+ ...runtime,
945
+ handleSessionUpdate: (handler) =>
946
+ Effect.sync(() => {
947
+ sessionUpdate = handler;
948
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
949
+ handleRequestPermission: (handler) =>
950
+ Effect.sync(() => {
951
+ requestPermission = handler;
952
+ }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))),
953
+ prompt: () =>
954
+ Effect.gen(function* () {
955
+ yield* send({ sessionUpdate: "tool_call", ...command, status: "in_progress" });
956
+ yield* send({
957
+ sessionUpdate: "agent_message_chunk",
958
+ content: { type: "text", text: "I'll render once the fetch finishes." },
959
+ });
960
+ yield* send(usage);
961
+ return { stopReason: "end_turn" as const };
962
+ }),
963
+ })),
964
+ ),
965
+ withProcess: (_stop, task) => task,
966
+ defaultModel: Effect.undefined,
967
+ });
968
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
969
+ runtimeMode: "full-access",
970
+ interactionMode: "default",
971
+ cwd: process.cwd(),
972
+ });
973
+ const modelSelection = { instanceId, model: "gemini-test-low" } as const;
974
+ const session = yield* adapter.openSession({
975
+ threadId,
976
+ providerSessionId: ProviderSessionId.make("provider-session-antigravity-wake"),
977
+ modelSelection,
978
+ runtimePolicy,
979
+ });
980
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
981
+ yield* session.events.pipe(
982
+ Stream.runForEach((event) => Queue.offer(events, event)),
983
+ Effect.forkScoped,
984
+ );
985
+ const throughTerminal = Effect.gen(function* () {
986
+ const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
987
+ while (true) {
988
+ const event = yield* Queue.take(events);
989
+ seen.push(event);
990
+ if (event.type === "turn.terminal") return seen;
991
+ }
992
+ });
993
+ const providerThread = yield* session.ensureThread({
994
+ threadId,
995
+ modelSelection,
996
+ runtimePolicy,
997
+ });
998
+ const now = yield* DateTime.now;
999
+ const startTurn = (ordinal: number, continuation: boolean) =>
1000
+ session.startTurn({
1001
+ appThread: {
1002
+ createdBy: "user",
1003
+ creationSource: "web",
1004
+ id: threadId,
1005
+ projectId: ProjectId.make("project-antigravity-wake"),
1006
+ title: "Antigravity wake",
1007
+ providerInstanceId: instanceId,
1008
+ modelSelection,
1009
+ runtimeMode: "full-access",
1010
+ interactionMode: "default",
1011
+ branch: null,
1012
+ worktreePath: process.cwd(),
1013
+ activeProviderThreadId: providerThread.id,
1014
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1015
+ forkedFrom: null,
1016
+ createdAt: now,
1017
+ updatedAt: now,
1018
+ archivedAt: null,
1019
+ settledOverride: null,
1020
+ settledAt: null,
1021
+ lastVisitedAt: null,
1022
+ deletedAt: null,
1023
+ },
1024
+ threadId,
1025
+ runId: RunId.make(`run-antigravity-wake-${ordinal}`),
1026
+ runOrdinal: ordinal,
1027
+ providerTurnOrdinal: ordinal,
1028
+ attemptId: RunAttemptId.make(`attempt-antigravity-wake-${ordinal}`),
1029
+ rootNodeId: NodeId.make(`node-antigravity-wake-${ordinal}`),
1030
+ providerThread,
1031
+ message: {
1032
+ ...(continuation
1033
+ ? { createdBy: "agent" as const, creationSource: "provider" as const }
1034
+ : { createdBy: "user" as const, creationSource: "web" as const }),
1035
+ messageId: MessageId.make(`message-antigravity-wake-${ordinal}`),
1036
+ text: "chart the throughput",
1037
+ attachments: [],
1038
+ },
1039
+ modelSelection,
1040
+ runtimePolicy,
1041
+ });
1042
+
1043
+ yield* startTurn(1, false);
1044
+ const promptTerminal = (yield* throughTerminal).at(-1);
1045
+ assert.equal(promptTerminal?.type === "turn.terminal" && promptTerminal.status, "completed");
1046
+
1047
+ yield* send({
1048
+ sessionUpdate: "tool_call_update",
1049
+ ...command,
1050
+ status: "completed",
1051
+ rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1052
+ });
1053
+ assert.lengthOf(offers, 1, "the finished command must wake the thread");
1054
+ // The agent can ask before the app has started the continuation run.
1055
+ const followUp = { toolCallId: "call_analyze", kind: "execute", title: "node analyze.mjs" };
1056
+ const permission = yield* Effect.suspend(() =>
1057
+ requestPermission === undefined
1058
+ ? Effect.die("the adapter must handle permission requests")
1059
+ : requestPermission(
1060
+ {
1061
+ sessionId: "mock-session-1",
1062
+ toolCall: { ...followUp, status: "pending" },
1063
+ options: [
1064
+ { optionId: "allow", name: "Allow", kind: "allow_once" },
1065
+ { optionId: "deny", name: "Deny", kind: "reject_once" },
1066
+ ],
1067
+ },
1068
+ { requestId: "permission-1", method: "session/request_permission" },
1069
+ ),
1070
+ ).pipe(Effect.forkScoped({ startImmediately: true }));
1071
+ yield* offers[0]!.dispatchIfCurrent!(Effect.void);
1072
+ yield* startTurn(2, true);
1073
+ assert.deepEqual(yield* Fiber.join(permission), {
1074
+ outcome: { outcome: "selected", optionId: "allow" },
1075
+ });
1076
+
1077
+ // The model took 6.7 s to answer the finished command; the run must outlast that silence.
1078
+ yield* TestClock.adjust("10 seconds");
1079
+ yield* send({ sessionUpdate: "tool_call", ...followUp, status: "completed" });
1080
+ yield* send({
1081
+ sessionUpdate: "agent_message_chunk",
1082
+ content: { type: "text", text: "Here is the chart." },
1083
+ });
1084
+ yield* TestClock.adjust("10 seconds");
1085
+ yield* send(usage);
1086
+ yield* TestClock.adjust("3 seconds");
1087
+ const continued = yield* throughTerminal;
1088
+ const continuedTerminal = continued.at(-1);
1089
+ assert.equal(
1090
+ continuedTerminal?.type === "turn.terminal" && continuedTerminal.status,
1091
+ "completed",
1092
+ );
1093
+ assert.isTrue(
1094
+ continued.some(
1095
+ (event) =>
1096
+ event.type === "turn_item.updated" &&
1097
+ event.turnItem.type === "assistant_message" &&
1098
+ event.turnItem.runId === RunId.make("run-antigravity-wake-2"),
1099
+ ),
1100
+ "the reply belongs to the continuation run",
1101
+ );
1102
+ const finished = continued.findLast(
1103
+ (event) =>
1104
+ event.type === "turn_item.updated" &&
1105
+ event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1106
+ );
1107
+ assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed");
1108
+ assert.lengthOf(offers, 1, "one wake is one run");
1109
}).pipe(Effect.provide(layerSession)),
1110
);
1111
});