feat: add bounded diagnostics and improve UX feedback

Ask and Execute guidance, Runtime state, live announcements, loading states,
retry paths, settings focus, and update failures now provide consistent and
accessible feedback across the desktop experience.

Add bounded redacted Desktop and Agent diagnostic logs, a read-only Agent
diagnostics command, and an explicit opt-in for attaching a small Desktop
diagnostic summary to in-app feedback. Diagnostics stay local by default and
the existing feedback v1 service contract remains compatible.

Release note: 新增可选桌面诊断反馈与 Agent 诊断导出,并统一 Ask/Execute 状态、错误恢复和无障碍反馈;诊断默认保留在本地,仅在用户明确勾选时附加桌面摘要。
This commit is contained in:
mesalogo
2026-08-31 15:35:13 +08:00
parent b1729125e1
commit 2833a27f83
60 changed files with 4679 additions and 216 deletions
+155 -1
View File
@@ -106,7 +106,12 @@ describe('AgentRuntimeController', () => {
it('fails retired runtime requests and disposes them after exit', async () => {
const previous = new TestRuntime(true, true)
const next = new TestRuntime()
const controller = new AgentRuntimeController(previous)
const observeFailure = vi.fn()
const controller = new AgentRuntimeController(
previous,
undefined,
observeFailure
)
const authorize = vi.fn(async () => 'once' as const)
const approvedStream = controller.run(
{
@@ -137,6 +142,7 @@ describe('AgentRuntimeController', () => {
await expect(controller.getStatus()).resolves.toMatchObject({
label: 'Test'
})
expect(observeFailure).not.toHaveBeenCalled()
})
it('keeps a retiring runtime alive until its status probe finishes', async () => {
@@ -449,6 +455,132 @@ describe('AgentRuntimeController', () => {
expect(authorize).not.toHaveBeenCalled()
})
it('does not report cancellation, AbortError, or tool denial', async () => {
const observeFailure = vi.fn()
const canceledRuntime = new TestRuntime()
canceledRuntime.run = async function* (
_request,
signal
): AsyncGenerator<AgentEvent, void, void> {
yield* []
signal.throwIfAborted()
await new Promise<void>((_resolve, reject) => {
signal.addEventListener(
'abort',
() => reject(signal.reason),
{ once: true }
)
})
}
const canceledController = new AgentRuntimeController(
canceledRuntime,
undefined,
observeFailure
)
const abortController = new AbortController()
const canceled = canceledController.run(
{
requestId: '1c608898-ecb7-4081-8174-2b6a52f53b18',
conversationId: 'conversation-canceled',
prompt: 'test',
workMode: 'ask'
},
abortController.signal
)
const pending = canceled.next()
abortController.abort()
await expect(pending).rejects.toMatchObject({
name: 'AbortError'
})
await canceledController.dispose()
const abortErrorRuntime = new TestRuntime()
abortErrorRuntime.run = async function* (): AsyncGenerator<
AgentEvent,
void,
void
> {
yield* []
throw new DOMException('aborted', 'AbortError')
}
const abortErrorController = new AgentRuntimeController(
abortErrorRuntime,
undefined,
observeFailure
)
const aborted = abortErrorController.run(
{
requestId: '1c608898-ecb7-4081-8174-2b6a52f53b19',
conversationId: 'conversation-abort-error',
prompt: 'test',
workMode: 'ask'
},
new AbortController().signal
)
await expect(aborted.next()).rejects.toMatchObject({
name: 'AbortError'
})
await abortErrorController.dispose()
const deniedRuntime = new TestRuntime(false, false, true)
const deniedController = new AgentRuntimeController(
deniedRuntime,
undefined,
observeFailure
)
const denied = deniedController.run(
{
requestId: '1c608898-ecb7-4081-8174-2b6a52f53b20',
conversationId: 'conversation-tool-denied',
prompt: 'test',
workMode: 'execute'
},
new AbortController().signal,
async () => 'deny'
)
await expect(denied.next()).rejects.toThrow('tool denied')
await deniedController.dispose()
expect(observeFailure).not.toHaveBeenCalled()
})
it('reports genuine Runtime run failures', async () => {
const runtime = new TestRuntime()
const failure = new Error('provider failed')
runtime.run = async function* (): AsyncGenerator<
AgentEvent,
void,
void
> {
yield* []
throw failure
}
const observeFailure = vi.fn()
const controller = new AgentRuntimeController(
runtime,
undefined,
observeFailure
)
const stream = controller.run(
{
requestId: '1c608898-ecb7-4081-8174-2b6a52f53b21',
conversationId: 'conversation-run-failed',
prompt: 'test',
workMode: 'ask'
},
new AbortController().signal
)
await expect(stream.next()).rejects.toBe(failure)
expect(observeFailure).toHaveBeenCalledWith({
component: 'runtime',
stage: 'run',
code: 'runtime.run.failed',
error: failure
})
await controller.dispose()
})
it('forwards per-tool authorization without adding a whole-run gate', async () => {
const runtime = new TestRuntime(false, false, true)
const controller = new AgentRuntimeController(runtime)
@@ -490,4 +622,26 @@ describe('AgentRuntimeController', () => {
'当前 Runtime 不支持工具执行'
)
})
it('reports Runtime boundary failures without request content', async () => {
const runtime = new TestRuntime()
const failure = new Error('provider raw response: secret prompt')
runtime.getStatus = vi.fn(async () => {
throw failure
})
const observeFailure = vi.fn()
const controller = new AgentRuntimeController(
runtime,
undefined,
observeFailure
)
await expect(controller.getStatus()).rejects.toBe(failure)
expect(observeFailure).toHaveBeenCalledWith({
component: 'runtime',
stage: 'status',
code: 'runtime.operation.failed',
error: failure
})
})
})
+100 -22
View File
@@ -11,6 +11,9 @@ import type {
RuntimeConversationCompactOutcome,
RuntimeEvent
} from './runtime'
import type {
DesktopDiagnosticFailureObserver
} from '../desktop-diagnostics'
type RuntimeSlot = {
runtime: AgentRuntime
@@ -80,7 +83,9 @@ export class AgentRuntimeController implements AgentRuntime {
constructor(
runtime: AgentRuntime,
private readonly shutdownGraceMs = 2_000
private readonly shutdownGraceMs = 2_000,
private readonly observeFailure?:
DesktopDiagnosticFailureObserver
) {
this.current = {
runtime,
@@ -201,18 +206,22 @@ export class AgentRuntimeController implements AgentRuntime {
}
async getStatus(): Promise<AgentRuntimeStatus> {
return this.probeStatus((runtime) => runtime.getStatus())
return this.probeStatus(
'status',
(runtime) => runtime.getStatus()
)
}
async testConnection(): Promise<AgentRuntimeStatus> {
return this.probeStatus(
'connection-test',
(runtime) =>
runtime.testConnection?.() ?? runtime.getStatus()
)
}
async getNativeSnapshot(): Promise<RuntimeNativeSnapshot> {
return this.invoke((runtime) => {
return this.invoke('native-snapshot', (runtime) => {
if (!runtime.getNativeSnapshot) {
throw new Error('当前 Runtime 不支持原生能力清单')
}
@@ -225,18 +234,23 @@ export class AgentRuntimeController implements AgentRuntime {
signal: AbortSignal
): Promise<RuntimeConversationCompactOutcome> {
this.ownedConversationIds.add(request.conversationId)
return this.invoke((runtime) => {
if (!runtime.compactConversation) {
throw new Error('当前 Runtime 不支持手动压缩')
}
return runtime.compactConversation(request, signal)
})
return this.invoke(
'compact',
(runtime) => {
if (!runtime.compactConversation) {
throw new Error('当前 Runtime 不支持手动压缩')
}
return runtime.compactConversation(request, signal)
},
signal
)
}
private async probeStatus(
stage: string,
operation: (runtime: AgentRuntime) => Promise<AgentRuntimeStatus>
): Promise<AgentRuntimeStatus> {
const status = await this.invoke(operation)
const status = await this.invoke(stage, operation)
return {
...status,
supportsToolExecution: this.current.runtime.supportsToolExecution
@@ -244,7 +258,9 @@ export class AgentRuntimeController implements AgentRuntime {
}
private async invoke<T>(
operation: (runtime: AgentRuntime) => Promise<T>
stage: string,
operation: (runtime: AgentRuntime) => Promise<T>,
signal?: AbortSignal
): Promise<T> {
if (this.closing) {
throw new Error('Agent Runtime 正在关闭')
@@ -257,6 +273,15 @@ export class AgentRuntimeController implements AgentRuntime {
throw new Error('Runtime 已切换,请重试')
}
return status
} catch (error) {
if (
slot === this.current &&
!signal?.aborted &&
!isAbortError(error)
) {
this.reportFailure(stage, 'runtime.operation.failed', error)
}
throw error
} finally {
slot.activeRequests -= 1
if (
@@ -280,9 +305,21 @@ export class AgentRuntimeController implements AgentRuntime {
const slot = this.current
this.ownedConversationIds.add(request.conversationId)
const toolsAllowed = request.workMode === 'execute'
let toolDenied = false
const effectiveAuthorize: RuntimeAuthorizer | undefined = toolsAllowed
? authorize
: async () => 'deny'
? authorize === undefined
? undefined
: async (authorizationRequest) => {
const decision = await authorize(authorizationRequest)
if (decision === 'deny') {
toolDenied = true
}
return decision
}
: async () => {
toolDenied = true
return 'deny'
}
slot.activeRequests += 1
try {
if (toolsAllowed && !slot.runtime.supportsToolExecution) {
@@ -304,18 +341,31 @@ export class AgentRuntimeController implements AgentRuntime {
throw new Error('用户拒绝了 Agent 工具执行')
}
}
for await (const event of slot.runtime.run(
request,
signal,
effectiveAuthorize
)) {
try {
for await (const event of slot.runtime.run(
request,
signal,
effectiveAuthorize
)) {
if (slot !== this.current && !slot.drainable) {
throw new Error('Runtime 已切换,当前请求已中断')
}
toolDenied = false
yield event
}
if (slot !== this.current && !slot.drainable) {
throw new Error('Runtime 已切换,当前请求已中断')
}
yield event
}
if (slot !== this.current && !slot.drainable) {
throw new Error('Runtime 已切换,当前请求已中断')
} catch (error) {
if (
!signal.aborted &&
!toolDenied &&
!isAbortError(error) &&
(slot === this.current || slot.drainable)
) {
this.reportFailure('run', 'runtime.run.failed', error)
}
throw error
}
} finally {
slot.activeRequests -= 1
@@ -329,6 +379,23 @@ export class AgentRuntimeController implements AgentRuntime {
}
}
private reportFailure(
stage: string,
code: string,
error: unknown
): void {
try {
this.observeFailure?.({
component: 'runtime',
stage,
code,
error
})
} catch {
// Diagnostics must not alter Runtime behavior.
}
}
async releaseConversation(conversationId: string): Promise<void> {
const results = await Promise.allSettled([
this.current.runtime.releaseConversation?.(conversationId),
@@ -549,6 +616,17 @@ export class AgentRuntimeController implements AgentRuntime {
}
}
function isAbortError(error: unknown): boolean {
if (typeof error !== 'object' || error === null) {
return false
}
try {
return 'name' in error && error.name === 'AbortError'
} catch {
return false
}
}
async function waitWithin(
promise: Promise<void>,
timeoutMs: number
+34 -2
View File
@@ -13,6 +13,9 @@ import type {
} from './runtime'
import { AgentRuntimeController } from './runtime-controller'
import type { ExecutionSpaceDescriptor } from '../execution-space'
import type {
DesktopDiagnosticFailureObserver
} from '../desktop-diagnostics'
export type SelectedRuntimeResolver = {
getRuntime(
@@ -70,7 +73,9 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
private readonly maximumCachedRuntimes =
DEFAULT_MAXIMUM_CACHED_RUNTIMES,
private readonly maximumRetainedRuntimes =
DEFAULT_MAXIMUM_RETAINED_RUNTIMES
DEFAULT_MAXIMUM_RETAINED_RUNTIMES,
private readonly observeFailure?:
DesktopDiagnosticFailureObserver
) {
if (
!Number.isSafeInteger(maximumCachedRuntimes) ||
@@ -129,7 +134,11 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
await runtime.dispose()
throw new Error('Runtime 设置已更改,请重新选择')
}
const controller = new AgentRuntimeController(runtime)
const controller = new AgentRuntimeController(
runtime,
undefined,
this.observeFailure
)
entry.controller = controller
return controller
}
@@ -148,6 +157,7 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
if (this.entries.get(key) === entry) {
this.entries.delete(key)
}
this.reportFailure('create', error)
throw error
}
}
@@ -162,6 +172,9 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
this.tests.add(operation)
try {
return await operation
} catch (error) {
this.reportFailure('status', error)
throw error
} finally {
this.tests.delete(operation)
}
@@ -177,6 +190,9 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
this.tests.add(operation)
try {
return await operation
} catch (error) {
this.reportFailure('connection-test', error)
throw error
} finally {
this.tests.delete(operation)
}
@@ -196,6 +212,9 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
this.snapshots.add(operation)
try {
return await operation
} catch (error) {
this.reportFailure('native-snapshot', error)
throw error
} finally {
this.snapshots.delete(operation)
}
@@ -421,4 +440,17 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
void this.startRetiring(entry, false)
}
}
private reportFailure(stage: string, error: unknown): void {
try {
this.observeFailure?.({
component: 'runtime',
stage,
code: 'runtime.operation.failed',
error
})
} catch {
// Diagnostics must not alter Runtime behavior.
}
}
}
+228
View File
@@ -0,0 +1,228 @@
import {
mkdtemp,
readFile,
readdir,
rm,
stat,
writeFile
} from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { afterEach, describe, expect, it } from 'vitest'
import {
DesktopDiagnostics,
MAXIMUM_PENDING_DESKTOP_DIAGNOSTIC_WRITES,
normalizeDesktopDiagnosticRecord
} from './desktop-diagnostics'
const temporaryDirectories: string[] = []
async function temporaryDirectory(): Promise<string> {
const directory = await mkdtemp(
join(tmpdir(), 'goodbuddy-desktop-diagnostics-')
)
temporaryDirectories.push(directory)
return directory
}
afterEach(async () => {
await Promise.all(
temporaryDirectories.splice(0).map((directory) =>
rm(directory, { recursive: true, force: true })
)
)
})
describe('DesktopDiagnostics', () => {
it('rotates within fixed file and byte bounds', async () => {
const directory = await temporaryDirectory()
let sequence = 0
const diagnostics = new DesktopDiagnostics(directory, {
maximumFileBytes: 420,
maximumFiles: 3,
now: () => new Date(sequence++ * 1_000)
})
for (let index = 0; index < 12; index += 1) {
await diagnostics.recordFailure({
component: 'runtime',
stage: 'run',
code: 'runtime.run.failed',
error: new Error(`failure ${index}`)
})
}
await diagnostics.dispose()
const files = await readdir(directory)
expect(files).toHaveLength(3)
for (const file of files) {
expect((await stat(join(directory, file))).size).toBeLessThanOrEqual(
420
)
}
const reopened = new DesktopDiagnostics(directory, {
maximumFileBytes: 420,
maximumFiles: 3
})
const records = await reopened.readRecent()
expect(records.length).toBeGreaterThan(0)
expect(records.length).toBeLessThan(12)
expect(records.at(-1)).toMatchObject({
component: 'runtime',
stage: 'run',
code: 'runtime.run.failed',
message: 'Runtime request failed'
})
await reopened.dispose()
})
it('reads bounded recent records after restart', async () => {
const directory = await temporaryDirectory()
const first = new DesktopDiagnostics(directory, {
maximumRecords: 2
})
await first.recordFailure({
component: 'desktop',
stage: 'startup',
code: 'desktop.startup.failed',
error: new TypeError('first')
})
await first.recordFailure({
component: 'remote-agent',
stage: 'connect',
code: 'remote.connection.network',
error: new Error('second')
})
await first.recordFailure({
component: 'runtime',
stage: 'status',
code: 'runtime.operation.failed',
error: new Error('third')
})
await first.dispose()
const restarted = new DesktopDiagnostics(directory, {
maximumRecords: 2
})
await expect(restarted.readRecent(100)).resolves.toMatchObject([
{ code: 'remote.connection.network' },
{ code: 'runtime.operation.failed' }
])
const exported = await restarted.exportRecent()
expect(exported.toString('utf8').trim().split('\n')).toHaveLength(2)
await restarted.dispose()
})
it('never persists raw error content or unknown error names', async () => {
const directory = await temporaryDirectory()
const diagnostics = new DesktopDiagnostics(directory)
const secret =
'Prompt body password=hunter2 API_KEY=abc https://provider.test/path?token=raw-response'
const error = new Error(secret)
error.name = `Credential-${secret}`
await diagnostics.recordFailure({
component: 'runtime',
stage: secret,
code: secret,
error
})
const exported = await diagnostics.exportRecent()
await diagnostics.dispose()
expect(exported.toString('utf8')).not.toContain(secret)
expect(exported.toString('utf8')).not.toContain('hunter2')
expect(exported.toString('utf8')).not.toContain('provider.test')
expect(JSON.parse(exported.toString('utf8'))).toMatchObject({
errorType: 'Error',
stage: 'unknown',
code: 'diagnostic.failure',
message: 'Runtime operation failed'
})
const persisted = await readFile(
join(directory, 'desktop-diagnostics.ndjson'),
'utf8'
)
expect(persisted).not.toContain('API_KEY')
})
it('uses one safe normalizer for externally damaged records', async () => {
const directory = await temporaryDirectory()
const damaged = {
timestamp: '2026-08-25T01:02:03+00:00',
component: 'remote-agent',
stage: 'disconnect',
code: 'remote.connection.lost',
errorType: 'SensitiveProviderError',
message: 'password=hunter2'
}
expect(normalizeDesktopDiagnosticRecord(damaged)).toEqual({
timestamp: '2026-08-25T01:02:03.000Z',
component: 'remote-agent',
stage: 'disconnect',
code: 'remote.connection.lost',
errorType: 'Error',
message: 'Remote connection was lost'
})
await writeFile(
join(directory, 'desktop-diagnostics.ndjson'),
`${JSON.stringify(damaged)}\n`,
'utf8'
)
const diagnostics = new DesktopDiagnostics(directory)
const records = await diagnostics.readRecent()
await diagnostics.dispose()
expect(records).toEqual([
{
timestamp: '2026-08-25T01:02:03.000Z',
component: 'remote-agent',
stage: 'disconnect',
code: 'remote.connection.lost',
errorType: 'Error',
message: 'Remote connection was lost'
}
])
expect(JSON.stringify(records)).not.toContain('hunter2')
})
it('normalizes errors immediately and bounds pending writes', async () => {
const directory = await temporaryDirectory()
const diagnostics = new DesktopDiagnostics(directory)
let errorNameReads = 0
const writes = Array.from(
{
length:
MAXIMUM_PENDING_DESKTOP_DIAGNOSTIC_WRITES + 8
},
() => {
const error = new Error('raw provider failure')
Object.defineProperty(error, 'name', {
get: () => {
errorNameReads += 1
return 'TypeError'
}
})
return diagnostics.recordFailure({
component: 'runtime',
stage: 'run',
code: 'runtime.run.failed',
error
})
}
)
expect(errorNameReads).toBe(writes.length)
expect(diagnostics.pendingWriteCount).toBe(
MAXIMUM_PENDING_DESKTOP_DIAGNOSTIC_WRITES
)
await Promise.all(writes)
expect(diagnostics.pendingWriteCount).toBe(0)
await expect(diagnostics.readRecent()).resolves.toHaveLength(
MAXIMUM_PENDING_DESKTOP_DIAGNOSTIC_WRITES
)
await diagnostics.dispose()
})
})
+442
View File
@@ -0,0 +1,442 @@
import {
mkdir,
open,
readFile,
rename,
unlink,
type FileHandle
} from 'node:fs/promises'
import { join } from 'node:path'
const DEFAULT_MAXIMUM_FILE_BYTES = 256 * 1024
const DEFAULT_MAXIMUM_FILES = 4
const DEFAULT_MAXIMUM_RECORDS = 1_000
export const MAXIMUM_PENDING_DESKTOP_DIAGNOSTIC_WRITES = 32
const DIAGNOSTIC_FILE_NAME = 'desktop-diagnostics.ndjson'
const allowedStages = new Set([
'startup',
'create',
'status',
'connection-test',
'native-snapshot',
'compact',
'run',
'connect',
'disconnect'
])
const allowedCodes = new Set([
'desktop.startup.failed',
'runtime.operation.failed',
'runtime.run.failed',
'remote.connection.network',
'remote.connection.host-invalidated',
'remote.connection.host-identity',
'remote.connection.authentication',
'remote.connection.installation',
'remote.connection.protocol',
'remote.connection.daemon-status',
'remote.connection.platform',
'remote.connection.capability',
'remote.connection.shutdown',
'remote.connection.lost'
])
const safeErrorTypes = new Set([
'AbortError',
'AggregateError',
'Error',
'EvalError',
'RangeError',
'ReferenceError',
'RemoteAgentConnectionError',
'StartupPrerequisiteError',
'SyntaxError',
'TimeoutError',
'TypeError',
'URIError'
])
export type DesktopDiagnosticComponent =
| 'desktop'
| 'runtime'
| 'remote-agent'
export type DesktopDiagnosticFailure = Readonly<{
component: DesktopDiagnosticComponent
stage: string
code: string
error: unknown
}>
export type DesktopDiagnosticFailureObserver = (
failure: DesktopDiagnosticFailure
) => void
export type DesktopDiagnosticRecord = Readonly<{
timestamp: string
component: DesktopDiagnosticComponent
stage: string
code: string
errorType: string
message: string
}>
export type DesktopDiagnosticsOptions = Readonly<{
maximumFileBytes?: number
maximumFiles?: number
maximumRecords?: number
now?: () => Date
}>
function safeErrorType(error: unknown): string {
if (!(error instanceof Error)) {
return 'NonError'
}
let name: unknown
try {
name = error.name
} catch {
return 'Error'
}
return typeof name === 'string' && safeErrorTypes.has(name)
? name
: 'Error'
}
function fixedMessage(
component: DesktopDiagnosticComponent,
stage: string
): string {
if (component === 'desktop') {
return 'Desktop startup failed'
}
if (component === 'remote-agent') {
return stage === 'disconnect'
? 'Remote connection was lost'
: 'Remote connection failed'
}
return stage === 'run'
? 'Runtime request failed'
: 'Runtime operation failed'
}
function safeComponent(component: unknown): DesktopDiagnosticComponent {
switch (component) {
case 'runtime':
case 'remote-agent':
return component
default:
return 'desktop'
}
}
function safeStage(stage: unknown): string {
return typeof stage === 'string' && allowedStages.has(stage)
? stage
: 'unknown'
}
function safeCode(code: unknown): string {
return typeof code === 'string' && allowedCodes.has(code)
? code
: 'diagnostic.failure'
}
function safeStoredErrorType(errorType: unknown): string {
return typeof errorType === 'string' &&
(errorType === 'NonError' || safeErrorTypes.has(errorType))
? errorType
: 'Error'
}
export function normalizeDesktopDiagnosticRecord(
value: unknown
): DesktopDiagnosticRecord | undefined {
if (typeof value !== 'object' || value === null) {
return undefined
}
const candidate = value as Partial<DesktopDiagnosticRecord>
if (typeof candidate.timestamp !== 'string') {
return undefined
}
const timestamp = new Date(candidate.timestamp)
if (Number.isNaN(timestamp.valueOf())) {
return undefined
}
const component = safeComponent(candidate.component)
const stage = safeStage(candidate.stage)
return Object.freeze({
timestamp: timestamp.toISOString(),
component,
stage,
code: safeCode(candidate.code),
errorType: safeStoredErrorType(candidate.errorType),
message: fixedMessage(component, stage)
})
}
function ignoreMissing(error: unknown): void {
if (
!(error instanceof Error) ||
!('code' in error) ||
error.code !== 'ENOENT'
) {
throw error
}
}
export class DesktopDiagnostics {
readonly #directoryPath: string
readonly #maximumFileBytes: number
readonly #maximumFiles: number
readonly #maximumRecords: number
readonly #now: () => Date
#handle: FileHandle | undefined
#currentBytes = 0
#initialized = false
#accepting = true
#pendingWrites = 0
#queue: Promise<void> = Promise.resolve()
constructor(
directoryPath: string,
options: DesktopDiagnosticsOptions = {}
) {
this.#directoryPath = directoryPath
this.#maximumFileBytes =
options.maximumFileBytes ?? DEFAULT_MAXIMUM_FILE_BYTES
this.#maximumFiles =
options.maximumFiles ?? DEFAULT_MAXIMUM_FILES
this.#maximumRecords =
options.maximumRecords ?? DEFAULT_MAXIMUM_RECORDS
this.#now = options.now ?? (() => new Date())
if (
!Number.isSafeInteger(this.#maximumFileBytes) ||
this.#maximumFileBytes < 256 ||
!Number.isSafeInteger(this.#maximumFiles) ||
this.#maximumFiles < 1 ||
this.#maximumFiles > 16 ||
!Number.isSafeInteger(this.#maximumRecords) ||
this.#maximumRecords < 1 ||
this.#maximumRecords > 10_000
) {
throw new RangeError('Invalid desktop diagnostic bounds')
}
}
initialize(): Promise<void> {
return this.#enqueue(async () => this.#ensureInitialized())
}
get pendingWriteCount(): number {
return this.#pendingWrites
}
recordFailure(
failure: DesktopDiagnosticFailure
): Promise<void> {
if (!this.#accepting) {
return Promise.resolve()
}
let record: DesktopDiagnosticRecord
try {
const normalized = normalizeDesktopDiagnosticRecord({
timestamp: this.#now().toISOString(),
component: failure.component,
stage: failure.stage,
code: failure.code,
errorType: safeErrorType(failure.error)
})
if (normalized === undefined) {
return Promise.reject(
new Error('Desktop diagnostic record is invalid')
)
}
record = normalized
} catch (error) {
return Promise.reject(error)
}
if (
this.#pendingWrites >=
MAXIMUM_PENDING_DESKTOP_DIAGNOSTIC_WRITES
) {
return Promise.resolve()
}
this.#pendingWrites += 1
return this.#enqueue(async () => {
try {
await this.#ensureInitialized()
const encoded = Buffer.from(
`${JSON.stringify(record)}\n`,
'utf8'
)
if (encoded.byteLength > this.#maximumFileBytes) {
throw new RangeError(
'Desktop diagnostic record exceeds file bound'
)
}
if (
this.#currentBytes > 0 &&
this.#currentBytes + encoded.byteLength >
this.#maximumFileBytes
) {
await this.#rotate()
}
await this.#handle!.write(encoded)
this.#currentBytes += encoded.byteLength
} finally {
this.#pendingWrites -= 1
}
})
}
readRecent(
limit = this.#maximumRecords
): Promise<readonly DesktopDiagnosticRecord[]> {
const requestedLimit = Number.isFinite(limit)
? Math.trunc(limit)
: this.#maximumRecords
const boundedLimit = Math.min(
Math.max(0, requestedLimit),
this.#maximumRecords
)
if (boundedLimit === 0) {
return Promise.resolve([])
}
return this.#enqueue(async () => {
await this.#ensureInitialized()
await this.#handle!.sync()
const records: DesktopDiagnosticRecord[] = []
for (let index = this.#maximumFiles - 1; index >= 0; index -= 1) {
const contents = await this.#readFile(index)
if (contents === undefined) {
continue
}
for (const line of contents.split('\n')) {
if (line.length === 0) {
continue
}
try {
const parsed: unknown = JSON.parse(line)
const record = normalizeDesktopDiagnosticRecord(parsed)
if (record !== undefined) {
records.push(record)
}
} catch {
// Ignore a final partial or externally damaged record.
}
}
}
return Object.freeze(records.slice(-boundedLimit))
})
}
async exportRecent(
limit = this.#maximumRecords
): Promise<Buffer> {
const records = await this.readRecent(limit)
return Buffer.from(
records.map((record) => JSON.stringify(record)).join('\n') +
(records.length > 0 ? '\n' : ''),
'utf8'
)
}
flush(): Promise<void> {
return this.#enqueue(async () => {
if (this.#handle) {
await this.#handle.sync()
}
})
}
dispose(): Promise<void> {
if (!this.#accepting) {
return this.#queue
}
this.#accepting = false
return this.#enqueue(async () => {
const handle = this.#handle
this.#handle = undefined
this.#initialized = false
if (handle) {
await handle.sync()
await handle.close()
}
})
}
#enqueue<T>(operation: () => Promise<T>): Promise<T> {
const result = this.#queue.then(operation)
this.#queue = result.then(
() => undefined,
() => undefined
)
return result
}
async #ensureInitialized(): Promise<void> {
if (this.#initialized) {
return
}
await mkdir(this.#directoryPath, { recursive: true })
const currentPath = this.#filePath(0)
this.#handle = await open(currentPath, 'a+')
this.#currentBytes = (await this.#handle.stat()).size
this.#initialized = true
if (this.#currentBytes > this.#maximumFileBytes) {
await this.#handle.close()
this.#handle = undefined
await unlink(currentPath)
this.#handle = await open(currentPath, 'a+')
this.#currentBytes = 0
}
}
async #rotate(): Promise<void> {
const handle = this.#handle
this.#handle = undefined
if (handle) {
await handle.close()
}
await unlink(this.#filePath(this.#maximumFiles - 1)).catch(
ignoreMissing
)
for (
let index = this.#maximumFiles - 2;
index >= 0;
index -= 1
) {
await rename(
this.#filePath(index),
this.#filePath(index + 1)
).catch(ignoreMissing)
}
this.#handle = await open(this.#filePath(0), 'a+')
this.#currentBytes = 0
}
async #readFile(index: number): Promise<string | undefined> {
try {
return await readFile(this.#filePath(index), 'utf8')
} catch (error) {
if (
error instanceof Error &&
'code' in error &&
error.code === 'ENOENT'
) {
return undefined
}
throw error
}
}
#filePath(index: number): string {
return join(
this.#directoryPath,
index === 0
? DIAGNOSTIC_FILE_NAME
: `${DIAGNOSTIC_FILE_NAME}.${index}`
)
}
}
+7
View File
@@ -50,6 +50,7 @@ describe('feedback IPC', () => {
category: 'bug',
title: ' Feedback title ',
description: 'A useful feedback description.',
includeDiagnostics: false,
locale: 'zh-CN',
clientRequestId:
'00000000-0000-4000-8000-000000000501'
@@ -78,6 +79,12 @@ describe('feedback IPC', () => {
endpoint: 'https://attacker.example/api/v1/feedback'
})
).toThrow()
expect(() =>
handler(event, {
...input,
diagnostics: [{ message: 'renderer supplied content' }]
})
).toThrow()
expect(submit).toHaveBeenCalledOnce()
remove()
+173 -7
View File
@@ -1,11 +1,17 @@
import { describe, expect, it, vi } from 'vitest'
import type { FeedbackSubmitInput } from '../../shared/feedback-contracts'
import {
feedbackLimits,
type FeedbackSubmitInput
} from '../../shared/feedback-contracts'
import { FeedbackIdentityStore } from './feedback-identity-store'
import {
FeedbackClientError,
StrictFeedbackHttpClient
} from './feedback-http-client'
import { FeedbackService } from './feedback-service'
import {
FeedbackService,
type FeedbackDiagnosticsProvider
} from './feedback-service'
vi.mock('electron', () => ({
nativeImage: {
@@ -17,6 +23,7 @@ const input: FeedbackSubmitInput = {
category: 'feature',
title: 'Feedback title',
description: 'A useful feedback description.',
includeDiagnostics: false,
contactEmail: 'user@example.com',
locale: 'en-US',
clientRequestId: '00000000-0000-4000-8000-000000000401'
@@ -24,7 +31,9 @@ const input: FeedbackSubmitInput = {
function service(
submit: StrictFeedbackHttpClient['submit'],
clear = vi.fn(async () => undefined)
clear = vi.fn(async () => undefined),
readRecent: FeedbackDiagnosticsProvider['readRecent'] =
vi.fn(async () => [])
) {
const identityStore = {
getInstallationId: vi.fn(
@@ -42,10 +51,12 @@ function service(
platform: 'win32',
architecture: 'x64',
identityStore: identityStore as unknown as FeedbackIdentityStore,
client: client as unknown as StrictFeedbackHttpClient
client: client as unknown as StrictFeedbackHttpClient,
diagnosticsProvider: { readRecent }
}),
identityStore,
client
client,
readRecent
}
}
@@ -64,21 +75,176 @@ describe('FeedbackService', () => {
duplicate: false
})
expect(submit).toHaveBeenCalledWith(
expect.objectContaining({
{
schemaVersion: 1,
productKey: 'goodbuddy',
category: input.category,
title: input.title,
description: input.description,
contactEmail: input.contactEmail,
installationId:
'00000000-0000-4000-8000-000000000402',
clientRequestId: input.clientRequestId,
environment: {
appVersion: '0.11.0',
platform: 'windows',
architecture: 'x64',
locale: 'en-US'
}
}),
},
undefined,
expect.any(AbortSignal)
)
expect(fixture.readRecent).not.toHaveBeenCalled()
})
it('appends bounded desktop diagnostics without changing public fields', async () => {
const submit = vi.fn<StrictFeedbackHttpClient['submit']>(
async () => ({
reference: 'GOODBUDDY-000013',
duplicate: false
})
)
const readRecent = vi.fn(async () => [
{
timestamp: '2026-08-25T01:02:03.000Z',
component: 'runtime' as const,
stage: 'run',
code: 'runtime.run.failed',
errorType: 'TimeoutError',
message: 'password=hunter2'
}
])
const fixture = service(
submit,
vi.fn(async () => undefined),
readRecent
)
await expect(
fixture.service.submit({
...input,
includeDiagnostics: true
})
).resolves.toMatchObject({ ok: true })
expect(readRecent).toHaveBeenCalledWith(
feedbackLimits.maximumDiagnosticRecords
)
const payload = submit.mock.calls[0]![0]
expect(payload).toMatchObject({
schemaVersion: 1,
productKey: 'goodbuddy',
category: input.category,
title: input.title,
contactEmail: input.contactEmail
})
expect(payload).not.toHaveProperty('includeDiagnostics')
expect(payload.description).toContain(input.description)
expect(payload.description).toContain(
'[GOODBUDDY_DESKTOP_DIAGNOSTICS_V1_BEGIN]\n'
)
expect(payload.description).toContain(
'{"timestamp":"2026-08-25T01:02:03.000Z","component":"runtime","stage":"run","code":"runtime.run.failed","errorType":"TimeoutError","message":"Runtime request failed"}'
)
expect(payload.description).not.toContain('hunter2')
expect(payload.description).toMatch(
/\n\[GOODBUDDY_DESKTOP_DIAGNOSTICS_V1_END\]$/u
)
expect(payload.description.length).toBeLessThanOrEqual(
feedbackLimits.maximumDescriptionCharacters
)
})
it('states when no recent desktop diagnostics exist', async () => {
const submit = vi.fn<StrictFeedbackHttpClient['submit']>(
async () => ({
reference: 'GOODBUDDY-000014',
duplicate: false
})
)
const fixture = service(submit)
await fixture.service.submit({
...input,
includeDiagnostics: true
})
expect(submit.mock.calls[0]![0].description).toContain(
'{"status":"no-recent-diagnostics"}'
)
})
it('keeps a bounded summary on complete diagnostic lines', async () => {
const submit = vi.fn<StrictFeedbackHttpClient['submit']>(
async () => ({
reference: 'GOODBUDDY-000017',
duplicate: false
})
)
const records = Array.from({ length: 20 }, (_, index) => ({
timestamp: new Date(
Date.UTC(2026, 7, 25, 1, index)
).toISOString(),
component: 'runtime' as const,
stage: 'run',
code: 'runtime.run.failed',
errorType: 'TimeoutError',
message: 'Runtime request failed'
}))
const fixture = service(
submit,
vi.fn(async () => undefined),
vi.fn(async () => records)
)
await fixture.service.submit({
...input,
includeDiagnostics: true
})
const summary = submit.mock.calls[0]![0].description.split(
'\n\n'
)[1]!
expect(summary.length).toBeLessThanOrEqual(
feedbackLimits.maximumDiagnosticsSummaryCharacters
)
const lines = summary.split('\n')
expect(lines[0]).toBe(
'[GOODBUDDY_DESKTOP_DIAGNOSTICS_V1_BEGIN]'
)
expect(lines.at(-1)).toBe(
'[GOODBUDDY_DESKTOP_DIAGNOSTICS_V1_END]'
)
const included = lines
.slice(1, -1)
.map((line) => JSON.parse(line) as { timestamp: string })
expect(included.length).toBeGreaterThan(0)
expect(included.length).toBeLessThan(records.length)
expect(included.at(-1)?.timestamp).toBe(
records.at(-1)?.timestamp
)
})
it('does not send when selected diagnostics cannot be read', async () => {
const submit = vi.fn<StrictFeedbackHttpClient['submit']>(
async () => ({
reference: 'GOODBUDDY-000015',
duplicate: false
})
)
const readRecent = vi.fn(async () => {
throw new Error('read failed')
})
const fixture = service(
submit,
vi.fn(async () => undefined),
readRecent
)
await expect(
fixture.service.submit({
...input,
includeDiagnostics: true
})
).resolves.toEqual({
ok: false,
error: 'diagnostics-unavailable'
})
expect(submit).not.toHaveBeenCalled()
})
it('coalesces concurrent submissions with the same client request ID', async () => {
+75 -1
View File
@@ -1,10 +1,15 @@
import {
feedbackLimits,
feedbackPublicPayloadSchema,
feedbackSubmitInputSchema,
type FeedbackPublicPayload,
type FeedbackSubmitInput,
type FeedbackSubmitResult
} from '../../shared/feedback-contracts'
import {
normalizeDesktopDiagnosticRecord,
type DesktopDiagnosticRecord
} from '../desktop-diagnostics'
import { FeedbackIdentityStore } from './feedback-identity-store'
import {
FeedbackClientError,
@@ -15,6 +20,57 @@ import {
normalizeFeedbackScreenshot
} from './feedback-screenshot'
const diagnosticsBeginMarker =
'[GOODBUDDY_DESKTOP_DIAGNOSTICS_V1_BEGIN]'
const diagnosticsEndMarker =
'[GOODBUDDY_DESKTOP_DIAGNOSTICS_V1_END]'
export type FeedbackDiagnosticsProvider = {
readRecent: (
limit: number
) => Promise<readonly DesktopDiagnosticRecord[]>
}
function formatDiagnosticsSummary(
records: readonly DesktopDiagnosticRecord[]
): string {
const lines = records
.map(normalizeDesktopDiagnosticRecord)
.filter(
(record): record is DesktopDiagnosticRecord =>
record !== undefined
)
.map((record) => JSON.stringify(record))
if (lines.length === 0) {
return [
diagnosticsBeginMarker,
JSON.stringify({ status: 'no-recent-diagnostics' }),
diagnosticsEndMarker
].join('\n')
}
const included: string[] = []
for (let index = lines.length - 1; index >= 0; index -= 1) {
const candidate = [lines[index]!, ...included]
const summary = [
diagnosticsBeginMarker,
...candidate,
diagnosticsEndMarker
].join('\n')
if (
summary.length >
feedbackLimits.maximumDiagnosticsSummaryCharacters
) {
break
}
included.unshift(lines[index]!)
}
return [
diagnosticsBeginMarker,
...included,
diagnosticsEndMarker
].join('\n')
}
function mapPlatform(
platform: NodeJS.Platform
): FeedbackPublicPayload['environment']['platform'] {
@@ -56,6 +112,7 @@ export class FeedbackService {
architecture: string
identityStore: FeedbackIdentityStore
client: StrictFeedbackHttpClient
diagnosticsProvider: FeedbackDiagnosticsProvider
}
) {}
@@ -143,6 +200,23 @@ export class FeedbackService {
signal: AbortSignal
): Promise<FeedbackSubmitResult> {
try {
let description = input.description
if (input.includeDiagnostics) {
try {
const records =
await this.options.diagnosticsProvider.readRecent(
feedbackLimits.maximumDiagnosticRecords
)
description = `${description}\n\n${formatDiagnosticsSummary(
records
)}`
} catch {
return {
ok: false,
error: 'diagnostics-unavailable'
}
}
}
const installationId =
await this.options.identityStore.getInstallationId()
const payload = feedbackPublicPayloadSchema.parse({
@@ -150,7 +224,7 @@ export class FeedbackService {
productKey: 'goodbuddy',
category: input.category,
title: input.title,
description: input.description,
description,
...(input.contactEmail
? { contactEmail: input.contactEmail }
: {}),
+33 -5
View File
@@ -152,6 +152,10 @@ import type {
RuntimeSettings,
RuntimeSettingsInput
} from '../shared/contracts'
import {
DesktopDiagnostics,
type DesktopDiagnosticFailureObserver
} from './desktop-diagnostics'
const legacyDefaultShortcut =
defaultGlobalShortcutSettings.accelerator
@@ -164,6 +168,14 @@ const portableUserDataPath = resolvePortableUserDataPath({
if (portableUserDataPath) {
app.setPath('userData', portableUserDataPath)
}
const desktopDiagnostics = new DesktopDiagnostics(
join(app.getPath('userData'), 'diagnostics')
)
const observeDesktopFailure: DesktopDiagnosticFailureObserver = (
failure
) => {
void desktopDiagnostics.recordFailure(failure).catch(() => undefined)
}
const installedWindowsBuild = isInstalledWindowsBuild({
packaged: app.isPackaged,
platform: process.platform,
@@ -677,7 +689,8 @@ if (hasSingleInstanceLock) {
appPath: app.getAppPath(),
resourcesPath: process.resourcesPath,
packaged: app.isPackaged,
controlPlanePackageInstaller
controlPlanePackageInstaller,
observeFailure: observeDesktopFailure
})
remoteAgentServices = startupRemoteAgentServices
const startupManagedRemoteExecutionServices =
@@ -776,7 +789,8 @@ if (hasSingleInstanceLock) {
client: new StrictFeedbackHttpClient({
appVersion: app.getVersion(),
dispatcher: createStrictFeedbackDispatcher()
})
}),
diagnosticsProvider: desktopDiagnostics
})
feedbackService = startupFeedbackService
const startupEmbeddingModelManager = new EmbeddingModelManager({
@@ -1078,9 +1092,16 @@ if (hasSingleInstanceLock) {
initialResolvedSettings
)
)
runtime = new AgentRuntimeController(configuredRuntime)
runtime = new AgentRuntimeController(
configuredRuntime,
undefined,
observeDesktopFailure
)
selectedRuntimeManager = new SelectedRuntimeManager(
createSelectedRuntime
createSelectedRuntime,
undefined,
undefined,
observeDesktopFailure
)
const contextManager = new ContextManager({
parseDocument: documentParsingService.parse
@@ -1394,6 +1415,12 @@ if (hasSingleInstanceLock) {
}
})
}).catch((error: unknown) => {
void desktopDiagnostics.recordFailure({
component: 'desktop',
stage: 'startup',
code: 'desktop.startup.failed',
error
}).catch(() => undefined)
console.error(
'GoodBuddy startup failed',
createStartupFailureDiagnostic(error)
@@ -1449,7 +1476,8 @@ app.on('before-quit', (event) => {
[() => managedRemoteExecutionServices?.dispose()],
[() => remoteAgentServices?.dispose()],
[() => knowledgeGateway?.dispose()],
[() => knowledgeService?.dispose()]
[() => knowledgeService?.dispose()],
[() => desktopDiagnostics.dispose()]
])
globalShortcut.unregisterAll()
tray?.destroy()
@@ -26,6 +26,9 @@ import {
RemoteAgentConnectionManager,
type RemoteAgentSshPool
} from './remote-agent-connection-manager'
import type {
DesktopDiagnosticFailureObserver
} from '../desktop-diagnostics'
class MemoryStateFile implements ControllerStateFile {
value?: unknown
@@ -158,7 +161,8 @@ const installation = {
function harness(
connectGate?: Promise<void>,
reconnectResumeGate?: Promise<void>,
idleTimeoutMs = 0
idleTimeoutMs = 0,
observeFailure?: DesktopDiagnosticFailureObserver
) {
let currentTarget = target()
const release = vi.fn()
@@ -206,6 +210,7 @@ function harness(
controllerState: new ControllerStateStore(stateFile),
goodBuddyVersion: '0.11.0',
idleTimeoutMs,
observeFailure,
connectTransport,
createProtocolClient: () => {
const client = new FakeProtocolClient(clients.length)
@@ -482,6 +487,27 @@ describe('RemoteAgentConnectionManager', () => {
await test.manager.dispose()
})
it('does not report acquisition canceled by its caller', async () => {
const observeFailure = vi.fn()
const test = harness(undefined, undefined, 0, observeFailure)
const controller = new AbortController()
const cancellation = new Error('caller canceled')
test.resolver.resolve.mockImplementationOnce(async () => {
controller.abort(cancellation)
throw cancellation
})
await expect(
test.manager.acquire(
'host-1',
installation,
controller.signal
)
).rejects.toBe(cancellation)
expect(observeFailure).not.toHaveBeenCalled()
await test.manager.dispose()
})
it('invalidates every connection for a Host without stopping its daemon', async () => {
const test = harness()
const lease = await test.manager.acquire('host-1', installation)
@@ -497,7 +523,8 @@ describe('RemoteAgentConnectionManager', () => {
const gate = new Promise<void>((resolve) => {
finishTransport = resolve
})
const test = harness(gate)
const observeFailure = vi.fn()
const test = harness(gate, undefined, 0, observeFailure)
const acquiring = test.manager.acquire('host-1', installation)
await vi.waitFor(() =>
expect(test.connectTransport).toHaveBeenCalledOnce()
@@ -512,6 +539,7 @@ describe('RemoteAgentConnectionManager', () => {
})
expect(test.clients[0]?.disposed).toBe(true)
expect(test.release).toHaveBeenCalledOnce()
expect(observeFailure).not.toHaveBeenCalled()
await test.manager.dispose()
})
@@ -834,4 +862,46 @@ describe('RemoteAgentConnectionManager', () => {
test.manager.acquire('host-1', installation)
).rejects.toMatchObject({ reason: 'shutdown' })
})
it('reports classified connect and disconnect failures once', async () => {
const observeFailure = vi.fn()
const failed = harness(undefined, undefined, 0, observeFailure)
failed.connectTransport.mockRejectedValueOnce(
new Error('provider unavailable')
)
await expect(
failed.manager.acquire('host-1', installation)
).rejects.toThrow()
expect(observeFailure).toHaveBeenCalledWith(
expect.objectContaining({
component: 'remote-agent',
stage: 'connect',
code: 'remote.connection.network'
})
)
await failed.manager.dispose()
observeFailure.mockClear()
const connected = harness(
undefined,
undefined,
0,
observeFailure
)
const lease = await connected.manager.acquire(
'host-1',
installation
)
connected.clients[0]!.transportClose()
expect(observeFailure).toHaveBeenCalledWith(
expect.objectContaining({
component: 'remote-agent',
stage: 'disconnect',
code: 'remote.connection.lost'
})
)
lease.release()
await connected.manager.dispose()
})
})
@@ -27,6 +27,9 @@ import {
AgentProtocolClient,
type AgentProtocolClientError
} from './agent-protocol-client'
import type {
DesktopDiagnosticFailureObserver
} from '../desktop-diagnostics'
import {
ControllerStateStore,
type ControllerAcpRecoveryBinding,
@@ -170,6 +173,9 @@ export class RemoteAgentConnectionManager {
readonly #goodBuddyVersion: string
readonly #idleTimeoutMs: number
readonly #attachTimeoutMs: number
readonly #observeFailure:
| DesktopDiagnosticFailureObserver
| undefined
readonly #identityKey = randomBytes(32)
readonly #entries = new Map<string, ConnectionEntry>()
readonly #hostConnectionStates = new Map<
@@ -192,6 +198,7 @@ export class RemoteAgentConnectionManager {
createProtocolClient?: (
transport: AgentAttachTransport
) => AgentProtocolClient
observeFailure?: DesktopDiagnosticFailureObserver
}) {
this.#resolver = options.resolver
this.#sshPool = options.sshPool
@@ -206,6 +213,7 @@ export class RemoteAgentConnectionManager {
options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS
this.#attachTimeoutMs =
options.attachTimeoutMs ?? DEFAULT_ATTACH_TIMEOUT_MS
this.#observeFailure = options.observeFailure
if (
this.#goodBuddyVersion.length < 1 ||
Buffer.byteLength(this.#goodBuddyVersion, 'utf8') > 64
@@ -236,16 +244,30 @@ export class RemoteAgentConnectionManager {
}
signal?.throwIfAborted()
const installation = validateInstallation(installationInput)
// One atomic resolver call supplies the complete current host target.
const target = await this.#resolver.resolve(hostId)
signal?.throwIfAborted()
if (target.host.id !== hostId) {
throw terminalError(
'Resolved SSH Host identity does not match the request',
'host-identity'
)
let target: SshConnectionPoolTarget
let identity: RemoteAgentConnectionIdentity
try {
// One atomic resolver call supplies the complete current host target.
target = await this.#resolver.resolve(hostId)
signal?.throwIfAborted()
if (target.host.id !== hostId) {
throw terminalError(
'Resolved SSH Host identity does not match the request',
'host-identity'
)
}
identity = this.#identity(target, installation)
} catch (error) {
const classified = classifyConnectionError(error)
if (!signal?.aborted) {
this.#reportFailure(
'connect',
`remote.connection.${classified.reason}`,
classified
)
}
throw error
}
const identity = this.#identity(target, installation)
let entry = this.#entries.get(identity.cacheKey)
if (entry === undefined) {
if (this.#entries.size >= MAXIMUM_CONNECTIONS) {
@@ -515,6 +537,13 @@ export class RemoteAgentConnectionManager {
transport?.dispose()
sshLease?.release()
const classified = classifyConnectionError(error)
if (!isAbortCancellation(entry.controller.signal)) {
this.#reportFailure(
'connect',
`remote.connection.${classified.reason}`,
classified
)
}
if (
this.#entries.get(entry.key) === entry &&
entry.connectionState !== 'disposed'
@@ -914,6 +943,11 @@ export class RemoteAgentConnectionManager {
error
)
entry.connectionState = 'offline'
this.#reportFailure(
'disconnect',
'remote.connection.lost',
entry.failure
)
this.#syncHostConnectionState(entry.hostId)
active?.unsubscribeClose()
active?.sshLease.release()
@@ -922,6 +956,23 @@ export class RemoteAgentConnectionManager {
}
}
#reportFailure(
stage: string,
code: string,
error: unknown
): void {
try {
this.#observeFailure?.({
component: 'remote-agent',
stage,
code,
error
})
} catch {
// Diagnostics must not alter remote connection behavior.
}
}
async #persistConnection(
entry: ConnectionEntry,
active: ActiveConnection,
@@ -1070,6 +1121,21 @@ export class RemoteAgentConnectionManager {
}
}
function isAbortCancellation(signal: AbortSignal): boolean {
if (!signal.aborted) {
return false
}
const reason: unknown = signal.reason
if (typeof reason !== 'object' || reason === null) {
return true
}
try {
return !('name' in reason) || reason.name === 'AbortError'
} catch {
return true
}
}
function validateInstallation(
input: RemoteAgentInstallationIdentity
): RemoteAgentInstallationIdentity {
@@ -14,6 +14,9 @@ import {
RemoteAgentConnectionManager,
type RemoteAgentTargetResolver
} from './remote-agent-connection-manager'
import type {
DesktopDiagnosticFailureObserver
} from '../desktop-diagnostics'
const CONTROLLER_STATE_FILE_NAME = 'remote-agent-controller-state.json'
@@ -34,6 +37,7 @@ type RemoteAgentServiceFactories = {
sshPool: SshConnectionPool
controllerState: ControllerStateStore
goodBuddyVersion: string
observeFailure?: DesktopDiagnosticFailureObserver
}) => RemoteAgentConnectionManager
}
@@ -45,6 +49,7 @@ export type RemoteAgentServicesOptions = {
resourcesPath: string
packaged: boolean
controlPlanePackageInstaller: Buffer | string
observeFailure?: DesktopDiagnosticFailureObserver
factories?: Partial<RemoteAgentServiceFactories>
}
@@ -103,7 +108,8 @@ export class RemoteAgentServices {
resolver: this.targetResolver,
sshPool: this.sshPool,
controllerState: this.controllerState,
goodBuddyVersion: options.goodBuddyVersion
goodBuddyVersion: options.goodBuddyVersion,
observeFailure: options.observeFailure
})
}