Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 侧栏列表不再显示过期任务摘要 (#3078)

Dash4f3e8b005a8a
diff --git a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts
index 04171a4ced..26feb07f2d 100644
--- a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts
@@ -19,6 +19,11 @@ import {
pickTier,
maxCharsForTier,
hasSummarizableMaterial,
+ shouldGeneratePinnedCardSummary,
+ shouldVoidSummaryAfterGenerationAttempt,
+ nonCardTurnDisplayPatch,
+ shouldForceGenerateOnClear,
+ shouldScheduleForceGenerateAfterInFlight,
} from '../sessionTaskSummary.logic';
describe('pickTier — 距今时间为主轴的档位选择', () => {
@@ -98,6 +103,131 @@ describe('hasSummarizableMaterial — 空草稿跳过', () => {
});
});
+describe('shouldGeneratePinnedCardSummary', () => {
+ it('只在置顶 + 活跃 + 卡片模式时生成', () => {
+ expect(
+ shouldGeneratePinnedCardSummary({
+ status: 'active',
+ pinnedAt: 1,
+ pinnedSectionIsCard: true,
+ }),
+ ).toBe(true);
+ expect(
+ shouldGeneratePinnedCardSummary({
+ status: 'active',
+ pinnedAt: 1,
+ pinnedSectionIsCard: false,
+ }),
+ ).toBe(false);
+ expect(
+ shouldGeneratePinnedCardSummary({
+ status: 'active',
+ pinnedAt: null,
+ pinnedSectionIsCard: true,
+ }),
+ ).toBe(false);
+ expect(
+ shouldGeneratePinnedCardSummary({
+ status: 'archived',
+ pinnedAt: 1,
+ pinnedSectionIsCard: true,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('shouldVoidSummaryAfterGenerationAttempt', () => {
+ it('成功写回则留下,即使随后切出卡片', () => {
+ expect(
+ shouldVoidSummaryAfterGenerationAttempt({
+ wroteFresh: true,
+ pinnedSectionIsCard: false,
+ }),
+ ).toBe(false);
+ });
+ it('仍在卡片模式则不因失败作废', () => {
+ expect(
+ shouldVoidSummaryAfterGenerationAttempt({
+ wroteFresh: false,
+ pinnedSectionIsCard: true,
+ }),
+ ).toBe(false);
+ });
+ it('未写回且已切出卡片 → 作废旧句子', () => {
+ expect(
+ shouldVoidSummaryAfterGenerationAttempt({
+ wroteFresh: false,
+ pinnedSectionIsCard: false,
+ }),
+ ).toBe(true);
+ });
+});
+
+describe('shouldForceGenerateOnClear', () => {
+ it('切回卡片且没有生成在飞 → 可以 force 再生成', () => {
+ expect(
+ shouldForceGenerateOnClear({
+ pinnedSectionIsCard: true,
+ sessionGenerateInFlight: false,
+ }),
+ ).toBe(true);
+ });
+ it('仍在列表 → 不生成', () => {
+ expect(
+ shouldForceGenerateOnClear({
+ pinnedSectionIsCard: false,
+ sessionGenerateInFlight: false,
+ }),
+ ).toBe(false);
+ });
+ it('生成尚未 settle 时不得再入,否则 await 同一条 inFlight 死锁', () => {
+ expect(
+ shouldForceGenerateOnClear({
+ pinnedSectionIsCard: true,
+ sessionGenerateInFlight: true,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('shouldScheduleForceGenerateAfterInFlight', () => {
+ it('切回卡片且生成仍在飞 → 结算后再 force,不在当前栈 await', () => {
+ expect(
+ shouldScheduleForceGenerateAfterInFlight({
+ pinnedSectionIsCard: true,
+ sessionGenerateInFlight: true,
+ }),
+ ).toBe(true);
+ });
+ it('空闲或仍在列表 → 不预约', () => {
+ expect(
+ shouldScheduleForceGenerateAfterInFlight({
+ pinnedSectionIsCard: true,
+ sessionGenerateInFlight: false,
+ }),
+ ).toBe(false);
+ expect(
+ shouldScheduleForceGenerateAfterInFlight({
+ pinnedSectionIsCard: false,
+ sessionGenerateInFlight: true,
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('nonCardTurnDisplayPatch', () => {
+ it('列表结算必须同时清摘要并带上最新 preview', () => {
+ expect(nonCardTurnDisplayPatch('刚完成的回复')).toEqual({
+ summary: null,
+ preview: '刚完成的回复',
+ });
+ expect(nonCardTurnDisplayPatch(null)).toEqual({
+ summary: null,
+ preview: null,
+ });
+ });
+});
+
describe('sanitize — 去噪 + 句界截断', () => {
it('短文本原样(去引号/折叠空白)', () => {
expect(sanitize('"生成海报。"', SUMMARY_MAX_CHARS)).toBe('生成海报。');
@@ -151,15 +281,17 @@ describe('extractText — messages.content JSON → 纯文本', () => {
const raw = JSON.stringify({
text,
quotesEncoded: true,
- agentReferences: [{
- kind: 'message',
- start: text.indexOf(href),
- end: text.indexOf(href) + href.length,
- href,
- sessionId: 'session-a',
- messageClientId: 'message-a',
- text: 'Target message body',
- }],
+ agentReferences: [
+ {
+ kind: 'message',
+ start: text.indexOf(href),
+ end: text.indexOf(href) + href.length,
+ href,
+ sessionId: 'session-a',
+ messageClientId: 'message-a',
+ text: 'Target message body',
+ },
+ ],
});
const projected = extractText(raw, 'user');
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index 18119b36e9..69abcd89b7 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -27,6 +27,7 @@ const h = vi.hoisted(() => ({
})),
tapWindowBroadcast: vi.fn(),
summarizeSession: vi.fn(async () => undefined),
+ setPinnedSectionCardMode: vi.fn(),
routeLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>
task(),
) as SessionRouteLockMock,
@@ -58,6 +59,10 @@ vi.mock('../../../device-link/broadcast-tap.js', () => ({
}));
vi.mock('../../../sessionTaskSummary.js', () => ({
maybeGenerateSessionTaskSummary: h.summarizeSession,
+ setPinnedSectionCardMode: h.setPinnedSectionCardMode,
+}));
+vi.mock('../../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
}));
vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));
vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));
@@ -68,6 +73,7 @@ vi.mock('../../../maker-host/claude-transcript-relocation.js', () => ({
import { registerSessionIpc } from '../sessions';
import { setSessionRouteLockImplementation } from '../../sessionRouteLock';
+import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';
function createDb(): void {
const sqlite = new Database(':memory:');
@@ -113,6 +119,7 @@ function createDb(): void {
im_user_id TEXT,
summary TEXT,
provider_id TEXT,
+ codex_plan_json TEXT,
plan_mode_enabled INTEGER NOT NULL DEFAULT 0,
active_turn_started_at INTEGER,
active_turn_pid INTEGER,
@@ -137,11 +144,15 @@ function createDb(): void {
insert.run('cc-local', '/old/dir', 'cc', null, 'dialogue');
insert.run('codex-local', '/old/dir', 'codex', null, 'dialogue');
insert.run('cc-remote', '/remote/dir', 'cc', 'host-1', 'project');
- sqlite.prepare(`
+ sqlite
+ .prepare(
+ `
INSERT INTO sessions (
id, working_dir, agent_kind, remote_host_id, workspace_kind, source, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, 'review', 1, 1)
- `).run('review-local', '/review/dir', 'codex', null, 'dialogue');
+ `,
+ )
+ .run('review-local', '/review/dir', 'codex', null, 'dialogue');
h.sqlite = sqlite;
h.db = drizzle(sqlite, { schema: { messages, sessions } });
}
@@ -235,19 +246,24 @@ describe('local-db:sessions:update handler wiring', () => {
sessionId: 'codex-local',
patch: { pinnedAt, status: 'active' },
});
- expect(h.summarizeSession).toHaveBeenCalledWith('codex-local');
+ expect(h.summarizeSession).toHaveBeenCalledWith('codex-local', { force: true });
h.tapWindowBroadcast.mockClear();
h.summarizeSession.mockClear();
+ h.sqlite!.prepare('UPDATE sessions SET summary = ? WHERE id = ?').run(
+ 'PR 已提交并开启,相关单测通过。',
+ 'codex-local',
+ );
await invokeUpdate('codex-local', { pinnedAt: null });
const unpinned = h
- .sqlite!.prepare('SELECT pinned_at AS pinnedAt FROM sessions WHERE id = ?')
- .get('codex-local') as { pinnedAt: number | null };
+ .sqlite!.prepare('SELECT pinned_at AS pinnedAt, summary FROM sessions WHERE id = ?')
+ .get('codex-local') as { pinnedAt: number | null; summary: string | null };
expect(unpinned.pinnedAt).toBeNull();
+ expect(unpinned.summary).toBeNull();
expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {
sessionId: 'codex-local',
- patch: { pinnedAt: null },
+ patch: { pinnedAt: null, summary: null },
});
expect(h.summarizeSession).not.toHaveBeenCalled();
});
@@ -262,7 +278,7 @@ describe('local-db:sessions:update handler wiring', () => {
expect(persisted.pinnedAt).toBeNull();
expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {
sessionId: 'codex-local',
- patch: { pinnedAt: null },
+ patch: { pinnedAt: null, summary: null },
});
expect(h.summarizeSession).not.toHaveBeenCalled();
});
@@ -332,3 +348,33 @@ describe('local-db:sessions:update handler wiring', () => {
expect(h.relocate).not.toHaveBeenCalled();
});
});
+
+async function invokeSetPinnedCardSummaries(event: unknown, enabled: unknown): Promise<unknown> {
+ const handler = h.handlers.get('local-db:sessions:set-pinned-card-summaries');
+ if (!handler) throw new Error('set-pinned-card-summaries handler not registered');
+ return handler(event, enabled);
+}
+
+describe('local-db:sessions:set-pinned-card-summaries', () => {
+ it('boolean 主路径先校验 sender 再通知摘要开关', async () => {
+ await invokeSetPinnedCardSummaries({ senderFrame: { url: 'cindy://app' } }, true);
+ await vi.dynamicImportSettled();
+
+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledTimes(1);
+ expect(h.setPinnedSectionCardMode).toHaveBeenCalledWith(true);
+ });
+
+ it('非 boolean 走 INVALID_PARAMS,不改摘要开关', async () => {
+ await expect(invokeSetPinnedCardSummaries({}, 'yes')).rejects.toThrow(/INVALID_PARAMS/);
+ expect(assertTrustedAppRendererEvent).toHaveBeenCalledTimes(1);
+ expect(h.setPinnedSectionCardMode).not.toHaveBeenCalled();
+ });
+
+ it('sender 守卫失败时不加载摘要模块', async () => {
+ vi.mocked(assertTrustedAppRendererEvent).mockImplementationOnce(() => {
+ throw new Error('UNTRUSTED_RENDERER');
+ });
+ await expect(invokeSetPinnedCardSummaries({}, true)).rejects.toThrow('UNTRUSTED_RENDERER');
+ expect(h.setPinnedSectionCardMode).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 8f1fd67e31..559f11d11e 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -268,7 +268,8 @@ export async function recycleSessionWorktreeForStatusChange(
// quiescence and ref/worktree deletion.
await removeDeletedSessionMediaRefs(targetSessionId, mediaDb)
.then((count) => {
- if (count > 0) log.info('session media refs removed', { sessionId: targetSessionId, count });
+ if (count > 0)
+ log.info('session media refs removed', { sessionId: targetSessionId, count });
})
.catch((err) => {
log.warn('session media ref cleanup failed', {
@@ -1436,8 +1437,8 @@ export function registerSessionIpc(
if (p.clearedAt !== undefined) {
noteSessionClearBoundary(sid, p.clearedAt as string | null);
// sidebar-card-mode(codex review):summary 是基于 clear 前内容生成的,clear 后
- // 已过时;SessionCard / rail flyout 优先用 summary 而非 preview,不清就会继续
- // 显示旧任务摘要。这里一并清空,待 clear 后新一轮 turn-done 重新生成。
+ // 已过时;置顶卡片优先用 summary 而非 preview,不清就会继续显示旧任务摘要。
+ // 这里一并清空,待 clear 后新一轮 turn-done 重新生成。
await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sid));
// 广播 summary:null,让已挂载的 sidebar 立即清掉旧摘要(codex review)——renderer 的
// clearSession 乐观 patch 只带 sdkSessionId/clearedAt、不含 summary,本 update handler
@@ -1473,6 +1474,11 @@ export function registerSessionIpc(
}
const row = await selectSessionWithCount(db, sid);
if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
+ // 取消置顶后摘要不再有展示面,立刻清掉,避免列表/再次置顶前继续吃旧句。
+ if (p.pinnedAt !== undefined && row.pinnedAt == null) {
+ await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sid));
+ row.summary = null;
+ }
const updated = sessionToCamel(row);
const broadcastPatch =
p.pinnedAt === undefined
@@ -1480,7 +1486,7 @@ export function registerSessionIpc(
: {
...p,
pinnedAt: updated.pinnedAt,
- ...(updated.pinnedAt === null ? {} : { status: updated.status }),
+ ...(updated.pinnedAt === null ? { summary: null } : { status: updated.status }),
};
const projectTargetChanged = p.workspaceKind !== undefined || p.workingDir !== undefined;
const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));
@@ -1503,7 +1509,7 @@ export function registerSessionIpc(
// 模块环;fire-and-forget,模块内部自带置顶/节流守卫。
if (p.pinnedAt !== undefined && updated.pinnedAt !== null) {
void import('../../sessionTaskSummary.js').then((m) =>
- m.maybeGenerateSessionTaskSummary(sid),
+ m.maybeGenerateSessionTaskSummary(sid, { force: true }),
);
}
notifyAgentIslandSessionPatch(updated.id, {
@@ -1547,6 +1553,21 @@ export function registerSessionIpc(
await touchUserSendInDb(sid, typeof atMs === 'number' ? atMs : undefined);
},
);
+
+ // 本机 UI 偏好:置顶段是不是卡片模式。故意不进 device-link allowlist —— 摘要
+ // oneShot 只服务本机卡片展示,控制端卡片回退 preview,不把付费生成推到被控端。
+ // 新增 handler 一律校验顶层 app renderer(electron-security §5)。
+ ipcMain.handle(
+ 'local-db:sessions:set-pinned-card-summaries',
+ async (event, enabled: unknown): Promise<void> => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof enabled !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'enabled must be a boolean');
+ }
+ const m = await import('../../sessionTaskSummary.js');
+ m.setPinnedSectionCardMode(enabled);
+ },
+ );
}
export async function patchSessionMetaInDb(
@@ -1583,6 +1604,10 @@ export async function patchSessionMetaInDb(
await writeSessionPatch(db, sessionId, setObj, patch.status);
const row = await selectSessionWithCount(db, sessionId);
if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');
+ if (patch.pinnedAt !== undefined && row.pinnedAt == null) {
+ await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sessionId));
+ row.summary = null;
+ }
return sessionToCamel(row);
});
notifyAgentIslandSessionPatch(updated.id, {
@@ -1612,7 +1637,16 @@ export async function patchSessionMetaInDb(
// - sessionsStore.onPatched → patchLocal,即时反映到 sidebar(删/归档移出 active 桶、改名/置顶刷新);
// - CCAgentSessionView.onPatched → 合并进 serverSession。
// 经 tap 转发:订阅了该被控端 `sessions` topic 的控制端也即时收到这条 patched(push 驱动镜像)。
- if (isOwnerScopeCurrent(ownerScope)) broadcastSessionPatched(sessionId, patch, ownerScope);
+ const broadcastPatch =
+ patch.pinnedAt !== undefined && updated.pinnedAt == null ? { ...patch, summary: null } : patch;
+ if (isOwnerScopeCurrent(ownerScope)) {
+ broadcastSessionPatched(sessionId, broadcastPatch, ownerScope);
+ }
+ if (patch.pinnedAt !== undefined && updated.pinnedAt != null) {
+ void import('../../sessionTaskSummary.js').then((m) =>
+ m.maybeGenerateSessionTaskSummary(sessionId, { force: true }),
+ );
+ }
return updated;
}
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 8b2319f8a9..6401955191 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -89,9 +89,9 @@ export const sessions = sqliteTable(
clearedAt: integer('cleared_at'), // unix ms
pinnedAt: integer('pinned_at'), // unix ms
/**
- * 任务现状一句话摘要(sidebar-card-mode 卡片/rail flyout 展示)。
- * 由 main/sessionTaskSummary.ts 在置顶会话 turn 结束时经 oneShot 生成,
- * NULL = 尚未生成(非置顶会话不生成)。
+ * 任务现状一句话摘要(仅置顶段卡片模式展示/生成)。
+ * 由 main/sessionTaskSummary.ts 在置顶会话 turn 结束或置顶时经 oneShot 生成,
+ * 取消置顶时清空。NULL = 尚未生成或非卡片置顶。
*/
summary: text('summary'),
/**
diff --git a/apps/desktop/src/main/sessionTaskSummary.logic.ts b/apps/desktop/src/main/sessionTaskSummary.logic.ts
index fa80692ed4..e1a6ad8871 100644
--- a/apps/desktop/src/main/sessionTaskSummary.logic.ts
+++ b/apps/desktop/src/main/sessionTaskSummary.logic.ts
@@ -39,7 +39,8 @@ export const TIER_DIRECTIVE: Record<SummaryTier, string> = {
short: '本任务使用短档:不超过12字。',
long: '本任务是重度使用的会话,优先使用长档(18~26字);例外:如果会话本质是重复的单次简单操作(如反复生图、批量翻译),仍用短档。',
auto: '请按上面的档位说明,根据会话内容自行判断用短档还是长档。',
- stale: '本任务很久没有活动了:用超短档,不超过8字,几个词点出任务即可(如"生成海报。""术语表方案。")。',
+ stale:
+ '本任务很久没有活动了:用超短档,不超过8字,几个词点出任务即可(如"生成海报。""术语表方案。")。',
};
/** 档位 → sanitize 硬上限。短档也硬截,保证时间衰减回填的"length > 16 才重生成"条件能收敛。 */
@@ -161,3 +162,47 @@ export function pickTier(args: {
export function hasSummarizableMaterial(userMsg: string, assistantMsg: string): boolean {
return Boolean(userMsg || assistantMsg);
}
+
+/** 摘要只在「置顶 + 置顶段是卡片模式」时生成。列表/文字模式不花 oneShot。 */
+export function shouldGeneratePinnedCardSummary(args: {
+ status: string;
+ pinnedAt: number | string | null | undefined;
+ pinnedSectionIsCard: boolean;
+}): boolean {
+ return args.status === 'active' && args.pinnedAt != null && args.pinnedSectionIsCard;
+}
+
+/** 一次生成尝试结算后:没写出新摘要、且已经不在卡片模式 → 必须作废库里的旧句子。
+ * 成功写回的本轮摘要留下;失败 / 空结果 / 写回放弃 / 中途抛错都走这条。 */
+export function shouldVoidSummaryAfterGenerationAttempt(args: {
+ wroteFresh: boolean;
+ pinnedSectionIsCard: boolean;
+}): boolean {
+ return !args.wroteFresh && !args.pinnedSectionIsCard;
+}
+
+/** 列表/文字 turn-done:摘要必须清空,同时带上最新消息 preview。
+ * 列表不再展示 summary,若只广播 summary:null,侧栏会停在进入本轮前的旧 preview。 */
+export function nonCardTurnDisplayPatch(preview: string | null): {
+ summary: null;
+ preview: string | null;
+} {
+ return { summary: null, preview };
+}
+
+/** clear 若发现已切回卡片,只在该 session 没有生成在飞时才 force 再生成。
+ * generateSummaryOnce.finally → clear → maybeGenerate 会 await 尚未 settle 的同一条 inFlight,死锁。 */
+export function shouldForceGenerateOnClear(args: {
+ pinnedSectionIsCard: boolean;
+ sessionGenerateInFlight: boolean;
+}): boolean {
+ return args.pinnedSectionIsCard && !args.sessionGenerateInFlight;
+}
+
+/** 切回卡片时若同 session 仍在飞:不能 await 自己,但必须在结算后 force 一次。 */
+export function shouldScheduleForceGenerateAfterInFlight(args: {
+ pinnedSectionIsCard: boolean;
+ sessionGenerateInFlight: boolean;
+}): boolean {
+ return args.pinnedSectionIsCard && args.sessionGenerateInFlight;
+}
diff --git a/apps/desktop/src/main/sessionTaskSummary.ts b/apps/desktop/src/main/sessionTaskSummary.ts
index 621f63ecc6..c5c147b056 100644
--- a/apps/desktop/src/main/sessionTaskSummary.ts
+++ b/apps/desktop/src/main/sessionTaskSummary.ts
@@ -1,16 +1,17 @@
/**
* sessionTaskSummary — 置顶会话的"任务现状一句话摘要"生成器
* ---------------------------------------------------------------------------
- * sidebar-card-mode redesign:置顶卡片与折叠 rail flyout 不再展示"最近消息前
- * 140 字"原文,而是一句概括"任务是什么 + 当前进展"(对照 redesign 稿示例:
- * "重构 Prompt 模板与变量结构,已完成 3/5 个模块。")。
+ * sidebar-card-mode redesign:置顶卡片不再展示"最近消息前 140 字"原文,
+ * 而是一句概括"任务是什么 + 当前进展"。列表/文字模式不展示摘要。
*
* 生成时机(两处调用方,都 fire-and-forget):
* 1. maker-ipc/register.ts — turn 结束(done event)
* 2. localDb/ipc/sessions.ts — 会话被置顶那一刻(动态 import 避免模块环)
+ * 两处都还要满足「置顶段当前是卡片模式」(由 renderer 通知)。
+ * 列表/文字模式下的 turn-done(force)会清掉旧摘要,切回卡片时由回填按最新内容重写。
*
* 成本控制(对齐 title.ts 的口径):
- * - 仅 status='active' 且 pinnedAt 非空的会话生成(卡片/rail 只展示置顶)
+ * - 仅 status='active' 且 pinnedAt 非空、置顶段是卡片模式时生成
* - maker.oneShot 路由到低价模型(Claude → haiku / Codex → mini),maxTokens 80
* - per-session in-flight 守卫 + 20s 节流,失败 swallow
*
@@ -22,13 +23,14 @@
*/
import { BrowserWindow } from 'electron';
-import { and, count, eq, gt, isNotNull, isNull, lt, or, sql } from 'drizzle-orm';
+import { and, count, desc, eq, gt, isNotNull, isNull, lt, or, sql } from 'drizzle-orm';
import { getMaker } from './maker-host/index.js';
import { isAgentOneShotRouteDisabled } from './maker-host/model-route-guard-live.js';
import { agentSupportsOneShot, requestUtilityText } from './utility-model/oneShotCandidates.js';
import { getDbClient } from './localDb/client/current.js';
import { latestMessageText } from './localDb/latestMessageText.js';
+import { extractMessagePreview } from './localDb/mapper.js';
import { messages, sessions } from './localDb/schema.js';
import { createLogger } from './logger.js';
import { tapWindowBroadcast } from './device-link/broadcast-tap.js';
@@ -41,6 +43,11 @@ import {
pickTier,
maxCharsForTier,
hasSummarizableMaterial,
+ shouldGeneratePinnedCardSummary,
+ shouldVoidSummaryAfterGenerationAttempt,
+ nonCardTurnDisplayPatch,
+ shouldForceGenerateOnClear,
+ shouldScheduleForceGenerateAfterInFlight,
} from './sessionTaskSummary.logic.js';
const log = createLogger('sessionTaskSummary');
@@ -48,6 +55,11 @@ const log = createLogger('sessionTaskSummary');
/** 同一 session 两次生成的最小间隔。 */
const THROTTLE_MS = 20_000;
+/** 置顶段当前是否卡片模式。默认 false:renderer 未通知前不生成。 */
+let pinnedSectionIsCard = false;
+/** 一次启动只回填一轮。切到卡片模式会清掉再跑。 */
+let backfillDone = false;
+
/** 正在生成中的 session → 其生成 Promise。去重用;force 模式据此等在跑的那次结束再重生成。 */
const inFlight = new Map<string, Promise<void>>();
const lastGeneratedAt = new Map<string, number>();
@@ -69,14 +81,124 @@ function broadcastPatched(sessionId: string, patch: Record<string, unknown>): vo
}
}
-/**
- * 为置顶会话生成/刷新任务摘要。非置顶/归档/草稿自动跳过;失败 swallow。
- * fire-and-forget——调用方 `void maybeGenerateSessionTaskSummary(id)` 即可。
- */
+const messageRowid = sql<number>`rowid`;
+
+/** 与 sessions:list / 删除消息同一口径的最近可见消息 preview。 */
+async function latestVisiblePreview(sessionId: string): Promise<string | null> {
+ const db = getDbClient().drizzle;
+ const [sessionRow] = await db
+ .select({ clearedAt: sessions.clearedAt })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ const visibleAfterClear =
+ sessionRow?.clearedAt == null ? undefined : gt(messages.createdAt, sessionRow.clearedAt);
+ const [latestRow] = await db
+ .select({ content: messages.content, role: messages.role })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ sql`${messages.role} IN ('user', 'assistant')`,
+ isNull(messages.rewindAt),
+ sql`(${messages.agentMeta} IS NULL OR json_extract(${messages.agentMeta}, '$.autoResume') IS NOT 1)`,
+ visibleAfterClear,
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
+ return extractMessagePreview(latestRow?.content, latestRow?.role);
+}
+
+/** 已切回卡片:绝不继续写 null。没有生成在飞才 force 再生成;在飞则交给那次结算,避免自等待。 */
+async function stopClearBecauseCard(sessionId: string): Promise<boolean> {
+ if (!pinnedSectionIsCard) return false;
+ const sessionGenerateInFlight = inFlight.has(sessionId);
+ if (
+ shouldForceGenerateOnClear({
+ pinnedSectionIsCard: true,
+ sessionGenerateInFlight,
+ })
+ ) {
+ await maybeGenerateSessionTaskSummary(sessionId, { force: true });
+ return true;
+ }
+ if (
+ shouldScheduleForceGenerateAfterInFlight({
+ pinnedSectionIsCard: true,
+ sessionGenerateInFlight,
+ })
+ ) {
+ const pending = inFlight.get(sessionId);
+ if (pending) {
+ void pending
+ .catch(() => undefined)
+ .then(() => {
+ if (!pinnedSectionIsCard) return;
+ return maybeGenerateSessionTaskSummary(sessionId, { force: true });
+ });
+ }
+ }
+ return true;
+}
+
+/** 列表/文字模式下作废旧摘要,并补上最新 preview。不 bump updatedAt。
+ * 读/写之间用户可能已切回卡片:那时不能再抹掉摘要(回填可能刚因非空跳过),
+ * 且当前没有生成在飞时才 force 再生成——不得从 generateSummaryOnce.finally 再入 inFlight。 */
+async function clearSessionTaskSummary(sessionId: string): Promise<void> {
+ try {
+ if (await stopClearBecauseCard(sessionId)) return;
+ let preview: string | null = null;
+ try {
+ preview = await latestVisiblePreview(sessionId);
+ } catch (err) {
+ log.warn('latest visible preview for list settle failed (swallowed)', {
+ sessionId,
+ error: String(err),
+ });
+ }
+ if (await stopClearBecauseCard(sessionId)) return;
+ const db = getDbClient().drizzle;
+ const [row] = await db
+ .select({ summary: sessions.summary })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (row?.summary) {
+ if (await stopClearBecauseCard(sessionId)) return;
+ await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sessionId));
+ if (await stopClearBecauseCard(sessionId)) return;
+ }
+ lastGeneratedAt.delete(sessionId);
+ broadcastPatched(sessionId, nonCardTurnDisplayPatch(preview));
+ } catch (err) {
+ log.warn('clear stale task summary failed (swallowed)', {
+ sessionId,
+ error: String(err),
+ });
+ }
+}
+
+/** renderer 在置顶段显示模式变化时通知。切到卡片会重跑一次置顶回填。 */
+export function setPinnedSectionCardMode(enabled: boolean): void {
+ const next = enabled === true;
+ const was = pinnedSectionIsCard;
+ pinnedSectionIsCard = next;
+ if (next && !was) {
+ backfillDone = false;
+ void backfillPinnedSessionSummaries();
+ }
+}
+
export async function maybeGenerateSessionTaskSummary(
sessionId: string,
opts: { force?: boolean } = {},
): Promise<void> {
+ if (!pinnedSectionIsCard) {
+ // turn-done 是权威边界:列表态不生成,但必须作废旧摘要,否则切回卡片会先露出上一轮句子。
+ if (opts.force) await clearSessionTaskSummary(sessionId);
+ return;
+ }
const existing = inFlight.get(sessionId);
if (existing) {
if (!opts.force) return; // 已有生成在跑 → 去重跳过
@@ -102,6 +224,7 @@ export async function maybeGenerateSessionTaskSummary(
/** 实际生成一次:读素材 → 选档 → oneShot → 写回前重查 → 落库 + 广播。失败 swallow。 */
async function generateSummaryOnce(sessionId: string): Promise<void> {
+ let wroteFresh = false;
try {
const db = getDbClient().drizzle;
const [session] = await db
@@ -118,7 +241,16 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
- if (!session || session.status !== 'active' || session.pinnedAt == null) return;
+ if (
+ !session ||
+ !shouldGeneratePinnedCardSummary({
+ status: session.status,
+ pinnedAt: session.pinnedAt,
+ pinnedSectionIsCard,
+ })
+ ) {
+ return;
+ }
const isScheduled = isScheduledSession(session.source, session.title);
// 消息计数与 latestMessageText 同口径地尊重 /clear 边界——只数 clearedAt 之后、
@@ -130,7 +262,10 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
const [userMsg, assistantMsg, [msgCount]] = await Promise.all([
latestMessageText(sessionId, 'user'),
latestMessageText(sessionId, 'assistant'),
- db.select({ n: count() }).from(messages).where(and(...msgCountConds)),
+ db
+ .select({ n: count() })
+ .from(messages)
+ .where(and(...msgCountConds)),
]);
// 没有任何对话素材(空草稿被置顶)——没东西可总结
if (!hasSummarizableMaterial(userMsg, assistantMsg)) return;
@@ -144,7 +279,10 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
const inactiveMs = Date.now() - (session.userSendAt ?? session.updatedAt);
const tier = pickTier({ inactiveMs, messageCount, isScheduled });
- const agentKind = session.agentKind === 'codex' || session.agentKind === 'pi' ? session.agentKind : 'claude-code';
+ const agentKind =
+ session.agentKind === 'codex' || session.agentKind === 'pi'
+ ? session.agentKind
+ : 'claude-code';
const prompt = SUMMARY_PROMPT(session.title, userMsg, assistantMsg, tier);
// 模型走系统统一配置:优先用"轻量任务模型链"(utility-model,与起标题同源,
// 由 getUtilityModelChainProfiles 决定),配置缺失/不可用时再回退到 agent 自带的
@@ -160,7 +298,7 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
// 那样跨 agent 兜底 —— 会话 agent 不支持 oneShot 时直接跳过兜底(仅靠 utility-model)。
const text = utility.ok
? utility.text
- : (!agentSupportsOneShot(agentKind) || (await isAgentOneShotRouteDisabled(agentKind)))
+ : !agentSupportsOneShot(agentKind) || (await isAgentOneShotRouteDisabled(agentKind))
? ''
: await getMaker().oneShot(agentKind, prompt, { maxTokens: 120 });
const summary = sanitize(text, maxCharsForTier(tier));
@@ -182,12 +320,15 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
+ if (!cur || cur.clearedAt !== session.clearedAt || cur.userSendAt !== session.userSendAt) {
+ return;
+ }
if (
- !cur ||
- cur.status !== 'active' ||
- cur.pinnedAt == null ||
- cur.clearedAt !== session.clearedAt ||
- cur.userSendAt !== session.userSendAt
+ !shouldGeneratePinnedCardSummary({
+ status: cur.status,
+ pinnedAt: cur.pinnedAt,
+ pinnedSectionIsCard,
+ })
) {
return;
}
@@ -195,17 +336,27 @@ async function generateSummaryOnce(sessionId: string): Promise<void> {
// 直写 summary,不 bump updatedAt——摘要刷新不应引起 sidebar 重排
await db.update(sessions).set({ summary }).where(eq(sessions.id, sessionId));
lastGeneratedAt.set(sessionId, Date.now());
+ wroteFresh = true;
broadcastPatched(sessionId, { summary });
} catch (err) {
log.warn('generate task summary failed (swallowed)', {
sessionId,
error: String(err),
});
+ } finally {
+ // 不变量:生成尝试一旦开始,结算时若不在卡片模式且没写出新摘要,旧句子必须作废。
+ // 覆盖成功写回以外的全部出口(空结果 / 抛错 / 写回放弃 / 中途 return)。
+ if (
+ shouldVoidSummaryAfterGenerationAttempt({
+ wroteFresh,
+ pinnedSectionIsCard,
+ })
+ ) {
+ await clearSessionTaskSummary(sessionId);
+ }
}
}
-/** 一次启动只回填一轮。 */
-let backfillDone = false;
/** 回填上限——置顶通常个位数,封顶防极端数据。 */
const BACKFILL_MAX = 20;
@@ -217,6 +368,7 @@ const BACKFILL_MAX = 20;
* 久置会话不会再有 turn-done,启动巡检是衰减唯一的执行点
*/
export async function backfillPinnedSessionSummaries(): Promise<void> {
+ if (!pinnedSectionIsCard) return;
if (backfillDone) return;
backfillDone = true;
try {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index d17e28a6af..31a6088c5d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4710,6 +4710,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('local-db:sessions:update', id, patch),
touchUserSend: (id: string, atMs?: number): Promise<void> =>
ipcRenderer.invoke('local-db:sessions:touchUserSend', id, atMs),
+ setPinnedCardSummaries: (enabled: boolean): Promise<void> =>
+ ipcRenderer.invoke('local-db:sessions:set-pinned-card-summaries', enabled),
/** interrupted-turn-resume:「疑似中断」(startedAt > endedAt)的 active 会话 id。 */
interruptedPending: (): Promise<string[]> =>
ipcRenderer.invoke('local-db:sessions:interrupted-pending'),
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 0a2fc6c614..640f59a6d9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -2601,9 +2601,14 @@ function ExpandedView({
return;
}
// 同 handleRename:回滚值刻意仍读 sessions,不换成 sessionsById。
- const oldPinnedAt = sessionsRef.current.find((s) => s.id === sessionId)?.pinnedAt ?? null;
+ const current = sessionsRef.current.find((s) => s.id === sessionId);
+ const oldPinnedAt = current?.pinnedAt ?? null;
+ const oldSummary = current?.summary ?? null;
const newPinnedAt = currentlyPinned ? null : new Date().toISOString();
- patchLocal(sessionId, { pinnedAt: newPinnedAt });
+ patchLocal(
+ sessionId,
+ currentlyPinned ? { pinnedAt: null, summary: null } : { pinnedAt: newPinnedAt },
+ );
// pin / re-pin 时把它顶到 manualPinnedOrder 首位,否则带着老 rank 会卡回原位。
// unpin 不主动从 order 里删(无害,下次 drag 触发的 normalize 会顺手 GC)。
if (!currentlyPinned) {
@@ -2618,7 +2623,12 @@ function ExpandedView({
} catch (err) {
log.error('[session pin]', err);
toast.error(t('ccAgent.sidebar.pinFailed'));
- patchLocal(sessionId, { pinnedAt: oldPinnedAt });
+ patchLocal(
+ sessionId,
+ currentlyPinned
+ ? { pinnedAt: oldPinnedAt, summary: oldSummary }
+ : { pinnedAt: oldPinnedAt },
+ );
}
},
// 只依赖 filter.promotePin(useCallback 稳定),不要整个 filter ——
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts
index 6837d298e9..2e65ffb8ab 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionHardwareTaskActions.ts
@@ -42,15 +42,19 @@ export function useSessionHardwareTaskActions({
return;
}
const newPinnedAt = pinnedAt ? null : new Date().toISOString();
- patchLocal?.(sessionId, { pinnedAt: newPinnedAt });
+ const oldSummary = session?.summary ?? null;
+ patchLocal?.(
+ sessionId,
+ pinnedAt ? { pinnedAt: null, summary: null } : { pinnedAt: newPinnedAt },
+ );
try {
await sessionService.patchMeta(sessionId, { pinnedAt: newPinnedAt });
} catch (err) {
log.error('[session pin]', err);
toast.error(t('ccAgent.sidebar.pinFailed'));
- patchLocal?.(sessionId, { pinnedAt });
+ patchLocal?.(sessionId, pinnedAt ? { pinnedAt, summary: oldSummary } : { pinnedAt });
}
- }, [onRemoteWriteBlocked, patchLocal, pinnedAt, remoteWritesBlocked, sessionId, t]);
+ }, [onRemoteWriteBlocked, patchLocal, pinnedAt, remoteWritesBlocked, session, sessionId, t]);
const archive = useCallback(async () => {
if (!sessionId) return;
@@ -76,7 +80,9 @@ export function useSessionHardwareTaskActions({
title: t('ccAgent.sidebar.confirmArchive.title'),
description:
t('ccAgent.sidebar.confirmArchive.description') +
- (preflight === 'dirty' ? ' ' + t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning') : ''),
+ (preflight === 'dirty'
+ ? ' ' + t('ccAgent.sidebar.confirmArchive.dirtyWorktreeWarning')
+ : ''),
confirmText: t('ccAgent.sidebar.confirmArchive.confirm'),
cancelText: t('ccAgent.sidebar.confirmArchive.cancel'),
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
index 5352728052..9988f5abb8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/RailNav.tsx
@@ -30,6 +30,7 @@ import {
import { AttentionDot } from '@/components/sidebar/AttentionDot';
import { SortableList } from '@/components/sidebar/SortableList';
import { useReducedMotion } from '@/hooks/useReducedMotion';
+import { useSidebarCardMode } from '@/hooks/useSidebarCardMode';
import { Tip } from '@/components/ui/tooltip';
import { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { projectIdentityKeyForSession } from '../lib/projectGrouping';
@@ -37,6 +38,7 @@ import { getSessionDisplayTitle } from '../lib/sessionDisplayTitle';
import { SessionStatusIcon } from './SessionStatusIcon';
import { formatSidebarTime } from '../lib/formatSidebarTime';
import { railPanelStore, type RailPanelSection } from './railPanelStore';
+import { resolveSessionCardBody } from './sessionCardPreview';
/** 预览卡宽度(px)——旧 RailFlyout 同宽。 */
const PREVIEW_WIDTH = 208;
@@ -126,7 +128,13 @@ function SessionPreviewCard({ preview }: { preview: PreviewState }) {
}, [preview]);
const { session, isRunning, hasUnread } = preview;
- const body = session.summary ?? session.preview ?? null;
+ const { mode: pinnedViewMode } = useSidebarCardMode();
+ const body = resolveSessionCardBody({
+ variant: pinnedViewMode === 'card' ? 'card' : 'list',
+ pinned: session.pinnedAt != null,
+ summary: session.summary,
+ preview: session.preview,
+ });
const meta = [
formatSidebarTime(session.updatedAt, t),
hasUnread ? t('ccAgent.sidebar.railUnreadHint') : null,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index 8079c8f910..2fd6d9e087 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -80,6 +80,7 @@ import { SidebarTitleMarquee, type SessionItemProps } from './SessionItem';
import { RemoteProjectIcon } from './RemoteProjectIcon';
import { isRemoteSessionWriteBlocked } from '../lib/remoteSessionWriteGuard';
import { prefetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
+import { resolveSessionCardBody } from './sessionCardPreview';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
@@ -199,9 +200,14 @@ export function SessionCard({
const canHighlightDisplayTitle = canHighlightSessionDisplayTitle(session);
const isArchived = session.status === 'archived';
const canQuickArchive = !isArchived && !isEmpty && !remoteWritesBlocked;
- // 卡片/列表的正文固定给预览区域。list 保留 main 既有实时执行文案;
- // card 模式不跟随 runningDetail 跳动,只显示稳定任务摘要 / 最近消息,完成后由 summary 更新。
- const summaryPreview = session.summary ?? session.preview ?? null;
+ // 卡片/列表的正文固定给预览区域。list 保留实时执行文案,正文只用最近消息;
+ // card + 置顶才用稳定任务摘要,完成后由 summary 更新。
+ const bodyPreview = resolveSessionCardBody({
+ variant,
+ pinned: isPinned,
+ summary: session.summary,
+ preview: session.preview,
+ });
// awaiting 角标数据源:优先 Agent Island 的实时活动(mac);但 Agent Island 仅在
// macOS Sonoma+ 可用(service 在其它平台 return null),故非 mac / 旧系统平台中立兜底
@@ -227,9 +233,16 @@ export function SessionCard({
islandActivity?.phase === 'running' && islandActivity.compactDetail
? islandActivity.compactDetail
: null;
- const listPreview = awaitingText ?? runningDetail ?? summaryPreview;
- const cardPreview = awaitingText ?? summaryPreview;
- const cardPreviewLineClamp = session.summary ? 3 : isRunning ? 2 : isAutomationGenerated ? 1 : 2;
+ const listPreview = awaitingText ?? runningDetail ?? bodyPreview;
+ const cardPreview = awaitingText ?? bodyPreview;
+ const usesPinnedCardSummary = variant === 'card' && isPinned && Boolean(session.summary);
+ const cardPreviewLineClamp = usesPinnedCardSummary
+ ? 3
+ : isRunning
+ ? 2
+ : isAutomationGenerated
+ ? 1
+ : 2;
// 任务信息复选(C / C' 期):卡片右下角信息槽内容,与整理菜单同源共享状态。
const { fields: taskInfoFields } = useTaskInfoFields();
const cardPrRefs = usePrRefsForSession(session.id);
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardPreview.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardPreview.test.ts
new file mode 100644
index 0000000000..2861255925
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardPreview.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveSessionCardBody } from '../sessionCardPreview';
+
+describe('resolveSessionCardBody', () => {
+ it('list 模式只用最近消息,即使有摘要', () => {
+ expect(
+ resolveSessionCardBody({
+ variant: 'list',
+ pinned: true,
+ summary: 'PR 已提交并开启,相关单测通过。',
+ preview: '不是键盘没插上,是同时有两份 Cindy 在抢同一块 HID。',
+ }),
+ ).toBe('不是键盘没插上,是同时有两份 Cindy 在抢同一块 HID。');
+ });
+
+ it('卡片 + 置顶才用摘要', () => {
+ expect(
+ resolveSessionCardBody({
+ variant: 'card',
+ pinned: true,
+ summary: 'PR 已提交并开启,相关单测通过。',
+ preview: '不是键盘没插上',
+ }),
+ ).toBe('PR 已提交并开启,相关单测通过。');
+ });
+
+ it('卡片但未置顶回退最近消息', () => {
+ expect(
+ resolveSessionCardBody({
+ variant: 'card',
+ pinned: false,
+ summary: 'PR 已提交并开启,相关单测通过。',
+ preview: '看一下我们现在的开发版',
+ }),
+ ).toBe('看一下我们现在的开发版');
+ });
+
+ it('摘要为空时卡片也回退 preview', () => {
+ expect(
+ resolveSessionCardBody({
+ variant: 'card',
+ pinned: true,
+ summary: ' ',
+ preview: '最近一条消息',
+ }),
+ ).toBe('最近一条消息');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
index f524ab4b45..8b03078d37 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
@@ -43,7 +43,7 @@ describe('SessionCard review regressions', () => {
it('keeps awaiting text in list mode previews', () => {
expect(sessionCardSource).toContain(
- 'const listPreview = awaitingText ?? runningDetail ?? summaryPreview',
+ 'const listPreview = awaitingText ?? runningDetail ?? bodyPreview',
);
expect(sessionCardSource).toContain('{listPreview}');
});
@@ -143,8 +143,9 @@ describe('SessionCard review regressions', () => {
it('keeps card preview line budgets stable across content sources', () => {
expect(sessionCardSource).toContain(
- 'const cardPreviewLineClamp = session.summary ? 3 : isRunning ? 2 : isAutomationGenerated ? 1 : 2',
+ "const usesPinnedCardSummary = variant === 'card' && isPinned && Boolean(session.summary)",
);
+ expect(sessionCardSource).toContain('const cardPreviewLineClamp = usesPinnedCardSummary');
expect(sessionCardSource).toContain('style={{ WebkitLineClamp: cardPreviewLineClamp }}');
});
@@ -234,11 +235,11 @@ describe('SessionCard review regressions', () => {
it('keeps running card previews stable instead of streaming compact activity text', () => {
expect(sessionCardSource).toContain(
- 'const listPreview = awaitingText ?? runningDetail ?? summaryPreview',
+ 'const listPreview = awaitingText ?? runningDetail ?? bodyPreview',
);
- expect(sessionCardSource).toContain('const cardPreview = awaitingText ?? summaryPreview');
+ expect(sessionCardSource).toContain('const cardPreview = awaitingText ?? bodyPreview');
expect(sessionCardSource).not.toContain(
- 'const cardPreview = awaitingText ?? runningDetail ?? summaryPreview',
+ 'const cardPreview = awaitingText ?? runningDetail ?? bodyPreview',
);
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionCardPreview.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionCardPreview.ts
new file mode 100644
index 0000000000..ecf8759f34
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionCardPreview.ts
@@ -0,0 +1,17 @@
+/**
+ * 侧栏任务预览正文:摘要只属于「置顶 + 卡片」。
+ * 列表 / 文字模式、以及非置顶任务一律用最近消息 preview。
+ */
+export function resolveSessionCardBody(args: {
+ variant: 'card' | 'list';
+ pinned: boolean;
+ summary?: string | null;
+ preview?: string | null;
+}): string | null {
+ if (args.variant === 'card' && args.pinned) {
+ const summary = args.summary?.trim();
+ if (summary) return summary;
+ }
+ const preview = args.preview?.trim();
+ return preview || null;
+}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useSidebarCardMode.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useSidebarCardMode.test.ts
new file mode 100644
index 0000000000..6db15c05ae
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useSidebarCardMode.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+
+import { shouldNotifyMainOnPinnedModeMount } from '../useSidebarCardMode';
+
+describe('shouldNotifyMainOnPinnedModeMount', () => {
+ it('本 renderer 首次挂载才通知 main', () => {
+ expect(shouldNotifyMainOnPinnedModeMount(false)).toBe(true);
+ });
+
+ it('重挂载不再通知,避免失败的 setItem 旧值盖回 main', () => {
+ expect(shouldNotifyMainOnPinnedModeMount(true)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts b/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts
index 04656a54e3..32e54967a2 100644
--- a/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts
+++ b/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts
@@ -86,9 +86,44 @@ export function getSidebarMainViewMode(): SidebarMainViewMode {
return DEFAULT_MAIN_MODE;
}
+function notifyPinnedCardSummaries(mode: SidebarViewMode): void {
+ try {
+ const setEnabled = window.electronAPI?.localDb?.sessions?.setPinnedCardSummaries;
+ if (typeof setEnabled !== 'function') return;
+ void setEnabled(mode === 'card');
+ } catch {
+ // tests / preload 未挂载
+ }
+}
+
/** 同标签页内的实例间同步(原生 storage 事件只发给其它窗口)。 */
const listeners = new Set<() => void>();
+/** main 的卡片模式投影只由 setMode / storage 事件 / 本 renderer 首次挂载写入。
+ * 重挂载不得再通知:否则会把失败的 setItem 留下的旧持久值盖回 main。 */
+let mainNotified = false;
+let storageListenerBound = false;
+
+export function shouldNotifyMainOnPinnedModeMount(mainAlreadyNotified: boolean): boolean {
+ return !mainAlreadyNotified;
+}
+
+function applyPinnedModeFromStorage(raw: string | null): void {
+ memoryValue = parseMode(raw) ?? DEFAULT_MODE;
+ mainNotified = true;
+ notifyPinnedCardSummaries(memoryValue);
+ listeners.forEach((fn) => fn());
+}
+
+function ensurePinnedModeStorageListener(): void {
+ if (storageListenerBound || typeof window === 'undefined') return;
+ storageListenerBound = true;
+ window.addEventListener('storage', (e: StorageEvent) => {
+ if (e.key !== STORAGE_KEY) return;
+ applyPinnedModeFromStorage(e.newValue);
+ });
+}
+
export function useSidebarCardMode(): {
mode: SidebarViewMode;
setMode: (next: SidebarViewMode) => void;
@@ -105,21 +140,21 @@ export function useSidebarCardMode(): {
} catch {
// localStorage 不可用——内存 SoT 已生效;仅跨窗口同步缺失。
}
+ mainNotified = true;
+ notifyPinnedCardSummaries(next);
listeners.forEach((fn) => fn());
}, []);
useEffect(() => {
+ ensurePinnedModeStorageListener();
+ if (shouldNotifyMainOnPinnedModeMount(mainNotified)) {
+ mainNotified = true;
+ notifyPinnedCardSummaries(getSidebarViewMode());
+ }
const sync = () => setModeState(getSidebarViewMode());
listeners.add(sync);
- const onStorage = (e: StorageEvent) => {
- if (e.key !== STORAGE_KEY) return;
- memoryValue = parseMode(e.newValue) ?? DEFAULT_MODE;
- sync();
- };
- window.addEventListener('storage', onStorage);
return () => {
listeners.delete(sync);
- window.removeEventListener('storage', onStorage);
};
}, []);
diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.ts
index 7d8ac79ef8..7000e7c6b2 100644
--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts
+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts
@@ -302,8 +302,8 @@ export interface Session {
*/
preview?: string | null;
/**
- * 任务现状一句话摘要(main/sessionTaskSummary.ts 在置顶会话 turn 结束时
- * 经 oneShot 生成并落库)。卡片/rail flyout 优先展示它,无摘要回退 preview。
+ * 任务现状一句话摘要(main/sessionTaskSummary.ts 仅在置顶段为卡片模式时
+ * 为置顶会话生成)。卡片置顶行优先展示它,列表/文字模式只用 preview。
*/
summary?: string | null;
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index de1082f944..169f239503 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4238,6 +4238,8 @@ interface ElectronAPI {
* fire-and-forget;renderer 应在 emitPatch userSendAt 之后调用,作为持久化兜底。
*/
touchUserSend: (id: string, atMs?: number) => Promise<void>;
+ /** 置顶段切到卡片模式才生成/回填任务摘要。 */
+ setPinnedCardSummaries: (enabled: boolean) => Promise<void>;
/** interrupted-turn-resume:「疑似中断」(startedAt > endedAt)的 active 会话 id。 */
interruptedPending: () => Promise<string[]>;
/** 红点派生的周期性重算源:尾部停在未 dismissed 错误行的 active 会话 id。 */