Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(content-moderation): 完善审核流程与个人模型授权 (#243)
Liziac494388aee0
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 9e03c8e0e8..41fe30bfac 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -44,6 +44,7 @@"license": "Apache-2.0","dependencies": {"@cindy/auth-client": "workspace:*",+ "@cindy/content-moderation-protocol": "workspace:*","@cindy/slack-hook-protocol": "workspace:*","@codemirror/commands": "^6.10.3","@codemirror/lang-cpp": "^6.0.3",diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 29c24e9ebd..656744e988 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -14,6 +14,8 @@ const sourcePath = resolve(__dirname, '..', 'maker-ipc', 'register.ts');const source = readFileSync(sourcePath, 'utf8').replace(/\r\n?/g, '\n');const usageSourcePath = resolve(__dirname, '..', 'maker-ipc', 'usage.ts');const usageSource = readFileSync(usageSourcePath, 'utf8').replace(/\r\n?/g, '\n');+const turnRunnerSourcePath = resolve(__dirname, '..', 'im', 'shared', 'turnRunner.ts');+const turnRunnerSource = readFileSync(turnRunnerSourcePath, 'utf8').replace(/\r\n?/g, '\n');describe('maker:event hot path ordering', () => {it('broadcasts EVENT before usage/context/island/idle side effects', () => {@@ -132,10 +134,17 @@ describe('maker:event hot path ordering', () => {it('isolates Agent Island interaction updates after renderer delivery', () => {const interactionListenerSource = extractInstallDesktopInteractionListenerSource();+ const releaseBoundaryIndex = interactionListenerSource.indexOf(+ 'await waitForReleasedOutput(session.id);',+ );+ const flushIndex = interactionListenerSource.indexOf('flushAssistantBlock(session.id);');const broadcastIndex = interactionListenerSource.indexOf('broadcastToAllWindows(MAKER_PUSH.INTERACTION_REQUEST');const pendingIndex = interactionListenerSource.indexOf('pendingInteractionResolvers.set(req.requestId, entry);');const islandIndex = interactionListenerSource.indexOf('handleAgentIslandInteractionAfterBroadcast(');+ expect(releaseBoundaryIndex).toBeGreaterThanOrEqual(0);+ expect(flushIndex).toBeGreaterThan(releaseBoundaryIndex);+ expect(broadcastIndex).toBeGreaterThan(flushIndex);expect(broadcastIndex).toBeGreaterThanOrEqual(0);expect(pendingIndex).toBeGreaterThan(broadcastIndex);expect(islandIndex).toBeGreaterThan(pendingIndex);@@ -143,6 +152,25 @@ describe('maker:event hot path ordering', () => {expect(source).toContain('Agent Island interaction update failed after maker interaction broadcast');});+ it('waits for released output before sending an IM interaction card', () => {+ const start = turnRunnerSource.indexOf('function handleInteractionFor(');+ const end = turnRunnerSource.indexOf('async function finalizeActiveStream(', start);+ const interactionSource = turnRunnerSource.slice(start, end);+ const releaseBoundaryIndex = interactionSource.indexOf(+ 'await waitForReleasedOutput(localSessionId);',+ );+ const finalizeIndex = interactionSource.indexOf(+ 'await finalizeActiveStream(localSessionId);',+ );+ const sendIndex = interactionSource.indexOf('await im.sendInteractiveCard(');++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(releaseBoundaryIndex).toBeGreaterThanOrEqual(0);+ expect(finalizeIndex).toBeGreaterThan(releaseBoundaryIndex);+ expect(sendIndex).toBeGreaterThan(finalizeIndex);+ });+it('clears git snapshot coordinator state when sessions close', () => {const wireSessionSource = extractWireSessionSource();const closedBlock = wireSessionSource.slice(wireSessionSource.indexOf("if (status === 'closed') {"));diff --git a/apps/desktop/src/main/__tests__/profileEdit.test.ts b/apps/desktop/src/main/__tests__/profileEdit.test.tsindex 46f62ecd0f..c0acbcab53 100644--- a/apps/desktop/src/main/__tests__/profileEdit.test.ts+++ b/apps/desktop/src/main/__tests__/profileEdit.test.ts@@ -32,6 +32,7 @@ function makeDeps(overrides: Partial<ProfileEditDeps> = {}): {showAvatarOpenDialog: vi.fn(async () => null),readFile: vi.fn(async () => Buffer.from([1, 2, 3])),uploadAvatar: vi.fn(async () => ({ ok: true as const, publicUrl: PUBLIC_URL })),+ moderateProfile: vi.fn(async () => 'allow' as const),patchProfile: vi.fn(async (patch: ProfilePatch) => {patches.push(patch);return { ok: true as const };@@ -103,9 +104,16 @@ describe('名字收敛(留空 / 与当前一致 = 不改名)', () => {});describe('头像三态', () => {- it('set:读文件 → OSS 直传 → PATCH avatarUrl=publicUrl', async () => {+ it('set:读文件 → 私有审核 → OSS 直传 → PATCH avatarUrl=publicUrl', async () => {const { deps, patches } = makeDeps();await updateProfile(deps, { name: null, avatar: { type: 'set', filePath: 'C:\\pics\\me.PNG' } });+ expect(deps.moderateProfile).toHaveBeenCalledWith({+ avatar: {+ bytes: expect.any(Buffer),+ fileName: 'me.PNG',+ mimeType: 'image/png',+ },+ });expect(deps.uploadAvatar).toHaveBeenCalledWith({buffer: expect.any(Buffer),mimeType: 'image/png',@@ -116,9 +124,42 @@ describe('头像三态', () => {it('set + 改名:一次 PATCH 同时带两个字段', async () => {const { deps, patches } = makeDeps();await updateProfile(deps, { name: 'Lizi', avatar: { type: 'set', filePath: '/a/b.webp' } });+ expect(deps.moderateProfile).toHaveBeenCalledWith({+ displayName: 'Lizi',+ avatar: {+ bytes: expect.any(Buffer),+ fileName: 'b.webp',+ mimeType: 'image/webp',+ },+ });expect(patches).toEqual([{ displayName: 'Lizi', avatarUrl: PUBLIC_URL }]);});+ it('昵称或头像被审核拒绝:不公开上传且不 PATCH', async () => {+ const { deps } = makeDeps({+ moderateProfile: vi.fn(async () => 'reject' as const),+ });+ await expect(+ updateProfile(deps, {+ name: 'Rejected',+ avatar: { type: 'set', filePath: '/a/b.png' },+ }),+ ).rejects.toSatisfy((e) => ipcCode(e) === 'CONTENT_MODERATION_REJECTED');+ expect(deps.uploadAvatar).not.toHaveBeenCalled();+ expect(deps.patchProfile).not.toHaveBeenCalled();+ });++ it('审核期间身份切换:保存取消且不产生正式副作用', async () => {+ const { deps } = makeDeps({+ moderateProfile: vi.fn(async () => 'cancelled' as const),+ });+ await expect(+ updateProfile(deps, { name: 'Lizi', avatar: { type: 'keep' } }),+ ).rejects.toSatisfy((e) => ipcCode(e) === 'CONTENT_MODERATION_CANCELLED');+ expect(deps.uploadAvatar).not.toHaveBeenCalled();+ expect(deps.patchProfile).not.toHaveBeenCalled();+ });+it('reset:PATCH avatarUrl=null(清除自定义头像)', async () => {const { deps, patches } = makeDeps();await updateProfile(deps, { name: null, avatar: { type: 'reset' } });diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 12c02a6f25..3b3d24cca1 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -1078,6 +1078,14 @@ export function getAccessToken(): string | null {return accessToken;}+/**+ * Monotonic identity boundary for account-scoped asynchronous work.+ * Callers must compare the value again before committing a reviewed mutation.+ */+export function getAuthIdentityEpoch(): number {+ return authStateEpoch;+}+/** SkillHub v0.2.1: 返回当前登录用户 id(cuid),未登录时返回 null */export function getCurrentUserId(): string | null {return currentUser?.id ?? null;diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 67c8a021a6..7f4c2b6285 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -150,6 +150,12 @@ import * as authManager from './authManager';import { hasPersistedSessionHint } from './authSessionHint';import { createAccountDeletionIpcHandlers } from './accountDeletionIpc';import * as profileEdit from './profileEdit';+import { moderateProfileUpdate } from './content-moderation/profile.js';+import {+ moderateUserPrompt,+ validateUserPromptReviewValue,+} from './content-moderation/userPrompt.js';+import { cancelAllReleasedOutputs } from './content-moderation/outputHub.js';import { uploadPublicAsset } from './ossPublicUpload';import { removeRefs as removeMediaRefs } from './cindy-media/ledger';import { installWebviewHardener } from './webview-security';@@ -2292,6 +2298,7 @@ const createWindow = () => {let disposeSkillhubAutoSyncAuthListener: (() => void) | null = null;let disposeProviderAccessAuthListener: (() => void) | null = null;+let disposeContentModerationAuthListener: (() => void) | null = null;const registerIpcHandlers = () => {// Find the primary app window, skipping transient utility BrowserWindows like@@ -3341,6 +3348,12 @@ const registerIpcHandlers = () => {accountDeletionHandlers.consumeRestoredNotice(),);+ ipcMain.handle('content-moderation:review-user-prompt', async (event, value: unknown) => {+ assertTrustedAppRendererEvent(event);+ validateUserPromptReviewValue(value);+ return moderateUserPrompt(value);+ });+// ── Profile 编辑 IPC(设置 → 用户卡片编辑;业务体在 profileEdit.ts,// 资料直写 auth-server,头像经 oss-server 预签名直传) ──@@ -3370,6 +3383,7 @@ const registerIpcHandlers = () => {}return result;},+ moderateProfile: (input) => moderateProfileUpdate(input),patchProfile: (patch) => authManager.updateServerProfile(patch),logWarn: (message, err) => profileEditLog.warn(message, err),};@@ -4034,6 +4048,13 @@ const registerIpcHandlers = () => {disposeProviderAccessAuthListener = authManager.onAuthStateChange(() => {refreshProviderAccessAfterAuthChange();});+ let moderationAuthEpoch = authManager.getAuthIdentityEpoch();+ disposeContentModerationAuthListener = authManager.onAuthStateChange(() => {+ const nextEpoch = authManager.getAuthIdentityEpoch();+ if (nextEpoch === moderationAuthEpoch) return;+ moderationAuthEpoch = nextEpoch;+ cancelAllReleasedOutputs();+ });// ── Dialog: 目录选择器(v0.6 新增,与旧 show-open-directory-dialog 并存) ──ipcMain.handle(@@ -5522,6 +5543,8 @@ onQuit(() => {disposeProviderAccessAuthListener?.();disposeProviderAccessAuthListener = null;+ disposeContentModerationAuthListener?.();+ disposeContentModerationAuthListener = null;},'sync',);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/assistantReplyHook.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/assistantReplyHook.test.tsindex 097bec029a..3eedbb69f3 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/assistantReplyHook.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/assistantReplyHook.test.ts@@ -20,6 +20,7 @@ function makeDeps(overrides: Partial<AssistantReplyHookDeps> = {}) {hasHook: () => true,isEligible: async () => true,screen: async (): Promise<GhostAssistantScreenResult> => ({ action: 'allow' }),+ approveReplacement: async () => true,persistRewrite: calls.persistRewrite,applyRenderCard: calls.applyRenderCard,broadcastRewritten: calls.broadcastRewritten,@@ -83,6 +84,16 @@ describe('runAssistantReplyHook', () => {expect(calls.setPending).toHaveBeenLastCalledWith('s1', 'c1', false);});+ it('rewrite 二次审核不通过时保留已审核原文', async () => {+ const { deps, calls } = makeDeps({+ screen: async () => ({ action: 'rewrite', ghostId: 'g', ghostName: '意识', text: '未通过' }),+ approveReplacement: async () => false,+ });+ await runAssistantReplyHook(deps, 's1', 'c1', '原文');+ expect(calls.persistRewrite).not.toHaveBeenCalled();+ expect(calls.broadcastRewritten).not.toHaveBeenCalled();+ });+it('render:落自绘卡(净化/广播在 applyRenderCard 内),pending 收尾', async () => {const { deps, calls } = makeDeps({screen: async () => ({@@ -105,6 +116,21 @@ describe('runAssistantReplyHook', () => {expect(calls.setPending).toHaveBeenLastCalledWith('s1', 'c1', false);});+ it('render 二次审核不通过时不落自绘卡', async () => {+ const { deps, calls } = makeDeps({+ screen: async () => ({+ action: 'render',+ ghostId: 'g',+ ghostName: '意识',+ html: '<div>未通过</div>',+ text: '原文',+ }),+ approveReplacement: async () => false,+ });+ await runAssistantReplyHook(deps, 's1', 'c1', '原文');+ expect(calls.applyRenderCard).not.toHaveBeenCalled();+ });+it('screen 抛错:吞掉,pending 仍被关闭(finally)', async () => {const { deps, calls } = makeDeps({screen: async () => {diff --git a/apps/desktop/src/main/cindy-brain/assistantReplyHook.ts b/apps/desktop/src/main/cindy-brain/assistantReplyHook.tsindex f23c73d49e..e9ecd6ba2a 100644--- a/apps/desktop/src/main/cindy-brain/assistantReplyHook.ts+++ b/apps/desktop/src/main/cindy-brain/assistantReplyHook.ts@@ -31,6 +31,8 @@ export interface AssistantReplyHookDeps {isEligible(sessionId: string): Promise<boolean>;/** 网关串行链式裁决(allow/rewrite/render)。 */screen(sessionId: string, text: string): Promise<GhostAssistantScreenResult>;+ /** 对 hook 新生成的最终可见文本做二次输出审核。 */+ approveReplacement(sessionId: string, clientId: string, text: string): Promise<boolean>;/** rewrite:用改写正文覆盖该 assistant 消息内容(落库)。 */persistRewrite(sessionId: string, clientId: string, text: string): Promise<void>;/**@@ -74,6 +76,7 @@ export async function runAssistantReplyHook(try {const result = await deps.screen(sessionId, text);if (result.action === 'rewrite') {+ if (!(await deps.approveReplacement(sessionId, clientId, result.text))) return;await deps.persistRewrite(sessionId, clientId, result.text);deps.broadcastRewritten({sessionId,@@ -83,6 +86,7 @@ export async function runAssistantReplyHook(text: result.text,});} else if (result.action === 'render') {+ if (!(await deps.approveReplacement(sessionId, clientId, result.html))) return;await deps.applyRenderCard(sessionId, clientId, {ghostId: result.ghostId,ghostName: result.ghostName,diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 775a6450bf..a90f635a45 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -99,6 +99,7 @@ import { sanitizeGhostCardHtml } from './cardSanitizer.js';import { getGhostCard, listGhostCardsBySession, reassignGhostCards, updateGhostCardHeight, upsertGhostCard } from './cardStoreDb.js';import { updateMessageContent } from '../localDb/ipc/messages.js';import { runAssistantReplyHook } from './assistantReplyHook.js';+import { reviewPostProcessedOutput } from '../content-moderation/postProcessedOutput.js';import { GATEWAY_IMAGE_MODELS, GATEWAY_VIDEO_MODELS } from '../cindy-proxy-media/types.js';import { submitAndAwaitVideo } from '../cindy-proxy-media/video/run.js';@@ -1017,6 +1018,11 @@ export function runGhostAssistantReplyHook(sessionId: string, clientId: string,hasHook: hasEnabledGhostAssistantHook,isEligible: async (sid) => (await isGhostEligibleSession(sid)).outcome === 'eligible',screen: (sid, t) => getGhostSubscriptionGateway().screenAssistantMessage({ sessionId: sid, text: t }),+ approveReplacement: (sid, cid, replacement) => reviewPostProcessedOutput(+ sid,+ `ghost:${cid}`,+ replacement,+ ),persistRewrite: async (sid, cid, t) => {await updateMessageContent(sid, cid, t);},diff --git a/apps/desktop/src/main/content-moderation/__tests__/client.test.ts b/apps/desktop/src/main/content-moderation/__tests__/client.test.tsnew file mode 100644index 0000000000..4ca091bbe1--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/client.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it, vi } from 'vitest';+import { ModerationClient } from '../client.js';++function response(body: unknown, status: number): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });+}++const reviewInput = {+ signBaseUrl: 'https://sign.example.com',+ accessToken: 'access-token',+ membershipId: 'member-1',+ businessCode: 'maker-nickname' as const,+ dataId: 'profile-nickname:member-1:mutation-1',+ items: [{ type: 'TEXT' as const, data: 'Alice', content_id: 'mutation-1:text:0' }],+ deadlineMs: 5_000,+};++function signedResponse() {+ return response({+ gateway_base_url: 'https://moderation.example.com/gateway',+ logical_path: '/api/v1/review/submit',+ headers: {+ Authorization: 'short-lived-hmac',+ 'X-Timestamp': '1700000000',+ 'X-Nonce': '00112233445566778899aabbccddeeff',+ 'Content-Type': 'application/json',+ },+ }, 200);+}++describe('ModerationClient', () => {+ it('queries once per second and rejects only an explicit status 3', async () => {+ vi.useFakeTimers();+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(signedResponse())+ .mockResolvedValueOnce(response({+ code: 200,+ data: { task_token: 'task-token', status: 1 },+ }, 201))+ .mockResolvedValueOnce(response({ code: 200, data: { status: 1 } }, 200))+ .mockResolvedValueOnce(response({ code: 200, data: { status: 3 } }, 200));+ const promise = new ModerationClient(fetchMock as typeof fetch).review(reviewInput);+ await vi.advanceTimersByTimeAsync(2_000);+ await expect(promise).resolves.toBe('reject');+ expect(fetchMock).toHaveBeenCalledTimes(4);+ expect(fetchMock.mock.calls[2]?.[0]).toBe(+ 'https://moderation.example.com/gateway/api/v1/review/tasks',+ );+ expect(fetchMock.mock.calls[2]?.[1]).toMatchObject({+ method: 'GET',+ headers: { Authorization: 'Bearer task-token' },+ });+ vi.useRealTimers();+ });++ it.each([+ ['approved', 2],+ ['manual-required', 4],+ ])('allows immediate %s submit status', async (_label, status) => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(signedResponse())+ .mockResolvedValueOnce(response({+ code: 200,+ data: { task_token: 'task-token', status },+ }, 201));+ await expect(+ new ModerationClient(fetchMock as typeof fetch).review(reviewInput),+ ).resolves.toBe('allow');+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('fails open on malformed responses and unknown status', async () => {+ const malformed = vi.fn().mockResolvedValue(response({ nope: true }, 200));+ await expect(+ new ModerationClient(malformed as typeof fetch).review(reviewInput),+ ).resolves.toBe('allow');++ const unknown = vi.fn()+ .mockResolvedValueOnce(signedResponse())+ .mockResolvedValueOnce(response({+ code: 200,+ data: { task_token: 'task-token', status: 9 },+ }, 201));+ await expect(+ new ModerationClient(unknown as typeof fetch).review(reviewInput),+ ).resolves.toBe('allow');+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/eligibility.test.ts b/apps/desktop/src/main/content-moderation/__tests__/eligibility.test.tsnew file mode 100644index 0000000000..281568f2e9--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/eligibility.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';+import { resolveModerationIdentity } from '../eligibility.js';++const base = {+ isPackaged: true,+ region: 'cn' as const,+ commandLineEnabled: false,+ membershipKind: 'personal' as const,+ membershipId: 'member-1',+ accessToken: 'access-token',+ identityEpoch: 7,+ productionSignBaseUrl: 'https://sign.example.com',+ testSignBaseUrl: 'https://test-sign.example.com',+};++describe('content moderation eligibility', () => {+ it('enables packaged cn personal users without consulting the dev switch', () => {+ expect(resolveModerationIdentity(base)).toMatchObject({+ environment: 'production',+ signBaseUrl: 'https://sign.example.com',+ });+ });++ it('bypasses org, logged-out, and packaged global users', () => {+ expect(resolveModerationIdentity({ ...base, membershipKind: 'org' })).toBeNull();+ expect(resolveModerationIdentity({ ...base, accessToken: null })).toBeNull();+ expect(resolveModerationIdentity({ ...base, region: 'global' })).toBeNull();+ });++ it('requires the switch and the separate test endpoint for every dev shape', () => {+ expect(resolveModerationIdentity({ ...base, isPackaged: false })).toBeNull();+ expect(resolveModerationIdentity({+ ...base,+ isPackaged: false,+ commandLineEnabled: true,+ })).toMatchObject({+ environment: 'test',+ signBaseUrl: 'https://test-sign.example.com',+ });+ expect(resolveModerationIdentity({+ ...base,+ region: 'dev',+ commandLineEnabled: true,+ })).toMatchObject({ environment: 'test' });+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/input.test.ts b/apps/desktop/src/main/content-moderation/__tests__/input.test.tsnew file mode 100644index 0000000000..642abc8628--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/input.test.ts@@ -0,0 +1,141 @@+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { ModerationClient } from '../client.js';++const {+ getModerationIdentity,+ isModerationIdentityCurrent,+ resolveCindyMediaUrl,+ resolveLegacyImageUrl,+} = vi.hoisted(() => ({+ getModerationIdentity: vi.fn(),+ isModerationIdentityCurrent: vi.fn(),+ resolveCindyMediaUrl: vi.fn(),+ resolveLegacyImageUrl: vi.fn(),+}));++vi.mock('../identity.js', () => ({+ getModerationIdentity,+ isModerationIdentityCurrent,+}));++vi.mock('../../cindy-media/blobStore.js', () => ({+ resolveSafe: resolveCindyMediaUrl,+}));++vi.mock('../../imageCacheStore.js', () => ({+ resolveSafe: resolveLegacyImageUrl,+}));++import { moderateAgentInput } from '../input.js';++function queuedImage(+ file: NonNullable<AgentInputQueuedMessage['files']>[number],+): AgentInputQueuedMessage {+ return {+ clientId: 'client-1',+ text: '',+ persistedContent: JSON.stringify({ text: '', images: [], files: [] }),+ model: 'gpt-5.4-mini',+ effort: 'medium',+ permissionMode: 'ask',+ workingDir: 'C:\\workspace',+ files: [file],+ chatMessage: {+ clientId: 'client-1',+ role: 'user',+ content: '',+ },+ createOpts: {+ agentKind: 'codex',+ workingDir: 'C:\\workspace',+ model: 'gpt-5.4-mini',+ },+ };+}++function fakeClient() {+ const uploadLocalImage = vi.fn(async () => 'xdmoderation://uploaded/local');+ const uploadImageBytes = vi.fn(async () => 'xdmoderation://uploaded/bytes');+ const review = vi.fn(async () => 'allow' as const);+ return {+ client: { uploadLocalImage, uploadImageBytes, review } as unknown as ModerationClient,+ uploadLocalImage,+ uploadImageBytes,+ review,+ };+}++describe('moderateAgentInput image projection', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getModerationIdentity.mockReturnValue({+ membershipId: 'member-1',+ accessToken: 'access-token',+ identityEpoch: 1,+ signBaseUrl: 'https://sign.example.invalid',+ environment: 'test',+ });+ isModerationIdentityCurrent.mockReturnValue(true);+ });++ it('uploads an attachment-only base64 image and reviews it as maker-input-t2t', async () => {+ const fixture = fakeClient();+ const raw = Buffer.from('png-bytes');++ await expect(moderateAgentInput('session-1', queuedImage({+ id: 'image-1',+ name: 'paste.png',+ path: 'clipboard://paste-1',+ ext: '.png',+ size: raw.byteLength,+ category: 'image',+ mimeType: 'image/png',+ base64: raw.toString('base64'),+ originalName: 'screenshot.png',+ }), fixture.client)).resolves.toBe('allow');++ expect(fixture.uploadImageBytes).toHaveBeenCalledWith(expect.objectContaining({+ bytes: raw,+ fileName: 'screenshot.png',+ mimeType: 'image/png',+ }));+ expect(fixture.uploadLocalImage).not.toHaveBeenCalled();+ expect(fixture.review).toHaveBeenCalledWith(expect.objectContaining({+ businessCode: 'maker-input-t2t',+ items: [{+ type: 'IMAGE',+ data: 'xdmoderation://uploaded/bytes',+ content_id: 'client-1:image:0',+ }],+ }));+ });++ it('resolves a managed cindy-media image before uploading it', async () => {+ const fixture = fakeClient();+ resolveCindyMediaUrl.mockReturnValue({+ absPath: 'C:\\user-data\\cindy-media\\blobs\\image.png',+ mimeType: 'image/png',+ });++ await moderateAgentInput('session-1', queuedImage({+ id: 'image-2',+ name: 'paste.png',+ path: 'clipboard://paste-2',+ url: 'cindy-media://blobs/abcdef.png',+ ext: '.png',+ size: 10,+ category: 'image',+ mimeType: 'image/png',+ }), fixture.client);++ expect(resolveCindyMediaUrl).toHaveBeenCalledWith('cindy-media://blobs/abcdef.png');+ expect(fixture.uploadLocalImage).toHaveBeenCalledWith(expect.objectContaining({+ filePath: 'C:\\user-data\\cindy-media\\blobs\\image.png',+ }));+ expect(fixture.review).toHaveBeenCalledWith(expect.objectContaining({+ businessCode: 'maker-input-t2t',+ items: [expect.objectContaining({ type: 'IMAGE' })],+ }));+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/notifications.test.ts b/apps/desktop/src/main/content-moderation/__tests__/notifications.test.tsnew file mode 100644index 0000000000..93e549ee98--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/notifications.test.ts@@ -0,0 +1,58 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { getAllWindows, tapWindowBroadcast } = vi.hoisted(() => ({+ getAllWindows: vi.fn(),+ tapWindowBroadcast: vi.fn(),+}));++vi.mock('electron', () => ({+ BrowserWindow: { getAllWindows },+}));+vi.mock('../../device-link/broadcast-tap.js', () => ({+ tapWindowBroadcast,+}));++import {+ CONTENT_MODERATION_INPUT_BLOCKED_CHANNEL,+ broadcastModerationInputBlocked,+} from '../notifications.js';++describe('broadcastModerationInputBlocked', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getAllWindows.mockReturnValue([]);+ });++ it('同时通知本机 renderer 和 device-link 控制端', () => {+ const send = vi.fn();+ getAllWindows.mockReturnValue([+ {+ isDestroyed: () => false,+ webContents: { send },+ },+ ]);++ broadcastModerationInputBlocked({+ sessionId: 'session-1',+ item: {+ clientId: 'client-1',+ text: 'blocked input',+ files: [],+ } as never,+ reason: 'rejected',+ });++ const payload = {+ sessionId: 'session-1',+ clientId: 'client-1',+ text: 'blocked input',+ files: [],+ reason: 'rejected',+ };+ expect(tapWindowBroadcast).toHaveBeenCalledWith(+ CONTENT_MODERATION_INPUT_BLOCKED_CHANNEL,+ payload,+ );+ expect(send).toHaveBeenCalledWith(CONTENT_MODERATION_INPUT_BLOCKED_CHANNEL, payload);+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/output.test.ts b/apps/desktop/src/main/content-moderation/__tests__/output.test.tsnew file mode 100644index 0000000000..155fa4f5e5--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/output.test.ts@@ -0,0 +1,449 @@+import type { AgentEvent } from '@cindy/maker-core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { StreamModerationClient, StreamModerationCallbacks } from '../streamClient.js';++const {+ getModerationIdentity,+ isModerationIdentityCurrent,+} = vi.hoisted(() => ({+ getModerationIdentity: vi.fn(),+ isModerationIdentityCurrent: vi.fn(),+}));++vi.mock('../identity.js', () => ({+ getModerationIdentity,+ isModerationIdentityCurrent,+}));++import { OutputModerationGate } from '../output.js';+import { CONTENT_MODERATION_BLOCKED_MESSAGE } from '../constants.js';++function text(value: string, isFinal = false): AgentEvent {+ return { type: 'text', data: { text: value, isFinal }, source: 'codex' };+}++function done(result: string): AgentEvent {+ return { type: 'done', data: { result }, source: 'codex' };+}++function status(isRunning: boolean): AgentEvent {+ return { type: 'status', data: { isRunning }, source: 'codex' };+}++function fakeStreamFactory() {+ let callbacks: StreamModerationCallbacks | null = null;+ let nextSequence = 0;+ const stream = {+ push: vi.fn(() => nextSequence++),+ finish: vi.fn(),+ cancel: vi.fn(),+ } as unknown as StreamModerationClient;+ const createStream = vi.fn(async (_input, cb: StreamModerationCallbacks) => {+ callbacks = cb;+ return stream;+ });+ return {+ createStream,+ stream,+ callbacks: () => {+ if (!callbacks) throw new Error('stream callbacks not installed');+ return callbacks;+ },+ };+}++async function flushStartup(): Promise<void> {+ await Promise.resolve();+ await Promise.resolve();+}++describe('OutputModerationGate', () => {+ beforeEach(() => {+ getModerationIdentity.mockReturnValue({+ membershipId: 'member-1',+ accessToken: 'token',+ identityEpoch: 1,+ signBaseUrl: 'https://sign.example.invalid',+ environment: 'test',+ });+ isModerationIdentityCurrent.mockReturnValue(true);+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ it('只向下游释放连续安全正文,并把终态挡到 task.completed', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('raw'));+ gate.handle(text('raw', true));+ gate.handle(status(false));+ gate.handle(done('raw-unreviewed-result'));+ await flushStartup();++ expect(factory.stream.push).toHaveBeenCalledTimes(1);+ expect(factory.stream.finish).toHaveBeenCalledTimes(1);+ expect(delivered).toEqual([]);++ factory.callbacks().onRelease({ sequence: 0, text: 'safe' });+ expect(delivered.map((event) => event.type)).toEqual(['text', 'text']);+ expect(delivered.map((event) => (event.data as { text?: string }).text)).toEqual([+ 'safe',+ 'safe',+ ]);++ factory.callbacks().onCompleted();+ expect(delivered.map((event) => event.type)).toEqual([+ 'text',+ 'text',+ 'status',+ 'done',+ ]);+ expect((delivered.at(-1)?.data as { result?: string }).result).toBe('safe');+ });++ it('content.block 丢弃未 release 正文,发临时信号并用安全结果收尾', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const abortTurn = vi.fn(async () => undefined);+ const onBlocked = vi.fn();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn,+ onBlocked,+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('first'));+ gate.handle(text('blocked'));+ await flushStartup();+ factory.callbacks().onRelease({ sequence: 0, text: 'first-safe' });+ factory.callbacks().onBlock();++ expect(delivered.map((event) => event.type)).toEqual(['text', 'done']);+ expect((delivered[1]?.data as { result?: string }).result).toBe(+ `first-safe\n\n${CONTENT_MODERATION_BLOCKED_MESSAGE}`,+ );+ expect(JSON.stringify(delivered)).not.toContain('blocked');+ expect(onBlocked).toHaveBeenCalledTimes(1);+ expect(abortTurn).toHaveBeenCalledTimes(1);++ gate.handle(text('late-abort-text'));+ gate.handle(done('late-raw-result'));+ expect(JSON.stringify(delivered)).not.toContain('late');+ });++ it('content.block 在零安全输出时持久化阻断说明', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('blocked-before-release'));+ await flushStartup();+ factory.callbacks().onBlock();++ expect(delivered).toHaveLength(1);+ expect(delivered[0]?.type).toBe('done');+ expect(delivered[0]?.data).toMatchObject({+ result: CONTENT_MODERATION_BLOCKED_MESSAGE,+ contentModerationBlocked: true,+ });+ expect(JSON.stringify(delivered)).not.toContain('blocked-before-release');+ });++ it('task.failed 是明确失败终态,不走 fail-open', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const onFailed = vi.fn();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed,+ createStream: factory.createStream,+ });++ gate.handle(text('raw'));+ await flushStartup();+ factory.callbacks().onFailed();++ expect(delivered).toHaveLength(1);+ expect(delivered[0]?.type).toBe('error');+ expect(delivered[0]?.data).toMatchObject({+ reason: 'turn-failed',+ contentModerationFailed: true,+ isTerminal: true,+ });+ expect(onFailed).toHaveBeenCalledTimes(1);+ });++ it('用户停止时保留已 release 文本、丢弃缓冲,并用安全 done 收口', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('safe-raw'));+ gate.handle(text('pending-raw'));+ await flushStartup();+ factory.callbacks().onRelease({ sequence: 0, text: 'safe' });+ gate.cancel();+ gate.handle({+ type: 'error',+ data: { message: 'aborted', isTerminal: true },+ source: 'codex',+ });++ expect(delivered.map((event) => event.type)).toEqual(['text', 'done']);+ expect((delivered[1]?.data as { result?: string }).result).toBe('safe');+ expect(JSON.stringify(delivered)).not.toContain('pending-raw');+ });++ it('创建链路超过 5 秒时 fail-open,且 done.result 使用已直出的正文', async () => {+ vi.useFakeTimers();+ const delivered: AgentEvent[] = [];+ let resolveCreate: (value: StreamModerationClient | null) => void = () => undefined;+ const createStream = vi.fn(() => new Promise<StreamModerationClient | null>((resolve) => {+ resolveCreate = resolve;+ }));+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream,+ });++ gate.handle(text('raw'));+ gate.handle(done('unreviewed-result'));+ await vi.advanceTimersByTimeAsync(5_000);++ expect(delivered.map((event) => event.type)).toEqual(['text', 'done']);+ expect((delivered[1]?.data as { result?: string }).result).toBe('raw');+ resolveCreate(null);+ await flushStartup();+ });++ it('无审核资格时完全透传,不创建流任务', () => {+ getModerationIdentity.mockReturnValue(null);+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('plain'));+ gate.handle(done('plain'));+ expect(delivered.map((event) => event.type)).toEqual(['text', 'done']);+ expect(factory.createStream).not.toHaveBeenCalled();+ });++ it('取消后的 status:false 不会吞掉随后用于持久化收口的 done', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('raw'));+ await flushStartup();+ factory.callbacks().onRelease({ sequence: 0, text: 'safe' });+ gate.cancel();+ gate.handle(status(false));+ gate.handle(done('raw'));++ expect(delivered.map((event) => event.type)).toEqual(['text', 'status', 'done']);+ expect((delivered.at(-1)?.data as { result?: string }).result).toBe('safe');+ });++ it('已在终态事件上完成 fail-open 后会 reset,下一 turn 重新审核', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('raw'));+ gate.handle(done('raw'));+ await flushStartup();+ factory.callbacks().onRelease({ sequence: 0, text: 'raw' });+ factory.callbacks().onFailOpen();++ gate.handle(status(true));+ await flushStartup();+ expect(factory.createStream).toHaveBeenCalledTimes(2);+ });++ it('turn 启动状态即绑定审核身份,尚无正文时也可被账号切换取消', async () => {+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: vi.fn(),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(status(true));+ await flushStartup();+ expect(gate.cancel()).toBe(true);+ expect(factory.stream.cancel).toHaveBeenCalledTimes(1);+ });++ it('空的 final text 不创建无意义审核任务', () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('', true));+ expect(delivered).toHaveLength(1);+ expect(factory.createStream).not.toHaveBeenCalled();+ });++ it('interaction boundary waits only for output queued before it', async () => {+ const delivered: AgentEvent[] = [];+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('before'));+ await flushStartup();+ let boundaryReleased = false;+ const boundary = gate.waitForReleaseBoundary().then(() => {+ boundaryReleased = true;+ });+ gate.handle(text('after'));++ factory.callbacks().onRelease({ sequence: 0, text: 'safe-before' });+ await boundary;++ expect(boundaryReleased).toBe(true);+ expect(delivered).toHaveLength(1);+ expect((delivered[0]?.data as { text?: string }).text).toBe('safe-before');+ expect(JSON.stringify(delivered)).not.toContain('after');+ });++ it('interaction boundary queued during startup preserves event order', async () => {+ const delivered: AgentEvent[] = [];+ let callbacks: StreamModerationCallbacks | null = null;+ let resolveCreate: (stream: StreamModerationClient) => void = () => undefined;+ const stream = {+ push: vi.fn()+ .mockReturnValueOnce(0)+ .mockReturnValueOnce(1),+ finish: vi.fn(),+ cancel: vi.fn(),+ } as unknown as StreamModerationClient;+ const createStream = vi.fn((_input, cb: StreamModerationCallbacks) => {+ callbacks = cb;+ return new Promise<StreamModerationClient>((resolve) => {+ resolveCreate = resolve;+ });+ });+ const installedCallbacks = (): StreamModerationCallbacks => {+ if (!callbacks) throw new Error('stream callbacks not installed');+ return callbacks;+ };+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: (event) => delivered.push(event),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream,+ });++ gate.handle(text('before'));+ let boundaryReleased = false;+ const boundary = gate.waitForReleaseBoundary().then(() => {+ boundaryReleased = true;+ });+ gate.handle(text('after'));+ resolveCreate(stream);+ await flushStartup();++ expect(boundaryReleased).toBe(false);+ installedCallbacks().onRelease({ sequence: 0, text: 'safe-before' });+ await boundary;++ expect(boundaryReleased).toBe(true);+ expect(delivered).toHaveLength(1);+ expect((delivered[0]?.data as { text?: string }).text).toBe('safe-before');+ });++ it('terminal moderation outcomes release pending interaction boundaries', async () => {+ const factory = fakeStreamFactory();+ const gate = new OutputModerationGate({+ sessionId: 'session-1',+ deliver: vi.fn(),+ abortTurn: vi.fn(async () => undefined),+ onBlocked: vi.fn(),+ onFailed: vi.fn(),+ createStream: factory.createStream,+ });++ gate.handle(text('pending'));+ await flushStartup();+ const boundary = gate.waitForReleaseBoundary();+ factory.callbacks().onBlock();++ await expect(boundary).resolves.toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/profile.test.ts b/apps/desktop/src/main/content-moderation/__tests__/profile.test.tsnew file mode 100644index 0000000000..b7502ad404--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/profile.test.ts@@ -0,0 +1,70 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { ModerationClient } from '../client.js';++const { getModerationIdentity, isModerationIdentityCurrent } = vi.hoisted(() => ({+ getModerationIdentity: vi.fn(),+ isModerationIdentityCurrent: vi.fn(),+}));++vi.mock('../identity.js', () => ({+ getModerationIdentity,+ isModerationIdentityCurrent,+}));++import { moderateProfileUpdate } from '../profile.js';++describe('moderateProfileUpdate', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getModerationIdentity.mockReturnValue({+ membershipId: 'u1',+ accessToken: 'token',+ identityEpoch: 1,+ signBaseUrl: 'https://sign.example.invalid',+ environment: 'test',+ });+ isModerationIdentityCurrent.mockReturnValue(true);+ });++ it('先把本地头像字节上传到审核网关,再用 maker-avatar 审核', async () => {+ const bytes = new Uint8Array([1, 2, 3]);+ const uploadImageBytes = vi.fn(async () => 'xdmoderation://uploaded/avatar');+ const review = vi.fn(async () => 'allow' as const);+ const client = { uploadImageBytes, review } as unknown as ModerationClient;++ await expect(+ moderateProfileUpdate(+ {+ avatar: {+ bytes,+ fileName: 'avatar.png',+ mimeType: 'image/png',+ },+ },+ client,+ ),+ ).resolves.toBe('allow');++ expect(uploadImageBytes).toHaveBeenCalledWith(+ expect.objectContaining({+ bytes,+ fileName: 'avatar.png',+ mimeType: 'image/png',+ }),+ );+ expect(review).toHaveBeenCalledWith(+ expect.objectContaining({+ businessCode: 'maker-avatar',+ items: [+ expect.objectContaining({+ type: 'IMAGE',+ data: 'xdmoderation://uploaded/avatar',+ }),+ ],+ }),+ );+ expect(uploadImageBytes.mock.invocationCallOrder[0]).toBeLessThan(+ review.mock.invocationCallOrder[0]!,+ );+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/streamClient.test.ts b/apps/desktop/src/main/content-moderation/__tests__/streamClient.test.tsnew file mode 100644index 0000000000..f68dda8656--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/streamClient.test.ts@@ -0,0 +1,313 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ StreamModerationClient,+ type StreamModerationCallbacks,+} from '../streamClient.js';++function json(body: unknown, status: number): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });+}++function createHarness() {+ let sseController: ReadableStreamDefaultController<Uint8Array> | null = null;+ const inputBodies: string[] = [];+ const encoder = new TextEncoder();+ const events = new ReadableStream<Uint8Array>({+ start(controller) {+ sseController = controller;+ },+ });+ const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ const target = String(url);+ if (target.endsWith('/api/moderation/sign/json')) {+ return json({+ gateway_base_url: 'https://gateway.example.invalid',+ logical_path: '/api/v1/review/stream/tasks',+ headers: {+ Authorization: 'signed',+ 'X-Timestamp': '1700000000',+ 'X-Nonce': 'nonce',+ 'Content-Type': 'application/json',+ },+ }, 200);+ }+ if (target.endsWith('/api/v1/review/stream/tasks') && init?.method === 'POST') {+ return json({+ code: 200,+ data: {+ task_id: 'task-1',+ write_token: 'write-token',+ read_token: 'read-token',+ },+ }, 201);+ }+ if (target.endsWith('/events')) {+ return new Response(events, {+ status: 200,+ headers: { 'Content-Type': 'text/event-stream' },+ });+ }+ if (target.endsWith('/input')) {+ const reader = (init?.body as ReadableStream<Uint8Array>).getReader();+ const decoder = new TextDecoder();+ let body = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ body += decoder.decode(value, { stream: true });+ }+ inputBodies.push(body);+ const nextSequence = body.trim()+ ? body.trim().split('\n').length+ : 0;+ return json({ code: 200, data: { accepted: true, next_sequence: nextSequence } }, 200);+ }+ throw new Error(`unexpected fetch: ${target}`);+ });+ return {+ fetchMock,+ inputBodies,+ emit(event: string, data: unknown, id: string): void {+ sseController?.enqueue(encoder.encode(+ `id: ${id}\nevent: ${event}\ndata: ${JSON.stringify(data)}\n\n`,+ ));+ },+ emitRaw(value: string): void {+ sseController?.enqueue(encoder.encode(value));+ },+ closeEvents(): void {+ sseController?.close();+ },+ };+}++const createInput = {+ signBaseUrl: 'https://sign.example.invalid',+ accessToken: 'access-token',+ membershipId: 'member-1',+ sessionId: 'session-1',+ turnId: 'turn-1',+};++function callbacks() {+ return {+ onRelease: vi.fn(),+ onBlock: vi.fn(),+ onFailed: vi.fn(),+ onCompleted: vi.fn(),+ onFailOpen: vi.fn(),+ } satisfies StreamModerationCallbacks;+}++afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe('StreamModerationClient completion safety', () => {+ it('task.completed 作为整项通过终态,按 sequence 释放剩余缓冲', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('raw');+ client?.finish();+ harness.emit('task.completed', {}, 'completed');+ await vi.waitFor(() => expect(cb.onCompleted).toHaveBeenCalledTimes(1));+ expect(cb.onRelease).toHaveBeenCalledWith({ sequence: 0, text: 'raw' });+ expect(cb.onFailOpen).not.toHaveBeenCalled();+ harness.closeEvents();+ });++ it('task.completed 前已收到的安全 release 不会被原文覆盖', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('raw');+ client?.finish();+ harness.emit('content.release', { sequence: 0, text: 'safe' }, 'release');+ harness.emit('task.completed', {}, 'completed');++ await vi.waitFor(() => expect(cb.onCompleted).toHaveBeenCalledTimes(1));+ expect(cb.onRelease).toHaveBeenCalledWith({ sequence: 0, text: 'safe' });+ expect(cb.onFailOpen).not.toHaveBeenCalled();+ harness.closeEvents();+ });++ it('接受 final 空 frame 的 release,仅用它推进顺序而不下发正文', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('raw');+ client?.finish();++ // The real gateway may release the final frame before an earlier text+ // frame reaches the SSE consumer, so both ordering and invisibility matter.+ harness.emit('content.release', { sequence: 1, text: '' }, 'final-release');+ await Promise.resolve();+ expect(cb.onRelease).not.toHaveBeenCalled();+ expect(cb.onFailOpen).not.toHaveBeenCalled();++ harness.emit('content.release', { sequence: 0, text: 'safe' }, 'text-release');+ harness.emit('task.completed', {}, 'completed');++ await vi.waitFor(() => expect(cb.onCompleted).toHaveBeenCalledTimes(1));+ expect(cb.onRelease).toHaveBeenCalledTimes(1);+ expect(cb.onRelease).toHaveBeenCalledWith({ sequence: 0, text: 'safe' });+ expect(cb.onFailOpen).not.toHaveBeenCalled();+ harness.closeEvents();+ });++ it('拒绝携带正文的 final release 并安全 fail-open', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('raw');+ client?.finish();+ harness.emit('content.release', { sequence: 1, text: 'unexpected' }, 'bad-final');++ await vi.waitFor(() => expect(cb.onFailOpen).toHaveBeenCalledTimes(1));+ expect(cb.onRelease).toHaveBeenCalledTimes(1);+ expect(cb.onRelease).toHaveBeenCalledWith({ sequence: 0, text: 'raw' });+ harness.closeEvents();+ });++ it('finish 幂等,且 final 后拒绝继续 push', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ expect(client?.push('before')).toBe(0);+ client?.finish();+ client?.finish();+ expect(client?.push('after')).toBe(-1);++ await vi.waitFor(() => expect(harness.inputBodies).toHaveLength(1));+ expect(harness.inputBodies[0]?.trim().split('\n')).toHaveLength(2);+ client?.cancel();+ harness.closeEvents();+ });++ it('可解析跨网络 chunk 拆分的 CRLF', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('raw');+ harness.emitRaw('id: 1\r\nevent: content.release\r\ndata: {"sequence":0,"text":"safe"}\r');+ harness.emitRaw('\n\r\n');++ await vi.waitFor(() => expect(cb.onRelease).toHaveBeenCalledWith({+ sequence: 0,+ text: 'safe',+ }));+ client?.cancel();+ harness.closeEvents();+ });+});++describe('StreamModerationClient', () => {+ it('SSE 先建立,release 去重并按 sequence 连续释放', async () => {+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ expect(client).not.toBeNull();+ expect(String(harness.fetchMock.mock.calls[2]?.[0])).toContain('/events');++ client?.push('a');+ client?.push('b');+ harness.emit('content.release', { sequence: 1, text: 'B' }, '2');+ await Promise.resolve();+ expect(cb.onRelease).not.toHaveBeenCalled();++ harness.emit('content.release', { sequence: 0, text: 'A' }, '1');+ harness.emit('content.release', { sequence: 0, text: 'A' }, '1-duplicate');+ await vi.waitFor(() => expect(cb.onRelease).toHaveBeenCalledTimes(2));+ expect(cb.onRelease.mock.calls.map(([frame]) => frame)).toEqual([+ { sequence: 0, text: 'A' },+ { sequence: 1, text: 'B' },+ ]);++ client?.finish();+ await vi.waitFor(() => expect(harness.inputBodies).toHaveLength(1));+ expect(harness.inputBodies[0]?.trim().split('\n').map((line) => JSON.parse(line))).toEqual([+ { sequence: 0, text: 'a', is_final: false },+ { sequence: 1, text: 'b', is_final: false },+ { sequence: 2, text: '', is_final: true },+ ]);+ client?.cancel();+ harness.closeEvents();+ });++ it('最老未 release frame 等待 5 秒后 fail-open,并忽略迟到 block', async () => {+ vi.useFakeTimers();+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('raw');++ await vi.advanceTimersByTimeAsync(5_000);+ expect(cb.onRelease).toHaveBeenCalledWith({ sequence: 0, text: 'raw' });+ expect(cb.onFailOpen).toHaveBeenCalledTimes(1);++ harness.emit('content.block', { audited_through: 0 }, 'late');+ await Promise.resolve();+ expect(cb.onBlock).not.toHaveBeenCalled();+ harness.closeEvents();+ });++ it('首段 release 后为后续最老待审 frame 重新启动 5 秒 watchdog', async () => {+ vi.useFakeTimers();+ const harness = createHarness();+ const cb = callbacks();+ const client = await StreamModerationClient.create(+ createInput,+ cb,+ harness.fetchMock as typeof fetch,+ );+ client?.push('first');+ await vi.advanceTimersByTimeAsync(4_000);+ harness.emit('content.release', { sequence: 0, text: 'first-safe' }, '1');+ await Promise.resolve();+ client?.push('second');++ await vi.advanceTimersByTimeAsync(4_999);+ expect(cb.onFailOpen).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(cb.onFailOpen).toHaveBeenCalledTimes(1);+ expect(cb.onRelease).toHaveBeenLastCalledWith({ sequence: 1, text: 'second' });+ harness.closeEvents();+ });+});diff --git a/apps/desktop/src/main/content-moderation/__tests__/userPrompt.test.ts b/apps/desktop/src/main/content-moderation/__tests__/userPrompt.test.tsnew file mode 100644index 0000000000..7f4b9d7f5e--- /dev/null+++ b/apps/desktop/src/main/content-moderation/__tests__/userPrompt.test.ts@@ -0,0 +1,70 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { ModerationClient } from '../client.js';++const {+ getModerationIdentity,+ isModerationIdentityCurrent,+} = vi.hoisted(() => ({+ getModerationIdentity: vi.fn(),+ isModerationIdentityCurrent: vi.fn(),+}));++vi.mock('../identity.js', () => ({+ getModerationIdentity,+ isModerationIdentityCurrent,+}));++import {+ moderateUserPrompt,+ validateUserPromptReviewValue,+} from '../userPrompt.js';++describe('moderateUserPrompt', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getModerationIdentity.mockReturnValue({+ membershipId: 'u1',+ accessToken: 'token',+ identityEpoch: 1,+ signBaseUrl: 'https://sign.example.invalid',+ environment: 'test',+ });+ isModerationIdentityCurrent.mockReturnValue(true);+ });++ it('清空提示词直接放行,不请求审核', async () => {+ const client = new ModerationClient();+ const review = vi.spyOn(client, 'review');+ await expect(moderateUserPrompt(' ', client)).resolves.toBe('allow');+ expect(getModerationIdentity).not.toHaveBeenCalled();+ expect(review).not.toHaveBeenCalled();+ });++ it('使用 maker-sys-prompt 审核完整文本', async () => {+ const client = new ModerationClient();+ const review = vi.spyOn(client, 'review').mockResolvedValue('allow');+ await expect(moderateUserPrompt('Be concise.', client)).resolves.toBe('allow');+ expect(review).toHaveBeenCalledWith(expect.objectContaining({+ businessCode: 'maker-sys-prompt',+ membershipId: 'u1',+ items: [expect.objectContaining({ type: 'TEXT', data: 'Be concise.' })],+ }));+ });++ it('明确拒绝阻断;审核期间换号则作废结果', async () => {+ const client = new ModerationClient();+ vi.spyOn(client, 'review').mockResolvedValue('reject');+ await expect(moderateUserPrompt('blocked', client)).resolves.toBe('reject');++ isModerationIdentityCurrent.mockReturnValue(false);+ await expect(moderateUserPrompt('blocked', client)).resolves.toBe('cancelled');+ });+});++describe('validateUserPromptReviewValue', () => {+ it('拒绝非字符串和超过共享上限的文本', () => {+ expect(() => validateUserPromptReviewValue(null)).toThrowError();+ expect(() => validateUserPromptReviewValue('a'.repeat(8_001))).toThrowError();+ expect(() => validateUserPromptReviewValue('a'.repeat(8_000))).not.toThrow();+ });+});diff --git a/apps/desktop/src/main/content-moderation/client.ts b/apps/desktop/src/main/content-moderation/client.tsnew file mode 100644index 0000000000..0940596297--- /dev/null+++ b/apps/desktop/src/main/content-moderation/client.ts@@ -0,0 +1,330 @@+import {+ MODERATION_JSON_SIGN_PATH,+ MODERATION_SUBMIT_LOGICAL_PATH,+ MODERATION_UPLOAD_SIGN_PATH,+ parseModerationSignedJsonResponse,+ parseModerationSignedUploadResponse,+ type ModerationBusinessCode,+ type ModerationItem,+ type ModerationJsonSignRequest,+ type ModerationSignedJsonResponse,+ type ModerationSignedUploadResponse,+ type ModerationSubmitBody,+} from '@cindy/content-moderation-protocol';+import { promises as fs } from 'node:fs';+import path from 'node:path';+import { createLogger } from '../logger.js';++const log = createLogger('content-moderation');+const QUERY_PATH = '/api/v1/review/tasks';+const QUERY_INTERVAL_MS = 1_000;+const MAX_QUERY_COUNT = 3;++export type { ModerationBusinessCode, ModerationItem } from '@cindy/content-moderation-protocol';++export type ModerationDecision = 'allow' | 'reject' | 'cancelled';++interface ReviewInput {+ signBaseUrl: string;+ accessToken: string;+ membershipId: string;+ businessCode: ModerationBusinessCode;+ dataId: string;+ items: ModerationItem[];+ extra?: {+ scene?: string;+ agentKind?: string;+ modelId?: string;+ };+ deadlineMs: number;+ signal?: AbortSignal;+}++interface UploadInput {+ signBaseUrl: string;+ accessToken: string;+ filePath: string;+ mimeType: string;+ deadlineAt: number;+ signal?: AbortSignal;+}++interface UploadBytesInput {+ signBaseUrl: string;+ accessToken: string;+ bytes: Uint8Array;+ fileName: string;+ mimeType: string;+ deadlineAt: number;+ signal?: AbortSignal;+}++interface TimedSignal {+ signal: AbortSignal;+ deadlineReached(): boolean;+ dispose(): void;+}++function joinedUrl(baseUrl: string, logicalPath: string): string {+ return `${baseUrl.replace(/\/+$/, '')}${logicalPath}`;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++function nonEmptyString(value: unknown): value is string {+ return typeof value === 'string' && value.length > 0;+}++function knownStatus(value: unknown): value is 1 | 2 | 3 | 4 {+ return value === 1 || value === 2 || value === 3 || value === 4;+}++function decisionForStatus(status: 1 | 2 | 3 | 4): ModerationDecision | 'waiting' {+ if (status === 1) return 'waiting';+ if (status === 3) return 'reject';+ return 'allow';+}++function timedSignal(deadlineMs: number, callerSignal?: AbortSignal): TimedSignal {+ const controller = new AbortController();+ let deadline = false;+ const timer = setTimeout(() => {+ deadline = true;+ controller.abort();+ }, Math.max(0, deadlineMs));+ const abortFromCaller = () => controller.abort();+ callerSignal?.addEventListener('abort', abortFromCaller, { once: true });+ if (callerSignal?.aborted) controller.abort();+ return {+ signal: controller.signal,+ deadlineReached: () => deadline,+ dispose: () => {+ clearTimeout(timer);+ callerSignal?.removeEventListener('abort', abortFromCaller);+ },+ };+}++async function sleep(ms: number, signal: AbortSignal): Promise<void> {+ if (signal.aborted) throw new DOMException('Aborted', 'AbortError');+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ signal.removeEventListener('abort', abort);+ resolve();+ }, ms);+ const abort = () => {+ clearTimeout(timer);+ reject(new DOMException('Aborted', 'AbortError'));+ };+ signal.addEventListener('abort', abort, { once: true });+ });+}++async function jsonResponse(response: Response): Promise<Record<string, unknown> | null> {+ try {+ const value = await response.json();+ return isRecord(value) ? value : null;+ } catch {+ return null;+ }+}++export class ModerationClient {+ constructor(+ private readonly fetchImpl: typeof fetch = globalThis.fetch,+ private readonly now: () => number = Date.now,+ ) {}++ /**+ * Product contract: only an explicit REJECTED verdict blocks the operation.+ * Signing, transport, malformed-response and polling-exhaustion failures are+ * infrastructure failures and deliberately fail open within the caller's+ * bounded deadline.+ */+ async review(input: ReviewInput): Promise<ModerationDecision> {+ if (input.items.length === 0) return 'allow';+ const timer = timedSignal(input.deadlineMs, input.signal);+ const startedAt = this.now();+ let queryCount = 0;+ try {+ const requestBody: ModerationSubmitBody = {+ business_code: input.businessCode,+ data_id: input.dataId,+ items: input.items,+ user_info: { user_id: input.membershipId },+ ...(input.extra ? { extra: input.extra } : {}),+ };+ const body = JSON.stringify(requestBody);+ const signed = await this.requestJsonSignature(+ input.signBaseUrl,+ input.accessToken,+ body,+ timer.signal,+ );+ if (!signed) return 'allow';+ const submit = await this.fetchImpl(+ joinedUrl(signed.gateway_base_url, signed.logical_path),+ {+ method: 'POST',+ headers: { ...signed.headers },+ body,+ signal: timer.signal,+ },+ );+ const submitBody = await jsonResponse(submit);+ const submitData = submitBody && isRecord(submitBody.data) ? submitBody.data : null;+ const submitStatus = submitData?.status;+ const taskToken = submitData?.task_token;+ if (+ submit.status !== 201+ || submitBody?.code !== 200+ || !knownStatus(submitStatus)+ || !nonEmptyString(taskToken)+ ) {+ return 'allow';+ }+ const immediate = decisionForStatus(submitStatus);+ if (immediate !== 'waiting') return immediate;++ for (let index = 0; index < MAX_QUERY_COUNT; index += 1) {+ await sleep(QUERY_INTERVAL_MS, timer.signal);+ queryCount += 1;+ const response = await this.fetchImpl(+ joinedUrl(signed.gateway_base_url, QUERY_PATH),+ {+ method: 'GET',+ headers: { Authorization: `Bearer ${taskToken}` },+ signal: timer.signal,+ },+ );+ const queryBody = await jsonResponse(response);+ const queryData = queryBody && isRecord(queryBody.data) ? queryBody.data : null;+ const status = queryData?.status;+ if (response.status !== 200 || queryBody?.code !== 200 || !knownStatus(status)) {+ return 'allow';+ }+ const decision = decisionForStatus(status);+ if (decision !== 'waiting') return decision;+ }+ return 'allow';+ } catch (error) {+ if (input.signal?.aborted && !timer.deadlineReached()) return 'cancelled';+ log.warn('moderation review failed open', {+ businessCode: input.businessCode,+ queryCount,+ elapsedMs: this.now() - startedAt,+ error: error instanceof Error ? error.name : 'unknown',+ });+ return 'allow';+ } finally {+ timer.dispose();+ }+ }++ async uploadLocalImage(input: UploadInput): Promise<string | null> {+ try {+ const bytes = await fs.readFile(input.filePath);+ return await this.uploadImageBytes({+ signBaseUrl: input.signBaseUrl,+ accessToken: input.accessToken,+ bytes,+ fileName: path.basename(input.filePath),+ mimeType: input.mimeType,+ deadlineAt: input.deadlineAt,+ signal: input.signal,+ });+ } catch {+ return null;+ }+ }++ async uploadImageBytes(input: UploadBytesInput): Promise<string | null> {+ const remaining = input.deadlineAt - this.now();+ if (remaining <= 0) return null;+ const timer = timedSignal(remaining, input.signal);+ try {+ const signedResponse = await this.fetchImpl(+ joinedUrl(input.signBaseUrl, MODERATION_UPLOAD_SIGN_PATH),+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${input.accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: '{}',+ signal: timer.signal,+ },+ );+ const signedBody = await jsonResponse(signedResponse);+ const signed = this.parseSignedUpload(signedResponse, signedBody);+ if (!signed) return null;+ const bytes = new Uint8Array(input.bytes.byteLength);+ bytes.set(input.bytes);+ const form = new FormData();+ form.append(+ 'file',+ new Blob([bytes.buffer], { type: input.mimeType || 'application/octet-stream' }),+ input.fileName,+ );+ const uploadUrl = new URL(joinedUrl(signed.gateway_base_url, signed.logical_path));+ uploadUrl.searchParams.set('folder', signed.query.folder);+ const response = await this.fetchImpl(uploadUrl, {+ method: 'POST',+ headers: { ...signed.headers },+ body: form,+ signal: timer.signal,+ });+ const body = await jsonResponse(response);+ const data = body && isRecord(body.data) ? body.data : null;+ return response.status === 201 && body?.code === 200 && nonEmptyString(data?.file_url)+ ? data.file_url+ : null;+ } catch {+ return null;+ } finally {+ timer.dispose();+ }+ }++ private async requestJsonSignature(+ signBaseUrl: string,+ accessToken: string,+ body: string,+ signal: AbortSignal,+ ): Promise<ModerationSignedJsonResponse | null> {+ const signRequest: ModerationJsonSignRequest = {+ logical_path: MODERATION_SUBMIT_LOGICAL_PATH,+ body,+ };+ const response = await this.fetchImpl(joinedUrl(signBaseUrl, MODERATION_JSON_SIGN_PATH), {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(signRequest),+ signal,+ });+ return this.parseSignedJson(response, await jsonResponse(response));+ }++ private parseSignedJson(+ response: Response,+ value: Record<string, unknown> | null,+ ): ModerationSignedJsonResponse | null {+ if (response.status !== 200) return null;+ const parsed = parseModerationSignedJsonResponse(value, MODERATION_SUBMIT_LOGICAL_PATH);+ return parsed.ok ? parsed.value : null;+ }++ private parseSignedUpload(+ response: Response,+ value: Record<string, unknown> | null,+ ): ModerationSignedUploadResponse | null {+ if (response.status !== 200) return null;+ const parsed = parseModerationSignedUploadResponse(value);+ return parsed.ok ? parsed.value : null;+ }+}diff --git a/apps/desktop/src/main/content-moderation/constants.ts b/apps/desktop/src/main/content-moderation/constants.tsnew file mode 100644index 0000000000..41797307f4--- /dev/null+++ b/apps/desktop/src/main/content-moderation/constants.ts@@ -0,0 +1 @@+export const CONTENT_MODERATION_BLOCKED_MESSAGE = '抱歉,当前问题暂时无法为您解答,请调整提问表述。';diff --git a/apps/desktop/src/main/content-moderation/eligibility.ts b/apps/desktop/src/main/content-moderation/eligibility.tsnew file mode 100644index 0000000000..71a6792db9--- /dev/null+++ b/apps/desktop/src/main/content-moderation/eligibility.ts@@ -0,0 +1,56 @@+import type { CindyRegion } from '@cindy/maker-shared/brand-identity';++export interface ModerationEligibilityInput {+ isPackaged: boolean;+ region: CindyRegion;+ commandLineEnabled: boolean;+ membershipKind: 'personal' | 'org' | null;+ membershipId: string | null;+ accessToken: string | null;+ identityEpoch: number;+ productionSignBaseUrl: string;+ testSignBaseUrl: string;+}++export interface ModerationIdentity {+ membershipId: string;+ accessToken: string;+ identityEpoch: number;+ signBaseUrl: string;+ environment: 'production' | 'test';+}++export function resolveModerationIdentity(+ input: ModerationEligibilityInput,+): ModerationIdentity | null {+ if (+ input.membershipKind !== 'personal'+ || !input.membershipId+ || !input.accessToken+ ) {+ return null;+ }++ if (input.isPackaged) {+ if (input.region === 'global') return null;+ if (input.region === 'cn') {+ if (!input.productionSignBaseUrl) return null;+ return {+ membershipId: input.membershipId,+ accessToken: input.accessToken,+ identityEpoch: input.identityEpoch,+ signBaseUrl: input.productionSignBaseUrl,+ environment: 'production',+ };+ }+ }++ if (!input.commandLineEnabled || !input.testSignBaseUrl) return null;+ return {+ membershipId: input.membershipId,+ accessToken: input.accessToken,+ identityEpoch: input.identityEpoch,+ signBaseUrl: input.testSignBaseUrl,+ environment: 'test',+ };+}diff --git a/apps/desktop/src/main/content-moderation/identity.ts b/apps/desktop/src/main/content-moderation/identity.tsnew file mode 100644index 0000000000..ef94e5092f--- /dev/null+++ b/apps/desktop/src/main/content-moderation/identity.ts@@ -0,0 +1,47 @@+import { app } from 'electron';+import {+ getAccessToken,+ getAuthIdentityEpoch,+ getAuthState,+} from '../authManager.js';+import { getClientEndpoint } from '../clientEndpointsService.js';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import {+ resolveModerationIdentity,+ type ModerationIdentity,+} from './eligibility.js';++function commandLineModerationEnabled(): boolean {+ return process.argv.includes('--content-moderation')+ || (!app.isPackaged && process.env.XDT_CONTENT_MODERATION === '1');+}++export function getModerationIdentity(): ModerationIdentity | null {+ try {+ const auth = getAuthState();+ return resolveModerationIdentity({+ isPackaged: app.isPackaged,+ region: CURRENT_CINDY_REGION,+ commandLineEnabled: commandLineModerationEnabled(),+ membershipKind: auth.user?.membershipKind ?? null,+ membershipId: auth.user?.id ?? null,+ accessToken: getAccessToken(),+ identityEpoch: getAuthIdentityEpoch(),+ productionSignBaseUrl: getClientEndpoint('moderationSignApiBaseUrl'),+ testSignBaseUrl: getClientEndpoint('moderationSignTestApiBaseUrl'),+ });+ } catch {+ // 启动早期或测试环境 endpoint 尚未初始化时按无审核资格处理,保持 fail-open。+ return null;+ }+}++export function isModerationIdentityCurrent(identity: ModerationIdentity): boolean {+ const current = getModerationIdentity();+ return Boolean(+ current+ && current.membershipId === identity.membershipId+ && current.identityEpoch === identity.identityEpoch+ && current.environment === identity.environment,+ );+}diff --git a/apps/desktop/src/main/content-moderation/input.ts b/apps/desktop/src/main/content-moderation/input.tsnew file mode 100644index 0000000000..345465070c--- /dev/null+++ b/apps/desktop/src/main/content-moderation/input.ts@@ -0,0 +1,117 @@+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';+import { resolveSafe as resolveCindyMediaUrl } from '../cindy-media/blobStore.js';+import { resolveSafe as resolveLegacyImageUrl } from '../imageCacheStore.js';+import { ModerationClient, type ModerationItem } from './client.js';+import {+ getModerationIdentity,+ isModerationIdentityCurrent,+} from './identity.js';++const TEXT_DEADLINE_MS = 5_000;+const LOCAL_IMAGE_DEADLINE_MS = 10_000;++export type InputModerationResult = 'allow' | 'reject' | 'cancelled';++function httpsUrl(value: string | undefined): string | null {+ if (!value) return null;+ try {+ const parsed = new URL(value);+ return parsed.protocol === 'https:' ? parsed.toString() : null;+ } catch {+ return null;+ }+}++function resolveManagedImagePath(value: string | undefined): string | null {+ if (!value) return null;+ try {+ if (value.startsWith('cindy-media://')) return resolveCindyMediaUrl(value).absPath;+ if (value.startsWith('xdt-image://')) return resolveLegacyImageUrl(value).absPath;+ } catch {+ return null;+ }+ return null;+}++export async function moderateAgentInput(+ sessionId: string,+ item: AgentInputQueuedMessage,+ client = new ModerationClient(),+): Promise<InputModerationResult> {+ if (item.origin?.kind === 'scheduler' || item.origin?.kind === 'orca') return 'allow';+ const identity = getModerationIdentity();+ if (!identity) return 'allow';++ const imageFiles = (item.files ?? []).filter(+ (file) => file.category === 'image' && file.ext.toLowerCase() !== '.gif',+ );+ const hasLocalImage = imageFiles.some((file) => !httpsUrl(file.url) && !httpsUrl(file.path));+ const deadlineMs = hasLocalImage ? LOCAL_IMAGE_DEADLINE_MS : TEXT_DEADLINE_MS;+ const deadlineAt = Date.now() + deadlineMs;+ const moderationItems: ModerationItem[] = [];+ if (item.text.length > 0) {+ moderationItems.push({+ type: 'TEXT',+ data: item.text,+ content_id: `${item.clientId}:text:0`,+ });+ }++ for (const [index, file] of imageFiles.entries()) {+ const directUrl = httpsUrl(file.url) ?? httpsUrl(file.path);+ let data = directUrl;+ if (!data && file.base64) {+ const bytes = Buffer.from(file.base64, 'base64');+ if (bytes.byteLength > 0) {+ data = await client.uploadImageBytes({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ bytes,+ fileName: file.originalName || file.name,+ mimeType: file.mimeType,+ deadlineAt,+ });+ }+ }+ if (!data) {+ // A plain path is intentional for local Desktop input and same-account,+ // explicitly enabled device-link remote control. That trust boundary+ // already permits remote file browsing and agent execution; managed+ // references remain preferred because they are path-contained.+ const filePath =+ resolveManagedImagePath(file.url)+ ?? resolveManagedImagePath(file.path)+ ?? file.path;+ data = await client.uploadLocalImage({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ filePath,+ mimeType: file.mimeType,+ deadlineAt,+ });+ }+ if (!data) continue;+ moderationItems.push({+ type: 'IMAGE',+ data,+ content_id: `${item.clientId}:image:${index}`,+ });+ }++ const decision = await client.review({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ membershipId: identity.membershipId,+ businessCode: 'maker-input-t2t',+ dataId: `input:${identity.membershipId}:${sessionId}:${item.clientId}`,+ items: moderationItems,+ extra: {+ scene: 'user',+ agentKind: item.createOpts.agentKind,+ modelId: item.model,+ },+ deadlineMs: Math.max(0, deadlineAt - Date.now()),+ });+ if (!isModerationIdentityCurrent(identity)) return 'cancelled';+ return decision;+}diff --git a/apps/desktop/src/main/content-moderation/notifications.ts b/apps/desktop/src/main/content-moderation/notifications.tsnew file mode 100644index 0000000000..1aa03ccb6d--- /dev/null+++ b/apps/desktop/src/main/content-moderation/notifications.ts@@ -0,0 +1,51 @@+import { BrowserWindow } from 'electron';+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';+import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';++export { CONTENT_MODERATION_BLOCKED_MESSAGE } from './constants.js';++export const CONTENT_MODERATION_INPUT_BLOCKED_CHANNEL =+ 'content-moderation:input-blocked';+export const CONTENT_MODERATION_OUTPUT_BLOCKED_CHANNEL =+ 'content-moderation:output-blocked';++export function broadcastModerationInputBlocked(input: {+ sessionId: string;+ item: AgentInputQueuedMessage;+ reason: 'rejected' | 'cancelled';+}): void {+ const files = input.item.files ?? [];+ const payload = {+ sessionId: input.sessionId,+ clientId: input.item.clientId,+ text: input.item.text,+ files,+ reason: input.reason,+ };+ // Device-link drops oversized frames for non-maker:event channels.+ // Strip large blob fields to keep the notification deliverable.+ const compactFiles = files.map(({ base64: _b, textContent: _t, ...rest }) => rest);+ const compactPayload = { ...payload, files: compactFiles };+ tapWindowBroadcast(CONTENT_MODERATION_INPUT_BLOCKED_CHANNEL, compactPayload);+ for (const window of BrowserWindow.getAllWindows()) {+ if (window.isDestroyed()) continue;+ window.webContents.send(CONTENT_MODERATION_INPUT_BLOCKED_CHANNEL, payload);+ }+}++export function broadcastModerationOutputBlocked(input: {+ sessionId: string;+ turnId: string;+}): void {+ const payload = {+ sessionId: input.sessionId,+ turnId: input.turnId,+ kind: 'blocked',+ i18nKey: 'contentModeration.blocked',+ } as const;+ tapWindowBroadcast(CONTENT_MODERATION_OUTPUT_BLOCKED_CHANNEL, payload);+ for (const window of BrowserWindow.getAllWindows()) {+ if (window.isDestroyed()) continue;+ window.webContents.send(CONTENT_MODERATION_OUTPUT_BLOCKED_CHANNEL, payload);+ }+}diff --git a/apps/desktop/src/main/content-moderation/output.ts b/apps/desktop/src/main/content-moderation/output.tsnew file mode 100644index 0000000000..acdae26847--- /dev/null+++ b/apps/desktop/src/main/content-moderation/output.ts@@ -0,0 +1,557 @@+import { randomUUID } from 'node:crypto';+import type { AgentEvent } from '@cindy/maker-core';+import {+ getModerationIdentity,+ isModerationIdentityCurrent,+} from './identity.js';+import {+ StreamModerationClient,+ type CreateStreamModerationInput,+ type StreamModerationCallbacks,+} from './streamClient.js';+import { CONTENT_MODERATION_BLOCKED_MESSAGE } from './constants.js';++const STARTUP_FAIL_OPEN_MS = 5_000;++type Mode = 'idle' | 'starting' | 'active' | 'fail-open' | 'terminal';+type TerminalKind = 'blocked' | 'failed' | 'cancelled' | 'identity-changed';++type ReleaseBoundary = { kind: 'boundary'; resolve: () => void };+type StartupEntry =+ | { kind: 'event'; event: AgentEvent }+ | ReleaseBoundary;+type PendingEntry =+ | { kind: 'text'; sequence: number; event: AgentEvent }+ | { kind: 'event'; event: AgentEvent; terminalBarrier: boolean }+ | ReleaseBoundary;++type CreateStream = (+ input: CreateStreamModerationInput,+ callbacks: StreamModerationCallbacks,+) => Promise<StreamModerationClient | null>;++export interface OutputModerationGateOptions {+ sessionId: string;+ agentKind?: string;+ deliver(event: AgentEvent): void;+ abortTurn(): Promise<void>;+ onBlocked(turnId: string): void;+ onFailed(turnId: string): void;+ createStream?: CreateStream;+}++function textEvent(event: AgentEvent): { text: string; isFinal: boolean } | null {+ if (event.type !== 'text' || !event.data || typeof event.data !== 'object') return null;+ const data = event.data as { text?: unknown; isFinal?: unknown };+ if (typeof data.text !== 'string') return null;+ return { text: data.text, isFinal: data.isFinal === true };+}++function terminalError(event: AgentEvent): boolean {+ if (event.type !== 'error' || !event.data || typeof event.data !== 'object') return false;+ const data = event.data as { isTerminal?: unknown; willRetry?: unknown };+ if (typeof data.isTerminal === 'boolean') return data.isTerminal;+ return data.willRetry !== true;+}++function isRunningStatus(event: AgentEvent, running: boolean): boolean {+ if (event.type !== 'status' || !event.data || typeof event.data !== 'object') return false;+ return (event.data as { isRunning?: unknown }).isRunning === running;+}++function withText(event: AgentEvent, text: string, isFinal?: boolean): AgentEvent {+ return {+ ...event,+ data: {+ ...(event.data && typeof event.data === 'object' ? event.data : {}),+ text,+ ...(typeof isFinal === 'boolean' ? { isFinal } : {}),+ },+ } as AgentEvent;+}++export class OutputModerationGate {+ private mode: Mode = 'idle';+ private terminalKind: TerminalKind | null = null;+ private identity: ReturnType<typeof getModerationIdentity> = null;+ private stream: StreamModerationClient | null = null;+ private startupQueue: StartupEntry[] = [];+ private startupTimer: ReturnType<typeof setTimeout> | null = null;+ private startupAbort: AbortController | null = null;+ private pending: PendingEntry[] = [];+ private releasedBySequence = new Map<number, string>();+ private currentBlockSubmittedText = '';+ private releasedBlockText = '';+ private releasedText = '';+ private turnId = '';+ private finishSent = false;+ private completionApproved = false;+ private lastTurnEvent: AgentEvent | null = null;+ private terminalSettleDelivered = false;++ constructor(private readonly options: OutputModerationGateOptions) {}++ handle(event: AgentEvent): void {+ if (this.mode === 'starting') {+ this.lastTurnEvent = event;+ this.startupQueue.push({ kind: 'event', event });+ return;+ }+ if (this.mode === 'active') {+ this.lastTurnEvent = event;+ this.handleActive(event);+ return;+ }+ if (this.mode === 'terminal') {+ this.handleTerminal(event);+ return;+ }+ if (this.mode === 'fail-open') {+ this.deliverFailOpen(event);+ return;+ }++ const text = textEvent(event);+ if (text?.isFinal && text.text.length === 0) {+ this.options.deliver(event);+ return;+ }+ if (!text && !isRunningStatus(event, true)) {+ this.options.deliver(event);+ return;+ }+ const identity = getModerationIdentity();+ if (!identity) {+ this.options.deliver(event);+ return;+ }+ this.beginTurn(event, identity);+ }++ waitForReleaseBoundary(): Promise<void> {+ if (this.mode !== 'starting' && this.mode !== 'active') {+ return Promise.resolve();+ }+ return new Promise<void>((resolve) => {+ const boundary: ReleaseBoundary = { kind: 'boundary', resolve };+ if (this.mode === 'starting') {+ this.startupQueue.push(boundary);+ return;+ }+ this.pending.push(boundary);+ this.flushReleased();+ });+ }++ private beginTurn(+ event: AgentEvent,+ identity: NonNullable<ReturnType<typeof getModerationIdentity>>,+ ): void {+ this.mode = 'starting';+ this.identity = identity;+ this.turnId = randomUUID();+ this.lastTurnEvent = event;+ this.startupQueue.push({ kind: 'event', event });+ this.startupAbort = new AbortController();+ this.startupTimer = setTimeout(() => this.failOpenStarting(), STARTUP_FAIL_OPEN_MS);+ void this.start(identity);+ }++ cancel(): boolean {+ if (this.mode === 'idle') return false;+ this.stream?.cancel();+ this.startupAbort?.abort();+ this.startupAbort = null;+ this.clearStartupTimer();+ this.mode = 'terminal';+ this.terminalKind = 'cancelled';+ this.resolveReleaseBoundaries();+ this.startupQueue = [];+ this.pending = [];+ this.releasedBySequence.clear();+ return true;+ }++ close(): void {+ this.stream?.cancel();+ this.reset();+ }++ private async start(identity: NonNullable<ReturnType<typeof getModerationIdentity>>): Promise<void> {+ const callbacks: StreamModerationCallbacks = {+ onRelease: (frame) => this.onRelease(frame.sequence, frame.text),+ onBlock: () => this.onBlock(),+ onFailed: () => this.onFailed(),+ onCompleted: () => this.onCompleted(),+ onFailOpen: () => this.onFailOpen(),+ };+ const createStream = this.options.createStream ?? StreamModerationClient.create;+ let stream: StreamModerationClient | null = null;+ try {+ stream = await createStream({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ membershipId: identity.membershipId,+ sessionId: this.options.sessionId,+ turnId: this.turnId,+ agentKind: this.options.agentKind,+ signal: this.startupAbort?.signal,+ }, callbacks);+ } catch {+ stream = null;+ }+ if (this.mode !== 'starting') {+ stream?.cancel();+ return;+ }+ this.clearStartupTimer();+ this.startupAbort = null;+ if (!isModerationIdentityCurrent(identity)) {+ stream?.cancel();+ this.cancelForIdentityChange();+ return;+ }+ const queued = this.startupQueue;+ this.startupQueue = [];+ if (!stream) {+ this.mode = 'fail-open';+ for (const entry of queued) {+ if (entry.kind === 'boundary') entry.resolve();+ else this.deliverFailOpen(entry.event);+ }+ return;+ }+ this.stream = stream;+ this.mode = 'active';+ for (const entry of queued) {+ if (entry.kind === 'boundary') {+ this.pending.push(entry);+ this.flushReleased();+ } else {+ this.handleActive(entry.event);+ }+ }+ }++ private failOpenStarting(): void {+ if (this.mode !== 'starting') return;+ const queued = this.startupQueue;+ this.startupQueue = [];+ this.mode = 'fail-open';+ this.startupAbort?.abort();+ this.startupAbort = null;+ this.stream?.cancel();+ this.stream = null;+ for (const entry of queued) {+ if (entry.kind === 'boundary') entry.resolve();+ else this.deliverFailOpen(entry.event);+ }+ }++ private handleActive(event: AgentEvent): void {+ const text = textEvent(event);+ if (text) {+ if (!text.isFinal) {+ this.enqueueText(event, text.text);+ this.currentBlockSubmittedText += text.text;+ return;+ }+ if (this.currentBlockSubmittedText.length > 0) {+ const suffix = text.text.startsWith(this.currentBlockSubmittedText)+ ? text.text.slice(this.currentBlockSubmittedText.length)+ : '';+ if (suffix) this.enqueueText(withText(event, suffix, false), suffix);+ this.pending.push({+ kind: 'event',+ event,+ terminalBarrier: false,+ });+ this.currentBlockSubmittedText = '';+ this.flushReleased();+ return;+ }+ this.enqueueText(event, text.text);+ return;+ }++ this.pending.push({+ kind: 'event',+ event,+ terminalBarrier: event.type === 'done'+ || terminalError(event)+ || isRunningStatus(event, false),+ });+ if (event.type === 'tool_use') this.currentBlockSubmittedText = '';+ if ((event.type === 'done' || terminalError(event)) && !this.finishSent) {+ this.finishSent = true;+ this.stream?.finish();+ }+ this.flushReleased();+ }++ private enqueueText(event: AgentEvent, text: string): void {+ const sequence = this.stream?.push(text) ?? -1;+ if (sequence >= 0) this.pending.push({ kind: 'text', sequence, event });+ }++ private onRelease(sequence: number, text: string): void {+ if (this.mode !== 'active' || !this.identity) return;+ if (!isModerationIdentityCurrent(this.identity)) {+ this.cancelForIdentityChange();+ return;+ }+ this.releasedBySequence.set(sequence, text);+ this.flushReleased();+ }++ private flushReleased(): void {+ while (this.pending.length > 0) {+ const entry = this.pending[0];+ if (entry.kind === 'text') {+ const released = this.releasedBySequence.get(entry.sequence);+ if (released === undefined) return;+ this.pending.shift();+ this.releasedBySequence.delete(entry.sequence);+ this.releasedText += released;+ this.releasedBlockText += released;+ this.options.deliver(withText(entry.event, released));+ if (textEvent(entry.event)?.isFinal) this.releasedBlockText = '';+ continue;+ }+ if (entry.kind === 'boundary') {+ this.pending.shift();+ entry.resolve();+ continue;+ }+ if (entry.terminalBarrier && !this.completionApproved) return;+ this.pending.shift();+ const text = textEvent(entry.event);+ if (text?.isFinal) {+ this.options.deliver(withText(entry.event, this.releasedBlockText, true));+ this.releasedBlockText = '';+ } else {+ this.options.deliver(this.sanitizeReleasedResult(entry.event));+ if (entry.event.type === 'tool_use') this.releasedBlockText = '';+ }+ }+ }++ private sanitizeReleasedResult(event: AgentEvent): AgentEvent {+ if (event.type !== 'done' || !event.data || typeof event.data !== 'object') return event;+ return {+ ...event,+ data: { ...event.data, result: this.releasedText },+ } as AgentEvent;+ }++ private deliverFailOpen(event: AgentEvent): void {+ const text = textEvent(event);+ if (text) {+ if (!text.isFinal) {+ this.currentBlockSubmittedText += text.text;+ this.releasedText += text.text;+ this.options.deliver(event);+ return;+ }+ if (this.currentBlockSubmittedText.length > 0) {+ const suffix = text.text.startsWith(this.currentBlockSubmittedText)+ ? text.text.slice(this.currentBlockSubmittedText.length)+ : '';+ if (suffix) {+ this.releasedText += suffix;+ this.options.deliver(withText(event, suffix, false));+ }+ this.currentBlockSubmittedText = '';+ this.options.deliver(event);+ return;+ }+ this.releasedText += text.text;+ this.options.deliver(event);+ return;+ }+ this.options.deliver(this.sanitizeReleasedResult(event));+ if (event.type === 'done' || terminalError(event)) this.reset();+ }++ private onCompleted(): void {+ if (this.mode !== 'active' || !this.identity) return;+ if (!isModerationIdentityCurrent(this.identity)) {+ this.cancelForIdentityChange();+ return;+ }+ this.completionApproved = true;+ this.flushReleased();+ if (this.pending.length > 0) return;+ this.reset();+ }++ private onFailOpen(): void {+ if (this.mode !== 'active' || !this.identity) return;+ if (!isModerationIdentityCurrent(this.identity)) {+ this.cancelForIdentityChange();+ return;+ }+ this.completionApproved = true;+ this.flushReleased();+ if (this.finishSent && this.pending.length === 0) {+ this.reset();+ return;+ }+ this.mode = 'fail-open';+ this.stream = null;+ }++ private onBlock(): void {+ if (!this.enterExplicitTerminal('blocked')) return;+ this.options.onBlocked(this.turnId);+ this.options.deliver(this.syntheticDoneEvent());+ void this.options.abortTurn().catch(() => undefined);+ }++ private onFailed(): void {+ if (!this.enterExplicitTerminal('failed')) return;+ this.options.onFailed(this.turnId);+ this.options.deliver(this.syntheticFailureEvent());+ void this.options.abortTurn().catch(() => undefined);+ }++ private enterExplicitTerminal(kind: 'blocked' | 'failed'): boolean {+ if (this.mode !== 'active' || !this.identity) return false;+ if (!isModerationIdentityCurrent(this.identity)) {+ this.cancelForIdentityChange();+ return false;+ }+ this.mode = 'terminal';+ this.terminalKind = kind;+ this.resolveReleaseBoundaries();+ this.pending = [];+ this.releasedBySequence.clear();+ return true;+ }++ private syntheticDoneEvent(): AgentEvent {+ const result = this.releasedText.length > 0+ ? `${this.releasedText}\n\n${CONTENT_MODERATION_BLOCKED_MESSAGE}`+ : CONTENT_MODERATION_BLOCKED_MESSAGE;+ return {+ type: 'done',+ data: {+ result,+ contentModerationBlocked: true,+ },+ ...this.turnMetadata(),+ };+ }++ private syntheticFailureEvent(): AgentEvent {+ return {+ type: 'error',+ data: {+ message: 'Content generation failed',+ reason: 'turn-failed',+ contentModerationFailed: true,+ isTerminal: true,+ },+ ...this.turnMetadata(),+ };+ }++ private turnMetadata(): Pick<AgentEvent, 'source' | 'turnOrigin' | 'agentMeta'> {+ const event = this.lastTurnEvent;+ return {+ ...(event?.source ? { source: event.source } : {}),+ ...(event?.turnOrigin ? { turnOrigin: event.turnOrigin } : {}),+ ...(event?.agentMeta ? { agentMeta: event.agentMeta } : {}),+ };+ }++ private handleTerminal(event: AgentEvent): void {+ if (isRunningStatus(event, true)) {+ if (+ !this.terminalSettleDelivered+ && (this.terminalKind === 'cancelled' || this.terminalKind === 'identity-changed')+ ) {+ this.terminalSettleDelivered = true;+ this.options.deliver({+ type: 'done',+ data: { result: this.releasedText, cancelled: true },+ ...this.turnMetadata(),+ });+ }+ this.reset();+ this.handle(event);+ return;+ }+ if (+ this.terminalSettleDelivered+ || (this.terminalKind !== 'cancelled' && this.terminalKind !== 'identity-changed')+ ) {+ return;+ }+ if (isRunningStatus(event, false)) {+ this.options.deliver(event);+ } else if (event.type === 'done') {+ this.terminalSettleDelivered = true;+ this.options.deliver(this.sanitizeReleasedResult(event));+ } else if (terminalError(event)) {+ this.terminalSettleDelivered = true;+ this.options.deliver({+ type: 'done',+ data: { result: this.releasedText, cancelled: true },+ ...this.turnMetadata(),+ });+ }+ }++ private cancelForIdentityChange(): void {+ this.stream?.cancel();+ this.startupAbort?.abort();+ this.startupAbort = null;+ this.clearStartupTimer();+ this.mode = 'terminal';+ this.terminalKind = 'identity-changed';+ this.resolveReleaseBoundaries();+ this.startupQueue = [];+ this.pending = [];+ this.releasedBySequence.clear();+ void this.options.abortTurn().catch(() => undefined);+ }++ private clearStartupTimer(): void {+ if (!this.startupTimer) return;+ clearTimeout(this.startupTimer);+ this.startupTimer = null;+ }++ private resolveReleaseBoundaries(): void {+ for (const entry of this.startupQueue) {+ if (entry.kind === 'boundary') entry.resolve();+ }+ for (const entry of this.pending) {+ if (entry.kind === 'boundary') entry.resolve();+ }+ }++ private reset(): void {+ this.stream?.cancel();+ this.startupAbort?.abort();+ this.startupAbort = null;+ this.clearStartupTimer();+ this.resolveReleaseBoundaries();+ this.mode = 'idle';+ this.terminalKind = null;+ this.identity = null;+ this.stream = null;+ this.startupQueue = [];+ this.pending = [];+ this.releasedBySequence.clear();+ this.currentBlockSubmittedText = '';+ this.releasedBlockText = '';+ this.releasedText = '';+ this.turnId = '';+ this.finishSent = false;+ this.completionApproved = false;+ this.lastTurnEvent = null;+ this.terminalSettleDelivered = false;+ }+}diff --git a/apps/desktop/src/main/content-moderation/outputHub.ts b/apps/desktop/src/main/content-moderation/outputHub.tsnew file mode 100644index 0000000000..cb430b2fff--- /dev/null+++ b/apps/desktop/src/main/content-moderation/outputHub.ts@@ -0,0 +1,97 @@+import type { AgentEvent } from '@cindy/maker-core';+import { OutputModerationGate } from './output.js';+import { emitOutputModerationSignal } from './signals.js';++interface SessionOutputSource {+ id: string;+ agentKind?: string;+ // 部分 host 测试替身保留宽松的 event shape;唯一 raw 边界在下方收窄为 AgentEvent。+ onEvent(listener: (event: any) => void): () => void;+ abort(): Promise<void>;+}++interface Hub {+ session: SessionOutputSource;+ gate: OutputModerationGate;+ listeners: Set<(event: AgentEvent) => void>;+ stopRaw: () => void;+}++const hubsBySession = new Map<string, Hub>();++function closeHub(hub: Hub): void {+ hub.stopRaw();+ hub.gate.close();+ hub.listeners.clear();+ if (hubsBySession.get(hub.session.id) === hub) {+ hubsBySession.delete(hub.session.id);+ }+}++function ensureHub(session: SessionOutputSource): Hub {+ const existing = hubsBySession.get(session.id);+ if (existing?.session === session) return existing;+ if (existing) closeHub(existing);++ const listeners = new Set<(event: AgentEvent) => void>();+ let hub: Hub;+ const gate = new OutputModerationGate({+ sessionId: session.id,+ agentKind: session.agentKind,+ deliver: (event) => {+ for (const listener of [...listeners]) {+ try {+ listener(event);+ } catch {+ // 与 maker-core 原始多 listener 语义一致:单个消费者异常不阻断其他出口。+ }+ }+ },+ abortTurn: () => session.abort(),+ onBlocked: (turnId) => {+ emitOutputModerationSignal({ sessionId: session.id, turnId, kind: 'blocked' });+ },+ onFailed: () => undefined,+ });+ const stopRaw = session.onEvent((event: AgentEvent) => gate.handle(event));+ hub = { session, gate, listeners, stopRaw };+ hubsBySession.set(session.id, hub);+ return hub;+}++/**+ * 唯一允许正文消费者订阅的事件出口。每个 live session 只有这里持有 raw+ * `session.onEvent`,所有下游只会收到已 release 或 fail-open 的正文。+ */+export function onReleasedAgentEvent(+ session: SessionOutputSource,+ listener: (event: AgentEvent) => void,+): () => void {+ const hub = ensureHub(session);+ hub.listeners.add(listener);+ return () => {+ hub.listeners.delete(listener);+ if (hub.listeners.size === 0) closeHub(hub);+ };+}++export function cancelReleasedOutput(sessionId: string): void {+ hubsBySession.get(sessionId)?.gate.cancel();+}++export function waitForReleasedOutput(sessionId: string): Promise<void> {+ return hubsBySession.get(sessionId)?.gate.waitForReleaseBoundary() ?? Promise.resolve();+}++export function cancelAllReleasedOutputs(): void {+ for (const hub of hubsBySession.values()) {+ if (hub.gate.cancel()) {+ void hub.session.abort().catch(() => undefined);+ }+ }+}++export function closeReleasedOutput(session: SessionOutputSource): void {+ const hub = hubsBySession.get(session.id);+ if (hub?.session === session) closeHub(hub);+}diff --git a/apps/desktop/src/main/content-moderation/postProcessedOutput.ts b/apps/desktop/src/main/content-moderation/postProcessedOutput.tsnew file mode 100644index 0000000000..8e64c8f7b9--- /dev/null+++ b/apps/desktop/src/main/content-moderation/postProcessedOutput.ts@@ -0,0 +1,74 @@+import {+ getModerationIdentity,+ isModerationIdentityCurrent,+} from './identity.js';+import { emitOutputModerationSignal } from './signals.js';+import {+ StreamModerationClient,+ type StreamModerationCallbacks,+} from './streamClient.js';++const STARTUP_TIMEOUT_MS = 5_000;++export async function reviewPostProcessedOutput(+ sessionId: string,+ turnId: string,+ text: string,+): Promise<boolean> {+ const identity = getModerationIdentity();+ if (!identity || text.length === 0) return true;++ return new Promise<boolean>((resolve) => {+ const startupAbort = new AbortController();+ let stream: StreamModerationClient | null = null;+ let settled = false;+ const settle = (allowed: boolean): void => {+ if (settled) return;+ settled = true;+ clearTimeout(startupTimer);+ if (!isModerationIdentityCurrent(identity)) {+ stream?.cancel();+ resolve(false);+ return;+ }+ resolve(allowed);+ };+ const callbacks: StreamModerationCallbacks = {+ onRelease: () => undefined,+ onBlock: () => {+ emitOutputModerationSignal({ sessionId, turnId, kind: 'blocked' });+ settle(false);+ },+ onFailed: () => settle(false),+ onCompleted: () => settle(true),+ onFailOpen: () => settle(true),+ };+ const startupTimer = setTimeout(() => {+ startupAbort.abort();+ stream?.cancel();+ settle(true);+ }, STARTUP_TIMEOUT_MS);++ void StreamModerationClient.create({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ membershipId: identity.membershipId,+ sessionId,+ turnId,+ agentKind: 'ghost',+ signal: startupAbort.signal,+ }, callbacks).then((created) => {+ stream = created;+ if (settled) {+ created?.cancel();+ return;+ }+ if (!created) {+ settle(true);+ return;+ }+ created.push(text);+ created.finish();+ }).catch(() => settle(true));+ });+}diff --git a/apps/desktop/src/main/content-moderation/profile.ts b/apps/desktop/src/main/content-moderation/profile.tsnew file mode 100644index 0000000000..79f5fd89ba--- /dev/null+++ b/apps/desktop/src/main/content-moderation/profile.ts@@ -0,0 +1,80 @@+import { randomUUID } from 'node:crypto';+import { ModerationClient, type ModerationDecision } from './client.js';+import {+ getModerationIdentity,+ isModerationIdentityCurrent,+} from './identity.js';++const TEXT_DEADLINE_MS = 5_000;+const IMAGE_DEADLINE_MS = 10_000;++export interface ProfileModerationInput {+ displayName?: string;+ avatar?: {+ bytes: Uint8Array;+ fileName: string;+ mimeType: string;+ };+}++export type ProfileModerationResult = 'allow' | 'reject' | 'cancelled';++export async function moderateProfileUpdate(+ input: ProfileModerationInput,+ client = new ModerationClient(),+): Promise<ProfileModerationResult> {+ const identity = getModerationIdentity();+ if (!identity) return 'allow';++ const operationId = randomUUID();+ const reviews: Promise<ModerationDecision>[] = [];++ if (input.displayName) {+ reviews.push(client.review({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ membershipId: identity.membershipId,+ businessCode: 'maker-nickname',+ dataId: `nickname:${identity.membershipId}:${operationId}`,+ items: [{+ type: 'TEXT',+ data: input.displayName,+ content_id: `${operationId}:nickname`,+ }],+ extra: { scene: 'profile' },+ deadlineMs: TEXT_DEADLINE_MS,+ }));+ }++ if (input.avatar) {+ const deadlineAt = Date.now() + IMAGE_DEADLINE_MS;+ const avatarUrl = await client.uploadImageBytes({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ bytes: input.avatar.bytes,+ fileName: input.avatar.fileName,+ mimeType: input.avatar.mimeType,+ deadlineAt,+ });+ if (avatarUrl) reviews.push(client.review({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ membershipId: identity.membershipId,+ businessCode: 'maker-avatar',+ dataId: `avatar:${identity.membershipId}:${operationId}`,+ items: [{+ type: 'IMAGE',+ data: avatarUrl,+ content_id: `${operationId}:avatar`,+ }],+ extra: { scene: 'profile' },+ deadlineMs: Math.max(0, deadlineAt - Date.now()),+ }));+ }++ const decisions = await Promise.all(reviews);+ if (!isModerationIdentityCurrent(identity)) return 'cancelled';+ if (decisions.includes('reject')) return 'reject';+ if (decisions.includes('cancelled')) return 'cancelled';+ return 'allow';+}diff --git a/apps/desktop/src/main/content-moderation/signals.ts b/apps/desktop/src/main/content-moderation/signals.tsnew file mode 100644index 0000000000..b3d1a90e1e--- /dev/null+++ b/apps/desktop/src/main/content-moderation/signals.ts@@ -0,0 +1,24 @@+export interface OutputModerationSignal {+ sessionId: string;+ turnId: string;+ kind: 'blocked';+}++const listeners = new Set<(signal: OutputModerationSignal) => void>();++export function emitOutputModerationSignal(signal: OutputModerationSignal): void {+ for (const listener of [...listeners]) {+ try {+ listener(signal);+ } catch {+ // 临时通知失败不能阻断 turn 收尾。+ }+ }+}++export function onOutputModerationSignal(+ listener: (signal: OutputModerationSignal) => void,+): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}diff --git a/apps/desktop/src/main/content-moderation/streamClient.ts b/apps/desktop/src/main/content-moderation/streamClient.tsnew file mode 100644index 0000000000..b230f377ef--- /dev/null+++ b/apps/desktop/src/main/content-moderation/streamClient.ts@@ -0,0 +1,627 @@+import {+ MODERATION_JSON_SIGN_PATH,+ MODERATION_STREAM_CREATE_LOGICAL_PATH,+ parseModerationSignedJsonResponse,+ type ModerationJsonSignRequest,+ type ModerationStreamCreateBody,+} from '@cindy/content-moderation-protocol';+import { createLogger } from '../logger.js';++const log = createLogger('content-moderation-stream');+const INITIAL_RELEASE_TIMEOUT_MS = 5_000;+const FINALIZATION_TIMEOUT_MS = 5_000;+const RECOVERY_DELAY_MS = 1_000;+const MAX_RECOVERY_ATTEMPTS = 2;++interface StreamFrame {+ sequence: number;+ text: string;+ is_final: boolean;+ queuedAt: number;+}++interface StreamTaskTokens {+ gatewayBaseUrl: string;+ taskId: string;+ writeToken: string;+ readToken: string;+}++export interface StreamModerationCallbacks {+ onRelease(frame: { sequence: number; text: string }): void;+ onBlock(): void;+ onFailed(): void;+ onCompleted(): void;+ onFailOpen(): void;+}++export interface CreateStreamModerationInput {+ signBaseUrl: string;+ accessToken: string;+ membershipId: string;+ sessionId: string;+ turnId: string;+ agentKind?: string;+ modelId?: string;+ signal?: AbortSignal;+}++type LocalTerminal = 'block' | 'failed' | 'completed' | 'fail-open' | 'cancelled';+type ProgressState = 'CREATED' | 'OPEN' | 'BLOCKED' | 'FAILED' | 'COMPLETED';++function joinedUrl(baseUrl: string, logicalPath: string): string {+ return `${baseUrl.replace(/\/+$/, '')}${logicalPath}`;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);+}++function nonEmptyString(value: unknown): value is string {+ return typeof value === 'string' && value.length > 0;+}++async function jsonResponse(response: Response): Promise<Record<string, unknown> | null> {+ try {+ const value = await response.json();+ return isRecord(value) ? value : null;+ } catch {+ return null;+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function taskPath(taskId: string, suffix: string): string {+ return `/api/v1/review/stream/tasks/${encodeURIComponent(taskId)}/${suffix}`;+}++function serializeFrame(frame: StreamFrame): string {+ return JSON.stringify({+ sequence: frame.sequence,+ text: frame.text,+ is_final: frame.is_final,+ });+}++export class StreamModerationClient {+ private readonly lifecycle = new AbortController();+ private readonly frames = new Map<number, StreamFrame>();+ private readonly released = new Map<number, string>();+ private readonly pendingReleases = new Map<number, string>();+ private readonly encoder = new TextEncoder();+ private nextSequence = 0;+ private nextReleaseSequence = 0;+ private terminal: LocalTerminal | null = null;+ private finished = false;+ private finalSequence: number | null = null;+ private completionObserved = false;+ private lastEventId: string | null = null;+ private initialReleaseTimer: ReturnType<typeof setTimeout> | null = null;+ private finalizationTimer: ReturnType<typeof setTimeout> | null = null;+ private inputWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;+ private inputResponse: Promise<void> | null = null;+ private eventsActive = false;+ private recovery: Promise<void> | null = null;+ private recoveryNeedsInput = false;+ private recoveryNeedsEvents = false;+ private sendChain: Promise<void> = Promise.resolve();++ private constructor(+ private readonly task: StreamTaskTokens,+ private readonly callbacks: StreamModerationCallbacks,+ private readonly fetchImpl: typeof fetch,+ ) {}++ static async create(+ input: CreateStreamModerationInput,+ callbacks: StreamModerationCallbacks,+ fetchImpl: typeof fetch = globalThis.fetch,+ ): Promise<StreamModerationClient | null> {+ const requestBody: ModerationStreamCreateBody = {+ business_code: 'stream-output',+ data_id: `output:${input.membershipId}:${input.sessionId}:${input.turnId}`,+ items: [],+ user_info: { user_id: input.membershipId },+ extra: {+ scene: 'assistant',+ ...(input.agentKind ? { agentKind: input.agentKind } : {}),+ ...(input.modelId ? { modelId: input.modelId } : {}),+ },+ };+ const body = JSON.stringify(requestBody);+ const signRequest: ModerationJsonSignRequest = {+ logical_path: MODERATION_STREAM_CREATE_LOGICAL_PATH,+ body,+ };+ try {+ const signResponse = await fetchImpl(+ joinedUrl(input.signBaseUrl, MODERATION_JSON_SIGN_PATH),+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${input.accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(signRequest),+ signal: input.signal,+ },+ );+ const signedBody = await jsonResponse(signResponse);+ const parsedSigned = parseModerationSignedJsonResponse(+ signedBody,+ MODERATION_STREAM_CREATE_LOGICAL_PATH,+ );+ if (signResponse.status !== 200 || !parsedSigned.ok) {+ return null;+ }+ const signed = parsedSigned.value;+ const createResponse = await fetchImpl(+ joinedUrl(signed.gateway_base_url, MODERATION_STREAM_CREATE_LOGICAL_PATH),+ {+ method: 'POST',+ headers: { ...signed.headers },+ body,+ signal: input.signal,+ },+ );+ const createBody = await jsonResponse(createResponse);+ const data = createBody && isRecord(createBody.data) ? createBody.data : null;+ if (+ createResponse.status !== 201+ || createBody?.code !== 200+ || !nonEmptyString(data?.task_id)+ || !nonEmptyString(data.write_token)+ || !nonEmptyString(data.read_token)+ ) {+ return null;+ }+ const client = new StreamModerationClient(+ {+ gatewayBaseUrl: signed.gateway_base_url,+ taskId: data.task_id,+ writeToken: data.write_token,+ readToken: data.read_token,+ },+ callbacks,+ fetchImpl,+ );+ if (input.signal?.aborted) {+ client.cancel();+ return null;+ }+ const abortClient = () => client.cancel();+ input.signal?.addEventListener('abort', abortClient, { once: true });+ try {+ await client.openEvents();+ if (input.signal?.aborted) {+ client.cancel();+ return null;+ }+ return client;+ } catch {+ client.cancel();+ return null;+ } finally {+ input.signal?.removeEventListener('abort', abortClient);+ }+ } catch {+ return null;+ }+ }++ push(text: string): number {+ if (this.terminal || this.finished) return -1;+ const frame: StreamFrame = {+ sequence: this.nextSequence,+ text,+ is_final: false,+ queuedAt: Date.now(),+ };+ this.nextSequence += 1;+ this.frames.set(frame.sequence, frame);+ this.armInitialReleaseTimeout();+ this.enqueueFrame(frame);+ return frame.sequence;+ }++ finish(): void {+ if (this.terminal || this.finished) return;+ this.finished = true;+ const frame: StreamFrame = {+ sequence: this.nextSequence,+ text: '',+ is_final: true,+ queuedAt: Date.now(),+ };+ this.finalSequence = frame.sequence;+ this.nextSequence += 1;+ this.frames.set(frame.sequence, frame);+ this.armFinalizationTimeout();+ this.enqueueFrame(frame);+ }++ cancel(): void {+ if (this.terminal) return;+ this.terminal = 'cancelled';+ this.clearInitialReleaseTimeout();+ this.clearFinalizationTimeout();+ this.lifecycle.abort();+ void this.inputWriter?.abort().catch(() => undefined);+ }++ private armInitialReleaseTimeout(): void {+ if (this.initialReleaseTimer || this.terminal) return;+ const oldest = [...this.frames.values()]+ .filter((frame) => !frame.is_final && !this.released.has(frame.sequence))+ .sort((left, right) => left.sequence - right.sequence)[0];+ if (!oldest) return;+ const remaining = Math.max(0, INITIAL_RELEASE_TIMEOUT_MS - (Date.now() - oldest.queuedAt));+ this.initialReleaseTimer = setTimeout(+ () => this.failOpen('pending-release-timeout'),+ remaining,+ );+ }++ private clearInitialReleaseTimeout(): void {+ if (!this.initialReleaseTimer) return;+ clearTimeout(this.initialReleaseTimer);+ this.initialReleaseTimer = null;+ }++ private armFinalizationTimeout(): void {+ if (this.finalizationTimer || this.terminal) return;+ this.finalizationTimer = setTimeout(+ () => this.failOpen('finalization-timeout'),+ FINALIZATION_TIMEOUT_MS,+ );+ }++ private clearFinalizationTimeout(): void {+ if (!this.finalizationTimer) return;+ clearTimeout(this.finalizationTimer);+ this.finalizationTimer = null;+ }++ private enqueueFrame(frame: StreamFrame): void {+ this.sendChain = this.sendChain+ .then(async () => {+ if (this.terminal) return;+ const writer = await this.ensureInputWriter();+ await writer.write(this.encoder.encode(`${serializeFrame(frame)}\n`));+ if (frame.is_final) {+ await writer.close();+ this.inputWriter = null;+ await this.inputResponse;+ }+ })+ .catch(() => this.recover('input'));+ }++ private async ensureInputWriter(): Promise<WritableStreamDefaultWriter<Uint8Array>> {+ if (this.inputWriter) return this.inputWriter;+ const stream = new TransformStream<Uint8Array, Uint8Array>();+ const writer = stream.writable.getWriter();+ this.inputWriter = writer;+ const init = {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${this.task.writeToken}`,+ 'Content-Type': 'application/x-ndjson',+ },+ body: stream.readable,+ signal: this.lifecycle.signal,+ duplex: 'half',+ } as RequestInit & { duplex: 'half' };+ this.inputResponse = this.fetchImpl(+ joinedUrl(this.task.gatewayBaseUrl, taskPath(this.task.taskId, 'input')),+ init,+ ).then(async (response) => {+ const body = await jsonResponse(response);+ const data = body && isRecord(body.data) ? body.data : null;+ if (+ response.status !== 200+ || body?.code !== 200+ || data?.accepted !== true+ || data.next_sequence !== this.nextSequence+ ) {+ throw new Error('stream input rejected');+ }+ });+ void this.inputResponse.catch(() => {+ if (!this.terminal) void this.recover('input');+ });+ return writer;+ }++ private async openEvents(): Promise<void> {+ if (this.terminal || this.eventsActive) return;+ const headers: Record<string, string> = {+ Authorization: `Bearer ${this.task.readToken}`,+ Accept: 'text/event-stream',+ };+ if (this.lastEventId) headers['Last-Event-ID'] = this.lastEventId;+ const response = await this.fetchImpl(+ joinedUrl(this.task.gatewayBaseUrl, taskPath(this.task.taskId, 'events')),+ { method: 'GET', headers, signal: this.lifecycle.signal },+ );+ if (response.status !== 200 || !response.body) throw new Error('stream events unavailable');+ this.eventsActive = true;+ void this.consumeEvents(response.body)+ .catch(() => undefined)+ .finally(() => {+ this.eventsActive = false;+ if (!this.terminal) void this.recover('events');+ });+ }++ private async consumeEvents(body: ReadableStream<Uint8Array>): Promise<void> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ while (!this.terminal) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ buffer = buffer.replace(/\r\n/g, '\n').replace(/\r(?!$)/g, '\n');+ let boundary = buffer.indexOf('\n\n');+ while (boundary >= 0) {+ const block = buffer.slice(0, boundary);+ buffer = buffer.slice(boundary + 2);+ this.handleSseBlock(block);+ boundary = buffer.indexOf('\n\n');+ }+ }+ }++ private handleSseBlock(block: string): void {+ let id: string | null = null;+ let event = '';+ const dataLines: string[] = [];+ for (const line of block.split('\n')) {+ if (line.startsWith(':')) continue;+ const separator = line.indexOf(':');+ const field = separator >= 0 ? line.slice(0, separator) : line;+ const value = separator >= 0 ? line.slice(separator + 1).replace(/^ /, '') : '';+ if (field === 'id') id = value;+ if (field === 'event') event = value;+ if (field === 'data') dataLines.push(value);+ }+ if (!event) return;+ let data: Record<string, unknown> | null = null;+ try {+ const parsed = JSON.parse(dataLines.join('\n')) as unknown;+ data = isRecord(parsed) ? parsed : null;+ } catch {+ return;+ }+ if (!data) return;+ if (event === 'content.release') {+ const sequence = data.sequence;+ const text = data.text;+ if (!Number.isInteger(sequence) || (sequence as number) < 0 || typeof text !== 'string') return;+ const frame = this.frames.get(sequence as number);+ if (!frame || (sequence as number) >= this.nextSequence) {+ this.failOpen('invalid-release-sequence');+ return;+ }+ // The gateway releases the terminal empty frame as well as text frames.+ // It advances ordering but must never become user-visible output.+ if (frame.is_final && text !== '') {+ this.failOpen('invalid-final-release');+ return;+ }+ const releasedText = this.released.get(sequence as number);+ const pendingText = this.pendingReleases.get(sequence as number);+ if (+ (releasedText !== undefined && releasedText !== text)+ || (pendingText !== undefined && pendingText !== text)+ ) {+ this.failOpen('conflicting-release');+ return;+ }+ if (releasedText === undefined) this.pendingReleases.set(sequence as number, text);+ this.drainOrderedReleases();+ } else if (event === 'content.block') {+ this.block();+ } else if (event === 'task.completed') {+ this.complete();+ } else if (event === 'task.failed') {+ this.fail();+ } else {+ return;+ }+ if (id !== null) this.lastEventId = id;+ }++ private drainOrderedReleases(): void {+ while (this.pendingReleases.has(this.nextReleaseSequence)) {+ const sequence = this.nextReleaseSequence;+ const text = this.pendingReleases.get(sequence);+ this.pendingReleases.delete(sequence);+ this.nextReleaseSequence += 1;+ if (text === undefined || this.released.has(sequence)) continue;+ this.released.set(sequence, text);+ const frame = this.frames.get(sequence);+ if (frame && !frame.is_final) this.callbacks.onRelease({ sequence, text });+ }+ this.clearInitialReleaseTimeout();+ this.armInitialReleaseTimeout();+ this.completeIfReady();+ }++ private async recover(reason: 'input' | 'events'): Promise<void> {+ if (this.terminal) return;+ if (reason === 'input') this.recoveryNeedsInput = true;+ if (reason === 'events') this.recoveryNeedsEvents = true;+ if (this.recovery) return this.recovery;+ this.recovery = (async () => {+ for (let attempt = 0; attempt < MAX_RECOVERY_ATTEMPTS; attempt += 1) {+ if (attempt > 0) await sleep(RECOVERY_DELAY_MS);+ try {+ const progress = await this.getProgress();+ if (progress.streamState === 'BLOCKED') {+ this.block();+ return;+ }+ if (progress.streamState === 'FAILED') {+ this.fail();+ return;+ }+ if (progress.streamState === 'COMPLETED') {+ this.completionObserved = true;+ if (this.completeIfReady()) return;+ }+ if (this.recoveryNeedsInput) {+ this.recoveryNeedsInput = false;+ this.inputWriter = null;+ this.inputResponse = null;+ await this.replayMissingFrames(progress.nextSequence);+ }+ this.recoveryNeedsEvents = false;+ if (!this.eventsActive) await this.openEvents();+ if (this.recoveryNeedsInput || this.recoveryNeedsEvents || !this.eventsActive) {+ throw new Error('stream recovery incomplete');+ }+ return;+ } catch {+ // retry+ }+ }+ this.failOpen(`${reason}-recovery-exhausted`);+ })().finally(() => {+ this.recovery = null;+ if (!this.terminal && (this.recoveryNeedsInput || this.recoveryNeedsEvents || !this.eventsActive)) {+ void this.recover(this.recoveryNeedsInput ? 'input' : 'events');+ }+ });+ return this.recovery;+ }++ private async getProgress(): Promise<{ nextSequence: number; streamState: ProgressState }> {+ const response = await this.fetchImpl(+ joinedUrl(this.task.gatewayBaseUrl, taskPath(this.task.taskId, 'progress')),+ {+ method: 'GET',+ headers: { Authorization: `Bearer ${this.task.writeToken}` },+ signal: this.lifecycle.signal,+ },+ );+ const body = await jsonResponse(response);+ const data = body && isRecord(body.data) ? body.data : null;+ const nextSequence = data?.next_sequence;+ const streamState = data?.stream_state;+ if (+ response.status !== 200+ || body?.code !== 200+ || !Number.isInteger(nextSequence)+ || (nextSequence as number) < 0+ || !['CREATED', 'OPEN', 'BLOCKED', 'FAILED', 'COMPLETED'].includes(String(streamState))+ ) {+ throw new Error('invalid stream progress');+ }+ return {+ nextSequence: nextSequence as number,+ streamState: streamState as ProgressState,+ };+ }++ private async replayMissingFrames(nextSequence: number): Promise<void> {+ const missing = [...this.frames.values()]+ .filter((frame) => frame.sequence >= nextSequence)+ .sort((left, right) => left.sequence - right.sequence);+ for (const frame of missing) {+ const response = await this.fetchImpl(+ joinedUrl(this.task.gatewayBaseUrl, taskPath(this.task.taskId, 'chunks')),+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${this.task.writeToken}`,+ 'Content-Type': 'application/json',+ },+ body: serializeFrame(frame),+ signal: this.lifecycle.signal,+ },+ );+ const body = await jsonResponse(response);+ const data = body && isRecord(body.data) ? body.data : null;+ if (+ response.status !== 200+ || body?.code !== 200+ || data?.accepted !== true+ || data.next_sequence !== frame.sequence + 1+ ) {+ throw new Error('stream chunk rejected');+ }+ }+ }++ private releaseRemainingRaw(): void {+ for (const frame of [...this.frames.values()].sort((left, right) => left.sequence - right.sequence)) {+ if (frame.is_final || this.released.has(frame.sequence)) continue;+ this.released.set(frame.sequence, frame.text);+ this.callbacks.onRelease({ sequence: frame.sequence, text: frame.text });+ }+ this.nextReleaseSequence = this.finalSequence ?? this.nextSequence;+ this.pendingReleases.clear();+ }++ private block(): void {+ if (this.terminal) return;+ this.terminal = 'block';+ this.clearInitialReleaseTimeout();+ this.clearFinalizationTimeout();+ this.lifecycle.abort();+ this.callbacks.onBlock();+ }++ private fail(): void {+ if (this.terminal) return;+ this.terminal = 'failed';+ this.clearInitialReleaseTimeout();+ this.clearFinalizationTimeout();+ this.lifecycle.abort();+ this.callbacks.onFailed();+ }++ private complete(): void {+ if (this.terminal) return;+ this.completionObserved = true;+ this.completeIfReady();+ }++ private completeIfReady(): boolean {+ if (+ this.terminal+ || !this.completionObserved+ || this.finalSequence === null+ ) {+ return false;+ }+ this.terminal = 'completed';+ this.clearInitialReleaseTimeout();+ this.clearFinalizationTimeout();+ // COMPLETED is the gateway's approval for the entire stream item, so any+ // frames that did not receive individual release events are safe to emit.+ this.releaseRemainingRaw();+ this.lifecycle.abort();+ this.callbacks.onCompleted();+ return true;+ }++ private failOpen(reason: string): void {+ if (this.terminal) return;+ this.terminal = 'fail-open';+ this.clearInitialReleaseTimeout();+ this.clearFinalizationTimeout();+ // Product contract: bounded infrastructure failures must not make model+ // output disappear. Explicit BLOCKED and FAILED terminal states never take+ // this path and continue to fail closed.+ this.releaseRemainingRaw();+ this.lifecycle.abort();+ log.warn('stream moderation failed open', { reason });+ this.callbacks.onFailOpen();+ }+}diff --git a/apps/desktop/src/main/content-moderation/userPrompt.ts b/apps/desktop/src/main/content-moderation/userPrompt.tsnew file mode 100644index 0000000000..7ef06e7ca0--- /dev/null+++ b/apps/desktop/src/main/content-moderation/userPrompt.ts@@ -0,0 +1,51 @@+import { randomUUID } from 'node:crypto';+import { ModerationClient } from './client.js';+import { USER_PROMPT_MAX_LENGTH } from '../../shared/userPrompt.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import {+ getModerationIdentity,+ isModerationIdentityCurrent,+} from './identity.js';++const TEXT_DEADLINE_MS = 5_000;++export type UserPromptModerationResult = 'allow' | 'reject' | 'cancelled';++export function validateUserPromptReviewValue(value: unknown): asserts value is string {+ if (typeof value !== 'string') {+ throwIpcError('INVALID_PARAMS', 'user prompt must be a string');+ }+ if (value.length > USER_PROMPT_MAX_LENGTH) {+ throwIpcError(+ 'INVALID_PARAMS',+ `user prompt exceeds ${USER_PROMPT_MAX_LENGTH} characters`,+ );+ }+}++export async function moderateUserPrompt(+ text: string,+ client = new ModerationClient(),+): Promise<UserPromptModerationResult> {+ if (text.trim().length === 0) return 'allow';+ const identity = getModerationIdentity();+ if (!identity) return 'allow';++ const operationId = randomUUID();+ const decision = await client.review({+ signBaseUrl: identity.signBaseUrl,+ accessToken: identity.accessToken,+ membershipId: identity.membershipId,+ businessCode: 'maker-sys-prompt',+ dataId: `sys-prompt:${identity.membershipId}:${operationId}`,+ items: [{+ type: 'TEXT',+ data: text,+ content_id: `${operationId}:sys-prompt`,+ }],+ extra: { scene: 'settings' },+ deadlineMs: TEXT_DEADLINE_MS,+ });+ if (!isModerationIdentityCurrent(identity)) return 'cancelled';+ return decision;+}diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.tsindex a4f79cdfe7..275cb7a1d4 100644--- a/apps/desktop/src/main/goal-host/controller.ts+++ b/apps/desktop/src/main/goal-host/controller.ts@@ -20,6 +20,10 @@ import type { AgentEvent } from '@cindy/maker-core';import { buildContinuationDirective, buildFirstTurnDirective } from './directive';import { agentHandoffPending } from '../maker-ipc/agentHandoffPendingSingleton';import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff';+import {+ cancelReleasedOutput,+ onReleasedAgentEvent,+} from '../content-moderation/outputHub.js';import { classifyTurnUsageLimit } from './usageLimit';import { parseVerdict, type GoalVerdict } from './verdict';import {@@ -349,6 +353,7 @@ export class GoalController {// 终止事件可能在 detach 前被 onEvent 消费 → 并发 finalizeTurn 把下面刚写的 active 覆盖成// paused(用户编辑目标后 chip 误显"暂停")。detach 在前,abort 的终止事件就不再触达裁决。this.stopSession(sessionId);+ cancelReleasedOutput(sessionId);await session.abort();} else {this.stopSession(sessionId);@@ -709,7 +714,7 @@ export class GoalController {// session 被 agent switch 换掉了 → 迁移 listener 到新对象。try { this.unsubscribers.get(sessionId)?.(); } catch { /* ignore */ }}- const off = session.onEvent((event) => {+ const off = onReleasedAgentEvent(session, (event) => {try {this.onEvent(sessionId, event);} catch (e) {diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex 87d89079a0..69b0c205eb 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -62,6 +62,7 @@ import { registerSlackToolBridge, unregisterSlackToolBridge } from './slackToolBimport { createHookBindingStore } from './bindings.js';import { createHookDispatcher } from './dispatcher.js';import { createMakerHookSessionRunner } from './session-runner.js';+import { cancelReleasedOutput } from '../content-moderation/outputHub.js';import { resolveHookInteraction } from './interactions.js';import { listRecentHookSessions } from './recentSessions.js';import { validateTelegramExternalUrl } from './telegramDeepLink.js';@@ -294,6 +295,7 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManager},// task.cancel 的中断出口: 与用户手动 Stop 同一条 session.abort() 路径abortSession: async (sessionId) => {+ cancelReleasedOutput(sessionId);await getMaker().getSession(sessionId)?.abort();},// session.archive 的归档出口: 与 device-link 远程归档同一条diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 9094e11aa6..820f6b1103 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -48,6 +48,7 @@ import {} from '@cindy/model-providers';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import { onReleasedAgentEvent } from '../content-moderation/outputHub.js';import { getMaker } from '../maker-host/index.js';import {wireSessionToIpc,@@ -596,7 +597,7 @@ export function createMakerHookSessionRunner(deps: {}, BG_TASK_IDLE_FALLBACK_MS);bgFallbackTimer.unref?.();};- const off = session.onEvent((ev: AgentEvent) => {+ const off = onReleasedAgentEvent(session, (ev: AgentEvent) => {if (waitingForBgTasks) armBgTimer();if (ev.type === 'agent_task_update') {const data = ev.data as { taskId?: string; status?: string } | null;diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 0f7b593ce0..de037cd377 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -50,6 +50,12 @@ import { hasCustomProviderKey } from '../../maker-host/provider-route';import { createLogger } from '../../logger';import { resolveSafe as resolveXdtImageUrl } from '../../imageCacheStore';import { resolveSafe as resolveCindyMediaUrl } from '../../cindy-media/blobStore';+import {+ cancelReleasedOutput,+ onReleasedAgentEvent,+ waitForReleasedOutput,+} from '../../content-moderation/outputHub.js';+import { CONTENT_MODERATION_BLOCKED_MESSAGE } from '../../content-moderation/constants.js';import { isTerminalAgentErrorEvent } from '@cindy/maker-core';import type {@@ -761,7 +767,7 @@ export function createTurnRunner(previous.setInteractionListener(null);state.makerSession = current;wireSessionToIpcExternal(current);- state.unsubscribers.push(current.onEvent(handleEventFor(sessionId, userId)));+ state.unsubscribers.push(onReleasedAgentEvent(current, handleEventFor(sessionId, userId)));current.setInteractionListener(handleInteractionFor(sessionId, userId, state.scopeKey));sessionStates.set(sessionId, state);} finally {@@ -982,7 +988,7 @@ export function createTurnRunner(// 注册本渠道自己的 onEvent listener — multi-listener 语义, 跟 desktop 那个// (如果存在) 并存。事件 fan-out 给 streamingHandle / 渠道卡片。- state.unsubscribers.push(makerSession.onEvent(handleEventFor(row.id, userId)));+ state.unsubscribers.push(onReleasedAgentEvent(makerSession, handleEventFor(row.id, userId)));// setInteractionListener 是 single-listener: 这一调会覆盖上方// wireSessionToIpcExternal 装上的 desktop 版 — 渠道会话(含接管期间)的@@ -1286,6 +1292,16 @@ export function createTurnRunner(case 'tool_result_full':return handleToolResultFullEvent(turn, event);case 'done':+ if (+ event.data+ && typeof event.data === 'object'+ && (event.data as { contentModerationBlocked?: unknown }).contentModerationBlocked === true+ ) {+ turn.buffer = turn.buffer+ ? `${turn.buffer}\n\n${CONTENT_MODERATION_BLOCKED_MESSAGE}`+ : CONTENT_MODERATION_BLOCKED_MESSAGE;+ turn.streamingHandle?.replace(composeStreamingView(turn));+ }// silent-stop done(上游用空内容静默收尾): 不当普通 done 收口 —// 守卫可能自动续跑,续跑轮事件要继续流进本 turn 的卡片,// 见 handleSilentStopDone。@@ -1990,6 +2006,7 @@ export function createTurnRunner(// (eventually resolved) interaction card — not into the pre-existing card// that sits above it. Without this, the user sees the conclusion stream// into a card chronologically older than the "✅ 已选择" patch.+ await waitForReleasedOutput(localSessionId);await finalizeActiveStream(localSessionId);let messageId: string;@@ -2148,6 +2165,7 @@ export function createTurnRunner(cleanupSessionState(state);settleDetachDrain(state, 'cancelled');if (hasImTurnInFlight) {+ cancelReleasedOutput(state.makerSession.id);aborts.push(state.makerSession.abort().catch((err) => {const msg = err instanceof Error ? err.message : String(err);@@ -2190,6 +2208,7 @@ export function createTurnRunner(// 不产生任何事件,不重置的话守卫照样自动续跑,用户喊停后 agent 原地复活。// 重置后守卫判 superseded → settle('skip') → 挂起 turn 经现有订阅按 done 收口。noteSilentStopSessionReset(state.makerSession.id);+ cancelReleasedOutput(state.makerSession.id);await state.makerSession.abort();log.info(`!stop aborted turn for session=...${state.makerSession.id.slice(-8)} droppedQueued=${droppedQueued}`,diff --git a/apps/desktop/src/main/learn-host/controller.ts b/apps/desktop/src/main/learn-host/controller.tsindex a260660ecd..fee65aea26 100644--- a/apps/desktop/src/main/learn-host/controller.ts+++ b/apps/desktop/src/main/learn-host/controller.ts@@ -29,6 +29,10 @@ import {import type { FileChange } from '../skillhub/snapshot';import { getSkillInstallLockOwner, tryAcquireSkillInstallLock } from '../skillhub/installLock';import { prependHandoffToUserMessage } from '../maker-ipc/agentHandoff';+import {+ cancelReleasedOutput,+ onReleasedAgentEvent,+} from '../content-moderation/outputHub.js';import type { EvidenceSearchFn } from './evidence';import { collectEvidence } from './evidence';import { extractKeywords } from './evidence.pure';@@ -488,6 +492,7 @@ export class LearnController {// update 的终态保护会拒绝 cancelled → distilling,此处按返回值收口,把刚建的// 会话中止掉,不再白跑一轮模型调用。if (afterCreate.status !== 'distilling' || this.disposed) {+ cancelReleasedOutput(session.id);void session.abort().catch(() => undefined);// dispose 窗口里 'distilling' 已被持久化 —— 必须收口成终态,否则 runs.json// 留着非终态 run,重启前 startLearn 永远 LEARN_BUSY(Codex review)。cancel@@ -524,7 +529,7 @@ export class LearnController {let assistantText = '';const turnFinished = new Promise<void>((resolve, reject) => {let off: () => void = () => undefined;- off = session.onEvent((ev) => {+ off = onReleasedAgentEvent(session, (ev) => {if (ev.type === 'text') {const data = ev.data as { text?: string; isFinal?: boolean } | null;if (data && typeof data.text === 'string') {@@ -548,6 +553,7 @@ export class LearnController {const timeoutMs = this.deps.turnTimeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;const timedOut = new Promise<never>((_resolve, reject) => {const handle = setTimeout(() => {+ cancelReleasedOutput(session.id);void session.abort().catch(() => undefined);reject(new Error(`distillation timed out after ${Math.round(timeoutMs / 1000)}s`));}, timeoutMs);@@ -694,7 +700,7 @@ export class LearnController {this.revisionRescans.set(runId, rescan);void rescan;};- const off = session.onEvent((ev) => {+ const off = onReleasedAgentEvent(session, (ev) => {// 回合活跃跟踪只认真实 turn 事件:account_usage / interaction_dismissed// 这类全局通知不能把 apply 永久卡在 LEARN_BUSY。if (this.deps.isTerminalErrorEvent(ev)) {@@ -982,6 +988,7 @@ export class LearnController {throw new LearnError('LEARN_INVALID_STATE', `run ${runId} is not awaiting review (${run.status})`);}const watcher = this.detachWatcher(runId);+ if (watcher) cancelReleasedOutput(watcher.session.id);await watcher?.session.abort().catch(() => undefined);await this.revisionRescans.get(runId)?.catch(() => undefined);await this.deps.staging.cleanup(runId);@@ -1041,6 +1048,7 @@ export class LearnController {}let rejectTurn: ((err: Error) => void) | undefined;if (this.active?.runId === runId) {+ cancelReleasedOutput(this.active.session.id);void this.active.session.abort().catch(() => undefined);rejectTurn = this.active.rejectTurn;}@@ -1061,6 +1069,7 @@ export class LearnController {// 登出/切账号时活跃蒸馏必须真正中止(Codex review):只摘监听不 abort 的话,// bypassPermissions 的模型进程会带着旧账号状态继续跑、烧 token;pipeline// promise 也会永久 pending。abort + rejectTurn 与 cancel() 同语义。+ cancelReleasedOutput(this.active.session.id);aborts.push(this.active.session.abort().catch(() => undefined));rejectActiveTurn = this.active.rejectTurn;this.active.stopListening?.();@@ -1071,6 +1080,7 @@ export class LearnController {// awaiting-review 后的修订 turn 只由 watcher 观察,不在 this.active 里。// 切账号/登出时必须中止这些会话,否则模型会继续用旧 controller deps 写// staging、消耗 token(Codex review)。+ cancelReleasedOutput(watcher.session.id);aborts.push(watcher.session.abort().catch(() => undefined));watcher.stopListening();}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 62b416322f..0a2b944d50 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -216,8 +216,8 @@ function createHarness() {noteSessionClearBoundary,resolveSessionReferences,hasPendingCredentialSwitch: () => hasPendingCredentialSwitch?.() === true,- screenUserMessage: (sessionId, item) =>- screenUserMessage ? screenUserMessage(sessionId, item) : Promise.resolve({ action: 'allow' }),+ screenUserMessage: (sessionId, text, item) =>+ screenUserMessage ? screenUserMessage(sessionId, text, item) : Promise.resolve({ action: 'allow' }),onUserMessageBlocked,onUserMessageRewritten,emitProjection,diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 3c8a3099b4..7fb46ebb02 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -151,6 +151,7 @@ export interface AgentInputCoordinatorDeps {screenUserMessage?: (sessionId: string,agentFacingText: string,+ item: AgentInputQueuedMessage,) => Promise<| { action: 'allow' }| { action: 'block'; ghostId: string; ghostName: string; reason: string }@@ -1015,7 +1016,7 @@ export class AgentInputCoordinator {// marker 已置位,筛查期间并发 steer / drain 被挡;stop / clearSession 竞态// 由筛查后的 marker 复查兜底。if (!item.bypassGhostHooks && this.deps.screenUserMessage) {- const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(item));+ const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(item), item);const cur = this.getState(sessionId);if (!cur.steeringQueueClientIds.includes(item.clientId)) {// stop/close/clearSession 赢在筛查期间:steer 事务已被取消,静默放弃。@@ -1955,7 +1956,7 @@ export class AgentInputCoordinator {// 留痕署名后照常派发。activeTurn 已置位,并发 drain 被挡住,询问期间// 不会抢发下一条。if (!head.bypassGhostHooks && this.deps.screenUserMessage) {- const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(head));+ const verdict = await this.deps.screenUserMessage(sessionId, getAgentFacingText(head), head);if (!this.isActiveTurnCurrent(sessionId, active)) return;if (verdict.action === 'block') {this.getState(sessionId).activeTurn = null;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 0eabe800ed..aec849961b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -123,6 +123,18 @@ import {} from '../localDb/orcaTeamStore.js';import { messages, orcaTeams, orcaWorkers, sessions } from '../localDb/schema.js';import { createLogger } from '../logger.js';+import { moderateAgentInput } from '../content-moderation/input.js';+import {+ broadcastModerationInputBlocked,+ broadcastModerationOutputBlocked,+} from '../content-moderation/notifications.js';+import {+ cancelReleasedOutput,+ closeReleasedOutput,+ onReleasedAgentEvent,+ waitForReleasedOutput,+} from '../content-moderation/outputHub.js';+import { onOutputModerationSignal } from '../content-moderation/signals.js';import { desktopClaudeAuthAdapter, desktopCodexAuthAdapter, readClaudeApiKey } from '../maker-host/auth-adapters.js';import { prepareSharedProjectSkillLinks } from '../maker-host/shared-global-skills.js';import { syncExternalCodexSessionFromDesktop } from '../maker-host/codex-local-sessions.js';@@ -1279,6 +1291,17 @@ export function takePendingInteractionsForSession(* 进程级单例 —— register.ts 模块只 load 一次, 此 Set 在 closeSession 时按 id 清理。*/const wiredSessionIds = new Set<string>();+let moderationOutputSignalWired = false;++function ensureModerationOutputSignalWired(): void {+ if (moderationOutputSignalWired) return;+ moderationOutputSignalWired = true;+ onOutputModerationSignal((signal) => {+ if (signal.kind === 'blocked') {+ broadcastModerationOutputBlocked(signal);+ }+ });+}/*** SDK result 事件的 total_cost_usd 是 session 累计 (不是 per-turn) ——@@ -1872,6 +1895,7 @@ export function installDesktopInteractionListener(// F1-a Phase 2: interaction(ask_user / plan_review / permission)是 turn 暂停边界,// 且不走 onEvent —— 在这把在飞 assistant 文本落库,等价于 renderer 老逻辑在// ask_user_question / plan_review case 里的 mid-turn assistant 抢救(只入队、不阻塞)。+ await waitForReleasedOutput(session.id);flushAssistantBlock(session.id);// F1-a Phase 5: ask_user / plan_review 的消息本身也收口 main 单点落库(单 persistId,// 修 F1 重复),persistId 盖进 payload 让 renderer 用同一 id 建气泡 + answered 回写命中。@@ -2065,6 +2089,7 @@ async function handleSilentStopTurnEnd(export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void {if (!session) return;+ ensureModerationOutputSignalWired();if (wiredSessionIds.has(session.id)) return;wiredSessionIds.add(session.id);@@ -2075,7 +2100,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 订阅槽①旁听 tap(独立监听,叠加在主转发之外互不干扰):AgentEvent →// did-turn-*。资格(用户主会话)与自动化轮次过滤都在 tap 内部,这里零逻辑。const ghostSessionTap = createGhostSessionTap(session.id);- session.onEvent((event: AgentEvent) => {+ onReleasedAgentEvent(session, (event: AgentEvent) => {ghostSessionTap.handleEvent(event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },);@@ -2083,7 +2108,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// 转发事件到所有 window。interaction_dismissed 单独走专用 channel,// 让 renderer chat store 不必扫所有 vendor-raw 找它。- session.onEvent((event: AgentEvent) => {+ onReleasedAgentEvent(session, (event: AgentEvent) => {const broadcastEvent = redactEventForRenderer(event);if (event.type === 'interaction_dismissed') {const data = event.data as { requestId?: unknown; reason?: unknown };@@ -2837,6 +2862,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidsession.onStatusChange((status) => {broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });if (status === 'closed') {+ closeReleasedOutput(session);cleanupPendingInteractionsForSession(session.id, 'session_closed');agentInputCoordinatorHolder?.onSessionClosed(session.id);// 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。@@ -4920,6 +4946,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsif (sess) {try {if (sess.isTurnRunning?.()) {+ cancelReleasedOutput(w.sessionId);await sess.abort();}} catch (err) {@@ -5067,6 +5094,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionscloseWorkerSession: async (sessionId) => {const sess = maker.getSession(sessionId);if (sess) {+ cancelReleasedOutput(sessionId);await sess.abort();}await maker.closeSession(sessionId);@@ -5801,6 +5829,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsmarkWorkerManualInterruptIfKnown(sessionId, 'input_stop');const sess = maker.getSession(sessionId);if (!sess) return;+ cancelReleasedOutput(sessionId);await sess.abort();cleanupPendingInteractionsForSession(sessionId, 'session_aborted');},@@ -5911,15 +5940,41 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions},// 意识拦截钩(订阅槽①):派发/落库前问已装钩子意识;fail-open 由// screenGhostUserMessage 内部收敛,快路径(无钩子意识)零开销。- screenUserMessage: (sessionId, agentFacingText) =>- screenGhostUserMessage(sessionId, agentFacingText),- onUserMessageBlocked: (sessionId, item, verdict) =>+ screenUserMessage: async (sessionId, agentFacingText, item) => {+ // Run rewrites first: moderation must see the exact text that would be+ // persisted and dispatched.+ const ghostVerdict = await screenGhostUserMessage(sessionId, agentFacingText);+ if (ghostVerdict.action === 'block') return ghostVerdict;+ const moderationItem = ghostVerdict.action === 'rewrite'+ ? { ...item, text: ghostVerdict.text }+ : item;+ const moderation = await moderateAgentInput(sessionId, moderationItem);+ if (moderation === 'reject' || moderation === 'cancelled') {+ return {+ action: 'block' as const,+ ghostId: '__content_moderation__',+ ghostName: '',+ reason: moderation === 'cancelled' ? 'cancelled' : 'rejected',+ };+ }+ return ghostVerdict;+ },+ onUserMessageBlocked: (sessionId, item, verdict) => {+ if (verdict.ghostId === '__content_moderation__') {+ broadcastModerationInputBlocked({+ sessionId,+ item,+ reason: verdict.reason === 'cancelled' ? 'cancelled' : 'rejected',+ });+ return;+ }broadcastGhostMessageBlocked({sessionId,clientId: item.clientId,text: item.text,...verdict,- }),+ });+ },onUserMessageRewritten: (sessionId, item, info) =>broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info }),beforeDispatchUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnStart(sessionId),@@ -6484,6 +6539,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions// 监听),**再** abort。这样 abort 产生的终止事件到来时目标已暂停、监听已摘,不会被误判成// 续跑(原本依赖 error 文案正则判 paused/blocked,不可靠)。null-safe;无 active goal 时 no-op。await goalStopObserver?.(sessionId);+ cancelReleasedOutput(sessionId);await sess.abort();cleanupPendingInteractionsForSession(sessionId, 'session_aborted');});diff --git a/apps/desktop/src/main/profileEdit.ts b/apps/desktop/src/main/profileEdit.tsindex d6109b3791..df4b923319 100644--- a/apps/desktop/src/main/profileEdit.ts+++ b/apps/desktop/src/main/profileEdit.ts@@ -11,6 +11,7 @@* authManager.updateServerProfile 就地更新并广播。*/+import path from 'node:path';import { throwIpcError } from './utils/ipcValidate';// ── 常量 ────────────────────────────────────────────────────────────────────@@ -51,6 +52,15 @@ export interface ProfileEditDeps {| { ok: true; publicUrl: string }| { ok: false; stage: 'presign' | 'put'; status: number; code?: string }>;+ /** 昵称与新头像内容审核;头像必须在公开 OSS 上传前审核本地字节。 */+ moderateProfile(params: {+ displayName?: string;+ avatar?: {+ bytes: Uint8Array;+ fileName: string;+ mimeType: string;+ };+ }): Promise<'allow' | 'reject' | 'cancelled'>;/** PATCH /api/me/profile(authManager.updateServerProfile,成功后已广播)。 */patchProfile(patch: { displayName?: string; avatarUrl?: string | null }): Promise<{ ok: true } | { ok: false; status: number; code?: string }@@ -184,8 +194,13 @@ export async function updateProfile(const nextDisplayName =trimmedName !== '' && trimmedName !== profile.name ? trimmedName : undefined;- // ── 头像收敛(set 时先直传 OSS 拿公开地址) ──+ // ── 头像收敛(set 时先保留本地字节,审核放行后才公开上传 Cindy OSS) ──let nextAvatarUrl: string | null | undefined;+ let pendingAvatar: {+ buffer: Buffer;+ fileName: string;+ mimeType: string;+ } | undefined;if (avatarAction.type === 'set') {const mime = avatarMimeForPath(avatarAction.filePath);if (!mime) {@@ -200,7 +215,49 @@ export async function updateProfile(if (buffer.byteLength === 0 || buffer.byteLength > AVATAR_MAX_BYTES) {throwIpcError('INVALID_PARAMS', `avatar file size out of range: ${buffer.byteLength}`);}- const uploaded = await deps.uploadAvatar({ buffer, mimeType: mime });+ pendingAvatar = {+ buffer,+ fileName: path.posix.basename(avatarAction.filePath.replaceAll('\\', '/')),+ mimeType: mime,+ };+ } else if (avatarAction.type === 'reset') {+ nextAvatarUrl = null;+ }++ // ── 审核(无变化则零请求;昵称与头像在 moderateProfile 内并行) ──+ if (+ nextDisplayName === undefined+ && nextAvatarUrl === undefined+ && pendingAvatar === undefined+ ) {+ return { ok: true };+ }+ if (nextDisplayName !== undefined || pendingAvatar !== undefined) {+ const moderation = await deps.moderateProfile({+ ...(nextDisplayName !== undefined ? { displayName: nextDisplayName } : {}),+ ...(pendingAvatar !== undefined+ ? {+ avatar: {+ bytes: pendingAvatar.buffer,+ fileName: pendingAvatar.fileName,+ mimeType: pendingAvatar.mimeType,+ },+ }+ : {}),+ });+ if (moderation === 'reject') {+ throwIpcError('CONTENT_MODERATION_REJECTED', 'profile content rejected');+ }+ if (moderation === 'cancelled') {+ throwIpcError('CONTENT_MODERATION_CANCELLED', 'profile moderation identity changed');+ }+ }++ if (pendingAvatar) {+ const uploaded = await deps.uploadAvatar({+ buffer: pendingAvatar.buffer,+ mimeType: pendingAvatar.mimeType,+ });if (!uploaded.ok) {throwIpcError('PROFILE_AVATAR_UPLOAD_FAILED',@@ -208,14 +265,9 @@ export async function updateProfile();}nextAvatarUrl = uploaded.publicUrl;- } else if (avatarAction.type === 'reset') {- nextAvatarUrl = null;}- // ── 提交(无变化则零请求) ──- if (nextDisplayName === undefined && nextAvatarUrl === undefined) {- return { ok: true };- }+ // ── 原子提交 ──const patched = await deps.patchProfile({...(nextDisplayName !== undefined ? { displayName: nextDisplayName } : {}),...(nextAvatarUrl !== undefined ? { avatarUrl: nextAvatarUrl } : {}),diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.tsindex f37e3132c4..1ba613e688 100644--- a/apps/desktop/src/main/scheduler-host/runner.ts+++ b/apps/desktop/src/main/scheduler-host/runner.ts@@ -73,6 +73,10 @@ import type { SchedulerDrizzleDb } from './storage';import { backfillSessionMeta } from './runners/_shared';import { buildSkipResultText, executePreRunHook, formatPreRunHookFailure } from './pre-run-hook';import { defaultModelFor } from './model-defaults';+import {+ cancelReleasedOutput,+ onReleasedAgentEvent,+} from '../content-moderation/outputHub.js';const ALLOWED_EFFORT = new Set<string>(['minimal',@@ -757,6 +761,7 @@ export class MakerScheduleRunner implements ScheduleRunner {this.deps.logger.info?.(`[runner] ctx.signal aborted, calling session.abort() for ${session.id}`,);+ cancelReleasedOutput(session.id);void session.abort().catch((err) => {this.deps.logger.warn?.('[runner] session.abort failed', err);});@@ -1140,6 +1145,7 @@ export class MakerScheduleRunner implements ScheduleRunner {// 不让已暂停/删除的任务在会话里继续执行(PR #972 review P2)。if (ctx.signal.aborted) {if (live) {+ cancelReleasedOutput(sessionId);void live.abort().catch((err) => {this.deps.logger.warn?.('[runner] late-dispatch abort failed', err);});@@ -1216,6 +1222,7 @@ export class MakerScheduleRunner implements ScheduleRunner {if (dispatched) {const live = this.deps.maker.getSession(sessionId);if (live) {+ cancelReleasedOutput(sessionId);void live.abort().catch((err) => {this.deps.logger.warn?.('[runner] session.abort failed', err);});@@ -1437,7 +1444,7 @@ export class MakerScheduleRunner implements ScheduleRunner {* 一个 turn 的 canonical 文本)。异常保护见 BG_TASK_IDLE_FALLBACK_MS。*/private createTurnCompletionWaiter(- session: Pick<Awaited<ReturnType<Maker['createSession']>>, 'id' | 'onEvent'>,+ session: Pick<Awaited<ReturnType<Maker['createSession']>>, 'id' | 'onEvent' | 'abort'>,): TurnCompletionWaiter {let assistantText = '';let stopped = false;@@ -1474,7 +1481,7 @@ export class MakerScheduleRunner implements ScheduleRunner {}, BG_TASK_IDLE_FALLBACK_MS);bgFallbackTimer.unref?.();};- const off = session.onEvent((ev: AgentEvent) => {+ const off = onReleasedAgentEvent(session, (ev: AgentEvent) => {// 等待后台任务期间,任何事件都说明会话还活着 → 刷新兜底计时if (waitingForBgTasks) armBgFallbackTimer();if (ev.type === 'agent_task_update') {diff --git a/apps/desktop/src/main/scheduler-host/runners/_shared.ts b/apps/desktop/src/main/scheduler-host/runners/_shared.tsindex 48e51693bd..4b6e77403a 100644--- a/apps/desktop/src/main/scheduler-host/runners/_shared.ts+++ b/apps/desktop/src/main/scheduler-host/runners/_shared.ts@@ -13,6 +13,10 @@ import type { Logger } from '@cindy/maker-scheduler';import { sessions as sessionsTable } from '../../localDb/schema';import type { SchedulerDrizzleDb } from '../storage';+import {+ cancelReleasedOutput,+ onReleasedAgentEvent,+} from '../../content-moderation/outputHub.js';/*** 修正 runner 新建 sessions 行的 metadata 列。@@ -114,6 +118,7 @@ export async function runOneTurn(off();// 超时强制 abort,agent 子进程会停止运行(不再烧 token)try {+ cancelReleasedOutput(session.id);void session.abort();} catch (err) {logger.warn?.('[runner] session.abort() on timeout failed', err);@@ -121,7 +126,7 @@ export async function runOneTurn(reject(new Error(`timeout after ${timeoutMs}ms`));}, timeoutMs);- const off = session.onEvent((ev: AgentEvent) => {+ const off = onReleasedAgentEvent(session, (ev: AgentEvent) => {if (ev.type === 'text') {const data = ev.data as { text?: string; isFinal?: boolean } | null;if (data && typeof data.text === 'string') {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex f87e7ec178..aedc975bea 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -354,6 +354,12 @@ const fanOutGhostCardUpdated = createIpcFanOut('ghosts:card-updated');const fanOutGhostSessionActivity = createIpcFanOut('ghosts:session-activity');// 用户消息被意识钩子拦下(卡槽①:renderer 把乐观气泡原地降级为被拦态)。const fanOutGhostMessageBlocked = createIpcFanOut('ghosts:user-message-blocked');+const fanOutContentModerationInputBlocked = createIpcFanOut(+ 'content-moderation:input-blocked',+);+const fanOutContentModerationOutputBlocked = createIpcFanOut(+ 'content-moderation:output-blocked',+);// 用户消息被意识钩子改写(卡槽①:renderer 把气泡正文换成改写版并留痕署名)。const fanOutGhostMessageRewritten = createIpcFanOut('ghosts:user-message-rewritten');// AI 回复被出口钩子(will-assistant-message)改写(renderer 气泡静默换文本)。@@ -854,6 +860,13 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('ghosts:dev-runtime', action, id),},+ contentModeration: {+ onInputBlocked: fanOutContentModerationInputBlocked,+ onOutputBlocked: fanOutContentModerationOutputBlocked,+ reviewUserPrompt: (text: string): Promise<'allow' | 'reject' | 'cancelled'> =>+ ipcRenderer.invoke('content-moderation:review-user-prompt', text),+ },+voiceInput: {prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }): Promise<{ ok: true }> =>ipcRenderer.invoke('voice-input:prewarm', payload),diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsxnew file mode 100644index 0000000000..bc5f4fdb84--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardOpenAiAuth.test.tsx@@ -0,0 +1,111 @@+// @vitest-environment jsdom++/**+ * OpenAI 向导必须以本次显式授权结果为完成边界。+ *+ * 系统 ~/.codex/auth.json 可能已登录,但当前 Cindy 账号尚未绑定该凭证。仅观察到+ * useCodexAuth 的 authenticated 快照时不能自动关闭向导;否则从 CLI 检测建议进入+ * OpenAI 会出现弹窗一闪即逝,且 provider 仍保持未连接。+ */++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import React from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { ProviderView } from '@cindy/model-providers';++const { triggerLogin, cancelLogin } = vi.hoisted(() => ({+ triggerLogin: vi.fn(),+ cancelLogin: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }),+}));++vi.mock('@/hooks/useCodexAuth', () => ({+ useCodexAuth: () => ({+ state: { kind: 'authenticated', authSource: 'oauth' },+ triggerLogin,+ cancelLogin,+ logout: vi.fn(),+ }),+}));++vi.mock('@/lib/toast', () => ({+ toast: { error: vi.fn(), success: vi.fn() },+}));++vi.mock('@/lib/providerModels', () => ({+ providerMonogram: () => 'O',+}));++vi.mock('@/components/icons/ProviderLogoMark', () => ({+ hasProviderLogo: () => false,+ ProviderLogoMark: () => null,+}));++import { AddProviderWizard } from '@/components/settings/AddProviderWizard';++const OPENAI_PROVIDER = {+ id: 'openai',+ name: 'OpenAI',+ source: 'builtin',+ agents: ['codex'],+ auth: { method: 'oauth' },+ routing: {},+ models: { codex: [] },+ connected: false,+} satisfies ProviderView;++beforeEach(() => {+ triggerLogin.mockReset();+ cancelLogin.mockReset();+ triggerLogin.mockResolvedValue('authenticated');+ (window as unknown as { electronAPI: unknown }).electronAPI = {+ maker: {+ listProviderPresets: vi.fn(async () => ({ presets: [] })),+ },+ };+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('AddProviderWizard — OpenAI 授权边界', () => {+ it('已有系统 Codex OAuth 快照时仍停留在授权页,不自动完成当前 Cindy 绑定', async () => {+ const onDone = vi.fn();+ render(+ <AddProviderWizard+ providers={[OPENAI_PROVIDER]}+ entry={{ kind: 'builtin', providerId: 'openai' }}+ onOpenCustomForm={vi.fn()}+ onClose={vi.fn()}+ onDone={onDone}+ />,+ );++ expect(screen.getByText('settings.providers.button.authorize')).not.toBeNull();+ await waitFor(() => expect(onDone).not.toHaveBeenCalled());+ });++ it('仅在用户点击授权且本次登录成功后完成绑定流程', async () => {+ const onDone = vi.fn();+ render(+ <AddProviderWizard+ providers={[OPENAI_PROVIDER]}+ entry={{ kind: 'builtin', providerId: 'openai' }}+ onOpenCustomForm={vi.fn()}+ onClose={vi.fn()}+ onDone={onDone}+ />,+ );++ fireEvent.click(screen.getByText('settings.providers.button.authorize'));++ await waitFor(() => expect(triggerLogin).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(onDone).toHaveBeenCalledWith('openai'));+ });+});diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex 4ebc9d51a7..b749b23bf4 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -25,7 +25,7 @@ import { Tip } from '@/components/ui/tooltip';import { createCustomProvider, type RuntimeKeys } from '@/lib/customProviders';import { uniqueCustomProviderId } from '@/lib/customProviderId';import { providerMonogram } from '@/lib/providerModels';-import { isChatGptConnectionConnected, useCodexAuth } from '@/hooks/useCodexAuth';+import { useCodexAuth } from '@/hooks/useCodexAuth';import { hasProviderLogo, ProviderLogoMark } from '@/components/icons/ProviderLogoMark';import { sortPresetsForLocale } from '@cindy/model-providers';@@ -322,21 +322,6 @@ export function AddProviderWizard({onClose();}, [loggingIn, cancelAuthorize, onClose]);- // OpenAI 走 useCodexAuth:hook 状态翻 connected 时视为完成(triggerLogin 也会返回,- // oneshot ref 保证只收口一次)。- const openaiDoneRef = useRef(false);- useEffect(() => {- if (openaiDoneRef.current) return;- if (- sel?.kind === 'oauth' &&- sel.provider.id === 'openai' &&- isChatGptConnectionConnected(codexAuth.state, false)- ) {- openaiDoneRef.current = true;- onDone('openai');- }- }, [codexAuth.state, sel, onDone]);-// ── 预设:进入 Step 3 时自动拉取模型 ─────────────────────────────────────const startFetch = useCallback(async () => {if (!sel || sel.kind !== 'preset') return;diff --git a/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx b/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsxindex 9906859ca1..cd1fb50bca 100644--- a/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';import { ConfirmDialog } from '@/components/ui/confirm-dialog';+import { extractIpcError } from '@/utils/ipcError';/*** ProfileEditDialog — 设置页用户卡片的「编辑名字 / 头像」弹窗。@@ -94,10 +95,15 @@ export function ProfileEditDialog({ open, onOpenChange }: ProfileEditDialogPropssavingRef.current = false;setSaving(false);onOpenChange(false);- } catch {+ } catch (error) {savingRef.current = false;setSaving(false);- toast.error(t('settings.userProfile.edit.saveFailed'));+ const ipcError = extractIpcError(error);+ toast.error(+ ipcError?.code === 'CONTENT_MODERATION_REJECTED'+ ? t('contentModeration.blocked')+ : t('settings.userProfile.edit.saveFailed'),+ );}}, [state, name, avatarDraft, onOpenChange, t]);diff --git a/apps/desktop/src/renderer/components/settings/UserPromptSection.tsx b/apps/desktop/src/renderer/components/settings/UserPromptSection.tsxindex 255650529d..28a86d21fe 100644--- a/apps/desktop/src/renderer/components/settings/UserPromptSection.tsx+++ b/apps/desktop/src/renderer/components/settings/UserPromptSection.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -11,6 +11,9 @@ export function UserPromptSection() {const { t } = useTranslation();const [draft, setDraft] = useState(value);+ const [saving, setSaving] = useState(false);+ const draftRef = useRef(draft);+ draftRef.current = draft;// 外部 storage 变化(其他 window 实例 setValue 触发的 storage event)时刷新草稿。// 单 Electron 窗口里几乎不会触发,留作兜底。@@ -21,12 +24,35 @@ export function UserPromptSection() {const length = draft.length;const overLimit = length > USER_PROMPT_MAX_LENGTH;const dirty = draft !== value;- const canSave = dirty && !overLimit;+ const canSave = dirty && !overLimit && !saving;- const handleSave = useCallback(() => {+ const handleSave = useCallback(async () => {if (!canSave) return;- setValue(draft);- toast.success(t('settings.personalization.toast.saved'));+ const snapshot = draft;+ setSaving(true);+ try {+ const reviewFn = window.electronAPI.contentModeration?.reviewUserPrompt;+ if (!reviewFn) {+ toast.error(t('settings.personalization.toast.saveFailed'));+ return;+ }+ const decision = await reviewFn(snapshot);+ if (decision === 'reject') {+ toast.error(t('contentModeration.blocked'));+ return;+ }+ if (decision === 'cancelled') {+ toast.error(t('settings.personalization.toast.saveFailed'));+ return;+ }+ if (draftRef.current !== snapshot) return;+ setValue(snapshot);+ toast.success(t('settings.personalization.toast.saved'));+ } catch {+ toast.error(t('settings.personalization.toast.saveFailed'));+ } finally {+ setSaving(false);+ }}, [canSave, draft, setValue, t]);const counter = useMemo(diff --git a/apps/desktop/src/renderer/components/settings/__tests__/UserPromptSection.placeholder.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/UserPromptSection.placeholder.test.tsxindex 3c1f3defb7..811c1bfdef 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/UserPromptSection.placeholder.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/UserPromptSection.placeholder.test.tsx@@ -1,18 +1,20 @@// @vitest-environment jsdom-import { render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';+const setValue = vi.fn();+vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));vi.mock('@/hooks/useUserPrompt', () => ({- useUserPrompt: () => ({ value: '', setValue: vi.fn() }),+ useUserPrompt: () => ({ value: '', setValue }),}));vi.mock('@/lib/toast', () => ({- toast: { success: vi.fn() },+ toast: { error: vi.fn(), success: vi.fn() },}));import { UserPromptSection } from '../UserPromptSection';@@ -28,4 +30,30 @@ describe('UserPromptSection placeholder', () => {expect(textarea.className).toContain('placeholder:font-normal');expect(textarea.className).toContain('placeholder:opacity-45');});++ it('审核期间继续编辑时不让旧快照覆盖新草稿', async () => {+ let resolveReview!: (decision: 'allow') => void;+ const reviewUserPrompt = vi.fn(() => new Promise<'allow'>((resolve) => {+ resolveReview = resolve;+ }));+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { contentModeration: { reviewUserPrompt } },+ });+ setValue.mockClear();++ render(<UserPromptSection />);+ const textarea = screen.getByRole('textbox', {+ name: 'settings.personalization.ariaLabel',+ });+ fireEvent.change(textarea, { target: { value: 'first draft' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.personalization.save' }));+ expect(reviewUserPrompt).toHaveBeenCalledWith('first draft');++ fireEvent.change(textarea, { target: { value: 'newer draft' } });+ await act(async () => resolveReview('allow'));++ expect(setValue).not.toHaveBeenCalled();+ expect((textarea as HTMLTextAreaElement).value).toBe('newer draft');+ });});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b895e55603..67e9ee17af 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,4 +1,7 @@{+ "contentModeration": {+ "blocked": "Sorry, we can't answer this question right now. Please rephrase your question."+ },"ipcError": {"SESSION_RUNNING": "This session is currently running a task. Please try again shortly.","CREDENTIAL_SWITCH_BUSY": "Another Codex task is still running, so this provider switch was not applied (the session keeps its previous provider). Try again after those tasks finish."@@ -1532,7 +1535,8 @@"save": "Save","overLimit": " — over limit","toast": {- "saved": "Custom instructions saved"+ "saved": "Custom instructions saved",+ "saveFailed": "Failed to save custom instructions"}},"chipMetrics": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex af222e3cbf..b2617b9b71 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,4 +1,7 @@{+ "contentModeration": {+ "blocked": "申し訳ありませんが、現在この質問には回答できません。質問の表現を変えてください。"+ },"ipcError": {"SESSION_RUNNING": "このセッションは現在タスクを実行中です。しばらくしてからもう一度お試しください。","CREDENTIAL_SWITCH_BUSY": "他の Codex タスクが実行中のため、今回の提供元切り替えは適用されませんでした(セッションは元の提供元のままです)。他のタスクが終わってからもう一度お試しください。"@@ -1531,7 +1534,8 @@"save": "保存","overLimit": " — 文字数制限を超過","toast": {- "saved": "カスタム指示を保存しました"+ "saved": "カスタム指示を保存しました",+ "saveFailed": "カスタム指示を保存できませんでした"}},"chipMetrics": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 89a2973b2c..ce4c7cfac1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,4 +1,7 @@{+ "contentModeration": {+ "blocked": "죄송하지만 현재 이 질문에는 답변해 드릴 수 없습니다. 질문 표현을 바꿔 주세요."+ },"ipcError": {"SESSION_RUNNING": "이 세션은 현재 작업을 실행 중입니다. 잠시 후 다시 시도해 주세요.","CREDENTIAL_SWITCH_BUSY": "다른 Codex 작업이 실행 중이어서 이번 제공자 전환은 적용되지 않았습니다(세션은 기존 제공자를 유지합니다). 다른 작업이 끝난 후 다시 시도해 주세요."@@ -1531,7 +1534,8 @@"save": "저장","overLimit": " — 길이 제한 초과","toast": {- "saved": "사용자 정의 지침이 저장되었습니다"+ "saved": "사용자 정의 지침이 저장되었습니다",+ "saveFailed": "사용자 정의 지침을 저장하지 못했습니다"}},"chipMetrics": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 267ba5ffd3..4b7448f4eb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,4 +1,7 @@{+ "contentModeration": {+ "blocked": "抱歉,当前问题暂时无法为您解答,请调整提问表述。"+ },"ipcError": {"SESSION_RUNNING": "当前会话正在执行任务,请稍后再试。","CREDENTIAL_SWITCH_BUSY": "其他 Codex 任务正在运行,本次来源切换未生效(会话仍使用原来源)。等其他任务结束后再试。"@@ -1556,7 +1559,8 @@"save": "保存","overLimit": " — 已超出长度限制","toast": {- "saved": "自定义指令已保存"+ "saved": "自定义指令已保存",+ "saveFailed": "自定义指令保存失败"}},"chipMetrics": {diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 16b44743c7..15dd9f7376 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -120,6 +120,7 @@ const REMOTE_HEAVY_INBOUND_CHANNELS: ReadonlySet<string> = new Set(['maker:input:projection','maker:interaction-request','maker:interaction-dismissed',+ 'content-moderation:output-blocked','local-db:messages:created','usage:message-turn-cost','maker:session-model-pref:changed',@@ -166,7 +167,11 @@ import {parseUserContent,stringifyUserContent,} from '@/lib/imageRef';-import { saveDraft as saveComposerDraft, plainTextToTiptapDoc } from '@/lib/composerDraftStore';+import {+ getDraft as getComposerDraft,+ saveDraft as saveComposerDraft,+ plainTextToTiptapDoc,+} from '@/lib/composerDraftStore';import {canStartComposerSteer,canStartQueuedSteer,@@ -3617,6 +3622,9 @@ function initGlobalListeners(): void {case 'maker:interaction-dismissed':handleInteractionDismissedRaw(push.payload);break;+ case 'content-moderation:output-blocked':+ handleContentModerationOutputBlocked(push.payload);+ break;case 'local-db:messages:created':// 远程会话的持久化消息(接管路径)→ 注入 in-memory state(同本机)。handleMessageCreatedRaw(push.payload);@@ -3832,6 +3840,78 @@ function initGlobalListeners(): void {'ghosts-user-message-blocked',);+ bindIpc(+ (cb) => window.electronAPI.contentModeration?.onInputBlocked?.(cb),+ (raw: unknown) => {+ const payload = raw as {+ sessionId?: string;+ clientId?: string;+ text?: string;+ files?: SerializedAttachedFile[];+ reason?: 'rejected' | 'cancelled';+ } | null;+ if (!payload?.sessionId || !payload.clientId || typeof payload.text !== 'string') return;++ setState(payload.sessionId, (state) => ({+ ...state,+ messages: state.messages.filter(+ (message) => !(message.clientId === payload.clientId && message.isPendingPersist),+ ),+ }));++ const existing = getComposerDraft(payload.sessionId);+ const restoredText = plainTextToTiptapDoc(payload.text);+ const text = existing?.text?.content?.length+ ? {+ type: 'doc',+ content: [+ ...(restoredText.content ?? []),+ { type: 'paragraph' },+ ...existing.text.content,+ ],+ }+ : restoredText;++ const restoredFiles = (payload.files ?? []) as AttachedFile[];+ const seen = new Set<string>();+ const attachments = [...restoredFiles, ...(existing?.attachments ?? [])].filter((file) => {+ const key = file.id || file.url || file.path;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });++ saveComposerDraft(payload.sessionId, { text, attachments });+ if (payload.reason === 'rejected') {+ toast.error(i18n.t('contentModeration.blocked'));+ }+ },+ 'content-moderation-input-blocked',+ );++ const handleContentModerationOutputBlocked = (raw: unknown): void => {+ const payload = raw as {+ sessionId?: string;+ kind?: string;+ i18nKey?: string;+ } | null;+ if (+ !payload?.sessionId+ || payload.kind !== 'blocked'+ || payload.i18nKey !== 'contentModeration.blocked'+ || !_activeViewSessions.has(payload.sessionId)+ ) {+ return;+ }+ toast.error(i18n.t('contentModeration.blocked'));+ };++ bindIpc(+ (cb) => window.electronAPI.contentModeration?.onOutputBlocked?.(cb),+ handleContentModerationOutputBlocked,+ 'content-moderation-output-blocked',+ );+// ── 意识改写(订阅槽①):用户消息正文被钩子优化 ──// main 已用改写版落库 + 送 agent;这里把乐观气泡 content 静默换成改写版// (无标记,所见即送给 AI 的),保持气泡与 AI 实收一致。乐观气泡(空闲发)diff --git a/apps/desktop/src/renderer/lib/userPrompt.constants.ts b/apps/desktop/src/renderer/lib/userPrompt.constants.tsindex 435d657fda..b02506ddad 100644--- a/apps/desktop/src/renderer/lib/userPrompt.constants.ts+++ b/apps/desktop/src/renderer/lib/userPrompt.constants.ts@@ -1,10 +1 @@-/**- * 用户级 system prompt 长度上限。- *- * 8000 chars ≈ 2k tokens —— 够写人格化指令、风格、禁用词,又不至于把 context 撑爆。- * 前端 textarea 字数提示 + Save 按钮 over-limit 判断都用这个。- *- * 这里独立成一个 constants 文件而不是住在 userPreferences.types.ts 里 ——- * 因为 userPrompt 不走服务端 UserPreferences 同步,归属不应混在一起。- */-export const USER_PROMPT_MAX_LENGTH = 8000;+export { USER_PROMPT_MAX_LENGTH } from '../../shared/userPrompt';diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 357a3a9f07..708cd730c0 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1208,6 +1208,27 @@ interface ElectronAPI {) => Promise<{ states?: Record<string, string>; state?: string }>;};+ contentModeration: {+ reviewUserPrompt: (text: string) => Promise<'allow' | 'reject' | 'cancelled'>;+ onInputBlocked: (+ callback: (payload: {+ sessionId: string;+ clientId: string;+ text: string;+ files: import('../shared/agentInputQueue').AgentInputSerializedFile[];+ reason: 'rejected' | 'cancelled';+ }) => void,+ ) => () => void;+ onOutputBlocked: (+ callback: (payload: {+ sessionId: string;+ turnId: string;+ kind: 'blocked';+ i18nKey: 'contentModeration.blocked';+ }) => void,+ ) => () => void;+ };+voiceInput: {prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }) => Promise<{ ok: true }>;getBenchmarkFixtureAudio: () => Promise<{ ok: true; path: string; wav: ArrayBuffer } | { ok: false }>;diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 2aab2ac31b..9fb5d101c9 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -109,6 +109,8 @@ export type IpcErrorCode =// 个人资料自助修改(settings → 用户卡片;服务端直写)| 'PROFILE_AVATAR_UPLOAD_FAILED' // 头像经 oss-server 预签名直传失败(presign 或 PUT 阶段)| 'PROFILE_UPDATE_FAILED' // PATCH /api/me/profile 失败(网络 / 服务端拒绝)+ | 'CONTENT_MODERATION_REJECTED' // 内容审核明确拒绝+ | 'CONTENT_MODERATION_CANCELLED' // 审核期间登录身份切换,结果作废// 会话分享(.cshare 导出/导入)| 'SHARE_FILE_INVALID' // 不是 .cshare / 头或 manifest 损坏 / payload 不是 zip| 'SHARE_PASSWORD_REQUIRED' // 文件已加密但未提供密码@@ -207,6 +209,8 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['MODEL_ACCESS_UNSUPPORTED','PROFILE_AVATAR_UPLOAD_FAILED','PROFILE_UPDATE_FAILED',+ 'CONTENT_MODERATION_REJECTED',+ 'CONTENT_MODERATION_CANCELLED','SHARE_FILE_INVALID','SHARE_PASSWORD_REQUIRED','SHARE_PASSWORD_WRONG',diff --git a/apps/desktop/src/shared/userPrompt.ts b/apps/desktop/src/shared/userPrompt.tsnew file mode 100644index 0000000000..e016be8f35--- /dev/null+++ b/apps/desktop/src/shared/userPrompt.ts@@ -0,0 +1,2 @@+/** 用户级 system prompt 的 renderer / main 共享长度上限。 */+export const USER_PROMPT_MAX_LENGTH = 8_000;diff --git a/apps/desktop/src/test/vitest/clientEndpointsFixture.ts b/apps/desktop/src/test/vitest/clientEndpointsFixture.tsindex f830f2038c..a8a281decb 100644--- a/apps/desktop/src/test/vitest/clientEndpointsFixture.ts+++ b/apps/desktop/src/test/vitest/clientEndpointsFixture.ts@@ -32,6 +32,8 @@ export const TEST_CLIENT_ENDPOINTS: ClientEndpointMap = {websiteUrl: 'https://website.test.invalid',modelAccessApiBaseUrl: 'https://model-access.test.invalid',voiceApiBaseUrl: 'https://voice.test.invalid',+ moderationSignApiBaseUrl: 'https://moderation-sign.test.invalid',+ moderationSignTestApiBaseUrl: 'https://moderation-sign-dev.test.invalid',githubApiBaseUrl: 'https://github-api.test.invalid',skillhubApiBaseUrl: 'https://skillhub.test.invalid',cdnBaseUrl: TEST_CDN_BASE_URL,diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 39f65429fb..454d0f8b30 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -374,6 +374,7 @@ import {sessionMetaWriteGuard,sessionMetaWriteQueue,sessionPendingWrites,+ useContentModerationNotice,useRemoteSessions,useSessionGoalStatus,useSessionInputProjection,@@ -640,6 +641,11 @@ export default function SessionScreen() {const revokedDevices = useRevokedDevices();const maker = useMobileMakerTransport(deviceId);const sessions = useRemoteSessions();+ const contentModerationNotice = useContentModerationNotice(sessionId);+ useEffect(() => {+ remoteSessionStore.setViewedSessionId(sessionId);+ return () => remoteSessionStore.setViewedSessionId(null);+ }, [sessionId]);const messages = useSessionMessages(sessionId, deviceId);const pending = useSessionPendingInteractions(sessionId);const inputProjection = useSessionInputProjection(sessionId);@@ -685,6 +691,32 @@ export default function SessionScreen() {const [pendingMediaAssets, setPendingMediaAssets] = useState<ContextSheetMediaAsset[]>([]);// 本机图片附件的本地预览 uri(attachmentId → file://),composer 托盘缩略图 / 全图查看用。const [attachmentPreviews, setAttachmentPreviews] = useState<Record<string, string>>({});+ useEffect(() => {+ if (!contentModerationNotice) return;+ if (contentModerationNotice.kind === 'input') {+ const restoredDraft = readComposerDraftSync(sessionId);+ if (restoredDraft !== null) setDraft(restoredDraft);+ const restoredAttachments = drainComposerAttachments(sessionId);+ if (restoredAttachments.length > 0) {+ setAttachments((current) => {+ const merged = [...restoredAttachments];+ for (const attachment of current) {+ if (merged.length >= MOBILE_MAX_ATTACHMENTS) break;+ if (merged.some((item) => item.id === attachment.id)) continue;+ merged.push(attachment);+ }+ return merged.slice(0, MOBILE_MAX_ATTACHMENTS);+ });+ }+ }+ if (+ contentModerationNotice.kind === 'output'+ || contentModerationNotice.reason === 'rejected'+ ) {+ Alert.alert('提示', '抱歉,当前问题暂时无法为您解答,请调整提问表述。');+ }+ remoteSessionStore.consumeContentModerationNotice(contentModerationNotice.revision);+ }, [contentModerationNotice, sessionId]);// composer 托盘里正被全屏查看的图片附件 id(null = 关闭)。const [composerPreviewAttachmentId, setComposerPreviewAttachmentId] = useState<string | null>(null);const [goalBusy, setGoalBusy] = useState(false);diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex dc95887bb9..105acf2845 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -1,5 +1,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { remoteSessionStore, sessionPendingWrites } from '@/session/remoteSessionStore';+import {+ clearComposerDraft,+ readComposerDraftSync,+ saveComposerDraft,+} from '@/session/composerDraftStore';+import { drainComposerAttachments } from '@/session/composerAttachmentInbox';import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';function session(id: string, patch: Partial<RemoteSession> = {}): RemoteSession {@@ -1976,4 +1982,107 @@ describe('引用调和(2026-07-18 首页重渲染风暴修复)', () => {}expect(remoteSessionStore.getSessions()).toBe(snapshot);});++ it('仅当前查看的会话消费输出审核阻断临时通知', () => {+ remoteSessionStore.setViewedSessionId('s1');+ remoteSessionStore.applyRemotePush('dev-1', 'content-moderation:output-blocked', {+ sessionId: 's2',+ turnId: 'turn-2',+ kind: 'blocked',+ i18nKey: 'contentModeration.blocked',+ });+ expect(remoteSessionStore.getContentModerationNotice('s1')).toBeNull();++ remoteSessionStore.applyRemotePush('dev-1', 'content-moderation:output-blocked', {+ sessionId: 's1',+ turnId: 'turn-1',+ kind: 'blocked',+ i18nKey: 'contentModeration.blocked',+ });+ const notice = remoteSessionStore.getContentModerationNotice('s1');+ expect(notice).toMatchObject({ sessionId: 's1', turnId: 'turn-1' });+ remoteSessionStore.consumeContentModerationNotice(notice!.revision);+ expect(remoteSessionStore.getContentModerationNotice('s1')).toBeNull();+ });++ it('恢复远程输入审核拦截的文本和附件,并移除乐观消息', () => {+ const sessionId = 's-moderation-input';+ remoteSessionStore.setViewedSessionId(sessionId);+ remoteSessionStore.appendMessage(sessionId, {+ ...message('client-blocked', sessionId),+ role: 'user',+ content: 'blocked input',+ });+ saveComposerDraft(sessionId, 'newer draft');++ remoteSessionStore.applyRemotePush('dev-1', 'content-moderation:input-blocked', {+ sessionId,+ clientId: 'client-blocked',+ text: 'blocked input',+ reason: 'rejected',+ files: [{+ id: 'image-1',+ name: 'image.png',+ path: 'xd-attachment://image-1',+ ext: '.png',+ size: 3,+ category: 'image',+ mimeType: 'image/png',+ }],+ });++ expect(remoteSessionStore.getMessages(sessionId)).toEqual([]);+ expect(readComposerDraftSync(sessionId)).toBe('blocked input\n\nnewer draft');+ expect(drainComposerAttachments(sessionId)).toEqual([+ expect.objectContaining({ id: 'image-1', category: 'image' }),+ ]);+ expect(remoteSessionStore.getContentModerationNotice(sessionId)).toMatchObject({+ kind: 'input',+ clientId: 'client-blocked',+ reason: 'rejected',+ });+ clearComposerDraft(sessionId);+ });++ it('过滤 desktop-only clipboard:// 附件,不放入 mobile composer', () => {+ const sessionId = 's-moderation-clipboard';+ remoteSessionStore.setViewedSessionId(sessionId);+ remoteSessionStore.appendMessage(sessionId, {+ ...message('client-clip', sessionId),+ role: 'user',+ content: 'pasted input',+ });++ remoteSessionStore.applyRemotePush('dev-1', 'content-moderation:input-blocked', {+ sessionId,+ clientId: 'client-clip',+ text: 'pasted input',+ reason: 'rejected',+ files: [+ {+ id: 'clip-1',+ name: 'clipboard.png',+ path: 'clipboard://tmp/paste-001.png',+ ext: '.png',+ size: 100,+ category: 'image',+ mimeType: 'image/png',+ },+ {+ id: 'real-1',+ name: 'photo.jpg',+ path: 'xd-attachment://real-1',+ ext: '.jpg',+ size: 200,+ category: 'image',+ mimeType: 'image/jpeg',+ },+ ],+ });++ const attachments = drainComposerAttachments(sessionId);+ expect(attachments).toHaveLength(1);+ expect(attachments[0]).toMatchObject({ id: 'real-1' });+ clearComposerDraft(sessionId);+ });});diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex fba68c21dd..2f99f4683e 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -19,9 +19,20 @@ import {createSessionWriteQueue,} from '@/session/swipeRowRegistry';import { cacheSessionMessages, getCachedSessionMessages } from '@/session/mobileSessionMessageCache';+import {+ readComposerDraftSync,+ saveComposerDraft,+} from '@/session/composerDraftStore';+import { queueComposerAttachment } from '@/session/composerAttachmentInbox';import { contentToPreview } from '@/utils/contentPreview';import type { MobileSystemCardType } from '@/session/systemCard';-import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';+import type {+ InputProjection,+ PendingInteraction,+ RemoteMessage,+ RemoteSerializedAttachment,+ RemoteSession,+} from '@/session/types';interface DeviceShard {deviceId: string;@@ -63,6 +74,22 @@ interface LivePlanSnapshot {toolUseId: string;}+export type ContentModerationNotice =+ | {+ kind: 'output';+ sessionId: string;+ turnId: string;+ i18nKey: 'contentModeration.blocked';+ revision: number;+ }+ | {+ kind: 'input';+ sessionId: string;+ clientId: string;+ reason: 'rejected' | 'cancelled';+ revision: number;+ };+const EMPTY_SESSION_RUN_STATUS: RemoteSessionRunStatus = Object.freeze({isRunning: false,sideTaskRunning: false,@@ -150,6 +177,9 @@ const EMPTY_TASK_UPDATES: ReadonlyMap<string, AgentTaskUpdate> = new Map();let mergedSessions: RemoteSession[] = [];let messageVersion = 0;let storeVersion = 0;+let viewedSessionId: string | null = null;+let contentModerationNotice: ContentModerationNotice | null = null;+let contentModerationNoticeRevision = 0;// 当前权威设备列表(由首页从设备列表 API reconcile 后注入)。每次重算会话时基于它 + 当前 shards(stale 侧)// 重建身份索引,用于给会话算展示用 canonicalDeviceId(把 re-link 后残留 stale shard 认领回当前设备);// 为 null 时不归一,安全退化。@@ -825,6 +855,24 @@ function recallParkedTaskUpdates(}export const remoteSessionStore = {+ setViewedSessionId(sessionId: string | null): void {+ viewedSessionId = sessionId;+ if (contentModerationNotice && contentModerationNotice.sessionId !== sessionId) {+ contentModerationNotice = null;+ emit();+ }+ },++ getContentModerationNotice(sessionId: string): ContentModerationNotice | null {+ return contentModerationNotice?.sessionId === sessionId ? contentModerationNotice : null;+ },++ consumeContentModerationNotice(revision: number): void {+ if (contentModerationNotice?.revision !== revision) return;+ contentModerationNotice = null;+ emit();+ },+// 注入当前权威设备列表(首页从 /api/device-link/devices reconcile 后调用),用于设备身份归一化。// 仅在身份索引实际变化时重算,避免每次设备列表引用变动都刷新全部会话。setDeviceIdentity(devices: readonly { deviceId: string; name: string }[]): void {@@ -1427,6 +1475,60 @@ export const remoteSessionStore = {},applyRemotePush(deviceId: string, channel: string, payload: unknown): void {+ if (channel === 'content-moderation:input-blocked') {+ if (!isRecord(payload)) return;+ const sessionId = readString(payload, 'sessionId');+ const clientId = readString(payload, 'clientId');+ const text = typeof payload.text === 'string' ? payload.text : null;+ const reason = payload.reason === 'rejected' || payload.reason === 'cancelled'+ ? payload.reason+ : null;+ if (!sessionId || !clientId || text === null || !reason) return;++ this.removeMessages(sessionId, [clientId], deviceId);+ const existingDraft = readComposerDraftSync(sessionId);+ const restoredDraft = existingDraft+ ? [text, existingDraft].filter((part) => part.length > 0).join('\n\n')+ : text;+ if (restoredDraft.length > 0) saveComposerDraft(sessionId, restoredDraft);+ for (const file of normalizeModerationInputFiles(payload.files)) {+ queueComposerAttachment(sessionId, file);+ }++ if (sessionId === viewedSessionId) {+ contentModerationNotice = {+ kind: 'input',+ sessionId,+ clientId,+ reason,+ revision: ++contentModerationNoticeRevision,+ };+ emit();+ }+ return;+ }+ if (channel === 'content-moderation:output-blocked') {+ if (!isRecord(payload)) return;+ const sessionId = readString(payload, 'sessionId');+ const turnId = readString(payload, 'turnId');+ if (+ sessionId+ && turnId+ && sessionId === viewedSessionId+ && payload.kind === 'blocked'+ && payload.i18nKey === 'contentModeration.blocked'+ ) {+ contentModerationNotice = {+ kind: 'output',+ sessionId,+ turnId,+ i18nKey: 'contentModeration.blocked',+ revision: ++contentModerationNoticeRevision,+ };+ emit();+ }+ return;+ }if (channel === SESSION_ACTIVITY_CHANNEL) {this.applySessionActivity(deviceId, payload);return;@@ -1877,6 +1979,8 @@ export const remoteSessionStore = {reseedHandlers.clear();mergedSessions = [];deviceList = null;+ viewedSessionId = null;+ contentModerationNotice = null;bumpMessageVersion();emit();},@@ -2160,10 +2264,55 @@ function readNumber(value: unknown, key: string): number | null {return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;}+function normalizeModerationInputFiles(value: unknown): RemoteSerializedAttachment[] {+ if (!Array.isArray(value)) return [];+ const categories = new Set(['image', 'pdf', 'text', 'office', 'file']);+ const normalized: RemoteSerializedAttachment[] = [];+ for (const item of value) {+ if (!isRecord(item)) continue;+ const id = readString(item, 'id');+ const name = readString(item, 'name');+ const path = readString(item, 'path');+ const ext = typeof item.ext === 'string' ? item.ext : null;+ const mimeType = typeof item.mimeType === 'string' ? item.mimeType : null;+ const size = readNumber(item, 'size');+ const category = typeof item.category === 'string' && categories.has(item.category)+ ? item.category as RemoteSerializedAttachment['category']+ : null;+ if (!id || !name || !path || ext === null || mimeType === null || size === null || !category) {+ continue;+ }+ if (path.startsWith('clipboard://')) continue;+ normalized.push({+ id,+ name,+ path,+ ext,+ size,+ category,+ mimeType,+ ...(typeof item.url === 'string' ? { url: item.url } : {}),+ ...(typeof item.originalName === 'string' ? { originalName: item.originalName } : {}),+ ...(typeof item.base64 === 'string' ? { base64: item.base64 } : {}),+ ...(typeof item.textContent === 'string' ? { textContent: item.textContent } : {}),+ ...(typeof item.truncated === 'boolean' ? { truncated: item.truncated } : {}),+ ...(typeof item.annotated === 'boolean' ? { annotated: item.annotated } : {}),+ });+ }+ return normalized;+}+export function useRemoteSessions(): RemoteSession[] {return useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getSessions);}+export function useContentModerationNotice(sessionId: string): ContentModerationNotice | null {+ return useSyncExternalStore(+ remoteSessionStore.subscribe,+ () => remoteSessionStore.getContentModerationNotice(sessionId),+ );+}+/** Subscribe to one session's message mirror without triggering cache hydration side effects. */export function useRemoteSessionMessages(sessionId: string): RemoteMessage[] {return useSyncExternalStore(diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex af41132b8b..1a3c0e0175 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -93,7 +93,7 @@ export interface RemoteMessage {systemCardType?: 'help' | 'context' | 'cost' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'auto-resume' | 'learn' | 'agent-switch';}-export type RemoteAttachmentCategory = 'image' | 'pdf' | 'text' | 'office';+export type RemoteAttachmentCategory = 'image' | 'pdf' | 'text' | 'office' | 'file';export interface RemoteFileRef {name: string;diff --git a/cindy-protocol b/cindy-protocolindex 446873069a..0f511cf09e 160000--- a/cindy-protocol+++ b/cindy-protocol@@ -1 +1 @@-Subproject commit 446873069add56c51d54a6b8aaa886a6c02093ae+Subproject commit 0f511cf09e6f056a803f76e9e2aec9ea35b04deediff --git a/config/endpoint.dev.json.example b/config/endpoint.dev.json.exampleindex 626a106dc8..e4f2fea281 100644--- a/config/endpoint.dev.json.example+++ b/config/endpoint.dev.json.example@@ -11,6 +11,8 @@"websiteUrl": "http://localhost:3000","modelAccessApiBaseUrl": "http://localhost:3339","voiceApiBaseUrl": "http://localhost:3342",+ "moderationSignApiBaseUrl": "",+ "moderationSignTestApiBaseUrl": "http://localhost:3346","githubApiBaseUrl": "http://localhost:3336","skillhubApiBaseUrl": "http://localhost:3341","cdnBaseUrl": "http://localhost:3345/cindy",diff --git a/config/endpoint.global.json b/config/endpoint.global.jsonindex 586af37873..27f70b6876 100644--- a/config/endpoint.global.json+++ b/config/endpoint.global.json@@ -10,6 +10,8 @@"websiteUrl": "https://cindy.app","modelAccessApiBaseUrl": "https://model-access.cindy.app","voiceApiBaseUrl": "https://voice.cindy.app",+ "moderationSignApiBaseUrl": "",+ "moderationSignTestApiBaseUrl": "","githubApiBaseUrl": "https://github.cindy.app","skillhubApiBaseUrl": "https://xd-skillhub.cindy.app","cdnBaseUrl": "https://hotfix.cindy.app/cindy",diff --git a/config/endpoint.json b/config/endpoint.jsonindex 4c7c9ad65c..fe2fdfb9eb 100644--- a/config/endpoint.json+++ b/config/endpoint.json@@ -10,6 +10,8 @@"websiteUrl": "https://cindy.com.cn","modelAccessApiBaseUrl": "https://model-access.cindy.com.cn","voiceApiBaseUrl": "https://voice.cindy.com.cn",+ "moderationSignApiBaseUrl": "",+ "moderationSignTestApiBaseUrl": "","githubApiBaseUrl": "https://github.cindy.com.cn","skillhubApiBaseUrl": "https://xd-skillhub.cindy.com.cn","cdnBaseUrl": "https://hotfix.cindy.com.cn/cindy",diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex 61613d907b..81a294673e 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -261,6 +261,8 @@ describe('PUSH_FORWARD_ALLOWLIST', () => {'maker:status-changed','maker:interaction-request','maker:interaction-dismissed',+ 'content-moderation:input-blocked',+ 'content-moderation:output-blocked','maker:auto-permission:fallback','maker:provider:changed','maker:schedule:event',diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex a434f2598f..de4b441a8d 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -383,6 +383,8 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set(['maker:input:projection','maker:interaction-request','maker:interaction-dismissed',+ 'content-moderation:input-blocked',+ 'content-moderation:output-blocked',// Claude Auto classifier 故障后降级到 ask;payload 带 sessionId,控制端显示同款提示。'maker:auto-permission:fallback',// 被控端 active-catalog revision 变化:控制端按 deviceId 驱逐并重拉 provider 目录。diff --git a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts b/packages/maker-shared/src/__tests__/clientEndpoints.test.tsindex c73b6fa24c..d6e2f3fa05 100644--- a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts+++ b/packages/maker-shared/src/__tests__/clientEndpoints.test.ts@@ -19,6 +19,8 @@ const VALID_MANIFEST = {websiteUrl: 'https://www.example.com',modelAccessApiBaseUrl: 'https://model-access.example.com',voiceApiBaseUrl: 'https://voice.example.com',+ moderationSignApiBaseUrl: 'https://moderation-sign.example.com',+ moderationSignTestApiBaseUrl: 'https://moderation-sign-test.example.com',githubApiBaseUrl: 'https://github-api.example.com',skillhubApiBaseUrl: 'https://skillhub.example.com',cdnBaseUrl: 'https://cdn.example.com/app',diff --git a/packages/maker-shared/src/clientEndpoints.ts b/packages/maker-shared/src/clientEndpoints.tsindex 21159fb975..85e056a82b 100644--- a/packages/maker-shared/src/clientEndpoints.ts+++ b/packages/maker-shared/src/clientEndpoints.ts@@ -86,6 +86,10 @@ export const CLIENT_ENDPOINT_KEYS = ['modelAccessApiBaseUrl',// voice-server(一期开通免费语音输入的数据面)API 基址。'voiceApiBaseUrl',+ // content-moderation short-lived signing services. Production and test are+ // separate keys so a dev build can never fall through to production HMAC.+ 'moderationSignApiBaseUrl',+ 'moderationSignTestApiBaseUrl',// github-server(用户反馈 → 官方仓 GitHub issue 的薄代理)的 API 基址。'githubApiBaseUrl',// skillhub-server(SkillHub 技能市场/发布 → XD hub 的 S2S 代理)的 API 基址。@@ -140,6 +144,8 @@ const FIELD_PROTOCOLS: Record<ClientEndpointKey, readonly string[]> = {websiteUrl: ['https:'],modelAccessApiBaseUrl: ['https:'],voiceApiBaseUrl: ['https:'],+ moderationSignApiBaseUrl: ['https:'],+ moderationSignTestApiBaseUrl: ['https:'],githubApiBaseUrl: ['https:'],skillhubApiBaseUrl: ['https:'],cdnBaseUrl: ['https:'],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e25d0783c2..6802793eb6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -57,6 +57,9 @@ importers:'@cindy/browser-control-runtime':specifier: workspace:*version: link:../../packages/browser-control-runtime+ '@cindy/content-moderation-protocol':+ specifier: workspace:*+ version: link:../../cindy-protocol/packages/content-moderation-protocol'@cindy/device-link':specifier: workspace:*version: link:../../packages/device-link@@ -687,6 +690,15 @@ importers:specifier: ^3.2.4version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+ cindy-protocol/packages/content-moderation-protocol:+ devDependencies:+ typescript:+ specifier: ^5.7.0+ version: 5.9.3+ vitest:+ specifier: ^3.2.4+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+cindy-protocol/packages/device-link-protocol:devDependencies:typescript:@@ -13976,7 +13988,9 @@ snapshots:metro-runtime: 0.84.4transitivePeerDependencies:- '@babel/core'+ - bufferutil- supports-color+ - utf-8-validate'@react-native/[email protected]': {}diff --git a/scripts/__tests__/endpoint-local-file.test.mjs b/scripts/__tests__/endpoint-local-file.test.mjsindex 58b8d81489..d17d6abe8a 100644--- a/scripts/__tests__/endpoint-local-file.test.mjs+++ b/scripts/__tests__/endpoint-local-file.test.mjs@@ -46,6 +46,8 @@ test('localhost 七件套覆写,其余字段照抄 cn 正本,返回绝对路径'assert.equal(local.authApiBaseUrl, 'http://localhost:3344');assert.equal(local.deviceLinkApiBaseUrl, 'http://localhost:3335');assert.equal(local.ossApiBaseUrl, 'http://localhost:3340');+ assert.equal(local.moderationSignApiBaseUrl, 'http://localhost:3346');+ assert.equal(local.moderationSignTestApiBaseUrl, 'http://localhost:3346');assert.equal(local.githubApiBaseUrl, 'http://localhost:3336');assert.equal(local.skillhubApiBaseUrl, 'http://localhost:3341');// 其余字段与正本一致(oauth broker 等本地不起的服务沿用远程值)@@ -82,6 +84,8 @@ test('生成物能过客户端 parser 的 allowHttp 校验(与仓内正本同一'heartbeatUrl','slackHookWsUrl','websiteUrl',+ 'moderationSignApiBaseUrl',+ 'moderationSignTestApiBaseUrl','githubApiBaseUrl','skillhubApiBaseUrl','cdnBaseUrl',diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjsindex 8c24e739e3..9539efd331 100644--- a/scripts/__tests__/restart-desktop-remote.test.mjs+++ b/scripts/__tests__/restart-desktop-remote.test.mjs@@ -7,6 +7,7 @@ import test from "node:test";import { fileURLToPath } from "node:url";import {+ applyDesktopDevEnvOverrides,devEnvPrefix,isRepositoryDesktopDevProcess,formatDesktopStartupFailure,@@ -388,3 +389,44 @@ test("devEnvPrefix passes harness envs through on Windows cmd with quote strippitest("devEnvPrefix omits harness envs when unset (whitelist stays opt-in)", () => {assert.equal(devEnvPrefix({}, "darwin"), "");});++test("devEnvPrefix passes the content moderation dev switch to Electron", () => {+ assert.equal(+ devEnvPrefix({ XDT_CONTENT_MODERATION: "1" }, "win32"),+ 'set "XDT_CONTENT_MODERATION=1" && ',+ );+});++test("desktop .env allowlists local moderation dev overrides without replacing explicit env", () => {+ const env = {+ XDT_ENDPOINT_MANIFEST_FILE: "C:\\explicit\\endpoint.json",+ };+ applyDesktopDevEnvOverrides(+ [+ "XDT_CONTENT_MODERATION=1",+ "XDT_ENDPOINT_MANIFEST_FILE=C:\\local\\moderation.json",+ "MODERATION_APP_SECRET=must-not-be-loaded",+ ].join("\n"),+ env,+ );+ assert.deepEqual(env, {+ XDT_CONTENT_MODERATION: "1",+ XDT_ENDPOINT_MANIFEST_FILE: "C:\\explicit\\endpoint.json",+ });+});++test("desktop .env overrides respect explicit empty-string env values", () => {+ const env = {+ XDT_CONTENT_MODERATION: "",+ };+ applyDesktopDevEnvOverrides(+ ["XDT_CONTENT_MODERATION=1", "XDT_ENDPOINT_MANIFEST_FILE=/some/path"].join(+ "\n",+ ),+ env,+ );+ assert.deepEqual(env, {+ XDT_CONTENT_MODERATION: "",+ XDT_ENDPOINT_MANIFEST_FILE: "/some/path",+ });+});diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjsindex d45dc33bd5..d1bdf6202f 100644--- a/scripts/restart-desktop-remote.mjs+++ b/scripts/restart-desktop-remote.mjs@@ -149,6 +149,7 @@ function ensureDesktopEnv() {} else {console.log(`==> Checked desktop env: ${path.relative(rootDir, envPath)}`);}+ return content;}function readEnvValue(content, key) {@@ -156,6 +157,21 @@ function readEnvValue(content, key) {return content.match(pattern)?.[1]?.trim() ?? '';}+/**+ * Remote dev intentionally does not load the whole desktop .env. These two+ * dev-only overrides are allowlisted so local moderation can be tested while+ * auth and the rest of the client continue to use the selected endpoint+ * manifest. Explicit process/CLI values keep precedence.+ */+export function applyDesktopDevEnvOverrides(content, env = process.env) {+ for (const key of ['XDT_CONTENT_MODERATION', 'XDT_ENDPOINT_MANIFEST_FILE']) {+ if (key in env) continue;+ const value = readEnvValue(content, key);+ if (value) env[key] = value;+ }+ return env;+}+function upsertEnvValue(content, key, value, options = {}) {const lines = content.split(/\r?\n/);const pattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*=`);@@ -457,6 +473,7 @@ export function devEnvPrefix(env = process.env, platform = process.platform) {['XDT_SCHEDULER_PASSIVE', env.XDT_SCHEDULER_PASSIVE],['XDT_ISOLATED', env.XDT_ISOLATED],['XDT_ISOLATED_NAME', env.XDT_ISOLATED_NAME],+ ['XDT_CONTENT_MODERATION', env.XDT_CONTENT_MODERATION],// 端点清单来源覆写:--endpoints-cdn(dev 走线上 CDN)/ local 模式的// endpoint.local.json 文件路径,均由主进程 clientEndpointsService 消费。['XDT_ENDPOINTS_CDN', env.XDT_ENDPOINTS_CDN],@@ -647,6 +664,10 @@ async function main() {);}console.log(`==> Desktop region: ${startupConfig.region}`);+ if (argv.includes('--content-moderation')) {+ process.env.XDT_CONTENT_MODERATION = '1';+ console.log('==> Content moderation test mode: enabled.');+ }// --passive: 定时任务被动模式 —— 本实例不参与自动触发(交给同机 primary,// 典型场景多个 dev preview 与 release/primary 共享数据时 preview 让位)。// 实现方式是置 XDT_SCHEDULER_PASSIVE=1,经 devEnvPrefix 白名单透传进新开的@@ -699,7 +720,10 @@ async function main() {fs.mkdirSync(process.env.XDT_USER_DATA_DIR, { recursive: true });console.log(`==> Isolated dev user data${isolationName ? ` (sandbox "${isolationName}")` : ''}: ${process.env.XDT_USER_DATA_DIR}`);}- if (!killOnly) ensureDesktopEnv();+ if (!killOnly) {+ const desktopEnv = ensureDesktopEnv();+ applyDesktopDevEnvOverrides(desktopEnv);+ }const devAncestor = findDevAncestor();if (devAncestor && !preserveRunning) {diff --git a/scripts/shared/endpoint-local-file.mjs b/scripts/shared/endpoint-local-file.mjsindex 189f01df4a..1a78b8f62f 100644--- a/scripts/shared/endpoint-local-file.mjs+++ b/scripts/shared/endpoint-local-file.mjs@@ -23,6 +23,7 @@ const LOCAL_DEVICE_LINK_BASE_URL = 'http://localhost:3335';const LOCAL_OSS_BASE_URL = 'http://localhost:3340';const LOCAL_MODEL_ACCESS_BASE_URL = 'http://localhost:3339';const LOCAL_VOICE_BASE_URL = 'http://localhost:3342';+const LOCAL_MODERATION_SIGN_BASE_URL = 'http://localhost:3346';const LOCAL_GITHUB_BASE_URL = 'http://localhost:3336';const LOCAL_SKILLHUB_BASE_URL = 'http://localhost:3341';@@ -45,6 +46,8 @@ export function generateEndpointLocalFile({ repoRoot }) {ossApiBaseUrl: LOCAL_OSS_BASE_URL,modelAccessApiBaseUrl: LOCAL_MODEL_ACCESS_BASE_URL,voiceApiBaseUrl: LOCAL_VOICE_BASE_URL,+ moderationSignApiBaseUrl: LOCAL_MODERATION_SIGN_BASE_URL,+ moderationSignTestApiBaseUrl: LOCAL_MODERATION_SIGN_BASE_URL,githubApiBaseUrl: LOCAL_GITHUB_BASE_URL,skillhubApiBaseUrl: LOCAL_SKILLHUB_BASE_URL,};diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex f2394b7864..a2f4ebc9b2 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -136,6 +136,7 @@ export default {noCollectableWorkspace('project-context', 'packages/project-context'),requiredUnitWorkspace('@cindy/remote-file-service', 'packages/remote-file-service'),requiredUnitWorkspace('@cindy/voice-input-core', 'packages/voice-input-core'),+ requiredUnitWorkspace('@cindy/content-moderation-protocol', 'cindy-protocol/packages/content-moderation-protocol'),noCollectableWorkspace('@cindy/device-link-protocol', 'cindy-protocol/packages/device-link-protocol'),requiredUnitWorkspace('@cindy/plugin-protocol', 'cindy-protocol/packages/plugin-protocol'),requiredUnitWorkspace('@cindy/skill-protocol', 'cindy-protocol/packages/skill-protocol'),