mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-18 14:25:51 +00:00
* fix: harden ACP communication boundaries Harden ACP communication boundaries Remote ACP sessions now cannot widen permission mode through untrusted metadata or client payloads. WebSocket ACP ingress measures payloads by bytes before binary decode, and prompt queue handoff keeps exactly one prompt active while queued prompts are drained FIFO. Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent Constraint: WebSocket payload limits must be byte-based and checked before binary decode Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing Confidence: high Scope-risk: moderate Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build Not-tested: Manual live ACP/RCS session against an external client * fix: restore repository verification gates Keep the full repository test, typecheck, build, and Biome lint gates usable after the ACP fix pass. This commit is intentionally separate from the ACP behavior change: it fixes Windows-safe Langfuse home redaction, removes stale lint suppressions, resolves Biome warning/info diagnostics, and keeps env expansion tests explicit without template-placeholder lint noise. Constraint: The project completion contract requires full typecheck, lint, test, and build evidence Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims Confidence: high Scope-risk: narrow Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build Not-tested: Manual Langfuse export against a real external Langfuse service * fix: harden ACP failure boundaries after review Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter. Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed Confidence: high Scope-risk: moderate Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bunx tsc --noEmit Tested: bunx biome lint src/ packages/acp-link/src/ Tested: bun run test:all Tested: bun run build Not-tested: Manual end-to-end ACP client session over a real editor WebSocket * fix: prevent ACP coverage runs from seeing partial mocks GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module. This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure. Constraint: bun:test mock.module is process-global inside a worker. Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution. Rejected: Keep per-file helper copies | duplication would let restore semantics drift again. Confidence: high Scope-risk: narrow Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests. Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov Tested: bunx tsc --noEmit Tested: bun run lint Tested: git diff --check Not-tested: Linux runner directly before push * fix: normalize ACP bypass requests without warning noise The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path. This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order. Constraint: CI output should not contain expected warning noise for covered policy branches. Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch. Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site. Confidence: high Scope-risk: narrow Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass. Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0 Tested: bun run test:all Tested: bun run lint Tested: bunx tsc --noEmit Tested: git diff --check * fix: harden ACP bypass and CI warning gates ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state. Constraint: CI must stay warning-clean without hiding real ACP permission failures Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path Confidence: high Scope-risk: moderate Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts Tested: bun run test:all Tested: bun run lint Tested: bun run build:vite with zero warning matches Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches Not-tested: GitHub Actions result after this push * fix: remove remaining CI warning noise The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics. Constraint: Do not use shell log filtering to hide warnings after they happen Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find Confidence: high Scope-risk: narrow Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects Tested: bunx tsc --noEmit --pretty false Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts Tested: bun run build:vite with zero warning matches Not-tested: GitHub Actions result after this push * fix: reject unauthorized ACP bypass and harden CI actions ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings. CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token. Constraint: Must not hide warnings with test isolation or log filtering Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope Confidence: high Scope-risk: moderate Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false Tested: bunx tsc --noEmit --pretty false Tested: bun run lint Tested: bun run test:all Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0 Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR * fix: resolve dependency audit findings precisely Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified. Constraint: no audit ignores or warning suppression Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution Confidence: high Scope-risk: moderate Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: keep ACP auth tokens out of URLs Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change. Constraint: token must not be embedded in the URL Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs Confidence: high Scope-risk: moderate Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code Tested: targeted ACP/RCS transport tests Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: normalize WebFetch request headers Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline. Constraint: preserve header semantics without widening the fetch surface Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites Confidence: high Scope-risk: narrow Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically Tested: targeted WebFetch header tests Not-tested: unrelated fetch backend behavior beyond header normalization * fix: harden ACP remote auth surfaces Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist. Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string. Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data. Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries. Confidence: high Scope-risk: moderate Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>. Tested: bunx tsc --noEmit --pretty false Tested: bun run typecheck in packages/remote-control-server Tested: bun run build in packages/acp-link Tested: bun run lint Tested: bun audit Tested: focused RCS/acp-link/web tests, 160 pass Tested: Edge headless browser WebSocket subprotocol handshake Tested: bun run test:all, 3669 pass Tested: bun run build:vite Tested: bun run build Not-tested: Manual end-to-end relay with a live external ACP agent * fix: resolve CI dependency override lookup The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating. Constraint: Do not add a new root dependency for a transitive smoke test. Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync. Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface. Confidence: high Scope-risk: narrow Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting. Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check --------- Co-authored-by: unraid <local@unraid.local>
1151 lines
38 KiB
TypeScript
1151 lines
38 KiB
TypeScript
import {
|
|
describe,
|
|
expect,
|
|
test,
|
|
mock,
|
|
beforeEach,
|
|
afterEach,
|
|
afterAll,
|
|
spyOn,
|
|
} from 'bun:test'
|
|
|
|
// ── Mock infrastructure ──────────────────────────────────────────
|
|
// bun:test mock.module is process-global: it leaks to sibling test files
|
|
// in the same worker. Preserve real exports before partial module mocking
|
|
// so afterAll can restore them, preventing cross-file pollution.
|
|
|
|
const _restores: (() => void)[] = []
|
|
const originalCwd = process.cwd()
|
|
const originalAcpPermissionMode = process.env.ACP_PERMISSION_MODE
|
|
const originalAcpAllowBypass = process.env.CLAUDE_CODE_ACP_ALLOW_BYPASS_PERMISSIONS
|
|
|
|
function mockModulePreservingExports(
|
|
tsPath: string,
|
|
overrides: Record<string, unknown>,
|
|
) {
|
|
const jsPath = tsPath.replace(/\.ts$/, '.js')
|
|
const snapshot = { ...(require(tsPath) as Record<string, unknown>) }
|
|
mock.module(jsPath, () => ({ ...snapshot, ...overrides }))
|
|
_restores.push(() => mock.module(jsPath, () => snapshot))
|
|
}
|
|
|
|
afterAll(() => {
|
|
for (let i = _restores.length - 1; i >= 0; i--) {
|
|
_restores[i]()
|
|
}
|
|
_restores.length = 0
|
|
restoreEnv('ACP_PERMISSION_MODE', originalAcpPermissionMode)
|
|
restoreEnv(
|
|
'CLAUDE_CODE_ACP_ALLOW_BYPASS_PERMISSIONS',
|
|
originalAcpAllowBypass,
|
|
)
|
|
})
|
|
|
|
// ── Module mocks (must precede any import of the module under test) ──
|
|
|
|
const mockSetModel = mock(() => {})
|
|
const mockSubmitMessage = mock(async function* (_input: string) {})
|
|
|
|
mockModulePreservingExports('../../../QueryEngine.ts', {
|
|
QueryEngine: class MockQueryEngine {
|
|
submitMessage = mockSubmitMessage
|
|
interrupt = mock(() => {})
|
|
resetAbortController = mock(() => {})
|
|
getAbortSignal = mock(() => new AbortController().signal)
|
|
setModel = mockSetModel
|
|
},
|
|
})
|
|
|
|
mockModulePreservingExports('../../../tools.ts', {
|
|
getTools: mock(() => []),
|
|
})
|
|
|
|
mockModulePreservingExports('../../../Tool.ts', {
|
|
toolMatchesName: mock(() => false),
|
|
findToolByName: mock(() => undefined),
|
|
filterToolProgressMessages: mock(() => []),
|
|
buildTool: mock((def: any) => def),
|
|
})
|
|
|
|
mockModulePreservingExports('../../../utils/config.ts', {
|
|
enableConfigs: mock(() => {}),
|
|
})
|
|
|
|
mockModulePreservingExports('../../../bootstrap/state.ts', {
|
|
setOriginalCwd: mock(() => {}),
|
|
addSlowOperation: mock(() => {}),
|
|
})
|
|
|
|
const mockGetDefaultAppState = mock(() => ({
|
|
toolPermissionContext: {
|
|
mode: 'default',
|
|
additionalWorkingDirectories: new Map(),
|
|
alwaysAllowRules: { user: [], project: [], local: [] },
|
|
alwaysDenyRules: { user: [], project: [], local: [] },
|
|
alwaysAskRules: { user: [], project: [], local: [] },
|
|
isBypassPermissionsModeAvailable: true,
|
|
},
|
|
fastMode: false,
|
|
settings: {},
|
|
tasks: {},
|
|
verbose: false,
|
|
mainLoopModel: null,
|
|
mainLoopModelForSession: null,
|
|
}))
|
|
|
|
mockModulePreservingExports('../../../state/AppStateStore.ts', {
|
|
getDefaultAppState: mockGetDefaultAppState,
|
|
})
|
|
|
|
mockModulePreservingExports('../utils.ts', {
|
|
computeSessionFingerprint: mock(() => '{}'),
|
|
sanitizeTitle: mock((s: string) => s),
|
|
})
|
|
|
|
mockModulePreservingExports('../bridge.ts', {
|
|
forwardSessionUpdates: mock(async () => ({
|
|
stopReason: 'end_turn' as const,
|
|
})),
|
|
replayHistoryMessages: mock(async () => {}),
|
|
toolInfoFromToolUse: mock(() => ({
|
|
title: 'Test',
|
|
kind: 'other',
|
|
content: [],
|
|
locations: [],
|
|
})),
|
|
})
|
|
|
|
mockModulePreservingExports('../../../utils/listSessionsImpl.ts', {
|
|
listSessionsImpl: mock(async () => []),
|
|
})
|
|
|
|
const mockGetMainLoopModel = mock(() => 'claude-sonnet-4-6')
|
|
|
|
mockModulePreservingExports('../../../utils/model/model.ts', {
|
|
getMainLoopModel: mockGetMainLoopModel,
|
|
})
|
|
|
|
mockModulePreservingExports('../../../utils/model/modelOptions.ts', {
|
|
getModelOptions: mock(() => []),
|
|
})
|
|
|
|
const mockApplySafeEnvVars = mock(() => {})
|
|
mockModulePreservingExports('../../../utils/managedEnv.ts', {
|
|
applySafeConfigEnvironmentVariables: mockApplySafeEnvVars,
|
|
})
|
|
|
|
const mockGetSettings = mock(() => ({}))
|
|
mockModulePreservingExports('../../../utils/settings/settings.ts', {
|
|
getSettings_DEPRECATED: mockGetSettings,
|
|
})
|
|
|
|
const mockDeserializeMessages = mock((msgs: unknown[]) => msgs)
|
|
mockModulePreservingExports('../../../utils/conversationRecovery.ts', {
|
|
deserializeMessages: mockDeserializeMessages,
|
|
})
|
|
|
|
const mockGetLastSessionLog = mock(async () => null)
|
|
const mockSessionIdExists = mock(() => false)
|
|
mockModulePreservingExports('../../../utils/sessionStorage.ts', {
|
|
getLastSessionLog: mockGetLastSessionLog,
|
|
sessionIdExists: mockSessionIdExists,
|
|
})
|
|
|
|
const mockGetCommands = mock(async () => [
|
|
{
|
|
name: 'commit',
|
|
description: 'Create a git commit',
|
|
type: 'prompt',
|
|
userInvocable: true,
|
|
isHidden: false,
|
|
argumentHint: '[message]',
|
|
},
|
|
{
|
|
name: 'compact',
|
|
description: 'Compact conversation',
|
|
type: 'local',
|
|
userInvocable: true,
|
|
isHidden: false,
|
|
},
|
|
{
|
|
name: 'hidden-skill',
|
|
description: 'Hidden skill',
|
|
type: 'prompt',
|
|
userInvocable: false,
|
|
isHidden: true,
|
|
},
|
|
])
|
|
|
|
mockModulePreservingExports('../../../commands.ts', {
|
|
getCommands: mockGetCommands,
|
|
})
|
|
|
|
// ── Import after mocks ────────────────────────────────────────────
|
|
|
|
const { AcpAgent } = await import('../agent.js')
|
|
const { forwardSessionUpdates } = await import('../bridge.js')
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────────
|
|
|
|
function makeConn() {
|
|
return {
|
|
sessionUpdate: mock(async () => {}),
|
|
requestPermission: mock(async () => ({
|
|
outcome: { outcome: 'cancelled' },
|
|
})),
|
|
} as any
|
|
}
|
|
|
|
function removeBypassMode(session: any) {
|
|
session.modes = {
|
|
...session.modes,
|
|
availableModes: session.modes.availableModes.filter(
|
|
(mode: any) => mode.id !== 'bypassPermissions',
|
|
),
|
|
}
|
|
session.appState.toolPermissionContext = {
|
|
...session.appState.toolPermissionContext,
|
|
isBypassPermissionsModeAvailable: false,
|
|
}
|
|
}
|
|
|
|
function restoreEnv(name: string, value: string | undefined) {
|
|
if (value === undefined) {
|
|
delete process.env[name]
|
|
} else {
|
|
process.env[name] = value
|
|
}
|
|
}
|
|
|
|
// ── Tests ─────────────────────────────────────────────────────────
|
|
|
|
describe('AcpAgent', () => {
|
|
beforeEach(() => {
|
|
delete process.env.ACP_PERMISSION_MODE
|
|
delete process.env.CLAUDE_CODE_ACP_ALLOW_BYPASS_PERMISSIONS
|
|
mockSetModel.mockClear()
|
|
mockSubmitMessage.mockReset()
|
|
mockSubmitMessage.mockImplementation(async function* (_input: string) {})
|
|
mockGetMainLoopModel.mockClear()
|
|
mockGetDefaultAppState.mockClear()
|
|
mockGetSettings.mockReset()
|
|
mockGetSettings.mockImplementation(() => ({}))
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockReset()
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockImplementation(
|
|
async () => ({ stopReason: 'end_turn' as const }),
|
|
)
|
|
})
|
|
|
|
afterEach(() => {
|
|
process.chdir(originalCwd)
|
|
})
|
|
|
|
describe('initialize', () => {
|
|
test('returns protocol version and agent info', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.initialize({} as any)
|
|
expect(res.protocolVersion).toBeDefined()
|
|
expect(res.agentInfo?.name).toBe('claude-code')
|
|
expect(typeof res.agentInfo?.version).toBe('string')
|
|
})
|
|
|
|
test('advertises image and embeddedContext capability', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.initialize({} as any)
|
|
expect(res.agentCapabilities?.promptCapabilities?.image).toBe(true)
|
|
expect(res.agentCapabilities?.promptCapabilities?.embeddedContext).toBe(
|
|
true,
|
|
)
|
|
})
|
|
|
|
test('loadSession capability is true', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.initialize({} as any)
|
|
expect(res.agentCapabilities?.loadSession).toBe(true)
|
|
})
|
|
|
|
test('session capabilities include fork, list, resume, close', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.initialize({} as any)
|
|
expect(res.agentCapabilities?.sessionCapabilities).toBeDefined()
|
|
})
|
|
})
|
|
|
|
describe('authenticate', () => {
|
|
test('returns empty object (no auth required)', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.authenticate({} as any)
|
|
expect(res).toEqual({})
|
|
})
|
|
})
|
|
|
|
describe('newSession', () => {
|
|
test('returns a sessionId string', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(typeof res.sessionId).toBe('string')
|
|
expect(res.sessionId.length).toBeGreaterThan(0)
|
|
})
|
|
|
|
test('returns modes and models', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(res.modes).toBeDefined()
|
|
expect(res.models).toBeDefined()
|
|
expect(res.configOptions).toBeDefined()
|
|
})
|
|
|
|
test('each call returns a unique sessionId', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const r1 = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const r2 = await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(r1.sessionId).not.toBe(r2.sessionId)
|
|
})
|
|
|
|
test('does not leave process cwd changed after session creation', async () => {
|
|
const cwdBeforeSession = process.cwd()
|
|
const agent = new AcpAgent(makeConn())
|
|
await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(process.cwd()).toBe(cwdBeforeSession)
|
|
})
|
|
|
|
test('calls getDefaultAppState to build session appState', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(mockGetDefaultAppState).toHaveBeenCalled()
|
|
})
|
|
|
|
test('calls getMainLoopModel to resolve current model', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(mockGetMainLoopModel).toHaveBeenCalled()
|
|
expect(res.models?.currentModelId).toBe('claude-sonnet-4-6')
|
|
})
|
|
|
|
test('calls queryEngine.setModel with resolved model', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(mockSetModel).toHaveBeenCalledWith('claude-sonnet-4-6')
|
|
})
|
|
|
|
test('respects model alias resolution via getMainLoopModel', async () => {
|
|
mockGetMainLoopModel.mockReturnValueOnce('glm-5.1')
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(res.models?.currentModelId).toBe('glm-5.1')
|
|
expect(mockSetModel).toHaveBeenCalledWith('glm-5.1')
|
|
})
|
|
|
|
test('stores clientCapabilities from initialize', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await agent.initialize({
|
|
clientCapabilities: { _meta: { terminal_output: true } },
|
|
} as any)
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
expect(res.sessionId).toBeDefined()
|
|
})
|
|
|
|
test('uses settings permissions.defaultMode when _meta does not provide a mode', async () => {
|
|
mockGetSettings.mockImplementationOnce(() => ({
|
|
permissions: { defaultMode: 'acceptEdits' },
|
|
}))
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
expect(res.modes?.currentModeId).toBe('acceptEdits')
|
|
})
|
|
|
|
test('uses _meta.permissionMode before settings permissions.defaultMode', async () => {
|
|
mockGetSettings.mockImplementationOnce(() => ({
|
|
permissions: { defaultMode: 'acceptEdits' },
|
|
}))
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({
|
|
cwd: '/tmp',
|
|
_meta: { permissionMode: 'plan' },
|
|
} as any)
|
|
|
|
expect(res.modes?.currentModeId).toBe('plan')
|
|
})
|
|
|
|
test('rejects _meta.permissionMode bypass without a local ACP bypass gate', async () => {
|
|
mockGetSettings.mockImplementationOnce(() => ({
|
|
permissions: { defaultMode: 'acceptEdits' },
|
|
}))
|
|
const consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {})
|
|
const agent = new AcpAgent(makeConn())
|
|
try {
|
|
await expect(
|
|
agent.newSession({
|
|
cwd: '/tmp',
|
|
_meta: { permissionMode: 'bypassPermissions' },
|
|
} as any),
|
|
).rejects.toThrow('Mode not available: bypassPermissions')
|
|
|
|
expect(consoleErrorSpy).not.toHaveBeenCalled()
|
|
} finally {
|
|
consoleErrorSpy.mockRestore()
|
|
}
|
|
})
|
|
|
|
test('honors _meta.permissionMode bypass with a local ACP bypass gate', async () => {
|
|
process.env.CLAUDE_CODE_ACP_ALLOW_BYPASS_PERMISSIONS = '1'
|
|
const agent = new AcpAgent(makeConn())
|
|
const res = await agent.newSession({
|
|
cwd: '/tmp',
|
|
_meta: { permissionMode: 'bypassPermissions' },
|
|
} as any)
|
|
|
|
expect(res.modes?.currentModeId).toBe('bypassPermissions')
|
|
expect(res.modes?.availableModes.map((mode: any) => mode.id)).toContain(
|
|
'bypassPermissions',
|
|
)
|
|
})
|
|
|
|
test('falls back to default when settings permissions.defaultMode is invalid', async () => {
|
|
mockGetSettings.mockImplementationOnce(() => ({
|
|
permissions: { defaultMode: 'invalid-mode' },
|
|
}))
|
|
const consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {})
|
|
const agent = new AcpAgent(makeConn())
|
|
try {
|
|
const res = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
expect(res.modes?.currentModeId).toBe('default')
|
|
expect(consoleErrorSpy).toHaveBeenCalled()
|
|
} finally {
|
|
consoleErrorSpy.mockRestore()
|
|
}
|
|
})
|
|
|
|
test('rejects invalid _meta.permissionMode without falling back to settings', async () => {
|
|
mockGetSettings.mockImplementationOnce(() => ({
|
|
permissions: { defaultMode: 'acceptEdits' },
|
|
}))
|
|
const consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {})
|
|
const agent = new AcpAgent(makeConn())
|
|
try {
|
|
await expect(
|
|
agent.newSession({
|
|
cwd: '/tmp',
|
|
_meta: { permissionMode: 'invalid-mode' },
|
|
} as any),
|
|
).rejects.toThrow('Invalid _meta.permissionMode: invalid-mode')
|
|
|
|
expect(consoleErrorSpy).not.toHaveBeenCalled()
|
|
} finally {
|
|
consoleErrorSpy.mockRestore()
|
|
}
|
|
})
|
|
})
|
|
|
|
describe('prompt', () => {
|
|
test('throws when session not found', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await expect(
|
|
agent.prompt({ sessionId: 'nonexistent', prompt: [] } as any),
|
|
).rejects.toThrow('nonexistent')
|
|
})
|
|
|
|
test('returns end_turn for empty prompt text', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const res = await agent.prompt({ sessionId, prompt: [] } as any)
|
|
expect(res.stopReason).toBe('end_turn')
|
|
})
|
|
|
|
test('returns end_turn for whitespace-only prompt', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: ' ' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('end_turn')
|
|
})
|
|
|
|
test('calls forwardSessionUpdates for valid prompt', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('end_turn')
|
|
})
|
|
|
|
test('cancel before prompt does not block next prompt', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await agent.cancel({ sessionId } as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('end_turn')
|
|
})
|
|
|
|
test('cancel during prompt returns cancelled', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
let resolveStream!: () => void
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveStream = () => resolve({ stopReason: 'cancelled' })
|
|
}),
|
|
)
|
|
const promptPromise = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
await agent.cancel({ sessionId } as any)
|
|
resolveStream()
|
|
const res = await promptPromise
|
|
expect(res.stopReason).toBe('cancelled')
|
|
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
const res2 = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'world' }],
|
|
} as any)
|
|
expect(res2.stopReason).toBe('end_turn')
|
|
})
|
|
|
|
test('propagates unexpected prompt errors', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(async () => {
|
|
throw new Error('unexpected')
|
|
})
|
|
|
|
await expect(
|
|
agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any),
|
|
).rejects.toThrow('unexpected')
|
|
})
|
|
|
|
test('returns usage from forwardSessionUpdates', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{
|
|
stopReason: 'end_turn',
|
|
usage: {
|
|
inputTokens: 100,
|
|
outputTokens: 50,
|
|
cachedReadTokens: 10,
|
|
cachedWriteTokens: 5,
|
|
},
|
|
},
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.usage).toBeDefined()
|
|
expect(res.usage!.inputTokens).toBe(100)
|
|
expect(res.usage!.outputTokens).toBe(50)
|
|
expect(res.usage!.totalTokens).toBe(165)
|
|
})
|
|
})
|
|
|
|
describe('cancel', () => {
|
|
test('does not throw for unknown session', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await expect(
|
|
agent.cancel({ sessionId: 'ghost' } as any),
|
|
).resolves.toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('closeSession', () => {
|
|
test('throws for unknown session', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await expect(
|
|
agent.unstable_closeSession({ sessionId: 'ghost' } as any),
|
|
).rejects.toThrow('Session not found')
|
|
})
|
|
|
|
test('removes session after close', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await agent.unstable_closeSession({ sessionId } as any)
|
|
expect(agent.sessions.has(sessionId)).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('setSessionModel', () => {
|
|
test('updates model on queryEngine', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
mockSetModel.mockClear()
|
|
await agent.unstable_setSessionModel({
|
|
sessionId,
|
|
modelId: 'glm-5.1',
|
|
} as any)
|
|
expect(mockSetModel).toHaveBeenCalledWith('glm-5.1')
|
|
})
|
|
|
|
test('passes alias modelId to queryEngine as-is for later resolution', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
mockSetModel.mockClear()
|
|
await agent.unstable_setSessionModel({
|
|
sessionId,
|
|
modelId: 'sonnet[1m]',
|
|
} as any)
|
|
expect(mockSetModel).toHaveBeenCalledWith('sonnet[1m]')
|
|
})
|
|
})
|
|
|
|
describe('entry.ts initialization contract', () => {
|
|
test('entry.ts imports applySafeConfigEnvironmentVariables from managedEnv', async () => {
|
|
const entrySource = await Bun.file(
|
|
new URL('../entry.ts', import.meta.url),
|
|
).text()
|
|
expect(entrySource).toContain('applySafeConfigEnvironmentVariables')
|
|
expect(entrySource).toContain('enableConfigs')
|
|
|
|
const enableIdx = entrySource.indexOf('enableConfigs()')
|
|
const applyIdx = entrySource.indexOf(
|
|
'applySafeConfigEnvironmentVariables()',
|
|
)
|
|
expect(enableIdx).toBeGreaterThan(-1)
|
|
expect(applyIdx).toBeGreaterThan(-1)
|
|
expect(enableIdx).toBeLessThan(applyIdx)
|
|
})
|
|
})
|
|
|
|
describe('prompt usage tracking', () => {
|
|
test('returns totalTokens as sum of all token types', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{
|
|
stopReason: 'end_turn',
|
|
usage: {
|
|
inputTokens: 100,
|
|
outputTokens: 50,
|
|
cachedReadTokens: 10,
|
|
cachedWriteTokens: 5,
|
|
},
|
|
},
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.usage).toBeDefined()
|
|
expect(res.usage!.totalTokens).toBe(165)
|
|
})
|
|
|
|
test('returns undefined usage when forwardSessionUpdates returns none', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{
|
|
stopReason: 'end_turn',
|
|
},
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.usage).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('prompt error handling', () => {
|
|
test('returns cancelled when session was cancelled during prompt', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(async () => {
|
|
const session = agent.sessions.get(sessionId)
|
|
if (session) session.cancelled = true
|
|
return { stopReason: 'end_turn' }
|
|
})
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('cancelled')
|
|
})
|
|
|
|
test('returns cancelled on cancel after error', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(async () => {
|
|
const session = agent.sessions.get(sessionId)
|
|
if (session) session.cancelled = true
|
|
throw new Error('unexpected')
|
|
})
|
|
const res = await agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'hello' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('cancelled')
|
|
})
|
|
})
|
|
|
|
describe('resumeSession', () => {
|
|
test('creates new session with the requested sessionId when not in memory', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const requestedId = 'e73e9b66-9637-4477-b512-af45357b1dcb'
|
|
const res = await agent.unstable_resumeSession({
|
|
sessionId: requestedId,
|
|
cwd: '/tmp',
|
|
mcpServers: [],
|
|
} as any)
|
|
expect(agent.sessions.has(requestedId)).toBe(true)
|
|
expect(res.modes).toBeDefined()
|
|
expect(res.models).toBeDefined()
|
|
})
|
|
|
|
test('reuses existing session when sessionId matches and fingerprint unchanged', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const res1 = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const sid = res1.sessionId
|
|
const originalSession = agent.sessions.get(sid)
|
|
const res2 = await agent.unstable_resumeSession({
|
|
sessionId: sid,
|
|
cwd: '/tmp',
|
|
mcpServers: [],
|
|
} as any)
|
|
expect(agent.sessions.get(sid)).toBe(originalSession)
|
|
})
|
|
|
|
test('can prompt after resumeSession with previously unknown sessionId', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const sid = 'restored-session-id-1234'
|
|
await agent.unstable_resumeSession({
|
|
sessionId: sid,
|
|
cwd: '/tmp',
|
|
mcpServers: [],
|
|
} as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId: sid,
|
|
prompt: [{ type: 'text', text: 'hello after restore' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('end_turn')
|
|
})
|
|
})
|
|
|
|
describe('loadSession', () => {
|
|
test('creates new session with the requested sessionId', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const requestedId = 'aaaa-bbbb-cccc'
|
|
await agent.loadSession({
|
|
sessionId: requestedId,
|
|
cwd: '/tmp',
|
|
mcpServers: [],
|
|
} as any)
|
|
expect(agent.sessions.has(requestedId)).toBe(true)
|
|
})
|
|
|
|
test('can prompt after loadSession', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const sid = 'loaded-session-id'
|
|
await agent.loadSession({
|
|
sessionId: sid,
|
|
cwd: '/tmp',
|
|
mcpServers: [],
|
|
} as any)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
const res = await agent.prompt({
|
|
sessionId: sid,
|
|
prompt: [{ type: 'text', text: 'hello after load' }],
|
|
} as any)
|
|
expect(res.stopReason).toBe('end_turn')
|
|
})
|
|
})
|
|
|
|
describe('forkSession', () => {
|
|
test('returns a different sessionId from any existing', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const original = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const forked = await agent.unstable_forkSession({
|
|
cwd: '/tmp',
|
|
mcpServers: [],
|
|
} as any)
|
|
expect(forked.sessionId).not.toBe(original.sessionId)
|
|
expect(agent.sessions.has(forked.sessionId)).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('setSessionMode', () => {
|
|
test('updates current mode on the session', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await agent.setSessionMode({ sessionId, modeId: 'auto' } as any)
|
|
const session = agent.sessions.get(sessionId)
|
|
expect(session?.modes.currentModeId).toBe('auto')
|
|
})
|
|
|
|
test('throws for invalid mode', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await expect(
|
|
agent.setSessionMode({ sessionId, modeId: 'invalid_mode' } as any),
|
|
).rejects.toThrow('Invalid mode')
|
|
})
|
|
|
|
test('throws for unknown session', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
await expect(
|
|
agent.setSessionMode({ sessionId: 'ghost', modeId: 'auto' } as any),
|
|
).rejects.toThrow('Session not found')
|
|
})
|
|
|
|
test('availableModes excludes bypassPermissions without a local ACP bypass gate', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const session = agent.sessions.get(sessionId)
|
|
const modeIds = session?.modes.availableModes.map((m: any) => m.id)
|
|
expect(modeIds).not.toContain('bypassPermissions')
|
|
})
|
|
|
|
test('rejects bypassPermissions without a local ACP bypass gate', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await expect(
|
|
agent.setSessionMode({ sessionId, modeId: 'bypassPermissions' } as any),
|
|
).rejects.toThrow('Mode not available')
|
|
|
|
const session = agent.sessions.get(sessionId)
|
|
expect(session?.modes.currentModeId).toBe('default')
|
|
expect(session?.appState.toolPermissionContext.mode).toBe('default')
|
|
})
|
|
|
|
test('can switch to bypassPermissions mode with a local ACP bypass gate', async () => {
|
|
process.env.CLAUDE_CODE_ACP_ALLOW_BYPASS_PERMISSIONS = '1'
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await agent.setSessionMode({
|
|
sessionId,
|
|
modeId: 'bypassPermissions',
|
|
} as any)
|
|
const session = agent.sessions.get(sessionId)
|
|
expect(session?.modes.currentModeId).toBe('bypassPermissions')
|
|
expect(session?.appState.toolPermissionContext.mode).toBe(
|
|
'bypassPermissions',
|
|
)
|
|
})
|
|
|
|
test('rejects bypassPermissions when the session does not expose it', async () => {
|
|
process.env.CLAUDE_CODE_ACP_ALLOW_BYPASS_PERMISSIONS = '1'
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const session = agent.sessions.get(sessionId)
|
|
removeBypassMode(session)
|
|
|
|
await expect(
|
|
agent.setSessionMode({ sessionId, modeId: 'bypassPermissions' } as any),
|
|
).rejects.toThrow('Mode not available')
|
|
|
|
expect(session?.modes.currentModeId).toBe('default')
|
|
expect(session?.appState.toolPermissionContext.mode).toBe('default')
|
|
})
|
|
})
|
|
|
|
describe('setSessionConfigOption', () => {
|
|
test('throws for unknown config option', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await expect(
|
|
agent.setSessionConfigOption({
|
|
sessionId,
|
|
configId: 'nonexistent',
|
|
value: 'x',
|
|
} as any),
|
|
).rejects.toThrow('Unknown config option')
|
|
})
|
|
|
|
test('throws for non-string value', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
await expect(
|
|
agent.setSessionConfigOption({
|
|
sessionId,
|
|
configId: 'mode',
|
|
value: 42,
|
|
} as any),
|
|
).rejects.toThrow('Invalid value')
|
|
})
|
|
|
|
test('rejects unavailable mode config values', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
const session = agent.sessions.get(sessionId)
|
|
removeBypassMode(session)
|
|
|
|
await expect(
|
|
agent.setSessionConfigOption({
|
|
sessionId,
|
|
configId: 'mode',
|
|
value: 'bypassPermissions',
|
|
} as any),
|
|
).rejects.toThrow('Mode not available')
|
|
|
|
expect(session?.modes.currentModeId).toBe('default')
|
|
expect(session?.appState.toolPermissionContext.mode).toBe('default')
|
|
})
|
|
})
|
|
|
|
describe('prompt queueing', () => {
|
|
test('queued prompts execute in order after current prompt finishes', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
let resolveFirst!: () => void
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveFirst = () => resolve({ stopReason: 'end_turn' })
|
|
}),
|
|
)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
|
|
const p1 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'first' }],
|
|
} as any)
|
|
const p2 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'second' }],
|
|
} as any)
|
|
|
|
resolveFirst()
|
|
const [r1, r2] = await Promise.all([p1, p2])
|
|
expect(r1.stopReason).toBe('end_turn')
|
|
expect(r2.stopReason).toBe('end_turn')
|
|
})
|
|
|
|
test('drains 1000 queued prompts in FIFO order without sorting the pending map', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
let resolveFirst!: () => void
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveFirst = () => resolve({ stopReason: 'end_turn' })
|
|
}),
|
|
)
|
|
|
|
const first = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'first' }],
|
|
} as any)
|
|
const queued = Array.from({ length: 1000 }, (_, index) =>
|
|
agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: `queued-${index}` }],
|
|
} as any),
|
|
)
|
|
|
|
resolveFirst()
|
|
const results = await Promise.all([first, ...queued])
|
|
|
|
expect(results.every(result => result.stopReason === 'end_turn')).toBe(true)
|
|
expect(mockSubmitMessage.mock.calls.map(call => call[0])).toEqual([
|
|
'first',
|
|
...Array.from({ length: 1000 }, (_, index) => `queued-${index}`),
|
|
])
|
|
})
|
|
|
|
test('keeps promptRunning true while handing off to the next queued prompt', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
let resolveFirst!: () => void
|
|
let resolveSecond!: () => void
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveFirst = () => resolve({ stopReason: 'end_turn' })
|
|
}),
|
|
)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveSecond = () => resolve({ stopReason: 'end_turn' })
|
|
}),
|
|
)
|
|
|
|
const p1 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'first' }],
|
|
} as any)
|
|
const p2 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'second' }],
|
|
} as any)
|
|
|
|
const p3 = p1.then(() =>
|
|
agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'third' }],
|
|
} as any),
|
|
)
|
|
|
|
resolveFirst()
|
|
await p1
|
|
const session = agent.sessions.get(sessionId)
|
|
expect(session?.promptRunning).toBe(true)
|
|
expect(mockSubmitMessage.mock.calls.map(call => call[0])).toEqual([
|
|
'first',
|
|
'second',
|
|
])
|
|
|
|
resolveSecond()
|
|
await Promise.all([p2, p3])
|
|
expect(mockSubmitMessage.mock.calls.map(call => call[0])).toEqual([
|
|
'first',
|
|
'second',
|
|
'third',
|
|
])
|
|
})
|
|
|
|
test('queued prompts return cancelled when session is cancelled', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
let resolveFirst!: () => void
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveFirst = () => resolve({ stopReason: 'end_turn' })
|
|
}),
|
|
)
|
|
|
|
const p1 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'first' }],
|
|
} as any)
|
|
const p2 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'second' }],
|
|
} as any)
|
|
|
|
await agent.cancel({ sessionId } as any)
|
|
resolveFirst()
|
|
const [r1, r2] = await Promise.all([p1, p2])
|
|
expect(r1.stopReason).toBe('cancelled')
|
|
expect(r2.stopReason).toBe('cancelled')
|
|
})
|
|
|
|
test('queued prompt does not clear active prompt cancellation', async () => {
|
|
const agent = new AcpAgent(makeConn())
|
|
const { sessionId } = await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
let resolveFirst!: () => void
|
|
;(
|
|
forwardSessionUpdates as ReturnType<typeof mock>
|
|
).mockImplementationOnce(
|
|
() =>
|
|
new Promise<{ stopReason: string }>(resolve => {
|
|
resolveFirst = () => resolve({ stopReason: 'end_turn' })
|
|
}),
|
|
)
|
|
;(forwardSessionUpdates as ReturnType<typeof mock>).mockResolvedValueOnce(
|
|
{ stopReason: 'end_turn' },
|
|
)
|
|
|
|
const p1 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'first' }],
|
|
} as any)
|
|
|
|
await agent.cancel({ sessionId } as any)
|
|
|
|
const p2 = agent.prompt({
|
|
sessionId,
|
|
prompt: [{ type: 'text', text: 'second' }],
|
|
} as any)
|
|
|
|
resolveFirst()
|
|
|
|
const [r1, r2] = await Promise.all([p1, p2])
|
|
expect(r1.stopReason).toBe('cancelled')
|
|
expect(r2.stopReason).toBe('end_turn')
|
|
expect(mockSubmitMessage.mock.calls.map(call => call[0])).toEqual([
|
|
'first',
|
|
'second',
|
|
])
|
|
})
|
|
})
|
|
|
|
describe('commands', () => {
|
|
test('sends filtered prompt-type commands to client', async () => {
|
|
const conn = makeConn()
|
|
const agent = new AcpAgent(conn)
|
|
await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
await new Promise(r => setTimeout(r, 10))
|
|
|
|
const calls = (conn.sessionUpdate as ReturnType<typeof mock>).mock.calls
|
|
const cmdUpdate = calls.find((c: any[]) => {
|
|
const update = c[0]?.update
|
|
return update?.sessionUpdate === 'available_commands_update'
|
|
})
|
|
expect(cmdUpdate).toBeDefined()
|
|
|
|
const cmds = (cmdUpdate as any[])[0].update.availableCommands
|
|
const names = cmds.map((c: any) => c.name)
|
|
expect(names).toContain('commit')
|
|
expect(names).not.toContain('compact')
|
|
expect(names).not.toContain('hidden-skill')
|
|
})
|
|
|
|
test('maps argumentHint to input.hint', async () => {
|
|
const conn = makeConn()
|
|
const agent = new AcpAgent(conn)
|
|
await agent.newSession({ cwd: '/tmp' } as any)
|
|
|
|
await new Promise(r => setTimeout(r, 10))
|
|
|
|
const calls = (conn.sessionUpdate as ReturnType<typeof mock>).mock.calls
|
|
const cmdUpdate = calls.find((c: any[]) => {
|
|
const update = c[0]?.update
|
|
return update?.sessionUpdate === 'available_commands_update'
|
|
})
|
|
const commit = (cmdUpdate as any[])[0].update.availableCommands.find(
|
|
(c: any) => c.name === 'commit',
|
|
)
|
|
expect(commit.input).toEqual({ hint: '[message]' })
|
|
})
|
|
})
|
|
})
|