feat: 统一日志系统——结构化滚动文件 + api.log 插件通道 + 73 个 IPC 通道追踪 + pi 事件/渲染层错误归档

This commit is contained in:
Rick Ye
2026-09-11 02:12:40 +08:00
parent 2ad1743e10
commit 8e4b5496e8
9 changed files with 332 additions and 98 deletions
+92 -72
View File
@@ -5,6 +5,26 @@ import { AgentService } from './pi/agent-service'
import { getPluginHost } from './plugins/plugin-host'
import { getBrowserController } from './browser/browser-controller'
import { detectBrowserSources, importBrowserProfile } from './browser/browser-profile'
import { getLogger } from './logger'
const log = getLogger('ipc')
/* eslint-disable @typescript-eslint/no-explicit-any */
/** ipcMain.handle 追踪包装:成功 debug(含耗时)、失败 error(含通道/耗时)——Agent 自诊断的数据源之一 */
function handle(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any): void {
ipcMain.handle(channel, async (event, ...args: any[]) => {
const started = Date.now()
try {
const result = await listener(event, ...args)
log.debug('ipc ok', { channel, ms: Date.now() - started })
return result
} catch (err) {
log.error('ipc failed', { channel, ms: Date.now() - started, err })
throw err
}
})
}
/* eslint-enable @typescript-eslint/no-explicit-any */
/**
* 注册 IPC 通道并把 agent 事件转发到所有渲染窗口。
@@ -21,7 +41,7 @@ export function registerIpc(): AgentService {
}
})
ipcMain.handle('agent:send', (_event, text: unknown, images: unknown) => {
handle('agent:send', (_event, text: unknown, images: unknown) => {
if (typeof text !== 'string' || !text.trim()) {
throw new Error('empty prompt')
}
@@ -37,49 +57,49 @@ export function registerIpc(): AgentService {
return service.send(text, sendImages)
})
ipcMain.handle('agent:steer', (_event, text: unknown) => {
handle('agent:steer', (_event, text: unknown) => {
if (typeof text !== 'string' || !text.trim()) {
throw new Error('empty steer text')
}
return service.steer(text)
})
ipcMain.handle('agent:stop', () => service.stop())
handle('agent:stop', () => service.stop())
ipcMain.handle('agent:state', () =>
handle('agent:state', () =>
service.getState().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
// ---- 会话管理 ----
ipcMain.handle('sessions:list', () =>
handle('sessions:list', () =>
service.listSessions().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
ipcMain.handle('sessions:new', () =>
handle('sessions:new', () =>
service.newSession().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
ipcMain.handle('sessions:open', (_event, path: unknown) => {
handle('sessions:open', (_event, path: unknown) => {
if (typeof path !== 'string' || !path.trim()) throw new Error('invalid session path')
return service.openSession(path).catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
})
ipcMain.handle('sessions:rename', (_event, name: unknown) => {
handle('sessions:rename', (_event, name: unknown) => {
if (typeof name !== 'string' || !name.trim()) throw new Error('invalid session name')
return service.renameSession(name.trim()).catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
})
ipcMain.handle('sessions:delete', (_event, path: unknown) => {
handle('sessions:delete', (_event, path: unknown) => {
if (typeof path !== 'string' || !path.trim()) throw new Error('invalid session path')
return service.deleteSession(path).catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
@@ -92,12 +112,12 @@ export function registerIpc(): AgentService {
throw new Error(err instanceof Error ? err.message : String(err))
})
ipcMain.handle('models:catalog', () => pass(() => service.getModelCatalog()))
handle('models:catalog', () => pass(() => service.getModelCatalog()))
// ---- 自定义 API 提供商(models.json)----
ipcMain.handle('models:custom:list', () => service.listCustomProviders())
handle('models:custom:list', () => service.listCustomProviders())
ipcMain.handle('models:custom:save', (_event, config: unknown) => {
handle('models:custom:save', (_event, config: unknown) => {
if (typeof config !== 'object' || config === null) throw new Error('invalid custom provider')
const c = config as Record<string, unknown>
if (
@@ -120,51 +140,51 @@ export function registerIpc(): AgentService {
return pass(() => service.saveCustomProvider(normalized))
})
ipcMain.handle('models:custom:delete', (_event, id: unknown) => {
handle('models:custom:delete', (_event, id: unknown) => {
if (typeof id !== 'string' || !id.trim()) throw new Error('invalid provider id')
return pass(() => service.deleteCustomProvider(id))
})
ipcMain.handle('models:set', (_event, providerId: unknown, modelId: unknown) => {
handle('models:set', (_event, providerId: unknown, modelId: unknown) => {
if (typeof providerId !== 'string' || typeof modelId !== 'string') throw new Error('invalid model')
return pass(() => service.setModel(providerId, modelId))
})
ipcMain.handle('auth:setKey', (_event, providerId: unknown, apiKey: unknown) => {
handle('auth:setKey', (_event, providerId: unknown, apiKey: unknown) => {
if (typeof providerId !== 'string' || typeof apiKey !== 'string' || !apiKey.trim()) {
throw new Error('invalid api key')
}
return pass(() => service.setApiKey(providerId, apiKey.trim()))
})
ipcMain.handle('auth:logout', (_event, providerId: unknown) => {
handle('auth:logout', (_event, providerId: unknown) => {
if (typeof providerId !== 'string') throw new Error('invalid provider')
return pass(() => service.logoutProvider(providerId))
})
// ---- 思考等级 / 压缩 / 分支摘要(pi 原生能力) ----
ipcMain.handle('thinking:set', (_event, level: unknown) => {
handle('thinking:set', (_event, level: unknown) => {
if (typeof level !== 'string') throw new Error('invalid thinking level')
return pass(() => service.setThinkingLevel(level as never))
})
ipcMain.handle('session:compact', (_event, instructions: unknown) => {
handle('session:compact', (_event, instructions: unknown) => {
if (instructions !== undefined && instructions !== null && typeof instructions !== 'string') {
throw new Error('invalid compaction instructions')
}
return pass(() => service.compactSession(instructions || undefined))
})
ipcMain.handle('session:compact:abort', () => pass(() => service.abortCompaction()))
handle('session:compact:abort', () => pass(() => service.abortCompaction()))
ipcMain.handle('session:autoCompact', (_event, enabled: unknown) => {
handle('session:autoCompact', (_event, enabled: unknown) => {
if (typeof enabled !== 'boolean') throw new Error('invalid flag')
return pass(() => service.setAutoCompactionEnabled(enabled))
})
ipcMain.handle('session:forkPoints', () => pass(() => service.listForkPoints()))
handle('session:forkPoints', () => pass(() => service.listForkPoints()))
ipcMain.handle('session:navigate', (_event, entryId: unknown, options: unknown) => {
handle('session:navigate', (_event, entryId: unknown, options: unknown) => {
if (typeof entryId !== 'string' || !entryId.trim()) throw new Error('invalid entry id')
const o = (options ?? {}) as { summarize?: unknown; customInstructions?: unknown }
if (o.summarize !== undefined && typeof o.summarize !== 'boolean') throw new Error('invalid navigate options')
@@ -180,33 +200,33 @@ export function registerIpc(): AgentService {
})
// 会话末尾分叉为新会话(pi fork,原会话保留)
ipcMain.handle('session:fork', () => pass(() => service.forkSession()))
handle('session:fork', () => pass(() => service.forkSession()))
// 从会话树上的锚点分叉为新会话('at' 含该条为止 / 'before' 到其父条目为止)
ipcMain.handle('session:forkAt', (_event, entryId: unknown, position: unknown) => {
handle('session:forkAt', (_event, entryId: unknown, position: unknown) => {
if (typeof entryId !== 'string' || !entryId.trim()) throw new Error('invalid entry id')
if (position !== 'at' && position !== 'before') throw new Error('invalid fork position')
return pass(() => service.forkSessionAt(entryId, position))
})
// ---- 应用设置 ----
ipcMain.handle('settings:get', () => service.getSettings())
handle('settings:get', () => service.getSettings())
// 当前生效的系统提示词(pi 原生 + 技能注入,只读展示)
ipcMain.handle('settings:getSystemPrompt', () => service.getSystemPrompt())
handle('settings:getSystemPrompt', () => service.getSystemPrompt())
ipcMain.handle('settings:setTheme', (_event, id: unknown) => {
handle('settings:setTheme', (_event, id: unknown) => {
if (typeof id !== 'string' || !id.trim()) throw new Error('invalid theme id')
service.setThemeColor(id.trim())
})
ipcMain.handle('settings:setThemeMode', (_event, mode: unknown) => {
handle('settings:setThemeMode', (_event, mode: unknown) => {
if (mode !== 'light' && mode !== 'dark' && mode !== 'system') throw new Error('invalid theme mode')
service.setThemeMode(mode)
})
// 启用/禁用单个技能或命令(重建运行时使发现阶段过滤生效)
ipcMain.handle('settings:setResourceEnabled', (_event, kind: unknown, name: unknown, enabled: unknown) => {
handle('settings:setResourceEnabled', (_event, kind: unknown, name: unknown, enabled: unknown) => {
if (kind !== 'skill' && kind !== 'command') throw new Error('invalid resource kind')
if (typeof name !== 'string' || !name.trim() || name.length > 200) throw new Error('invalid resource name')
if (typeof enabled !== 'boolean') throw new Error('invalid enabled flag')
@@ -214,20 +234,20 @@ export function registerIpc(): AgentService {
})
// ---- 工作区 ----
ipcMain.handle('workspaces:list', () =>
handle('workspaces:list', () =>
service.listWorkspaces().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
ipcMain.handle('workspaces:create', (_event, name: unknown) => {
handle('workspaces:create', (_event, name: unknown) => {
if (typeof name !== 'string' || !name.trim()) throw new Error('invalid workspace name')
return service.createWorkspace(name).catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
})
ipcMain.handle('workspaces:open', (_event, path: unknown) => {
handle('workspaces:open', (_event, path: unknown) => {
if (typeof path !== 'string' || !path.trim()) throw new Error('invalid workspace path')
return service.openWorkspace(path).catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
@@ -235,7 +255,7 @@ export function registerIpc(): AgentService {
})
// 调起系统目录选择器;取消返回 null
ipcMain.handle('workspaces:browse', async () => {
handle('workspaces:browse', async () => {
const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0]
const result = await dialog.showOpenDialog(win, {
title: '选择工作区目录',
@@ -247,14 +267,14 @@ export function registerIpc(): AgentService {
})
// ---- 工具审批 ----
ipcMain.handle('approval:resolve', (_event, id: unknown, approved: unknown) => {
handle('approval:resolve', (_event, id: unknown, approved: unknown) => {
if (typeof id !== 'string' || typeof approved !== 'boolean') throw new Error('invalid approval')
// settle 内部经 onSettle 订阅发出 approval_settled,此处无需重复广播
service.approvals.settle(id, approved)
return Promise.resolve()
})
ipcMain.handle('app:versions', () => ({
handle('app:versions', () => ({
app: process.env.npm_package_version ?? '0.0.0',
electron: process.versions.electron,
node: process.versions.node,
@@ -263,38 +283,38 @@ export function registerIpc(): AgentService {
}))
// ---- Chatbox 资源(/ 命令 + 技能、@ 工作区文件、+ 附件)----
ipcMain.handle('chat:resources', () =>
handle('chat:resources', () =>
service.listChatResources().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
ipcMain.handle('queue:set', (_event, steering: unknown, followUp: unknown) => {
handle('queue:set', (_event, steering: unknown, followUp: unknown) => {
const norm = (value: unknown): string[] =>
Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
return service.setQueue(norm(steering), norm(followUp))
})
ipcMain.handle('permissions:set', (_event, mode: unknown) => {
handle('permissions:set', (_event, mode: unknown) => {
if (mode !== 'confirm' && mode !== 'full') throw new Error('invalid permission mode')
service.setPermissionMode(mode)
})
// ---- 设置页:技能 / 命令详情 ----
ipcMain.handle('resources:details', () =>
handle('resources:details', () =>
service.listResourceDetails().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
// 在系统文件管理器中打开(技能/命令来源文件所在目录)
ipcMain.handle('shell:openPath', (_event, target: unknown) => {
handle('shell:openPath', (_event, target: unknown) => {
if (typeof target !== 'string' || !target.trim()) throw new Error('invalid path')
return shell.openPath(target)
})
// 打开资源目录:不存在时先创建(skills/prompts 目录通常尚未建立)
ipcMain.handle('shell:openDirectory', (_event, target: unknown) => {
handle('shell:openDirectory', (_event, target: unknown) => {
if (typeof target !== 'string' || !target.trim()) throw new Error('invalid path')
try {
mkdirSync(target, { recursive: true })
@@ -307,13 +327,13 @@ export function registerIpc(): AgentService {
})
})
ipcMain.handle('files:list', () =>
handle('files:list', () =>
service.listWorkspaceFiles().catch((err: unknown) => {
throw new Error(err instanceof Error ? err.message : String(err))
})
)
ipcMain.handle('attachments:pick', async (event) => {
handle('attachments:pick', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender) ?? BrowserWindow.getAllWindows()[0]
return service.pickAttachments(win ?? undefined)
})
@@ -337,30 +357,30 @@ export function registerIpc(): AgentService {
}
}
ipcMain.handle('browser:getState', () => browserPass(() => getBrowserController().getState()))
ipcMain.handle('browser:navigate', (_e, input: unknown) =>
handle('browser:getState', () => browserPass(() => getBrowserController().getState()))
handle('browser:navigate', (_e, input: unknown) =>
browserPass(() => getBrowserController().navigateDisplay(typeof input === 'string' ? input : ''))
)
ipcMain.handle('browser:goBack', () => browserPass(() => getBrowserController().goBack()))
ipcMain.handle('browser:goForward', () => browserPass(() => getBrowserController().goForward()))
ipcMain.handle('browser:reload', () => browserPass(() => getBrowserController().reload()))
ipcMain.handle('browser:newTab', (_e, url: unknown) =>
handle('browser:goBack', () => browserPass(() => getBrowserController().goBack()))
handle('browser:goForward', () => browserPass(() => getBrowserController().goForward()))
handle('browser:reload', () => browserPass(() => getBrowserController().reload()))
handle('browser:newTab', (_e, url: unknown) =>
browserPass(() => getBrowserController().newTab(typeof url === 'string' && url ? url : undefined, false))
)
ipcMain.handle('browser:selectTab', (_e, tabId: unknown) =>
handle('browser:selectTab', (_e, tabId: unknown) =>
browserPass(() => getBrowserController().selectTab(typeof tabId === 'string' ? tabId : ''))
)
ipcMain.handle('browser:closeTab', (_e, tabId: unknown) =>
handle('browser:closeTab', (_e, tabId: unknown) =>
browserPass(() => getBrowserController().closeTab(typeof tabId === 'string' ? tabId : undefined))
)
ipcMain.handle('browser:close', () => browserPass(() => getBrowserController().close()))
handle('browser:close', () => browserPass(() => getBrowserController().close()))
// 渲染层冻结帧:菜单弹出需暂时隐藏原生视图前,截当前页面画面做占位
ipcMain.handle('browser:captureTab', (_e, tabId: unknown) =>
handle('browser:captureTab', (_e, tabId: unknown) =>
browserPass(() => getBrowserController().captureTabDataUrl(typeof tabId === 'string' && tabId ? tabId : undefined))
)
ipcMain.handle('browser:acknowledgeRisk', () => browserPass(() => getBrowserController().acknowledgeRisk()))
handle('browser:acknowledgeRisk', () => browserPass(() => getBrowserController().acknowledgeRisk()))
// 渲染层 BrowserSlot 量出的占位矩形(原生 WebContentsView 对齐到 DOM 布局)
ipcMain.handle('browser:layout', (_e, layout: unknown) => {
handle('browser:layout', (_e, layout: unknown) => {
const l = layout as { tabId?: unknown; visible?: unknown; revision?: unknown; bounds?: unknown }
const { tabId, visible, revision } = l
const bounds = l.bounds as { x?: unknown; y?: unknown; width?: unknown; height?: unknown } | undefined
@@ -383,8 +403,8 @@ export function registerIpc(): AgentService {
})
// ---- 本地浏览器配置导入 ----
ipcMain.handle('browser:detectSources', () => browserPass(() => detectBrowserSources()))
ipcMain.handle('browser:importProfile', (_e, sourceId: unknown, profileDir: unknown) => {
handle('browser:detectSources', () => browserPass(() => detectBrowserSources()))
handle('browser:importProfile', (_e, sourceId: unknown, profileDir: unknown) => {
if (typeof sourceId !== 'string' || typeof profileDir !== 'string') throw new Error('invalid import source')
return browserPass(() => importBrowserProfile(sourceId, profileDir))
})
@@ -395,32 +415,32 @@ export function registerIpc(): AgentService {
getPluginHost().setRuntimeRebuilder(() => service.rebuildRuntime())
})
ipcMain.handle('plugins:list', () => getPluginHost().list())
ipcMain.handle('plugins:uiState', () => getPluginHost().uiState())
handle('plugins:list', () => getPluginHost().list())
handle('plugins:uiState', () => getPluginHost().uiState())
// 外置插件来源目录(设置页「打开目录」)
ipcMain.handle('plugins:dirs', () => getPluginHost().pluginDirs())
handle('plugins:dirs', () => getPluginHost().pluginDirs())
// 外置插件渲染层模块源码(渲染层以 Blob URL import,绕开 dev http 源对 plugin:// 的 CORS 限制)
ipcMain.handle('plugins:readRenderer', (_e, id: unknown) => {
handle('plugins:readRenderer', (_e, id: unknown) => {
if (typeof id !== 'string' || !/^[a-z][a-z0-9-]*$/.test(id)) throw new Error('invalid plugin id')
return getPluginHost().readRendererSource(id)
})
// ---- 插件设置表单(声明式 schema;值持久化与动作回推在 plugin-host) ----
ipcMain.handle('plugins:settingsSchemas', () => getPluginHost().settingsSchemasList())
ipcMain.handle('plugins:settingsValues', () => getPluginHost().settingsValuesList())
ipcMain.handle('plugins:setSettingValue', (_e, id: unknown, key: unknown, value: unknown) => {
handle('plugins:settingsSchemas', () => getPluginHost().settingsSchemasList())
handle('plugins:settingsValues', () => getPluginHost().settingsValuesList())
handle('plugins:setSettingValue', (_e, id: unknown, key: unknown, value: unknown) => {
if (typeof id !== 'string' || typeof key !== 'string' || !key) throw new Error('invalid setting value')
getPluginHost().setSettingValue(id, key, value)
})
ipcMain.handle('plugins:setSettingsNav', (_e, id: unknown, on: unknown) => {
handle('plugins:setSettingsNav', (_e, id: unknown, on: unknown) => {
if (typeof id !== 'string' || typeof on !== 'boolean') throw new Error('invalid settings nav toggle')
return getPluginHost().setSettingsNav(id, on)
})
ipcMain.handle('plugins:settingsAction', (_e, id: unknown, key: unknown) => {
handle('plugins:settingsAction', (_e, id: unknown, key: unknown) => {
if (typeof id !== 'string' || typeof key !== 'string') throw new Error('invalid settings action')
getPluginHost().settingsAction(id, key)
})
// path/image 控件的系统选择框
ipcMain.handle('plugins:pickPath', async (event, mode: unknown) => {
handle('plugins:pickPath', async (event, mode: unknown) => {
if (mode !== 'file' && mode !== 'directory' && mode !== 'image') throw new Error('invalid path mode')
const win = BrowserWindow.fromWebContents(event.sender)
const filters =
@@ -435,7 +455,7 @@ export function registerIpc(): AgentService {
return result.canceled || result.filePaths.length === 0 ? null : result.filePaths[0]
})
// image 控件缩略图:渲染层(dev 是 http 源)不能直接 <img src="file://">,回传 data URL
ipcMain.handle('plugins:readImage', (_e, path: unknown) => {
handle('plugins:readImage', (_e, path: unknown) => {
if (typeof path !== 'string' || !path || !/\.(png|jpe?g|gif|webp|bmp|svg|ico|avif)$/i.test(path)) return null
try {
const buf = readFileSync(path)
@@ -446,17 +466,17 @@ export function registerIpc(): AgentService {
return null
}
})
ipcMain.handle('plugins:setEnabled', (_e, id: unknown, enabled: unknown) => {
handle('plugins:setEnabled', (_e, id: unknown, enabled: unknown) => {
if (typeof id !== 'string' || typeof enabled !== 'boolean') throw new Error('invalid plugin toggle')
return getPluginHost().setEnabled(id, enabled)
})
ipcMain.handle('plugins:reload', () => getPluginHost().reload())
ipcMain.handle('plugins:openView', (_e, view: unknown, params: unknown) => {
handle('plugins:reload', () => getPluginHost().reload())
handle('plugins:openView', (_e, view: unknown, params: unknown) => {
if (typeof view !== 'string' || !view) throw new Error('invalid view')
getPluginHost().openView(view, params)
})
// 插件页(iframe)经渲染层桥转发来的状态胶囊写请求;pluginId 键控防越权
ipcMain.handle('plugins:setStatus', (_e, pluginId: unknown, itemId: unknown, item: unknown) => {
handle('plugins:setStatus', (_e, pluginId: unknown, itemId: unknown, item: unknown) => {
if (typeof pluginId !== 'string' || typeof itemId !== 'string') throw new Error('invalid status item')
getPluginHost().setStatusItem(pluginId, itemId, (item ?? null) as never)
return Promise.resolve()