fix: make managed SSH sessions fast and resilient
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s

Managed SSH project selection repeatedly activated the remote Host and could
leave idle ACP bindings rejected as stale-controller after a controller
generation change. Host environment updates also coupled project state to
component installation evidence and presented a crowded control surface.

Project selection is now local-only, one Host connection serves compatible
project and conversation callers, idle bindings are safely replaced only
after proven controller takeover, and active prompts keep exact resume/replay.
Remote environment setup now uses explicit signed compound package
preparation with bounded transfer, rollback, recovery, and clearer settings.

Managed Hosts must be updated to separately distributed Agent 0.11.6 before
the daemon-side controller recovery fix takes effect. Desktop packages do not
embed the Agent or remote Runtime, and existing project data is preserved.

Release note: 托管 SSH 项目切换不再重复连接,同一 Host 可顺畅承载多个项目和对话;同时修复重连后的 stale-controller,并优化远程环境安装、更新与状态布局。
This commit is contained in:
mesalogo
2026-08-29 10:58:19 +08:00
parent eb947213c8
commit 459cc21e3d
117 changed files with 19876 additions and 9664 deletions
+52 -4
View File
@@ -26,7 +26,10 @@ import {
type ManagedInstallationPaths
} from './cli'
import { InstallationRegistry } from './installation-registry'
import type { VerifiedInstalledAgentBundle } from './installed-bundle-verifier'
import {
RegisteredAgentBundleError,
type VerifiedInstalledAgentBundle
} from './installed-bundle-verifier'
import { RuntimeBundleRegistry } from './runtime-bundle-registry'
import type { VerifiedRuntimeBundle } from './runtime-bundle-verifier'
import type { RemoteRuntimeLock } from '../shared/remote-runtime-launch-contracts'
@@ -90,7 +93,7 @@ describe('Agent CLI fixed command contract', () => {
expect(runModelBridgeHelper).toHaveBeenCalledOnce()
})
it('passes verified manifest version and protocol into the daemon', async () => {
it('starts the daemon from Host-managed registry evidence without full verification', async () => {
const root = privateTemporaryDirectory()
const paths: ManagedInstallationPaths = {
executablePath: resolve(root, 'install-1', 'goodbuddy-agent'),
@@ -115,6 +118,8 @@ describe('Agent CLI fixed command contract', () => {
status: () => ({ daemonBootId: 'daemon-boot-1' })
}))
const recordCurrentDaemonReady = vi.fn(async () => undefined)
const verifyInstallation = vi.fn(async () => verified)
const loadRegisteredInstallation = vi.fn(async () => verified)
const io = cliIo()
const result = await runAgentCli(
@@ -123,7 +128,8 @@ describe('Agent CLI fixed command contract', () => {
installationPaths: () => paths,
releaseKeyRegistry,
installationRegistry: registry,
verifyInstallation: async () => verified,
verifyInstallation,
loadRegisteredInstallation,
peerIdentityProvider: {
async getPeerIdentity() {
return { uid: 1 }
@@ -156,6 +162,8 @@ describe('Agent CLI fixed command contract', () => {
expect(recordCurrentDaemonReady).toHaveBeenCalledWith(
'daemon-boot-1'
)
expect(loadRegisteredInstallation).toHaveBeenCalledOnce()
expect(verifyInstallation).not.toHaveBeenCalled()
})
it('dispatches generated doctor and lifecycle argv through the real parser', async () => {
@@ -274,6 +282,8 @@ describe('Agent CLI fixed command contract', () => {
storagePath: resolve(root, 'registry.json')
})
installationRegistry.stageCandidate(verified)
const verifyInstallation = vi.fn(async () => verified)
const loadRegisteredInstallation = vi.fn(async () => verified)
const io = cliIo()
const attachResult = await runAgentCli(
@@ -283,7 +293,8 @@ describe('Agent CLI fixed command contract', () => {
installationPaths: () => paths,
releaseKeyRegistry,
installationRegistry,
verifyInstallation: async () => verified,
verifyInstallation,
loadRegisteredInstallation,
io
}
)
@@ -297,6 +308,43 @@ describe('Agent CLI fixed command contract', () => {
secret: Buffer.alloc(32, 7)
})
)
expect(loadRegisteredInstallation).toHaveBeenCalledOnce()
expect(verifyInstallation).not.toHaveBeenCalled()
})
it('emits a fixed repair diagnostic when registered attach metadata is invalid', async () => {
const installationId = verifyAgentInstallationId('install-1')
const root = privateTemporaryDirectory()
const paths = {
executablePath: resolve(root, 'agent', 'goodbuddy-agent'),
stateDirectory: resolve(root, 'state', 'install-1'),
socketPath: resolve(root, 'run', 'install-1.sock')
}
const verified = verifiedInstallation(paths, installationId)
const installationRegistry = new InstallationRegistry({
storagePath: resolve(root, 'registry.json')
})
installationRegistry.stageCandidate(verified)
const io = cliIo()
const result = await runAgentCli(
buildFixedAgentCliArgv(installationId, { kind: 'attach' }),
{
installationPaths: () => paths,
installationRegistry,
loadRegisteredInstallation: vi.fn(async () => {
throw new RegisteredAgentBundleError(
'private installation detail'
)
}),
io
}
)
expect(result).toBe(2)
expect(io.error.read()?.toString()).toBe(
`${AGENT_PROTOCOL_FAILURE_STDERR_PREFIX}installation-repair-required\n`
)
})
it('derives fixed Linux paths and rejects untrusted installation IDs', () => {
+73 -17
View File
@@ -28,7 +28,9 @@ import {
} from './private-endpoint'
import { createLinuxPeerIdentityProvider } from './peer-identity-provider'
import {
loadRegisteredAgentBundle,
readManagedAgentReleaseKeyRegistry,
RegisteredAgentBundleError,
verifyInstalledAgentBundle,
type VerifiedInstalledAgentBundle
} from './installed-bundle-verifier'
@@ -79,6 +81,7 @@ export type AgentCliDependencies = {
releaseKeyRegistry: AgentReleaseKeyRegistry
}
) => Promise<VerifiedInstalledAgentBundle>
loadRegisteredInstallation?: typeof loadRegisteredAgentBundle
runtimePaths?: (
installationId: string,
runtimeId: 'opencode',
@@ -124,8 +127,8 @@ export async function runAgentCli(
output: process.stdout,
error: process.stderr
}
const [command, ...rest] = argv
try {
const [command, ...rest] = argv
switch (command) {
case 'daemon':
await runDaemon(rest, dependencies)
@@ -151,9 +154,18 @@ export async function runAgentCli(
)
}
} catch (error) {
io.error.write(
`${error instanceof Error ? error.message : String(error)}\n`
)
if (
error instanceof RegisteredAgentBundleError &&
(command === 'daemon' || command === 'attach-or-bootstrap')
) {
io.error.write(
`${AGENT_PROTOCOL_FAILURE_STDERR_PREFIX}installation-repair-required\n`
)
} else {
io.error.write(
`${error instanceof Error ? error.message : String(error)}\n`
)
}
return error instanceof AgentUnsupportedError ? 3 : 2
}
}
@@ -294,12 +306,11 @@ async function runDaemon(
options['installation-id']!
)
const paths = resolveInstallationPaths(installationId, dependencies)
const { verified, registry } = await verifyManagedInstallation(
const { verified } = await loadManagedInstallation(
installationId,
paths,
dependencies
)
registry.assertVerifiedRole(verified, ['current', 'candidate'])
prepareManagedSocketDirectory(paths)
const daemonOptions: ConstructorParameters<typeof AgentDaemon>[0] = {
installationId,
@@ -340,7 +351,8 @@ async function runDaemon(
await createDetachedLifecycle(
installationId,
paths,
dependencies
dependencies,
'registered'
).recordCurrentDaemonReady(daemon.status().daemonBootId)
await (dependencies.waitForShutdown?.() ?? waitForShutdownSignal())
} finally {
@@ -362,12 +374,11 @@ async function runAttach(
installationId,
dependencies
)
const { verified, registry } = await verifyManagedInstallation(
await loadManagedInstallation(
installationId,
paths,
dependencies
)
registry.assertVerifiedRole(verified, ['current', 'candidate'])
prepareManagedSocketDirectory(paths)
const stateDirectory = paths.stateDirectory
ensurePrivateDirectory(stateDirectory, { create: false })
@@ -387,7 +398,8 @@ async function runAttach(
await createDetachedLifecycle(
installationId,
paths,
dependencies
dependencies,
'registered'
).bootstrap()
}
})
@@ -518,7 +530,8 @@ async function runLifecycle(
function createDetachedLifecycle(
installationId: string,
paths: ManagedInstallationPaths,
dependencies: AgentCliDependencies
dependencies: AgentCliDependencies,
identitySource: 'verified' | 'registered' = 'verified'
): DetachedAgentLifecycle {
const options: DetachedAgentLifecycleOptions = {
installationId,
@@ -526,12 +539,25 @@ function createDetachedLifecycle(
stateDirectory: paths.stateDirectory,
socketPath: paths.socketPath,
verifyInstallation: async () => {
const { verified, registry } = await verifyManagedInstallation(
installationId,
paths,
dependencies
)
registry.assertVerifiedRole(verified, ['current', 'candidate'])
if (identitySource === 'registered') {
return (
await loadManagedInstallation(
installationId,
paths,
dependencies
)
).verified
}
const { verified, registry } =
await verifyManagedInstallation(
installationId,
paths,
dependencies
)
registry.assertVerifiedRole(verified, [
'current',
'candidate'
])
return verified
},
probeEndpoint: async (verified) =>
@@ -597,6 +623,36 @@ async function verifyManagedInstallation(
return { verified, registry, releaseKeyRegistry }
}
async function loadManagedInstallation(
installationId: string,
paths: ManagedInstallationPaths,
dependencies: AgentCliDependencies
): Promise<{
verified: VerifiedInstalledAgentBundle
registry: InstallationRegistry
}> {
const architecture = currentAgentArchitecture()
const agentRoot = dirname(dirname(dirname(paths.executablePath)))
const registry =
dependencies.installationRegistry ??
new InstallationRegistry({
storagePath: resolve(agentRoot, 'registry.json')
})
const registered = registry.assertRegisteredRole(
installationId,
['current', 'candidate']
)
const verified = await (
dependencies.loadRegisteredInstallation ??
loadRegisteredAgentBundle
)(dirname(paths.executablePath), {
installationId,
architecture,
registered
})
return { verified, registry }
}
export function deriveManagedInstallationPaths(
installationIdInput: string,
options: {
@@ -62,6 +62,18 @@ describe('Agent installation registry', () => {
expect(() =>
registry.assertVerifiedRole(current, ['current'])
).not.toThrow()
expect(
registry.assertRegisteredRole('install-a', ['current'])
).toMatchObject({
installationId: 'install-a',
manifestSha256: 'a'.repeat(64)
})
expect(() =>
registry.assertRegisteredRole('missing', [
'current',
'candidate'
])
).toThrow('authorized registry role')
})
it('replaces a stale candidate with the requested signed identity', () => {
+22 -7
View File
@@ -105,19 +105,34 @@ export class InstallationRegistry {
roles: readonly ('current' | 'candidate')[]
): InstallationRegistryEntry {
const entry = entryFromVerified(verified)
const registered = this.assertRegisteredRole(
entry.installationId,
roles
)
if (!entryEquals(registered, entry)) {
throw new Error(
'Verified Agent installation does not match its authorized registry role'
)
}
return registered
}
assertRegisteredRole(
installationIdInput: string,
roles: readonly ('current' | 'candidate')[]
): InstallationRegistryEntry {
const installationId = installationRegistryIdSchema.parse(
installationIdInput
)
const registered = roles
.map((role) => this.#state[role])
.find(
(candidate) =>
candidate !== undefined &&
candidate.installationId === entry.installationId
candidate?.installationId === installationId
)
if (
registered === undefined ||
!entryEquals(registered, entry)
) {
if (registered === undefined) {
throw new Error(
'Verified Agent installation does not match its authorized registry role'
'Agent installation does not have an authorized registry role'
)
}
return registered
@@ -23,6 +23,7 @@ import {
import {
canonicalInstalledAgentManifestBytes,
installedAgentManifestSignaturePayload,
loadRegisteredAgentBundle,
verifyInstalledAgentBundle
} from './installed-bundle-verifier'
@@ -132,6 +133,60 @@ describe('installed Agent bundle verifier', () => {
)
})
it('loads Host-managed registry evidence without repeating signature or payload verification', async () => {
writeBundle()
const manifestBytes = readFileSync(
join(installationDirectory, 'manifest.json')
)
const manifestSha256 = createHash('sha256')
.update(manifestBytes)
.digest('hex')
writeFileSync(
join(installationDirectory, 'manifest.sig'),
'not-used-during-attach\n',
{ mode: 0o644 }
)
await expect(
loadRegisteredAgentBundle(installationDirectory, {
installationId: 'install-10',
architecture: 'x64',
registered: {
installationId: 'install-10',
agentVersion: '0.11.0',
manifestSha256,
arch: 'x64'
},
enforceFilesystemMode: process.platform !== 'win32'
})
).resolves.toMatchObject({
installationId: 'install-10',
manifestSha256,
binaryDigest: `sha256:${manifestSha256}`,
manifest: {
agentVersion: '0.11.0',
protocol: { major: 1, minor: 0 }
}
})
writeFileSync(
join(installationDirectory, 'manifest.json'),
Buffer.concat([manifestBytes, Buffer.from(' ')])
)
await expect(
loadRegisteredAgentBundle(installationDirectory, {
installationId: 'install-10',
architecture: 'x64',
registered: {
installationId: 'install-10',
agentVersion: '0.11.0',
manifestSha256,
arch: 'x64'
}
})
).rejects.toThrow('Host-managed registry')
})
})
function resetInstallation(): void {
@@ -17,6 +17,10 @@ import {
type AgentReleaseKey,
type AgentReleaseKeyRegistry
} from '../shared/agent-installation-contracts'
import {
installationRegistryEntrySchema,
type InstallationRegistryEntry
} from '../shared/remote-environment-registry-contracts'
import { assertAbsoluteManagedPath } from './managed-paths'
import {
assertElfArchitecture,
@@ -56,6 +60,22 @@ export type VerifyInstalledAgentBundleOptions = {
uid?: number
}
export type LoadRegisteredAgentBundleOptions = {
installationId: string
architecture: AgentArchitecture
registered: InstallationRegistryEntry
enforceFilesystemMode?: boolean
filesystemPlatform?: NodeJS.Platform
uid?: number
}
export class RegisteredAgentBundleError extends Error {
constructor(message: string, cause?: unknown) {
super(message, { cause })
this.name = 'RegisteredAgentBundleError'
}
}
export async function readManagedAgentReleaseKeyRegistry(
filePath: string,
options: { uid?: number; filesystemPlatform?: NodeJS.Platform } = {}
@@ -202,6 +222,126 @@ export async function verifyInstalledAgentBundle(
}
}
/**
* Reconstructs the identity previously verified and committed by Host
* management. Normal attach/bootstrap uses this bounded metadata path instead
* of rehashing the complete installation on every project switch.
*/
export async function loadRegisteredAgentBundle(
installationDirectoryInput: string,
options: LoadRegisteredAgentBundleOptions
): Promise<VerifiedInstalledAgentBundle> {
try {
return await loadRegisteredAgentBundleUnchecked(
installationDirectoryInput,
options
)
} catch (error) {
if (error instanceof RegisteredAgentBundleError) {
throw error
}
throw new RegisteredAgentBundleError(
error instanceof Error
? error.message
: 'Registered Agent installation is invalid',
error
)
}
}
async function loadRegisteredAgentBundleUnchecked(
installationDirectoryInput: string,
options: LoadRegisteredAgentBundleOptions
): Promise<VerifiedInstalledAgentBundle> {
const installationId = validateInstallationId(options.installationId)
const installationDirectory = resolve(installationDirectoryInput)
assertAbsoluteManagedPath(installationDirectory)
if (basename(installationDirectory) !== installationId) {
throw new Error(
'Agent installation ID does not match its managed directory'
)
}
const registered = installationRegistryEntrySchema.parse(
options.registered
)
if (
registered.installationId !== installationId ||
registered.arch !== options.architecture
) {
throw new Error(
'Registered Agent identity does not match the current installation'
)
}
const rootStat = await lstat(installationDirectory)
assertOwnedDirectory(
rootStat,
'Agent installation directory',
options.uid
)
if (
shouldEnforceMode(options) &&
modeString(rootStat.mode) !== '0700'
) {
throw new Error(
'Agent installation directory permissions must be 0700'
)
}
const manifestBytes = await readMetadataFile(
join(installationDirectory, MANIFEST_FILE_NAME),
'Agent manifest',
options
)
if (sha256Bytes(manifestBytes) !== registered.manifestSha256) {
throw new Error(
'Agent manifest does not match the Host-managed registry'
)
}
let untrusted: unknown
try {
untrusted = JSON.parse(manifestBytes.toString('utf8'))
} catch (error) {
throw new Error('Agent manifest JSON is invalid', { cause: error })
}
const manifest = agentBundleManifestSchema.parse(untrusted)
if (
!canonicalInstalledAgentManifestBytes(manifest).equals(
manifestBytes
) ||
manifest.agentVersion !== registered.agentVersion ||
manifest.arch !== registered.arch
) {
throw new Error(
'Agent manifest does not match the Host-managed registry'
)
}
const executablePath = join(
installationDirectory,
manifest.entrypoint.path
)
await assertRegisteredEntrypoint(executablePath, '0755', options)
await assertRegisteredEntrypoint(
join(installationDirectory, manifest.entrypoint.runtimePath),
'0755',
options
)
await assertRegisteredEntrypoint(
join(installationDirectory, manifest.entrypoint.scriptPath),
'0644',
options
)
return {
installationId,
installationDirectory,
executablePath,
manifest,
manifestSha256: registered.manifestSha256,
binaryDigest: `sha256:${registered.manifestSha256}`
}
}
export function canonicalInstalledAgentManifestBytes(
manifest: AgentBundleManifest
): Buffer {
@@ -351,6 +491,26 @@ function importPublicKey(key: AgentReleaseKey) {
return publicKey
}
async function assertRegisteredEntrypoint(
filePath: string,
expectedMode: string,
options: Pick<
LoadRegisteredAgentBundleOptions,
'uid' | 'filesystemPlatform' | 'enforceFilesystemMode'
>
): Promise<void> {
const stat = await lstat(filePath)
assertOwnedRegularFile(stat, filePath, options.uid)
if (
shouldEnforceMode(options) &&
modeString(stat.mode) !== expectedMode
) {
throw new Error(
`Agent payload mode mismatch: ${basename(filePath)}`
)
}
}
async function readMetadataFile(
filePath: string,
label: string,
+49
View File
@@ -673,6 +673,55 @@ describe('AgentProtocolServer connection bounds', () => {
harness.close()
})
it('marks method context only after exact controller takeover', async () => {
const takeoverStates: Array<boolean | undefined> = []
const harness = createHarness({
reconnect: true,
methods: {
'runtime/openAcpChannel': (_params, context) => {
takeoverStates.push(context.controllerTakeoverProven)
return null
}
}
})
const previous = harness.previousController!
harness.socket.receive(
controlFrame(harness.controller, 'before-resume', '1', 1, {
jsonrpc: '2.0',
id: 1,
method: 'runtime/openAcpChannel',
params: {}
})
)
await waitFor(() => harness.socket.writes.length === 2)
harness.socket.receive(
controlFrame(harness.controller, 'resume', '1', 1, {
jsonrpc: '2.0',
id: 2,
method: 'controller/resume',
params: {
previousGeneration: previous.generation,
previousConnectionId: previous.connectionId,
daemonBootId: daemonStatus.daemonBootId,
capabilityGeneration: previous.capabilityGeneration
}
})
)
await waitFor(() => harness.socket.writes.length === 4)
harness.socket.receive(
controlFrame(harness.controller, 'after-resume', '1', 1, {
jsonrpc: '2.0',
id: 3,
method: 'runtime/openAcpChannel',
params: {}
})
)
await waitFor(() => harness.socket.writes.length === 6)
expect(takeoverStates).toEqual([false, true])
harness.close()
})
it.each([
['previous connection', { previousConnectionId: 'connection-wrong' }],
['capability generation', { capabilityGeneration: 2 }],
+2
View File
@@ -82,6 +82,7 @@ const RUNTIME_ACP_METHODS = [
export type ProtocolMethodContext = {
controller: ControllerLease
channelId: string
controllerTakeoverProven?: boolean
signal?: AbortSignal
}
@@ -841,6 +842,7 @@ class ProtocolConnection {
const result = await handler(request.params, {
controller: this.#controller,
channelId: channel.channelId,
controllerTakeoverProven: this.#takeoverProven,
signal: this.#abortController.signal
})
if (request.method === 'runtime/resumeAcpChannel') {
+172 -11
View File
@@ -155,11 +155,7 @@ class MemoryAcpJournal implements RuntimeAcpJournal {
}
class FakeProcess implements RuntimeAcpProcessOwner {
readonly identity: RuntimeAcpProcessIdentity = {
launchId: 'launch-1',
processId: 'process-1',
supervisorIdentityDigest: digest('9')
}
readonly identity: RuntimeAcpProcessIdentity
readonly writes: Uint8Array[] = []
readonly stops: string[] = []
readonly prompts: Array<{
@@ -167,15 +163,24 @@ class FakeProcess implements RuntimeAcpProcessOwner {
maximumInputBytes: number
}> = []
completions = 0
reconciliation: RuntimeAcpProcessReconciliation = {
identity: this.identity,
state: 'running',
processTree: 'running'
}
reconciliation: RuntimeAcpProcessReconciliation
#listener?: (
output: RuntimeAcpProcessOutput
) => void | Promise<void>
constructor(identity = '1') {
this.identity = {
launchId: `launch-${identity}`,
processId: `process-${identity}`,
supervisorIdentityDigest: digest(identity)
}
this.reconciliation = {
identity: this.identity,
state: 'running',
processTree: 'running'
}
}
beginPrompt(input: {
deadlineAt: string
maximumInputBytes: number
@@ -238,6 +243,8 @@ function harness(input: {
now?: number
maximumOutputBytes?: number
bridgeCloseError?: boolean
uniqueProcesses?: boolean
outputGate?: Promise<void>
} = {}) {
const workMode = input.workMode ?? 'ask'
let now = input.now ?? 1_000
@@ -275,10 +282,13 @@ function harness(input: {
workMode: launch.workMode,
scratch: launch.scratch
})
return process
return input.uniqueProcesses && launches.length > 1
? new FakeProcess(String(launches.length))
: process
}),
now: () => now,
outputSink: vi.fn(async (frame) => {
await input.outputGate
outputFrames.push(Buffer.from(frame.payload).toString())
}),
blobSink,
@@ -644,6 +654,113 @@ describe('RuntimeAcpBackend', () => {
).rejects.toMatchObject({ code: 'stale-controller' })
})
it('reopens a detached idle binding after a proven same-controller takeover', async () => {
const fixture = harness()
await open(fixture)
await invoke(
fixture,
'runtime/preparePrompt',
fixture.preparation()
)
await invoke(fixture, 'runtime/completePrompt', {
bindingId: 'binding-1',
operationId: 'request-1',
requestId: 'request-1'
})
fixture.context.abort.abort()
await new Promise<void>((resolve) => setImmediate(resolve))
const replacement = protocolContext({
generation: 2,
connectionId: 'connection-2'
})
replacement.controllerTakeoverProven = true
await expect(
fixture.backend.methods['runtime/openAcpChannel']!(
fixture.openRequest,
replacement
)
).resolves.toMatchObject({
bindingId: 'binding-1',
channelEpoch: '1001'
})
expect(fixture.process.stops).toEqual(['binding-closed'])
expect(fixture.journal.retired).toContainEqual({
controllerId: 'controller-1',
bindingId: 'binding-1',
channelEpoch: '1000'
})
})
it('drains the detached old epoch before replacing an idle binding', async () => {
let releaseOutput!: () => void
const outputGate = new Promise<void>((resolve) => {
releaseOutput = resolve
})
const fixture = harness({ outputGate })
await open(fixture)
await invoke(
fixture,
'runtime/preparePrompt',
fixture.preparation()
)
const pendingOutput = fixture.process.emit('stdout', 'pending')
await new Promise<void>((resolve) => setImmediate(resolve))
await invoke(fixture, 'runtime/completePrompt', {
bindingId: 'binding-1',
operationId: 'request-1',
requestId: 'request-1'
})
fixture.context.abort.abort()
await new Promise<void>((resolve) => setImmediate(resolve))
const replacement = protocolContext({
generation: 2,
connectionId: 'connection-2'
})
replacement.controllerTakeoverProven = true
let replaced = false
const reopen = fixture.backend.methods[
'runtime/openAcpChannel'
]!(fixture.openRequest, replacement).then((result) => {
replaced = true
return result
})
await new Promise<void>((resolve) => setImmediate(resolve))
expect(replaced).toBe(false)
releaseOutput()
await pendingOutput
await expect(reopen).resolves.toMatchObject({
bindingId: 'binding-1',
channelEpoch: '1001'
})
expect(fixture.journal.frames).toContainEqual(
expect.objectContaining({
bindingId: 'binding-1',
channelEpoch: '1000',
sequence: '1'
})
)
})
it('does not adopt an idle binding without exact takeover proof', async () => {
const fixture = harness()
await open(fixture)
fixture.context.abort.abort()
await new Promise<void>((resolve) => setImmediate(resolve))
await expect(
fixture.backend.methods['runtime/openAcpChannel']!(
fixture.openRequest,
protocolContext({
generation: 2,
connectionId: 'connection-2'
})
)
).rejects.toMatchObject({ code: 'stale-controller' })
})
it('reopens a definitively closed stable binding with a fresh epoch and generation', async () => {
const fixture = harness()
await open(fixture)
@@ -799,6 +916,13 @@ describe('RuntimeAcpBackend', () => {
generation: 2,
connectionId: 'connection-2'
})
resumedContext.controllerTakeoverProven = true
await expect(
fixture.backend.methods['runtime/openAcpChannel']!(
fixture.openRequest,
resumedContext
)
).rejects.toMatchObject({ code: 'stale-controller' })
await expect(
fixture.backend.methods['runtime/resumeAcpChannel']!(
{
@@ -1019,6 +1143,43 @@ describe('RuntimeAcpBackend', () => {
).rejects.toMatchObject({ code: 'identity' })
expect(fixture.process.stops).toEqual(['identity-conflict'])
})
it('runs independent conversations for two workspaces on one controller', async () => {
const fixture = harness({ uniqueProcesses: true })
await open(fixture)
const secondOpen = {
...fixture.openRequest,
bindingId: 'binding-2',
workspaceIdentity: 'workspace-identity-2'
}
await invoke(
fixture,
'runtime/openAcpChannel',
secondOpen
)
await Promise.all([
invoke(
fixture,
'runtime/preparePrompt',
fixture.preparation()
),
invoke(
fixture,
'runtime/preparePrompt',
fixture.preparation({
bindingId: 'binding-2',
operationId: 'request-2',
requestId: 'request-2',
channelEpoch: '1001',
workspaceIdentity: 'workspace-identity-2'
})
)
])
expect(fixture.launches).toHaveLength(2)
expect(fixture.process.stops).toEqual([])
})
})
async function open(fixture: Harness): Promise<Record<string, unknown>> {
+24 -2
View File
@@ -621,8 +621,30 @@ export class RuntimeAcpBackend {
)
}
if (existing.state !== 'closed' || existing.process !== undefined) {
this.#assertBindingOwner(existing, context)
return acpOpenChannelResultSchema.parse(existing.openResult)
const ownedByCurrentConnection =
existing.controllerGeneration ===
context.controller.generation &&
existing.connectionId ===
context.controller.connectionId
if (ownedByCurrentConnection) {
return acpOpenChannelResultSchema.parse(existing.openResult)
}
const canReplaceDetachedIdleBinding =
context.controllerTakeoverProven === true &&
context.controller.generation >
existing.controllerGeneration &&
existing.transportState === 'detached' &&
existing.activeOperationId === undefined &&
(existing.state === 'open' ||
existing.state === 'running')
if (!canReplaceDetachedIdleBinding) {
this.#assertBindingOwner(existing, context)
}
await Promise.all([
existing.inputTail,
existing.outputTail
])
await this.#stopAndReconcile(existing, 'binding-closed')
}
this.#assertOpenCapacity(context.controller.controllerId)
const channelEpoch = this.#allocateChannelEpoch()