fix(orchestrator): Harden Grok v2 runtime lifecycle

Settle root turns from provider signals and preserve post-settle continuations.

Track asynchronous subagent and monitor work, allow image prompts, and keep steered messages visible.

Separate soft steering from hard Stop while containing and reaping native process trees.
This commit is contained in:
Mike Olson committed 2026-07-20 11:47:41 -04:00
1 parent 0f3ceb5f57
commit 542c87ba03
42 files changed
+15720 -774

No files matched your search

+10
View File
@@ -48,6 +48,16 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
# Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present),
# but ACP process-tree live tests compile a small pthread fixture with `cc`
# and soft-skip when it is missing. Install build-essential so that path
# always runs in CI instead of silently no-oping.
- name: Install C toolchain for process-tree fixtures
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends build-essential
command -v cc
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
+436 -1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as Effect from "effect/Effect";
@@ -17,13 +18,36 @@ const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitPostSettleMonitorFlow = process.env.T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW === "1";
const emitInTurnTaskOutputThenLateDuplicate =
process.env.T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE === "1";
const injectedReportTriggerPath = process.env.T3_ACP_INJECTED_REPORT_TRIGGER_PATH;
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitElicitation = process.env.T3_ACP_EMIT_ELICITATION === "1";
const emitUrlElicitation = process.env.T3_ACP_EMIT_URL_ELICITATION === "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 hangAfterPermission = process.env.T3_ACP_HANG_AFTER_PERMISSION === "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 emitTaskBackgroundedAfterCancel =
process.env.T3_ACP_EMIT_TASK_BACKGROUNDED_AFTER_CANCEL === "1";
const residualCallbackResponseLogPath = process.env.T3_ACP_RESIDUAL_CALLBACK_RESPONSE_LOG_PATH;
const residualCallbackTriggerPath = process.env.T3_ACP_RESIDUAL_CALLBACK_TRIGGER_PATH;
const exitAfterResidualCallbacks = process.env.T3_ACP_EXIT_AFTER_RESIDUAL_CALLBACKS === "1";
const emitRunningCommandThenHang = process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG === "1";
const emitRunningCommandThenHangOnFirstPrompt =
process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG_FIRST_PROMPT === "1";
const emitEmptySuccessfulBash = process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH === "1";
const emitEmptySuccessfulBashThenHang =
process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG === "1";
const exitOnCancel = process.env.T3_ACP_EXIT_ON_CANCEL === "1";
const runningCommandIgnoresTerm = process.env.T3_ACP_RUNNING_COMMAND_IGNORE_TERM === "1";
const runningCommandPidPath = process.env.T3_ACP_RUNNING_COMMAND_PID_PATH;
const runningCommandSeparateSession = process.env.T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION === "1";
const exitAfterRunningCommandLaunch = process.env.T3_ACP_EXIT_AFTER_RUNNING_COMMAND_LAUNCH === "1";
const omitXAiPromptCompleteStopReason =
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
@@ -83,6 +107,11 @@ function writeJsonRpcNotification(method: string, params: unknown): void {
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
}
function logResidualCallbackResponse(kind: string): void {
if (!residualCallbackResponseLogPath) return;
NodeFS.appendFileSync(residualCallbackResponseLogPath, `${kind}\n`, "utf8");
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
@@ -481,6 +510,9 @@ const program = Effect.gen(function* () {
Effect.gen(function* () {
const cancelledSessionId = String(sessionId ?? "mock-session-1");
cancelledSessions.add(cancelledSessionId);
if (exitOnCancel) {
return yield* Effect.sync(() => process.exit(0));
}
if (emitLateUpdateAfterCancel) {
yield* Effect.sleep("50 millis");
yield* Effect.sync(() => {
@@ -493,6 +525,36 @@ const program = Effect.gen(function* () {
});
});
}
if (emitTaskBackgroundedAfterCancel) {
// Grok cancel-as-detach: the foreground command is re-run as a
// background task that later completes on its own.
yield* Effect.sync(() => {
writeJsonRpcNotification("_x.ai/task_backgrounded", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "task_backgrounded",
tool_call_id: "task-bg-1",
task_id: "task-bg-1",
command: "sleep 30",
},
});
});
yield* Effect.sleep("1200 millis")
.pipe(
Effect.andThen(
Effect.sync(() => {
writeJsonRpcNotification("_x.ai/task_completed", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "task_completed",
task_snapshot: { task_id: "task-bg-1", command: "sleep 30" },
},
});
}),
),
)
.pipe(Effect.forkDetach);
}
}),
);
@@ -501,6 +563,80 @@ const program = Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
promptCount += 1;
if (residualCallbackTriggerPath !== undefined) {
yield* Effect.gen(function* () {
while (!(yield* Effect.sync(() => NodeFS.existsSync(residualCallbackTriggerPath)))) {
yield* Effect.sleep("20 millis");
}
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "residual assistant callback" },
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "residual-tool-call",
title: "Residual tool callback",
kind: "other",
status: "pending",
rawInput: {},
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "plan",
entries: [
{ content: "Residual plan callback", priority: "high", status: "pending" },
],
},
});
});
yield* agent.client
.requestPermission({
sessionId: requestedSessionId,
toolCall: {
toolCallId: "residual-permission",
title: "Residual permission callback",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
})
.pipe(
Effect.exit,
Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("permission"))),
Effect.ignore,
Effect.forkDetach,
);
yield* agent.client
.elicit({
sessionId: requestedSessionId,
message: "Residual elicitation callback",
mode: "form",
requestedSchema: {
type: "object",
properties: {
approved: { type: "boolean", title: "Approved" },
},
},
})
.pipe(
Effect.exit,
Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("elicitation"))),
Effect.ignore,
Effect.forkDetach,
);
if (exitAfterResidualCallbacks) {
yield* Effect.sleep("100 millis");
return yield* Effect.sync(() => process.exit(0));
}
}).pipe(Effect.forkDetach);
}
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
@@ -562,10 +698,126 @@ const program = Effect.gen(function* () {
return yield* Effect.never;
}
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
if (
hangPromptForever ||
(hangFirstPromptForever && promptCount === 1) ||
(emitEmptySuccessfulBashThenHang && promptCount === 2)
) {
return yield* Effect.never;
}
if (
emitRunningCommandThenHang ||
(emitRunningCommandThenHangOnFirstPrompt && promptCount === 1)
) {
const toolCallId = "tool-call-running-1";
if (runningCommandPidPath !== undefined) {
const command = runningCommandIgnoresTerm
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"'
: 'sleep 120 & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"';
if (runningCommandSeparateSession) {
const launcher = [
'const { spawn } = require("node:child_process");',
"const child = spawn(process.argv[1], process.argv.slice(2), { stdio: 'ignore' });",
"child.once('exit', (code, signal) => process.exitCode = code ?? (signal ? 1 : 0));",
].join(" ");
const detachedCommand = runningCommandIgnoresTerm
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"'
: 'sleep 120 & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"';
// Nested bash publishes "$PPID $$ $child" once it starts. Do not
// write the launcher PID alone here: that races with bash and can
// clobber the triple that interrupt tests wait for.
const detachedLauncher = NodeChildProcess.spawn(
process.execPath,
["-e", launcher, "bash", "-c", detachedCommand, "bash", runningCommandPidPath],
{ detached: true, stdio: "ignore" },
);
detachedLauncher.unref();
} else {
NodeChildProcess.spawn("bash", ["-c", command, "bash", runningCommandPidPath], {
stdio: "ignore",
});
}
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
command: ["sleep", "120"],
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
title: "Terminal",
kind: "execute",
status: "in_progress",
rawInput: {
command: ["sleep", "120"],
},
// Grok-like mid-stream Bash re-report: exit_code 0 while still running.
rawOutput: { type: "Bash", exit_code: 0 },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-output-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_id: "task-running-1" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-output-1",
status: "in_progress",
rawOutput: { task_id: "task-running-1", status: "running" },
},
});
if (exitAfterRunningCommandLaunch) {
yield* Effect.sleep("100 millis");
return yield* Effect.sync(() => process.exit(0));
}
// Stay open until session/cancel so interrupt tests can observe a running tool.
while (!cancelledSessions.has(requestedSessionId)) {
yield* Effect.sleep("25 millis");
}
cancelledSessions.delete(requestedSessionId);
return { stopReason: "cancelled" };
}
if (emitEmptySuccessfulBash || (emitEmptySuccessfulBashThenHang && promptCount === 1)) {
const update = {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-empty-success-1",
title: "Terminal",
kind: "execute",
status: "completed",
rawInput: { command: "true" },
rawOutput: { type: "Bash", exit_code: 0 },
},
} as const;
yield* agent.client.sessionUpdate(update);
yield* Effect.sleep("25 millis");
yield* agent.client.sessionUpdate(update);
return { stopReason: "end_turn" };
}
if (emitXAiPromptCompleteThenHang) {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
@@ -674,6 +926,32 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitElicitation) {
yield* agent.client.elicit({
sessionId: requestedSessionId,
message: "Approve this request?",
mode: "form",
requestedSchema: {
type: "object",
properties: {
approved: { type: "boolean", title: "Approved" },
},
},
});
return { stopReason: "end_turn" };
}
if (emitUrlElicitation) {
yield* agent.client.elicit({
sessionId: requestedSessionId,
message: "Open authentication page",
mode: "url",
url: "https://example.com/auth",
elicitationId: "url-elicitation-1",
});
return { stopReason: "end_turn" };
}
if (emitToolCalls) {
const toolCallId = "tool-call-1";
@@ -732,6 +1010,10 @@ const program = Effect.gen(function* () {
cancelledSessions.delete(requestedSessionId) ||
permission.outcome.outcome === "cancelled";
if (hangAfterPermission) {
return yield* Effect.never;
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
@@ -798,6 +1080,159 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
// In-turn monitor + TaskOutput hydrate, then a late post-finalize
// duplicate terminal TaskOutput for the same task. Exercises the
// already-handled short-circuit: must not pin hasPendingBackgroundWork.
if (emitInTurnTaskOutputThenLateDuplicate) {
const monitorToolCallId = "tool-call-monitor-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: monitorToolCallId,
title: "Monitor: mock background task",
kind: "execute",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: monitorToolCallId,
status: "in_progress",
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-fetch-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_id: "task-monitor-1" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-fetch-1",
status: "completed",
rawOutput: { output: "MONITOR_LISTING_TOKEN" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Monitor listing ready in-turn." },
},
});
// After deferred finalize (~2s) clears activeTurn, re-emit a terminal
// TaskOutput for the same task so bufferPostSettleWake sees
// alreadyHandledToolUpdate with a non-empty wake path.
yield* Effect.gen(function* () {
yield* Effect.sleep("2500 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-fetch-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "completed",
rawOutput: { output: "MONITOR_LISTING_TOKEN_LATE" },
},
});
});
}).pipe(Effect.forkDetach);
return { stopReason: "end_turn" };
}
if (emitPostSettleMonitorFlow) {
const monitorToolCallId = "tool-call-monitor-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: monitorToolCallId,
title: "Monitor: mock background task",
kind: "execute",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: monitorToolCallId,
status: "in_progress",
},
});
// After the prompt settles, replay the CLI-injected monitor-event
// turn: end notice, TaskOutput hydration, then (once the trigger
// file exists) the report chunk. Detached fiber on the real clock;
// it outlives the prompt handler.
yield* Effect.gen(function* () {
yield* Effect.sleep("150 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "user_message_chunk",
content: {
type: "text",
text: 'Monitor "task-monitor-1" ended: [monitor ended: exit 0]',
},
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-fetch-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_id: "task-monitor-1" },
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-fetch-1",
status: "completed",
rawOutput: { output: "MONITOR_LISTING_TOKEN" },
},
});
});
if (injectedReportTriggerPath === undefined) return;
while (!(yield* Effect.sync(() => NodeFS.existsSync(injectedReportTriggerPath)))) {
yield* Effect.sleep("20 millis");
}
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" },
},
});
});
}).pipe(Effect.forkDetach);
return { stopReason: "end_turn" };
}
if (emitAskQuestion) {
yield* agent.client.extRequest("cursor/ask_question", {
toolCallId: "ask-question-tool-call-1",
@@ -0,0 +1,37 @@
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
static const char *pid_path;
static void *spawn_child(void *unused) {
(void)unused;
pid_t child = fork();
if (child == 0) {
execlp("sleep", "sleep", "120", NULL);
_exit(127);
}
if (child < 0) return NULL;
FILE *file = fopen(pid_path, "w");
if (file != NULL) {
fprintf(file, "%ld %d\n", syscall(SYS_gettid), child);
fclose(file);
}
waitpid(child, NULL, 0);
return NULL;
}
int main(int argc, char **argv) {
if (argc != 2) return 2;
pid_path = argv[1];
pthread_t worker;
if (pthread_create(&worker, NULL, spawn_child, NULL) != 0) return 3;
if (pthread_join(worker, NULL) != 0) return 4;
return 0;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,9 +1,25 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type * as EffectAcpSchema from "effect-acp/schema";
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
import { AcpProviderCapabilitiesV2, acpPermissionDisposition } from "./AcpAdapterV2.ts";
import { GrokProviderCapabilitiesV2 } from "./GrokAdapterV2.ts";
import {
AcpProviderCapabilitiesV2,
acpCompletedTurnShouldTerminalizeTool,
acpPermissionDisposition,
acpRootSessionUpdateIngestsOutput,
acpRootTurnCompletionDrainMs,
acpRootTurnHasIngestedOutput,
acpRootTurnIsIdle,
acpRootTurnSettleDebounceMs,
acpRootTurnShouldRearmRecoveryTimers,
acpSupportsImagePrompts,
} from "./AcpAdapterV2.ts";
import {
makeGrokAcpAdapterFlavor,
GrokProviderCapabilitiesV2,
type GrokAdapterV2Options,
} from "./GrokAdapterV2.ts";
function permissionRequest(
kind: EffectAcpSchema.ToolKind,
@@ -37,7 +53,221 @@ function runtimePolicy(input: {
});
}
describe("acpRootTurnSettleDebounceMs", () => {
it("keeps the historical debounce constant for re-enable experiments", () => {
assert.equal(acpRootTurnSettleDebounceMs, 2_000);
});
});
describe("acpRootTurnCompletionDrainMs", () => {
it("gives trailing root chunks a short landing window", () => {
assert.equal(acpRootTurnCompletionDrainMs, 100);
});
});
describe("acpRootSessionUpdateIngestsOutput", () => {
const sessionId = "session-1";
it("ignores empty assistant chunks used as Grok keepalives", () => {
assert.isFalse(
acpRootSessionUpdateIngestsOutput({
sessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "" },
},
}),
);
});
it("accepts non-empty assistant and reasoning chunks", () => {
assert.isTrue(
acpRootSessionUpdateIngestsOutput({
sessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello" },
},
}),
);
assert.isTrue(
acpRootSessionUpdateIngestsOutput({
sessionId,
update: {
sessionUpdate: "agent_thought_chunk",
content: { type: "text", text: "thinking" },
},
}),
);
});
it("accepts tool and plan updates", () => {
assert.isTrue(
acpRootSessionUpdateIngestsOutput({
sessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-1",
title: "Read",
kind: "read",
status: "pending",
},
}),
);
assert.isTrue(
acpRootSessionUpdateIngestsOutput({
sessionId,
update: {
sessionUpdate: "plan",
entries: [{ content: "Step 1", status: "pending", priority: "medium" }],
},
}),
);
});
});
describe("acpRootTurnHasIngestedOutput", () => {
const empty = {
assistant: { current: null, nextSegment: 0 },
reasoning: { current: null, nextSegment: 0 },
tools: new Map(),
plan: null,
} as const;
it("is false before any root turn items land", () => {
assert.isFalse(acpRootTurnHasIngestedOutput(empty));
});
it("is true once assistant segments have streamed", () => {
assert.isTrue(
acpRootTurnHasIngestedOutput({
...empty,
assistant: { current: null, nextSegment: 1 },
}),
);
});
});
describe("acpRootTurn recovery timer re-arm", () => {
it("re-arms idle settle after pending clears on active turns", () => {
assert.isTrue(acpRootTurnShouldRearmRecoveryTimers({ finalized: false, interrupted: false }));
});
it("skips re-arm when the turn is already terminal", () => {
assert.isFalse(acpRootTurnShouldRearmRecoveryTimers({ finalized: true, interrupted: false }));
assert.isFalse(acpRootTurnShouldRearmRecoveryTimers({ finalized: false, interrupted: true }));
});
});
describe("acpRootTurnIsIdle", () => {
const quiet = {
finalized: false,
interrupted: false,
assistantStreamOpen: false,
reasoningStreamOpen: false,
hasRunningTool: false,
hasPendingRuntimeRequest: false,
hasToolHistory: false,
hasRunningSubagent: false,
hasOutput: true,
} as const;
it("is false while assistant text is still streaming", () => {
assert.isFalse(acpRootTurnIsIdle({ ...quiet, assistantStreamOpen: true }));
});
it("is false while a tool is running", () => {
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasRunningTool: true }));
});
it("is false after tool history (prompt RPC owns terminalization)", () => {
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasToolHistory: true }));
});
it("is false while a native subagent task is still running", () => {
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasRunningSubagent: true }));
});
it("is false when only reasoning or tools have streamed", () => {
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasOutput: false }));
});
it("is false for assistant-only quiet (preamble-before-tools must not settle)", () => {
assert.isFalse(acpRootTurnIsIdle(quiet));
});
it("is false when tools finished and root is quiet (no speculative multi-wave settle)", () => {
assert.isFalse(
acpRootTurnIsIdle({
...quiet,
hasToolHistory: true,
hasRunningTool: false,
}),
);
});
});
describe("GrokAdapterV2 capabilities", () => {
it("wires hard Stop teardown but soft non-Stop interrupts in the constructor flavor", () => {
const flavor = makeGrokAcpAdapterFlavor({
makeRuntime: () => Effect.never,
} as unknown as GrokAdapterV2Options);
assert.isFalse(flavor.interruptPromptOnCancel);
// User Stop (requestRuntimeRestart) keeps the hard process-group kill and
// respawn: Grok cancel is detach-and-continue, so only a process kill
// stops the work.
assert.isTrue(flavor.restartRuntimeAfterInterrupt);
assert.isTrue(flavor.terminateRuntimeProcessGroupOnInterrupt);
// Non-Stop interrupts (steering, restart_active) reuse the process and
// session; the cancelled work backgrounds and the model decides its fate.
assert.isUndefined(flavor.restartRuntimeOnEveryInterrupt);
assert.isTrue(flavor.preserveRuntimeOnSettledInterrupt);
});
it("terminalizes only foreground tools under the actual Grok flavor", () => {
const flavor = makeGrokAcpAdapterFlavor({
makeRuntime: () => Effect.never,
} as unknown as GrokAdapterV2Options);
const foreground = {
toolCallId: "foreground-1",
title: "Terminal",
status: "inProgress" as const,
data: {
rawInput: { command: "true" },
rawOutput: { type: "Bash", exit_code: 0 },
},
};
const monitor = {
toolCallId: "monitor-1",
title: "Monitor",
status: "inProgress" as const,
data: {
rawInput: { variant: "Monitor", command: "sleep 30" },
rawOutput: {
type: "Monitor",
taskId: "019f44b8-8e98-7c80-a40e-df1e26a5f9e3",
},
},
};
const subagent = {
toolCallId: "subagent-1",
title: "Task",
status: "inProgress" as const,
data: {
rawInput: {
description: "Inspect interrupt handling",
prompt: "Review the adapter.",
subagent_type: "generalPurpose",
},
},
};
assert.isTrue(acpCompletedTurnShouldTerminalizeTool(foreground, flavor));
assert.isFalse(acpCompletedTurnShouldTerminalizeTool(monitor, flavor));
assert.isFalse(acpCompletedTurnShouldTerminalizeTool(subagent, flavor));
});
it("keeps optional protocol features conservative until a flavor or handshake confirms them", () => {
assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsModelSwitchInSession);
assert.isFalse(AcpProviderCapabilitiesV2.sessions.supportsRuntimeModeSwitchInSession);
@@ -45,6 +275,27 @@ describe("GrokAdapterV2 capabilities", () => {
assert.isFalse(AcpProviderCapabilitiesV2.tools.supportsMcpTools);
});
it("overrides ACP image capability false so screenshot attachments can prompt", () => {
// Handshake alone would refuse attachments (Grok advertises image:false).
assert.isFalse(
acpSupportsImagePrompts({
negotiatedImage: false,
}),
);
// Flavor override unblocks image content blocks for Grok.
assert.isTrue(
acpSupportsImagePrompts({
flavorSupportsImagePrompts: true,
negotiatedImage: false,
}),
);
assert.isTrue(
acpSupportsImagePrompts({
negotiatedImage: true,
}),
);
});
it("declares Grok Task envelopes as native subagents", () => {
assert.isFalse(GrokProviderCapabilitiesV2.threads.canForkThread);
assert.isTrue(GrokProviderCapabilitiesV2.subagents.supportsSubagents);
@@ -21,17 +21,26 @@ import {
resolveGrokAcpBaseModelId,
} from "../../provider/acp/GrokAcpSupport.ts";
import {
extractXAiAcpBackgroundToolMutation,
extractXAiAcpSubagentEndNotice,
extractXAiAcpSubagentUpdate,
extractXAiAskUserQuestionIdentity,
extractXAiAskUserQuestions,
extractXAiAcpSubagentUpdate,
extractXAiBackgroundTaskCompletion,
extractXAiKilledBackgroundTasks,
extractXAiMonitorTaskId,
isXAiPersistentMonitor,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
normalizeXAiAcpToolCallState,
registerXAiBackgroundTaskTracking,
XAiAskUserQuestionRequest,
} from "../../provider/acp/XAiAcpExtension.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts";
import { IdAllocatorV2 } from "../IdAllocator.ts";
import { ProviderContinuationRequests } from "../ProviderContinuationRequests.ts";
import { ProviderAdapterV2 } from "../ProviderAdapter.ts";
import {
ProviderAdapterDriverCreateError,
@@ -41,6 +50,7 @@ import {
import {
AcpProviderCapabilitiesV2,
makeAcpAdapterV2,
type AcpAdapterV2ExtensionContext,
type AcpAdapterV2Flavor,
type AcpAdapterV2RuntimeInput,
} from "./AcpAdapterV2.ts";
@@ -89,6 +99,7 @@ export interface GrokAdapterV2Options {
readonly idAllocator: IdAllocatorV2["Service"];
readonly serverConfig: ServerConfig["Service"];
readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
readonly makeRuntime?: (
input: AcpAdapterV2RuntimeInput,
) => Effect.Effect<
@@ -102,7 +113,16 @@ export interface GrokAdapterV2Options {
export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
runtime,
requestUserInput,
applyBackgroundTaskMutation,
}) =>
registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation).pipe(
Effect.andThen(registerGrokAskUserQuestionExtensions({ runtime, requestUserInput })),
);
const registerGrokAskUserQuestionExtensions = ({
runtime,
requestUserInput,
}: Pick<AcpAdapterV2ExtensionContext, "runtime" | "requestUserInput">) =>
Effect.forEach(
["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
(method) =>
@@ -116,37 +136,78 @@ export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["register
}));
return requestUserInput({
nativeItemId: `${identity.sessionId}:xai-question:${identity.toolCallId}`,
nativeMethod: method,
nativeRequestId: identity.toolCallId,
nativeSessionId: identity.sessionId,
questions,
}).pipe(
Effect.map((answers) =>
answers === null
? makeXAiAskUserQuestionCancelledResponse()
: makeXAiAskUserQuestionResponse(params, answers),
Effect.flatMap(({ acknowledgeNativeResponse, answers }) =>
Effect.succeed(
answers === null
? makeXAiAskUserQuestionCancelledResponse()
: makeXAiAskUserQuestionResponse(params, answers),
).pipe(Effect.tap(() => acknowledgeNativeResponse)),
),
);
}),
{ discard: true },
);
export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
const flavor: AcpAdapterV2Flavor = {
export function makeGrokAcpAdapterFlavor(options: GrokAdapterV2Options): AcpAdapterV2Flavor {
return {
driver: GROK_PROVIDER,
capabilities: GrokProviderCapabilitiesV2,
// Idle settle over-settled preamble-before-tools turns and cancelled the
// prompt while Grok continued, freezing T3 projection mid-turn.
settleRootTurnWhenIdle: false,
interruptPromptOnCancel: false,
// User Stop (requestRuntimeRestart) still hard-kills the process group
// and respawns: Grok `session/cancel` is detach-and-continue (the CLI
// re-runs cancelled foreground work as a background task no client RPC
// can kill, E3 harness 2026-07-18), so only a process kill truly stops
// work. Non-Stop interrupts (mid-prompt steering, restart_active) omit
// requestRuntimeRestart and stay soft: the session survives in the same
// process, cancelled work backgrounds, and the model itself decides via
// kill_command_or_subagent whether it keeps running.
restartRuntimeAfterInterrupt: true,
terminateRuntimeProcessGroupOnInterrupt: true,
// Steering restarts on a settled turn additionally skip session/cancel so
// fire-and-forget subagents survive the steer (E1 harness confirmed the
// Grok CLI accepts a concurrent session/prompt in that state).
preserveRuntimeOnSettledInterrupt: true,
// Grok ACP initialize reports promptCapabilities.image:false but the agent
// still accepts image content blocks (verified with real screenshots).
supportsImagePrompts: true,
resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model),
makeRuntime:
options.makeRuntime ??
((input) =>
makeGrokAcpRuntime({
...input,
interruptPromptOnCancel: input.interruptPromptOnCancel ?? false,
grokSettings: options.settings,
environment: options.environment,
childProcessSpawner: options.childProcessSpawner,
})),
registerExtensions: registerGrokAcpExtensions,
extractSubagentUpdate: extractXAiAcpSubagentUpdate,
extractSubagentEndNotice: extractXAiAcpSubagentEndNotice,
normalizeToolCall: normalizeXAiAcpToolCallState,
extractBackgroundTaskId: extractXAiMonitorTaskId,
extractBackgroundToolMutation: extractXAiAcpBackgroundToolMutation,
extractBackgroundTaskCompletion: (toolCall) => [
...extractXAiBackgroundTaskCompletion(toolCall),
...extractXAiKilledBackgroundTasks(toolCall),
],
isPersistentBackgroundTool: isXAiPersistentMonitor,
deferFinalizeForBackgroundWork: true,
enablePostSettleContinuation: true,
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
};
}
export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
const flavor = makeGrokAcpAdapterFlavor(options);
return makeAcpAdapterV2({
instanceId: options.instanceId,
flavor,
@@ -155,6 +216,9 @@ export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
idAllocator: options.idAllocator,
serverConfig: options.serverConfig,
...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
...(options.continuationRequests === undefined
? {}
: { continuationRequests: options.continuationRequests }),
});
}
@@ -179,6 +243,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
const idAllocator = yield* IdAllocatorV2;
const providerEventLoggers = yield* ProviderEventLoggers;
const serverConfig = yield* ServerConfig;
const continuationRequests = yield* ProviderContinuationRequests;
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
return makeGrokAdapterV2({
instanceId: input.instanceId,
@@ -189,6 +254,7 @@ export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapte
fileSystem,
idAllocator,
serverConfig,
continuationRequests,
nativeLogging: (threadId) =>
makeNativeLogger({
nativeEventLogger: providerEventLoggers.native,
@@ -231,6 +297,7 @@ export const layer: Layer.Layer<
const idAllocator = yield* IdAllocatorV2;
const providerEventLoggers = yield* ProviderEventLoggers;
const serverConfig = yield* ServerConfig;
const continuationRequests = yield* ProviderContinuationRequests;
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
return makeGrokAdapterV2({
instanceId: GROK_DEFAULT_INSTANCE_ID,
@@ -241,6 +308,7 @@ export const layer: Layer.Layer<
fileSystem,
idAllocator,
serverConfig,
continuationRequests,
nativeLogging: (threadId) =>
makeNativeLogger({
nativeEventLogger: providerEventLoggers.native,
@@ -17,7 +17,11 @@ import * as Ref from "effect/Ref";
import { CheckpointRollbackServiceV2 } from "./CheckpointRollbackService.ts";
import type { OrchestrationEffectV2 } from "./EffectOutbox.ts";
import { executorLayer, OrchestrationEffectExecutorV2 } from "./EffectWorker.ts";
import {
executorLayer,
isNonRetryableProviderTurnControlFailure,
OrchestrationEffectExecutorV2,
} from "./EffectWorker.ts";
import { RunFinalizationService } from "./RunFinalizationService.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";
@@ -133,6 +137,40 @@ function makeExecutorLayer(input: {
return executorLayer.pipe(Layer.provide(dependencies));
}
it("does not retry pure interrupt races where the turn is already gone", () => {
assert.isTrue(
isNonRetryableProviderTurnControlFailure(
"provider-turn.interrupt",
"ProviderAdapterInterruptError: ... ACP provider turn provider-turn:x is not active",
),
);
assert.isTrue(
isNonRetryableProviderTurnControlFailure(
"provider-turn.interrupt",
"Provider session provider-session:x is not active.",
),
);
// Restart is compound (interrupt + detach + start). Do not swallow start failures.
assert.isFalse(
isNonRetryableProviderTurnControlFailure(
"provider-turn.restart",
"Provider session provider-session:x is not active.",
),
);
assert.isFalse(
isNonRetryableProviderTurnControlFailure(
"provider-turn.start",
"Provider session provider-session:x is not active.",
),
);
assert.isFalse(
isNonRetryableProviderTurnControlFailure(
"provider-turn.interrupt",
"ACP hard teardown failed unexpectedly; the session is poisoned",
),
);
});
it.effect("detaches a handed-off session only after the old turn terminalizes", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
@@ -25,6 +25,30 @@ export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<O
},
) {}
/**
* Pure interrupt races with hard process teardown or a dead session produce
* "not active" protocol errors. Retrying those only delays recovery.
*
* Do not apply this to `provider-turn.restart`: that compound effect also runs
* detach and start. Swallowing a start failure that happens to mention
* "is not active" would drop the outbox item without ever starting the
* replacement turn.
*/
export function isNonRetryableProviderTurnControlFailure(
effectType: string,
errorText: string,
): boolean {
if (effectType !== "provider-turn.interrupt") {
return false;
}
return (
/is not active/i.test(errorText) ||
/hard teardown is already in progress/i.test(errorText) ||
/treating as already interrupted/i.test(errorText) ||
/treating as already stopped/i.test(errorText)
);
}
export interface OrchestrationEffectExecutorV2Shape {
readonly execute: (
effect: OrchestrationEffectV2,
@@ -348,14 +372,19 @@ export const layerWithOptions = (
}
const error = Cause.pretty(exit.cause);
const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
yield* Effect.logWarning("Orchestration effect execution failed", {
effectId: effect.id,
effectType: effect.request.type,
attemptCount: effect.attemptCount,
nonRetryable,
error,
});
const updated =
effect.attemptCount >= maxAttempts
// Prefer succeed for terminal interrupt races so the outbox does not
// keep a failed interrupt around; fail only when we must not retry.
const updated = nonRetryable
? yield* outbox.succeed({ effectId: effect.id, workerId })
: effect.attemptCount >= maxAttempts
? yield* outbox.fail({ effectId: effect.id, workerId, error })
: yield* outbox.retry({
effectId: effect.id,
@@ -573,6 +573,7 @@ function activeLocalTurnItems(
item,
runs: projection.runs,
attempts: projection.attempts,
items: projection.turnItems,
}),
)
.map((item, position) => ({
@@ -668,6 +669,7 @@ function visibleTurnItemsThroughRun(input: {
isOrchestrationV2SupersededInterrupt({
item,
attempts: input.sourceProjection.attempts,
items: input.sourceProjection.turnItems,
})
) {
return false;
@@ -407,6 +407,8 @@ export interface ProviderAdapterV2SteerInput {
export interface ProviderAdapterV2InterruptInput {
readonly providerThread: OrchestrationV2ProviderThread;
readonly providerTurnId: ProviderTurnId;
/** When true, the next `startTurn` may respawn the provider runtime (Grok Stop recovery). */
readonly requestRuntimeRestart?: boolean;
}
export interface ProviderAdapterV2RuntimeRequestResponseInput {
@@ -2,6 +2,7 @@ import { ProviderDriverKind, ProviderThreadId, ThreadId } from "@t3tools/contrac
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
export interface ProviderContinuationRequest {
@@ -9,6 +10,9 @@ export interface ProviderContinuationRequest {
readonly providerThreadId: ProviderThreadId;
readonly driver: ProviderDriverKind;
readonly detail: string | null;
readonly dispatchIfCurrent?: <A, E, R>(
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<Option.Option<A>, E, R>;
}
/**
@@ -0,0 +1,193 @@
import { assert, describe, it } from "@effect/vitest";
import {
ProviderDriverKind,
ProviderThreadId,
ThreadId,
type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
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 Semaphore from "effect/Semaphore";
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
import {
type ProviderContinuationRequest,
ProviderContinuationRequests,
layer as continuationRequestsLayer,
} from "./ProviderContinuationRequests.ts";
import { workerLive } from "./ProviderContinuationService.ts";
import { ThreadManagementService } from "./ThreadManagementService.ts";
const threadId = ThreadId.make("thread-provider-continuation");
const providerThreadId = ProviderThreadId.make("provider-thread-continuation");
const driver = ProviderDriverKind.make("continuation-test");
const projection = {
thread: { archivedAt: null },
messages: [],
} as unknown as OrchestrationV2ThreadProjection;
const request = (
dispatchIfCurrent?: ProviderContinuationRequest["dispatchIfCurrent"],
detail: string | null = null,
): ProviderContinuationRequest => ({
threadId,
providerThreadId,
driver,
detail,
...(dispatchIfCurrent === undefined ? {} : { dispatchIfCurrent }),
});
const makeGuard = Effect.fnUntraced(function* (completed?: Deferred.Deferred<void>) {
const generation = yield* Ref.make(0);
const permit = yield* Semaphore.make(1);
const capture = Effect.gen(function* () {
const captured = yield* Ref.updateAndGet(generation, (value) => value + 1);
return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
permit
.withPermit(
Effect.gen(function* () {
if ((yield* Ref.get(generation)) !== captured) return Option.none();
return Option.some(yield* effect);
}),
)
.pipe(
completed === undefined
? (effect) => effect
: Effect.ensuring(Deferred.succeed(completed, undefined)),
);
});
return {
capture,
invalidate: permit.withPermit(Ref.update(generation, (value) => value + 1)),
};
});
function testLayer(input: {
readonly dispatched: Queue.Queue<unknown>;
readonly getThreadProjection: () => Effect.Effect<OrchestrationV2ThreadProjection>;
}) {
const threads = Layer.mock(ThreadManagementService)({
getThreadProjection: input.getThreadProjection,
dispatch: (command) => Queue.offer(input.dispatched, command).pipe(Effect.as({} as never)),
});
const worker = workerLive.pipe(
Layer.provide(Layer.mergeAll(idAllocatorLayer, continuationRequestsLayer, threads)),
);
return Layer.merge(continuationRequestsLayer, worker);
}
describe("ProviderContinuationService", () => {
it.effect("dispatches a current request exactly once", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
yield* Effect.gen(function* () {
const requests = yield* ProviderContinuationRequests;
yield* requests.offer(request());
yield* Queue.take(dispatched);
yield* Effect.yieldNow;
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
}).pipe(
Effect.provide(
testLayer({ dispatched, getThreadProjection: () => Effect.succeed(projection) }),
),
Effect.scoped,
);
});
});
it.effect("drops a request invalidated before dispatch", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
yield* Effect.gen(function* () {
const requests = yield* ProviderContinuationRequests;
const guard = yield* makeGuard();
const dispatchIfCurrent = yield* guard.capture;
yield* guard.invalidate;
yield* requests.offer(request(dispatchIfCurrent));
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
}).pipe(
Effect.provide(
testLayer({ dispatched, getThreadProjection: () => Effect.succeed(projection) }),
),
Effect.scoped,
);
});
});
it.effect("drops a request invalidated while projection is blocked", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
const projectionEntered = yield* Deferred.make<void>();
const releaseProjection = yield* Deferred.make<void>();
const guardCompleted = yield* Deferred.make<void>();
yield* Effect.gen(function* () {
const requests = yield* ProviderContinuationRequests;
const guard = yield* makeGuard(guardCompleted);
const dispatchIfCurrent = yield* guard.capture;
yield* requests.offer(request(dispatchIfCurrent));
yield* Deferred.await(projectionEntered);
yield* guard.invalidate;
yield* Deferred.succeed(releaseProjection, undefined);
yield* Deferred.await(guardCompleted);
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
}).pipe(
Effect.provide(
testLayer({
dispatched,
getThreadProjection: () =>
Deferred.succeed(projectionEntered, undefined).pipe(
Effect.andThen(Deferred.await(releaseProjection)),
Effect.as(projection),
),
}),
),
Effect.scoped,
);
});
});
it.effect("does not revive an old request when a later generation is current", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
const firstProjectionEntered = yield* Deferred.make<void>();
const releaseFirstProjection = yield* Deferred.make<void>();
let projectionCalls = 0;
yield* Effect.gen(function* () {
const requests = yield* ProviderContinuationRequests;
const guard = yield* makeGuard();
const first = yield* guard.capture;
yield* requests.offer(request(first, "A"));
yield* Deferred.await(firstProjectionEntered);
const second = yield* guard.capture;
yield* requests.offer(request(second, "B"));
yield* Deferred.succeed(releaseFirstProjection, undefined);
const command = yield* Queue.take(dispatched);
assert.equal((command as { readonly text?: unknown }).text, "B");
yield* Effect.yieldNow;
assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
}).pipe(
Effect.provide(
testLayer({
dispatched,
getThreadProjection: () => {
projectionCalls += 1;
return projectionCalls === 1
? Deferred.succeed(firstProjectionEntered, undefined).pipe(
Effect.andThen(Deferred.await(releaseFirstProjection)),
Effect.as(projection),
)
: Effect.succeed(projection);
},
}),
),
Effect.scoped,
);
});
});
});
@@ -32,14 +32,20 @@ export const workerLive = Layer.effectDiscard(
threadId: request.threadId,
providerThreadId: request.providerThreadId,
});
// Still run the guard so adapters can clear sticky continuationRequested.
if (request.dispatchIfCurrent !== undefined) {
yield* request.dispatchIfCurrent(Effect.void);
}
return;
}
// The ordinal is display metadata only: allocate.message appends a
// random UUID, so a stale projection read here cannot collide ids.
const messageId = yield* ids.allocate.message({
threadId: request.threadId,
ordinal: projection.messages.length + 1,
});
const commandId = CommandId.make(`provider-continuation:${messageId}`);
yield* threads.dispatch({
const dispatch = threads.dispatch({
type: "message.dispatch",
commandId,
threadId: request.threadId,
@@ -50,6 +56,11 @@ export const workerLive = Layer.effectDiscard(
createdBy: "agent",
creationSource: "provider",
});
if (request.dispatchIfCurrent === undefined) {
yield* dispatch;
return;
}
yield* request.dispatchIfCurrent(dispatch);
},
);
@@ -1233,6 +1233,99 @@ it.effect(
}),
);
it.effect("ProviderSessionManagerV2 does not apply a stale idle pin to a replacement session", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
const firstCheck = yield* Ref.make(true);
const checkEntered = yield* Deferred.make<void>();
const checkGate = yield* Deferred.make<void>();
const effect = Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const idAllocator = yield* IdAllocatorV2;
const manager = yield* ProviderSessionManagerV2;
const now = yield* DateTime.now;
const threadId = yield* idAllocator.allocate.thread({
fixtureName: "provider-session-manager-stale-pin",
projectId: yield* idAllocator.allocate.project({
fixtureName: "provider-session-manager-stale-pin",
}),
});
const providerSessionId = yield* idAllocator.allocate.providerSession({
providerInstanceId: modelSelection.instanceId,
threadId,
});
yield* eventSink.write({
events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
});
yield* manager.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy,
});
// Park the first idle fiber inside an uninterruptible pending-work probe.
yield* TestClock.adjust("1 second");
yield* Deferred.await(checkEntered);
// close removes the map entry first, then waits to interrupt the idle
// fiber (still uninterruptible). That window lets a replacement open
// under the same providerSessionId before the stale probe finishes.
const closeFiber = yield* manager.close(providerSessionId).pipe(Effect.forkDetach);
for (let i = 0; i < 20; i += 1) {
yield* Effect.yieldNow;
}
yield* manager.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy,
});
assert.equal((yield* Ref.get(state)).openCount, 2);
// Stale probe reports pending work against the old runtime; the pin
// stamp must no-op on the replacement (runtime / generation mismatch).
yield* Deferred.succeed(checkGate, undefined);
yield* Fiber.join(closeFiber);
for (let i = 0; i < 10; i += 1) {
yield* Effect.yieldNow;
}
assert.isTrue(Option.isSome(yield* manager.get(providerSessionId)));
assert.equal((yield* Ref.get(state)).closeCount, 1);
// Replacement has no pending background work. After one idle window it
// must release. A stale pin stamp would have deferred release until
// maxIdlePinMs.
yield* TestClock.adjust("1 second");
yield* Effect.yieldNow;
assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
assert.equal((yield* Ref.get(state)).closeCount, 2);
});
yield* effect.pipe(
Effect.provide(
makeTestLayer({
state,
idleTimeoutMs: 1000,
maxIdlePinMs: 60_000,
hasPendingBackgroundWork: Effect.uninterruptible(
Effect.gen(function* () {
if (yield* Ref.getAndSet(firstCheck, false)) {
yield* Deferred.succeed(checkEntered, undefined);
yield* Deferred.await(checkGate);
return true;
}
return false;
}),
),
}),
),
);
}),
);
it.effect(
"ProviderSessionManagerV2 keeps active sessions alive until the provider turn terminates",
() =>
@@ -605,31 +605,47 @@ export const layerWithOptions = (
) {
return;
}
// Capture runtime identity before yielding: a replacement session
// can reuse the same providerSessionId while this fiber is parked.
const probedRuntime = entry.runtime;
const hasPendingWork =
entry.runtime.hasPendingBackgroundWork === undefined
probedRuntime.hasPendingBackgroundWork === undefined
? false
: yield* entry.runtime.hasPendingBackgroundWork.pipe(
: yield* probedRuntime.hasPendingBackgroundWork.pipe(
Effect.catchCause(() => Effect.succeed(false)),
);
if (hasPendingWork) {
const now = yield* Clock.currentTimeMillis;
const pinnedSinceMs = entry.pinnedSinceMs ?? now;
if (now - pinnedSinceMs < maxIdlePinMs) {
const shouldContinuePin = yield* Ref.modify(sessions, (latest) => {
const latestEntry = latest.get(key);
if (
latestEntry === undefined ||
latestEntry.busyCount > 0 ||
latestEntry.idleGeneration !== input.generation ||
latestEntry.runtime !== probedRuntime
) {
return [false, latest] as const;
}
const updated = new Map(latest);
updated.set(key, { ...latestEntry, pinnedSinceMs });
return [true, updated] as const;
});
if (!shouldContinuePin) {
// Generation or runtime advanced while we probed pending work;
// the current owner of the entry owns idle release.
return;
}
yield* Effect.logInfo("orchestration-v2.driver-session.idle-release-deferred", {
providerSessionId: input.providerSessionId,
pinnedForMs: now - pinnedSinceMs,
});
yield* Ref.update(sessions, (latest) => {
const latestEntry = latest.get(key);
if (latestEntry === undefined || latestEntry.busyCount > 0) {
return latest;
}
const updated = new Map(latest);
updated.set(key, { ...latestEntry, pinnedSinceMs });
return updated;
});
yield* scheduleIdleReleaseInternal(input.providerSessionId);
return;
// Re-check on this fiber after another idle window. Do not call
// scheduleIdleReleaseInternal: that cancels entry.idleFiber, which
// is this fiber, and can self-deadlock on Fiber.interrupt.
yield* Effect.sleep(Duration.millis(idleTimeoutMs));
return yield* releaseIfStillIdle(input);
}
yield* Effect.logWarning("orchestration-v2.driver-session.idle-release-pin-expired", {
providerSessionId: input.providerSessionId,
@@ -129,6 +129,28 @@ export const layer: Layer.Layer<
}
const session = yield* sessions.get(input.providerSessionId);
if (Option.isNone(session)) {
// Interrupt/restart against a already-released session must not fail
// the durable effect (and retry 5x). The turn may still look running
// in projection until recovery/finalization; there is no live adapter
// to interrupt.
if (input.operation === "interrupt" || input.operation === "restart") {
yield* Effect.logWarning(
"Provider interrupt/restart found no live session; treating as already stopped",
{
threadId: input.threadId,
operation: input.operation,
providerSessionId: input.providerSessionId,
providerTurnId: input.providerTurnId,
providerTurnStatus: providerTurn.status,
},
);
return {
projection,
providerThread: interruptProviderThread,
providerTurn,
session: Option.none(),
};
}
return yield* new ProviderTurnControlError({
threadId: input.threadId,
operation: input.operation,
@@ -147,6 +169,7 @@ export const layer: Layer.Layer<
yield* loaded.session.value.interruptTurn({
providerThread: loaded.providerThread,
providerTurnId: loaded.providerTurn.id,
requestRuntimeRestart: true,
});
}).pipe(
Effect.mapError((cause) =>
@@ -163,13 +186,28 @@ export const layer: Layer.Layer<
interruptAndAwaitTerminal: (input) =>
Effect.gen(function* () {
const loaded = yield* load({ ...input, operation: "restart" });
if (Option.isSome(loaded.session)) {
yield* loaded.session.value.interruptTurn({
providerThread: loaded.providerThread,
providerTurnId: loaded.providerTurn.id,
});
if (Option.isNone(loaded.session)) {
// No live adapter: nothing can emit a terminal provider-turn update
// from interrupt. Do not poll for projection terminalization or the
// restart effect stalls; let detach/start proceed.
if (loaded.providerTurn.status === "running") {
yield* Effect.logWarning(
"Provider restart interrupt skipped; no live session for a still-projected running turn",
{
threadId: input.threadId,
providerSessionId: input.providerSessionId,
providerTurnId: input.providerTurnId,
},
);
}
return;
}
yield* loaded.session.value.interruptTurn({
providerThread: loaded.providerThread,
providerTurnId: loaded.providerTurn.id,
});
for (let remaining = 1_000; remaining > 0; remaining -= 1) {
const projection = yield* projections.getThreadProjection(input.threadId);
const providerTurn = projection.providerTurns.find(
@@ -439,6 +439,23 @@ export const layer: Layer.Layer<
}),
Effect.catchCause(() => Effect.succeed(false)),
),
hasUnpairedRunInterruptRequest: () =>
projectionStore.getThreadProjection(projection.thread.id).pipe(
Effect.map((current) => {
const requestId = idAllocator.derive.runSignalTurnItem({
runId: run.id,
signal: "interrupt-request",
});
const resultId = idAllocator.derive.runSignalTurnItem({
runId: run.id,
signal: "interrupt-result",
});
const hasRequest = current.turnItems.some((item) => item.id === requestId);
const hasResult = current.turnItems.some((item) => item.id === resultId);
return hasRequest && !hasResult;
}),
Effect.catchCause(() => Effect.succeed(false)),
),
message: {
messageId: message.id,
text:
@@ -31,7 +31,7 @@ import * as Stream from "effect/Stream";
import { ServerSettingsService } from "../serverSettings.ts";
import { CheckpointServiceV2 } from "./CheckpointService.ts";
import { EventSinkV2 } from "./EventSink.ts";
import { layer as idAllocatorLayer } from "./IdAllocator.ts";
import { IdAllocatorV2, layer as idAllocatorLayer } from "./IdAllocator.ts";
import type { ProviderAdapterV2Event, ProviderAdapterV2SessionRuntime } from "./ProviderAdapter.ts";
import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts";
import {
@@ -542,6 +542,194 @@ it.effect("does not pin ingestion on background items when the root turn is inte
}),
);
it.effect("omits run_interrupt_result when a superseding attempt already owns the run", () =>
Effect.gen(function* () {
const written = yield* captureInterruptTerminalTurnItems({
key: "steer-supersede",
shouldFinalizeRun: () => Effect.succeed(false),
});
assert.deepEqual(
written.map((item) => item.type),
[],
);
}),
);
it.effect("emits run_interrupt_result when superseded attempt still has a hard-stop request", () =>
Effect.gen(function* () {
const written = yield* captureInterruptTerminalTurnItems({
key: "stop-then-steer-supersede",
shouldFinalizeRun: () => Effect.succeed(false),
hasUnpairedRunInterruptRequest: () => Effect.succeed(true),
});
assert.deepEqual(
written.map((item) => item.type),
["run_interrupt_result"],
);
const ids = backgroundScenarioIds("stop-then-steer-supersede");
const expectedRequestId = yield* Effect.gen(function* () {
const idAllocator = yield* IdAllocatorV2;
return idAllocator.derive.runSignalTurnItem({
runId: ids.runId,
signal: "interrupt-request",
});
}).pipe(Effect.provide(idAllocatorLayer));
assert.equal(written[0]?.parentItemId, expectedRequestId);
}),
);
it.effect("omits run_interrupt_result when superseded attempt request is already paired", () =>
Effect.gen(function* () {
const written = yield* captureInterruptTerminalTurnItems({
key: "stop-then-steer-already-paired",
shouldFinalizeRun: () => Effect.succeed(false),
hasUnpairedRunInterruptRequest: () => Effect.succeed(false),
});
assert.deepEqual(
written.map((item) => item.type),
[],
);
}),
);
it.effect("emits run_interrupt_result when hard-stop finalizes the active attempt", () =>
Effect.gen(function* () {
const written = yield* captureInterruptTerminalTurnItems({
key: "hard-stop",
shouldFinalizeRun: () => Effect.succeed(true),
});
assert.deepEqual(
written.map((item) => item.type),
["run_interrupt_result"],
);
}),
);
function captureInterruptTerminalTurnItems(input: {
readonly key: string;
readonly shouldFinalizeRun: () => Effect.Effect<boolean, never>;
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
}) {
return Effect.gen(function* () {
const ids = backgroundScenarioIds(input.key);
const providerInstanceId = ProviderInstanceId.make("codex");
const writtenItems = yield* Ref.make<
ReadonlyArray<{ readonly type: string; readonly parentItemId: string | null }>
>([]);
const ingestionDone = yield* Deferred.make<void>();
const captureTurnItem = (payload: {
readonly type: string;
readonly parentItemId: string | null;
}) =>
Ref.update(writtenItems, (current) => [
...current,
{ type: payload.type, parentItemId: payload.parentItemId },
]);
const testLayer = runExecutionServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
Layer.mock(EventSinkV2)({
write: (payload) =>
Effect.gen(function* () {
for (const event of payload.events) {
if (event.type === "turn-item.updated") {
yield* captureTurnItem(event.payload);
}
}
return [];
}),
writeWithEffects: (payload) =>
Effect.gen(function* () {
for (const event of payload.events) {
if (event.type === "turn-item.updated") {
yield* captureTurnItem(event.payload);
}
}
return [];
}),
writeIfRunCurrent: () => Effect.succeed({ committed: true, storedEvents: [] }),
}),
idAllocatorLayer,
Layer.mock(ProviderEventIngestorV2)({
ingestNormalized: () => Effect.succeed([]),
}),
ServerSettingsService.layerTest(),
),
),
);
yield* Effect.gen(function* () {
const runExecution = yield* RunExecutionServiceV2;
yield* runExecution.startRootRun({
commandId: CommandId.make(`command:${input.key}`),
appThread: { id: ids.threadId } as OrchestrationV2AppThread,
providerSessionId: ProviderSessionId.make(`session:${input.key}`),
session: {
events: Stream.empty,
subscribeEvents: Effect.succeed({
events: Stream.fromIterable([rootTerminalEvent(ids, "interrupted")]),
close: Deferred.succeed(ingestionDone, undefined),
}),
startTurn: () => Effect.void,
} as unknown as ProviderAdapterV2SessionRuntime,
run: {
id: ids.runId,
threadId: ids.threadId,
ordinal: 1,
providerInstanceId,
} as OrchestrationV2Run,
rootNode: {
id: ids.rootNodeId,
providerTurnId: ids.rootProviderTurnId,
} as OrchestrationV2ExecutionNode,
checkpointScope: {
id: CheckpointScopeId.make(`checkpoint-scope:${input.key}`),
} as OrchestrationV2CheckpointScope,
providerThread: {
id: ids.providerThreadId,
driver,
} as OrchestrationV2ProviderThread,
attempt: {
id: ids.attemptId,
providerTurnId: ids.rootProviderTurnId,
} as OrchestrationV2RunAttempt,
attemptId: ids.attemptId,
providerTurnOrdinal: 1,
shouldFinalizeRun: input.shouldFinalizeRun,
...(input.hasUnpairedRunInterruptRequest === undefined
? {}
: {
hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
}),
message: {
messageId: MessageId.make(`message:${input.key}`),
text: "interrupt projection",
attachments: [],
createdBy: "user",
creationSource: "web",
},
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
runtimePolicy: {
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
approvalPolicy: "never",
sandboxPolicy: {
type: "readOnly",
access: { type: "fullAccess" },
networkAccess: false,
},
},
});
}).pipe(Effect.provide(testLayer));
const closed = yield* Deferred.await(ingestionDone).pipe(Effect.timeoutOption("2 seconds"));
assert.isTrue(Option.isSome(closed), "event ingestion fiber did not finish");
return yield* Ref.get(writtenItems);
});
}
interface BackgroundScenarioIds {
readonly threadId: ThreadId;
readonly childThreadId: ThreadId;
@@ -260,6 +260,7 @@ export interface RunExecutionServiceV2StartRootRunInput {
readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, never>;
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
readonly message: ProviderAdapterV2TurnMessage;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
@@ -323,6 +324,7 @@ export const layer: Layer.Layer<
readonly providerThread: OrchestrationV2ProviderThread;
readonly attempt: OrchestrationV2RunAttempt;
readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
readonly terminal: ProviderTerminalEvent;
readonly failureItemPersisted: boolean;
}) =>
@@ -336,30 +338,37 @@ export const layer: Layer.Layer<
const shouldFinalizeRun =
input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun();
if (!shouldFinalizeRun) {
// A newer attempt already owns the run and the command that created
// it terminalized this attempt as superseded. Preserve that domain
// status while retaining the provider's interruption artifact.
// Superseded attempt (steer / selection restart). Emit
// run_interrupt_result only when hard Stop left an unpaired request
// for this run; plain steers and already-paired stops emit nothing.
if (input.terminal.status === "interrupted") {
yield* eventSink.write({
events: [
{
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
type: "turn-item.updated" as const,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: makeInterruptResultTurnItem({
idAllocator,
run: input.run,
rootNode: input.rootNode,
providerThread: input.providerThread,
completedAt,
}),
},
],
});
const hasUnpairedRequest =
input.hasUnpairedRunInterruptRequest === undefined
? false
: yield* input.hasUnpairedRunInterruptRequest();
if (hasUnpairedRequest) {
yield* eventSink.writeWithEffects({
effects: [],
events: [
{
id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
type: "turn-item.updated" as const,
threadId: input.run.threadId,
runId: input.run.id,
nodeId: input.rootNode.id,
providerInstanceId: input.run.providerInstanceId,
occurredAt: completedAt,
payload: makeInterruptResultTurnItem({
idAllocator,
run: input.run,
rootNode: input.rootNode,
providerThread: input.providerThread,
completedAt,
}),
},
],
});
}
}
return;
}
@@ -594,6 +603,11 @@ export const layer: Layer.Layer<
...(input.shouldFinalizeRun === undefined
? {}
: { shouldFinalizeRun: input.shouldFinalizeRun }),
...(input.hasUnpairedRunInterruptRequest === undefined
? {}
: {
hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
}),
terminal,
failureItemPersisted: terminal.status === "failed",
}).pipe(
@@ -776,6 +790,12 @@ export const layer: Layer.Layer<
...(input.shouldFinalizeRun === undefined
? {}
: { shouldFinalizeRun: input.shouldFinalizeRun }),
...(input.hasUnpairedRunInterruptRequest === undefined
? {}
: {
hasUnpairedRunInterruptRequest:
input.hasUnpairedRunInterruptRequest,
}),
terminal: makeFailedTerminalEvent(
makeProviderFailure({
cause: Cause.squash(cause),
@@ -847,6 +867,12 @@ export const layer: Layer.Layer<
...(input.shouldFinalizeRun === undefined
? {}
: { shouldFinalizeRun: input.shouldFinalizeRun }),
...(input.hasUnpairedRunInterruptRequest === undefined
? {}
: {
hasUnpairedRunInterruptRequest:
input.hasUnpairedRunInterruptRequest,
}),
terminal: makeFailedTerminalEvent(
makeProviderFailure({
cause: Cause.squash(cause),
@@ -490,7 +490,12 @@ it.live("restarts selection as a new attempt and retries after old-session clean
projection.providerTurns.map((turn) => turn.status),
["interrupted", "completed"],
);
assert.isTrue(projection.turnItems.some((item) => item.type === "run_interrupt_result"));
assert.isFalse(
projection.turnItems.some(
(item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
),
"selection restart supersede must not project hard-Stop interrupt items",
);
assert.equal(projection.runs[0]?.modelSelection.model, replacementSelection.model);
assert.isTrue(captured.failedReplacementOpen);
// The old pooled process remains available to its other threads; this
@@ -24,7 +24,7 @@ export function assertCursorMessageSteeringOutput(
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]);
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
assertRuntimeRequestCounts(projection, { total: 0 });
assertUserMessagesInclude(projection, [
MESSAGE_STEERING_INITIAL_PROMPT,
@@ -47,9 +47,10 @@ export function assertCursorMessageSteeringOutput(
);
assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id);
assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId);
assert.notInclude(
projection.visibleTurnItems.map((row) => row.item.type),
"run_interrupt_result",
"restart steering must keep its internal interruption out of visible chat history",
assert.isFalse(
projection.turnItems.some(
(item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
),
"steer supersede must not project run_interrupt_* items (those are hard Stop only)",
);
}
@@ -23,7 +23,7 @@ export function assertGrokMessageSteeringOutput(
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]);
assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
assertRuntimeRequestCounts(projection, { total: 0 });
assertUserMessagesInclude(projection, [
MESSAGE_STEERING_INITIAL_PROMPT,
@@ -46,9 +46,10 @@ export function assertGrokMessageSteeringOutput(
);
assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id);
assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId);
assert.notInclude(
projection.visibleTurnItems.map((row) => row.item.type),
"run_interrupt_result",
"restart steering must keep its internal interruption out of visible chat history",
assert.isFalse(
projection.turnItems.some(
(item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
),
"steer supersede must not project run_interrupt_* items (those are hard Stop only)",
);
}
@@ -749,6 +749,40 @@ describe("AcpSessionRuntime", () => {
),
);
it.effect("completes ad-hoc loadSession after replay becomes idle while RPC stays pending", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const loaded = yield* runtime.loadSession("mock-session-1").pipe(Effect.timeout("2 seconds"));
expect(loaded.sessionId).toBe("mock-session-1");
expect(loaded.sessionSetupResult._meta).toMatchObject({
t3SessionLoadReady: "replay_idle",
});
}).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(),
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,7 @@ import {
parsePermissionRequest,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateCountsAsLoadReplayActivity,
sessionUpdateIsReplay,
syntheticLoadSessionResponseFromInitialize,
} from "./AcpRuntimeModel.ts";
@@ -83,6 +84,98 @@ describe("AcpRuntimeModel", () => {
).toBe(false);
});
it("ignores Grok keepalive chunks when tracking session/load replay activity", () => {
expect(
sessionUpdateCountsAsLoadReplayActivity({
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(false);
expect(
sessionUpdateCountsAsLoadReplayActivity({
_meta: { isReplay: true },
sessionId: "session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "replay-tool",
title: "Replay",
kind: "search",
status: "completed",
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
});
it("ignores load-replay activity from other sessions while a load gate is active", () => {
expect(
sessionUpdateCountsAsLoadReplayActivity(
{
sessionId: "session-other",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "unrelated" },
},
} satisfies EffectAcpSchema.SessionNotification,
"session-loading",
),
).toBe(false);
expect(
sessionUpdateCountsAsLoadReplayActivity(
{
sessionId: "session-loading",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replay" },
},
} satisfies EffectAcpSchema.SessionNotification,
"session-loading",
),
).toBe(true);
});
it("counts mode/config/session/usage updates as load-replay activity", () => {
expect(
sessionUpdateCountsAsLoadReplayActivity({
sessionId: "session-1",
update: {
sessionUpdate: "current_mode_update",
currentModeId: "code",
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
expect(
sessionUpdateCountsAsLoadReplayActivity({
sessionId: "session-1",
update: {
sessionUpdate: "config_option_update",
configOptions: [],
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
expect(
sessionUpdateCountsAsLoadReplayActivity({
sessionId: "session-1",
update: {
sessionUpdate: "session_info_update",
title: "Restored",
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
expect(
sessionUpdateCountsAsLoadReplayActivity({
sessionId: "session-1",
update: {
sessionUpdate: "usage_update",
used: 1,
size: 10,
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
});
it("builds a synthetic load response from initialize model state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
@@ -459,8 +459,38 @@ export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotificatio
return isRecord(meta) && meta.isReplay === true;
}
/** Replay chunks and substantive updates during session/load; not Grok keepalives. */
export function sessionUpdateCountsAsLoadReplayActivity(
params: EffectAcpSchema.SessionNotification,
gatedSessionId?: string,
): boolean {
if (gatedSessionId !== undefined && params.sessionId !== gatedSessionId) {
return false;
}
if (sessionUpdateIsReplay(params)) return true;
const update = params.update;
switch (update.sessionUpdate) {
case "agent_message_chunk":
case "agent_thought_chunk":
return update.content.type === "text" && update.content.text.length > 0;
case "tool_call":
case "tool_call_update":
case "plan":
case "available_commands_update":
case "current_mode_update":
case "config_option_update":
case "session_info_update":
case "usage_update":
return true;
default:
return false;
}
}
export interface SessionLoadGate {
readonly active: boolean;
/** Only notifications for this session refresh load-replay idle activity. */
readonly sessionId: string;
readonly lastActivityAtMillis: number | undefined;
readonly idleGap: Duration.Duration;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -5,9 +5,33 @@ import * as EffectAcpErrors from "effect-acp/errors";
import {
applyGrokAcpModelSelection,
buildGrokAcpSpawnInput,
grokAcpRuntimeProcessOwnership,
resolveGrokAcpBaseModelId,
} from "./GrokAcpSupport.ts";
describe("grokAcpRuntimeProcessOwnership", () => {
it("opts Grok into detached process-tree ownership on the injected host platform", () => {
expect(grokAcpRuntimeProcessOwnership("linux")).toEqual({
ownDescendantProcessGroups: true,
ownDetachedProcessGroup: true,
processGroupPlatform: "linux",
});
});
it("uses the prior provider-group path on Darwin and Windows", () => {
expect(grokAcpRuntimeProcessOwnership("darwin")).toEqual({
ownDescendantProcessGroups: false,
ownDetachedProcessGroup: true,
processGroupPlatform: "darwin",
});
expect(grokAcpRuntimeProcessOwnership("win32")).toEqual({
ownDescendantProcessGroups: false,
ownDetachedProcessGroup: true,
processGroupPlatform: "win32",
});
});
});
describe("resolveGrokAcpBaseModelId", () => {
it("normalizes empty and custom Grok model ids", () => {
expect(resolveGrokAcpBaseModelId(undefined)).toBe("grok-build");
@@ -1,3 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
@@ -6,6 +7,7 @@ import * as Scope from "effect/Scope";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizeModelSlug } from "@t3tools/shared/model";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
@@ -51,6 +53,21 @@ function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): st
: GROK_AUTH_METHOD_CACHED_TOKEN;
}
export function grokAcpRuntimeProcessOwnership(
processGroupPlatform: NodeJS.Platform,
): Pick<
AcpSessionRuntime.AcpSessionRuntimeOptions,
"ownDescendantProcessGroups" | "ownDetachedProcessGroup" | "processGroupPlatform"
> {
return {
// macOS keeps the prior provider-group teardown until a stable libproc
// identity provider can cover Grok's nested detached tool groups.
ownDescendantProcessGroups: processGroupPlatform === "linux",
ownDetachedProcessGroup: true,
processGroupPlatform,
};
}
export const makeGrokAcpRuntime = (
input: GrokAcpRuntimeInput,
): Effect.Effect<
@@ -59,11 +76,15 @@ export const makeGrokAcpRuntime = (
Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const processGroupPlatform = yield* HostProcessPlatform.pipe(
Effect.provide(NodeServices.layer),
);
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
...input,
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
authMethodId: resolveGrokAuthMethodId(input.environment),
...grokAcpRuntimeProcessOwnership(processGroupPlatform),
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -5,7 +5,10 @@ import {
ProviderInstanceId,
ThreadId,
RunId,
TurnItemId,
type OrchestrationV2ProjectedTurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import type { Thread } from "../types";
@@ -15,6 +18,7 @@ import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveCommittedServerUserMessageIds,
deriveComposerSendState,
getStartedThreadModelChangeBlockReason,
hasServerAcknowledgedLocalDispatch,
@@ -463,3 +467,103 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
expect(hasServerAcknowledgedLocalDispatch({ ...common, threadError: "failed" })).toBe(true);
});
});
describe("deriveCommittedServerUserMessageIds", () => {
it("tracks only committed user turn items, not assistant rows or projection-only messages", () => {
const turnStartId = MessageId.make("message-turn-start");
const steerId = MessageId.make("message-steer");
const assistantId = MessageId.make("message-assistant");
const committedAt = DateTime.makeUnsafe("2026-06-26T17:50:15.180Z");
const runId = RunId.make("run:thread:thread-1:ordinal:1");
const visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = [
{
position: 0,
visibility: "local",
sourceThreadId: threadId,
sourceItemId: TurnItemId.make("turn-item:message-turn-start"),
item: {
id: TurnItemId.make("turn-item:message-turn-start"),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "completed",
title: null,
startedAt: committedAt,
completedAt: committedAt,
updatedAt: committedAt,
createdBy: "user",
creationSource: "web",
type: "user_message",
messageId: turnStartId,
inputIntent: "turn_start",
text: "start",
attachments: [],
},
},
{
position: 1,
visibility: "local",
sourceThreadId: threadId,
sourceItemId: TurnItemId.make("turn-item:message-assistant"),
item: {
id: TurnItemId.make("turn-item:message-assistant"),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 2,
status: "completed",
title: null,
startedAt: committedAt,
completedAt: committedAt,
updatedAt: committedAt,
type: "assistant_message",
messageId: assistantId,
text: "working",
streaming: false,
},
},
{
position: 2,
visibility: "local",
sourceThreadId: threadId,
sourceItemId: TurnItemId.make("turn-item:message-steer"),
item: {
id: TurnItemId.make("turn-item:message-steer"),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 3,
status: "completed",
title: null,
startedAt: committedAt,
completedAt: committedAt,
updatedAt: committedAt,
createdBy: "user",
creationSource: "web",
type: "user_message",
messageId: steerId,
inputIntent: "steer",
text: "continue",
attachments: [],
},
},
];
expect(deriveCommittedServerUserMessageIds(visibleTurnItems)).toEqual(
new Set([turnStartId, steerId]),
);
});
});
+17
View File
@@ -3,6 +3,7 @@ import {
isProviderDriverKind,
ProjectId,
type ModelSelection,
type OrchestrationV2ProjectedTurnItem,
type ProviderDriverKind,
type ServerProvider,
type ScopedThreadRef,
@@ -392,6 +393,22 @@ export function createLocalDispatchSnapshot(
};
}
/**
* The timeline renders committed user rows from `visibleTurnItems`, but
* `message.updated` can land in `projection.messages` one event earlier than
* the matching `turn-item.updated`. Basing optimistic eviction on visible user
* turn items avoids dropping steer rows in that gap.
*/
export function deriveCommittedServerUserMessageIds(
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
): ReadonlySet<ChatMessage["id"]> {
return new Set(
visibleTurnItems.flatMap((row) =>
row.item.type === "user_message" ? [row.item.messageId] : [],
),
);
}
export function hasServerAcknowledgedLocalDispatch(input: {
localDispatch: LocalDispatchSnapshot | null;
phase: SessionPhase;
+8 -3
View File
@@ -247,6 +247,7 @@ import {
buildLocalDraftThread,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveCommittedServerUserMessageIds,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
getStartedThreadModelChangeBlockReason,
@@ -1154,8 +1155,8 @@ function ChatViewContent(props: ChatViewProps) {
const serverProjection = serverThreadProjection?.projection ?? null;
const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadRef);
const committedServerMessageIds = useMemo(
() => new Set(serverProjection?.messages.map((message) => message.id) ?? []),
[serverProjection],
() => deriveCommittedServerUserMessageIds(serverVisibleTurnItems),
[serverVisibleTurnItems],
);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
@@ -1444,7 +1445,11 @@ function ChatViewContent(props: ChatViewProps) {
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
const activeThreadId = activeThread?.id ?? null;
const activeMessageCount = isServerThread ? committedServerMessageIds.size : 0;
// Prefer the larger of turn-item-committed ids and projection messages so
// env lock does not unlock while turn items lag projection hydration.
const activeMessageCount = isServerThread
? Math.max(committedServerMessageIds.size, serverProjection?.messages.length ?? 0)
: 0;
const runningTerminalIds = useThreadRunningTerminalIds({
environmentId: activeThread?.environmentId ?? null,
threadId: activeThreadId,
@@ -1268,10 +1268,6 @@ function ProposedPlanTimelineRow({
type V2EventTone = "muted" | "warning" | "danger" | "success";
function subagentDisplayTitle(title: string): string {
return title.replace(/^Subagent:\s*/i, "");
}
function v2EventPresentation(item: OrchestrationV2TurnItem): {
readonly label: string;
readonly detail: string | null;
@@ -1328,14 +1324,6 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): {
icon: MinusIcon,
};
}
case "subagent":
return {
label: subagentDisplayTitle(item.title ?? "Subagent"),
detail: item.result ?? item.progress ?? item.prompt,
tone:
item.status === "failed" ? "danger" : item.status === "completed" ? "success" : "muted",
icon: BotIcon,
};
case "approval_request":
return {
label: "Approval requested",
@@ -1410,7 +1398,14 @@ function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event"
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="text-xs font-medium text-foreground/90">{presentation.label}</span>
{item.status !== "completed" ? (
<span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
<span
className={cn(
"rounded-full border px-1.5 py-0.5 font-mono text-[10px]",
item.status === "failed"
? "border-destructive/40 text-destructive"
: "border-border/70 text-muted-foreground",
)}
>
{item.status}
</span>
) : null}
@@ -2265,8 +2260,19 @@ function workEntryPreview(
workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
workspaceRoot: string | undefined,
) {
// Prefer stdout/detail so completed shell/monitor results are visible collapsed
// (command alone hid ls listings behind expand-only inspector JSON).
if (workEntry.detail?.trim()) {
const lines = workEntry.detail
.trim()
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.length > 0);
if (lines.length > 0) {
return lines.slice(0, 3).join(" · ");
}
}
if (workEntry.command) return workEntry.command;
if (workEntry.detail) return workEntry.detail;
if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
const [firstPath] = workEntry.changedFiles ?? [];
if (!firstPath) return null;
@@ -39,6 +39,7 @@ function shouldShowLocalTurnItem(
item,
runs: projection.runs,
attempts: projection.attempts,
items: projection.turnItems,
});
}
+10
View File
@@ -26,6 +26,10 @@ export interface AcpClientOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
readonly onIncomingRequest?: AcpProtocol.AcpPatchedProtocolOptions["onIncomingRequest"];
readonly onTermination?: AcpProtocol.AcpPatchedProtocolOptions["onTermination"];
readonly onOutgoingResponseFailure?: AcpProtocol.AcpPatchedProtocolOptions["onOutgoingResponseFailure"];
readonly onOutgoingResponse?: AcpProtocol.AcpPatchedProtocolOptions["onOutgoingResponse"];
}
type AcpClientRaw = {
@@ -403,6 +407,12 @@ export const make = Effect.fn("effect-acp/AcpClient.make")(function* (
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
...(options.logger ? { logger: options.logger } : {}),
...(options.onIncomingRequest ? { onIncomingRequest: options.onIncomingRequest } : {}),
...(options.onTermination ? { onTermination: options.onTermination } : {}),
...(options.onOutgoingResponseFailure
? { onOutgoingResponseFailure: options.onOutgoingResponseFailure }
: {}),
...(options.onOutgoingResponse ? { onOutgoingResponse: options.onOutgoingResponse } : {}),
onNotification: dispatchNotification,
onExtRequest: dispatchExtRequest,
});
+200
View File
@@ -3,8 +3,12 @@ import * as AcpError from "./errors.ts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Exit from "effect/Exit";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import * as Ref from "effect/Ref";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -457,6 +461,177 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
}),
);
it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
Effect.gen(function* () {
const { stdio } = yield* makeInMemoryStdio();
const acknowledged = yield* Deferred.make<string>();
const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
onOutgoingResponse: (requestId) =>
Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
onOutgoingResponseFailure: (requestId, error) =>
Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
});
yield* transport.serverProtocol.send(0, {
_tag: "Exit",
requestId: "success-1",
exit: { _tag: "Success", value: { ok: true } },
});
assert.equal(yield* Deferred.await(acknowledged), "success-1");
const circular: { self?: unknown } = {};
circular.self = circular;
yield* transport.serverProtocol
.send(0, {
_tag: "Exit",
requestId: "failure-1",
exit: { _tag: "Success", value: circular },
})
.pipe(Effect.exit);
const [requestId, error] = yield* Deferred.await(failed);
assert.equal(requestId, "failure-1");
assert.instanceOf(error, AcpError.AcpProtocolParseError);
}),
);
it.effect("acknowledges a response only after the stdout write completes", () =>
Effect.gen(function* () {
const writeStarted = yield* Deferred.make<void>();
const releaseWrite = yield* Deferred.make<void>();
const acknowledged = yield* Deferred.make<string>();
const stdio = Stdio.make({
args: Effect.succeed([]),
stdin: Stream.never,
stdout: () =>
Sink.forEach(() =>
Deferred.succeed(writeStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseWrite)),
),
),
stderr: () => Sink.drain,
});
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
onOutgoingResponse: (requestId) =>
Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
});
const sendFiber = yield* transport.serverProtocol
.send(0, {
_tag: "Exit",
requestId: "held-write",
exit: { _tag: "Success", value: { ok: true } },
})
.pipe(Effect.forkScoped);
yield* Deferred.await(writeStarted);
assert.isUndefined(sendFiber.pollUnsafe());
assert.isFalse(yield* Deferred.isDone(acknowledged));
yield* Deferred.succeed(releaseWrite, undefined);
yield* Fiber.join(sendFiber);
assert.equal(yield* Deferred.await(acknowledged), "held-write");
}),
);
it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
Effect.gen(function* () {
const writeStarted = yield* Deferred.make<void>();
const releaseFailure = yield* Deferred.make<void>();
const failures = yield* Queue.unbounded<string>();
const terminated = yield* Deferred.make<AcpError.AcpError>();
const stdio = Stdio.make({
args: Effect.succeed([]),
stdin: Stream.never,
stdout: () =>
Sink.forEach(() =>
Deferred.succeed(writeStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseFailure)),
Effect.andThen(Effect.die("stdout failed")),
),
),
stderr: () => Sink.drain,
});
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
});
const send = (requestId: string) =>
transport.serverProtocol
.send(0, {
_tag: "Exit",
requestId,
exit: { _tag: "Success", value: { ok: true } },
})
.pipe(Effect.exit);
const current = yield* send("current").pipe(Effect.forkScoped);
yield* Deferred.await(writeStarted);
const queued = yield* send("queued").pipe(Effect.forkScoped);
yield* Effect.yieldNow;
assert.isUndefined(current.pollUnsafe());
assert.isUndefined(queued.pollUnsafe());
yield* Deferred.succeed(releaseFailure, undefined);
assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
yield* Fiber.join(current);
yield* Fiber.join(queued);
yield* send("future");
assert.deepEqual(
new Set(yield* Queue.takeN(failures, 3)),
new Set(["current", "queued", "future"]),
);
}),
);
it.effect(
"atomically rejects an admitted response when the writer closes before queue offer",
() =>
Effect.gen(function* () {
const admitted = yield* Deferred.make<void>();
const releaseAdmission = yield* Deferred.make<void>();
const failures = yield* Queue.unbounded<string>();
const protocolScope = yield* Scope.make();
const stdio = Stdio.make({
args: Effect.succeed([]),
stdin: Stream.never,
stdout: () => Sink.drain,
stderr: () => Sink.drain,
});
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
testHooks: {
onOutgoingWriteAdmitted: () =>
Deferred.succeed(admitted, undefined).pipe(
Effect.andThen(Deferred.await(releaseAdmission)),
),
},
}).pipe(Effect.provideService(Scope.Scope, protocolScope));
const send = (requestId: string) =>
transport.serverProtocol
.send(0, {
_tag: "Exit",
requestId,
exit: { _tag: "Success", value: { ok: true } },
})
.pipe(Effect.exit);
const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
yield* Deferred.await(admitted);
yield* Scope.close(protocolScope, Exit.void);
yield* Deferred.succeed(releaseAdmission, undefined);
yield* Fiber.join(admittedSend);
yield* send("future");
assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
}),
);
it.effect("cleans up interrupted extension requests before a late response arrives", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
@@ -562,6 +737,31 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
}),
);
it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
const terminations = yield* Ref.make(0);
const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
stdio,
serverRequestMethods: new Set(),
onTermination: () => Ref.update(terminations, (count) => count + 1),
testHooks: {
onOutgoingWriterExit: (detail) =>
Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
},
});
yield* transport.serverProtocol.end(0);
const exitDetail = yield* Deferred.await(writerExit);
assert.isTrue(exitDetail.intentionalEnd);
assert.equal(yield* Ref.get(terminations), 0);
// Tear down the forever input reader so the scoped test can finish.
yield* Queue.end(input);
}),
);
it.effect("does not emit a second process-exit error after a decode failure", () =>
Effect.gen(function* () {
const handle = yield* makeHandle({
+218 -7
View File
@@ -1,6 +1,7 @@
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Exit from "effect/Exit";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -48,6 +49,11 @@ export interface AcpPatchedProtocolOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
readonly onIncomingRequest?: (
requestId: string,
method: string,
payload: unknown,
) => Effect.Effect<void, never>;
readonly onNotification?: (
notification: AcpIncomingNotification,
) => Effect.Effect<void, AcpError.AcpError, never>;
@@ -56,6 +62,18 @@ export interface AcpPatchedProtocolOptions {
params: unknown,
) => Effect.Effect<unknown, AcpError.AcpError, never>;
readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
readonly onOutgoingResponseFailure?: (
requestId: string,
error: AcpError.AcpError,
) => Effect.Effect<void, never>;
readonly onOutgoingResponse?: (requestId: string) => Effect.Effect<void, never>;
readonly testHooks?: {
readonly onOutgoingWriteAdmitted?: () => Effect.Effect<void>;
/** Invoked from the stdout writer exit path (after intentional/unexpected handling). */
readonly onOutgoingWriterExit?: (input: {
readonly intentionalEnd: boolean;
}) => Effect.Effect<void>;
};
}
export interface AcpPatchedProtocol {
@@ -71,6 +89,17 @@ interface AcpPendingRequest {
readonly method: string;
}
interface AcpOutgoingWrite {
readonly acknowledgement?: Deferred.Deferred<void, AcpError.AcpError>;
readonly payload: string | Uint8Array;
}
interface AcpOutgoingWriterState {
readonly outstandingAcknowledgements: ReadonlySet<Deferred.Deferred<void, AcpError.AcpError>>;
readonly intentionalEnd: boolean;
readonly terminalError?: AcpError.AcpError;
}
const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
const decodeElicitationComplete = Schema.decodeUnknownEffect(
AcpSchema.ElicitationCompleteNotification,
@@ -85,7 +114,11 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();
const disconnects = yield* Queue.unbounded<number>();
const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
const outgoing = yield* Queue.unbounded<AcpOutgoingWrite, AcpError.AcpError | Cause.Done<void>>();
const outgoingWriterState = yield* Ref.make<AcpOutgoingWriterState>({
intentionalEnd: false,
outstandingAcknowledgements: new Set(),
});
const nextRequestId = yield* Ref.make(1n);
const terminationHandled = yield* Ref.make(false);
const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
@@ -132,7 +165,66 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
});
yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
const acknowledgement =
message._tag === "Exit" ? yield* Deferred.make<void, AcpError.AcpError>() : undefined;
const admissionError = yield* Ref.modify(outgoingWriterState, (state) => {
if (state.terminalError !== undefined) {
return [state.terminalError, state] as const;
}
if (acknowledgement === undefined) {
return [undefined, state] as const;
}
return [
undefined,
{
...state,
outstandingAcknowledgements: new Set(state.outstandingAcknowledgements).add(
acknowledgement,
),
},
] as const;
});
if (admissionError !== undefined) {
return yield* admissionError;
}
if (options.testHooks?.onOutgoingWriteAdmitted !== undefined) {
yield* options.testHooks.onOutgoingWriteAdmitted();
}
yield* Queue.offer(outgoing, {
payload: encoded,
...(acknowledgement === undefined ? {} : { acknowledgement }),
}).pipe(
Effect.mapError(
(cause) =>
new AcpError.AcpTransportError({
detail: "Failed to queue an outgoing ACP message",
cause,
}),
),
Effect.filterOrFail(
(accepted) => accepted,
() =>
new AcpError.AcpTransportError({
detail: "The ACP output queue was closed before accepting a message",
cause: "Output queue closed",
}),
),
Effect.tapError((error) =>
acknowledgement === undefined
? Effect.void
: Ref.update(outgoingWriterState, (state) => {
const updated = new Set(state.outstandingAcknowledgements);
updated.delete(acknowledgement);
return { ...state, outstandingAcknowledgements: updated };
}).pipe(Effect.andThen(Deferred.fail(acknowledgement, error)), Effect.asVoid),
),
);
if (acknowledgement !== undefined) {
yield* Deferred.await(acknowledgement);
}
if (message._tag === "Exit" && options.onOutgoingResponse !== undefined) {
yield* options.onOutgoingResponse(message.requestId);
}
}
});
@@ -308,8 +400,11 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
});
}
const observeIncoming =
options.onIncomingRequest?.(message.id, message.tag, message.payload) ?? Effect.void;
if (!options.serverRequestMethods.has(message.tag)) {
return handleExtRequest(message).pipe(
return observeIncoming.pipe(Effect.andThen(handleExtRequest(message))).pipe(
Effect.catchTags({
AcpProtocolParseError: (error) =>
Effect.logWarning(error).pipe(
@@ -334,7 +429,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
);
}
return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
return observeIncoming.pipe(Effect.andThen(Queue.offer(serverQueue, message)), Effect.asVoid);
};
const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
@@ -473,7 +568,112 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
Effect.forkScoped,
);
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
const failOutgoingWrites = (error: AcpError.AcpError) =>
Ref.modify(outgoingWriterState, (state) => {
const terminalError = state.terminalError ?? error;
return [
[terminalError, state.outstandingAcknowledgements] as const,
{
...state,
terminalError,
outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
},
] as const;
}).pipe(
Effect.flatMap((acknowledgements) =>
Effect.forEach(
acknowledgements[1],
(acknowledgement) => Deferred.fail(acknowledgement, acknowledgements[0]),
{ concurrency: "unbounded", discard: true },
),
),
Effect.andThen(Queue.fail(outgoing, error)),
Effect.asVoid,
);
const completeOutgoingWrites = () =>
Ref.modify(outgoingWriterState, (state) => {
return [
state.outstandingAcknowledgements,
{
...state,
outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
},
] as const;
}).pipe(
Effect.flatMap((acknowledgements) =>
Effect.forEach(
acknowledgements,
(acknowledgement) => Deferred.succeed(acknowledgement, undefined),
{ concurrency: "unbounded", discard: true },
),
),
Effect.asVoid,
);
const acknowledgeOutgoingWrite = (acknowledgement: Deferred.Deferred<void, AcpError.AcpError>) =>
Ref.update(outgoingWriterState, (state) => {
const updated = new Set(state.outstandingAcknowledgements);
updated.delete(acknowledgement);
return { ...state, outstandingAcknowledgements: updated };
}).pipe(Effect.andThen(Deferred.succeed(acknowledgement, undefined)), Effect.asVoid);
yield* Stream.fromQueue(outgoing).pipe(
Stream.flatMap((write) => {
const acknowledgement = write.acknowledgement;
const completion =
acknowledgement === undefined
? Stream.empty
: Stream.fromEffect(acknowledgeOutgoingWrite(acknowledgement)).pipe(Stream.drain);
return Stream.make(write.payload).pipe(Stream.concat(completion));
}),
Stream.run(options.stdio.stdout()),
Effect.onExit((exit) =>
Exit.match(exit, {
onFailure: (cause) => {
const error = new AcpError.AcpTransportError({
detail: Cause.hasInterruptsOnly(cause)
? "The ACP output writer was interrupted while closing"
: "Failed to write an outgoing ACP message",
cause,
});
return failOutgoingWrites(error).pipe(
Effect.andThen(
Cause.hasInterruptsOnly(cause)
? Effect.void
: handleTermination(() => Effect.succeed(error)),
),
);
},
onSuccess: () =>
Ref.get(outgoingWriterState).pipe(
Effect.flatMap((state) => {
// Intentional Queue.end (serverProtocol.end) completes the writer
// successfully. Do not invent a transport failure or client protocol
// error for a clean RPC shutdown.
const handled = state.intentionalEnd
? completeOutgoingWrites()
: (() => {
const error = new AcpError.AcpTransportError({
detail: "ACP output writer ended before the protocol closed",
cause: "Output writer ended",
});
return failOutgoingWrites(error).pipe(
Effect.andThen(handleTermination(() => Effect.succeed(error))),
);
})();
return handled.pipe(
Effect.andThen(
options.testHooks?.onOutgoingWriterExit === undefined
? Effect.void
: options.testHooks.onOutgoingWriterExit({
intentionalEnd: state.intentionalEnd,
}),
),
);
}),
),
}),
),
Effect.forkScoped,
);
const clientProtocol = RpcClient.Protocol.of({
run: (_clientId, f) =>
@@ -504,8 +704,19 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
Effect.forever,
),
disconnects,
send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
end: (_clientId) => Queue.end(outgoing),
send: (_clientId, response) =>
offerOutgoing(response).pipe(
Effect.tapError((error) =>
response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined
? options.onOutgoingResponseFailure(response.requestId, error)
: Effect.void,
),
Effect.orDie,
),
end: (_clientId) =>
Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(
Effect.andThen(Queue.end(outgoing)),
),
clientIds: Effect.succeed(new Set([0])),
initialMessage: Effect.succeedNone,
supportsAck: true,
@@ -7,22 +7,52 @@ const runId = RunId.make("run:timeline-visibility");
const nodeId = NodeId.make("node:timeline-visibility");
describe("isOrchestrationV2TurnItemVisible", () => {
it("hides interruption results from superseded attempts", () => {
it("hides unpaired interruption results from superseded attempts", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "run_interrupt_result", runId, nodeId },
runs: [{ id: runId, status: "running" }],
attempts: [{ runId, rootNodeId: nodeId, status: "superseded" }],
items: [{ type: "run_interrupt_result", runId, nodeId }],
}),
).toBe(false);
});
it("keeps interruption results from terminal attempts", () => {
it("keeps paired interruption results from superseded attempts", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "run_interrupt_result", runId, nodeId },
runs: [{ id: runId, status: "running" }],
attempts: [{ runId, rootNodeId: nodeId, status: "superseded" }],
items: [
{ type: "run_interrupt_request", runId, nodeId },
{ type: "run_interrupt_result", runId, nodeId },
],
}),
).toBe(true);
});
it("keeps interruption results from terminal attempts without a request", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "run_interrupt_result", runId, nodeId },
runs: [{ id: runId, status: "interrupted" }],
attempts: [{ runId, rootNodeId: nodeId, status: "interrupted" }],
items: [{ type: "run_interrupt_result", runId, nodeId }],
}),
).toBe(true);
});
it("keeps interruption results from terminal attempts with a request", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "run_interrupt_result", runId, nodeId },
runs: [{ id: runId, status: "interrupted" }],
attempts: [{ runId, rootNodeId: nodeId, status: "interrupted" }],
items: [
{ type: "run_interrupt_request", runId, nodeId },
{ type: "run_interrupt_result", runId, nodeId },
],
}),
).toBe(true);
});
@@ -40,6 +70,7 @@ describe("isOrchestrationV2TurnItemVisible", () => {
},
{ runId, rootNodeId: nodeId, status: "interrupted" },
],
items: [{ type: "run_interrupt_result", runId, nodeId }],
}),
).toBe(true);
});
+18 -2
View File
@@ -11,24 +11,36 @@ type TimelineTurnItem = Pick<OrchestrationV2TurnItem, "type" | "runId" | "nodeId
export function isOrchestrationV2SupersededInterrupt(input: {
readonly item: TimelineTurnItem;
readonly attempts: ReadonlyArray<TimelineRunAttempt>;
readonly items: ReadonlyArray<TimelineTurnItem>;
}): boolean {
const { item } = input;
if (item.type !== "run_interrupt_result" || item.runId === null || item.nodeId === null) {
return false;
}
return input.attempts.some(
const isSuperseded = input.attempts.some(
(attempt) =>
attempt.runId === item.runId &&
attempt.rootNodeId === item.nodeId &&
attempt.status === "superseded",
);
if (!isSuperseded) {
return false;
}
// Paired stop-then-steer results have a matching request on the same run and
// must stay visible. Legacy plain-steer results have no request and stay hidden.
const hasMatchingRequest = input.items.some(
(candidate) => candidate.type === "run_interrupt_request" && candidate.runId === item.runId,
);
return !hasMatchingRequest;
}
export function isOrchestrationV2TurnItemVisible(input: {
readonly item: TimelineTurnItem;
readonly runs: ReadonlyArray<TimelineRun>;
readonly attempts: ReadonlyArray<TimelineRunAttempt>;
readonly items: ReadonlyArray<TimelineTurnItem>;
}): boolean {
const { item } = input;
if (
@@ -38,5 +50,9 @@ export function isOrchestrationV2TurnItemVisible(input: {
return false;
}
return !isOrchestrationV2SupersededInterrupt({ item, attempts: input.attempts });
return !isOrchestrationV2SupersededInterrupt({
item,
attempts: input.attempts,
items: input.items,
});
}