diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index d137791ab7724..630280503a825 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -17,6 +17,7 @@ import type * as AcpCompat from "effect-acp/compat"; import { beginAcpMockPrompt } from "./acpMockCancellationState.ts"; const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH; +const sessionListNextCursor = process.env.T3_ACP_SESSION_LIST_NEXT_CURSOR; const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1"; const antigravityThoughtLevel = process.env.T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL === "1"; const antigravityResumeThoughtLevel = process.env.T3_ACP_RESUME_THOUGHT_LEVEL; @@ -776,6 +777,7 @@ const program = Effect.gen(function* () { updatedAt: "1970-01-01T00:00:00.000Z", }, ], + ...(sessionListNextCursor === undefined ? {} : { nextCursor: sessionListNextCursor }), }; }), ); diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index f9a982dfef503..c243cd1c321ff 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -5,7 +5,7 @@ import * as NodeURL from "node:url"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Layer from "effect/Layer"; -import { ProviderInstanceId } from "@t3tools/contracts"; +import { ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH, ProviderInstanceId } from "@t3tools/contracts"; import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -417,6 +417,63 @@ describe("ACP Registry probe", () => { ); }); + it.effect.each([ + { + name: "an unaltered cursor at the limit", + cursor: ` ${"c".repeat(ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH - 2)} `, + expected: [null, ` ${"c".repeat(ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH - 2)} `], + }, + { + name: "an error for a cursor past the limit", + cursor: "c".repeat(ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH + 1), + expected: "The ACP agent returned a session page cursor that is too long.", + }, + ])("returns $name for the next session page", ({ cursor, expected }) => { + const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ + search: () => Effect.die("unused search"), + prepare: () => Effect.die("unused prepare"), + refreshIndex: () => Effect.succeed(false), + invalidateIndex: () => Effect.void, + inspect: () => Effect.die("unused inspect"), + uninstallManagedBinary: () => Effect.die("unused uninstall"), + resolve: () => + Effect.succeed({ + agent: { + id: "mock-agent", + name: "Mock Agent", + version: "1.0.0", + description: "ACP session paging test agent", + distribution: { npx: { package: "mock-agent@1.0.0" } }, + }, + distribution: "npx" as const, + spawn: { + command: "node", + args: [mockAgentPath], + env: { + ...process.env, + T3_ACP_SESSION_LIFECYCLE: "1", + T3_ACP_SESSION_LIST_NEXT_CURSOR: cursor, + }, + }, + }), + }); + + return listAcpRegistrySessions({ + instanceId, + settings: decodeSettings({ agentId: "mock-agent" }), + cwd: process.cwd(), + environment: process.env, + }).pipe( + Effect.match({ + onSuccess: (listed) => [listed.nextCursor, listed.longNextCursor], + onFailure: (error) => error.message, + }), + Effect.map((nextCursor) => expect(nextCursor).toEqual(expected)), + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); + }); + it.live.each(["succeeds", "fails"] as const)( "deletes its health-probe session when deletion is advertised and %s", (deleteOutcome) => diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.tsx index 6ac63a01837d2..a20fe552d30e6 100644 --- a/apps/web/src/components/settings/AcpSessionManagementSection.tsx +++ b/apps/web/src/components/settings/AcpSessionManagementSection.tsx @@ -215,7 +215,7 @@ function InstanceSessionManagement( setSessions((current) => cursor === undefined ? listedSessions : [...current, ...listedSessions], ); - setNextCursor(result.value.nextCursor); + setNextCursor(result.value.nextCursor ?? result.value.longNextCursor ?? null); return; } reportFailure(gt`Could not list ACP sessions`, result); diff --git a/packages/contracts/src/acpRegistry.ts b/packages/contracts/src/acpRegistry.ts index fffbe8dd44934..8af4b26eb5d0a 100644 --- a/packages/contracts/src/acpRegistry.ts +++ b/packages/contracts/src/acpRegistry.ts @@ -155,16 +155,27 @@ export const AcpRegistrySession = Schema.Struct({ }); export type AcpRegistrySession = typeof AcpRegistrySession.Type; +// ACP cursors are opaque; agents may encode the pages they already returned in them. +export const ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH = 65_536; +export const ACP_REGISTRY_LEGACY_SESSION_CURSOR_MAX_LENGTH = 2_048; +const AcpRegistrySessionCursor = Schema.String.check( + Schema.isMaxLength(ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH), +); + export const AcpRegistryListSessionsInput = Schema.Struct({ instanceId: ProviderInstanceId, projectId: ProjectId, - cursor: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2_048))), + cursor: Schema.optionalKey(AcpRegistrySessionCursor), }); export type AcpRegistryListSessionsInput = typeof AcpRegistryListSessionsInput.Type; export const AcpRegistryListSessionsResult = Schema.Struct({ sessions: Schema.Array(AcpRegistrySession).check(Schema.isMaxLength(256)), - nextCursor: Schema.NullOr(Schema.String.check(Schema.isMaxLength(2_048))), + // Clients built before `longNextCursor` reject a longer `nextCursor`, so it carries those instead. + nextCursor: Schema.NullOr( + Schema.String.check(Schema.isMaxLength(ACP_REGISTRY_LEGACY_SESSION_CURSOR_MAX_LENGTH)), + ), + longNextCursor: Schema.optionalKey(AcpRegistrySessionCursor), canLoad: Schema.Boolean, canResume: Schema.Boolean, canDelete: Schema.Boolean, diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 7bf0fe28114c9..1db342bfbb389 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -1,5 +1,7 @@ import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { + ACP_REGISTRY_LEGACY_SESSION_CURSOR_MAX_LENGTH, + ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH, AcpRegistryListProvidersResult, AcpRegistryOperationError, AcpRegistryListSessionsResult, @@ -869,6 +871,13 @@ export const listAcpRegistrySessions = Effect.fn("AcpRegistryProbe.listSessions" const runtime = yield* makeAcpRegistryManagementRuntime(input); const initialized = yield* runtime.initialize(); const listed = yield* runtime.listSessions(input.cursor); + // Cursors are opaque, so one that does not fit is rejected rather than altered or dropped. + if ((listed.nextCursor?.length ?? 0) > ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH) { + return yield* new AcpRegistryOperationError({ + reason: "probe_failed", + message: "The ACP agent returned a session page cursor that is too long.", + }); + } const sessions = listed.sessions.slice(0, 256).flatMap((session) => { const sessionId = boundedOpaqueValue(session.sessionId, 1_024); const cwd = boundedOpaqueValue(session.cwd, 4_096); @@ -895,12 +904,13 @@ export const listAcpRegistrySessions = Effect.fn("AcpRegistryProbe.listSessions" }, ]; }); + const nextCursor = listed.nextCursor || null; + const isLong = + nextCursor !== null && nextCursor.length > ACP_REGISTRY_LEGACY_SESSION_CURSOR_MAX_LENGTH; return AcpRegistryListSessionsResult.make({ sessions, - nextCursor: - listed.nextCursor === undefined || listed.nextCursor === null - ? null - : boundedText(listed.nextCursor, 2_048) || null, + nextCursor: isLong ? null : nextCursor, + ...(isLong ? { longNextCursor: nextCursor } : {}), canLoad: initialized.agentCapabilities?.loadSession === true, canResume: initialized.agentCapabilities?.sessionCapabilities?.resume != null, canDelete: initialized.agentCapabilities?.sessionCapabilities?.delete != null, diff --git a/scripts/scenarios/acp-session-list-keeps-pagination-token.e2e.ts b/scripts/scenarios/acp-session-list-keeps-pagination-token.e2e.ts new file mode 100644 index 0000000000000..159a08d9a1fbc --- /dev/null +++ b/scripts/scenarios/acp-session-list-keeps-pagination-token.e2e.ts @@ -0,0 +1,89 @@ +// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable. +import * as NodePath from "node:path"; + +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const ACP = ` +import { createInterface } from "node:readline"; + +// An opaque cursor can encode the IDs the agent has already returned. +const ids = Array.from({ length: 60 }, (_, index) => "sample-conversation-session-" + index); +const nextCursor = Buffer.from(JSON.stringify(ids)).toString("base64url"); +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +for await (const line of createInterface({ input: process.stdin })) { + const { id, method, params } = JSON.parse(line); + if (id === undefined) continue; + if (method === "initialize") { + send({ id, result: { + protocolVersion: 1, + agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } }, + authMethods: [], + } }); + } else if (method === "session/new") { + send({ id, result: { sessionId: "probe" } }); + } else if (method === "session/list" && params.cursor === undefined) { + send({ id, result: { + nextCursor, + sessions: ids.map((sessionId, index) => ({ + sessionId, + cwd: params.cwd, + title: "Native conversation " + (index + 1), + })), + } }); + } else if (method === "session/list" && params.cursor === nextCursor) { + send({ id, result: { + sessions: [{ sessionId: "archived", cwd: params.cwd, title: "Older conversation" }], + } }); + } else { + send({ id, error: method === "session/list" + ? { code: -32602, message: "Invalid session cursor" } + : { code: -32601, message: "Method not found" }, + }); + } +} +`; + +test( + "Load more opens the next ACP session page when its cursor is long", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo", { "session-agent.mjs": ACP }); + const instanceId = ProviderInstanceId.make("scenario-long-session-cursor"); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, app.baseUrl ?? ""); + yield* client["server.updateSettings"]({ + patch: {}, + providerInstanceMutation: { + operation: "upsert", + instanceId, + instance: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "Local Session Agent", + enabled: true, + config: { + source: "local", + commandPath: process.execPath, + commandArgs: [NodePath.join(project, "session-agent.mjs")], + }, + }, + }, + }); + }).pipe(Effect.scoped), + ); + + await t3.open(`/settings/providers?instanceId=${instanceId}`); + await screen.getByRole("button", "List sessions", { exact: true }).tap({ timeout: 60_000 }); + await screen.getByRole("button", "Load more", { exact: true }).tap(); + await screen.getByRole("button", "Refresh", { exact: true }).waitFor(); + + const older = screen.getByText("Older conversation", { exact: true }); + await app.screenshot("native-sessions-after-load-more"); + expect(await older.isVisible()).toBe(true); + }, +);