Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 合并并发 sessions:list 为单次查询 (#3381)
Dashe91d3f048241
diff --git a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.tsindex a04a2f8edb..90cec56d9e 100644--- a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts+++ b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts@@ -8,8 +8,14 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { resetSessionListSingleFlightForTests } from '../localDb/ipc/sessionListSingleFlight.js';+const h = vi.hoisted(() => {const queryResults: unknown[][] = [];+ const queryHold = {+ pending: null as Promise<void> | null,+ remaining: 0,+ };// builder 方法一律返回自身,**只有 await(then)才消费一份 queryResults**。// 惰性很关键:list 走两段式后,CTE 内层的 `select(...).limit(cap)` 只是被交给@@ -28,7 +34,15 @@ const h = vi.hoisted(() => {chain.then = (resolve: (value: unknown[]) => void,reject: (reason?: unknown) => void,- ) => Promise.resolve(queryResults.shift() ?? []).then(resolve, reject);+ ) => {+ const rows = queryResults.shift() ?? [];+ const finish = () => Promise.resolve(rows).then(resolve, reject);+ if (queryHold.remaining > 0 && queryHold.pending) {+ queryHold.remaining -= 1;+ return queryHold.pending.then(finish);+ }+ return finish();+ };return chain;};@@ -41,6 +55,7 @@ const h = vi.hoisted(() => {logDebug: vi.fn(),logInfo: vi.fn(),queryResults,+ queryHold,listQuery: withFn,fakeDb: {select: vi.fn(() => makeSelectChain()),@@ -57,7 +72,10 @@ vi.mock('electron', () => ({vi.mock('../logger', () => ({createLogger: () => ({ debug: h.logDebug, info: h.logInfo, warn: vi.fn(), error: vi.fn() }),}));-vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: h.fakeDb }) }));+vi.mock('../localDb/client/current', () => ({+ getDbClient: () => ({ drizzle: h.fakeDb }),+ getCurrentDbClientUserId: () => 'test-user',+}));vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));@@ -77,6 +95,9 @@ import { registerSessionIpc } from '../localDb/ipc/sessions.js';beforeEach(() => {vi.clearAllMocks();h.queryResults.length = 0;+ h.queryHold.pending = null;+ h.queryHold.remaining = 0;+ resetSessionListSingleFlightForTests();});function sessionRow(id: string, patch: Record<string, unknown> = {}) {@@ -217,6 +238,32 @@ describe('local-db:sessions:list includePinned', () => {expect(h.logInfo).toHaveBeenCalledTimes(2);expect(h.logDebug).toHaveBeenCalledTimes(1);});++ it('does not let a fresh list join an in-flight matching query', async () => {+ const handler = sessionsListHandler();+ let release!: () => void;+ h.queryHold.pending = new Promise<void>((resolve) => {+ release = resolve;+ });+ h.queryHold.remaining = 1;+ h.queryResults.push([listRow('stale')], [listRow('fresh')]);++ const stale = handler({}, 20, 'active');+ await vi.waitFor(() => expect(h.listQuery).toHaveBeenCalledTimes(1));++ const joined = handler({}, 20, 'active');+ const fresh = handler({}, 20, 'active', { fresh: true });+ await vi.waitFor(() => expect(h.listQuery).toHaveBeenCalledTimes(2));++ release();+ await expect(Promise.all([stale, joined])).resolves.toEqual([+ [expect.objectContaining({ id: 'stale' })],+ [expect.objectContaining({ id: 'stale' })],+ ]);+ await expect(fresh).resolves.toEqual([expect.objectContaining({ id: 'fresh' })]);+ expect(h.listQuery).toHaveBeenCalledTimes(2);+ expect(h.queryResults).toHaveLength(0);+ });});describe('local-db:sessions:resolve-references', () => {diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 764322c284..2da27d3fcf 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -31,7 +31,7 @@ import { randomUUID } from 'node:crypto';import fs from 'node:fs/promises';import path from 'node:path';-import { app, BrowserWindow } from 'electron';+import { app } from 'electron';import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import { MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';@@ -48,7 +48,7 @@ import {visibleModelUnion,} from '@cindy/model-providers';-import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';import { getMaker } from '../maker-host/index.js';import { resolveLenientRoute } from '../maker-host/model-route-guard.js';import { resolveLenientSessionRoute } from '../maker-host/model-route-guard-live.js';@@ -235,18 +235,9 @@ async function resolveNewSessionConfig(/*** 广播「新会话已建」给所有窗口 + device-link tap —— renderer sessionsStore* 收到即重拉列表, 新 hook 会话实时出现在侧边栏(不广播的话要等手动刷新)。- * 与 fork.ts / cardActionHandler.ts / learn-host 同款(各模块本地副本是既有惯例)。*/function broadcastSessionCreated(sessionId: string): void {- tapWindowBroadcast('local-db:sessions:created', { sessionId });- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send('local-db:sessions:created', { sessionId });- } catch {- // best-effort UI refresh- }- }+ emitSessionCreated(sessionId);}// ── turn 时长策略: hook 侧**不设任何**上限(2026-08-01 定) ────────────────────diff --git a/apps/desktop/src/main/im/shared/sessionBroadcast.ts b/apps/desktop/src/main/im/shared/sessionBroadcast.tsindex e9c9b23e6a..5947cd6cf0 100644--- a/apps/desktop/src/main/im/shared/sessionBroadcast.ts+++ b/apps/desktop/src/main/im/shared/sessionBroadcast.ts@@ -4,27 +4,17 @@* IM 渠道新建会话行后的 renderer 通知。sidebar 的 Projects 列表靠* `local-db:sessions:created` push 增量感知新会话(renderer sessionsStore.onCreated* → 重拉列表),不广播的话 IM 进来的新会话要等用户手动刷新才出现。- * tapWindowBroadcast 把同一事件旁路给 device-link 控制端(channel 在- * PUSH_FORWARD_ALLOWLIST 内),远程控制端的列表同样即时出现。- * 同 maker-ipc/register.ts / fork.ts / hook-control/session-runner.ts 的本地- * 副本语义一致(那几处因 device-link 源码断言测试锚定,不在本模块收敛)。+ * 创建通知统一走 emitSessionCreated。*/import { BrowserWindow } from 'electron';import { tapWindowBroadcast } from '../../device-link/broadcast-tap';+import { emitSessionCreated } from '../../localDb/ipc/sessionCreatedBroadcast';/** 广播「session 行已创建」到本机所有窗口 + device-link 控制端。best-effort。 */export function broadcastSessionCreated(sessionId: string): void {- tapWindowBroadcast('local-db:sessions:created', { sessionId });- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send('local-db:sessions:created', { sessionId });- } catch {- // best-effort UI 刷新失败不影响 IM 业务- }- }+ emitSessionCreated(sessionId);}/**diff --git a/apps/desktop/src/main/learn-host/index.ts b/apps/desktop/src/main/learn-host/index.tsindex 8703c6d942..31bb6a163f 100644--- a/apps/desktop/src/main/learn-host/index.ts+++ b/apps/desktop/src/main/learn-host/index.ts@@ -12,12 +12,10 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { BrowserWindow } from 'electron';-import type { Effort, Maker } from '@cindy/maker-core';import { isTerminalAgentErrorEvent } from '@cindy/maker-core';-import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';import { createLogger } from '../logger.js';import { getCurrentDataOwnerId } from '../authManager';import { getResolvedMainLocale } from '../i18n.js';@@ -286,19 +284,9 @@ export function startLearnHost(deps: StartLearnHostDeps): LearnController {logger,);// 侧边栏刷新:直连 maker.createSession 不经 renderer 建会话 funnel,不广播- // 的话新蒸馏会话要等无关刷新才出现在侧边栏(Codex review)。与 register.ts- // broadcastSessionCreated 同款(该 helper 各模块本地复制是既有惯例,见其- // 注释);放在 backfill 之后,renderer 重拉时 source='learn' 已就位,直接- // 落自动化分组不跳变。- tapWindowBroadcast('local-db:sessions:created', { sessionId });- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send('local-db:sessions:created', { sessionId });- } catch {- // best-effort UI refresh,失败不影响业务- }- }+ // 的话新蒸馏会话要等无关刷新才出现在侧边栏。统一走 emitSessionCreated;+ // 放在 backfill 之后,renderer 重拉时 source='learn' 已就位,直接落自动化分组。+ emitSessionCreated(sessionId);},...(deps.fetchHubSkill ? { fetchHubSkill: deps.fetchHubSkill } : {}),logger,diff --git a/apps/desktop/src/main/localDb/client/current.ts b/apps/desktop/src/main/localDb/client/current.tsindex 35d8cbe1dc..de93a05ed2 100644--- a/apps/desktop/src/main/localDb/client/current.ts+++ b/apps/desktop/src/main/localDb/client/current.ts@@ -1,13 +1,23 @@import type { DbClient } from './DbClient.js';-let current: { client: DbClient; userId: string } | null = null;+export type CurrentDbClientSnapshot = {+ client: DbClient;+ userId: string;+ clientEpoch: number;+};++let clientEpoch = 0;+let current: CurrentDbClientSnapshot | null = null;export function setCurrentDbClient(client: DbClient, userId: string): void {- current = { client, userId };+ clientEpoch += 1;+ current = { client, userId, clientEpoch };}export function clearCurrentDbClient(client?: DbClient): void {if (client && current?.client !== client) return;+ if (current === null) return;+ clientEpoch += 1;current = null;}@@ -44,3 +54,8 @@ export function tryGetDbClient(): DbClient | null {export function getCurrentDbClientUserId(): string | null {return current?.userId ?? null;}++/** 同一引用上读出 client、userId 与 clientEpoch,避免分两次读赶上账号切换。 */+export function getCurrentDbClientSnapshot(): CurrentDbClientSnapshot | null {+ return current;+}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.tsindex e4bd9d6e33..f2cdf1d5ff 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts@@ -23,7 +23,10 @@ vi.mock('electron', () => ({vi.mock('../../../logger', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));-vi.mock('../../client/current', () => ({ getDbClient: () => ({ drizzle: h.db }) }));+vi.mock('../../client/current', () => ({+ getDbClient: () => ({ drizzle: h.db }),+ getCurrentDbClientUserId: () => 'test-user',+}));vi.mock('../../dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../../../git-context/prRefsStore', () => ({recomputePrRefsForSession: vi.fn(async () => undefined),diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionCreatedBroadcast.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionCreatedBroadcast.test.tsnew file mode 100644index 0000000000..51bd67caa8--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionCreatedBroadcast.test.ts@@ -0,0 +1,75 @@+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ tap: vi.fn(),+ send: vi.fn(),+}));++vi.mock('electron', () => ({+ BrowserWindow: {+ getAllWindows: () => [+ { isDestroyed: () => false, webContents: { send: h.send } },+ ],+ },+}));+vi.mock('../../../device-link/broadcast-tap', () => ({+ tapWindowBroadcast: h.tap,+}));++import {+ buildSessionListFlightKey,+ resetSessionListSingleFlightForTests,+} from '../sessionListSingleFlight';+import { emitSessionCreated } from '../sessionCreatedBroadcast';++afterEach(() => {+ resetSessionListSingleFlightForTests();+ h.tap.mockClear();+ h.send.mockClear();+});++const listParams = {+ userId: 'u1',+ clientEpoch: 1,+ cap: 200,+ statusFilter: 'active' as const,+ includePinned: true,+};++describe('emitSessionCreated', () => {+ it('notifies windows and device-link without owning write generation', () => {+ const before = buildSessionListFlightKey(listParams);+ emitSessionCreated('s1');+ expect(buildSessionListFlightKey(listParams)).toBe(before);+ expect(h.tap).toHaveBeenCalledWith('local-db:sessions:created', { sessionId: 's1' });+ expect(h.send).toHaveBeenCalledWith('local-db:sessions:created', { sessionId: 's1' });+ });+});++describe('sessions:created 唯一出口', () => {+ it('main 侧 created 广播只留在 emitSessionCreated', () => {+ const mainRoot = join(dirname(fileURLToPath(import.meta.url)), '../../..');+ const helper = readFileSync(join(mainRoot, 'localDb/ipc/sessionCreatedBroadcast.ts'), 'utf8');+ expect(helper).toContain("tapWindowBroadcast('local-db:sessions:created'");+ expect(helper).toContain("win.webContents.send('local-db:sessions:created'");+ expect(helper).not.toContain('bumpSessionListWriteGeneration()');++ const callers = [+ 'maker-ipc/register.ts',+ 'maker-ipc/fork.ts',+ 'hook-control/session-runner.ts',+ 'learn-host/index.ts',+ 'im/shared/sessionBroadcast.ts',+ ];+ for (const rel of callers) {+ const src = readFileSync(join(mainRoot, rel), 'utf8');+ expect(src, rel).toContain('emitSessionCreated');+ expect(src, rel).not.toContain("tapWindowBroadcast('local-db:sessions:created'");+ expect(src, rel).not.toContain("webContents.send('local-db:sessions:created'");+ }+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionListSingleFlight.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionListSingleFlight.test.tsnew file mode 100644index 0000000000..d163df0197--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionListSingleFlight.test.ts@@ -0,0 +1,172 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ buildSessionListFlightKey,+ resetSessionListSingleFlightForTests,+ runSessionListSingleFlight,+} from '../sessionListSingleFlight';++afterEach(() => {+ resetSessionListSingleFlightForTests();+});++describe('buildSessionListFlightKey', () => {+ it('uses normalized status all for null filter', () => {+ expect(+ buildSessionListFlightKey({+ userId: 'u1',+ clientEpoch: 1,+ cap: 200,+ statusFilter: null,+ includePinned: true,+ }),+ ).toBe('u1|c1|all|200|pinned');+ });++ it('separates filter, cap, pinned, userId, and client epoch', () => {+ const base = {+ userId: 'u1',+ clientEpoch: 1,+ cap: 200,+ statusFilter: 'active' as const,+ includePinned: true,+ };+ expect(buildSessionListFlightKey(base)).toBe('u1|c1|active|200|pinned');+ expect(buildSessionListFlightKey({ ...base, clientEpoch: 2 })).toBe(+ 'u1|c2|active|200|pinned',+ );+ expect(buildSessionListFlightKey({ ...base, statusFilter: null })).not.toBe(+ buildSessionListFlightKey(base),+ );+ expect(buildSessionListFlightKey({ ...base, cap: 1000 })).not.toBe(+ buildSessionListFlightKey(base),+ );+ expect(buildSessionListFlightKey({ ...base, includePinned: false })).toBe(+ 'u1|c1|active|200|plain',+ );+ expect(buildSessionListFlightKey({ ...base, userId: 'u2' })).not.toBe(+ buildSessionListFlightKey(base),+ );+ });+});++describe('runSessionListSingleFlight', () => {+ it('coalesces concurrent callers with the same key into one run', async () => {+ let calls = 0;+ let release!: (value: string) => void;+ const gate = new Promise<string>((resolve) => {+ release = resolve;+ });+ const run = vi.fn(async () => {+ calls += 1;+ return gate;+ });++ const a = runSessionListSingleFlight('k', run);+ const b = runSessionListSingleFlight('k', run);+ const c = runSessionListSingleFlight('k', run);+ expect(run).toHaveBeenCalledTimes(1);++ release('same');+ await expect(Promise.all([a, b, c])).resolves.toEqual(['same', 'same', 'same']);+ expect(calls).toBe(1);+ });++ it('does not coalesce different keys', async () => {+ const runA = vi.fn(async () => 'a');+ const runB = vi.fn(async () => 'b');+ const runC = vi.fn(async () => 'c');+ await expect(+ Promise.all([+ runSessionListSingleFlight('active|200|pinned', runA),+ runSessionListSingleFlight('all|1000|plain', runB),+ runSessionListSingleFlight('all|1|pinned', runC),+ ]),+ ).resolves.toEqual(['a', 'b', 'c']);+ expect(runA).toHaveBeenCalledTimes(1);+ expect(runB).toHaveBeenCalledTimes(1);+ expect(runC).toHaveBeenCalledTimes(1);+ });++ it('runs again after the previous flight settles', async () => {+ const run = vi.fn(async () => 'ok');+ await runSessionListSingleFlight('k', run);+ await runSessionListSingleFlight('k', run);+ expect(run).toHaveBeenCalledTimes(2);+ });++ it('rejects every joiner and does not stick the error', async () => {+ const boom = new Error('db busy');+ const failing = vi.fn(async () => {+ throw boom;+ });+ const first = runSessionListSingleFlight('k', failing);+ const second = runSessionListSingleFlight('k', failing);+ await expect(first).rejects.toBe(boom);+ await expect(second).rejects.toBe(boom);+ expect(failing).toHaveBeenCalledTimes(1);++ const recovering = vi.fn(async () => 'recovered');+ await expect(runSessionListSingleFlight('k', recovering)).resolves.toBe('recovered');+ expect(recovering).toHaveBeenCalledTimes(1);+ });++ it('does not join a later user onto an earlier user flight', async () => {+ let releaseU1!: (value: string) => void;+ const u1Gate = new Promise<string>((resolve) => {+ releaseU1 = resolve;+ });+ const u1 = runSessionListSingleFlight(+ buildSessionListFlightKey({+ userId: 'u1',+ clientEpoch: 1,+ cap: 200,+ statusFilter: 'active',+ includePinned: true,+ }),+ async () => u1Gate,+ );+ const u2Run = vi.fn(async () => 'u2');+ const u2 = runSessionListSingleFlight(+ buildSessionListFlightKey({+ userId: 'u2',+ clientEpoch: 1,+ cap: 200,+ statusFilter: 'active',+ includePinned: true,+ }),+ u2Run,+ );++ await expect(u2).resolves.toBe('u2');+ expect(u2Run).toHaveBeenCalledTimes(1);+ releaseU1('u1');+ await expect(u1).resolves.toBe('u1');+ });++ it('does not join a later client epoch onto an earlier client flight', async () => {+ const params = {+ userId: 'u1',+ cap: 200,+ statusFilter: 'active' as const,+ includePinned: true,+ };+ let release!: (value: string) => void;+ const gate = new Promise<string>((resolve) => {+ release = resolve;+ });+ const first = runSessionListSingleFlight(+ buildSessionListFlightKey({ ...params, clientEpoch: 1 }),+ async () => gate,+ );+ const later = vi.fn(async () => 'new-client');+ const second = runSessionListSingleFlight(+ buildSessionListFlightKey({ ...params, clientEpoch: 2 }),+ later,+ );+ await expect(second).resolves.toBe('new-client');+ expect(later).toHaveBeenCalledTimes(1);+ release('old-client');+ await expect(first).resolves.toBe('old-client');+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.tsindex 600ade4113..6484a2d04d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.ts@@ -21,6 +21,7 @@ vi.mock('../../../logger', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));vi.mock('../../client/current', () => ({+ getCurrentDbClientUserId: () => 'test-user',getDbClient: () => {if (h.failNext.value) {h.failNext.value = false;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex 514117df28..641e00e6ee 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -37,6 +37,7 @@ vi.mock('../../../logger', () => ({}));vi.mock('../../client/current', () => ({getDbClient: () => ({ drizzle: h.db }),+ getCurrentDbClientUserId: () => 'test-user',}));vi.mock('../../dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../../../git-context/prRefsStore', () => ({diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 05d7587e50..5fe89bd64c 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -78,6 +78,7 @@ vi.mock('../../../logger', () => ({}));vi.mock('../../client/current', () => ({getDbClient: () => ({ drizzle: h.db }),+ getCurrentDbClientUserId: () => 'test-user',}));vi.mock('../../dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../../../git-context/prRefsStore', () => ({diff --git a/apps/desktop/src/main/localDb/ipc/sessionCreatedBroadcast.ts b/apps/desktop/src/main/localDb/ipc/sessionCreatedBroadcast.tsnew file mode 100644index 0000000000..99d3771f34--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/sessionCreatedBroadcast.ts@@ -0,0 +1,23 @@+/**+ * 新建会话通知的唯一出口:tap + 本机广播。+ * 写代次由 DbClient 写路径推进,这里只负责通知 renderer / device-link。+ *+ * Maker / scheduler / plugin / IM / fork / hook / learn 必须走这里,+ * 不要再复制 tapWindowBroadcast + webContents.send 循环。+ */++import { BrowserWindow } from 'electron';++import { tapWindowBroadcast } from '../../device-link/broadcast-tap';++export function emitSessionCreated(sessionId: string): void {+ tapWindowBroadcast('local-db:sessions:created', { sessionId });+ for (const win of BrowserWindow.getAllWindows()) {+ if (win.isDestroyed()) continue;+ try {+ win.webContents.send('local-db:sessions:created', { sessionId });+ } catch {+ // best-effort UI refresh, 失败不影响业务+ }+ }+}diff --git a/apps/desktop/src/main/localDb/ipc/sessionListSingleFlight.ts b/apps/desktop/src/main/localDb/ipc/sessionListSingleFlight.tsnew file mode 100644index 0000000000..51994d3210--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/sessionListSingleFlight.ts@@ -0,0 +1,45 @@+/**+ * sessions:list 单飞:相同账号 + 同一 DbClient 代次 + 归一化参数的并发请求共用一次查询。+ *+ * 只合并 in-flight Promise,查完即删,不加 TTL。+ * key 必须用归一化后的 cap / status / includePinned,并带上当前 userId 和 clientEpoch,+ * 否则切账号或重登会接到旧库那次查询。options 以后若加字段,同步扩 key。+ *+ * 写后 freshness 不靠写代次:forceRefresh / status 重拉传 fresh,直接绕开单飞。+ */++export type SessionListStatusFilter = 'active' | 'archived' | null;++const inflight = new Map<string, Promise<unknown>>();++export function buildSessionListFlightKey(input: {+ userId: string;+ clientEpoch: number;+ cap: number;+ statusFilter: SessionListStatusFilter;+ includePinned: boolean;+}): string {+ const status = input.statusFilter ?? 'all';+ return `${input.userId}|c${input.clientEpoch}|${status}|${input.cap}|${input.includePinned ? 'pinned' : 'plain'}`;+}++export function runSessionListSingleFlight<T>(key: string, run: () => Promise<T>): Promise<T> {+ const existing = inflight.get(key);+ if (existing) return existing as Promise<T>;++ let flight: Promise<T>;+ try {+ flight = Promise.resolve(run()).finally(() => {+ if (inflight.get(key) === flight) inflight.delete(key);+ });+ } catch (err) {+ return Promise.reject(err);+ }+ inflight.set(key, flight);+ return flight;+}++/** 测试用:清空残留 flight,避免用例互相污染。 */+export function resetSessionListSingleFlightForTests(): void {+ inflight.clear();+}diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex a247f8e15d..b426bb014f 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -20,8 +20,10 @@ import {import { DEFAULT_DRAFT_SESSION_TITLE, normalizeAutoTitle } from '@cindy/maker-shared/session-title';import { getDbClient } from '../client/current';+import * as currentDb from '../client/current';import type { DbClient } from '../client/DbClient';import { sessions, messages } from '../schema';+import { buildSessionListFlightKey, runSessionListSingleFlight } from './sessionListSingleFlight';import { throwIpcError, requireString, requireObject } from '../../utils/ipcValidate';import { bindDeletedPiSubagentCleanupCancel } from './piSubagentDeletion';import { resolveBusinessSessionId } from '../../sessionIds';@@ -71,6 +73,27 @@ const log = createLogger('sessions');const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);const initialSessionListLogged = new Set<string>();const SLOW_SESSION_LIST_MS = 250;++function readCurrentDbClientSnapshot(): {+ client: DbClient;+ userId: string;+ clientEpoch: number;+} | null {+ try {+ return currentDb.getCurrentDbClientSnapshot?.() ?? null;+ } catch {+ return null;+ }+}++function readCurrentDbClientUserId(): string | null {+ try {+ return currentDb.getCurrentDbClientUserId?.() ?? null;+ } catch {+ return null;+ }+}+type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;type SessionRemovalCancelOperations = (sessionId: string) => Promise<void>;type SessionRemovalCleanup = (sessionId: string) => Promise<void>;@@ -981,12 +1004,16 @@ export function registerSessionIpc('local-db:sessions:list',async (_e, limit: unknown, status: unknown, options: unknown) => {const startedAt = performance.now();- const db = getDbClient().drizzle;+ const snapshot = readCurrentDbClientSnapshot();+ const db = snapshot?.client.drizzle ?? getDbClient().drizzle;+ const userId = snapshot?.userId ?? readCurrentDbClientUserId();+ const clientEpoch = snapshot?.clientEpoch ?? 0;// sidebar-card-mode: 首次 list(db 必然 ready)触发一次置顶摘要回填——// 老置顶会话没有 turn-done 触发点。模块内部 once 守卫 + 串行 + swallow。void import('../../sessionTaskSummary.js').then((m) => m.backfillPinnedSessionSummaries());const cap = clampLimit(limit, 20);const includePinned = shouldIncludePinnedSessions(options);+ const fresh = shouldBypassSessionListSingleFlight(options);// 支持 Sidebar Filter 的 Active/Archived/All status 过滤。// - 'active' / 'archived' → WHERE status = ?// - 'all' / undefined / 其它非法值 → WHERE status != 'deleted'@@ -994,33 +1021,49 @@ export function registerSessionIpc(// listSessions 行为一致:'all' 白名单 ['active','archived'])const statusFilter: 'active' | 'archived' | null =status === 'active' || status === 'archived' ? status : null;- // 按 DESKTOP_VISIBLE_SESSION_SOURCES 白名单过滤 — 包含 IM 渠道- // (feishu/slack/discord)与本机自动化(scheduler/learn/shared);- // feishu 会话以「对话」分组展示(workspaceKind='dialogue')。- const sourceFilter = inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES);- const statusWhere = () =>- statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');- const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap);-- let mergedRows = rows;- if (includePinned) {- const pinnedRows = await selectSessionListRows(- db,- and(sourceFilter, statusWhere(), isNotNull(sessions.pinnedAt)),- null,- );- mergedRows = mergeSessionListRows(rows, pinnedRows);- }+ const loadRows = async () => {+ // 按 DESKTOP_VISIBLE_SESSION_SOURCES 白名单过滤 — 包含 IM 渠道+ // (feishu/slack/discord)与本机自动化(scheduler/learn/shared);+ // feishu 会话以「对话」分组展示(workspaceKind='dialogue')。+ const sourceFilter = inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES);+ const statusWhere = () =>+ statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');+ const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap);++ let mergedRows = rows;+ if (includePinned) {+ const pinnedRows = await selectSessionListRows(+ db,+ and(sourceFilter, statusWhere(), isNotNull(sessions.pinnedAt)),+ null,+ );+ mergedRows = mergeSessionListRows(rows, pinnedRows);+ }- const queryFinishedAt = performance.now();- const result = mergedRows.map((r) =>- sessionToCamel({- ...r.session,- messageCount: r.messageCount,- latestMessageContent: r.latestMessageContent,- latestMessageRole: r.latestMessageRole,- }),- );+ return mergedRows.map((r) =>+ sessionToCamel({+ ...r.session,+ messageCount: r.messageCount,+ latestMessageContent: r.latestMessageContent,+ latestMessageRole: r.latestMessageRole,+ }),+ );+ };+ // key 用同一快照上的 userId + clientEpoch + 归一化参数。+ // forceRefresh / status 重拉带 fresh,不并入写前那次查询。+ const result =+ userId && !fresh+ ? await runSessionListSingleFlight(+ buildSessionListFlightKey({+ userId,+ clientEpoch,+ cap,+ statusFilter,+ includePinned,+ }),+ loadRows,+ )+ : await loadRows();const finishedAt = performance.now();const filter = statusFilter ?? 'all';const elapsedMs = Math.round(finishedAt - startedAt);@@ -1030,8 +1073,8 @@ export function registerSessionIpc(cap,includePinned,rows: result.length,- queryElapsedMs: Math.round(queryFinishedAt - startedAt),- mapElapsedMs: Math.round(finishedAt - queryFinishedAt),+ queryElapsedMs: elapsedMs,+ mapElapsedMs: 0,elapsedMs,});const logScope = readSessionListLogScope() ?? 'unscoped';@@ -2194,6 +2237,14 @@ function shouldIncludePinnedSessions(options: unknown): boolean {);}+function shouldBypassSessionListSingleFlight(options: unknown): boolean {+ return !!(+ options &&+ typeof options === 'object' &&+ (options as { fresh?: unknown }).fresh === true+ );+}+function mergeSessionListRows<T extends { session: { id: string } }>(recentRows: readonly T[],pinnedRows: readonly T[],diff --git a/apps/desktop/src/main/maker-ipc/fork.ts b/apps/desktop/src/main/maker-ipc/fork.tsindex 725c20c8f0..11c53ae470 100644--- a/apps/desktop/src/main/maker-ipc/fork.ts+++ b/apps/desktop/src/main/maker-ipc/fork.ts@@ -12,12 +12,12 @@* fork 点支持 user / assistant 消息 (语义区别见 forkSessionAtMessage doc)。*/-import { ipcMain, BrowserWindow } from 'electron';+import { ipcMain } from 'electron';import { createLogger } from '../logger.js';import { forkSessionAtMessage, forkSessionStripEncrypted } from '../maker-orchestration/fork.js';import { requireString, throwIpcError } from '../utils/ipcValidate.js';-import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';+import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';import { MAKER_INVOKE } from './channels.js';@@ -25,20 +25,10 @@ const log = createLogger('maker-ipc/fork');/*** 广播「新会话已建」给所有窗口 + device-link tap(转发给订阅 `sessions` topic 的控制端)。- * 与 register.ts / cardActionHandler.ts / maker-host 同款(跨 module 提取不在本次范围,沿用副本)。- * fork 出的会话过去**没有**走这条 → 在被控端自己窗口 / 其它控制端侧边栏凭空消失,只有发起方- * 靠手动重拉能看到;这里补上,使所有端收敛。+ * 统一走 emitSessionCreated,避免 fork 会话在被控端 / 其它控制端侧边栏凭空消失。*/function broadcastSessionCreated(sessionId: string): void {- tapWindowBroadcast('local-db:sessions:created', { sessionId });- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send('local-db:sessions:created', { sessionId });- } catch {- // best-effort UI refresh- }- }+ emitSessionCreated(sessionId);}export function registerMakerForkIpc(): void {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 9216ba17f5..f70a5c51c3 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -932,6 +932,7 @@ import {captureDataOwnerBroadcastScope,tapWindowBroadcast,} from '../device-link/broadcast-tap.js';+import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';import { setBusyProbe as setDeviceLinkBusyProbe } from '../device-link/index.js';import {markRemoteSettingPersistedInsideHandler,@@ -1529,19 +1530,10 @@ export async function applyCodexSpawnConfigChangeWithRestart<T extends object>(}// ─── Sessions push helpers ────────────────────────────────────────────────-// maker-ipc 会话创建路径与 scheduler-host 共享此导出,统一广播-// `local-db:sessions:created`;renderer sessionsStore.onCreated 收到后-// forceRefreshAll 重拉所有桶。其它生命周期专属路径仍保留各自的同契约 helper。+// maker-ipc 会话创建路径与 scheduler-host 共享此导出,统一走 emitSessionCreated。+// renderer sessionsStore.onCreated 收到后 forceRefreshAll 重拉所有桶。export function broadcastSessionCreated(sessionId: string): void {- tapWindowBroadcast('local-db:sessions:created', { sessionId });- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send('local-db:sessions:created', { sessionId });- } catch {- // best-effort UI refresh, 失败不影响业务- }- }+ emitSessionCreated(sessionId);}/**diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7cf9e9eff3..64d082f0c1 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4843,8 +4843,8 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<{ ready: true } | { ready: false; error: { code: string; message: string } }> =>ipcRenderer.invoke('local-db:ensure-ready', userId),sessions: {- list: (limit?: number, status?: string): Promise<unknown> =>- ipcRenderer.invoke('local-db:sessions:list', limit, status),+ list: (limit?: number, status?: string, options?: unknown): Promise<unknown> =>+ ipcRenderer.invoke('local-db:sessions:list', limit, status, options),create: (body?: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:create', body),get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex 22d9afa419..b5d887f70b 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -413,8 +413,8 @@ contextBridge.exposeInMainWorld('electronAPI', {// shared makerChatStore. Do not expose the primary window's full DB API.sessions: {get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),- list: (limit?: number, status?: string): Promise<unknown> =>- ipcRenderer.invoke('local-db:sessions:list', limit, status),+ list: (limit?: number, status?: string, options?: unknown): Promise<unknown> =>+ ipcRenderer.invoke('local-db:sessions:list', limit, status, options),resolveReferences: (sessionIds: string[]): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:resolve-references', sessionIds),ackInterrupted: (id: string): Promise<void> =>diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex c8c4ad866d..3910cf4d39 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1351,7 +1351,9 @@ describe('远程交互接线不变式', () => {it('F2: fork IPC handler 广播 sessions:created(否则 fork 会话在被控端/其它控制端不出现)', () => {const src = mainSrc('maker-ipc/fork.ts');expect(src).toContain('broadcastSessionCreated(session.id)');- expect(src).toContain("tapWindowBroadcast('local-db:sessions:created'");+ expect(src).toContain('emitSessionCreated');+ const helper = mainSrc('localDb/ipc/sessionCreatedBroadcast.ts');+ expect(helper).toContain("tapWindowBroadcast('local-db:sessions:created'");});it('F3: schedule / project-automation 的 broadcast 补 tapWindowBroadcast(否则远程不回流)', () => {diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex c40e58019d..56d7ddaf5c 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -299,7 +299,7 @@ describe('refreshRemoteDeviceSessions retry', () => {expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [200,'active',- { includePinned: true },+ { includePinned: true, fresh: true },]);expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['recent-1',@@ -321,7 +321,7 @@ describe('refreshRemoteDeviceSessions retry', () => {expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [1000,'archived',- { includePinned: true },+ { includePinned: true, fresh: true },]);expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).toEqual(['active-1',@@ -398,7 +398,7 @@ describe('refreshRemoteDeviceSessions retry', () => {expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [1000,'archived',- { includePinned: true },+ { includePinned: true, fresh: true },]);});@@ -638,6 +638,30 @@ describe('refreshRemoteDeviceSessions retry', () => {]);});+ it('事件重拉传 fresh,周期 tick 不传', async () => {+ const d = did();+ invoke.mockResolvedValue([]);++ await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });+ expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [+ 200,+ 'active',+ { includePinned: true, fresh: true },+ ]);++ invoke.mockClear();+ invoke.mockResolvedValue([]);+ await refreshRemoteDeviceSessions(d, 'Mac B', {+ sleep: noSleep,+ coalescingMode: 'weak',+ });+ expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [+ 200,+ 'active',+ { includePinned: true },+ ]);+ });+it('同设备补跑排队时立即作废当前 snapshot,避免旧结果短暂覆盖 push 状态', async () => {const d = did();const firstSnapshot = deferred<Session[]>();@@ -684,6 +708,11 @@ describe('refreshRemoteDeviceSessions retry', () => {await expect(Promise.all([periodic, bootstrap])).resolves.toEqual(['ok', 'ok']);expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);+ expect(invoke.mock.calls[1]?.[2]).toEqual([+ 200,+ 'active',+ { includePinned: true, fresh: true },+ ]);});it('事件型 refresh 在途时弱周期 tick 直接复用,不补跑也不取消当前请求', async () => {diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex 9b67a4652a..8d3ea8723e 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -288,6 +288,8 @@ export async function refreshRemoteDeviceSessions((existing.opts.snapshotMode ?? 'merge') === 'replace' || requestedSnapshotMode === 'replace'? 'replace': 'merge',+ // 走到这里的一定不是弱周期 tick;补跑按事件语义带 fresh。+ coalescingMode: undefined,};// 先让当前 in-flight snapshot 失效,否则它可能在排队的补跑开始前覆盖 push 带来的新状态。remoteProjectsStore.nextSnapshotEpoch(deviceId, status);@@ -398,7 +400,11 @@ async function runRefreshRemoteDeviceSessions(const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:list', [listLimit,status,- { includePinned: true },+ {+ includePinned: true,+ // 周期 tick 保持单飞;created / bootstrap 等事件重拉必须绕开写前查询。+ ...(opts.coalescingMode === 'weak' ? {} : { fresh: true }),+ },]);// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.tsindex 64f2fde0b3..44a44e2260 100644--- a/apps/desktop/src/renderer/lib/sessionService.ts+++ b/apps/desktop/src/renderer/lib/sessionService.ts@@ -44,11 +44,18 @@ function wrap<T>(p: Promise<T>): Promise<T> {// settled rows must not become a stale renderer cache.const getInFlight = new Map<string, Promise<Session>>();+export type SessionListOptions = {+ includePinned?: boolean;+ /** forceRefresh / status 重拉:绕开 main 侧 in-flight 合并。 */+ fresh?: boolean;+};+export async function list(limit: number = 20,status?: ListStatusFilter,+ options?: SessionListOptions,): Promise<Session[]> {- return wrap(window.electronAPI.localDb.sessions.list(limit, status));+ return wrap(window.electronAPI.localDb.sessions.list(limit, status, options));}export async function create(body?: {diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.tsindex 72c4c985bd..a0ed8d0ec3 100644--- a/apps/desktop/src/renderer/lib/sessionsStore.ts+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts@@ -242,13 +242,20 @@ function applyOptimisticTitle(id: string, title: string): void {if (touched) notify();}-async function fetchFilter(filter: ListStatusFilter): Promise<Session[]> {+async function fetchFilter(+ filter: ListStatusFilter,+ opts?: { fresh?: boolean },+): Promise<Session[]> {// chat-data-localization round-5:IPC 'all'/undefined 与 HTTP 旧默认行为// 不一致,必须把 filter 原样透传,由 IPC handler 决定过滤语义。const spendRevisionAtStart = sessionSpendRevision;const titleRevisionAtStart = sessionTitleRevision;const startedAt = performance.now();- const sessions = await sessionService.list(DEFAULT_LIMIT, filter);+ const sessions = await sessionService.list(+ DEFAULT_LIMIT,+ filter,+ opts?.fresh ? { fresh: true } : undefined,+ );// 顺序:先把「请求发起之后到达的权威标题」补回去,再叠乐观预览。反过来的话预览会先// 盖在旧标题上、随后又被权威值挤掉,中间多一次跳变。const result = applyAutoTitlePreviews(@@ -305,11 +312,11 @@ export const sessionsStore = {* 确保指定桶已加载(命中即 noop,dedupe 并发请求)。* 失败时 throw 原始错误,由调用方决定如何展示。*/- async ensureByFilter(filter: ListStatusFilter): Promise<void> {- if (cache.has(filter)) return;+ async ensureByFilter(filter: ListStatusFilter, opts?: { fresh?: boolean }): Promise<void> {+ if (!opts?.fresh && cache.has(filter)) return;let promise = inflight.get(filter);if (!promise) {- const request = fetchFilter(filter)+ const request = fetchFilter(filter, opts).then((data) => {// reset / forceRefresh 会把旧 request 从 inflight 移除。只有仍被// 当前桶认领的 request 才能提交,避免旧账号请求回填新账号缓存。@@ -336,7 +343,7 @@ export const sessionsStore = {async forceRefresh(filter: ListStatusFilter): Promise<Session[]> {cache.delete(filter);inflight.delete(filter);- await this.ensureByFilter(filter);+ await this.ensureByFilter(filter, { fresh: true });return cache.get(filter) ?? [];},@@ -421,7 +428,7 @@ export const sessionsStore = {}if (removed) notify();for (const filter of toRefetch) {- void this.ensureByFilter(filter).catch(() => {+ void this.ensureByFilter(filter, { fresh: true }).catch(() => {/* 静默:后续主动操作或 refresh 会再次兜底。 */});}@@ -485,7 +492,7 @@ export const sessionsStore = {// 订阅者的 subscribe 回调拿到 null 不会 setState,会一直停在陈旧 snapshot。// 主动 ensure 一下,IPC 回来后 notify → 订阅者拿到新数据自动 swap。for (const filter of toRefetch) {- void this.ensureByFilter(filter).catch(() => {+ void this.ensureByFilter(filter, { fresh: true }).catch(() => {/* 静默:网络/IPC 失败由后续主动操作或 refresh 兜底,不上报 toast */});}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 035b897a3d..5f252e4828 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4247,6 +4247,7 @@ interface ElectronAPI {list: (limit?: number,status?: 'active' | 'archived' | 'all',+ options?: { includePinned?: boolean; fresh?: boolean },) => Promise<import('@/lib/ccAgent.types').Session[]>;create: (body?: {id?: string;diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsxindex 6e9d1422ac..75a0cb3f86 100644--- a/apps/mobile/app/devices/[deviceId].tsx+++ b/apps/mobile/app/devices/[deviceId].tsx@@ -247,7 +247,8 @@ export default function DeviceDetailScreen() {// 自动化任务作用域页承诺展示"该任务的全部 N 次运行",归档的 run 也算,// 必须拉全量;其余模式仍按当前筛选拉取。automationScopeKey ? 'all' : remoteListStatusFilter(statusFilter),- { includePinned: true },+ // 首拉 / reseed / 筛选重拉都是权威快照,不并入被控端写前查询。+ { includePinned: true, fresh: true },]);});remoteSessionStore.setDeviceSessions(deviceId, deviceName, Array.isArray(list) ? list : []);diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsxindex 6ccdd90093..e1489c9db8 100644--- a/apps/mobile/app/devices/index.tsx+++ b/apps/mobile/app/devices/index.tsx@@ -425,7 +425,8 @@ export default function HomeScreen() {invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [LIST_LIMIT,remoteListStatusFilter(statusFilter),- { includePinned: true },+ // hydrate / 重连是权威重拉,绕开被控端写前的同参数 in-flight list。+ { includePinned: true, fresh: true },]),// `sessions` topic replay covers list-level Agent Island activity, but the authoritative// "turn currently running" snapshot is maker:list-active. Pull it with the list so Homediff --git a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts b/apps/mobile/src/__tests__/remoteListIncludePinned.test.tsindex 030a97150d..7620f73c72 100644--- a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts+++ b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts@@ -6,7 +6,8 @@ describe('mobile remote session bootstrap', () => {it('asks the controlled desktop to include active pinned sessions outside the recent window', () => {const homeSource = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');const detailSource = readFileSync(resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8');- const listWithPinned = /local-db:sessions:list'[\s\S]{0,220}\{ includePinned: true \}/;+ const listWithPinned =+ /local-db:sessions:list'[\s\S]{0,280}\{ includePinned: true, fresh: true \}/;expect(homeSource).toMatch(listWithPinned);expect(detailSource).toMatch(listWithPinned);