fix: reclaim idle remote runtimes and retire replaced agents
Remote tasks could leave idle Runtime processes behind, and replaced Agent installations lacked a drain-and-exit lifecycle. Keep the current Agent resident, let displaced Agents finish existing work and reconnect for its results, then retire them without restarting obsolete installations. Reclaim Runtime processes when their last active task finishes, preserve pending questions and shared active tasks, and restore conversation history when the next turn starts. Remove the Remote Projects technical preview label from settings, errors, tests, and current documentation; the feature remains disabled by default. Validation recorded during implementation: 213 lifecycle tests and 28 focused UI/IPC tests passed, as did SettingsPanel and lint. Linux x64 real-Host checks used 8 provider requests. Broader tests and final typecheck encountered unrelated concurrent changes; details and coverage limits are documented. Release note: 远程任务结束后自动释放空闲运行进程,下一轮对话恢复历史;更新后的旧 Agent 等待已有任务完成再退出,当前 Agent 保持常驻。远程项目移除“技术预览”标识,仍默认关闭。
This commit is contained in:
@@ -252,6 +252,36 @@ describe('Agent CLI fixed command contract', () => {
|
||||
expect(bootstrap).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it.each(['stop', 'retire'] as const)('can %s a verified displaced installation without promoting it', async action => {
|
||||
const root = privateTemporaryDirectory()
|
||||
const installationId = verifyAgentInstallationId('install-old')
|
||||
const paths = {
|
||||
executablePath: resolve(root, 'agent', 'goodbuddy-agent'),
|
||||
stateDirectory: resolve(root, 'state', installationId),
|
||||
socketPath: resolve(root, 'run', 'old.sock')
|
||||
}
|
||||
const installationRegistry = new InstallationRegistry({ storagePath: resolve(root, 'registry.json') })
|
||||
const current = verifiedInstallation(paths, verifyAgentInstallationId('install-current'))
|
||||
installationRegistry.stageCandidate(current)
|
||||
installationRegistry.promoteCandidate('install-current')
|
||||
const verified = verifiedInstallation(paths, installationId)
|
||||
const verifyInstallation = vi.fn(async () => verified)
|
||||
const terminate = vi.fn(async () => ({ state: 'absent' as const }))
|
||||
const io = cliIo()
|
||||
const result = await runAgentCli([action, '--installation-id', installationId], {
|
||||
installationPaths: () => paths,
|
||||
installationRegistry,
|
||||
releaseKeyRegistry: { formatVersion: 1, keys: [], revocations: [] },
|
||||
verifyInstallation,
|
||||
createLifecycle: (() => ({ [action]: terminate })) as unknown as AgentCliDependencies['createLifecycle'],
|
||||
io
|
||||
})
|
||||
expect(result, io.error.read()?.toString()).toBe(0)
|
||||
expect(verifyInstallation).toHaveBeenCalledOnce()
|
||||
expect(terminate).toHaveBeenCalledOnce()
|
||||
expect(installationRegistry.snapshot().current?.installationId).toBe('install-current')
|
||||
})
|
||||
|
||||
it('exports only bounded diagnostics for a fixed installation ID as JSONL', async () => {
|
||||
const root = privateTemporaryDirectory()
|
||||
const stateDirectory = resolve(root, 'state', 'install-1')
|
||||
|
||||
+28
-5
@@ -375,6 +375,15 @@ async function runDaemon(
|
||||
protocol: verified.manifest.protocol,
|
||||
stateDirectory: paths.stateDirectory,
|
||||
socketPath: paths.socketPath,
|
||||
isSuperseded: () => {
|
||||
const registry = dependencies.installationRegistry ?? new InstallationRegistry({
|
||||
storagePath: resolve(dirname(dirname(dirname(paths.executablePath))), 'registry.json')
|
||||
})
|
||||
const snapshot = registry.snapshot()
|
||||
return snapshot.current !== undefined &&
|
||||
snapshot.current.installationId !== installationId &&
|
||||
snapshot.candidate?.installationId !== installationId
|
||||
},
|
||||
peerIdentityProvider:
|
||||
dependencies.peerIdentityProvider ??
|
||||
await createLinuxPeerIdentityProvider(),
|
||||
@@ -413,7 +422,10 @@ async function runDaemon(
|
||||
'registered',
|
||||
verified
|
||||
).recordCurrentDaemonReady(daemon.status().daemonBootId)
|
||||
await (dependencies.waitForShutdown?.() ?? waitForShutdownSignal())
|
||||
await Promise.race([
|
||||
dependencies.waitForShutdown?.() ?? waitForShutdownSignal(),
|
||||
daemon.retired
|
||||
])
|
||||
} finally {
|
||||
await daemon.stop()
|
||||
}
|
||||
@@ -436,7 +448,8 @@ async function runAttach(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
dependencies,
|
||||
true
|
||||
)
|
||||
prepareManagedSocketDirectory(paths)
|
||||
const stateDirectory = paths.stateDirectory
|
||||
@@ -454,6 +467,8 @@ async function runAttach(
|
||||
connectionId = welcome.connectionId
|
||||
},
|
||||
ensureEndpoint: async () => {
|
||||
// A displaced installation may still serve detached work, but must not restart.
|
||||
await loadManagedInstallation(installationId, paths, dependencies)
|
||||
await createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
@@ -686,7 +701,8 @@ async function runLifecycle(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
dependencies,
|
||||
true
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
@@ -702,7 +718,8 @@ async function runLifecycle(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
dependencies,
|
||||
true
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
@@ -820,7 +837,8 @@ async function verifyManagedInstallation(
|
||||
async function loadManagedInstallation(
|
||||
installationId: string,
|
||||
paths: ManagedInstallationPaths,
|
||||
dependencies: AgentCliDependencies
|
||||
dependencies: AgentCliDependencies,
|
||||
allowRetired = false
|
||||
): Promise<{
|
||||
verified: VerifiedInstalledAgentBundle
|
||||
registry: InstallationRegistry
|
||||
@@ -832,6 +850,11 @@ async function loadManagedInstallation(
|
||||
new InstallationRegistry({
|
||||
storagePath: resolve(agentRoot, 'registry.json')
|
||||
})
|
||||
const snapshot = registry.snapshot()
|
||||
if (allowRetired && snapshot.current?.installationId !== installationId &&
|
||||
snapshot.candidate?.installationId !== installationId) {
|
||||
return verifyManagedInstallation(installationId, paths, dependencies)
|
||||
}
|
||||
const registered = registry.assertRegisteredRole(
|
||||
installationId,
|
||||
['current', 'candidate']
|
||||
|
||||
@@ -48,6 +48,37 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('Agent daemon lifecycle', () => {
|
||||
it('keeps the current daemon resident and retires a superseded daemon only after detached work drains', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.spyOn(PrivateEndpoint.prototype, 'listen').mockResolvedValue()
|
||||
vi.spyOn(PrivateEndpoint.prototype, 'close').mockResolvedValue()
|
||||
let superseded = false
|
||||
let idle = false
|
||||
const drain = vi.fn(async () => idle)
|
||||
const daemon = daemonForTest({
|
||||
isSuperseded: () => superseded,
|
||||
runtimeProtocol: { runtimes: () => [], methods: {}, onAcpFrame: async () => {}, drain }
|
||||
})
|
||||
const retired = vi.fn()
|
||||
void daemon.retired.then(retired)
|
||||
try {
|
||||
await daemon.start()
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
expect(drain).not.toHaveBeenCalled()
|
||||
expect(retired).not.toHaveBeenCalled()
|
||||
superseded = true
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
expect(daemon.status().draining).toBe(true)
|
||||
expect(retired).not.toHaveBeenCalled()
|
||||
idle = true
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
expect(retired).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
await daemon.stop()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('returns the strict manifest-bound Linux daemon status', () => {
|
||||
const daemon = daemonForTest()
|
||||
const status = daemonStatusSchema.parse(daemon.status())
|
||||
|
||||
@@ -49,6 +49,7 @@ export type AgentDaemonOptions = {
|
||||
now?: () => number
|
||||
gitExecutable?: string
|
||||
workspaceRequestTimeoutMs?: number
|
||||
isSuperseded?: () => boolean
|
||||
runtimeProtocol?: {
|
||||
runtimes: () =>
|
||||
| DaemonCapabilities['runtimes']
|
||||
@@ -64,6 +65,7 @@ export type AgentDaemonOptions = {
|
||||
typeof AgentProtocolServer
|
||||
>[0]['authorizeBlobFrame']>
|
||||
dispose?: () => void | Promise<void>
|
||||
drain?: () => Promise<boolean>
|
||||
}
|
||||
runtimeFactory?: (context: {
|
||||
events: EventJournal
|
||||
@@ -118,6 +120,12 @@ export class AgentDaemon {
|
||||
#events?: EventJournal
|
||||
#workspaces?: WorkspaceRegistry
|
||||
#activeRuntimeProtocol?: AgentDaemonOptions['runtimeProtocol']
|
||||
readonly #isSuperseded?: () => boolean
|
||||
#draining = false
|
||||
#activeRequests = 0
|
||||
#retirementTimer?: NodeJS.Timeout
|
||||
#resolveRetirement!: () => void
|
||||
readonly retired = new Promise<void>(resolve => { this.#resolveRetirement = resolve })
|
||||
|
||||
constructor(options: AgentDaemonOptions) {
|
||||
this.#installationId = agentIdentifierSchema.parse(options.installationId)
|
||||
@@ -147,6 +155,7 @@ export class AgentDaemon {
|
||||
this.#peerIdentityProvider = options.peerIdentityProvider
|
||||
this.#gitExecutable = options.gitExecutable
|
||||
this.#workspaceRequestTimeoutMs = options.workspaceRequestTimeoutMs
|
||||
this.#isSuperseded = options.isSuperseded
|
||||
this.#runtimeProtocol = options.runtimeProtocol
|
||||
this.#runtimeFactory = options.runtimeFactory
|
||||
if (
|
||||
@@ -176,7 +185,7 @@ export class AgentDaemon {
|
||||
architecture: this.#architecture,
|
||||
supervisor: 'detached-on-demand',
|
||||
remoteUserIdentity: this.#remoteUserIdentity,
|
||||
draining: false
|
||||
draining: this.#draining
|
||||
})
|
||||
}
|
||||
|
||||
@@ -331,10 +340,17 @@ export class AgentDaemon {
|
||||
...(reason === undefined ? {} : { reason })
|
||||
})
|
||||
},
|
||||
methods: mergeProtocolMethods(
|
||||
methods: Object.fromEntries(Object.entries(mergeProtocolMethods(
|
||||
workspaceMethods,
|
||||
this.#activeRuntimeProtocol?.methods
|
||||
)
|
||||
)).map(([name, handler]) => [name, async (params, context) => {
|
||||
this.#activeRequests++
|
||||
try {
|
||||
return await handler(params, context)
|
||||
} finally {
|
||||
this.#activeRequests--
|
||||
}
|
||||
}]))
|
||||
})
|
||||
protocolBox.current = protocol
|
||||
this.#endpoint = new PrivateEndpoint({
|
||||
@@ -364,6 +380,7 @@ export class AgentDaemon {
|
||||
})
|
||||
await this.#endpoint.listen()
|
||||
this.#state = 'ready'
|
||||
if (this.#isSuperseded) this.#scheduleRetirementCheck()
|
||||
this.#diagnostics.tryRecord('daemon.ready', {
|
||||
daemonBootId: this.#bootId
|
||||
})
|
||||
@@ -378,6 +395,7 @@ export class AgentDaemon {
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.#retirementTimer) clearTimeout(this.#retirementTimer)
|
||||
if (this.#state !== 'stopped') {
|
||||
this.#diagnostics.tryRecord('daemon.stopping', {
|
||||
daemonBootId: this.#bootId
|
||||
@@ -440,6 +458,26 @@ export class AgentDaemon {
|
||||
}
|
||||
}
|
||||
|
||||
#scheduleRetirementCheck(): void {
|
||||
this.#retirementTimer = setTimeout(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
this.#draining ||= this.#isSuperseded?.() === true
|
||||
if (this.#draining &&
|
||||
(await this.#activeRuntimeProtocol?.drain?.() ?? true) &&
|
||||
this.#activeRequests === 0) {
|
||||
this.#resolveRetirement()
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
this.#reportError('Agent retirement check failed', error)
|
||||
}
|
||||
if (this.#state === 'ready') this.#scheduleRetirementCheck()
|
||||
})()
|
||||
}, 250)
|
||||
this.#retirementTimer.unref()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function mergeProtocolMethods(
|
||||
|
||||
@@ -15,6 +15,8 @@ import type { RemoteRuntimeBundleManifest } from '../shared/remote-runtime-launc
|
||||
import type { ControllerLease } from './controller-registry'
|
||||
import { AgentModelGatewayError } from './agent-model-gateway'
|
||||
import { EventJournal, EventJournalCapacityError } from './event-journal'
|
||||
import { SemanticPromptStore } from './semantic-prompt-store'
|
||||
import { AgentAcpConnection } from './agent-acp-connection'
|
||||
import type { ProtocolMethodContext } from './protocol-server'
|
||||
import type {
|
||||
ModelBridgeBrokerDispatch,
|
||||
@@ -183,6 +185,7 @@ class FakeProcess implements RuntimeAcpProcessOwner {
|
||||
maximumInputBytes: number
|
||||
}> = []
|
||||
completions = 0
|
||||
onWrite?: (payload: Uint8Array) => void
|
||||
reconciliation: RuntimeAcpProcessReconciliation
|
||||
#listener?: (
|
||||
output: RuntimeAcpProcessOutput
|
||||
@@ -222,6 +225,7 @@ class FakeProcess implements RuntimeAcpProcessOwner {
|
||||
|
||||
writeStdin(payload: Uint8Array): void {
|
||||
this.writes.push(payload.slice())
|
||||
this.onWrite?.(payload)
|
||||
}
|
||||
|
||||
stop(input: { reason: string }): void {
|
||||
@@ -288,6 +292,8 @@ function harness(input: {
|
||||
outputGate?: Promise<void>
|
||||
agentOwned?: boolean
|
||||
shareOwnedProcesses?: boolean
|
||||
semanticStore?: SemanticPromptStore
|
||||
configureProcess?: (process: FakeProcess) => void
|
||||
journal?: RuntimeAcpJournal
|
||||
modelGateway?: {
|
||||
dispatch: ReturnType<typeof vi.fn>
|
||||
@@ -299,6 +305,7 @@ function harness(input: {
|
||||
let now = input.now ?? 1_000
|
||||
const journal = new MemoryAcpJournal()
|
||||
const process = new FakeProcess()
|
||||
input.configureProcess?.(process)
|
||||
const outputFrames: string[] = []
|
||||
const launches: Array<{
|
||||
workMode: 'ask' | 'execute'
|
||||
@@ -349,9 +356,12 @@ function harness(input: {
|
||||
workMode: launch.workMode,
|
||||
scratch: launch.scratch
|
||||
})
|
||||
return input.uniqueProcesses && launches.length > 1
|
||||
? new FakeProcess(String(launches.length))
|
||||
: process
|
||||
if (input.uniqueProcesses && launches.length > 1) {
|
||||
const next = new FakeProcess(String(launches.length))
|
||||
input.configureProcess?.(next)
|
||||
return next
|
||||
}
|
||||
return process
|
||||
}),
|
||||
now: () => now,
|
||||
diagnostics,
|
||||
@@ -372,7 +382,7 @@ function harness(input: {
|
||||
},
|
||||
...(semanticPrompts
|
||||
? {
|
||||
semanticPrompts: semanticPrompts as never,
|
||||
semanticPrompts: (input.semanticStore ?? semanticPrompts) as never,
|
||||
modelGateway:
|
||||
(input.modelGateway ?? {
|
||||
dispatch: vi.fn(),
|
||||
@@ -526,6 +536,94 @@ describe('RuntimeAcpBackend', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it.each([false, true])('reclaims completed owned processes, preserves detached peers and loads native history (shared=%s)', async shared => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'goodbuddy-idle-runtime-'))
|
||||
const transcript = new SemanticPromptStore(join(root, 'prompts.sqlite'))
|
||||
const pending = new Map<string, () => Promise<void>>()
|
||||
const processes: FakeProcess[] = []
|
||||
const loaded: string[] = []
|
||||
const setRoute = vi.spyOn(AgentAcpConnection.prototype, 'setModelRoute').mockResolvedValue()
|
||||
let sessionSequence = 0
|
||||
const fixture = harness({
|
||||
agentOwned: true, shareOwnedProcesses: shared, uniqueProcesses: true, semanticStore: transcript,
|
||||
configureProcess: process => {
|
||||
processes.push(process)
|
||||
process.onWrite = payload => {
|
||||
const request = JSON.parse(Buffer.from(payload).toString())
|
||||
if (request.id === undefined) return
|
||||
const reply = (result: unknown) => process.emit('stdout', `${JSON.stringify({ jsonrpc: '2.0', id: request.id, result })}\n`)
|
||||
if (request.method === 'session/prompt') {
|
||||
pending.set(request.params.sessionId, () => reply({ stopReason: 'end_turn' }))
|
||||
return
|
||||
}
|
||||
let result: unknown = {}
|
||||
if (request.method === 'initialize') result = { protocolVersion: 1, agentCapabilities: { loadSession: true } }
|
||||
if (request.method === 'session/new') result = { sessionId: `native-${++sessionSequence}` }
|
||||
if (request.method === 'session/load') loaded.push(request.params.sessionId)
|
||||
if (request.method === 'session/set_config_option') result = {
|
||||
configOptions: [{ id: 'model', name: 'Model', type: 'select', currentValue: request.params.value, options: [] }]
|
||||
}
|
||||
void reply(result)
|
||||
}
|
||||
}
|
||||
})
|
||||
const disconnect = new AbortController()
|
||||
fixture.context.signal = disconnect.signal
|
||||
const start = async (index: number, operationId: string, sessionId?: string) => {
|
||||
const bindingId = `owned-${index}`
|
||||
const channel = await invoke(fixture, 'runtime/openAcpChannel', { ...fixture.openRequest, bindingId }) as { channelEpoch: string }
|
||||
await invoke(fixture, 'runtime/preparePrompt', fixture.preparation({ bindingId, channelEpoch: channel.channelEpoch,
|
||||
operationId, requestId: operationId, promptSequence: sessionId ? 1 : 0 }))
|
||||
return await invoke(fixture, 'runtime/startPrompt', { bindingId, operationId, requestId: operationId,
|
||||
...(sessionId ? { acpSessionId: sessionId } : {}), prompt: [{ type: 'text', text: 'Continue' }] }) as { sessionId: string }
|
||||
}
|
||||
try {
|
||||
const first = await start(1, 'operation-1')
|
||||
const second = await start(2, 'operation-2')
|
||||
expect(processes).toHaveLength(shared ? 1 : 2)
|
||||
await pending.get(first.sessionId)!()
|
||||
await vi.waitFor(() => expect(transcript.attach('owned-1', 'operation-1', fixture.context.controller.controllerId).state).toBe('completed'))
|
||||
expect(processes[0]!.stops).toHaveLength(shared ? 0 : 1)
|
||||
expect(processes.at(-1)!.stops).toHaveLength(0)
|
||||
await pending.get(second.sessionId)!()
|
||||
await vi.waitFor(() => expect(transcript.attach('owned-2', 'operation-2', fixture.context.controller.controllerId).state).toBe('completed'))
|
||||
expect(processes.every(process => process.stops.length === 1)).toBe(true)
|
||||
const resumed = await start(1, 'operation-3', first.sessionId)
|
||||
expect(loaded).toEqual([first.sessionId])
|
||||
expect(resumed.sessionId).toBe(first.sessionId)
|
||||
await processes.at(-1)!.emit('stdout', `${JSON.stringify({
|
||||
jsonrpc: '2.0', method: 'session/update', params: {
|
||||
sessionId: resumed.sessionId,
|
||||
update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: '' },
|
||||
_meta: { goodbuddyQuestion: {
|
||||
endpoint: `http://127.0.0.1:12345/${'a'.repeat(43)}`,
|
||||
question: { id: 'question-1', sessionID: resumed.sessionId,
|
||||
questions: [{ header: 'Continue', question: 'Proceed?', options: [] }] }
|
||||
} }
|
||||
}
|
||||
}
|
||||
})}\n`)
|
||||
await vi.waitFor(() => expect(transcript.page({
|
||||
bindingId: 'owned-1', operationId: 'operation-3',
|
||||
controllerId: fixture.context.controller.controllerId, afterSequence: '0', limit: 10
|
||||
}).events.some(event => JSON.stringify(event.payload).includes('question-1'))).toBe(true))
|
||||
disconnect.abort()
|
||||
await expect(fixture.backend.drain()).resolves.toBe(false)
|
||||
expect(processes.at(-1)!.stops).toHaveLength(0)
|
||||
await pending.get(resumed.sessionId)!()
|
||||
await vi.waitFor(() => expect(transcript.attach('owned-1', 'operation-3', fixture.context.controller.controllerId).state).toBe('completed'))
|
||||
await expect(fixture.backend.drain()).resolves.toBe(true)
|
||||
fixture.context.signal = new AbortController().signal
|
||||
await expect(start(1, 'operation-4', first.sessionId)).rejects.toThrow('draining')
|
||||
expect(transcript.attach('owned-1', 'operation-1', fixture.context.controller.controllerId).sessionId).toBe(first.sessionId)
|
||||
} finally {
|
||||
await fixture.backend.dispose()
|
||||
setRoute.mockRestore()
|
||||
transcript.close()
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('shares Agent-owned workspaces and modes, retaining peers and reclaiming only an unused process', async () => {
|
||||
const fixture = harness({ agentOwned: true, shareOwnedProcesses: true })
|
||||
const channels: Array<{ bindingId: string; channelId: string; channelEpoch: string }> = []
|
||||
|
||||
@@ -86,7 +86,7 @@ const DEFAULT_MAXIMUM_PENDING_OUTPUT_BYTES_GLOBAL =
|
||||
const DEFAULT_MAXIMUM_OPERATIONS_PER_BINDING = 1_000
|
||||
const DEFAULT_DISPOSE_TIMEOUT_MS = 10_000
|
||||
const OWNED_PROMPT_CANCEL_GRACE_MS = 1_000
|
||||
const SHARED_PROCESS_IDLE_MS = 60_000
|
||||
const SHARED_PROCESS_IDLE_MS = 0
|
||||
const OWNED_PROMPT_START_TIMEOUT_MS = 2 * 60_000
|
||||
const ACP_JOURNAL_RETRY_INITIAL_MILLISECONDS = 25
|
||||
const ACP_JOURNAL_RETRY_MAXIMUM_MILLISECONDS = 1_000
|
||||
@@ -309,6 +309,7 @@ type PreparedOperation = {
|
||||
modelProfile?: AgentPromptModelProfile
|
||||
promptSequence: number
|
||||
ownedPromptStarted?: boolean
|
||||
terminalAcknowledged?: boolean
|
||||
}
|
||||
|
||||
type BindingState = {
|
||||
@@ -374,6 +375,7 @@ export class RuntimeAcpBackend {
|
||||
#pendingOutputBytesGlobal = 0
|
||||
#controlTail: Promise<void> = Promise.resolve()
|
||||
#disposed = false
|
||||
#draining = false
|
||||
#disposePromise?: Promise<void>
|
||||
|
||||
constructor(options: RuntimeAcpBackendOptions) {
|
||||
@@ -636,6 +638,18 @@ export class RuntimeAcpBackend {
|
||||
frame.header.generation === binding.controllerGeneration
|
||||
)
|
||||
|
||||
async drain(): Promise<boolean> {
|
||||
this.#draining = true
|
||||
return this.#enqueueControl(() =>
|
||||
![...this.#bindings.values()].some(binding =>
|
||||
binding.activeOperationId !== undefined ||
|
||||
(binding.transportState !== 'detached' && [...binding.operations.values()].some(operation =>
|
||||
operation.ownedPromptStarted && !operation.terminalAcknowledged
|
||||
))
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
dispose(timeoutMs = DEFAULT_DISPOSE_TIMEOUT_MS): Promise<void> {
|
||||
if (this.#disposePromise !== undefined) {
|
||||
return this.#disposePromise
|
||||
@@ -1039,6 +1053,9 @@ export class RuntimeAcpBackend {
|
||||
existing.acceptance
|
||||
)
|
||||
}
|
||||
if (this.#draining) {
|
||||
throw new RuntimeAcpBackendError('Agent installation is draining after update', 'closed')
|
||||
}
|
||||
if (binding.activeOperationId !== undefined) {
|
||||
throw new RuntimeAcpBackendError(
|
||||
'Another prompt operation is still active',
|
||||
@@ -1055,6 +1072,7 @@ export class RuntimeAcpBackend {
|
||||
)
|
||||
}
|
||||
if (
|
||||
binding.process !== undefined &&
|
||||
binding.workMode !== undefined &&
|
||||
binding.workMode !== preparation.workMode &&
|
||||
binding.sharedProcess === undefined
|
||||
@@ -1617,10 +1635,19 @@ export class RuntimeAcpBackend {
|
||||
'process'
|
||||
)
|
||||
}
|
||||
return this.#options.semanticPrompts.acknowledge({
|
||||
const result = this.#options.semanticPrompts.acknowledge({
|
||||
...request,
|
||||
controllerId: context.controller.controllerId
|
||||
})
|
||||
const operation = this.#bindings.get(request.bindingId)?.operations.get(request.operationId)
|
||||
if (operation?.ownedPromptStarted) {
|
||||
const terminal = this.#options.semanticPrompts.attach(
|
||||
request.bindingId, request.operationId, context.controller.controllerId
|
||||
)
|
||||
operation.terminalAcknowledged = terminal.state !== 'starting' && terminal.state !== 'running' &&
|
||||
BigInt(result.acknowledgedSequence) >= BigInt(terminal.latestSemanticSequence)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async #terminalizeOwnedPrompt(
|
||||
@@ -1683,6 +1710,7 @@ export class RuntimeAcpBackend {
|
||||
clearTimeout(binding.ownedPromptStartTimer)
|
||||
binding.ownedPromptStartTimer = undefined
|
||||
}
|
||||
await this.#releaseIdleProcess(binding)
|
||||
}
|
||||
|
||||
async #startModelBridge(
|
||||
@@ -2195,6 +2223,25 @@ export class RuntimeAcpBackend {
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
await this.#releaseIdleProcess(binding)
|
||||
}
|
||||
|
||||
async #releaseIdleProcess(binding: BindingState): Promise<void> {
|
||||
if (binding.activeOperationId !== undefined || !binding.process) return
|
||||
const group = binding.sharedProcess
|
||||
if (group) {
|
||||
if ([...group.bindings].some(peer => peer.activeOperationId !== undefined)) return
|
||||
await this.#stopSharedProcess(group, 'binding-closed')
|
||||
} else {
|
||||
await binding.process.stop({
|
||||
reason: 'binding-closed', deadlineAt: new Date(this.#now() + 10_000).toISOString()
|
||||
})
|
||||
const result = await binding.process.reconcile()
|
||||
if (!sameProcessIdentity(result.identity, binding.process.identity) || result.processTree !== 'empty') {
|
||||
throw new RuntimeAcpBackendError('Idle Runtime process stop did not reconcile', 'process')
|
||||
}
|
||||
await this.#handleProcessExit(binding)
|
||||
}
|
||||
}
|
||||
|
||||
async #stopAndReconcile(
|
||||
@@ -2295,6 +2342,15 @@ export class RuntimeAcpBackend {
|
||||
if (binding.process === undefined) {
|
||||
return
|
||||
}
|
||||
if (binding.activeOperationId === undefined) {
|
||||
for (const operation of binding.operations.values()) {
|
||||
operation.processTree = 'empty'
|
||||
if (operation.completion) operation.completion.processTree = 'empty'
|
||||
}
|
||||
this.#finishProcess(binding)
|
||||
binding.state = 'open'
|
||||
return
|
||||
}
|
||||
this.#appendAbnormalOwnedPromptTerminal(binding, {
|
||||
status: this.#abnormalOwnedPromptState(binding),
|
||||
name: 'RuntimeExited',
|
||||
@@ -2466,11 +2522,13 @@ export class RuntimeAcpBackend {
|
||||
}
|
||||
|
||||
#scheduleSharedIdle(group: SharedProcess): void {
|
||||
if (group.bindings.size || group.exited || this.#disposed || group.idleTimer) return
|
||||
if ([...group.bindings].some(binding => binding.activeOperationId !== undefined) || group.exited || this.#disposed || group.idleTimer) return
|
||||
group.idleTimer = setTimeout(() => {
|
||||
group.idleTimer = undefined
|
||||
void this.#enqueueControl(async () => {
|
||||
if (!group.bindings.size) await this.#stopSharedProcess(group, 'binding-closed')
|
||||
if (![...group.bindings].some(binding => binding.activeOperationId !== undefined)) {
|
||||
await this.#stopSharedProcess(group, 'binding-closed')
|
||||
}
|
||||
}).catch(() => undefined)
|
||||
}, this.#options.sharedProcessIdleMs ?? SHARED_PROCESS_IDLE_MS)
|
||||
group.idleTimer.unref?.()
|
||||
|
||||
@@ -53,6 +53,7 @@ export type ProductionRuntimeProtocol = {
|
||||
onBlobFrame?: RuntimeAcpBackend['onBlobFrame']
|
||||
authorizeBlobFrame?: RuntimeAcpBackend['authorizeBlobFrame']
|
||||
dispose: () => Promise<void>
|
||||
drain: () => Promise<boolean>
|
||||
}
|
||||
|
||||
export type ProductionRuntimeCompositionOptions = {
|
||||
@@ -348,6 +349,7 @@ export async function createProductionRuntimeProtocol(
|
||||
}
|
||||
},
|
||||
methods: backend.methods,
|
||||
drain: () => backend.drain(),
|
||||
onAcpFrame: backend.onAcpFrame,
|
||||
...(options.blobSink === undefined ||
|
||||
options.agentExecutablePath === undefined
|
||||
|
||||
@@ -2869,12 +2869,18 @@ describe('AcpRemoteRuntime Agent-owned prompts', () => {
|
||||
expect(start).toHaveProperty('acpSessionId', original.acpSessionId)
|
||||
expect(resumed.promptSequence).toBe(1)
|
||||
}
|
||||
await collect(replacement.run({ ...request, requestId: 'third' }, new AbortController().signal))
|
||||
expect(await store.getByConversation(request.conversationId)).toMatchObject({
|
||||
bindingId: resumed.bindingId, state: 'ready', promptSequence: resumed.promptSequence + 1
|
||||
})
|
||||
await collect(replacement.run({ ...request, requestId: 'third', history }, new AbortController().signal))
|
||||
if (runtimeId === 'continue') {
|
||||
expect(await store.getByConversation(request.conversationId)).toMatchObject({ state: 'ready', promptSequence: 0 })
|
||||
expect(next.startOwnedPrompt.mock.calls[1]![0]).not.toHaveProperty('acpSessionId')
|
||||
expect(JSON.stringify(next.startOwnedPrompt.mock.calls[1]![0])).toContain('previous answer')
|
||||
} else {
|
||||
expect(await store.getByConversation(request.conversationId)).toMatchObject({
|
||||
bindingId: resumed.bindingId, state: 'ready', promptSequence: resumed.promptSequence + 1
|
||||
})
|
||||
expect(next.startOwnedPrompt.mock.calls[1]![0]).toHaveProperty('acpSessionId', resumed.acpSessionId)
|
||||
}
|
||||
expect(next.startOwnedPrompt).toHaveBeenCalledTimes(2)
|
||||
expect(next.startOwnedPrompt.mock.calls[1]![0]).toHaveProperty('acpSessionId', resumed.acpSessionId)
|
||||
expect(next.attachOwnedPrompt).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
await replacement?.dispose()
|
||||
|
||||
@@ -1746,6 +1746,13 @@ export class AcpRemoteRuntime implements AgentRuntime {
|
||||
signal: AbortSignal
|
||||
): Promise<SessionRecord> {
|
||||
let current = this.sessions.get(conversationId)
|
||||
if (current?.binding.state === 'ready' && this.options.runtimeId === 'continue' &&
|
||||
this.options.modelProfile !== undefined) {
|
||||
// Continue keeps native history in process memory; seed the next process
|
||||
// from the persisted conversation through the existing cold-open path.
|
||||
await this.releaseConversation(conversationId, signal)
|
||||
current = undefined
|
||||
}
|
||||
if (
|
||||
current?.binding.activePromptOperationId &&
|
||||
this.options.modelProfile !== undefined &&
|
||||
|
||||
@@ -2201,7 +2201,7 @@ describe('registerIpcHandlers SSH hosts', () => {
|
||||
).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('blocks disabled and unavailable preview access before remote services', async () => {
|
||||
it('blocks disabled and unavailable remote-project access before remote services', async () => {
|
||||
const hostId = '00000000-0000-4000-8000-000000000105'
|
||||
const candidateId = '00000000-0000-4000-8000-000000000106'
|
||||
const projectId = '00000000-0000-4000-8000-000000000107'
|
||||
@@ -2372,7 +2372,7 @@ describe('registerIpcHandlers SSH hosts', () => {
|
||||
for (const [channel, input] of disabledRequests) {
|
||||
await expect(
|
||||
electronMocks.handlers.get(channel)?.(event, input)
|
||||
).rejects.toThrow('远程项目(技术预览)未启用')
|
||||
).rejects.toThrow('远程项目未启用')
|
||||
}
|
||||
|
||||
await expect(
|
||||
@@ -2385,25 +2385,25 @@ describe('registerIpcHandlers SSH hosts', () => {
|
||||
defaultWorkMode: 'ask'
|
||||
}
|
||||
})
|
||||
).rejects.toThrow('远程项目(技术预览)未启用')
|
||||
).rejects.toThrow('远程项目未启用')
|
||||
await expect(
|
||||
electronMocks.handlers.get(ipcChannels.projectsSetArchived)?.(
|
||||
event,
|
||||
{ projectId, archived: true }
|
||||
)
|
||||
).rejects.toThrow('远程项目(技术预览)未启用')
|
||||
).rejects.toThrow('远程项目未启用')
|
||||
await expect(
|
||||
electronMocks.handlers.get(ipcChannels.projectsDelete)?.(event, {
|
||||
projectId,
|
||||
confirmation: remoteProject.name
|
||||
})
|
||||
).rejects.toThrow('远程项目(技术预览)未启用')
|
||||
).rejects.toThrow('远程项目未启用')
|
||||
await expect(
|
||||
electronMocks.handlers.get(ipcChannels.workspaceFileRead)?.(
|
||||
event,
|
||||
{ projectId, path: 'README.md' }
|
||||
)
|
||||
).rejects.toThrow('远程项目(技术预览)未启用')
|
||||
).rejects.toThrow('远程项目未启用')
|
||||
|
||||
expect(sshHostService.getSnapshot).not.toHaveBeenCalled()
|
||||
expect(sshHostService.remove).not.toHaveBeenCalled()
|
||||
@@ -2457,7 +2457,7 @@ describe('registerIpcHandlers SSH hosts', () => {
|
||||
)
|
||||
await expect(
|
||||
electronMocks.handlers.get(ipcChannels.sshHostsGet)?.(event)
|
||||
).rejects.toThrow('远程项目(技术预览)未启用')
|
||||
).rejects.toThrow('远程项目未启用')
|
||||
expect(sshHostService.getSnapshot).not.toHaveBeenCalled()
|
||||
|
||||
await dispose()
|
||||
|
||||
+1
-1
@@ -1461,7 +1461,7 @@ export function registerIpcHandlers(
|
||||
} catch {
|
||||
// Keep the feature closed when its settings cannot be read.
|
||||
}
|
||||
throw new Error('远程项目(技术预览)未启用')
|
||||
throw new Error('远程项目未启用')
|
||||
}
|
||||
const registerHandler = (
|
||||
channel: Parameters<typeof ipcMain.handle>[0],
|
||||
|
||||
@@ -697,7 +697,6 @@ function assertConnectionMatches(
|
||||
connection.identity.binaryDigest !== agent.binaryDigest ||
|
||||
connection.identity.protocolMajor !== agent.protocol.major ||
|
||||
connection.status.state !== 'ready' ||
|
||||
connection.status.draining ||
|
||||
connection.status.installationId !== agent.installationId ||
|
||||
connection.status.binaryDigest !== agent.binaryDigest ||
|
||||
connection.status.agentVersion !== agent.agentVersion ||
|
||||
|
||||
@@ -286,7 +286,7 @@ describe('ProtocolRemoteWorkspaceTransport', () => {
|
||||
installationMismatch.close()
|
||||
|
||||
const statusMismatch = createHarness({
|
||||
connectionStatus: { draining: true }
|
||||
connectionStatus: { state: 'offline' }
|
||||
})
|
||||
await expect(
|
||||
statusMismatch.transport.acquireLease(binding)
|
||||
|
||||
@@ -356,7 +356,6 @@ function assertConnectionStatus(
|
||||
const installation = resolution.installation
|
||||
if (
|
||||
status.state !== 'ready' ||
|
||||
status.draining ||
|
||||
status.installationId !== installation.installationId ||
|
||||
status.binaryDigest !== installation.binaryDigest ||
|
||||
status.agentVersion !== installation.agentVersion ||
|
||||
|
||||
@@ -645,7 +645,6 @@ export class RemoteAgentConnectionManager {
|
||||
const expected = entry.installation
|
||||
if (
|
||||
status.state !== 'ready' ||
|
||||
status.draining ||
|
||||
status.installationId !== expected.installationId ||
|
||||
status.binaryDigest !== expected.binaryDigest ||
|
||||
status.daemonBootId !== transport.welcome.daemonBootId
|
||||
|
||||
@@ -8586,11 +8586,11 @@ describe("App", () => {
|
||||
fireEvent.click(await screen.findByRole("tab", { name: "平台功能" }));
|
||||
fireEvent.click(
|
||||
await screen.findByRole("tab", {
|
||||
name: "远程项目(技术预览)",
|
||||
name: "远程项目",
|
||||
}),
|
||||
);
|
||||
const remoteProjectsSwitch = await screen.findByRole("switch", {
|
||||
name: "远程项目(技术预览)",
|
||||
name: "远程项目",
|
||||
});
|
||||
expect(remoteProjectsSwitch).toBeChecked();
|
||||
fireEvent.click(remoteProjectsSwitch);
|
||||
|
||||
@@ -1563,7 +1563,7 @@ describe('SettingsPanel runtime files', () => {
|
||||
})
|
||||
|
||||
expect(
|
||||
screen.getByRole('tab', { name: '远程项目(技术预览)' })
|
||||
screen.getByRole('tab', { name: '远程项目' })
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -2060,10 +2060,10 @@ describe('SettingsPanel runtime files', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '平台功能' }))
|
||||
fireEvent.click(
|
||||
screen.getByRole('tab', { name: '远程项目(技术预览)' })
|
||||
screen.getByRole('tab', { name: '远程项目' })
|
||||
)
|
||||
const remoteProjectsSwitch = await screen.findByRole('switch', {
|
||||
name: '远程项目(技术预览)'
|
||||
name: '远程项目'
|
||||
})
|
||||
expect(remoteProjectsSwitch).not.toBeChecked()
|
||||
expect(
|
||||
@@ -2178,7 +2178,7 @@ describe('SettingsPanel runtime files', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '平台功能' }))
|
||||
fireEvent.click(
|
||||
screen.getByRole('tab', { name: '远程项目(技术预览)' })
|
||||
screen.getByRole('tab', { name: '远程项目' })
|
||||
)
|
||||
expect(
|
||||
await screen.findByText(
|
||||
@@ -2239,7 +2239,7 @@ describe('SettingsPanel runtime files', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '平台功能' }))
|
||||
fireEvent.click(
|
||||
screen.getByRole('tab', { name: '远程项目(技术预览)' })
|
||||
screen.getByRole('tab', { name: '远程项目' })
|
||||
)
|
||||
|
||||
expect(
|
||||
@@ -2332,11 +2332,11 @@ describe('SettingsPanel runtime files', () => {
|
||||
screen.queryByRole('tab', { name: '主机与远程执行' })
|
||||
).not.toBeInTheDocument()
|
||||
fireEvent.click(
|
||||
screen.getByRole('tab', { name: '远程项目(技术预览)' })
|
||||
screen.getByRole('tab', { name: '远程项目' })
|
||||
)
|
||||
expect(
|
||||
await screen.findByRole('switch', {
|
||||
name: '远程项目(技术预览)'
|
||||
name: '远程项目'
|
||||
})
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -567,7 +567,7 @@ export const settingsSections = {
|
||||
enabled: 'Render HTML in conversations'
|
||||
},
|
||||
remoteProjects: {
|
||||
title: 'Remote Projects (Technical Preview)',
|
||||
title: 'Remote Projects',
|
||||
description:
|
||||
'Enables SSH Host management and GoodBuddy-managed remote projects.',
|
||||
enabled: 'Enable Remote Projects',
|
||||
|
||||
@@ -538,7 +538,7 @@ export const settingsSections = {
|
||||
enabled: '在会话中渲染 HTML'
|
||||
},
|
||||
remoteProjects: {
|
||||
title: '远程项目(技术预览)',
|
||||
title: '远程项目',
|
||||
description: '启用 SSH Host 管理和由 GoodBuddy 托管的远程项目。',
|
||||
enabled: '启用远程项目',
|
||||
agentInventory: {
|
||||
|
||||
Reference in New Issue
Block a user