Skip to content
Merged
2 changes: 2 additions & 0 deletions apps/server/scripts/acp-mock-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -776,6 +777,7 @@ const program = Effect.gen(function* () {
updatedAt: "1970-01-01T00:00:00.000Z",
},
],
...(sessionListNextCursor === undefined ? {} : { nextCursor: sessionListNextCursor }),
};
}),
);
Expand Down
59 changes: 58 additions & 1 deletion apps/server/src/provider/AcpRegistryProbe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
15 changes: 13 additions & 2 deletions packages/contracts/src/acpRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 14 additions & 4 deletions packages/provider-acp-registry/src/server/probe.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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,
Expand Down
89 changes: 89 additions & 0 deletions scripts/scenarios/acp-session-list-keeps-pagination-token.e2e.ts
Original file line number Diff line number Diff line change
@@ -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);
},
);
Loading