Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 任务列表预览在回合结束后不再跳回上一轮 (#3186)
Dash584a13bd1142
diff --git a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.tsindex 26feb07f2d..dbf4f707c5 100644--- a/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts+++ b/apps/desktop/src/main/__tests__/sessionTaskSummary.test.ts@@ -4,6 +4,8 @@* sessionTaskSummary.ts;这里锁住档位选择 / sanitize 截断 / 定时识别 / 素材判定 /* 内容抽取这些后续最容易被改坏、而 typecheck·db-validate 覆盖不到的判定。*/+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';import { describe, it, expect } from 'vitest';import {STALE_DEMOTE_MS,@@ -22,6 +24,7 @@ import {shouldGeneratePinnedCardSummary,shouldVoidSummaryAfterGenerationAttempt,nonCardTurnDisplayPatch,+ sessionListPreviewPatch,shouldForceGenerateOnClear,shouldScheduleForceGenerateAfterInFlight,} from '../sessionTaskSummary.logic';@@ -228,6 +231,74 @@ describe('nonCardTurnDisplayPatch', () => {});});+describe('sessionListPreviewPatch', () => {+ it('只补最近消息,不动摘要', () => {+ expect(sessionListPreviewPatch('那就对上了')).toEqual({ preview: '那就对上了' });+ expect(sessionListPreviewPatch(null)).toEqual({ preview: null });+ });+});++describe('turn-done list preview refresh', () => {+ it('回合结束后先刷新列表预览,再按需生成置顶摘要', () => {+ const registerSource = readFileSync(resolve(__dirname, '..', 'maker-ipc', 'register.ts'), 'utf8');+ const summarySource = readFileSync(resolve(__dirname, '..', 'sessionTaskSummary.ts'), 'utf8');+ expect(registerSource).toContain('await refreshSessionListPreview(session.id);');+ expect(registerSource).toContain('await maybeGenerateSessionTaskSummary(session.id, { force: true });');+ expect(registerSource.indexOf('await refreshSessionListPreview(session.id);')).toBeLessThan(+ registerSource.indexOf('await maybeGenerateSessionTaskSummary(session.id, { force: true });'),+ );+ expect(summarySource).toContain('export async function refreshSessionListPreview');+ expect(summarySource).toContain('const ownerScope = captureOwnerScope();');+ expect(summarySource).toContain('if (!isOwnerScopeCurrent(ownerScope)) return;');+ expect(summarySource).toContain(+ 'broadcastSessionListPreview(sessionId, preview, ownerScope);',+ );+ expect(summarySource).toContain(+ "import { latestMessageText, latestVisiblePreview } from './localDb/latestMessageText.js';",+ );+ });++ it('助手正文被改写后也刷新列表预览', () => {+ const messagesSource = readFileSync(+ resolve(__dirname, '..', 'localDb', 'ipc', 'messages.ts'),+ 'utf8',+ );+ const latestSource = readFileSync(+ resolve(__dirname, '..', 'localDb', 'latestMessageText.ts'),+ 'utf8',+ );+ const updateStart = messagesSource.indexOf('export async function updateMessageContent');+ const updateEnd = messagesSource.indexOf('function clampLimit', updateStart);+ const updateBlock = messagesSource.slice(updateStart, updateEnd);+ expect(updateBlock).toContain('const ownerScope = captureOwnerBroadcastScope();');+ expect(updateBlock.indexOf('const ownerScope = captureOwnerBroadcastScope();')).toBeLessThan(+ updateBlock.indexOf('.update(messages)'),+ );+ expect(updateBlock).toContain(+ 'await maybeBroadcastSessionListPreview(sessionId, row, ownerScope);',+ );+ const broadcastStart = messagesSource.indexOf(+ 'async function maybeBroadcastSessionListPreview',+ );+ const broadcastEnd = messagesSource.indexOf('function isAutoResumeUserRow', broadcastStart);+ const broadcastBlock = messagesSource.slice(broadcastStart, broadcastEnd);+ expect(broadcastBlock).toContain('latest = await latestVisiblePreviewRow(sessionId);');+ expect(broadcastBlock).toContain('if (latest?.clientId !== row.clientId) return;');+ expect(broadcastBlock).toContain(+ 'preview: extractMessagePreview(row.content, row.role)',+ );+ expect(broadcastBlock).not.toContain('if (!preview) return;');+ expect(latestSource).toContain('export async function latestVisiblePreviewRow');+ expect(latestSource).toContain(+ 'or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt))',+ );+ expect(latestSource).toContain('const joinedMessageRowid = sql<number>`"messages"."rowid"`;');+ expect(latestSource).toContain(+ '.orderBy(desc(messages.createdAt), desc(joinedMessageRowid))',+ );+ });+});+describe('sanitize — 去噪 + 句界截断', () => {it('短文本原样(去引号/折叠空白)', () => {expect(sanitize('"生成海报。"', SUMMARY_MAX_CHARS)).toBe('生成海报。');diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.tsindex db963ef47c..608888a34d 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts@@ -216,6 +216,7 @@ describe('sessions:list messageCount source', () => {expect(source).toMatch(/SESSION_MESSAGE_COUNT_SQL = sql<number>`\(\s*SELECT count\(\*\) FROM messages m WHERE m\.session_id = \$\{sessions\.id\}/,);+ expect(source).toMatch(/ORDER BY m\.created_at DESC, m\.rowid DESC LIMIT 1/);// 回表写法在任何路径都不允许。锚定的是 select 字段的**代码形态**(`messageCount:`// 紧跟内联的 messages 列),而不是裸的 `count(messages.id)` 字符串——后者会把diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 3665896d0f..35944a1a62 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -11,6 +11,7 @@ import { and, asc, eq, inArray, lt, gt, gte, desc, isNull, or, sql, type SQL } fimport { createId } from '@paralleldrive/cuid2';import { getDbClient } from '../client/current';+import { latestVisiblePreview, latestVisiblePreviewRow } from '../latestMessageText';import { messages, sessions } from '../schema';import {messageToCamel,@@ -98,6 +99,89 @@ function ownerStampForBroadcast(return getSafeOwnerPushStamp();}+function broadcastOwnedPayload(+ channel: string,+ payload: unknown,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ const ownerStamp = ownerStampForBroadcast(ownerScope);+ if (ownerStamp === null) return;+ if (ownerScope !== undefined && ownerScope !== null) {+ broadcastTap.tapWindowBroadcast(channel, payload, ownerStamp);+ } else if (ownerStamp === undefined) {+ broadcastTap.tapWindowBroadcast(channel, payload);+ } else {+ broadcastTap.tapWindowBroadcast(channel, payload, ownerStamp);+ }+ const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;+ for (const win of BrowserWindow.getAllWindows()) {+ if (win.isDestroyed()) continue;+ try {+ if (hasCapturedScope) {+ win.webContents.send(channel, payload, ownerStamp);+ } else if (ownerStamp === undefined) {+ win.webContents.send(channel, payload);+ } else {+ win.webContents.send(channel, payload, ownerStamp);+ }+ } catch {+ /* swallow per-window broadcast failures */+ }+ }+}++function isVisibleSessionListPreviewRow(row: MessageRow): boolean {+ if (row.role !== 'user' && row.role !== 'assistant') return false;+ if (row.rewindAt != null) return false;+ if (row.role === 'user' && isAutoResumeUserRow(row.agentMeta)) return false;+ return true;+}++/**+ * 可见 user/assistant 落库后立刻刷新侧栏 preview,不等 turn-done / 全量 reseed。+ * 只广播当前仍是该会话最近可见消息的那一行:改写旧回复不得盖住已经更新的预览。+ */+async function maybeBroadcastSessionListPreview(+ sessionId: string,+ row: MessageRow,+ ownerScope?: DataOwnerBroadcastScope | null,+): Promise<void> {+ if (!isVisibleSessionListPreviewRow(row)) return;+ let latest: Awaited<ReturnType<typeof latestVisiblePreviewRow>>;+ try {+ latest = await latestVisiblePreviewRow(sessionId);+ } catch (err) {+ log.warn('session list preview latest-row check failed (swallowed)', {+ sessionId,+ clientId: row.clientId,+ error: err instanceof Error ? err.message : String(err),+ });+ return;+ }+ if (latest?.clientId !== row.clientId) return;+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;+ broadcastOwnedPayload(+ 'local-db:sessions:patched',+ { sessionId, patch: { preview: extractMessagePreview(row.content, row.role) } },+ ownerScope,+ );+}++function isAutoResumeUserRow(agentMetaJson: string | null): boolean {+ if (!agentMetaJson) return false;+ try {+ const parsed: unknown = JSON.parse(agentMetaJson);+ return Boolean(+ parsed &&+ typeof parsed === 'object' &&+ !Array.isArray(parsed) &&+ (parsed as { autoResume?: unknown }).autoResume === true,+ );+ } catch {+ return false;+ }+}+// DbClient uses better-sqlite3 `.all()`: never return whole message bodies for// retention bookkeeping. JSON1 extracts only the distinct paths that startup// cleanup needs, while LIKE avoids invoking json_each for unrelated history.@@ -612,38 +696,7 @@ export function broadcastMessageRow(msg: Message,ownerScope?: DataOwnerBroadcastScope | null,): void {- const ownerStamp = ownerStampForBroadcast(ownerScope);- if (ownerStamp === null) return;- if (ownerScope !== undefined && ownerScope !== null) {- broadcastTap.tapWindowBroadcast(- 'local-db:messages:created',- { sessionId, message: msg },- ownerStamp,- );- } else if (ownerStamp === undefined) {- broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg });- } else {- broadcastTap.tapWindowBroadcast(- 'local-db:messages:created',- { sessionId, message: msg },- ownerStamp,- );- }- const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- if (hasCapturedScope) {- win.webContents.send('local-db:messages:created', { sessionId, message: msg }, ownerStamp);- } else if (ownerStamp === undefined) {- win.webContents.send('local-db:messages:created', { sessionId, message: msg });- } else {- win.webContents.send('local-db:messages:created', { sessionId, message: msg }, ownerStamp);- }- } catch {- /* swallow per-window broadcast failures */- }- }+ broadcastOwnedPayload('local-db:messages:created', { sessionId, message: msg }, ownerScope);}export interface MessageDeletedPayload {@@ -910,28 +963,7 @@ export async function commitMessageDeletion(// 口径要动得连 maker-shared/sessionList 的 messageCountLabel 一起改。let preview: string | null = null;try {- 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 visibleMessageProjection = 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,- );- const [latestRow] = await db- .select({ content: messages.content, role: messages.role })- .from(messages)- .where(visibleMessageProjection)- .orderBy(desc(messages.createdAt), desc(messageRowid))- .limit(1);- preview = extractMessagePreview(latestRow?.content, latestRow?.role);+ preview = await latestVisiblePreview(sessionId);} catch (error) {// 删除已经原子提交;投影查询失败不能把成功操作伪装成失败。广播保守空值,// 后续 sessions:list / reseed 会按 DB 真相收敛。@@ -1254,6 +1286,7 @@ export async function updateMessageContent(clientId: string,content: unknown,): Promise<Message | null> {+ const ownerScope = captureOwnerBroadcastScope();const db = getDbClient().drizzle;await db.update(messages)@@ -1279,6 +1312,7 @@ export async function updateMessageContent(error: err instanceof Error ? err.message : String(err),});});+ await maybeBroadcastSessionListPreview(sessionId, row, ownerScope);}return row ? messageToCamel(row) : null;}@@ -1554,6 +1588,7 @@ export async function createMessage(// 主动 push 过, 监听端按 (sessionId, clientId) dedupe 就不会重复显示。if (opts?.shouldBroadcast?.() !== false) {broadcastMessageRow(sessionId, msg, opts?.broadcastOwnerScope);+ await maybeBroadcastSessionListPreview(sessionId, row, opts?.broadcastOwnerScope);}// chat-history-embedder hook (Phase 1.2) —— fire-and-forget, 不 await。// 内部已有 enabled / cutoff / role / size 守卫; 关闭状态下零成本直接 return。diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 9c6c6eed73..b3e44b385e 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -556,7 +556,7 @@ const LATEST_MSG_CONTENT_SQL = sql<string | null>`(AND m.rewind_at IS NULLAND (m.agent_meta IS NULL OR json_extract(m.agent_meta, '$.autoResume') IS NOT 1)AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})- ORDER BY m.created_at DESC LIMIT 1+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1)`.as('latest_message_content');const LATEST_MSG_ROLE_SQL = sql<string | null>`(SELECT m.role FROM messages m@@ -565,7 +565,7 @@ const LATEST_MSG_ROLE_SQL = sql<string | null>`(AND m.rewind_at IS NULLAND (m.agent_meta IS NULL OR json_extract(m.agent_meta, '$.autoResume') IS NOT 1)AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})- ORDER BY m.created_at DESC LIMIT 1+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1)`.as('latest_message_role');/**diff --git a/apps/desktop/src/main/localDb/latestMessageText.ts b/apps/desktop/src/main/localDb/latestMessageText.tsindex baa5c3542b..58acbdd5d3 100644--- a/apps/desktop/src/main/localDb/latestMessageText.ts+++ b/apps/desktop/src/main/localDb/latestMessageText.ts@@ -16,6 +16,7 @@ import { and, asc, desc, eq, gt, inArray, isNull, lt, lte, or, sql } from 'drizzimport { extractText } from '../sessionTaskSummary.logic.js';import { getDbClient } from './client/current.js';+import { extractMessagePreview } from './mapper.js';import { messages, sessions } from './schema.js';import {isTitleTurnBoundaryUser,@@ -56,6 +57,49 @@ export interface RegenerateTitleMaterial {/** 同毫秒 tie-breaker:与 messages:list 一致,用 SQLite rowid 保持写入顺序。 */const messageRowid = sql<number>`rowid`;+/** JOIN sessions 时必须限定表名,否则 SQLite 报 no such column: rowid。 */+const joinedMessageRowid = sql<number>`"messages"."rowid"`;++export interface LatestVisiblePreviewRow {+ clientId: string;+ content: string;+ role: string;+}++/**+ * 与 sessions:list 同一口径的最近可见 user/assistant 行。+ * clear 边界与消息放进同一条 JOIN,避免先读旧 clearedAt 再选出清空前的行。+ */+export async function latestVisiblePreviewRow(+ sessionId: string,+): Promise<LatestVisiblePreviewRow | null> {+ const [row] = await getDbClient()+ .drizzle.select({+ clientId: messages.clientId,+ content: messages.content,+ role: messages.role,+ })+ .from(messages)+ .innerJoin(sessions, eq(messages.sessionId, sessions.id))+ .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)`,+ or(isNull(sessions.clearedAt), gt(messages.createdAt, sessions.clearedAt)),+ ),+ )+ .orderBy(desc(messages.createdAt), desc(joinedMessageRowid))+ .limit(1);+ return row ?? null;+}++/** 最近可见消息的列表预览;无可见行或抽不出正文时为 null,与 sessions:list 一致。 */+export async function latestVisiblePreview(sessionId: string): Promise<string | null> {+ const row = await latestVisiblePreviewRow(sessionId);+ return extractMessagePreview(row?.content, row?.role);+}/** 开场扫描窗口:会话开头可能连续多条纯附件等抽不出正文的消息,按序多看一批。 */const OPENING_SCAN_LIMIT = 15;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.tsindex 51cc110a19..24173e26b5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts@@ -49,8 +49,7 @@ describe('performMessageDeletion', () => {source.indexOf('export function broadcastMessageDeleted'),);- expect(deletionBlock).toContain('const visibleMessageProjection = and(');- expect(deletionBlock).toContain('.where(visibleMessageProjection)');+ expect(deletionBlock).toContain('preview = await latestVisiblePreview(sessionId);');expect(deletionBlock).not.toContain('.where(eq(messages.sessionId, sessionId))');});diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d4a231a64d..647c824b80 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -268,8 +268,11 @@ import {persistSessionFields,recycleSessionWorktreeForStatusChange,} from '../localDb/ipc/sessions.js';-// sidebar-card-mode: turn-done 后触发任务现状摘要生成-import { maybeGenerateSessionTaskSummary } from '../sessionTaskSummary.js';+// sidebar-card-mode: turn-done 后刷新列表预览,并按需生成置顶卡片摘要+import {+ maybeGenerateSessionTaskSummary,+ refreshSessionListPreview,+} from '../sessionTaskSummary.js';import {addOrUpdateWorker,archiveSingleWorkerSession,@@ -4446,6 +4449,10 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidif (event.type === 'done' && !isContinuationBoundary) {void (async () => {await drainPersistQueue();+ // 列表预览与置顶卡片摘要解耦:无论置顶区是不是卡片、这条有没有置顶,+ // 都要把最近一条可见消息立刻写回 session.preview。摘要生成失败也不能+ // 让侧栏停在进入本轮前的旧句子。+ await refreshSessionListPreview(session.id);// force:turn-done 是权威刷新点(本轮 assistant 已落库),必须以最新内容覆盖// 任何 pin 触发 / 上一轮残留的摘要——绕过 in-flight 早返与 20s 节流// (codex review:pin during running turn 会让卡片停在部分/旧摘要)。diff --git a/apps/desktop/src/main/sessionTaskSummary.logic.ts b/apps/desktop/src/main/sessionTaskSummary.logic.tsindex e1a6ad8871..298bffa116 100644--- a/apps/desktop/src/main/sessionTaskSummary.logic.ts+++ b/apps/desktop/src/main/sessionTaskSummary.logic.ts@@ -190,6 +190,13 @@ export function nonCardTurnDisplayPatch(preview: string | null): {return { summary: null, preview };}+/** 列表预览与置顶卡片摘要解耦:只补最近消息,不动 summary。 */+export function sessionListPreviewPatch(preview: string | null): {+ preview: string | null;+} {+ return { preview };+}+/** clear 若发现已切回卡片,只在该 session 没有生成在飞时才 force 再生成。* generateSummaryOnce.finally → clear → maybeGenerate 会 await 尚未 settle 的同一条 inFlight,死锁。 */export function shouldForceGenerateOnClear(args: {diff --git a/apps/desktop/src/main/sessionTaskSummary.ts b/apps/desktop/src/main/sessionTaskSummary.tsindex c5c147b056..f090ef647c 100644--- a/apps/desktop/src/main/sessionTaskSummary.ts+++ b/apps/desktop/src/main/sessionTaskSummary.ts@@ -29,11 +29,15 @@ 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 { latestMessageText, latestVisiblePreview } from './localDb/latestMessageText.js';import { messages, sessions } from './localDb/schema.js';import { createLogger } from './logger.js';-import { tapWindowBroadcast } from './device-link/broadcast-tap.js';+import {+ captureDataOwnerBroadcastScope,+ isDataOwnerBroadcastScopeCurrent,+ tapWindowBroadcast,+ type DataOwnerBroadcastScope,+} from './device-link/broadcast-tap.js';import {STALE_SHORT_MS,SUMMARY_STALE_MAX_CHARS,@@ -46,6 +50,7 @@ import {shouldGeneratePinnedCardSummary,shouldVoidSummaryAfterGenerationAttempt,nonCardTurnDisplayPatch,+ sessionListPreviewPatch,shouldForceGenerateOnClear,shouldScheduleForceGenerateAfterInFlight,} from './sessionTaskSummary.logic.js';@@ -64,50 +69,82 @@ let backfillDone = false;const inFlight = new Map<string, Promise<void>>();const lastGeneratedAt = new Map<string, number>();+function captureOwnerScope(): DataOwnerBroadcastScope | null {+ try {+ return captureDataOwnerBroadcastScope();+ } catch {+ return null;+ }+}++function isOwnerScopeCurrent(scope: DataOwnerBroadcastScope | null): boolean {+ if (scope === null) return true;+ try {+ return isDataOwnerBroadcastScopeCurrent(scope);+ } catch {+ return false;+ }+}+/*** 广播 sessions:patched 到本机所有窗口 + device-link tap。tap 让该 patch 经 topic 路由* 转发给订阅了 `sessions` 的控制端(push 驱动:控制端 applyPatch 即时镜像 summary,无需* 等下一次全量 reseed)——与 localDb/ipc/sessions.ts broadcastSessionPatched 同口径。+ * 异步路径必须传入查询前捕获的 ownerScope:切账号后不得把旧账号 preview 打到新界面。*/-function broadcastPatched(sessionId: string, patch: Record<string, unknown>): void {- tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });+function broadcastPatched(+ sessionId: string,+ patch: Record<string, unknown>,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ if (ownerScope !== undefined && !isOwnerScopeCurrent(ownerScope)) return;+ const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;+ const ownerStamp = hasCapturedScope ? ownerScope.ownerStamp : undefined;+ if (hasCapturedScope) {+ tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ } else {+ tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });+ }for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send('local-db:sessions:patched', { sessionId, patch });+ if (hasCapturedScope) {+ win.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ } else {+ win.webContents.send('local-db:sessions:patched', { sessionId, patch });+ }} catch {/* swallow */}}}-const messageRowid = sql<number>`rowid`;+/** 把已知的列表预览立刻推给侧栏。不 bump updatedAt,也不碰 summary。 */+export function broadcastSessionListPreview(+ sessionId: string,+ preview: string | null,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ broadcastPatched(sessionId, sessionListPreviewPatch(preview), ownerScope);+}-/** 与 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);+/**+ * 列表预览的权威刷新:读最近一条可见 user/assistant,广播 session.preview。+ * 与置顶卡片摘要无关——无论置顶区是不是卡片、这条有没有置顶,都要更新。+ * 失败 swallow,不能挡住 turn-done 收尾。+ */+export async function refreshSessionListPreview(sessionId: string): Promise<void> {+ const ownerScope = captureOwnerScope();+ try {+ const preview = await latestVisiblePreview(sessionId);+ if (!isOwnerScopeCurrent(ownerScope)) return;+ broadcastSessionListPreview(sessionId, preview, ownerScope);+ } catch (err) {+ log.warn('refresh session list preview failed (swallowed)', {+ sessionId,+ error: String(err),+ });+ }}/** 已切回卡片:绝不继续写 null。没有生成在飞才 force 再生成;在飞则交给那次结算,避免自等待。 */