diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index ed8f05bcd5c3..812feab637c8 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -61,6 +61,7 @@ import { probeAcpRegistryConfiguration, setAcpRegistryProvider, } from "./probe.ts"; +import { makeAcpRegistrySessionPages } from "./sessionPages.ts"; import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistryAuth from "./auth.ts"; @@ -1172,6 +1173,9 @@ export const AcpRegistryDriver: ProviderDriver( effect: Effect.Effect< A, @@ -1257,15 +1261,17 @@ export const AcpRegistryDriver: ProviderDriver + listSessions: (input) => provideAcpManagementServices( - listAcpRegistrySessions({ - instanceId, - settings: effectiveConfig, - cwd, - environment: processEnvironment, - ...(cursor === undefined ? {} : { cursor }), - }), + sessionPages.list(input, (cursor) => + listAcpRegistrySessions({ + instanceId, + settings: effectiveConfig, + cwd: input.cwd, + environment: processEnvironment, + ...(cursor === undefined ? {} : { cursor }), + }), + ), ), deleteSession: ({ cwd, sessionId }) => provideAcpManagementServices( @@ -1276,7 +1282,7 @@ export const AcpRegistryDriver: ProviderDriver sessionPages.forgetSession(sessionId))), listProviders: (cwd) => provideAcpManagementServices( listAcpRegistryProviders({ diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 1db342bfbb38..cb3b37be2410 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -4,7 +4,7 @@ import { ACP_REGISTRY_SESSION_CURSOR_MAX_LENGTH, AcpRegistryListProvidersResult, AcpRegistryOperationError, - AcpRegistryListSessionsResult, + type AcpRegistryListSessionsResult, AcpRegistryProbeResult, type AcpRegistryProbeAuthMethod, type AcpRegistryProbeModel, @@ -878,7 +878,7 @@ export const listAcpRegistrySessions = Effect.fn("AcpRegistryProbe.listSessions" message: "The ACP agent returned a session page cursor that is too long.", }); } - const sessions = listed.sessions.slice(0, 256).flatMap((session) => { + const sessions = listed.sessions.flatMap((session) => { const sessionId = boundedOpaqueValue(session.sessionId, 1_024); const cwd = boundedOpaqueValue(session.cwd, 4_096); if (sessionId === undefined || cwd === undefined) return []; @@ -907,14 +907,16 @@ 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({ + // Uncapped: the driver's session pages split a large agent page into list results. + const result: AcpRegistryListSessionsResult = { sessions, nextCursor: isLong ? null : nextCursor, ...(isLong ? { longNextCursor: nextCursor } : {}), canLoad: initialized.agentCapabilities?.loadSession === true, canResume: initialized.agentCapabilities?.sessionCapabilities?.resume != null, canDelete: initialized.agentCapabilities?.sessionCapabilities?.delete != null, - }); + }; + return result; }, (effect) => effect.pipe( diff --git a/packages/provider-acp-registry/src/server/sessionPages.test.ts b/packages/provider-acp-registry/src/server/sessionPages.test.ts new file mode 100644 index 000000000000..591f332528b5 --- /dev/null +++ b/packages/provider-acp-registry/src/server/sessionPages.test.ts @@ -0,0 +1,151 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { assert, it } from "@effect/vitest"; +import type { AcpRegistryListSessionsResult } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; + +import { makeAcpRegistrySessionPages } from "./sessionPages.ts"; + +const cwd = "/workspace/demo"; +const range = (first: number, last: number) => + Array.from({ length: last - first + 1 }, (_, index) => `native-${first + index}`); + +const agentPage = ( + sessionIds: ReadonlyArray, + nextCursor: string | null, +): AcpRegistryListSessionsResult => ({ + sessions: sessionIds.map((sessionId) => ({ + sessionId, + cwd, + additionalDirectories: [], + title: null, + updatedAt: null, + importedThreadId: null, + })), + ...(nextCursor !== null && nextCursor.length > 2_048 + ? { nextCursor: null, longNextCursor: nextCursor } + : { nextCursor }), + canLoad: true, + canResume: false, + canDelete: true, +}); + +const makeAgent = (pages: Record) => { + const requested: Array = []; + const fetch = (cursor: string | undefined) => { + requested.push(cursor); + const page = pages[cursor ?? ""]; + return page === undefined ? Effect.die(`unexpected cursor ${cursor}`) : Effect.succeed(page); + }; + return { requested, fetch }; +}; + +const listAll = Effect.fn(function* ( + pages: Effect.Success, + fetch: ReturnType["fetch"], +) { + const listed: Array> = []; + let cursor: string | undefined; + do { + const page = yield* pages.list({ cwd, ...(cursor === undefined ? {} : { cursor }) }, fetch); + listed.push(page.sessions.map(({ sessionId }) => sessionId)); + cursor = page.nextCursor ?? page.longNextCursor ?? undefined; + } while (cursor !== undefined && listed.length < 10); + assert.isUndefined(cursor); + return listed; +}); + +const longCursor = "c".repeat(2_048); +const longOlder = "o".repeat(4_096); + +it.effect("passes agent pages and their cursors through exactly, even ones shaped like ours", () => + Effect.gen(function* () { + const pages = yield* makeAcpRegistrySessionPages; + const agent = makeAgent({ + "": agentPage(range(1, 257), "t3-sessions-native-page-2"), + "t3-sessions-native-page-2": agentPage(["native-258"], null), + }); + assert.deepStrictEqual(yield* listAll(pages, agent.fetch), [ + range(1, 256), + ["native-257"], + ["native-258"], + ]); + assert.deepStrictEqual(agent.requested, [undefined, "t3-sessions-native-page-2"]); + }).pipe(Effect.provide(NodeCrypto.layer)), +); + +it.effect.each([ + { size: 257, expected: [["native-0"], range(1, 256), ["native-257"], ["native-258"]] }, + { + size: 513, + expected: [["native-0"], range(1, 256), range(257, 512), ["native-513"], ["native-514"]], + }, +])( + "splits an agent page of $size sessions reached through a maximum-length cursor", + ({ size, expected }) => + Effect.gen(function* () { + const pages = yield* makeAcpRegistrySessionPages; + const agent = makeAgent({ + "": agentPage(["native-0"], longCursor), + [longCursor]: agentPage(range(1, size), longOlder), + [longOlder]: agentPage([`native-${size + 1}`], null), + }); + assert.deepStrictEqual(yield* listAll(pages, agent.fetch), expected); + assert.deepStrictEqual(agent.requested, [undefined, longCursor, longOlder]); + }).pipe(Effect.provide(NodeCrypto.layer)), +); + +it.effect("serves the rest of a large page from the response the user already saw", () => + Effect.gen(function* () { + const pages = yield* makeAcpRegistrySessionPages; + const pagesByCursor: Record = { + "": agentPage(range(1, 257), null), + }; + const agent = makeAgent(pagesByCursor); + const first = yield* pages.list({ cwd }, agent.fetch); + assert.deepStrictEqual( + first.sessions.map(({ sessionId }) => sessionId), + range(1, 256), + ); + pagesByCursor[""] = agentPage(["native-new", ...range(2, 257)], null); + yield* pages.forgetSession("native-unrelated"); + const rest = yield* pages.list({ cwd, cursor: first.nextCursor ?? "" }, agent.fetch); + assert.deepStrictEqual( + rest.sessions.map(({ sessionId }) => sessionId), + ["native-257"], + ); + assert.isNull(rest.nextCursor); + assert.deepStrictEqual(agent.requested, [undefined]); + }).pipe(Effect.provide(NodeCrypto.layer)), +); + +it.effect("drops a deleted session from the rest of a large page", () => + Effect.gen(function* () { + const pages = yield* makeAcpRegistrySessionPages; + const agent = makeAgent({ "": agentPage(range(1, 258), null) }); + const first = yield* pages.list({ cwd }, agent.fetch); + yield* pages.forgetSession("native-257"); + const rest = yield* pages.list({ cwd, cursor: first.nextCursor ?? "" }, agent.fetch); + assert.deepStrictEqual( + rest.sessions.map(({ sessionId }) => sessionId), + ["native-258"], + ); + }).pipe(Effect.provide(NodeCrypto.layer)), +); + +it.effect("asks to list again when the rest of a large page expired or names another project", () => + Effect.gen(function* () { + const pages = yield* makeAcpRegistrySessionPages; + const agent = makeAgent({ "": agentPage(range(1, 257), null) }); + const first = yield* pages.list({ cwd }, agent.fetch); + const cursor = first.nextCursor ?? ""; + const otherProject = yield* pages + .list({ cwd: "/workspace/other", cursor }, agent.fetch) + .pipe(Effect.flip); + assert.strictEqual(otherProject.message, "The ACP session list expired. List sessions again."); + yield* TestClock.adjust("11 minutes"); + const expired = yield* pages.list({ cwd, cursor }, agent.fetch).pipe(Effect.flip); + assert.strictEqual(expired.message, "The ACP session list expired. List sessions again."); + assert.deepStrictEqual(agent.requested, [undefined]); + }).pipe(Effect.provide(NodeCrypto.layer)), +); diff --git a/packages/provider-acp-registry/src/server/sessionPages.ts b/packages/provider-acp-registry/src/server/sessionPages.ts new file mode 100644 index 000000000000..1a0056aa071b --- /dev/null +++ b/packages/provider-acp-registry/src/server/sessionPages.ts @@ -0,0 +1,79 @@ +import { AcpRegistryOperationError, type AcpRegistryListSessionsResult } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; + +const MAX_LISTED_SESSIONS = 256; +const MAX_CONTINUATIONS = 16; +const CONTINUATION_TTL_MS = 10 * 60_000; +const CONTINUATION_PREFIX = "t3-sessions-"; + +interface Continuation { + readonly cwd: string; + readonly listed: AcpRegistryListSessionsResult; + readonly expiresAt: number; +} + +/** + * Agents may return more sessions in one page than the list result carries. The rest is + * kept from that same response behind a short-lived cursor, so a list that changes between + * pages can neither repeat nor hide a session. Agent cursors pass through untouched. + */ +export const makeAcpRegistrySessionPages = Effect.gen(function* () { + const random = yield* SecureRandom.SecureRandom; + const continuations = yield* Ref.make>(new Map()); + + const list = Effect.fn("AcpRegistrySessionPages.list")(function* ( + input: { readonly cwd: string; readonly cursor?: string }, + fetch: (cursor: string | undefined) => Effect.Effect, + ) { + const now = yield* Clock.currentTimeMillis; + // Only membership marks a continuation: agent cursors are opaque and may look like ours. + const stored = + input.cursor === undefined ? undefined : (yield* Ref.get(continuations)).get(input.cursor); + if (stored !== undefined && (stored.cwd !== input.cwd || stored.expiresAt <= now)) { + return yield* new AcpRegistryOperationError({ + reason: "probe_failed", + message: "The ACP session list expired. List sessions again.", + }); + } + const listed = stored?.listed ?? (yield* fetch(input.cursor)); + if (listed.sessions.length <= MAX_LISTED_SESSIONS) return listed; + + const token = `${CONTINUATION_PREFIX}${yield* random.uuidV4()}`; + const continuation: Continuation = { + cwd: input.cwd, + listed: { ...listed, sessions: listed.sessions.slice(MAX_LISTED_SESSIONS) }, + expiresAt: now + CONTINUATION_TTL_MS, + }; + yield* Ref.update(continuations, (current) => { + const live = [...current].filter(([, entry]) => entry.expiresAt > now); + return new Map([...live.slice(-(MAX_CONTINUATIONS - 1)), [token, continuation]]); + }); + const { longNextCursor: _agentCursor, ...head } = listed; + return { ...head, sessions: listed.sessions.slice(0, MAX_LISTED_SESSIONS), nextCursor: token }; + }); + + const forgetSession = (sessionId: string) => + Ref.update( + continuations, + (current) => + new Map( + [...current].map(([token, entry]) => [ + token, + { + ...entry, + listed: { + ...entry.listed, + sessions: entry.listed.sessions.filter( + (session) => session.sessionId !== sessionId, + ), + }, + }, + ]), + ), + ); + + return { list, forgetSession }; +}); diff --git a/scripts/scenarios/acp-session-list-keeps-full-pages.e2e.ts b/scripts/scenarios/acp-session-list-keeps-full-pages.e2e.ts new file mode 100644 index 000000000000..c18019fa1246 --- /dev/null +++ b/scripts/scenarios/acp-session-list-keeps-full-pages.e2e.ts @@ -0,0 +1,87 @@ +// @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"; + +const session = (number, cwd) => ({ + sessionId: "native-" + number, + cwd, + title: "Native conversation " + number, +}); +for await (const line of createInterface({ input: process.stdin })) { + const { id, method, params } = JSON.parse(line); + if (id === undefined) continue; + const result = + method === "initialize" ? { + protocolVersion: 1, + agentCapabilities: { loadSession: true, sessionCapabilities: { list: {} } }, + authMethods: [], + } : + method === "session/new" ? { sessionId: "health-probe" } : + method === "session/list" ? ( + params.cursor === "older" + ? { sessions: [session(258, params.cwd)] } + : { + sessions: Array.from({ length: 257 }, (_, index) => session(index + 1, params.cwd)), + nextCursor: "older", + } + ) : + undefined; + const response = result === undefined + ? { id, error: { code: -32601, message: "Method not found" } } + : { id, result }; + process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...response }) + "\\n"); +} +`; + +test( + "Native ACP conversations remain available when an agent returns a large page", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo", { "session-agent.mjs": ACP }); + const instanceId = ProviderInstanceId.make("scenario-large-session-page"); + 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 }); + const more = screen.getByRole("button", "Load more", { exact: true }); + const loading = screen.getByRole("button", "Loading", { exact: true }); + await more.tap(); + await loading.waitFor({ state: "hidden" }); + if (await more.isVisible()) await more.tap(); + await screen.getByText("Native conversation 258", { exact: true }).waitFor(); + + const missingConversation = screen.getByText("Native conversation 257", { exact: true }); + await app.screenshot("native-sessions-after-last-page"); + expect(await missingConversation.isVisible()).toBe(true); + }, +);