Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(mobile): 缩小任务抽屉流式消息更新范围 (#3936)
Dashb4209159fbb5
diff --git a/apps/mobile/src/__tests__/sessionListDrawer.test.ts b/apps/mobile/src/__tests__/sessionListDrawer.test.tsindex bfc5704d58..ce2adb9a7c 100644--- a/apps/mobile/src/__tests__/sessionListDrawer.test.ts+++ b/apps/mobile/src/__tests__/sessionListDrawer.test.ts@@ -7,7 +7,7 @@ const readTextLf = (...args: Parameters<typeof readFileSync>): string =>/*** 宽屏任务列表抽屉的设计与行为门(与 sessionHeaderDesktopFirst 同款源码字符串门):- * 本仓 mobile 测试体系是纯函数 + 源码门,没有组件渲染设施,关键交互约定用字符串锁住。+ * 此处锁住视觉与手势约定;订阅更新另由 sessionListDrawerUpdates.test.tsx 验证。*/describe('mobile session list drawer', () => {const source = () =>@@ -61,7 +61,8 @@ describe('mobile session list drawer', () => {// 关闭动画期间 overlay 恒拦截,不放行点击穿透半透明 scrim(review #1328)。expect(text).toContain('pointerEvents="auto"');// 抽屉 presentation 必须带权威设备身份,防 canonicalDeviceId 被弱推断覆盖(review #1328)。- expect(text).toContain('devices: remoteSessionStore.getDeviceIdentity(),');+ expect(text).toContain('const devices = useRemoteDeviceIdentity();');+ expect(text).toMatch(/buildMobileHomePresentation\(\{(?:(?!\}\);)[\s\S])*?\n\s*devices,/);// 行内状态与标题兜底与首页同口径:pending/liveActivity 索引 + 已解析 unnamedLabel(review #1328)。expect(text).toContain('remoteSessionStore.getPendingInteractions(session.id).length');expect(text).toContain('remoteSessionStore.getSessionLiveActivity(session.id)');@@ -77,11 +78,11 @@ describe('mobile session list drawer', () => {expect(text).toContain('buildMobileHomePresentation({');expect(text).toContain('buildHomeSections(home, false, false)');expect(text).toContain('resolveMobileSessionRightStatus({');- expect(text).toContain('buildRemoteSessionCardPreview(item, { running })');+ expect(text).toMatch(/buildRemoteSessionCardPreview\((?:(?!\);)[\s\S])*?\{ running \},?\s*\)/);expect(text).toContain('formatRemoteSessionSidebarTime(lastActivityAt)');expect(text).toContain('conversationSearchOriginsFromDeviceModels');- expect(text).toContain('remoteSessionStore.getConversationSearchDeviceModels()');- expect(text).toContain('remoteSessionStore.getDeviceIdentity()');+ expect(text).toContain('useRemoteConversationSearchDeviceModels()');+ expect(text).toContain('useRemoteDeviceIdentity()');});it('exposes stable testIDs and modal accessibility semantics', () => {diff --git a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsxnew file mode 100644index 0000000000..e2925db816--- /dev/null+++ b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx@@ -0,0 +1,496 @@+// @vitest-environment jsdom+import { act, type ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SESSION_ACTIVITY_CHANNEL } from "@cindy/device-link";+import { SessionListDrawer } from "@/session/SessionListDrawer";+import { remoteSessionStore } from "@/session/remoteSessionStore";+import { buildMobileHomePresentation } from "@/session/mobileHome";+import { buildRemoteSessionCardPreview } from "@/session/sessionList";+import { i18n } from "@/i18n";+import type { HomeRow, HomeSection } from "@/session/homeSections";+import type { RemoteMessage, RemoteSession } from "@/session/types";++// Keep React, the store, search hook and presentation real. Only native views/gestures are+// replaced: assertions observe committed rows and count actual presentation executions.+const native = vi.hoisted(() => ({+ sections: [] as HomeSection[],+ search: { query: "", onChangeQuery: (_value: string) => {} },+ invoke: vi.fn(),+}));++vi.mock("react-native", async () => {+ const { createElement } = await import("react");+ type Props = {+ children?: ReactNode;+ testID?: string;+ onPress?: () => void;+ accessibilityState?: { selected?: boolean };+ ref?: import("react").Ref<HTMLDivElement>;+ };+ const View = ({+ children,+ testID,+ onPress,+ accessibilityState,+ ref,+ }: Props) =>+ createElement(+ "div",+ {+ "data-testid": testID,+ onClick: onPress,+ "aria-selected": accessibilityState?.selected,+ ref,+ },+ children,+ );+ return {+ View,+ Pressable: View,+ SectionList: ({+ sections,+ renderItem,+ }: {+ sections: HomeSection[];+ renderItem: (info: { item: HomeRow }) => ReactNode;+ }) => {+ native.sections = sections;+ return createElement(+ "div",+ {},+ sections.flatMap((section) =>+ section.data.map((item) =>+ createElement("div", { key: item.key }, renderItem({ item })),+ ),+ ),+ );+ },+ AccessibilityInfo: { setAccessibilityFocus: vi.fn() },+ BackHandler: { addEventListener: () => ({ remove() {} }) },+ findNodeHandle: () => null,+ StyleSheet: {+ create: (value: unknown) => value,+ hairlineWidth: 1,+ absoluteFill: {},+ },+ Platform: {+ OS: "ios",+ select: (values: Record<string, unknown>) => values.ios ?? values.default,+ },+ };+});+vi.mock("react-native-reanimated", async () => {+ const { useRef } = await import("react");+ const { View } = await import("react-native");+ return {+ default: { View },+ useSharedValue: (value: number) => useRef({ value }).current,+ useAnimatedStyle: () => ({}),+ Easing: { bezier: () => undefined },+ cancelAnimation() {},+ runOnJS: (fn: unknown) => fn,+ withRepeat: (value: number) => value,+ withTiming: (value: number) => value,+ };+});+vi.mock("@/platform/gestureHandler", () => ({+ GestureDetector: ({ children }: { children: ReactNode }) => children,+ Gesture: {+ Pan: () => {+ const chain = {+ activeOffsetX: () => chain,+ failOffsetX: () => chain,+ failOffsetY: () => chain,+ onUpdate: () => chain,+ onEnd: () => chain,+ };+ return chain;+ },+ },+}));+vi.mock("lucide-react-native", () => ({+ House: () => null,+ LoaderCircle: () => null,+ SquarePen: () => null,+}));+vi.mock("react-native-safe-area-context", () => ({+ useSafeAreaInsets: () => ({ left: 0, top: 0, bottom: 0 }),+}));+vi.mock("@/components/AppText", async () => ({+ Text: (await import("react-native")).View,+}));+vi.mock("@/theme", () => ({+ useThemedStyles: () => ({}),+ useTheme: () => ({ colors: {} }),+}));+vi.mock("@/hooks/useReduceMotion", () => ({+ useReduceMotionEnabled: () => true,+}));+vi.mock("@/session/HomeSearchBar", () => ({+ HomeSearchBar: (props: typeof native.search) => {+ native.search = props;+ return null;+ },+}));+vi.mock("@/session/ConversationSearchFilterSheet", () => ({+ ConversationSearchFilterSheet: () => null,+}));+vi.mock("@/device-link/DeviceLinkContext", () => ({+ useDeviceLink: () => ({ invoke: native.invoke }),+}));+vi.mock("@/session/mobileHome", async (importOriginal) => {+ const original =+ await importOriginal<typeof import("@/session/mobileHome")>();+ return {+ ...original,+ buildMobileHomePresentation: vi.fn(original.buildMobileHomePresentation),+ };+});+vi.mock("@/session/sessionList", async (importOriginal) => {+ const original =+ await importOriginal<typeof import("@/session/sessionList")>();+ return {+ ...original,+ buildRemoteSessionCardPreview: vi.fn(+ original.buildRemoteSessionCardPreview,+ ),+ };+});++function session(+ id: string,+ patch: Partial<RemoteSession> = {},+): RemoteSession {+ return {+ id,+ userId: "user",+ title: id,+ workingDir: "/repo",+ workspaceKind: "project",+ model: "claude",+ effort: "medium",+ permissionMode: "default",+ fastMode: false,+ status: "active",+ agentKind: "cc",+ userSendAt: null,+ createdAt: "2026-09-01T00:00:00.000Z",+ updatedAt: "2026-09-01T00:00:00.000Z",+ ...patch,+ };+}++function message(sessionId: string, content: string): RemoteMessage {+ return {+ id: `m-${sessionId}`,+ clientId: `m-${sessionId}`,+ sessionId,+ role: "assistant",+ content,+ toolUseId: null,+ agentMeta: null,+ createdAt: "2026-09-01T00:00:01.000Z",+ };+}++function delta(sessionId: string, text: string) {+ remoteSessionStore.applyRemotePush("dev-1", "maker:event", {+ sessionId,+ persistId: `live-${sessionId}`,+ event: { type: "text", data: { text, isFinal: false } },+ });+}++describe("drawer selective updates", () => {+ let root: Root;+ let container: HTMLDivElement;+ const onSelect = vi.fn();+ const onClosed = vi.fn();+ const props = {+ currentSessionId: "s1",+ onClose() {},+ onClosed,+ onGoHome() {},+ onNewSession() {},+ onSelectSession: onSelect,+ open: true,+ width: 360,+ };+ const render = async (open = true) => {+ await act(async () =>+ root.render(<SessionListDrawer {...props} open={open} />),+ );+ };+ const row = (id: string) =>+ container.querySelector(`[data-testid="sessionDrawer.row.${id}"]`);+ const status = (id: string, value: string) =>+ container.querySelector(+ `[data-testid="sessionDrawer.rowStatus.${value}.${id}"]`,+ );+ const tick = async (ms: number) => {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+ };++ beforeEach(async () => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ vi.useFakeTimers();+ remoteSessionStore.clear();+ native.invoke+ .mockReset()+ .mockResolvedValue({+ query: "needle",+ results: [],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ });+ onSelect.mockClear();+ onClosed.mockClear();+ await i18n.changeLanguage("zh-CN");+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ remoteSessionStore.setDeviceIdentity([+ { deviceId: "dev-1", name: "Studio" },+ ]);+ remoteSessionStore.setConversationSearchDeviceModels([+ { deviceId: "dev-1", name: "Studio", canOpen: true, state: "ready" },+ ]);+ remoteSessionStore.setDeviceSessions("dev-1", "Studio", [+ session("s1"),+ session("s2"),+ ]);+ });++ afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ remoteSessionStore.clear();+ vi.clearAllTimers();+ vi.useRealTimers();+ });++ it("updates only the changed preview without rebuilding sections, including a parent rerender", async () => {+ remoteSessionStore.setDeviceSessions(+ "dev-1",+ "Studio",+ Array.from({ length: 40 }, (_, i) => session(`s${i + 1}`)),+ );+ remoteSessionStore.setMessages("s2", [message("s2", "unchanged preview")]);+ await render();+ const sections = native.sections;+ vi.mocked(buildMobileHomePresentation).mockClear();+ vi.mocked(buildRemoteSessionCardPreview).mockClear();+ await act(async () => delta("s1", "first"));+ await tick(100);+ await act(async () => delta("s1", " second"));+ await tick(100);+ for (let index = 0; index < 98; index += 1) {+ await act(async () => delta("s1", "."));+ await tick(100);+ }+ expect(row("s1")?.textContent).toContain("first second");+ expect(row("s2")?.textContent).toContain("unchanged preview");+ expect(native.sections).toBe(sections);+ expect(buildMobileHomePresentation).not.toHaveBeenCalled();+ expect(buildRemoteSessionCardPreview).toHaveBeenCalled();+ expect(+ vi+ .mocked(buildRemoteSessionCardPreview)+ .mock.calls.every(([item]) => item.session.id === "s1"),+ ).toBe(true);+ await render(); // The surrounding session screen itself still renders while streaming.+ expect(buildMobileHomePresentation).not.toHaveBeenCalled();+ expect(native.sections).toBe(sections);+ });++ it("falls back to the host preview when loaded messages are cleared", async () => {+ remoteSessionStore.setDeviceSessions("dev-1", "Studio", [+ session("s1", { preview: "host preview" }),+ session("s2"),+ ]);+ await render();+ expect(row("s1")?.textContent).toContain("host preview");+ await act(async () =>+ remoteSessionStore.setMessages("s1", [message("s1", "loaded preview")]),+ );+ expect(row("s1")?.textContent).toContain("loaded preview");+ await act(async () => remoteSessionStore.setMessages("s1", []));+ expect(row("s1")?.textContent).toContain("host preview");+ expect(row("s1")?.textContent).not.toContain("loaded preview");+ });++ it("keeps pending, running, error and completed indicators current", async () => {+ await render();+ await act(async () => remoteSessionStore.setSessionRunning("s1", true));+ expect(status("s1", "running")).not.toBeNull();+ await act(async () =>+ remoteSessionStore.setPendingInteractions("s1", [+ { request: { kind: "permission", requestId: "p1" } },+ ]),+ );+ expect(status("s1", "awaiting")).not.toBeNull();+ await act(async () => remoteSessionStore.setPendingInteractions("s1", []));+ expect(status("s1", "running")).not.toBeNull();+ for (const [phase, rightStatus] of [+ ["error", "error"],+ ["completed", "done"],+ ] as const) {+ await act(async () =>+ remoteSessionStore.applyRemotePush("dev-1", SESSION_ACTIVITY_CHANNEL, {+ sessionId: "s1",+ phase,+ compactDetail: phase,+ attention: true,+ }),+ );+ expect(status("s1", rightStatus)).not.toBeNull();+ }+ });++ it("changes an automation group primary and its click target when an older run needs attention", async () => {+ remoteSessionStore.setDeviceSessions("dev-1", "Studio", [+ session("old", { source: "scheduler", title: "daily" }),+ session("new", {+ source: "scheduler",+ title: "daily",+ updatedAt: "2026-09-02T00:00:00.000Z",+ }),+ ]);+ // Schedule histories are intentionally retained only while their detail is in use.+ remoteSessionStore.enterSessionMessageDetail("old");+ remoteSessionStore.enterSessionMessageDetail("new");+ remoteSessionStore.setMessages("old", [message("old", "older run")]);+ remoteSessionStore.setMessages("new", [message("new", "newer run")]);+ await render();+ expect(row("new")?.textContent).toContain("newer run");+ await act(async () =>+ remoteSessionStore.setPendingInteractions("old", [+ { request: { kind: "ask_user_question", requestId: "question" } },+ ]),+ );+ expect(row("new")).toBeNull();+ expect(status("old", "awaiting")).not.toBeNull();+ await act(async () => (row("old") as HTMLElement).click());+ expect(onSelect.mock.calls.at(-1)?.[0].session.id).toBe("old");+ await act(async () => remoteSessionStore.setPendingInteractions("old", []));+ expect(row("new")?.textContent).toContain("newer run");+ });++ it("refreshes device search reachability without a session-array change", async () => {+ remoteSessionStore.setConversationSearchDeviceModels([+ { deviceId: "dev-1", name: "Studio", canOpen: false, state: "offline" },+ ]);+ await render();+ await act(async () => native.search.onChangeQuery("needle"));+ await tick(300);+ expect(native.invoke).not.toHaveBeenCalled();+ const sessions = remoteSessionStore.getSessions();+ await act(async () =>+ remoteSessionStore.setConversationSearchDeviceModels([+ { deviceId: "dev-1", name: "Studio", canOpen: true, state: "ready" },+ ]),+ );+ expect(remoteSessionStore.getSessions()).toBe(sessions);+ await tick(300);+ expect(native.invoke).toHaveBeenCalledTimes(1);+ expect(native.invoke.mock.calls[0].slice(0, 2)).toEqual([+ "dev-1",+ "local-db:conversations:search",+ ]);+ });++ it("refreshes device identity even when no session changes, with a stable empty snapshot", async () => {+ remoteSessionStore.clear();+ expect(remoteSessionStore.getDeviceIdentity()).toBe(+ remoteSessionStore.getDeviceIdentity(),+ );+ await render();+ const sessions = remoteSessionStore.getSessions();+ vi.mocked(buildMobileHomePresentation).mockClear();+ await act(async () =>+ remoteSessionStore.setDeviceIdentity([+ { deviceId: "empty-device", name: "Renamed" },+ ]),+ );+ expect(remoteSessionStore.getSessions()).toBe(sessions);+ expect(+ vi.mocked(buildMobileHomePresentation).mock.calls.at(-1)?.[0].devices,+ ).toEqual([{ deviceId: "empty-device", name: "Renamed" }]);+ });++ it("matches loaded text during search debounce without restarting the indexed request on each delta", async () => {+ await render();+ await act(async () => native.search.onChangeQuery("needle"));+ expect(row("s1")).toBeNull();+ await tick(100);+ await act(async () => delta("s1", "needle"));+ await tick(100);+ expect(row("s1")?.textContent).toContain("needle");+ await act(async () => delta("s1", " more"));+ await tick(100);+ expect(native.invoke).toHaveBeenCalledTimes(1);+ await tick(300);+ expect(native.invoke).toHaveBeenCalledTimes(1);+ });++ it("preserves indexed hit snippets and message focus while newer loaded messages arrive", async () => {+ const contentHit = {+ messageClientId: "hit-message",+ preview: "needle in old message",+ role: "assistant",+ createdAt: "2026-09-01T00:00:01.000Z",+ };+ native.invoke.mockResolvedValue({+ query: "needle",+ results: [+ {+ session: session("s1"),+ matchKind: "content",+ titleMatchIndices: [],+ titleScore: 0,+ contentHit,+ contentHits: [contentHit],+ rankScore: 10,+ },+ ],+ vectorUsed: false,+ vectorSkipReason: null,+ poolCapped: false,+ });+ remoteSessionStore.setMessages("s1", [+ message("s1", "latest unrelated message"),+ ]);+ await render();+ await act(async () => native.search.onChangeQuery("needle"));+ await tick(300);+ expect(row("s1")?.textContent).toContain("needle in old message");+ await act(async () =>+ remoteSessionStore.setMessages("s1", [+ message("s1", "even newer unrelated message"),+ ]),+ );+ expect(row("s1")?.textContent).toContain("needle in old message");+ await act(async () => (row("s1") as HTMLElement).click());+ expect(onSelect.mock.calls.at(-1)?.[0].searchFocusClientId).toBe(+ "hit-message",+ );+ });++ it("reads current previews when reopened and keeps the active selection and close callback", async () => {+ await render();+ await render(false);+ expect(onClosed).toHaveBeenCalledTimes(1);+ vi.mocked(buildMobileHomePresentation).mockClear();+ await act(async () => delta("s1", "received while closed"));+ await tick(100);+ expect(row("s1")).toBeNull();+ expect(buildMobileHomePresentation).not.toHaveBeenCalled();+ await render();+ expect(row("s1")?.textContent).toContain("received while closed");+ expect(row("s1")?.getAttribute("aria-selected")).toBe("true");+ });+});diff --git a/apps/mobile/src/session/SessionListDrawer.tsx b/apps/mobile/src/session/SessionListDrawer.tsxindex 18433b5063..2326677b92 100644--- a/apps/mobile/src/session/SessionListDrawer.tsx+++ b/apps/mobile/src/session/SessionListDrawer.tsx@@ -56,9 +56,12 @@ import { buildHomeSections, type HomeRow, type HomeSection } from '@/session/homimport { buildMobileHomePresentation, excludeOrcaWorkerSessions } from '@/session/mobileHome';import {remoteSessionStore,+ useRemoteConversationSearchDeviceModels,+ useRemoteDeviceIdentity,+ useRemoteHomeStatusVersion,useRemoteMessageVersion,+ useRemoteSessionMessagePreview,useRemoteSessions,- useRemoteSessionStoreVersion,useSessionRunning,} from '@/session/remoteSessionStore';import type { RemoteSessionLiveActivity } from '@/session/sessionList';@@ -248,22 +251,20 @@ export function SessionListDrawer({// 与首页同一套展示模型(排序 / 置顶区 / 自动化折叠);未挂载时跳过重建,// 常驻宽屏页面时不为收起的抽屉付 presentation 成本。const sessions = useRemoteSessions();- // storeVersion / messageVersion:pending 交互、liveActivity、消息镜像都不在 sessions- // 数组身份里,靠版本号驱动重算(与首页三个 index 的依赖口径一致);未挂载时 memo- // 早退,不为收起的抽屉付这份成本。- const storeVersion = useRemoteSessionStoreVersion();- const messageVersion = useRemoteMessageVersion();+ // pending/live/running 才重建分组;普通消息预览由可见行按 session 订阅。+ const homeStatusVersion = useRemoteHomeStatusVersion();+ // 设备身份和搜索可达性可单独变化,不能依赖 sessions 数组顺便触发刷新。+ const devices = useRemoteDeviceIdentity();+ const searchDeviceModels = useRemoteConversationSearchDeviceModels() as readonly ConversationSearchDeviceModel[];const unresponsiveDevices = useUnresponsiveDevices();const searchOrigins = useMemo(() => {- const models = remoteSessionStore.getConversationSearchDeviceModels() as ConversationSearchDeviceModel[];- if (models.length > 0) {- return conversationSearchOriginsFromDeviceModels(models, {+ if (searchDeviceModels.length > 0) {+ return conversationSearchOriginsFromDeviceModels(searchDeviceModels, {unresponsiveDeviceIds: unresponsiveDevices,});}- const identities = remoteSessionStore.getDeviceIdentity();- if (identities.length > 0) {- return identities.map((device) => ({+ if (devices.length > 0) {+ return devices.map((device) => ({deviceId: device.deviceId,deviceName: device.name,reachable: false,@@ -280,7 +281,7 @@ export function SessionListDrawer({});}return [...byId.values()];- }, [sessions, storeVersion, unresponsiveDevices]);+ }, [devices, searchDeviceModels, sessions, unresponsiveDevices]);const searchProjects = useMemo(() => listConversationSearchProjects(excludeOrcaWorkerSessions(sessions)),[sessions],@@ -291,6 +292,8 @@ export function SessionListDrawer({projects: searchProjects,});const searchQuery = indexedSearch.query;+ // 索引搜索就绪前的本地搜索仍须匹配已加载消息;普通列表不订阅全局消息版本。+ const messageSearchVersion = useRemoteMessageVersion(mounted && searchQuery.trim().length > 0);const [searchFilterOpen, setSearchFilterOpen] = useState(false);const searchFilterA11y = t('devices.list.search.filterAria', {agent: t(`devices.list.search.filter.agent.${indexedSearch.agentFilter}`),@@ -303,15 +306,26 @@ export function SessionListDrawer({});const sections = useMemo<HomeSection[]>(() => {if (!mounted) return [];- void storeVersion;- void messageVersion;- // 已 load 会话的预览走消息镜像(applyRemotePush 只追加镜像、不回写 session.preview,- // 缺这个索引会让「坐在会话页期间别的任务来了新消息」的摘要停在旧值);未打开过的- // 会话由 presentation 内部回退 session.preview,与首页同一套兜底链。- const messagePreviewIndex = buildSessionMessagePreviewIndex(- sessions.map((session) => session.id),- (sessionId) => remoteSessionStore.getMessages(sessionId),- );+ if (shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status)) {+ return [{+ data: indexedSearch.results.map((item) => ({+ item,+ key: `search:${(item.session as { deviceLinkDeviceId?: string | null }).deviceLinkDeviceId ?? 'local'}:${item.session.id}`,+ kind: 'session' as const,+ source: 'search' as const,+ })),+ key: 'search',+ title: null,+ }];+ }+ void homeStatusVersion;+ void messageSearchVersion;+ const messagePreviewIndex = searchQuery.trim()+ ? buildSessionMessagePreviewIndex(+ sessions.map((session) => session.id),+ (sessionId) => remoteSessionStore.getMessages(sessionId),+ )+ : undefined;// 与首页同口径的行内状态输入:等待授权/回复(awaiting)与 live error/done 都来自// 这两个 index,缺了会全部退化成普通时间行。const pendingInteractionIndex = new Map(@@ -328,9 +342,8 @@ export function SessionListDrawer({searchQuery,// 权威设备身份必须随会话一起进 presentation:canonicalizeSessionDevice 会按传入// devices 重算并覆盖 canonicalDeviceId,空列表会把 store 已认领好的规范 id 打回- // 弱推断(re-link 后点行路由到旧物理设备)。store 身份变化会触发 sessions 重算,- // 本 memo 以 sessions 为依赖即可保持同步。- devices: remoteSessionStore.getDeviceIdentity(),+ // 弱推断(re-link 后点行路由到旧物理设备)。+ devices,liveActivityIndex: new Map(liveActivityEntries),messagePreviewIndex,pendingInteractionIndex,@@ -345,20 +358,8 @@ export function SessionListDrawer({// 已解析的 i18n 文案传给共享层(共享层不出中文串;en/ja/ko 不再回退「未命名任务」)。unnamedLabel: t('session.menu.unnamedTitle'),});- if (shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status)) {- return [{- data: indexedSearch.results.map((item) => ({- item,- key: `search:${(item.session as { deviceLinkDeviceId?: string | null }).deviceLinkDeviceId ?? 'local'}:${item.session.id}`,- kind: 'session' as const,- source: 'search' as const,- })),- key: 'search',- title: null,- }];- }return buildHomeSections(home, false, false);- }, [indexedSearch.results, indexedSearch.status, messageVersion, mounted, searchQuery, sessions, storeVersion, t]);+ }, [devices, homeStatusVersion, indexedSearch.results, indexedSearch.status, messageSearchVersion, mounted, searchQuery, sessions, t]);const hasRows = useMemo(() => sections.some((section) => section.data.length > 0),[sections],@@ -375,6 +376,7 @@ export function SessionListDrawer({active={active}item={item.item}onSelect={onSelectSession}+ searchResult={item.source === 'search'}/>);},@@ -514,16 +516,19 @@ const DrawerSessionRow = memo(function DrawerSessionRow({active,item,onSelect,+ searchResult,}: {active: boolean;item: RemoteSessionListItem;onSelect(item: RemoteSessionListItem): void;+ searchResult: boolean;}) {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();const { t } = useTranslation();// 运行态走订阅(行 memo 化后命令式读取会 stale,与首页行同一取舍)。const sessionIsRunning = useSessionRunning(item.session.id);+ const loadedMessagePreview = useRemoteSessionMessagePreview(item.session.id);const running = sessionIsRunning || !!item.scheduleInfo?.running;const rightStatus = resolveMobileSessionRightStatus({liveAttention: item.liveActivity?.attention === true,@@ -532,7 +537,13 @@ const DrawerSessionRow = memo(function DrawerSessionRow({running,scheduleUnreadCount: item.scheduleInfo?.unreadCount ?? 0,});- const preview = buildRemoteSessionCardPreview(item, { running });+ // 索引搜索展示命中摘要;普通行(含自动化代表行)才使用自己的最新消息预览。+ const preview = buildRemoteSessionCardPreview(+ searchResult || loadedMessagePreview === undefined || loadedMessagePreview === item.messagePreview+ ? item+ : { ...item, messagePreview: loadedMessagePreview },+ { running },+ );return (<PressableaccessibilityLabel={t('devices.list.a11y.openConversation', { title: item.title })}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 63fbf10850..a1815b2d54 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1310,6 +1310,7 @@ function userMessageCanConsumePendingLiveReply(// 当前权威设备列表(由首页从设备列表 API reconcile 后注入)。每次重算会话时基于它 + 当前 shards(stale 侧)// 重建身份索引,用于给会话算展示用 canonicalDeviceId(把 re-link 后残留 stale shard 认领回当前设备);// 为 null 时不归一,安全退化。+const EMPTY_DEVICE_IDENTITY: readonly { deviceId: string; name: string }[] = [];let deviceList: readonly { deviceId: string; name: string }[] | null = null;let conversationSearchDeviceModels: readonly {canOpen: boolean;@@ -2925,7 +2926,7 @@ export const remoteSessionStore = {* store 已算好的规范 id 覆盖成仅凭会话内嵌名字推出的弱结果(re-link 后路由错设备)。*/getDeviceIdentity(): readonly { deviceId: string; name: string }[] {- return deviceList ?? [];+ return deviceList ?? EMPTY_DEVICE_IDENTITY;},getConversationSearchDeviceModels(): readonly {@@ -5494,6 +5495,19 @@ export function useRemoteSessions(): RemoteSession[] {return usePausableRemoteSessionStoreSnapshot('sessions', remoteSessionStore.getSessions);}+/** Device identity can change without changing any session's reconciled reference. */+export function useRemoteDeviceIdentity() {+ return usePausableRemoteSessionStoreSnapshot('device-identity', remoteSessionStore.getDeviceIdentity);+}++/** Search reachability changes independently of message and home-status updates. */+export function useRemoteConversationSearchDeviceModels() {+ return usePausableRemoteSessionStoreSnapshot(+ 'conversation-search-devices',+ remoteSessionStore.getConversationSearchDeviceModels,+ );+}+/** Subscribe to one session's message mirror without triggering cache hydration side effects. */export function useRemoteSessionMessages(sessionId: string): RemoteMessage[] {return useSyncExternalStore(