From a4f67bb276d5a1a6729b3c612dd5f80d39417589 Mon Sep 17 00:00:00 2001 From: iruzen-dono Date: Fri, 13 Nov 2026 20:00:56 +0000 Subject: [PATCH 1/2] refactor(settings): remove the Diagnostics page and the dry-run server Doctor Report a problem already collects the recent errors and exports the diagnostics bundle, and Doctor still appears on the crash screen and the startup error screen, where it is needed. The Diagnostics tab, the /doctor command and the server half of Doctor duplicated that, and the tab's warning count was mostly requests failing while the server was starting. The desktop Doctor keeps the local repair of the safe UI keys, and a request that fails because the server was never reached is no longer recorded as a diagnostic event; a request the server rejects still is. --- CHANGELOG.md | 4 + .../__tests__/diagnosticsSettings.test.tsx | 219 -------- .../src/__tests__/generalSettings.test.tsx | 4 +- desktop/src/__tests__/pages.test.tsx | 2 +- desktop/src/api/client.test.ts | 9 + desktop/src/api/client.ts | 4 +- desktop/src/api/doctor.ts | 75 --- .../src/components/chat/composerUtils.test.ts | 1 - desktop/src/components/chat/composerUtils.ts | 1 - desktop/src/components/doctor/DoctorPanel.tsx | 53 +- desktop/src/i18n/locales/en.ts | 28 - desktop/src/i18n/locales/zh.ts | 28 - desktop/src/lib/doctorRepair.test.ts | 30 +- desktop/src/lib/doctorRepair.ts | 28 - desktop/src/pages/DiagnosticsSettings.tsx | 246 --------- desktop/src/pages/Settings.tsx | 4 - desktop/src/pages/SettingsModal.test.tsx | 1 - desktop/src/stores/uiStore.ts | 1 - docs/features/ui-refresh/design-log.zh.md | 2 +- docs/features/ui-refresh/settings-ui.zh.md | 1 - src/commands.ts | 2 - src/commands/doctor/doctor.tsx | 7 - src/commands/doctor/index.ts | 12 - src/server/__tests__/doctor-service.test.ts | 180 ------- src/server/api/doctor.ts | 57 -- src/server/router.ts | 4 - src/server/services/doctorService.ts | 503 ------------------ 27 files changed, 37 insertions(+), 1469 deletions(-) delete mode 100644 desktop/src/__tests__/diagnosticsSettings.test.tsx delete mode 100644 desktop/src/api/doctor.ts delete mode 100644 desktop/src/pages/DiagnosticsSettings.tsx delete mode 100644 src/commands/doctor/doctor.tsx delete mode 100644 src/commands/doctor/index.ts delete mode 100644 src/server/__tests__/doctor-service.test.ts delete mode 100644 src/server/api/doctor.ts delete mode 100644 src/server/services/doctorService.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2af4a3f5..0848a8a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,10 @@ All notable changes to DreamCoder will be documented in this file. - A lead session that is resumed after a restart keeps using its team's task list (#216). The lead looked for tasks in a list named after its session, so `TaskList` returned nothing and new tasks went to a different list than the one the teammates read. The lead now goes back to the team it created when the session is resumed. Thanks @WhitePepperLambSoup. - **Context usage no longer treats screenshot base64 as text** (#230). The estimate-only path and the Messages breakdown score images and documents as 2000 tokens instead of counting their base64 as text, so a session with many browser screenshots no longer shows a nearly full context bar when the provider still reports a modest input size. An @-mentioned image or PDF is estimated from the message the API receives, so that payload is no longer counted as text and the attachment line in `/context` stays in line with the total. Thanks @Oscar-Williams. +### Removed + +- **The Diagnostics settings page, the `/doctor` command and the dry-run server Doctor.** Report a problem in the sidebar already collects the recent errors and exports the diagnostics bundle, and Doctor still appears where it is needed, on the crash screen and the startup error screen. The Diagnostics tab and the `/doctor` command opened a page whose warning count was mostly requests failing while the server was starting. The desktop Doctor now only clears the safe UI keys, `DoctorService` and the `/api/doctor` routes are gone, and a request that fails because the server never answered is no longer recorded as a diagnostic event; a request the server rejects still is. + ## [0.8.0] — 2026-11-01 The first stable release of the Electron desktop app. These notes cover everything since 0.7.0, including 0.8.0-beta.1 and 0.8.0-beta.2. diff --git a/desktop/src/__tests__/diagnosticsSettings.test.tsx b/desktop/src/__tests__/diagnosticsSettings.test.tsx deleted file mode 100644 index 20e6990f..00000000 --- a/desktop/src/__tests__/diagnosticsSettings.test.tsx +++ /dev/null @@ -1,219 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { fireEvent, render, screen, waitFor } from '@testing-library/react' -import '@testing-library/jest-dom' - -import { Settings } from '../pages/Settings' -import { useSettingsStore } from '../stores/settingsStore' -import { useUIStore } from '../stores/uiStore' -import { toast } from 'sonner' - -const diagnosticsApiMock = vi.hoisted(() => ({ - getStatus: vi.fn(), - getEvents: vi.fn(), - exportBundle: vi.fn(), - openLogDir: vi.fn(), - clear: vi.fn(), -})) - -const doctorRepairMock = vi.hoisted(() => ({ - runDoctorRepair: vi.fn(), -})) - -vi.mock('../api/diagnostics', () => ({ - diagnosticsApi: diagnosticsApiMock, -})) - -vi.mock('../lib/doctorRepair', () => doctorRepairMock) - -vi.mock('../stores/providerStore', () => ({ - useProviderStore: () => ({ - providers: [], - activeId: null, - hasLoadedProviders: true, - presets: [], - isLoading: false, - isPresetsLoading: false, - fetchProviders: vi.fn(), - fetchPresets: vi.fn(), - deleteProvider: vi.fn(), - activateProvider: vi.fn(), - testProvider: vi.fn(), - createProvider: vi.fn(), - updateProvider: vi.fn(), - testConfig: vi.fn(), - }), -})) - -vi.mock('../api/providers', () => ({ - providersApi: { - getSettings: vi.fn().mockResolvedValue({}), - updateSettings: vi.fn().mockResolvedValue({}), - }, -})) - -vi.mock('../stores/agentStore', () => ({ - useAgentStore: () => ({ - activeAgents: [], - allAgents: [], - isLoading: false, - error: null, - selectedAgent: null, - fetchAgents: vi.fn(), - selectAgent: vi.fn(), - }), -})) - -vi.mock('../stores/skillStore', () => ({ - useSkillStore: () => ({ - skills: [], - selectedSkill: null, - isLoading: false, - isDetailLoading: false, - error: null, - fetchSkills: vi.fn(), - fetchSkillDetail: vi.fn(), - clearSelection: vi.fn(), - }), -})) - -vi.mock('../components/chat/CodeViewer', () => ({ - CodeViewer: ({ code }: { code: string }) =>
{code}
, -})) - -describe('Settings > Diagnostics tab', () => { - beforeEach(() => { - diagnosticsApiMock.getStatus.mockResolvedValue({ - logDir: '/tmp/claude/dreamcoder/diagnostics', - diagnosticsPath: '/tmp/claude/dreamcoder/diagnostics/diagnostics.jsonl', - cliDiagnosticsPath: '/tmp/claude/dreamcoder/diagnostics/cli-diagnostics.jsonl', - runtimeErrorsPath: '/tmp/claude/dreamcoder/diagnostics/runtime-errors.log', - exportDir: '/tmp/claude/dreamcoder/diagnostics/exports', - retentionDays: 7, - maxBytes: 50 * 1024 * 1024, - totalBytes: 4096, - eventCount: 2, - recentErrorCount: 1, - lastEventAt: '2026-05-02T00:00:00.000Z', - }) - diagnosticsApiMock.getEvents.mockResolvedValue({ - events: [{ - id: 'event-1', - timestamp: '2026-05-02T00:00:00.000Z', - type: 'cli_start_failed', - severity: 'error', - summary: 'CLI exited during startup with code 1', - sessionId: 'session-1', - details: { - exitCode: 1, - capturedOutput: 'stderr:\nprovider rejected request', - }, - }], - }) - diagnosticsApiMock.exportBundle.mockResolvedValue({ - bundle: { - path: '/tmp/claude/dreamcoder/diagnostics/exports/dreamcoder-diagnostics.tar.gz', - fileName: 'dreamcoder-diagnostics.tar.gz', - bytes: 1024, - }, - }) - diagnosticsApiMock.openLogDir.mockResolvedValue({ ok: true }) - diagnosticsApiMock.clear.mockResolvedValue({ ok: true }) - doctorRepairMock.runDoctorRepair.mockResolvedValue({ - local: { - removedKeys: ['dreamcoder-open-tabs', 'dreamcoder-session-runtime'], - missingKeys: ['dreamcoder-theme', 'dreamcoder-locale', 'dreamcoder.persistence.schemaVersion'], - failedKeys: [], - }, - server: { - ok: true, - }, - serverError: null, - }) - - useSettingsStore.setState({ locale: 'en' }) - useUIStore.setState({ settingsTab: 'providers' }) - }) - - it('shows diagnostics status, actions, and recent events', async () => { - render() - - fireEvent.click(screen.getByText('Diagnostics')) - - expect(await screen.findByText('Log directory')).toBeInTheDocument() - expect(screen.getByText('/tmp/claude/dreamcoder/diagnostics')).toBeInTheDocument() - expect(screen.getByRole('button', { name: /Export Bundle/i })).toBeInTheDocument() - expect(screen.getByRole('button', { name: /Copy Error Summary/i })).toBeInTheDocument() - expect(screen.getByText('cli_start_failed')).toBeInTheDocument() - expect(screen.getByText('CLI exited during startup with code 1')).toBeInTheDocument() - expect(screen.getByText('Details')).toBeInTheDocument() - }) - - it('exports a diagnostics bundle from the settings page', async () => { - render() - - fireEvent.click(screen.getByText('Diagnostics')) - fireEvent.click(await screen.findByRole('button', { name: /Export Bundle/i })) - - await waitFor(() => { - expect(diagnosticsApiMock.exportBundle).toHaveBeenCalled() - }) - expect(await screen.findByText('/tmp/claude/dreamcoder/diagnostics/exports/dreamcoder-diagnostics.tar.gz')).toBeInTheDocument() - }) - - it('copies the recent error summary with the legacy clipboard fallback', async () => { - const originalClipboard = navigator.clipboard - const originalExecCommand = document.execCommand - Object.defineProperty(document, 'execCommand', { - configurable: true, - value: vi.fn().mockReturnValue(true), - }) - const execCommand = vi.mocked(document.execCommand) - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: { - writeText: vi.fn().mockRejectedValue(new Error('clipboard blocked')), - }, - }) - const writeText = vi.mocked(navigator.clipboard.writeText) - - try { - render() - - fireEvent.click(screen.getByText('Diagnostics')) - fireEvent.click(await screen.findByRole('button', { name: /Copy Error Summary/i })) - - await waitFor(() => { - expect(execCommand).toHaveBeenCalledWith('copy') - }) - expect(writeText).toHaveBeenCalledWith(expect.stringContaining('capturedOutput')) - expect(toast.success).toHaveBeenLastCalledWith('Error summary copied.') - } finally { - Object.defineProperty(document, 'execCommand', { - configurable: true, - value: originalExecCommand, - }) - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: originalClipboard, - }) - } - }) - - it('runs Doctor from Diagnostics without clearing unrelated desktop state', async () => { - window.localStorage.setItem('dreamcoder-open-tabs', '{"activeTabId":"__settings__"}') - window.localStorage.setItem('dreamcoder-theme', 'dark') - window.localStorage.setItem('dreamcoder-chat-history', 'keep') - - render() - - fireEvent.click(screen.getByText('Diagnostics')) - fireEvent.click(await screen.findByRole('button', { name: /Run Doctor/i })) - - await waitFor(() => { - expect(doctorRepairMock.runDoctorRepair).toHaveBeenCalled() - }) - - expect(toast.success).toHaveBeenLastCalledWith(expect.stringContaining('Doctor')) - expect(window.localStorage.getItem('dreamcoder-chat-history')).toBe('keep') - }) -}) diff --git a/desktop/src/__tests__/generalSettings.test.tsx b/desktop/src/__tests__/generalSettings.test.tsx index a00b6d77..75be7c9d 100644 --- a/desktop/src/__tests__/generalSettings.test.tsx +++ b/desktop/src/__tests__/generalSettings.test.tsx @@ -688,12 +688,10 @@ describe('Settings > General tab', () => { expect(screen.getByText('The storage change has been saved. Restart the app for the new data directory to take effect.')).toBeInTheDocument() }) - it('opens the Token usage tab from Settings navigation above Diagnostics', () => { + it('opens the Token usage tab from Settings navigation', () => { render() const usageTab = screen.getByText('Token usage') - const diagnosticsTab = screen.getByText('Diagnostics') - expect((usageTab.compareDocumentPosition(diagnosticsTab) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0).toBe(true) fireEvent.click(usageTab) diff --git a/desktop/src/__tests__/pages.test.tsx b/desktop/src/__tests__/pages.test.tsx index 8f0031c0..5853ca4a 100644 --- a/desktop/src/__tests__/pages.test.tsx +++ b/desktop/src/__tests__/pages.test.tsx @@ -632,7 +632,7 @@ describe('Content-only pages render without errors', () => { expect(screen.getByText('Slash commands')).toBeInTheDocument() expect(screen.getByText('/clear')).toBeInTheDocument() expect(screen.getByText('/cost')).toBeInTheDocument() - expect(screen.getByText('14 more commands available. Type / to search the full command list.')).toBeInTheDocument() + expect(screen.getByText('13 more commands available. Type / to search the full command list.')).toBeInTheDocument() resetPageStores() }) diff --git a/desktop/src/api/client.test.ts b/desktop/src/api/client.test.ts index 4082fb7a..6fd8d70f 100644 --- a/desktop/src/api/client.test.ts +++ b/desktop/src/api/client.test.ts @@ -102,6 +102,15 @@ describe('api diagnostics reporting', () => { expect(JSON.stringify(body)).not.toContain('h5_super_secret') }) + it('does not record a request the server never answered', async () => { + const fetchMock = vi.spyOn(globalThis, 'fetch') + fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch')) + + await expect(api.get('/api/status')).rejects.toThrow('Failed to fetch') + + expect(fetchMock).toHaveBeenCalledTimes(1) + }) + it('does not recursively report diagnostics endpoint failures', async () => { const fetchMock = vi.spyOn(globalThis, 'fetch') fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ message: 'diagnostics down' }), { diff --git a/desktop/src/api/client.ts b/desktop/src/api/client.ts index 824cee3d..227ff922 100644 --- a/desktop/src/api/client.ts +++ b/desktop/src/api/client.ts @@ -107,7 +107,9 @@ async function request(method: string, path: string, body?: unknown, options? reportApiFailure(method, path, timeoutError, sensitiveValues) throw timeoutError } - reportApiFailure(method, path, err, sensitiveValues) + if (!(err instanceof TypeError)) { + reportApiFailure(method, path, err, sensitiveValues) + } throw err } } diff --git a/desktop/src/api/doctor.ts b/desktop/src/api/doctor.ts deleted file mode 100644 index bb50982e..00000000 --- a/desktop/src/api/doctor.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { api } from './client' - -export type DoctorReportItem = { - id: string - label: string - kind: 'json' | 'jsonl' | 'directory' - scope: 'user' | 'project' - path: string - protected: boolean - exists: boolean - status: 'ok' | 'missing' | 'invalid_json' | 'invalid_jsonl' | 'unreadable' - bytes: number - entryCount?: number - lineCount?: number - invalidLineCount?: number - error?: string -} - -export type DoctorReport = { - generatedAt: string - items: DoctorReportItem[] - protectedSkips: Array<{ - id: string - path: string - reason: 'protected' - }> - summary: { - total: number - protectedCount: number - missingCount: number - invalidCount: number - } -} - -export type DoctorRepairResult = { - dryRun: true - mutated: false - operations: Array<{ - id: string - path: string - action: 'would_repair' - }> - skips: Array<{ - id: string - path: string - reason: 'protected' - }> - summary: { - operationCount: number - skipCount: number - } -} - -export type DoctorReportRepairResponse = { - ok: boolean - report: DoctorReport - repair: DoctorRepairResult -} - -export const doctorApi = { - report: () => api.get<{ report: DoctorReport }>('/api/doctor/report', { timeout: 3_000 }), - repair: () => api.post<{ result: DoctorRepairResult }>('/api/doctor/repair', {}, { timeout: 3_000 }), - reportAndRepair: async (): Promise => { - const [{ report }, { result }] = await Promise.all([ - doctorApi.report(), - doctorApi.repair(), - ]) - - return { - ok: true, - report, - repair: result, - } - }, -} diff --git a/desktop/src/components/chat/composerUtils.test.ts b/desktop/src/components/chat/composerUtils.test.ts index 9a1ad7e4..41e95956 100644 --- a/desktop/src/components/chat/composerUtils.test.ts +++ b/desktop/src/components/chat/composerUtils.test.ts @@ -116,7 +116,6 @@ describe('composerUtils', () => { it('resolves hidden settings aliases without displaying duplicate fallback rows', () => { expect(resolveSlashUiAction('plugins')).toEqual({ type: 'settings', tab: 'plugins' }) expect(resolveSlashUiAction('memory')).toEqual({ type: 'settings', tab: 'memory' }) - expect(resolveSlashUiAction('doctor')).toEqual({ type: 'settings', tab: 'diagnostics' }) expect(mergeSlashCommands([]).map((command) => command.name)).toContain('plugin') expect(mergeSlashCommands([]).map((command) => command.name)).toContain('memory') expect(mergeSlashCommands([]).map((command) => command.name)).not.toContain('plugins') diff --git a/desktop/src/components/chat/composerUtils.ts b/desktop/src/components/chat/composerUtils.ts index 2b54b7c3..153558ac 100644 --- a/desktop/src/components/chat/composerUtils.ts +++ b/desktop/src/components/chat/composerUtils.ts @@ -15,7 +15,6 @@ export const PANEL_SLASH_COMMANDS = [ export const SETTINGS_SLASH_COMMANDS = [ { name: 'plugin', description: 'Open desktop plugin controls in Settings', tab: 'plugins' as const }, { name: 'memory', description: 'Open project memory files in Settings', tab: 'memory' as const }, - { name: 'doctor', description: 'Open Doctor in Diagnostics', tab: 'diagnostics' as const }, ] as const export const SLASH_COMMAND_ALIASES = [ diff --git a/desktop/src/components/doctor/DoctorPanel.tsx b/desktop/src/components/doctor/DoctorPanel.tsx index c369ed6b..e14883ca 100644 --- a/desktop/src/components/doctor/DoctorPanel.tsx +++ b/desktop/src/components/doctor/DoctorPanel.tsx @@ -2,7 +2,7 @@ import { Stethoscope } from 'lucide-react' import { useState } from 'react' import { Button } from '../shared/ui/button' import { useTranslation } from '../../i18n' -import { runDoctorRepair, type DoctorRepairResult } from '../../lib/doctorRepair' +import { runLocalDoctorRepair, type LocalDoctorRepairResult } from '../../lib/doctorRepair' import { useUIStore } from '../../stores/uiStore' type DoctorPanelProps = { @@ -12,26 +12,15 @@ type DoctorPanelProps = { export function DoctorPanel({ compact = false }: DoctorPanelProps) { const t = useTranslation() const addToast = useUIStore((s) => s.addToast) - const [isRunning, setIsRunning] = useState(false) - const [result, setResult] = useState(null) + const [result, setResult] = useState(null) - const handleRunDoctor = async () => { - setIsRunning(true) - try { - const nextResult = await runDoctorRepair() - setResult(nextResult) - addToast({ - type: nextResult.local.failedKeys.length === 0 ? 'success' : 'warning', - message: getDoctorToastMessage(t, nextResult), - }) - } catch (error) { - addToast({ - type: 'error', - message: error instanceof Error ? error.message : t('settings.diagnostics.doctorFailed'), - }) - } finally { - setIsRunning(false) - } + const handleRunDoctor = () => { + const nextResult = runLocalDoctorRepair() + setResult(nextResult) + addToast({ + type: nextResult.failedKeys.length === 0 ? 'success' : 'warning', + message: getDoctorToastMessage(t, nextResult), + }) } const statusText = result ? getDoctorStatusMessage(t, result) : null @@ -52,7 +41,6 @@ export function DoctorPanel({ compact = false }: DoctorPanelProps) { - } - /> - - - -
- -
- - {status?.logDir ?? '-'}} - actions={ - - } - /> -
- - - - {lastExportPath && ( - - {lastExportPath} - - )} -
- - -

{t('settings.diagnostics.privacyNote')}

- {events.length === 0 ? ( -
- {isLoading ? t('common.loading') : t('settings.diagnostics.noEvents')} -
- ) : ( -
- {events.map((event) => ( - - ))} -
- )} -
- - ) -} - -function EventRow({ - event, - detailsLabel, -}: { - event: DiagnosticEvent - detailsLabel: string -}) { - const severityClass = - event.severity === 'error' - ? 'text-destructive' - : event.severity === 'warn' - ? 'text-warning' - : 'text-subtle-foreground' - const detailsText = formatDetails(event.details) - - return ( -
-
- {new Date(event.timestamp).toLocaleString()} -
-
{event.severity}
-
-
- {event.type} - {event.sessionId && ( - {event.sessionId} - )} -
-
{event.summary}
- {detailsText && ( -
- - {detailsLabel} - -
-              {detailsText}
-            
-
- )} -
-
- ) -} - -function formatDetails(details: unknown): string { - if (details === null || details === undefined) return '' - if (typeof details === 'string') return details - try { - return JSON.stringify(details, null, 2) - } catch { - return String(details) - } -} - -function formatEventForCopy(event: DiagnosticEvent): string { - const header = `[${event.timestamp}] ${event.severity.toUpperCase()} ${event.type}${event.sessionId ? ` session=${event.sessionId}` : ''}` - const details = formatDetails(event.details) - if (!details) return `${header}: ${event.summary}` - return `${header}: ${event.summary}\nDetails:\n${details}` -} diff --git a/desktop/src/pages/Settings.tsx b/desktop/src/pages/Settings.tsx index 21abdbf2..d8a396de 100644 --- a/desktop/src/pages/Settings.tsx +++ b/desktop/src/pages/Settings.tsx @@ -15,7 +15,6 @@ import { SettingsIcon, ShieldCheck, Smartphone, - Wrench, Zap, type LucideIcon, } from 'lucide-react' @@ -31,7 +30,6 @@ import { H5AccessSettings } from '../components/settings/H5AccessSettings' import { BrowserTrustSettings } from '../components/settings/BrowserTrustSettings' import { isDesktopRuntime } from '../lib/desktopRuntime' import { McpSettings } from './McpSettings' -import { DiagnosticsSettings } from './DiagnosticsSettings' import { ActivitySettings } from './ActivitySettings' import { MemorySettings } from './MemorySettings' import { useUIStore, type SettingsTab } from '../stores/uiStore' @@ -64,7 +62,6 @@ const SETTINGS_NAV_GROUPS: SettingsNavGroup[] = [ items: [ { tab: 'h5Access', Icon: Smartphone }, { tab: 'computerUse', Icon: Monitor }, - { tab: 'diagnostics', Icon: Wrench }, ], }, { @@ -157,7 +154,6 @@ export function Settings() { {activeTab === 'memory' && } {activeTab === 'plugins' && } {activeTab === 'computerUse' && } - {activeTab === 'diagnostics' && } {activeTab === 'about' && } diff --git a/desktop/src/pages/SettingsModal.test.tsx b/desktop/src/pages/SettingsModal.test.tsx index b4279045..d31949c0 100644 --- a/desktop/src/pages/SettingsModal.test.tsx +++ b/desktop/src/pages/SettingsModal.test.tsx @@ -12,7 +12,6 @@ vi.mock('../components/settings/AboutSettings', () => ({ AboutSettings: () => ({ ComputerUseSettings: () => null })) vi.mock('./McpSettings', () => ({ McpSettings: () => null })) vi.mock('./TerminalSettings', () => ({ TerminalSettings: () => null })) -vi.mock('./DiagnosticsSettings', () => ({ DiagnosticsSettings: () => null })) vi.mock('./ActivitySettings', () => ({ ActivitySettings: () => null })) vi.mock('./MemorySettings', () => ({ MemorySettings: () =>
memory page
})) vi.mock('../components/plugins/PluginList', () => ({ PluginList: () => null })) diff --git a/desktop/src/stores/uiStore.ts b/desktop/src/stores/uiStore.ts index e72bfc6e..affb45d2 100644 --- a/desktop/src/stores/uiStore.ts +++ b/desktop/src/stores/uiStore.ts @@ -56,7 +56,6 @@ export type SettingsTab = | 'memory' | 'plugins' | 'computerUse' - | 'diagnostics' | 'about' type UIStore = { diff --git a/docs/features/ui-refresh/design-log.zh.md b/docs/features/ui-refresh/design-log.zh.md index 72837657..f15f0ed1 100644 --- a/docs/features/ui-refresh/design-log.zh.md +++ b/docs/features/ui-refresh/design-log.zh.md @@ -95,7 +95,7 @@ - 工作区:变更 / 全部文件、过滤、预览、差异、引用文件、行评论、路径复制。 - 终端:显示 / 收起、输入、清理、重启、展开 / 返回会话和停靠方式的演示入口;不再使用「独立标签」文案。 - 定时任务:列表、新建、编辑、暂停 / 启用、删除、关联会话。 -- 设置:服务商、权限、通用、H5、终端、MCP、Agents、Skills、记忆、插件、Computer Use、活动、诊断、关于。 +- 设置:服务商、权限、通用、H5、终端、MCP、Agents、Skills、记忆、插件、Computer Use、活动、关于。 主要源码定位:`desktop/src/components/layout/Sidebar.tsx`、`AppShell.tsx`、`TabBar.tsx`、`ContentRouter.tsx`;聊天区的 `ChatInput.tsx`、`MessageList.tsx`、`ActiveSession.tsx`、`WorkspacePanel.tsx` 等组件。文件可能随重构迁移,不能只凭旧文件名认定入口仍有效。 diff --git a/docs/features/ui-refresh/settings-ui.zh.md b/docs/features/ui-refresh/settings-ui.zh.md index d6b7fdf5..3b89fc83 100644 --- a/docs/features/ui-refresh/settings-ui.zh.md +++ b/docs/features/ui-refresh/settings-ui.zh.md @@ -30,7 +30,6 @@ | 插件 | 已知市场、已安装列表、概况、详情、启停/更新/卸载/应用变更、打包能力及关联入口 | `components/plugins/PluginList.tsx`、`PluginDetail.tsx` | | Computer Use | 总开关;cua-driver 安装状态(版本、来源、安装进度和失败重试);macOS 辅助功能和屏幕录制权限;cua 遥测;重新检测、自定义 cua-driver 路径、诊断信息;MCP 同名或重复配置提示;旧 Python 运行环境清理。样稿里的感知模式、Python 和已授权应用列表已随 cua-driver 改造删除 | `pages/ComputerUseSettings.tsx` | | 活动 | 今天/昨天/30 天 Token 用量、全年热力图、日期详情;纠正旧稿「工具调用记录」占位内容 | `pages/ActivitySettings.tsx` | -| 诊断 | 日志大小、事件数、保留策略、目录入口、诊断包/摘要/清理、最近事件详情 | `pages/DiagnosticsSettings.tsx` | | 关于 | 版本、仓库、更新日志、当前更新不可用说明、作者及反馈 | `components/settings/AboutSettings.tsx` | ## 交互与边界 diff --git a/src/commands.ts b/src/commands.ts index e28b531e..1d77e896 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -19,7 +19,6 @@ import { context, contextNonInteractive } from './commands/context/index.js' import cost from './commands/cost/index.js' import diff from './commands/diff/index.js' import ctx_viz from './commands/ctx_viz/index.js' -import doctor from './commands/doctor/index.js' import memory from './commands/memory/index.js' import help from './commands/help/index.js' import ide from './commands/ide/index.js' @@ -264,7 +263,6 @@ const COMMANDS = memoize((): Command[] => [ contextNonInteractive, cost, diff, - doctor, effort, exit, fast, diff --git a/src/commands/doctor/doctor.tsx b/src/commands/doctor/doctor.tsx deleted file mode 100644 index 447cd40e..00000000 --- a/src/commands/doctor/doctor.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import React from 'react'; -import { Doctor } from '../../screens/Doctor.js'; -import type { LocalJSXCommandCall } from '../../types/command.js'; -export const call: LocalJSXCommandCall = (onDone, _context, _args) => { - return Promise.resolve(); -}; -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIkRvY3RvciIsIkxvY2FsSlNYQ29tbWFuZENhbGwiLCJjYWxsIiwib25Eb25lIiwiX2NvbnRleHQiLCJfYXJncyIsIlByb21pc2UiLCJyZXNvbHZlIl0sInNvdXJjZXMiOlsiZG9jdG9yLnRzeCJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnXG5pbXBvcnQgeyBEb2N0b3IgfSBmcm9tICcuLi8uLi9zY3JlZW5zL0RvY3Rvci5qcydcbmltcG9ydCB0eXBlIHsgTG9jYWxKU1hDb21tYW5kQ2FsbCB9IGZyb20gJy4uLy4uL3R5cGVzL2NvbW1hbmQuanMnXG5cbmV4cG9ydCBjb25zdCBjYWxsOiBMb2NhbEpTWENvbW1hbmRDYWxsID0gKG9uRG9uZSwgX2NvbnRleHQsIF9hcmdzKSA9PiB7XG4gIHJldHVybiBQcm9taXNlLnJlc29sdmUoPERvY3RvciBvbkRvbmU9e29uRG9uZX0gLz4pXG59XG4iXSwibWFwcGluZ3MiOiJBQUFBLE9BQU9BLEtBQUssTUFBTSxPQUFPO0FBQ3pCLFNBQVNDLE1BQU0sUUFBUSx5QkFBeUI7QUFDaEQsY0FBY0MsbUJBQW1CLFFBQVEsd0JBQXdCO0FBRWpFLE9BQU8sTUFBTUMsSUFBSSxFQUFFRCxtQkFBbUIsR0FBR0MsQ0FBQ0MsTUFBTSxFQUFFQyxRQUFRLEVBQUVDLEtBQUssS0FBSztFQUNwRSxPQUFPQyxPQUFPLENBQUNDLE9BQU8sQ0FBQyxDQUFDLE1BQU0sQ0FBQyxNQUFNLENBQUMsQ0FBQ0osTUFBTSxDQUFDLEdBQUcsQ0FBQztBQUNwRCxDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/src/commands/doctor/index.ts b/src/commands/doctor/index.ts deleted file mode 100644 index 6a0b0899..00000000 --- a/src/commands/doctor/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Command } from '../../commands.js' -import { isEnvTruthy } from '../../utils/envUtils.js' - -const doctor: Command = { - name: 'doctor', - description: 'Diagnose and verify your Claude Code installation and settings', - isEnabled: () => !isEnvTruthy(process.env.DISABLE_DOCTOR_COMMAND), - type: 'local-jsx', - load: () => import('./doctor.js'), -} - -export default doctor diff --git a/src/server/__tests__/doctor-service.test.ts b/src/server/__tests__/doctor-service.test.ts deleted file mode 100644 index 5a1f476e..00000000 --- a/src/server/__tests__/doctor-service.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test' -import * as fs from 'node:fs/promises' -import * as os from 'node:os' -import * as path from 'node:path' -import { handleDoctorApi } from '../api/doctor.js' -import { handleApiRequest } from '../router.js' -import { DoctorService } from '../services/doctorService.js' - -let tmpDir: string -let homeDir: string -let configDir: string -let projectRoot: string -let originalConfigDir: string | undefined - -beforeEach(async () => { - tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'doctor-service-test-')) - homeDir = path.join(tmpDir, 'home') - configDir = path.join(homeDir, '.claude') - projectRoot = path.join(tmpDir, 'workspace', 'demo-project') - originalConfigDir = process.env.DREAMCODER_CONFIG_DIR - process.env.DREAMCODER_CONFIG_DIR = configDir - - await fs.mkdir(path.join(configDir, 'projects', 'demo-project'), { recursive: true }) - await fs.mkdir(path.join(configDir, 'skills', 'alpha-skill'), { recursive: true }) - await fs.mkdir(path.join(configDir, 'dreamcoder'), { recursive: true }) - await fs.mkdir(path.join(projectRoot, '.claude', 'skills', 'beta-skill'), { recursive: true }) - - await fs.writeFile(path.join(configDir, 'settings.json'), '{"defaultMode":', 'utf-8') - await fs.writeFile(path.join(projectRoot, '.claude', 'settings.json'), '{"model":', 'utf-8') - await fs.writeFile( - path.join(configDir, 'projects', 'demo-project', 'session-1.jsonl'), - '{"type":"message"}\n{bad json}\n', - 'utf-8', - ) - await fs.writeFile( - path.join(configDir, 'dreamcoder', 'providers.json'), - JSON.stringify({ activeId: null, providers: [{ id: 'provider-1' }] }), - 'utf-8', - ) - await fs.writeFile( - path.join(configDir, 'skills', 'alpha-skill', 'SKILL.md'), - '# Alpha\n', - 'utf-8', - ) - await fs.writeFile( - path.join(projectRoot, '.claude', 'skills', 'beta-skill', 'SKILL.md'), - '# Beta\n', - 'utf-8', - ) -}) - -afterEach(async () => { - if (originalConfigDir === undefined) delete process.env.DREAMCODER_CONFIG_DIR - else process.env.DREAMCODER_CONFIG_DIR = originalConfigDir - await fs.rm(tmpDir, { recursive: true, force: true }) -}) - -function makeRequest( - method: string, - urlStr: string, - body?: Record, -): { req: Request; url: URL; segments: string[] } { - const url = new URL(urlStr, 'http://localhost:3456') - const init: RequestInit = { method } - if (body) { - init.headers = { 'Content-Type': 'application/json' } - init.body = JSON.stringify(body) - } - const req = new Request(url.toString(), init) - const segments = url.pathname.split('/').filter(Boolean) - return { req, url, segments } -} - -describe('DoctorService', () => { - test('report redacts filesystem paths and lists protected skipped items', async () => { - const service = new DoctorService({ configDir, homeDir, projectRoot }) - - const report = await service.getReport() - const serialized = JSON.stringify(report) - - expect(serialized).not.toContain(tmpDir) - expect(serialized).not.toContain(projectRoot) - - const userSettings = report.items.find((item) => item.path === '~/.claude/settings.json') - expect(userSettings).toBeDefined() - expect(userSettings?.protected).toBe(true) - expect(userSettings?.status).toBe('invalid_json') - - const projectSettings = report.items.find( - (item) => item.path === '/.claude/settings.json', - ) - expect(projectSettings).toBeDefined() - expect(projectSettings?.protected).toBe(true) - expect(projectSettings?.status).toBe('invalid_json') - - const sessionJsonl = report.items.find( - (item) => item.path === '~/.claude/projects/demo-project/session-1.jsonl', - ) - expect(sessionJsonl).toBeDefined() - expect(sessionJsonl?.protected).toBe(true) - expect(sessionJsonl?.status).toBe('invalid_jsonl') - expect(sessionJsonl?.lineCount).toBe(2) - expect(sessionJsonl?.invalidLineCount).toBe(1) - - expect(report.protectedSkips).toEqual( - expect.arrayContaining([ - expect.objectContaining({ path: '~/.claude/settings.json', reason: 'protected' }), - expect.objectContaining({ path: '/.claude/settings.json', reason: 'protected' }), - expect.objectContaining({ - path: '~/.claude/projects/demo-project/session-1.jsonl', - reason: 'protected', - }), - ]), - ) - }) - - test('safe repair skips protected malformed files without modifying them', async () => { - const service = new DoctorService({ configDir, homeDir, projectRoot }) - const userSettingsPath = path.join(configDir, 'settings.json') - const projectSettingsPath = path.join(projectRoot, '.claude', 'settings.json') - const beforeUser = await fs.readFile(userSettingsPath, 'utf-8') - const beforeProject = await fs.readFile(projectSettingsPath, 'utf-8') - - const result = await service.repair() - - expect(result.mutated).toBe(false) - expect(result.operations).toEqual([]) - expect(result.skips).toEqual( - expect.arrayContaining([ - expect.objectContaining({ path: '~/.claude/settings.json', reason: 'protected' }), - expect.objectContaining({ path: '/.claude/settings.json', reason: 'protected' }), - ]), - ) - - expect(await fs.readFile(userSettingsPath, 'utf-8')).toBe(beforeUser) - expect(await fs.readFile(projectSettingsPath, 'utf-8')).toBe(beforeProject) - }) -}) - -describe('doctor API', () => { - test('returns a report and dry-run repair result', async () => { - const reportReq = makeRequest( - 'GET', - `/api/doctor/report?cwd=${encodeURIComponent(projectRoot)}`, - ) - const reportRes = await handleDoctorApi(reportReq.req, reportReq.url, reportReq.segments) - expect(reportRes.status).toBe(200) - const reportBody = await reportRes.json() as { - report: { summary: { protectedCount: number } } - } - expect(reportBody.report.summary.protectedCount).toBeGreaterThan(0) - - const repairReq = makeRequest('POST', '/api/doctor/repair', { cwd: projectRoot }) - const repairRes = await handleDoctorApi(repairReq.req, repairReq.url, repairReq.segments) - expect(repairRes.status).toBe(200) - const repairBody = await repairRes.json() as { result: { mutated: boolean } } - expect(repairBody.result.mutated).toBe(false) - }) - - test('routes doctor requests through the main API router', async () => { - const url = new URL( - `/api/doctor/report?cwd=${encodeURIComponent(projectRoot)}`, - 'http://localhost:3456', - ) - const res = await handleApiRequest(new Request(url.toString(), { method: 'GET' }), url) - - expect(res.status).toBe(200) - const body = await res.json() as { - report: { items: Array<{ path: string; status: string }> } - } - expect(body.report.items).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - path: '~/.claude/settings.json', - status: 'invalid_json', - }), - ]), - ) - }) -}) diff --git a/src/server/api/doctor.ts b/src/server/api/doctor.ts deleted file mode 100644 index 6fba2dd8..00000000 --- a/src/server/api/doctor.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { ApiError, errorResponse } from '../middleware/errorHandler.js' -import { DoctorService } from '../services/doctorService.js' - -export async function handleDoctorApi( - req: Request, - url: URL, - segments: string[], -): Promise { - try { - const sub = segments[2] - - if ((req.method === 'GET' && !sub) || (req.method === 'GET' && sub === 'report')) { - const cwd = url.searchParams.get('cwd') || undefined - const service = new DoctorService({ projectRoot: cwd }) - return Response.json({ report: await service.getReport() }) - } - - if (req.method === 'POST' && sub === 'repair') { - const body = await parseJsonBody(req) - const cwd = typeof body.cwd === 'string' ? body.cwd : url.searchParams.get('cwd') || undefined - const targetIds = Array.isArray(body.targetIds) - ? body.targetIds.filter((value): value is string => typeof value === 'string' && value.length > 0) - : undefined - const service = new DoctorService({ projectRoot: cwd }) - return Response.json({ result: await service.repair(targetIds) }) - } - - if (!sub) { - throw methodNotAllowed(req.method, '/api/doctor') - } - - throw ApiError.notFound(`Unknown doctor endpoint: ${sub}`) - } catch (error) { - return errorResponse(error) - } -} - -async function parseJsonBody(req: Request): Promise> { - if ( - !req.headers.get('content-length') && - !req.headers.get('transfer-encoding') && - !req.headers.get('content-type') - ) { - return {} - } - - try { - const body = await req.json() - return body && typeof body === 'object' ? body as Record : {} - } catch { - throw ApiError.badRequest('Invalid JSON body') - } -} - -function methodNotAllowed(method: string, route: string): ApiError { - return new ApiError(405, `Method ${method} not allowed on ${route}`, 'METHOD_NOT_ALLOWED') -} diff --git a/src/server/router.ts b/src/server/router.ts index 339e83d1..1d7b1fcd 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -17,7 +17,6 @@ import { handleSkillsApi } from './api/skills.js' import { handleComputerUseApi } from './api/computer-use.js' import { handleMcpApi } from './api/mcp.js' import { handleDiagnosticsApi } from './api/diagnostics.js' -import { handleDoctorApi } from './api/doctor.js' import { handleH5AccessApi } from './api/h5-access.js' import { handleActivityStatsApi } from './api/activityStats.js' import { handleOpenTargetsApi } from './api/open-targets.js' @@ -95,9 +94,6 @@ export async function handleApiRequest(req: Request, url: URL): Promise' - } - - async getReport(): Promise { - const targets = await this.buildTargets() - const items = await Promise.all(targets.map((target) => this.inspectTarget(target))) - const protectedSkips = items - .filter((item) => item.protected) - .map((item) => ({ - id: item.id, - path: item.path, - reason: 'protected' as const, - })) - - return { - generatedAt: new Date().toISOString(), - items, - protectedSkips, - summary: { - total: items.length, - protectedCount: protectedSkips.length, - missingCount: items.filter((item) => item.status === 'missing').length, - invalidCount: items.filter((item) => - item.status === 'invalid_json' || - item.status === 'invalid_jsonl' || - item.status === 'unreadable' - ).length, - }, - } - } - - async repair(targetIds?: string[]): Promise { - const report = await this.getReport() - const selectedIds = targetIds?.length ? new Set(targetIds) : null - const selectedItems = selectedIds - ? report.items.filter((item) => selectedIds.has(item.id)) - : report.items - - const operations: DoctorRepairOperation[] = [] - const skips = selectedItems.map((item) => { - if (!item.protected && item.status !== 'ok') { - operations.push({ - id: item.id, - path: item.path, - action: 'would_repair', - }) - } - return { - id: item.id, - path: item.path, - reason: 'protected' as const, - } - }) - - return { - dryRun: true, - mutated: false, - operations, - skips, - summary: { - operationCount: operations.length, - skipCount: skips.length, - }, - } - } - - private async buildTargets(): Promise { - const targets: DoctorTarget[] = [ - this.jsonTarget('user-settings', 'User settings', 'user', path.join(this.configDir, 'settings.json')), - this.jsonTarget( - 'dreamcoder-providers', - 'Managed providers', - 'user', - path.join(this.configDir, 'dreamcoder', 'providers.json'), - ), - this.jsonTarget( - 'dreamcoder-settings', - 'Managed provider settings', - 'user', - path.join(this.configDir, 'dreamcoder', 'settings.json'), - ), - this.directoryTarget('user-skills', 'User skills', 'user', path.join(this.configDir, 'skills')), - this.directoryTarget('teams', 'Teams', 'user', path.join(this.configDir, 'teams')), - this.directoryTarget('plugins', 'Plugins', 'user', path.join(this.configDir, 'plugins')), - this.directoryTarget( - 'cowork-plugins', - 'Cowork plugins', - 'user', - path.join(this.configDir, 'cowork_plugins'), - ), - this.jsonTarget('user-mcp', 'User MCP config', 'user', this.getUserMcpConfigPath()), - this.jsonTarget('oauth', 'OAuth tokens', 'user', path.join(this.configDir, 'dreamcoder', 'oauth.json')), - this.jsonTarget( - 'openai-oauth', - 'OpenAI OAuth tokens', - 'user', - path.join(this.configDir, 'dreamcoder', 'openai-oauth.json'), - ), - ] - - if (this.projectRoot) { - targets.push( - this.jsonTarget( - 'project-settings', - 'Project settings', - 'project', - path.join(this.projectRoot, '.claude', 'settings.json'), - ), - this.directoryTarget( - 'project-skills', - 'Project skills', - 'project', - path.join(this.projectRoot, '.claude', 'skills'), - ), - this.jsonTarget( - 'project-mcp', - 'Project MCP config', - 'project', - path.join(this.projectRoot, '.mcp.json'), - ), - ) - } - - const sessionFiles = await this.listJsonlFiles(path.join(this.configDir, 'projects')) - for (const filePath of sessionFiles) { - const relativePath = toPosix(path.relative(this.configDir, filePath)) - targets.push( - this.jsonlTarget( - `session-jsonl:${relativePath}`, - 'Session transcript', - 'user', - filePath, - ), - ) - } - - return targets - } - - private async inspectTarget(target: DoctorTarget): Promise { - switch (target.kind) { - case 'json': - return this.inspectJsonTarget(target) - case 'jsonl': - return this.inspectJsonlTarget(target) - case 'directory': - return this.inspectDirectoryTarget(target) - default: - return this.inspectMissingTarget(target) - } - } - - private async inspectJsonTarget(target: DoctorTarget): Promise { - const exists = await this.pathExists(target.filePath) - if (!exists) return this.inspectMissingTarget(target) - - let raw: string - try { - raw = await fs.readFile(target.filePath, 'utf-8') - } catch (error) { - return this.inspectUnreadableTarget(target, error) - } - const bytes = Buffer.byteLength(raw, 'utf-8') - if (!raw.trim()) { - return { - ...this.baseItem(target), - exists: true, - status: 'invalid_json', - bytes, - error: 'Empty JSON file', - } - } - - try { - const parsed = JSON.parse(raw) - return { - ...this.baseItem(target), - exists: true, - status: 'ok', - bytes, - entryCount: countJsonEntries(parsed), - } - } catch (error) { - return { - ...this.baseItem(target), - exists: true, - status: 'invalid_json', - bytes, - error: this.sanitizeText(error instanceof Error ? error.message : String(error)), - } - } - } - - private async inspectJsonlTarget(target: DoctorTarget): Promise { - const exists = await this.pathExists(target.filePath) - if (!exists) return this.inspectMissingTarget(target) - - let raw: string - try { - raw = await fs.readFile(target.filePath, 'utf-8') - } catch (error) { - return this.inspectUnreadableTarget(target, error) - } - const lines = raw.split(/\r?\n/).filter((line) => line.trim().length > 0) - let invalidLineCount = 0 - - for (const line of lines) { - try { - JSON.parse(line) - } catch { - invalidLineCount += 1 - } - } - - return { - ...this.baseItem(target), - exists: true, - status: invalidLineCount > 0 ? 'invalid_jsonl' : 'ok', - bytes: Buffer.byteLength(raw, 'utf-8'), - lineCount: lines.length, - invalidLineCount, - } - } - - private async inspectDirectoryTarget(target: DoctorTarget): Promise { - const exists = await this.pathExists(target.filePath) - if (!exists) return this.inspectMissingTarget(target) - - let entries: Dirent[] - try { - entries = await fs.readdir(target.filePath, { withFileTypes: true }) - } catch (error) { - return this.inspectUnreadableTarget(target, error) - } - return { - ...this.baseItem(target), - exists: true, - status: 'ok', - bytes: 0, - entryCount: countVisibleEntries(entries), - } - } - - private inspectMissingTarget(target: DoctorTarget): DoctorReportItem { - return { - ...this.baseItem(target), - exists: false, - status: 'missing', - bytes: 0, - } - } - - private inspectUnreadableTarget(target: DoctorTarget, error: unknown): DoctorReportItem { - return { - ...this.baseItem(target), - exists: true, - status: 'unreadable', - bytes: 0, - error: this.sanitizeText(error instanceof Error ? error.message : String(error)), - } - } - - private baseItem(target: DoctorTarget): Omit { - return { - id: target.id, - label: target.label, - kind: target.kind, - scope: target.scope, - path: this.sanitizePath(target.filePath), - protected: target.protected, - } - } - - private sanitizePath(filePath: string): string { - if (this.projectRoot && isWithinRoot(filePath, this.projectRoot)) { - return this.withAlias('', filePath, this.projectRoot) - } - if (isWithinRoot(filePath, this.configDir)) { - return this.withAlias(this.configAlias, filePath, this.configDir) - } - if (isWithinRoot(filePath, this.homeDir)) { - return this.withAlias('~', filePath, this.homeDir) - } - return this.sanitizeText(filePath) - } - - private sanitizeText(value: string): string { - let sanitized = diagnosticsService.sanitizeString(value) - const replacements: Array<[string | undefined, string]> = [ - [this.projectRoot, ''], - [this.configDir, this.configAlias], - [this.homeDir, '~'], - ] - - for (const [from, to] of replacements) { - if (!from) continue - sanitized = sanitized.split(from).join(to) - } - return sanitized - } - - private getUserMcpConfigPath(): string { - return path.join(this.configDir, '.claude.json') - } - - private async listJsonlFiles(rootDir: string): Promise { - const exists = await this.pathExists(rootDir) - if (!exists) return [] - - const results: string[] = [] - const stack = [rootDir] - - while (stack.length > 0) { - const current = stack.pop() - if (!current) continue - let entries: Dirent[] - try { - entries = await fs.readdir(current, { withFileTypes: true }) - } catch { - continue - } - for (const entry of entries) { - const fullPath = path.join(current, entry.name) - if (entry.isDirectory()) { - stack.push(fullPath) - continue - } - if (entry.isFile() && fullPath.endsWith('.jsonl')) { - results.push(fullPath) - } - } - } - - results.sort((left, right) => left.localeCompare(right)) - return results - } - - private async pathExists(filePath: string): Promise { - try { - await fs.access(filePath) - return true - } catch { - return false - } - } - - private jsonTarget( - id: string, - label: string, - scope: 'user' | 'project', - filePath: string, - ): DoctorTarget { - return { id, label, kind: 'json', scope, filePath, protected: true } - } - - private jsonlTarget( - id: string, - label: string, - scope: 'user' | 'project', - filePath: string, - ): DoctorTarget { - return { id, label, kind: 'jsonl', scope, filePath, protected: true } - } - - private directoryTarget( - id: string, - label: string, - scope: 'user' | 'project', - filePath: string, - ): DoctorTarget { - return { id, label, kind: 'directory', scope, filePath, protected: true } - } - - private withAlias(alias: string, filePath: string, root: string): string { - const relativePath = path.relative(root, filePath) - if (!relativePath) return alias - return `${alias}/${toPosix(relativePath)}` - } -} - -function countJsonEntries(value: unknown): number { - if (Array.isArray(value)) return value.length - if (value && typeof value === 'object') return Object.keys(value as Record).length - if (value === null || value === undefined) return 0 - return 1 -} - -function countVisibleEntries(entries: Dirent[]): number { - return entries.filter((entry) => entry.name !== '.DS_Store').length -} - -function inferHomeDir(configDir: string): string { - const name = path.basename(configDir) - if (name === '.claude' || name === '.dreamcoder') { - return path.dirname(configDir) - } - return os.homedir() -} - -function isWithinRoot(filePath: string, root: string): boolean { - const relativePath = path.relative(root, filePath) - return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)) -} - -function toPosix(value: string): string { - return value.split(path.sep).join('/') -} From 2bace5b36d251ee2ba5782e161794dd2a0c1a340 Mon Sep 17 00:00:00 2001 From: iruzen-dono Date: Sat, 14 Nov 2026 08:54:08 +0000 Subject: [PATCH 2/2] refactor(settings): finish the Diagnostics removal the review asked for Item 3 of #248 was not done: the endpoints and client methods that only the Diagnostics page used were all still there with no callers left. - desktop/src/api/diagnostics.ts: drop getStatus, getEvents, openLogDir, clear and recordEvent, plus the types they needed. getProblemReport, exportBundle and revealExport stay. - server: drop DELETE /api/diagnostics, GET status, GET events and POST open-log-dir, with the service methods and getDirectorySize that only served them. readRecentEvents stays for the problem report and the export bundle. - the API test keeps POST events and the export, and scripts/repro-issue-247-real.ts reads the log through the service instead of the removed route. Messages that sent users to the removed /doctor slash command now name the `dreamcoder doctor` CLI subcommand, which still renders the same screen: sandbox-adapter, errorUtils, the bundled keybindings skill, reload-plugins, MCPSettings, useSettingsErrors and KeybindingProviderSetup. Also: the English error boundary text no longer says the error was recorded "in Diagnostics" (its test follows), design-log.zh.md line 339 and both UI mockups drop the Diagnostics tab, and the unused doctorShownAtSession config field is gone. --- desktop/src/api/diagnostics.ts | 39 ------------ desktop/src/components/ErrorBoundary.test.tsx | 2 +- desktop/src/i18n/locales/en.ts | 2 +- docs/features/ui-refresh/design-log.zh.md | 2 +- .../mockups/dreamcoder-complete-study.html | 17 +++--- .../mockups/dreamcoder-preview.html | 17 +++--- scripts/repro-issue-247-real.ts | 9 +-- src/commands/reload-plugins/reload-plugins.ts | 2 +- src/components/mcp/MCPSettings.tsx | 2 +- src/hooks/notifs/useSettingsErrors.tsx | 2 +- src/keybindings/KeybindingProviderSetup.tsx | 4 +- .../__tests__/diagnostics-service.test.ts | 21 +------ src/server/api/diagnostics.ts | 22 +------ src/server/services/diagnosticsService.ts | 60 ------------------- src/services/api/errorUtils.ts | 2 +- src/skills/bundled/keybindings.ts | 6 +- src/utils/config.ts | 2 - src/utils/sandbox/sandbox-adapter.ts | 2 +- 18 files changed, 34 insertions(+), 179 deletions(-) diff --git a/desktop/src/api/diagnostics.ts b/desktop/src/api/diagnostics.ts index c75b5c13..87545d76 100644 --- a/desktop/src/api/diagnostics.ts +++ b/desktop/src/api/diagnostics.ts @@ -1,39 +1,5 @@ import { api } from './client' -export type DiagnosticSeverity = 'debug' | 'info' | 'warn' | 'error' - -export type DiagnosticEvent = { - id: string - timestamp: string - type: string - severity: DiagnosticSeverity - summary: string - sessionId?: string - details?: unknown -} - -export type DiagnosticEventInput = { - type: string - severity?: DiagnosticSeverity - summary: string - sessionId?: string - details?: unknown -} - -export type DiagnosticsStatus = { - logDir: string - diagnosticsPath: string - cliDiagnosticsPath: string - runtimeErrorsPath: string - exportDir: string - retentionDays: number - maxBytes: number - totalBytes: number - eventCount: number - recentErrorCount: number - lastEventAt: string | null -} - export type DiagnosticsBundle = { path: string fileName: string @@ -51,10 +17,5 @@ export type ProblemReport = { export const diagnosticsApi = { getProblemReport: () => api.get('/api/diagnostics/report'), revealExport: (fileName: string) => api.post<{ ok: true }>('/api/diagnostics/reveal-export', { fileName }), - getStatus: () => api.get('/api/diagnostics/status'), - getEvents: (limit = 100) => api.get<{ events: DiagnosticEvent[] }>(`/api/diagnostics/events?limit=${limit}`), - recordEvent: (event: DiagnosticEventInput) => api.post<{ ok: true }>('/api/diagnostics/events', event, { timeout: 5_000 }), exportBundle: () => api.post<{ bundle: DiagnosticsBundle }>('/api/diagnostics/export', undefined, { timeout: 60_000 }), - openLogDir: () => api.post<{ ok: true }>('/api/diagnostics/open-log-dir'), - clear: () => api.delete<{ ok: true }>('/api/diagnostics'), } diff --git a/desktop/src/components/ErrorBoundary.test.tsx b/desktop/src/components/ErrorBoundary.test.tsx index 672e73bf..70e3606e 100644 --- a/desktop/src/components/ErrorBoundary.test.tsx +++ b/desktop/src/components/ErrorBoundary.test.tsx @@ -41,7 +41,7 @@ describe('ErrorBoundary', () => { ) expect(screen.getByText('Something went wrong.')).toBeInTheDocument() - expect(screen.getByText('The error was recorded in Diagnostics.')).toBeInTheDocument() + expect(screen.getByText('The error was recorded in the diagnostics log.')).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument() expect(await screen.findByTestId('doctor-panel')).toHaveTextContent('compact doctor') expect(reportReactError).toHaveBeenCalled() diff --git a/desktop/src/i18n/locales/en.ts b/desktop/src/i18n/locales/en.ts index 643da334..7e547862 100644 --- a/desktop/src/i18n/locales/en.ts +++ b/desktop/src/i18n/locales/en.ts @@ -435,7 +435,7 @@ export const en = { 'settings.diagnostics.doctorResultLocal': 'Cleared {count} safe UI key(s).', 'settings.diagnostics.doctorResultFailedKeys': '{count} key(s) could not be removed.', 'errorBoundary.title': 'Something went wrong.', - 'errorBoundary.description': 'The error was recorded in Diagnostics.', + 'errorBoundary.description': 'The error was recorded in the diagnostics log.', 'settings.providers.title': 'Providers', 'settings.providers.description': 'Manage API providers for model access.', diff --git a/docs/features/ui-refresh/design-log.zh.md b/docs/features/ui-refresh/design-log.zh.md index f15f0ed1..a9f9aac0 100644 --- a/docs/features/ui-refresh/design-log.zh.md +++ b/docs/features/ui-refresh/design-log.zh.md @@ -336,7 +336,7 @@ - 关闭方式:右上角 ×、按 Esc 或点遮罩都能关闭,关闭后焦点回到打开前的位置,下面的会话和草稿保持不变。弹窗或下拉菜单打开时,按 Esc 先关它们。 - 左侧导航:顶部是搜索框,按分类名过滤。分类按四组排列: - 设置:模型服务商、通用、权限、活动 - - 本机:终端、H5 访问、Computer Use、诊断 + - 本机:终端、H5 访问、Computer Use - 自定义:MCP、Agents、Skills、记忆、插件 - 关于:单独放在最后 - 右侧内容:单独滚动,内容最大宽度 760px。不再显示固定的「设置」标题,应用侧栏被遮罩盖住,不再与设置导航并排占宽度。 diff --git a/docs/features/ui-refresh/mockups/dreamcoder-complete-study.html b/docs/features/ui-refresh/mockups/dreamcoder-complete-study.html index 4201f497..7dd8161a 100644 --- a/docs/features/ui-refresh/mockups/dreamcoder-complete-study.html +++ b/docs/features/ui-refresh/mockups/dreamcoder-complete-study.html @@ -630,9 +630,9 @@ const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const icon=name=>``; const icons=()=>{if(globalThis.lucide) lucide.createIcons({attrs:{width:16,height:16}});}; -const settings=['模型服务商','权限','通用','H5 访问','终端','MCP','Agents','Skills','记忆','插件','Computer Use','活动','诊断','关于']; -const settingsGroups=[['设置',['模型服务商','通用','权限','活动']],['本机',['终端','H5 访问','Computer Use','诊断']],['自定义',['MCP','Agents','Skills','记忆','插件']],['',['关于']]]; -const settingsIcons={'模型服务商':'network','权限':'shield-check','通用':'settings','H5 访问':'smartphone','终端':'terminal','MCP':'plug','Agents':'bot','Skills':'scroll-text','记忆':'brain','插件':'puzzle','Computer Use':'monitor','活动':'chart-no-axes-column','诊断':'wrench','关于':'info'}; +const settings=['模型服务商','权限','通用','H5 访问','终端','MCP','Agents','Skills','记忆','插件','Computer Use','活动','关于']; +const settingsGroups=[['设置',['模型服务商','通用','权限','活动']],['本机',['终端','H5 访问','Computer Use']],['自定义',['MCP','Agents','Skills','记忆','插件']],['',['关于']]]; +const settingsIcons={'模型服务商':'network','权限':'shield-check','通用':'settings','H5 访问':'smartphone','终端':'terminal','MCP':'plug','Agents':'bot','Skills':'scroll-text','记忆':'brain','插件':'puzzle','Computer Use':'monitor','活动':'chart-no-axes-column','关于':'info'}; const permissionNames={'询问权限':'Default','自动接受编辑':'Accept edits','计划模式':'Plan','绕过权限':'Bypass permissions'}; const state={openFiles:new Set(['chatStore.ts']),appearance:'跟随系统',bodySize:16,scene:'回复完成',active:'s1',page:'chat',settingsOpen:true,permission:'询问权限',model:'Sonnet',effort:'Medium',provider:'Anthropic API',launch:null,importProgress:0,files:false,terminal:false,fileView:'changed',file:'chatStore.ts',batch:false,selected:new Set(),refs:[],drafts:{},hiddenProjects:new Set(),collapsed:new Set(),pinned:new Set(),projectOrder:['dreamcoder','GoTrans','skillset-manager'],sort:'更新时间',organization:'按项目',settingsTab:'Skills',terminalLines:['~/dreamcoder main','$ git status --short',' M desktop/src/stores/chatStore.ts',' M server/sessionService.ts'],tasks:[{name:'每日代码检查',when:'每天 09:00',on:true},{name:'整理开发进展',when:'每周五 18:00',on:false}]}; let sessions=[{id:'s1',title:'会话恢复流程',project:'dreamcoder',meta:'刚刚',full:true},{id:'s2',title:'精简模型服务配置',project:'dreamcoder',meta:'昨天',full:false},{id:'s3',title:'桌面主题与排版',project:'dreamcoder',meta:'昨天 · worktree',full:false},{id:'s4',title:'整理安装说明',project:'dreamcoder',meta:'周三',full:false},{id:'s5',title:'长文本翻译',project:'GoTrans',meta:'周二',full:false},{id:'s6',title:'技能来源管理',project:'skillset-manager',meta:'周一',full:false}]; @@ -773,14 +773,14 @@ function contextDialog(){openDialog('上下文用量',`
${esc(state.provider)} · ${esc(state.model)}28%
已使用56,000 tokens
剩余空间144,000 tokens
上下文窗口200,000 tokens
查看组成与压缩摘要

系统指令 12,000 · 工具定义 8,000 · 对话与文件 36,000

此前已完成恢复入口检查,当前在统一实时事件类型。

根据最近一次上下文快照估算

`);} function repositoryDialog(){const isNew=!sessions.find(s=>s.id===state.active)?.full;openDialog(isNew?'启动位置':'项目位置',`${isNew?'':'

当前会话在原工作目录中运行。

'}
`);$('#repo-done').onclick=()=>{if(isNew){$('#project-label').textContent=$('#repo-worktree').checked?'dreamcoder · worktree':'dreamcoder';}closeDialog();};} function commandDialog(kind='commands'){ - const fileMode=kind==='files';const commands=['/help','/status','/cost','/context','/mcp','/skills','/plugin','/memory','/doctor','/compact','/clear','/goal','/review','/commit','/pr','/init']; + const fileMode=kind==='files';const commands=['/help','/status','/cost','/context','/mcp','/skills','/plugin','/memory','/compact','/clear','/goal','/review','/commit','/pr','/init']; openDialog(fileMode?'引用项目文件':'命令',`
`); const draw=()=>{const q=$('#command-search').value.toLowerCase();const list=(fileMode?['desktop/src/stores/chatStore.ts','server/sessionService.ts','README.md','desktop/src/components/']:commands).filter(v=>v.toLowerCase().includes(q)).slice(0,7);$('#command-results').innerHTML=list.map(v=>``).join('')||'

没有匹配结果

';};$('#command-search').oninput=draw;draw();$('#command-search').focus(); } function runCommand(cmd){ closeDialog();$('#prompt').value='';resizePrompt(); if(cmd==='/context'){contextDialog();return;} - if(cmd==='/memory'||cmd==='/plugin'||cmd==='/doctor'){state.settingsTab=cmd==='/memory'?'记忆':cmd==='/plugin'?'插件':'诊断';openSettings();return;} + if(cmd==='/memory'||cmd==='/plugin'){state.settingsTab=cmd==='/memory'?'记忆':'插件';openSettings();return;} const content={ '/status':'
会话空闲
运行位置dreamcoder / main
模型'+esc(state.model)+'
', '/cost':'
输入 tokens42,180
输出 tokens5,326
本次会话费用估算$0.24
', @@ -800,7 +800,7 @@ servers:[{name:'filesystem',scope:'全局用户',type:'STDIO',enabled:true},{name:'github',scope:'项目共享',type:'Streamable HTTP',enabled:true}], plugins:[{name:'开发辅助',source:'用户',enabled:true},{name:'项目工具',source:'项目',enabled:false}], terminalTabs:[{id:1,lines:['~/dreamcoder main','$ pwd','~/dreamcoder']},{id:2,lines:['~/dreamcoder main','$ git status --short',' M desktop/src/stores/chatStore.ts']}],terminalActive:1,terminalNext:3, - memoryFile:'MEMORY.md',memoryMode:'预览',memorySaved:{'MEMORY.md':'# 项目记忆\n\n- 历史记录与实时消息使用统一数据结构。\n- 修改 UI 时同步设计记录。','architecture.md':'# 架构约定\n\n服务端解析事件,桌面端负责展示与交互。'},memoryDraft:{},logsCleared:false, + memoryFile:'MEMORY.md',memoryMode:'预览',memorySaved:{'MEMORY.md':'# 项目记忆\n\n- 历史记录与实时消息使用统一数据结构。\n- 修改 UI 时同步设计记录。','architecture.md':'# 架构约定\n\n服务端解析事件,桌面端负责展示与交互。'},memoryDraft:{}, }; const prefsAgents=[{name:'reviewer',source:'项目',desc:'检查代码变更,报告可验证的问题。',model:'Sonnet',tools:'Read · Grep · Glob',prompt:'阅读相关代码与变更,检查正确性和回归风险。只报告有证据的问题,并给出代码位置。'},{name:'Explore',source:'内置',desc:'快速查找文件,理解项目结构与相关实现。',model:'继承会话',tools:'Read · Grep · Glob',prompt:'搜索代码并整理相关实现,帮助主会话理解代码库。'},{name:'research-assistant',source:'用户',desc:'收集资料并整理来源。',model:'继承会话',tools:'Read · WebSearch · WebFetch',prompt:'围绕问题收集资料,区分事实与推测,保留来源。'},{name:'code-simplifier',source:'Claude Code',desc:'在不改变行为的前提下简化代码。',model:'继承会话',tools:'Read · Edit · Grep',prompt:'保持行为不变,减少重复和不必要的抽象。'}]; const prefsSkills=[{name:'code-review',source:'用户',desc:'检查变更中的正确性、回归风险与遗漏。',tokens:1800},{name:'frontend-design',source:'用户',desc:'设计清晰、有层级的前端界面。',tokens:2400},{name:'pdf-tools',source:'Claude Code',desc:'读取、拆分与整理 PDF 文档。',tokens:1500},{name:'project-conventions',source:'项目',desc:'项目的开发约定与验证步骤。',tokens:900}]; @@ -913,9 +913,8 @@ function prefsPluginDetail(){const p=prefs.plugins[prefs.detail.index];return prefBack()+prefHead(esc(p.name),'项目开发与检查辅助工具。')+prefLine('状态',p.enabled?'已启用':'已禁用',prefButton(p.enabled?'禁用':'启用','plugin-toggle',prefs.detail.index)+prefButton('更新','notice','演示:插件已检查更新。')+prefButton('卸载','plugin-delete',prefs.detail.index))+prefLine('安装范围',p.source,'')+prefLine('安装位置','~/.claude/plugins/…','')+prefSummary([['技能','1'],['Agents','1'],['MCP','1'],['Hooks','0']])+prefSection('打包能力',prefLine('技能','code-review',prefButton('查看','plugin-skill'))+prefLine('Agents','reviewer',prefButton('查看','plugin-agent'))+prefLine('MCP 服务','filesystem',prefButton('查看','plugin-mcp'))+prefLine('命令 / Hooks','未暴露',''))+'

启用、禁用或更新后,需要应用变更到当前运行时。

'+prefButton('应用变更','notice','演示:变更已应用。');} function prefsComputer(){return prefHead('Computer Use','允许助手截屏、点击、输入与操作应用。')+prefLine('计算机操作',prefs.values.computer?'已开启':'新会话不提供计算机操作工具。',prefToggle('启用','computer'))+prefSection('感知模式',prefChoices('vision',['截图视觉','Windows 无障碍树'])+`

${prefs.values.vision==='截图视觉'?'通过截图理解界面,需要支持图像的模型。':'读取界面元素并按元素 ID 操作,支持纯文本模型;仅 Windows 可用。'}

`)+prefSection('运行环境',prefLine('Python 3','已检测到 · /usr/bin/python3','示例')+prefLine('虚拟环境','尚未创建','')+prefLine('依赖包','未安装','')+prefInput('Python 解释器路径','pythonPath','','text','placeholder="自动检测,或选择 Python 可执行文件"')+`
${prefButton('选择','notice','正式应用会打开文件选择器。')}${prefButton('应用','save')}${prefButton('自动','python-auto')}${prefButton('安装环境','notice','演示:正式应用将在确认后安装所需环境。')}${prefButton('重新检测','notice','演示:运行环境检测完成。')}
`)+prefSection('macOS 系统权限',prefLine('辅助功能','未授权',prefButton('打开设置','notice','正式应用会打开系统「辅助功能」设置。'))+prefLine('屏幕录制','未授权',prefButton('打开设置','notice','正式应用会打开系统「屏幕录制」设置。'))+'

在系统设置中授权后,需要重新启动应用。

')+prefSection('已授权应用','

预先授权后,操作这些应用时不再逐次请求确认。

'+``+['Finder','Terminal','Safari'].map((a,i)=>`
${prefLine(a,'',prefToggle('授权','app'+i))}
`).join('')+prefLine('剪贴板访问','',prefToggle('允许','clipboard'))+prefLine('系统快捷键','',prefToggle('允许','systemKeys')));} function prefsActivity(){const cells=Array.from({length:364},(_,i)=>{const day=new Date(Date.UTC(2025,9,19+i));const date=day.toISOString().slice(0,10);const level=(i*17+3)%9<4?(i*17+3)%4:0;return ``;}).join('');return prefHead('Token 用量','2025 年 10 月 — 2026 年 10 月 · 示例数据')+prefSummary([['今天','37.2k','3 个会话'],['昨天','24.8k','2 个会话'],['30 天','812k','64 个会话']])+`
2025 · 10 月1 月4 月7 月10 月
${cells}
点击日期查看用量少 ··· 多
10 月 17 日 · 37,200 tokens · 3 个会话
`;} -function prefsDiagnostics(){return prefHead('诊断','查看服务启动、服务商与会话运行错误。',prefButton('刷新','notice','演示:诊断事件已刷新。'))+prefSummary([['日志大小',prefs.logsCleared?'0 KB':'248 KB'],['事件数',prefs.logsCleared?'0':'3'],['保留策略','7 天','最多 20 MB']])+prefLine('日志目录','~/.claude/dreamcoder/logs',prefButton('打开','notice','正式应用会在文件管理器中打开日志目录。'))+`
${prefButton('导出诊断包','notice','演示:正式应用将导出脱敏后的诊断包。')}${prefButton('复制错误摘要','diagnostic-copy')}${prefButton('清理日志','diagnostic-clear')}
`+prefSection('最近事件',prefs.logsCleared?'
暂无诊断事件。
':[['14:28','会话运行完成','info','session.completed'],['14:26','服务商连接超时','error','provider.timeout'],['14:20','本地服务启动','info','server.started']].map(r=>`
${r[0]} ${r[1]} ${r[2]}
${r[3]}\nproject: dreamcoder\n${r[2]==='error'?'message: request timed out after 120s':'status: completed'}
`).join(''))+'

导出的诊断包会脱敏,不包含聊天内容、文件内容、完整环境变量或 API Key。

';} function prefsAbout(){return prefHead('DreamCoder','版本 0.4.5 · 桌面工作区')+prefLine('项目仓库','GoDiao / dreamcoder','GitHub ↗')+prefLine('更新日志','查看发布说明','查看 ↗')+prefSection('应用更新','

首个公开版本尚未发布,更新检查暂未开放。

')+prefLine('作者','GoDiao','GitHub ↗')+prefLine('反馈与建议','报告问题,或提出功能建议。','提交反馈 ↗');} -const prefsPages={'模型服务商':prefsProviderList,'权限':prefsPermissions,'通用':prefsGeneral,'H5 访问':prefsH5,'终端':prefsTerminal,'MCP':prefsMcp,'Agents':prefsAgentsPage,'Skills':prefsSkillsPage,'记忆':prefsMemory,'插件':prefsPlugins,'Computer Use':prefsComputer,'活动':prefsActivity,'诊断':prefsDiagnostics,'关于':prefsAbout}; +const prefsPages={'模型服务商':prefsProviderList,'权限':prefsPermissions,'通用':prefsGeneral,'H5 访问':prefsH5,'终端':prefsTerminal,'MCP':prefsMcp,'Agents':prefsAgentsPage,'Skills':prefsSkillsPage,'记忆':prefsMemory,'插件':prefsPlugins,'Computer Use':prefsComputer,'活动':prefsActivity,'关于':prefsAbout}; const prefsDetails={provider:prefsProviderForm,mcp:prefsMcpForm,agent:prefsAgentDetail,skill:prefsSkillDetail,plugin:prefsPluginDetail}; function renderSettings(){ $('#settings-overlay').hidden=!state.settingsOpen;$('.ds-side').inert=state.settingsOpen;$('.ds-main').inert=state.settingsOpen;if(!state.settingsOpen){$('#settings-modal-body').innerHTML='';return;} @@ -991,8 +990,6 @@ if(['plugin-skill','plugin-agent','plugin-mcp'].includes(action)){if(!prefs.plugins[prefs.detail.index].enabled){prefFeedback('先启用插件并应用变更,再查看关联能力。');return;}const tab=action==='plugin-skill'?'Skills':action==='plugin-agent'?'Agents':'MCP';state.settingsTab=tab;prefs.detail=null;renderSettings();return;} if(action==='python-auto'){delete prefs.values.pythonPath;renderSettings();return;} if(action==='usage-day'){$('#prefs-day-detail').textContent=value;return;} - if(action==='diagnostic-copy'){copyText(prefs.logsCleared?'暂无诊断事件。':'14:26 provider.timeout — request timed out after 120s(示例)');return;} - if(action==='diagnostic-clear'){confirmAction('清理诊断日志?','此处只清空演示事件。',()=>{prefs.logsCleared=true;renderSettings();},'清理');return;} } root.addEventListener('input',e=>{ if(e.target.dataset.pref){const key=e.target.dataset.pref;prefs.values[key]=e.target.type==='checkbox'?e.target.checked:e.target.value;} diff --git a/docs/features/ui-refresh/mockups/dreamcoder-preview.html b/docs/features/ui-refresh/mockups/dreamcoder-preview.html index 53cfe015..1f475cdd 100644 --- a/docs/features/ui-refresh/mockups/dreamcoder-preview.html +++ b/docs/features/ui-refresh/mockups/dreamcoder-preview.html @@ -2418,9 +2418,9 @@ const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); const icon=name=>`<i data-lucide="${name}" aria-hidden="true"></i>`; const icons=()=>{if(globalThis.lucide) lucide.createIcons({attrs:{width:16,height:16}});}; -const settings=['模型服务商','权限','通用','H5 访问','终端','MCP','Agents','Skills','记忆','插件','Computer Use','活动','诊断','关于']; -const settingsGroups=[['设置',['模型服务商','通用','权限','活动']],['本机',['终端','H5 访问','Computer Use','诊断']],['自定义',['MCP','Agents','Skills','记忆','插件']],['',['关于']]]; -const settingsIcons={'模型服务商':'network','权限':'shield-check','通用':'settings','H5 访问':'smartphone','终端':'terminal','MCP':'plug','Agents':'bot','Skills':'scroll-text','记忆':'brain','插件':'puzzle','Computer Use':'monitor','活动':'chart-no-axes-column','诊断':'wrench','关于':'info'}; +const settings=['模型服务商','权限','通用','H5 访问','终端','MCP','Agents','Skills','记忆','插件','Computer Use','活动','关于']; +const settingsGroups=[['设置',['模型服务商','通用','权限','活动']],['本机',['终端','H5 访问','Computer Use']],['自定义',['MCP','Agents','Skills','记忆','插件']],['',['关于']]]; +const settingsIcons={'模型服务商':'network','权限':'shield-check','通用':'settings','H5 访问':'smartphone','终端':'terminal','MCP':'plug','Agents':'bot','Skills':'scroll-text','记忆':'brain','插件':'puzzle','Computer Use':'monitor','活动':'chart-no-axes-column','关于':'info'}; const permissionNames={'询问权限':'Default','自动接受编辑':'Accept edits','计划模式':'Plan','绕过权限':'Bypass permissions'}; const state={openFiles:new Set(['chatStore.ts']),appearance:'跟随系统',bodySize:16,scene:'回复完成',active:'s1',page:'chat',settingsOpen:true,permission:'询问权限',model:'Sonnet',effort:'Medium',provider:'Anthropic API',launch:null,importProgress:0,files:false,terminal:false,fileView:'changed',file:'chatStore.ts',batch:false,selected:new Set(),refs:[],drafts:{},hiddenProjects:new Set(),collapsed:new Set(),pinned:new Set(),projectOrder:['dreamcoder','GoTrans','skillset-manager'],sort:'更新时间',organization:'按项目',settingsTab:'Skills',terminalLines:['~/dreamcoder main','$ git status --short',' M desktop/src/stores/chatStore.ts',' M server/sessionService.ts'],tasks:[{name:'每日代码检查',when:'每天 09:00',on:true},{name:'整理开发进展',when:'每周五 18:00',on:false}]}; let sessions=[{id:'s1',title:'会话恢复流程',project:'dreamcoder',meta:'刚刚',full:true},{id:'s2',title:'精简模型服务配置',project:'dreamcoder',meta:'昨天',full:false},{id:'s3',title:'桌面主题与排版',project:'dreamcoder',meta:'昨天 · worktree',full:false},{id:'s4',title:'整理安装说明',project:'dreamcoder',meta:'周三',full:false},{id:'s5',title:'长文本翻译',project:'GoTrans',meta:'周二',full:false},{id:'s6',title:'技能来源管理',project:'skillset-manager',meta:'周一',full:false}]; @@ -2561,14 +2561,14 @@ function contextDialog(){openDialog('上下文用量',`<div class="row space"><span>${esc(state.provider)} · ${esc(state.model)}</span><strong>28%</strong></div><div class="usage-track"><span></span></div><div class="metric-row"><span>已使用</span><span>56,000 tokens</span></div><div class="metric-row"><span>剩余空间</span><span>144,000 tokens</span></div><div class="metric-row"><span>上下文窗口</span><span>200,000 tokens</span></div><details class="event-log"><summary>查看组成与压缩摘要</summary><p>系统指令 12,000 · 工具定义 8,000 · 对话与文件 36,000</p><p>此前已完成恢复入口检查,当前在统一实时事件类型。</p></details><p class="muted">根据最近一次上下文快照估算</p>`);} function repositoryDialog(){const isNew=!sessions.find(s=>s.id===state.active)?.full;openDialog(isNew?'启动位置':'项目位置',`<label>工作目录<input id="repo-path" value="~/Projects/GoDiao/dreamcoder" ${isNew?'':'readonly'}></label><label>分支<select id="repo-branch" ${isNew?'':'disabled'}><option>main</option><option>refactor/typed-live-events</option></select></label>${isNew?'<label><input type="checkbox" id="repo-worktree"> 使用独立 worktree</label>':'<p>当前会话在原工作目录中运行。</p>'}<div class="dialog-actions"><button class="soft-button" id="repo-done">${isNew?'使用此位置':'完成'}</button></div>`);$('#repo-done').onclick=()=>{if(isNew){$('#project-label').textContent=$('#repo-worktree').checked?'dreamcoder · worktree':'dreamcoder';}closeDialog();};} function commandDialog(kind='commands'){ - const fileMode=kind==='files';const commands=['/help','/status','/cost','/context','/mcp','/skills','/plugin','/memory','/doctor','/compact','/clear','/goal','/review','/commit','/pr','/init']; + const fileMode=kind==='files';const commands=['/help','/status','/cost','/context','/mcp','/skills','/plugin','/memory','/compact','/clear','/goal','/review','/commit','/pr','/init']; openDialog(fileMode?'引用项目文件':'命令',`<input id="command-search" aria-label="过滤${fileMode?'文件':'命令'}" placeholder="搜索${fileMode?'文件或目录':'命令'}…"><div id="command-results"></div>`); const draw=()=>{const q=$('#command-search').value.toLowerCase();const list=(fileMode?['desktop/src/stores/chatStore.ts','server/sessionService.ts','README.md','desktop/src/components/']:commands).filter(v=>v.toLowerCase().includes(q)).slice(0,7);$('#command-results').innerHTML=list.map(v=>`<button class="search-result" data-command="${esc(v)}" data-is-file="${fileMode}">${esc(v)}</button>`).join('')||'<p>没有匹配结果</p>';};$('#command-search').oninput=draw;draw();$('#command-search').focus(); } function runCommand(cmd){ closeDialog();$('#prompt').value='';resizePrompt(); if(cmd==='/context'){contextDialog();return;} - if(cmd==='/memory'||cmd==='/plugin'||cmd==='/doctor'){state.settingsTab=cmd==='/memory'?'记忆':cmd==='/plugin'?'插件':'诊断';openSettings();return;} + if(cmd==='/memory'||cmd==='/plugin'){state.settingsTab=cmd==='/memory'?'记忆':'插件';openSettings();return;} const content={ '/status':'<div class="metric-row"><span>会话</span><span>空闲</span></div><div class="metric-row"><span>运行位置</span><span>dreamcoder / main</span></div><div class="metric-row"><span>模型</span><span>'+esc(state.model)+'</span></div>', '/cost':'<div class="metric-row"><span>输入 tokens</span><span>42,180</span></div><div class="metric-row"><span>输出 tokens</span><span>5,326</span></div><div class="metric-row"><span>本次会话费用估算</span><span>$0.24</span></div>', @@ -2588,7 +2588,7 @@ servers:[{name:'filesystem',scope:'全局用户',type:'STDIO',enabled:true},{name:'github',scope:'项目共享',type:'Streamable HTTP',enabled:true}], plugins:[{name:'开发辅助',source:'用户',enabled:true},{name:'项目工具',source:'项目',enabled:false}], terminalTabs:[{id:1,lines:['~/dreamcoder main','$ pwd','~/dreamcoder']},{id:2,lines:['~/dreamcoder main','$ git status --short',' M desktop/src/stores/chatStore.ts']}],terminalActive:1,terminalNext:3, - memoryFile:'MEMORY.md',memoryMode:'预览',memorySaved:{'MEMORY.md':'# 项目记忆\n\n- 历史记录与实时消息使用统一数据结构。\n- 修改 UI 时同步设计记录。','architecture.md':'# 架构约定\n\n服务端解析事件,桌面端负责展示与交互。'},memoryDraft:{},logsCleared:false, + memoryFile:'MEMORY.md',memoryMode:'预览',memorySaved:{'MEMORY.md':'# 项目记忆\n\n- 历史记录与实时消息使用统一数据结构。\n- 修改 UI 时同步设计记录。','architecture.md':'# 架构约定\n\n服务端解析事件,桌面端负责展示与交互。'},memoryDraft:{}, }; const prefsAgents=[{name:'reviewer',source:'项目',desc:'检查代码变更,报告可验证的问题。',model:'Sonnet',tools:'Read · Grep · Glob',prompt:'阅读相关代码与变更,检查正确性和回归风险。只报告有证据的问题,并给出代码位置。'},{name:'Explore',source:'内置',desc:'快速查找文件,理解项目结构与相关实现。',model:'继承会话',tools:'Read · Grep · Glob',prompt:'搜索代码并整理相关实现,帮助主会话理解代码库。'},{name:'research-assistant',source:'用户',desc:'收集资料并整理来源。',model:'继承会话',tools:'Read · WebSearch · WebFetch',prompt:'围绕问题收集资料,区分事实与推测,保留来源。'},{name:'code-simplifier',source:'Claude Code',desc:'在不改变行为的前提下简化代码。',model:'继承会话',tools:'Read · Edit · Grep',prompt:'保持行为不变,减少重复和不必要的抽象。'}]; const prefsSkills=[{name:'code-review',source:'用户',desc:'检查变更中的正确性、回归风险与遗漏。',tokens:1800},{name:'frontend-design',source:'用户',desc:'设计清晰、有层级的前端界面。',tokens:2400},{name:'pdf-tools',source:'Claude Code',desc:'读取、拆分与整理 PDF 文档。',tokens:1500},{name:'project-conventions',source:'项目',desc:'项目的开发约定与验证步骤。',tokens:900}]; @@ -2701,9 +2701,8 @@ function prefsPluginDetail(){const p=prefs.plugins[prefs.detail.index];return prefBack()+prefHead(esc(p.name),'项目开发与检查辅助工具。')+prefLine('状态',p.enabled?'已启用':'已禁用',prefButton(p.enabled?'禁用':'启用','plugin-toggle',prefs.detail.index)+prefButton('更新','notice','演示:插件已检查更新。')+prefButton('卸载','plugin-delete',prefs.detail.index))+prefLine('安装范围',p.source,'')+prefLine('安装位置','~/.claude/plugins/…','')+prefSummary([['技能','1'],['Agents','1'],['MCP','1'],['Hooks','0']])+prefSection('打包能力',prefLine('技能','code-review',prefButton('查看','plugin-skill'))+prefLine('Agents','reviewer',prefButton('查看','plugin-agent'))+prefLine('MCP 服务','filesystem',prefButton('查看','plugin-mcp'))+prefLine('命令 / Hooks','未暴露',''))+'<p class="prefs-note">启用、禁用或更新后,需要应用变更到当前运行时。</p>'+prefButton('应用变更','notice','演示:变更已应用。');} function prefsComputer(){return prefHead('Computer Use','允许助手截屏、点击、输入与操作应用。')+prefLine('计算机操作',prefs.values.computer?'已开启':'新会话不提供计算机操作工具。',prefToggle('启用','computer'))+prefSection('感知模式',prefChoices('vision',['截图视觉','Windows 无障碍树'])+`<p class="prefs-note">${prefs.values.vision==='截图视觉'?'通过截图理解界面,需要支持图像的模型。':'读取界面元素并按元素 ID 操作,支持纯文本模型;仅 Windows 可用。'}</p>`)+prefSection('运行环境',prefLine('Python 3','已检测到 · /usr/bin/python3','<span class="prefs-badge">示例</span>')+prefLine('虚拟环境','尚未创建','')+prefLine('依赖包','未安装','')+prefInput('Python 解释器路径','pythonPath','','text','placeholder="自动检测,或选择 Python 可执行文件"')+`<div class="prefs-actions">${prefButton('选择','notice','正式应用会打开文件选择器。')}${prefButton('应用','save')}${prefButton('自动','python-auto')}${prefButton('安装环境','notice','演示:正式应用将在确认后安装所需环境。')}${prefButton('重新检测','notice','演示:运行环境检测完成。')}</div>`)+prefSection('macOS 系统权限',prefLine('辅助功能','未授权',prefButton('打开设置','notice','正式应用会打开系统「辅助功能」设置。'))+prefLine('屏幕录制','未授权',prefButton('打开设置','notice','正式应用会打开系统「屏幕录制」设置。'))+'<p class="prefs-note">在系统设置中授权后,需要重新启动应用。</p>')+prefSection('已授权应用','<p class="prefs-help">预先授权后,操作这些应用时不再逐次请求确认。</p>'+`<label class="prefs-field"><span>搜索应用</span><input data-pref-filter="apps" placeholder="搜索 App…"></label>`+['Finder','Terminal','Safari'].map((a,i)=>`<div data-pref-filter-item="apps" data-search="${a}">${prefLine(a,'',prefToggle('授权','app'+i))}</div>`).join('')+prefLine('剪贴板访问','',prefToggle('允许','clipboard'))+prefLine('系统快捷键','',prefToggle('允许','systemKeys')));} function prefsActivity(){const cells=Array.from({length:364},(_,i)=>{const day=new Date(Date.UTC(2025,9,19+i));const date=day.toISOString().slice(0,10);const level=(i*17+3)%9<4?(i*17+3)%4:0;return `<button data-pref-action="usage-day" data-value="${date} · ${level*12400} tokens · ${level} 个会话" data-level="${level}" aria-label="${date},${level*12400} tokens"></button>`;}).join('');return prefHead('Token 用量','2025 年 10 月 — 2026 年 10 月 · 示例数据')+prefSummary([['今天','37.2k','3 个会话'],['昨天','24.8k','2 个会话'],['30 天','812k','64 个会话']])+`<div class="row space prefs-help"><span>2025 · 10 月</span><span>1 月</span><span>4 月</span><span>7 月</span><span>10 月</span></div><div class="prefs-heatmap" aria-label="按天统计的 Token 用量">${cells}</div><div class="row space prefs-help"><span>点击日期查看用量</span><span>少 ··· 多</span></div><div id="prefs-day-detail" class="prefs-status" aria-live="polite">10 月 17 日 · 37,200 tokens · 3 个会话</div>`;} -function prefsDiagnostics(){return prefHead('诊断','查看服务启动、服务商与会话运行错误。',prefButton('刷新','notice','演示:诊断事件已刷新。'))+prefSummary([['日志大小',prefs.logsCleared?'0 KB':'248 KB'],['事件数',prefs.logsCleared?'0':'3'],['保留策略','7 天','最多 20 MB']])+prefLine('日志目录','~/.claude/dreamcoder/logs',prefButton('打开','notice','正式应用会在文件管理器中打开日志目录。'))+`<div class="prefs-actions" style="margin-top:18px">${prefButton('导出诊断包','notice','演示:正式应用将导出脱敏后的诊断包。')}${prefButton('复制错误摘要','diagnostic-copy')}${prefButton('清理日志','diagnostic-clear')}</div>`+prefSection('最近事件',prefs.logsCleared?'<div class="prefs-empty">暂无诊断事件。</div>':[['14:28','会话运行完成','info','session.completed'],['14:26','服务商连接超时','error','provider.timeout'],['14:20','本地服务启动','info','server.started']].map(r=>`<details class="prefs-disclosure"><summary>${r[0]} ${r[1]} <span class="prefs-badge">${r[2]}</span></summary><pre class="prefs-code">${r[3]}\nproject: dreamcoder\n${r[2]==='error'?'message: request timed out after 120s':'status: completed'}</pre></details>`).join(''))+'<p class="prefs-note">导出的诊断包会脱敏,不包含聊天内容、文件内容、完整环境变量或 API Key。</p>';} function prefsAbout(){return prefHead('DreamCoder','版本 0.4.5 · 桌面工作区')+prefLine('项目仓库','GoDiao / dreamcoder','<a href="https://github.com/GoDiao/dreamcoder" target="_blank" rel="noopener">GitHub ↗</a>')+prefLine('更新日志','查看发布说明','<a href="https://github.com/GoDiao/dreamcoder/releases" target="_blank" rel="noopener">查看 ↗</a>')+prefSection('应用更新','<p class="prefs-note">首个公开版本尚未发布,更新检查暂未开放。</p>')+prefLine('作者','GoDiao','<a href="https://github.com/GoDiao" target="_blank" rel="noopener">GitHub ↗</a>')+prefLine('反馈与建议','报告问题,或提出功能建议。','<a href="https://github.com/GoDiao/dreamcoder/issues" target="_blank" rel="noopener">提交反馈 ↗</a>');} -const prefsPages={'模型服务商':prefsProviderList,'权限':prefsPermissions,'通用':prefsGeneral,'H5 访问':prefsH5,'终端':prefsTerminal,'MCP':prefsMcp,'Agents':prefsAgentsPage,'Skills':prefsSkillsPage,'记忆':prefsMemory,'插件':prefsPlugins,'Computer Use':prefsComputer,'活动':prefsActivity,'诊断':prefsDiagnostics,'关于':prefsAbout}; +const prefsPages={'模型服务商':prefsProviderList,'权限':prefsPermissions,'通用':prefsGeneral,'H5 访问':prefsH5,'终端':prefsTerminal,'MCP':prefsMcp,'Agents':prefsAgentsPage,'Skills':prefsSkillsPage,'记忆':prefsMemory,'插件':prefsPlugins,'Computer Use':prefsComputer,'活动':prefsActivity,'关于':prefsAbout}; const prefsDetails={provider:prefsProviderForm,mcp:prefsMcpForm,agent:prefsAgentDetail,skill:prefsSkillDetail,plugin:prefsPluginDetail}; function renderSettings(){ $('#settings-overlay').hidden=!state.settingsOpen;$('.ds-side').inert=state.settingsOpen;$('.ds-main').inert=state.settingsOpen;if(!state.settingsOpen){$('#settings-modal-body').innerHTML='';return;} @@ -2779,8 +2778,6 @@ if(['plugin-skill','plugin-agent','plugin-mcp'].includes(action)){if(!prefs.plugins[prefs.detail.index].enabled){prefFeedback('先启用插件并应用变更,再查看关联能力。');return;}const tab=action==='plugin-skill'?'Skills':action==='plugin-agent'?'Agents':'MCP';state.settingsTab=tab;prefs.detail=null;renderSettings();return;} if(action==='python-auto'){delete prefs.values.pythonPath;renderSettings();return;} if(action==='usage-day'){$('#prefs-day-detail').textContent=value;return;} - if(action==='diagnostic-copy'){copyText(prefs.logsCleared?'暂无诊断事件。':'14:26 provider.timeout — request timed out after 120s(示例)');return;} - if(action==='diagnostic-clear'){confirmAction('清理诊断日志?','此处只清空演示事件。',()=>{prefs.logsCleared=true;renderSettings();},'清理');return;} } root.addEventListener('input',e=>{ if(e.target.dataset.pref){const key=e.target.dataset.pref;prefs.values[key]=e.target.type==='checkbox'?e.target.checked:e.target.value;} diff --git a/scripts/repro-issue-247-real.ts b/scripts/repro-issue-247-real.ts index 62557c47..c2d68bbe 100644 --- a/scripts/repro-issue-247-real.ts +++ b/scripts/repro-issue-247-real.ts @@ -2,6 +2,7 @@ import * as fs from 'node:fs/promises' import * as os from 'node:os' import * as path from 'node:path' import { startServer } from '../src/server/index.js' +import { diagnosticsService } from '../src/server/services/diagnosticsService.js' type ServerMsg = { type: string @@ -73,10 +74,10 @@ async function createSession(workDir: string): Promise { } async function fetchDiagnostics(sessionId: string) { - const res = await fetch(`${baseUrl}/api/diagnostics/events?limit=200`) - if (!res.ok) return [] - const body = await res.json() as { events?: Array> } - return (body.events ?? []).filter((event) => event.sessionId === sessionId) + // Read the log through the service instead of HTTP: the GET /api/diagnostics/events + // route this used to call only ever existed for the Diagnostics page. + const events = await diagnosticsService.readRecentEvents(200) + return events.filter((event) => event.sessionId === sessionId) } async function resolveProviderId(): Promise { diff --git a/src/commands/reload-plugins/reload-plugins.ts b/src/commands/reload-plugins/reload-plugins.ts index facca09b..e3ac9ebf 100644 --- a/src/commands/reload-plugins/reload-plugins.ts +++ b/src/commands/reload-plugins/reload-plugins.ts @@ -50,7 +50,7 @@ export const call: LocalCommandCall = async (_args, context) => { let msg = `Reloaded: ${parts.join(' · ')}` if (r.error_count > 0) { - msg += `\n${n(r.error_count, 'error')} during load. Run /doctor for details.` + msg += `\n${n(r.error_count, 'error')} during load. Run dreamcoder doctor for details.` } return { type: 'text', value: msg } diff --git a/src/components/mcp/MCPSettings.tsx b/src/components/mcp/MCPSettings.tsx index 95562c73..ef4f75ad 100644 --- a/src/components/mcp/MCPSettings.tsx +++ b/src/components/mcp/MCPSettings.tsx @@ -147,7 +147,7 @@ export function MCPSettings(t0) { return; } if (servers.length === 0 && agentMcpServers.length === 0) { - onComplete("No MCP servers configured. Please run /doctor if this is unexpected. Otherwise, run `claude mcp --help` or visit https://code.claude.com/docs/en/mcp to learn more."); + onComplete("No MCP servers configured. Please run dreamcoder doctor if this is unexpected. Otherwise, run `claude mcp --help` or visit https://code.claude.com/docs/en/mcp to learn more."); } }; t8 = [servers.length, filteredClients.length, agentMcpServers.length, onComplete]; diff --git a/src/hooks/notifs/useSettingsErrors.tsx b/src/hooks/notifs/useSettingsErrors.tsx index d2694824..0b8b0ca4 100644 --- a/src/hooks/notifs/useSettingsErrors.tsx +++ b/src/hooks/notifs/useSettingsErrors.tsx @@ -35,7 +35,7 @@ export function useSettingsErrors() { return; } if (errors_0.length > 0) { - const message = `Found ${errors_0.length} settings ${errors_0.length === 1 ? "issue" : "issues"} · /doctor for details`; + const message = `Found ${errors_0.length} settings ${errors_0.length === 1 ? "issue" : "issues"} · dreamcoder doctor for details`; addNotification({ key: SETTINGS_ERRORS_NOTIFICATION_KEY, text: message, diff --git a/src/keybindings/KeybindingProviderSetup.tsx b/src/keybindings/KeybindingProviderSetup.tsx index 84817eac..555dfea2 100644 --- a/src/keybindings/KeybindingProviderSetup.tsx +++ b/src/keybindings/KeybindingProviderSetup.tsx @@ -54,7 +54,7 @@ type Props = { */ /** * Display keybinding warnings to the user via notifications. - * Shows a brief message pointing to /doctor for details. + * Shows a brief message pointing to `dreamcoder doctor` for details. */ function useKeybindingWarnings(warnings, isReload) { const $ = _c(9); @@ -81,7 +81,7 @@ function useKeybindingWarnings(warnings, isReload) { message = `Found ${warnCount} keybinding ${plural(warnCount, "warning")}`; } } - message = message + " \xB7 /doctor for details"; + message = message + " \xB7 dreamcoder doctor for details"; addNotification({ key: "keybinding-config-warning", text: message, diff --git a/src/server/__tests__/diagnostics-service.test.ts b/src/server/__tests__/diagnostics-service.test.ts index bf11ded5..6b9881ea 100644 --- a/src/server/__tests__/diagnostics-service.test.ts +++ b/src/server/__tests__/diagnostics-service.test.ts @@ -186,7 +186,7 @@ describe('DiagnosticsService', () => { }) describe('diagnostics API', () => { - test('returns status, events, export path, and supports clearing logs', async () => { + test('accepts client events and returns an export path', async () => { const service = diagnosticsService await service.recordEvent({ type: 'api_unhandled_error', @@ -194,20 +194,6 @@ describe('diagnostics API', () => { summary: 'boom', }) - const statusReq = makeRequest('GET', '/api/diagnostics/status') - const statusRes = await handleDiagnosticsApi(statusReq.req, statusReq.url, statusReq.segments) - expect(statusRes.status).toBe(200) - const status = await statusRes.json() as { logDir: string; cliDiagnosticsPath: string; recentErrorCount: number } - expect(status.logDir).toContain(path.join('dreamcoder', 'diagnostics')) - expect(status.cliDiagnosticsPath).toContain('cli-diagnostics.jsonl') - expect(status.recentErrorCount).toBe(1) - - const eventsReq = makeRequest('GET', '/api/diagnostics/events?limit=10') - const eventsRes = await handleDiagnosticsApi(eventsReq.req, eventsReq.url, eventsReq.segments) - expect(eventsRes.status).toBe(200) - const events = await eventsRes.json() as { events: Array<{ type: string }> } - expect(events.events[0].type).toBe('api_unhandled_error') - const clientEventReq = new Request('http://localhost:3456/api/diagnostics/events', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -235,11 +221,6 @@ describe('diagnostics API', () => { expect(exportRes.status).toBe(200) const exported = await exportRes.json() as { bundle: { path: string } } await expect(fs.stat(exported.bundle.path)).resolves.toBeTruthy() - - const clearReq = makeRequest('DELETE', '/api/diagnostics') - const clearRes = await handleDiagnosticsApi(clearReq.req, clearReq.url, clearReq.segments) - expect(clearRes.status).toBe(200) - expect(await service.readRecentEvents()).toEqual([]) }) }) diff --git a/src/server/api/diagnostics.ts b/src/server/api/diagnostics.ts index 037762e4..4b322c8c 100644 --- a/src/server/api/diagnostics.ts +++ b/src/server/api/diagnostics.ts @@ -4,27 +4,12 @@ import { ApiError, errorResponse } from '../middleware/errorHandler.js' export async function handleDiagnosticsApi( req: Request, - url: URL, + _url: URL, segments: string[], ): Promise { try { const action = segments[2] - if (!action && req.method === 'DELETE') { - await diagnosticsService.clear() - return Response.json({ ok: true }) - } - - if (action === 'status' && req.method === 'GET') { - return Response.json(await diagnosticsService.getStatus()) - } - - if (action === 'events' && req.method === 'GET') { - const limit = Number.parseInt(url.searchParams.get('limit') || '100', 10) - const events = await diagnosticsService.readRecentEvents(Number.isFinite(limit) ? limit : 100) - return Response.json({ events }) - } - if (action === 'events' && req.method === 'POST') { const body = await parseJsonBody(req) const type = typeof body.type === 'string' && body.type.trim() @@ -64,11 +49,6 @@ export async function handleDiagnosticsApi( return Response.json({ ok: true }) } - if (action === 'open-log-dir' && req.method === 'POST') { - await diagnosticsService.openLogDir() - return Response.json({ ok: true }) - } - throw new ApiError(404, `Unknown diagnostics endpoint: ${action ?? '(root)'}`, 'NOT_FOUND') } catch (error) { return errorResponse(error) diff --git a/src/server/services/diagnosticsService.ts b/src/server/services/diagnosticsService.ts index cca1e47b..0f2e90c8 100644 --- a/src/server/services/diagnosticsService.ts +++ b/src/server/services/diagnosticsService.ts @@ -26,20 +26,6 @@ export type DiagnosticEvent = { details?: unknown } -export type DiagnosticsStatus = { - logDir: string - diagnosticsPath: string - cliDiagnosticsPath: string - runtimeErrorsPath: string - exportDir: string - retentionDays: number - maxBytes: number - totalBytes: number - eventCount: number - recentErrorCount: number - lastEventAt: string | null -} - export type DiagnosticsExportResult = { path: string fileName: string @@ -163,29 +149,6 @@ export class DiagnosticsService { }) } - async getStatus(): Promise { - await this.ensureLogDir() - const events = await this.readRecentEvents(500) - const totalBytes = await this.getDirectorySize(this.getLogDir()) - const cutoff = Date.now() - 24 * 60 * 60 * 1000 - return { - logDir: this.getLogDir(), - diagnosticsPath: this.getDiagnosticsPath(), - cliDiagnosticsPath: this.getCliDiagnosticsPath(), - runtimeErrorsPath: this.getRuntimeErrorsPath(), - exportDir: this.getExportDir(), - retentionDays: RETENTION_DAYS, - maxBytes: MAX_BYTES, - totalBytes, - eventCount: events.length, - recentErrorCount: events.filter((event) => - (event.severity === 'error' || event.severity === 'warn') && - Date.parse(event.timestamp) >= cutoff - ).length, - lastEventAt: events[0]?.timestamp ?? null, - } - } - async readRecentEvents(limit = 100): Promise { const boundedLimit = Math.max(1, Math.min(limit, 1000)) let raw = '' @@ -258,20 +221,6 @@ export class DiagnosticsService { return { path: outPath, fileName, bytes: archive.byteLength } } - async openLogDir(): Promise { - await this.ensureLogDir() - const dir = this.getLogDir() - if (process.platform === 'darwin') { - Bun.spawn(['open', dir], { stdout: 'ignore', stderr: 'ignore' }) - return - } - if (process.platform === 'win32') { - Bun.spawn(['cmd', '/c', 'start', '', dir], { stdout: 'ignore', stderr: 'ignore', windowsHide: true }) - return - } - Bun.spawn(['xdg-open', dir], { stdout: 'ignore', stderr: 'ignore' }) - } - /** Shows an exported bundle in Finder or Explorer. Only names a file inside the export folder. */ async revealExport(fileName: string): Promise { if (!fileName || fileName === '.' || fileName === '..' || path.basename(fileName) !== fileName) { @@ -290,11 +239,6 @@ export class DiagnosticsService { Bun.spawn(['xdg-open', this.getExportDir()], { stdout: 'ignore', stderr: 'ignore' }) } - async clear(): Promise { - await fs.rm(this.getLogDir(), { recursive: true, force: true }) - await this.ensureLogDir() - } - sanitizeValue(value: unknown, depth = 0): unknown { if (depth > 6) return '[TRUNCATED_DEPTH]' if (value === null || value === undefined) return value @@ -564,10 +508,6 @@ export class DiagnosticsService { } } - private async getDirectorySize(dir: string): Promise { - return (await this.listFiles(dir)).reduce((sum, file) => sum + file.size, 0) - } - private async listFiles(dir: string): Promise> { const results: Array<{ path: string; size: number; mtimeMs: number }> = [] let entries: Dirent[] diff --git a/src/services/api/errorUtils.ts b/src/services/api/errorUtils.ts index 20e4441f..95f8c884 100644 --- a/src/services/api/errorUtils.ts +++ b/src/services/api/errorUtils.ts @@ -96,7 +96,7 @@ export function getSSLErrorHint(error: unknown): string | null { if (!details?.isSSLError) { return null } - return `SSL certificate error (${details.code}). If you are behind a corporate proxy or TLS-intercepting firewall, set NODE_EXTRA_CA_CERTS to your CA bundle path, or ask IT to allowlist *.anthropic.com. Run /doctor for details.` + return `SSL certificate error (${details.code}). If you are behind a corporate proxy or TLS-intercepting firewall, set NODE_EXTRA_CA_CERTS to your CA bundle path, or ask IT to allowlist *.anthropic.com. Run dreamcoder doctor for details.` } /** diff --git a/src/skills/bundled/keybindings.ts b/src/skills/bundled/keybindings.ts index 373ba217..6bc99cb5 100644 --- a/src/skills/bundled/keybindings.ts +++ b/src/skills/bundled/keybindings.ts @@ -229,9 +229,9 @@ const SECTION_BEHAVIORAL_RULES = [ ].join('\n') const SECTION_DOCTOR = [ - '## Validation with /doctor', + '## Validation with dreamcoder doctor', '', - 'The `/doctor` command includes a "Keybinding Configuration Issues" section that validates `~/.dreamcoder/keybindings.json`.', + 'The `dreamcoder doctor` command includes a "Keybinding Configuration Issues" section that validates `~/.dreamcoder/keybindings.json`.', '', '### Common Issues and Fixes', '', @@ -276,7 +276,7 @@ const SECTION_DOCTOR = [ ], ), '', - '### Example /doctor Output', + '### Example dreamcoder doctor Output', '', '```', 'Keybinding Configuration Issues', diff --git a/src/utils/config.ts b/src/utils/config.ts index 48553c78..57ed6e63 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -191,8 +191,6 @@ export type GlobalConfig = { autoUpdates?: boolean // Flag to distinguish protection-based disabling from user preference autoUpdatesProtectedForNative?: boolean - // Session count when Doctor was last shown - doctorShownAtSession?: number userID?: string theme: ThemeSetting hasCompletedOnboarding?: boolean diff --git a/src/utils/sandbox/sandbox-adapter.ts b/src/utils/sandbox/sandbox-adapter.ts index 9ae23783..344aeed9 100644 --- a/src/utils/sandbox/sandbox-adapter.ts +++ b/src/utils/sandbox/sandbox-adapter.ts @@ -581,7 +581,7 @@ function getSandboxUnavailableReason(): string | undefined { const platform = getPlatform() const hint = platform === 'macos' - ? 'run /sandbox or /doctor for details' + ? 'run /sandbox or dreamcoder doctor for details' : 'install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details' return `sandbox.enabled is set but dependencies are missing: ${deps.errors.join(', ')} · ${hint}` }