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:
@@ -33,6 +33,7 @@ import {
|
||||
import { RuntimeBundleRegistry } from './runtime-bundle-registry'
|
||||
import type { VerifiedRuntimeBundle } from './runtime-bundle-verifier'
|
||||
import type { RemoteRuntimeLock } from '../shared/remote-runtime-launch-contracts'
|
||||
import { AgentDiagnosticLog } from './diagnostic-log'
|
||||
|
||||
const temporaryPaths: string[] = []
|
||||
|
||||
@@ -246,6 +247,58 @@ describe('Agent CLI fixed command contract', () => {
|
||||
expect(bootstrap).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('exports only bounded diagnostics for a fixed installation ID as JSONL', async () => {
|
||||
const root = privateTemporaryDirectory()
|
||||
const stateDirectory = resolve(root, 'state', 'install-1')
|
||||
mkdirSync(stateDirectory, { recursive: true, mode: 0o700 })
|
||||
if (process.platform !== 'win32') {
|
||||
chmodSync(resolve(root, 'state'), 0o700)
|
||||
chmodSync(stateDirectory, 0o700)
|
||||
}
|
||||
const log = new AgentDiagnosticLog(stateDirectory, {
|
||||
pid: 42
|
||||
})
|
||||
log.record('daemon.ready', {
|
||||
daemonBootId: 'boot-1'
|
||||
})
|
||||
log.record('runtime.start.failed', {
|
||||
runtimeId: 'opencode',
|
||||
error: new Error('private Prompt and /private/path')
|
||||
})
|
||||
await log.flush()
|
||||
const io = cliIo()
|
||||
|
||||
const result = await runAgentCli(
|
||||
['diagnostics', '--installation-id', 'install-1'],
|
||||
{
|
||||
installationPaths: () => ({
|
||||
executablePath: resolve(root, 'agent', 'goodbuddy-agent'),
|
||||
stateDirectory,
|
||||
socketPath: resolve(root, 'run', 'agent.sock')
|
||||
}),
|
||||
io
|
||||
}
|
||||
)
|
||||
|
||||
expect(result, io.error.read()?.toString()).toBe(0)
|
||||
const output = io.output.read()!.toString()
|
||||
expect(output).not.toContain('private Prompt')
|
||||
expect(output).not.toContain('/private/path')
|
||||
expect(
|
||||
output.trimEnd().split('\n').map((line) => JSON.parse(line))
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
event: 'daemon.ready',
|
||||
daemonBootId: 'boot-1'
|
||||
}),
|
||||
expect.objectContaining({
|
||||
event: 'runtime.start.failed',
|
||||
runtimeId: 'opencode',
|
||||
error: { name: 'Error' }
|
||||
})
|
||||
])
|
||||
})
|
||||
|
||||
it('dispatches generated attach argv using only derived managed paths', async () => {
|
||||
const root = privateTemporaryDirectory()
|
||||
const paths: ManagedInstallationPaths = {
|
||||
|
||||
+23
-1
@@ -53,6 +53,7 @@ import {
|
||||
DetachedAgentLifecycle,
|
||||
type DetachedAgentLifecycleOptions
|
||||
} from './detached-agent-lifecycle'
|
||||
import { readAgentDiagnostics } from './diagnostic-log'
|
||||
|
||||
type CliIo = {
|
||||
input: Readable
|
||||
@@ -141,6 +142,9 @@ export async function runAgentCli(
|
||||
case 'doctor':
|
||||
await runDoctor(rest, dependencies, io)
|
||||
return 0
|
||||
case 'diagnostics':
|
||||
runDiagnostics(rest, dependencies, io)
|
||||
return 0
|
||||
case 'runtime':
|
||||
await runRuntime(rest, dependencies, io)
|
||||
return 0
|
||||
@@ -152,7 +156,7 @@ export async function runAgentCli(
|
||||
return 0
|
||||
}
|
||||
throw new Error(
|
||||
'Expected daemon, attach-or-bootstrap, doctor, a lifecycle action, runtime, or model-bridge-helper'
|
||||
'Expected daemon, attach-or-bootstrap, doctor, diagnostics, a lifecycle action, runtime, or model-bridge-helper'
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -353,6 +357,7 @@ async function runDaemon(
|
||||
runtimeFactory: async ({
|
||||
events,
|
||||
workspaces,
|
||||
diagnostics,
|
||||
outputSink,
|
||||
blobSink
|
||||
}) =>
|
||||
@@ -367,6 +372,7 @@ async function runDaemon(
|
||||
workspaces,
|
||||
outputSink,
|
||||
blobSink,
|
||||
diagnostics,
|
||||
agentExecutablePath: paths.executablePath,
|
||||
installationId
|
||||
})
|
||||
@@ -501,6 +507,22 @@ async function runDoctor(
|
||||
})}\n`)
|
||||
}
|
||||
|
||||
function runDiagnostics(
|
||||
argv: readonly string[],
|
||||
dependencies: AgentCliDependencies,
|
||||
io: CliIo
|
||||
): void {
|
||||
const options = parseOptions(argv, ['installation-id'])
|
||||
requireOptions(options, ['installation-id'])
|
||||
const installationId = validateInstallationId(
|
||||
options['installation-id']!
|
||||
)
|
||||
const paths = resolveInstallationPaths(installationId, dependencies)
|
||||
for (const record of readAgentDiagnostics(paths.stateDirectory)) {
|
||||
io.output.write(`${JSON.stringify(record)}\n`)
|
||||
}
|
||||
}
|
||||
|
||||
async function runLifecycle(
|
||||
argv: readonly string[],
|
||||
dependencies: AgentCliDependencies,
|
||||
|
||||
@@ -36,6 +36,7 @@ import { AgentUnsupportedError } from './errors'
|
||||
import { WorkspaceGitService } from './workspace-git-service'
|
||||
import { createWorkspaceProtocolMethods } from './workspace-protocol-methods'
|
||||
import { WorkspaceRegistry } from './workspace-registry'
|
||||
import { AgentDiagnosticLog } from './diagnostic-log'
|
||||
|
||||
export type AgentDaemonOptions = {
|
||||
installationId: string
|
||||
@@ -67,6 +68,7 @@ export type AgentDaemonOptions = {
|
||||
runtimeFactory?: (context: {
|
||||
events: EventJournal
|
||||
workspaces: WorkspaceRegistry
|
||||
diagnostics: AgentDiagnosticLog
|
||||
outputSink: (
|
||||
frame: AgentFrame,
|
||||
context: {
|
||||
@@ -109,6 +111,7 @@ export class AgentDaemon {
|
||||
readonly #runtimeProtocol?: AgentDaemonOptions['runtimeProtocol']
|
||||
readonly #runtimeFactory?: AgentDaemonOptions['runtimeFactory']
|
||||
readonly #reportError: (message: string, error: unknown) => void
|
||||
readonly #diagnostics: AgentDiagnosticLog
|
||||
#state: 'starting' | 'ready' | 'stopped' = 'stopped'
|
||||
#endpoint?: PrivateEndpoint
|
||||
#events?: EventJournal
|
||||
@@ -136,8 +139,11 @@ export class AgentDaemon {
|
||||
)
|
||||
this.#stateDirectory = resolve(options.stateDirectory)
|
||||
this.#socketPath = resolve(options.socketPath)
|
||||
this.#peerIdentityProvider = options.peerIdentityProvider
|
||||
this.#now = options.now ?? Date.now
|
||||
this.#diagnostics = new AgentDiagnosticLog(this.#stateDirectory, {
|
||||
now: this.#now
|
||||
})
|
||||
this.#peerIdentityProvider = options.peerIdentityProvider
|
||||
this.#gitExecutable = options.gitExecutable
|
||||
this.#workspaceRequestTimeoutMs = options.workspaceRequestTimeoutMs
|
||||
this.#runtimeProtocol = options.runtimeProtocol
|
||||
@@ -186,6 +192,9 @@ export class AgentDaemon {
|
||||
this.#state = 'starting'
|
||||
try {
|
||||
ensurePrivateDirectory(this.#stateDirectory)
|
||||
this.#diagnostics.tryRecord('daemon.starting', {
|
||||
daemonBootId: this.#bootId
|
||||
})
|
||||
ensurePrivateDirectoryTree(
|
||||
resolve(this.#stateDirectory, 'journal'),
|
||||
this.#stateDirectory
|
||||
@@ -234,6 +243,7 @@ export class AgentDaemon {
|
||||
await this.#runtimeFactory?.({
|
||||
events: this.#events,
|
||||
workspaces: this.#workspaces,
|
||||
diagnostics: this.#diagnostics,
|
||||
outputSink: async (frame) => {
|
||||
if (protocolBox.current === undefined) {
|
||||
throw new Error(
|
||||
@@ -277,6 +287,10 @@ export class AgentDaemon {
|
||||
connectionId,
|
||||
category
|
||||
}) => {
|
||||
this.#diagnostics.tryRecord('connection.failed', {
|
||||
daemonBootId: this.#bootId,
|
||||
reason: category
|
||||
})
|
||||
try {
|
||||
writePrivateFileAtomic(
|
||||
resolve(
|
||||
@@ -299,6 +313,20 @@ export class AgentDaemon {
|
||||
)
|
||||
}
|
||||
},
|
||||
onConnectionClose: ({ category }) => {
|
||||
if (category === undefined) {
|
||||
this.#diagnostics.tryRecord('connection.closed', {
|
||||
daemonBootId: this.#bootId,
|
||||
reason: 'peer-closed'
|
||||
})
|
||||
}
|
||||
},
|
||||
onRecovery: ({ outcome, reason }) => {
|
||||
this.#diagnostics.tryRecord(`recovery.${outcome}`, {
|
||||
daemonBootId: this.#bootId,
|
||||
...(reason === undefined ? {} : { reason })
|
||||
})
|
||||
},
|
||||
methods: mergeProtocolMethods(
|
||||
workspaceMethods,
|
||||
this.#activeRuntimeProtocol?.methods
|
||||
@@ -317,18 +345,40 @@ export class AgentDaemon {
|
||||
daemonBootId: this.#bootId,
|
||||
protocol: this.#protocol,
|
||||
onAttach: ({ socket, controller }) => {
|
||||
this.#diagnostics.tryRecord('connection.attached', {
|
||||
daemonBootId: this.#bootId
|
||||
})
|
||||
protocol.accept(socket, controller)
|
||||
},
|
||||
onConnectionFailure: (error) => {
|
||||
this.#diagnostics.tryRecord('connection.failed', {
|
||||
daemonBootId: this.#bootId,
|
||||
reason: 'authentication',
|
||||
error
|
||||
})
|
||||
}
|
||||
})
|
||||
await this.#endpoint.listen()
|
||||
this.#state = 'ready'
|
||||
this.#diagnostics.tryRecord('daemon.ready', {
|
||||
daemonBootId: this.#bootId
|
||||
})
|
||||
} catch (error) {
|
||||
this.#diagnostics.tryRecord('daemon.start.failed', {
|
||||
daemonBootId: this.#bootId,
|
||||
error
|
||||
})
|
||||
await this.stop()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.#state !== 'stopped') {
|
||||
this.#diagnostics.tryRecord('daemon.stopping', {
|
||||
daemonBootId: this.#bootId
|
||||
})
|
||||
}
|
||||
const endpoint = this.#endpoint
|
||||
const events = this.#events
|
||||
const workspaces = this.#workspaces
|
||||
@@ -337,10 +387,14 @@ export class AgentDaemon {
|
||||
this.#events = undefined
|
||||
this.#workspaces = undefined
|
||||
this.#activeRuntimeProtocol = undefined
|
||||
let stopError: unknown
|
||||
try {
|
||||
if (endpoint !== undefined) {
|
||||
await endpoint.close()
|
||||
}
|
||||
} catch (error) {
|
||||
stopError = error
|
||||
throw error
|
||||
} finally {
|
||||
if (runtimeProtocol?.dispose !== undefined) {
|
||||
await Promise.resolve(runtimeProtocol.dispose()).catch(
|
||||
@@ -352,10 +406,25 @@ export class AgentDaemon {
|
||||
workspaces?.closeAll()
|
||||
events?.close()
|
||||
this.#state = 'stopped'
|
||||
this.#diagnostics.tryRecord(
|
||||
stopError === undefined
|
||||
? 'daemon.stopped'
|
||||
: 'daemon.stop.failed',
|
||||
{
|
||||
daemonBootId: this.#bootId,
|
||||
...(stopError === undefined ? {} : { error: stopError })
|
||||
}
|
||||
)
|
||||
await this.#diagnostics.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
#reportRuntimeShutdownError(error: unknown): void {
|
||||
this.#diagnostics.tryRecord('daemon.stop.failed', {
|
||||
daemonBootId: this.#bootId,
|
||||
reason: 'runtime-dispose',
|
||||
error
|
||||
})
|
||||
try {
|
||||
this.#reportError('Agent Runtime shutdown failed', error)
|
||||
} catch (reportError) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from './linux-process-identity'
|
||||
import { writePrivateFileAtomic } from './managed-paths'
|
||||
import type { VerifiedInstalledAgentBundle } from './installed-bundle-verifier'
|
||||
import { readAgentDiagnostics } from './diagnostic-log'
|
||||
|
||||
const parentPid = 1101
|
||||
const childPid = 2202
|
||||
@@ -73,6 +74,16 @@ describe('detached Agent lifecycle', () => {
|
||||
)
|
||||
expect(harness.unref).toHaveBeenCalledOnce()
|
||||
expect(harness.probe).toHaveBeenCalled()
|
||||
expect(
|
||||
readAgentDiagnostics(harness.stateDirectory).map(
|
||||
(record) => record.event
|
||||
)
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
'detached.launching',
|
||||
'detached.spawned'
|
||||
])
|
||||
)
|
||||
})
|
||||
|
||||
it('creates the managed state parent before bootstrapping', async () => {
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
writePrivateFileAtomic
|
||||
} from './managed-paths'
|
||||
import type { AttachWelcome } from '../shared/agent-protocol'
|
||||
import { AgentDiagnosticLog } from './diagnostic-log'
|
||||
|
||||
const DEFAULT_READINESS_TIMEOUT_MS = 15_000
|
||||
const DEFAULT_STOP_TIMEOUT_MS = 5_000
|
||||
@@ -140,6 +141,7 @@ export class DetachedAgentLifecycle {
|
||||
readonly #retireLegacyInstallation?: (
|
||||
verified: VerifiedInstalledAgentBundle
|
||||
) => void | Promise<void>
|
||||
readonly #diagnostics: AgentDiagnosticLog
|
||||
|
||||
constructor(options: DetachedAgentLifecycleOptions) {
|
||||
this.#installationId = validateInstallationId(options.installationId)
|
||||
@@ -156,6 +158,10 @@ export class DetachedAgentLifecycle {
|
||||
this.#spawnDetached = options.spawnDetached ?? spawnDetachedProcess
|
||||
this.#currentPid = positivePid(options.currentPid ?? process.pid)
|
||||
this.#now = options.now ?? Date.now
|
||||
this.#diagnostics = new AgentDiagnosticLog(this.#stateDirectory, {
|
||||
now: this.#now,
|
||||
pid: this.#currentPid
|
||||
})
|
||||
this.#sleep =
|
||||
options.sleep ??
|
||||
(async (milliseconds) =>
|
||||
@@ -215,6 +221,7 @@ export class DetachedAgentLifecycle {
|
||||
|
||||
const launchArgv = ['daemon', '--installation-id', this.#installationId]
|
||||
const runtimePath = expectedRuntimePath(verified)
|
||||
this.#diagnostics.tryRecord('detached.launching')
|
||||
const child = this.#spawnDetached(this.#executablePath, launchArgv, {
|
||||
env: detachedEnvironment(this.#environment),
|
||||
detached: true,
|
||||
@@ -226,6 +233,7 @@ export class DetachedAgentLifecycle {
|
||||
throw new Error('Detached Agent spawn did not return a process ID')
|
||||
}
|
||||
child.unref()
|
||||
this.#diagnostics.tryRecord('detached.spawned')
|
||||
const processIdentity = await this.#waitForProcessIdentity(
|
||||
child.pid,
|
||||
runtimePath
|
||||
@@ -246,8 +254,18 @@ export class DetachedAgentLifecycle {
|
||||
throw new Error('Detached Agent readiness timed out')
|
||||
}
|
||||
return ready
|
||||
} catch (error) {
|
||||
this.#diagnostics.tryRecord('recovery.failed', {
|
||||
reason: 'bootstrap',
|
||||
error
|
||||
})
|
||||
throw error
|
||||
} finally {
|
||||
releaseLock()
|
||||
try {
|
||||
releaseLock()
|
||||
} finally {
|
||||
await this.#diagnostics.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
AGENT_DIAGNOSTIC_DIRECTORY_NAME,
|
||||
AgentDiagnosticLog,
|
||||
readAgentDiagnostics
|
||||
} from './diagnostic-log'
|
||||
|
||||
const temporaryPaths: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const path of temporaryPaths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent diagnostic log', () => {
|
||||
it('rotates within fixed file and byte bounds and remains readable after restart', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
let now = Date.UTC(2026, 7, 31)
|
||||
const first = new AgentDiagnosticLog(stateDirectory, {
|
||||
maximumFileBytes: 512,
|
||||
fileCount: 2,
|
||||
now: () => now,
|
||||
pid: 42
|
||||
})
|
||||
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
first.record('connection.failed', {
|
||||
daemonBootId: `boot-${index}`,
|
||||
reason: 'socket-error',
|
||||
error: Object.assign(new Error(`failure-${index}`), {
|
||||
code: 'ECONNRESET'
|
||||
})
|
||||
})
|
||||
now += 1_000
|
||||
}
|
||||
await first.flush()
|
||||
|
||||
const directory = resolve(
|
||||
stateDirectory,
|
||||
AGENT_DIAGNOSTIC_DIRECTORY_NAME
|
||||
)
|
||||
const files = readdirSync(directory)
|
||||
expect(files).toHaveLength(2)
|
||||
for (const file of files) {
|
||||
expect(statSync(resolve(directory, file)).size).toBeLessThanOrEqual(512)
|
||||
}
|
||||
|
||||
const restarted = new AgentDiagnosticLog(stateDirectory, {
|
||||
maximumFileBytes: 512,
|
||||
fileCount: 2,
|
||||
pid: 43
|
||||
})
|
||||
const records = restarted.read()
|
||||
expect(records.length).toBeGreaterThan(0)
|
||||
expect(records.at(-1)).toMatchObject({
|
||||
event: 'connection.failed',
|
||||
daemonBootId: 'boot-19',
|
||||
error: {
|
||||
name: 'Error',
|
||||
code: 'ECONNRESET'
|
||||
}
|
||||
})
|
||||
expect(records.some((record) => record.daemonBootId === 'boot-0')).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
it('persists only allowlisted metadata and never error messages or sensitive payloads', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
const secretPrompt = 'accepted Prompt: summarize private-file.txt'
|
||||
const secretKey = 'sk-private-model-key'
|
||||
const secretConfig = '{"providerUrl":"https://private.invalid"}'
|
||||
const secretEnvironment = 'GOODBUDDY_SECRET=hidden'
|
||||
const secretSsh = 'ssh -i /home/user/private-key user@host'
|
||||
const secretOutput = 'MODEL_OUTPUT_PRIVATE'
|
||||
const error = Object.assign(
|
||||
new Error(
|
||||
[
|
||||
secretPrompt,
|
||||
secretKey,
|
||||
secretConfig,
|
||||
secretEnvironment,
|
||||
secretSsh,
|
||||
secretOutput
|
||||
].join(' ')
|
||||
),
|
||||
{
|
||||
code: secretKey,
|
||||
name: secretConfig
|
||||
}
|
||||
)
|
||||
const log = new AgentDiagnosticLog(stateDirectory, {
|
||||
pid: 42
|
||||
})
|
||||
|
||||
log.record('runtime.start.failed', {
|
||||
runtimeId: 'opencode',
|
||||
workMode: 'execute',
|
||||
error
|
||||
})
|
||||
await log.flush()
|
||||
|
||||
const raw = readdirSync(
|
||||
resolve(stateDirectory, AGENT_DIAGNOSTIC_DIRECTORY_NAME)
|
||||
)
|
||||
.map((name) =>
|
||||
readFileSync(
|
||||
resolve(
|
||||
stateDirectory,
|
||||
AGENT_DIAGNOSTIC_DIRECTORY_NAME,
|
||||
name
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
)
|
||||
.join('')
|
||||
for (const sensitive of [
|
||||
secretPrompt,
|
||||
secretKey,
|
||||
secretConfig,
|
||||
secretEnvironment,
|
||||
secretSsh,
|
||||
secretOutput
|
||||
]) {
|
||||
expect(raw).not.toContain(sensitive)
|
||||
}
|
||||
expect(JSON.parse(raw)).toEqual({
|
||||
formatVersion: 1,
|
||||
timestamp: expect.any(String),
|
||||
level: 'error',
|
||||
event: 'runtime.start.failed',
|
||||
pid: 42,
|
||||
runtimeId: 'opencode',
|
||||
workMode: 'execute',
|
||||
error: {
|
||||
name: 'Error'
|
||||
}
|
||||
})
|
||||
expect(readAgentDiagnostics(stateDirectory)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps a single-file configuration bounded', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
const log = new AgentDiagnosticLog(stateDirectory, {
|
||||
maximumFileBytes: 512,
|
||||
fileCount: 1,
|
||||
pid: 42
|
||||
})
|
||||
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
log.record('daemon.ready', {
|
||||
daemonBootId: `boot-${index}`
|
||||
})
|
||||
}
|
||||
await log.flush()
|
||||
|
||||
const files = readdirSync(
|
||||
resolve(stateDirectory, AGENT_DIAGNOSTIC_DIRECTORY_NAME)
|
||||
)
|
||||
expect(files).toHaveLength(1)
|
||||
expect(
|
||||
statSync(
|
||||
resolve(
|
||||
stateDirectory,
|
||||
AGENT_DIAGNOSTIC_DIRECTORY_NAME,
|
||||
files[0]!
|
||||
)
|
||||
).size
|
||||
).toBeLessThanOrEqual(512)
|
||||
})
|
||||
|
||||
it('keeps the default three 64 KiB private JSONL files bounded', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
const log = new AgentDiagnosticLog(stateDirectory, {
|
||||
pid: 42
|
||||
})
|
||||
|
||||
for (let batch = 0; batch < 50; batch += 1) {
|
||||
for (let index = 0; index < 60; index += 1) {
|
||||
log.record('connection.failed', {
|
||||
daemonBootId: `boot-${batch}-${index}`,
|
||||
reason: 'socket-error',
|
||||
error: Object.assign(new Error('private failure'), {
|
||||
code: 'ECONNRESET'
|
||||
})
|
||||
})
|
||||
}
|
||||
await log.flush()
|
||||
}
|
||||
|
||||
const directory = resolve(
|
||||
stateDirectory,
|
||||
AGENT_DIAGNOSTIC_DIRECTORY_NAME
|
||||
)
|
||||
const files = readdirSync(directory).sort()
|
||||
expect(files).toEqual([
|
||||
'agent-diagnostics.jsonl',
|
||||
'agent-diagnostics.jsonl.1',
|
||||
'agent-diagnostics.jsonl.2'
|
||||
])
|
||||
for (const file of files) {
|
||||
const path = resolve(directory, file)
|
||||
expect(statSync(path).size).toBeLessThanOrEqual(64 * 1024)
|
||||
for (const line of readFileSync(path, 'utf8').trimEnd().split('\n')) {
|
||||
expect(() => JSON.parse(line)).not.toThrow()
|
||||
}
|
||||
if (process.platform !== 'win32') {
|
||||
expect(statSync(path).mode & 0o777).toBe(0o600)
|
||||
}
|
||||
}
|
||||
if (process.platform !== 'win32') {
|
||||
expect(statSync(directory).mode & 0o777).toBe(0o700)
|
||||
}
|
||||
})
|
||||
|
||||
it('drops records beyond the fixed queue bound', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
const log = new AgentDiagnosticLog(stateDirectory, {
|
||||
maximumQueuedRecords: 4,
|
||||
pid: 42
|
||||
})
|
||||
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
log.tryRecord('daemon.ready', {
|
||||
daemonBootId: `boot-${index}`
|
||||
})
|
||||
}
|
||||
await log.flush()
|
||||
|
||||
expect(log.read().map((record) => record.daemonBootId)).toEqual([
|
||||
'boot-0',
|
||||
'boot-1',
|
||||
'boot-2',
|
||||
'boot-3'
|
||||
])
|
||||
})
|
||||
|
||||
it('serializes independent process writers without a size cache', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
const daemonLog = new AgentDiagnosticLog(stateDirectory, {
|
||||
pid: 42
|
||||
})
|
||||
const attachLog = new AgentDiagnosticLog(stateDirectory, {
|
||||
pid: 43
|
||||
})
|
||||
|
||||
daemonLog.tryRecord('daemon.ready', {
|
||||
daemonBootId: 'daemon-boot'
|
||||
})
|
||||
attachLog.tryRecord('detached.spawned')
|
||||
await Promise.all([daemonLog.flush(), attachLog.flush()])
|
||||
|
||||
expect(
|
||||
readAgentDiagnostics(stateDirectory).map((record) => record.pid).sort()
|
||||
).toEqual([42, 43])
|
||||
})
|
||||
|
||||
it('does not touch the disk synchronously from tryRecord', async () => {
|
||||
const stateDirectory = temporaryStateDirectory()
|
||||
const log = new AgentDiagnosticLog(stateDirectory, {
|
||||
pid: 42
|
||||
})
|
||||
const directory = resolve(
|
||||
stateDirectory,
|
||||
AGENT_DIAGNOSTIC_DIRECTORY_NAME
|
||||
)
|
||||
|
||||
log.tryRecord('connection.attached')
|
||||
|
||||
expect(existsSync(directory)).toBe(false)
|
||||
await log.flush()
|
||||
expect(existsSync(directory)).toBe(true)
|
||||
})
|
||||
|
||||
it('isolates asynchronous write failures from runtime callers', async () => {
|
||||
const root = temporaryStateDirectory()
|
||||
const unavailableStateDirectory = resolve(root, 'missing-state')
|
||||
const log = new AgentDiagnosticLog(unavailableStateDirectory, {
|
||||
pid: 42
|
||||
})
|
||||
let runtimeContinued = false
|
||||
|
||||
expect(() => {
|
||||
log.tryRecord('runtime.start.failed', {
|
||||
error: new Error('private failure')
|
||||
})
|
||||
runtimeContinued = true
|
||||
}).not.toThrow()
|
||||
await expect(log.flush()).resolves.toBeUndefined()
|
||||
|
||||
expect(runtimeContinued).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
function temporaryStateDirectory(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'goodbuddy-diagnostics-'))
|
||||
temporaryPaths.push(root)
|
||||
if (process.platform !== 'win32') {
|
||||
chmodSync(root, 0o700)
|
||||
}
|
||||
return root
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
import { constants } from 'node:fs'
|
||||
import {
|
||||
lstat,
|
||||
open,
|
||||
rename
|
||||
} from 'node:fs/promises'
|
||||
import { resolve } from 'node:path'
|
||||
import { agentIdentifierSchema } from '../shared/agent-protocol'
|
||||
import {
|
||||
boundedInteger,
|
||||
isNodeError,
|
||||
settleWithin
|
||||
} from './async-utils'
|
||||
import {
|
||||
assertPrivateRegularFile,
|
||||
ensurePrivateDirectory,
|
||||
ensurePrivateDirectoryTree,
|
||||
readPrivateFile,
|
||||
unlinkOwnedPrivateFile
|
||||
} from './managed-paths'
|
||||
|
||||
export const AGENT_DIAGNOSTIC_DIRECTORY_NAME = 'diagnostics'
|
||||
export const AGENT_DIAGNOSTIC_FILE_NAME = 'agent-diagnostics.jsonl'
|
||||
export const DEFAULT_AGENT_DIAGNOSTIC_MAXIMUM_FILE_BYTES = 64 * 1024
|
||||
export const DEFAULT_AGENT_DIAGNOSTIC_FILE_COUNT = 3
|
||||
export const DEFAULT_AGENT_DIAGNOSTIC_MAXIMUM_QUEUED_RECORDS = 64
|
||||
export const DEFAULT_AGENT_DIAGNOSTIC_FLUSH_TIMEOUT_MS = 1_000
|
||||
const AGENT_DIAGNOSTIC_LOCK_FILE_NAME = '.agent-diagnostics.lock'
|
||||
const AGENT_DIAGNOSTIC_LOCK_ATTEMPTS = 10
|
||||
const AGENT_DIAGNOSTIC_LOCK_RETRY_MS = 10
|
||||
|
||||
export type AgentDiagnosticEvent =
|
||||
| 'daemon.starting'
|
||||
| 'daemon.ready'
|
||||
| 'daemon.start.failed'
|
||||
| 'daemon.stopping'
|
||||
| 'daemon.stopped'
|
||||
| 'daemon.stop.failed'
|
||||
| 'detached.launching'
|
||||
| 'detached.spawned'
|
||||
| 'connection.attached'
|
||||
| 'connection.closed'
|
||||
| 'connection.failed'
|
||||
| 'recovery.started'
|
||||
| 'recovery.succeeded'
|
||||
| 'recovery.failed'
|
||||
| 'runtime.starting'
|
||||
| 'runtime.started'
|
||||
| 'runtime.start.failed'
|
||||
| 'runtime.exited'
|
||||
|
||||
export type AgentDiagnosticRecord = {
|
||||
formatVersion: 1
|
||||
timestamp: string
|
||||
level: 'info' | 'error'
|
||||
event: AgentDiagnosticEvent
|
||||
pid: number
|
||||
daemonBootId?: string
|
||||
reason?: string
|
||||
runtimeId?: string
|
||||
workMode?: 'ask' | 'execute'
|
||||
outcome?: 'completed' | 'failed' | 'cancelled' | 'interrupted' | 'outcome-unknown'
|
||||
error?: {
|
||||
name: string
|
||||
code?: string
|
||||
}
|
||||
}
|
||||
|
||||
export type AgentDiagnosticInput = {
|
||||
daemonBootId?: string
|
||||
reason?: string
|
||||
runtimeId?: string
|
||||
workMode?: 'ask' | 'execute'
|
||||
outcome?: AgentDiagnosticRecord['outcome']
|
||||
error?: unknown
|
||||
}
|
||||
|
||||
export type AgentDiagnosticLogOptions = {
|
||||
maximumFileBytes?: number
|
||||
fileCount?: number
|
||||
maximumQueuedRecords?: number
|
||||
now?: () => number
|
||||
pid?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A small, process-safe-enough JSONL diagnostic trail for detached operation.
|
||||
*
|
||||
* Callers can provide only fixed operational metadata. Arbitrary error
|
||||
* messages are deliberately not persisted because they can contain prompts,
|
||||
* credentials, command lines, paths, environment values, or Runtime output.
|
||||
*/
|
||||
export class AgentDiagnosticLog {
|
||||
readonly directoryPath: string
|
||||
readonly currentFilePath: string
|
||||
readonly #maximumFileBytes: number
|
||||
readonly #fileCount: number
|
||||
readonly #maximumQueuedRecords: number
|
||||
readonly #now: () => number
|
||||
readonly #pid: number
|
||||
readonly #queuedLines: string[] = []
|
||||
#pendingRecordCount = 0
|
||||
#drainPromise?: Promise<void>
|
||||
#disposed = false
|
||||
|
||||
constructor(
|
||||
stateDirectoryInput: string,
|
||||
options: AgentDiagnosticLogOptions = {}
|
||||
) {
|
||||
const stateDirectory = resolve(stateDirectoryInput)
|
||||
this.directoryPath = diagnosticDirectoryForStateDirectory(stateDirectory)
|
||||
this.currentFilePath = resolve(
|
||||
this.directoryPath,
|
||||
AGENT_DIAGNOSTIC_FILE_NAME
|
||||
)
|
||||
this.#maximumFileBytes = boundedInteger(
|
||||
options.maximumFileBytes ??
|
||||
DEFAULT_AGENT_DIAGNOSTIC_MAXIMUM_FILE_BYTES,
|
||||
512,
|
||||
1024 * 1024,
|
||||
'Agent diagnostic file size'
|
||||
)
|
||||
this.#fileCount = boundedInteger(
|
||||
options.fileCount ?? DEFAULT_AGENT_DIAGNOSTIC_FILE_COUNT,
|
||||
1,
|
||||
8,
|
||||
'Agent diagnostic file count'
|
||||
)
|
||||
this.#maximumQueuedRecords = boundedInteger(
|
||||
options.maximumQueuedRecords ??
|
||||
DEFAULT_AGENT_DIAGNOSTIC_MAXIMUM_QUEUED_RECORDS,
|
||||
1,
|
||||
256,
|
||||
'Agent diagnostic queue size'
|
||||
)
|
||||
this.#now = options.now ?? Date.now
|
||||
this.#pid = boundedInteger(
|
||||
options.pid ?? process.pid,
|
||||
1,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
'Agent diagnostic process ID'
|
||||
)
|
||||
}
|
||||
|
||||
record(event: AgentDiagnosticEvent, input: AgentDiagnosticInput = {}): void {
|
||||
if (this.#disposed) {
|
||||
throw new Error('Agent diagnostic log is disposed')
|
||||
}
|
||||
const line = this.#normalizeLine(event, input)
|
||||
if (!this.#enqueue(line)) {
|
||||
throw new Error('Agent diagnostic queue is full')
|
||||
}
|
||||
}
|
||||
|
||||
tryRecord(
|
||||
event: AgentDiagnosticEvent,
|
||||
input: AgentDiagnosticInput = {}
|
||||
): void {
|
||||
try {
|
||||
if (this.#disposed) {
|
||||
return
|
||||
}
|
||||
// Normalize now so the queue retains only bounded JSON, never the
|
||||
// original Error object or any message that it may contain.
|
||||
this.#enqueue(this.#normalizeLine(event, input))
|
||||
} catch {
|
||||
// Diagnostics must never interfere with daemon, attach, or Runtime I/O.
|
||||
}
|
||||
}
|
||||
|
||||
async flush(
|
||||
timeoutMs = DEFAULT_AGENT_DIAGNOSTIC_FLUSH_TIMEOUT_MS
|
||||
): Promise<void> {
|
||||
const boundedTimeout = boundedInteger(
|
||||
timeoutMs,
|
||||
1,
|
||||
30_000,
|
||||
'Agent diagnostic flush timeout'
|
||||
)
|
||||
await settleWithin(this.#waitForIdle(), boundedTimeout)
|
||||
}
|
||||
|
||||
async dispose(
|
||||
timeoutMs = DEFAULT_AGENT_DIAGNOSTIC_FLUSH_TIMEOUT_MS
|
||||
): Promise<void> {
|
||||
this.#disposed = true
|
||||
await this.flush(timeoutMs)
|
||||
}
|
||||
|
||||
read(): AgentDiagnosticRecord[] {
|
||||
return readAgentDiagnostics(resolve(this.directoryPath, '..'), {
|
||||
maximumFileBytes: this.#maximumFileBytes,
|
||||
fileCount: this.#fileCount
|
||||
})
|
||||
}
|
||||
|
||||
#normalizeLine(
|
||||
event: AgentDiagnosticEvent,
|
||||
input: AgentDiagnosticInput
|
||||
): string {
|
||||
const record: AgentDiagnosticRecord = {
|
||||
formatVersion: 1,
|
||||
timestamp: new Date(this.#now()).toISOString(),
|
||||
level: event.endsWith('.failed') ? 'error' : 'info',
|
||||
event,
|
||||
pid: this.#pid,
|
||||
...optionalToken('daemonBootId', input.daemonBootId, 128),
|
||||
...optionalToken('reason', input.reason, 96),
|
||||
...optionalToken('runtimeId', input.runtimeId, 64),
|
||||
...(input.workMode === undefined
|
||||
? {}
|
||||
: { workMode: input.workMode }),
|
||||
...(input.outcome === undefined
|
||||
? {}
|
||||
: { outcome: input.outcome }),
|
||||
...(input.error === undefined
|
||||
? {}
|
||||
: { error: summarizeDiagnosticError(input.error) })
|
||||
}
|
||||
const line = `${JSON.stringify(record)}\n`
|
||||
if (Buffer.byteLength(line, 'utf8') > this.#maximumFileBytes) {
|
||||
throw new Error('Agent diagnostic record exceeds its file bound')
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
#enqueue(line: string): boolean {
|
||||
if (this.#pendingRecordCount >= this.#maximumQueuedRecords) {
|
||||
return false
|
||||
}
|
||||
this.#queuedLines.push(line)
|
||||
this.#pendingRecordCount += 1
|
||||
this.#scheduleDrain()
|
||||
return true
|
||||
}
|
||||
|
||||
#scheduleDrain(): void {
|
||||
if (this.#drainPromise !== undefined) {
|
||||
return
|
||||
}
|
||||
this.#drainPromise = Promise.resolve()
|
||||
.then(async () => await this.#drain())
|
||||
.catch(() => {
|
||||
// Diagnostic write failures are deliberately isolated from callers.
|
||||
})
|
||||
.finally(() => {
|
||||
this.#drainPromise = undefined
|
||||
if (this.#queuedLines.length > 0) {
|
||||
this.#scheduleDrain()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async #drain(): Promise<void> {
|
||||
while (this.#queuedLines.length > 0) {
|
||||
const lines = this.#queuedLines.splice(0)
|
||||
try {
|
||||
await this.#writeLines(lines)
|
||||
} catch {
|
||||
// Drop this bounded batch. Diagnostics may not affect the protocol.
|
||||
} finally {
|
||||
this.#pendingRecordCount -= lines.length
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #waitForIdle(): Promise<void> {
|
||||
while (this.#pendingRecordCount > 0) {
|
||||
const drain = this.#drainPromise
|
||||
if (drain === undefined) {
|
||||
this.#scheduleDrain()
|
||||
} else {
|
||||
await drain
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #writeLines(lines: readonly string[]): Promise<void> {
|
||||
ensurePrivateDirectory(resolve(this.directoryPath, '..'), {
|
||||
create: false
|
||||
})
|
||||
ensurePrivateDirectoryTree(
|
||||
this.directoryPath,
|
||||
resolve(this.directoryPath, '..')
|
||||
)
|
||||
const releaseLock = await acquireDiagnosticLock(
|
||||
resolve(this.directoryPath, AGENT_DIAGNOSTIC_LOCK_FILE_NAME)
|
||||
)
|
||||
try {
|
||||
let nextLine = 0
|
||||
while (nextLine < lines.length) {
|
||||
let currentBytes = await privateFileSize(this.currentFilePath)
|
||||
if (currentBytes >= this.#maximumFileBytes) {
|
||||
await this.#rotate()
|
||||
currentBytes = 0
|
||||
}
|
||||
const availableBytes = this.#maximumFileBytes - currentBytes
|
||||
let batchBytes = 0
|
||||
let batchEnd = nextLine
|
||||
while (batchEnd < lines.length) {
|
||||
const lineBytes = Buffer.byteLength(lines[batchEnd]!, 'utf8')
|
||||
if (batchBytes + lineBytes > availableBytes) {
|
||||
break
|
||||
}
|
||||
batchBytes += lineBytes
|
||||
batchEnd += 1
|
||||
}
|
||||
if (batchEnd === nextLine) {
|
||||
await this.#rotate()
|
||||
continue
|
||||
}
|
||||
await appendPrivateFile(
|
||||
this.currentFilePath,
|
||||
lines.slice(nextLine, batchEnd).join('')
|
||||
)
|
||||
nextLine = batchEnd
|
||||
}
|
||||
} finally {
|
||||
releaseLock()
|
||||
}
|
||||
}
|
||||
|
||||
async #rotate(): Promise<void> {
|
||||
const oldest = rotatedPath(
|
||||
this.currentFilePath,
|
||||
this.#fileCount - 1
|
||||
)
|
||||
try {
|
||||
unlinkOwnedPrivateFile(oldest)
|
||||
} catch (error) {
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
for (let index = this.#fileCount - 2; index >= 0; index -= 1) {
|
||||
const source = rotatedPath(this.currentFilePath, index)
|
||||
const target = rotatedPath(this.currentFilePath, index + 1)
|
||||
try {
|
||||
assertPrivateRegularFile(source)
|
||||
await rename(source, target)
|
||||
} catch (error) {
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function acquireDiagnosticLock(
|
||||
path: string
|
||||
): Promise<() => void> {
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < AGENT_DIAGNOSTIC_LOCK_ATTEMPTS;
|
||||
attempt += 1
|
||||
) {
|
||||
try {
|
||||
const descriptor = await open(
|
||||
path,
|
||||
constants.O_CREAT |
|
||||
constants.O_EXCL |
|
||||
constants.O_WRONLY |
|
||||
(constants.O_NOFOLLOW ?? 0),
|
||||
0o600
|
||||
)
|
||||
try {
|
||||
if (process.platform !== 'win32') {
|
||||
await descriptor.chmod(0o600)
|
||||
}
|
||||
} finally {
|
||||
await descriptor.close()
|
||||
}
|
||||
assertPrivateRegularFile(path)
|
||||
return () => {
|
||||
unlinkOwnedPrivateFile(path)
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isNodeError(error) || error.code !== 'EEXIST') {
|
||||
throw error
|
||||
}
|
||||
assertPrivateRegularFile(path)
|
||||
await new Promise<void>((resolveRetry) => {
|
||||
setTimeout(resolveRetry, AGENT_DIAGNOSTIC_LOCK_RETRY_MS)
|
||||
})
|
||||
}
|
||||
}
|
||||
throw new Error('Agent diagnostic file is busy')
|
||||
}
|
||||
|
||||
async function privateFileSize(path: string): Promise<number> {
|
||||
try {
|
||||
assertPrivateRegularFile(path)
|
||||
return (await lstat(path)).size
|
||||
} catch (error) {
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
async function appendPrivateFile(
|
||||
path: string,
|
||||
contents: string
|
||||
): Promise<void> {
|
||||
const descriptor = await open(
|
||||
path,
|
||||
constants.O_CREAT |
|
||||
constants.O_APPEND |
|
||||
constants.O_WRONLY |
|
||||
(constants.O_NOFOLLOW ?? 0),
|
||||
0o600
|
||||
)
|
||||
try {
|
||||
if (process.platform !== 'win32') {
|
||||
await descriptor.chmod(0o600)
|
||||
}
|
||||
await descriptor.writeFile(contents, 'utf8')
|
||||
} finally {
|
||||
await descriptor.close()
|
||||
}
|
||||
assertPrivateRegularFile(path)
|
||||
}
|
||||
|
||||
export function diagnosticDirectoryForStateDirectory(
|
||||
stateDirectoryInput: string
|
||||
): string {
|
||||
return resolve(stateDirectoryInput, AGENT_DIAGNOSTIC_DIRECTORY_NAME)
|
||||
}
|
||||
|
||||
export function readAgentDiagnostics(
|
||||
stateDirectoryInput: string,
|
||||
options: Pick<
|
||||
AgentDiagnosticLogOptions,
|
||||
'maximumFileBytes' | 'fileCount'
|
||||
> = {}
|
||||
): AgentDiagnosticRecord[] {
|
||||
const directory = diagnosticDirectoryForStateDirectory(
|
||||
resolve(stateDirectoryInput)
|
||||
)
|
||||
const current = resolve(directory, AGENT_DIAGNOSTIC_FILE_NAME)
|
||||
const maximumFileBytes =
|
||||
boundedInteger(
|
||||
options.maximumFileBytes ??
|
||||
DEFAULT_AGENT_DIAGNOSTIC_MAXIMUM_FILE_BYTES,
|
||||
512,
|
||||
1024 * 1024,
|
||||
'Agent diagnostic file size'
|
||||
)
|
||||
const fileCount =
|
||||
boundedInteger(
|
||||
options.fileCount ?? DEFAULT_AGENT_DIAGNOSTIC_FILE_COUNT,
|
||||
1,
|
||||
8,
|
||||
'Agent diagnostic file count'
|
||||
)
|
||||
const output: AgentDiagnosticRecord[] = []
|
||||
for (let index = fileCount - 1; index >= 0; index -= 1) {
|
||||
const path = rotatedPath(current, index)
|
||||
let contents: string
|
||||
try {
|
||||
contents = readPrivateFile(path, maximumFileBytes).toString('utf8')
|
||||
} catch (error) {
|
||||
if (isNodeError(error) && error.code === 'ENOENT') {
|
||||
continue
|
||||
}
|
||||
throw error
|
||||
}
|
||||
for (const line of contents.split('\n')) {
|
||||
if (line.length === 0) {
|
||||
continue
|
||||
}
|
||||
const parsed = parseDiagnosticRecord(line)
|
||||
if (parsed !== undefined) {
|
||||
output.push(parsed)
|
||||
}
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
export function summarizeDiagnosticError(error: unknown): {
|
||||
name: string
|
||||
code?: string
|
||||
} {
|
||||
const name = diagnosticErrorName(error)
|
||||
const candidate =
|
||||
error !== null && typeof error === 'object' && 'code' in error
|
||||
? (error as { code?: unknown }).code
|
||||
: undefined
|
||||
const code =
|
||||
typeof candidate === 'string' &&
|
||||
SAFE_DIAGNOSTIC_ERROR_CODES.has(candidate)
|
||||
? candidate
|
||||
: undefined
|
||||
return {
|
||||
name,
|
||||
...(code === undefined ? {} : { code })
|
||||
}
|
||||
}
|
||||
|
||||
function diagnosticErrorName(error: unknown): string {
|
||||
if (error instanceof TypeError) {
|
||||
return 'TypeError'
|
||||
}
|
||||
if (error instanceof RangeError) {
|
||||
return 'RangeError'
|
||||
}
|
||||
if (error instanceof SyntaxError) {
|
||||
return 'SyntaxError'
|
||||
}
|
||||
return error instanceof Error ? 'Error' : 'NonError'
|
||||
}
|
||||
|
||||
const SAFE_DIAGNOSTIC_ERROR_CODES = new Set([
|
||||
'EACCES',
|
||||
'EADDRINUSE',
|
||||
'ECONNREFUSED',
|
||||
'ECONNRESET',
|
||||
'EEXIST',
|
||||
'EIO',
|
||||
'EISDIR',
|
||||
'ELOOP',
|
||||
'EMFILE',
|
||||
'ENAMETOOLONG',
|
||||
'ENFILE',
|
||||
'ENOENT',
|
||||
'ENOSPC',
|
||||
'ENOTDIR',
|
||||
'EPERM',
|
||||
'EPIPE',
|
||||
'EROFS',
|
||||
'ESRCH',
|
||||
'ETIMEDOUT'
|
||||
] as const)
|
||||
|
||||
function parseDiagnosticRecord(line: string): AgentDiagnosticRecord | undefined {
|
||||
try {
|
||||
const value: unknown = JSON.parse(line)
|
||||
if (
|
||||
value === null ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value)
|
||||
) {
|
||||
return undefined
|
||||
}
|
||||
const record = value as Partial<AgentDiagnosticRecord>
|
||||
if (
|
||||
record.formatVersion !== 1 ||
|
||||
typeof record.timestamp !== 'string' ||
|
||||
(record.level !== 'info' && record.level !== 'error') ||
|
||||
typeof record.event !== 'string' ||
|
||||
!isDiagnosticEvent(record.event) ||
|
||||
!Number.isSafeInteger(record.pid) ||
|
||||
(record.pid ?? 0) <= 0
|
||||
) {
|
||||
return undefined
|
||||
}
|
||||
return record as AgentDiagnosticRecord
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function rotatedPath(currentPath: string, index: number): string {
|
||||
return index === 0 ? currentPath : `${currentPath}.${index}`
|
||||
}
|
||||
|
||||
function optionalToken<Key extends 'daemonBootId' | 'reason' | 'runtimeId'>(
|
||||
key: Key,
|
||||
value: string | undefined,
|
||||
maximumLength: number
|
||||
): Partial<Record<Key, string>> {
|
||||
if (
|
||||
value === undefined ||
|
||||
value.length > maximumLength ||
|
||||
!agentIdentifierSchema.safeParse(value).success
|
||||
) {
|
||||
return {}
|
||||
}
|
||||
return { [key]: value } as Record<Key, string>
|
||||
}
|
||||
|
||||
function isDiagnosticEvent(value: string): value is AgentDiagnosticEvent {
|
||||
return DIAGNOSTIC_EVENTS.has(value as AgentDiagnosticEvent)
|
||||
}
|
||||
|
||||
const DIAGNOSTIC_EVENTS = new Set<AgentDiagnosticEvent>([
|
||||
'daemon.starting',
|
||||
'daemon.ready',
|
||||
'daemon.start.failed',
|
||||
'daemon.stopping',
|
||||
'daemon.stopped',
|
||||
'daemon.stop.failed',
|
||||
'detached.launching',
|
||||
'detached.spawned',
|
||||
'connection.attached',
|
||||
'connection.closed',
|
||||
'connection.failed',
|
||||
'recovery.started',
|
||||
'recovery.succeeded',
|
||||
'recovery.failed',
|
||||
'runtime.starting',
|
||||
'runtime.started',
|
||||
'runtime.start.failed',
|
||||
'runtime.exited'
|
||||
])
|
||||
@@ -6,6 +6,7 @@ export * from './cli'
|
||||
export * from './controller-registry'
|
||||
export * from './daemon'
|
||||
export * from './detached-agent-lifecycle'
|
||||
export * from './diagnostic-log'
|
||||
export * from './direct-linux-stdio-process-owner'
|
||||
export * from './errors'
|
||||
export * from './entry'
|
||||
|
||||
@@ -76,6 +76,7 @@ export class PrivateEndpoint {
|
||||
readonly #challenge: InstallationChallengeVerifier
|
||||
readonly #controllers: ControllerRegistry
|
||||
readonly #onAttach: (attach: AuthenticatedAttach) => void | Promise<void>
|
||||
readonly #onConnectionFailure?: (error: unknown) => void
|
||||
readonly #installationId: string
|
||||
readonly #binaryDigest: string
|
||||
readonly #daemonBootId: string
|
||||
@@ -92,6 +93,7 @@ export class PrivateEndpoint {
|
||||
challenge: InstallationChallengeVerifier
|
||||
controllers: ControllerRegistry
|
||||
onAttach: (attach: AuthenticatedAttach) => void | Promise<void>
|
||||
onConnectionFailure?: (error: unknown) => void
|
||||
installationId: string
|
||||
binaryDigest: string
|
||||
daemonBootId: string
|
||||
@@ -103,6 +105,7 @@ export class PrivateEndpoint {
|
||||
this.#challenge = options.challenge
|
||||
this.#controllers = options.controllers
|
||||
this.#onAttach = options.onAttach
|
||||
this.#onConnectionFailure = options.onConnectionFailure
|
||||
this.#installationId = agentIdentifierSchema.parse(options.installationId)
|
||||
this.#binaryDigest = sha256DigestSchema.parse(options.binaryDigest)
|
||||
this.#daemonBootId = agentIdentifierSchema.parse(options.daemonBootId)
|
||||
@@ -141,7 +144,10 @@ export class PrivateEndpoint {
|
||||
socket.once('close', () => {
|
||||
this.#sockets.delete(socket)
|
||||
})
|
||||
void this.#authenticate(socket).catch(() => socket.destroy())
|
||||
void this.#authenticate(socket).catch((error: unknown) => {
|
||||
this.#onConnectionFailure?.(error)
|
||||
socket.destroy()
|
||||
})
|
||||
})
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const server = this.#server
|
||||
|
||||
@@ -122,6 +122,15 @@ export class AgentProtocolServer {
|
||||
connectionId: string
|
||||
category: AgentProtocolFailureCategory
|
||||
}) => void
|
||||
readonly #onConnectionClose?: (input: {
|
||||
connectionId: string
|
||||
category?: AgentProtocolFailureCategory
|
||||
}) => void
|
||||
readonly #onRecovery?: (input: {
|
||||
connectionId: string
|
||||
outcome: 'started' | 'succeeded' | 'failed'
|
||||
reason?: 'invalid-request' | 'identity-mismatch' | 'takeover-rejected'
|
||||
}) => void
|
||||
readonly #connections = new Map<string, ProtocolConnection>()
|
||||
|
||||
constructor(options: {
|
||||
@@ -148,6 +157,15 @@ export class AgentProtocolServer {
|
||||
connectionId: string
|
||||
category: AgentProtocolFailureCategory
|
||||
}) => void
|
||||
onConnectionClose?: (input: {
|
||||
connectionId: string
|
||||
category?: AgentProtocolFailureCategory
|
||||
}) => void
|
||||
onRecovery?: (input: {
|
||||
connectionId: string
|
||||
outcome: 'started' | 'succeeded' | 'failed'
|
||||
reason?: 'invalid-request' | 'identity-mismatch' | 'takeover-rejected'
|
||||
}) => void
|
||||
incomingQueueLimits?: Partial<IncomingQueueLimits>
|
||||
}) {
|
||||
this.#controllers = options.controllers
|
||||
@@ -159,6 +177,8 @@ export class AgentProtocolServer {
|
||||
this.#onBlobFrame = options.onBlobFrame
|
||||
this.#authorizeBlobFrame = options.authorizeBlobFrame
|
||||
this.#onProtocolFailure = options.onProtocolFailure
|
||||
this.#onConnectionClose = options.onConnectionClose
|
||||
this.#onRecovery = options.onRecovery
|
||||
this.#incomingQueueLimits = incomingQueueLimits(
|
||||
options.incomingQueueLimits
|
||||
)
|
||||
@@ -239,12 +259,33 @@ export class AgentProtocolServer {
|
||||
})
|
||||
},
|
||||
'controller/resume': async (params) => {
|
||||
const request = controllerResumeRequestSchema.parse(params)
|
||||
this.#onRecovery?.({
|
||||
connectionId: controller.connectionId,
|
||||
outcome: 'started'
|
||||
})
|
||||
let request: ReturnType<
|
||||
typeof controllerResumeRequestSchema.parse
|
||||
>
|
||||
try {
|
||||
request = controllerResumeRequestSchema.parse(params)
|
||||
} catch (error) {
|
||||
this.#onRecovery?.({
|
||||
connectionId: controller.connectionId,
|
||||
outcome: 'failed',
|
||||
reason: 'invalid-request'
|
||||
})
|
||||
throw error
|
||||
}
|
||||
const status = daemonStatusSchema.parse(await this.#status())
|
||||
if (
|
||||
request.daemonBootId !== status.daemonBootId ||
|
||||
request.previousGeneration >= controller.generation
|
||||
) {
|
||||
this.#onRecovery?.({
|
||||
connectionId: controller.connectionId,
|
||||
outcome: 'failed',
|
||||
reason: 'identity-mismatch'
|
||||
})
|
||||
return controllerResumeResultSchema.parse({
|
||||
resumed: false,
|
||||
generation: controller.generation,
|
||||
@@ -263,6 +304,11 @@ export class AgentProtocolServer {
|
||||
request
|
||||
)
|
||||
} catch {
|
||||
this.#onRecovery?.({
|
||||
connectionId: controller.connectionId,
|
||||
outcome: 'failed',
|
||||
reason: 'takeover-rejected'
|
||||
})
|
||||
return controllerResumeResultSchema.parse({
|
||||
resumed: false,
|
||||
generation: controller.generation,
|
||||
@@ -276,6 +322,10 @@ export class AgentProtocolServer {
|
||||
this.#connections
|
||||
.get(request.previousConnectionId)
|
||||
?.fence()
|
||||
this.#onRecovery?.({
|
||||
connectionId: controller.connectionId,
|
||||
outcome: 'succeeded'
|
||||
})
|
||||
return controllerResumeResultSchema.parse({
|
||||
resumed: true,
|
||||
generation: resumed.generation,
|
||||
@@ -293,6 +343,10 @@ export class AgentProtocolServer {
|
||||
onBlobFrame: this.#onBlobFrame,
|
||||
incomingQueueLimits: this.#incomingQueueLimits,
|
||||
onClose: (category) => {
|
||||
this.#onConnectionClose?.({
|
||||
connectionId: controller.connectionId,
|
||||
...(category === undefined ? {} : { category })
|
||||
})
|
||||
if (category !== undefined) {
|
||||
this.#onProtocolFailure?.({
|
||||
connectionId: controller.connectionId,
|
||||
|
||||
@@ -273,6 +273,7 @@ function harness(input: {
|
||||
dispatch: ReturnType<typeof vi.fn>
|
||||
finalizePrompt: ReturnType<typeof vi.fn>
|
||||
}
|
||||
launchError?: Error
|
||||
} = {}) {
|
||||
const workMode = input.workMode ?? 'ask'
|
||||
let now = input.now ?? 1_000
|
||||
@@ -284,6 +285,9 @@ function harness(input: {
|
||||
scratch: string
|
||||
}> = []
|
||||
const lifecycle: string[] = []
|
||||
const diagnostics = {
|
||||
tryRecord: vi.fn()
|
||||
}
|
||||
const bridgeCloses = vi.fn(async () => {
|
||||
if (input.bridgeCloseError) {
|
||||
throw new Error('broker close failed')
|
||||
@@ -315,6 +319,9 @@ function harness(input: {
|
||||
})),
|
||||
launchProcess: vi.fn(async (launch) => {
|
||||
lifecycle.push('launch')
|
||||
if (input.launchError !== undefined) {
|
||||
throw input.launchError
|
||||
}
|
||||
launchModelBridges.push(launch.modelBridge)
|
||||
launches.push({
|
||||
workMode: launch.workMode,
|
||||
@@ -325,6 +332,7 @@ function harness(input: {
|
||||
: process
|
||||
}),
|
||||
now: () => now,
|
||||
diagnostics,
|
||||
outputSink: vi.fn(async (frame) => {
|
||||
await input.outputGate
|
||||
outputFrames.push(Buffer.from(frame.payload).toString())
|
||||
@@ -366,6 +374,7 @@ function harness(input: {
|
||||
process,
|
||||
launches,
|
||||
lifecycle,
|
||||
diagnostics,
|
||||
bridgeCloses,
|
||||
blobSink,
|
||||
get bridgeDispatch() {
|
||||
@@ -876,6 +885,56 @@ describe('RuntimeAcpBackend', () => {
|
||||
)
|
||||
)
|
||||
expect(fixture.bridgeCloses).toHaveBeenCalledOnce()
|
||||
await vi.waitFor(() =>
|
||||
expect(fixture.diagnostics.tryRecord).toHaveBeenCalledWith(
|
||||
'runtime.exited',
|
||||
{
|
||||
runtimeId: 'opencode',
|
||||
workMode: 'ask',
|
||||
outcome: 'failed'
|
||||
}
|
||||
)
|
||||
)
|
||||
expect(fixture.diagnostics.tryRecord).toHaveBeenCalledWith(
|
||||
'runtime.starting',
|
||||
{
|
||||
runtimeId: 'opencode',
|
||||
workMode: 'ask'
|
||||
}
|
||||
)
|
||||
expect(fixture.diagnostics.tryRecord).toHaveBeenCalledWith(
|
||||
'runtime.started',
|
||||
{
|
||||
runtimeId: 'opencode',
|
||||
workMode: 'ask'
|
||||
}
|
||||
)
|
||||
await fixture.backend.dispose()
|
||||
})
|
||||
|
||||
it('records a redacted Runtime launch failure at the unified preparation point', async () => {
|
||||
const launchError = new Error(
|
||||
'accepted Prompt and API key must never be persisted'
|
||||
)
|
||||
const fixture = harness({ launchError })
|
||||
await open(fixture)
|
||||
|
||||
await expect(
|
||||
invoke(
|
||||
fixture,
|
||||
'runtime/preparePrompt',
|
||||
fixture.preparation()
|
||||
)
|
||||
).rejects.toThrow('Runtime process launch failed')
|
||||
|
||||
expect(fixture.diagnostics.tryRecord).toHaveBeenCalledWith(
|
||||
'runtime.start.failed',
|
||||
{
|
||||
runtimeId: 'opencode',
|
||||
workMode: 'ask',
|
||||
error: launchError
|
||||
}
|
||||
)
|
||||
await fixture.backend.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@ import {
|
||||
type AgentFrame
|
||||
} from '../shared/agent-protocol'
|
||||
import { canonicalJson } from '../shared/agent-protocol/canonical'
|
||||
import type {
|
||||
AgentDiagnosticLog,
|
||||
AgentDiagnosticRecord
|
||||
} from './diagnostic-log'
|
||||
import {
|
||||
acpJournalCursorSchema,
|
||||
remoteOwnedPromptAttachRequestSchema,
|
||||
@@ -279,6 +283,7 @@ export type RuntimeAcpBackendOptions = {
|
||||
}) => ModelBridgeBrokerServer
|
||||
semanticPrompts?: SemanticPromptStore
|
||||
modelGateway?: AgentModelGateway
|
||||
diagnostics?: Pick<AgentDiagnosticLog, 'tryRecord'>
|
||||
now?: () => number
|
||||
limits?: Partial<RuntimeAcpBackendLimits>
|
||||
}
|
||||
@@ -1106,6 +1111,10 @@ export class RuntimeAcpBackend {
|
||||
|
||||
if (binding.process === undefined) {
|
||||
let process: RuntimeAcpProcessOwner
|
||||
this.#options.diagnostics?.tryRecord('runtime.starting', {
|
||||
runtimeId: verified.manifest.runtimeId,
|
||||
workMode: preparation.workMode
|
||||
})
|
||||
try {
|
||||
process = await this.#options.launchProcess({
|
||||
manifest: verified.manifest,
|
||||
@@ -1126,7 +1135,12 @@ export class RuntimeAcpBackend {
|
||||
})
|
||||
})
|
||||
assertProcessIdentity(process.identity)
|
||||
} catch {
|
||||
} catch (error) {
|
||||
this.#options.diagnostics?.tryRecord('runtime.start.failed', {
|
||||
runtimeId: verified.manifest.runtimeId,
|
||||
workMode: preparation.workMode,
|
||||
error
|
||||
})
|
||||
await this.#closeModelBridge(binding, false).catch(
|
||||
() => undefined
|
||||
)
|
||||
@@ -1199,6 +1213,10 @@ export class RuntimeAcpBackend {
|
||||
'process'
|
||||
)
|
||||
}
|
||||
this.#options.diagnostics?.tryRecord('runtime.started', {
|
||||
runtimeId: verified.manifest.runtimeId,
|
||||
workMode: preparation.workMode
|
||||
})
|
||||
} else {
|
||||
try {
|
||||
await binding.process.beginPrompt({
|
||||
@@ -2162,6 +2180,8 @@ export class RuntimeAcpBackend {
|
||||
)
|
||||
let state: 'completed' | 'failed' | 'cancelled' | 'interrupted' =
|
||||
'interrupted'
|
||||
let diagnosticOutcome: AgentDiagnosticRecord['outcome'] =
|
||||
'interrupted'
|
||||
try {
|
||||
const reconciliation = await binding.process.reconcile()
|
||||
if (
|
||||
@@ -2172,10 +2192,29 @@ export class RuntimeAcpBackend {
|
||||
reconciliation.processTree === 'empty'
|
||||
) {
|
||||
state = terminalState(reconciliation.state)
|
||||
diagnosticOutcome = state
|
||||
}
|
||||
} catch {
|
||||
} catch (error) {
|
||||
binding.state = 'outcome-unknown'
|
||||
diagnosticOutcome = 'outcome-unknown'
|
||||
this.#options.diagnostics?.tryRecord('runtime.exited', {
|
||||
runtimeId: binding.resolvedBundle.entry.runtimeId,
|
||||
...(binding.workMode === undefined
|
||||
? {}
|
||||
: { workMode: binding.workMode }),
|
||||
outcome: diagnosticOutcome,
|
||||
error
|
||||
})
|
||||
this.#finishBinding(binding, state)
|
||||
return
|
||||
}
|
||||
this.#options.diagnostics?.tryRecord('runtime.exited', {
|
||||
runtimeId: binding.resolvedBundle.entry.runtimeId,
|
||||
...(binding.workMode === undefined
|
||||
? {}
|
||||
: { workMode: binding.workMode }),
|
||||
outcome: diagnosticOutcome
|
||||
})
|
||||
this.#finishBinding(binding, state)
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
AgentModelCallLedger,
|
||||
AgentModelGateway
|
||||
} from './agent-model-gateway'
|
||||
import type { AgentDiagnosticLog } from './diagnostic-log'
|
||||
|
||||
const BWRAP_EXECUTABLE = '/usr/bin/bwrap'
|
||||
|
||||
@@ -93,6 +94,7 @@ export type ProductionRuntimeCompositionOptions = {
|
||||
verificationEnvironment?: 'production' | 'test'
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
reportError?: (message: string, error: unknown) => void
|
||||
diagnostics?: Pick<AgentDiagnosticLog, 'tryRecord'>
|
||||
}
|
||||
|
||||
export async function createProductionRuntimeProtocol(
|
||||
@@ -304,6 +306,7 @@ export async function createProductionRuntimeProtocol(
|
||||
outputSink: options.outputSink,
|
||||
semanticPrompts,
|
||||
modelGateway,
|
||||
diagnostics: options.diagnostics,
|
||||
...(options.blobSink === undefined
|
||||
? {}
|
||||
: { blobSink: options.blobSink })
|
||||
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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}`
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
@@ -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
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+140
-12
@@ -1358,6 +1358,19 @@ describe('App', () => {
|
||||
await screen.findByRole('heading', {
|
||||
name: '今天想一起完成什么?'
|
||||
})
|
||||
const runtimeStatus = document.querySelector<HTMLElement>(
|
||||
'.runtime-status'
|
||||
)
|
||||
expect(runtimeStatus).not.toBeNull()
|
||||
expect(
|
||||
within(runtimeStatus!).getByText('就绪')
|
||||
).toBeInTheDocument()
|
||||
expect(runtimeStatus).toHaveAttribute(
|
||||
'aria-describedby',
|
||||
'topbar-runtime-detail'
|
||||
)
|
||||
expect(screen.getByText('Ready', { selector: '.sr-only' }))
|
||||
.toHaveAttribute('id', 'topbar-runtime-detail')
|
||||
expect(
|
||||
screen.getByText(
|
||||
/你好,我是 GoodBuddy。你可以直接向我提问、添加本地文件/u
|
||||
@@ -2049,6 +2062,25 @@ describe('App', () => {
|
||||
within(conversationList).queryByText('其他项目里的 Alpha')
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.change(search, { target: { value: 'missing topic' } })
|
||||
expect(
|
||||
await within(conversationList).findByText('没有匹配的对话')
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
within(conversationList).getByText(
|
||||
'请修改搜索关键词,或清除搜索后查看全部会话。'
|
||||
)
|
||||
).toBeInTheDocument()
|
||||
fireEvent.click(
|
||||
within(conversationList).getByRole('button', {
|
||||
name: '清除搜索'
|
||||
})
|
||||
)
|
||||
expect(search).toHaveValue('')
|
||||
expect(
|
||||
await within(conversationList).findByText('标题里的 Alpha')
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps Settings open when the interface language changes', async () => {
|
||||
@@ -2235,7 +2267,7 @@ describe('App', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('does not disturb startup when updates are current or offline', async () => {
|
||||
it('keeps current-version checks quiet and reports startup check failures', async () => {
|
||||
const currentResult = {
|
||||
updateAvailable: false,
|
||||
currentVersion: '0.8.4',
|
||||
@@ -2252,7 +2284,11 @@ describe('App', () => {
|
||||
const check = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(currentResult)
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.mockRejectedValueOnce(
|
||||
new Error(
|
||||
"Error invoking remote method 'application:update:check': TypeError: fetch failed"
|
||||
)
|
||||
)
|
||||
api.updates = {
|
||||
getSettings: vi.fn(async () => ({
|
||||
checkUpdatesOnStartup: true,
|
||||
@@ -2289,13 +2325,39 @@ describe('App', () => {
|
||||
render(<App />)
|
||||
await waitFor(() => expect(check).toHaveBeenCalledTimes(2))
|
||||
expect(
|
||||
screen.queryByText(/发现 GoodBuddy|版本检查失败/u)
|
||||
).not.toBeInTheDocument()
|
||||
await screen.findByRole('alert')
|
||||
).toHaveTextContent(
|
||||
'启动更新检查失败(GitHub):无法连接更新源,请检查网络或代理后重试'
|
||||
)
|
||||
} finally {
|
||||
delete api.updates
|
||||
}
|
||||
})
|
||||
|
||||
it('shows a recoverable recent-conversation load failure', async () => {
|
||||
vi.mocked(api.projects.list)
|
||||
.mockRejectedValueOnce(new Error('database busy'))
|
||||
.mockResolvedValueOnce([project])
|
||||
|
||||
render(<App />)
|
||||
|
||||
const loadError = await screen.findByRole('alert')
|
||||
expect(loadError).toHaveTextContent('最近会话加载失败')
|
||||
expect(loadError).toHaveTextContent('database busy')
|
||||
fireEvent.click(
|
||||
within(loadError).getByRole('button', {
|
||||
name: '重新读取会话'
|
||||
})
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(api.projects.list).toHaveBeenCalledTimes(2)
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('最近会话加载失败'))
|
||||
.not.toBeInTheDocument()
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps rendering when an older preload has no browser bridge', async () => {
|
||||
Object.defineProperty(window, 'goodbuddy', {
|
||||
configurable: true,
|
||||
@@ -4134,9 +4196,10 @@ describe('App', () => {
|
||||
fireEvent.change(await screen.findByLabelText('默认工作区目录'), {
|
||||
target: { value: 'C:\\Unsaved from App' }
|
||||
})
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: '知识库' })
|
||||
)
|
||||
const knowledgeNavigation = screen.getByRole('button', {
|
||||
name: '知识库'
|
||||
})
|
||||
fireEvent.click(knowledgeNavigation)
|
||||
|
||||
expect(
|
||||
screen.getByRole('heading', { name: '设置中心' })
|
||||
@@ -4150,6 +4213,43 @@ describe('App', () => {
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: '知识库' })
|
||||
).toBeVisible()
|
||||
await waitFor(() => expect(knowledgeNavigation).toHaveFocus())
|
||||
})
|
||||
|
||||
it('restores focus outside Settings after closing the page', async () => {
|
||||
render(<App />)
|
||||
|
||||
await screen.findByLabelText('向 GoodBuddy 提问')
|
||||
const settingsTrigger = screen.getByRole('button', {
|
||||
name: /本地工作区/u
|
||||
})
|
||||
fireEvent.click(settingsTrigger)
|
||||
await screen.findByRole('heading', { name: '设置中心' })
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: '关闭设置' })
|
||||
)
|
||||
|
||||
await waitFor(() => expect(settingsTrigger).toHaveFocus())
|
||||
})
|
||||
|
||||
it('focuses the Composer after closing automatically opened Settings', async () => {
|
||||
vi.mocked(api.agent.getStatus).mockResolvedValueOnce({
|
||||
id: 'setup',
|
||||
label: '未配置',
|
||||
available: false,
|
||||
supportsToolExecution: false,
|
||||
detail: '尚未配置 Runtime'
|
||||
})
|
||||
render(<App />)
|
||||
|
||||
await screen.findByRole('heading', { name: '设置中心' })
|
||||
const composer = screen.getByLabelText('向 GoodBuddy 提问')
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: '关闭设置' })
|
||||
)
|
||||
|
||||
await waitFor(() => expect(composer).toHaveFocus())
|
||||
})
|
||||
|
||||
it('updates and removes the composer shortcut hint immediately after saving Settings', async () => {
|
||||
@@ -5043,6 +5143,32 @@ describe('App', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('associates attachment errors with the Composer controls', async () => {
|
||||
vi.mocked(api.context.selectFiles).mockRejectedValueOnce(
|
||||
new Error('文件解析失败,请重新选择')
|
||||
)
|
||||
render(<App />)
|
||||
|
||||
const addButton = await screen.findByLabelText('添加附件')
|
||||
const input = screen.getByLabelText('向 GoodBuddy 提问')
|
||||
fireEvent.click(addButton)
|
||||
|
||||
const error = await screen.findByRole('alert', {
|
||||
name: '文件解析失败,请重新选择'
|
||||
})
|
||||
expect(error).toHaveAttribute('id', 'composer-context-error')
|
||||
expect(input).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(input).toHaveAttribute(
|
||||
'aria-describedby',
|
||||
'composer-context-error'
|
||||
)
|
||||
expect(addButton).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(addButton).toHaveAttribute(
|
||||
'aria-describedby',
|
||||
'composer-context-error'
|
||||
)
|
||||
})
|
||||
|
||||
it('sends and renders five selected images together', async () => {
|
||||
const imageAttachments = Array.from({ length: 5 }, (_, index) => ({
|
||||
id: `00000000-0000-4000-8000-00000000031${index}`,
|
||||
@@ -5279,11 +5405,13 @@ describe('App', () => {
|
||||
newConversationListener?.()
|
||||
})
|
||||
|
||||
expect(
|
||||
screen.getAllByRole('button', {
|
||||
name: /^更多会话操作/u
|
||||
})
|
||||
).toHaveLength(2)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getAllByRole('button', {
|
||||
name: /^更多会话操作/u
|
||||
})
|
||||
).toHaveLength(2)
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a workspace Markdown file in the right-side preview', async () => {
|
||||
|
||||
+207
-31
@@ -222,7 +222,10 @@ import {
|
||||
type KeepAliveCacheEntry
|
||||
} from './keep-alive-cache'
|
||||
import { activateModalFocus, trapTabFocus } from './dialog-focus'
|
||||
import { displayErrorMessage } from './error-message'
|
||||
import {
|
||||
displayErrorMessage,
|
||||
displayNetworkAwareErrorMessage
|
||||
} from './error-message'
|
||||
import { getProjectDisplayText } from './project-display'
|
||||
|
||||
const knowledgeWorkspaceRoute = createPreloadableComponent(
|
||||
@@ -2304,6 +2307,12 @@ function App(): React.JSX.Element {
|
||||
Record<string, BrowserLiveState>
|
||||
>({})
|
||||
const [view, setViewState] = useState<WorkspaceView>('chat')
|
||||
const settingsEntryFocusRef = useRef<HTMLElement | undefined>(
|
||||
undefined
|
||||
)
|
||||
const settingsExitFocusRef = useRef<HTMLElement | undefined>(
|
||||
undefined
|
||||
)
|
||||
const settingsLeaveRequesterRef = useRef<
|
||||
SettingsLeaveRequester | undefined
|
||||
>(undefined)
|
||||
@@ -2319,6 +2328,7 @@ function App(): React.JSX.Element {
|
||||
)
|
||||
const commitView = useCallback(
|
||||
(next: WorkspaceView): void => {
|
||||
const previous = viewRef.current
|
||||
const now = Date.now()
|
||||
const runningConversationIds = new Set(
|
||||
[...activeRuns.current.values()].map((run) => run.conversationId)
|
||||
@@ -2355,6 +2365,25 @@ function App(): React.JSX.Element {
|
||||
})
|
||||
)
|
||||
setViewState(next)
|
||||
if (previous === 'settings' && next !== 'settings') {
|
||||
const preferred = settingsExitFocusRef.current
|
||||
const returnTarget = settingsEntryFocusRef.current
|
||||
settingsExitFocusRef.current = undefined
|
||||
settingsEntryFocusRef.current = undefined
|
||||
requestAnimationFrame(() => {
|
||||
const target =
|
||||
preferred?.isConnected
|
||||
? preferred
|
||||
: returnTarget?.isConnected
|
||||
? returnTarget
|
||||
: next === 'chat'
|
||||
? inputRef.current
|
||||
: document.querySelector<HTMLElement>(
|
||||
`.primary-nav [aria-current="page"]`
|
||||
)
|
||||
target?.focus()
|
||||
})
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
@@ -2364,6 +2393,19 @@ function App(): React.JSX.Element {
|
||||
typeof update === 'function'
|
||||
? update(viewRef.current)
|
||||
: update
|
||||
if (
|
||||
viewRef.current !== 'settings' &&
|
||||
next === 'settings' &&
|
||||
!settingsEntryFocusRef.current?.isConnected
|
||||
) {
|
||||
const activeElement = document.activeElement
|
||||
settingsEntryFocusRef.current =
|
||||
activeElement instanceof HTMLElement &&
|
||||
activeElement !== document.body &&
|
||||
activeElement.isConnected
|
||||
? activeElement
|
||||
: undefined
|
||||
}
|
||||
if (viewRef.current === 'settings' && next !== 'settings') {
|
||||
const requestLeave = settingsLeaveRequesterRef.current
|
||||
if (requestLeave) {
|
||||
@@ -2442,6 +2484,9 @@ function App(): React.JSX.Element {
|
||||
const deferredSearchQuery = useDeferredValue(searchQuery)
|
||||
const [searchConversationSnapshot, setSearchConversationSnapshot] =
|
||||
useState(conversations)
|
||||
const [conversationLoadError, setConversationLoadError] =
|
||||
useState<string>()
|
||||
const [conversationLoadRetry, setConversationLoadRetry] = useState(0)
|
||||
const [conversationActionsId, setConversationActionsId] = useState('')
|
||||
const [confirmingConversationId, setConfirmingConversationId] =
|
||||
useState('')
|
||||
@@ -2629,7 +2674,15 @@ function App(): React.JSX.Element {
|
||||
requestAnimationFrame(() => sidebarToggleRef.current?.focus())
|
||||
}, [])
|
||||
const navigateFromSidebar = useCallback(
|
||||
(nextView: WorkspaceView): void => {
|
||||
(nextView: WorkspaceView, trigger: HTMLElement): void => {
|
||||
if (viewRef.current !== 'settings' && nextView === 'settings') {
|
||||
settingsEntryFocusRef.current = trigger
|
||||
} else if (
|
||||
viewRef.current === 'settings' &&
|
||||
nextView !== 'settings'
|
||||
) {
|
||||
settingsExitFocusRef.current = trigger
|
||||
}
|
||||
setView(nextView)
|
||||
if (narrowWindow) {
|
||||
closeNarrowSidebar()
|
||||
@@ -2849,6 +2902,7 @@ function App(): React.JSX.Element {
|
||||
return
|
||||
}
|
||||
startupUpdateCheckStartedRef.current = true
|
||||
let updateCheckSource: 'github' | 'mirror' | undefined
|
||||
void updates
|
||||
.getSettings()
|
||||
.then(async (settings) => {
|
||||
@@ -2865,6 +2919,7 @@ function App(): React.JSX.Element {
|
||||
if (!settings.checkUpdatesOnStartup) {
|
||||
return
|
||||
}
|
||||
updateCheckSource = settings.updateSource
|
||||
const result = await updates.check()
|
||||
if (result.updateAvailable) {
|
||||
notify({
|
||||
@@ -2877,7 +2932,27 @@ function App(): React.JSX.Element {
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.catch((reason: unknown) => {
|
||||
if (!updateCheckSource) {
|
||||
return
|
||||
}
|
||||
notify({
|
||||
tone: 'error',
|
||||
message: i18n.t('notices.startupUpdateCheckFailed', {
|
||||
ns: 'app',
|
||||
source: i18n.t(
|
||||
`notices.updateSources.${updateCheckSource}`,
|
||||
{ ns: 'app' }
|
||||
),
|
||||
error: displayNetworkAwareErrorMessage(
|
||||
reason,
|
||||
i18n.t('notices.updateCheckFailed', { ns: 'app' }),
|
||||
i18n.t('notices.updateCheckNetwork', { ns: 'app' })
|
||||
)
|
||||
}),
|
||||
dedupeKey: 'startup-update-check'
|
||||
})
|
||||
})
|
||||
}, [i18n, setView])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -4588,7 +4663,9 @@ function App(): React.JSX.Element {
|
||||
status:
|
||||
event.type === 'error' && !representedToolError
|
||||
? event.message
|
||||
: undefined,
|
||||
: event.type === 'done'
|
||||
? tRef.current('chat.status.taskCompleted')
|
||||
: undefined,
|
||||
contextCompression:
|
||||
event.type === 'error' &&
|
||||
message.contextCompression?.state === 'compressing'
|
||||
@@ -5346,19 +5423,18 @@ function App(): React.JSX.Element {
|
||||
)
|
||||
void initialization.catch((reason: unknown) => {
|
||||
if (active) {
|
||||
notify({
|
||||
tone: 'error',
|
||||
message:
|
||||
reason instanceof Error
|
||||
? reason.message
|
||||
: tRef.current('notices.projectReadFailed')
|
||||
})
|
||||
setConversationLoadError(
|
||||
displayErrorMessage(
|
||||
reason,
|
||||
tRef.current('notices.projectReadFailed')
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [notify, setActiveId])
|
||||
}, [conversationLoadRetry, setActiveId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeProjectId) {
|
||||
@@ -7958,6 +8034,23 @@ function App(): React.JSX.Element {
|
||||
|
||||
const mainSidebarOpen = narrowWindow && sidebarOpen
|
||||
const backgroundIsolated = mainSidebarOpen
|
||||
const runtimeState =
|
||||
runtimeSwitching ||
|
||||
!runtime ||
|
||||
runtimeStatusKey !== activeRuntimeSelectionKey
|
||||
? 'connecting'
|
||||
: runtime.available
|
||||
? 'ready'
|
||||
: 'unavailable'
|
||||
const runtimeDetailId = 'topbar-runtime-detail'
|
||||
const runtimeDetail =
|
||||
runtimeState === 'connecting'
|
||||
? t('runtime.connecting')
|
||||
: runtime?.detail ||
|
||||
(runtimeState === 'unavailable'
|
||||
? t('runtime.unavailable')
|
||||
: t('runtime.state.ready'))
|
||||
const composerContextErrorId = 'composer-context-error'
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
@@ -8037,7 +8130,9 @@ function App(): React.JSX.Element {
|
||||
className={
|
||||
view === 'chat' ? 'nav-item nav-item--active' : 'nav-item'
|
||||
}
|
||||
onClick={() => navigateFromSidebar('chat')}
|
||||
onClick={(event) =>
|
||||
navigateFromSidebar('chat', event.currentTarget)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<MessageSquare aria-hidden="true" size={17} />
|
||||
@@ -8052,7 +8147,9 @@ function App(): React.JSX.Element {
|
||||
: 'nav-item'
|
||||
}
|
||||
onFocus={() => preloadWorkspaceRouteOnIntent('magic-notes')}
|
||||
onClick={() => navigateFromSidebar('magic-notes')}
|
||||
onClick={(event) =>
|
||||
navigateFromSidebar('magic-notes', event.currentTarget)
|
||||
}
|
||||
onPointerEnter={() =>
|
||||
preloadWorkspaceRouteOnIntent('magic-notes')
|
||||
}
|
||||
@@ -8083,7 +8180,9 @@ function App(): React.JSX.Element {
|
||||
: 'nav-item'
|
||||
}
|
||||
onFocus={() => preloadWorkspaceRouteOnIntent('knowledge')}
|
||||
onClick={() => navigateFromSidebar('knowledge')}
|
||||
onClick={(event) =>
|
||||
navigateFromSidebar('knowledge', event.currentTarget)
|
||||
}
|
||||
onPointerEnter={() =>
|
||||
preloadWorkspaceRouteOnIntent('knowledge')
|
||||
}
|
||||
@@ -8099,7 +8198,9 @@ function App(): React.JSX.Element {
|
||||
? 'nav-item nav-item--active'
|
||||
: 'nav-item'
|
||||
}
|
||||
onClick={() => navigateFromSidebar('heartbeat')}
|
||||
onClick={(event) =>
|
||||
navigateFromSidebar('heartbeat', event.currentTarget)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<HeartPulse aria-hidden="true" size={17} />
|
||||
@@ -8123,7 +8224,9 @@ function App(): React.JSX.Element {
|
||||
: 'nav-item'
|
||||
}
|
||||
onFocus={() => preloadWorkspaceRouteOnIntent('activity')}
|
||||
onClick={() => navigateFromSidebar('activity')}
|
||||
onClick={(event) =>
|
||||
navigateFromSidebar('activity', event.currentTarget)
|
||||
}
|
||||
onPointerEnter={() =>
|
||||
preloadWorkspaceRouteOnIntent('activity')
|
||||
}
|
||||
@@ -8136,7 +8239,8 @@ function App(): React.JSX.Element {
|
||||
|
||||
<div className="conversation-list">
|
||||
<p className="section-label">{t('sidebar.recent')}</p>
|
||||
{filteredConversations.map((conversation) => {
|
||||
{!conversationLoadError &&
|
||||
filteredConversations.map((conversation) => {
|
||||
const conversationTasks =
|
||||
tasksByConversation.get(conversation.id) ?? []
|
||||
const tasksExpanded =
|
||||
@@ -8577,14 +8681,55 @@ function App(): React.JSX.Element {
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{filteredConversations.length === 0 && (
|
||||
<p className="conversation-empty">
|
||||
{activeProject?.kind === 'channel' &&
|
||||
!deferredSearchQuery.trim()
|
||||
? t('conversation.noRemote')
|
||||
: t('conversation.noMatches')}
|
||||
</p>
|
||||
)}
|
||||
{conversationLoadError ? (
|
||||
<div className="conversation-empty" role="alert">
|
||||
<strong>{t('conversation.loadFailed')}</strong>
|
||||
<span>{conversationLoadError}</span>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => {
|
||||
setConversationLoadError(undefined)
|
||||
setConversationLoadRetry((current) => current + 1)
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<RefreshCw aria-hidden="true" size={13} />
|
||||
{t('conversation.retryLoad')}
|
||||
</button>
|
||||
</div>
|
||||
) : filteredConversations.length === 0 ? (
|
||||
deferredSearchQuery.trim() ? (
|
||||
<div className="conversation-empty">
|
||||
<strong>{t('conversation.noMatches')}</strong>
|
||||
<span>{t('conversation.noMatchesDescription')}</span>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => setSearchQuery('')}
|
||||
type="button"
|
||||
>
|
||||
{t('conversation.clearSearch')}
|
||||
</button>
|
||||
</div>
|
||||
) : activeProject?.kind === 'channel' ? (
|
||||
<div className="conversation-empty">
|
||||
<strong>{t('conversation.noRemote')}</strong>
|
||||
<span>{t('chat.remote.waiting')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="conversation-empty">
|
||||
<strong>{t('conversation.empty')}</strong>
|
||||
<span>{t('conversation.emptyDescription')}</span>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={newConversation}
|
||||
type="button"
|
||||
>
|
||||
<MessageSquarePlus aria-hidden="true" size={13} />
|
||||
{t('sidebar.newConversation')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="sidebar-footer">
|
||||
@@ -8592,7 +8737,9 @@ function App(): React.JSX.Element {
|
||||
className="user-card"
|
||||
type="button"
|
||||
onFocus={() => preloadWorkspaceRouteOnIntent('settings')}
|
||||
onClick={() => navigateFromSidebar('settings')}
|
||||
onClick={(event) =>
|
||||
navigateFromSidebar('settings', event.currentTarget)
|
||||
}
|
||||
onPointerEnter={() =>
|
||||
preloadWorkspaceRouteOnIntent('settings')
|
||||
}
|
||||
@@ -8684,23 +8831,30 @@ function App(): React.JSX.Element {
|
||||
)}
|
||||
<div className="topbar__actions">
|
||||
<span
|
||||
aria-describedby={runtimeDetailId}
|
||||
className={
|
||||
runtime?.available
|
||||
runtimeState === 'ready'
|
||||
? 'runtime-status runtime-status--online'
|
||||
: 'runtime-status'
|
||||
}
|
||||
title={runtime?.detail}
|
||||
title={runtimeDetail}
|
||||
>
|
||||
<span className="runtime-status__dot" />
|
||||
<span className="runtime-status__label">
|
||||
{runtime?.label ?? t('runtime.detecting')}
|
||||
</span>
|
||||
<span className="runtime-status__state">
|
||||
{t(`runtime.state.${runtimeState}`)}
|
||||
</span>
|
||||
{runtime?.capability === 'image-generation' && (
|
||||
<span className="runtime-capability-badge">
|
||||
{t('runtime.imageGeneration')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="sr-only" id={runtimeDetailId}>
|
||||
{runtimeDetail}
|
||||
</span>
|
||||
<button
|
||||
aria-label={
|
||||
resolvedAppearanceTheme === 'dark'
|
||||
@@ -8886,6 +9040,10 @@ function App(): React.JSX.Element {
|
||||
{(attachments.length > 0 || selectingContextFiles) && (
|
||||
<div
|
||||
aria-busy={selectingContextFiles}
|
||||
aria-describedby={
|
||||
contextError ? composerContextErrorId : undefined
|
||||
}
|
||||
aria-invalid={contextError ? true : undefined}
|
||||
className="context-list"
|
||||
>
|
||||
{attachments.map((attachment) => (
|
||||
@@ -8979,6 +9137,10 @@ function App(): React.JSX.Element {
|
||||
)}
|
||||
<div className="composer__input">
|
||||
<textarea
|
||||
aria-describedby={
|
||||
contextError ? composerContextErrorId : undefined
|
||||
}
|
||||
aria-invalid={contextError ? true : undefined}
|
||||
aria-label={t('composer.inputLabel')}
|
||||
placeholder={`${
|
||||
runtime?.capability === 'image-generation'
|
||||
@@ -9050,11 +9212,15 @@ function App(): React.JSX.Element {
|
||||
role="group"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('composer.addAttachment')}
|
||||
aria-describedby={
|
||||
contextError ? composerContextErrorId : undefined
|
||||
}
|
||||
aria-invalid={contextError ? true : undefined}
|
||||
disabled={selectingContextFiles}
|
||||
onClick={() => void selectContextFiles()}
|
||||
title={t('composer.addAttachment')}
|
||||
type="button"
|
||||
>
|
||||
<Paperclip aria-hidden="true" size={18} />
|
||||
</button>
|
||||
@@ -9527,6 +9693,11 @@ function App(): React.JSX.Element {
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
aria-describedby={
|
||||
runtimeState !== 'ready'
|
||||
? runtimeDetailId
|
||||
: undefined
|
||||
}
|
||||
className="send-button"
|
||||
type="button"
|
||||
aria-label={
|
||||
@@ -9773,7 +9944,12 @@ function App(): React.JSX.Element {
|
||||
</div>
|
||||
)}
|
||||
{contextError && (
|
||||
<span className="composer-meta__error">
|
||||
<span
|
||||
aria-label={contextError}
|
||||
className="composer-meta__error"
|
||||
id={composerContextErrorId}
|
||||
role="alert"
|
||||
>
|
||||
{contextError}
|
||||
</span>
|
||||
)}
|
||||
|
||||
@@ -352,4 +352,143 @@ describe('ChatTimeline', () => {
|
||||
expect.stringContaining('父 Agent 最终回复')
|
||||
])
|
||||
})
|
||||
|
||||
it('uses one live source per event without announcing historical tool rows', () => {
|
||||
const messages: Message[] = [
|
||||
{
|
||||
id: 'working',
|
||||
role: 'assistant',
|
||||
content: 'streamed reply body',
|
||||
createdAt: 1_775_000_000_000,
|
||||
state: 'streaming',
|
||||
status: 'Preparing tools'
|
||||
},
|
||||
{
|
||||
id: 'approval',
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
createdAt: 1_775_000_000_001,
|
||||
state: 'complete',
|
||||
approval: {
|
||||
id: 'approval-1',
|
||||
title: 'Write workspace file',
|
||||
description: 'Update release.md',
|
||||
toolName: 'write_file'
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'failed',
|
||||
role: 'assistant',
|
||||
content: 'bounded failure context',
|
||||
createdAt: 1_775_000_000_002,
|
||||
state: 'error',
|
||||
status: 'Runtime connection failed'
|
||||
},
|
||||
{
|
||||
id: 'tool-history',
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
createdAt: 1_775_000_000_003,
|
||||
state: 'complete',
|
||||
tools: [
|
||||
{
|
||||
callId: 'tool-1',
|
||||
name: 'read_file',
|
||||
summary: 'Read the file',
|
||||
state: 'completed'
|
||||
}
|
||||
],
|
||||
subagents: [
|
||||
{
|
||||
childTaskId: 'subagent-1',
|
||||
expertId: 'expert-1',
|
||||
expertName: 'reviewer',
|
||||
routingMode: 'manual',
|
||||
state: 'completed'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'retrieval',
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
createdAt: 1_775_000_000_004,
|
||||
state: 'complete',
|
||||
status: 'Knowledge search complete',
|
||||
knowledgeRetrieval: {
|
||||
mode: 'always',
|
||||
state: 'succeeded',
|
||||
libraryCount: 1,
|
||||
resultCount: 2,
|
||||
durationMs: 20,
|
||||
usedChannels: ['fts'],
|
||||
warnings: []
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'compression',
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
createdAt: 1_775_000_000_005,
|
||||
state: 'complete',
|
||||
status: 'Context compression complete',
|
||||
contextCompression: {
|
||||
state: 'completed',
|
||||
estimatedBeforeTokens: 20_000,
|
||||
estimatedAfterTokens: 8_000
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
const { container } = render(
|
||||
<ChatTimeline
|
||||
artifactById={new Map()}
|
||||
conversationId="conversation-1"
|
||||
hiddenMessageCount={0}
|
||||
isUnusedConversation={false}
|
||||
locale="en-US"
|
||||
messageStartIndex={0}
|
||||
messages={messages}
|
||||
{...callbacks}
|
||||
retryContent=""
|
||||
totalMessageCount={messages.length}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.getByRole('status', { name: 'Preparing tools' })
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('status', {
|
||||
name: '等待审批:write_file'
|
||||
})
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('alert', {
|
||||
name: 'Runtime connection failed'
|
||||
})
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByText('streamed reply body')
|
||||
).not.toHaveAttribute('aria-live')
|
||||
expect(screen.getByLabelText('已完成', { selector: 'small' }))
|
||||
.not.toHaveAttribute('aria-live')
|
||||
expect(
|
||||
screen.getByLabelText('已完成', {
|
||||
selector: '.subagent-status-card__status'
|
||||
})
|
||||
).not.toHaveAttribute('aria-live')
|
||||
expect(
|
||||
screen.getByLabelText('Knowledge search complete')
|
||||
).not.toHaveAttribute('aria-live')
|
||||
expect(
|
||||
screen.getByLabelText('Context compression complete')
|
||||
).not.toHaveAttribute('aria-live')
|
||||
expect(
|
||||
container.querySelectorAll('.approval-card [aria-live="polite"]')
|
||||
).toHaveLength(1)
|
||||
expect(
|
||||
container.querySelectorAll('.message-retrieval-status[aria-live]')
|
||||
).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -213,7 +213,11 @@ function ToolExecutionList({
|
||||
<strong>{tool.name}</strong>
|
||||
<span>{tool.summary}</span>
|
||||
</span>
|
||||
<small>{t(`chat.tools.states.${tool.state}`)}</small>
|
||||
<small
|
||||
aria-label={t(`chat.tools.states.${tool.state}`)}
|
||||
>
|
||||
{t(`chat.tools.states.${tool.state}`)}
|
||||
</small>
|
||||
</summary>
|
||||
<div className="tool-execution__details">
|
||||
{tool.input && (
|
||||
@@ -292,6 +296,7 @@ const SubagentStatusCard = memo(function SubagentStatusCard({
|
||||
</small>
|
||||
</span>
|
||||
<span
|
||||
aria-label={t(`chat.subagents.states.${subagent.state}`)}
|
||||
className={`subagent-status-card__status subagent-status-card__status--${subagent.state}`}
|
||||
>
|
||||
<StateIcon aria-hidden="true" size={14} />
|
||||
@@ -678,8 +683,17 @@ function ChatMessageRowView({
|
||||
})}
|
||||
{message.knowledgeRetrieval && (
|
||||
<section
|
||||
aria-live="polite"
|
||||
aria-live={
|
||||
message.knowledgeRetrieval.state === 'failed'
|
||||
? 'assertive'
|
||||
: 'polite'
|
||||
}
|
||||
className={`message-retrieval-status message-retrieval-status--${message.knowledgeRetrieval.state}`}
|
||||
role={
|
||||
message.knowledgeRetrieval.state === 'failed'
|
||||
? 'alert'
|
||||
: 'status'
|
||||
}
|
||||
>
|
||||
<Library aria-hidden="true" size={14} />
|
||||
<div>
|
||||
@@ -804,6 +818,19 @@ function ChatMessageRowView({
|
||||
)}
|
||||
{message.approval && (
|
||||
<div className="approval-card">
|
||||
<span
|
||||
aria-atomic="true"
|
||||
aria-label={t('chat.approval.waiting', {
|
||||
tool: message.approval.toolName ?? message.approval.title
|
||||
})}
|
||||
aria-live="polite"
|
||||
className="sr-only"
|
||||
role="status"
|
||||
>
|
||||
{t('chat.approval.waiting', {
|
||||
tool: message.approval.toolName ?? message.approval.title
|
||||
})}
|
||||
</span>
|
||||
<ShieldCheck size={18} />
|
||||
<div>
|
||||
<strong>{message.approval.title}</strong>
|
||||
@@ -895,11 +922,27 @@ function ChatMessageRowView({
|
||||
)}
|
||||
{message.status && (
|
||||
<div
|
||||
aria-atomic="true"
|
||||
aria-label={message.status}
|
||||
aria-live={
|
||||
message.knowledgeRetrieval || compressionMarkers.length > 0
|
||||
? undefined
|
||||
: message.state === 'error'
|
||||
? 'assertive'
|
||||
: 'polite'
|
||||
}
|
||||
className={
|
||||
message.state === 'error'
|
||||
? 'message__status message__status--error'
|
||||
: 'message__status'
|
||||
}
|
||||
role={
|
||||
message.knowledgeRetrieval || compressionMarkers.length > 0
|
||||
? undefined
|
||||
: message.state === 'error'
|
||||
? 'alert'
|
||||
: 'status'
|
||||
}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
@@ -930,10 +973,12 @@ function ChatMessageRowView({
|
||||
{message.role === 'assistant' &&
|
||||
compressionMarkers.map((compression, index) => (
|
||||
<div
|
||||
aria-live="polite"
|
||||
aria-live={
|
||||
compression.state === 'failed' ? 'assertive' : 'polite'
|
||||
}
|
||||
className={`context-compression-event context-compression-event--${compression.state}`}
|
||||
key={`${compression.scope ?? 'conversation'}:${index}`}
|
||||
role="status"
|
||||
role={compression.state === 'failed' ? 'alert' : 'status'}
|
||||
>
|
||||
<span className="context-compression-event__line" />
|
||||
<span className="context-compression-event__label">
|
||||
|
||||
@@ -91,6 +91,11 @@ describe('FeedbackDialog', () => {
|
||||
value: '打开平台功能后,魔法笔记页签没有显示。'
|
||||
}
|
||||
})
|
||||
const diagnostics = screen.getByRole('checkbox', {
|
||||
name: '附加最近桌面诊断记录'
|
||||
})
|
||||
expect(diagnostics).not.toBeChecked()
|
||||
fireEvent.click(diagnostics)
|
||||
const submitButton = screen.getByRole('button', {
|
||||
name: '提交反馈'
|
||||
})
|
||||
@@ -120,6 +125,53 @@ describe('FeedbackDialog', () => {
|
||||
expect(submit.mock.calls[1]![0].clientRequestId).toBe(
|
||||
firstRequestId
|
||||
)
|
||||
expect(submit.mock.calls[0]![0].includeDiagnostics).toBe(true)
|
||||
expect(submit.mock.calls[1]![0].includeDiagnostics).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps an over-budget diagnostics draft and shows a field error', () => {
|
||||
installApi(
|
||||
vi.fn<DesktopApi['feedback']['submit']>(async () => ({
|
||||
ok: true,
|
||||
reference: 'GOODBUDDY-000016',
|
||||
duplicate: false
|
||||
}))
|
||||
)
|
||||
render(
|
||||
<FeedbackDialog
|
||||
appInfo={{
|
||||
name: 'GoodBuddy',
|
||||
version: '0.11.0',
|
||||
platform: 'win32',
|
||||
arch: 'x64',
|
||||
shortcut: 'Ctrl+Shift+Space'
|
||||
}}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
)
|
||||
const description = 'x'.repeat(3_399)
|
||||
fireEvent.change(screen.getByLabelText('标题'), {
|
||||
target: { value: 'Diagnostics budget' }
|
||||
})
|
||||
fireEvent.change(screen.getByLabelText('详细描述'), {
|
||||
target: { value: description }
|
||||
})
|
||||
fireEvent.click(
|
||||
screen.getByRole('checkbox', {
|
||||
name: '附加最近桌面诊断记录'
|
||||
})
|
||||
)
|
||||
expect(screen.getByLabelText('详细描述')).toHaveValue(
|
||||
description
|
||||
)
|
||||
expect(
|
||||
screen.getByText(
|
||||
'附加桌面诊断时,详细描述不能超过 3398 个字符;草稿已保留,请缩短后重试。'
|
||||
)
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('button', { name: '提交反馈' })
|
||||
).toBeDisabled()
|
||||
})
|
||||
|
||||
it('validates fields, traps focus, and closes with Escape', () => {
|
||||
|
||||
@@ -61,6 +61,7 @@ export function FeedbackDialog({
|
||||
: 'zh-CN'
|
||||
const titleId = useId()
|
||||
const descriptionId = useId()
|
||||
const diagnosticsDescriptionId = useId()
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
const categoryRef = useRef<HTMLSelectElement>(null)
|
||||
const titleRef = useRef<HTMLInputElement>(null)
|
||||
@@ -73,6 +74,8 @@ export function FeedbackDialog({
|
||||
const [category, setCategory] = useState<FeedbackCategory>('bug')
|
||||
const [title, setTitle] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [includeDiagnostics, setIncludeDiagnostics] =
|
||||
useState(false)
|
||||
const [contactEmail, setContactEmail] = useState('')
|
||||
const [screenshot, setScreenshot] = useState<ScreenshotDraft>()
|
||||
const [screenshotProcessing, setScreenshotProcessing] =
|
||||
@@ -214,6 +217,19 @@ export function FeedbackDialog({
|
||||
'feedback.validation.descriptionMinimum'
|
||||
)
|
||||
}
|
||||
const maximumDescriptionCharacters = includeDiagnostics
|
||||
? feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
: feedbackLimits.maximumDescriptionCharacters
|
||||
if (
|
||||
description.trim().length > maximumDescriptionCharacters
|
||||
) {
|
||||
errors.description = t(
|
||||
includeDiagnostics
|
||||
? 'feedback.validation.descriptionMaximumWithDiagnostics'
|
||||
: 'feedback.validation.descriptionMaximum',
|
||||
{ maximum: maximumDescriptionCharacters }
|
||||
)
|
||||
}
|
||||
if (
|
||||
contactEmail.trim() &&
|
||||
!feedbackContactEmailSchema.safeParse(contactEmail.trim())
|
||||
@@ -228,6 +244,10 @@ export function FeedbackDialog({
|
||||
title.trim().length > 0 &&
|
||||
description.trim().length >=
|
||||
feedbackLimits.minimumDescriptionCharacters &&
|
||||
description.trim().length <=
|
||||
(includeDiagnostics
|
||||
? feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
: feedbackLimits.maximumDescriptionCharacters) &&
|
||||
(!contactEmail.trim() ||
|
||||
feedbackContactEmailSchema.safeParse(contactEmail.trim())
|
||||
.success) &&
|
||||
@@ -260,6 +280,7 @@ export function FeedbackDialog({
|
||||
category,
|
||||
title,
|
||||
description,
|
||||
includeDiagnostics,
|
||||
...(contactEmail.trim()
|
||||
? { contactEmail: contactEmail.trim() }
|
||||
: {}),
|
||||
@@ -451,16 +472,27 @@ export function FeedbackDialog({
|
||||
aria-label={t('feedback.fields.description')}
|
||||
aria-invalid={Boolean(fieldErrors.description)}
|
||||
disabled={submitting}
|
||||
maxLength={
|
||||
feedbackLimits.maximumDescriptionCharacters
|
||||
}
|
||||
onBlur={() =>
|
||||
setFieldErrors((current) => ({
|
||||
...current,
|
||||
description:
|
||||
description.trim().length >=
|
||||
feedbackLimits.minimumDescriptionCharacters
|
||||
? undefined
|
||||
feedbackLimits.minimumDescriptionCharacters
|
||||
? description.trim().length <=
|
||||
(includeDiagnostics
|
||||
? feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
: feedbackLimits.maximumDescriptionCharacters)
|
||||
? undefined
|
||||
: t(
|
||||
includeDiagnostics
|
||||
? 'feedback.validation.descriptionMaximumWithDiagnostics'
|
||||
: 'feedback.validation.descriptionMaximum',
|
||||
{
|
||||
maximum: includeDiagnostics
|
||||
? feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
: feedbackLimits.maximumDescriptionCharacters
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'feedback.validation.descriptionMinimum'
|
||||
)
|
||||
@@ -485,7 +517,9 @@ export function FeedbackDialog({
|
||||
{t('feedback.fields.characterCount', {
|
||||
count: description.length,
|
||||
maximum:
|
||||
feedbackLimits.maximumDescriptionCharacters
|
||||
includeDiagnostics
|
||||
? feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
: feedbackLimits.maximumDescriptionCharacters
|
||||
})}
|
||||
</small>
|
||||
{fieldErrors.description && (
|
||||
@@ -495,6 +529,48 @@ export function FeedbackDialog({
|
||||
)}
|
||||
</label>
|
||||
|
||||
<label className="feedback-diagnostics-option">
|
||||
<input
|
||||
aria-label={t('feedback.diagnostics.label')}
|
||||
checked={includeDiagnostics}
|
||||
disabled={submitting}
|
||||
onChange={(event) => {
|
||||
const selected = event.target.checked
|
||||
setIncludeDiagnostics(selected)
|
||||
const maximum = selected
|
||||
? feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
: feedbackLimits.maximumDescriptionCharacters
|
||||
setFieldErrors((current) => ({
|
||||
...current,
|
||||
description:
|
||||
description.trim().length <
|
||||
feedbackLimits.minimumDescriptionCharacters
|
||||
? t(
|
||||
'feedback.validation.descriptionMinimum'
|
||||
)
|
||||
: description.trim().length > maximum
|
||||
? t(
|
||||
selected
|
||||
? 'feedback.validation.descriptionMaximumWithDiagnostics'
|
||||
: 'feedback.validation.descriptionMaximum',
|
||||
{ maximum }
|
||||
)
|
||||
: undefined
|
||||
}))
|
||||
}}
|
||||
type="checkbox"
|
||||
aria-describedby={diagnosticsDescriptionId}
|
||||
/>
|
||||
<span>
|
||||
<strong>
|
||||
{t('feedback.diagnostics.label')}
|
||||
</strong>
|
||||
<small id={diagnosticsDescriptionId}>
|
||||
{t('feedback.diagnostics.description')}
|
||||
</small>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>{t('feedback.fields.contactEmail')}</span>
|
||||
<input
|
||||
|
||||
@@ -542,6 +542,10 @@ describe('HeartbeatCenter', () => {
|
||||
)
|
||||
|
||||
expect(screen.getByText('正在加载智能心跳')).toBeInTheDocument()
|
||||
expect(screen.getByRole('status')).toHaveAttribute(
|
||||
'aria-busy',
|
||||
'true'
|
||||
)
|
||||
expect(
|
||||
screen.queryByRole('button', { name: '配置智能心跳' })
|
||||
).not.toBeInTheDocument()
|
||||
|
||||
@@ -433,6 +433,7 @@ export function HeartbeatCenter({
|
||||
icon={<RefreshCw size={24} />}
|
||||
level="page"
|
||||
title={t('center.loading.title')}
|
||||
variant="loading"
|
||||
/>
|
||||
) : loadError && !hasHeartbeatData ? (
|
||||
<EmptyState
|
||||
|
||||
@@ -1887,6 +1887,10 @@ describe('KnowledgeWorkspace', () => {
|
||||
)
|
||||
|
||||
expect(screen.getByText('正在加载知识库')).toBeInTheDocument()
|
||||
expect(screen.getByRole('status')).toHaveAttribute(
|
||||
'aria-busy',
|
||||
'true'
|
||||
)
|
||||
expect(
|
||||
screen.queryByText('建立第一个知识库')
|
||||
).not.toBeInTheDocument()
|
||||
|
||||
@@ -4404,6 +4404,7 @@ export function KnowledgeWorkspace({
|
||||
icon={<LoaderCircle size={28} />}
|
||||
level="page"
|
||||
title={t('loading.title')}
|
||||
variant="loading"
|
||||
/>
|
||||
) : loadError && libraries.length === 0 ? (
|
||||
<EmptyState
|
||||
|
||||
@@ -3,12 +3,15 @@ import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
within,
|
||||
waitFor
|
||||
} from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { WorkspaceFilePreview } from '../../shared/assistant-contracts'
|
||||
import {
|
||||
RightAssistantSidebar,
|
||||
type AssistantSidebarTab,
|
||||
type PendingSidebarApproval,
|
||||
type SidebarArtifact
|
||||
} from './RightAssistantSidebar'
|
||||
|
||||
@@ -23,20 +26,44 @@ beforeEach(() => {
|
||||
|
||||
function renderSidebar({
|
||||
tab = 'tasks',
|
||||
approvals = [],
|
||||
artifacts = [],
|
||||
onListWorkspaceDirectory = vi.fn(async (path: string) => ({
|
||||
path,
|
||||
entries: [],
|
||||
truncated: false
|
||||
})),
|
||||
onLoadArtifact = vi.fn(async () => undefined),
|
||||
onLoadWorkspaceFile = vi.fn(),
|
||||
workspaceProjectId,
|
||||
restoreFocusRef
|
||||
}: {
|
||||
tab?: AssistantSidebarTab
|
||||
approvals?: PendingSidebarApproval[]
|
||||
artifacts?: SidebarArtifact[]
|
||||
onListWorkspaceDirectory?: (
|
||||
path: string
|
||||
) => Promise<{
|
||||
path: string
|
||||
entries: {
|
||||
name: string
|
||||
path: string
|
||||
type: 'file' | 'directory'
|
||||
}[]
|
||||
truncated: boolean
|
||||
}>
|
||||
onLoadArtifact?: (artifactId: string) => Promise<void>
|
||||
onLoadWorkspaceFile?: (
|
||||
path: string
|
||||
) => Promise<WorkspaceFilePreview>
|
||||
workspaceProjectId?: string
|
||||
restoreFocusRef?: { current: HTMLElement | null }
|
||||
} = {}): HTMLElement {
|
||||
render(
|
||||
<div>
|
||||
<main className="workspace" />
|
||||
<RightAssistantSidebar
|
||||
approvals={[]}
|
||||
approvals={approvals}
|
||||
artifacts={artifacts}
|
||||
schedules={[]}
|
||||
tasks={[]}
|
||||
@@ -44,13 +71,9 @@ function renderSidebar({
|
||||
projectNames={new Map()}
|
||||
onCreateCustomTask={vi.fn()}
|
||||
onImportArtifacts={vi.fn(async () => undefined)}
|
||||
onListWorkspaceDirectory={vi.fn(async (path: string) => ({
|
||||
path,
|
||||
entries: [],
|
||||
truncated: false
|
||||
}))}
|
||||
onListWorkspaceDirectory={onListWorkspaceDirectory}
|
||||
onLoadArtifact={onLoadArtifact}
|
||||
onLoadWorkspaceFile={vi.fn()}
|
||||
onLoadWorkspaceFile={onLoadWorkspaceFile}
|
||||
onOpenWorkspaceEntry={vi.fn(async () => undefined)}
|
||||
onInteractBrowser={vi.fn(async () => undefined)}
|
||||
onRefreshChanges={vi.fn(async () => undefined)}
|
||||
@@ -64,6 +87,7 @@ function renderSidebar({
|
||||
open
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
tab={tab}
|
||||
workspaceProjectId={workspaceProjectId}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -265,6 +289,91 @@ describe('RightAssistantSidebar resizing', () => {
|
||||
expect(screen.queryByText('最近任务')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels approval counts and cards without duplicate live regions', () => {
|
||||
renderSidebar({
|
||||
approvals: [
|
||||
{
|
||||
conversationId: 'conversation-1',
|
||||
messageId: 'message-1',
|
||||
approvalId: 'approval-1',
|
||||
title: '写入工作区',
|
||||
description: '更新 release.md',
|
||||
toolName: 'write_file'
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(
|
||||
screen.getByLabelText('等待审批: 1')
|
||||
).not.toHaveAttribute('aria-live')
|
||||
expect(
|
||||
screen.getByLabelText('等待审批: write_file')
|
||||
).not.toHaveAttribute('aria-live')
|
||||
expect(
|
||||
screen.queryByRole('status', { name: /等待审批/u })
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps a failed workspace preview in place and retries it', async () => {
|
||||
let rejectPreview: ((reason: unknown) => void) | undefined
|
||||
const onLoadWorkspaceFile = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((_resolve, reject) => {
|
||||
rejectPreview = reject
|
||||
})
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
path: 'README.md',
|
||||
name: 'README.md',
|
||||
content: 'Recovered preview',
|
||||
mimeType: 'text/plain',
|
||||
size: 17
|
||||
})
|
||||
renderSidebar({
|
||||
tab: 'workspace',
|
||||
workspaceProjectId: 'project-1',
|
||||
onListWorkspaceDirectory: vi.fn(async (path: string) => ({
|
||||
path,
|
||||
entries: [
|
||||
{
|
||||
name: 'README.md',
|
||||
path: 'README.md',
|
||||
type: 'file' as const
|
||||
}
|
||||
],
|
||||
truncated: false
|
||||
})),
|
||||
onLoadWorkspaceFile
|
||||
})
|
||||
|
||||
fireEvent.click(
|
||||
await screen.findByRole('button', { name: 'README.md' })
|
||||
)
|
||||
const loading = screen.getByRole('status', {
|
||||
name: '正在读取文件…'
|
||||
})
|
||||
expect(loading).toHaveAttribute('aria-live', 'polite')
|
||||
expect(loading.closest('section')).toHaveAttribute(
|
||||
'aria-busy',
|
||||
'true'
|
||||
)
|
||||
|
||||
rejectPreview?.(new Error('临时网络错误'))
|
||||
const error = await screen.findByRole('alert')
|
||||
expect(error).toHaveTextContent('临时网络错误')
|
||||
expect(screen.getByText('README.md')).toBeInTheDocument()
|
||||
fireEvent.click(
|
||||
within(error).getByRole('button', { name: '刷新' })
|
||||
)
|
||||
|
||||
expect(await screen.findByText('Recovered preview'))
|
||||
.toBeInTheDocument()
|
||||
expect(onLoadWorkspaceFile).toHaveBeenCalledTimes(2)
|
||||
expect(onLoadWorkspaceFile).toHaveBeenNthCalledWith(2, 'README.md')
|
||||
})
|
||||
|
||||
it('previews a result without switching to a separate tab', () => {
|
||||
const onLoadArtifact = vi.fn(async () => undefined)
|
||||
renderSidebar({
|
||||
|
||||
@@ -601,7 +601,10 @@ export function RightAssistantSidebar({
|
||||
>
|
||||
{item.label}
|
||||
{item.id === 'tasks' && approvals.length > 0 && (
|
||||
<span className="assistant-sidebar__badge">
|
||||
<span
|
||||
aria-label={`${t('sidebar.tasks.approvalsTitle')}: ${approvals.length}`}
|
||||
className="assistant-sidebar__badge"
|
||||
>
|
||||
{approvals.length}
|
||||
</span>
|
||||
)}
|
||||
@@ -633,6 +636,9 @@ export function RightAssistantSidebar({
|
||||
) : (
|
||||
approvals.map((approval) => (
|
||||
<article
|
||||
aria-label={`${t('sidebar.tasks.approvalsTitle')}: ${
|
||||
approval.toolName ?? approval.title
|
||||
}`}
|
||||
className="assistant-sidebar__approval"
|
||||
key={approval.approvalId}
|
||||
>
|
||||
@@ -808,7 +814,10 @@ export function RightAssistantSidebar({
|
||||
|
||||
{tab === 'workspace' && (
|
||||
currentWorkspacePreview ? (
|
||||
<section className="assistant-sidebar__preview">
|
||||
<section
|
||||
aria-busy={currentWorkspacePreview.state === 'loading'}
|
||||
className="assistant-sidebar__preview"
|
||||
>
|
||||
<header>
|
||||
<button
|
||||
aria-label={t('sidebar.workspace.back')}
|
||||
@@ -838,13 +847,28 @@ export function RightAssistantSidebar({
|
||||
</span>
|
||||
</header>
|
||||
{currentWorkspacePreview.state === 'loading' ? (
|
||||
<p className="assistant-sidebar__empty">
|
||||
<p
|
||||
aria-label={t('sidebar.workspace.reading')}
|
||||
aria-live="polite"
|
||||
className="assistant-sidebar__empty"
|
||||
role="status"
|
||||
>
|
||||
{t('sidebar.workspace.reading')}
|
||||
</p>
|
||||
) : currentWorkspacePreview.state === 'error' ? (
|
||||
<p className="assistant-sidebar__empty" role="alert">
|
||||
{currentWorkspacePreview.error}
|
||||
</p>
|
||||
<div className="assistant-sidebar__empty" role="alert">
|
||||
<p>{currentWorkspacePreview.error}</p>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() =>
|
||||
openWorkspaceFile(currentWorkspacePreview.path)
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
<RefreshCw aria-hidden="true" size={13} />
|
||||
{t('sidebar.workspace.refresh')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="markdown-body markdown-content">
|
||||
{currentWorkspacePreview.file.mimeType ===
|
||||
@@ -1070,9 +1094,15 @@ export function RightAssistantSidebar({
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
aria-live="polite"
|
||||
aria-live={
|
||||
browserState.status === 'failed'
|
||||
? 'assertive'
|
||||
: 'polite'
|
||||
}
|
||||
className={`assistant-sidebar__browser-status assistant-sidebar__browser-status--${browserState.status}`}
|
||||
role="status"
|
||||
role={
|
||||
browserState.status === 'failed' ? 'alert' : 'status'
|
||||
}
|
||||
>
|
||||
{browserState.status === 'creating'
|
||||
? t('sidebar.browser.statuses.creating')
|
||||
|
||||
@@ -2322,15 +2322,29 @@ describe('SettingsPanel runtime files', () => {
|
||||
expect(
|
||||
screen.getByRole('tab', { name: '外观' })
|
||||
).toHaveAttribute('aria-selected', 'true')
|
||||
fireEvent.click(screen.getByRole('button', { name: '关闭设置' }))
|
||||
const content = screen.getByRole('tabpanel')
|
||||
content.scrollTop = 320
|
||||
const closeButton = screen.getByRole('button', {
|
||||
name: '关闭设置'
|
||||
})
|
||||
fireEvent.click(closeButton)
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(
|
||||
screen.getByRole('alert')
|
||||
).toHaveTextContent('当前设置有未保存更改')
|
||||
expect(
|
||||
screen.getByRole('button', { name: '继续编辑' })
|
||||
).toHaveFocus()
|
||||
expect(content).toHaveProperty('scrollTop', 0)
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: '继续编辑' })
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: '关闭设置' })
|
||||
).toHaveFocus()
|
||||
)
|
||||
fireEvent.click(runtimeTab)
|
||||
expect(await screen.findByLabelText('默认工作区目录')).toHaveValue(
|
||||
'C:\\Unsaved workspace'
|
||||
@@ -2343,6 +2357,7 @@ describe('SettingsPanel runtime files', () => {
|
||||
screen.getByRole('button', { name: '放弃更改并关闭' })
|
||||
)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(closeButton).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('routes external leave requests through the existing dirty confirmation', async () => {
|
||||
@@ -2420,6 +2435,7 @@ describe('SettingsPanel runtime files', () => {
|
||||
screen.getByRole('button', { name: '放弃更改并切换' })
|
||||
)
|
||||
expect(appearanceTab).toHaveAttribute('aria-selected', 'true')
|
||||
await waitFor(() => expect(appearanceTab).toHaveFocus())
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole('tab', { name: '主机与远程执行' })
|
||||
|
||||
@@ -764,6 +764,8 @@ export function SettingsPanel({
|
||||
>()
|
||||
const runtimeCustomizationRef =
|
||||
useRef<RuntimeCustomizationSectionHandle>(null)
|
||||
const keepEditingRef = useRef<HTMLButtonElement>(null)
|
||||
const leaveTriggerRef = useRef<HTMLElement | undefined>(undefined)
|
||||
const handleRuntimeCustomizationDirtyChange = useCallback(
|
||||
(dirty: boolean): void => {
|
||||
setRuntimeCustomizationDirty(dirty)
|
||||
@@ -976,12 +978,18 @@ export function SettingsPanel({
|
||||
}, [hasUnsavedDrafts, open])
|
||||
|
||||
const requestTabChange = (
|
||||
category: SettingsCategoryId
|
||||
category: SettingsCategoryId,
|
||||
trigger?: HTMLElement
|
||||
): boolean => {
|
||||
if (category === activeTab) {
|
||||
return true
|
||||
}
|
||||
if (navigationWouldLoseDraft) {
|
||||
leaveTriggerRef.current =
|
||||
trigger ??
|
||||
(document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: undefined)
|
||||
setPendingLeave({ kind: 'navigate', category })
|
||||
return false
|
||||
}
|
||||
@@ -1018,7 +1026,7 @@ export function SettingsPanel({
|
||||
}
|
||||
event.preventDefault()
|
||||
const nextTab = settingsTabs[nextIndex]!
|
||||
if (!requestTabChange(nextTab)) {
|
||||
if (!requestTabChange(nextTab, event.currentTarget)) {
|
||||
return
|
||||
}
|
||||
event.currentTarget.parentElement
|
||||
@@ -1174,8 +1182,13 @@ export function SettingsPanel({
|
||||
return normalizedContextCompression
|
||||
}
|
||||
|
||||
const close = (): void => {
|
||||
const close = (trigger?: HTMLElement): void => {
|
||||
if (hasUnsavedDrafts) {
|
||||
leaveTriggerRef.current =
|
||||
trigger ??
|
||||
(document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: undefined)
|
||||
setPendingLeave({ kind: 'close' })
|
||||
return
|
||||
}
|
||||
@@ -1240,6 +1253,11 @@ export function SettingsPanel({
|
||||
setError(undefined)
|
||||
if (leave?.kind === 'navigate') {
|
||||
setActiveTab(leave.category)
|
||||
requestAnimationFrame(() =>
|
||||
document
|
||||
.getElementById(`settings-tab-${leave.category}`)
|
||||
?.focus()
|
||||
)
|
||||
return
|
||||
}
|
||||
if (leave?.kind === 'external') {
|
||||
@@ -1252,9 +1270,34 @@ export function SettingsPanel({
|
||||
}
|
||||
}
|
||||
|
||||
const keepEditing = (): void => {
|
||||
const trigger = leaveTriggerRef.current
|
||||
setPendingLeave(undefined)
|
||||
setError(undefined)
|
||||
requestAnimationFrame(() => {
|
||||
if (trigger?.isConnected) {
|
||||
trigger.focus()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!pendingLeave) {
|
||||
return
|
||||
}
|
||||
if (settingsBodyRef.current) {
|
||||
settingsBodyRef.current.scrollTop = 0
|
||||
}
|
||||
keepEditingRef.current?.focus()
|
||||
}, [pendingLeave])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const requestLeave: SettingsLeaveRequester = (proceed) => {
|
||||
if (hasUnsavedDrafts) {
|
||||
leaveTriggerRef.current =
|
||||
document.activeElement instanceof HTMLElement
|
||||
? document.activeElement
|
||||
: undefined
|
||||
setPendingLeave({ kind: 'external', proceed })
|
||||
return
|
||||
}
|
||||
@@ -1902,7 +1945,7 @@ export function SettingsPanel({
|
||||
<button
|
||||
aria-label={t('center.close')}
|
||||
className="icon-button"
|
||||
onClick={close}
|
||||
onClick={(event) => close(event.currentTarget)}
|
||||
type="button"
|
||||
>
|
||||
<X aria-hidden="true" size={19} />
|
||||
@@ -1931,8 +1974,8 @@ export function SettingsPanel({
|
||||
aria-selected={activeTab === category.id}
|
||||
id={`settings-tab-${category.id}`}
|
||||
key={category.id}
|
||||
onClick={() => {
|
||||
requestTabChange(category.id)
|
||||
onClick={(event) => {
|
||||
requestTabChange(category.id, event.currentTarget)
|
||||
}}
|
||||
onKeyDown={(event) =>
|
||||
handleTabKeyDown(event, category.id)
|
||||
@@ -1973,10 +2016,8 @@ export function SettingsPanel({
|
||||
<div className="update-settings__actions">
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => {
|
||||
setPendingLeave(undefined)
|
||||
setError(undefined)
|
||||
}}
|
||||
onClick={keepEditing}
|
||||
ref={keepEditingRef}
|
||||
type="button"
|
||||
>
|
||||
{t('unsaved.keepEditing')}
|
||||
@@ -3895,7 +3936,9 @@ export function SettingsPanel({
|
||||
magicNotesEnabled={magicNotesEnabled}
|
||||
/>
|
||||
)}
|
||||
{activeTab === 'about' && <UpdateSettingsSection />}
|
||||
{activeTab === 'about' && (
|
||||
<UpdateSettingsSection onNotify={onNotify} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -345,6 +345,36 @@ describe('SshHostsSettingsSection', () => {
|
||||
expect(getSnapshot).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('separates a failed Host read from an empty list and retries it', async () => {
|
||||
getSnapshot
|
||||
.mockRejectedValueOnce(new Error('Host database unavailable'))
|
||||
.mockResolvedValueOnce(emptySnapshot)
|
||||
render(<SshHostsSettingsSection />)
|
||||
|
||||
expect(
|
||||
await screen.findByText('SSH 主机加载失败')
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText('Host database unavailable')).toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByText('尚未配置 SSH 主机')
|
||||
).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '重试' }))
|
||||
|
||||
expect(await screen.findByText('尚未配置 SSH 主机'))
|
||||
.toBeInTheDocument()
|
||||
expect(getSnapshot).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('uses the shared live busy state while Hosts load', () => {
|
||||
getSnapshot.mockReturnValue(new Promise(() => {}))
|
||||
render(<SshHostsSettingsSection />)
|
||||
|
||||
const status = screen.getByRole('status')
|
||||
expect(status).toHaveAttribute('aria-live', 'polite')
|
||||
expect(status).toHaveAttribute('aria-busy', 'true')
|
||||
})
|
||||
|
||||
it('keeps failed authentication editable and retries without saving a failed host', async () => {
|
||||
getSnapshot
|
||||
.mockResolvedValueOnce(emptySnapshot)
|
||||
|
||||
@@ -107,6 +107,7 @@ export function SshHostsSettingsSection({
|
||||
const [projectReferences, setProjectReferences] =
|
||||
useState<SshHostsSnapshot['projectReferences']>()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [loadError, setLoadError] = useState<string>()
|
||||
const [error, setError] = useState<string>()
|
||||
const [editingId, setEditingId] = useState<string | 'new'>()
|
||||
const [busyHostId, setBusyHostId] = useState<string>()
|
||||
@@ -202,34 +203,51 @@ export function SshHostsSettingsSection({
|
||||
setHosts(snapshot.hosts)
|
||||
setSecureStorageAvailable(snapshot.secureStorageAvailable)
|
||||
setProjectReferences(snapshot.projectReferences)
|
||||
setError(undefined)
|
||||
setLoadError(undefined)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const loadSnapshot = useCallback(async (): Promise<void> => {
|
||||
setLoading(true)
|
||||
setLoadError(undefined)
|
||||
try {
|
||||
applySnapshot(await requestSnapshot())
|
||||
} catch (reason) {
|
||||
setLoadError(
|
||||
displayErrorMessage(
|
||||
reason,
|
||||
t('sshHosts.errors.readFailed')
|
||||
)
|
||||
)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [applySnapshot, requestSnapshot, t])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
void requestSnapshot()
|
||||
.then((snapshot) => {
|
||||
setLoading(true)
|
||||
setLoadError(undefined)
|
||||
void requestSnapshot().then(
|
||||
(snapshot) => {
|
||||
if (active) {
|
||||
applySnapshot(snapshot)
|
||||
setLoading(false)
|
||||
}
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
},
|
||||
(reason: unknown) => {
|
||||
if (active) {
|
||||
setError(
|
||||
setLoadError(
|
||||
displayErrorMessage(
|
||||
reason,
|
||||
t('sshHosts.errors.readFailed')
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) {
|
||||
setLoading(false)
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
@@ -620,7 +638,28 @@ export function SshHostsSettingsSection({
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="settings-empty">{t('sshHosts.loading')}</div>
|
||||
<EmptyState
|
||||
description={t('sshHosts.loading')}
|
||||
icon={<LoaderCircle size={22} />}
|
||||
title={t('sshHosts.loading')}
|
||||
variant="loading"
|
||||
/>
|
||||
) : loadError ? (
|
||||
<EmptyState
|
||||
action={
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => void loadSnapshot()}
|
||||
type="button"
|
||||
>
|
||||
<RefreshCw aria-hidden="true" size={14} />
|
||||
{t('sshHosts.actions.retry')}
|
||||
</button>
|
||||
}
|
||||
description={loadError}
|
||||
icon={<Server size={22} />}
|
||||
title={t('sshHosts.loadFailedTitle')}
|
||||
/>
|
||||
) : hosts.length === 0 ? (
|
||||
<EmptyState
|
||||
action={
|
||||
|
||||
@@ -122,11 +122,12 @@ describe('UpdateSettingsSection', () => {
|
||||
checkUpdatesOnStartup: false
|
||||
})
|
||||
)
|
||||
expect(source).toBeDisabled()
|
||||
expect(source).toBeEnabled()
|
||||
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: '立即检查更新' })
|
||||
)
|
||||
expect(source).toHaveValue('mirror')
|
||||
expect(await screen.findByText('发现新版本 0.9.0'))
|
||||
.toBeInTheDocument()
|
||||
expect(
|
||||
@@ -144,7 +145,7 @@ describe('UpdateSettingsSection', () => {
|
||||
expect(dialog).toHaveAttribute('aria-modal', 'true')
|
||||
expect(screen.getByLabelText('反馈类型')).toHaveFocus()
|
||||
expect(
|
||||
screen.getByText(/不会自动发送对话、日志、文件/)
|
||||
screen.getByText(/不会发送对话、Prompt、凭据、文件内容/)
|
||||
).toBeInTheDocument()
|
||||
fireEvent.keyDown(dialog, { key: 'Escape' })
|
||||
expect(
|
||||
@@ -204,6 +205,55 @@ describe('UpdateSettingsSection', () => {
|
||||
expect(alert).not.toHaveTextContent('Error invoking remote method')
|
||||
})
|
||||
|
||||
it('routes download-page failures through app notifications', async () => {
|
||||
const onNotify = vi.fn()
|
||||
Object.defineProperty(window, 'goodbuddy', {
|
||||
configurable: true,
|
||||
value: {
|
||||
app: {
|
||||
getInfo: vi.fn(async () => ({
|
||||
name: 'GoodBuddy',
|
||||
version: '0.8.1',
|
||||
platform: 'win32',
|
||||
arch: 'x64',
|
||||
shortcut: 'Ctrl+Shift+Space'
|
||||
}))
|
||||
},
|
||||
updates: {
|
||||
getSettings: vi.fn(async () => ({
|
||||
checkUpdatesOnStartup: false,
|
||||
updateSource: 'mirror',
|
||||
magicNotesEnabled: true,
|
||||
magicNoteCommentMode: 'immediate',
|
||||
magicNoteCommentFormat: 'combined'
|
||||
})),
|
||||
updateSettings: vi.fn(),
|
||||
check: vi.fn(),
|
||||
openReleasePage: vi.fn(async () => {
|
||||
throw new Error('Shell refused the release URL')
|
||||
}),
|
||||
onResult: vi.fn(() => () => {})
|
||||
}
|
||||
} as unknown as DesktopApi
|
||||
})
|
||||
|
||||
render(<UpdateSettingsSection onNotify={onNotify} />)
|
||||
fireEvent.click(
|
||||
await screen.findByRole('button', { name: '打开下载页' })
|
||||
)
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onNotify).toHaveBeenCalledWith({
|
||||
dedupeKey: 'open-update-download-page-failed',
|
||||
message: 'Shell refused the release URL',
|
||||
tone: 'error'
|
||||
})
|
||||
)
|
||||
expect(
|
||||
screen.queryByText('Shell refused the release URL')
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps feedback available when update settings are unavailable', async () => {
|
||||
Object.defineProperty(window, 'goodbuddy', {
|
||||
configurable: true,
|
||||
|
||||
@@ -11,11 +11,15 @@ import type {
|
||||
VersionCheckResult
|
||||
} from '../../shared/application-settings-contracts'
|
||||
import type { AppInfo } from '../../shared/contracts'
|
||||
import type { AppNotificationInput } from './notifications'
|
||||
import {
|
||||
SettingsCategoryHeader,
|
||||
SettingsWarningList
|
||||
} from './SettingsPrimitives'
|
||||
import { displayErrorMessage } from './error-message'
|
||||
import {
|
||||
displayErrorMessage,
|
||||
displayNetworkAwareErrorMessage
|
||||
} from './error-message'
|
||||
import { FeedbackDialog } from './FeedbackDialog'
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
@@ -25,19 +29,11 @@ function formatBytes(bytes: number): string {
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function updateErrorMessage(
|
||||
reason: unknown,
|
||||
fallback: string,
|
||||
networkMessage: string
|
||||
): string {
|
||||
const message = displayErrorMessage(reason, fallback)
|
||||
if (/fetch failed/i.test(message)) {
|
||||
return networkMessage
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
export function UpdateSettingsSection(): React.JSX.Element {
|
||||
export function UpdateSettingsSection({
|
||||
onNotify
|
||||
}: {
|
||||
onNotify?: (notification: AppNotificationInput) => void
|
||||
}): React.JSX.Element {
|
||||
const { t } = useTranslation('settingsSections')
|
||||
const [settings, setSettings] = useState<ApplicationSettings>()
|
||||
const [appInfo, setAppInfo] = useState<AppInfo>()
|
||||
@@ -79,7 +75,7 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
if (active) {
|
||||
const fallback = t('updates.errors.readSettingsFailed')
|
||||
setError(
|
||||
updateErrorMessage(
|
||||
displayNetworkAwareErrorMessage(
|
||||
reason,
|
||||
fallback,
|
||||
t('updates.errors.network', { fallback })
|
||||
@@ -108,7 +104,7 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
} catch (reason) {
|
||||
const fallback = t('updates.errors.saveSettingsFailed')
|
||||
setError(
|
||||
updateErrorMessage(
|
||||
displayNetworkAwareErrorMessage(
|
||||
reason,
|
||||
fallback,
|
||||
t('updates.errors.network', { fallback })
|
||||
@@ -134,7 +130,7 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
} catch (reason) {
|
||||
const fallback = t('updates.errors.saveSourceFailed')
|
||||
setError(
|
||||
updateErrorMessage(
|
||||
displayNetworkAwareErrorMessage(
|
||||
reason,
|
||||
fallback,
|
||||
t('updates.errors.network', {
|
||||
@@ -159,7 +155,7 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
} catch (reason) {
|
||||
const fallback = t('updates.errors.checkFailed')
|
||||
setError(
|
||||
updateErrorMessage(
|
||||
displayNetworkAwareErrorMessage(
|
||||
reason,
|
||||
fallback,
|
||||
t('updates.errors.sourceNetwork', {
|
||||
@@ -175,6 +171,30 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
}
|
||||
}
|
||||
|
||||
const openReleasePage = async (): Promise<void> => {
|
||||
const updates = window.goodbuddy.updates
|
||||
if (!updates) {
|
||||
onNotify?.({
|
||||
dedupeKey: 'open-update-download-page-failed',
|
||||
message: t('updates.errors.serviceUnavailable'),
|
||||
tone: 'error'
|
||||
})
|
||||
return
|
||||
}
|
||||
try {
|
||||
await updates.openReleasePage()
|
||||
} catch (reason) {
|
||||
onNotify?.({
|
||||
dedupeKey: 'open-update-download-page-failed',
|
||||
message: displayErrorMessage(
|
||||
reason,
|
||||
t('updates.errors.openReleasePageFailed')
|
||||
),
|
||||
tone: 'error'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsCategoryHeader
|
||||
@@ -219,7 +239,6 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
aria-label={t('updates.source.label')}
|
||||
disabled={
|
||||
!settings ||
|
||||
!settings.checkUpdatesOnStartup ||
|
||||
saving ||
|
||||
checking
|
||||
}
|
||||
@@ -254,9 +273,7 @@ export function UpdateSettingsSection(): React.JSX.Element {
|
||||
</button>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() =>
|
||||
void window.goodbuddy.updates?.openReleasePage()
|
||||
}
|
||||
onClick={() => void openReleasePage()}
|
||||
type="button"
|
||||
>
|
||||
<ExternalLink aria-hidden="true" size={13} />
|
||||
|
||||
@@ -611,6 +611,20 @@ describe('WorkspacePrimitives', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('announces shared loading empty states consistently', () => {
|
||||
render(
|
||||
<EmptyState
|
||||
description="正在读取内容。"
|
||||
title="正在加载"
|
||||
variant="loading"
|
||||
/>
|
||||
)
|
||||
|
||||
const status = screen.getByRole('status')
|
||||
expect(status).toHaveAttribute('aria-live', 'polite')
|
||||
expect(status).toHaveAttribute('aria-busy', 'true')
|
||||
})
|
||||
|
||||
it('uses the shared destructive confirmation flow', () => {
|
||||
const onRequestConfirm = vi.fn()
|
||||
const onConfirm = vi.fn()
|
||||
|
||||
@@ -330,16 +330,23 @@ export function EmptyState({
|
||||
description,
|
||||
icon,
|
||||
level = 'section',
|
||||
title
|
||||
title,
|
||||
variant = 'default'
|
||||
}: {
|
||||
action?: ReactNode
|
||||
description: ReactNode
|
||||
icon?: ReactNode
|
||||
level?: 'page' | 'section' | 'table'
|
||||
title?: string
|
||||
variant?: 'default' | 'loading'
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<div className={`empty-state empty-state--${level}`}>
|
||||
<div
|
||||
aria-busy={variant === 'loading' ? 'true' : undefined}
|
||||
aria-live={variant === 'loading' ? 'polite' : undefined}
|
||||
className={`empty-state empty-state--${level}`}
|
||||
role={variant === 'loading' ? 'status' : undefined}
|
||||
>
|
||||
{icon && (
|
||||
<span aria-hidden="true" className="empty-state__icon">
|
||||
{icon}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
displayErrorMessage,
|
||||
displayNetworkAwareErrorMessage
|
||||
} from './error-message'
|
||||
|
||||
describe('error message formatting', () => {
|
||||
it('replaces fetch failures with localized network guidance', () => {
|
||||
expect(
|
||||
displayNetworkAwareErrorMessage(
|
||||
new Error(
|
||||
"Error invoking remote method 'application:update:check': TypeError: fetch failed"
|
||||
),
|
||||
'Version check failed',
|
||||
'Check your network and try again'
|
||||
)
|
||||
).toBe('Check your network and try again')
|
||||
})
|
||||
|
||||
it('preserves bounded HTTP and provider details', () => {
|
||||
expect(
|
||||
displayNetworkAwareErrorMessage(
|
||||
new Error('HTTP 503: release manifest unavailable'),
|
||||
'Version check failed',
|
||||
'Check your network and try again'
|
||||
)
|
||||
).toBe('HTTP 503: release manifest unavailable')
|
||||
expect(
|
||||
displayErrorMessage(
|
||||
new Error(
|
||||
"Error invoking remote method 'application:update:check': Error: provider rejected request"
|
||||
),
|
||||
'Version check failed'
|
||||
)
|
||||
).toBe('provider rejected request')
|
||||
})
|
||||
})
|
||||
@@ -22,3 +22,16 @@ export function displayErrorMessage(
|
||||
.trim()
|
||||
return message || fallback
|
||||
}
|
||||
|
||||
export function displayNetworkAwareErrorMessage(
|
||||
reason: unknown,
|
||||
fallback: string,
|
||||
networkMessage: string
|
||||
): string {
|
||||
const message = displayErrorMessage(reason, fallback)
|
||||
return /(?:fetch failed|failed to fetch|networkerror|network request failed)/iu.test(
|
||||
message
|
||||
)
|
||||
? networkMessage
|
||||
: message
|
||||
}
|
||||
|
||||
@@ -79,7 +79,15 @@ export const app = {
|
||||
unread: 'Unread',
|
||||
unreadRemote: 'Unread remote message',
|
||||
noRemote: 'No remote conversations yet',
|
||||
empty: 'No recent conversations yet',
|
||||
emptyDescription:
|
||||
'Start a conversation and it will appear here.',
|
||||
noMatches: 'No matching conversations',
|
||||
noMatchesDescription:
|
||||
'Change your search terms or clear the search to view all conversations.',
|
||||
clearSearch: 'Clear search',
|
||||
loadFailed: 'Could not load recent conversations',
|
||||
retryLoad: 'Reload conversations',
|
||||
renameAria: 'Rename conversation {{title}}',
|
||||
saveName: 'Save conversation name',
|
||||
cancelRename: 'Cancel rename',
|
||||
@@ -159,8 +167,9 @@ export const app = {
|
||||
workspace: 'Workspace',
|
||||
tools: 'Tools and approval',
|
||||
executeApproval:
|
||||
'Use authorized tools; high-risk actions still require approval',
|
||||
askReadOnly: 'Read-only run with no changes allowed',
|
||||
'Use all tools, processes, network access, and writable paths available to the current account; calls are recorded in Activity',
|
||||
askReadOnly:
|
||||
'Stay within the read-only boundary for answers and retrieval; make no changes',
|
||||
noWorkspace: 'No workspace configured'
|
||||
},
|
||||
errors: {
|
||||
@@ -204,6 +213,11 @@ export const app = {
|
||||
readStatus: 'Failed to read Agent Runtime status',
|
||||
readSettings: 'Failed to read Runtime settings',
|
||||
switch: 'Failed to switch Runtime'
|
||||
},
|
||||
state: {
|
||||
ready: 'Ready',
|
||||
connecting: 'Connecting',
|
||||
unavailable: 'Unavailable'
|
||||
}
|
||||
},
|
||||
chat: {
|
||||
@@ -367,6 +381,7 @@ export const app = {
|
||||
}
|
||||
},
|
||||
approval: {
|
||||
waiting: 'Awaiting approval: {{tool}}',
|
||||
deny: 'Deny',
|
||||
once: 'Allow once',
|
||||
session: 'Allow for conversation',
|
||||
@@ -476,11 +491,13 @@ export const app = {
|
||||
modes: {
|
||||
ask: {
|
||||
label: 'Ask · Read only',
|
||||
description: 'Read-only answers without modifying files'
|
||||
description:
|
||||
'Stay within the read-only boundary for answers and retrieval; make no changes'
|
||||
},
|
||||
execute: {
|
||||
label: 'Execute · Full access',
|
||||
description: 'Run tools with the account’s full permissions'
|
||||
description:
|
||||
'Use all tools, processes, network access, and writable paths available to the current account; calls are recorded in Activity'
|
||||
}
|
||||
},
|
||||
voice: {
|
||||
@@ -556,12 +573,13 @@ export const app = {
|
||||
imageGeneration:
|
||||
'Image model: describe a scene to generate an image that will appear here and be saved to Results.',
|
||||
agentAsk:
|
||||
'{{runtime}} Ask mode: can only search enabled knowledge bases and cannot modify files.',
|
||||
'{{runtime}} Ask mode: stays within the read-only boundary for answers and retrieval and makes no changes.',
|
||||
agentExecute:
|
||||
'{{runtime}} Execute mode: tool calls do not show GoodBuddy approvals and are recorded in Activity.',
|
||||
ask: 'Ask mode: read-only answers without tool calls or file changes.',
|
||||
'{{runtime}} Execute mode: uses all tools, processes, network access, and writable paths available to the current account; calls are recorded in Activity.',
|
||||
ask:
|
||||
'Ask mode: stays within the read-only boundary for answers and retrieval and makes no changes.',
|
||||
execute:
|
||||
'Execute mode: tools are automatically authorized and calls are still recorded in Activity.'
|
||||
'Execute mode: uses all tools, processes, network access, and writable paths available to the current account; calls are recorded in Activity.'
|
||||
},
|
||||
errors: {
|
||||
pasteImageType: 'Only JPEG, PNG, or WebP images can be pasted',
|
||||
@@ -574,6 +592,15 @@ export const app = {
|
||||
brandingSaved: 'Branding saved',
|
||||
updateAvailable:
|
||||
'GoodBuddy {{version}} is available. View it in About & Updates.',
|
||||
startupUpdateCheckFailed:
|
||||
'Startup update check failed ({{source}}): {{error}}',
|
||||
updateCheckFailed: 'Version check failed',
|
||||
updateCheckNetwork:
|
||||
'Could not connect to the update source. Check your network or proxy and try again.',
|
||||
updateSources: {
|
||||
github: 'GitHub',
|
||||
mirror: 'Mirror node'
|
||||
},
|
||||
channelConversationAutomatic:
|
||||
'Channel conversations are created automatically when the client receives a new message',
|
||||
deleteConversationCancelFailed:
|
||||
|
||||
@@ -10,6 +10,7 @@ export const settingsSections = {
|
||||
},
|
||||
sshHosts: {
|
||||
loading: 'Loading SSH hosts…',
|
||||
loadFailedTitle: 'Could not load SSH hosts',
|
||||
listLabel: 'SSH host list',
|
||||
securityNotice:
|
||||
'When a host is added or edited, GoodBuddy inspects its host key before sending credentials and running a bounded system probe. The host and encrypted password are saved only after every step succeeds.',
|
||||
@@ -191,6 +192,7 @@ export const settingsSections = {
|
||||
removeProjectsHeading: 'Also remove these related project records:',
|
||||
actions: {
|
||||
add: 'Add host',
|
||||
retry: 'Retry',
|
||||
edit: 'Edit and revalidate',
|
||||
validate: 'Validate and save',
|
||||
editNamed: 'Edit {{name}}',
|
||||
@@ -757,6 +759,11 @@ export const settingsSections = {
|
||||
'Used only if we need to contact you for more information.',
|
||||
characterCount: '{{count}} / {{maximum}} characters'
|
||||
},
|
||||
diagnostics: {
|
||||
label: 'Attach recent desktop diagnostics',
|
||||
description:
|
||||
'Off by default. When selected, this adds only timestamps, components, stages, stable error codes, error types, and fixed short messages from recent desktop diagnostics. It does not include conversations, prompts, credentials, file contents, paths, raw provider responses, or remote Agent logs.'
|
||||
},
|
||||
screenshot: {
|
||||
title: 'Screenshot (optional)',
|
||||
help:
|
||||
@@ -783,11 +790,15 @@ export const settingsSections = {
|
||||
}
|
||||
},
|
||||
privacy:
|
||||
'GoodBuddy will send the feedback type, title, description, optional email, app version, operating system, architecture, interface language, and any screenshot you add. Conversations, logs, files, project paths, model settings, and credentials are never attached automatically.',
|
||||
'GoodBuddy will send the feedback type, title, description, optional email, app version, operating system, architecture, interface language, and any screenshot you add. Desktop diagnostics are not uploaded by default; a bounded summary is appended to the description only when selected. Conversations, prompts, credentials, file contents, paths, raw provider responses, and remote Agent logs are not sent.',
|
||||
validation: {
|
||||
titleRequired: 'Enter a feedback title.',
|
||||
descriptionMinimum:
|
||||
'The detailed description must contain at least 10 characters.',
|
||||
descriptionMaximum:
|
||||
'The detailed description must be {{maximum}} characters or fewer. Your draft is preserved; shorten it and try again.',
|
||||
descriptionMaximumWithDiagnostics:
|
||||
'When desktop diagnostics are attached, the detailed description must be {{maximum}} characters or fewer. Your draft is preserved; shorten it and try again.',
|
||||
emailInvalid: 'Enter a valid contact email or leave it blank.'
|
||||
},
|
||||
actions: {
|
||||
@@ -830,7 +841,9 @@ export const settingsSections = {
|
||||
timeout:
|
||||
'The feedback service connection timed out. Check your network and try again.',
|
||||
'invalid-response':
|
||||
'The feedback service returned an invalid result. Try again later.'
|
||||
'The feedback service returned an invalid result. Try again later.',
|
||||
'diagnostics-unavailable':
|
||||
'The selected desktop diagnostics could not be read, so no feedback was sent. Your draft and selection are preserved; retry or clear the diagnostics checkbox before submitting.'
|
||||
}
|
||||
},
|
||||
updates: {
|
||||
@@ -842,6 +855,7 @@ export const settingsSections = {
|
||||
saveSettingsFailed: 'Could not save update settings',
|
||||
saveSourceFailed: 'Could not save the update source',
|
||||
checkFailed: 'Version check failed',
|
||||
openReleasePageFailed: 'Could not open the download page',
|
||||
network: '{{fallback}}. Check the system status and try again.',
|
||||
sourceNetwork:
|
||||
'{{fallback}}: Could not connect to update source "{{source}}". Check your network or proxy and try again.'
|
||||
|
||||
@@ -76,7 +76,13 @@ export const app = {
|
||||
unread: '未读',
|
||||
unreadRemote: '未读远程消息',
|
||||
noRemote: '尚无远程会话',
|
||||
empty: '还没有最近会话',
|
||||
emptyDescription: '新建对话后,会话会显示在这里。',
|
||||
noMatches: '没有匹配的对话',
|
||||
noMatchesDescription: '请修改搜索关键词,或清除搜索后查看全部会话。',
|
||||
clearSearch: '清除搜索',
|
||||
loadFailed: '最近会话加载失败',
|
||||
retryLoad: '重新读取会话',
|
||||
renameAria: '重命名会话 {{title}}',
|
||||
saveName: '保存会话名称',
|
||||
cancelRename: '取消重命名',
|
||||
@@ -148,8 +154,9 @@ export const app = {
|
||||
runtime: 'Runtime',
|
||||
workspace: '工作目录',
|
||||
tools: '工具与审批',
|
||||
executeApproval: '使用已授权工具;高风险操作仍需审批',
|
||||
askReadOnly: '只读运行,不允许执行变更',
|
||||
executeApproval:
|
||||
'使用当前账号可用的全部工具、进程、网络和可写路径;调用记录到活动',
|
||||
askReadOnly: '保持只读边界,仅问答和检索,不执行任何变更',
|
||||
noWorkspace: '未设置工作目录'
|
||||
},
|
||||
errors: {
|
||||
@@ -193,6 +200,11 @@ export const app = {
|
||||
readStatus: 'Agent Runtime 状态读取失败',
|
||||
readSettings: 'Runtime 设置读取失败',
|
||||
switch: 'Runtime 切换失败'
|
||||
},
|
||||
state: {
|
||||
ready: '就绪',
|
||||
connecting: '连接中',
|
||||
unavailable: '不可用'
|
||||
}
|
||||
},
|
||||
chat: {
|
||||
@@ -351,6 +363,7 @@ export const app = {
|
||||
}
|
||||
},
|
||||
approval: {
|
||||
waiting: '等待审批:{{tool}}',
|
||||
deny: '拒绝',
|
||||
once: '仅此次',
|
||||
session: '此会话',
|
||||
@@ -455,11 +468,12 @@ export const app = {
|
||||
modes: {
|
||||
ask: {
|
||||
label: 'Ask · 只读问答',
|
||||
description: '只读问答,不修改文件'
|
||||
description: '保持只读边界,仅问答和检索,不执行任何变更'
|
||||
},
|
||||
execute: {
|
||||
label: 'Execute · 完全权限',
|
||||
description: '使用当前账号的完整权限执行工具操作'
|
||||
description:
|
||||
'使用当前账号可用的全部工具、进程、网络和可写路径;调用记录到活动'
|
||||
}
|
||||
},
|
||||
voice: {
|
||||
@@ -521,11 +535,12 @@ export const app = {
|
||||
imageGeneration:
|
||||
'图像生成模型:输入画面描述后,生成结果会直接显示并保存到成果。',
|
||||
agentAsk:
|
||||
'{{runtime}} Ask 模式:只允许搜索当前启用的知识库,不会修改文件。',
|
||||
'{{runtime}} Ask 模式:保持只读边界,仅问答和检索,不执行任何变更。',
|
||||
agentExecute:
|
||||
'{{runtime}} Execute 模式:工具调用不会弹出 GoodBuddy 审批,并会记录到活动。',
|
||||
ask: 'Ask 模式:只读问答,不会调用工具或修改文件。',
|
||||
execute: 'Execute 模式:已启用工具自动授权,调用仍会记录到活动。'
|
||||
'{{runtime}} Execute 模式:使用当前账号可用的全部工具、进程、网络和可写路径;调用记录到活动。',
|
||||
ask: 'Ask 模式:保持只读边界,仅问答和检索,不执行任何变更。',
|
||||
execute:
|
||||
'Execute 模式:使用当前账号可用的全部工具、进程、网络和可写路径;调用记录到活动。'
|
||||
},
|
||||
errors: {
|
||||
pasteImageType: '仅支持粘贴 JPEG、PNG 或 WebP 图片',
|
||||
@@ -537,6 +552,14 @@ export const app = {
|
||||
notices: {
|
||||
brandingSaved: '品牌设置已保存',
|
||||
updateAvailable: '发现 GoodBuddy {{version}},可在“关于与更新”中查看',
|
||||
startupUpdateCheckFailed:
|
||||
'启动更新检查失败({{source}}):{{error}}',
|
||||
updateCheckFailed: '版本检查失败',
|
||||
updateCheckNetwork: '无法连接更新源,请检查网络或代理后重试',
|
||||
updateSources: {
|
||||
github: 'GitHub',
|
||||
mirror: '镜像节点'
|
||||
},
|
||||
channelConversationAutomatic:
|
||||
'通道项目的会话由客户端收到新消息后自动创建',
|
||||
deleteConversationCancelFailed:
|
||||
|
||||
@@ -5,6 +5,7 @@ export const settingsSections = {
|
||||
},
|
||||
sshHosts: {
|
||||
loading: '正在读取 SSH 主机…',
|
||||
loadFailedTitle: 'SSH 主机加载失败',
|
||||
listLabel: 'SSH 主机列表',
|
||||
securityNotice:
|
||||
'添加或编辑主机时,GoodBuddy 会先检查 Host Key,再发送认证凭据并执行有界系统探测。只有全部成功后才会保存主机和加密密码。',
|
||||
@@ -183,6 +184,7 @@ export const settingsSections = {
|
||||
removeProjectsHeading: '同时删除以下关联项目记录:',
|
||||
actions: {
|
||||
add: '添加主机',
|
||||
retry: '重试',
|
||||
edit: '编辑',
|
||||
validate: '验证并保存',
|
||||
editNamed: '编辑 {{name}}',
|
||||
@@ -710,6 +712,11 @@ export const settingsSections = {
|
||||
emailHelp: '仅在需要进一步了解情况时用于联系你。',
|
||||
characterCount: '已输入 {{count}} / {{maximum}} 个字符'
|
||||
},
|
||||
diagnostics: {
|
||||
label: '附加最近桌面诊断记录',
|
||||
description:
|
||||
'默认关闭。选中后仅附加最近桌面诊断的时间、组件、阶段、稳定错误码、错误类型和固定短消息;不包含对话、Prompt、凭据、文件内容、路径、Provider 原始响应或远端 Agent 日志。'
|
||||
},
|
||||
screenshot: {
|
||||
title: '截图(可选)',
|
||||
help: '选择或粘贴一张 PNG、JPEG 或 WebP 图片,最大 5 MB。',
|
||||
@@ -734,10 +741,14 @@ export const settingsSections = {
|
||||
}
|
||||
},
|
||||
privacy:
|
||||
'将发送反馈类型、标题、描述、可选邮箱、GoodBuddy 版本、操作系统、架构、界面语言,以及你主动添加的截图。不会自动发送对话、日志、文件、项目路径、模型配置或凭据。',
|
||||
'将发送反馈类型、标题、描述、可选邮箱、GoodBuddy 版本、操作系统、架构、界面语言,以及你主动添加的截图。默认不会上传桌面诊断;只有勾选后才会把有界诊断摘要追加到描述。不会发送对话、Prompt、凭据、文件内容、路径、Provider 原始响应或远端 Agent 日志。',
|
||||
validation: {
|
||||
titleRequired: '请输入反馈标题。',
|
||||
descriptionMinimum: '详细描述至少需要 10 个字符。',
|
||||
descriptionMaximum:
|
||||
'详细描述不能超过 {{maximum}} 个字符;草稿已保留,请缩短后重试。',
|
||||
descriptionMaximumWithDiagnostics:
|
||||
'附加桌面诊断时,详细描述不能超过 {{maximum}} 个字符;草稿已保留,请缩短后重试。',
|
||||
emailInvalid: '请输入有效的联系邮箱,或将其留空。'
|
||||
},
|
||||
actions: {
|
||||
@@ -774,7 +785,9 @@ export const settingsSections = {
|
||||
network: '无法连接反馈服务,请检查网络后重试。',
|
||||
timeout: '连接反馈服务超时,请检查网络后重试。',
|
||||
'invalid-response':
|
||||
'反馈服务返回了无效结果,请稍后重试。'
|
||||
'反馈服务返回了无效结果,请稍后重试。',
|
||||
'diagnostics-unavailable':
|
||||
'无法读取所选的桌面诊断记录,本次没有发送反馈。草稿和选择已保留,请重试或取消附加诊断后提交。'
|
||||
}
|
||||
},
|
||||
updates: {
|
||||
@@ -785,6 +798,7 @@ export const settingsSections = {
|
||||
saveSettingsFailed: '保存更新设置失败',
|
||||
saveSourceFailed: '保存检查更新源失败',
|
||||
checkFailed: '版本检查失败',
|
||||
openReleasePageFailed: '打开下载页失败',
|
||||
network: '{{fallback}}:请检查系统状态后重试',
|
||||
sourceNetwork:
|
||||
'{{fallback}}:无法连接更新源“{{source}}”,请检查网络或代理后重试'
|
||||
|
||||
@@ -9059,6 +9059,41 @@ details.settings-section > :not(summary) + :not(summary) {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.feedback-diagnostics-option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.feedback-diagnostics-option > input {
|
||||
margin: 2px 0 0;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.feedback-diagnostics-option > span {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.feedback-diagnostics-option strong {
|
||||
font-size: var(--font-body);
|
||||
}
|
||||
|
||||
.feedback-diagnostics-option small {
|
||||
color: var(--text-muted);
|
||||
font-size: var(--font-caption);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.feedback-diagnostics-option:has(input:disabled) {
|
||||
cursor: default;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.feedback-screenshot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -17,6 +17,7 @@ describe('feedback contracts', () => {
|
||||
category,
|
||||
title: ' Feedback title ',
|
||||
description: ' A useful feedback description. ',
|
||||
includeDiagnostics: false,
|
||||
locale: 'zh-CN',
|
||||
clientRequestId
|
||||
})
|
||||
@@ -33,6 +34,7 @@ describe('feedback contracts', () => {
|
||||
category: 'bug',
|
||||
title: 'Feedback title',
|
||||
description: 'A useful feedback description.',
|
||||
includeDiagnostics: false,
|
||||
locale: 'zh-CN',
|
||||
clientRequestId,
|
||||
endpoint: 'https://attacker.example'
|
||||
@@ -43,6 +45,7 @@ describe('feedback contracts', () => {
|
||||
category: 'bug',
|
||||
title: 'Feedback title',
|
||||
description: 'A useful feedback description.',
|
||||
includeDiagnostics: false,
|
||||
contactEmail: 'not-an-email',
|
||||
locale: 'zh-CN',
|
||||
clientRequestId
|
||||
@@ -53,6 +56,7 @@ describe('feedback contracts', () => {
|
||||
category: 'bug',
|
||||
title: 'Feedback title',
|
||||
description: 'A useful feedback description.',
|
||||
includeDiagnostics: false,
|
||||
locale: 'zh-CN',
|
||||
clientRequestId,
|
||||
screenshot: {
|
||||
@@ -65,6 +69,39 @@ describe('feedback contracts', () => {
|
||||
).toThrow()
|
||||
})
|
||||
|
||||
it('reserves description space only when diagnostics are selected', () => {
|
||||
expect(
|
||||
feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
).toBe(
|
||||
feedbackLimits.maximumDescriptionCharacters -
|
||||
feedbackLimits.maximumDiagnosticsSummaryCharacters -
|
||||
'\n\n'.length
|
||||
)
|
||||
const description = 'x'.repeat(
|
||||
feedbackLimits.maximumDescriptionCharactersWithDiagnostics + 1
|
||||
)
|
||||
expect(() =>
|
||||
feedbackSubmitInputSchema.parse({
|
||||
category: 'bug',
|
||||
title: 'Feedback title',
|
||||
description,
|
||||
includeDiagnostics: true,
|
||||
locale: 'zh-CN',
|
||||
clientRequestId
|
||||
})
|
||||
).toThrow()
|
||||
expect(
|
||||
feedbackSubmitInputSchema.parse({
|
||||
category: 'bug',
|
||||
title: 'Feedback title',
|
||||
description,
|
||||
includeDiagnostics: false,
|
||||
locale: 'zh-CN',
|
||||
clientRequestId
|
||||
}).description
|
||||
).toBe(description)
|
||||
})
|
||||
|
||||
it('matches the deployed version 1 public payload and response', () => {
|
||||
expect(
|
||||
feedbackPublicPayloadSchema.parse({
|
||||
@@ -87,6 +124,24 @@ describe('feedback contracts', () => {
|
||||
schemaVersion: 1,
|
||||
productKey: 'goodbuddy'
|
||||
})
|
||||
expect(() =>
|
||||
feedbackPublicPayloadSchema.parse({
|
||||
schemaVersion: 1,
|
||||
productKey: 'goodbuddy',
|
||||
category: 'experience',
|
||||
title: 'Feedback title',
|
||||
description: 'A useful feedback description.',
|
||||
includeDiagnostics: true,
|
||||
environment: {
|
||||
appVersion: '0.11.0',
|
||||
platform: 'windows',
|
||||
architecture: 'x64',
|
||||
locale: 'en-US'
|
||||
},
|
||||
installationId,
|
||||
clientRequestId
|
||||
})
|
||||
).toThrow()
|
||||
expect(
|
||||
feedbackPublicResponseSchema.parse({
|
||||
reference: 'GOODBUDDY-1000000',
|
||||
|
||||
@@ -7,10 +7,20 @@ export const feedbackCategories = [
|
||||
'other'
|
||||
] as const
|
||||
|
||||
const maximumDescriptionCharacters = 5_000
|
||||
const maximumDiagnosticsSummaryCharacters = 1_600
|
||||
const diagnosticsDescriptionSeparatorCharacters = '\n\n'.length
|
||||
|
||||
export const feedbackLimits = {
|
||||
maximumTitleCharacters: 120,
|
||||
minimumDescriptionCharacters: 10,
|
||||
maximumDescriptionCharacters: 5_000,
|
||||
maximumDescriptionCharacters,
|
||||
maximumDiagnosticsSummaryCharacters,
|
||||
maximumDiagnosticRecords: 20,
|
||||
maximumDescriptionCharactersWithDiagnostics:
|
||||
maximumDescriptionCharacters -
|
||||
maximumDiagnosticsSummaryCharacters -
|
||||
diagnosticsDescriptionSeparatorCharacters,
|
||||
maximumEmailCharacters: 254,
|
||||
maximumScreenshotBytes: 5 * 1_024 * 1_024,
|
||||
maximumScreenshotDimension: 8_192,
|
||||
@@ -61,11 +71,30 @@ const feedbackContentSchema = z
|
||||
|
||||
export const feedbackSubmitInputSchema = feedbackContentSchema
|
||||
.extend({
|
||||
includeDiagnostics: z.boolean(),
|
||||
locale: feedbackLocaleSchema,
|
||||
clientRequestId: z.uuid(),
|
||||
screenshot: feedbackScreenshotInputSchema.optional()
|
||||
})
|
||||
.strict()
|
||||
.superRefine((input, context) => {
|
||||
if (
|
||||
input.includeDiagnostics &&
|
||||
input.description.length >
|
||||
feedbackLimits.maximumDescriptionCharactersWithDiagnostics
|
||||
) {
|
||||
context.addIssue({
|
||||
code: 'too_big',
|
||||
maximum:
|
||||
feedbackLimits.maximumDescriptionCharactersWithDiagnostics,
|
||||
origin: 'string',
|
||||
inclusive: true,
|
||||
path: ['description'],
|
||||
message:
|
||||
'Description exceeds the limit when diagnostics are included'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export const feedbackEnvironmentSchema = z
|
||||
.object({
|
||||
@@ -103,7 +132,8 @@ export const feedbackSubmissionErrorCodes = [
|
||||
'service-error',
|
||||
'network',
|
||||
'timeout',
|
||||
'invalid-response'
|
||||
'invalid-response',
|
||||
'diagnostics-unavailable'
|
||||
] as const
|
||||
|
||||
export const feedbackSubmitResultSchema = z.discriminatedUnion('ok', [
|
||||
|
||||
Reference in New Issue
Block a user