Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 已安装插件区按未读通知优先排序,去掉冻结快照的会话内过时 (#1810)
Chris Zhang71113c38a650
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsindex 10634956b6..958a639e5d 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -210,10 +210,12 @@ describe('ChatInput session switch focus contract', () => {expect(pluginPageSource).toContain('window.electronAPI.ghosts.onRecentUsageChanged(({ ids }) => {',);- expect(pluginPageSource).toMatch(- /sortGhostPluginItemsByRecentUse\(installedItems, recentGhostIds\)/,- );- expect(pluginPageSource).not.toContain('sortGhostPluginItemsByRecentUse(\n ghosts');+ // Ranking runs over the (searched) installed set, not the raw ghost list, and feeds+ // recent-use + unread signals into the shared pure sorter.+ expect(pluginPageSource).toMatch(/sortInstalledForDisplay\(searchedInstalledItems, \{/);+ expect(pluginPageSource).toContain('recentIds: recentGhostIds');+ expect(pluginPageSource).not.toContain('sortInstalledForDisplay(ghosts');+ expect(pluginPageSource).not.toContain('sortInstalledForDisplay(installedItems');});});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.tsindex 08f2667248..54ad4b184d 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts@@ -14,6 +14,8 @@ import {marketPresentationForInstalledGhost,nextOpenPanelIdForOwner,sortGhostPluginItemsByRecentUse,+ installedVisibleCount,+ sortInstalledForDisplay,toGhostPluginDetail,toGhostPluginListItem,type GhostPluginListItem,@@ -140,6 +142,72 @@ describe('ghostPluginViewModel', () => {).toEqual(['third', 'first', 'second', 'fourth']);});+ describe('sortInstalledForDisplay', () => {+ const items = [{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }];++ it('surfaces unread notifications first, newest badge on top', () => {+ expect(+ sortInstalledForDisplay(items, {+ recentIds: [],+ unreadAtById: new Map([+ ['c', 100],+ ['a', 300],+ ]),+ }).map((item) => item.id),+ ).toEqual(['a', 'c', 'b', 'd']);+ });++ it('ranks unread above recently-used, then recent, then base order', () => {+ // b is unread (top); d & a are recently used (d newest); c falls to base tail.+ expect(+ sortInstalledForDisplay(items, {+ recentIds: ['d', 'a'],+ unreadAtById: new Map([['b', 5]]),+ }).map((item) => item.id),+ ).toEqual(['b', 'd', 'a', 'c']);+ });++ it('keeps base order stable when no signal applies and ignores marketUpdate entirely', () => {+ // No unread / no recent → untouched. marketUpdate is not an input, so it cannot reorder.+ expect(+ sortInstalledForDisplay(items, { recentIds: [], unreadAtById: new Map() }).map(+ (item) => item.id,+ ),+ ).toEqual(['a', 'b', 'c', 'd']);+ });++ it('breaks unread ties on the same badge time by stable base order', () => {+ expect(+ sortInstalledForDisplay(items, {+ recentIds: [],+ unreadAtById: new Map([+ ['d', 7],+ ['b', 7],+ ]),+ }).map((item) => item.id),+ ).toEqual(['b', 'd', 'a', 'c']);+ });+ });++ describe('installedVisibleCount (unread never folded)', () => {+ const items = Array.from({ length: 12 }, (_, index) => ({ id: `p-${index}` }));++ it('keeps the base cap when unread count is within it', () => {+ expect(installedVisibleCount(items, new Map([['p-0', 9]]), 8)).toBe(8);+ expect(installedVisibleCount(items, new Map(), 8)).toBe(8);+ });++ it('expands the window to cover every unread plugin beyond the cap', () => {+ const unread = new Map(Array.from({ length: 10 }, (_, i) => [`p-${i}`, i]));+ // 10 unread > cap 8 → window grows to 10 so no unread plugin is folded.+ expect(installedVisibleCount(items, unread, 8)).toBe(10);+ });++ it('ignores unread ids that are not in the installed list', () => {+ expect(installedVisibleCount(items, new Map([['not-installed', 1]]), 8)).toBe(8);+ });+ });+it('maps install-record facts onto the list item', () => {const item = toGhostPluginListItem(installed());diff --git a/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.ts b/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.tsindex 0dba251389..29d84c323d 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostUnreadStore.ts@@ -21,6 +21,9 @@ interface UnreadEntry {const unread = new Map<string, UnreadEntry>();const listeners = new Set<() => void>();let ready = false;+// Bumped on every mutation so the sorted entries snapshot can be cached by identity+// (useSyncExternalStore requires getSnapshot to return a stable ref when nothing changed).+let version = 0;interface UnreadSnapshotEntry {ghostId: string;@@ -42,6 +45,7 @@ function api(): GhostUnreadApi | undefined {}function emit(): void {+ version += 1;for (const cb of [...listeners]) cb();}@@ -149,6 +153,43 @@ export function useGhostUnreadSummary(ghostId: string): string | undefined {);}+/** 某意识当前未读通知的点亮时刻(用于排序),没有未读时 undefined。 */+export interface GhostUnreadOrderEntry {+ ghostId: string;+ at: number;+}++const EMPTY_UNREAD_ENTRIES: readonly GhostUnreadOrderEntry[] = [];+let cachedEntries: { version: number; value: readonly GhostUnreadOrderEntry[] } | null = null;++/**+ * 全部未读条目的快照,按点亮时刻 `at` 从新到旧排序。+ * 按 version 缓存:表没变就返回同一引用,满足 useSyncExternalStore 的稳定性要求;+ * 插件页用它把「有未读通知」的插件排到已安装区最前(见 sortInstalledForDisplay)。+ */+function unreadEntriesSnapshot(): readonly GhostUnreadOrderEntry[] {+ if (unread.size === 0) return EMPTY_UNREAD_ENTRIES;+ if (!cachedEntries || cachedEntries.version !== version) {+ const value = [...unread.entries()]+ .map(([ghostId, entry]) => ({ ghostId, at: entry.at }))+ .sort((a, b) => b.at - a.at);+ cachedEntries = { version, value };+ }+ return cachedEntries.value;+}++/** 全部未读条目(id + 点亮时刻),新→旧;用于已安装区排序。 */+export function useGhostUnreadEntries(): readonly GhostUnreadOrderEntry[] {+ return useSyncExternalStore(+ subscribe,+ () => {+ ensureReady();+ return unreadEntriesSnapshot();+ },+ () => EMPTY_UNREAD_ENTRIES,+ );+}+/*** 是否**任一**意识有未读(侧栏插件入口的聚合静态点)。* 返回 boolean 而非计数:入口点不显示数量,订阅 boolean 能少掉一大半重渲染。@@ -280,5 +321,6 @@ export function __ingestGhostBadgeForTest(export function __resetGhostUnreadForTest(): void {unread.clear();listeners.clear();+ version += 1;ready = false;}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 39cc93c848..62338ca7a7 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -58,7 +58,11 @@ import { confirmAndInstallGhost, pickAndUpdateGhost } from '@/cindy-brain/instalimport { GhostPermissionList, GhostUpdateReview } from '@/cindy-brain/GhostPermissionList';import { cn } from '@/lib/utils';import { AttentionDot } from '@/components/sidebar/AttentionDot';-import { useGhostUnread, useGhostUnreadSummary } from '@/cindy-brain/ghostUnreadStore';+import {+ useGhostUnread,+ useGhostUnreadEntries,+ useGhostUnreadSummary,+} from '@/cindy-brain/ghostUnreadStore';import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';import { findSplitChildByPanelKind } from '../../../shared/layoutTree';import { resolveSystemLocale } from '../../../shared/locale';@@ -85,8 +89,9 @@ import {ghostPanelOwnerKey,ghostPrimaryAction,marketPresentationForInstalledGhost,+ installedVisibleCount,nextOpenPanelIdForOwner,- sortGhostPluginItemsByRecentUse,+ sortInstalledForDisplay,type GhostPluginListItem,} from './lib/ghostPluginViewModel';import { ignoredRoundStorageKey, isBatchFinished, updateRoundKey } from './lib/updateAllModel';@@ -155,55 +160,6 @@ function collapsedInstalledPluginPreviewItems<T>(items: readonly T[]): T[] {return items.slice(0, MAX_COLLAPSED_INSTALLED_PLUGIN_PREVIEWS);}-function reconcileInstalledPluginOrderSnapshot(- snapshot: readonly string[],- previousIds: readonly string[],- nextIds: readonly string[],-): string[] {- const previousSet = new Set(previousIds);- const nextSet = new Set(nextIds);- const addedIds = nextIds.filter((id) => !previousSet.has(id));- const addedSet = new Set(addedIds);- const retainedIds = snapshot.filter((id) => nextSet.has(id) && !addedSet.has(id));- const retainedSet = new Set(retainedIds);- const untrackedIds = nextIds.filter((id) => !addedSet.has(id) && !retainedSet.has(id));- return [...addedIds, ...retainedIds, ...untrackedIds];-}--function initializeInstalledPluginOrderSnapshot(- marketSortedIds: readonly string[],- preSnapshotIds: readonly string[],- currentIds: readonly string[],-): string[] {- return reconcileInstalledPluginOrderSnapshot(marketSortedIds, preSnapshotIds, currentIds);-}--function shouldInitializeInstalledPluginOrderSnapshot(- hasOrderSnapshot: boolean,- orderSnapshotHasAvailableMarket: boolean,- marketSnapshot: PluginMarketSnapshot | null,-): boolean {- if (marketSnapshot === null) return false;- if (!hasOrderSnapshot) return true;- return !orderSnapshotHasAvailableMarket && marketSnapshot.unavailableReason === null;-}--function surfaceNewlyUpdatableInstalledPlugins(- orderSnapshot: readonly string[],- previousUpdatableIds: readonly string[],- nextUpdatableIds: readonly string[],-): readonly string[] {- const previousUpdatableSet = new Set(previousUpdatableIds);- const newlyUpdatableSet = new Set(nextUpdatableIds.filter((id) => !previousUpdatableSet.has(id)));- const hiddenNewlyUpdatableIds = orderSnapshot- .slice(MAX_VISIBLE_INSTALLED_PLUGINS)- .filter((id) => newlyUpdatableSet.has(id));- if (hiddenNewlyUpdatableIds.length === 0) return orderSnapshot;-- const promotedSet = new Set(hiddenNewlyUpdatableIds);- return [...hiddenNewlyUpdatableIds, ...orderSnapshot.filter((id) => !promotedSet.has(id))];-}-type InstalledPluginPreviewItem = Pick<PresentedGhostPluginItem, 'id' | 'name' | 'iconDataUrl'>;function InstalledPluginOverflow({@@ -298,10 +254,6 @@ export const __installedPluginLayoutForTests = {MAX_VISIBLE_INSTALLED_PLUGINS,MAX_COLLAPSED_INSTALLED_PLUGIN_PREVIEWS,visibleInstalledPluginItems,- initializeInstalledPluginOrderSnapshot,- reconcileInstalledPluginOrderSnapshot,- shouldInitializeInstalledPluginOrderSnapshot,- surfaceNewlyUpdatableInstalledPlugins,InstalledPluginOverflow,InstalledPluginDisclosure,};@@ -343,18 +295,11 @@ export function GhostPluginPage() {const [selectedId, setSelectedId] = useState<string | null>(null);const [query, setQuery] = useState('');const [installedExpanded, setInstalledExpanded] = useState(false);- const [orderSnapshot, setOrderSnapshot] = useState<string[] | null>(null);- const preOrderSnapshotInstalledGhostIdsRef = useRef(installedGhostIds);const installedOverflowId = useId();const [marketSnapshot, setMarketSnapshot] = useState<PluginMarketSnapshot | null>(null);const [openPanelId, setOpenPanelId] = useState<string | null>(null);- // 数据归属键:面板宿主与排序快照都按它失效(定义要早于两处消费点)。+ // 数据归属键:面板宿主按它失效(定义要早于消费点)。const panelOwnerKey = ghostPanelOwnerKey(mode, dataOwnerId);- const orderSnapshotStatusRef = useRef<{- ownerKey: string | null;- hasAvailableMarket: boolean;- updatableIds: string[];- }>({ ownerKey: panelOwnerKey, hasAvailableMarket: false, updatableIds: [] });const ignoredRoundKey = ignoredRoundStorageKey(mode, dataOwnerId);const [ignoredRound, setIgnoredRound] = useState(() => readIgnoredRound(ignoredRoundKey));// 账号 / 本地云模式切换:换桶重读,不把上一个身份的「忽略本轮」带进来。@@ -388,7 +333,6 @@ export function GhostPluginPage() {const lastMarketRefreshAtRef = useRef(0);const marketDetailRequestRef = useRef(0);const installedGhostIdsKeyRef = useRef(installedGhostIdsKey);- const installedGhostIdsRef = useRef(installedGhostIds);const legacyRecoveryStatusRequestRef = useRef(0);const legacyRecoveryRetryRequestRef = useRef(0);const [legacyRecoveryStatus, setLegacyRecoveryStatus] =@@ -435,22 +379,10 @@ export function GhostPluginPage() {usePluginMarketForegroundRefresh(refreshMarketOnForeground, lastMarketRefreshAtRef);useEffect(() => {if (installedGhostIdsKeyRef.current === installedGhostIdsKey) return;- const previousInstalledGhostIds = installedGhostIdsRef.current;installedGhostIdsKeyRef.current = installedGhostIdsKey;- installedGhostIdsRef.current = installedGhostIds;- setOrderSnapshot((snapshot) =>- snapshot === null- ? null- : reconcileInstalledPluginOrderSnapshot(- snapshot,- previousInstalledGhostIds,- installedGhostIds,- ),- );- // refreshMarket(true) reports an unavailable market by rejecting after preserving- // the current snapshot; the state update already happened in refreshMarket.+ // 已装集合变化(装/卸)时刷新市场;排序是反应式的,没有快照需要维护。void refreshMarket(true).catch(() => undefined);- }, [installedGhostIds, installedGhostIdsKey, refreshMarket]);+ }, [installedGhostIdsKey, refreshMarket]);const activeSessionWorkingDir = useSyncExternalStore(subscribeToLastWorkingDir,getLastWorkingDir,@@ -666,120 +598,47 @@ export function GhostPluginPage() {return counts;}, [searchedAvailableMarketItems]);- // ── 排序快照:首个市场结果先定序;若它不可用,首次恢复时再升级一次 ──- // 可更新的排最前,其余按最近使用。有效快照建立后保持稳定;只有刷新中新出现- // 且原本藏在折叠区的更新会临时移入前 8,避免更新提示不可见。- // 换账号/模式要丢弃旧顺序:两个 owner 的已装集合、可更新集合与最近使用- // 都不同,沿用账号 A 的 id 顺序会把 B 的非更新项排到更新项前面,违背- // 「可更新优先」。清空后由下面的 effect 基于**新 owner 的首个市场快照**重排。- const orderOwnerKeyRef = useRef(panelOwnerKey);+ // ── 已安装区排序:未读通知(新→旧) → 最近使用 → 基础序,实时计算 ──+ // 反应式而非冻结快照:排序信号变化即重排。安全边界——`markUsed` 只在对话里+ // 触发(ChatInput),插件页自身不打点,所以「最近使用」的变化只发生在离开本页+ // 之后,回到页面即已重排,不会在用户眼皮下洗牌;后台到达的未读通知冒头则正是+ // 目的所在。切账号/模式时 recentGhostIds 与未读表都会随 owner 快照整体作废。+ // marketUpdate 刻意不作排序键——更新已有统一横幅兜底,可被折叠。+ const unreadEntries = useGhostUnreadEntries();+ const unreadAtById = useMemo(+ () => new Map(unreadEntries.map((entry) => [entry.ghostId, entry.at])),+ [unreadEntries],+ );+ // 切账号/模式收起折叠区:换 owner 的已装集合不同,上一个身份的展开态不带过去。+ const collapseOwnerKeyRef = useRef(panelOwnerKey);useEffect(() => {- if (orderOwnerKeyRef.current === panelOwnerKey) return;- orderOwnerKeyRef.current = panelOwnerKey;- orderSnapshotStatusRef.current = {- ownerKey: null,- hasAvailableMarket: false,- updatableIds: [],- };- preOrderSnapshotInstalledGhostIdsRef.current = installedGhostIds;- setOrderSnapshot(null);+ if (collapseOwnerKeyRef.current === panelOwnerKey) return;+ collapseOwnerKeyRef.current = panelOwnerKey;setInstalledExpanded(false);- }, [installedGhostIds, panelOwnerKey]);- useEffect(() => {- const orderSnapshotStatus = orderSnapshotStatusRef.current;- if (orderSnapshot !== null && orderSnapshotStatus.ownerKey !== panelOwnerKey) return;- if (marketSnapshot === null) return;- const updatableIds = installedItems- .filter((item) => item.marketUpdate !== null)- .map((item) => item.id);- const marketAvailable = marketSnapshot.unavailableReason === null;- const shouldInitializeOrder = shouldInitializeInstalledPluginOrderSnapshot(- orderSnapshot !== null,- orderSnapshotStatus.hasAvailableMarket,- marketSnapshot,- );- if (!shouldInitializeOrder) {- if (orderSnapshot === null || !marketAvailable || !orderSnapshotStatus.hasAvailableMarket) {- return;- }- orderSnapshotStatusRef.current = {- ownerKey: panelOwnerKey,- hasAvailableMarket: true,- updatableIds,- };- setOrderSnapshot((currentOrderSnapshot) => {- if (currentOrderSnapshot === null) return currentOrderSnapshot;- const nextOrderSnapshot = surfaceNewlyUpdatableInstalledPlugins(- currentOrderSnapshot,- orderSnapshotStatus.updatableIds,- updatableIds,- );- return nextOrderSnapshot === currentOrderSnapshot- ? currentOrderSnapshot- : [...nextOrderSnapshot];- });- return;- }- const updatable = new Set(updatableIds);- const byRecentUse = sortGhostPluginItemsByRecentUse(installedItems, recentGhostIds);- const ids = byRecentUse- .map((item, stableIndex) => ({ item, stableIndex }))- .sort((a, b) => {- const aUp = updatable.has(a.item.id) ? 0 : 1;- const bUp = updatable.has(b.item.id) ? 0 : 1;- if (aUp !== bUp) return aUp - bUp;- return a.stableIndex - b.stableIndex;- })- .map(({ item }) => item.id);- orderSnapshotStatusRef.current = {- ownerKey: panelOwnerKey,- hasAvailableMarket: marketAvailable,- updatableIds: marketAvailable ? updatableIds : [],- };- setOrderSnapshot(- initializeInstalledPluginOrderSnapshot(- ids,- preOrderSnapshotInstalledGhostIdsRef.current,- installedGhostIds,- ),- );- }, [- orderSnapshot,- marketSnapshot,- installedGhostIds,- installedItems,- panelOwnerKey,- recentGhostIds,- ]);- const displayInstalledItems = useMemo(() => {- if (orderSnapshot === null) return searchedInstalledItems;- const orderIndex = new Map(orderSnapshot.map((id, index) => [id, index]));- return searchedInstalledItems- .map((item, stableIndex) => ({ item, stableIndex }))- .sort((a, b) => {- const aIndex = orderIndex.get(a.item.id);- const bIndex = orderIndex.get(b.item.id);- if (aIndex !== undefined && bIndex !== undefined && aIndex !== bIndex) {- return aIndex - bIndex;- }- if (aIndex !== undefined && bIndex === undefined) return -1;- if (aIndex === undefined && bIndex !== undefined) return 1;- return a.stableIndex - b.stableIndex;- })- .map(({ item }) => item);- }, [orderSnapshot, searchedInstalledItems]);+ }, [panelOwnerKey]);+ const displayInstalledItems = useMemo(+ () =>+ sortInstalledForDisplay(searchedInstalledItems, {+ recentIds: recentGhostIds,+ unreadAtById,+ }),+ [searchedInstalledItems, recentGhostIds, unreadAtById],+ );+ // 未读通知永不折叠:可见窗口至少 MAX_VISIBLE_INSTALLED_PLUGINS 个,并容纳全部+ // 未读——未读已排在最前,按未读数量扩窗即可保证它们都落在可见区(更新可被折叠)。+ const visibleInstalledCount = useMemo(+ () => installedVisibleCount(displayInstalledItems, unreadAtById, MAX_VISIBLE_INSTALLED_PLUGINS),+ [displayInstalledItems, unreadAtById],+ );const primaryInstalledItems = useMemo(- () => visibleInstalledPluginItems(displayInstalledItems),- [displayInstalledItems],+ () => displayInstalledItems.slice(0, visibleInstalledCount),+ [displayInstalledItems, visibleInstalledCount],);const additionalInstalledItems = useMemo(- () => displayInstalledItems.slice(MAX_VISIBLE_INSTALLED_PLUGINS),- [displayInstalledItems],- );- const hiddenInstalledCount = Math.max(- 0,- displayInstalledItems.length - MAX_VISIBLE_INSTALLED_PLUGINS,+ () => displayInstalledItems.slice(visibleInstalledCount),+ [displayInstalledItems, visibleInstalledCount],);+ const hiddenInstalledCount = Math.max(0, displayInstalledItems.length - visibleInstalledCount);// ── 更新横幅与批量更新(设计定稿:全部更新;扩权单独确认,绝不静默放行)──const updatableInstalledItems = useMemo(diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex f82848b1f0..479f1c12b0 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -44,10 +44,6 @@ const {InstalledPluginOverflow,MAX_COLLAPSED_INSTALLED_PLUGIN_PREVIEWS,MAX_VISIBLE_INSTALLED_PLUGINS,- initializeInstalledPluginOrderSnapshot,- reconcileInstalledPluginOrderSnapshot,- shouldInitializeInstalledPluginOrderSnapshot,- surfaceNewlyUpdatableInstalledPlugins,visibleInstalledPluginItems,} = __installedPluginLayoutForTests;@@ -448,83 +444,6 @@ describe('MarketPluginCard', () => {});describe('installed Plugin disclosure', () => {- it('surfaces newly installed plugins before the collapsed grid cutoff', () => {- const previousIds = Array.from(- { length: MAX_VISIBLE_INSTALLED_PLUGINS },- (_, index) => `plugin-${index}`,- );-- expect(- reconcileInstalledPluginOrderSnapshot(previousIds, previousIds, [- ...previousIds,- 'new-plugin',- ]),- ).toEqual(['new-plugin', ...previousIds]);- });-- it('seeds installs that arrive before the first market snapshot', () => {- const preSnapshotIds = Array.from(- { length: MAX_VISIBLE_INSTALLED_PLUGINS },- (_, index) => `plugin-${index}`,- );- const marketSortedIds = [...preSnapshotIds].reverse();-- expect(- initializeInstalledPluginOrderSnapshot(marketSortedIds, preSnapshotIds, [- ...preSnapshotIds,- 'new-plugin',- ]),- ).toEqual(['new-plugin', ...marketSortedIds]);- });-- it('upgrades a provisional installed order once market data recovers', () => {- const unavailableMarketSnapshot = {- items: [],- unavailableReason: 'authentication-required',- customSourceNames: [],- };- const availableMarketSnapshot = {- items: [],- unavailableReason: null,- customSourceNames: [],- };-- expect(- shouldInitializeInstalledPluginOrderSnapshot(false, false, unavailableMarketSnapshot),- ).toBe(true);- expect(- shouldInitializeInstalledPluginOrderSnapshot(true, false, unavailableMarketSnapshot),- ).toBe(false);- expect(shouldInitializeInstalledPluginOrderSnapshot(true, false, availableMarketSnapshot)).toBe(- true,- );- expect(shouldInitializeInstalledPluginOrderSnapshot(true, true, availableMarketSnapshot)).toBe(- false,- );- });-- it('surfaces newly update-available plugins only when they were hidden by the cutoff', () => {- const orderSnapshot = Array.from(- { length: MAX_VISIBLE_INSTALLED_PLUGINS + 3 },- (_, index) => `plugin-${index}`,- );-- expect(surfaceNewlyUpdatableInstalledPlugins(orderSnapshot, [], ['plugin-6'])).toBe(- orderSnapshot,- );- expect(- surfaceNewlyUpdatableInstalledPlugins(- orderSnapshot,- ['plugin-1'],- ['plugin-1', 'plugin-6', 'plugin-9', 'plugin-10'],- ),- ).toEqual([- 'plugin-9',- 'plugin-10',- ...orderSnapshot.filter((id) => id !== 'plugin-9' && id !== 'plugin-10'),- ]);- });-it('shows at most eight installed plugins until the user expands the section', () => {const items = Array.from({ length: MAX_VISIBLE_INSTALLED_PLUGINS + 3 }, (_, index) => index);diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex fb3713e31b..142590423d 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -172,6 +172,62 @@ export function sortGhostPluginItemsByRecentUse<T extends Pick<GhostPluginListIt.map(({ item }) => item);}+/**+ * Ranks the installed shortcut row for display. Three lexicographic tiers:+ * 1. Plugins with an unread notification (notify.badge) first, newest badge (larger `at`) on top.+ * A pushed notification has no other entry point, so surfacing it is the whole point.+ * 2. Then recently used (host-recorded MRU), newest first.+ * 3. Then base install order, stably.+ * `marketUpdate` is deliberately NOT a key: the updates banner already surfaces updatable plugins,+ * so letting them jump the row would only bury the unread signal.+ * Pure and reactive — recompute freely from current signals; there is no frozen snapshot to go stale.+ */+export function sortInstalledForDisplay<T extends Pick<GhostPluginListItem, 'id'>>(+ items: readonly T[],+ {+ recentIds,+ unreadAtById,+ }: { recentIds: readonly string[]; unreadAtById: ReadonlyMap<string, number> },+): T[] {+ const recentIndex = new Map(recentIds.map((id, index) => [id, index]));+ return items+ .map((item, stableIndex) => ({ item, stableIndex }))+ .sort((a, b) => {+ // Tier 1 — unread notifications, newest badge first.+ const aAt = unreadAtById.get(a.item.id);+ const bAt = unreadAtById.get(b.item.id);+ if ((aAt !== undefined) !== (bAt !== undefined)) return aAt !== undefined ? -1 : 1;+ if (aAt !== undefined && bAt !== undefined && aAt !== bAt) return bAt - aAt;+ // Tier 2 — recently used, newest first.+ const aRecent = recentIndex.get(a.item.id);+ const bRecent = recentIndex.get(b.item.id);+ if (aRecent !== undefined || bRecent !== undefined) {+ if (aRecent === undefined) return 1;+ if (bRecent === undefined) return -1;+ if (aRecent !== bRecent) return aRecent - bRecent;+ }+ // Tier 3 — base install order, stable.+ return a.stableIndex - b.stableIndex;+ })+ .map(({ item }) => item);+}++/**+ * Size of the always-visible installed window: at least `cap`, expanded to also cover every+ * plugin carrying an unread notification. Because `sortInstalledForDisplay` ranks unread items+ * first, taking this many from the front guarantees no unread plugin is ever folded away — even+ * when the user has many plugins. Updatable-but-read plugins can still fold (the banner surfaces+ * updates).+ */+export function installedVisibleCount<T extends Pick<GhostPluginListItem, 'id'>>(+ items: readonly T[],+ unreadAtById: ReadonlyMap<string, number>,+ cap: number,+): number {+ const unreadCount = items.reduce((count, item) => count + (unreadAtById.has(item.id) ? 1 : 0), 0);+ return Math.max(cap, unreadCount);+}+/*** 将安装清单转换成列表卡片需要的最小字段。*