|
| 1 | +import {afterEach, describe, expect, it, vi} from 'vitest'; |
| 2 | +import * as acp from '@agentclientprotocol/sdk'; |
| 3 | +import * as acpV2 from '@agentclientprotocol/sdk/experimental/v2'; |
| 4 | +import {z} from 'zod'; |
| 5 | +import {createAcpAgentRouter} from '../../AcpAgentRouter'; |
| 6 | +import {CodexAcpServer} from '../../CodexAcpServer'; |
| 7 | +import {CodexAcpClient} from '../../CodexAcpClient'; |
| 8 | +import {CodexAppServerClient} from '../../CodexAppServerClient'; |
| 9 | +import type {Thread} from '../../app-server/v2'; |
| 10 | +import { |
| 11 | + SESSION_ARCHIVE_METHOD, |
| 12 | + SESSION_LIST_CHANGES_METHOD, |
| 13 | + SESSION_LIST_SUBSCRIBE_METHOD, |
| 14 | + SESSION_LIST_UNSUBSCRIBE_METHOD, |
| 15 | + SESSION_RENAME_METHOD, |
| 16 | + SESSION_UNARCHIVE_METHOD, |
| 17 | +} from '../../SessionIndex'; |
| 18 | +import {createTestModel} from '../acp-test-utils'; |
| 19 | +import {createMockConnections} from './test-utils'; |
| 20 | +import {checkV2SessionUpdate, expectConformingV2SessionUpdates} from './v2-session-update-guard'; |
| 21 | + |
| 22 | +const sessionId = "thread-1"; |
| 23 | +const cwd = "/workspace"; |
| 24 | + |
| 25 | +function createThread(overrides?: Partial<Thread>): Thread { |
| 26 | + return { |
| 27 | + id: sessionId, |
| 28 | + sessionId, |
| 29 | + parentThreadId: null, |
| 30 | + threadSource: null, |
| 31 | + originator: null, |
| 32 | + forkedFromId: null, |
| 33 | + preview: "Earlier session", |
| 34 | + ephemeral: false, |
| 35 | + modelProvider: "openai", |
| 36 | + model: "gpt-5", |
| 37 | + reasoningEffort: null, |
| 38 | + createdAt: 100, |
| 39 | + updatedAt: 200, |
| 40 | + recencyAt: 300, |
| 41 | + status: {type: "notLoaded"}, |
| 42 | + path: null, |
| 43 | + cwd, |
| 44 | + cliVersion: "0.0.0", |
| 45 | + section: null, |
| 46 | + sectionEnteredAt: null, |
| 47 | + projectId: null, |
| 48 | + historyMode: "paginated", |
| 49 | + source: "cli", |
| 50 | + agentNickname: null, |
| 51 | + agentRole: null, |
| 52 | + gitInfo: null, |
| 53 | + name: null, |
| 54 | + turns: [], |
| 55 | + ...overrides, |
| 56 | + }; |
| 57 | +} |
| 58 | + |
| 59 | +function codexResponse(method: string): unknown { |
| 60 | + switch (method) { |
| 61 | + case "thread/start": |
| 62 | + return { |
| 63 | + thread: createThread({status: {type: "idle"}}), |
| 64 | + model: "gpt-5", |
| 65 | + modelProvider: "openai", |
| 66 | + reasoningEffort: "medium", |
| 67 | + serviceTier: null, |
| 68 | + }; |
| 69 | + case "thread/read": |
| 70 | + return {thread: createThread({ |
| 71 | + status: {type: "active", activeFlags: []}, |
| 72 | + name: "Renamed", |
| 73 | + path: "/codex-home/sessions/rollout.jsonl", |
| 74 | + })}; |
| 75 | + case "thread/list": |
| 76 | + return {data: [createThread()], nextCursor: null, backwardsCursor: null}; |
| 77 | + case "model/list": |
| 78 | + return {data: [createTestModel({id: "gpt-5"})], nextCursor: null}; |
| 79 | + case "skills/list": |
| 80 | + return {data: []}; |
| 81 | + case "config/read": |
| 82 | + return {config: {}, origins: {}, layers: []}; |
| 83 | + case "thread/goal/get": |
| 84 | + return {goal: null}; |
| 85 | + default: |
| 86 | + return {}; |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +/** Methods whose requests the snapshots record; the rest is session-setup noise. */ |
| 91 | +const recordedCodexMethods = new Set([ |
| 92 | + "thread/list", |
| 93 | + "thread/name/set", |
| 94 | + "thread/archive", |
| 95 | + "thread/unarchive", |
| 96 | +]); |
| 97 | + |
| 98 | +async function connectV2Client(airCapabilities: string[]) { |
| 99 | + const mocks = createMockConnections(); |
| 100 | + const codexRequests: Array<{method: string, params: unknown}> = []; |
| 101 | + mocks.mockCodexConnection.sendRequest.mockImplementation(async (method: string, params?: unknown) => { |
| 102 | + if (recordedCodexMethods.has(method)) { |
| 103 | + codexRequests.push({method, params}); |
| 104 | + } |
| 105 | + return codexResponse(method); |
| 106 | + }); |
| 107 | + const codexAcpClient = new CodexAcpClient(new CodexAppServerClient(mocks.mockCodexConnection as any)); |
| 108 | + vi.spyOn(codexAcpClient, "readAuthRequirement").mockResolvedValue({required: false, account: null}); |
| 109 | + vi.spyOn(codexAcpClient, "getAgentConfiguredModelProvider").mockResolvedValue("openai"); |
| 110 | + vi.spyOn(codexAcpClient, "getAccount").mockResolvedValue({account: null, requiresOpenaiAuth: false}); |
| 111 | + vi.spyOn(codexAcpClient, "awaitMcpServerStartup").mockResolvedValue({ready: [], failed: [], cancelled: []}); |
| 112 | + const router = createAcpAgentRouter((connection) => new CodexAcpServer(connection, codexAcpClient)); |
| 113 | + const clientToAgent = new TransformStream<Uint8Array, Uint8Array>(); |
| 114 | + const agentToClient = new TransformStream<Uint8Array, Uint8Array>(); |
| 115 | + router.connect(acp.ndJsonStream(agentToClient.writable, clientToAgent.readable)); |
| 116 | + |
| 117 | + const updates: acpV2.UpdateSessionNotification[] = []; |
| 118 | + const listChanges: unknown[] = []; |
| 119 | + const connection = acpV2.client({name: "test-client"}) |
| 120 | + .onNotification(acpV2.methods.client.session.update, (ctx) => { |
| 121 | + checkV2SessionUpdate(ctx.params.update); |
| 122 | + updates.push(ctx.params); |
| 123 | + }) |
| 124 | + .onNotification(SESSION_LIST_CHANGES_METHOD, z.object({}).passthrough(), (ctx) => { |
| 125 | + listChanges.push(ctx.params); |
| 126 | + }) |
| 127 | + .connect(acp.ndJsonStream(clientToAgent.writable, agentToClient.readable)); |
| 128 | + const initialize = await connection.agent.request(acpV2.methods.agent.initialize, { |
| 129 | + protocolVersion: 2, |
| 130 | + info: {name: "test-client", version: "1.0.0"}, |
| 131 | + capabilities: {_meta: {jetbrains: {air: {version: 1, capabilities: airCapabilities}}}}, |
| 132 | + }); |
| 133 | + const sendServerNotification = (notification: unknown) => mocks.getUnhandledNotificationHandler()?.(notification); |
| 134 | + return {connection, initialize, codexRequests, updates, listChanges, sendServerNotification}; |
| 135 | +} |
| 136 | + |
| 137 | +function airCapabilitiesOf(response: acpV2.InitializeResponse): unknown { |
| 138 | + return (response._meta as any)?.jetbrains?.air?.capabilities ?? null; |
| 139 | +} |
| 140 | + |
| 141 | +function dump(value: unknown): string { |
| 142 | + return `${JSON.stringify(value, null, 2)}\n`; |
| 143 | +} |
| 144 | + |
| 145 | +describe('AIR sessionIndex over ACP v2', () => { |
| 146 | + let closeClient: (() => void) | null = null; |
| 147 | + |
| 148 | + afterEach(() => { |
| 149 | + closeClient?.(); |
| 150 | + closeClient = null; |
| 151 | + vi.useRealTimers(); |
| 152 | + vi.clearAllMocks(); |
| 153 | + expectConformingV2SessionUpdates(); |
| 154 | + }); |
| 155 | + |
| 156 | + it('neither advertises nor serves sessionIndex to a v2 client that does not declare it', async () => { |
| 157 | + const {connection, initialize} = await connectV2Client([]); |
| 158 | + closeClient = () => connection.close(); |
| 159 | + |
| 160 | + expect(airCapabilitiesOf(initialize)).not.toContain("sessionIndex"); |
| 161 | + await expect(connection.agent.request(SESSION_RENAME_METHOD, {sessionId, title: "Renamed"})) |
| 162 | + .rejects.toMatchObject({code: -32601}); |
| 163 | + }); |
| 164 | + |
| 165 | + it('lists, renames, archives and unarchives sessions', async () => { |
| 166 | + const {connection, initialize, codexRequests, updates} = await connectV2Client(["sessionIndex"]); |
| 167 | + closeClient = () => connection.close(); |
| 168 | + await connection.agent.request(acpV2.methods.agent.session.new, {cwd}); |
| 169 | + await vi.waitFor(() => expect(updates.length).toBeGreaterThan(0)); |
| 170 | + updates.length = 0; |
| 171 | + |
| 172 | + const list = await connection.agent.request(acpV2.methods.agent.session.list, { |
| 173 | + cwd, |
| 174 | + _meta: {jetbrains: {air: {list: {limit: 10}}}}, |
| 175 | + }); |
| 176 | + const rename = await connection.agent.request(SESSION_RENAME_METHOD, {sessionId, title: "Renamed"}); |
| 177 | + // The session is open here: archiving closes it and tells the client why. |
| 178 | + const archive = await connection.agent.request(SESSION_ARCHIVE_METHOD, {sessionId}); |
| 179 | + const unarchive = await connection.agent.request(SESSION_UNARCHIVE_METHOD, {sessionId}); |
| 180 | + |
| 181 | + await expect(dump({ |
| 182 | + capabilities: airCapabilitiesOf(initialize), |
| 183 | + list, |
| 184 | + rename, |
| 185 | + archive, |
| 186 | + unarchive, |
| 187 | + codexRequests, |
| 188 | + updates: updates.filter(({update}) => update.sessionUpdate === "session_info_update"), |
| 189 | + })).toMatchFileSnapshot('data/session-index-v2.json'); |
| 190 | + }); |
| 191 | + |
| 192 | + it('pushes the changed rows of a subscription', async () => { |
| 193 | + const {connection, listChanges, sendServerNotification} = await connectV2Client(["sessionIndex"]); |
| 194 | + closeClient = () => connection.close(); |
| 195 | + |
| 196 | + const {subscriptionId} = await connection.agent.request(SESSION_LIST_SUBSCRIBE_METHOD, {cwd}) as {subscriptionId: string}; |
| 197 | + sendServerNotification({ |
| 198 | + method: "thread/status/changed", |
| 199 | + params: {threadId: sessionId, status: {type: "active", activeFlags: []}}, |
| 200 | + }); |
| 201 | + await vi.waitFor(() => expect(listChanges).toHaveLength(1)); |
| 202 | + const unsubscribe = await connection.agent.request(SESSION_LIST_UNSUBSCRIBE_METHOD, {subscriptionId}); |
| 203 | + |
| 204 | + await expect(dump({ |
| 205 | + listChanges: listChanges.map((change: any) => ({...change, subscriptionId: "<subscriptionId>"})), |
| 206 | + unsubscribe, |
| 207 | + })).toMatchFileSnapshot('data/session-index-v2-subscription.json'); |
| 208 | + }); |
| 209 | +}); |
0 commit comments