chore: prepare GoodBuddy 0.8.6
Cross-platform packages / Validate source (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (arm64, linux, ubuntu-24.04-arm) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (arm64, macos, macos-15) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (arm64, windows, windows-2025) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (x64, linux, ubuntu-24.04) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (x64, macos, macos-15-intel) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (x64, windows, windows-2025) (push) Has been cancelled
Cross-platform packages / Publish GitHub Release (push) Has been cancelled
Cross-platform packages / Validate source (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (arm64, linux, ubuntu-24.04-arm) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (arm64, macos, macos-15) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (arm64, windows, windows-2025) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (x64, linux, ubuntu-24.04) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (x64, macos, macos-15-intel) (push) Has been cancelled
Cross-platform packages / ${{ matrix.platform }} ${{ matrix.arch }} (x64, windows, windows-2025) (push) Has been cancelled
Cross-platform packages / Publish GitHub Release (push) Has been cancelled
This commit is contained in:
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "goodbuddy",
|
"name": "goodbuddy",
|
||||||
"version": "0.8.5",
|
"version": "0.8.6",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "goodbuddy",
|
"name": "goodbuddy",
|
||||||
"version": "0.8.5",
|
"version": "0.8.6",
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modelcontextprotocol/sdk": "^1.30.0",
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "goodbuddy",
|
"name": "goodbuddy",
|
||||||
"version": "0.8.5",
|
"version": "0.8.6",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Secure desktop AI workspace with controlled Agent Runtimes",
|
"description": "Secure desktop AI workspace with controlled Agent Runtimes",
|
||||||
"desktopName": "GoodBuddy",
|
"desktopName": "GoodBuddy",
|
||||||
|
|||||||
@@ -77,7 +77,18 @@ async function createDistribution(version = '1.5.47'): Promise<{
|
|||||||
'listen(i,async()=>{console.log(Ht.green(`Server started on http://localhost:${i}`))',
|
'listen(i,async()=>{console.log(Ht.green(`Server started on http://localhost:${i}`))',
|
||||||
'async function SCt(e){return n5e||',
|
'async function SCt(e){return n5e||',
|
||||||
'shouldUseResponsesEndpoint(t){return this.config.useResponsesApi===!1?!1:this.apiBase==="https://api.openai.com/v1/"&&A0e(t)}',
|
'shouldUseResponsesEndpoint(t){return this.config.useResponsesApi===!1?!1:this.apiBase==="https://api.openai.com/v1/"&&A0e(t)}',
|
||||||
'function uAe(e,t){let n={provider:e.provider,model:e.model,apiKey:e.apiKey,apiBase:e.apiBase,requestOptions:e.requestOptions,env:e.env};return CGn(n)??null}'
|
'function uAe(e,t){let n={provider:e.provider,model:e.model,apiKey:e.apiKey,apiBase:e.apiBase,requestOptions:e.requestOptions,env:e.env};return CGn(n)??null}',
|
||||||
|
'function Csa(e){return process.platform==="win32"?{shell:"powershell.exe",args:["-NoLogo","-ExecutionPolicy","Bypass","-Command",e]}',
|
||||||
|
'a={onContent:u=>{},onContentComplete:u=>{},onToolStart:(u,l)=>{},onToolResult:(u,l,c)=>{},onToolError:(u,l)=>{},onToolPermissionRequest:',
|
||||||
|
'pendingPermission:null},B=',
|
||||||
|
'j.get("/state",(we,Te)=>{M.lastActivity=Date.now(),B();let ue=e7e(M.session,M.isProcessing,rS.getQueueLength(),M.pendingPermission);Te.json(ue)})',
|
||||||
|
'n?.onToolStart?.(i.name,i.arguments);',
|
||||||
|
'n?.onToolError?.(l,i.name)',
|
||||||
|
't?.onToolStart?.(c.name,c.arguments);',
|
||||||
|
't?.onToolResult?.(String(y.content),c.name,"canceled")',
|
||||||
|
't?.onToolResult?.(f,c.name,"done")',
|
||||||
|
't?.onToolError?.(g,c.name)',
|
||||||
|
't?.onToolError?.(p,c.name)'
|
||||||
].join(';')
|
].join(';')
|
||||||
await writeFile(join(distribution, 'index.js'), sourceBundle, 'utf8')
|
await writeFile(join(distribution, 'index.js'), sourceBundle, 'utf8')
|
||||||
return {
|
return {
|
||||||
@@ -138,6 +149,12 @@ describe('ContinueHostAdapter', () => {
|
|||||||
expect(bundle).toContain(
|
expect(bundle).toContain(
|
||||||
'useResponsesApi:e.useResponsesApi'
|
'useResponsesApi:e.useResponsesApi'
|
||||||
)
|
)
|
||||||
|
expect(bundle).toContain('"-NoProfile"')
|
||||||
|
expect(bundle).toContain('[Console]::OutputEncoding')
|
||||||
|
expect(bundle).toContain('goodbuddyEvents:[]')
|
||||||
|
expect(bundle).toContain('goodbuddyEvents:ce')
|
||||||
|
expect(bundle).toContain('type:"text",delta:u')
|
||||||
|
expect(bundle).toContain('onToolStart?.(c.name,c.arguments,c.id)')
|
||||||
expect(bundle).toContain(
|
expect(bundle).toContain(
|
||||||
'function ZZo(e){let t=[];if(e.allow)'
|
'function ZZo(e){let t=[];if(e.allow)'
|
||||||
)
|
)
|
||||||
@@ -394,7 +411,7 @@ describe('ContinueHostAdapter', () => {
|
|||||||
cacheWriteTokens: 0
|
cacheWriteTokens: 0
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
expect(launch?.entryPath).toContain('host-v4')
|
expect(launch?.entryPath).toContain('host-v6')
|
||||||
expect(launch?.args).toEqual([
|
expect(launch?.args).toEqual([
|
||||||
'--config',
|
'--config',
|
||||||
expect.stringContaining('model-config-'),
|
expect.stringContaining('model-config-'),
|
||||||
@@ -870,6 +887,7 @@ describe('ContinueHostAdapter', () => {
|
|||||||
const distribution = await createDistribution()
|
const distribution = await createDistribution()
|
||||||
let launchArgs: string[] = []
|
let launchArgs: string[] = []
|
||||||
const permissionBodies: unknown[] = []
|
const permissionBodies: unknown[] = []
|
||||||
|
const streamEvents: unknown[] = []
|
||||||
const launchHost: ContinueHostLauncher = (
|
const launchHost: ContinueHostLauncher = (
|
||||||
_entryPath,
|
_entryPath,
|
||||||
args
|
args
|
||||||
@@ -915,7 +933,16 @@ describe('ContinueHostAdapter', () => {
|
|||||||
toolName: 'Bash',
|
toolName: 'Bash',
|
||||||
toolArgs: { command: 'npm test' },
|
toolArgs: { command: 'npm test' },
|
||||||
requestId: 'permission-1'
|
requestId: 'permission-1'
|
||||||
}
|
},
|
||||||
|
goodbuddyEvents: [
|
||||||
|
{ type: 'text', delta: '先检查命令。' },
|
||||||
|
{
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Bash',
|
||||||
|
state: 'running'
|
||||||
|
}
|
||||||
|
]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return Response.json({
|
return Response.json({
|
||||||
@@ -940,7 +967,16 @@ describe('ContinueHostAdapter', () => {
|
|||||||
},
|
},
|
||||||
isProcessing: false,
|
isProcessing: false,
|
||||||
messageQueueLength: 0,
|
messageQueueLength: 0,
|
||||||
pendingPermission: null
|
pendingPermission: null,
|
||||||
|
goodbuddyEvents: [
|
||||||
|
{
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Bash',
|
||||||
|
state: 'completed'
|
||||||
|
},
|
||||||
|
{ type: 'text', delta: 'TOOLS_OK' }
|
||||||
|
]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return Response.json({})
|
return Response.json({})
|
||||||
@@ -959,9 +995,19 @@ describe('ContinueHostAdapter', () => {
|
|||||||
const authorize = vi.fn(async () => 'once' as const)
|
const authorize = vi.fn(async () => 'once' as const)
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
adapter.run('hello', new AbortController().signal, authorize)
|
adapter.run(
|
||||||
|
'hello',
|
||||||
|
new AbortController().signal,
|
||||||
|
authorize,
|
||||||
|
{
|
||||||
|
onEvent: (event) => {
|
||||||
|
streamEvents.push(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
).resolves.toEqual({
|
).resolves.toEqual({
|
||||||
text: 'TOOLS_OK',
|
text: 'TOOLS_OK',
|
||||||
|
streamedText: true,
|
||||||
tools: [
|
tools: [
|
||||||
{
|
{
|
||||||
callId: 'call-1',
|
callId: 'call-1',
|
||||||
@@ -970,6 +1016,26 @@ describe('ContinueHostAdapter', () => {
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
expect(streamEvents).toEqual([
|
||||||
|
{ type: 'text', delta: '先检查命令。' },
|
||||||
|
{
|
||||||
|
type: 'tool',
|
||||||
|
tool: {
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Bash',
|
||||||
|
state: 'running'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'tool',
|
||||||
|
tool: {
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Bash',
|
||||||
|
state: 'completed'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ type: 'text', delta: 'TOOLS_OK' }
|
||||||
|
])
|
||||||
expect(launchArgs).not.toContain('--readonly')
|
expect(launchArgs).not.toContain('--readonly')
|
||||||
expect(authorize).toHaveBeenCalledWith(
|
expect(authorize).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({ toolName: 'Bash' })
|
expect.objectContaining({ toolName: 'Bash' })
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ const maximumBundleBytes = 32 * 1024 * 1024
|
|||||||
const maximumStateBytes = 8 * 1024 * 1024
|
const maximumStateBytes = 8 * 1024 * 1024
|
||||||
const maximumConfigBytes = 1024 * 1024
|
const maximumConfigBytes = 1024 * 1024
|
||||||
const maximumConfiguredMcpServers = 100
|
const maximumConfiguredMcpServers = 100
|
||||||
|
const maximumStreamEvents = 5_000
|
||||||
const knowledgeMcpName = 'goodbuddy-knowledge'
|
const knowledgeMcpName = 'goodbuddy-knowledge'
|
||||||
export const continueConfigurationRequiredMessage =
|
export const continueConfigurationRequiredMessage =
|
||||||
'Continue 尚未配置模型连接,请在设置中选择 GoodBuddy 模型连接或指定 Continue 配置文件'
|
'Continue 尚未配置模型连接,请在设置中选择 GoodBuddy 模型连接或指定 Continue 配置文件'
|
||||||
@@ -74,6 +75,24 @@ const sessionUsageSchema = z.object({
|
|||||||
.optional()
|
.optional()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const continueHostStreamEventSchema = z.discriminatedUnion('type', [
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
type: z.literal('text'),
|
||||||
|
delta: z.string().min(1).max(100_000)
|
||||||
|
})
|
||||||
|
.strict(),
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
type: z.literal('tool'),
|
||||||
|
callId: z.string().min(1).max(256),
|
||||||
|
name: z.string().min(1).max(200),
|
||||||
|
state: z.enum(['running', 'completed', 'failed']),
|
||||||
|
error: z.string().max(1_000).optional()
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
])
|
||||||
|
|
||||||
const stateSchema = z.object({
|
const stateSchema = z.object({
|
||||||
session: z.object({
|
session: z.object({
|
||||||
history: z.array(z.unknown()).max(5_000),
|
history: z.array(z.unknown()).max(5_000),
|
||||||
@@ -88,7 +107,11 @@ const stateSchema = z.object({
|
|||||||
requestId: z.string().min(1).max(256),
|
requestId: z.string().min(1).max(256),
|
||||||
toolCallPreview: z.array(z.unknown()).max(100).optional()
|
toolCallPreview: z.array(z.unknown()).max(100).optional()
|
||||||
})
|
})
|
||||||
.nullable()
|
.nullable(),
|
||||||
|
goodbuddyEvents: z
|
||||||
|
.array(continueHostStreamEventSchema)
|
||||||
|
.max(maximumStreamEvents)
|
||||||
|
.optional()
|
||||||
})
|
})
|
||||||
|
|
||||||
type ContinueHostState = z.infer<typeof stateSchema>
|
type ContinueHostState = z.infer<typeof stateSchema>
|
||||||
@@ -124,10 +147,15 @@ export type ContinueHostTool = {
|
|||||||
|
|
||||||
export type ContinueHostRunResult = {
|
export type ContinueHostRunResult = {
|
||||||
text: string
|
text: string
|
||||||
|
streamedText?: true
|
||||||
usage?: ContinueHostUsage
|
usage?: ContinueHostUsage
|
||||||
tools?: ContinueHostTool[]
|
tools?: ContinueHostTool[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ContinueHostStreamEvent =
|
||||||
|
| { type: 'text'; delta: string }
|
||||||
|
| { type: 'tool'; tool: ContinueHostTool }
|
||||||
|
|
||||||
export class ContinueHostRunError extends Error {
|
export class ContinueHostRunError extends Error {
|
||||||
constructor(
|
constructor(
|
||||||
message: string,
|
message: string,
|
||||||
@@ -158,6 +186,7 @@ export type ContinueHostRunOptions = {
|
|||||||
endpoint: string
|
endpoint: string
|
||||||
token: string
|
token: string
|
||||||
}
|
}
|
||||||
|
onEvent?: (event: ContinueHostStreamEvent) => void | Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
type KnowledgeCapability = NonNullable<
|
type KnowledgeCapability = NonNullable<
|
||||||
@@ -434,7 +463,7 @@ function extractContinueTools(
|
|||||||
: 'failed'
|
: 'failed'
|
||||||
const error =
|
const error =
|
||||||
normalizedState === 'failed'
|
normalizedState === 'failed'
|
||||||
? safeToolErrorDetail(state.output)
|
? normalizeContinueToolError(state.output)
|
||||||
: undefined
|
: undefined
|
||||||
tools.set(callId, {
|
tools.set(callId, {
|
||||||
callId,
|
callId,
|
||||||
@@ -447,6 +476,28 @@ function extractContinueTools(
|
|||||||
return [...tools.values()]
|
return [...tools.values()]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mergeContinueTools(
|
||||||
|
current: ContinueHostTool[],
|
||||||
|
updates: ContinueHostTool[]
|
||||||
|
): ContinueHostTool[] {
|
||||||
|
const tools = new Map(current.map((tool) => [tool.callId, tool]))
|
||||||
|
for (const tool of updates) {
|
||||||
|
tools.set(tool.callId, tool)
|
||||||
|
}
|
||||||
|
return [...tools.values()]
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeContinueToolError(value: unknown): string | undefined {
|
||||||
|
const detail = safeToolErrorDetail(value)
|
||||||
|
if (!detail) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
const replacementCharacters = detail.match(/\uFFFD/gu)?.length ?? 0
|
||||||
|
return replacementCharacters >= 3
|
||||||
|
? 'PowerShell 输出编码异常,原始错误无法安全显示;请重试该命令'
|
||||||
|
: detail
|
||||||
|
}
|
||||||
|
|
||||||
function subtractTokenCount(completed: number, initial: number): number {
|
function subtractTokenCount(completed: number, initial: number): number {
|
||||||
return Math.max(0, completed - initial)
|
return Math.max(0, completed - initial)
|
||||||
}
|
}
|
||||||
@@ -538,6 +589,25 @@ export class ContinueHostAdapter {
|
|||||||
'shouldUseResponsesEndpoint(t){return this.config.useResponsesApi===!1?!1:this.apiBase==="https://api.openai.com/v1/"&&A0e(t)}'
|
'shouldUseResponsesEndpoint(t){return this.config.useResponsesApi===!1?!1:this.apiBase==="https://api.openai.com/v1/"&&A0e(t)}'
|
||||||
const modelConfigurationMarker =
|
const modelConfigurationMarker =
|
||||||
'function uAe(e,t){let n={provider:e.provider,model:e.model,apiKey:e.apiKey,apiBase:e.apiBase,requestOptions:e.requestOptions,env:e.env};return CGn(n)??null}'
|
'function uAe(e,t){let n={provider:e.provider,model:e.model,apiKey:e.apiKey,apiBase:e.apiBase,requestOptions:e.requestOptions,env:e.env};return CGn(n)??null}'
|
||||||
|
const windowsShellMarker =
|
||||||
|
'function Csa(e){return process.platform==="win32"?{shell:"powershell.exe",args:["-NoLogo","-ExecutionPolicy","Bypass","-Command",e]}'
|
||||||
|
const streamCallbacksMarker =
|
||||||
|
'a={onContent:u=>{},onContentComplete:u=>{},onToolStart:(u,l)=>{},onToolResult:(u,l,c)=>{},onToolError:(u,l)=>{},onToolPermissionRequest:'
|
||||||
|
const serverStateMarker = 'pendingPermission:null},B='
|
||||||
|
const serverStateEndpointMarker =
|
||||||
|
'j.get("/state",(we,Te)=>{M.lastActivity=Date.now(),B();let ue=e7e(M.session,M.isProcessing,rS.getQueueLength(),M.pendingPermission);Te.json(ue)})'
|
||||||
|
const preprocessToolStartMarker =
|
||||||
|
'n?.onToolStart?.(i.name,i.arguments);'
|
||||||
|
const preprocessToolErrorMarker =
|
||||||
|
'n?.onToolError?.(l,i.name)'
|
||||||
|
const executeToolStartMarker =
|
||||||
|
't?.onToolStart?.(c.name,c.arguments);'
|
||||||
|
const cancelledToolResultMarker =
|
||||||
|
't?.onToolResult?.(String(y.content),c.name,"canceled")'
|
||||||
|
const completedToolResultMarker =
|
||||||
|
't?.onToolResult?.(f,c.name,"done")'
|
||||||
|
const failedToolResultMarker = 't?.onToolError?.(g,c.name)'
|
||||||
|
const permissionToolErrorMarker = 't?.onToolError?.(p,c.name)'
|
||||||
let patched = replaceExactly(
|
let patched = replaceExactly(
|
||||||
sourceBundle,
|
sourceBundle,
|
||||||
serveInitializationMarker,
|
serveInitializationMarker,
|
||||||
@@ -583,11 +653,66 @@ export class ContinueHostAdapter {
|
|||||||
modelConfigurationMarker,
|
modelConfigurationMarker,
|
||||||
'function uAe(e,t){let n={provider:e.provider,model:e.model,apiKey:e.apiKey,apiBase:e.apiBase,requestOptions:e.requestOptions,env:e.env,useResponsesApi:e.useResponsesApi};return CGn(n)??null}'
|
'function uAe(e,t){let n={provider:e.provider,model:e.model,apiKey:e.apiKey,apiBase:e.apiBase,requestOptions:e.requestOptions,env:e.env,useResponsesApi:e.useResponsesApi};return CGn(n)??null}'
|
||||||
)
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
windowsShellMarker,
|
||||||
|
'function Csa(e){return process.platform==="win32"?{shell:"powershell.exe",args:["-NoLogo","-NoProfile","-ExecutionPolicy","Bypass","-Command",\'[Console]::InputEncoding=[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);$OutputEncoding=[Console]::OutputEncoding;\'+e]}'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
streamCallbacksMarker,
|
||||||
|
'a={onContent:u=>{u&&e.goodbuddyEvents.length<5e3&&e.goodbuddyEvents.push({type:"text",delta:u})},onContentComplete:u=>{},onToolStart:(u,l,c)=>{c&&e.goodbuddyEvents.length<5e3&&e.goodbuddyEvents.push({type:"tool",callId:c,name:u,state:"running"})},onToolResult:(u,l,c,d)=>{d&&e.goodbuddyEvents.length<5e3&&e.goodbuddyEvents.push({type:"tool",callId:d,name:l,state:c==="done"?"completed":"failed"})},onToolError:(u,l,c)=>{c&&e.goodbuddyEvents.length<5e3&&e.goodbuddyEvents.push({type:"tool",callId:c,name:l??"unknown",state:"failed",error:String(u).slice(0,1e3)})},onToolPermissionRequest:'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
serverStateMarker,
|
||||||
|
'pendingPermission:null,goodbuddyEvents:[]},B='
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
serverStateEndpointMarker,
|
||||||
|
'j.get("/state",(we,Te)=>{M.lastActivity=Date.now(),B();let ue=e7e(M.session,M.isProcessing,rS.getQueueLength(),M.pendingPermission),ce=M.goodbuddyEvents.splice(0);Te.json({...ue,goodbuddyEvents:ce})})'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
preprocessToolStartMarker,
|
||||||
|
'n?.onToolStart?.(i.name,i.arguments,i.id);'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
preprocessToolErrorMarker,
|
||||||
|
'n?.onToolError?.(l,i.name,i.id)'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
executeToolStartMarker,
|
||||||
|
't?.onToolStart?.(c.name,c.arguments,c.id);'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
cancelledToolResultMarker,
|
||||||
|
't?.onToolResult?.(String(y.content),c.name,"canceled",c.id)'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
completedToolResultMarker,
|
||||||
|
't?.onToolResult?.(f,c.name,"done",c.id)'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
failedToolResultMarker,
|
||||||
|
't?.onToolError?.(g,c.name,c.id)'
|
||||||
|
)
|
||||||
|
patched = replaceExactly(
|
||||||
|
patched,
|
||||||
|
permissionToolErrorMarker,
|
||||||
|
't?.onToolError?.(p,c.name,c.id)'
|
||||||
|
)
|
||||||
const patchedHash = hashContents(patched)
|
const patchedHash = hashContents(patched)
|
||||||
const digest = sourceHash.slice(0, 16)
|
const digest = sourceHash.slice(0, 16)
|
||||||
const targetRoot = join(
|
const targetRoot = join(
|
||||||
this.options.cacheRoot,
|
this.options.cacheRoot,
|
||||||
`host-v4-${supportedVersion}-${digest}`
|
`host-v6-${supportedVersion}-${digest}`
|
||||||
)
|
)
|
||||||
const targetDist = join(targetRoot, 'dist')
|
const targetDist = join(targetRoot, 'dist')
|
||||||
const targetBundle = join(targetDist, 'index.js')
|
const targetBundle = join(targetDist, 'index.js')
|
||||||
@@ -942,6 +1067,7 @@ export class ContinueHostAdapter {
|
|||||||
signal.addEventListener('abort', abort, { once: true })
|
signal.addEventListener('abort', abort, { once: true })
|
||||||
|
|
||||||
let observedTools: ContinueHostTool[] = []
|
let observedTools: ContinueHostTool[] = []
|
||||||
|
let streamedText = false
|
||||||
try {
|
try {
|
||||||
const initialState = await this.waitForStartup(
|
const initialState = await this.waitForStartup(
|
||||||
child,
|
child,
|
||||||
@@ -972,10 +1098,27 @@ export class ContinueHostAdapter {
|
|||||||
const state = stateSchema.parse(
|
const state = stateSchema.parse(
|
||||||
await this.request(origin, token, '/state', { signal })
|
await this.request(origin, token, '/state', { signal })
|
||||||
)
|
)
|
||||||
observedTools = extractContinueTools(
|
observedTools = mergeContinueTools(
|
||||||
state.session.history,
|
observedTools,
|
||||||
startIndex
|
extractContinueTools(state.session.history, startIndex)
|
||||||
)
|
)
|
||||||
|
for (const event of state.goodbuddyEvents ?? []) {
|
||||||
|
if (event.type === 'text') {
|
||||||
|
streamedText = true
|
||||||
|
await runOptions.onEvent?.(event)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const tool: ContinueHostTool = {
|
||||||
|
callId: event.callId,
|
||||||
|
name: event.name,
|
||||||
|
state: event.state,
|
||||||
|
...(event.error
|
||||||
|
? { error: normalizeContinueToolError(event.error) }
|
||||||
|
: {})
|
||||||
|
}
|
||||||
|
observedTools = mergeContinueTools(observedTools, [tool])
|
||||||
|
await runOptions.onEvent?.({ type: 'tool', tool })
|
||||||
|
}
|
||||||
const pending = state.pendingPermission
|
const pending = state.pendingPermission
|
||||||
if (pending && !handledPermissionIds.has(pending.requestId)) {
|
if (pending && !handledPermissionIds.has(pending.requestId)) {
|
||||||
if (handledPermissionIds.size >= 100) {
|
if (handledPermissionIds.size >= 100) {
|
||||||
@@ -1053,6 +1196,7 @@ export class ContinueHostAdapter {
|
|||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
text,
|
text,
|
||||||
|
...(streamedText ? { streamedText: true as const } : {}),
|
||||||
...(usage ? { usage } : {}),
|
...(usage ? { usage } : {}),
|
||||||
...(observedTools.length > 0
|
...(observedTools.length > 0
|
||||||
? { tools: observedTools }
|
? { tools: observedTools }
|
||||||
|
|||||||
@@ -101,7 +101,10 @@ describe('ContinueAgentRuntime', () => {
|
|||||||
expect(mocks.runHost).toHaveBeenCalledWith(
|
expect(mocks.runHost).toHaveBeenCalledWith(
|
||||||
'test',
|
'test',
|
||||||
expect.any(AbortSignal),
|
expect.any(AbortSignal),
|
||||||
expect.any(Function)
|
expect.any(Function),
|
||||||
|
expect.objectContaining({
|
||||||
|
onEvent: expect.any(Function)
|
||||||
|
})
|
||||||
)
|
)
|
||||||
expect(events).toContainEqual({
|
expect(events).toContainEqual({
|
||||||
requestId: '3f496642-f47d-4e0a-8944-a32c77b0d6ef',
|
requestId: '3f496642-f47d-4e0a-8944-a32c77b0d6ef',
|
||||||
@@ -189,7 +192,8 @@ describe('ContinueAgentRuntime', () => {
|
|||||||
knowledgeCapability: {
|
knowledgeCapability: {
|
||||||
endpoint: 'http://127.0.0.1:4567/mcp',
|
endpoint: 'http://127.0.0.1:4567/mcp',
|
||||||
token: 'main-only-token'
|
token: 'main-only-token'
|
||||||
}
|
},
|
||||||
|
onEvent: expect.any(Function)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
const authorize = mocks.runHost.mock.calls[0]?.[2]
|
const authorize = mocks.runHost.mock.calls[0]?.[2]
|
||||||
@@ -403,6 +407,74 @@ describe('ContinueAgentRuntime', () => {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('forwards streamed text and tool events in host order', async () => {
|
||||||
|
mocks.runHost.mockImplementation(
|
||||||
|
async (
|
||||||
|
_prompt,
|
||||||
|
_signal,
|
||||||
|
_authorize,
|
||||||
|
options
|
||||||
|
) => {
|
||||||
|
await options?.onEvent?.({
|
||||||
|
type: 'text',
|
||||||
|
delta: '先分析'
|
||||||
|
})
|
||||||
|
await options?.onEvent?.({
|
||||||
|
type: 'tool',
|
||||||
|
tool: {
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Read',
|
||||||
|
state: 'running'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await options?.onEvent?.({
|
||||||
|
type: 'tool',
|
||||||
|
tool: {
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Read',
|
||||||
|
state: 'completed'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await options?.onEvent?.({
|
||||||
|
type: 'text',
|
||||||
|
delta: '再回答'
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
text: '再回答',
|
||||||
|
streamedText: true,
|
||||||
|
tools: [
|
||||||
|
{
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'Read',
|
||||||
|
state: 'completed'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const events = await collectEvents(createRuntime(), 'execute')
|
||||||
|
|
||||||
|
expect(
|
||||||
|
events.filter(
|
||||||
|
(event) => event.type === 'text' || event.type === 'tool'
|
||||||
|
)
|
||||||
|
).toEqual([
|
||||||
|
expect.objectContaining({ type: 'text', delta: '先分析' }),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
state: 'running'
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
state: 'completed'
|
||||||
|
}),
|
||||||
|
expect.objectContaining({ type: 'text', delta: '再回答' })
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
it('emits terminal tool audits before a failed Continue run', async () => {
|
it('emits terminal tool audits before a failed Continue run', async () => {
|
||||||
mocks.runHost.mockRejectedValue(
|
mocks.runHost.mockRejectedValue(
|
||||||
new ContinueHostRunError('Continue failed', {
|
new ContinueHostRunError('Continue failed', {
|
||||||
@@ -441,7 +513,7 @@ describe('ContinueAgentRuntime', () => {
|
|||||||
await expect(stream.next()).rejects.toThrow('Continue failed')
|
await expect(stream.next()).rejects.toThrow('Continue failed')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('returns a failed Continue tool detail through AgentRuntime', async () => {
|
it('keeps a completed Continue response when an earlier tool attempt failed', async () => {
|
||||||
mocks.runHost.mockResolvedValue({
|
mocks.runHost.mockResolvedValue({
|
||||||
text: 'Continue response',
|
text: 'Continue response',
|
||||||
tools: [
|
tools: [
|
||||||
@@ -466,17 +538,25 @@ describe('ContinueAgentRuntime', () => {
|
|||||||
await expect(stream.next()).resolves.toMatchObject({
|
await expect(stream.next()).resolves.toMatchObject({
|
||||||
value: { type: 'status' }
|
value: { type: 'status' }
|
||||||
})
|
})
|
||||||
await expect(stream.next()).resolves.toMatchObject({
|
const events: RuntimeEvent[] = []
|
||||||
value: {
|
for await (const event of stream) {
|
||||||
|
events.push(event)
|
||||||
|
}
|
||||||
|
expect(events).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
type: 'tool',
|
type: 'tool',
|
||||||
callId: 'call-1',
|
callId: 'call-1',
|
||||||
state: 'failed',
|
state: 'recoverable',
|
||||||
error: 'PowerShell EmptyPipeElement'
|
error: 'PowerShell EmptyPipeElement'
|
||||||
}
|
})
|
||||||
})
|
|
||||||
await expect(stream.next()).rejects.toThrow(
|
|
||||||
'PowerShell EmptyPipeElement'
|
|
||||||
)
|
)
|
||||||
|
expect(events).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'text',
|
||||||
|
delta: 'Continue response'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(events.at(-1)).toMatchObject({ type: 'done' })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fails a run that returns a nonterminal tool state', async () => {
|
it('fails a run that returns a nonterminal tool state', async () => {
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import {
|
|||||||
type ContinueHostAdapterOptions,
|
type ContinueHostAdapterOptions,
|
||||||
type ContinueHostLauncher,
|
type ContinueHostLauncher,
|
||||||
type ContinueHostRunResult,
|
type ContinueHostRunResult,
|
||||||
|
type ContinueHostStreamEvent,
|
||||||
type ContinueHostTool
|
type ContinueHostTool
|
||||||
} from './continue-host-adapter'
|
} from './continue-host-adapter'
|
||||||
|
|
||||||
@@ -56,7 +57,8 @@ function continueToolFailureMessage(tool: ContinueHostTool): string {
|
|||||||
function toContinueToolEvent(
|
function toContinueToolEvent(
|
||||||
requestId: string,
|
requestId: string,
|
||||||
tool: ContinueHostTool,
|
tool: ContinueHostTool,
|
||||||
terminalize: boolean
|
terminalize: boolean,
|
||||||
|
recoverFailure = false
|
||||||
): Extract<AgentEvent, { type: 'tool' }> {
|
): Extract<AgentEvent, { type: 'tool' }> {
|
||||||
return {
|
return {
|
||||||
requestId,
|
requestId,
|
||||||
@@ -64,7 +66,9 @@ function toContinueToolEvent(
|
|||||||
callId: tool.callId,
|
callId: tool.callId,
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
state:
|
state:
|
||||||
terminalize && tool.state !== 'completed'
|
recoverFailure && tool.state === 'failed'
|
||||||
|
? 'recoverable'
|
||||||
|
: terminalize && tool.state !== 'completed'
|
||||||
? 'failed'
|
? 'failed'
|
||||||
: tool.state,
|
: tool.state,
|
||||||
summary: `Continue 工具:${tool.name}`,
|
summary: `Continue 工具:${tool.name}`,
|
||||||
@@ -283,6 +287,7 @@ export class ContinueAgentRuntime implements AgentRuntime {
|
|||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
let result: ContinueHostRunResult
|
let result: ContinueHostRunResult
|
||||||
|
const emittedTools = new Map<string, ContinueHostTool>()
|
||||||
try {
|
try {
|
||||||
const host = this.getHostAdapter(
|
const host = this.getHostAdapter(
|
||||||
binaryPath,
|
binaryPath,
|
||||||
@@ -299,17 +304,72 @@ export class ContinueAgentRuntime implements AgentRuntime {
|
|||||||
approval.toolName === 'knowledge_search')
|
approval.toolName === 'knowledge_search')
|
||||||
? 'once' as const
|
? 'once' as const
|
||||||
: 'deny' as const
|
: 'deny' as const
|
||||||
result = knowledgeCapability
|
const queuedEvents: ContinueHostStreamEvent[] = []
|
||||||
? await host.run(
|
let wakeStream: (() => void) | undefined
|
||||||
conversationContext,
|
let streamFinished = false
|
||||||
signal,
|
let streamResult: ContinueHostRunResult | undefined
|
||||||
authorize,
|
let streamError: unknown
|
||||||
{
|
const onEvent = (event: ContinueHostStreamEvent): void => {
|
||||||
workMode: request.workMode,
|
queuedEvents.push(event)
|
||||||
knowledgeCapability
|
wakeStream?.()
|
||||||
|
wakeStream = undefined
|
||||||
|
}
|
||||||
|
const hostRun = host
|
||||||
|
.run(
|
||||||
|
conversationContext,
|
||||||
|
signal,
|
||||||
|
authorize,
|
||||||
|
{
|
||||||
|
workMode: request.workMode,
|
||||||
|
...(knowledgeCapability ? { knowledgeCapability } : {}),
|
||||||
|
onEvent
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.then(
|
||||||
|
(value) => {
|
||||||
|
streamResult = value
|
||||||
|
},
|
||||||
|
(error: unknown) => {
|
||||||
|
streamError = error
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.finally(() => {
|
||||||
|
streamFinished = true
|
||||||
|
wakeStream?.()
|
||||||
|
wakeStream = undefined
|
||||||
|
})
|
||||||
|
|
||||||
|
while (!streamFinished || queuedEvents.length > 0) {
|
||||||
|
if (queuedEvents.length === 0) {
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
wakeStream = resolve
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const event = queuedEvents.shift()!
|
||||||
|
if (event.type === 'tool') {
|
||||||
|
emittedTools.set(event.tool.callId, event.tool)
|
||||||
|
}
|
||||||
|
yield event.type === 'text'
|
||||||
|
? {
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'text',
|
||||||
|
delta: event.delta
|
||||||
}
|
}
|
||||||
)
|
: toContinueToolEvent(
|
||||||
: await host.run(conversationContext, signal, authorize)
|
request.requestId,
|
||||||
|
event.tool,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
await hostRun
|
||||||
|
if (streamError) {
|
||||||
|
throw streamError
|
||||||
|
}
|
||||||
|
if (!streamResult) {
|
||||||
|
throw new Error('Continue 宿主未返回运行结果')
|
||||||
|
}
|
||||||
|
result = streamResult
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ContinueHostRunError) {
|
if (error instanceof ContinueHostRunError) {
|
||||||
for (const tool of error.tools) {
|
for (const tool of error.tools) {
|
||||||
@@ -323,23 +383,50 @@ export class ContinueAgentRuntime implements AgentRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const tools = result.tools ?? []
|
const tools = result.tools ?? []
|
||||||
const unsuccessfulTool = tools.find(
|
const incompleteTool = tools.find(
|
||||||
(tool) => tool.state !== 'completed'
|
(tool) => tool.state === 'pending' || tool.state === 'running'
|
||||||
)
|
)
|
||||||
if (unsuccessfulTool) {
|
if (incompleteTool) {
|
||||||
for (const tool of tools) {
|
for (const tool of tools) {
|
||||||
yield toContinueToolEvent(request.requestId, tool, true)
|
const terminalEvent = toContinueToolEvent(
|
||||||
|
request.requestId,
|
||||||
|
tool,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
const previous = emittedTools.get(tool.callId)
|
||||||
|
if (
|
||||||
|
!previous ||
|
||||||
|
previous.state !== terminalEvent.state ||
|
||||||
|
previous.error !== terminalEvent.error
|
||||||
|
) {
|
||||||
|
yield terminalEvent
|
||||||
|
}
|
||||||
}
|
}
|
||||||
throw new Error(continueToolFailureMessage(unsuccessfulTool))
|
throw new Error(continueToolFailureMessage(incompleteTool))
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const tool of tools) {
|
for (const tool of tools) {
|
||||||
yield toContinueToolEvent(request.requestId, tool, false)
|
const finalEvent = toContinueToolEvent(
|
||||||
|
request.requestId,
|
||||||
|
tool,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
const previous = emittedTools.get(tool.callId)
|
||||||
|
if (
|
||||||
|
!previous ||
|
||||||
|
previous.state !== finalEvent.state ||
|
||||||
|
previous.error !== finalEvent.error
|
||||||
|
) {
|
||||||
|
yield finalEvent
|
||||||
|
}
|
||||||
}
|
}
|
||||||
yield {
|
if (!result.streamedText) {
|
||||||
requestId: request.requestId,
|
yield {
|
||||||
type: 'text',
|
requestId: request.requestId,
|
||||||
delta: result.text
|
type: 'text',
|
||||||
|
delta: result.text
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (result.usage) {
|
if (result.usage) {
|
||||||
const usage = result.usage
|
const usage = result.usage
|
||||||
|
|||||||
@@ -153,6 +153,14 @@ function runClient(events: Record<string, unknown>[]) {
|
|||||||
data: true,
|
data: true,
|
||||||
error: undefined
|
error: undefined
|
||||||
})
|
})
|
||||||
|
const questionReply = vi.fn().mockResolvedValue({
|
||||||
|
data: true,
|
||||||
|
error: undefined
|
||||||
|
})
|
||||||
|
const questionReject = vi.fn().mockResolvedValue({
|
||||||
|
data: true,
|
||||||
|
error: undefined
|
||||||
|
})
|
||||||
const client = {
|
const client = {
|
||||||
session: {
|
session: {
|
||||||
list: vi.fn().mockResolvedValue({ data: [], error: undefined }),
|
list: vi.fn().mockResolvedValue({ data: [], error: undefined }),
|
||||||
@@ -192,6 +200,10 @@ function runClient(events: Record<string, unknown>[]) {
|
|||||||
permission: {
|
permission: {
|
||||||
reply: permissionReply
|
reply: permissionReply
|
||||||
},
|
},
|
||||||
|
question: {
|
||||||
|
reply: questionReply,
|
||||||
|
reject: questionReject
|
||||||
|
},
|
||||||
mcp: {
|
mcp: {
|
||||||
add: vi
|
add: vi
|
||||||
.fn()
|
.fn()
|
||||||
@@ -218,6 +230,8 @@ function runClient(events: Record<string, unknown>[]) {
|
|||||||
client,
|
client,
|
||||||
callOrder,
|
callOrder,
|
||||||
permissionReply,
|
permissionReply,
|
||||||
|
questionReply,
|
||||||
|
questionReject,
|
||||||
session: client.session,
|
session: client.session,
|
||||||
event: client.event,
|
event: client.event,
|
||||||
tool: client.tool
|
tool: client.tool
|
||||||
@@ -978,6 +992,84 @@ describe('OpenCodeRuntime embedded launcher', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('OpenCodeRuntime embedded permission mediation', () => {
|
describe('OpenCodeRuntime embedded permission mediation', () => {
|
||||||
|
it('parses OpenCode questions and sends the selected answers back', async () => {
|
||||||
|
const setup = runClient([
|
||||||
|
{
|
||||||
|
id: 'question-event',
|
||||||
|
type: 'question.asked',
|
||||||
|
properties: {
|
||||||
|
id: 'question-1',
|
||||||
|
sessionID: 'session-1',
|
||||||
|
questions: [
|
||||||
|
{
|
||||||
|
header: '实现方式',
|
||||||
|
question: '请选择实现方式',
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
label: '直接修改',
|
||||||
|
description: '立即更新现有实现'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '先写测试',
|
||||||
|
description: '先增加回归测试'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
multiple: false,
|
||||||
|
custom: true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
tool: {
|
||||||
|
messageID: 'message-1',
|
||||||
|
callID: 'call-question-1'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'idle',
|
||||||
|
type: 'session.idle',
|
||||||
|
properties: { sessionID: 'session-1' }
|
||||||
|
}
|
||||||
|
])
|
||||||
|
const runtime = embeddedRuntime(setup.client)
|
||||||
|
const stream = runtime.run(
|
||||||
|
{
|
||||||
|
requestId: '3f496642-f47d-4e0a-8944-a32c77b0d6ef',
|
||||||
|
conversationId: 'conversation-1',
|
||||||
|
prompt: 'test',
|
||||||
|
workMode: 'execute'
|
||||||
|
},
|
||||||
|
new AbortController().signal
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(stream.next()).resolves.toMatchObject({
|
||||||
|
value: { type: 'status' }
|
||||||
|
})
|
||||||
|
await expect(stream.next()).resolves.toMatchObject({
|
||||||
|
value: {
|
||||||
|
type: 'question',
|
||||||
|
questionId: 'question-1',
|
||||||
|
questions: [
|
||||||
|
{
|
||||||
|
header: '实现方式',
|
||||||
|
question: '请选择实现方式',
|
||||||
|
multiple: false,
|
||||||
|
custom: true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await runtime.respondToQuestion('question-1', [['先写测试']])
|
||||||
|
expect(setup.questionReply).toHaveBeenCalledWith({
|
||||||
|
requestID: 'question-1',
|
||||||
|
directory: process.cwd(),
|
||||||
|
answers: [['先写测试']]
|
||||||
|
})
|
||||||
|
await expect(stream.next()).resolves.toMatchObject({
|
||||||
|
value: { type: 'done' }
|
||||||
|
})
|
||||||
|
await runtime.dispose()
|
||||||
|
})
|
||||||
|
|
||||||
it('adds only the request-scoped knowledge MCP tool for Ask and disconnects it', async () => {
|
it('adds only the request-scoped knowledge MCP tool for Ask and disconnects it', async () => {
|
||||||
const setup = runClient([
|
const setup = runClient([
|
||||||
{
|
{
|
||||||
@@ -1420,6 +1512,33 @@ describe('OpenCodeRuntime embedded permission mediation', () => {
|
|||||||
delta: 'approved output'
|
delta: 'approved output'
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
expect(
|
||||||
|
events.filter(
|
||||||
|
(event) =>
|
||||||
|
event.type === 'reasoning' ||
|
||||||
|
event.type === 'text' ||
|
||||||
|
event.type === 'tool'
|
||||||
|
)
|
||||||
|
).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
state: 'pending'
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
state: 'completed'
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'reasoning',
|
||||||
|
delta: 'reasoning output'
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'text',
|
||||||
|
delta: 'approved output'
|
||||||
|
})
|
||||||
|
])
|
||||||
expect(events.at(-1)).toMatchObject({ type: 'done' })
|
expect(events.at(-1)).toMatchObject({ type: 'done' })
|
||||||
await runtime.dispose()
|
await runtime.dispose()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,12 +3,16 @@ import {
|
|||||||
type AssistantMessage,
|
type AssistantMessage,
|
||||||
type OpencodeClient,
|
type OpencodeClient,
|
||||||
type PermissionRequest,
|
type PermissionRequest,
|
||||||
type PermissionRuleset
|
type PermissionRuleset,
|
||||||
|
type QuestionRequest
|
||||||
} from '@opencode-ai/sdk/v2'
|
} from '@opencode-ai/sdk/v2'
|
||||||
import spawn from 'cross-spawn'
|
import spawn from 'cross-spawn'
|
||||||
import { createHash, randomBytes } from 'node:crypto'
|
import { createHash, randomBytes } from 'node:crypto'
|
||||||
import { resolve } from 'node:path'
|
import { resolve } from 'node:path'
|
||||||
import type { AgentRuntimeStatus } from '../../shared/contracts'
|
import type {
|
||||||
|
AgentQuestionAnswer,
|
||||||
|
AgentRuntimeStatus
|
||||||
|
} from '../../shared/contracts'
|
||||||
import { createAnthropicApiBaseUrl } from './anthropic-endpoint'
|
import { createAnthropicApiBaseUrl } from './anthropic-endpoint'
|
||||||
import { createOpenAIApiBaseUrl } from './openai-endpoint'
|
import { createOpenAIApiBaseUrl } from './openai-endpoint'
|
||||||
import type {
|
import type {
|
||||||
@@ -42,6 +46,9 @@ const MAX_PERMISSION_PATTERN_LENGTH = 1_024
|
|||||||
const MAX_PERMISSION_PATTERNS_BYTES = 8 * 1_024
|
const MAX_PERMISSION_PATTERNS_BYTES = 8 * 1_024
|
||||||
const MAX_PERMISSION_METADATA_BYTES = 8 * 1_024
|
const MAX_PERMISSION_METADATA_BYTES = 8 * 1_024
|
||||||
const MAX_TOOL_CALLS_PER_RUN = 100
|
const MAX_TOOL_CALLS_PER_RUN = 100
|
||||||
|
const MAX_QUESTION_REQUEST_BYTES = 32 * 1_024
|
||||||
|
const MAX_QUESTIONS_PER_REQUEST = 4
|
||||||
|
const MAX_QUESTION_OPTIONS = 20
|
||||||
const EMBEDDED_SERVER_USERNAME = 'goodbuddy'
|
const EMBEDDED_SERVER_USERNAME = 'goodbuddy'
|
||||||
|
|
||||||
type SpawnedProcess = ReturnType<typeof spawn>
|
type SpawnedProcess = ReturnType<typeof spawn>
|
||||||
@@ -230,6 +237,69 @@ function parsePermissionRequest(
|
|||||||
return properties as PermissionRequest
|
return properties as PermissionRequest
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseQuestionRequest(
|
||||||
|
properties: unknown,
|
||||||
|
sessionId: string
|
||||||
|
): QuestionRequest | undefined {
|
||||||
|
if (!isRecord(properties) || properties.sessionID !== sessionId) {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
const { id, questions, tool } = properties
|
||||||
|
if (
|
||||||
|
typeof id !== 'string' ||
|
||||||
|
id.length === 0 ||
|
||||||
|
id.length > MAX_PERMISSION_NAME_LENGTH ||
|
||||||
|
!Array.isArray(questions) ||
|
||||||
|
questions.length === 0 ||
|
||||||
|
questions.length > MAX_QUESTIONS_PER_REQUEST ||
|
||||||
|
!questions.every(
|
||||||
|
(question) =>
|
||||||
|
isRecord(question) &&
|
||||||
|
typeof question.question === 'string' &&
|
||||||
|
question.question.trim().length > 0 &&
|
||||||
|
question.question.length <= 2_000 &&
|
||||||
|
typeof question.header === 'string' &&
|
||||||
|
question.header.trim().length > 0 &&
|
||||||
|
question.header.length <= 120 &&
|
||||||
|
Array.isArray(question.options) &&
|
||||||
|
question.options.length <= MAX_QUESTION_OPTIONS &&
|
||||||
|
question.options.every(
|
||||||
|
(option) =>
|
||||||
|
isRecord(option) &&
|
||||||
|
typeof option.label === 'string' &&
|
||||||
|
option.label.trim().length > 0 &&
|
||||||
|
option.label.length <= 200 &&
|
||||||
|
typeof option.description === 'string' &&
|
||||||
|
option.description.length <= 1_000
|
||||||
|
) &&
|
||||||
|
(question.multiple === undefined ||
|
||||||
|
typeof question.multiple === 'boolean') &&
|
||||||
|
(question.custom === undefined ||
|
||||||
|
typeof question.custom === 'boolean')
|
||||||
|
) ||
|
||||||
|
(tool !== undefined &&
|
||||||
|
(!isRecord(tool) ||
|
||||||
|
typeof tool.messageID !== 'string' ||
|
||||||
|
tool.messageID.length === 0 ||
|
||||||
|
tool.messageID.length > 256 ||
|
||||||
|
typeof tool.callID !== 'string' ||
|
||||||
|
tool.callID.length === 0 ||
|
||||||
|
tool.callID.length > 256))
|
||||||
|
) {
|
||||||
|
throw new Error('OpenCode 提问请求格式无效')
|
||||||
|
}
|
||||||
|
let serialized: string
|
||||||
|
try {
|
||||||
|
serialized = JSON.stringify(properties)
|
||||||
|
} catch {
|
||||||
|
throw new Error('OpenCode 提问请求无法序列化')
|
||||||
|
}
|
||||||
|
if (!byteLengthWithin(serialized, MAX_QUESTION_REQUEST_BYTES)) {
|
||||||
|
throw new Error('OpenCode 提问请求超过安全限制')
|
||||||
|
}
|
||||||
|
return properties as QuestionRequest
|
||||||
|
}
|
||||||
|
|
||||||
function isSafeTokenCount(value: number): boolean {
|
function isSafeTokenCount(value: number): boolean {
|
||||||
return Number.isSafeInteger(value) && value >= 0
|
return Number.isSafeInteger(value) && value >= 0
|
||||||
}
|
}
|
||||||
@@ -355,6 +425,14 @@ export class OpenCodeRuntime implements AgentRuntime {
|
|||||||
string,
|
string,
|
||||||
Promise<string>
|
Promise<string>
|
||||||
>()
|
>()
|
||||||
|
private readonly pendingQuestions = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
client: OpencodeClient
|
||||||
|
directory: string
|
||||||
|
questionCount: number
|
||||||
|
}
|
||||||
|
>()
|
||||||
private embeddedRunTail: Promise<void> = Promise.resolve()
|
private embeddedRunTail: Promise<void> = Promise.resolve()
|
||||||
private readonly dependencies: OpenCodeRuntimeDependencies
|
private readonly dependencies: OpenCodeRuntimeDependencies
|
||||||
|
|
||||||
@@ -904,6 +982,7 @@ export class OpenCodeRuntime implements AgentRuntime {
|
|||||||
}
|
}
|
||||||
>()
|
>()
|
||||||
const reasoningPartIds = new Set<string>()
|
const reasoningPartIds = new Set<string>()
|
||||||
|
const reportedQuestionIds = new Set<string>()
|
||||||
try {
|
try {
|
||||||
const promptText =
|
const promptText =
|
||||||
session.created && request.history?.length
|
session.created && request.history?.length
|
||||||
@@ -1027,6 +1106,50 @@ export class OpenCodeRuntime implements AgentRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
event.type === 'question.asked' &&
|
||||||
|
event.properties.sessionID === sessionId
|
||||||
|
) {
|
||||||
|
const questionRequest = parseQuestionRequest(
|
||||||
|
event.properties,
|
||||||
|
sessionId
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
questionRequest &&
|
||||||
|
!reportedQuestionIds.has(questionRequest.id)
|
||||||
|
) {
|
||||||
|
reportedQuestionIds.add(questionRequest.id)
|
||||||
|
this.pendingQuestions.set(questionRequest.id, {
|
||||||
|
client,
|
||||||
|
directory,
|
||||||
|
questionCount: questionRequest.questions.length
|
||||||
|
})
|
||||||
|
yield {
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'question',
|
||||||
|
questionId: questionRequest.id,
|
||||||
|
questions: questionRequest.questions.map((question) => ({
|
||||||
|
header: question.header,
|
||||||
|
question: question.question,
|
||||||
|
options: question.options.map((option) => ({
|
||||||
|
label: option.label,
|
||||||
|
description: option.description
|
||||||
|
})),
|
||||||
|
multiple: question.multiple ?? false,
|
||||||
|
custom: question.custom ?? true
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
(event.type === 'question.replied' ||
|
||||||
|
event.type === 'question.rejected') &&
|
||||||
|
event.properties.sessionID === sessionId
|
||||||
|
) {
|
||||||
|
this.pendingQuestions.delete(event.properties.requestID)
|
||||||
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
this.usesEmbeddedPermissionMediation() &&
|
this.usesEmbeddedPermissionMediation() &&
|
||||||
event.type === 'permission.asked'
|
event.type === 'permission.asked'
|
||||||
@@ -1193,6 +1316,9 @@ export class OpenCodeRuntime implements AgentRuntime {
|
|||||||
throw error
|
throw error
|
||||||
} finally {
|
} finally {
|
||||||
signal.removeEventListener('abort', abortSession)
|
signal.removeEventListener('abort', abortSession)
|
||||||
|
for (const questionId of reportedQuestionIds) {
|
||||||
|
this.pendingQuestions.delete(questionId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (knowledgeMcpName) {
|
if (knowledgeMcpName) {
|
||||||
@@ -1203,7 +1329,39 @@ export class OpenCodeRuntime implements AgentRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async respondToQuestion(
|
||||||
|
questionId: string,
|
||||||
|
answers?: AgentQuestionAnswer[]
|
||||||
|
): Promise<void> {
|
||||||
|
const pending = this.pendingQuestions.get(questionId)
|
||||||
|
if (!pending) {
|
||||||
|
throw new Error('OpenCode 提问已失效或不存在')
|
||||||
|
}
|
||||||
|
const response = answers
|
||||||
|
? answers.length === pending.questionCount
|
||||||
|
? await pending.client.question.reply({
|
||||||
|
requestID: questionId,
|
||||||
|
directory: pending.directory,
|
||||||
|
answers
|
||||||
|
})
|
||||||
|
: undefined
|
||||||
|
: await pending.client.question.reject({
|
||||||
|
requestID: questionId,
|
||||||
|
directory: pending.directory
|
||||||
|
})
|
||||||
|
if (!response) {
|
||||||
|
throw new Error('OpenCode 提问回答数量不匹配')
|
||||||
|
}
|
||||||
|
if (response.error || response.data !== true) {
|
||||||
|
throw new Error(
|
||||||
|
answers ? 'OpenCode 提交回答失败' : 'OpenCode 取消提问失败'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
this.pendingQuestions.delete(questionId)
|
||||||
|
}
|
||||||
|
|
||||||
async dispose(): Promise<void> {
|
async dispose(): Promise<void> {
|
||||||
|
this.pendingQuestions.clear()
|
||||||
const startingChild = this.startingChild
|
const startingChild = this.startingChild
|
||||||
this.startingChild = undefined
|
this.startingChild = undefined
|
||||||
if (startingChild) {
|
if (startingChild) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type {
|
import type {
|
||||||
|
AgentQuestionAnswer,
|
||||||
AgentRequest,
|
AgentRequest,
|
||||||
AgentRuntimeStatus
|
AgentRuntimeStatus
|
||||||
} from '../../shared/contracts'
|
} from '../../shared/contracts'
|
||||||
@@ -167,6 +168,20 @@ export class AgentRuntimeController implements AgentRuntime {
|
|||||||
await this.current.runtime.releaseConversation?.(conversationId)
|
await this.current.runtime.releaseConversation?.(conversationId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async respondToQuestion(
|
||||||
|
questionId: string,
|
||||||
|
answers?: AgentQuestionAnswer[]
|
||||||
|
): Promise<void> {
|
||||||
|
if (this.closing) {
|
||||||
|
throw new Error('Agent Runtime 正在关闭')
|
||||||
|
}
|
||||||
|
const runtime = this.current.runtime
|
||||||
|
if (!runtime.respondToQuestion) {
|
||||||
|
throw new Error('当前 Runtime 不支持回答交互式问题')
|
||||||
|
}
|
||||||
|
await runtime.respondToQuestion(questionId, answers)
|
||||||
|
}
|
||||||
|
|
||||||
private retire(slot: RuntimeSlot): Promise<void> {
|
private retire(slot: RuntimeSlot): Promise<void> {
|
||||||
slot.retiring = true
|
slot.retiring = true
|
||||||
if (!slot.disposal) {
|
if (!slot.disposal) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type {
|
import type {
|
||||||
ApprovalDecision,
|
ApprovalDecision,
|
||||||
AgentEvent,
|
AgentEvent,
|
||||||
|
AgentQuestionAnswer,
|
||||||
AgentRequest,
|
AgentRequest,
|
||||||
AgentRuntimeStatus
|
AgentRuntimeStatus
|
||||||
} from '../../shared/contracts'
|
} from '../../shared/contracts'
|
||||||
@@ -57,6 +58,10 @@ export interface AgentRuntime {
|
|||||||
signal: AbortSignal,
|
signal: AbortSignal,
|
||||||
authorize?: RuntimeAuthorizer
|
authorize?: RuntimeAuthorizer
|
||||||
): AsyncGenerator<RuntimeEvent, void, void>
|
): AsyncGenerator<RuntimeEvent, void, void>
|
||||||
|
respondToQuestion?(
|
||||||
|
questionId: string,
|
||||||
|
answers?: AgentQuestionAnswer[]
|
||||||
|
): Promise<void>
|
||||||
releaseConversation?(conversationId: string): Promise<void>
|
releaseConversation?(conversationId: string): Promise<void>
|
||||||
dispose(): Promise<void>
|
dispose(): Promise<void>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,44 @@ describe('SelectedRuntimeManager', () => {
|
|||||||
await manager.dispose()
|
await manager.dispose()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('isolates cached runtimes by effective project workspace', async () => {
|
||||||
|
const first = runtime()
|
||||||
|
const second = runtime()
|
||||||
|
const create = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(first.value)
|
||||||
|
.mockResolvedValueOnce(second.value)
|
||||||
|
const manager = new SelectedRuntimeManager(create)
|
||||||
|
const selection = { provider: 'opencode' as const }
|
||||||
|
|
||||||
|
const projectOne = await manager.getRuntime(
|
||||||
|
selection,
|
||||||
|
'C:\\Projects\\One'
|
||||||
|
)
|
||||||
|
const projectOneAgain = await manager.getRuntime(
|
||||||
|
selection,
|
||||||
|
'C:\\Projects\\One'
|
||||||
|
)
|
||||||
|
const projectTwo = await manager.getRuntime(
|
||||||
|
selection,
|
||||||
|
'C:\\Projects\\Two'
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(projectOneAgain).toBe(projectOne)
|
||||||
|
expect(projectTwo).not.toBe(projectOne)
|
||||||
|
expect(create).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
selection,
|
||||||
|
'C:\\Projects\\One'
|
||||||
|
)
|
||||||
|
expect(create).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
selection,
|
||||||
|
'C:\\Projects\\Two'
|
||||||
|
)
|
||||||
|
await manager.dispose()
|
||||||
|
})
|
||||||
|
|
||||||
it('retires cached runtimes when settings change', async () => {
|
it('retires cached runtimes when settings change', async () => {
|
||||||
const first = runtime()
|
const first = runtime()
|
||||||
const second = runtime()
|
const second = runtime()
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ import type { AgentRuntime } from './runtime'
|
|||||||
import { AgentRuntimeController } from './runtime-controller'
|
import { AgentRuntimeController } from './runtime-controller'
|
||||||
|
|
||||||
export type SelectedRuntimeResolver = {
|
export type SelectedRuntimeResolver = {
|
||||||
getRuntime(selection: AgentRuntimeSelection): Promise<AgentRuntime>
|
getRuntime(
|
||||||
|
selection: AgentRuntimeSelection,
|
||||||
|
workspacePath?: string
|
||||||
|
): Promise<AgentRuntime>
|
||||||
getStatus(
|
getStatus(
|
||||||
selection: AgentRuntimeSelection
|
selection: AgentRuntimeSelection
|
||||||
): Promise<AgentRuntimeStatus>
|
): Promise<AgentRuntimeStatus>
|
||||||
@@ -15,6 +18,7 @@ export type SelectedRuntimeResolver = {
|
|||||||
selection: AgentRuntimeSelection
|
selection: AgentRuntimeSelection
|
||||||
): Promise<AgentRuntimeStatus>
|
): Promise<AgentRuntimeStatus>
|
||||||
releaseConversation(conversationId: string): Promise<void>
|
releaseConversation(conversationId: string): Promise<void>
|
||||||
|
reset?(): Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
export class SelectedRuntimeManager implements SelectedRuntimeResolver {
|
export class SelectedRuntimeManager implements SelectedRuntimeResolver {
|
||||||
@@ -28,28 +32,35 @@ export class SelectedRuntimeManager implements SelectedRuntimeResolver {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly createRuntime: (
|
private readonly createRuntime: (
|
||||||
selection: AgentRuntimeSelection
|
selection: AgentRuntimeSelection,
|
||||||
|
workspacePath?: string
|
||||||
) => Promise<AgentRuntime>
|
) => Promise<AgentRuntime>
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getRuntime(
|
async getRuntime(
|
||||||
selection: AgentRuntimeSelection
|
selection: AgentRuntimeSelection,
|
||||||
|
workspacePath?: string
|
||||||
): Promise<AgentRuntime> {
|
): Promise<AgentRuntime> {
|
||||||
if (this.disposed) {
|
if (this.disposed) {
|
||||||
throw new Error('Agent Runtime 正在关闭')
|
throw new Error('Agent Runtime 正在关闭')
|
||||||
}
|
}
|
||||||
const key = agentRuntimeSelectionKey(selection)
|
const key = JSON.stringify([
|
||||||
|
agentRuntimeSelectionKey(selection),
|
||||||
|
workspacePath ?? ''
|
||||||
|
])
|
||||||
const existing = this.entries.get(key)
|
const existing = this.entries.get(key)
|
||||||
if (existing) {
|
if (existing) {
|
||||||
return existing
|
return existing
|
||||||
}
|
}
|
||||||
const operation = this.createRuntime(selection).then(async (runtime) => {
|
const operation = this.createRuntime(selection, workspacePath).then(
|
||||||
if (this.disposed || this.entries.get(key) !== operation) {
|
async (runtime) => {
|
||||||
await runtime.dispose()
|
if (this.disposed || this.entries.get(key) !== operation) {
|
||||||
throw new Error('Runtime 设置已更改,请重新选择')
|
await runtime.dispose()
|
||||||
|
throw new Error('Runtime 设置已更改,请重新选择')
|
||||||
|
}
|
||||||
|
return new AgentRuntimeController(runtime)
|
||||||
}
|
}
|
||||||
return new AgentRuntimeController(runtime)
|
)
|
||||||
})
|
|
||||||
this.entries.set(key, operation)
|
this.entries.set(key, operation)
|
||||||
try {
|
try {
|
||||||
return await operation
|
return await operation
|
||||||
|
|||||||
@@ -234,6 +234,97 @@ describe('AssistantDatabase', () => {
|
|||||||
database.close()
|
database.close()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('safely deletes a confirmed project and its scoped data', async () => {
|
||||||
|
const database = await createDatabase()
|
||||||
|
const project = database.createProject({
|
||||||
|
name: '待删除项目',
|
||||||
|
description: '删除测试',
|
||||||
|
rootPath: 'C:\\Delete',
|
||||||
|
defaultWorkMode: 'execute'
|
||||||
|
})
|
||||||
|
const conversationId = '00000000-0000-4000-8000-000000000111'
|
||||||
|
const taskId = '00000000-0000-4000-8000-000000000211'
|
||||||
|
database.replaceConversations([
|
||||||
|
{
|
||||||
|
id: conversationId,
|
||||||
|
projectId: project.id,
|
||||||
|
title: '项目对话',
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
messages: []
|
||||||
|
}
|
||||||
|
])
|
||||||
|
database.createTask({
|
||||||
|
id: taskId,
|
||||||
|
projectId: project.id,
|
||||||
|
conversationId,
|
||||||
|
title: '项目任务',
|
||||||
|
instructions: '执行任务',
|
||||||
|
workMode: 'execute'
|
||||||
|
})
|
||||||
|
database.createTextArtifact({
|
||||||
|
projectId: project.id,
|
||||||
|
taskId,
|
||||||
|
title: '项目成果',
|
||||||
|
content: '内容'
|
||||||
|
})
|
||||||
|
database.createMemory({
|
||||||
|
scope: 'project',
|
||||||
|
scopeId: project.id,
|
||||||
|
type: 'fact',
|
||||||
|
content: '项目记忆'
|
||||||
|
})
|
||||||
|
database.createSchedule({
|
||||||
|
projectId: project.id,
|
||||||
|
title: '项目计划',
|
||||||
|
prompt: '执行计划',
|
||||||
|
workMode: 'ask',
|
||||||
|
recurrence: 'daily',
|
||||||
|
nextRunAt: '2026-08-08T00:00:00.000Z'
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
database.deleteProject(project.id, project.name)
|
||||||
|
).toThrow('项目仍有进行中的任务')
|
||||||
|
database.updateTaskStatus(taskId, 'completed')
|
||||||
|
expect(() =>
|
||||||
|
database.deleteProject(project.id, '错误名称')
|
||||||
|
).toThrow('项目名称确认不匹配')
|
||||||
|
|
||||||
|
database.deleteProject(project.id, project.name)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
database.listProjects(true).some((item) => item.id === project.id)
|
||||||
|
).toBe(false)
|
||||||
|
expect(
|
||||||
|
database.listConversations().some(
|
||||||
|
(conversation) => conversation.projectId === project.id
|
||||||
|
)
|
||||||
|
).toBe(false)
|
||||||
|
expect(
|
||||||
|
database.listTasks().some((task) => task.projectId === project.id)
|
||||||
|
).toBe(false)
|
||||||
|
expect(database.listArtifacts(project.id)).toEqual([])
|
||||||
|
expect(database.listSchedules(project.id)).toEqual([])
|
||||||
|
expect(
|
||||||
|
database
|
||||||
|
.listMemories(project.id)
|
||||||
|
.some((memory) => memory.scopeId === project.id)
|
||||||
|
).toBe(false)
|
||||||
|
expect(database.listProjects()).toHaveLength(1)
|
||||||
|
database.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not delete the final active project', async () => {
|
||||||
|
const database = await createDatabase()
|
||||||
|
const project = database.listProjects()[0]!
|
||||||
|
|
||||||
|
expect(() =>
|
||||||
|
database.deleteProject(project.id, project.name)
|
||||||
|
).toThrow('至少需要保留一个可用项目')
|
||||||
|
expect(database.listProjects()).toHaveLength(1)
|
||||||
|
database.close()
|
||||||
|
})
|
||||||
|
|
||||||
it('creates, updates, and soft-deletes expert roles', async () => {
|
it('creates, updates, and soft-deletes expert roles', async () => {
|
||||||
const database = await createDatabase()
|
const database = await createDatabase()
|
||||||
const expert = database.createExpert({
|
const expert = database.createExpert({
|
||||||
@@ -613,6 +704,29 @@ describe('AssistantDatabase', () => {
|
|||||||
id: '00000000-0000-4000-8000-000000000213',
|
id: '00000000-0000-4000-8000-000000000213',
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: '处理中',
|
content: '处理中',
|
||||||
|
reasoning: '先分析发布范围',
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
id: '00000000-0000-4000-8000-000000000217',
|
||||||
|
type: 'reasoning',
|
||||||
|
content: '先分析发布范围'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '00000000-0000-4000-8000-000000000218',
|
||||||
|
type: 'tool',
|
||||||
|
tool: {
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'read',
|
||||||
|
state: 'running',
|
||||||
|
summary: 'OpenCode 工具:read'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '00000000-0000-4000-8000-000000000219',
|
||||||
|
type: 'text',
|
||||||
|
content: '处理中'
|
||||||
|
}
|
||||||
|
],
|
||||||
createdAt: 1_775_000_001_000,
|
createdAt: 1_775_000_001_000,
|
||||||
state: 'streaming',
|
state: 'streaming',
|
||||||
artifactIds: [
|
artifactIds: [
|
||||||
@@ -665,6 +779,24 @@ describe('AssistantDatabase', () => {
|
|||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
state: 'error',
|
state: 'error',
|
||||||
status: expect.stringContaining('意外中断'),
|
status: expect.stringContaining('意外中断'),
|
||||||
|
reasoning: '先分析发布范围',
|
||||||
|
blocks: [
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'reasoning',
|
||||||
|
content: '先分析发布范围'
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'tool',
|
||||||
|
tool: expect.objectContaining({
|
||||||
|
callId: 'call-1',
|
||||||
|
state: 'interrupted'
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'text',
|
||||||
|
content: '处理中'
|
||||||
|
})
|
||||||
|
],
|
||||||
artifactIds: [
|
artifactIds: [
|
||||||
'00000000-0000-4000-8000-000000000216'
|
'00000000-0000-4000-8000-000000000216'
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -89,6 +89,8 @@ type MessageRow = {
|
|||||||
type MessageMetadata = {
|
type MessageMetadata = {
|
||||||
createdAt?: number
|
createdAt?: number
|
||||||
status?: string
|
status?: string
|
||||||
|
reasoning?: ConversationSnapshot['messages'][number]['reasoning']
|
||||||
|
blocks?: ConversationSnapshot['messages'][number]['blocks']
|
||||||
tools?: ConversationSnapshot['messages'][number]['tools']
|
tools?: ConversationSnapshot['messages'][number]['tools']
|
||||||
sources?: string[]
|
sources?: string[]
|
||||||
sourceReferences?: ConversationSnapshot['messages'][number]['sourceReferences']
|
sourceReferences?: ConversationSnapshot['messages'][number]['sourceReferences']
|
||||||
@@ -579,6 +581,20 @@ function interruptActiveTools(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function interruptActiveToolBlocks(
|
||||||
|
blocks: MessageMetadata['blocks']
|
||||||
|
): MessageMetadata['blocks'] {
|
||||||
|
return blocks?.map((block) =>
|
||||||
|
block.type === 'tool' &&
|
||||||
|
(block.tool.state === 'pending' || block.tool.state === 'running')
|
||||||
|
? {
|
||||||
|
...block,
|
||||||
|
tool: { ...block.tool, state: 'interrupted' as const }
|
||||||
|
}
|
||||||
|
: block
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export class AssistantDatabase {
|
export class AssistantDatabase {
|
||||||
private database?: DatabaseSync
|
private database?: DatabaseSync
|
||||||
|
|
||||||
@@ -714,7 +730,13 @@ export class AssistantDatabase {
|
|||||||
metadata.tools?.some(
|
metadata.tools?.some(
|
||||||
(tool) =>
|
(tool) =>
|
||||||
tool.state === 'pending' || tool.state === 'running'
|
tool.state === 'pending' || tool.state === 'running'
|
||||||
)
|
) ||
|
||||||
|
metadata.blocks?.some(
|
||||||
|
(block) =>
|
||||||
|
block.type === 'tool' &&
|
||||||
|
(block.tool.state === 'pending' ||
|
||||||
|
block.tool.state === 'running')
|
||||||
|
)
|
||||||
)
|
)
|
||||||
if (message.state !== 'streaming' && !hasActiveTool) {
|
if (message.state !== 'streaming' && !hasActiveTool) {
|
||||||
continue
|
continue
|
||||||
@@ -727,7 +749,8 @@ export class AssistantDatabase {
|
|||||||
message.state === 'streaming'
|
message.state === 'streaming'
|
||||||
? interruptedMessageStatus
|
? interruptedMessageStatus
|
||||||
: metadata.status,
|
: metadata.status,
|
||||||
tools: interruptActiveTools(metadata.tools)
|
tools: interruptActiveTools(metadata.tools),
|
||||||
|
blocks: interruptActiveToolBlocks(metadata.blocks)
|
||||||
}),
|
}),
|
||||||
message.id
|
message.id
|
||||||
)
|
)
|
||||||
@@ -859,6 +882,96 @@ export class AssistantDatabase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
deleteProject(projectId: string, confirmation: string): void {
|
||||||
|
const database = this.requireDatabase()
|
||||||
|
database.exec('BEGIN IMMEDIATE')
|
||||||
|
try {
|
||||||
|
const project = database
|
||||||
|
.prepare('SELECT name, status FROM projects WHERE id = ?')
|
||||||
|
.get(projectId) as
|
||||||
|
| { name: string; status: AssistantProject['status'] }
|
||||||
|
| undefined
|
||||||
|
if (!project) {
|
||||||
|
throw new Error('项目不存在')
|
||||||
|
}
|
||||||
|
if (confirmation !== project.name) {
|
||||||
|
throw new Error('项目名称确认不匹配')
|
||||||
|
}
|
||||||
|
const activeProjectCount = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT COUNT(*) AS count FROM projects
|
||||||
|
WHERE status = 'active'`
|
||||||
|
)
|
||||||
|
.get() as { count: number }
|
||||||
|
if (project.status === 'active' && activeProjectCount.count <= 1) {
|
||||||
|
throw new Error('至少需要保留一个可用项目')
|
||||||
|
}
|
||||||
|
const activeTaskCount = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT COUNT(*) AS count FROM tasks
|
||||||
|
WHERE project_id = ?
|
||||||
|
AND status IN ('queued', 'running', 'waiting_approval', 'paused')`
|
||||||
|
)
|
||||||
|
.get(projectId) as { count: number }
|
||||||
|
if (activeTaskCount.count > 0) {
|
||||||
|
throw new Error('项目仍有进行中的任务,请先停止任务')
|
||||||
|
}
|
||||||
|
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`DELETE FROM notifications
|
||||||
|
WHERE task_id IN (
|
||||||
|
SELECT id FROM tasks WHERE project_id = ?
|
||||||
|
) OR schedule_id IN (
|
||||||
|
SELECT id FROM schedules WHERE project_id = ?
|
||||||
|
)`
|
||||||
|
)
|
||||||
|
.run(projectId, projectId)
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`DELETE FROM delegation_outbox
|
||||||
|
WHERE task_id IN (
|
||||||
|
SELECT id FROM tasks WHERE project_id = ?
|
||||||
|
)`
|
||||||
|
)
|
||||||
|
.run(projectId)
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`DELETE FROM memory_items
|
||||||
|
WHERE (scope = 'project' AND scope_id = ?)
|
||||||
|
OR (scope = 'conversation' AND scope_id IN (
|
||||||
|
SELECT id FROM conversations WHERE project_id = ?
|
||||||
|
))`
|
||||||
|
)
|
||||||
|
.run(projectId, projectId)
|
||||||
|
database
|
||||||
|
.prepare('DELETE FROM heartbeat_configs WHERE project_id = ?')
|
||||||
|
.run(projectId)
|
||||||
|
database
|
||||||
|
.prepare('DELETE FROM artifacts WHERE project_id = ?')
|
||||||
|
.run(projectId)
|
||||||
|
database
|
||||||
|
.prepare('DELETE FROM tasks WHERE project_id = ?')
|
||||||
|
.run(projectId)
|
||||||
|
database
|
||||||
|
.prepare('DELETE FROM conversations WHERE project_id = ?')
|
||||||
|
.run(projectId)
|
||||||
|
database
|
||||||
|
.prepare('DELETE FROM schedules WHERE project_id = ?')
|
||||||
|
.run(projectId)
|
||||||
|
const result = database
|
||||||
|
.prepare('DELETE FROM projects WHERE id = ?')
|
||||||
|
.run(projectId)
|
||||||
|
if (result.changes !== 1) {
|
||||||
|
throw new Error('项目不存在')
|
||||||
|
}
|
||||||
|
database.exec('COMMIT')
|
||||||
|
} catch (error) {
|
||||||
|
database.exec('ROLLBACK')
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
listConversations(): ConversationSnapshot[] {
|
listConversations(): ConversationSnapshot[] {
|
||||||
const database = this.requireDatabase()
|
const database = this.requireDatabase()
|
||||||
const conversations = database
|
const conversations = database
|
||||||
@@ -897,6 +1010,10 @@ export class AssistantDatabase {
|
|||||||
id: message.id,
|
id: message.id,
|
||||||
role: message.role,
|
role: message.role,
|
||||||
content: message.content,
|
content: message.content,
|
||||||
|
reasoning: metadata.reasoning,
|
||||||
|
blocks: interrupted
|
||||||
|
? interruptActiveToolBlocks(metadata.blocks)
|
||||||
|
: metadata.blocks,
|
||||||
createdAt:
|
createdAt:
|
||||||
metadata.createdAt ?? Date.parse(message.created_at),
|
metadata.createdAt ?? Date.parse(message.created_at),
|
||||||
state: interrupted ? ('error' as const) : message.state,
|
state: interrupted ? ('error' as const) : message.state,
|
||||||
@@ -1006,6 +1123,8 @@ export class AssistantDatabase {
|
|||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
createdAt: message.createdAt,
|
createdAt: message.createdAt,
|
||||||
status: message.status,
|
status: message.status,
|
||||||
|
reasoning: message.reasoning,
|
||||||
|
blocks: message.blocks,
|
||||||
tools: message.tools,
|
tools: message.tools,
|
||||||
sources: message.sources,
|
sources: message.sources,
|
||||||
sourceReferences: message.sourceReferences,
|
sourceReferences: message.sourceReferences,
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ describe('getWorkspaceChanges', () => {
|
|||||||
expect(changes.patch).toContain('+after')
|
expect(changes.patch).toContain('+after')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fails safely for a non-Git directory', async () => {
|
it('keeps file browsing available without reporting Git errors', async () => {
|
||||||
const directory = await mkdtemp(join(tmpdir(), 'goodbuddy-changes-'))
|
const directory = await mkdtemp(join(tmpdir(), 'goodbuddy-changes-'))
|
||||||
temporaryDirectories.push(directory)
|
temporaryDirectories.push(directory)
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ describe('getWorkspaceChanges', () => {
|
|||||||
|
|
||||||
expect(changes.available).toBe(false)
|
expect(changes.available).toBe(false)
|
||||||
expect(changes.files).toEqual([])
|
expect(changes.files).toEqual([])
|
||||||
expect(changes.error).toBeTruthy()
|
expect(changes.error).toBeUndefined()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import spawn from 'cross-spawn'
|
import spawn from 'cross-spawn'
|
||||||
import { basename, extname } from 'node:path'
|
import { basename, extname, join } from 'node:path'
|
||||||
|
import { stat } from 'node:fs/promises'
|
||||||
import type {
|
import type {
|
||||||
WorkspaceChangedFile,
|
WorkspaceChangedFile,
|
||||||
WorkspaceChanges,
|
WorkspaceChanges,
|
||||||
@@ -164,6 +165,15 @@ async function resolveWorkspacePath(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function resolveWorkspaceEntryPath(
|
||||||
|
rootPath: string,
|
||||||
|
inputPath: string,
|
||||||
|
expected: 'file' | 'directory'
|
||||||
|
): Promise<string> {
|
||||||
|
return (await resolveWorkspacePath(rootPath, inputPath, expected))
|
||||||
|
.canonicalPath
|
||||||
|
}
|
||||||
|
|
||||||
function parseChangedFiles(status: string): {
|
function parseChangedFiles(status: string): {
|
||||||
files: WorkspaceChangedFile[]
|
files: WorkspaceChangedFile[]
|
||||||
truncated: boolean
|
truncated: boolean
|
||||||
@@ -223,6 +233,19 @@ export async function getWorkspaceChanges(
|
|||||||
error: '项目尚未配置工作区目录'
|
error: '项目尚未配置工作区目录'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const gitMetadata = await stat(join(rootPath, '.git')).catch(
|
||||||
|
() => undefined
|
||||||
|
)
|
||||||
|
if (!gitMetadata) {
|
||||||
|
return {
|
||||||
|
rootPath,
|
||||||
|
available: false,
|
||||||
|
status: '',
|
||||||
|
patch: '',
|
||||||
|
files: [],
|
||||||
|
truncated: false
|
||||||
|
}
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const [status, patch] = await Promise.all([
|
const [status, patch] = await Promise.all([
|
||||||
runGit(rootPath, [
|
runGit(rootPath, [
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||||
import { tmpdir } from 'node:os'
|
import { tmpdir } from 'node:os'
|
||||||
import { join } from 'node:path'
|
import { join } from 'node:path'
|
||||||
|
import { strToU8, zipSync } from 'fflate'
|
||||||
import {
|
import {
|
||||||
afterEach,
|
afterEach,
|
||||||
describe,
|
describe,
|
||||||
@@ -265,6 +266,62 @@ describe('CapabilityService', () => {
|
|||||||
).rejects.toThrow('只能删除已导入')
|
).rejects.toThrow('只能删除已导入')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('imports a managed Skill from a ZIP package', async () => {
|
||||||
|
const { directory, importedRoot, service } = await createService()
|
||||||
|
const packageRoot = join(directory, 'zip-source')
|
||||||
|
await writeSkill(packageRoot, 'meeting-helper', '会议助手')
|
||||||
|
const skillMarkdown = await readFile(
|
||||||
|
join(packageRoot, 'meeting-helper', 'SKILL.md')
|
||||||
|
)
|
||||||
|
const archivePath = join(directory, 'meeting-helper.zip')
|
||||||
|
await writeFile(
|
||||||
|
archivePath,
|
||||||
|
zipSync({
|
||||||
|
'meeting-helper/SKILL.md': skillMarkdown,
|
||||||
|
'meeting-helper/template.txt': strToU8('template')
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
const imported = await service.importSkill(archivePath)
|
||||||
|
|
||||||
|
expect(imported.skills).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'meeting-helper',
|
||||||
|
source: 'imported'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
await expect(
|
||||||
|
readFile(
|
||||||
|
join(importedRoot, 'meeting-helper', 'template.txt'),
|
||||||
|
'utf8'
|
||||||
|
)
|
||||||
|
).resolves.toBe('template')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects unsafe paths in a Skill ZIP package', async () => {
|
||||||
|
const { directory, importedRoot, service } = await createService()
|
||||||
|
const packageRoot = join(directory, 'unsafe-source')
|
||||||
|
await writeSkill(packageRoot, 'unsafe-skill', '不安全 Skill')
|
||||||
|
const skillMarkdown = await readFile(
|
||||||
|
join(packageRoot, 'unsafe-skill', 'SKILL.md')
|
||||||
|
)
|
||||||
|
const archivePath = join(directory, 'unsafe-skill.zip')
|
||||||
|
await writeFile(
|
||||||
|
archivePath,
|
||||||
|
zipSync({
|
||||||
|
'../escape.txt': strToU8('escape'),
|
||||||
|
'unsafe-skill/SKILL.md': skillMarkdown
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
await expect(service.importSkill(archivePath)).rejects.toThrow(
|
||||||
|
'Skill ZIP 包含不安全路径'
|
||||||
|
)
|
||||||
|
await expect(
|
||||||
|
readFile(join(importedRoot, 'escape.txt'), 'utf8')
|
||||||
|
).rejects.toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
it('encrypts remote MCP secrets and never returns them publicly', async () => {
|
it('encrypts remote MCP secrets and never returns them publicly', async () => {
|
||||||
const { filePath, service } = await createService()
|
const { filePath, service } = await createService()
|
||||||
const snapshot = await service.saveMcpServer(undefined, {
|
const snapshot = await service.saveMcpServer(undefined, {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createHash, randomUUID } from 'node:crypto'
|
import { createHash, randomUUID } from 'node:crypto'
|
||||||
|
import { unzipSync } from 'fflate'
|
||||||
import {
|
import {
|
||||||
lstat,
|
lstat,
|
||||||
mkdir,
|
mkdir,
|
||||||
@@ -10,7 +11,7 @@ import {
|
|||||||
stat,
|
stat,
|
||||||
writeFile
|
writeFile
|
||||||
} from 'node:fs/promises'
|
} from 'node:fs/promises'
|
||||||
import { basename, dirname, join } from 'node:path'
|
import { basename, dirname, extname, join } from 'node:path'
|
||||||
import { parse as parseYaml } from 'yaml'
|
import { parse as parseYaml } from 'yaml'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import {
|
import {
|
||||||
@@ -207,7 +208,7 @@ function defaultSkillState(): z.infer<typeof skillStateSchema> {
|
|||||||
async function readSkill(
|
async function readSkill(
|
||||||
directoryPath: string,
|
directoryPath: string,
|
||||||
source: SkillSummary['source'],
|
source: SkillSummary['source'],
|
||||||
expectedId = basename(directoryPath)
|
expectedId: string | null = basename(directoryPath)
|
||||||
): Promise<Omit<SkillSummary, 'enabled' | 'assignments'>> {
|
): Promise<Omit<SkillSummary, 'enabled' | 'assignments'>> {
|
||||||
const filePath = join(directoryPath, 'SKILL.md')
|
const filePath = join(directoryPath, 'SKILL.md')
|
||||||
const file = await stat(filePath)
|
const file = await stat(filePath)
|
||||||
@@ -220,7 +221,7 @@ async function readSkill(
|
|||||||
throw new Error(`${basename(directoryPath)} 的 SKILL.md 格式无效`)
|
throw new Error(`${basename(directoryPath)} 的 SKILL.md 格式无效`)
|
||||||
}
|
}
|
||||||
const metadata = skillMetadataSchema.parse(parseYaml(match[1]))
|
const metadata = skillMetadataSchema.parse(parseYaml(match[1]))
|
||||||
if (metadata.id !== expectedId) {
|
if (expectedId !== null && metadata.id !== expectedId) {
|
||||||
throw new Error(`Skill ID 必须与目录名一致:${metadata.id}`)
|
throw new Error(`Skill ID 必须与目录名一致:${metadata.id}`)
|
||||||
}
|
}
|
||||||
return skillSummarySchema
|
return skillSummarySchema
|
||||||
@@ -309,6 +310,132 @@ async function copySkillPackage(
|
|||||||
await copyDirectory(sourceRoot, targetRoot, 0)
|
await copyDirectory(sourceRoot, targetRoot, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseSkillZipPath(path: string): string[] {
|
||||||
|
const normalized = path.replaceAll('\\', '/')
|
||||||
|
const withoutTrailingSlash = normalized.replace(/\/+$/u, '')
|
||||||
|
if (
|
||||||
|
!withoutTrailingSlash ||
|
||||||
|
normalized.startsWith('/') ||
|
||||||
|
/^[a-z]:/iu.test(normalized)
|
||||||
|
) {
|
||||||
|
throw new Error('Skill ZIP 包含不安全路径')
|
||||||
|
}
|
||||||
|
const segments = withoutTrailingSlash.split('/')
|
||||||
|
if (
|
||||||
|
segments.some(
|
||||||
|
(segment) =>
|
||||||
|
!segment ||
|
||||||
|
segment === '.' ||
|
||||||
|
segment === '..' ||
|
||||||
|
segment.length > 255 ||
|
||||||
|
[...segment].some((character) => {
|
||||||
|
const code = character.charCodeAt(0)
|
||||||
|
return code <= 31 || code === 127
|
||||||
|
})
|
||||||
|
) ||
|
||||||
|
normalized.length > 512
|
||||||
|
) {
|
||||||
|
throw new Error('Skill ZIP 包含不安全路径')
|
||||||
|
}
|
||||||
|
return segments
|
||||||
|
}
|
||||||
|
|
||||||
|
function isIgnoredSkillZipPath(segments: readonly string[]): boolean {
|
||||||
|
return (
|
||||||
|
segments[0] === '__MACOSX' ||
|
||||||
|
segments.at(-1) === '.DS_Store'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function extractSkillZip(
|
||||||
|
archivePath: string,
|
||||||
|
targetRoot: string
|
||||||
|
): Promise<string | undefined> {
|
||||||
|
const archiveDetails = await stat(archivePath)
|
||||||
|
if (
|
||||||
|
!archiveDetails.isFile() ||
|
||||||
|
archiveDetails.size > MAX_SKILL_PACKAGE_BYTES
|
||||||
|
) {
|
||||||
|
throw new Error('Skill ZIP 文件无效或过大')
|
||||||
|
}
|
||||||
|
const archiveBytes = await readFile(archivePath)
|
||||||
|
const selectedPaths = new Map<string, string[]>()
|
||||||
|
const normalizedPaths = new Set<string>()
|
||||||
|
let fileCount = 0
|
||||||
|
let totalBytes = 0
|
||||||
|
let files: Record<string, Uint8Array>
|
||||||
|
try {
|
||||||
|
files = unzipSync(archiveBytes, {
|
||||||
|
filter: (file) => {
|
||||||
|
const segments = parseSkillZipPath(file.name)
|
||||||
|
if (
|
||||||
|
file.name.endsWith('/') ||
|
||||||
|
isIgnoredSkillZipPath(segments)
|
||||||
|
) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const normalizedPath = segments.join('/').toLowerCase()
|
||||||
|
if (normalizedPaths.has(normalizedPath)) {
|
||||||
|
throw new Error('Skill ZIP 包含重复文件路径')
|
||||||
|
}
|
||||||
|
normalizedPaths.add(normalizedPath)
|
||||||
|
fileCount += 1
|
||||||
|
totalBytes += file.originalSize
|
||||||
|
if (
|
||||||
|
fileCount > MAX_SKILL_PACKAGE_FILES ||
|
||||||
|
file.originalSize > MAX_SKILL_FILE_BYTES ||
|
||||||
|
totalBytes > MAX_SKILL_PACKAGE_BYTES
|
||||||
|
) {
|
||||||
|
throw new Error('Skill ZIP 大小或文件数量超过安全限制')
|
||||||
|
}
|
||||||
|
selectedPaths.set(file.name, segments)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && error.message.startsWith('Skill ZIP')) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Skill ZIP 文件无效或不受支持', {
|
||||||
|
cause: error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const skillEntries = [...selectedPaths.entries()].filter(
|
||||||
|
([, segments]) => segments.at(-1) === 'SKILL.md'
|
||||||
|
)
|
||||||
|
if (skillEntries.length !== 1) {
|
||||||
|
throw new Error('Skill ZIP 必须且只能包含一个 SKILL.md')
|
||||||
|
}
|
||||||
|
const packageRoot = skillEntries[0]![1].slice(0, -1)
|
||||||
|
const packageRootKey = packageRoot
|
||||||
|
.map((segment) => segment.toLowerCase())
|
||||||
|
for (const segments of selectedPaths.values()) {
|
||||||
|
const belongsToPackage = packageRootKey.every(
|
||||||
|
(segment, index) => segments[index]?.toLowerCase() === segment
|
||||||
|
)
|
||||||
|
if (!belongsToPackage || segments.length <= packageRoot.length) {
|
||||||
|
throw new Error('Skill ZIP 只能包含一个 Skill 包')
|
||||||
|
}
|
||||||
|
if (segments.length - packageRoot.length - 1 > MAX_SKILL_DEPTH) {
|
||||||
|
throw new Error('Skill ZIP 目录层级超过安全限制')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await mkdir(targetRoot, { recursive: true })
|
||||||
|
for (const [archiveName, contents] of Object.entries(files)) {
|
||||||
|
const segments = selectedPaths.get(archiveName)
|
||||||
|
if (!segments) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const relativeSegments = segments.slice(packageRoot.length)
|
||||||
|
const targetPath = join(targetRoot, ...relativeSegments)
|
||||||
|
await mkdir(dirname(targetPath), { recursive: true })
|
||||||
|
await writeFile(targetPath, contents, { mode: 0o600 })
|
||||||
|
}
|
||||||
|
return packageRoot.at(-1)
|
||||||
|
}
|
||||||
|
|
||||||
export class CapabilityService {
|
export class CapabilityService {
|
||||||
private state?: StoredCapabilities
|
private state?: StoredCapabilities
|
||||||
private loadPromise?: Promise<StoredCapabilities>
|
private loadPromise?: Promise<StoredCapabilities>
|
||||||
@@ -819,21 +946,13 @@ export class CapabilityService {
|
|||||||
importSkill(sourcePath: string): Promise<CapabilitySnapshot> {
|
importSkill(sourcePath: string): Promise<CapabilitySnapshot> {
|
||||||
return this.queue(async () => {
|
return this.queue(async () => {
|
||||||
const canonicalSource = await realpath(sourcePath)
|
const canonicalSource = await realpath(sourcePath)
|
||||||
if (!(await stat(canonicalSource)).isDirectory()) {
|
const sourceDetails = await stat(canonicalSource)
|
||||||
throw new Error('所选 Skill 路径不是目录')
|
const isDirectory = sourceDetails.isDirectory()
|
||||||
}
|
const isZip =
|
||||||
const skill = await readSkill(canonicalSource, 'imported')
|
sourceDetails.isFile() &&
|
||||||
const builtins = await listSkills(this.builtinSkillsRoot, 'builtin')
|
extname(canonicalSource).toLowerCase() === '.zip'
|
||||||
if (builtins.some((item) => item.id === skill.id)) {
|
if (!isDirectory && !isZip) {
|
||||||
throw new Error('导入的 Skill ID 与内置 Skill 冲突')
|
throw new Error('所选 Skill 路径必须是目录或 .zip 文件')
|
||||||
}
|
|
||||||
const targetPath = join(this.importedSkillsRoot, skill.id)
|
|
||||||
if (
|
|
||||||
await stat(targetPath)
|
|
||||||
.then(() => true)
|
|
||||||
.catch(() => false)
|
|
||||||
) {
|
|
||||||
throw new Error('同名 Skill 已导入,请先删除后重试')
|
|
||||||
}
|
}
|
||||||
await mkdir(this.importedSkillsRoot, { recursive: true })
|
await mkdir(this.importedSkillsRoot, { recursive: true })
|
||||||
const temporaryPath = join(
|
const temporaryPath = join(
|
||||||
@@ -841,22 +960,47 @@ export class CapabilityService {
|
|||||||
`.import-${randomUUID()}`
|
`.import-${randomUUID()}`
|
||||||
)
|
)
|
||||||
try {
|
try {
|
||||||
await copySkillPackage(canonicalSource, temporaryPath)
|
const archiveDirectoryName = isZip
|
||||||
|
? await extractSkillZip(canonicalSource, temporaryPath)
|
||||||
|
: undefined
|
||||||
|
const skill = await readSkill(
|
||||||
|
isDirectory ? canonicalSource : temporaryPath,
|
||||||
|
'imported',
|
||||||
|
isDirectory ? undefined : (archiveDirectoryName ?? null)
|
||||||
|
)
|
||||||
|
const builtins = await listSkills(
|
||||||
|
this.builtinSkillsRoot,
|
||||||
|
'builtin'
|
||||||
|
)
|
||||||
|
if (builtins.some((item) => item.id === skill.id)) {
|
||||||
|
throw new Error('导入的 Skill ID 与内置 Skill 冲突')
|
||||||
|
}
|
||||||
|
const targetPath = join(this.importedSkillsRoot, skill.id)
|
||||||
|
if (
|
||||||
|
await stat(targetPath)
|
||||||
|
.then(() => true)
|
||||||
|
.catch(() => false)
|
||||||
|
) {
|
||||||
|
throw new Error('同名 Skill 已导入,请先删除后重试')
|
||||||
|
}
|
||||||
|
if (isDirectory) {
|
||||||
|
await copySkillPackage(canonicalSource, temporaryPath)
|
||||||
|
}
|
||||||
await readSkill(temporaryPath, 'imported', skill.id)
|
await readSkill(temporaryPath, 'imported', skill.id)
|
||||||
await rename(temporaryPath, targetPath)
|
await rename(temporaryPath, targetPath)
|
||||||
|
const state = await this.load()
|
||||||
|
await this.persist({
|
||||||
|
...state,
|
||||||
|
skills: {
|
||||||
|
...state.skills,
|
||||||
|
[skill.id]: defaultSkillState()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return this.getSnapshot()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await rm(temporaryPath, { recursive: true, force: true })
|
await rm(temporaryPath, { recursive: true, force: true })
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
const state = await this.load()
|
|
||||||
await this.persist({
|
|
||||||
...state,
|
|
||||||
skills: {
|
|
||||||
...state.skills,
|
|
||||||
[skill.id]: defaultSkillState()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return this.getSnapshot()
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { showDesktopNotificationWhenUnfocused } from './desktop-notification'
|
||||||
|
|
||||||
|
const notificationMocks = vi.hoisted(() => ({
|
||||||
|
isSupported: vi.fn(() => true),
|
||||||
|
show: vi.fn()
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('electron', () => ({
|
||||||
|
Notification: class {
|
||||||
|
static isSupported = notificationMocks.isSupported
|
||||||
|
|
||||||
|
show = notificationMocks.show
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('showDesktopNotificationWhenUnfocused', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
notificationMocks.isSupported.mockReturnValue(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('suppresses desktop notifications while GoodBuddy is focused', () => {
|
||||||
|
const shown = showDesktopNotificationWhenUnfocused(
|
||||||
|
{
|
||||||
|
isDestroyed: vi.fn(() => false),
|
||||||
|
isFocused: vi.fn(() => true)
|
||||||
|
} as never,
|
||||||
|
{ title: '任务已完成' }
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(shown).toBe(false)
|
||||||
|
expect(notificationMocks.show).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows desktop notifications while GoodBuddy is unfocused', () => {
|
||||||
|
const shown = showDesktopNotificationWhenUnfocused(
|
||||||
|
{
|
||||||
|
isDestroyed: vi.fn(() => false),
|
||||||
|
isFocused: vi.fn(() => false)
|
||||||
|
} as never,
|
||||||
|
{ title: '任务已完成' }
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(shown).toBe(true)
|
||||||
|
expect(notificationMocks.show).toHaveBeenCalledOnce()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import {
|
||||||
|
Notification,
|
||||||
|
type BrowserWindow,
|
||||||
|
type NotificationConstructorOptions
|
||||||
|
} from 'electron'
|
||||||
|
|
||||||
|
export function showDesktopNotificationWhenUnfocused(
|
||||||
|
window: BrowserWindow,
|
||||||
|
options: NotificationConstructorOptions
|
||||||
|
): boolean {
|
||||||
|
if (
|
||||||
|
window.isDestroyed() ||
|
||||||
|
window.isFocused() ||
|
||||||
|
!Notification.isSupported()
|
||||||
|
) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
new Notification(options).show()
|
||||||
|
return true
|
||||||
|
}
|
||||||
+5
-2
@@ -382,14 +382,17 @@ if (hasSingleInstanceLock) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
const createSelectedRuntime = async (
|
const createSelectedRuntime = async (
|
||||||
selection: AgentRuntimeSelection
|
selection: AgentRuntimeSelection,
|
||||||
|
workspacePath?: string
|
||||||
): Promise<AgentRuntime> => {
|
): Promise<AgentRuntime> => {
|
||||||
const resolved = applyRuntimeSelection(
|
const resolved = applyRuntimeSelection(
|
||||||
await settingsStore.getResolvedSettings(),
|
await settingsStore.getResolvedSettings(),
|
||||||
selection
|
selection
|
||||||
)
|
)
|
||||||
return createRuntimeWithCapabilities(
|
return createRuntimeWithCapabilities(
|
||||||
resolved.settings,
|
workspacePath
|
||||||
|
? { ...resolved.settings, workspacePath }
|
||||||
|
: resolved.settings,
|
||||||
resolved.target
|
resolved.target
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+41
-3
@@ -18,6 +18,10 @@ const electronMocks = vi.hoisted(() => {
|
|||||||
removeHandler: vi.fn((channel: string) => {
|
removeHandler: vi.fn((channel: string) => {
|
||||||
handlers.delete(channel)
|
handlers.delete(channel)
|
||||||
}),
|
}),
|
||||||
|
showOpenDialog: vi.fn(async () => ({
|
||||||
|
canceled: true,
|
||||||
|
filePaths: [] as string[]
|
||||||
|
})),
|
||||||
openPath: vi.fn(async () => ''),
|
openPath: vi.fn(async () => ''),
|
||||||
showItemInFolder: vi.fn(),
|
showItemInFolder: vi.fn(),
|
||||||
openExternal: vi.fn(async () => undefined)
|
openExternal: vi.fn(async () => undefined)
|
||||||
@@ -78,6 +82,7 @@ describe('registerIpcHandlers computer capabilities', () => {
|
|||||||
browserProfiles: { profiles: [], defaultProfileId: null }
|
browserProfiles: { profiles: [], defaultProfileId: null }
|
||||||
}
|
}
|
||||||
const capabilityService = {
|
const capabilityService = {
|
||||||
|
importSkill: vi.fn(async () => snapshot),
|
||||||
setComputerCapabilityEnabled: vi.fn(async () => snapshot),
|
setComputerCapabilityEnabled: vi.fn(async () => snapshot),
|
||||||
createBrowserProfile: vi.fn(async () => snapshot),
|
createBrowserProfile: vi.fn(async () => snapshot),
|
||||||
diagnoseComputerCapability: vi.fn(async () => ({
|
diagnoseComputerCapability: vi.fn(async () => ({
|
||||||
@@ -131,6 +136,31 @@ describe('registerIpcHandlers computer capabilities', () => {
|
|||||||
).toHaveBeenCalledWith('host-browser-control', true)
|
).toHaveBeenCalledWith('host-browser-control', true)
|
||||||
expect(onRuntimeSettingsChanged).toHaveBeenCalledOnce()
|
expect(onRuntimeSettingsChanged).toHaveBeenCalledOnce()
|
||||||
|
|
||||||
|
electronMocks.showOpenDialog.mockResolvedValueOnce({
|
||||||
|
canceled: false,
|
||||||
|
filePaths: ['C:\\meeting-helper.zip']
|
||||||
|
})
|
||||||
|
await expect(
|
||||||
|
electronMocks.handlers.get(
|
||||||
|
ipcChannels.capabilitiesImportSkill
|
||||||
|
)?.(event, 'zip')
|
||||||
|
).resolves.toEqual(snapshot)
|
||||||
|
expect(electronMocks.showOpenDialog).toHaveBeenCalledWith(
|
||||||
|
window,
|
||||||
|
expect.objectContaining({
|
||||||
|
properties: ['openFile'],
|
||||||
|
filters: [{ name: 'Skill ZIP', extensions: ['zip'] }]
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(capabilityService.importSkill).toHaveBeenCalledWith(
|
||||||
|
'C:\\meeting-helper.zip'
|
||||||
|
)
|
||||||
|
await expect(
|
||||||
|
electronMocks.handlers.get(
|
||||||
|
ipcChannels.capabilitiesImportSkill
|
||||||
|
)?.(event, 'unsupported')
|
||||||
|
).rejects.toThrow()
|
||||||
|
|
||||||
browserStateListener?.({
|
browserStateListener?.({
|
||||||
conversationId: 'browser-conversation',
|
conversationId: 'browser-conversation',
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
@@ -183,7 +213,9 @@ vi.mock('electron', () => ({
|
|||||||
getVersion: vi.fn(() => '0.1.0')
|
getVersion: vi.fn(() => '0.1.0')
|
||||||
},
|
},
|
||||||
BrowserWindow: class {},
|
BrowserWindow: class {},
|
||||||
dialog: {},
|
dialog: {
|
||||||
|
showOpenDialog: electronMocks.showOpenDialog
|
||||||
|
},
|
||||||
ipcMain: {
|
ipcMain: {
|
||||||
handle: electronMocks.handle,
|
handle: electronMocks.handle,
|
||||||
removeHandler: electronMocks.removeHandler
|
removeHandler: electronMocks.removeHandler
|
||||||
@@ -838,7 +870,11 @@ describe('registerIpcHandlers agent terminal state', () => {
|
|||||||
upsertModelUsageCall: vi.fn(),
|
upsertModelUsageCall: vi.fn(),
|
||||||
clearAssistantData: vi.fn(),
|
clearAssistantData: vi.fn(),
|
||||||
listExperts: vi.fn<() => Array<Record<string, unknown>>>(() => []),
|
listExperts: vi.fn<() => Array<Record<string, unknown>>>(() => []),
|
||||||
getExpert: vi.fn()
|
getExpert: vi.fn(),
|
||||||
|
getProject: vi.fn((projectId: string) => ({
|
||||||
|
id: projectId,
|
||||||
|
rootPath: 'C:\\ProjectWorkspace'
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
const webContents = {
|
const webContents = {
|
||||||
mainFrame: { url: 'file:///goodbuddy/index.html' },
|
mainFrame: { url: 'file:///goodbuddy/index.html' },
|
||||||
@@ -1229,6 +1265,7 @@ describe('registerIpcHandlers agent terminal state', () => {
|
|||||||
harness.handler?.(event, {
|
harness.handler?.(event, {
|
||||||
requestId: '00000000-0000-4000-8000-000000000011',
|
requestId: '00000000-0000-4000-8000-000000000011',
|
||||||
conversationId: 'conversation-one',
|
conversationId: 'conversation-one',
|
||||||
|
projectId: '00000000-0000-4000-8000-000000000101',
|
||||||
prompt: 'first request',
|
prompt: 'first request',
|
||||||
workMode: 'ask',
|
workMode: 'ask',
|
||||||
runtimeSelection: firstSelection
|
runtimeSelection: firstSelection
|
||||||
@@ -1258,7 +1295,8 @@ describe('registerIpcHandlers agent terminal state', () => {
|
|||||||
})
|
})
|
||||||
expect(fallbackRuntime.run).not.toHaveBeenCalled()
|
expect(fallbackRuntime.run).not.toHaveBeenCalled()
|
||||||
expect(selectedRuntimes.getRuntime).toHaveBeenCalledWith(
|
expect(selectedRuntimes.getRuntime).toHaveBeenCalledWith(
|
||||||
firstSelection
|
firstSelection,
|
||||||
|
'C:\\ProjectWorkspace'
|
||||||
)
|
)
|
||||||
expect(selectedRuntimes.getRuntime).toHaveBeenCalledWith(
|
expect(selectedRuntimes.getRuntime).toHaveBeenCalledWith(
|
||||||
secondSelection
|
secondSelection
|
||||||
|
|||||||
+144
-45
@@ -3,7 +3,6 @@ import {
|
|||||||
BrowserWindow,
|
BrowserWindow,
|
||||||
dialog,
|
dialog,
|
||||||
ipcMain,
|
ipcMain,
|
||||||
Notification,
|
|
||||||
shell
|
shell
|
||||||
} from 'electron'
|
} from 'electron'
|
||||||
import { mkdir, readFile, realpath, stat } from 'node:fs/promises'
|
import { mkdir, readFile, realpath, stat } from 'node:fs/promises'
|
||||||
@@ -14,6 +13,7 @@ import { z } from 'zod'
|
|||||||
import { formatShortcutForDisplay } from '../shared/shortcut'
|
import { formatShortcutForDisplay } from '../shared/shortcut'
|
||||||
import {
|
import {
|
||||||
approvalDecisionSchema,
|
approvalDecisionSchema,
|
||||||
|
agentQuestionResponseSchema,
|
||||||
agentRequestSchema,
|
agentRequestSchema,
|
||||||
browserStopRequestSchema,
|
browserStopRequestSchema,
|
||||||
knowledgeCreateSchema,
|
knowledgeCreateSchema,
|
||||||
@@ -30,8 +30,10 @@ import {
|
|||||||
windowCaptureRequestSchema,
|
windowCaptureRequestSchema,
|
||||||
workspaceDirectoryRequestSchema,
|
workspaceDirectoryRequestSchema,
|
||||||
workspaceFileRequestSchema,
|
workspaceFileRequestSchema,
|
||||||
|
workspaceOpenPathRequestSchema,
|
||||||
type AgentRuntimeDetection,
|
type AgentRuntimeDetection,
|
||||||
type AgentEvent,
|
type AgentEvent,
|
||||||
|
type AgentRequest,
|
||||||
type AppInfo,
|
type AppInfo,
|
||||||
type BrowserLiveState,
|
type BrowserLiveState,
|
||||||
type KnowledgeSnapshot,
|
type KnowledgeSnapshot,
|
||||||
@@ -49,6 +51,7 @@ import {
|
|||||||
mcpServerInputSchema,
|
mcpServerInputSchema,
|
||||||
skillAssignmentsInputSchema,
|
skillAssignmentsInputSchema,
|
||||||
skillIdSchema,
|
skillIdSchema,
|
||||||
|
skillImportKindSchema,
|
||||||
skillToggleInputSchema,
|
skillToggleInputSchema,
|
||||||
type CapabilitySnapshot,
|
type CapabilitySnapshot,
|
||||||
type CapabilityDiagnosticReport,
|
type CapabilityDiagnosticReport,
|
||||||
@@ -111,9 +114,11 @@ import { RemoteDelegationService } from './assistant/remote-delegation-service'
|
|||||||
import {
|
import {
|
||||||
getWorkspaceChanges,
|
getWorkspaceChanges,
|
||||||
listWorkspaceDirectory,
|
listWorkspaceDirectory,
|
||||||
readWorkspaceFile
|
readWorkspaceFile,
|
||||||
|
resolveWorkspaceEntryPath
|
||||||
} from './assistant/workspace-changes-service'
|
} from './assistant/workspace-changes-service'
|
||||||
import { HeartbeatService } from './assistant/heartbeat-service'
|
import { HeartbeatService } from './assistant/heartbeat-service'
|
||||||
|
import { showDesktopNotificationWhenUnfocused } from './desktop-notification'
|
||||||
import {
|
import {
|
||||||
SubagentRunError,
|
SubagentRunError,
|
||||||
type SubagentService
|
type SubagentService
|
||||||
@@ -238,6 +243,12 @@ const projectArchiveRequestSchema = z
|
|||||||
archived: z.boolean()
|
archived: z.boolean()
|
||||||
})
|
})
|
||||||
.strict()
|
.strict()
|
||||||
|
const projectDeleteRequestSchema = z
|
||||||
|
.object({
|
||||||
|
projectId: assistantIdSchema,
|
||||||
|
confirmation: z.string().max(120)
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
const memoryStatusRequestSchema = z
|
const memoryStatusRequestSchema = z
|
||||||
.object({
|
.object({
|
||||||
memoryId: assistantIdSchema,
|
memoryId: assistantIdSchema,
|
||||||
@@ -494,6 +505,10 @@ export function registerIpcHandlers(
|
|||||||
knowledgeGateway?: KnowledgeMcpGateway
|
knowledgeGateway?: KnowledgeMcpGateway
|
||||||
): () => Promise<void> {
|
): () => Promise<void> {
|
||||||
const activeRequests = new Map<string, AbortController>()
|
const activeRequests = new Map<string, AbortController>()
|
||||||
|
const pendingAgentQuestions = new Map<
|
||||||
|
string,
|
||||||
|
{ requestId: string; runtime: AgentRuntime }
|
||||||
|
>()
|
||||||
const heartbeatControllers = new Set<AbortController>()
|
const heartbeatControllers = new Set<AbortController>()
|
||||||
let shuttingDown = false
|
let shuttingDown = false
|
||||||
let executionPaused = false
|
let executionPaused = false
|
||||||
@@ -506,6 +521,21 @@ export function registerIpcHandlers(
|
|||||||
)
|
)
|
||||||
return execution
|
return execution
|
||||||
}
|
}
|
||||||
|
const resolveRequestRuntime = async (
|
||||||
|
request: Pick<AgentRequest, 'projectId' | 'runtimeSelection'>
|
||||||
|
): Promise<AgentRuntime> => {
|
||||||
|
const projectWorkspace = request.projectId
|
||||||
|
? assistantDatabase.getProject(request.projectId).rootPath.trim()
|
||||||
|
: ''
|
||||||
|
if (!selectedRuntimes || (!request.runtimeSelection && !projectWorkspace)) {
|
||||||
|
return runtime
|
||||||
|
}
|
||||||
|
const selection =
|
||||||
|
request.runtimeSelection ?? ({ provider: 'auto' } as const)
|
||||||
|
return projectWorkspace
|
||||||
|
? selectedRuntimes.getRuntime(selection, projectWorkspace)
|
||||||
|
: selectedRuntimes.getRuntime(selection)
|
||||||
|
}
|
||||||
const channels = Object.values(ipcChannels).filter(
|
const channels = Object.values(ipcChannels).filter(
|
||||||
(channel) =>
|
(channel) =>
|
||||||
channel !== ipcChannels.agentEvent &&
|
channel !== ipcChannels.agentEvent &&
|
||||||
@@ -618,7 +648,10 @@ export function registerIpcHandlers(
|
|||||||
assistantDatabase,
|
assistantDatabase,
|
||||||
{
|
{
|
||||||
summarize: async (request) => {
|
summarize: async (request) => {
|
||||||
if (runtime.capability === 'image-generation') {
|
const requestRuntime = await resolveRequestRuntime({
|
||||||
|
projectId: request.projectId
|
||||||
|
})
|
||||||
|
if (requestRuntime.capability === 'image-generation') {
|
||||||
throw new Error('智能心跳需要文本模型,当前默认连接仅支持图像生成')
|
throw new Error('智能心跳需要文本模型,当前默认连接仅支持图像生成')
|
||||||
}
|
}
|
||||||
const controller = new AbortController()
|
const controller = new AbortController()
|
||||||
@@ -644,10 +677,11 @@ export function registerIpcHandlers(
|
|||||||
let output = ''
|
let output = ''
|
||||||
let completed = false
|
let completed = false
|
||||||
try {
|
try {
|
||||||
for await (const event of runtime.run(
|
for await (const event of requestRuntime.run(
|
||||||
{
|
{
|
||||||
requestId,
|
requestId,
|
||||||
conversationId,
|
conversationId,
|
||||||
|
projectId: request.projectId,
|
||||||
workMode: 'ask',
|
workMode: 'ask',
|
||||||
prompt: [
|
prompt: [
|
||||||
request.systemInstruction,
|
request.systemInstruction,
|
||||||
@@ -704,7 +738,7 @@ export function registerIpcHandlers(
|
|||||||
} finally {
|
} finally {
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
heartbeatControllers.delete(controller)
|
heartbeatControllers.delete(controller)
|
||||||
await runtime.releaseConversation?.(conversationId)
|
await requestRuntime.releaseConversation?.(conversationId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -755,7 +789,10 @@ export function registerIpcHandlers(
|
|||||||
let output = ''
|
let output = ''
|
||||||
let completed = false
|
let completed = false
|
||||||
try {
|
try {
|
||||||
for await (const agentEvent of runtime.run(
|
const requestRuntime = await resolveRequestRuntime({
|
||||||
|
projectId: schedule.projectId
|
||||||
|
})
|
||||||
|
for await (const agentEvent of requestRuntime.run(
|
||||||
{
|
{
|
||||||
requestId,
|
requestId,
|
||||||
conversationId: `${origin}:${schedule.id}`,
|
conversationId: `${origin}:${schedule.id}`,
|
||||||
@@ -841,12 +878,10 @@ export function registerIpcHandlers(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
assistantDatabase.updateTaskStatus(requestId, 'completed')
|
assistantDatabase.updateTaskStatus(requestId, 'completed')
|
||||||
if (Notification.isSupported()) {
|
showDesktopNotificationWhenUnfocused(window, {
|
||||||
new Notification({
|
title: `定时任务完成:${schedule.title}`,
|
||||||
title: `定时任务完成:${schedule.title}`,
|
body: '结果已保存到 GoodBuddy 成果工作栏。'
|
||||||
body: '结果已保存到 GoodBuddy 成果工作栏。'
|
})
|
||||||
}).show()
|
|
||||||
}
|
|
||||||
return { status: 'completed', output }
|
return { status: 'completed', output }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = safeRuntimeError(error, '定时任务执行失败')
|
const message = safeRuntimeError(error, '定时任务执行失败')
|
||||||
@@ -855,12 +890,10 @@ export function registerIpcHandlers(
|
|||||||
controller.signal.aborted ? 'cancelled' : 'failed',
|
controller.signal.aborted ? 'cancelled' : 'failed',
|
||||||
message
|
message
|
||||||
)
|
)
|
||||||
if (Notification.isSupported()) {
|
showDesktopNotificationWhenUnfocused(window, {
|
||||||
new Notification({
|
title: `定时任务失败:${schedule.title}`,
|
||||||
title: `定时任务失败:${schedule.title}`,
|
body: '打开 GoodBuddy 任务工作栏查看详情。'
|
||||||
body: '打开 GoodBuddy 任务工作栏查看详情。'
|
})
|
||||||
}).show()
|
|
||||||
}
|
|
||||||
return { status: 'failed', error: message }
|
return { status: 'failed', error: message }
|
||||||
} finally {
|
} finally {
|
||||||
externalSignal?.removeEventListener(
|
externalSignal?.removeEventListener(
|
||||||
@@ -1182,12 +1215,7 @@ export function registerIpcHandlers(
|
|||||||
throw new Error('请求包含不存在的知识库')
|
throw new Error('请求包含不存在的知识库')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const selectedRuntime =
|
const selectedRuntime = await resolveRequestRuntime(parsedInput)
|
||||||
parsedInput.runtimeSelection && selectedRuntimes
|
|
||||||
? await selectedRuntimes.getRuntime(
|
|
||||||
parsedInput.runtimeSelection
|
|
||||||
)
|
|
||||||
: runtime
|
|
||||||
const normalizedWorkMode = normalizeInteractiveWorkMode(
|
const normalizedWorkMode = normalizeInteractiveWorkMode(
|
||||||
parsedInput.workMode
|
parsedInput.workMode
|
||||||
)
|
)
|
||||||
@@ -1381,6 +1409,12 @@ export function registerIpcHandlers(
|
|||||||
if (publicEvent.type === 'tool') {
|
if (publicEvent.type === 'tool') {
|
||||||
toolStates.set(publicEvent.callId, publicEvent)
|
toolStates.set(publicEvent.callId, publicEvent)
|
||||||
}
|
}
|
||||||
|
if (publicEvent.type === 'question') {
|
||||||
|
pendingAgentQuestions.set(publicEvent.questionId, {
|
||||||
|
requestId: request.requestId,
|
||||||
|
runtime: selectedRuntime
|
||||||
|
})
|
||||||
|
}
|
||||||
if (publicEvent.type === 'error') {
|
if (publicEvent.type === 'error') {
|
||||||
assistantDatabase.appendTaskEvent(
|
assistantDatabase.appendTaskEvent(
|
||||||
request.requestId,
|
request.requestId,
|
||||||
@@ -1446,12 +1480,10 @@ export function registerIpcHandlers(
|
|||||||
request.requestId,
|
request.requestId,
|
||||||
'completed'
|
'completed'
|
||||||
)
|
)
|
||||||
if (!window.isFocused() && Notification.isSupported()) {
|
showDesktopNotificationWhenUnfocused(window, {
|
||||||
new Notification({
|
title: 'GoodBuddy 任务已完成',
|
||||||
title: 'GoodBuddy 任务已完成',
|
body: '任务结果已保存到成果工作栏。'
|
||||||
body: '任务结果已保存到成果工作栏。'
|
})
|
||||||
}).show()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (!window.isDestroyed()) {
|
if (!window.isDestroyed()) {
|
||||||
window.webContents.send(ipcChannels.agentEvent, publicEvent)
|
window.webContents.send(ipcChannels.agentEvent, publicEvent)
|
||||||
@@ -1485,18 +1517,21 @@ export function registerIpcHandlers(
|
|||||||
agentEvent
|
agentEvent
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (!window.isFocused() && Notification.isSupported()) {
|
showDesktopNotificationWhenUnfocused(window, {
|
||||||
new Notification({
|
title: controller.signal.aborted
|
||||||
title: controller.signal.aborted
|
? 'GoodBuddy 任务已取消'
|
||||||
? 'GoodBuddy 任务已取消'
|
: 'GoodBuddy 任务失败',
|
||||||
: 'GoodBuddy 任务失败',
|
body: '打开任务工作栏查看详情。'
|
||||||
body: '打开任务工作栏查看详情。'
|
})
|
||||||
}).show()
|
|
||||||
}
|
|
||||||
if (!window.isDestroyed()) {
|
if (!window.isDestroyed()) {
|
||||||
window.webContents.send(ipcChannels.agentEvent, agentEvent)
|
window.webContents.send(ipcChannels.agentEvent, agentEvent)
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
|
for (const [questionId, pending] of pendingAgentQuestions) {
|
||||||
|
if (pending.requestId === request.requestId) {
|
||||||
|
pendingAgentQuestions.delete(questionId)
|
||||||
|
}
|
||||||
|
}
|
||||||
knowledgeGateway?.revoke(request.knowledgeCapabilityToken)
|
knowledgeGateway?.revoke(request.knowledgeCapabilityToken)
|
||||||
activeRequests.delete(request.requestId)
|
activeRequests.delete(request.requestId)
|
||||||
}
|
}
|
||||||
@@ -1515,6 +1550,22 @@ export function registerIpcHandlers(
|
|||||||
const response = approvalResponseSchema.parse(input)
|
const response = approvalResponseSchema.parse(input)
|
||||||
approvalBroker.respond(response.approvalId, response.decision)
|
approvalBroker.respond(response.approvalId, response.decision)
|
||||||
})
|
})
|
||||||
|
ipcMain.handle(
|
||||||
|
ipcChannels.agentQuestionRespond,
|
||||||
|
async (event, input: unknown) => {
|
||||||
|
assertTrustedSender(event, window)
|
||||||
|
const response = agentQuestionResponseSchema.parse(input)
|
||||||
|
const pending = pendingAgentQuestions.get(response.questionId)
|
||||||
|
if (!pending?.runtime.respondToQuestion) {
|
||||||
|
throw new Error('OpenCode 提问已失效或不存在')
|
||||||
|
}
|
||||||
|
await pending.runtime.respondToQuestion(
|
||||||
|
response.questionId,
|
||||||
|
response.answers.length > 0 ? response.answers : undefined
|
||||||
|
)
|
||||||
|
pendingAgentQuestions.delete(response.questionId)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
ipcMain.handle(
|
ipcMain.handle(
|
||||||
ipcChannels.runtimeSettingsGet,
|
ipcChannels.runtimeSettingsGet,
|
||||||
@@ -2016,10 +2067,15 @@ export function registerIpcHandlers(
|
|||||||
|
|
||||||
ipcMain.handle(
|
ipcMain.handle(
|
||||||
ipcChannels.projectsUpdate,
|
ipcChannels.projectsUpdate,
|
||||||
(event, input: unknown) => {
|
async (event, input: unknown) => {
|
||||||
assertTrustedSender(event, window)
|
assertTrustedSender(event, window)
|
||||||
const value = projectUpdateRequestSchema.parse(input)
|
const value = projectUpdateRequestSchema.parse(input)
|
||||||
return assistantDatabase.updateProject(value.projectId, value.input)
|
const project = assistantDatabase.updateProject(
|
||||||
|
value.projectId,
|
||||||
|
value.input
|
||||||
|
)
|
||||||
|
await selectedRuntimes?.reset?.()
|
||||||
|
return project
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -2034,6 +2090,18 @@ export function registerIpcHandlers(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
ipcMain.handle(
|
||||||
|
ipcChannels.projectsDelete,
|
||||||
|
async (event, input: unknown) => {
|
||||||
|
assertTrustedSender(event, window)
|
||||||
|
const value = projectDeleteRequestSchema.parse(input)
|
||||||
|
assistantDatabase.deleteProject(
|
||||||
|
value.projectId,
|
||||||
|
value.confirmation
|
||||||
|
)
|
||||||
|
await selectedRuntimes?.reset?.()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
ipcMain.handle(ipcChannels.conversationsList, (event) => {
|
ipcMain.handle(ipcChannels.conversationsList, (event) => {
|
||||||
assertTrustedSender(event, window)
|
assertTrustedSender(event, window)
|
||||||
@@ -2078,6 +2146,27 @@ export function registerIpcHandlers(
|
|||||||
return readWorkspaceFile(project.rootPath, value.path)
|
return readWorkspaceFile(project.rootPath, value.path)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
ipcMain.handle(
|
||||||
|
ipcChannels.workspacePathOpen,
|
||||||
|
async (event, input: unknown) => {
|
||||||
|
assertTrustedSender(event, window)
|
||||||
|
const value = workspaceOpenPathRequestSchema.parse(input)
|
||||||
|
const project = assistantDatabase.getProject(value.projectId)
|
||||||
|
const targetPath = await resolveWorkspaceEntryPath(
|
||||||
|
project.rootPath,
|
||||||
|
value.path,
|
||||||
|
value.type
|
||||||
|
)
|
||||||
|
const error = await shell.openPath(targetPath)
|
||||||
|
if (error) {
|
||||||
|
throw new Error(
|
||||||
|
value.type === 'directory'
|
||||||
|
? '无法在系统资源管理器中打开文件夹'
|
||||||
|
: '无法使用系统默认应用打开文件'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
ipcMain.handle(ipcChannels.tasksList, (event) => {
|
ipcMain.handle(ipcChannels.tasksList, (event) => {
|
||||||
assertTrustedSender(event, window)
|
assertTrustedSender(event, window)
|
||||||
@@ -2337,12 +2426,22 @@ export function registerIpcHandlers(
|
|||||||
|
|
||||||
ipcMain.handle(
|
ipcMain.handle(
|
||||||
ipcChannels.capabilitiesImportSkill,
|
ipcChannels.capabilitiesImportSkill,
|
||||||
async (event): Promise<CapabilitySnapshot> => {
|
async (event, input: unknown): Promise<CapabilitySnapshot> => {
|
||||||
assertTrustedSender(event, window)
|
assertTrustedSender(event, window)
|
||||||
const result = await dialog.showOpenDialog(window, {
|
const kind = skillImportKindSchema.parse(input)
|
||||||
title: '选择包含 SKILL.md 的目录',
|
const result = await dialog.showOpenDialog(
|
||||||
properties: ['openDirectory']
|
window,
|
||||||
})
|
kind === 'zip'
|
||||||
|
? {
|
||||||
|
title: '选择 Skill ZIP 文件',
|
||||||
|
properties: ['openFile'],
|
||||||
|
filters: [{ name: 'Skill ZIP', extensions: ['zip'] }]
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
title: '选择包含 SKILL.md 的目录',
|
||||||
|
properties: ['openDirectory']
|
||||||
|
}
|
||||||
|
)
|
||||||
if (result.canceled || !result.filePaths[0]) {
|
if (result.canceled || !result.filePaths[0]) {
|
||||||
return capabilityService.getSnapshot()
|
return capabilityService.getSnapshot()
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-3
@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron'
|
|||||||
import {
|
import {
|
||||||
type ApprovalDecision,
|
type ApprovalDecision,
|
||||||
type AgentEvent,
|
type AgentEvent,
|
||||||
|
type AgentQuestionAnswer,
|
||||||
type AgentRequest,
|
type AgentRequest,
|
||||||
type AgentRuntimeDetection,
|
type AgentRuntimeDetection,
|
||||||
type AgentRuntimeStatus,
|
type AgentRuntimeStatus,
|
||||||
@@ -141,6 +142,15 @@ const desktopApi: DesktopApi = {
|
|||||||
decision
|
decision
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
respondQuestion: async (
|
||||||
|
questionId: string,
|
||||||
|
answers?: AgentQuestionAnswer[]
|
||||||
|
) => {
|
||||||
|
await ipcRenderer.invoke(ipcChannels.agentQuestionRespond, {
|
||||||
|
questionId,
|
||||||
|
answers: answers ?? []
|
||||||
|
})
|
||||||
|
},
|
||||||
onEvent: (listener) => {
|
onEvent: (listener) => {
|
||||||
const handler = (_event: Electron.IpcRendererEvent, payload: AgentEvent): void =>
|
const handler = (_event: Electron.IpcRendererEvent, payload: AgentEvent): void =>
|
||||||
listener(payload)
|
listener(payload)
|
||||||
@@ -355,6 +365,12 @@ const desktopApi: DesktopApi = {
|
|||||||
projectId,
|
projectId,
|
||||||
archived
|
archived
|
||||||
})
|
})
|
||||||
|
},
|
||||||
|
delete: async (projectId: string, confirmation: string) => {
|
||||||
|
await ipcRenderer.invoke(ipcChannels.projectsDelete, {
|
||||||
|
projectId,
|
||||||
|
confirmation
|
||||||
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
conversations: {
|
conversations: {
|
||||||
@@ -384,7 +400,18 @@ const desktopApi: DesktopApi = {
|
|||||||
ipcRenderer.invoke(ipcChannels.workspaceFileRead, {
|
ipcRenderer.invoke(ipcChannels.workspaceFileRead, {
|
||||||
projectId,
|
projectId,
|
||||||
path
|
path
|
||||||
}) as Promise<WorkspaceFilePreview>
|
}) as Promise<WorkspaceFilePreview>,
|
||||||
|
openPath: async (
|
||||||
|
projectId: string,
|
||||||
|
path: string,
|
||||||
|
type: 'file' | 'directory'
|
||||||
|
) => {
|
||||||
|
await ipcRenderer.invoke(ipcChannels.workspacePathOpen, {
|
||||||
|
projectId,
|
||||||
|
path,
|
||||||
|
type
|
||||||
|
})
|
||||||
|
}
|
||||||
},
|
},
|
||||||
tasks: {
|
tasks: {
|
||||||
list: () =>
|
list: () =>
|
||||||
@@ -534,9 +561,10 @@ const desktopApi: DesktopApi = {
|
|||||||
ipcRenderer.invoke(
|
ipcRenderer.invoke(
|
||||||
ipcChannels.capabilitiesSnapshot
|
ipcChannels.capabilitiesSnapshot
|
||||||
) as Promise<CapabilitySnapshot>,
|
) as Promise<CapabilitySnapshot>,
|
||||||
importSkill: () =>
|
importSkill: (kind) =>
|
||||||
ipcRenderer.invoke(
|
ipcRenderer.invoke(
|
||||||
ipcChannels.capabilitiesImportSkill
|
ipcChannels.capabilitiesImportSkill,
|
||||||
|
kind
|
||||||
) as Promise<CapabilitySnapshot>,
|
) as Promise<CapabilitySnapshot>,
|
||||||
removeSkill: (skillId) =>
|
removeSkill: (skillId) =>
|
||||||
ipcRenderer.invoke(
|
ipcRenderer.invoke(
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import { CircleHelp } from 'lucide-react'
|
||||||
|
import { useMemo, useState } from 'react'
|
||||||
|
import type {
|
||||||
|
AgentEvent,
|
||||||
|
AgentQuestionAnswer
|
||||||
|
} from '../../shared/contracts'
|
||||||
|
|
||||||
|
type AgentQuestion = Extract<AgentEvent, { type: 'question' }>
|
||||||
|
|
||||||
|
type AgentQuestionCardProps = {
|
||||||
|
value: AgentQuestion
|
||||||
|
onReject: () => Promise<void>
|
||||||
|
onSubmit: (answers: AgentQuestionAnswer[]) => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AgentQuestionCard({
|
||||||
|
value,
|
||||||
|
onReject,
|
||||||
|
onSubmit
|
||||||
|
}: AgentQuestionCardProps): React.JSX.Element {
|
||||||
|
const [selected, setSelected] = useState<string[][]>(
|
||||||
|
value.questions.map(() => [])
|
||||||
|
)
|
||||||
|
const [custom, setCustom] = useState<string[]>(
|
||||||
|
value.questions.map(() => '')
|
||||||
|
)
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const answers = useMemo(
|
||||||
|
() =>
|
||||||
|
value.questions.map((question, index) => {
|
||||||
|
const ownAnswer = custom[index]?.trim()
|
||||||
|
const choices = selected[index] ?? []
|
||||||
|
return [
|
||||||
|
...choices,
|
||||||
|
...(ownAnswer && (question.multiple || choices.length === 0)
|
||||||
|
? [ownAnswer]
|
||||||
|
: [])
|
||||||
|
]
|
||||||
|
}),
|
||||||
|
[custom, selected, value.questions]
|
||||||
|
)
|
||||||
|
const complete = answers.every((answer) => answer.length > 0)
|
||||||
|
|
||||||
|
const run = async (action: () => Promise<void>): Promise<void> => {
|
||||||
|
setSubmitting(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
} catch (reason) {
|
||||||
|
setError(
|
||||||
|
reason instanceof Error ? reason.message : '回答提交失败,请重试'
|
||||||
|
)
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
className="agent-question-card"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
if (complete) {
|
||||||
|
void run(() => onSubmit(answers))
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<header>
|
||||||
|
<CircleHelp aria-hidden="true" size={18} />
|
||||||
|
<strong>OpenCode 需要补充信息</strong>
|
||||||
|
</header>
|
||||||
|
{value.questions.map((question, questionIndex) => (
|
||||||
|
<fieldset key={`${question.header}:${questionIndex}`}>
|
||||||
|
<legend>
|
||||||
|
<span>{question.header}</span>
|
||||||
|
{question.question}
|
||||||
|
</legend>
|
||||||
|
{question.options.map((option) => {
|
||||||
|
const checked =
|
||||||
|
selected[questionIndex]?.includes(option.label) ?? false
|
||||||
|
return (
|
||||||
|
<label key={option.label}>
|
||||||
|
<input
|
||||||
|
checked={checked}
|
||||||
|
disabled={submitting}
|
||||||
|
name={`agent-question-${value.questionId}-${questionIndex}`}
|
||||||
|
onChange={() => {
|
||||||
|
setSelected((current) =>
|
||||||
|
current.map((answer, index) =>
|
||||||
|
index !== questionIndex
|
||||||
|
? answer
|
||||||
|
: question.multiple
|
||||||
|
? checked
|
||||||
|
? answer.filter(
|
||||||
|
(label) => label !== option.label
|
||||||
|
)
|
||||||
|
: [...answer, option.label]
|
||||||
|
: [option.label]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if (!question.multiple) {
|
||||||
|
setCustom((current) =>
|
||||||
|
current.map((answer, index) =>
|
||||||
|
index === questionIndex ? '' : answer
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
type={question.multiple ? 'checkbox' : 'radio'}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<strong>{option.label}</strong>
|
||||||
|
{option.description && <small>{option.description}</small>}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{(question.custom || question.options.length === 0) && (
|
||||||
|
<label className="agent-question-card__custom">
|
||||||
|
<span>其他回答</span>
|
||||||
|
<input
|
||||||
|
disabled={submitting}
|
||||||
|
maxLength={2_000}
|
||||||
|
onChange={(event) => {
|
||||||
|
const answer = event.target.value
|
||||||
|
setCustom((current) =>
|
||||||
|
current.map((item, index) =>
|
||||||
|
index === questionIndex ? answer : item
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if (!question.multiple && answer.trim()) {
|
||||||
|
setSelected((current) =>
|
||||||
|
current.map((item, index) =>
|
||||||
|
index === questionIndex ? [] : item
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
placeholder="输入你的回答"
|
||||||
|
type="text"
|
||||||
|
value={custom[questionIndex] ?? ''}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</fieldset>
|
||||||
|
))}
|
||||||
|
{error && (
|
||||||
|
<p className="agent-question-card__error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<footer>
|
||||||
|
<button
|
||||||
|
className="secondary-button"
|
||||||
|
disabled={submitting}
|
||||||
|
onClick={() => void run(onReject)}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
跳过
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="primary-button"
|
||||||
|
disabled={submitting || !complete}
|
||||||
|
type="submit"
|
||||||
|
>
|
||||||
|
{submitting ? '提交中…' : '提交回答'}
|
||||||
|
</button>
|
||||||
|
</footer>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -85,6 +85,7 @@ const api: DesktopApi = {
|
|||||||
run,
|
run,
|
||||||
cancel: vi.fn(async () => {}),
|
cancel: vi.fn(async () => {}),
|
||||||
respondApproval: vi.fn(async () => {}),
|
respondApproval: vi.fn(async () => {}),
|
||||||
|
respondQuestion: vi.fn(async () => {}),
|
||||||
onEvent: vi.fn((listener) => {
|
onEvent: vi.fn((listener) => {
|
||||||
agentListener = listener
|
agentListener = listener
|
||||||
return () => {
|
return () => {
|
||||||
@@ -265,7 +266,8 @@ const api: DesktopApi = {
|
|||||||
...input,
|
...input,
|
||||||
id: _projectId
|
id: _projectId
|
||||||
})),
|
})),
|
||||||
setArchived: vi.fn(async () => {})
|
setArchived: vi.fn(async () => {}),
|
||||||
|
delete: vi.fn(async () => {})
|
||||||
},
|
},
|
||||||
conversations: {
|
conversations: {
|
||||||
list: vi.fn(async () => []),
|
list: vi.fn(async () => []),
|
||||||
@@ -291,7 +293,8 @@ const api: DesktopApi = {
|
|||||||
content: '',
|
content: '',
|
||||||
mimeType: 'text/plain' as const,
|
mimeType: 'text/plain' as const,
|
||||||
size: 0
|
size: 0
|
||||||
}))
|
})),
|
||||||
|
openPath: vi.fn(async () => {})
|
||||||
},
|
},
|
||||||
tasks: {
|
tasks: {
|
||||||
list: vi.fn(async () => []),
|
list: vi.fn(async () => []),
|
||||||
@@ -765,7 +768,7 @@ describe('App', () => {
|
|||||||
expect(await screen.findByRole('status')).toBeVisible()
|
expect(await screen.findByRole('status')).toBeVisible()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('sends a prompt and renders streamed agent content', async () => {
|
it('renders streamed reasoning, text, and tools in event order', async () => {
|
||||||
render(<App />)
|
render(<App />)
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText('向 GoodBuddy 提问'), {
|
fireEvent.change(screen.getByLabelText('向 GoodBuddy 提问'), {
|
||||||
@@ -815,6 +818,55 @@ describe('App', () => {
|
|||||||
expect(streamingReasoning).toHaveAttribute('open')
|
expect(streamingReasoning).toHaveAttribute('open')
|
||||||
expect(screen.getByText('先检查项目结构')).toBeInTheDocument()
|
expect(screen.getByText('先检查项目结构')).toBeInTheDocument()
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
if (!request) {
|
||||||
|
throw new Error('Missing request')
|
||||||
|
}
|
||||||
|
agentListener?.({
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'read',
|
||||||
|
state: 'running',
|
||||||
|
summary: 'OpenCode 工具:read'
|
||||||
|
})
|
||||||
|
agentListener?.({
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'reasoning',
|
||||||
|
delta: '再检查关键文件'
|
||||||
|
})
|
||||||
|
agentListener?.({
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'text',
|
||||||
|
delta: '最终结论'
|
||||||
|
})
|
||||||
|
agentListener?.({
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'tool',
|
||||||
|
callId: 'call-1',
|
||||||
|
name: 'read',
|
||||||
|
state: 'completed',
|
||||||
|
summary: 'OpenCode 工具:read'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const assistantArticle = screen
|
||||||
|
.getByText('最终结论')
|
||||||
|
.closest('article')
|
||||||
|
const orderedBlocks = [
|
||||||
|
...assistantArticle!.querySelectorAll('.message-blocks > *')
|
||||||
|
].map((element) => element.textContent)
|
||||||
|
expect(orderedBlocks).toEqual([
|
||||||
|
expect.stringContaining('这是回答内容'),
|
||||||
|
expect.stringContaining('先检查项目结构'),
|
||||||
|
expect.stringContaining('OpenCode 工具:read'),
|
||||||
|
expect.stringContaining('再检查关键文件'),
|
||||||
|
expect.stringContaining('最终结论')
|
||||||
|
])
|
||||||
|
expect(
|
||||||
|
screen.getAllByText('OpenCode 工具:read')
|
||||||
|
).toHaveLength(1)
|
||||||
|
|
||||||
act(() => {
|
act(() => {
|
||||||
if (!request) {
|
if (!request) {
|
||||||
throw new Error('Missing request')
|
throw new Error('Missing request')
|
||||||
@@ -825,8 +877,11 @@ describe('App', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
const completedReasoning = await screen.findByText('推理过程')
|
const completedReasoning = await screen.findAllByText('推理过程')
|
||||||
expect(completedReasoning.closest('details')).not.toHaveAttribute('open')
|
expect(completedReasoning).toHaveLength(2)
|
||||||
|
for (const reasoning of completedReasoning) {
|
||||||
|
expect(reasoning.closest('details')).not.toHaveAttribute('open')
|
||||||
|
}
|
||||||
expect(screen.getByText('项目:默认项目')).toHaveClass('scope-badge')
|
expect(screen.getByText('项目:默认项目')).toHaveClass('scope-badge')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1274,7 +1329,7 @@ describe('App', () => {
|
|||||||
fireEvent.click(screen.getByLabelText('切换助手工作栏'))
|
fireEvent.click(screen.getByLabelText('切换助手工作栏'))
|
||||||
fireEvent.click(await screen.findByRole('tab', { name: '工作区' }))
|
fireEvent.click(await screen.findByRole('tab', { name: '工作区' }))
|
||||||
fireEvent.click(
|
fireEvent.click(
|
||||||
await screen.findByRole('button', { name: /README\.md/u })
|
await screen.findByRole('button', { name: 'README.md' })
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
@@ -1286,6 +1341,43 @@ describe('App', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('opens workspace entries from their row actions', async () => {
|
||||||
|
vi.mocked(api.workspace.listDirectory).mockResolvedValue({
|
||||||
|
path: '',
|
||||||
|
entries: [
|
||||||
|
{ name: 'docs', path: 'docs', type: 'directory' },
|
||||||
|
{ name: 'README.md', path: 'README.md', type: 'file' }
|
||||||
|
],
|
||||||
|
truncated: false
|
||||||
|
})
|
||||||
|
render(<App />)
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByLabelText('切换助手工作栏'))
|
||||||
|
fireEvent.click(await screen.findByRole('tab', { name: '工作区' }))
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole('button', {
|
||||||
|
name: '在系统资源管理器中打开文件夹 docs'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole('button', {
|
||||||
|
name: '使用默认应用打开文件 README.md'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(api.workspace.openPath).toHaveBeenCalledWith(
|
||||||
|
projectId,
|
||||||
|
'docs',
|
||||||
|
'directory'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
expect(api.workspace.openPath).toHaveBeenCalledWith(
|
||||||
|
projectId,
|
||||||
|
'README.md',
|
||||||
|
'file'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
it('refreshes generated workspace files when a run completes', async () => {
|
it('refreshes generated workspace files when a run completes', async () => {
|
||||||
vi.mocked(api.workspace.getChanges)
|
vi.mocked(api.workspace.getChanges)
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
@@ -2399,6 +2491,87 @@ describe('App', () => {
|
|||||||
).toBeInTheDocument()
|
).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('edits and safely deletes the current project from project settings', async () => {
|
||||||
|
const secondProject = {
|
||||||
|
...project,
|
||||||
|
id: '00000000-0000-4000-8000-000000000102',
|
||||||
|
name: '第二项目',
|
||||||
|
rootPath: 'C:\\Second'
|
||||||
|
}
|
||||||
|
vi.mocked(api.projects.list).mockResolvedValueOnce([
|
||||||
|
project,
|
||||||
|
secondProject
|
||||||
|
])
|
||||||
|
render(<App />)
|
||||||
|
|
||||||
|
fireEvent.click(await screen.findByLabelText('项目设置'))
|
||||||
|
let dialog = screen.getByRole('dialog', { name: '项目设置' })
|
||||||
|
expect(within(dialog).getByLabelText('名称')).toHaveValue(
|
||||||
|
project.name
|
||||||
|
)
|
||||||
|
expect(within(dialog).getByLabelText('根目录')).toHaveValue(
|
||||||
|
project.rootPath
|
||||||
|
)
|
||||||
|
fireEvent.change(within(dialog).getByLabelText('说明'), {
|
||||||
|
target: { value: '更新后的说明' }
|
||||||
|
})
|
||||||
|
fireEvent.click(
|
||||||
|
within(dialog).getByRole('button', { name: '保存项目' })
|
||||||
|
)
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(api.projects.update).toHaveBeenCalledWith(
|
||||||
|
project.id,
|
||||||
|
expect.objectContaining({
|
||||||
|
description: '更新后的说明',
|
||||||
|
rootPath: project.rootPath
|
||||||
|
})
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByLabelText('项目设置'))
|
||||||
|
dialog = screen.getByRole('dialog', { name: '项目设置' })
|
||||||
|
expect(dialog).toHaveTextContent('不会删除磁盘上的项目目录或文件')
|
||||||
|
fireEvent.click(
|
||||||
|
within(dialog).getByRole('button', { name: '删除项目' })
|
||||||
|
)
|
||||||
|
const confirmation = within(dialog).getByLabelText(
|
||||||
|
`输入“${project.name}”确认删除`
|
||||||
|
)
|
||||||
|
const deleteButton = within(dialog).getByRole('button', {
|
||||||
|
name: '永久删除项目'
|
||||||
|
})
|
||||||
|
expect(deleteButton).toBeDisabled()
|
||||||
|
fireEvent.change(confirmation, {
|
||||||
|
target: { value: project.name }
|
||||||
|
})
|
||||||
|
expect(deleteButton).toBeEnabled()
|
||||||
|
fireEvent.click(deleteButton)
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(api.projects.delete).toHaveBeenCalledWith(
|
||||||
|
project.id,
|
||||||
|
project.name
|
||||||
|
)
|
||||||
|
)
|
||||||
|
expect(screen.getByLabelText('当前项目')).toHaveValue(
|
||||||
|
secondProject.id
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses a message icon for conversation navigation', async () => {
|
||||||
|
render(<App />)
|
||||||
|
|
||||||
|
const conversationNavigation = await screen.findByRole('button', {
|
||||||
|
name: '对话'
|
||||||
|
})
|
||||||
|
expect(
|
||||||
|
conversationNavigation.querySelector('.lucide-message-square')
|
||||||
|
).not.toBeNull()
|
||||||
|
expect(
|
||||||
|
conversationNavigation.querySelector('.lucide-history')
|
||||||
|
).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
it('marks an image model and renders its generated artifact', async () => {
|
it('marks an image model and renders its generated artifact', async () => {
|
||||||
const anchorClick = vi
|
const anchorClick = vi
|
||||||
.spyOn(HTMLAnchorElement.prototype, 'click')
|
.spyOn(HTMLAnchorElement.prototype, 'click')
|
||||||
@@ -2711,6 +2884,60 @@ describe('App', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('renders and answers an OpenCode question request', async () => {
|
||||||
|
render(<App />)
|
||||||
|
fireEvent.change(screen.getByLabelText('向 GoodBuddy 提问'), {
|
||||||
|
target: { value: '需要确认的任务' }
|
||||||
|
})
|
||||||
|
fireEvent.click(await screen.findByLabelText('发送'))
|
||||||
|
await waitFor(() => expect(run).toHaveBeenCalledOnce())
|
||||||
|
const request = run.mock.calls[0]?.[0]
|
||||||
|
if (!request) {
|
||||||
|
throw new Error('Missing request')
|
||||||
|
}
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
agentListener?.({
|
||||||
|
requestId: request.requestId,
|
||||||
|
type: 'question',
|
||||||
|
questionId: 'question-1',
|
||||||
|
questions: [
|
||||||
|
{
|
||||||
|
header: '实现方式',
|
||||||
|
question: '请选择实现方式',
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
label: '直接修改',
|
||||||
|
description: '立即更新现有实现'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '先写测试',
|
||||||
|
description: '先增加回归测试'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
multiple: false,
|
||||||
|
custom: true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByText('OpenCode 需要补充信息')
|
||||||
|
).toBeInTheDocument()
|
||||||
|
fireEvent.click(screen.getByLabelText(/先写测试/u))
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: '提交回答' }))
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(api.agent.respondQuestion).toHaveBeenCalledWith(
|
||||||
|
'question-1',
|
||||||
|
[['先写测试']]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
screen.queryByText('OpenCode 需要补充信息')
|
||||||
|
).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
it('configures a runtime without reading an existing API key', async () => {
|
it('configures a runtime without reading an existing API key', async () => {
|
||||||
render(<App />)
|
render(<App />)
|
||||||
|
|
||||||
|
|||||||
+409
-83
@@ -11,11 +11,11 @@ import {
|
|||||||
Edit3,
|
Edit3,
|
||||||
FileText,
|
FileText,
|
||||||
HeartPulse,
|
HeartPulse,
|
||||||
History,
|
|
||||||
Info,
|
Info,
|
||||||
Library,
|
Library,
|
||||||
Maximize2,
|
Maximize2,
|
||||||
MessageSquarePlus,
|
MessageSquarePlus,
|
||||||
|
MessageSquare,
|
||||||
Mic,
|
Mic,
|
||||||
MicOff,
|
MicOff,
|
||||||
Minimize2,
|
Minimize2,
|
||||||
@@ -48,6 +48,7 @@ import {
|
|||||||
import type {
|
import type {
|
||||||
ApprovalDecision,
|
ApprovalDecision,
|
||||||
AgentEvent,
|
AgentEvent,
|
||||||
|
AgentQuestionAnswer,
|
||||||
AgentRuntimeStatus,
|
AgentRuntimeStatus,
|
||||||
AppInfo,
|
AppInfo,
|
||||||
BrowserLiveState,
|
BrowserLiveState,
|
||||||
@@ -77,16 +78,20 @@ import type {
|
|||||||
TokenUsageSummary,
|
TokenUsageSummary,
|
||||||
ConversationSnapshot,
|
ConversationSnapshot,
|
||||||
ConversationAttachment,
|
ConversationAttachment,
|
||||||
|
ConversationMessageBlock,
|
||||||
|
ConversationToolActivity,
|
||||||
ProjectCreateInput,
|
ProjectCreateInput,
|
||||||
InteractiveWorkMode,
|
InteractiveWorkMode,
|
||||||
WorkspaceChanges
|
WorkspaceChanges
|
||||||
} from '../../shared/assistant-contracts'
|
} from '../../shared/assistant-contracts'
|
||||||
import {
|
import {
|
||||||
conversationAttachmentSchema,
|
conversationAttachmentSchema,
|
||||||
|
conversationMessageBlocksSchema,
|
||||||
interactiveWorkModes,
|
interactiveWorkModes,
|
||||||
normalizeInteractiveWorkMode
|
normalizeInteractiveWorkMode
|
||||||
} from '../../shared/assistant-contracts'
|
} from '../../shared/assistant-contracts'
|
||||||
import { ActivityPanel } from './ActivityPanel'
|
import { ActivityPanel } from './ActivityPanel'
|
||||||
|
import { AgentQuestionCard } from './AgentQuestionCard'
|
||||||
import {
|
import {
|
||||||
loadActivityRecords,
|
loadActivityRecords,
|
||||||
reconcileActivityRecords,
|
reconcileActivityRecords,
|
||||||
@@ -268,20 +273,7 @@ function supportsSubagentSmartRouting(
|
|||||||
return workMode === 'ask' || ['plan'].includes(workMode)
|
return workMode === 'ask' || ['plan'].includes(workMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ToolActivity = {
|
type ToolActivity = ConversationToolActivity
|
||||||
callId?: string
|
|
||||||
name: string
|
|
||||||
state:
|
|
||||||
| 'pending'
|
|
||||||
| 'running'
|
|
||||||
| 'completed'
|
|
||||||
| 'failed'
|
|
||||||
| 'recoverable'
|
|
||||||
| 'cancelled'
|
|
||||||
| 'interrupted'
|
|
||||||
summary: string
|
|
||||||
error?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type SubagentActivity = {
|
type SubagentActivity = {
|
||||||
childTaskId: string
|
childTaskId: string
|
||||||
@@ -298,6 +290,7 @@ type Message = {
|
|||||||
role: 'user' | 'assistant'
|
role: 'user' | 'assistant'
|
||||||
content: string
|
content: string
|
||||||
reasoning?: string
|
reasoning?: string
|
||||||
|
blocks?: ConversationMessageBlock[]
|
||||||
createdAt: number
|
createdAt: number
|
||||||
state: 'streaming' | 'complete' | 'error'
|
state: 'streaming' | 'complete' | 'error'
|
||||||
status?: string
|
status?: string
|
||||||
@@ -311,6 +304,7 @@ type Message = {
|
|||||||
argumentSummary?: string
|
argumentSummary?: string
|
||||||
allowPermanent?: boolean
|
allowPermanent?: boolean
|
||||||
}
|
}
|
||||||
|
question?: Extract<AgentEvent, { type: 'question' }>
|
||||||
sources?: string[]
|
sources?: string[]
|
||||||
sourceReferences?: KnowledgeSearchReference[]
|
sourceReferences?: KnowledgeSearchReference[]
|
||||||
artifactIds?: string[]
|
artifactIds?: string[]
|
||||||
@@ -394,6 +388,89 @@ const subagentStateLabels: Record<SubagentActivity['state'], string> = {
|
|||||||
cancelled: '已取消'
|
cancelled: '已取消'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const maxMessageContentLength = 1_000_000
|
||||||
|
const maxMessageBlocks = 500
|
||||||
|
|
||||||
|
function appendMessageContentBlock(
|
||||||
|
blocks: ConversationMessageBlock[] | undefined,
|
||||||
|
type: 'text' | 'reasoning',
|
||||||
|
delta: string
|
||||||
|
): ConversationMessageBlock[] | undefined {
|
||||||
|
if (!blocks || !delta) {
|
||||||
|
return blocks
|
||||||
|
}
|
||||||
|
const current = [...blocks]
|
||||||
|
const previous = current.at(-1)
|
||||||
|
if (previous?.type === type) {
|
||||||
|
previous.content = `${previous.content}${delta}`.slice(
|
||||||
|
0,
|
||||||
|
maxMessageContentLength
|
||||||
|
)
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
if (current.length >= maxMessageBlocks) {
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
current.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
type,
|
||||||
|
content: delta.slice(0, maxMessageContentLength)
|
||||||
|
})
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
|
||||||
|
function upsertMessageToolBlock(
|
||||||
|
blocks: ConversationMessageBlock[] | undefined,
|
||||||
|
tool: ToolActivity
|
||||||
|
): ConversationMessageBlock[] | undefined {
|
||||||
|
if (!blocks) {
|
||||||
|
return blocks
|
||||||
|
}
|
||||||
|
const callId = tool.callId
|
||||||
|
const index = callId
|
||||||
|
? blocks.findIndex(
|
||||||
|
(block) =>
|
||||||
|
block.type === 'tool' && block.tool.callId === callId
|
||||||
|
)
|
||||||
|
: -1
|
||||||
|
if (index >= 0) {
|
||||||
|
return blocks.map((block, blockIndex) =>
|
||||||
|
blockIndex === index && block.type === 'tool'
|
||||||
|
? { ...block, tool }
|
||||||
|
: block
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (blocks.length >= maxMessageBlocks) {
|
||||||
|
return blocks
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
...blocks,
|
||||||
|
{
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
type: 'tool',
|
||||||
|
tool
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
function terminalizeMessageToolBlocks(
|
||||||
|
blocks: ConversationMessageBlock[] | undefined,
|
||||||
|
state: 'failed' | 'cancelled'
|
||||||
|
): ConversationMessageBlock[] | undefined {
|
||||||
|
return blocks?.map((block) =>
|
||||||
|
block.type === 'tool' &&
|
||||||
|
(block.tool.state === 'pending' || block.tool.state === 'running')
|
||||||
|
? {
|
||||||
|
...block,
|
||||||
|
tool: {
|
||||||
|
...block.tool,
|
||||||
|
state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: block
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function createConversation(
|
function createConversation(
|
||||||
projectId?: string,
|
projectId?: string,
|
||||||
runtimeSelection?: AgentRuntimeSelection
|
runtimeSelection?: AgentRuntimeSelection
|
||||||
@@ -492,6 +569,9 @@ function isConversation(value: unknown): value is Conversation {
|
|||||||
entry.content.length <= 1_000_000 &&
|
entry.content.length <= 1_000_000 &&
|
||||||
(entry.reasoning === undefined ||
|
(entry.reasoning === undefined ||
|
||||||
typeof entry.reasoning === 'string') &&
|
typeof entry.reasoning === 'string') &&
|
||||||
|
(entry.blocks === undefined ||
|
||||||
|
conversationMessageBlocksSchema.safeParse(entry.blocks)
|
||||||
|
.success) &&
|
||||||
typeof entry.createdAt === 'number' &&
|
typeof entry.createdAt === 'number' &&
|
||||||
(entry.state === 'streaming' ||
|
(entry.state === 'streaming' ||
|
||||||
entry.state === 'complete' ||
|
entry.state === 'complete' ||
|
||||||
@@ -525,6 +605,7 @@ function toConversationSnapshots(
|
|||||||
role: message.role,
|
role: message.role,
|
||||||
content: message.content,
|
content: message.content,
|
||||||
reasoning: message.reasoning,
|
reasoning: message.reasoning,
|
||||||
|
blocks: message.blocks,
|
||||||
createdAt: message.createdAt,
|
createdAt: message.createdAt,
|
||||||
state: message.state,
|
state: message.state,
|
||||||
status: message.status,
|
status: message.status,
|
||||||
@@ -1608,7 +1689,7 @@ function App(): React.JSX.Element {
|
|||||||
? {
|
? {
|
||||||
...task,
|
...task,
|
||||||
status:
|
status:
|
||||||
event.type === 'approval'
|
event.type === 'approval' || event.type === 'question'
|
||||||
? 'waiting_approval'
|
? 'waiting_approval'
|
||||||
: event.type === 'done'
|
: event.type === 'done'
|
||||||
? 'completed'
|
? 'completed'
|
||||||
@@ -1673,19 +1754,46 @@ function App(): React.JSX.Element {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (event.type === 'text') {
|
if (event.type === 'text') {
|
||||||
updateMessage(run.conversationId, run.messageId, (message) => ({
|
updateMessage(run.conversationId, run.messageId, (message) => {
|
||||||
...message,
|
const remaining = Math.max(
|
||||||
content: `${message.content}${event.delta}`.slice(0, 1_000_000),
|
0,
|
||||||
status:
|
maxMessageContentLength - message.content.length
|
||||||
message.content.length + event.delta.length > 1_000_000
|
)
|
||||||
? '回答过长,已在本地截断显示'
|
const acceptedDelta = event.delta.slice(0, remaining)
|
||||||
: undefined
|
return {
|
||||||
}))
|
...message,
|
||||||
|
content: `${message.content}${acceptedDelta}`,
|
||||||
|
blocks: appendMessageContentBlock(
|
||||||
|
message.blocks,
|
||||||
|
'text',
|
||||||
|
acceptedDelta
|
||||||
|
),
|
||||||
|
status:
|
||||||
|
event.delta.length > remaining
|
||||||
|
? '回答过长,已在本地截断显示'
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
})
|
||||||
} else if (event.type === 'reasoning') {
|
} else if (event.type === 'reasoning') {
|
||||||
updateMessage(run.conversationId, run.messageId, (message) => ({
|
updateMessage(run.conversationId, run.messageId, (message) => {
|
||||||
...message,
|
const currentReasoning = message.reasoning ?? ''
|
||||||
reasoning: `${message.reasoning ?? ''}${event.delta}`
|
const acceptedDelta = event.delta.slice(
|
||||||
}))
|
0,
|
||||||
|
Math.max(
|
||||||
|
0,
|
||||||
|
maxMessageContentLength - currentReasoning.length
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
...message,
|
||||||
|
reasoning: `${currentReasoning}${acceptedDelta}`,
|
||||||
|
blocks: appendMessageContentBlock(
|
||||||
|
message.blocks,
|
||||||
|
'reasoning',
|
||||||
|
acceptedDelta
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
} else if (event.type === 'status') {
|
} else if (event.type === 'status') {
|
||||||
updateMessage(run.conversationId, run.messageId, (message) => ({
|
updateMessage(run.conversationId, run.messageId, (message) => ({
|
||||||
...message,
|
...message,
|
||||||
@@ -1728,7 +1836,11 @@ function App(): React.JSX.Element {
|
|||||||
} else {
|
} else {
|
||||||
tools.push(tool)
|
tools.push(tool)
|
||||||
}
|
}
|
||||||
return { ...message, tools }
|
return {
|
||||||
|
...message,
|
||||||
|
tools,
|
||||||
|
blocks: upsertMessageToolBlock(message.blocks, tool)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
} else if (event.type === 'subagent') {
|
} else if (event.type === 'subagent') {
|
||||||
const childStatus = event.state
|
const childStatus = event.state
|
||||||
@@ -1831,6 +1943,12 @@ function App(): React.JSX.Element {
|
|||||||
allowPermanent: event.allowPermanent
|
allowPermanent: event.allowPermanent
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
} else if (event.type === 'question') {
|
||||||
|
updateMessage(run.conversationId, run.messageId, (message) => ({
|
||||||
|
...message,
|
||||||
|
status: undefined,
|
||||||
|
question: event
|
||||||
|
}))
|
||||||
} else if (event.type === 'artifact') {
|
} else if (event.type === 'artifact') {
|
||||||
updateMessage(run.conversationId, run.messageId, (message) => ({
|
updateMessage(run.conversationId, run.messageId, (message) => ({
|
||||||
...message,
|
...message,
|
||||||
@@ -1924,30 +2042,47 @@ function App(): React.JSX.Element {
|
|||||||
: 'Agent Runtime 已完成响应',
|
: 'Agent Runtime 已完成响应',
|
||||||
status: terminalStatus
|
status: terminalStatus
|
||||||
})
|
})
|
||||||
updateMessage(run.conversationId, run.messageId, (message) => ({
|
updateMessage(run.conversationId, run.messageId, (message) => {
|
||||||
...message,
|
const toolTerminalState =
|
||||||
state: event.type === 'error' ? 'error' : 'complete',
|
|
||||||
status: event.type === 'error' ? event.message : undefined,
|
|
||||||
approval: undefined,
|
|
||||||
tools:
|
|
||||||
event.type === 'error'
|
event.type === 'error'
|
||||||
|
? event.status === 'cancelled'
|
||||||
|
? ('cancelled' as const)
|
||||||
|
: ('failed' as const)
|
||||||
|
: undefined
|
||||||
|
const fallbackError =
|
||||||
|
event.type === 'error' && !message.content
|
||||||
|
? event.message.slice(0, maxMessageContentLength)
|
||||||
|
: ''
|
||||||
|
return {
|
||||||
|
...message,
|
||||||
|
state: event.type === 'error' ? 'error' : 'complete',
|
||||||
|
status: event.type === 'error' ? event.message : undefined,
|
||||||
|
approval: undefined,
|
||||||
|
question: undefined,
|
||||||
|
tools: toolTerminalState
|
||||||
? message.tools?.map((tool) =>
|
? message.tools?.map((tool) =>
|
||||||
tool.state === 'pending' || tool.state === 'running'
|
tool.state === 'pending' || tool.state === 'running'
|
||||||
? {
|
? { ...tool, state: toolTerminalState }
|
||||||
...tool,
|
|
||||||
state:
|
|
||||||
event.status === 'cancelled'
|
|
||||||
? ('cancelled' as const)
|
|
||||||
: ('failed' as const)
|
|
||||||
}
|
|
||||||
: tool
|
: tool
|
||||||
)
|
)
|
||||||
: message.tools,
|
: message.tools,
|
||||||
content:
|
blocks: toolTerminalState
|
||||||
event.type === 'error' && !message.content
|
? terminalizeMessageToolBlocks(
|
||||||
? event.message
|
appendMessageContentBlock(
|
||||||
: message.content
|
message.blocks,
|
||||||
}))
|
'text',
|
||||||
|
fallbackError
|
||||||
|
),
|
||||||
|
toolTerminalState
|
||||||
|
)
|
||||||
|
: appendMessageContentBlock(
|
||||||
|
message.blocks,
|
||||||
|
'text',
|
||||||
|
fallbackError
|
||||||
|
),
|
||||||
|
content: fallbackError || message.content
|
||||||
|
}
|
||||||
|
})
|
||||||
activeRuns.current.delete(event.requestId)
|
activeRuns.current.delete(event.requestId)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -2088,6 +2223,22 @@ function App(): React.JSX.Element {
|
|||||||
},
|
},
|
||||||
[activeProjectId]
|
[activeProjectId]
|
||||||
)
|
)
|
||||||
|
const openWorkspaceEntry = useCallback(
|
||||||
|
async (
|
||||||
|
path: string,
|
||||||
|
type: 'file' | 'directory'
|
||||||
|
): Promise<void> => {
|
||||||
|
if (!activeProjectId) {
|
||||||
|
throw new Error('请先选择项目')
|
||||||
|
}
|
||||||
|
await window.goodbuddy.workspace.openPath(
|
||||||
|
activeProjectId,
|
||||||
|
path,
|
||||||
|
type
|
||||||
|
)
|
||||||
|
},
|
||||||
|
[activeProjectId]
|
||||||
|
)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (assistantSidebarTab !== 'changes') {
|
if (assistantSidebarTab !== 'changes') {
|
||||||
@@ -2510,6 +2661,27 @@ function App(): React.JSX.Element {
|
|||||||
return project
|
return project
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updateProject = async (
|
||||||
|
projectId: string,
|
||||||
|
input: ProjectCreateInput
|
||||||
|
): Promise<AssistantProject> => {
|
||||||
|
const project = await window.goodbuddy.projects.update(
|
||||||
|
projectId,
|
||||||
|
input
|
||||||
|
)
|
||||||
|
setProjects((current) =>
|
||||||
|
current.map((candidate) =>
|
||||||
|
candidate.id === project.id ? project : candidate
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if (project.id === activeProjectId) {
|
||||||
|
setWorkMode(
|
||||||
|
normalizeInteractiveWorkMode(project.defaultWorkMode)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return project
|
||||||
|
}
|
||||||
|
|
||||||
const archiveProject = async (projectId: string): Promise<void> => {
|
const archiveProject = async (projectId: string): Promise<void> => {
|
||||||
await window.goodbuddy.projects.setArchived(projectId, true)
|
await window.goodbuddy.projects.setArchived(projectId, true)
|
||||||
const remaining = projects.filter((project) => project.id !== projectId)
|
const remaining = projects.filter((project) => project.id !== projectId)
|
||||||
@@ -2520,6 +2692,65 @@ function App(): React.JSX.Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const deleteProject = async (
|
||||||
|
projectId: string,
|
||||||
|
confirmation: string
|
||||||
|
): Promise<void> => {
|
||||||
|
await window.goodbuddy.projects.delete(projectId, confirmation)
|
||||||
|
const remainingProjects = projects.filter(
|
||||||
|
(project) => project.id !== projectId
|
||||||
|
)
|
||||||
|
const remainingConversations = conversations.filter(
|
||||||
|
(conversation) => conversation.projectId !== projectId
|
||||||
|
)
|
||||||
|
setProjects(remainingProjects)
|
||||||
|
setConversations(remainingConversations)
|
||||||
|
setAssistantTasks((current) =>
|
||||||
|
current.filter((task) => task.projectId !== projectId)
|
||||||
|
)
|
||||||
|
setAssistantArtifacts((current) =>
|
||||||
|
current.filter((artifact) => artifact.projectId !== projectId)
|
||||||
|
)
|
||||||
|
setAssistantMemories((current) =>
|
||||||
|
current.filter(
|
||||||
|
(memory) =>
|
||||||
|
!(
|
||||||
|
memory.scope === 'project' &&
|
||||||
|
memory.scopeId === projectId
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
setAssistantSchedules((current) =>
|
||||||
|
current.filter((schedule) => schedule.projectId !== projectId)
|
||||||
|
)
|
||||||
|
setAssistantHeartbeats((current) =>
|
||||||
|
current.filter((heartbeat) => heartbeat.projectId !== projectId)
|
||||||
|
)
|
||||||
|
const next = remainingProjects[0]
|
||||||
|
if (next) {
|
||||||
|
setActiveProjectId(next.id)
|
||||||
|
setWorkMode(
|
||||||
|
normalizeInteractiveWorkMode(next.defaultWorkMode)
|
||||||
|
)
|
||||||
|
const nextConversation = remainingConversations.find(
|
||||||
|
(conversation) => conversation.projectId === next.id
|
||||||
|
)
|
||||||
|
if (nextConversation) {
|
||||||
|
setActiveId(nextConversation.id)
|
||||||
|
} else {
|
||||||
|
const created = createConversation(
|
||||||
|
next.id,
|
||||||
|
runtimeSettings
|
||||||
|
? getDefaultRuntimeSelection(runtimeSettings)
|
||||||
|
: undefined
|
||||||
|
)
|
||||||
|
setConversations((current) => [created, ...current])
|
||||||
|
setActiveId(created.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setView('chat')
|
||||||
|
}
|
||||||
|
|
||||||
const newConversation = (): void => {
|
const newConversation = (): void => {
|
||||||
startNewConversation(activeProjectId || undefined)
|
startNewConversation(activeProjectId || undefined)
|
||||||
}
|
}
|
||||||
@@ -2818,6 +3049,7 @@ function App(): React.JSX.Element {
|
|||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: '',
|
content: '',
|
||||||
|
blocks: [],
|
||||||
createdAt: Date.now(),
|
createdAt: Date.now(),
|
||||||
state: 'streaming',
|
state: 'streaming',
|
||||||
status: '正在连接 Agent Runtime'
|
status: '正在连接 Agent Runtime'
|
||||||
@@ -2982,6 +3214,20 @@ function App(): React.JSX.Element {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const respondToQuestion = async (
|
||||||
|
conversationId: string,
|
||||||
|
messageId: string,
|
||||||
|
questionId: string,
|
||||||
|
answers?: AgentQuestionAnswer[]
|
||||||
|
): Promise<void> => {
|
||||||
|
await window.goodbuddy.agent.respondQuestion(questionId, answers)
|
||||||
|
updateMessage(conversationId, messageId, (message) => ({
|
||||||
|
...message,
|
||||||
|
question: undefined,
|
||||||
|
status: answers ? '回答已提交,OpenCode 正在继续执行' : '已跳过问题'
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
const addContext = async (
|
const addContext = async (
|
||||||
action: () => Promise<ContextAttachment | ContextAttachment[]>
|
action: () => Promise<ContextAttachment | ContextAttachment[]>
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
@@ -3383,10 +3629,12 @@ function App(): React.JSX.Element {
|
|||||||
activeProjectId={activeProjectId}
|
activeProjectId={activeProjectId}
|
||||||
onArchive={archiveProject}
|
onArchive={archiveProject}
|
||||||
onCreate={createProject}
|
onCreate={createProject}
|
||||||
|
onDelete={deleteProject}
|
||||||
onSelect={selectProject}
|
onSelect={selectProject}
|
||||||
onSelectRoot={() =>
|
onSelectRoot={() =>
|
||||||
window.goodbuddy.settings.selectWorkspace()
|
window.goodbuddy.settings.selectWorkspace()
|
||||||
}
|
}
|
||||||
|
onUpdate={updateProject}
|
||||||
projects={projects}
|
projects={projects}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -3414,7 +3662,7 @@ function App(): React.JSX.Element {
|
|||||||
onClick={() => setView('chat')}
|
onClick={() => setView('chat')}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
<History size={17} />
|
<MessageSquare size={17} />
|
||||||
<span>对话</span>
|
<span>对话</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
@@ -3901,30 +4149,85 @@ function App(): React.JSX.Element {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{message.reasoning && (
|
{message.blocks && message.blocks.length > 0 ? (
|
||||||
<details
|
<div className="message-blocks">
|
||||||
className="message-reasoning"
|
{message.blocks.map((block) =>
|
||||||
key={`${message.id}-${message.state}`}
|
block.type === 'reasoning' ? (
|
||||||
open={message.state === 'streaming'}
|
<details
|
||||||
>
|
className="message-reasoning"
|
||||||
<summary>
|
key={block.id}
|
||||||
{message.state === 'streaming'
|
open={
|
||||||
? '正在推理'
|
message.state === 'streaming' &&
|
||||||
: '推理过程'}
|
message.blocks?.at(-1)?.id === block.id
|
||||||
</summary>
|
}
|
||||||
<div className="markdown-content message-reasoning__content">
|
>
|
||||||
<MarkdownRenderer>
|
<summary>
|
||||||
{message.reasoning}
|
{message.state === 'streaming'
|
||||||
</MarkdownRenderer>
|
? '正在推理'
|
||||||
</div>
|
: '推理过程'}
|
||||||
</details>
|
</summary>
|
||||||
)}
|
<div className="markdown-content message-reasoning__content">
|
||||||
{message.content && (
|
<MarkdownRenderer>
|
||||||
<div className="markdown-content message__content">
|
{block.content}
|
||||||
<MarkdownRenderer>
|
</MarkdownRenderer>
|
||||||
{message.content}
|
</div>
|
||||||
</MarkdownRenderer>
|
</details>
|
||||||
|
) : block.type === 'text' ? (
|
||||||
|
<div
|
||||||
|
className="markdown-content message__content"
|
||||||
|
key={block.id}
|
||||||
|
>
|
||||||
|
<MarkdownRenderer>
|
||||||
|
{block.content}
|
||||||
|
</MarkdownRenderer>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="tool-activity"
|
||||||
|
key={block.id}
|
||||||
|
>
|
||||||
|
<TerminalSquare size={15} />
|
||||||
|
<div className="tool-activity__content">
|
||||||
|
<span>{block.tool.summary}</span>
|
||||||
|
{block.tool.error && (
|
||||||
|
<code>{block.tool.error}</code>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<small>
|
||||||
|
{toolStateLabels[block.tool.state]}
|
||||||
|
</small>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{message.reasoning && (
|
||||||
|
<details
|
||||||
|
className="message-reasoning"
|
||||||
|
key={`${message.id}-${message.state}`}
|
||||||
|
open={message.state === 'streaming'}
|
||||||
|
>
|
||||||
|
<summary>
|
||||||
|
{message.state === 'streaming'
|
||||||
|
? '正在推理'
|
||||||
|
: '推理过程'}
|
||||||
|
</summary>
|
||||||
|
<div className="markdown-content message-reasoning__content">
|
||||||
|
<MarkdownRenderer>
|
||||||
|
{message.reasoning}
|
||||||
|
</MarkdownRenderer>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{message.content && (
|
||||||
|
<div className="markdown-content message__content">
|
||||||
|
<MarkdownRenderer>
|
||||||
|
{message.content}
|
||||||
|
</MarkdownRenderer>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
{message.artifactIds?.map((artifactId) => {
|
{message.artifactIds?.map((artifactId) => {
|
||||||
const candidate =
|
const candidate =
|
||||||
@@ -4043,19 +4346,20 @@ function App(): React.JSX.Element {
|
|||||||
</ol>
|
</ol>
|
||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
{message.tools?.map((tool) => (
|
{(!message.blocks || message.blocks.length === 0) &&
|
||||||
<div
|
message.tools?.map((tool) => (
|
||||||
className="tool-activity"
|
<div
|
||||||
key={tool.callId ?? tool.name}
|
className="tool-activity"
|
||||||
>
|
key={tool.callId ?? tool.name}
|
||||||
<TerminalSquare size={15} />
|
>
|
||||||
<div className="tool-activity__content">
|
<TerminalSquare size={15} />
|
||||||
<span>{tool.summary}</span>
|
<div className="tool-activity__content">
|
||||||
{tool.error && <code>{tool.error}</code>}
|
<span>{tool.summary}</span>
|
||||||
|
{tool.error && <code>{tool.error}</code>}
|
||||||
|
</div>
|
||||||
|
<small>{toolStateLabels[tool.state]}</small>
|
||||||
</div>
|
</div>
|
||||||
<small>{toolStateLabels[tool.state]}</small>
|
))}
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{message.subagents && message.subagents.length > 0 && (
|
{message.subagents && message.subagents.length > 0 && (
|
||||||
<section
|
<section
|
||||||
aria-label="子专家状态"
|
aria-label="子专家状态"
|
||||||
@@ -4159,6 +4463,27 @@ function App(): React.JSX.Element {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{message.question && (
|
||||||
|
<AgentQuestionCard
|
||||||
|
key={message.question.questionId}
|
||||||
|
onReject={() =>
|
||||||
|
respondToQuestion(
|
||||||
|
activeConversation.id,
|
||||||
|
message.id,
|
||||||
|
message.question!.questionId
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onSubmit={(answers) =>
|
||||||
|
respondToQuestion(
|
||||||
|
activeConversation.id,
|
||||||
|
message.id,
|
||||||
|
message.question!.questionId,
|
||||||
|
answers
|
||||||
|
)
|
||||||
|
}
|
||||||
|
value={message.question}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{message.status && (
|
{message.status && (
|
||||||
<div
|
<div
|
||||||
className={
|
className={
|
||||||
@@ -5064,6 +5389,7 @@ function App(): React.JSX.Element {
|
|||||||
onSetHeartbeatPaused={setHeartbeatPaused}
|
onSetHeartbeatPaused={setHeartbeatPaused}
|
||||||
onListWorkspaceDirectory={listWorkspaceDirectory}
|
onListWorkspaceDirectory={listWorkspaceDirectory}
|
||||||
onLoadWorkspaceFile={loadWorkspaceFile}
|
onLoadWorkspaceFile={loadWorkspaceFile}
|
||||||
|
onOpenWorkspaceEntry={openWorkspaceEntry}
|
||||||
onRefreshChanges={refreshWorkspaceChanges}
|
onRefreshChanges={refreshWorkspaceChanges}
|
||||||
onRespondApproval={(approval, decision) => {
|
onRespondApproval={(approval, decision) => {
|
||||||
void respondToApproval(
|
void respondToApproval(
|
||||||
|
|||||||
@@ -1,4 +1,11 @@
|
|||||||
import { Archive, FolderOpen, Plus, X } from 'lucide-react'
|
import {
|
||||||
|
Archive,
|
||||||
|
FolderOpen,
|
||||||
|
Plus,
|
||||||
|
Settings,
|
||||||
|
Trash2,
|
||||||
|
X
|
||||||
|
} from 'lucide-react'
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import type {
|
import type {
|
||||||
AssistantProject,
|
AssistantProject,
|
||||||
@@ -6,7 +13,10 @@ import type {
|
|||||||
ProjectCreateInput,
|
ProjectCreateInput,
|
||||||
WorkMode
|
WorkMode
|
||||||
} from '../../shared/assistant-contracts'
|
} from '../../shared/assistant-contracts'
|
||||||
import { interactiveWorkModes } from '../../shared/assistant-contracts'
|
import {
|
||||||
|
interactiveWorkModes,
|
||||||
|
normalizeInteractiveWorkMode
|
||||||
|
} from '../../shared/assistant-contracts'
|
||||||
import { trapTabFocus } from './dialog-focus'
|
import { trapTabFocus } from './dialog-focus'
|
||||||
|
|
||||||
type ProjectSwitcherProps = {
|
type ProjectSwitcherProps = {
|
||||||
@@ -14,8 +24,13 @@ type ProjectSwitcherProps = {
|
|||||||
activeProjectId: string
|
activeProjectId: string
|
||||||
onArchive: (projectId: string) => Promise<void>
|
onArchive: (projectId: string) => Promise<void>
|
||||||
onCreate: (input: ProjectCreateInput) => Promise<AssistantProject>
|
onCreate: (input: ProjectCreateInput) => Promise<AssistantProject>
|
||||||
|
onDelete: (projectId: string, confirmation: string) => Promise<void>
|
||||||
onSelect: (projectId: string) => void
|
onSelect: (projectId: string) => void
|
||||||
onSelectRoot: () => Promise<string | undefined>
|
onSelectRoot: () => Promise<string | undefined>
|
||||||
|
onUpdate: (
|
||||||
|
projectId: string,
|
||||||
|
input: ProjectCreateInput
|
||||||
|
) => Promise<AssistantProject>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const workModeLabels: Record<InteractiveWorkMode, string> = {
|
export const workModeLabels: Record<InteractiveWorkMode, string> = {
|
||||||
@@ -28,59 +43,86 @@ export function ProjectSwitcher({
|
|||||||
activeProjectId,
|
activeProjectId,
|
||||||
onArchive,
|
onArchive,
|
||||||
onCreate,
|
onCreate,
|
||||||
|
onDelete,
|
||||||
onSelect,
|
onSelect,
|
||||||
onSelectRoot
|
onSelectRoot,
|
||||||
|
onUpdate
|
||||||
}: ProjectSwitcherProps): React.JSX.Element {
|
}: ProjectSwitcherProps): React.JSX.Element {
|
||||||
const [creating, setCreating] = useState(false)
|
const [dialogMode, setDialogMode] = useState<
|
||||||
|
'create' | 'settings'
|
||||||
|
>()
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [archiving, setArchiving] = useState(false)
|
const [archiving, setArchiving] = useState(false)
|
||||||
|
const [deleting, setDeleting] = useState(false)
|
||||||
|
const [confirmingDelete, setConfirmingDelete] = useState(false)
|
||||||
|
const [deleteConfirmation, setDeleteConfirmation] = useState('')
|
||||||
const [error, setError] = useState<string>()
|
const [error, setError] = useState<string>()
|
||||||
const createButtonRef = useRef<HTMLButtonElement>(null)
|
const createButtonRef = useRef<HTMLButtonElement>(null)
|
||||||
|
const settingsButtonRef = useRef<HTMLButtonElement>(null)
|
||||||
const dialogRef = useRef<HTMLDivElement>(null)
|
const dialogRef = useRef<HTMLDivElement>(null)
|
||||||
const restoreCreateButtonFocus = useRef(false)
|
const restoreFocusTarget = useRef<
|
||||||
|
'create' | 'settings' | undefined
|
||||||
|
>(undefined)
|
||||||
const [draft, setDraft] = useState<ProjectCreateInput>({
|
const [draft, setDraft] = useState<ProjectCreateInput>({
|
||||||
name: '',
|
name: '',
|
||||||
description: '',
|
description: '',
|
||||||
rootPath: '',
|
rootPath: '',
|
||||||
defaultWorkMode: 'ask'
|
defaultWorkMode: 'ask'
|
||||||
})
|
})
|
||||||
|
const activeProject = projects.find(
|
||||||
|
(project) => project.id === activeProjectId
|
||||||
|
)
|
||||||
|
const busy = saving || archiving || deleting
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!creating) {
|
if (!dialogMode) {
|
||||||
if (restoreCreateButtonFocus.current) {
|
if (restoreFocusTarget.current === 'create') {
|
||||||
createButtonRef.current?.focus()
|
createButtonRef.current?.focus()
|
||||||
restoreCreateButtonFocus.current = false
|
} else if (restoreFocusTarget.current === 'settings') {
|
||||||
|
settingsButtonRef.current?.focus()
|
||||||
}
|
}
|
||||||
|
restoreFocusTarget.current = undefined
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
restoreCreateButtonFocus.current = true
|
|
||||||
const onKeyDown = (event: KeyboardEvent): void => {
|
const onKeyDown = (event: KeyboardEvent): void => {
|
||||||
if (event.key === 'Escape' && !saving && !archiving) {
|
if (event.key === 'Escape' && !busy) {
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
setCreating(false)
|
setConfirmingDelete(false)
|
||||||
|
setDeleteConfirmation('')
|
||||||
|
setDialogMode(undefined)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
trapTabFocus(event, dialogRef.current)
|
trapTabFocus(event, dialogRef.current)
|
||||||
}
|
}
|
||||||
document.addEventListener('keydown', onKeyDown)
|
document.addEventListener('keydown', onKeyDown)
|
||||||
return () => document.removeEventListener('keydown', onKeyDown)
|
return () => document.removeEventListener('keydown', onKeyDown)
|
||||||
}, [archiving, creating, saving])
|
}, [busy, dialogMode])
|
||||||
|
|
||||||
const create = async (): Promise<void> => {
|
const closeDialog = (): void => {
|
||||||
|
setError(undefined)
|
||||||
|
setConfirmingDelete(false)
|
||||||
|
setDeleteConfirmation('')
|
||||||
|
setDialogMode(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const save = async (): Promise<void> => {
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
try {
|
try {
|
||||||
const project = await onCreate(draft)
|
if (dialogMode === 'settings' && activeProject) {
|
||||||
onSelect(project.id)
|
await onUpdate(activeProject.id, draft)
|
||||||
setDraft({
|
} else {
|
||||||
name: '',
|
await onCreate(draft)
|
||||||
description: '',
|
}
|
||||||
rootPath: '',
|
closeDialog()
|
||||||
defaultWorkMode: 'ask'
|
|
||||||
})
|
|
||||||
setCreating(false)
|
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
setError(reason instanceof Error ? reason.message : '创建项目失败')
|
setError(
|
||||||
|
reason instanceof Error
|
||||||
|
? reason.message
|
||||||
|
: dialogMode === 'settings'
|
||||||
|
? '保存项目失败'
|
||||||
|
: '创建项目失败'
|
||||||
|
)
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false)
|
setSaving(false)
|
||||||
}
|
}
|
||||||
@@ -110,7 +152,7 @@ export function ProjectSwitcher({
|
|||||||
setError(undefined)
|
setError(undefined)
|
||||||
try {
|
try {
|
||||||
await onArchive(activeProjectId)
|
await onArchive(activeProjectId)
|
||||||
setCreating(false)
|
closeDialog()
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
setError(
|
setError(
|
||||||
reason instanceof Error ? reason.message : '归档项目失败'
|
reason instanceof Error ? reason.message : '归档项目失败'
|
||||||
@@ -120,6 +162,24 @@ export function ProjectSwitcher({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const deleteProject = async (): Promise<void> => {
|
||||||
|
if (!activeProject) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setDeleting(true)
|
||||||
|
setError(undefined)
|
||||||
|
try {
|
||||||
|
await onDelete(activeProject.id, deleteConfirmation)
|
||||||
|
closeDialog()
|
||||||
|
} catch (reason) {
|
||||||
|
setError(
|
||||||
|
reason instanceof Error ? reason.message : '删除项目失败'
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
setDeleting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="project-switcher">
|
<div className="project-switcher">
|
||||||
<div className="project-switcher__row">
|
<div className="project-switcher__row">
|
||||||
@@ -139,45 +199,79 @@ export function ProjectSwitcher({
|
|||||||
className="icon-button"
|
className="icon-button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setError(undefined)
|
setError(undefined)
|
||||||
setCreating(true)
|
setConfirmingDelete(false)
|
||||||
|
setDeleteConfirmation('')
|
||||||
|
setDraft({
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
rootPath: '',
|
||||||
|
defaultWorkMode: 'ask'
|
||||||
|
})
|
||||||
|
restoreFocusTarget.current = 'create'
|
||||||
|
setDialogMode('create')
|
||||||
}}
|
}}
|
||||||
ref={createButtonRef}
|
ref={createButtonRef}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
<Plus size={15} />
|
<Plus size={15} />
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
aria-label="项目设置"
|
||||||
|
className="icon-button"
|
||||||
|
disabled={!activeProject}
|
||||||
|
onClick={() => {
|
||||||
|
if (!activeProject) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setError(undefined)
|
||||||
|
setConfirmingDelete(false)
|
||||||
|
setDeleteConfirmation('')
|
||||||
|
setDraft({
|
||||||
|
name: activeProject.name,
|
||||||
|
description: activeProject.description,
|
||||||
|
rootPath: activeProject.rootPath,
|
||||||
|
defaultWorkMode: normalizeInteractiveWorkMode(
|
||||||
|
activeProject.defaultWorkMode
|
||||||
|
)
|
||||||
|
})
|
||||||
|
restoreFocusTarget.current = 'settings'
|
||||||
|
setDialogMode('settings')
|
||||||
|
}}
|
||||||
|
ref={settingsButtonRef}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Settings size={15} />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{creating && (
|
{dialogMode && (
|
||||||
<div
|
<div
|
||||||
className="project-create-backdrop"
|
className="project-create-backdrop"
|
||||||
onMouseDown={(event) => {
|
onMouseDown={(event) => {
|
||||||
if (
|
if (event.currentTarget === event.target && !busy) {
|
||||||
event.currentTarget === event.target &&
|
closeDialog()
|
||||||
!saving &&
|
|
||||||
!archiving
|
|
||||||
) {
|
|
||||||
setError(undefined)
|
|
||||||
setCreating(false)
|
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
aria-labelledby="project-create-title"
|
aria-labelledby="project-dialog-title"
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
className="project-create-card"
|
className="project-create-card"
|
||||||
ref={dialogRef}
|
ref={dialogRef}
|
||||||
role="dialog"
|
role="dialog"
|
||||||
>
|
>
|
||||||
<header>
|
<header>
|
||||||
<strong id="project-create-title">新建项目</strong>
|
<strong id="project-dialog-title">
|
||||||
|
{dialogMode === 'create' ? '新建项目' : '项目设置'}
|
||||||
|
</strong>
|
||||||
<button
|
<button
|
||||||
aria-label="关闭新建项目"
|
aria-label={
|
||||||
|
dialogMode === 'create'
|
||||||
|
? '关闭新建项目'
|
||||||
|
: '关闭项目设置'
|
||||||
|
}
|
||||||
className="icon-button"
|
className="icon-button"
|
||||||
disabled={saving || archiving}
|
disabled={busy}
|
||||||
onClick={() => {
|
onClick={closeDialog}
|
||||||
setError(undefined)
|
|
||||||
setCreating(false)
|
|
||||||
}}
|
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
<X size={14} />
|
<X size={14} />
|
||||||
@@ -186,7 +280,7 @@ export function ProjectSwitcher({
|
|||||||
<label>
|
<label>
|
||||||
<span>名称</span>
|
<span>名称</span>
|
||||||
<input
|
<input
|
||||||
autoFocus
|
autoFocus={!confirmingDelete}
|
||||||
maxLength={120}
|
maxLength={120}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
setDraft((current) => ({
|
setDraft((current) => ({
|
||||||
@@ -218,7 +312,7 @@ export function ProjectSwitcher({
|
|||||||
<button
|
<button
|
||||||
aria-label="选择项目根目录"
|
aria-label="选择项目根目录"
|
||||||
className="secondary-button"
|
className="secondary-button"
|
||||||
disabled={saving || archiving}
|
disabled={busy}
|
||||||
onClick={() => void selectRoot()}
|
onClick={() => void selectRoot()}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
@@ -249,27 +343,117 @@ export function ProjectSwitcher({
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{dialogMode === 'settings' && (
|
||||||
|
<section
|
||||||
|
aria-labelledby="project-danger-title"
|
||||||
|
className="project-danger-zone"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<strong id="project-danger-title">危险操作</strong>
|
||||||
|
<p>
|
||||||
|
删除项目会永久移除 GoodBuddy
|
||||||
|
中的项目、对话、任务、计划、心跳、记忆和成果,但不会删除磁盘上的项目目录或文件。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{!confirmingDelete ? (
|
||||||
|
<button
|
||||||
|
className="danger-button danger-button--quiet"
|
||||||
|
disabled={busy || projects.length <= 1}
|
||||||
|
onClick={() => {
|
||||||
|
setError(undefined)
|
||||||
|
setDeleteConfirmation('')
|
||||||
|
setConfirmingDelete(true)
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Trash2 size={13} />
|
||||||
|
删除项目
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="project-delete-confirmation">
|
||||||
|
<label>
|
||||||
|
<span>
|
||||||
|
输入“{activeProject?.name}”确认删除
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(event) =>
|
||||||
|
setDeleteConfirmation(event.target.value)
|
||||||
|
}
|
||||||
|
value={deleteConfirmation}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
className="secondary-button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => {
|
||||||
|
setError(undefined)
|
||||||
|
setDeleteConfirmation('')
|
||||||
|
setConfirmingDelete(false)
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
取消删除
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="danger-button"
|
||||||
|
disabled={
|
||||||
|
busy ||
|
||||||
|
deleteConfirmation !== activeProject?.name
|
||||||
|
}
|
||||||
|
onClick={() => void deleteProject()}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Trash2 size={13} />
|
||||||
|
{deleting ? '删除中' : '永久删除项目'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{projects.length <= 1 && (
|
||||||
|
<small>至少需要保留一个可用项目。</small>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
<div className="project-create-card__actions">
|
<div className="project-create-card__actions">
|
||||||
{projects.length > 1 && activeProjectId && (
|
{dialogMode === 'settings' &&
|
||||||
<button
|
projects.length > 1 &&
|
||||||
className="secondary-button"
|
activeProjectId && (
|
||||||
disabled={saving || archiving}
|
<button
|
||||||
onClick={() => void archive()}
|
className="secondary-button"
|
||||||
type="button"
|
disabled={busy}
|
||||||
>
|
onClick={() => void archive()}
|
||||||
<Archive size={13} />
|
type="button"
|
||||||
{archiving ? '归档中' : '归档当前'}
|
>
|
||||||
</button>
|
<Archive size={13} />
|
||||||
)}
|
{archiving ? '归档中' : '归档项目'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
className="secondary-button"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={closeDialog}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
className="primary-button"
|
className="primary-button"
|
||||||
disabled={
|
disabled={
|
||||||
saving || archiving || !draft.name.trim()
|
busy || !draft.name.trim() || confirmingDelete
|
||||||
}
|
}
|
||||||
onClick={() => void create()}
|
onClick={() => void save()}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
{saving ? '创建中' : '创建'}
|
{saving
|
||||||
|
? dialogMode === 'create'
|
||||||
|
? '创建中'
|
||||||
|
: '保存中'
|
||||||
|
: dialogMode === 'create'
|
||||||
|
? '创建'
|
||||||
|
: '保存项目'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ function renderSidebar({
|
|||||||
}))}
|
}))}
|
||||||
onLoadArtifact={vi.fn(async () => undefined)}
|
onLoadArtifact={vi.fn(async () => undefined)}
|
||||||
onLoadWorkspaceFile={vi.fn()}
|
onLoadWorkspaceFile={vi.fn()}
|
||||||
|
onOpenWorkspaceEntry={vi.fn(async () => undefined)}
|
||||||
onOpenConversation={vi.fn()}
|
onOpenConversation={vi.fn()}
|
||||||
onOpenHeartbeat={vi.fn()}
|
onOpenHeartbeat={vi.fn()}
|
||||||
onRefreshChanges={vi.fn(async () => undefined)}
|
onRefreshChanges={vi.fn(async () => undefined)}
|
||||||
|
|||||||
@@ -104,6 +104,10 @@ type RightAssistantSidebarProps = {
|
|||||||
path: string
|
path: string
|
||||||
) => Promise<WorkspaceDirectoryListing>
|
) => Promise<WorkspaceDirectoryListing>
|
||||||
onLoadWorkspaceFile: (path: string) => Promise<WorkspaceFilePreview>
|
onLoadWorkspaceFile: (path: string) => Promise<WorkspaceFilePreview>
|
||||||
|
onOpenWorkspaceEntry: (
|
||||||
|
path: string,
|
||||||
|
type: 'file' | 'directory'
|
||||||
|
) => Promise<void>
|
||||||
onRemoveMemory: (memoryId: string) => Promise<void>
|
onRemoveMemory: (memoryId: string) => Promise<void>
|
||||||
onSetMemoryStatus: (
|
onSetMemoryStatus: (
|
||||||
memoryId: string,
|
memoryId: string,
|
||||||
@@ -139,7 +143,7 @@ const tabs: Array<{
|
|||||||
{
|
{
|
||||||
id: 'changes',
|
id: 'changes',
|
||||||
label: '工作区',
|
label: '工作区',
|
||||||
description: '浏览项目文件、Git 变更与工具活动'
|
description: '浏览项目文件与工具活动'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'browser',
|
id: 'browser',
|
||||||
@@ -262,6 +266,7 @@ export function RightAssistantSidebar({
|
|||||||
onRefreshChanges,
|
onRefreshChanges,
|
||||||
onListWorkspaceDirectory,
|
onListWorkspaceDirectory,
|
||||||
onLoadWorkspaceFile,
|
onLoadWorkspaceFile,
|
||||||
|
onOpenWorkspaceEntry,
|
||||||
onRemoveMemory,
|
onRemoveMemory,
|
||||||
onSetMemoryStatus,
|
onSetMemoryStatus,
|
||||||
onRespondApproval,
|
onRespondApproval,
|
||||||
@@ -1079,8 +1084,8 @@ export function RightAssistantSidebar({
|
|||||||
<>
|
<>
|
||||||
<section className="assistant-sidebar__section">
|
<section className="assistant-sidebar__section">
|
||||||
<p className="assistant-sidebar__section-description">
|
<p className="assistant-sidebar__section-description">
|
||||||
浏览当前项目文件、检查未提交 Git 变更,并查看 Agent
|
浏览当前项目文件,并查看 Agent 的工具活动。Git
|
||||||
的工具活动。
|
项目还会显示未提交更改。
|
||||||
</p>
|
</p>
|
||||||
<h3>
|
<h3>
|
||||||
<FolderTree size={15} />
|
<FolderTree size={15} />
|
||||||
@@ -1088,6 +1093,7 @@ export function RightAssistantSidebar({
|
|||||||
<button
|
<button
|
||||||
aria-label="刷新工作区文件"
|
aria-label="刷新工作区文件"
|
||||||
className="icon-button"
|
className="icon-button"
|
||||||
|
disabled={!workspaceProjectId}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setWorkspaceRefreshVersion((current) => current + 1)
|
setWorkspaceRefreshVersion((current) => current + 1)
|
||||||
runAction(
|
runAction(
|
||||||
@@ -1095,6 +1101,7 @@ export function RightAssistantSidebar({
|
|||||||
'刷新工作区文件失败'
|
'刷新工作区文件失败'
|
||||||
)
|
)
|
||||||
}}
|
}}
|
||||||
|
title="刷新"
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
<RefreshCw size={14} />
|
<RefreshCw size={14} />
|
||||||
@@ -1104,6 +1111,7 @@ export function RightAssistantSidebar({
|
|||||||
changedFiles={workspaceChanges?.files ?? emptyChangedFiles}
|
changedFiles={workspaceChanges?.files ?? emptyChangedFiles}
|
||||||
key={`${workspaceProjectId ?? 'none'}:${workspaceRefreshVersion}`}
|
key={`${workspaceProjectId ?? 'none'}:${workspaceRefreshVersion}`}
|
||||||
onListDirectory={onListWorkspaceDirectory}
|
onListDirectory={onListWorkspaceDirectory}
|
||||||
|
onOpenEntry={onOpenWorkspaceEntry}
|
||||||
onOpenFile={openWorkspaceFile}
|
onOpenFile={openWorkspaceFile}
|
||||||
projectId={workspaceProjectId}
|
projectId={workspaceProjectId}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -193,6 +193,9 @@ const capabilitySnapshot = {
|
|||||||
}
|
}
|
||||||
} satisfies CapabilitySnapshot
|
} satisfies CapabilitySnapshot
|
||||||
const getCapabilitySnapshot = vi.fn(async () => capabilitySnapshot)
|
const getCapabilitySnapshot = vi.fn(async () => capabilitySnapshot)
|
||||||
|
const importSkill = vi.fn<DesktopApi['capabilities']['importSkill']>(
|
||||||
|
async () => capabilitySnapshot
|
||||||
|
)
|
||||||
const saveMcpServer = vi.fn(async () => capabilitySnapshot)
|
const saveMcpServer = vi.fn(async () => capabilitySnapshot)
|
||||||
const setSkillEnabled = vi.fn(async (_skillId: string, enabled: boolean) => ({
|
const setSkillEnabled = vi.fn(async (_skillId: string, enabled: boolean) => ({
|
||||||
...capabilitySnapshot,
|
...capabilitySnapshot,
|
||||||
@@ -342,7 +345,7 @@ describe('SettingsPanel runtime files', () => {
|
|||||||
},
|
},
|
||||||
capabilities: {
|
capabilities: {
|
||||||
getSnapshot: getCapabilitySnapshot,
|
getSnapshot: getCapabilitySnapshot,
|
||||||
importSkill: vi.fn(async () => capabilitySnapshot),
|
importSkill,
|
||||||
removeSkill: vi.fn(async () => capabilitySnapshot),
|
removeSkill: vi.fn(async () => capabilitySnapshot),
|
||||||
setSkillEnabled,
|
setSkillEnabled,
|
||||||
setSkillAssignments: vi.fn(async () => capabilitySnapshot),
|
setSkillAssignments: vi.fn(async () => capabilitySnapshot),
|
||||||
@@ -1654,6 +1657,16 @@ describe('SettingsPanel runtime files', () => {
|
|||||||
|
|
||||||
fireEvent.click(screen.getByRole('tab', { name: 'Skills' }))
|
fireEvent.click(screen.getByRole('tab', { name: 'Skills' }))
|
||||||
expect(await screen.findByText('文档写作')).toBeInTheDocument()
|
expect(await screen.findByText('文档写作')).toBeInTheDocument()
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole('button', { name: '导入 Skill 目录' })
|
||||||
|
)
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(importSkill).toHaveBeenCalledWith('directory')
|
||||||
|
)
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole('button', { name: '导入 Skill ZIP' })
|
||||||
|
)
|
||||||
|
await waitFor(() => expect(importSkill).toHaveBeenCalledWith('zip'))
|
||||||
fireEvent.click(screen.getByLabelText('启用 文档写作'))
|
fireEvent.click(screen.getByLabelText('启用 文档写作'))
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(setSkillEnabled).toHaveBeenCalledWith(
|
expect(setSkillEnabled).toHaveBeenCalledWith(
|
||||||
|
|||||||
@@ -1194,15 +1194,17 @@ export function SettingsPanel({
|
|||||||
<div className="settings-section__title">
|
<div className="settings-section__title">
|
||||||
<FolderOpen size={17} />
|
<FolderOpen size={17} />
|
||||||
<div>
|
<div>
|
||||||
<strong>工作区</strong>
|
<strong>默认工作区</strong>
|
||||||
<small>Agent 工具只能以此目录作为默认工作位置</small>
|
<small>
|
||||||
|
当前项目未设置根目录时,Agent 才使用此默认位置
|
||||||
|
</small>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<label className="field">
|
<label className="field">
|
||||||
<span>工作区目录</span>
|
<span>默认工作区目录</span>
|
||||||
<div className="workspace-picker">
|
<div className="workspace-picker">
|
||||||
<input
|
<input
|
||||||
aria-label="工作区目录"
|
aria-label="默认工作区目录"
|
||||||
onChange={(event) => setWorkspacePath(event.target.value)}
|
onChange={(event) => setWorkspacePath(event.target.value)}
|
||||||
value={workspacePath}
|
value={workspacePath}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -68,13 +68,26 @@ export function SkillsSettingsSection(): React.JSX.Element {
|
|||||||
disabled={Boolean(busy)}
|
disabled={Boolean(busy)}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
void run('import', () =>
|
void run('import', () =>
|
||||||
window.goodbuddy.capabilities.importSkill()
|
window.goodbuddy.capabilities.importSkill('directory')
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
<Download size={14} />
|
<Download size={14} />
|
||||||
导入 SKILL.md
|
导入 Skill 目录
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="secondary-button"
|
||||||
|
disabled={Boolean(busy)}
|
||||||
|
onClick={() =>
|
||||||
|
void run('import', () =>
|
||||||
|
window.goodbuddy.capabilities.importSkill('zip')
|
||||||
|
)
|
||||||
|
}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Download size={14} />
|
||||||
|
导入 Skill ZIP
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -37,25 +37,39 @@ describe('WorkspaceFilesPanel', () => {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
const onOpenFile = vi.fn()
|
const onOpenFile = vi.fn()
|
||||||
|
const onOpenEntry = vi.fn(async () => undefined)
|
||||||
|
|
||||||
render(
|
render(
|
||||||
<WorkspaceFilesPanel
|
<WorkspaceFilesPanel
|
||||||
changedFiles={[{ path: 'notes.txt', status: ' M' }]}
|
changedFiles={[{ path: 'notes.txt', status: ' M' }]}
|
||||||
onListDirectory={onListDirectory}
|
onListDirectory={onListDirectory}
|
||||||
|
onOpenEntry={onOpenEntry}
|
||||||
onOpenFile={onOpenFile}
|
onOpenFile={onOpenFile}
|
||||||
projectId="00000000-0000-4000-8000-000000000101"
|
projectId="00000000-0000-4000-8000-000000000101"
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(await screen.findByText('当前工作区')).toBeInTheDocument()
|
expect(await screen.findByText('当前工作区')).toBeInTheDocument()
|
||||||
fireEvent.click(await screen.findByRole('button', { name: /docs/u }))
|
fireEvent.click(await screen.findByRole('button', { name: 'docs' }))
|
||||||
fireEvent.click(
|
fireEvent.click(
|
||||||
await screen.findByRole('button', { name: /guide\.md/u })
|
await screen.findByRole('button', { name: 'guide.md' })
|
||||||
)
|
)
|
||||||
|
|
||||||
expect(onListDirectory).toHaveBeenCalledWith('')
|
expect(onListDirectory).toHaveBeenCalledWith('')
|
||||||
expect(onListDirectory).toHaveBeenCalledWith('docs')
|
expect(onListDirectory).toHaveBeenCalledWith('docs')
|
||||||
expect(onOpenFile).toHaveBeenCalledWith('docs/guide.md')
|
expect(onOpenFile).toHaveBeenCalledWith('docs/guide.md')
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole('button', {
|
||||||
|
name: '使用默认应用打开文件 guide.md'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(onOpenEntry).toHaveBeenCalledWith('docs/guide.md', 'file')
|
||||||
|
fireEvent.click(
|
||||||
|
screen.getByRole('button', {
|
||||||
|
name: '在系统资源管理器中打开文件夹 docs'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
expect(onOpenEntry).toHaveBeenCalledWith('docs', 'directory')
|
||||||
expect(screen.getAllByText('修改')).not.toHaveLength(0)
|
expect(screen.getAllByText('修改')).not.toHaveLength(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -84,6 +98,7 @@ describe('WorkspaceFilesPanel', () => {
|
|||||||
<WorkspaceFilesPanel
|
<WorkspaceFilesPanel
|
||||||
changedFiles={[]}
|
changedFiles={[]}
|
||||||
onListDirectory={onListDirectory}
|
onListDirectory={onListDirectory}
|
||||||
|
onOpenEntry={vi.fn(async () => undefined)}
|
||||||
onOpenFile={vi.fn()}
|
onOpenFile={vi.fn()}
|
||||||
projectId="00000000-0000-4000-8000-000000000101"
|
projectId="00000000-0000-4000-8000-000000000101"
|
||||||
/>
|
/>
|
||||||
@@ -94,6 +109,7 @@ describe('WorkspaceFilesPanel', () => {
|
|||||||
<WorkspaceFilesPanel
|
<WorkspaceFilesPanel
|
||||||
changedFiles={[]}
|
changedFiles={[]}
|
||||||
onListDirectory={onListDirectory}
|
onListDirectory={onListDirectory}
|
||||||
|
onOpenEntry={vi.fn(async () => undefined)}
|
||||||
onOpenFile={vi.fn()}
|
onOpenFile={vi.fn()}
|
||||||
projectId="00000000-0000-4000-8000-000000000102"
|
projectId="00000000-0000-4000-8000-000000000102"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
|
FileSearch,
|
||||||
FileText,
|
FileText,
|
||||||
Folder,
|
Folder,
|
||||||
FolderOpen
|
FolderOpen
|
||||||
@@ -23,6 +24,10 @@ type WorkspaceFilesPanelProps = {
|
|||||||
changedFiles: WorkspaceChangedFile[]
|
changedFiles: WorkspaceChangedFile[]
|
||||||
onListDirectory: (path: string) => Promise<WorkspaceDirectoryListing>
|
onListDirectory: (path: string) => Promise<WorkspaceDirectoryListing>
|
||||||
onOpenFile: (path: string) => void
|
onOpenFile: (path: string) => void
|
||||||
|
onOpenEntry: (
|
||||||
|
path: string,
|
||||||
|
type: WorkspaceDirectoryEntry['type']
|
||||||
|
) => Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
function statusLabel(status: string): string {
|
function statusLabel(status: string): string {
|
||||||
@@ -46,7 +51,8 @@ export function WorkspaceFilesPanel({
|
|||||||
projectId,
|
projectId,
|
||||||
changedFiles,
|
changedFiles,
|
||||||
onListDirectory,
|
onListDirectory,
|
||||||
onOpenFile
|
onOpenFile,
|
||||||
|
onOpenEntry
|
||||||
}: WorkspaceFilesPanelProps): React.JSX.Element {
|
}: WorkspaceFilesPanelProps): React.JSX.Element {
|
||||||
const [listingState, setListingState] = useState<{
|
const [listingState, setListingState] = useState<{
|
||||||
projectId?: string
|
projectId?: string
|
||||||
@@ -174,6 +180,21 @@ export function WorkspaceFilesPanel({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const openEntry = (entry: WorkspaceDirectoryEntry): void => {
|
||||||
|
setErrorState({ projectId })
|
||||||
|
void onOpenEntry(entry.path, entry.type).catch((reason: unknown) => {
|
||||||
|
setErrorState({
|
||||||
|
projectId,
|
||||||
|
value:
|
||||||
|
reason instanceof Error
|
||||||
|
? reason.message
|
||||||
|
: entry.type === 'directory'
|
||||||
|
? '打开文件夹失败'
|
||||||
|
: '打开文件失败'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const renderEntry = (
|
const renderEntry = (
|
||||||
entry: WorkspaceDirectoryEntry
|
entry: WorkspaceDirectoryEntry
|
||||||
): React.JSX.Element => {
|
): React.JSX.Element => {
|
||||||
@@ -183,20 +204,31 @@ export function WorkspaceFilesPanel({
|
|||||||
if (entry.type === 'directory') {
|
if (entry.type === 'directory') {
|
||||||
return (
|
return (
|
||||||
<div key={entry.path}>
|
<div key={entry.path}>
|
||||||
<button
|
<div className="workspace-files__entry">
|
||||||
aria-expanded={expanded}
|
<button
|
||||||
className="workspace-files__row"
|
aria-expanded={expanded}
|
||||||
onClick={() => toggleDirectory(entry.path)}
|
className="workspace-files__row"
|
||||||
type="button"
|
onClick={() => toggleDirectory(entry.path)}
|
||||||
>
|
type="button"
|
||||||
{expanded ? (
|
>
|
||||||
<ChevronDown size={13} />
|
{expanded ? (
|
||||||
) : (
|
<ChevronDown size={13} />
|
||||||
<ChevronRight size={13} />
|
) : (
|
||||||
)}
|
<ChevronRight size={13} />
|
||||||
{expanded ? <FolderOpen size={15} /> : <Folder size={15} />}
|
)}
|
||||||
<span title={entry.path}>{entry.name}</span>
|
{expanded ? <FolderOpen size={15} /> : <Folder size={15} />}
|
||||||
</button>
|
<span title={entry.path}>{entry.name}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
aria-label={`在系统资源管理器中打开文件夹 ${entry.name}`}
|
||||||
|
className="workspace-files__open-entry"
|
||||||
|
onClick={() => openEntry(entry)}
|
||||||
|
title="打开文件夹"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<FolderOpen size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
{expanded && (
|
{expanded && (
|
||||||
<div className="workspace-files__children">
|
<div className="workspace-files__children">
|
||||||
{listing?.entries.map((child) =>
|
{listing?.entries.map((child) =>
|
||||||
@@ -216,22 +248,32 @@ export function WorkspaceFilesPanel({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<button
|
<div className="workspace-files__entry" key={entry.path}>
|
||||||
className="workspace-files__row"
|
<button
|
||||||
key={entry.path}
|
className="workspace-files__row"
|
||||||
onClick={() => onOpenFile(entry.path)}
|
onClick={() => onOpenFile(entry.path)}
|
||||||
title={entry.path}
|
title={entry.path}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
<span className="workspace-files__indent" />
|
<span className="workspace-files__indent" />
|
||||||
<FileText size={15} />
|
<FileText size={15} />
|
||||||
<span>{entry.name}</span>
|
<span>{entry.name}</span>
|
||||||
{changed && (
|
{changed && (
|
||||||
<small className="workspace-files__change">
|
<small className="workspace-files__change">
|
||||||
{statusLabel(changed.status)}
|
{statusLabel(changed.status)}
|
||||||
</small>
|
</small>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
aria-label={`使用默认应用打开文件 ${entry.name}`}
|
||||||
|
className="workspace-files__open-entry"
|
||||||
|
onClick={() => openEntry(entry)}
|
||||||
|
title="打开文件"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<FileSearch size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+197
-1
@@ -171,7 +171,7 @@ textarea:focus-visible {
|
|||||||
display: grid;
|
display: grid;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
grid-template-columns: minmax(0, 1fr) auto;
|
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.project-switcher select {
|
.project-switcher select {
|
||||||
@@ -272,6 +272,56 @@ textarea:focus-visible {
|
|||||||
font-size: 9px;
|
font-size: 9px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.project-danger-zone {
|
||||||
|
display: flex;
|
||||||
|
padding: var(--space-3);
|
||||||
|
border: 1px solid var(--danger-border);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
background: var(--danger-subtle);
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-danger-zone > div:first-child {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-danger-zone strong {
|
||||||
|
color: var(--danger);
|
||||||
|
font-size: var(--font-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-danger-zone p,
|
||||||
|
.project-danger-zone small {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: var(--font-caption);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-danger-zone > .danger-button {
|
||||||
|
align-self: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-delete-confirmation {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-delete-confirmation > div {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.project-delete-confirmation .danger-button,
|
||||||
|
.project-delete-confirmation .secondary-button {
|
||||||
|
align-self: auto;
|
||||||
|
}
|
||||||
|
|
||||||
.new-chat {
|
.new-chat {
|
||||||
display: flex;
|
display: flex;
|
||||||
min-width: 248px;
|
min-width: 248px;
|
||||||
@@ -798,9 +848,49 @@ textarea:focus-visible {
|
|||||||
|
|
||||||
.workspace-files__row {
|
.workspace-files__row {
|
||||||
padding: var(--space-2);
|
padding: var(--space-2);
|
||||||
|
padding-right: 38px;
|
||||||
grid-template-columns: auto auto minmax(0, 1fr) auto;
|
grid-template-columns: auto auto minmax(0, 1fr) auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.workspace-files__entry {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-files__open-entry {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
right: var(--space-1);
|
||||||
|
display: grid;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
background: var(--surface-raised);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
cursor: pointer;
|
||||||
|
opacity: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
transition:
|
||||||
|
opacity var(--motion-fast) ease-out,
|
||||||
|
background var(--motion-fast) ease-out,
|
||||||
|
color var(--motion-fast) ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-files__entry:hover .workspace-files__open-entry,
|
||||||
|
.workspace-files__entry:focus-within .workspace-files__open-entry {
|
||||||
|
opacity: 1;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.workspace-files__open-entry:hover {
|
||||||
|
background: var(--accent-selected);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
.workspace-files__changed-row:hover:not(:disabled),
|
.workspace-files__changed-row:hover:not(:disabled),
|
||||||
.workspace-files__row:hover {
|
.workspace-files__row:hover {
|
||||||
background: var(--accent-subtle);
|
background: var(--accent-subtle);
|
||||||
@@ -1853,6 +1943,16 @@ textarea:focus-visible {
|
|||||||
border-bottom: 1px solid var(--border-subtle);
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.message-blocks {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-blocks .message-reasoning,
|
||||||
|
.message-blocks .tool-activity {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.markdown-content > :first-child {
|
.markdown-content > :first-child {
|
||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
}
|
}
|
||||||
@@ -2152,6 +2252,102 @@ textarea:focus-visible {
|
|||||||
color: #fff;
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.agent-question-card {
|
||||||
|
display: flex;
|
||||||
|
padding: var(--space-4);
|
||||||
|
border: 1px solid var(--border-control);
|
||||||
|
border-radius: var(--radius-card);
|
||||||
|
margin-top: var(--space-3);
|
||||||
|
background: var(--surface-raised);
|
||||||
|
color: var(--text-primary);
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card > header,
|
||||||
|
.agent-question-card > footer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card > header {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card > footer {
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card fieldset {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
padding: var(--space-3);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
margin: 0;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card legend {
|
||||||
|
padding: 0 var(--space-1);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: var(--font-body);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card legend span {
|
||||||
|
display: block;
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: var(--font-caption);
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card fieldset > label {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
cursor: pointer;
|
||||||
|
gap: var(--space-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card fieldset > label > span {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card fieldset > label strong {
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: var(--font-body);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card fieldset > label small {
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: var(--font-caption);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card__custom {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card__custom input {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 34px;
|
||||||
|
padding: 0 var(--space-3);
|
||||||
|
border: 1px solid var(--border-control);
|
||||||
|
border-radius: var(--radius-control);
|
||||||
|
background: var(--surface-raised);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-question-card__error {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--danger);
|
||||||
|
font-size: var(--font-caption);
|
||||||
|
}
|
||||||
|
|
||||||
.composer-wrap {
|
.composer-wrap {
|
||||||
padding:
|
padding:
|
||||||
8px
|
8px
|
||||||
|
|||||||
@@ -61,6 +61,59 @@ export type ConversationAttachment = z.infer<
|
|||||||
typeof conversationAttachmentSchema
|
typeof conversationAttachmentSchema
|
||||||
>
|
>
|
||||||
|
|
||||||
|
export const conversationToolActivitySchema = z
|
||||||
|
.object({
|
||||||
|
callId: z.string().max(256).optional(),
|
||||||
|
name: z.string().max(200),
|
||||||
|
state: z.enum([
|
||||||
|
'pending',
|
||||||
|
'running',
|
||||||
|
'completed',
|
||||||
|
'failed',
|
||||||
|
'recoverable',
|
||||||
|
'cancelled',
|
||||||
|
'interrupted'
|
||||||
|
]),
|
||||||
|
summary: z.string().max(2_000),
|
||||||
|
error: z.string().max(2_000).optional()
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const conversationMessageBlockSchema = z.discriminatedUnion('type', [
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
id: assistantIdSchema,
|
||||||
|
type: z.literal('text'),
|
||||||
|
content: z.string().min(1).max(1_000_000)
|
||||||
|
})
|
||||||
|
.strict(),
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
id: assistantIdSchema,
|
||||||
|
type: z.literal('reasoning'),
|
||||||
|
content: z.string().min(1).max(1_000_000)
|
||||||
|
})
|
||||||
|
.strict(),
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
id: assistantIdSchema,
|
||||||
|
type: z.literal('tool'),
|
||||||
|
tool: conversationToolActivitySchema
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
])
|
||||||
|
|
||||||
|
export const conversationMessageBlocksSchema = z
|
||||||
|
.array(conversationMessageBlockSchema)
|
||||||
|
.max(500)
|
||||||
|
|
||||||
|
export type ConversationToolActivity = z.infer<
|
||||||
|
typeof conversationToolActivitySchema
|
||||||
|
>
|
||||||
|
export type ConversationMessageBlock = z.infer<
|
||||||
|
typeof conversationMessageBlockSchema
|
||||||
|
>
|
||||||
|
|
||||||
export const conversationSnapshotSchema = z
|
export const conversationSnapshotSchema = z
|
||||||
.object({
|
.object({
|
||||||
id: assistantIdSchema,
|
id: assistantIdSchema,
|
||||||
@@ -76,31 +129,11 @@ export const conversationSnapshotSchema = z
|
|||||||
role: z.enum(['user', 'assistant']),
|
role: z.enum(['user', 'assistant']),
|
||||||
content: z.string().max(1_000_000),
|
content: z.string().max(1_000_000),
|
||||||
reasoning: z.string().optional(),
|
reasoning: z.string().optional(),
|
||||||
|
blocks: conversationMessageBlocksSchema.optional(),
|
||||||
createdAt: z.number().int().nonnegative(),
|
createdAt: z.number().int().nonnegative(),
|
||||||
state: z.enum(['streaming', 'complete', 'error']),
|
state: z.enum(['streaming', 'complete', 'error']),
|
||||||
status: z.string().max(4_000).optional(),
|
status: z.string().max(4_000).optional(),
|
||||||
tools: z
|
tools: z.array(conversationToolActivitySchema).max(100).optional(),
|
||||||
.array(
|
|
||||||
z
|
|
||||||
.object({
|
|
||||||
callId: z.string().max(256).optional(),
|
|
||||||
name: z.string().max(200),
|
|
||||||
state: z.enum([
|
|
||||||
'pending',
|
|
||||||
'running',
|
|
||||||
'completed',
|
|
||||||
'failed',
|
|
||||||
'recoverable',
|
|
||||||
'cancelled',
|
|
||||||
'interrupted'
|
|
||||||
]),
|
|
||||||
summary: z.string().max(2_000),
|
|
||||||
error: z.string().max(2_000).optional()
|
|
||||||
})
|
|
||||||
.strict()
|
|
||||||
)
|
|
||||||
.max(100)
|
|
||||||
.optional(),
|
|
||||||
sources: z.array(z.string().max(8_192)).max(100).optional(),
|
sources: z.array(z.string().max(8_192)).max(100).optional(),
|
||||||
sourceReferences: z
|
sourceReferences: z
|
||||||
.array(
|
.array(
|
||||||
|
|||||||
@@ -51,6 +51,9 @@ export const skillIdSchema = z
|
|||||||
.max(128)
|
.max(128)
|
||||||
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
|
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
|
||||||
|
|
||||||
|
export const skillImportKindSchema = z.enum(['directory', 'zip'])
|
||||||
|
export type SkillImportKind = z.infer<typeof skillImportKindSchema>
|
||||||
|
|
||||||
export const skillToggleInputSchema = z
|
export const skillToggleInputSchema = z
|
||||||
.object({
|
.object({
|
||||||
skillId: skillIdSchema,
|
skillId: skillIdSchema,
|
||||||
|
|||||||
+51
-2
@@ -7,7 +7,8 @@ import type {
|
|||||||
CapabilitySnapshot,
|
CapabilitySnapshot,
|
||||||
ComputerCapabilityId,
|
ComputerCapabilityId,
|
||||||
McpServerInput,
|
McpServerInput,
|
||||||
McpServerTestResult
|
McpServerTestResult,
|
||||||
|
SkillImportKind
|
||||||
} from './capability-contracts'
|
} from './capability-contracts'
|
||||||
import {
|
import {
|
||||||
assistantIdSchema,
|
assistantIdSchema,
|
||||||
@@ -93,6 +94,29 @@ export const workspaceFileRequestSchema = z
|
|||||||
})
|
})
|
||||||
.strict()
|
.strict()
|
||||||
|
|
||||||
|
export const workspaceOpenPathRequestSchema = z
|
||||||
|
.object({
|
||||||
|
projectId: assistantIdSchema,
|
||||||
|
path: workspaceRelativePathSchema,
|
||||||
|
type: z.enum(['file', 'directory'])
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const agentQuestionAnswerSchema = z
|
||||||
|
.array(z.string().trim().min(1).max(2_000))
|
||||||
|
.max(20)
|
||||||
|
|
||||||
|
export const agentQuestionResponseSchema = z
|
||||||
|
.object({
|
||||||
|
questionId: z.string().trim().min(1).max(128),
|
||||||
|
answers: z.array(agentQuestionAnswerSchema).max(4)
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export type AgentQuestionAnswer = z.infer<
|
||||||
|
typeof agentQuestionAnswerSchema
|
||||||
|
>
|
||||||
|
|
||||||
export const conversationIdSchema = z.string().min(1).max(128)
|
export const conversationIdSchema = z.string().min(1).max(128)
|
||||||
|
|
||||||
export const agentRequestSchema = z
|
export const agentRequestSchema = z
|
||||||
@@ -648,6 +672,21 @@ export type AgentEvent =
|
|||||||
argumentSummary?: string
|
argumentSummary?: string
|
||||||
allowPermanent?: boolean
|
allowPermanent?: boolean
|
||||||
}
|
}
|
||||||
|
| {
|
||||||
|
requestId: string
|
||||||
|
type: 'question'
|
||||||
|
questionId: string
|
||||||
|
questions: Array<{
|
||||||
|
header: string
|
||||||
|
question: string
|
||||||
|
options: Array<{
|
||||||
|
label: string
|
||||||
|
description: string
|
||||||
|
}>
|
||||||
|
multiple: boolean
|
||||||
|
custom: boolean
|
||||||
|
}>
|
||||||
|
}
|
||||||
| {
|
| {
|
||||||
requestId: string
|
requestId: string
|
||||||
type: 'artifact'
|
type: 'artifact'
|
||||||
@@ -873,6 +912,10 @@ export type DesktopApi = {
|
|||||||
approvalId: string,
|
approvalId: string,
|
||||||
decision: ApprovalDecision
|
decision: ApprovalDecision
|
||||||
) => Promise<void>
|
) => Promise<void>
|
||||||
|
respondQuestion: (
|
||||||
|
questionId: string,
|
||||||
|
answers?: AgentQuestionAnswer[]
|
||||||
|
) => Promise<void>
|
||||||
onEvent: (listener: (event: AgentEvent) => void) => () => void
|
onEvent: (listener: (event: AgentEvent) => void) => () => void
|
||||||
}
|
}
|
||||||
browser: {
|
browser: {
|
||||||
@@ -949,6 +992,7 @@ export type DesktopApi = {
|
|||||||
input: ProjectCreateInput
|
input: ProjectCreateInput
|
||||||
) => Promise<AssistantProject>
|
) => Promise<AssistantProject>
|
||||||
setArchived: (projectId: string, archived: boolean) => Promise<void>
|
setArchived: (projectId: string, archived: boolean) => Promise<void>
|
||||||
|
delete: (projectId: string, confirmation: string) => Promise<void>
|
||||||
}
|
}
|
||||||
conversations: {
|
conversations: {
|
||||||
list: () => Promise<ConversationSnapshot[]>
|
list: () => Promise<ConversationSnapshot[]>
|
||||||
@@ -964,6 +1008,11 @@ export type DesktopApi = {
|
|||||||
projectId: string,
|
projectId: string,
|
||||||
path: string
|
path: string
|
||||||
) => Promise<WorkspaceFilePreview>
|
) => Promise<WorkspaceFilePreview>
|
||||||
|
openPath: (
|
||||||
|
projectId: string,
|
||||||
|
path: string,
|
||||||
|
type: 'file' | 'directory'
|
||||||
|
) => Promise<void>
|
||||||
}
|
}
|
||||||
tasks: {
|
tasks: {
|
||||||
list: () => Promise<AssistantTask[]>
|
list: () => Promise<AssistantTask[]>
|
||||||
@@ -1026,7 +1075,7 @@ export type DesktopApi = {
|
|||||||
}
|
}
|
||||||
capabilities: {
|
capabilities: {
|
||||||
getSnapshot: () => Promise<CapabilitySnapshot>
|
getSnapshot: () => Promise<CapabilitySnapshot>
|
||||||
importSkill: () => Promise<CapabilitySnapshot>
|
importSkill: (kind: SkillImportKind) => Promise<CapabilitySnapshot>
|
||||||
removeSkill: (skillId: string) => Promise<CapabilitySnapshot>
|
removeSkill: (skillId: string) => Promise<CapabilitySnapshot>
|
||||||
setSkillEnabled: (
|
setSkillEnabled: (
|
||||||
skillId: string,
|
skillId: string,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export const ipcChannels = {
|
|||||||
agentRun: 'agent:run',
|
agentRun: 'agent:run',
|
||||||
agentCancel: 'agent:cancel',
|
agentCancel: 'agent:cancel',
|
||||||
agentApprovalRespond: 'agent:approval:respond',
|
agentApprovalRespond: 'agent:approval:respond',
|
||||||
|
agentQuestionRespond: 'agent:question:respond',
|
||||||
agentEvent: 'agent:event',
|
agentEvent: 'agent:event',
|
||||||
browserStop: 'browser:stop',
|
browserStop: 'browser:stop',
|
||||||
browserState: 'browser:state',
|
browserState: 'browser:state',
|
||||||
@@ -52,11 +53,13 @@ export const ipcChannels = {
|
|||||||
projectsCreate: 'projects:create',
|
projectsCreate: 'projects:create',
|
||||||
projectsUpdate: 'projects:update',
|
projectsUpdate: 'projects:update',
|
||||||
projectsSetArchived: 'projects:set-archived',
|
projectsSetArchived: 'projects:set-archived',
|
||||||
|
projectsDelete: 'projects:delete',
|
||||||
conversationsList: 'conversations:list',
|
conversationsList: 'conversations:list',
|
||||||
conversationsReplace: 'conversations:replace',
|
conversationsReplace: 'conversations:replace',
|
||||||
workspaceChangesGet: 'workspace:changes:get',
|
workspaceChangesGet: 'workspace:changes:get',
|
||||||
workspaceDirectoryList: 'workspace:directory:list',
|
workspaceDirectoryList: 'workspace:directory:list',
|
||||||
workspaceFileRead: 'workspace:file:read',
|
workspaceFileRead: 'workspace:file:read',
|
||||||
|
workspacePathOpen: 'workspace:path:open',
|
||||||
tasksList: 'tasks:list',
|
tasksList: 'tasks:list',
|
||||||
tasksSetStatus: 'tasks:set-status',
|
tasksSetStatus: 'tasks:set-status',
|
||||||
tokenUsageSummary: 'usage:token-summary',
|
tokenUsageSummary: 'usage:token-summary',
|
||||||
|
|||||||
Reference in New Issue
Block a user