Merge main into orchestration v2

Carry forward the reusable ACP replay, drain, and xAI extension work from #3156 while retaining V2-owned adapters, presentation, and provider-acknowledged cancellation semantics.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-25 23:55:10 -07:00
commit 1467717c12
17 files changed
+1609 -132

No files matched your search

+2
View File
@@ -1,4 +1,5 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -91,6 +92,7 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
+5 -1
View File
@@ -25,6 +25,7 @@ import type {
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import {
type BrowserWindow,
@@ -379,6 +380,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
artifactDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcessPlatform;
const path = yield* Path.Path;
const parentScope = yield* Scope.Scope;
const context = yield* Effect.context<never>();
@@ -2226,7 +2228,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
sendCleanup: SendCommand,
) {
yield* prepareAutomationInput(send, false);
const keySequence = makePreviewAutomationKeySequence(input);
const keySequence = makePreviewAutomationKeySequence(input, {
isMac: hostPlatform === "darwin",
});
const previouslyFocused = yield* attempt(
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
() => webContents.getFocusedWebContents(),
@@ -42,7 +42,9 @@ describe("preview keyboard packets", () => {
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown).toEqual({
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
@@ -50,9 +52,20 @@ describe("preview keyboard packets", () => {
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
@@ -20,6 +20,7 @@ export interface PreviewAutomationKeyEvent {
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
@@ -79,6 +80,42 @@ const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
@@ -136,12 +173,14 @@ function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
@@ -156,6 +195,7 @@ export function makePreviewAutomationKeySequence(
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
+260 -13
View File
@@ -19,6 +19,23 @@ const emitInterleavedAssistantToolCalls =
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
const omitXAiPromptCompleteStopReason =
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
const emitStaleXAiPromptCompleteBeforeSecondHang =
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
const emitOverlappingXAiPromptCompleteOutOfOrder =
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
@@ -40,8 +57,21 @@ let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
let authenticated = !requiresAuthentication;
let promptCount = 0;
let overlappingFirstPromptId: string | undefined;
const cancelledSessions = new Set<string>();
function promptIdFromRequestMeta(
request: Pick<AcpSchema.PromptRequest, "_meta">,
): string | undefined {
const meta = request._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
function logExit(reason: string): void {
if (!exitLogPath) {
return;
@@ -49,6 +79,10 @@ function logExit(reason: string): void {
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
function writeJsonRpcNotification(method: string, params: unknown): void {
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
@@ -325,22 +359,66 @@ const program = Effect.gen(function* () {
}),
);
const emitLoadReplayNotifications = (requestedSessionId: string) => {
writeJsonRpcNotification("session/update", {
_meta: { isReplay: true },
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "replay-tool-1",
title: "Replay tool",
kind: "search",
status: "completed",
},
});
writeJsonRpcNotification("session/update", {
_meta: { isReplay: true },
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replayed assistant text" },
},
});
};
yield* agent.handleLoadSession((request) =>
agent.client
.sessionUpdate({
sessionId: String(request.sessionId ?? sessionId),
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (failLoadSession) {
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
}
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
emitLoadReplayNotifications(requestedSessionId);
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay-tail" },
},
});
yield* Effect.sleep(loadSessionDelayMs);
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}
if (emitLoadReplay) {
emitLoadReplayNotifications(requestedSessionId);
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay" },
},
})
.pipe(
Effect.as({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
),
});
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
);
yield* agent.handleListSessions((request) =>
@@ -429,19 +507,152 @@ const program = Effect.gen(function* () {
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
Effect.gen(function* () {
const cancelledSessionId = String(sessionId ?? "mock-session-1");
cancelledSessions.add(cancelledSessionId);
if (emitLateUpdateAfterCancel) {
yield* Effect.sleep("50 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "late after cancel" },
},
});
});
}
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
promptCount += 1;
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (failPrompt) {
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
}
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
return {
stopReason: "end_turn",
_meta: {
promptId: "mock-stale-xai-prompt-1",
requestId: "mock-stale-xai-prompt-1",
},
};
}
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: "mock-stale-xai-prompt-1",
stopReason: "end_turn",
agentResult: null,
});
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: currentPromptId,
stopReason: "end_turn",
agentResult: null,
});
return yield* Effect.never;
}
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
overlappingFirstPromptId = promptIdFromRequestMeta(request);
return yield* Effect.never;
}
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
const secondPromptId = promptIdFromRequestMeta(request);
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: secondPromptId,
stopReason: "end_turn",
agentResult: null,
});
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: overlappingFirstPromptId,
stopReason: "end_turn",
agentResult: null,
});
}
return yield* Effect.never;
}
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
return yield* Effect.never;
}
if (emitXAiPromptCompleteThenHang) {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello from " },
},
});
if (emitForeignSessionUpdates) {
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child before completion" },
},
});
}
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
agentResult: null,
});
if (emitForeignSessionUpdates) {
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "child-tool-call-1",
title: "Child-only tool",
kind: "other",
status: "pending",
rawInput: {},
},
});
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child after completion" },
},
});
}
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "mock" },
},
});
return yield* Effect.never;
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
@@ -672,6 +883,42 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitForeignSessionUpdates) {
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "root before child" },
},
});
yield* agent.client.sessionUpdate({
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child content" },
},
});
yield* agent.client.sessionUpdate({
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "child-tool-call-1",
title: "Child-only tool",
kind: "other",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: " root after child" },
},
});
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
@@ -81,6 +81,7 @@ export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const;
export interface AcpAdapterV2RuntimeInput {
readonly cwd: string;
readonly mcpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly interruptPromptOnCancel: false;
readonly clientCapabilities: EffectAcpSchema.InitializeRequest["clientCapabilities"];
readonly clientInfo: AcpSessionRuntimeOptions["clientInfo"];
readonly requestLogger?: NonNullable<AcpSessionRuntimeOptions["requestLogger"]>;
@@ -604,6 +605,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
const runtime = yield* flavor.makeRuntime({
cwd: input.runtimePolicy.cwd ?? process.cwd(),
mcpServers: acpMcpServers(input.threadId),
interruptPromptOnCancel: false,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
@@ -7,6 +7,9 @@ import * as NodeFS from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as TestClock from "effect/testing/TestClock";
import * as Stream from "effect/Stream";
import { describe, expect } from "vite-plus/test";
@@ -200,6 +203,122 @@ describe("AcpSessionRuntime", () => {
),
);
it.effect("drops session updates emitted for a child ACP session", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes.map((note) => note._tag)).toEqual([
"AssistantItemStarted",
"ContentDelta",
"ContentDelta",
"AssistantItemCompleted",
]);
expect(
notes
.filter((note) => note._tag === "ContentDelta")
.map((note) => note.text)
.join(""),
).toBe("root before child root after child");
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("supports successive standard ACP prompts", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const firstPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "first" }],
});
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const promptFiber = yield* runtime
.prompt({
prompt: [{ type: "text", text: "hang forever" }],
})
.pipe(Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust("500 millis");
yield* runtime.cancel;
const firstPromptResult = yield* Fiber.join(promptFiber);
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("segments assistant text around ACP tool calls", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
@@ -490,6 +609,109 @@ describe("AcpSessionRuntime", () => {
);
});
it.effect("fails session startup when session/load returns an error", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const error = yield* runtime.start().pipe(Effect.flip);
expect(error._tag).toBe("AcpRequestError");
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_FAIL_LOAD_SESSION: "1",
},
},
cwd: process.cwd(),
resumeSessionId: "stale-session-id",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("ignores session/update replay notifications during session/load", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes.map((note) => note._tag)).toEqual([
"PlanUpdated",
"AssistantItemStarted",
"ContentDelta",
"AssistantItemCompleted",
]);
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_EMIT_LOAD_REPLAY: "1",
},
},
cwd: process.cwd(),
resumeSessionId: "mock-session-1",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
expect(started.sessionId).toBe("mock-session-1");
expect(started.sessionSetupResult._meta).toMatchObject({
t3SessionLoadReady: "replay_idle",
});
const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
Effect.timeoutOption("100 millis"),
);
expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
},
},
cwd: process.cwd(),
resumeSessionId: "mock-session-1",
sessionLoadReplayIdleGap: "50 millis",
sessionLoadTimeout: "1 second",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
TestClock.withLive,
),
);
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
@@ -8,6 +8,8 @@ import {
parsePermissionRequest,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateIsReplay,
syntheticLoadSessionResponseFromInitialize,
} from "./AcpRuntimeModel.ts";
describe("AcpRuntimeModel", () => {
@@ -59,6 +61,95 @@ describe("AcpRuntimeModel", () => {
expect(modelConfigId).toBe("model");
});
it("detects Grok session replay updates from _meta.isReplay", () => {
expect(
sessionUpdateIsReplay({
_meta: { isReplay: true },
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replayed" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
expect(
sessionUpdateIsReplay({
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "live" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(false);
});
it("builds a synthetic load response from initialize model state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.models?.currentModelId).toBe("grok-build");
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
});
it("accepts initialize model descriptions with null", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.models?.availableModels[0]?.description).toBeNull();
});
it("ignores malformed initialize model state in synthetic load responses", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [null],
},
modeState: {
currentModeId: "code",
availableModes: [{ id: "code", name: 12 }],
},
},
} as EffectAcpSchema.InitializeResponse);
expect(response.models).toBeUndefined();
expect(response.modes).toBeUndefined();
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
});
it("builds a synthetic load response with initialize mode state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modeState: {
currentModeId: "code",
availableModes: [
{ id: "ask", name: "Ask" },
{ id: "code", name: "Code" },
],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.modes?.currentModeId).toBe("code");
expect(response.modes?.availableModes).toHaveLength(2);
});
it("projects typed ACP tool call updates into runtime events", () => {
const created = parseSessionUpdateEvent({
sessionId: "session-1",
@@ -1,3 +1,8 @@
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import type * as EffectAcpSchema from "effect-acp/schema";
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
import type { ToolLifecycleItemType } from "@t3tools/contracts";
@@ -6,6 +11,40 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
if (!isRecord(value) || typeof value.currentModelId !== "string") {
return false;
}
if (!Array.isArray(value.availableModels)) {
return false;
}
return value.availableModels.every(
(model) =>
isRecord(model) &&
typeof model.modelId === "string" &&
typeof model.name === "string" &&
(model.description === undefined ||
model.description === null ||
typeof model.description === "string"),
);
}
function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
if (!isRecord(value) || typeof value.currentModeId !== "string") {
return false;
}
if (!Array.isArray(value.availableModes)) {
return false;
}
return value.availableModes.every(
(mode) =>
isRecord(mode) &&
typeof mode.id === "string" &&
typeof mode.name === "string" &&
(mode.description === undefined || typeof mode.description === "string"),
);
}
export interface AcpSessionMode {
readonly id: string;
readonly name: string;
@@ -415,6 +454,58 @@ export function parsePermissionRequest(
};
}
export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
const meta = params._meta;
return isRecord(meta) && meta.isReplay === true;
}
export interface SessionLoadGate {
readonly active: boolean;
readonly lastActivityAtMillis: number | undefined;
readonly idleGap: Duration.Duration;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
}
export const waitForSessionLoadReplayIdle = (input: {
readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
Effect.gen(function* () {
const pollInterval = Duration.millis(25);
while (true) {
const gate = yield* Ref.get(input.gateRef);
if (
Option.isSome(gate) &&
gate.value.active &&
gate.value.lastActivityAtMillis !== undefined
) {
const idleGapMillis = Duration.toMillis(gate.value.idleGap);
const nowMillis = yield* Clock.currentTimeMillis;
if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
}
}
yield* Effect.sleep(pollInterval);
}
});
export function syntheticLoadSessionResponseFromInitialize(
initializeResult: EffectAcpSchema.InitializeResponse,
): EffectAcpSchema.LoadSessionResponse {
const meta = initializeResult._meta;
const modelState = isRecord(meta) ? meta.modelState : undefined;
const modeState = isRecord(meta) ? meta.modeState : undefined;
const models = isSessionModelState(modelState) ? modelState : undefined;
const modes = isSessionModeState(modeState) ? modeState : undefined;
return {
...(models ? { models } : {}),
...(modes ? { modes } : {}),
_meta: {
t3SessionLoadReady: "replay_idle",
},
};
}
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
readonly modeId?: string;
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
+342 -108
View File
@@ -1,12 +1,16 @@
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -23,6 +27,9 @@ import {
mergeToolCallState,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateIsReplay,
waitForSessionLoadReplayIdle,
type SessionLoadGate,
type AcpParsedSessionEvent,
type AcpSessionModeState,
type AcpToolCallState,
@@ -32,6 +39,16 @@ function formatConfigOptionValue(value: string | boolean): string {
return JSON.stringify(value);
}
export interface AcpSessionEventStreamBarrier {
readonly _tag: "EventStreamBarrier";
readonly acknowledge: Deferred.Deferred<void>;
}
export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
const defaultSessionLoadTimeout = Duration.seconds(90);
const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
export interface AcpSpawnInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -43,6 +60,9 @@ export interface AcpSessionRuntimeOptions {
readonly spawn: AcpSpawnInput;
readonly cwd: string;
readonly resumeSessionId?: string;
readonly sessionLoadTimeout?: Duration.Input;
readonly sessionLoadReplayIdleGap?: Duration.Input;
readonly interruptPromptOnCancel?: boolean;
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
readonly clientInfo: {
readonly name: string;
@@ -92,69 +112,170 @@ export interface AcpSessionRuntimeStartResult {
readonly modelConfigId: string | undefined;
}
export interface AcpSessionRuntimeShape {
readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"];
readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"];
readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"];
readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"];
readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"];
readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"];
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"];
readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"];
readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"];
readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"];
readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"];
readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"];
readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"];
readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
readonly loadSession: (
sessionId: string,
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly resumeSession: (
sessionId: string,
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly forkSession: (
sessionId: string,
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly listSessions: (
cursor?: string,
) => Effect.Effect<EffectAcpSchema.ListSessionsResponse, EffectAcpErrors.AcpError>;
readonly closeSession: (
sessionId?: string,
) => Effect.Effect<EffectAcpSchema.CloseSessionResponse, EffectAcpErrors.AcpError>;
readonly prompt: (
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly setMode: (
modeId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
readonly setConfigOption: (
configId: string,
value: string | boolean,
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly setSessionModel: (
modelId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
readonly request: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
readonly notify: (
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
}
export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
"t3/provider/acp/AcpSessionRuntime",
) {
export class AcpSessionRuntime extends Context.Service<
AcpSessionRuntime,
{
/**
* Registers a handler for `session/request_permission`.
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
*/
readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"];
/**
* Registers a handler for `session/elicitation`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
*/
readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"];
/**
* Registers a handler for `fs/read_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
*/
readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"];
/**
* Registers a handler for `fs/write_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
*/
readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"];
/**
* Registers a handler for `terminal/create`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
*/
readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"];
/**
* Registers a handler for `terminal/output`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
*/
readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"];
/**
* Registers a handler for `terminal/wait_for_exit`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
*/
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"];
/**
* Registers a handler for `terminal/kill`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
*/
readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"];
/**
* Registers a handler for `terminal/release`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
*/
readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"];
/**
* Registers a handler for `session/update`.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"];
/**
* Registers a handler for `session/elicitation/complete`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
*/
readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"];
/**
* Registers a fallback extension request handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"];
/**
* Registers a fallback extension notification handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"];
/**
* Registers a typed extension request handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"];
/**
* Registers a typed extension notification handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
/**
* Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.
* Concurrent calls share the same in-flight startup and a failed startup may be retried.
*/
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
/** Stream of parsed ACP session events emitted after startup. */
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
/** Waits until the current event consumer has processed every queued event. */
readonly drainEvents: Effect.Effect<void>;
/** Latest mode state observed from session setup and `session/update` notifications. */
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
/** Latest configuration options observed from session setup and configuration writes. */
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
readonly loadSession: (
sessionId: string,
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly resumeSession: (
sessionId: string,
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly forkSession: (
sessionId: string,
) => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly listSessions: (
cursor?: string,
) => Effect.Effect<EffectAcpSchema.ListSessionsResponse, EffectAcpErrors.AcpError>;
readonly closeSession: (
sessionId?: string,
) => Effect.Effect<EffectAcpSchema.CloseSessionResponse, EffectAcpErrors.AcpError>;
/**
* Sends a prompt turn to the active session.
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
*/
readonly prompt: (
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
/**
* Sends a real ACP `session/cancel` notification for the active session.
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
*/
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
/**
* Selects the active mode through the negotiated `mode` configuration option.
* This is a no-op when the requested mode is already active.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setMode: (
modeId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
/**
* Updates a session configuration option and the runtime configuration snapshot.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setConfigOption: (
configId: string,
value: string | boolean,
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
/**
* Selects the base model through the negotiated model configuration option.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
/**
* Selects the active model through the unstable ACP `session/set_model` capability.
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
*/
readonly setSessionModel: (
modelId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
/**
* Sends a generic ACP extension request and records it through the request logger.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly request: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
/**
* Sends a generic ACP extension notification.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly notify: (
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
}
>()("t3/provider/acp/AcpSessionRuntime") {
static layer(
options: AcpSessionRuntimeOptions,
): Layer.Layer<
@@ -196,12 +317,17 @@ export const make = (
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
const promptSerializationSemaphore = yield* Semaphore.make(1);
const activePromptFiberRef = yield* Ref.make<
Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
>(Option.none());
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
const logRequest = (event: AcpSessionRequestLogEvent) =>
options.requestLogger ? options.requestLogger(event) : Effect.void;
@@ -273,15 +399,40 @@ export const make = (
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
yield* acp.handleSessionUpdate((notification) =>
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
Effect.gen(function* () {
const gate = yield* Ref.get(sessionLoadGateRef);
if (Option.isSome(gate) && gate.value.active) {
const lastActivityAtMillis = yield* Clock.currentTimeMillis;
yield* Ref.set(
sessionLoadGateRef,
Option.some({
...gate.value,
lastActivityAtMillis,
}),
);
return;
}
if (sessionUpdateIsReplay(notification)) {
return;
}
const startState = yield* Ref.get(startStateRef);
// One runtime projects one root ACP session. Child-session updates need
// explicit lineage routing and must never be flattened into this stream.
if (
startState._tag !== "Started" ||
notification.sessionId !== startState.result.sessionId
) {
return;
}
yield* handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
});
}),
);
const initializeClientCapabilities = {
fs: {
readTextFile: false,
@@ -498,27 +649,75 @@ export const make = (
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
acp.agent.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.agent.createSession(createPayload),
const sessionLoadTimeout = Duration.fromInputUnsafe(
options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
);
const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
);
yield* Ref.set(
sessionLoadGateRef,
Option.some({
active: true,
lastActivityAtMillis: undefined,
idleGap: sessionLoadReplayIdleGap,
initializeResult,
}),
);
sessionId = options.resumeSessionId;
sessionSetupResult = yield* Effect.gen(function* () {
yield* logRequest({
method: "session/load",
payload: loadPayload,
status: "started",
});
const idleFiber = yield* waitForSessionLoadReplayIdle({
gateRef: sessionLoadGateRef,
}).pipe(Effect.forkIn(runtimeScope));
const loaded = yield* Effect.raceFirst(
acp.agent.loadSession(loadPayload),
Fiber.join(idleFiber),
).pipe(
Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
Effect.timeoutOption(sessionLoadTimeout),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new EffectAcpErrors.AcpTransportError({
operation: "call-rpc",
method: "session/load",
detail:
"session/load timed out waiting for RPC response or replay idle gap",
cause: undefined,
}),
),
onSome: Effect.succeed,
}),
),
Effect.tap((result) =>
logRequest({
method: "session/load",
payload: loadPayload,
status: "succeeded",
result,
}),
),
Effect.onError((cause) =>
logRequest({
method: "session/load",
payload: loadPayload,
status: "failed",
cause,
}),
),
);
sessionId = created.sessionId;
sessionSetupResult = created;
}
return loaded;
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
} else {
const createPayload = {
cwd: options.cwd,
@@ -606,6 +805,14 @@ export const make = (
handleExtNotification: acp.handleExtNotification,
start: () => start,
getEvents: () => Stream.fromQueue(eventQueue),
drainEvents: Effect.gen(function* () {
const acknowledge = yield* Deferred.make<void>();
yield* Queue.offer(eventQueue, {
_tag: "EventStreamBarrier",
acknowledge,
});
yield* Deferred.await(acknowledge);
}),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
loadSession: (sessionId) =>
@@ -685,22 +892,37 @@ export const make = (
}),
),
prompt: (payload) =>
getStartedState.pipe(
Effect.flatMap((started) => {
promptSerializationSemaphore.withPermit(
Effect.gen(function* () {
const started = yield* getStartedState;
yield* closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
});
const requestPayload = {
sessionId: started.sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
return closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
}).pipe(
Effect.andThen(
runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
),
const cancelledResponse = {
stopReason: "cancelled",
} satisfies EffectAcpSchema.PromptResponse;
const promptRpcFiber = yield* runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
).pipe(Effect.forkIn(runtimeScope));
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
return yield* Fiber.join(promptRpcFiber).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.succeed(cancelledResponse)
: Effect.failCause(cause),
),
Effect.ensuring(
Effect.gen(function* () {
yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
yield* Ref.set(activePromptFiberRef, Option.none());
}),
),
Effect.tap(() =>
closeActiveAssistantSegment({
@@ -712,7 +934,19 @@ export const make = (
}),
),
cancel: getStartedState.pipe(
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
Effect.flatMap((started) =>
options.interruptPromptOnCancel === false
? acp.agent.cancel({ sessionId: started.sessionId })
: Effect.gen(function* () {
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
if (Option.isSome(activePromptFiber)) {
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
}
yield* acp.agent
.cancel({ sessionId: started.sessionId })
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
}),
),
),
setMode: (modeId) =>
Ref.get(modeStateRef).pipe(
@@ -791,7 +1025,7 @@ const handleSessionUpdate = ({
assistantSegmentRef,
params,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
@@ -887,7 +1121,7 @@ const ensureActiveAssistantSegment = ({
assistantSegmentRef,
sessionId,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
}) =>
@@ -924,7 +1158,7 @@ const closeActiveAssistantSegment = ({
queue,
assistantSegmentRef,
}: {
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
}) =>
Ref.modify(assistantSegmentRef, (current) => {
@@ -8,6 +8,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { normalizeModelSlug } from "@t3tools/shared/model";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
const GROK_API_KEY_ENV = "XAI_API_KEY";
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
@@ -68,9 +69,10 @@ export const makeGrokAcpRuntime = (
),
),
);
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(acpContext),
);
return yield* makeXAiPromptCompletionRuntime(runtime);
});
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
@@ -1,12 +1,39 @@
import { describe, expect, it } from "vite-plus/test";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { describe, expect } from "vite-plus/test";
import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
makeXAiPromptCompletionRuntime,
XAiAskUserQuestionRequest,
} from "./XAiAcpExtension.ts";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.make({
spawn: {
command: process.execPath,
args: [mockAgentPath],
env,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
});
return yield* makeXAiPromptCompletionRuntime(runtime);
});
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
@@ -247,4 +274,59 @@ describe("XAiAcpExtension", () => {
},
});
});
it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
Effect.gen(function* () {
const runtime = yield* makePromptCompletionRuntime({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
});
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const promptId = promptResult._meta?.promptId;
expect(typeof promptId).toBe("string");
expect(promptResult).toMatchObject({
stopReason: "end_turn",
_meta: {
sessionId: "mock-session-1",
promptId,
requestId: promptId,
},
});
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("ignores stale xAI completion from an already settled prompt", () =>
Effect.gen(function* () {
const runtime = yield* makePromptCompletionRuntime({
T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
});
yield* runtime.start();
const firstPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "first" }],
});
expect(firstPromptResult).toMatchObject({
stopReason: "end_turn",
_meta: { promptId: "mock-stale-xai-prompt-1" },
});
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
const secondPromptId = secondPromptResult._meta?.promptId;
expect(typeof secondPromptId).toBe("string");
expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
expect(secondPromptResult).toMatchObject({
stopReason: "end_turn",
_meta: {
promptId: secondPromptId,
requestId: secondPromptId,
},
});
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -1,5 +1,29 @@
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import type * as EffectAcpSchema from "effect-acp/schema";
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const XAiPromptCompleteNotification = Schema.Struct({
sessionId: Schema.String,
promptId: Schema.optional(Schema.String),
stopReason: Schema.optional(Schema.String),
agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
});
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
interface PendingXAiPromptCompletion {
readonly sessionId: string;
readonly promptId: string;
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
}
const completedXAiPromptIdLimit = 128;
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
const XAiAskUserQuestionOption = Schema.Struct({
label: Schema.String,
@@ -182,3 +206,238 @@ export function makeXAiAskUserQuestionResponse(
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
return { outcome: "cancelled" };
}
/**
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
* The underlying runtime remains unaware of xAI methods and metadata.
*/
export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
let nextPromptFallbackId = 0;
const allocatePromptFallbackId = Effect.sync(() => {
nextPromptFallbackId += 1;
return `t3-xai-prompt-${nextPromptFallbackId}`;
});
yield* runtime.handleExtNotification(
"_x.ai/session/prompt_complete",
XAiPromptCompleteNotification,
(notification) =>
resolveXAiPromptCompletionFallback({
pendingRef,
completedPromptIdsRef,
notification,
}),
);
return {
...runtime,
start: () =>
runtime
.start()
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
prompt: (payload) =>
Effect.gen(function* () {
const sessionId = yield* Ref.get(activeSessionIdRef);
if (sessionId === undefined) {
return yield* runtime.prompt(payload);
}
const promptId = yield* allocatePromptFallbackId;
const fallback = yield* registerXAiPromptCompletionFallback(
pendingRef,
sessionId,
promptId,
);
const requestPayload = {
...payload,
_meta: {
...payload._meta,
promptId: fallback.promptId,
requestId: fallback.promptId,
},
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
return yield* Effect.raceFirst(
runtime.prompt(requestPayload),
Deferred.await(fallback.deferred),
).pipe(
Effect.tap((response) =>
rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
),
Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
);
}),
cancel: Ref.get(activeSessionIdRef).pipe(
Effect.flatMap((sessionId) =>
sessionId === undefined
? runtime.cancel
: abortPendingPromptCompletions(pendingRef, sessionId).pipe(
Effect.andThen(runtime.cancel),
),
),
),
} satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
},
);
const registerXAiPromptCompletionFallback = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
sessionId: string,
promptId: string,
) =>
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
Effect.tap((deferred) =>
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
),
Effect.map((deferred) => ({ deferred, promptId })),
);
const unregisterXAiPromptCompletionFallback = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
const abortPendingPromptCompletions = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
sessionId: string,
) =>
Ref.modify(pendingRef, (pending) => {
const [toAbort, remaining] = pending.reduce<
[ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
>(
([aborting, kept], entry) =>
entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
[[], []],
);
if (toAbort.length === 0) {
return [Effect.void, pending] as const;
}
return [
Effect.forEach(
toAbort,
(entry) =>
Deferred.succeed(
entry.deferred,
promptResponseFromXAi({
sessionId: entry.sessionId,
promptId: entry.promptId,
stopReason: "cancelled",
agentResult: null,
}),
),
{ concurrency: "unbounded" },
).pipe(Effect.asVoid),
remaining,
] as const;
}).pipe(Effect.flatten);
const resolveXAiPromptCompletionFallback = ({
pendingRef,
completedPromptIdsRef,
notification,
}: {
readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
readonly notification: XAiPromptCompleteNotification;
}) =>
Ref.get(completedPromptIdsRef).pipe(
Effect.flatMap((completedPromptIds) => {
if (
notification.promptId !== undefined &&
completedPromptIds.includes(notification.promptId)
) {
return Effect.void;
}
return Ref.modify(pendingRef, (pending) => {
const index =
notification.promptId !== undefined
? pending.findIndex(
(entry) =>
entry.sessionId === notification.sessionId &&
entry.promptId === notification.promptId,
)
: pending.findIndex((entry) => entry.sessionId === notification.sessionId);
if (index < 0) {
return [Effect.void, pending] as const;
}
const entry = pending[index];
if (!entry) {
return [Effect.void, pending] as const;
}
return [
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
[...pending.slice(0, index), ...pending.slice(index + 1)],
] as const;
}).pipe(Effect.flatten);
}),
);
const rememberCompletedXAiPromptId = (
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
response: EffectAcpSchema.PromptResponse,
fallbackPromptId: string,
) => {
const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
if (completedPromptIds.includes(promptId)) {
return completedPromptIds;
}
return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
});
};
function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
const meta = response._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
export function promptResponseHasMissingXAiStopReason(
response: EffectAcpSchema.PromptResponse,
): boolean {
const meta = response._meta;
return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
}
function promptResponseFromXAi(
notification: XAiPromptCompleteNotification,
): EffectAcpSchema.PromptResponse {
const stopReason = normalizeXAiStopReason(notification.stopReason);
const meta: Record<string, unknown> = {
sessionId: notification.sessionId,
};
if (notification.stopReason === undefined) {
meta[xAiStopReasonMissingMetaKey] = true;
}
if (notification.promptId !== undefined) {
meta.promptId = notification.promptId;
meta.requestId = notification.promptId;
}
if (notification.agentResult !== undefined) {
meta.agentResult = notification.agentResult;
}
return {
stopReason,
_meta: meta,
};
}
function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
switch (value) {
case "cancelled":
case "end_turn":
case "max_tokens":
case "max_turn_requests":
case "refusal":
return value;
default:
return "end_turn";
}
}
@@ -51,6 +51,7 @@ import {
PreviewAutomationTargetUnavailableError,
PreviewAutomationViewportTimeoutError,
} from "./previewAutomationErrors";
import { previewAutomationOpenNeedsOverlay } from "./previewAutomationOpenReadiness";
import { createPreviewAutomationRequestConsumerAtom } from "./previewAutomationRequestConsumer";
import { createPreviewAutomationClientId } from "./previewAutomationClientId";
import {
@@ -333,6 +334,9 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
const input = request.input as PreviewAutomationOpenInput;
let activeTabId =
(input.reuseExistingTab ?? true) ? (state.snapshot?.tabId ?? null) : null;
let activeSnapshot = activeTabId
? (state.sessions[activeTabId] ?? state.snapshot ?? undefined)
: undefined;
const reusedExistingTab = activeTabId !== null;
tabId = activeTabId;
if (!activeTabId) {
@@ -349,17 +353,20 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
activeSnapshot = snapshot;
tabId = activeTabId;
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
}
if (reusedExistingTab && input.url && previewBridge) {
const resolution = resolveBrowserNavigationTarget(environmentId, {
kind: "url",
@@ -0,0 +1,46 @@
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { previewAutomationOpenNeedsOverlay } from "./previewAutomationOpenReadiness";
const snapshot = (navStatus: PreviewSessionSnapshot["navStatus"]): PreviewSessionSnapshot => ({
threadId: "thread-1",
tabId: "tab-1",
navStatus,
canGoBack: false,
canGoForward: false,
updatedAt: "2026-06-26T00:00:00.000Z",
});
describe("preview automation open readiness", () => {
it("does not wait for a desktop overlay when opening an empty tab", () => {
expect(
previewAutomationOpenNeedsOverlay(
{} as PreviewAutomationOpenInput,
snapshot({ _tag: "Idle" }),
),
).toBe(false);
});
it("waits when an empty tab is immediately given a URL", () => {
expect(
previewAutomationOpenNeedsOverlay(
{ url: "https://example.com" } as PreviewAutomationOpenInput,
snapshot({ _tag: "Idle" }),
),
).toBe(true);
});
it("waits for existing tabs that already have rendered content", () => {
expect(
previewAutomationOpenNeedsOverlay(
{} as PreviewAutomationOpenInput,
snapshot({
_tag: "Success",
url: "https://example.com/",
title: "Example",
}),
),
).toBe(true);
});
});
@@ -0,0 +1,8 @@
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
export function previewAutomationOpenNeedsOverlay(
input: PreviewAutomationOpenInput,
snapshot: PreviewSessionSnapshot,
): boolean {
return input.url !== undefined || snapshot.navStatus._tag !== "Idle";
}
+128 -1
View File
@@ -17,18 +17,59 @@ import { it, assert } from "@effect/vitest";
import * as AcpClient from "./client.ts";
import * as AcpSchema from "./_generated/schema.gen.ts";
import * as AcpError from "./errors.ts";
import { encodeJsonl, jsonRpcRequest, jsonRpcResponse } from "./_internal/shared.ts";
import {
encodeJsonl,
jsonRpcNotification,
jsonRpcRequest,
jsonRpcResponse,
} from "./_internal/shared.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);
const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);
const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
const XAiPromptCompleteNotification = jsonRpcNotification(
"_x.ai/session/prompt_complete",
Schema.Struct({
sessionId: Schema.String,
promptId: Schema.String,
stopReason: Schema.String,
agentResult: Schema.NullOr(Schema.Unknown),
}),
);
const XAiQueueChangedNotification = jsonRpcNotification(
"_x.ai/queue/changed",
Schema.Struct({
sessionId: Schema.String,
entries: Schema.Array(Schema.Unknown),
}),
);
const XAiSessionsChangedNotification = jsonRpcNotification(
"_x.ai/sessions/changed",
Schema.Struct({
upserted: Schema.Array(Schema.Unknown),
removed: Schema.Array(Schema.Unknown),
}),
);
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
);
const mockPeerArgs = (path: string) => [path];
function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
const batch = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
let offset = 0;
for (const chunk of chunks) {
batch.set(chunk, offset);
offset += chunk.length;
}
return batch;
}
it.layer(NodeServices.layer)("effect-acp client", (it) => {
const makeHandle = (env?: Record<string, string>) =>
Effect.gen(function* () {
@@ -446,4 +487,90 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
yield* Scope.close(scope, Exit.void);
}),
);
it.effect(
"routes a standard prompt response after Grok extension notifications in the same batch",
() =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const scope = yield* Scope.make();
const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
const promptFiber = yield* acp.agent
.prompt({
sessionId: "grok-session-1",
prompt: [{ type: "text", text: "run the ls command" }],
})
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
const decodedPrompt = yield* decodePromptRequestLine(outbound);
const responseBatch = concatBytes(
yield* Effect.all([
encodeJsonl(XAiQueueChangedNotification, {
jsonrpc: "2.0",
method: "_x.ai/queue/changed",
params: { sessionId: "grok-session-1", entries: [] },
}),
encodeJsonl(XAiPromptCompleteNotification, {
jsonrpc: "2.0",
method: "_x.ai/session/prompt_complete",
params: {
sessionId: "grok-session-1",
promptId: "prompt-1",
stopReason: "end_turn",
agentResult: null,
},
}),
encodeJsonl(XAiSessionsChangedNotification, {
jsonrpc: "2.0",
method: "_x.ai/sessions/changed",
params: {
upserted: [
{
sessionId: "grok-session-1",
title: null,
cwd: process.cwd(),
isWorktree: false,
modelId: "grok-composer-2.5-fast",
yolo: false,
activity: "idle",
resident: true,
lastChangeUnixMs: 1_710_000_000_000,
origin: { kind: "local" },
},
],
removed: [],
},
}),
encodeJsonl(PromptResponse, {
jsonrpc: "2.0",
id: decodedPrompt.id,
result: {
stopReason: "end_turn",
_meta: {
sessionId: "grok-session-1",
requestId: "prompt-1",
promptId: "prompt-1",
modelId: "grok-composer-2.5-fast",
},
},
}),
]),
);
yield* Queue.offer(input, responseBatch);
assert.deepEqual(yield* Fiber.join(promptFiber), {
stopReason: "end_turn",
_meta: {
sessionId: "grok-session-1",
requestId: "prompt-1",
promptId: "prompt-1",
modelId: "grok-composer-2.5-fast",
},
});
yield* Scope.close(scope, Exit.void);
}),
);
});