Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 更新重启确认说明会打断的活动类别
shenjiacheng8d4b56261a1e
diff --git a/apps/desktop/src/main/__tests__/relaunchBusyActivityIpcBoundary.test.ts b/apps/desktop/src/main/__tests__/relaunchBusyActivityIpcBoundary.test.tsindex ab25894749..bf26d15656 100644--- a/apps/desktop/src/main/__tests__/relaunchBusyActivityIpcBoundary.test.ts+++ b/apps/desktop/src/main/__tests__/relaunchBusyActivityIpcBoundary.test.ts@@ -15,6 +15,10 @@ const h = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),trusted: true,reads: 0,+ turnReads: 0,+ selects: 0,+ dbRows: [] as unknown[],+ dbError: null as Error | null,removed: [] as string[],log: {warn: vi.fn(),@@ -48,12 +52,26 @@ vi.mock('../security/trustedAppRenderer', () => ({if (!h.trusted) throw new Error('[PERMISSION_DENIED] 此操作只能从 Cindy 主页面发起');},}));+vi.mock('../localDb/client/current', () => ({+ getDbClient: () => {+ if (h.dbError) throw h.dbError;+ const chain = {+ from: () => chain,+ leftJoin: () => chain,+ where: () => Promise.resolve(h.dbRows),+ };+ return { drizzle: { select: () => { h.selects += 1; return chain; } } };+ },+}));import {RELAUNCH_BLOCKING_ACTIVITY_CHANNEL,+ RELAUNCH_BLOCKING_SUMMARY_CHANNEL,readRelaunchBackgroundActivity,+ readRelaunchBlockingActivity,registerRelaunchBusyActivityIpc,} from '../relaunchBusyActivityIpc.js';+import { readRelaunchTurnFacts } from '../relaunchTurnFacts.js';/** 每个来源都记一次读取,用来证明拒绝路径下一个都没被碰。 */function countingSources(busy: boolean) {@@ -75,6 +93,10 @@ beforeEach(() => {h.handlers.clear();h.trusted = true;h.reads = 0;+ h.turnReads = 0;+ h.selects = 0;+ h.dbRows = [];+ h.dbError = null;h.removed = [];h.log.info.mockClear();});@@ -158,3 +180,178 @@ describe('readRelaunchBackgroundActivity', () => {});});});+++/**+ * 测试价值+ * - 生产入口与可观察结果:update-relaunch:blocking-summary 与 blocking-activity handler。+ * 侧栏确认能看到全部活动类别;旧调用方仍拿到布尔,busy:false 不会因为对象而被当成有活动。+ * - Bug/规则依据:issue #5265。reasons 以前只写日志,确认句无法区分伙伴回复和其它活动。+ * - 现有覆盖缺口:原用例只断言布尔 busy,没有摘要、脱敏名字,也没有「对象被当成 true」。+ * - 最小失败输入:session-in-turn 加 background-bash;或布尔通道在全空闲时被改成返回对象。+ * - tier:unit。handler 用注入来源,不碰真实数据库以外的 readRelaunchTurnFacts 假查询。+ */+describe('relaunch blocking summary', () => {+ function sources(overrides: Record<string, unknown> = {}) {+ return () => ({+ anySessionInTurn: (): boolean => false,+ listClaudeBackgroundSessions: (): readonly string[] => [],+ anyGhostSessionBusy: (): boolean => false,+ anyBackgroundBashRunning: (): boolean => false,+ anyCindySlotJobRunning: (): boolean => false,+ anyPiSubagentRunning: (): boolean => false,+ anySchedulerRunRunning: async (): Promise<boolean> => false,+ ...overrides,+ });+ }++ it('keeps the boolean channel a real boolean when nothing is running', async () => {+ registerRelaunchBusyActivityIpc(sources(), {+ describeTurns: async () => {+ h.turnReads += 1;+ return { companions: [{ name: 'Cindy' }], conversation: false };+ },+ });+ const handler = h.handlers.get(RELAUNCH_BLOCKING_ACTIVITY_CHANNEL)!;+ await expect(handler(fakeEvent)).resolves.toBe(false);+ expect(h.turnReads).toBe(0);+ const internal = await readRelaunchBlockingActivity();+ expect(internal).toEqual({ busy: false, reasons: [] });+ });++ it('lists every readable category and a visible teammate name, not the first hit only', async () => {+ registerRelaunchBusyActivityIpc(sources({+ anySessionInTurn: () => true,+ anyBackgroundBashRunning: () => true,+ anyCindySlotJobRunning: () => true,+ anyPiSubagentRunning: () => true,+ listClaudeBackgroundSessions: () => ['claude-session'],+ anyGhostSessionBusy: () => true,+ }), {+ describeTurns: async () => {+ h.turnReads += 1;+ return {+ companions: [{ name: 'Cindy' }, { name: 'Mika' }],+ conversation: true,+ };+ },+ });+ const handler = h.handlers.get(RELAUNCH_BLOCKING_SUMMARY_CHANNEL)!;+ const result = await handler(fakeEvent);+ expect(result).toEqual({+ busy: true,+ categories: [+ 'companion',+ 'conversation',+ 'background-command',+ 'generation',+ 'subtask',+ ],+ companionNames: ['Cindy', 'Mika'],+ });+ expect(h.turnReads).toBe(1);+ expect(JSON.stringify(result)).not.toContain('claude-session');+ expect(JSON.stringify(h.log.info.mock.calls)).not.toContain('Cindy');+ });++ it('reports a scheduled run when that is the activity', async () => {+ registerRelaunchBusyActivityIpc(sources({+ anySchedulerRunRunning: async () => true,+ }), {+ describeTurns: async () => {+ h.turnReads += 1;+ return { companions: [{ name: 'Cindy' }], conversation: true };+ },+ });+ const handler = h.handlers.get(RELAUNCH_BLOCKING_SUMMARY_CHANNEL)!;+ await expect(handler(fakeEvent)).resolves.toEqual({+ busy: true,+ categories: ['scheduled-task'],+ companionNames: [],+ });+ expect(h.turnReads).toBe(0);+ });++ it('drops unsafe names and keeps only the teammate category', async () => {+ registerRelaunchBusyActivityIpc(sources({ anySessionInTurn: () => true }), {+ describeTurns: async () => ({+ companions: [{ name: '3c4c962a-1111-4111-8111-111111111111' }, { name: 'Cindy' }],+ conversation: false,+ }),+ });+ const handler = h.handlers.get(RELAUNCH_BLOCKING_SUMMARY_CHANNEL)!;+ await expect(handler(fakeEvent)).resolves.toEqual({+ busy: true,+ categories: ['companion'],+ companionNames: [],+ });+ });++ it('keeps the generic summary when any source cannot be classified', async () => {+ registerRelaunchBusyActivityIpc(sources({+ anySessionInTurn: () => { throw new Error('probe down'); },+ anyBackgroundBashRunning: () => true,+ }));+ const handler = h.handlers.get(RELAUNCH_BLOCKING_SUMMARY_CHANNEL)!;+ await expect(handler(fakeEvent)).resolves.toEqual({+ busy: true,+ categories: [],+ companionNames: [],+ });+ const booleanHandler = h.handlers.get(RELAUNCH_BLOCKING_ACTIVITY_CHANNEL)!;+ await expect(booleanHandler(fakeEvent)).resolves.toBe(true);+ });++ it('does not read activity or teammate facts for an untrusted sender', async () => {+ h.trusted = false;+ registerRelaunchBusyActivityIpc(sources({ anySessionInTurn: () => { h.reads += 1; return true; } }), {+ describeTurns: async () => {+ h.turnReads += 1;+ return { companions: [], conversation: true };+ },+ });+ const handler = h.handlers.get(RELAUNCH_BLOCKING_SUMMARY_CHANNEL)!;+ await expect(handler(fakeEvent)).rejects.toThrow('PERMISSION_DENIED');+ expect(h.reads).toBe(0);+ expect(h.turnReads).toBe(0);+ });+});++describe('readRelaunchTurnFacts', () => {+ it('classifies a visible teammate and a normal chat without returning the session id', async () => {+ h.dbRows = [+ { id: 'bot-session', source: 'bot', displayName: 'Cindy', botStatus: 'active', hiddenAt: null },+ { id: 'task-session', source: 'desktop', displayName: null, botStatus: null, hiddenAt: null },+ ];+ await expect(readRelaunchTurnFacts(['bot-session', 'task-session'])).resolves.toEqual({+ companions: [{ name: 'Cindy' }],+ conversation: true,+ });+ expect(h.selects).toBe(1);+ });++ it('does not expose a hidden teammate name', async () => {+ h.dbRows = [+ { id: 'bot-session', source: 'bot', displayName: 'Cindy', botStatus: 'active', hiddenAt: 1 },+ ];+ await expect(readRelaunchTurnFacts(['bot-session'])).resolves.toEqual({+ companions: [{ name: null }],+ conversation: false,+ });+ });++ it('returns null when the row lookup fails or a requested turn is missing', async () => {+ h.dbError = new Error('db down');+ await expect(readRelaunchTurnFacts(['bot-session'])).resolves.toBeNull();+ expect(h.selects).toBe(0);+ h.dbError = null;+ h.dbRows = [];+ await expect(readRelaunchTurnFacts(['missing-session'])).resolves.toBeNull();+ });++ it('does not query once there are too many turns to classify safely', async () => {+ const ids = Array.from({ length: 33 }, (_, index) => 'session-' + index);+ await expect(readRelaunchTurnFacts(ids)).resolves.toBeNull();+ expect(h.selects).toBe(0);+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 1e6de79d3d..8fe1d6a2f4 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -764,6 +764,7 @@ import {} from './right-sidebar-window/settings-store.js';import {anySessionInTurn,+ listInTurnSessionIds,applyCodexSpawnConfigChangeWithRestart,clearDeferredCodexRestartForOwnerBoundary,scheduleDeferredCodexRestart,@@ -1127,6 +1128,7 @@ import { configureMailAttachmentHost } from './cindy-brain/mailAttachmentUpload.import { writeTempFile, materializeDirectSendOssAttachments } from './maker-ipc/normalizeAttachments.js';import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-session-background-activity.js';import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';+import { describeRelaunchTurns } from './relaunchTurnFacts.js';import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';import { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';@@ -6251,7 +6253,9 @@ const registerIpcHandlers = () => {//// 不进 device-link allowlist:updater 类 channel 按 allowlist 顶部注释属「永不放行」,// 且远程控制端不会代替用户点被控端的更新重启。- registerRelaunchBusyActivityIpc(readRelaunchActivitySources);+ registerRelaunchBusyActivityIpc(readRelaunchActivitySources, {+ describeTurns: () => describeRelaunchTurns(() => listInTurnSessionIds(getMakerIfReady())),+ });// getMakerCore() 首次调用触发 Maker 构造,同时发起自定义 MCP 初始加载。// await 确保第一个会话的 mcpProviders 数组已填入已保存的自定义 MCP(P2 冷启动竞态修复)。getMakerCore();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnActivityTracker.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnActivityTracker.test.tsindex f7f1e5ece8..1915f53b6c 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnActivityTracker.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionTurnActivityTracker.test.ts@@ -10,6 +10,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {+ collectInTurnSessionIds,isSessionTurnDispatchBoundaryBusy,SessionTurnActivityTracker,} from '../sessionTurnActivityTracker';@@ -117,3 +118,17 @@ describe('SessionTurnActivityTracker per-session change listener', () => {expect(t.isSessionInTurn('s')).toBe(true);});});+++describe('collectInTurnSessionIds', () => {+ it('includes tracker turns and live turns that are not latched yet, once each', () => {+ const tracker = new SessionTurnActivityTracker();+ tracker.setSessionInTurn('tracked', true);+ tracker.setSessionInTurn('idle', false);+ expect(collectInTurnSessionIds(tracker, [+ { id: 'tracked', isTurnRunning: () => true },+ { id: 'live', isTurnRunning: () => true },+ { id: 'stopped', isTurnRunning: () => false },+ ])).toEqual(['tracked', 'live']);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex eff77214f7..8a02010d85 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1292,6 +1292,7 @@ import {createDeferredRestartQueueGate,} from './deferredRestartQueueWiring.js';import {+ collectInTurnSessionIds,hasAnySessionInTurn,isSessionTurnDispatchBoundaryBusy,isTerminalTurnErrorEvent,@@ -5095,6 +5096,11 @@ export function anySessionInTurn(maker?: Pick<Maker, 'listActiveSessions'> | nulreturn hasAnySessionInTurn(sessionTurnActivityTracker, maker?.listActiveSessions() ?? []);}+/** 重启会打断的 turn 会话 id:tracker 已记下的,再加上还没记上 tracker 的 live session。 */+export function listInTurnSessionIds(maker?: Pick<Maker, 'listActiveSessions'> | null): string[] {+ return collectInTurnSessionIds(sessionTurnActivityTracker, maker?.listActiveSessions() ?? []);+}+/*** /goal 生命周期旁路(setter 注入避免 register↔goal-host 环):* - goalClearObserver:clear-context(INPUT_CLEAR_SESSION)时清除该会话目标(上下文已抹,目标失去依据)。diff --git a/apps/desktop/src/main/maker-ipc/sessionTurnActivityTracker.ts b/apps/desktop/src/main/maker-ipc/sessionTurnActivityTracker.tsindex fa52413573..e419586d9a 100644--- a/apps/desktop/src/main/maker-ipc/sessionTurnActivityTracker.ts+++ b/apps/desktop/src/main/maker-ipc/sessionTurnActivityTracker.ts@@ -60,6 +60,14 @@ export class SessionTurnActivityTracker {return false;}+ listSessionsInTurn(): readonly string[] {+ const ids: string[] = [];+ for (const [sessionId, isRunning] of this.sessionInTurn) {+ if (isRunning) ids.push(sessionId);+ }+ return ids;+ }+setSessionInTurn(sessionId: string, isRunning: boolean): void {if (isRunning) this.clearScheduledSessionTurnKeepalive(sessionId);this.setInTurn(sessionId, isRunning);@@ -130,6 +138,17 @@ export interface TurnRunningSessionSnapshot {isTurnRunning?: () => boolean;}+export function collectInTurnSessionIds(+ tracker: { listSessionsInTurn(): readonly string[] },+ activeSessions: Iterable<{ id: string; isTurnRunning?: () => boolean }>,+): string[] {+ const ids = new Set(tracker.listSessionsInTurn());+ for (const session of activeSessions) {+ if (session.isTurnRunning?.()) ids.add(session.id);+ }+ return [...ids];+}+export function hasAnySessionInTurn(tracker: { anySessionInTurn(): boolean },activeSessions: Iterable<TurnRunningSessionSnapshot>,diff --git a/apps/desktop/src/main/relaunchBusyActivity.ts b/apps/desktop/src/main/relaunchBusyActivity.tsindex fff98dc533..f0a69c45f5 100644--- a/apps/desktop/src/main/relaunchBusyActivity.ts+++ b/apps/desktop/src/main/relaunchBusyActivity.ts@@ -76,7 +76,7 @@ export interface RelaunchBusyActivitySources {anySchedulerRunRunning: () => Promise<boolean>;}-/** 判定出的忙闲,附带命中的来源(只用于日志/诊断,不进 UI 文案)。 */+/** 判定出的忙闲,附带命中的来源。reasons 仍只进日志;给用户的类别在 IPC 边界另算,不把 reasons 原样送进界面。 */export interface RelaunchBusyActivity {busy: boolean;/** 命中的来源标签;fail-closed 时是抛错的那个来源。 */diff --git a/apps/desktop/src/main/relaunchBusyActivityIpc.ts b/apps/desktop/src/main/relaunchBusyActivityIpc.tsindex c69c37f753..4fae31e688 100644--- a/apps/desktop/src/main/relaunchBusyActivityIpc.ts+++ b/apps/desktop/src/main/relaunchBusyActivityIpc.ts@@ -2,25 +2,31 @@* relaunchBusyActivityIpc.ts — 「现在重启会打断什么」查询的 IPC 装配。* ---------------------------------------------------------------------------* 判定逻辑在 relaunchBusyActivity.ts(纯函数、零 Electron 依赖);这里只负责 handler 注册与- * **授权边界**。单独成文件是为了能按仓库既有的 *IpcBoundary 测试模式直接测 handler ——+ * 授权边界。单独成文件是为了能按仓库既有的 *IpcBoundary 测试模式直接测 handler ——* bootstrap-electron.ts 那个模块 import 一次就会拉起整个 app 启动链,没法单测。** sender 断言不是可选项:按 docs/dev-rules/electron-security-and-process-boundaries.md §5,* 新增 handler 不得以「旧代码没校验」为由省略 sender 验证。这个 handler 读的是全局会话 /* Claude / Ghost 活动态 —— 带 preload 的窗口被导航到不可信内容、WebView、子 frame 都能发* IPC,不校验就等于把「本机现在在跑什么」这类信息暴露给它们。+ *+ * blocking-activity 继续只回布尔。旧调用方若收到对象,会把 busy:false 的对象当成有活动。+ * 脱敏类别走另一条 channel,而且只含固定类别和已经可见的伙伴名。*/import { ipcMain } from 'electron';+import { summarizeRelaunchActivity, type RelaunchTurnFacts } from '../shared/relaunchActivitySummary.js';import { createLogger } from './logger.js';import { evaluateRelaunchBusyActivity, type RelaunchBusyActivitySources } from './relaunchBusyActivity.js';import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';export const RELAUNCH_BLOCKING_ACTIVITY_CHANNEL = 'update-relaunch:blocking-activity';+export const RELAUNCH_BLOCKING_SUMMARY_CHANNEL = 'update-relaunch:blocking-summary';const log = createLogger('relaunch-activity');let currentSources: (() => RelaunchBusyActivitySources) | undefined;+let currentDescribeTurns: (() => Promise<RelaunchTurnFacts | null>) | undefined;/** Shared by local version switching; unknown activity must not permit a restart. */export async function readRelaunchBlockingActivity() {@@ -40,31 +46,42 @@ export async function readRelaunchBackgroundActivity() {}/**- * 横幅延后轮询会反复问同一条探针,但不能把每次 busy 都打成「manual relaunch」INFO。- * Renderer 传入的 payload 不可信:只有精确 `{ silent: true }` 才静默,其余一律按手动查询打日志。+ * 横幅延后轮询会反复问同一条探针,但不能把每次 busy 都打成 manual relaunch INFO。+ * Renderer 传入的 payload 不可信:只有精确 silent:true 才静默,其余一律按手动查询打日志。*/function isSilentBusyProbe(payload: unknown): boolean {if (payload == null || typeof payload !== 'object' || Array.isArray(payload)) return false;return (payload as { silent?: unknown }).silent === true;}+async function readTurnFacts(reasons: readonly string[]): Promise<RelaunchTurnFacts | null> {+ if (!reasons.includes('session-in-turn') || !currentDescribeTurns) return null;+ try {+ return await currentDescribeTurns();+ } catch {+ return null;+ }+}+/*** 注册手动更新重启的阻断查询。*- * `sources` 用工厂形态传入(而非直接给值):handler 每次被调用都要拿**当时**的跟踪器,+ * sources 用工厂形态传入(而非直接给值):handler 每次被调用都要拿当时的跟踪器,* maker 会在 app session owner 边界被整体换掉,提前捕获会读到过期实例。*/export function registerRelaunchBusyActivityIpc(resolveSources: () => RelaunchBusyActivitySources,+ options?: { describeTurns?: () => Promise<RelaunchTurnFacts | null> },): void {currentSources = resolveSources;- // **幂等注册**,不是防御性冗余:调用点(bootstrap-electron 的 registerMakerIpcsAfterSplash)- // 在它之后还有会抛的初始化,而那个 try 的 catch 明写「下次 splash retry 再尝试」,重试时+ currentDescribeTurns = options?.describeTurns;+ // 幂等注册,不是防御性冗余:调用点(bootstrap-electron 的 registerMakerIpcsAfterSplash)+ // 在它之后还有会抛的初始化,而那个 try 的 catch 明写下次 splash retry 再尝试,重试时// makerIpcsRegistered 仍是 false —— 于是这行会被执行第二次。ipcMain.handle 对同一 channel- // 第二次注册会抛「Attempted to register a second handler」,那不只是本 handler 注册失败:- // 异常会从这里穿出去,把**排在它后面的全部 maker IPC 注册**一起掀掉,而且每次重试都卡在+ // 第二次注册会抛 Attempted to register a second handler,那不只是本 handler 注册失败:+ // 异常会从这里穿出去,把排在它后面的全部 maker IPC 注册一起掀掉,而且每次重试都卡在// 同一行 —— 结果是 maker 链路永久不可用。先 remove 再 handle,让重复调用总是收敛到- // 「一个当前有效的 handler」。+ // 一个当前有效的 handler。ipcMain.removeHandler(RELAUNCH_BLOCKING_ACTIVITY_CHANNEL);ipcMain.handle(RELAUNCH_BLOCKING_ACTIVITY_CHANNEL, async (event, payload) => {assertTrustedAppRendererEvent(event);@@ -75,4 +92,19 @@ export function registerRelaunchBusyActivityIpc(}return result.busy;});++ ipcMain.removeHandler(RELAUNCH_BLOCKING_SUMMARY_CHANNEL);+ ipcMain.handle(RELAUNCH_BLOCKING_SUMMARY_CHANNEL, async (event) => {+ assertTrustedAppRendererEvent(event);+ const result = await evaluateRelaunchBusyActivity(resolveSources());+ if (result.busy) {+ log.info('manual relaunch has live activity', { reasons: result.reasons });+ }+ const summary = summarizeRelaunchActivity(result.reasons, await readTurnFacts(result.reasons));+ return {+ busy: result.busy,+ categories: summary.categories,+ companionNames: summary.companionNames,+ };+ });}diff --git a/apps/desktop/src/main/relaunchTurnFacts.ts b/apps/desktop/src/main/relaunchTurnFacts.tsnew file mode 100644index 0000000000..b70b7a270e--- /dev/null+++ b/apps/desktop/src/main/relaunchTurnFacts.ts@@ -0,0 +1,68 @@+/**+ * relaunchTurnFacts.ts — 把正在跑的 turn 收成「伙伴 / 对话」,只为更新重启确认的摘要。+ *+ * 不改变 busy 判定。查不到、超限或数据库失败都返回 null,确认句退回通用警告。+ * 查询列只有来源和伙伴显示名,不读标题、路径、欢迎语或会话正文。+ */+import { and, eq, inArray, isNull } from 'drizzle-orm';++import {+ classifyRelaunchTurnRows,+ type RelaunchTurnFacts,+ type RelaunchTurnRow,+} from '../shared/relaunchActivitySummary.js';+import { getDbClient } from './localDb/client/current.js';+import { botProfiles, botSessionLinks, sessions } from './localDb/schema.js';++const MAX_TURN_FACTS = 32;++export async function readRelaunchTurnFacts(+ sessionIds: readonly string[],+): Promise<RelaunchTurnFacts | null> {+ const ids: string[] = [];+ const seen = new Set<string>();+ for (const id of sessionIds) {+ if (typeof id !== 'string' || id.length === 0 || seen.has(id)) continue;+ seen.add(id);+ ids.push(id);+ }+ if (ids.length === 0) return { companions: [], conversation: false };+ if (ids.length > MAX_TURN_FACTS) return null;+ try {+ const rows = await getDbClient().drizzle+ .select({+ id: sessions.id,+ source: sessions.source,+ displayName: botProfiles.displayName,+ botStatus: botProfiles.status,+ hiddenAt: botProfiles.hiddenAt,+ })+ .from(sessions)+ .leftJoin(+ botSessionLinks,+ and(eq(botSessionLinks.sessionId, sessions.id), isNull(botSessionLinks.archivedAt)),+ )+ .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))+ .where(inArray(sessions.id, ids));+ const facts: RelaunchTurnRow[] = rows.map((row) => ({+ id: row.id,+ source: row.source ?? null,+ displayName: row.displayName ?? null,+ botStatus: row.botStatus ?? null,+ hiddenAt: row.hiddenAt ?? null,+ }));+ return classifyRelaunchTurnRows(ids, facts);+ } catch {+ return null;+ }+}++export async function describeRelaunchTurns(+ listSessionIds: () => readonly string[],+): Promise<RelaunchTurnFacts | null> {+ try {+ return await readRelaunchTurnFacts(listSessionIds());+ } catch {+ return null;+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex df811c2a28..be4055ce1d 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4610,6 +4610,16 @@ contextBridge.exposeInMainWorld('electronAPI', {anyActivityBlockingRelaunch: (opts?: { silent?: boolean }): Promise<boolean> =>ipcRenderer.invoke('update-relaunch:blocking-activity', opts),+ /**+ * 同一条忙闲判定的脱敏摘要。busy 仍是布尔;categories 为空表示读不出具体类别,+ * 界面保留通用警告。不返回会话 id、路径、提示词或远程控制者。+ */+ describeRelaunchBlockingActivity: (): Promise<{+ busy: boolean;+ categories: Array<'companion' | 'conversation' | 'background-command' | 'scheduled-task' | 'generation' | 'subtask'>;+ companionNames: string[];+ }> => ipcRenderer.invoke('update-relaunch:blocking-summary'),+/*** Tell the main process to apply the downloaded update and relaunch.*/diff --git a/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx b/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsxindex e656693418..7c54adc180 100644--- a/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx@@ -371,3 +371,137 @@ describe('UpdateBanner relaunch entry', () => {expect(relaunchToUpdate).not.toHaveBeenCalled();});});+++/**+ * 测试价值+ * - 生产入口与可观察结果:UpdateBanner 的「立即重启」。有活动时确认句写出全部类别并可取消;+ * 没有活动时直接重启。取消和迟到的探针都不重启。+ * - Bug/规则依据:issue #5265。确认句以前固定是「重启会中断运行中的任务」,看不出是哪一类。+ * - 现有覆盖缺口:上面的用例只覆盖布尔探针和通用警告,没有类别摘要,也没有摘要通道上的竞态。+ * - 最小失败输入:摘要同时给出伙伴和后台命令;或摘要还在飞时点「稍后再说」/补丁被替换。+ * - tier:unit。jsdom 渲染真实组件,探针是注入的 electronAPI。+ */+describe('UpdateBanner relaunch activity summary', () => {+ function withDescribe(impl: () => Promise<unknown>) {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ anyActivityBlockingRelaunch,+ describeRelaunchBlockingActivity: impl,+ relaunchToUpdate,+ openExternal,+ clientEndpoints: { websiteUrl: 'https://cindy.ai' },+ },+ });+ }++ function deferredDescribe(): (value: unknown) => void {+ let settle!: (value: unknown) => void;+ withDescribe(() => new Promise((resolve) => { settle = resolve; }));+ return (value) => settle(value);+ }++ const namedHint = [+ 'update.banner.confirmBusyLead',+ 'update.banner.activity.companionNamedLead',+ 'Cindy',+ 'update.banner.activityNameJoiner',+ 'Mika',+ 'update.banner.activity.companionNamedTail',+ 'update.banner.activityJoinerPair',+ 'update.banner.activity.backgroundCommand',+ ].join('');++ it('names every interrupting activity and can still be cancelled', async () => {+ withDescribe(async () => ({+ busy: true,+ categories: ['background-command', 'companion'],+ companionNames: ['Cindy', 'Mika'],+ }));+ render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ expect(await screen.findByText(namedHint)).toBeTruthy();+ expect(screen.queryByText('update.banner.confirmBusyHint')).toBeNull();+ expect(anyActivityBlockingRelaunch).not.toHaveBeenCalled();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.cancelAria' }));+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'update.banner.ariaExpanded' })).toBeTruthy();+ expect(screen.queryByText(namedHint)).toBeNull();+ });++ it('hides an unsafe name and still shows the category', async () => {+ withDescribe(async () => ({+ busy: true,+ categories: ['companion'],+ companionNames: ['3c4c962a-1111-4111-8111-111111111111'],+ }));+ render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ const hint = [+ 'update.banner.confirmBusyLead',+ 'update.banner.activity.companion',+ ].join('');+ expect(await screen.findByText(hint)).toBeTruthy();+ expect(screen.queryByText('3c4c962a-1111-4111-8111-111111111111')).toBeNull();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ });++ it('keeps the generic warning when the summary has no category', async () => {+ withDescribe(async () => ({ busy: true, categories: [], companionNames: [] }));+ render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ expect(await screen.findByText('update.banner.confirmBusyHint')).toBeTruthy();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ });++ it('relaunches immediately when the summary says nothing is running', async () => {+ withDescribe(async () => ({ busy: false, categories: ['companion'], companionNames: ['Cindy'] }));+ render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ await waitFor(() => expect(relaunchToUpdate).toHaveBeenCalledTimes(1));+ expect(screen.queryByRole('button', { name: 'update.banner.confirmAria' })).toBeNull();+ });++ it('fails closed to the generic warning when the summary shape is unusable', async () => {+ withDescribe(async () => ({ categories: ['companion'] }));+ render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ expect(await screen.findByText('update.banner.confirmBusyHint')).toBeTruthy();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ });++ it('fails closed when the summary probe rejects', async () => {+ withDescribe(() => Promise.reject(new Error('ipc channel closed')));+ render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ expect(await screen.findByText('update.banner.confirmBusyHint')).toBeTruthy();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ });++ it('discards a late summary after the user dismisses the banner', async () => {+ const settle = deferredDescribe();+ const { rerender } = render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.dismissAria' }));+ rerender(<UpdateBanner isCollapsed={false} />);+ settle({ busy: false, categories: [], companionNames: [] });+ await Promise.resolve();+ await Promise.resolve();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ });++ it('discards a late summary when the ready patch is replaced', async () => {+ const settle = deferredDescribe();+ const { rerender } = render(<UpdateBanner isCollapsed={false} />);+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));+ updateStatus.current = { status: 'superseding', version: '1.2.3', errorCode: null };+ rerender(<UpdateBanner isCollapsed={false} />);+ settle({ busy: false, categories: [], companionNames: [] });+ await Promise.resolve();+ await Promise.resolve();+ expect(relaunchToUpdate).not.toHaveBeenCalled();+ expect(screen.getByText('update.banner.preparingButton')).toBeTruthy();+ });+});diff --git a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsxindex 4a776522c5..1bc303a26a 100644--- a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx+++ b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx@@ -57,6 +57,11 @@ import { useLocale } from '@/hooks/useLocale';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Tip } from '@/components/ui/tooltip';import { fetchReleaseNotes } from '@/release-notes';+import {+ formatRelaunchActivityHint,+ normalizeRelaunchActivitySummary,+ type RelaunchActivitySummary,+} from '../../../shared/relaunchActivitySummary';// 运行期端点清单(dev/packaged 都在启动阻断后有真值,烘焙兜底已退役)const websiteUrl = () => window.electronAPI.clientEndpoints.websiteUrl;@@ -83,6 +88,8 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerPconst hideUntilBusyDecision = useDeferUpdateBannerWhileBusy(status, version);// 就地中断警告态:只在点击入口时探到「有任务在跑」才进入。const [confirming, setConfirming] = useState(false);+ // 只有全部类别都读出来才替换通用警告。null = 沿用原来那句。+ const [activitySummary, setActivitySummary] = useState<RelaunchActivitySummary | null>(null);// 入口点击的 busy 探针在飞标记 —— 防重入。探针是一次 IPC round trip(毫秒级),所以// 刻意不给 loading UI(几毫秒的 spinner 只会闪一下),只用 ref 挡住连点导致的// 重复探针 / 重复重启。与 WindowControls 的关窗入口保持同样的「无 loading 态」处理。@@ -150,6 +157,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerPuseEffect(() => {if (status !== 'ready' || isWindowsRuntimeMissing || isLinuxInstallationUnsupported) {relaunchEpochRef.current += 1;+ setActivitySummary(null);setConfirming(false);}}, [status, isWindowsRuntimeMissing, isLinuxInstallationUnsupported]);@@ -196,6 +204,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP// 取消:先打标记再复位,让上面的 effect 在入口按钮重新挂载后把焦点还回去。const handleCancelConfirm = () => {restoreFocusRef.current = true;+ setActivitySummary(null);setConfirming(false);};@@ -207,6 +216,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP// 的探针结论不能反过来推翻它(否则轻则 confirming 残留、重则直接重启)。const handleDismiss = () => {relaunchEpochRef.current += 1;+ setActivitySummary(null);setConfirming(false);dismiss(status, version ?? null);};@@ -226,6 +236,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP// Main may emit exactly the same prerequisite error again. Keep the// prompt visible without relying on a false -> true error transition.if (isLinuxInstallationUnsupported) {+ setActivitySummary(null);setConfirming(false);setShowLinuxInstallationDialog(true);}@@ -268,12 +279,29 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerPif (relaunchProbeRef.current) return;relaunchProbeRef.current = true;const epoch = relaunchEpochRef.current;- // 初值取 true:探针没给出可信答案的任何路径(reject、桥同步 throw)都落在保守的那一侧。+ // 初值取 true:探针没给出可信答案的任何路径(reject、桥同步 throw、形状不对)都落在保守的那一侧。+ // 是否确认只看 busy 布尔。不能把返回对象当成 true,否则 busy 为 false 的对象也会被拦下。let hasInFlight = true;+ let summary: RelaunchActivitySummary | null = null;try {- hasInFlight = await window.electronAPI.anyActivityBlockingRelaunch();+ const describe = window.electronAPI.describeRelaunchBlockingActivity;+ if (describe) {+ const normalized = normalizeRelaunchActivitySummary(await describe());+ if (!normalized) {+ hasInFlight = true;+ } else {+ hasInFlight = normalized.busy;+ summary = normalized.busy && normalized.categories.length > 0+ ? { categories: normalized.categories, companionNames: normalized.companionNames }+ : null;+ }+ } else {+ const busy = await window.electronAPI.anyActivityBlockingRelaunch();+ hasInFlight = busy === true ? true : busy === false ? false : true;+ }} catch {hasInFlight = true;+ summary = null;} finally {relaunchProbeRef.current = false;}@@ -284,6 +312,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerPif (statusRef.current !== 'ready') return;if (hasInFlight) {setShowLinuxInstallationDialog(false);+ setActivitySummary(summary);setConfirming(true);} else handleRelaunch();};@@ -428,7 +457,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerPif (confirming && !isPreparing) {return withPrerequisiteDialogs(<div className="flex flex-col items-center gap-0.5 border-t border-sidebar-border py-1.5">- <Tip text={t('update.banner.confirmTooltip')} side="right">+ <Tip text={formatRelaunchActivityHint((key) => t(key), activitySummary) ?? t('update.banner.confirmTooltip')} side="right"><buttononClick={handleRelaunch}aria-label={t('update.banner.confirmAria')}@@ -544,7 +573,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP{isPreparing? t('update.banner.preparingSubtitle'): confirming- ? t('update.banner.confirmBusyHint')+ ? (formatRelaunchActivityHint((key) => t(key), activitySummary) ?? t('update.banner.confirmBusyHint')): t('update.banner.subtitle')}</p>{notesVersion && (diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b1e3740fa7..85ae0a03e1 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8794,6 +8794,21 @@"preparingAria": "Preparing newer version, please wait","confirmTitle": "A task is still running","confirmBusyHint": "Restarting will interrupt it",+ "confirmBusyLead": "Restarting will interrupt ",+ "activityJoiner": ", ",+ "activityJoinerPair": " and ",+ "activityJoinerLast": ", and ",+ "activityNameJoiner": ", ",+ "activity": {+ "companion": "a teammate replying",+ "companionNamedLead": "teammate ",+ "companionNamedTail": " is replying",+ "conversation": "a chat in progress",+ "backgroundCommand": "a background command",+ "scheduledTask": "a scheduled task",+ "generation": "a generation",+ "subtask": "a subtask"+ },"confirmButton": "Restart App Anyway","cancel": "Cancel","confirmTooltip": "A task is still running — restarting will interrupt it",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 3a1f93b378..795992bec5 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8762,6 +8762,21 @@"preparingAria": "新しいバージョンを準備中、お待ちください","confirmTitle": "実行中のタスクがあります","confirmBusyHint": "再起動すると中断されます",+ "confirmBusyLead": "再起動すると",+ "activityJoiner": "、",+ "activityJoinerPair": "、",+ "activityJoinerLast": "、",+ "activityNameJoiner": "、",+ "activity": {+ "companion": "仲間が返信しています",+ "companionNamedLead": "仲間 ",+ "companionNamedTail": " が返信しています",+ "conversation": "チャットが進行中です",+ "backgroundCommand": "バックグラウンドコマンド",+ "scheduledTask": "スケジュールタスク",+ "generation": "生成タスク",+ "subtask": "サブタスク"+ },"confirmButton": "それでもアプリを再起動","cancel": "キャンセル","confirmTooltip": "実行中のタスクがあります — 再起動すると中断されます",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 27768ef70c..628ef425ca 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8762,6 +8762,21 @@"preparingAria": "새 버전 준비 중입니다. 잠시만 기다려 주세요","confirmTitle": "아직 실행 중인 작업이 있습니다","confirmBusyHint": "재시작하면 작업이 중단됩니다",+ "confirmBusyLead": "다시 시작하면 중단됩니다: ",+ "activityJoiner": ", ",+ "activityJoinerPair": ", ",+ "activityJoinerLast": ", ",+ "activityNameJoiner": ", ",+ "activity": {+ "companion": "동료가 답장하는 중",+ "companionNamedLead": "동료 ",+ "companionNamedTail": " 답장 중",+ "conversation": "채팅이 진행 중",+ "backgroundCommand": "백그라운드 명령",+ "scheduledTask": "예약 작업",+ "generation": "생성 작업",+ "subtask": "하위 작업"+ },"confirmButton": "그래도 앱 재시작","cancel": "취소","confirmTooltip": "아직 실행 중인 작업이 있습니다 — 재시작하면 중단됩니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 109529e46f..b7824a0ab7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8762,6 +8762,21 @@"preparingAria": "正在准备新版本,请稍候","confirmTitle": "仍有任务在运行中","confirmBusyHint": "重启会中断运行中的任务",+ "confirmBusyLead": "重启会中断",+ "activityJoiner": "、",+ "activityJoinerPair": "、",+ "activityJoinerLast": "、",+ "activityNameJoiner": "、",+ "activity": {+ "companion": "伙伴正在回复",+ "companionNamedLead": "伙伴 ",+ "companionNamedTail": " 正在回复",+ "conversation": "对话进行中",+ "backgroundCommand": "后台命令",+ "scheduledTask": "定时任务",+ "generation": "生成任务",+ "subtask": "子任务"+ },"confirmButton": "仍要重启应用","cancel": "取消","confirmTooltip": "仍有任务在运行中,重启会中断它",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 96d792aca3..1b74c10981 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8762,6 +8762,21 @@"preparingAria": "正在準備新版本,請稍候","confirmTitle": "仍有任務在執行中","confirmBusyHint": "重啟會中斷執行中的任務",+ "confirmBusyLead": "重啟會中斷",+ "activityJoiner": "、",+ "activityJoinerPair": "、",+ "activityJoinerLast": "、",+ "activityNameJoiner": "、",+ "activity": {+ "companion": "夥伴正在回覆",+ "companionNamedLead": "夥伴 ",+ "companionNamedTail": " 正在回覆",+ "conversation": "對話進行中",+ "backgroundCommand": "背景命令",+ "scheduledTask": "定時任務",+ "generation": "生成任務",+ "subtask": "子任務"+ },"confirmButton": "仍要重啟應用","cancel": "取消","confirmTooltip": "仍有任務在執行中,重啟會中斷它",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 9aef9f4fd1..13fe9568d5 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4012,6 +4012,11 @@ interface ElectronAPI {* `silent: true` 只抑制 busy 的「manual relaunch」INFO,供横幅延后轮询;判定不变。*/anyActivityBlockingRelaunch: (opts?: { silent?: boolean }) => Promise<boolean>;+ describeRelaunchBlockingActivity: () => Promise<{+ busy: boolean;+ categories: Array<'companion' | 'conversation' | 'background-command' | 'scheduled-task' | 'generation' | 'subtask'>;+ companionNames: string[];+ }>;/** Tell main process to apply the update and relaunch the app.* `theme` is the renderer's *resolved* light/dark (after collapsing 'system'),* forwarded to cindy-updater so its splash matches the app the user is seeing. */diff --git a/apps/desktop/src/shared/relaunchActivitySummary.ts b/apps/desktop/src/shared/relaunchActivitySummary.tsnew file mode 100644index 0000000000..08fe06957b--- /dev/null+++ b/apps/desktop/src/shared/relaunchActivitySummary.ts@@ -0,0 +1,228 @@+/**+ * relaunchActivitySummary.ts — 更新重启确认里给用户看的脱敏类别。+ *+ * 忙闲仍由 relaunchBusyActivity 的布尔决定。这里只把已有来源标签翻译成固定类别,+ * 不接收会话 id、路径、提示词或远程控制者。读不全时返回空类别,调用方保留通用警告。+ */++export const RELAUNCH_ACTIVITY_CATEGORIES = [+ 'companion',+ 'conversation',+ 'background-command',+ 'scheduled-task',+ 'generation',+ 'subtask',+] as const;++export type RelaunchActivityCategory = (typeof RELAUNCH_ACTIVITY_CATEGORIES)[number];++const REASON_CATEGORY: Record<string, RelaunchActivityCategory> = {+ 'background-bash': 'background-command',+ 'scheduler-run-running': 'scheduled-task',+ 'ghost-background-activity': 'generation',+ 'cindy-slot-async-job': 'generation',+ 'pi-subagent': 'subtask',+ 'claude-background-activity': 'subtask',+};++export interface RelaunchCompanionFact {+ /** 用户已经可见的伙伴名;null 表示只能说类别。 */+ name: string | null;+}++export interface RelaunchTurnFacts {+ companions: readonly RelaunchCompanionFact[];+ conversation: boolean;+}++export interface RelaunchActivitySummary {+ categories: RelaunchActivityCategory[];+ companionNames: string[];+}++const MAX_COMPANION_NAME_LENGTH = 40;+const COMPANION_NAME_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N} ._'’-]{0,39}$/u;+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * 只接受能放进侧栏确认句的伙伴显示名。隐藏、归档、路径、链接和 uuid 都不当成名字。+ */+export function safeCompanionDisplayName(+ raw: unknown,+ visibility?: { status?: string | null; hiddenAt?: number | null },+): string | null {+ if (visibility?.hiddenAt != null) return null;+ if (visibility?.status === 'archived' || visibility?.status === 'deleting') return null;+ if (typeof raw !== 'string') return null;+ const name = raw.replace(/\s+/g, ' ').trim();+ if (!name || name.length > MAX_COMPANION_NAME_LENGTH) return null;+ if (name.includes('..') || UUID_PATTERN.test(name)) return null;+ if (!COMPANION_NAME_PATTERN.test(name)) return null;+ return name;+}++/**+ * 把已有 reason 标签译成类别。任一标签读不出类别时整份摘要作废,+ * 避免只报第一个,或报一份不完整清单让用户以为只会打断这些。+ */+export function summarizeRelaunchActivity(+ reasons: readonly string[],+ turns: RelaunchTurnFacts | null,+): RelaunchActivitySummary {+ const found = new Set<RelaunchActivityCategory>();+ let incomplete = false;+ let companionNames: string[] = [];++ for (const reason of reasons) {+ if (reason === 'session-in-turn') {+ if (!turns || (turns.companions.length === 0 && !turns.conversation)) {+ incomplete = true;+ continue;+ }+ if (turns.companions.length > 0) found.add('companion');+ if (turns.conversation) found.add('conversation');+ const unnamed = turns.companions.some((companion) => safeCompanionDisplayName(companion.name) == null);+ companionNames = unnamed+ ? []+ : turns.companions.flatMap((companion) => {+ const safe = safeCompanionDisplayName(companion.name);+ return safe ? [safe] : [];+ });+ continue;+ }+ const category = REASON_CATEGORY[reason];+ if (!category) {+ incomplete = true;+ continue;+ }+ found.add(category);+ }++ if (incomplete || found.size === 0) return { categories: [], companionNames: [] };+ return {+ categories: RELAUNCH_ACTIVITY_CATEGORIES.filter((category) => found.has(category)),+ companionNames,+ };+}++export interface RelaunchTurnRow {+ id: string;+ source: string | null;+ displayName: string | null;+ botStatus: string | null;+ hiddenAt: number | null;+}++/** 把 turn 会话行收成伙伴 / 对话。缺行、超限或来源读不出时返回 null,不猜类别。 */+export function classifyRelaunchTurnRows(+ requestedIds: readonly string[],+ rows: readonly RelaunchTurnRow[],+): RelaunchTurnFacts | null {+ const ids: string[] = [];+ const seen = new Set<string>();+ for (const id of requestedIds) {+ if (typeof id !== 'string' || id.length === 0 || seen.has(id)) continue;+ seen.add(id);+ ids.push(id);+ }+ if (ids.length === 0) return { companions: [], conversation: false };+ if (ids.length > 32) return null;++ const byId = new Map<string, RelaunchTurnRow[]>();+ for (const row of rows) {+ const list = byId.get(row.id);+ if (list) list.push(row);+ else byId.set(row.id, [row]);+ }+ if (ids.some((id) => !byId.has(id))) return null;++ const named: RelaunchCompanionFact[] = [];+ const usedNames = new Set<string>();+ let unnamedCompanion = false;+ let conversation = false;+ for (const id of ids) {+ const group = byId.get(id) ?? [];+ const source = group.find((row) => row.source)?.source ?? null;+ const bot = group.find((row) =>+ row.displayName != null || row.botStatus != null || row.hiddenAt != null);+ const isCompanion = source === 'bot' || bot != null;+ if (!source && !isCompanion) return null;+ if (isCompanion) {+ const name = safeCompanionDisplayName(bot?.displayName, {+ status: bot?.botStatus,+ hiddenAt: bot?.hiddenAt,+ });+ if (!name) {+ unnamedCompanion = true;+ continue;+ }+ if (!usedNames.has(name)) {+ usedNames.add(name);+ named.push({ name });+ }+ continue;+ }+ conversation = true;+ }+ if (unnamedCompanion) return { companions: [{ name: null }], conversation };+ return { companions: named, conversation };+}++const CATEGORY_KEYS: Record<RelaunchActivityCategory, string> = {+ companion: 'update.banner.activity.companion',+ conversation: 'update.banner.activity.conversation',+ 'background-command': 'update.banner.activity.backgroundCommand',+ 'scheduled-task': 'update.banner.activity.scheduledTask',+ generation: 'update.banner.activity.generation',+ subtask: 'update.banner.activity.subtask',+};++/** 有具体类别时返回整句;没有时返回 null,调用方继续用原来的通用警告。 */+export function formatRelaunchActivityHint(+ translate: (key: string) => string,+ summary: RelaunchActivitySummary | null,+): string | null {+ if (!summary || summary.categories.length === 0) return null;+ const parts = summary.categories.map((category) => {+ if (category === 'companion' && summary.companionNames.length > 0) {+ return translate('update.banner.activity.companionNamedLead')+ + summary.companionNames.join(translate('update.banner.activityNameJoiner'))+ + translate('update.banner.activity.companionNamedTail');+ }+ return translate(CATEGORY_KEYS[category]);+ });+ const body = parts.map((part, index) => {+ if (index === 0) return part;+ const key = parts.length === 2+ ? 'update.banner.activityJoinerPair'+ : index === parts.length - 1+ ? 'update.banner.activityJoinerLast'+ : 'update.banner.activityJoiner';+ return translate(key) + part;+ }).join('');+ return translate('update.banner.confirmBusyLead') + body;+}++/** Renderer 不信任 IPC 形状。缺 busy 布尔时返回 null,由调用方 fail closed。 */+export function normalizeRelaunchActivitySummary(value: unknown): {+ busy: boolean;+ categories: RelaunchActivityCategory[];+ companionNames: string[];+} | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const record = value as { busy?: unknown; categories?: unknown; companionNames?: unknown };+ if (typeof record.busy !== 'boolean') return null;+ const categories = RELAUNCH_ACTIVITY_CATEGORIES.filter((category) =>+ Array.isArray(record.categories) && record.categories.includes(category));+ const rawNames = Array.isArray(record.companionNames) ? record.companionNames : [];+ const companionNames: string[] = [];+ for (const name of rawNames) {+ const safe = safeCompanionDisplayName(name);+ if (!safe) return { busy: record.busy, categories, companionNames: [] };+ if (!companionNames.includes(safe)) companionNames.push(safe);+ }+ if (!categories.includes('companion')) {+ return { busy: record.busy, categories, companionNames: [] };+ }+ return { busy: record.busy, categories, companionNames };+}