Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(issue): include redacted related logs (#4467)
Lizi4ea7ee5bdd97
diff --git a/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts b/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.tsindex 611971494f..8f9a9f0c71 100644--- a/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts+++ b/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts@@ -47,7 +47,7 @@ function makeDeps(over: Partial<GithubIssueSubmitServiceDeps> = {}) {getSubmitterName: () => 'Carol',...over,};- return { deps, confirm, postIssue };+ return { deps, confirm: deps.confirm as typeof confirm, postIssue };}describe('submitGithubIssueWithConfirm', () => {@@ -67,6 +67,63 @@ describe('submitGithubIssueWithConfirm', () => {}});+ it('用户同意后把安全相关日志作为独立模块放进确认稿和最终正文', async () => {+ const collectRelatedLogs = vi.fn(async () => ({+ recordCount: 1,+ section: '\n---\n## 相关日志\n\n- 2026-09-15T12:00:00+08:00 [main/network] token=<redacted>',+ }));+ const { deps, confirm, postIssue } = makeDeps({+ collectRelatedLogs,+ confirm: vi.fn(async (_sessionId, draft) => ({+ confirmed: true as const,+ ...draft,+ publicName: 'Carol',+ uiLanguage: 'zh-CN',+ })),+ });++ await expect(+ submitGithubIssueWithConfirm(deps, { ...REQ, includeRelatedLogs: true }),+ ).resolves.toMatchObject({ ok: true });++ expect(collectRelatedLogs).toHaveBeenCalledTimes(1);+ expect(confirm.mock.calls[0]![1].body).toContain('## 相关日志');+ expect(postIssue.mock.calls[0]![1]().description).toContain('## 相关日志');+ });++ it('未明确同意时不读取本地相关日志', async () => {+ const collectRelatedLogs = vi.fn(async () => ({ section: '\n## 相关日志\nsecret', recordCount: 1 }));+ const { deps } = makeDeps({ collectRelatedLogs });++ await expect(submitGithubIssueWithConfirm(deps, REQ)).resolves.toMatchObject({ ok: true });++ expect(collectRelatedLogs).not.toHaveBeenCalled();+ });++ it('正文超长时仍保留相关日志模块', async () => {+ const collectRelatedLogs = vi.fn(async () => ({+ recordCount: 1,+ section: '\n---\n## 相关日志\n\n- safe diagnostic record',+ }));+ const { deps, postIssue } = makeDeps({+ collectRelatedLogs,+ confirm: vi.fn(async (_sessionId, draft) => ({+ confirmed: true as const,+ ...draft,+ publicName: 'Carol',+ uiLanguage: 'zh-CN',+ })),+ });++ await submitGithubIssueWithConfirm(deps, {+ ...REQ,+ body: '正文'.repeat(3000),+ includeRelatedLogs: true,+ });++ expect(postIssue.mock.calls[0]![1]().description).toContain('## 相关日志');+ });+it('confirm 收到 agent 草稿 + env;confirmed 后 postIssue 收到用户编辑版', async () => {const confirm = vi.fn(async (): Promise<IssueConfirmDecision> => ({confirmed: true,diff --git a/apps/desktop/src/main/github-issue/__tests__/issueDiagnostics.test.ts b/apps/desktop/src/main/github-issue/__tests__/issueDiagnostics.test.tsnew file mode 100644index 0000000000..7d7ba7b724--- /dev/null+++ b/apps/desktop/src/main/github-issue/__tests__/issueDiagnostics.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { formatRelatedIssueLogs } from '../issueDiagnostics';+import type { UploadRecord } from '../../log-upload/types';++const NOW = Date.parse('2026-09-15T12:00:00.000+08:00');++function record(overrides: Partial<UploadRecord> = {}): UploadRecord {+ return {+ ts: '2026-09-15T11:30:00.000+08:00',+ level: 'error',+ src: 'main',+ scope: 'network',+ msg: 'request failed',+ ...overrides,+ };+}++describe('formatRelatedIssueLogs', () => {+ it('只保留最近两小时并生成固定的相关日志模块', () => {+ const result = formatRelatedIssueLogs(+ [+ record({ msg: 'recent' }),+ record({ ts: '2026-09-15T08:00:00.000+08:00', msg: 'old' }),+ ],+ NOW,+ );++ expect(result.recordCount).toBe(1);+ expect(result.section).toContain('## 相关日志');+ expect(result.section).toContain('recent');+ expect(result.section).not.toContain('old');+ });++ it('再次脱敏日志正文并压平多行内容', () => {+ const result = formatRelatedIssueLogs(+ [record({ msg: 'email [email protected]\npath /Users/alice/private' })],+ NOW,+ );++ expect(result.section).toContain('[REDACTED:email]');+ expect(result.section).toContain('↵');+ expect(result.section).not.toContain('/Users/alice');+ });+});diff --git a/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts b/apps/desktop/src/main/github-issue/githubIssueSubmitService.tsindex 1506f783ee..643c35527c 100644--- a/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts+++ b/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts@@ -22,6 +22,7 @@ import {import type { SubmittedIssueRecord } from '../../shared/myIssues.js';import { myIssueUrl } from '../../shared/myIssues.js';import { redactSensitive } from '../learn-host/redaction';+import { RELATED_LOG_SECTION_MARKER } from './issueDiagnostics';import type {IssueConfirmDecision,IssueDraft,@@ -60,6 +61,8 @@ export interface SubmitIssueRequest {title: string;body: string;type: 'bug' | 'feature';+ /** 只有 Agent 已取得用户同意时才采集并附加安全日志摘要。 */+ includeRelatedLogs?: boolean;}/** github-server 的 issue 创建 payload;userName 缺失时由服务端按 membership id 回退。 */@@ -100,6 +103,8 @@ export interface GithubIssueSubmitServiceDeps {getFallbackLocale: () => string;/** 当前 Cindy membership 的展示名,仅用于 issue 正文标记提交人。 */getSubmitterName: () => string | undefined;+ /** 只返回已经过日志采集安全管道的 Markdown 区块。 */+ collectRelatedLogs?: () => Promise<{ section: string; recordCount: number }>;/*** 提交成功后记账(「我的 Issue」列表靠它认出平台代发的那一半)。* 只在 postIssue 真正成功后调用一次,抛错由本模块吞掉 —— 记账失败绝不能把一次@@ -149,7 +154,19 @@ export async function submitGithubIssueWithConfirm(}const suggestedPublicName = normalizeIssuePublicName(deps.getSubmitterName()) ?? undefined;- const preparedDraft = redactIssueDraft(req);+ let draftBody = req.body;+ if (req.includeRelatedLogs === true && deps.collectRelatedLogs) {+ try {+ draftBody += (await deps.collectRelatedLogs()).section;+ } catch {+ // 日志只是反馈上下文,采集失败不能阻断用户提交正文反馈。+ draftBody += '\n\n---\n## 相关日志\n\n未能读取本机相关日志。';+ }+ }+ const preparedDraft = redactIssueDraft({ ...req, body: draftBody });+ if (req.includeRelatedLogs === true) {+ preparedDraft.draft.body = fitIssueBody(preparedDraft.draft.body, 4000);+ }const decision = await deps.confirm(req.sessionId,preparedDraft.draft,@@ -206,9 +223,9 @@ export async function submitGithubIssueWithConfirm(`**Model ID**: ${markdownCodeSpan(env.modelId)}`,`**界面语言**: ${uiLanguage}`,].join('\n');- // env 块必须完整保留,clamp 只裁用户正文部分。- const bodyBudget = SERVER_DESC_MAX - envBlock.length;- const description = decision.body.slice(0, Math.max(0, bodyBudget)) + envBlock;+ // 环境块必须完整保留;相关日志是独立模块,正文超限时优先保留它而不是让前面的+ // 用户正文把整个诊断区块挤掉。+ const description = buildIssueDescription(decision.body, envBlock);try {const result = await deps.postIssue(submissionIdentity, () => ({@@ -237,6 +254,26 @@ export async function submitGithubIssueWithConfirm(}}+function buildIssueDescription(body: string, envBlock: string): string {+ const bodyBudget = Math.max(0, SERVER_DESC_MAX - envBlock.length);+ return fitIssueBody(body, bodyBudget) + envBlock;+}++function fitIssueBody(body: string, bodyBudget: number): string {+ if (body.length <= bodyBudget) return body;+ const relatedLogsAt = body.lastIndexOf(RELATED_LOG_SECTION_MARKER);+ if (relatedLogsAt < 0) return body.slice(0, bodyBudget);++ const userBody = body.slice(0, relatedLogsAt);+ const section = body.slice(relatedLogsAt);+ const logs = section.length <= bodyBudget+ ? section+ : RELATED_LOG_SECTION_MARKER + '\n\n日志区块超过正文长度限制,未附带。';+ const note = '\n…(正文因长度限制省略)\n';+ const userBodyBudget = Math.max(0, bodyBudget - logs.length - note.length);+ return userBody.slice(0, userBodyBudget) + note + logs;+}+/*** Agent 可能把用户粘贴的日志、错误和路径直接带进初稿。先过高置信度脱敏,再交给* 用户确认;用户在确认卡里主动编辑的内容视为明确确认,不在这里静默改写。diff --git a/apps/desktop/src/main/github-issue/index.ts b/apps/desktop/src/main/github-issue/index.tsindex 24b959a0fc..9adcb1dc7d 100644--- a/apps/desktop/src/main/github-issue/index.ts+++ b/apps/desktop/src/main/github-issue/index.ts@@ -25,6 +25,8 @@ import {type SubmitIssueRequest,} from './githubIssueSubmitService';import { invalidateMyIssuesCache } from './myIssuesRuntime.js';+import { formatRelatedIssueLogs } from './issueDiagnostics';+import { collectLogsFromDisk } from '../log-upload/collectRuntime';import { recordSubmittedIssue } from './submittedIssueLedger.js';import {postGithubIssueAsUser,@@ -103,6 +105,15 @@ export async function submitGithubIssueForSession(getRegion: () => CURRENT_CINDY_REGION,getFallbackLocale: () => app.getLocale(),getSubmitterName: getCurrentMembershipDisplayName,+ collectRelatedLogs: async () => {+ const nowMs = Date.now();+ const result = await collectLogsFromDisk({+ reason: 'manual',+ anchors: [],+ includeAgentLogs: true,+ });+ return formatRelatedIssueLogs(result.records, nowMs, req.workingDir);+ },onSubmitted: (record) => {try {recordSubmittedIssue(record, submitScope);diff --git a/apps/desktop/src/main/github-issue/issueDiagnostics.ts b/apps/desktop/src/main/github-issue/issueDiagnostics.tsnew file mode 100644index 0000000000..818ba69f68--- /dev/null+++ b/apps/desktop/src/main/github-issue/issueDiagnostics.ts@@ -0,0 +1,100 @@+/**+ * /issue 的相关日志摘要。+ *+ * 这里只消费 log-upload 的最终安全记录,不直接读取日志文件,也不把原始日志交给+ * issue 提交链路。这样来源白名单、字段白名单、脱敏和长度限制始终只有一套事实源。+ */++import { redactSensitive } from '../learn-host/redaction';+import { redact } from '../log-upload/redact';+import type { UploadRecord } from '../log-upload/types';++const RELATED_LOG_LOOKBACK_MS = 2 * 60 * 60 * 1000;+const MAX_RELATED_LOG_RECORDS = 24;+const MAX_RELATED_LOG_CHARS = 2200;+const MAX_RELATED_LOG_LINE_CHARS = 500;+export const RELATED_LOG_SECTION_MARKER = '\n---\n## 相关日志';++export interface RelatedIssueLogs {+ section: string;+ recordCount: number;+}++function publicLogText(text: string, workingDir?: string): string {+ const withoutWorkdir = workingDir && workingDir.length > 1+ ? text.split(workingDir).join('[REDACTED:path]')+ : text;+ return redactSensitive(redact(withoutWorkdir)).text+ .replace(/[A-Za-z0-9.*_%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '[REDACTED:email]')+ .replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'<>]+/g, '[REDACTED:url]')+ .replace(/(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/(?:Users|home)\/)[^\r\n"']*/g, '[REDACTED:path]')+ .replace(/(^|[\s=("'])(\/(?!\/)[^\r\n"']+)/gm, '$1[REDACTED:path]')+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g, '');+}++function safeLogLine(record: UploadRecord, workingDir?: string): string {+ const timestamp = new Date(record.ts).toISOString();+ const scope = publicLogText(record.scope.split(/[/:]/)[0], workingDir);+ const level = ['info', 'warn', 'error', 'fatal'].includes(record.level.toLowerCase())+ ? record.level.toUpperCase()+ : 'INFO';+ const message = publicLogText(record.msg, workingDir).replace(/[\r\n]+/g, ' ↵ ').trim();+ const line = '- ' + timestamp + ' [' + level + '] [' + record.src + '/' + scope + '] ' + message;+ return line.length > MAX_RELATED_LOG_LINE_CHARS+ ? line.slice(0, MAX_RELATED_LOG_LINE_CHARS - 1) + '…'+ : line;+}++export function formatRelatedIssueLogs(+ records: readonly UploadRecord[],+ nowMs: number,+ workingDir?: string,+): RelatedIssueLogs {+ const recent = records+ .filter((record) => {+ const timestamp = Date.parse(record.ts);+ return Number.isFinite(timestamp) && timestamp <= nowMs &&+ timestamp >= nowMs - RELATED_LOG_LOOKBACK_MS &&+ ['info', 'warn', 'error', 'fatal'].includes(record.level.toLowerCase());+ })+ .sort((left, right) => {+ const priority = (record: UploadRecord) =>+ ['error', 'fatal'].includes(record.level.toLowerCase()) ? 2 :+ record.level.toLowerCase() === 'warn' ? 1 : 0;+ return priority(right) - priority(left) || Date.parse(right.ts) - Date.parse(left.ts);+ });++ const selected: { timestamp: number; line: string }[] = [];+ let remaining = MAX_RELATED_LOG_CHARS - 400;+ for (const record of recent) {+ const line = safeLogLine(record, workingDir);+ if (line.length + 1 > remaining) continue;+ selected.push({ timestamp: Date.parse(record.ts), line });+ remaining -= line.length + 1;+ if (selected.length >= MAX_RELATED_LOG_RECORDS) break;+ }+ const content = selected.sort((left, right) => left.timestamp - right.timestamp)+ .map((record) => record.line).join('\n');+ const fenceLength = Math.max(3, ...Array.from(content.matchAll(/\x60+/g), (match) => match[0].length + 1));+ const fence = String.fromCharCode(96).repeat(fenceLength);++ return {+ recordCount: selected.length,+ section: [+ '',+ '---',+ '## 相关日志',+ '',+ '提交客户端本机最近 2 小时的运行日志摘录,不代表已定位故障,也不包含 SSH 远端或手机日志。已按来源和字段白名单过滤并脱敏;不读取对话正文或原始请求响应。',+ ...(content ? [fence + 'text', content, fence] : ['未找到可公开的相关日志记录。']),+ ...(selected.length < recent.length ? ['部分记录因条数或长度限制省略,优先保留错误和警告。'] : []),+ ].join('\n'),+ };+}++export const __testing = {+ RELATED_LOG_LOOKBACK_MS,+ MAX_RELATED_LOG_RECORDS,+ MAX_RELATED_LOG_CHARS,+ safeLogLine,+};diff --git a/apps/desktop/src/main/log-upload/__tests__/collect.test.ts b/apps/desktop/src/main/log-upload/__tests__/collect.test.tsindex 7d20b7edf4..d02393c158 100644--- a/apps/desktop/src/main/log-upload/__tests__/collect.test.ts+++ b/apps/desktop/src/main/log-upload/__tests__/collect.test.ts@@ -126,7 +126,7 @@ describe('第一层源白名单:会话目录与调试原文永不被打开', (expect(result.records).toHaveLength(1);});- it('手动上报不读 agent 流(只在崩溃路径作上下文)', async () => {+ it('普通手动上报不读 agent 流(不含 /issue 同意路径)', async () => {const logDir = path.join('/tmp', 'cindy-logs');const today = dayKey(NOW);const files: Record<string, string> = {@@ -149,6 +149,42 @@ describe('第一层源白名单:会话目录与调试原文永不被打开', (expect(openedPaths.some((p) => p.includes('agent-'))).toBe(false);});+ it('手动路径仅在 includeAgentLogs=true 时读 agent 流,且仍只取 proxy 源', async () => {+ const logDir = path.join('/tmp', 'cindy-logs');+ const today = dayKey(NOW);+ const files: Record<string, string> = {+ [path.join(logDir, `main-${today}.log`)]: SENTINEL,+ [path.join(logDir, `agent-${today}.ndjson`)]: [+ JSON.stringify({+ ts: NOW - 20_000,+ level: 'info',+ source: 'proxy',+ scope: 'cc-proxy/req',+ msg: 'POST /v1/messages 200 812ms',+ }),+ JSON.stringify({+ ts: NOW - 19_000,+ level: 'debug',+ source: 'maker',+ scope: 'maker/s:abc',+ msg: '用户提示词正文',+ }),+ ].join('\n'),+ };+ const { deps, openedPaths } = harness(files);++ const result = await collectLogs(deps, {+ reason: 'manual',+ anchors: [],+ includeAgentLogs: true,+ });++ expect(openedPaths.some((p) => p.includes('agent-'))).toBe(true);+ expect(result.records).toHaveLength(1);+ expect(result.records[0].src).toBe('proxy');+ expect(JSON.stringify(result.records)).not.toContain('提示词');+ });+it('崩溃路径读 agent 流,但只取 proxy 源', async () => {const logDir = path.join('/tmp', 'cindy-logs');const today = dayKey(NOW);diff --git a/apps/desktop/src/main/log-upload/agentLogReader.ts b/apps/desktop/src/main/log-upload/agentLogReader.tsindex a1c14a5c27..11c2e58c9f 100644--- a/apps/desktop/src/main/log-upload/agentLogReader.ts+++ b/apps/desktop/src/main/log-upload/agentLogReader.ts@@ -1,9 +1,11 @@/*** `agent-<date>.ndjson`(logs 根,**不是** `sessions/<id>/`)的读侧。*- * 只在崩溃路径附带,且**只取 `source === 'proxy'` 的记录**:同一个文件里还有 `maker`+ * 打开时机由 `collect.ts` 决定:崩溃路径默认附带;普通手动上传不附带;`/issue` 反馈+ * 只有在用户明确同意公开诊断信息、且 `includeAgentLogs === true` 时才打开。无论哪条+ * 路径打开,读侧都**只取 `source === 'proxy'` 的记录**:同一个文件里还有 `maker`* 源的启动期 / 全局基础设施日志,那些可能带 agent 提示词与用户内容。需求 §4.2 的措辞是- * 「只取 proxy 的状态/耗时/错误,作崩溃上下文」。+ * 「只取 proxy 的状态/耗时/错误,作崩溃上下文」;issue 路径复用同一条窄出口,不得放宽。** ⚠️ **「按字面执行」不能靠原样搬 `msg`**(2026-08-04 review P1)。proxy 自己会把请求体与* 上游错误体写进日志上下文:diff --git a/apps/desktop/src/main/log-upload/collect.ts b/apps/desktop/src/main/log-upload/collect.tsindex 88a2aa9f45..da7dc564a0 100644--- a/apps/desktop/src/main/log-upload/collect.ts+++ b/apps/desktop/src/main/log-upload/collect.ts@@ -51,6 +51,11 @@ export interface CollectRequest {reason: LogUploadReason;/** 崩溃锚点(epoch ms)。手动上报为空数组。 */anchors: number[];+ /**+ * `/issue` 同意路径专用。普通手动上传必须保持 `undefined`/`false`(不读 agent 流);+ * 仅当用户明确同意公开诊断信息时由 issue 提交链路设为 `true`。崩溃路径不看此字段。+ */+ includeAgentLogs?: boolean;}/** `YYYY-MM-DD`(本地时区),与 logger 的 `dateKeyLocal` 同口径。 */@@ -163,8 +168,8 @@ export async function collectLogs(anchorDistanceMs: distance,});}- // agent 流只在崩溃路径附带(需求 §4.2:作崩溃上下文)。- if (request.reason !== 'manual') {+ // 普通手动上传不带 agent 流;反馈只有在用户明确同意后才附带安全 proxy 上下文。+ if (request.reason !== 'manual' || request.includeAgentLogs === true) {const agentName = `agent-${dateKey}.ndjson`;if (existing.has(agentName)) {plans.push({diff --git a/apps/desktop/src/main/log-upload/collectRuntime.ts b/apps/desktop/src/main/log-upload/collectRuntime.tsnew file mode 100644index 0000000000..c098f8bb50--- /dev/null+++ b/apps/desktop/src/main/log-upload/collectRuntime.ts@@ -0,0 +1,64 @@+/**+ * 日志采集的本机文件适配层。+ *+ * 采集、来源白名单和脱敏规则仍由 collectLogs 统一负责;本模块只提供 main 侧的+ * 只读文件句柄和运行期路径,供日志上报与 issue 反馈共用同一条安全管道。+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { getLogDir } from '../logger';+import { collectLogs, type CollectDeps, type CollectRequest } from './collect';+import type { RandomAccessFile } from './mainLogReader';+import type { CollectResult } from './types';++async function openReadOnly(+ filePath: string,+): Promise<(RandomAccessFile & { close(): Promise<void> }) | null> {+ let handle: fs.promises.FileHandle;+ try {+ handle = await fs.promises.open(filePath, 'r');+ } catch {+ return null;+ }+ return {+ async size() {+ const stat = await handle.stat();+ return stat.size;+ },+ async read(offset: number, length: number) {+ if (length <= 0) return Buffer.alloc(0);+ const buffer = Buffer.alloc(length);+ let read = 0;+ while (read < length) {+ const { bytesRead } = await handle.read(buffer, read, length - read, offset + read);+ if (bytesRead === 0) break;+ read += bytesRead;+ }+ return buffer.subarray(0, read);+ },+ async close() {+ await handle.close();+ },+ };+}++function collectDeps(): CollectDeps {+ const logDir = getLogDir();+ if (!logDir || !path.isAbsolute(logDir)) throw new Error('log directory unavailable');+ return {+ logDir,+ listDir: (dir) => fs.promises.readdir(dir),+ openFile: openReadOnly,+ now: () => Date.now(),+ homeDir: os.homedir(),+ yieldToEventLoop: () => new Promise<void>((resolve) => setImmediate(resolve)),+ joinPath: (...parts) => path.join(...parts),+ };+}++export function collectLogsFromDisk(request: CollectRequest): Promise<CollectResult> {+ return collectLogs(collectDeps(), request);+}diff --git a/apps/desktop/src/main/log-upload/index.ts b/apps/desktop/src/main/log-upload/index.tsindex 88f1593517..828d0e7d7c 100644--- a/apps/desktop/src/main/log-upload/index.ts+++ b/apps/desktop/src/main/log-upload/index.ts@@ -39,7 +39,7 @@ import { outboundFetch } from '../maker-host/outbound-fetch';import { getPreviousRunReports } from '../startup-diagnostics';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { throwIpcError } from '../utils/ipcValidate.js';-import { collectLogs, type CollectDeps } from './collect';+import { collectLogsFromDisk } from './collectRuntime';import {crashAtFromMarker,selectBackfillGrouping,@@ -57,7 +57,6 @@ import {refreshLogUploadSettingsFromDisk,setCrashAutoUploadEnabled,} from './logUploadSettingsStore';-import type { RandomAccessFile } from './mainLogReader';import { PendingMarkerStore, type MarkerFs } from './pendingMarkers';import type { LogUploadMeta, LogUploadTarget } from './types';import { generateUploadCode } from './uploadCode';@@ -146,52 +145,6 @@ const gateDeps: ConsentGateDeps = {},};-/** 打开一个只能随机读的文件句柄。不存在 / 不可读返回 null(跳过,不算失败)。 */-async function openReadOnly(- filePath: string,-): Promise<(RandomAccessFile & { close(): Promise<void> }) | null> {- let handle: fs.promises.FileHandle;- try {- handle = await fs.promises.open(filePath, 'r');- } catch {- return null;- }- return {- async size() {- const stat = await handle.stat();- return stat.size;- },- async read(offset: number, length: number) {- if (length <= 0) return Buffer.alloc(0);- const buffer = Buffer.alloc(length);- let read = 0;- // 网络盘 / FUSE 上单次 read 不保证填满请求区间,读满循环避免把内容截断。- while (read < length) {- const { bytesRead } = await handle.read(buffer, read, length - read, offset + read);- if (bytesRead === 0) break;- read += bytesRead;- }- return buffer.subarray(0, read);- },- async close() {- await handle.close();- },- };-}--function collectDeps(): CollectDeps {- return {- logDir: getLogDir(),- listDir: (dir) => fs.promises.readdir(dir),- openFile: openReadOnly,- now: () => Date.now(),- homeDir: os.homedir(),- // setImmediate 让出一次:采集跑在 main 上,连续同步解析几 MB 会造成可感知的卡顿。- yieldToEventLoop: () => new Promise<void>((resolve) => setImmediate(resolve)),- joinPath: (...parts) => path.join(...parts),- };-}-function buildMeta(args: {uploadCode: string;reason: LogUploadReason;@@ -220,7 +173,7 @@ function runnerDeps() {gate: gateDeps,resolveTarget: currentTarget,collect: (request: { reason: LogUploadReason; anchors: number[] }) =>- collectLogs(collectDeps(), request),+ collectLogsFromDisk(request),send: (target: LogUploadTarget, meta: LogUploadMeta, records: Parameters<typeof sendLogs>[3]) =>sendLogs({ fetchImpl: outboundFetch }, target, meta, records),buildMeta,diff --git a/apps/desktop/src/renderer/features/cc-agent/IssueConfirmCard.tsx b/apps/desktop/src/renderer/features/cc-agent/IssueConfirmCard.tsxindex 2e11c418cc..4162b0eb02 100644--- a/apps/desktop/src/renderer/features/cc-agent/IssueConfirmCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/IssueConfirmCard.tsx@@ -76,6 +76,7 @@ export function IssueConfirmCard({ sessionId, pending, onRespond }: IssueConfirm);});const { title, body, type, publicName = '' } = draft;+ const hasRelatedLogs = body.includes('## 相关日志');const selectedIdentity =legacyFixedGithubIdentity ??(draft.submissionIdentityKind === 'github-user' && pending.githubUserIdentity@@ -266,6 +267,11 @@ export function IssueConfirmCard({ sessionId, pending, onRespond }: IssueConfirm<p className="mt-1 text-12 leading-snug text-[var(--status-bar-meta)]">{t('issueAgent.confirm.privacyHint')}</p>+ {hasRelatedLogs && (+ <p className="mt-1 text-12 leading-snug text-[var(--status-bar-meta)]">+ {t('issueAgent.confirm.relatedLogsHint')}+ </p>+ )}{/*新版 Main:平台 Bot 默认 + 可选 GitHub 用户。旧版 Main 可能已固定为 GitHubdiff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex fbce8a009e..f556f868ff 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10926,6 +10926,7 @@"titleLabel": "Title","bodyLabel": "Body (Markdown)","privacyHint": "The Issue title and body will be public and may be searchable or cached. Automatic redaction only covers some common patterns and cannot detect all sensitive context.",+ "relatedLogsHint": "This submission includes the related client logs shown above. They are filtered, redacted, and length-limited before publication.","privacyConfirm": "I reviewed the public content above and it contains no personal, conversation, or business information that should remain private","submissionMethodLabel": "Submission Identity","identityGithubUser": "My GitHub account @{{login}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2244e12282..245db64e08 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10910,6 +10910,7 @@"titleLabel": "タイトル","bodyLabel": "本文(Markdown)","privacyHint": "Issue のタイトルと本文は公開され、検索やキャッシュの対象になる場合があります。自動マスキングで検出できるのは一部の一般的な形式だけで、文脈上の機密情報をすべて判別することはできません。",+ "relatedLogsHint": "この送信には、上に表示された関連するクライアントログが含まれます。公開前にフィルタリング、マスキング、長さ制限が適用されます。","privacyConfirm": "上記の公開内容を確認し、非公開にすべき個人情報、会話内容、業務情報が含まれていないことを確認しました","submissionMethodLabel": "送信元","identityGithubUser": "自分の GitHub アカウント @{{login}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b658969371..be5d179508 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10910,6 +10910,7 @@"titleLabel": "제목","bodyLabel": "본문(Markdown)","privacyHint": "Issue 제목과 본문은 공개되며 검색되거나 캐시될 수 있습니다. 자동 가림은 일부 일반적인 형식만 처리하며 문맥상 민감한 정보를 모두 감지할 수는 없습니다.",+ "relatedLogsHint": "이 제출에는 위에 표시된 관련 클라이언트 로그가 포함됩니다. 공개 전에 출처 및 필드 필터링, 가림, 길이 제한이 적용됩니다.","privacyConfirm": "위 공개 내용을 검토했으며 비공개로 유지해야 할 개인, 대화 또는 업무 정보가 포함되지 않았음을 확인했습니다","submissionMethodLabel": "제출 계정","identityGithubUser": "내 GitHub 계정 @{{login}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1792a08da9..ad191bc149 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10906,6 +10906,7 @@"titleLabel": "标题","bodyLabel": "正文(Markdown)","privacyHint": "Issue 的标题和正文将公开显示,并可能被搜索或缓存。系统只能隐藏部分常见敏感信息,无法识别所有语义隐私。",+ "relatedLogsHint": "本次提交包含上方显示的相关客户端日志;日志在公开前已经过来源和字段筛选、脱敏及长度限制。","privacyConfirm": "我已检查以上公开内容,不包含不应公开的个人、对话或业务信息","submissionMethodLabel": "提交身份","identityGithubUser": "我的 GitHub 账号 @{{login}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5391418f79..c7ba0fe35f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10906,6 +10906,7 @@"titleLabel": "標題","bodyLabel": "正文(Markdown)","privacyHint": "Issue 的標題與正文將公開顯示,且可能被搜尋或快取。系統只能遮蔽部分常見敏感資訊,無法辨識所有語意隱私。",+ "relatedLogsHint": "本次提交包含上方顯示的相關客戶端日誌;日誌在公開前已經過來源與欄位篩選、脫敏及長度限制。","privacyConfirm": "我已檢查以上公開內容,不包含不應公開的個人、對話或業務資訊","submissionMethodLabel": "釋出方式","identityGithubUser": "GitHub 帳號 @{{login}} 直接釋出",diff --git a/docs/dev-rules/log-upload-and-redaction.md b/docs/dev-rules/log-upload-and-redaction.mdindex ba6ebe5583..c8048b3a08 100644--- a/docs/dev-rules/log-upload-and-redaction.md+++ b/docs/dev-rules/log-upload-and-redaction.md@@ -115,8 +115,13 @@ override 语义见 [`configuration-and-overrides.md`](configuration-and-override| 3 正则红线 | 抹除敏感片段 | `redact.ts`(宁可多抹,不可漏) || 4 字段白名单 + 截断 | 带出哪些字段 | 只有 `ts` / `level` / `src` / `scope` / `msg` 五个字段离开本机 |-`agent-<date>.ndjson` 只在崩溃路径附带,且**只取 `source === 'proxy'` 且 scope 落在 proxy 根下-的记录**(双闸)。同一文件里还有 `maker` 源的日志,那些可能带 agent 提示词与用户内容。+`agent-<date>.ndjson` **默认只在崩溃路径附带**。普通手动日志上传(设置页点「上传日志」)+不打开这条流。唯一例外是 `/issue` 反馈:只有调用方把 `CollectRequest.includeAgentLogs`+显式设为 `true` 时才打开——这条开关只由用户明确同意公开诊断信息的 `/issue` 路径传入+(`include_related_logs=true` → `includeRelatedLogs` → `includeAgentLogs`),普通手动+上传不得设。无论哪条路径打开这条流,读侧都**只取 `source === 'proxy'` 且 scope 落在+proxy 根下的记录**(双闸)。同一文件里还有 `maker` 源的日志,那些可能带 agent 提示词+与用户内容。issue 路径复用同一条窄出口与字段重建,不得为了反馈放宽。⚠️ **proxy 记录不能原样搬 `msg`,必须逐字段重建**(2026-08-04 review P1)。proxy 自己会把请求体与上游错误体写进日志上下文:diff --git a/packages/lizi-mcps/src/__tests__/submitGithubIssueTool.test.ts b/packages/lizi-mcps/src/__tests__/submitGithubIssueTool.test.tsindex 99eb1274c8..6ab5087f65 100644--- a/packages/lizi-mcps/src/__tests__/submitGithubIssueTool.test.ts+++ b/packages/lizi-mcps/src/__tests__/submitGithubIssueTool.test.ts@@ -150,6 +150,15 @@ describe('submit_github_issue tool', () => {});});+ it('用户同意后透传 include_related_logs', async () => {+ const { registry, submit } = setup();+ await registry.call('submit_github_issue', { ...VALID_ARGS, include_related_logs: true });++ expect(submit).toHaveBeenCalledWith(+ expect.objectContaining({ includeRelatedLogs: true }),+ );+ });+it('host 错误码透传, isError=true', async () => {for (const errorCode of ['USER_CANCELLED', 'CONFIRM_TIMEOUT', 'NETWORK_ERROR'] as const) {const { registry } = setup({diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.tsindex ef700662c4..84425086d4 100644--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts@@ -129,7 +129,7 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [detail: ['用户输入 /issue(可带初始描述)或直接说"帮我提个 issue",agent 先把反馈整理清楚再提交:缺什么问什么,不套固定问卷,不够清楚时不会急着提交。','整理出对维护者有用的标题与正文,默认概括并脱敏;功能建议不写源码级方案。对话里的图不会传到 GitHub,不要声称截图已附。',- '整理出结构化标题与正文后调用 submit_github_issue(cindy_helper 的 feedback 类目),系统会尽量隐藏常见密钥、个人路径和邮箱。',+ '整理出结构化标题与正文后调用 submit_github_issue(cindy_helper 的 feedback 类目);用户明确同意公开相关日志时传 include_related_logs=true,系统自动生成独立的「相关日志」模块,并通过日志来源/字段白名单、脱敏和长度限制。','提交前 App 内弹系统确认卡片,用户可编辑标题/正文、确认或取消;','不需要安装或配置 GitHub 插件:默认由 Cindy 官方 Bot 提交;当前已配置且可用的 GitHub 账号只作为确认卡里的额外身份选项。',`客户端版本 / OS / Harness / 模型 ID / 界面语言由系统作为「提交时的任务环境」自动附加(OS 来自提交客户端本机,Harness / 模型是当前任务快照,不一定是出问题的那个)。用户说明的实际故障环境按需写进正文。最终创建到 ${BRAND_NAME} 官方 GitHub 仓库。创建后会返回 issue 链接,并可继续协助用户从源码复现、修复 Bug、开发功能和准备 PR。`,diff --git a/packages/lizi-mcps/src/xdt-helper/submit_github_issue.ts b/packages/lizi-mcps/src/xdt-helper/submit_github_issue.tsindex 984004aaf2..15d65db67e 100644--- a/packages/lizi-mcps/src/xdt-helper/submit_github_issue.ts+++ b/packages/lizi-mcps/src/xdt-helper/submit_github_issue.ts@@ -66,6 +66,7 @@ export interface SubmitGithubIssueDeps {title: string;body: string;type: 'bug' | 'feature';+ includeRelatedLogs?: boolean;}) => Promise<SubmitGithubIssueHostResult>;}@@ -74,6 +75,7 @@ const DESCRIPTION = ['【流程硬约束】','1) 调用前先与用户对话,把这条反馈整理到足以让维护者看懂、能行动。缺什么问什么,已说过的不要重复,不够清楚不要急着调用。问什么、问多深、正文怎么组织,由你按反馈本身判断,不要套固定问卷或章节清单。普通建议不必按缺陷来问,和环境无关不必追问 Harness / 模型 / 推理强度。用户不知道的标未知,不要猜。系统自动附加的 Harness / Model ID 是当前任务的快照,不一定是出问题的那个。功能建议写用户能看见的场景和诉求;不要写仓库路径、实现方案、验收清单或内部架构推测,除非用户明确要求。','2) Bug 和功能建议都遵循最小公开原则:默认概括、泛化用户提供的场景与示例,不要逐字复制用户消息、会话标题、真实姓名、账号、业务内容或其它可识别信息。只有复现问题确实需要且用户明确同意公开时,才保留最小必要片段。Bug 可以主动收集用户提供的错误摘要、经过脱敏的日志片段和必要截图说明,但先解释会公开到 GitHub,取得用户同意后再纳入正文。优先摘要而不是整段原始日志;不要提交令牌、密码、邮箱、个人路径、内部域名、私有代码或与问题无关的文件内容。本工具不能把对话里的图片传到 GitHub。禁止写「已提供截图」「截图见上」等让维护者以为 GitHub issue 里有图的话;用户给过图时,用文字描述图上可见内容。系统会在确认卡前自动隐藏部分常见敏感信息,但不能识别所有语义隐私,仍要让用户检查最终正文。',+ '2a) 用户明确同意后才传 include_related_logs=true;系统生成的「相关日志」模块会固定放在 issue 正文中,方便维护者识别故障上下文。不要把本地日志原文直接复制到 body。','3) 本工具被调用后会在 App 内弹出系统确认卡片,用户可以编辑标题/正文并确认或取消;最终提交内容以用户确认的版本为准(返回的 final_title 可能与你传入的不同)。确认前不得创建 issue。','4) Cindy 官方 Bot 是默认且始终可用的提交身份,不要求用户安装插件或配置 GitHub。仅当系统实时验证到可用的 Cindy GitHub 账号时,确认卡才额外提供“用本人账号提交”的选项(受其 token 仓库权限约束)。用户确认身份后,提交失败不会静默切换身份。','5) errorCode 语义: USER_CANCELLED = 用户主动取消了本次提交,如实告知即可,不要换参数自动重试; CONFIRM_TIMEOUT = 确认卡片超时无人响应(用户可能不在电脑前),告知用户可以再说一声重新发起; AUTH_NOT_READY / NETWORK_ERROR / SERVER_ERROR / HOST_NOT_READY = 提交失败,如实转告原因,不存在任何绕过确认、权限或失败的提交途径。',@@ -113,8 +115,13 @@ export function registerSubmitGithubIssueTool(title: z.string().min(8).max(120).describe(D_TITLE),body: z.string().min(20).max(4000).describe(D_BODY),type: z.enum(['bug', 'feature']).describe(D_TYPE),+ include_related_logs: z+ .boolean()+ .optional()+ .default(false)+ .describe('仅在用户明确同意公开脱敏相关日志后设为 true;否则保持 false。'),},- handler: async ({ title, body, type }) => {+ handler: async ({ title, body, type, include_related_logs }) => {const ctx = deps.getSessionContext();if (!ctx.sessionId) {return errorPayload(@@ -130,6 +137,7 @@ export function registerSubmitGithubIssueTool(title: title.trim(),body: body.trim(),type,+ ...(include_related_logs ? { includeRelatedLogs: true } : {}),});if (!result.ok) {