diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 3a389a5063645..3e13a4799eb6c 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -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" })], diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 68d8cc02b49f1..1699db1c35afb 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -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) diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index a70c0d25792b8..1d3f563f35b08 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -8,6 +8,7 @@ import { type OrchestrationV2ThreadShell, type SourceControlCloneRepositoryInput, ProjectId, + OrchestratorMcpFailure, ProviderInstanceId, RunId, ThreadId, @@ -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"; @@ -55,6 +57,7 @@ const boxRun = RunId.make("run:box-auto"); interface Seen { readonly sends: ReadonlyArray; readonly waits: ReadonlyArray; + readonly reads: ReadonlyArray; readonly launches: ReadonlyArray; readonly projects: ReadonlyArray; readonly clones: ReadonlyArray; @@ -64,6 +67,7 @@ interface Seen { const nothingSeen: Seen = { sends: [], waits: [], + reads: [], launches: [], projects: [], clones: [], @@ -85,17 +89,33 @@ const boxThreads = (seen: Ref.Ref, linkSession: Ref.Ref) => { ); 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 => 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) => @@ -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", { @@ -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 = []; + const olderPeer = (args: unknown): Effect.Effect => { + 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]); + }), +); diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index 080f701c45cb2..d60ebcd8f42d7 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -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* ( + read: (args: unknown) => Effect.Effect, + 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; @@ -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, OrchestratorMcpFailure> => + forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, args); + const newest = newestPageForAgent(scope, tool.name, params); const forwarded: Effect.Effect< Tool.Success, OrchestratorMcpFailure @@ -247,7 +278,9 @@ const make = Effect.gen(function* () { environmentId, params as OrchestratorMcpThreadWaitInput, ) as Effect.Effect, OrchestratorMcpFailure>) - : forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params); + : newest === undefined + ? forwardTool(params) + : readNewestOrRetry(forwardTool, newest, params); return Effect.andThen(requireEnabled, forwarded); };