Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,12 @@ it("readThread preserves caller access errors and prefers activity-run status ov
});
expect(laterPage.thread.pullRequests).toBeUndefined();
expect(laterPage.thread.pullRequestCount).toBe(8);
// A read from past the tail is the newest page, which a linked environment asks for.
const newestPage = yield* service.readThread(makeScope(), {
threadId: parentThreadId,
beforePosition: Number.MAX_SAFE_INTEGER,
});
expect(newestPage.thread.pullRequests?.map((link) => link.number)).toEqual([2, 8, 7, 6, 5]);

Object.assign(projection, {
runs: [makeRun({ id: activeRunId, ordinal: 1, status: "completed" })],
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3550,8 +3550,8 @@ const make = Effect.gen(function* () {
shell,
yield* Clock.currentTimeMillis,
input.afterPosition === undefined &&
input.beforePosition === undefined &&
input.itemId === undefined,
input.itemId === undefined &&
(input.beforePosition === undefined || input.beforePosition >= timeline.totalItems),
);
const recentRuns = target.runs
.toSorted((left, right) => right.ordinal - left.ordinal)
Expand Down
82 changes: 80 additions & 2 deletions apps/server/src/peer/PeerForwarding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type OrchestrationV2ThreadShell,
type SourceControlCloneRepositoryInput,
ProjectId,
OrchestratorMcpFailure,
ProviderInstanceId,
RunId,
ThreadId,
Expand All @@ -23,6 +24,7 @@ import * as TestClock from "effect/testing/TestClock";
import { McpSchema, McpServer } from "effect/ai";

import * as ServerConfig from "../config.ts";
import type { ProjectionTimelinePageOptions } from "../orchestration-v2/ProjectionStore.ts";
import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
Expand Down Expand Up @@ -55,6 +57,7 @@ const boxRun = RunId.make("run:box-auto");
interface Seen {
readonly sends: ReadonlyArray<ThreadManagement.ThreadManagementSendInput>;
readonly waits: ReadonlyArray<ThreadManagement.ThreadManagementWaitInput>;
readonly reads: ReadonlyArray<ProjectionTimelinePageOptions>;
readonly launches: ReadonlyArray<ThreadLaunch.ThreadLaunchInput>;
readonly projects: ReadonlyArray<ProjectService.ProjectCreateInput>;
readonly clones: ReadonlyArray<SourceControlCloneRepositoryInput>;
Expand All @@ -64,6 +67,7 @@ interface Seen {
const nothingSeen: Seen = {
sends: [],
waits: [],
reads: [],
launches: [],
projects: [],
clones: [],
Expand All @@ -85,17 +89,33 @@ const boxThreads = (seen: Ref.Ref<Seen>, linkSession: Ref.Ref<string>) => {
);
const users = { ...liveThreadShell(usersThread, { runtimeMode: "auto" }), projectId: boxProject };
const run = (status: OrchestrationV2Run["status"]) =>
({ id: boxRun, status }) as unknown as OrchestrationV2Run;
({
id: boxRun,
ordinal: 1,
status,
modelSelection: base.modelSelection,
requestedAt: base.createdAt,
startedAt: null,
completedAt: null,
}) as unknown as OrchestrationV2Run;
const shellOf = (threadId: ThreadId): Effect.Effect<OrchestrationV2ThreadShell | null> =>
threadId === boxThread ? linked : Effect.succeed(threadId === usersThread ? users : null);
const projectionOf = (threadId: ThreadId) =>
shellOf(threadId).pipe(
Effect.map((thread) => ({ thread, runs: [run("running")], runtimeRequests: [] }) as never),
Effect.map(
(thread) =>
({ thread, runs: [run("running")], runtimeRequests: [], providerTurns: [] }) as never,
),
);
return Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: shellOf,
getProjectThreadRecords: (input) => projectionOf(input.threadId),
getThreadRecords: (threadId) => projectionOf(threadId),
getRunCount: () => Effect.succeed(1),
getTimelinePage: (_threadId, options) =>
Ref.update(seen, (current) => ({ ...current, reads: [...current.reads, options] })).pipe(
Effect.as({ items: [], totalItems: 0, hasMore: false, hasEarlier: false }),
),
listProjectThreads: () => linked.pipe(Effect.map((shell) => [shell] as never)),
getShellSnapshot: () => linked.pipe(Effect.map((shell) => ({ threads: [shell] }) as never)),
sendToThread: (input) =>
Expand Down Expand Up @@ -627,6 +647,15 @@ it.effect("runs any tool that takes a linked environment there", () =>
});
expect(archived.isError).toBe(false);
expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]);
// A cursorless read from an agent here gets the newest page there, as it does locally.
const read = yield* a.call("thread:laptop-full", "t3_thread_read", {
environmentId: box.environmentId,
threadId: boxThread,
});
expect(read.isError).toBe(false);
expect((yield* Ref.get(seen)).reads).toEqual([
{ beforePosition: Number.MAX_SAFE_INTEGER, limit: 10, view: "messages" },
]);

// This environment's own id keeps the call here.
const own = yield* a.call("thread:laptop-full", "t3_thread_configure", {
Expand Down Expand Up @@ -744,3 +773,52 @@ it.effect("refuses a launch there above the link's access, naming the link", ()
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

const refusedRead = (message: string) =>
new OrchestratorMcpFailure({ code: "invalid_request", message });
const beforePositionRefusal = refusedRead(
`Invalid parameters for tool 't3_thread_read': Unknown argument "beforePosition". Accepted arguments: limit, view.`,
);

it("recognizes only a validation refusal of beforePosition", () => {
const cases: Array<[OrchestratorMcpFailure, boolean]> = [
[beforePositionRefusal, true],
[
refusedRead(
`Invalid parameters for tool 't3_thread_read': Unknown arguments "runLimit", "beforePosition". Accepted arguments: limit.`,
),
true,
],
[refusedRead(`Invalid parameters for tool 't3_thread_read': Unknown argument "limit".`), false],
// A thread id can carry the same words; only the refusal's code and prefix count.
[
new OrchestratorMcpFailure({
code: "thread_not_found",
message: `Thread Unknown argument "beforePosition". Accepted arguments: x. is no longer available.`,
}),
false,
],
];
for (const [failure, expected] of cases) {
expect(PeerForwarding.refusesBeforePosition(failure)).toBe(expected);
}
});

it.effect("retries a newest-page read without its cursor when the peer refuses the cursor", () =>
Effect.gen(function* () {
const sent: Array<unknown> = [];
const olderPeer = (args: unknown): Effect.Effect<string, OrchestratorMcpFailure> => {
sent.push(args);
return "beforePosition" in (args as object)
? Effect.fail(beforePositionRefusal)
: Effect.succeed("forward page");
};
const params = { threadId: "thread:box-auto", limit: 35 };
const newest = { ...params, beforePosition: Number.MAX_SAFE_INTEGER };

const page = yield* PeerForwarding.readNewestOrRetry(olderPeer, newest, params);

expect(page).toBe("forward page");
expect(sent).toEqual([newest, params]);
}),
);
35 changes: 34 additions & 1 deletion apps/server/src/peer/PeerForwarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,23 @@ const linkStorageFailure = (error: PeerLinkError) =>
export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) =>
environmentId === scope.environmentId ? undefined : environmentId;

// Older peers reject beforePosition during parameter validation.
const BEFORE_POSITION_REFUSAL =
/^Invalid parameters for tool 't3_thread_read': Unknown arguments? (?:"[^"]+", )*"beforePosition"(?:, "[^"]+")*\. Accepted arguments: /;
export const refusesBeforePosition = (failure: {
readonly code: string;
readonly message: string;
}) => failure.code === "invalid_request" && BEFORE_POSITION_REFUSAL.test(failure.message);

/** A newest-page read, retried as the peer always served it when the peer refuses the cursor. */
export const readNewestOrRetry = Effect.fn("PeerForwarding.readNewestOrRetry")(function* <A>(
read: (args: unknown) => Effect.Effect<A, OrchestratorMcpFailure>,
newest: unknown,
params: unknown,
) {
return yield* read(newest).pipe(Effect.catchIf(refusesBeforePosition, () => read(params)));
});

const make = Effect.gen(function* () {
const peers = yield* PeerMcpClient.PeerMcpClient;
const links = yield* PeerLinks.PeerLinks;
Expand Down Expand Up @@ -237,7 +254,21 @@ const make = Effect.gen(function* () {
Effect.flatMap((enabled) => (enabled ? Effect.void : Effect.fail(linkedEnvironmentsOff))),
);

// A peer pages a client's cursorless read forward; an agent's gets the newest page, as it does here.
const newestPageForAgent = (scope: Scope, toolName: string, params: unknown) => {
if (toolName !== "t3_thread_read" || scope.thread === undefined) return undefined;
const input = params as OrchestratorMcpThreadReadInput;
return input.afterPosition === undefined && input.beforePosition === undefined
? { ...input, beforePosition: Number.MAX_SAFE_INTEGER }
: undefined;
};

const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) => {
const forwardTool = (
args: unknown,
): Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure> =>
forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, args);
const newest = newestPageForAgent(scope, tool.name, params);
const forwarded: Effect.Effect<
Tool.Success<typeof tool>,
OrchestratorMcpFailure
Expand All @@ -247,7 +278,9 @@ const make = Effect.gen(function* () {
environmentId,
params as OrchestratorMcpThreadWaitInput,
) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
: forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
: newest === undefined
? forwardTool(params)
: readNewestOrRetry(forwardTool, newest, params);
return Effect.andThen(requireEnabled, forwarded);
};

Expand Down
Loading