mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 22:11:12 +00:00
* test(mcp): cancel analyze_javascript_application through an MCP client Refs #1065. The existing JavaScript cancellation tests either call the analysis function directly or cancel through a mocked progress reporter in the process-global project. These six mcp-boundary tests cancel through the production server, the real 100 ms progress throttle and a real worker, and pin the delivered cancelled result, the absent reply frame, the removed worker folders and the next call. The last test pins the late race: a cancel that arrives while the success reply is being written still lets that reply out, keeps the Evidence and logs ok. The terminal-progress cancel is left to the process-global test, which already covers it. The observer helper lives in tests/support so the reply and progress holds are not copied between files. 🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊 Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> * test(mcp): assert no reply only after the cancelled call settles The three no-reply checks followed a client ping, which only raced the server's handler tail on microtask order. With REA's transport changed to keep notifications/cancelled from the SDK, so the SDK really writes the cancelled result, the old tests still passed 6 of 6. observeToolCall now offers settled(): it waits until REA's handler for the call returned, lets the SDK make its reply decision, and joins any reply the SDK handed to REA's transport. The same late-reply change now fails all five cancellation tests at their no-reply check, also with a 50 ms delay in the handler or in REA's publish path. Raised by Greptile on #16476. 🤖 Generated with Claude Code (Opus 5.5) 🦊 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
468 lines
16 KiB
TypeScript
468 lines
16 KiB
TypeScript
import type { Client } from "@modelcontextprotocol/client";
|
|
import {
|
|
isCallToolResult,
|
|
isJSONRPCResultResponse,
|
|
type CallToolResult,
|
|
} from "@modelcontextprotocol/server";
|
|
import { access, mkdir, writeFile } from "node:fs/promises";
|
|
import { basename, join } from "node:path";
|
|
import pino from "pino";
|
|
import { expect, it, onTestFinished, vi } from "vitest";
|
|
import { z } from "zod";
|
|
|
|
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
|
|
import { parseEvidence } from "../../../src/domain/evidence.js";
|
|
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
|
import { ToolResultDelivery } from "../../../src/server/ToolResultDelivery.js";
|
|
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
|
|
import { createDeferred } from "../../fixtures/binarySession.js";
|
|
import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js";
|
|
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { phaseGate } from "../../support/lifecycleHarness.js";
|
|
import {
|
|
observeToolCall,
|
|
type HeldToolCallMessage,
|
|
} from "../../support/mcpToolCallObserver.js";
|
|
|
|
const TOOL = "analyze_javascript_application";
|
|
const TERMINAL_PROGRESS = `${TOOL}: Application graph and Electron boundaries reconstructed`;
|
|
|
|
/**
|
|
* The client rejects as soon as it aborts, so waits after an abort cannot race
|
|
* the call; the test's wait deadline bounds them.
|
|
*/
|
|
const SERVER_SIDE: Promise<never> = new Promise<never>(() => undefined);
|
|
|
|
const analysisCall = (root: string) => ({
|
|
name: TOOL,
|
|
arguments: { input_path: root, format: "directory" },
|
|
});
|
|
|
|
const writeFunctions = (path: string, count: number, prefix: string) =>
|
|
writeFile(
|
|
path,
|
|
Array.from(
|
|
{ length: count },
|
|
(_, index) =>
|
|
`function ${prefix}_${String(index)}(value) { const next = JSON.stringify(value); return next + 'item-${String(index)}'; }`,
|
|
).join("\n"),
|
|
);
|
|
|
|
const oneFileApplication = async () => {
|
|
const root = await createTestTempDirectory("rea-js-mcp-cancel-");
|
|
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
|
|
return root;
|
|
};
|
|
|
|
const completionSchema = z.object({
|
|
tool: z.string(),
|
|
status: z.string(),
|
|
msg: z.string(),
|
|
});
|
|
|
|
/**
|
|
* Production server, SDK client and a real JavaScript worker, plus three
|
|
* observation points: the worker roots REA allocates, the cancelled results the
|
|
* server delivers (the SDK drops the reply of a cancelled request), and the
|
|
* server's completion log.
|
|
*/
|
|
const fixture = async () => {
|
|
// The project shares one thread between files, so every spy dies with the test.
|
|
onTestFinished(() => {
|
|
vi.restoreAllMocks();
|
|
});
|
|
const roots: string[] = [];
|
|
const create = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot);
|
|
vi.spyOn(PrivateRuntimeRoot, "create").mockImplementation(async (...args) => {
|
|
const root = await create(...args);
|
|
if (basename(root.path).startsWith("rea-javascript-analysis-"))
|
|
roots.push(root.path);
|
|
return root;
|
|
});
|
|
const deliveries: CallToolResult[] = [];
|
|
const delivery = createDeferred<CallToolResult>();
|
|
const deliver = ToolResultDelivery.prototype.toPartialErrorToolResult;
|
|
vi.spyOn(
|
|
ToolResultDelivery.prototype,
|
|
"toPartialErrorToolResult",
|
|
).mockImplementation(function (this: ToolResultDelivery, ...args) {
|
|
const result = deliver.apply(this, args);
|
|
deliveries.push(result);
|
|
delivery.resolve(result);
|
|
return result;
|
|
});
|
|
const statuses: string[] = [];
|
|
const completed = createDeferred<string>();
|
|
const logger = pino(
|
|
{ level: "info" },
|
|
{
|
|
write(line) {
|
|
const entry = completionSchema.safeParse(JSON.parse(line));
|
|
if (
|
|
entry.success &&
|
|
entry.data.tool === TOOL &&
|
|
entry.data.msg === "MCP tool execution completed"
|
|
) {
|
|
statuses.push(entry.data.status);
|
|
completed.resolve(entry.data.status);
|
|
}
|
|
},
|
|
},
|
|
);
|
|
const harness = await createApplicationMcpHarness({
|
|
serverOptions: { logger },
|
|
});
|
|
return {
|
|
...harness,
|
|
roots,
|
|
deliveries,
|
|
statuses,
|
|
/** The first cancelled result the server built for the call. */
|
|
delivered: () =>
|
|
awaitAcknowledgement(
|
|
delivery.promise,
|
|
SERVER_SIDE,
|
|
"cancelled delivery",
|
|
).then(() => delivery.promise),
|
|
/** The status of the server's first completion log for the call. */
|
|
completion: () =>
|
|
awaitAcknowledgement(
|
|
completed.promise,
|
|
SERVER_SIDE,
|
|
"completion log",
|
|
).then(() => completed.promise),
|
|
};
|
|
};
|
|
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
|
|
|
const removed = async (paths: readonly string[]) => {
|
|
expect(paths.length).toBeGreaterThan(0);
|
|
for (const path of paths)
|
|
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
|
|
};
|
|
|
|
const partialStatisticsSchema = z.object({
|
|
statistics: z.object({
|
|
relevant_files: z.number(),
|
|
parsed_javascript_files: z.number(),
|
|
parse_failures: z.number(),
|
|
}),
|
|
});
|
|
|
|
/** Read the retained partial Evidence a cancelled result references. */
|
|
const partialStatistics = (test: Fixture, result: CallToolResult) => {
|
|
const { error } = parseMcpToolError(result);
|
|
const reference = z
|
|
.object({
|
|
partial_observation: z.object({
|
|
kind: z.literal("retained-evidence"),
|
|
evidence_id: z.string(),
|
|
}),
|
|
})
|
|
.parse(error.details).partial_observation;
|
|
const evidence = test.session.evidenceById(reference.evidence_id);
|
|
expect(evidence?.operation).toBe(TOOL);
|
|
return {
|
|
error,
|
|
evidenceId: reference.evidence_id,
|
|
statistics: partialStatisticsSchema.parse(evidence?.normalized_result)
|
|
.statistics,
|
|
};
|
|
};
|
|
|
|
/** A client call whose rejection is data, so a gate failure cannot orphan it. */
|
|
const startCall = (
|
|
client: Client,
|
|
root: string,
|
|
signal: AbortSignal,
|
|
): Promise<unknown> =>
|
|
client
|
|
.callTool(analysisCall(root), { signal, onprogress: () => undefined })
|
|
.then(
|
|
(reply) => reply,
|
|
(cause: unknown) => cause,
|
|
);
|
|
|
|
const retainedEvidenceIds = z
|
|
.object({
|
|
result: z.object({
|
|
kind: z.literal("evidence-bundle-summary"),
|
|
records: z.array(z.object({ evidence_id: z.string() })),
|
|
}),
|
|
})
|
|
.transform(({ result }) =>
|
|
result.records.map((record) => record.evidence_id),
|
|
);
|
|
|
|
const expectRetainedAndServing = async (test: Fixture, evidenceId: string) => {
|
|
await expect(test.client.ping()).resolves.toEqual({});
|
|
// Summary detail: a complete bundle of the cancelled multi-file graph can
|
|
// exceed the response budget, and identity is what this check needs.
|
|
const bundle = await test.client.callTool({
|
|
name: "get_evidence_bundle",
|
|
arguments: { detail: "summary" },
|
|
});
|
|
expect(bundle.isError, JSON.stringify(bundle.content)).not.toBe(true);
|
|
expect(retainedEvidenceIds.parse(bundle.structuredContent)).toEqual([
|
|
evidenceId,
|
|
]);
|
|
const next = await oneFileApplication();
|
|
const reply = await test.client.callTool(analysisCall(next));
|
|
expect(reply.isError, JSON.stringify(reply.content)).not.toBe(true);
|
|
expect(parseEvidence(reply.structuredContent).operation).toBe(TOOL);
|
|
};
|
|
|
|
/**
|
|
* Failure-path teardown: stop and join the call before its spy goes, even when
|
|
* a wait failed. Aborting an already settled call changes nothing.
|
|
*/
|
|
const teardown = async (
|
|
controller: AbortController,
|
|
observed: ReturnType<typeof observeToolCall>,
|
|
call: Promise<unknown>,
|
|
) => {
|
|
controller.abort();
|
|
observed.release();
|
|
await call;
|
|
observed.restore();
|
|
};
|
|
|
|
/** Cancel at the held boundary, wait until the server handled it, then release. */
|
|
const cancelHeld = async (held: {
|
|
readonly test: Fixture;
|
|
readonly controller: AbortController;
|
|
readonly observed: ReturnType<typeof observeToolCall>;
|
|
readonly call: Promise<unknown>;
|
|
readonly reason: Error;
|
|
readonly boundary: string;
|
|
}) => {
|
|
const { test, controller, observed, call, reason, boundary } = held;
|
|
await observed.reached(call, boundary);
|
|
controller.abort(reason);
|
|
await observed.cancelled(SERVER_SIDE, `${boundary} cancellation delivery`);
|
|
// In-memory messages are ordered: the ping reply follows the server's
|
|
// handling of the cancellation, so its signal is aborted before the release.
|
|
await test.client.ping();
|
|
expect(await call).toMatchObject({
|
|
code: "REQUEST_TIMEOUT",
|
|
message: expect.stringContaining(reason.message),
|
|
});
|
|
observed.release();
|
|
};
|
|
|
|
/**
|
|
* Cancel a one-file analysis held at `held` and check what every such
|
|
* cancellation shares: a typed cancelled result with retained partial
|
|
* Evidence, an error completion log, and no reply frame.
|
|
*/
|
|
const cancelOneFileAt = async (
|
|
held: HeldToolCallMessage,
|
|
reason: Error,
|
|
boundary: string,
|
|
) => {
|
|
const test = await fixture();
|
|
const observed = observeToolCall(TOOL, held);
|
|
const controller = new AbortController();
|
|
const call = startCall(
|
|
test.client,
|
|
await oneFileApplication(),
|
|
controller.signal,
|
|
);
|
|
try {
|
|
await cancelHeld({ test, controller, observed, call, reason, boundary });
|
|
expect(await test.completion()).toBe("error");
|
|
const partial = partialStatistics(test, await test.delivered());
|
|
expect(partial.error.code).toBe("cancelled");
|
|
await observed.settled(SERVER_SIDE, "cancelled call settlement");
|
|
expect(observed.replies).toEqual([]);
|
|
return { test, progress: [...observed.progress], ...partial };
|
|
} finally {
|
|
await teardown(controller, observed, call);
|
|
}
|
|
};
|
|
|
|
it("cancels one large source at its first worker boundary through the SDK and serves the next call", async () => {
|
|
const test = await fixture();
|
|
const root = await createTestTempDirectory("rea-js-mcp-cancel-large-");
|
|
await writeFunctions(join(root, "main.js"), 1200, "selected");
|
|
const observed = observeToolCall(TOOL, {
|
|
kind: "progress",
|
|
matches: (message) => message.startsWith("javascript_worker_"),
|
|
});
|
|
const controller = new AbortController();
|
|
const call = startCall(test.client, root, controller.signal);
|
|
try {
|
|
await cancelHeld({
|
|
test,
|
|
controller,
|
|
observed,
|
|
call,
|
|
reason: new Error("cancel at the first worker boundary"),
|
|
boundary: "first worker boundary",
|
|
});
|
|
expect(await test.completion()).toBe("error");
|
|
const result = await test.delivered();
|
|
const { error, evidenceId, statistics } = partialStatistics(test, result);
|
|
expect(error).toMatchObject({
|
|
code: "cancelled",
|
|
category: "cancelled",
|
|
retryable: true,
|
|
details: { operation: TOOL, cleanup: "complete" },
|
|
});
|
|
expect(statistics).toEqual({
|
|
relevant_files: 1,
|
|
parsed_javascript_files: 0,
|
|
parse_failures: 0,
|
|
});
|
|
// The SDK drops a cancelled request's reply once its handler returns.
|
|
await observed.settled(SERVER_SIDE, "cancelled call settlement");
|
|
expect(observed.replies).toEqual([]);
|
|
expect(observed.progress.at(-1)).toBe(
|
|
"javascript_worker_parse: JavaScript worker parse: main.js",
|
|
);
|
|
expect(test.roots).toHaveLength(1);
|
|
await removed(test.roots);
|
|
await expectRetainedAndServing(test, evidenceId);
|
|
} finally {
|
|
await teardown(controller, observed, call);
|
|
}
|
|
});
|
|
|
|
it("cancels between files of a multi-file application, keeping the parsed files", async () => {
|
|
const test = await fixture();
|
|
const root = await createTestTempDirectory("rea-js-mcp-cancel-files-");
|
|
const files = 40;
|
|
const cancelledFile = 12;
|
|
await mkdir(join(root, "src"));
|
|
await Promise.all(
|
|
Array.from({ length: files }, (_, index) =>
|
|
writeFunctions(
|
|
join(root, "src", `module_${String(index).padStart(2, "0")}.js`),
|
|
30,
|
|
`fn${String(index)}`,
|
|
),
|
|
),
|
|
);
|
|
// The reporter drops all but the first parse update per 100 ms, so cancel
|
|
// where each file reaches its worker instead of at a progress message.
|
|
const reached = phaseGate();
|
|
let started = 0;
|
|
const analyze = JavaScriptAnalysisWorker.prototype.analyze;
|
|
vi.spyOn(JavaScriptAnalysisWorker.prototype, "analyze").mockImplementation(
|
|
async function (this: JavaScriptAnalysisWorker, ...args) {
|
|
// Only sources analyzed for the result count, not preload discovery.
|
|
const counted = args[5] === undefined || args[5] === "analysis";
|
|
if (counted && ++started === cancelledFile) await reached.hold();
|
|
return analyze.apply(this, args);
|
|
},
|
|
);
|
|
const observed = observeToolCall(TOOL, { kind: "none" });
|
|
const controller = new AbortController();
|
|
const call = startCall(test.client, root, controller.signal);
|
|
const reason = new Error("cancel between files");
|
|
try {
|
|
await reached.reached(call, "file worker call");
|
|
controller.abort(reason);
|
|
await observed.cancelled(SERVER_SIDE, "between-file cancellation delivery");
|
|
await test.client.ping();
|
|
expect(await call).toMatchObject({
|
|
code: "REQUEST_TIMEOUT",
|
|
message: expect.stringContaining(reason.message),
|
|
});
|
|
reached.release();
|
|
expect(await test.completion()).toBe("error");
|
|
const result = await test.delivered();
|
|
const { error, evidenceId, statistics } = partialStatistics(test, result);
|
|
expect(error.code).toBe("cancelled");
|
|
expect(statistics.relevant_files).toBe(files);
|
|
// Sources run in order: the held call never ran, the rest never started.
|
|
expect(started).toBe(cancelledFile);
|
|
expect(statistics.parsed_javascript_files).toBe(cancelledFile - 1);
|
|
await observed.settled(SERVER_SIDE, "cancelled call settlement");
|
|
expect(observed.replies).toEqual([]);
|
|
await removed(test.roots);
|
|
await expectRetainedAndServing(test, evidenceId);
|
|
} finally {
|
|
reached.release();
|
|
await teardown(controller, observed, call);
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
"build_javascript_application_graph",
|
|
"validate_javascript_application_result",
|
|
"hash_javascript_application_evidence",
|
|
])(
|
|
"cancels at %s after every source parsed, keeping them and delivering no completion",
|
|
async (phase) => {
|
|
const { test, progress, evidenceId, statistics } = await cancelOneFileAt(
|
|
{
|
|
kind: "progress",
|
|
matches: (message) => message.startsWith(`${phase}:`),
|
|
},
|
|
new Error(`cancel at ${phase}`),
|
|
phase,
|
|
);
|
|
expect(statistics).toEqual({
|
|
relevant_files: 1,
|
|
parsed_javascript_files: 1,
|
|
parse_failures: 0,
|
|
});
|
|
expect(progress.at(-1)).toMatch(new RegExp(`^${phase}:`));
|
|
expect(progress).not.toContain(TERMINAL_PROGRESS);
|
|
await expectRetainedAndServing(test, evidenceId);
|
|
// A healthy worker stays parked on the session until it closes.
|
|
await test.close();
|
|
await removed(test.roots);
|
|
},
|
|
);
|
|
|
|
it("publishes a completed success whose reply was already being written when cancellation arrived", async () => {
|
|
const test = await fixture();
|
|
const root = await oneFileApplication();
|
|
const observed = observeToolCall(TOOL, { kind: "reply" });
|
|
const controller = new AbortController();
|
|
const reason = new Error("cancel while the success reply is held");
|
|
const call = startCall(test.client, root, controller.signal);
|
|
try {
|
|
await observed.reached(call, "success reply");
|
|
// The handler is done: it logged success and its Evidence is retained.
|
|
expect(test.statuses).toEqual(["ok"]);
|
|
const retained = test.session.exportEvidenceBundle().records;
|
|
expect(retained.map((record) => record.operation)).toEqual([TOOL]);
|
|
controller.abort(reason);
|
|
await observed.cancelled(SERVER_SIDE, "late cancellation delivery");
|
|
await test.client.ping();
|
|
expect(await call).toMatchObject({
|
|
code: "REQUEST_TIMEOUT",
|
|
message: expect.stringContaining(reason.message),
|
|
});
|
|
expect(observed.replies).toEqual([]);
|
|
observed.release();
|
|
await observed.replySent(SERVER_SIDE, "success reply write");
|
|
const [frame] = observed.replies;
|
|
if (frame === undefined || !isJSONRPCResultResponse(frame))
|
|
throw new Error("Expected the success reply frame");
|
|
expect(isCallToolResult(frame.result)).toBe(true);
|
|
expect(frame.result["isError"]).not.toBe(true);
|
|
const evidence = parseEvidence(frame.result["structuredContent"]);
|
|
expect(evidence.operation).toBe(TOOL);
|
|
expect(retained.map((record) => record.evidence_id)).toEqual([
|
|
evidence.evidence_id,
|
|
]);
|
|
expect(test.deliveries).toEqual([]);
|
|
expect(test.statuses).toEqual(["ok"]);
|
|
await expect(test.client.ping()).resolves.toEqual({});
|
|
const bundle = await test.client.callTool({
|
|
name: "get_evidence_bundle",
|
|
arguments: { detail: "summary" },
|
|
});
|
|
expect(retainedEvidenceIds.parse(bundle.structuredContent)).toEqual([
|
|
evidence.evidence_id,
|
|
]);
|
|
} finally {
|
|
await teardown(controller, observed, call);
|
|
}
|
|
});
|