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): preserve pin metadata across stale session lists

321sssrt-bitdbd689d9bcde
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx
index acfec048aa..937455f8fc 100644
--- a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx
@@ -11,23 +11,57 @@ type SpendPayload = {
};
type OwnerStamp = { dataOwnerId: string | null; ownerGeneration: number };
+const stickyOrigin = vi.hoisted(() => ({
+ deviceBySession: new Map<string, string>(),
+}));
+
+vi.mock('@/features/device-link/stickySessionOrigin', () => ({
+ getStickySessionDeviceId: (sessionId: string | null | undefined): string | undefined =>
+ sessionId ? stickyOrigin.deviceBySession.get(sessionId) : undefined,
+}));
+
const mocks = vi.hoisted(() => {
let spendListener: ((payload: SpendPayload, ownerStamp?: OwnerStamp) => void) | undefined;
+ let sessionPatchListener:
+ | ((payload: { sessionId: string; patch: Partial<Session> }, ownerStamp?: OwnerStamp) => void)
+ | undefined;
const onUsageSessionSpendChanged = vi.fn(
(listener: (payload: SpendPayload, ownerStamp?: OwnerStamp) => void) => {
spendListener = listener;
return vi.fn();
},
);
+ const onSessionPatched = vi.fn(
+ (
+ listener: (payload: { sessionId: string; patch: Partial<Session> }, ownerStamp?: OwnerStamp) => void,
+ ) => {
+ sessionPatchListener = listener;
+ return vi.fn();
+ },
+ );
Object.defineProperty(window, 'electronAPI', {
configurable: true,
- value: { onUsageSessionSpendChanged },
+ value: {
+ onUsageSessionSpendChanged,
+ localDb: {
+ sessionsPush: {
+ onPatched: onSessionPatched,
+ onCreated: vi.fn(() => vi.fn()),
+ },
+ },
+ },
});
return {
list: vi.fn(),
emitSessionSpend(payload: SpendPayload, ownerStamp?: OwnerStamp): void {
spendListener?.(payload, ownerStamp);
},
+ emitSessionPatch(
+ payload: { sessionId: string; patch: Partial<Session> },
+ ownerStamp?: OwnerStamp,
+ ): void {
+ sessionPatchListener?.(payload, ownerStamp);
+ },
};
});
@@ -61,6 +95,7 @@ function session(id: string, partial: Partial<Session> = {}): Session {
describe('sessionsStore account boundaries', () => {
beforeEach(() => {
mocks.list.mockReset();
+ stickyOrigin.deviceBySession.clear();
sessionsStore.reset();
});
@@ -70,6 +105,101 @@ describe('sessionsStore account boundaries', () => {
dataOwnerTesting.reset();
});
+ it('rejects an old hook patch callback after the data owner changes', async () => {
+ const pinnedAt = '2026-08-27T01:00:00.000Z';
+ setDataOwnerGeneration('owner-a', 1);
+ mocks.list.mockResolvedValueOnce([
+ session('same-id', { pinnedAt, summary: 'owner-a summary' }),
+ ]);
+ const view = renderHook(() => useCCSessions());
+ await waitFor(() => expect(view.result.current.sessions).toHaveLength(1));
+ const oldPatchLocal = view.result.current.patchLocal;
+
+ const newRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => newRequest.promise);
+ setDataOwnerGeneration('owner-b', 2);
+ act(() => sessionsStore.reset());
+ expect(mocks.list).toHaveBeenCalledTimes(2);
+
+ act(() => {
+ oldPatchLocal('same-id', { pinnedAt: null, summary: null });
+ });
+ newRequest.resolve([
+ session('same-id', { pinnedAt, summary: 'owner-b summary' }),
+ ]);
+ await waitFor(() => {
+ expect(view.result.current.sessions).toEqual([
+ expect.objectContaining({
+ id: 'same-id',
+ pinnedAt,
+ summary: 'owner-b summary',
+ }),
+ ]);
+ });
+ });
+
+ it('ignores a stale owner-stamped local sessions push', async () => {
+ setDataOwnerGeneration('owner-b', 2);
+ const pinnedAt = '2026-08-27T01:00:00.000Z';
+ mocks.list.mockResolvedValueOnce([
+ session('same-id', { pinnedAt, summary: 'owner-b summary' }),
+ ]);
+ await sessionsStore.ensureByFilter('active');
+
+ act(() => {
+ mocks.emitSessionPatch(
+ { sessionId: 'same-id', patch: { pinnedAt: null, summary: null } },
+ { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ );
+ });
+ expect(sessionsStore.findById('same-id')).toEqual(
+ expect.objectContaining({ pinnedAt, summary: 'owner-b summary' }),
+ );
+
+ act(() => {
+ mocks.emitSessionPatch(
+ { sessionId: 'same-id', patch: { pinnedAt: null, summary: null } },
+ { dataOwnerId: 'owner-b', ownerGeneration: 2 },
+ );
+ });
+ expect(sessionsStore.findById('same-id')).toEqual(
+ expect.objectContaining({ pinnedAt: null, summary: null }),
+ );
+ });
+
+ it('rejects a remote device-link patchLocal while a same-id local refresh is in flight', async () => {
+ const sessionId = 'same-id';
+ const pinnedAt = '2026-08-27T01:00:00.000Z';
+ stickyOrigin.deviceBySession.set(sessionId, 'device-a');
+ setDataOwnerGeneration('owner-b', 2);
+ const pinned = session(sessionId, { pinnedAt, summary: 'local summary' });
+ mocks.list.mockResolvedValueOnce([pinned]);
+ await sessionsStore.ensureByFilter('active');
+ const view = renderHook(() => useCCSessions());
+
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleLoad = sessionsStore.forceRefresh('active');
+ act(() => {
+ view.result.current.patchLocal(sessionId, { pinnedAt: null, summary: null });
+ });
+ await act(async () => {
+ staleRequest.resolve([pinned]);
+ await staleLoad;
+ });
+ expect(sessionsStore.findById(sessionId)).toEqual(
+ expect.objectContaining({ pinnedAt, summary: 'local summary' }),
+ );
+
+ stickyOrigin.deviceBySession.delete(sessionId);
+ act(() => {
+ view.result.current.patchLocal(sessionId, { pinnedAt: null, summary: null });
+ });
+ expect(sessionsStore.findById(sessionId)).toEqual(
+ expect.objectContaining({ pinnedAt: null, summary: null }),
+ );
+ });
+
it('does not let a request started before reset repopulate the cache', async () => {
const oldRequest = deferred<Session[]>();
const newRequest = deferred<Session[]>();
@@ -166,6 +296,25 @@ describe('sessionsStore account boundaries', () => {
expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual(['keep']);
});
+ it('clears pin metadata overrides when a removed session id is reused', async () => {
+ const pinnedAt = '2026-08-27T01:00:00.000Z';
+ const pinned = session('reused-id', { pinnedAt, summary: 'old summary' });
+ mocks.list.mockResolvedValueOnce([pinned]);
+ await sessionsStore.ensureByFilter('active');
+
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleLoad = sessionsStore.forceRefresh('active');
+ sessionsStore.patchLocal('reused-id', { pinnedAt: null, summary: null });
+ sessionsStore.removeLocal('reused-id');
+
+ staleRequest.resolve([pinned]);
+ await staleLoad;
+ expect(sessionsStore.findById('reused-id')).toEqual(
+ expect.objectContaining({ pinnedAt, summary: 'old summary' }),
+ );
+ });
+
it('patches only the matching cached session when persisted spend changes', async () => {
mocks.list.mockResolvedValueOnce([
session('target', { totalCostUsd: 1 }),
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
index dab7f3a206..a5055c87de 100644
--- a/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
@@ -30,7 +30,7 @@ vi.mock('@/lib/sessionService', () => ({
}));
import { useCCSessions } from '@/hooks/useCCSessions';
-import { emitAutoTitlePreview } from '@/lib/sessionsBus';
+import { emitAutoTitlePreview, emitPatch } from '@/lib/sessionsBus';
import { sessionsStore } from '@/lib/sessionsStore';
import type { ListStatusFilter } from '@/lib/sessionService';
@@ -72,6 +72,91 @@ describe('sessionsStore status bucket migration', () => {
sessionsStore.reset();
});
+ it('retains a successful unpin patch when an older list response returns', async () => {
+ const pinned = {
+ ...session('unpin-me'),
+ pinnedAt: '2026-08-27T01:00:00.000Z',
+ summary: 'old summary',
+ } as Session;
+ mocks.list.mockResolvedValueOnce([pinned]);
+ await sessionsStore.ensureByFilter('active');
+
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockReturnValueOnce(staleRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('active');
+
+ emitPatch('unpin-me', { pinnedAt: null, summary: null });
+ staleRequest.resolve([pinned]);
+ await staleRefresh;
+
+ expect(sessionsStore.findById('unpin-me')).toEqual(
+ expect.objectContaining({ pinnedAt: null, summary: null }),
+ );
+ });
+
+ it('does not let a summary-only update extend stale pin protection to a newer request', async () => {
+ const pinned = {
+ ...session('field-revisions'),
+ pinnedAt: '2026-08-27T01:00:00.000Z',
+ summary: 'old summary',
+ } as Session;
+ mocks.list.mockResolvedValueOnce([pinned]);
+ await sessionsStore.ensureByFilter('active');
+
+ emitPatch('field-revisions', {
+ status: 'active',
+ pinnedAt: pinned.pinnedAt,
+ updatedAt: '2026-08-27T02:00:00.000Z',
+ });
+ emitPatch('field-revisions', { pinnedAt: null, summary: null });
+
+ const listRequest = deferred<Session[]>();
+ mocks.list.mockReturnValueOnce(listRequest.promise);
+ const refresh = sessionsStore.forceRefresh('active');
+ emitPatch('field-revisions', { summary: 'new summary' });
+
+ const repinned = { ...pinned, pinnedAt: '2026-08-27T03:00:00.000Z' } as Session;
+ listRequest.resolve([repinned]);
+ await refresh;
+ expect(sessionsStore.findById('field-revisions')).toEqual(
+ expect.objectContaining({
+ pinnedAt: repinned.pinnedAt,
+ summary: 'new summary',
+ }),
+ );
+ });
+
+ it('replays a later repin after a failed pin over a stale list response', async () => {
+ const unpinned = {
+ ...session('repin-me'),
+ pinnedAt: null,
+ summary: null,
+ } as Session;
+ mocks.list.mockResolvedValueOnce([unpinned]);
+ await sessionsStore.ensureByFilter('active');
+
+ const failedPinRequest = deferred<Session[]>();
+ mocks.list.mockReturnValueOnce(failedPinRequest.promise);
+ const failedPinRefresh = sessionsStore.forceRefresh('active');
+ sessionsStore.patchLocal('repin-me', { pinnedAt: '2026-08-27T01:00:00.000Z' });
+ sessionsStore.patchLocal('repin-me', { pinnedAt: null });
+ failedPinRequest.resolve([unpinned]);
+ await failedPinRefresh;
+ expect(sessionsStore.findById('repin-me')).toEqual(
+ expect.objectContaining({ pinnedAt: null, summary: null }),
+ );
+
+ const repinRequest = deferred<Session[]>();
+ mocks.list.mockReturnValueOnce(repinRequest.promise);
+ const repinRefresh = sessionsStore.forceRefresh('active');
+ sessionsStore.patchLocal('repin-me', { pinnedAt: '2026-08-27T02:00:00.000Z' });
+ repinRequest.resolve([unpinned]);
+ await repinRefresh;
+ expect(sessionsStore.findById('repin-me')).toEqual(
+ expect.objectContaining({ pinnedAt: '2026-08-27T02:00:00.000Z', summary: null }),
+ );
+ });
+
it('publishes original list mutations with the preserved row, including deletion outside cached windows', async () => {
const row = session('task');
mocks.list.mockResolvedValueOnce([row]);
@@ -223,7 +308,10 @@ describe('sessionsStore status bucket migration', () => {
});
it('keeps an optimistic archive applied to list requests started before the DB write completes', async () => {
- const target = session('archive-me', 'active', '2026-08-27T02:00:00.000Z');
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T02:00:00.000Z'),
+ pinnedAt: '2026-08-27T01:00:00.000Z',
+ } as Session;
const keep = session('keep', 'active', '2026-08-27T01:00:00.000Z');
const alreadyArchived = session(
'already-archived',
@@ -258,11 +346,11 @@ describe('sessionsStore status bucket migration', () => {
expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep']);
expect(sessionsStore.getByFilter('archived')).toEqual([
- expect.objectContaining({ id: 'archive-me', status: 'archived' }),
+ expect.objectContaining({ id: 'archive-me', status: 'archived', pinnedAt: null }),
expect.objectContaining({ id: 'already-archived' }),
]);
expect(sessionsStore.getByFilter('all')?.find(({ id }) => id === 'archive-me')).toEqual(
- expect.objectContaining({ status: 'archived' }),
+ expect.objectContaining({ status: 'archived', pinnedAt: null }),
);
});
@@ -416,6 +504,89 @@ describe('sessionsStore status bucket migration', () => {
);
});
+ it('preserves newer pin metadata over a stale complete status row', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ pinnedAt: '2026-08-27T00:00:00.000Z',
+ summary: 'old summary',
+ model: 'old-model',
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('all');
+ sessionsStore.patchLocal('archive-me', {
+ pinnedAt: null,
+ summary: 'new summary',
+ model: 'new-model',
+ });
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ summary: 'persisted summary',
+ model: 'persisted-model',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ staleRequest.resolve([target]);
+ await staleRefresh;
+
+ expect(sessionsStore.findById('archive-me')).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ pinnedAt: null,
+ summary: 'new summary',
+ model: 'new-model',
+ }),
+ );
+ });
+
+ it('keeps the rollback pin while retaining concurrent metadata over a stale response', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ pinnedAt: '2026-08-27T00:00:00.000Z',
+ summary: 'old summary',
+ model: 'old-model',
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('all');
+ sessionsStore.patchLocal('archive-me', {
+ pinnedAt: '2026-08-27T02:00:00.000Z',
+ summary: 'new summary',
+ model: 'new-model',
+ });
+
+ expect(sessionsStore.rollbackStatusTransition(transition!)).toBe(true);
+ staleRequest.resolve([target]);
+ await staleRefresh;
+
+ expect(sessionsStore.findById('archive-me')).toEqual(
+ expect.objectContaining({
+ status: 'active',
+ pinnedAt: '2026-08-27T00:00:00.000Z',
+ summary: 'new summary',
+ model: 'new-model',
+ }),
+ );
+ });
+
it('keeps concurrent settings updates when the persisted status row has the same updatedAt', async () => {
const target = {
...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
diff --git a/apps/desktop/src/renderer/hooks/useCCSessions.ts b/apps/desktop/src/renderer/hooks/useCCSessions.ts
index 6637f2d43e..7a83f0d8e3 100644
--- a/apps/desktop/src/renderer/hooks/useCCSessions.ts
+++ b/apps/desktop/src/renderer/hooks/useCCSessions.ts
@@ -27,6 +27,11 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { AgentKind, Session, WorkspaceKind } from '@/lib/ccAgent.types';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
import * as sessionService from '@/lib/sessionService';
import type { ListStatusFilter } from '@/lib/sessionService';
import { sessionsStore } from '@/lib/sessionsStore';
@@ -80,6 +85,9 @@ interface SnapshotState {
export function useCCSessions(options?: UseCCSessionsOptions): UseCCSessionsReturn {
const filter: ListStatusFilter = options?.includeArchived ?? 'active';
+ // patchLocal 可能被异步写入失败回调持有;让该回调只属于创建它的 data owner,
+ // 避免旧账号的 remote/local pin 回滚在账号切换后的同 sessionId 上落入新缓存。
+ const patchOwner = getDataOwnerGeneration();
// 关键:初始 snapshot 来自 store —— remount 命中 cache 即非 null,无 skeleton 闪烁。
const [snapshotState, setSnapshotState] = useState<SnapshotState>(() => ({
@@ -196,8 +204,11 @@ export function useCCSessions(options?: UseCCSessionsOptions): UseCCSessionsRetu
/** Update a session's fields without re-fetching. Preserves list order — useful
* for renames that shouldn't re-sort. 实际转发给 store 让所有 subscriber 同步。 */
const patchLocal = useCallback(
- (id: string, patch: Partial<Session>) => sessionsStore.patchLocal(id, patch),
- [],
+ (id: string, patch: Partial<Session>) => {
+ if (!isDataOwnerGenerationCurrent(patchOwner) || getStickySessionDeviceId(id)) return;
+ sessionsStore.patchLocal(id, patch);
+ },
+ [patchOwner],
);
return {
diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.ts
index 291f8ba181..c8e1a78897 100644
--- a/apps/desktop/src/renderer/lib/sessionsStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts
@@ -222,6 +222,18 @@ interface SessionTitleOverride {
const sessionTitleOverrides = new Map<string, SessionTitleOverride>();
let sessionTitleRevision = 0;
+/**
+ * 置顶与卡片摘要各自记录版本和值,避免一个字段的事件延长另一个字段的保护期。
+ * 只有在列表请求起飞后到达的字段才会被重放;新请求仍以数据库返回值为准。
+ */
+interface SessionPinSummaryOverride {
+ pinnedAt?: { revision: number; value: Session['pinnedAt'] };
+ summary?: { revision: number; value: string | null };
+}
+
+const sessionPinSummaryOverrides = new Map<string, SessionPinSummaryOverride>();
+let sessionPinSummaryRevision = 0;
+
interface SessionStatusOverride {
/** status 事件版本;rollback 用它区分同向状态是否有更晚的权威写入。 */
revision: number;
@@ -240,6 +252,39 @@ const sessionStatusOverrides = new Map<string, SessionStatusOverride>();
let sessionStatusRevision = 0;
let sessionStatusRowRevision = 0;
+/**
+ * status override 的完整行可能带着较早的 pin / summary 值;这些字段有自己的版本,
+ * 新列表请求应让数据库值胜出,不能因其它字段推进 rowRevision 又重放旧 metadata。
+ */
+function filterStatusOverridePatch(
+ sessionId: string,
+ patch: Partial<Session>,
+ afterPinSummaryRevision: number,
+): Partial<Session> {
+ const pinSummaryOverride = sessionPinSummaryOverrides.get(sessionId);
+ if (!pinSummaryOverride) return patch;
+ const next = { ...patch };
+ const pending = pendingStatusTransitions.get(sessionId);
+ // 归档写库在途时,连带的乐观 unpin 必须继续生效;仅保留该事务实际修改的字段。
+ const hasPendingPin = pending && !pending.hasSucceeded && 'pinnedAt' in pending.rollbackPatch;
+ if (
+ next.pinnedAt !== undefined &&
+ pinSummaryOverride.pinnedAt &&
+ pinSummaryOverride.pinnedAt.revision <= afterPinSummaryRevision &&
+ !hasPendingPin
+ ) {
+ delete next.pinnedAt;
+ }
+ if (
+ next.summary !== undefined &&
+ pinSummaryOverride.summary &&
+ pinSummaryOverride.summary.revision <= afterPinSummaryRevision
+ ) {
+ delete next.summary;
+ }
+ return next;
+}
+
export interface SessionStatusTransitionToken {
sessionId: string;
token: number;
@@ -390,6 +435,7 @@ function applySessionStatusOverrides(
filter: ListStatusFilter,
afterRevision: number,
afterRowRevision: number,
+ afterPinSummaryRevision: number,
): Session[] {
if (sessionStatusOverrides.size === 0) return list;
let next = list;
@@ -420,7 +466,12 @@ function applySessionStatusOverrides(
}
if (idx !== -1) {
const before = next;
- next = upsertSessionByUpdatedAt(before, mergeSession(before[idx], override.patch));
+ const replayPatch = filterStatusOverridePatch(
+ sessionId,
+ override.patch,
+ afterPinSummaryRevision,
+ );
+ next = upsertSessionByUpdatedAt(before, mergeSession(before[idx], replayPatch));
recordPendingStatusEviction(sessionId, filter, before, next);
changed = true;
continue;
@@ -449,6 +500,35 @@ function applySessionTitleOverrides(list: Session[], afterRevision: number): Ses
return changed ? next : list;
}
+/** 仅重放请求启动后到达的置顶 / 摘要事件,两个字段的版本彼此独立。 */
+function applySessionPinSummaryOverrides(list: Session[], afterRevision: number): Session[] {
+ if (sessionPinSummaryOverrides.size === 0) return list;
+ let changed = false;
+ const next = list.map((session) => {
+ const override = sessionPinSummaryOverrides.get(session.id);
+ if (!override) return session;
+ const patch: Partial<Session> = {};
+ if (
+ override.pinnedAt &&
+ override.pinnedAt.revision > afterRevision &&
+ override.pinnedAt.value !== session.pinnedAt
+ ) {
+ patch.pinnedAt = override.pinnedAt.value;
+ }
+ if (
+ override.summary &&
+ override.summary.revision > afterRevision &&
+ override.summary.value !== session.summary
+ ) {
+ patch.summary = override.summary.value;
+ }
+ if (Object.keys(patch).length === 0) return session;
+ changed = true;
+ return mergeSession(session, patch);
+ });
+ return changed ? next : list;
+}
+
/** 仅重放请求启动后到达的费用事件,避免旧事件覆盖未来数据库刷新。 */
function applySessionSpendOverrides(list: Session[], afterRevision: number): Session[] {
let changed = false;
@@ -508,6 +588,7 @@ async function fetchFilter(
): Promise<Session[]> {
// chat-data-localization round-5:IPC 'all'/undefined 与 HTTP 旧默认行为
// 不一致,必须把 filter 原样透传,由 IPC handler 决定过滤语义。
+ const pinSummaryRevisionAtStart = sessionPinSummaryRevision;
const spendRevisionAtStart = sessionSpendRevision;
const titleRevisionAtStart = sessionTitleRevision;
const statusRevisionAtStart = sessionStatusRevision;
@@ -519,15 +600,19 @@ async function fetchFilter(
opts?.fresh ? { fresh: true } : undefined,
);
// 顺序:status override 可能携带写库返回的完整旧行,必须先应用;再重放请求期间到达的
- // 费用与权威标题,最后叠乐观标题预览。否则完整状态行会把这三类更新盖回旧值。
+ // 置顶/摘要、费用与权威标题,最后叠乐观标题预览。否则完整状态行会把这些更新盖回旧值。
const result = applyAutoTitlePreviews(
applySessionTitleOverrides(
applySessionSpendOverrides(
- applySessionStatusOverrides(
- sessions,
- filter,
- statusRevisionAtStart,
- statusRowRevisionAtStart,
+ applySessionPinSummaryOverrides(
+ applySessionStatusOverrides(
+ sessions,
+ filter,
+ statusRevisionAtStart,
+ statusRowRevisionAtStart,
+ pinSummaryRevisionAtStart,
+ ),
+ pinSummaryRevisionAtStart,
),
spendRevisionAtStart,
),
@@ -572,6 +657,21 @@ function runTrailingFilterBackfill(filter: ListStatusFilter): void {
runFilterBackfill(filter);
}
+function recordSessionPinSummaryOverrides(
+ sessionId: string,
+ patch: Pick<Partial<Session>, 'pinnedAt' | 'summary'>,
+): void {
+ const pinnedAt = patch.pinnedAt;
+ const summary = patch.summary;
+ if (pinnedAt === undefined && summary === undefined) return;
+ const revision = ++sessionPinSummaryRevision;
+ const previous = sessionPinSummaryOverrides.get(sessionId);
+ const next: SessionPinSummaryOverride = { ...previous };
+ if (pinnedAt !== undefined) next.pinnedAt = { revision, value: pinnedAt };
+ if (summary !== undefined) next.summary = { revision, value: summary };
+ sessionPinSummaryOverrides.set(sessionId, next);
+}
+
function recordStatusOverride(
sessionId: string,
patch: Partial<Session>,
@@ -625,6 +725,11 @@ function applyAuthoritativeStatusSession(
autoTitlePreviews.delete(session.id);
sessionTitleOverrides.delete(session.id);
sessionSpendOverrides.delete(session.id);
+ sessionPinSummaryOverrides.delete(session.id);
+ } else {
+ // 完整状态成功/回滚行是新的权威 metadata 基线,必须推进对应版本,
+ // 否则更早的列表请求可能在状态收敛后再次带回旧置顶或摘要。
+ recordSessionPinSummaryOverrides(session.id, session);
}
let touched = false;
const toBackfill = new Set<ListStatusFilter>();
@@ -1003,6 +1108,9 @@ export const sessionsStore = {
} else {
mergeAuthoritativePatchIntoStatusOverride(id, patch);
}
+ if (patch.pinnedAt !== undefined || patch.summary !== undefined) {
+ recordSessionPinSummaryOverrides(id, patch);
+ }
// 权威标题落地(main 写完占位 / 智能标题后经 sessions:patched 回流,或用户手动改名)
// → 无条件回收预览条目。留着它会在下一次全量刷新时把真实标题又顶掉。
//
@@ -1034,6 +1142,7 @@ export const sessionsStore = {
autoTitlePreviews.delete(id);
sessionTitleOverrides.delete(id);
sessionSpendOverrides.delete(id);
+ sessionPinSummaryOverrides.delete(id);
}
if (patch.totalCostUsd !== undefined || patch.totalMoney !== undefined) {
sessionSpendRevision += 1;
@@ -1153,6 +1262,7 @@ export const sessionsStore = {
autoTitlePreviews.delete(id);
sessionTitleOverrides.delete(id);
sessionSpendOverrides.delete(id);
+ sessionPinSummaryOverrides.delete(id);
sessionStatusOverrides.delete(id);
let touched = false;
for (const [filter, list] of cache) {
@@ -1171,6 +1281,7 @@ export const sessionsStore = {
sessionSpendOverrides.clear();
autoTitlePreviews.clear();
sessionTitleOverrides.clear();
+ sessionPinSummaryOverrides.clear();
sessionStatusOverrides.clear();
hiddenSessionIds.clear();
statusTransitionGeneration += 1;