🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(device): move branch lists, linked-PR refresh and port tunnels onto @lobechat/replica (#21299)
Arvin Xu5586cb65114e
diff --git a/apps/server/src/routers/lambda/__tests__/deviceGitBranches.test.ts b/apps/server/src/routers/lambda/__tests__/deviceGitBranches.test.tsnew file mode 100644index 00000000000..fa29650163f--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/deviceGitBranches.test.ts@@ -0,0 +1,62 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { deviceRouter } from '../device';++const mocks = vi.hoisted(() => ({+ listGitBranches: vi.fn(),+ listGitRemoteBranches: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));+vi.mock('@/server/services/deviceGateway', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ deviceGateway: {+ listGitBranches: mocks.listGitBranches,+ listGitRemoteBranches: mocks.listGitRemoteBranches,+ },+}));++/**+ * The branch-list procedures feed replicas that persist what they answer. A+ * device that could not answer must not look like a repository with no+ * branches (`[]`), and the response must stay an array for released clients+ * (no `null`): only a procedure error satisfies both.+ */+describe('device branch-list procedures', () => {+ const caller = deviceRouter.createCaller({ userId: 'user' } as never);+ const input = { deviceId: 'device', path: '/repo' };++ beforeEach(() => vi.clearAllMocks());++ it.each([+ ['listGitBranches', () => caller.listGitBranches(input), mocks.listGitBranches],+ [+ 'listGitRemoteBranches',+ () => caller.listGitRemoteBranches(input),+ mocks.listGitRemoteBranches,+ ],+ ] as const)('%s rejects when the device could not answer', async (_name, call, gateway) => {+ gateway.mockResolvedValue(undefined);++ const error = await call().catch((e: unknown) => e);++ expect(error).toBeInstanceOf(TRPCError);+ expect((error as TRPCError).code).toBe('BAD_GATEWAY');+ });++ it.each([+ ['listGitBranches', () => caller.listGitBranches(input), mocks.listGitBranches],+ [+ 'listGitRemoteBranches',+ () => caller.listGitRemoteBranches(input),+ mocks.listGitRemoteBranches,+ ],+ ] as const)('%s returns an empty answer as an empty array', async (_name, call, gateway) => {+ gateway.mockResolvedValue([]);++ await expect(call()).resolves.toEqual([]);+ });+});diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.tsindex b8cd096ba14..4f6ee8c1c74 100644--- a/apps/server/src/routers/lambda/device/git.ts+++ b/apps/server/src/routers/lambda/device/git.ts@@ -1,4 +1,5 @@import { deriveWorktreePath } from '@lobechat/types';+import { TRPCError } from '@trpc/server';import { z } from 'zod';import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewares/workspaceAuth';@@ -8,6 +9,18 @@ import { deviceGateway } from '@/server/services/deviceGateway';import { assertWorkspaceRootApproved } from '../deviceWorkspaceGuard';import { deviceProcedure } from './procedures';+/**+ * A gateway read that resolved to `undefined` (gateway unconfigured, device+ * offline, RPC failed). Thrown rather than mapped to `[]` or `null`: `[]` is+ * indistinguishable from a real empty list, and released clients expect an+ * array, so only a procedure error keeps both old and new clients correct.+ */+const requireDeviceAnswer = <T>(result: T | undefined, what: string): T => {+ if (result === undefined)+ throw new TRPCError({ code: 'BAD_GATEWAY', message: `The device could not list ${what}.` });+ return result;+};+export const gitRouter = router({/*** Granular git reads for a directory on a remote device, each via its own@@ -156,7 +169,9 @@ export const gitRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,});- return result ?? [];+ // `[]` is a real answer (an unborn repo); a device that could not answer+ // is an error, never an empty list a client could cache over its copy.+ return requireDeviceAnswer(result, 'branches');}),/*** Checkout (or create) a branch in a directory on a remote device, via the@@ -397,7 +412,8 @@ export const gitRouter = router({userId: ctx.userId,workspaceId: ctx.workspaceId,});- return result ?? [];+ // `[]` is a real answer (no `origin`); a device that could not answer is an error.+ return requireDeviceAnswer(result, 'remote branches');}),/*** Repo-relative paths of dirty working-tree files for a directory on a remotediff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 50034190f18..710e109970c 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -3247,6 +3247,7 @@"workingPanel.overview.ports.copy": "Copy link","workingPanel.overview.ports.createFailed": "Could not expose the port","workingPanel.overview.ports.detected.available": "{{count}} to open",+ "workingPanel.overview.ports.detected.checking": "Checking which ports are running…","workingPanel.overview.ports.detected.expose": "Open","workingPanel.overview.ports.detected.heading": "Detected","workingPanel.overview.ports.detected.hideOthers": "Hide other ports",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3841939fc0f..92a40fd0165 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -3247,6 +3247,7 @@"workingPanel.overview.ports.copy": "复制链接","workingPanel.overview.ports.createFailed": "开放端口失败","workingPanel.overview.ports.detected.available": "{{count}} 个可开放",+ "workingPanel.overview.ports.detected.checking": "正在确认端口状态…","workingPanel.overview.ports.detected.expose": "开放","workingPanel.overview.ports.detected.heading": "检测到的端口","workingPanel.overview.ports.detected.hideOthers": "收起其它端口",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 699aa9a9bdc..493b4af8373 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3455,6 +3455,7 @@ export default {'workingPanel.overview.ports.copy': 'Copy link','workingPanel.overview.ports.createFailed': 'Could not expose the port','workingPanel.overview.ports.detected.available': '{{count}} to open',+ 'workingPanel.overview.ports.detected.checking': 'Checking which ports are running…','workingPanel.overview.ports.detected.expose': 'Open','workingPanel.overview.ports.detected.heading': 'Detected','workingPanel.overview.ports.detected.hideOthers': 'Hide other ports',diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsxindex ea957b7f682..c129f4c33d2 100644--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx@@ -42,15 +42,14 @@ import {useState,} from 'react';import { useTranslation } from 'react-i18next';-import useSWR from 'swr';-import { deviceKeys } from '@/libs/swr/keys';import { gitService } from '@/services/git';import { useFetchGitWorkingTreeStatus } from '@/store/device';import { openCreateBranchModal } from './CreateBranchModal';import { gitMenuTriggerStyles } from './gitMenuTriggerStyles';import { openRenameBranchModal } from './RenameBranchModal';+import { useBranchList } from './useBranchList';import { useSwitchWorktree } from './useSwitchWorktree';import { findWorktreeForBranch, getPathName } from './worktreeHelpers';@@ -271,16 +270,15 @@ const BranchSwitcher = memo<BranchSwitcherProps>(const currentRowRef = useRef<HTMLDivElement>(null);const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath, topicId });+ // The persisted list paints the moment the dropdown opens; the read refreshes it.const {- data: branches = [],- isLoading,+ branches,error: branchesError,- mutate: mutateBranches,- } = useSWR(- open ? deviceKeys.gitBranches(deviceId ?? 'local', path) : null,- () => gitService.listGitBranches({ deviceId, path }),- { keepPreviousData: true, revalidateOnFocus: false, shouldRetryOnError: false },- );+ isLoading,+ loadFailed,+ refreshBranches,+ revalidate: mutateBranches,+ } = useBranchList(deviceId, path, open);const { data: workingStatus, mutate: mutateWorkingStatus } = useFetchGitWorkingTreeStatus(deviceId,path,@@ -405,12 +403,13 @@ const BranchSwitcher = memo<BranchSwitcherProps>(// the optimistic label back to the real branch.onAfterCheckout?.();if (result.success) {+ void refreshBranches();onOpenChange(false);return undefined;}return result.error || t('workingDirectory.checkoutFailed');},- [deviceId, onAfterCheckout, onOptimisticCheckout, onOpenChange, path, t],+ [deviceId, onAfterCheckout, onOptimisticCheckout, onOpenChange, path, refreshBranches, t],);const openCreateBranch = useCallback(() => {@@ -420,7 +419,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(// Rename a branch from a modal. Closes the dropdown first (mirrors create),// then reconciles via onAfterCheckout — a renamed current branch updates the- // header label, and the list refetches when the dropdown reopens.+ // header label — and re-reads the list, so its next open paints the new name.const handleRename = useCallback((event: MouseEvent, branch: string) => {event.stopPropagation();@@ -436,12 +435,15 @@ const BranchSwitcher = memo<BranchSwitcherProps>(to: newName,});onAfterCheckout?.();- if (result.success) return undefined;+ if (result.success) {+ void refreshBranches();+ return undefined;+ }return result.error || t('workingDirectory.renameFailed');},});},- [deviceId, onAfterCheckout, onOpenChange, path, t],+ [deviceId, onAfterCheckout, onOpenChange, path, refreshBranches, t],);const handleCopy = useCallback(@@ -471,14 +473,13 @@ const BranchSwitcher = memo<BranchSwitcherProps>(onOk: async () => {const result = await gitService.deleteGitBranch({ branch, deviceId, path });onAfterCheckout?.();- if (!result.success) {- toast.error(result.error || t('workingDirectory.deleteFailed'));- }+ if (result.success) void refreshBranches();+ else toast.error(result.error || t('workingDirectory.deleteFailed'));},title: t('workingDirectory.deleteBranchTitle'),});},- [deviceId, onAfterCheckout, onOpenChange, path, t, tCommon],+ [deviceId, onAfterCheckout, onOpenChange, path, refreshBranches, t, tCommon],);return (@@ -517,7 +518,8 @@ const BranchSwitcher = memo<BranchSwitcherProps>({isLoading && branches.length === 0 ? (<div className={styles.emptyState}>{t('workingDirectory.branchesLoading')}</div>- ) : !isLoading && branchesError ? (+ ) : loadFailed ? (+ // A failed refresh keeps the list it already has on screen.<div className={styles.emptyState}>{t('workingDirectory.branchesLoadFailed')}</div>) : filtered.length === 0 ? (<div className={styles.emptyState}>@@ -530,6 +532,11 @@ const BranchSwitcher = memo<BranchSwitcherProps>(virtualclassName={styles.list}getItemLabel={(_, index) => filtered[index]?.name}+ // The virtual viewport sizes itself on mount: a background+ // refresh that adds branches while the dropdown is open+ // would otherwise leave the extra rows (often the current+ // branch, last) undrawn. Remount when the count changes.+ key={filtered.length}listItemHeight={32}>{filtered.map((branch) => {diff --git a/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.ts b/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.tsnew file mode 100644index 00000000000..0c49d1c192d--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/useBranchList.test.ts@@ -0,0 +1,222 @@+/**+ * @vitest-environment happy-dom+ *+ * The branch switcher's list is a replica: after a reload the dropdown paints+ * the branches persisted last session the moment it opens, and the device read+ * only confirms them. Branch writes land in the replica, so the next open never+ * paints a branch that is gone.+ */+import { randomUUID } from 'node:crypto';++import type { DeviceGitBranchListItem } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { gitService } from '@/services/git';+import { initialGitStatusState, useGitStatusStore } from '@/store/device/gitStatus/store';++import { useBranchList } from '../useBranchList';+import { useWorktreeBranchSeed } from '../useWorktreeBranchSeed';++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal()),+ isDesktop: true,+}));++vi.mock('@/services/git', () => ({+ gitService: { listGitBranches: vi.fn() },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** Never-resolving read: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const branch = (name: string, current = false): DeviceGitBranchListItem => ({ current, name });+const names = (branches: DeviceGitBranchListItem[] | undefined) => branches?.map((b) => b.name);++const DEVICE = 'device-1';+const PATH = '/repo';+/** The persisted row of `deviceId + path`, as the branch-list replica stores it. */+const ROW_KEY = `${DEVICE}\u0000${PATH}`;+const storage = new IndexedDBQueryProjectionStorage<{ value?: DeviceGitBranchListItem[] }>({+ namespace: 'replica:deviceGitBranchList:v1',+});++describe('useBranchList', () => {+ const scopes = new Set<string>();+ let scope = '';+ const switchScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };+ const seed = (branches: DeviceGitBranchListItem[]) =>+ storage.set({ queryKey: ROW_KEY, scope }, { data: { value: branches }, updatedAt: 1 });+ const stored = async () => names((await storage.get({ queryKey: ROW_KEY, scope }))?.data?.value);++ beforeEach(() => {+ switchScope(`branch-user-${randomUUID()}:personal`);+ act(() => useGitStatusStore.setState(initialGitStatusState));+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].map((value) => storage.remove({ queryKey: ROW_KEY, scope: value })),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ // Regression: the list lived only in SWR's memory cache, so every reload+ // opened the dropdown on "Loading branches…" until the device answered.+ it('paints the persisted branches the moment it opens, before the device answers', async () => {+ await seed([branch('main', true), branch('feat/cached')]);+ vi.mocked(gitService.listGitBranches).mockImplementation(pending);++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, true), { wrapper });++ await waitFor(() => expect(names(result.current.branches)).toEqual(['main', 'feat/cached']));+ expect(result.current.isLoading).toBe(false);+ expect(gitService.listGitBranches).toHaveBeenCalledWith({ deviceId: DEVICE, path: PATH });+ });++ it('reads nothing while the dropdown is closed', async () => {+ await seed([branch('main', true)]);++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, false), { wrapper });++ expect(result.current.branches).toEqual([]);+ expect(gitService.listGitBranches).not.toHaveBeenCalled();+ });++ it('replaces the persisted list with the device read and persists it', async () => {+ await seed([branch('main', true), branch('feat/old')]);+ vi.mocked(gitService.listGitBranches).mockResolvedValue([+ branch('main', true),+ branch('feat/new'),+ ]);++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, true), { wrapper });++ await waitFor(() => expect(names(result.current.branches)).toEqual(['main', 'feat/new']));+ await waitFor(async () => expect(await stored()).toEqual(['main', 'feat/new']));+ });++ it('re-reads and persists the list after a branch write, even with the dropdown closed', async () => {+ await seed([branch('main', true), branch('feat/gone')]);+ vi.mocked(gitService.listGitBranches).mockResolvedValue([branch('main', true)]);++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, false), { wrapper });+ // e.g. after `deleteGitBranch` succeeded.+ await act(() => result.current.refreshBranches());++ expect(gitService.listGitBranches).toHaveBeenCalledTimes(1);+ await waitFor(async () => expect(await stored()).toEqual(['main']));+ });++ it('keeps the persisted list when the device cannot answer', async () => {+ await seed([branch('main', true), branch('feat/kept')]);+ // The router rejects (BAD_GATEWAY) when the device could not answer.+ vi.mocked(gitService.listGitBranches).mockRejectedValue(+ new Error('The device could not list branches.'),+ );++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, true), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ // "Couldn't ask" is not "no branches": the list stays, and so does its row.+ expect(names(result.current.branches)).toEqual(['main', 'feat/kept']);+ expect(result.current.loadFailed).toBe(false);+ expect(await stored()).toEqual(['main', 'feat/kept']);+ });++ // Review P2: an unborn repository really has no branches; that answer must+ // settle the switcher instead of reading as a failure Retry can never fix.+ it('accepts an empty list from the device as an answer', async () => {+ await seed([branch('main', true)]);+ vi.mocked(gitService.listGitBranches).mockResolvedValue([]);++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, true), { wrapper });++ await waitFor(() => expect(result.current.branches).toEqual([]));+ expect(result.current.error).toBeUndefined();+ expect(result.current.loadFailed).toBe(false);+ });++ it('reports a failure with nothing to show as a load failure', async () => {+ vi.mocked(gitService.listGitBranches).mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, true), { wrapper });++ await waitFor(() => expect(result.current.loadFailed).toBe(true));+ });++ it('does not paint another identity’s branches', async () => {+ await seed([branch('main', true), branch('theirs')]);+ switchScope(`branch-user-${randomUUID()}:personal`);+ vi.mocked(gitService.listGitBranches).mockImplementation(pending);++ const { result } = renderHook(() => useBranchList(DEVICE, PATH, true), { wrapper });+ await waitFor(() => expect(gitService.listGitBranches).toHaveBeenCalled());++ expect(result.current.branches).toEqual([]);+ expect(result.current.isLoading).toBe(true);+ });++ it('shares one read between the switcher and the worktree name seed', async () => {+ vi.mocked(gitService.listGitBranches).mockResolvedValue([branch('main', true)]);++ const { result } = renderHook(+ () => ({+ list: useBranchList(DEVICE, PATH, true),+ seed: useWorktreeBranchSeed(DEVICE, PATH),+ }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.seed.isReady).toBe(true));+ expect(names(result.current.list.branches)).toEqual(['main']);+ expect(gitService.listGitBranches).toHaveBeenCalledTimes(1);+ });++ it('draws no worktree name from a persisted list the device has not confirmed', async () => {+ // A branch made since last session would be missing from this list, and a+ // name drawn against it could collide (`refs/heads/wt` blocks `wt/…`).+ await seed([branch('main', true)]);+ vi.mocked(gitService.listGitBranches).mockImplementation(pending);++ const { result } = renderHook(+ () => ({+ list: useBranchList(DEVICE, PATH, true),+ seed: useWorktreeBranchSeed(DEVICE, PATH),+ }),+ { wrapper },+ );+ await waitFor(() => expect(names(result.current.list.branches)).toEqual(['main']));++ expect(result.current.seed.isReady).toBe(false);+ expect(result.current.seed.name).toBeUndefined();+ });+});diff --git a/src/features/ChatInput/ControlBar/useBranchList.ts b/src/features/ChatInput/ControlBar/useBranchList.tsnew file mode 100644index 00000000000..316cc8cf676--- /dev/null+++ b/src/features/ChatInput/ControlBar/useBranchList.ts@@ -0,0 +1,39 @@+import type { DeviceGitBranchListItem } from '@lobechat/types';+import { useCallback, useMemo } from 'react';++import { useFetchGitBranches } from '@/store/device';+import { getGitStatusStoreState } from '@/store/device/gitStatus/store';++const EMPTY: DeviceGitBranchListItem[] = [];++/**+ * The branch switcher's list. Read while the dropdown is open; the list+ * persisted last session paints the moment it opens and the device read+ * refreshes it. A failed refresh keeps that list on screen — only a failure+ * with nothing to show reads as "couldn't load".+ */+export const useBranchList = (deviceId: string | undefined, path: string, open: boolean) => {+ const { data, error, isLoading, mutate } = useFetchGitBranches(deviceId, path, open);+ const branches = data ?? EMPTY;++ /**+ * Re-read after a branch write (create / rename / delete), whether or not the+ * dropdown is open, so its next open never paints a branch that is gone.+ */+ const refreshBranches = useCallback(+ () => getGitStatusStoreState().refreshGitBranches(deviceId, path),+ [deviceId, path],+ );++ return useMemo(+ () => ({+ branches,+ error,+ isLoading,+ loadFailed: !isLoading && !!error && branches.length === 0,+ refreshBranches,+ revalidate: () => mutate(),+ }),+ [branches, error, isLoading, mutate, refreshBranches],+ );+};diff --git a/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.ts b/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.tsindex e92387f963c..3a59b608280 100644--- a/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.ts+++ b/src/features/ChatInput/ControlBar/useWorktreeBranchSeed.ts@@ -1,9 +1,7 @@import { generateWorktreeBranchName } from '@lobechat/const';import { useCallback, useEffect, useMemo, useState } from 'react';-import useSWR from 'swr';-import { deviceKeys } from '@/libs/swr/keys';-import { gitService } from '@/services/git';+import { useFetchGitBranches } from '@/store/device';export interface WorktreeBranchSeed {/** Whether the branch list has settled. No name may be drawn before this. */@@ -23,22 +21,21 @@ export interface WorktreeBranchSeed {* and a name drawn from a list that is still in flight reads as "no branches",* handing out a ref git is guaranteed to refuse (`cannot lock ref* 'refs/heads/wt/…': 'refs/heads/wt' exists`). The modal snapshots the name when- * it opens, so a late result could never repair that. Shares the branch- * switcher's SWR key, which means a branch dropdown opened earlier has the list- * cached and the name is ready immediately.+ * it opens, so a late result could never repair that. For the same reason the+ * list persisted from an earlier session does not count as settled: it may miss+ * a branch made since. Shares the branch switcher's replica, so a dropdown+ * opened earlier this session has the list confirmed and the name is ready+ * immediately.*/export const useWorktreeBranchSeed = (deviceId: string | undefined,path: string,): WorktreeBranchSeed => {- const { data: branches, isLoading } = useSWR(- deviceKeys.gitBranches(deviceId ?? 'local', path),- () => gitService.listGitBranches({ deviceId, path }),- { revalidateOnFocus: false, shouldRetryOnError: false },- );+ const { data: branches, error, isConfirmed } = useFetchGitBranches(deviceId, path);const excludeBranches = useMemo(() => branches?.map((branch) => branch.name) ?? [], [branches]);- const isReady = !isLoading;+ // A failed read still settles (git refuses a colliding name at create time).+ const isReady = isConfirmed || !!error;const [name, setName] = useState<string>();diff --git a/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx b/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsxindex 3aeea7df3ec..6ebba0adf7a 100644--- a/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/PortSwitcher.tsx@@ -227,14 +227,16 @@ const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirectocreatingPort,detected,detectionAvailable,+ detectionChecking,detectionLoading,- error,exposePort,isLoading,+ listFailed,openLink,otherPorts,refresh,refreshDetected,+ refreshFailed,revokeLink,tunnels,} = usePortTunnels({ active, cwd: workingDirectory, deviceId, onOpened: close, open });@@ -328,6 +330,9 @@ const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirectoconst renderDetected = (item: DeviceListeningPort) => (<DropdownMenuItemclassName={cx(styles.item, styles.idle)}+ // A port from an earlier probe may have stopped: shown, not exposable,+ // until the device confirms it still listens.+ disabled={detectionChecking}key={item.port}onClick={(event) => {event.preventDefault();@@ -344,6 +349,22 @@ const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirecto</DropdownMenuItem>);+ const checkingState = (+ <div className={styles.state}>+ <Icon spin icon={LoaderCircleIcon} size={13} />+ {t('workingPanel.overview.ports.detected.checking')}+ </div>+ );++ const loadFailedState = (+ <div className={styles.state}>+ {t('workingPanel.overview.ports.loadFailed')}+ <button className={styles.retry} type={'button'} onClick={() => void refresh()}>+ {tCommon('retry')}+ </button>+ </div>+ );+let body: ReactNode;if (isLoading) {body = (@@ -352,16 +373,12 @@ const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirecto{t('workingPanel.overview.ports.loading')}</div>);- } else if (error) {+ } else if (listFailed) {// "We couldn't ask" must not read as "nothing is open".- body = (- <div className={styles.state}>- {t('workingPanel.overview.ports.loadFailed')}- <button className={styles.retry} type={'button'} onClick={() => void refresh()}>- {tCommon('retry')}- </button>- </div>- );+ body = loadFailedState;+ } else if (tunnels.length === 0 && detected.length === 0 && detectionChecking) {+ // An empty earlier probe is not "nothing listens": wait for the device.+ body = checkingState;} else if (tunnels.length === 0 && detected.length === 0) {body = (<div className={styles.empty}>@@ -373,7 +390,12 @@ const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirecto} else {body = (<>+ {/* A failed refresh keeps the links already known. */}+ {refreshFailed && loadFailedState}{tunnels.map(renderLink)}+ {/* Ports from an earlier probe paint while the device is asked again;+ whether they still listen is unknown until it answers. */}+ {detected.length > 0 && detectionChecking && checkingState}{detected.map(renderDetected)}</>);@@ -388,9 +410,10 @@ const PortSwitcher = memo<PortSwitcherProps>(({ active, deviceId, workingDirectovalue={t('workingPanel.overview.ports.title')}trailing={<>- {detected.length > 0 && (+ {detected.length > 0 && !detectionChecking && (// A running dev server the user hasn't exposed yet — say so- // without making them open the menu.+ // without making them open the menu. Ports from an earlier+ // probe are not known to be running, so they wait for the device.<span className={styles.available}>{t('workingPanel.overview.ports.detected.available', { count: detected.length })}</span>diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.tsindex 71a0109d77e..ddf5c2e2a1c 100644--- a/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/usePortTunnels.test.ts@@ -16,8 +16,12 @@ const tunnels = vi.hoisted(() => ({value: [] as unknown[] | undefined,}));const isDesktop = vi.hoisted(() => ({ value: false }));+const addTunnelLink = vi.hoisted(() => vi.fn());+const removeTunnelLink = vi.hoisted(() => vi.fn());const detection = vi.hoisted(() => ({data: undefined as unknown,+ error: undefined as unknown,+ isConfirmed: true,isLoading: false,isValidating: false,mutate: vi.fn(),@@ -30,6 +34,7 @@ vi.mock('@/services/device', () => ({const tunnelsEnabledArgs = vi.hoisted(() => [] as boolean[]);vi.mock('@/store/device', () => ({+ getDeviceTunnelStoreState: () => ({ addTunnelLink, removeTunnelLink }),useFetchDeviceListeningPorts: () => detection,useFetchDeviceTunnels: (_deviceId: string, enabled: boolean) => {tunnelsEnabledArgs.push(enabled);@@ -93,6 +98,8 @@ beforeEach(() => {tunnels.isLoading = false;isDesktop.value = false;detection.data = undefined;+ detection.error = undefined;+ detection.isConfirmed = true;detection.isLoading = false;detection.isValidating = false;tab.location.href = '';@@ -114,6 +121,8 @@ describe('usePortTunnels', () => {await act(() => result.current.exposePort(3000));expect(createTunnel).toHaveBeenCalledWith({ deviceId: 'device-1', port: 3000 });+ // The new link lands in the replica (memory + storage) before the re-read.+ expect(addTunnelLink).toHaveBeenCalledWith(expect.objectContaining({ slug: 'abcdefgh' }));// Choosing a port means "let me see it": no second click to open it.expect(tab.location.href).toBe('https://3000--abcdefgh.lobe.sh/?token=fresh');expect(onOpened).toHaveBeenCalled();@@ -151,14 +160,15 @@ describe('usePortTunnels', () => {expect(toastSuccess).toHaveBeenCalledWith('workingPanel.overview.ports.copied');});- it('refreshes the list after revoking', async () => {+ it('drops the revoked link from the replica, not only from a refetch', async () => {revokeTunnel.mockResolvedValue({ success: true });const { result } = setup();await act(() => result.current.revokeLink(link));expect(revokeTunnel).toHaveBeenCalledWith({ slug: 'abcdefgh' });- expect(mutate).toHaveBeenCalled();+ expect(removeTunnelLink).toHaveBeenCalledWith('device-1', 'abcdefgh');+ expect(toastSuccess).toHaveBeenCalledWith('workingPanel.overview.ports.revoked');await waitFor(() => expect(result.current.busySlug).toBeUndefined());});@@ -229,6 +239,33 @@ describe('usePortTunnels', () => {});describe('list states', () => {+ it('keeps the known links on screen when a refresh fails', () => {+ tunnels.value = [link];+ tunnels.error = new Error('offline');++ // Review P2: a failed background refresh must not hide every cached link+ // behind the Retry state.+ expect(setup().result.current).toMatchObject({+ listFailed: false,+ refreshFailed: true,+ tunnels: [link],+ });+ });++ it('reports a failure with no known links as a load failure', () => {+ tunnels.value = undefined;+ tunnels.error = new Error('offline');+ expect(setup().result.current).toMatchObject({ listFailed: true, refreshFailed: false });+ });++ it('hides a persisted link that has expired since', () => {+ tunnels.value = [+ { ...link, expiresAt: Date.now() - 1000, port: 4000, slug: 'expired' },+ { ...link, expiresAt: Date.now() + 60_000 },+ ];+ expect(setup().result.current.tunnels.map((l) => l.slug)).toEqual(['abcdefgh']);+ });+it('keeps loading and failure distinct from an empty list', () => {tunnels.value = undefined;tunnels.isLoading = true;@@ -278,8 +315,49 @@ describe('usePortTunnels', () => {});it('reports no detection for a device that cannot answer', () => {- detection.data = null;- expect(setup().result.current).toMatchObject({ detected: [], detectionAvailable: false });+ detection.data = undefined;+ detection.error = new Error('Unable to detect listening ports');+ detection.isConfirmed = false;+ expect(setup().result.current).toMatchObject({+ detected: [],+ detectionAvailable: false,+ detectionChecking: false,+ });+ });++ it('treats ports from an earlier probe as unknown until the device answers', () => {+ detection.data = { ports: [port({ port: 5173 })], supported: true };+ detection.isConfirmed = false;++ // Painted (the menu shows the last ports at once) but flagged as checking,+ // so neither the badge nor the menu claims they are still running.+ expect(setup().result.current).toMatchObject({ detectionChecking: true });+ expect(setup().result.current.detected.map((p) => p.port)).toEqual([5173]);+ });++ // Review P2: a port from an earlier probe may have stopped since; exposing+ // it would create, persist and open a link onto nothing.+ it('does not expose a port from an unconfirmed probe', async () => {+ detection.data = { ports: [port({ port: 5173 })], supported: true };+ detection.isConfirmed = false;+ const { result } = setup();++ await act(() => result.current.exposePort(5173));++ expect(createTunnel).not.toHaveBeenCalled();+ expect(window.open).not.toHaveBeenCalled();+ });++ it('drops the earlier probe when the device cannot confirm it', () => {+ detection.data = { ports: [port({ port: 5173 })], supported: true };+ detection.isConfirmed = false;+ detection.error = new Error('offline');++ expect(setup().result.current).toMatchObject({+ detected: [],+ detectionAvailable: false,+ detectionChecking: false,+ });});it('shows a rescan in progress even though the previous answer is still there', () => {diff --git a/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts b/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.tsindex 0c876a78bed..d6d9ae6c94f 100644--- a/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts+++ b/src/features/Conversation/WorkingSidebar/Overview/usePortTunnels.ts@@ -8,6 +8,7 @@ import { isSafeExternalUrl } from '@/features/Work/descriptors';import { deviceService } from '@/services/device';import {type DeviceTunnelLink,+ getDeviceTunnelStoreState,useFetchDeviceListeningPorts,useFetchDeviceTunnels,} from '@/store/device';@@ -39,27 +40,44 @@ export const usePortTunnels = (options: {// "N to open" count subtracts already-exposed ports, and without the list it// would count a port that already has a link.const {- data: tunnels,+ data: storedTunnels,error,isLoading,mutate,} = useFetchDeviceTunnels(deviceId, active || open);const detection = useFetchDeviceListeningPorts(deviceId, cwd, active);+ // A link persisted last session may have expired since; the server drops it+ // from the next read, the row must not offer it meanwhile.+ const tunnels = useMemo(() => {+ const now = Date.now();+ return (storedTunnels ?? []).filter((link) => !link.expiresAt || link.expiresAt > now);+ }, [storedTunnels]);++ /**+ * Whether the ports on screen are still listening is unknown until the+ * device answers this session: the persisted probe paints, but reads as+ * "checking", never as running. A device that cannot answer leaves nothing+ * to offer.+ */+ const detectionConfirmed = detection.isConfirmed;+ const detectionChecking = !detectionConfirmed && !detection.error;+ const detectionData = detectionConfirmed || detectionChecking ? detection.data : undefined;+/*** Detected ports minus the ones already exposed on this device. Only the* project's own ports count as "available": a dev machine listens on dozens* of unrelated ports (databases, Docker, system services).*/const { detected, others } = useMemo(() => {- const ports = detection.data?.ports ?? [];- const exposed = new Set((tunnels ?? []).map((link) => link.port));+ const ports = detectionData?.ports ?? [];+ const exposed = new Set(tunnels.map((link) => link.port));const fresh = ports.filter((p) => !exposed.has(p.port));return {detected: fresh.filter((p) => p.inProject),others: fresh.filter((p) => !p.inProject),};- }, [detection.data, tunnels]);+ }, [detectionData, tunnels]);/*** Claim the tab while the click is still the browser's idea of user@@ -131,7 +149,9 @@ export const usePortTunnels = (options: {setBusySlug(link.slug);try {await deviceService.revokeTunnel({ slug: link.slug });- await mutate();+ // Written into the replica (and its storage) before the re-read, so a+ // reload never paints the revoked link back.+ getDeviceTunnelStoreState().removeTunnelLink(link.deviceId, link.slug);toast.success(t('workingPanel.overview.ports.revoked'));} catch {toast.error(t('workingPanel.overview.ports.revokeFailed'));@@ -139,7 +159,7 @@ export const usePortTunnels = (options: {setBusySlug(undefined);}},- [mutate, t],+ [t],);/** Expose a detected port and open it. */@@ -149,6 +169,9 @@ export const usePortTunnels = (options: {toast.error(t('workingPanel.overview.ports.invalidPort'));return;}+ // The ports on screen come from an earlier probe: one may have stopped+ // since, and a link to it would open onto nothing. Wait for the device.+ if (detectionChecking) return;const tab = reserveTab();if (!tab && !isDesktop) {@@ -159,7 +182,7 @@ export const usePortTunnels = (options: {setCreatingPort(target);try {const link = await deviceService.createTunnel({ deviceId, port: target });- await mutate();+ getDeviceTunnelStoreState().addTunnelLink(link);// Choosing a port means "let me see it" — open it without a second click.navigateTab(tab, link.openUrl);onOpened();@@ -170,7 +193,7 @@ export const usePortTunnels = (options: {setCreatingPort(undefined);}},- [deviceId, mutate, navigateTab, onOpened, reserveTab, t],+ [detectionChecking, deviceId, navigateTab, onOpened, reserveTab, t],);return {@@ -179,17 +202,27 @@ export const usePortTunnels = (options: {creatingPort,detected,/** False when the device can't detect (offline, or a client that predates it). */- detectionAvailable: !!detection.data?.supported,+ detectionAvailable: !!detectionData?.supported,+ /** The ports shown come from an earlier probe; the device has not answered yet. */+ detectionChecking,// Validating, not loading: a manual rescan keeps the old data and must still spin.detectionLoading: detection.isValidating,error,exposePort,isLoading,+ /**+ * The links could not be read and none are known: "couldn't ask" must not+ * read as "nothing is open". With links already known, a failed refresh+ * keeps them on screen (`refreshFailed`) — opening or revoking one is a+ * separate call that may well succeed.+ */+ listFailed: !!error && tunnels.length === 0,+ refreshFailed: !!error && tunnels.length > 0,openLink,refresh: mutate,refreshDetected: detection.mutate,otherPorts: others as DeviceListeningPort[],revokeLink,- tunnels: tunnels ?? [],+ tunnels,};};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex f49eb556284..07fc2d10d91 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -460,21 +460,6 @@ export const deviceKeys = {(workspaceId: string | null, deviceId: string, path?: string, cursor?: string) =>['device:browseDirectory', workspaceId, deviceId, path, cursor] as const,),- listeningPorts: def(- 'device:listeningPorts',- (workspaceId: string | null, deviceId: string, cwd?: string) =>- ['device:listeningPorts', workspaceId, deviceId, cwd] as const,- ),- tunnels: def('device:tunnels', (workspaceId: string | null, deviceId: string) => [- 'device:tunnels',- workspaceId,- deviceId,- ]),- gitBranches: def('device:gitBranches', (deviceId: string, path: string) => [- 'device:gitBranches',- deviceId,- path,- ]),gitLinkedPR: def('device:gitLinkedPR',(deviceId: string, path: string, branch: string, pullRequestNumber?: number) => [@@ -514,11 +499,6 @@ export const deviceKeys = {...(baseRefName === undefined ? [] : [baseRefName]),],),- gitRemoteBranches: def('device:gitRemoteBranches', (deviceId: string, dirPath: string) => [- 'device:gitRemoteBranches',- deviceId,- dirPath,- ]),gitReviewPatches: def('device:gitReviewPatches',(deviceId: string, dirPath: string, mode: string, baseRef: string) => [diff --git a/src/services/git.ts b/src/services/git.tsindex ac4031f5d05..2fbc91f690c 100644--- a/src/services/git.ts+++ b/src/services/git.ts@@ -53,7 +53,10 @@ export interface GitLinkedPRSummary {* symmetric: both transports expose the same granular git operations.*/class GitService {- /** Local branches of a working directory. */+ /**+ * Local branches of a working directory. A remote device that cannot answer+ * rejects; `[]` is a real answer (an unborn repo).+ */listGitBranches({deviceId,path,@@ -379,7 +382,10 @@ class GitService {: electronGitService.getGitBranchDiff({ baseRef, path });}- /** Remote branches (`refs/remotes/origin/*`) of a working directory. */+ /**+ * Remote branches (`refs/remotes/origin/*`) of a working directory. A remote+ * device that cannot answer rejects; `[]` is a real answer (no `origin`).+ */listGitRemoteBranches({deviceId,path,diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 8d94f9bdcc6..1c9eab5815c 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -30,11 +30,11 @@ import {type ReplicaPageResult,type ReplicaSyncResult,} from '@/libs/replica';-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';-import { cronKeys, deviceKeys, topicKeys } from '@/libs/swr/keys';+import { mutate } from '@/libs/swr';+import { cronKeys, topicKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';import { aiChatService } from '@/services/aiChat';-import { type GitLinkedPRSummary, gitService } from '@/services/git';+import { type GitLinkedPRSummary } from '@/services/git';import { messageService } from '@/services/message';import type { TopicBatchDeleteScope } from '@/services/topic';import { topicService } from '@/services/topic';@@ -80,6 +80,10 @@ import {import { type ChatTopicDispatch } from './reducer';import { topicSelectors } from './selectors';import { createTopicDetailSlice, RUN_WATCH_INTERVAL } from './topicDetail';+import {+ type TopicLinkedPullRequestRefreshParams,+ useTopicLinkedPullRequestSync,+} from './topicLinkedPullRequest';const n = setNamespace('t');@@ -189,14 +193,6 @@ export interface RemoveUnstarredTopicOptions {type Setter = StoreSetter<ChatStore>;-interface TopicLinkedPullRequestRefreshParams {- branch: string;- deviceId?: string;- path: string;- pullRequestNumber?: number;- topicId: string;-}-export const chatTopic = (set: Setter, get: () => ChatStore, _api?: unknown) =>new ChatTopicActionImpl(set, get, _api);@@ -1310,49 +1306,12 @@ export class ChatTopicActionImpl {return true;};- useFetchTopicLinkedPullRequest = (- topicId?: string,- metadata?: ChatTopicMetadata,- ): SWRResponse<GitLinkedPRSummary | undefined> => {- const params = topicId- ? this.#resolveTopicLinkedPullRequestRefreshParams(topicId, metadata)- : undefined;-- return useClientDataSWRWithSync<GitLinkedPRSummary | undefined>(- params- ? deviceKeys.gitLinkedPR(- params.deviceId ?? 'local',- params.path,- params.branch,- params.pullRequestNumber,- )- : null,- params- ? () =>- gitService.getLinkedPullRequest({- branch: params.branch,- deviceId: params.deviceId,- path: params.path,- pullRequestNumber: params.pullRequestNumber,- })- : null,- {- dedupingInterval: 60 * 1000,- focusThrottleInterval: 60 * 1000,- onData: (prData) => {- if (!params) return;-- void this.#get()- .internal_updateTopicLinkedPullRequest(params, prData)- .catch((error) => {- console.error('[useFetchTopicLinkedPullRequest] sync failed:', error);- });- },- revalidateOnFocus: true,- shouldRetryOnError: false,- },+ /** Keep a topic's recorded PR state current (see `useTopicLinkedPullRequestSync`). */+ useFetchTopicLinkedPullRequest = (topicId?: string, metadata?: ChatTopicMetadata) =>+ useTopicLinkedPullRequestSync(+ topicId ? this.#resolveTopicLinkedPullRequestRefreshParams(topicId, metadata) : undefined,+ (params, pr) => this.#get().internal_updateTopicLinkedPullRequest(params, pr),);- };autoRenameTopicTitle = async (id: string, topicAgentId?: string): Promise<void> => {const { activeAgentId, summaryTopicTitle } = this.#get();diff --git a/src/store/chat/slices/topic/topicLinkedPullRequest.ts b/src/store/chat/slices/topic/topicLinkedPullRequest.tsnew file mode 100644index 00000000000..3925fd07e62--- /dev/null+++ b/src/store/chat/slices/topic/topicLinkedPullRequest.ts@@ -0,0 +1,68 @@+import { useEffect, useRef } from 'react';++import type { GitLinkedPRSummary } from '@/services/git';+import { gitLinkedPRKey } from '@/store/device/gitReview/projection';+import { useGitReviewStore } from '@/store/device/gitReview/store';++export interface TopicLinkedPullRequestRefreshParams {+ branch: string;+ deviceId?: string;+ path: string;+ pullRequestNumber?: number;+ topicId: string;+}++/** Forwarded to SWR as given: a failed `gh` lookup is not retried. */+const NO_RETRY = { shouldRetryOnError: false };++/**+ * Keep a topic's recorded PR state current. Reads through the device's+ * linked-PR replica, so with no recorded PR number it shares the composer's+ * row and request for the same branch. Every device answer for that row is+ * written back to the topic — also one the composer fetched before this hook+ * mounted (inside the dedupe window no new response arrives). A row hydrated+ * from storage is not proof and is never written back.+ */+export const useTopicLinkedPullRequestSync = (+ params: TopicLinkedPullRequestRefreshParams | undefined,+ writeBack: (+ params: TopicLinkedPullRequestRefreshParams,+ pr?: GitLinkedPRSummary,+ ) => Promise<void>,+) => {+ const replicaParams = params+ ? {+ branch: params.branch,+ deviceId: params.deviceId,+ path: params.path,+ pullRequestNumber: params.pullRequestNumber,+ }+ : null;+ const key = replicaParams ? gitLinkedPRKey(replicaParams) : undefined;++ const sync = useGitReviewStore.getState().slices.linkedPR.useSync(replicaParams, {+ dedupingInterval: 60 * 1000,+ focusThrottleInterval: 60 * 1000,+ revalidateOnFocus: true,+ ...NO_RETRY,+ });++ const confirmed = useGitReviewStore((s) =>+ key && s.gitLinkedPRReplica.entries[key]?.source === 'server'+ ? s.gitLinkedPRMap[key]+ : undefined,+ );+ const latest = useRef({ params, writeBack });+ latest.current = { params, writeBack };++ useEffect(() => {+ const { params: current, writeBack: write } = latest.current;+ if (!confirmed || !current) return;++ void write(current, confirmed.value).catch((error) => {+ console.error('[useFetchTopicLinkedPullRequest] sync failed:', error);+ });+ }, [confirmed, params?.topicId]);++ return sync;+};diff --git a/src/store/device/deviceReplicaFirstPaint.test.ts b/src/store/device/deviceReplicaFirstPaint.test.tsnew file mode 100644index 00000000000..b3025af090c--- /dev/null+++ b/src/store/device/deviceReplicaFirstPaint.test.ts@@ -0,0 +1,266 @@+/**+ * @vitest-environment happy-dom+ *+ * Device reads that used to live only in SWR's memory cache — the base-ref+ * pickers' remote branches, the Ports row's tunnel links and listening ports,+ * and a topic's linked-PR refresh — are replicas: after a reload they paint the+ * persisted copy before the device answers, and the answer replaces it.+ */+import { randomUUID } from 'node:crypto';++import type { DeviceListeningPortsResult } from '@lobechat/types';+import { renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { IndexedDBQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { deviceService } from '@/services/device';+import { gitService } from '@/services/git';+import { useChatStore } from '@/store/chat';++import { useFetchGitLinkedPR, useGitRemoteBranches } from './gitHooks';+import { useFetchDeviceListeningPorts, useFetchDeviceTunnels } from './tunnelHooks';++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal()),+ isDesktop: true,+}));++vi.mock('@/services/git', () => ({+ gitService: {+ getLinkedPullRequest: vi.fn(),+ listGitRemoteBranches: vi.fn(),+ },+}));++vi.mock('@/services/device', () => ({+ deviceService: {+ listListeningPorts: vi.fn(),+ listTunnels: vi.fn(),+ },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++/** Never-resolving read: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const DEVICE = 'device-1';+const CWD = '/repo';++const remoteBranchStorage = new IndexedDBQueryProjectionStorage<{ value?: unknown }>({+ namespace: 'replica:deviceGitRemoteBranchList:v1',+});+const tunnelStorage = new IndexedDBQueryProjectionStorage<unknown[]>({+ namespace: 'replica:deviceTunnelLinks:v1',+});+const portStorage = new IndexedDBQueryProjectionStorage<DeviceListeningPortsResult>({+ namespace: 'replica:deviceListeningPorts:v1',+});++const REMOTE_BRANCH_ROW = `${DEVICE}\u0000${CWD}`;+const TUNNEL_ROW = DEVICE;+const PORT_ROW = `${DEVICE}\u0000${CWD}`;++const link = {+ createdAt: 1,+ deviceId: DEVICE,+ hostname: '3000--abcdefgh.lobe.sh',+ port: 3000,+ slug: 'abcdefgh',+ url: 'https://3000--abcdefgh.lobe.sh/',+};++const port = (value: number) => ({+ command: 'node',+ inProject: true,+ loopback: 'both' as const,+ port: value,+});++describe('device replicas paint from storage first', () => {+ const scopes = new Set<string>();+ let scope = '';+ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`device-user-${randomUUID()}:personal`);+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) => [+ remoteBranchStorage.remove({ queryKey: REMOTE_BRANCH_ROW, scope: value }),+ tunnelStorage.remove({ queryKey: TUNNEL_ROW, scope: value }),+ portStorage.remove({ queryKey: PORT_ROW, scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted remote branches when a base-ref picker opens', async () => {+ await remoteBranchStorage.set(+ { queryKey: REMOTE_BRANCH_ROW, scope },+ { data: { value: [{ name: 'origin/main' }, { name: 'origin/cached' }] }, updatedAt: 1 },+ );+ vi.mocked(gitService.listGitRemoteBranches).mockImplementation(pending);++ const { result } = renderHook(() => useGitRemoteBranches(CWD, true, DEVICE), { wrapper });++ await waitFor(() =>+ expect(result.current.data?.map((b) => b.name)).toEqual(['origin/main', 'origin/cached']),+ );+ expect(gitService.listGitRemoteBranches).toHaveBeenCalledWith({ deviceId: DEVICE, path: CWD });+ });++ // Review P2: a gateway outage used to arrive as `[]` and replace the cached list;+ // it now rejects, and the replica keeps its copy.+ it('keeps the persisted remote branches when the device cannot answer', async () => {+ await remoteBranchStorage.set(+ { queryKey: REMOTE_BRANCH_ROW, scope },+ { data: { value: [{ name: 'origin/main' }] }, updatedAt: 1 },+ );+ vi.mocked(gitService.listGitRemoteBranches).mockRejectedValue(+ new Error('The device could not list remote branches.'),+ );++ const { result } = renderHook(() => useGitRemoteBranches(CWD, true, DEVICE), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(result.current.data?.map((b) => b.name)).toEqual(['origin/main']);+ expect((await remoteBranchStorage.get({ queryKey: REMOTE_BRANCH_ROW, scope }))?.data).toEqual({+ value: [{ name: 'origin/main' }],+ });+ });++ it('paints the persisted tunnel links, then the server list replaces them', async () => {+ await tunnelStorage.set({ queryKey: TUNNEL_ROW, scope }, { data: [link], updatedAt: 1 });+ let answer!: (links: unknown[]) => void;+ vi.mocked(deviceService.listTunnels).mockImplementation(+ () => new Promise((resolve) => (answer = resolve as any)) as any,+ );++ const { result } = renderHook(() => useFetchDeviceTunnels(DEVICE), { wrapper });++ await waitFor(() => expect(result.current.data?.map((l) => l.slug)).toEqual(['abcdefgh']));+ expect(result.current.isLoading).toBe(false);++ answer([{ ...link, port: 5173, slug: 'fresh' }]);+ await waitFor(() => expect(result.current.data?.map((l) => l.slug)).toEqual(['fresh']));+ });++ it('paints the persisted ports as unconfirmed until the device answers', async () => {+ await portStorage.set(+ { queryKey: PORT_ROW, scope },+ { data: { ports: [port(5173)], supported: true }, updatedAt: 1 },+ );+ let answer!: (result: DeviceListeningPortsResult) => void;+ vi.mocked(deviceService.listListeningPorts).mockImplementation(+ () => new Promise((resolve) => (answer = resolve)) as any,+ );++ const { result } = renderHook(() => useFetchDeviceListeningPorts(DEVICE, CWD), { wrapper });++ await waitFor(() => expect(result.current.data?.ports.map((p) => p.port)).toEqual([5173]));+ // Whether 5173 still listens is unknown until this session's probe answers.+ expect((result.current as { isConfirmed?: boolean }).isConfirmed).toBe(false);++ answer({ ports: [port(3000)], supported: true });+ await waitFor(() => expect(result.current.data?.ports.map((p) => p.port)).toEqual([3000]));+ expect((result.current as { isConfirmed?: boolean }).isConfirmed).toBe(true);+ });++ // Review P2: a topic hook that mounts after the composer already fetched the+ // shared row (e.g. hovering a background topic) gets no new response inside+ // the dedupe window; it must still write the confirmed PR back to the topic.+ it('writes a PR the composer already confirmed back to a topic that mounts later', async () => {+ vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue({+ ghMissing: false,+ pullRequest: { number: 9, state: 'open', title: 'feat', url: 'https://x/9' } as any,+ pullRequestStatus: 'ok',+ });+ useChatStore.setState({ activeAgentId: 'agent-1' });+ const metadata = {+ workingDirectory: CWD,+ workingDirectoryConfig: { git: { branch: 'feat/late' }, path: CWD, repoType: 'github' },+ } as any;+ const update = vi.fn().mockResolvedValue(undefined);+ useChatStore.setState({ internal_updateTopicLinkedPullRequest: update } as any);++ const { result, rerender } = renderHook(+ ({ withTopic }: { withTopic: boolean }) => {+ useChatStore+ .getState()+ .useFetchTopicLinkedPullRequest(withTopic ? 'topic-late' : undefined, metadata);+ return useFetchGitLinkedPR(undefined, CWD, 'feat/late', true);+ },+ { initialProps: { withTopic: false }, wrapper },+ );+ await waitFor(() => expect(result.current.data?.pullRequest?.number).toBe(9));+ expect(update).not.toHaveBeenCalled();++ rerender({ withTopic: true });++ await waitFor(() => expect(update).toHaveBeenCalled());+ expect(update.mock.calls[0][0]).toMatchObject({ branch: 'feat/late', topicId: 'topic-late' });+ expect(update.mock.calls[0][1]).toMatchObject({ pullRequest: { number: 9 } });+ expect(gitService.getLinkedPullRequest).toHaveBeenCalledTimes(1);+ });++ // Regression: the topic refresh and the composer's lookup used the same SWR+ // key with different fetchers and value shapes, so whichever ran first owned+ // the cache — and each still sent its own `gh pr list`.+ it('shares one linked-PR read between a topic refresh and the composer', async () => {+ vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue({+ ghMissing: false,+ pullRequest: { number: 7, state: 'open', title: 'feat', url: 'https://x/7' } as any,+ pullRequestStatus: 'ok',+ });+ useChatStore.setState({ activeAgentId: 'agent-1' });+ const metadata = {+ workingDirectory: CWD,+ workingDirectoryConfig: { git: { branch: 'feat/x' }, path: CWD, repoType: 'github' },+ } as any;+ const update = vi+ .spyOn(useChatStore.getState(), 'internal_updateTopicLinkedPullRequest')+ .mockResolvedValue();+ useChatStore.setState({ internal_updateTopicLinkedPullRequest: update } as any);++ const { result } = renderHook(+ () => {+ useChatStore.getState().useFetchTopicLinkedPullRequest('topic-1', metadata);+ return useFetchGitLinkedPR(undefined, CWD, 'feat/x', true);+ },+ { wrapper },+ );++ await waitFor(() => expect(result.current.data?.pullRequest?.number).toBe(7));+ await waitFor(() => expect(update).toHaveBeenCalled());+ expect(update.mock.calls[0][1]).toMatchObject({ pullRequest: { number: 7 } });+ expect(gitService.getLinkedPullRequest).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.tsindex 03b14766819..00a5be2a158 100644--- a/src/store/device/gitHooks.ts+++ b/src/store/device/gitHooks.ts@@ -3,18 +3,20 @@ import type { ReplicaOptimisticToken } from '@lobechat/replica';import type { ReplicaSlice, ReplicaSyncSchedule } from '@lobechat/replica/zustand';import type {DeviceGitAheadBehind,+ DeviceGitBranchListItem,DeviceGitPullRequestActivity,DeviceGitPullRequestDetail,DeviceGitPullRequestDetailResult,DeviceGitPullRequestMergeContext,+ DeviceGitRemoteBranchListItem,DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';import { useCallback, useMemo, useRef } from 'react';-import { mutate, useClientDataSWR } from '@/libs/swr';+import { mutate } from '@/libs/swr';import { deviceKeys, localFileKeys } from '@/libs/swr/keys';-import { type GitBranchSummary, type GitLinkedPRSummary, gitService } from '@/services/git';+import type { GitBranchSummary, GitLinkedPRSummary } from '@/services/git';import {gitLinkedPRKey,@@ -254,10 +256,11 @@ const useGitStatusRead = <T>(deviceId: string | undefined,path: string | undefined,schedule: ReplicaSyncSchedule,+ enabled = true,): GitStatusReadResult<T> => {const params = useMemo(- () => (isEnabled(deviceId, path) ? { deviceId, path } : null),- [deviceId, path],+ () => (enabled && isEnabled(deviceId, path) ? { deviceId, path } : null),+ [enabled, deviceId, path],);const key = params ? gitStatusKey(params) : undefined;const stored = useGitStatusStore((s) => (key ? selectMap(s)[key] : undefined));@@ -341,6 +344,8 @@ const useGitStatusRead = <T>(};const selectBranchMap = (s: GitStatusStore) => s.gitBranchMap;+const selectBranchListMap = (s: GitStatusStore) => s.gitBranchListMap;+const selectRemoteBranchListMap = (s: GitStatusStore) => s.gitRemoteBranchListMap;const selectAheadBehindMap = (s: GitStatusStore) => s.gitAheadBehindMap;const selectWorkingTreeStatusMap = (s: GitStatusStore) => s.gitWorkingTreeStatusMap;const selectWorktreesMap = (s: GitStatusStore) => s.gitWorktreesMap;@@ -348,6 +353,8 @@ const selectWorktreesMap = (s: GitStatusStore) => s.gitWorktreesMap;const selectDiffStatsMap = (s: GitStatusStore) => s.gitDiffStatsMap;const selectBranchEntries = (s: GitStatusStore) => s.gitBranchReplica.entries;+const selectBranchListEntries = (s: GitStatusStore) => s.gitBranchListReplica.entries;+const selectRemoteBranchListEntries = (s: GitStatusStore) => s.gitRemoteBranchListReplica.entries;const selectAheadBehindEntries = (s: GitStatusStore) => s.gitAheadBehindReplica.entries;const selectDiffStatsEntries = (s: GitStatusStore) => s.gitDiffStatsReplica.entries;const selectWorkingTreeStatusEntries = (s: GitStatusStore) => s.gitWorkingTreeStatusReplica.entries;@@ -588,22 +595,43 @@ export const useFetchGitPullRequestMergeContext = (};/**- * Lazy-loaded list of remote branches under `refs/remotes/origin/*`.- * Disabled until the Review base-ref picker opens.+ * Local branches of a directory: the branch switcher's list and the names a new+ * worktree branch must avoid. The persisted list paints the switcher the moment+ * it opens; `isConfirmed` says whether this session's read has answered (a name+ * drawn against a stale list could collide with a branch made since). The 10s+ * dedupe lets the switcher and the worktree seed share one read; branch writes+ * re-read through `refreshGitBranches`.+ */+export const useFetchGitBranches = (+ deviceId: string | undefined,+ path: string | undefined,+ enabled = true,+) =>+ useGitStatusRead<DeviceGitBranchListItem[]>(+ useGitStatusStore.getState().slices.branches,+ selectBranchListMap,+ selectBranchListEntries,+ deviceId,+ path,+ { dedupingInterval: 10 * 1000, revalidateOnFocus: false },+ enabled,+ );++/**+ * Remote branches under `refs/remotes/origin/*`, read once a base-ref picker+ * opens. The persisted list paints the picker immediately; the read refreshes it.*/export const useGitRemoteBranches = (dirPath: string | undefined,enabled: boolean,deviceId?: string,-) => {- const key =- enabled && dirPath ? deviceKeys.gitRemoteBranches(deviceId ?? 'local', dirPath) : null;- return useClientDataSWR(- key,- () => gitService.listGitRemoteBranches({ deviceId, path: dirPath! }),- {- revalidateOnFocus: false,- shouldRetryOnError: false,- },+) =>+ useGitStatusRead<DeviceGitRemoteBranchListItem[]>(+ useGitStatusStore.getState().slices.remoteBranches,+ selectRemoteBranchListMap,+ selectRemoteBranchListEntries,+ deviceId,+ dirPath,+ { dedupingInterval: 10 * 1000, revalidateOnFocus: false },+ enabled,);-};diff --git a/src/store/device/gitReview/projection.ts b/src/store/device/gitReview/projection.tsindex a887a38accd..8dffb64cf27 100644--- a/src/store/device/gitReview/projection.ts+++ b/src/store/device/gitReview/projection.ts@@ -131,6 +131,11 @@ export interface GitLinkedPRParams {branch: string;deviceId?: string;path: string;+ /**+ * The PR a topic recorded for this branch, so the lookup follows that PR even+ * after another one opens on the branch. Absent for the composer's lookup.+ */+ pullRequestNumber?: number;}export interface GitPullRequestParams {@@ -148,8 +153,11 @@ export interface GitPullRequestMergeContextParams extends GitPullRequestParams {export const gitReviewPatchesKey = ({ baseRef, deviceId, mode, path }: GitReviewPatchesParams) =>joinKey(deviceId ?? LOCAL, path, mode, baseRef ?? '');-export const gitLinkedPRKey = ({ branch, deviceId, path }: GitLinkedPRParams) =>- joinKey(deviceId ?? LOCAL, path, branch);+/** Without a PR number this is the composer's key, so both readers share one row. */+export const gitLinkedPRKey = ({ branch, deviceId, path, pullRequestNumber }: GitLinkedPRParams) =>+ pullRequestNumber === undefined+ ? joinKey(deviceId ?? LOCAL, path, branch)+ : joinKey(deviceId ?? LOCAL, path, branch, pullRequestNumber);export const gitPullRequestKey = ({ deviceId, number, path }: GitPullRequestParams) =>joinKey(deviceId ?? LOCAL, path, number);@@ -188,7 +196,8 @@ export const gitLinkedPRResource = defineReplica<name: 'deviceGitLinkedPR',persist: { maxEntries: 50 },storage: 'indexedDB',- syncKey: ({ branch, deviceId, path }) => deviceKeys.gitLinkedPR(deviceId ?? LOCAL, path, branch),+ syncKey: ({ branch, deviceId, path, pullRequestNumber }) =>+ deviceKeys.gitLinkedPR(deviceId ?? LOCAL, path, branch, pullRequestNumber),version: 1,});diff --git a/src/store/device/gitReview/store.test.ts b/src/store/device/gitReview/store.test.tsindex 2bb2649904c..c0f40d6a23b 100644--- a/src/store/device/gitReview/store.test.ts+++ b/src/store/device/gitReview/store.test.ts@@ -31,6 +31,7 @@ import {import {getReviewSummaryState,GIT_REVIEW_MAX_PERSISTED_BYTES,+ gitLinkedPRKey,gitLinkedPRResource,gitPullRequestActivityResource,gitPullRequestDetailResource,@@ -615,4 +616,26 @@ describe('Review / PR tab replicas', () => {expect(result.current.isLoading).toBe(false);});});++ describe('linked PR key', () => {+ it('shares the composer row when a topic has no recorded PR, and splits it when it has one', () => {+ const composer = { branch: 'feat/x', deviceId: 'device-1', path: '/repo' };++ expect(gitLinkedPRKey({ ...composer, pullRequestNumber: undefined })).toBe(+ gitLinkedPRKey(composer),+ );+ // A topic that recorded PR #7 asks `gh` about that PR, not "the PR of+ // this branch": its answer must not land on the composer's row.+ expect(gitLinkedPRKey({ ...composer, pullRequestNumber: 7 })).not.toBe(+ gitLinkedPRKey(composer),+ );+ expect(gitLinkedPRResource.syncKey!({ ...composer, pullRequestNumber: 7 })).toEqual([+ 'device:gitLinkedPR',+ 'device-1',+ '/repo',+ 'feat/x',+ 7,+ ]);+ });+ });});diff --git a/src/store/device/gitStatus/projection.ts b/src/store/device/gitStatus/projection.tsindex 442e07e9b23..17ecbf035ff 100644--- a/src/store/device/gitStatus/projection.ts+++ b/src/store/device/gitStatus/projection.ts@@ -1,5 +1,7 @@import type {DeviceGitAheadBehind,+ DeviceGitBranchListItem,+ DeviceGitRemoteBranchListItem,DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';@@ -95,6 +97,33 @@ export const gitWorktreesResource = defineReplica<version: 1,});+/**+ * Local branches of a directory — the branch switcher's list and the names a+ * new worktree branch must avoid. Names + flags only.+ */+export const gitBranchListResource = defineReplica<+ GitStatusParams,+ GitStatusRead<DeviceGitBranchListItem[]>+>({+ key: gitStatusKey,+ name: 'deviceGitBranchList',+ persist,+ storage: 'indexedDB',+ version: 1,+});++/** `refs/remotes/origin/*` of a directory, for the Review / PR base-ref pickers. */+export const gitRemoteBranchListResource = defineReplica<+ GitStatusParams,+ GitStatusRead<DeviceGitRemoteBranchListItem[]>+>({+ key: gitStatusKey,+ name: 'deviceGitRemoteBranchList',+ persist,+ storage: 'indexedDB',+ version: 1,+});+/*** Memory + storage only: the counts are written from the review-patch read* (a sibling resource), so there is no fetcher of its own to run.diff --git a/src/store/device/gitStatus/store.ts b/src/store/device/gitStatus/store.tsindex 12862b55eaa..8a4e143242f 100644--- a/src/store/device/gitStatus/store.ts+++ b/src/store/device/gitStatus/store.ts@@ -1,5 +1,7 @@import type {DeviceGitAheadBehind,+ DeviceGitBranchListItem,+ DeviceGitRemoteBranchListItem,DeviceGitWorkingTreeStatus,DeviceGitWorktreeListItem,} from '@lobechat/types';@@ -18,9 +20,11 @@ import { expose } from '@/store/middleware/expose';import {gitAheadBehindResource,+ gitBranchListResource,gitBranchResource,type GitDiffStats,gitDiffStatsResource,+ gitRemoteBranchListResource,gitStatusKey,type GitStatusParams,type GitStatusRead,@@ -32,12 +36,18 @@ export interface GitStatusStoreState {/** `gitStatusKey(params)` → ahead/behind counts. */gitAheadBehindMap: Record<string, GitStatusRead<DeviceGitAheadBehind>>;gitAheadBehindReplica: ReplicaState<GitStatusRead<DeviceGitAheadBehind>>;+ /** `gitStatusKey(params)` → local branches (switcher list, worktree name seed). */+ gitBranchListMap: Record<string, GitStatusRead<DeviceGitBranchListItem[]>>;+ gitBranchListReplica: ReplicaState<GitStatusRead<DeviceGitBranchListItem[]>>;/** `gitStatusKey(params)` → current branch + detached + upstream. */gitBranchMap: Record<string, GitStatusRead<GitBranchSummary>>;gitBranchReplica: ReplicaState<GitStatusRead<GitBranchSummary>>;/** `gitStatusKey(params)` → uncommitted diff line/file counts (composer chip). */gitDiffStatsMap: Record<string, GitStatusRead<GitDiffStats>>;gitDiffStatsReplica: ReplicaState<GitStatusRead<GitDiffStats>>;+ /** `gitStatusKey(params)` → `origin/*` branches (base-ref pickers). */+ gitRemoteBranchListMap: Record<string, GitStatusRead<DeviceGitRemoteBranchListItem[]>>;+ gitRemoteBranchListReplica: ReplicaState<GitStatusRead<DeviceGitRemoteBranchListItem[]>>;/** `gitStatusKey(params)` → dirty-file counts. */gitWorkingTreeStatusMap: Record<string, GitStatusRead<DeviceGitWorkingTreeStatus>>;gitWorkingTreeStatusReplica: ReplicaState<GitStatusRead<DeviceGitWorkingTreeStatus>>;@@ -49,10 +59,14 @@ export interface GitStatusStoreState {export const initialGitStatusState: GitStatusStoreState = {gitAheadBehindMap: {},gitAheadBehindReplica: createReplicaState(),+ gitBranchListMap: {},+ gitBranchListReplica: createReplicaState(),gitBranchMap: {},gitBranchReplica: createReplicaState(),gitDiffStatsMap: {},gitDiffStatsReplica: createReplicaState(),+ gitRemoteBranchListMap: {},+ gitRemoteBranchListReplica: createReplicaState(),gitWorkingTreeStatusMap: {},gitWorkingTreeStatusReplica: createReplicaState(),gitWorktreesMap: {},@@ -60,7 +74,13 @@ export const initialGitStatusState: GitStatusStoreState = {};export type GitStatusKind =- 'aheadBehind' | 'branch' | 'diffStats' | 'workingTreeStatus' | 'worktrees';+ | 'aheadBehind'+ | 'branch'+ | 'branches'+ | 'diffStats'+ | 'remoteBranches'+ | 'workingTreeStatus'+ | 'worktrees';const createSlices = (set: (partial: Partial<GitStatusStore>, replace?: false, action?: any) => void,@@ -84,6 +104,18 @@ const createSlices = (stateKey: 'gitBranchReplica',view: recordLens<GitStatusStore, GitStatusRead<GitBranchSummary>>('gitBranchMap'),}),+ branches: createReplicaSlice(gitBranchListResource, {+ actionPrefix: 'gitStatus/branches',+ // A remote device that cannot answer rejects (the persisted list stays);+ // `[]` is a real answer (an unborn repository).+ fetcher: async (params: GitStatusParams) => ({+ value: await gitService.listGitBranches(params),+ }),+ get,+ set,+ stateKey: 'gitBranchListReplica',+ view: recordLens<GitStatusStore, GitStatusRead<DeviceGitBranchListItem[]>>('gitBranchListMap'),+ }),// No fetcher: the counts are written from the review-patch read that already// fetched them (see `useFetchGitDiffStats` + the GitStatus effect).diffStats: createReplicaSlice(gitDiffStatsResource, {@@ -93,6 +125,19 @@ const createSlices = (stateKey: 'gitDiffStatsReplica',view: recordLens<GitStatusStore, GitStatusRead<GitDiffStats>>('gitDiffStatsMap'),}),+ remoteBranches: createReplicaSlice(gitRemoteBranchListResource, {+ actionPrefix: 'gitStatus/remoteBranches',+ // As for local branches: a failed read rejects, `[]` is "no origin".+ fetcher: async (params: GitStatusParams) => ({+ value: await gitService.listGitRemoteBranches(params),+ }),+ get,+ set,+ stateKey: 'gitRemoteBranchListReplica',+ view: recordLens<GitStatusStore, GitStatusRead<DeviceGitRemoteBranchListItem[]>>(+ 'gitRemoteBranchListMap',+ ),+ }),workingTreeStatus: createReplicaSlice(gitWorkingTreeStatusResource, {actionPrefix: 'gitStatus/workingTreeStatus',fetcher: async (params: GitStatusParams) => ({@@ -120,6 +165,12 @@ const createSlices = (type GitStatusSlices = ReturnType<typeof createSlices>;export interface GitStatusStore extends GitStatusStoreState {+ /**+ * Re-read a directory's local branch list after a branch write (create /+ * rename / delete / checkout), whether or not the switcher is open: the+ * persisted list must not paint a branch that is gone on the next open.+ */+ refreshGitBranches: (deviceId: string | undefined, path: string) => Promise<void>;/*** Re-run the mounted reads of one directory (all kinds by default) — after a* pull / push / checkout / worktree change made outside the hooks' own views.@@ -136,7 +187,9 @@ export interface GitStatusStore extends GitStatusStoreState {const ALL_KINDS: GitStatusKind[] = ['aheadBehind','branch',+ 'branches','diffStats',+ 'remoteBranches','workingTreeStatus','worktrees',];@@ -149,6 +202,13 @@ export const useGitStatusStore = createWithEqualityFn<GitStatusStore>()(return {...initialGitStatusState,+ refreshGitBranches: async (deviceId, path) => {+ try {+ await slices.branches.fetch({ deviceId, path }, { fresh: true });+ } catch {+ // Keep the last list; the next open re-reads an unreachable device.+ }+ },revalidateGitStatus: async (deviceId, path, kinds = ALL_KINDS) => {const key = gitStatusKey({ deviceId, path });await Promise.all(kinds.map((kind) => slices[kind].revalidate(key)));diff --git a/src/store/device/tunnel/projection.ts b/src/store/device/tunnel/projection.tsnew file mode 100644index 00000000000..c4782080206--- /dev/null+++ b/src/store/device/tunnel/projection.ts@@ -0,0 +1,91 @@+import type { DeviceListeningPortsResult } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';++/**+ * The Working Sidebar "Ports" row reads: a device's tunnel links and the ports+ * it is listening on. Replicas so a reload paints the last links / ports on the+ * first frame and the reads only confirm them.+ *+ * Rows are partitioned by the cache scope (user + workspace). Links are keyed+ * by device; ports by device + project directory (the directory decides which+ * ports count as the project's). A stored link is the clean URL — the token+ * that opens it is minted per click and never stored.+ */+export interface DeviceTunnelLink {+ createdAt: number;+ deviceId: string;+ expiresAt?: number;+ hostname: string;+ port: number;+ slug: string;+ url: string;+}++/**+ * The stored shape of a link: only its clean fields. A create response also+ * carries `openUrl`, whose one-shot token is a credential and must never reach+ * memory or storage.+ */+export const toStoredTunnelLink = ({+ createdAt,+ deviceId,+ expiresAt,+ hostname,+ port,+ slug,+ url,+}: DeviceTunnelLink): DeviceTunnelLink => ({+ createdAt,+ deviceId,+ expiresAt,+ hostname,+ port,+ slug,+ url,+});++export interface DeviceTunnelsParams {+ deviceId: string;+}++export interface DeviceListeningPortsParams {+ cwd?: string;+ deviceId: string;+}++export const deviceTunnelsKey = ({ deviceId }: DeviceTunnelsParams) => deviceId;++export const deviceListeningPortsKey = ({ cwd, deviceId }: DeviceListeningPortsParams) =>+ `${deviceId}\u0000${cwd ?? ''}`;++/** A dev machine listens on dozens of ports; storage keeps a bounded list. */+export const MAX_PERSISTED_PORTS = 100;++export const toPersistedListeningPorts = (+ data: DeviceListeningPortsResult,+): DeviceListeningPortsResult => ({ ...data, ports: data.ports.slice(0, MAX_PERSISTED_PORTS) });++export const deviceTunnelsResource = defineReplica<DeviceTunnelsParams, DeviceTunnelLink[]>({+ key: deviceTunnelsKey,+ name: 'deviceTunnelLinks',+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ version: 1,+});++/**+ * Which ports were listening at the last probe. A persisted row is a paint-only+ * stand-in: whether those ports are still up is unknown until the device+ * answers (see `useFetchDeviceListeningPorts`' `isConfirmed`).+ */+export const deviceListeningPortsResource = defineReplica<+ DeviceListeningPortsParams,+ DeviceListeningPortsResult+>({+ key: deviceListeningPortsKey,+ name: 'deviceListeningPorts',+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/device/tunnel/store.test.ts b/src/store/device/tunnel/store.test.tsnew file mode 100644index 00000000000..0ccf22eb795--- /dev/null+++ b/src/store/device/tunnel/store.test.ts@@ -0,0 +1,239 @@+/**+ * @vitest-environment happy-dom+ *+ * Tunnel links and listening ports are replicas. Writes land in the replica+ * (memory and storage), a failed read keeps what is on screen, and nothing a+ * create response carries as a credential reaches storage.+ */+import { randomUUID } from 'node:crypto';++import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { deviceService } from '@/services/device';++import { useFetchDeviceListeningPorts, useFetchDeviceTunnels } from '../tunnelHooks';+import {+ deviceListeningPortsResource,+ type DeviceTunnelLink,+ deviceTunnelsResource,+ MAX_PERSISTED_PORTS,+} from './projection';+import { initialDeviceTunnelState, useDeviceTunnelStore } from './store';++vi.mock('@/services/device', () => ({+ deviceService: {+ listListeningPorts: vi.fn(),+ listTunnels: vi.fn(),+ },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const pending = () => new Promise<never>(() => {});++const DEVICE = 'device-1';+const TUNNELS = { deviceId: DEVICE };+const PORTS = { cwd: '/repo', deviceId: DEVICE };++const link = (slug: string, port = 3000): DeviceTunnelLink => ({+ createdAt: 1,+ deviceId: DEVICE,+ hostname: `${port}--${slug}.lobe.sh`,+ port,+ slug,+ url: `https://${port}--${slug}.lobe.sh/`,+});++const port = (value: number) => ({+ command: 'node',+ inProject: true,+ loopback: 'both' as const,+ port: value,+});++describe('device tunnel replicas', () => {+ const scopes = new Set<string>();+ let scope = '';+ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };+ const storedTunnels = async () =>+ (+ await deviceTunnelsResource.storage!.get({+ queryKey: deviceTunnelsResource.storageKey(TUNNELS),+ scope,+ })+ )?.data;+ const storedPorts = async () =>+ (+ await deviceListeningPortsResource.storage!.get({+ queryKey: deviceListeningPortsResource.storageKey(PORTS),+ scope,+ })+ )?.data;+ const seedTunnels = (links: DeviceTunnelLink[]) =>+ deviceTunnelsResource.storage!.set(+ { queryKey: deviceTunnelsResource.storageKey(TUNNELS), scope },+ { data: links, updatedAt: 1 },+ );++ beforeEach(() => {+ useScope(`tunnel-user-${randomUUID()}:personal`);+ act(() => useDeviceTunnelStore.setState(initialDeviceTunnelState));+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].flatMap((value) => [+ deviceTunnelsResource.storage!.remove({+ queryKey: deviceTunnelsResource.storageKey(TUNNELS),+ scope: value,+ }),+ deviceListeningPortsResource.storage!.remove({+ queryKey: deviceListeningPortsResource.storageKey(PORTS),+ scope: value,+ }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('removes a revoked link from storage too, so a reload cannot paint it back', async () => {+ vi.mocked(deviceService.listTunnels).mockResolvedValue([link('keep'), link('gone', 4000)]);+ const { result } = renderHook(() => useFetchDeviceTunnels(DEVICE), { wrapper });+ await waitFor(() => expect(result.current.data?.length).toBe(2));+ await waitFor(async () => expect((await storedTunnels())?.length).toBe(2));++ // The re-read after the revoke fails: the write alone must still hold.+ vi.mocked(deviceService.listTunnels).mockRejectedValue(new Error('offline'));+ act(() => useDeviceTunnelStore.getState().removeTunnelLink(DEVICE, 'gone'));++ expect(result.current.data?.map((l) => l.slug)).toEqual(['keep']);+ await waitFor(async () =>+ expect((await storedTunnels())?.map((l) => l.slug)).toEqual(['keep']),+ );+ });++ it('stores a created link without the one-shot openUrl token', async () => {+ vi.mocked(deviceService.listTunnels).mockImplementation(pending);+ const { result } = renderHook(() => useFetchDeviceTunnels(DEVICE), { wrapper });++ act(() =>+ useDeviceTunnelStore.getState().addTunnelLink({+ ...link('fresh'),+ openUrl: 'https://3000--fresh.lobe.sh/?token=secret',+ } as DeviceTunnelLink),+ );++ expect(result.current.data?.map((l) => l.slug)).toEqual(['fresh']);+ expect(JSON.stringify(result.current.data)).not.toContain('token=secret');+ await waitFor(async () => expect((await storedTunnels())?.[0]?.slug).toBe('fresh'));+ expect(JSON.stringify(await storedTunnels())).not.toContain('token=secret');+ });++ it('keeps the links on screen when a refresh fails', async () => {+ await seedTunnels([link('cached')]);+ vi.mocked(deviceService.listTunnels).mockRejectedValue(new Error('offline'));++ const { result } = renderHook(() => useFetchDeviceTunnels(DEVICE), { wrapper });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(result.current.data?.map((l) => l.slug)).toEqual(['cached']);+ });++ it('does not paint another identity’s links', async () => {+ await seedTunnels([link('theirs')]);+ useScope(`tunnel-user-${randomUUID()}:personal`);+ vi.mocked(deviceService.listTunnels).mockImplementation(pending);++ const { result } = renderHook(() => useFetchDeviceTunnels(DEVICE), { wrapper });+ await waitFor(() => expect(deviceService.listTunnels).toHaveBeenCalled());++ expect(result.current.data).toBeUndefined();+ expect(result.current.isLoading).toBe(true);+ });++ it('sends one request for readers mounting together', async () => {+ vi.mocked(deviceService.listTunnels).mockResolvedValue([link('one')]);++ const { result } = renderHook(+ () => [useFetchDeviceTunnels(DEVICE), useFetchDeviceTunnels(DEVICE)],+ { wrapper },+ );++ await waitFor(() => expect(result.current[1].data?.length).toBe(1));+ expect(deviceService.listTunnels).toHaveBeenCalledTimes(1);+ });++ it('keeps the persisted ports unconfirmed when the device cannot answer', async () => {+ await deviceListeningPortsResource.storage!.set(+ { queryKey: deviceListeningPortsResource.storageKey(PORTS), scope },+ { data: { ports: [port(5173)], supported: true }, updatedAt: 1 },+ );+ // `null` is the device failing to answer, not "nothing listens".+ vi.mocked(deviceService.listListeningPorts).mockResolvedValue(null as any);++ const { result } = renderHook(() => useFetchDeviceListeningPorts(DEVICE, '/repo'), {+ wrapper,+ });++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(result.current.isConfirmed).toBe(false);+ expect((await storedPorts())?.ports.map((p) => p.port)).toEqual([5173]);+ });++ it('keys ports by device and directory', async () => {+ await deviceListeningPortsResource.storage!.set(+ { queryKey: deviceListeningPortsResource.storageKey(PORTS), scope },+ { data: { ports: [port(5173)], supported: true }, updatedAt: 1 },+ );+ vi.mocked(deviceService.listListeningPorts).mockImplementation(pending);++ const { result } = renderHook(() => useFetchDeviceListeningPorts(DEVICE, '/other'), {+ wrapper,+ });+ await waitFor(() => expect(deviceService.listListeningPorts).toHaveBeenCalled());++ expect(result.current.data).toBeUndefined();+ });++ it('persists a bounded port list', async () => {+ const ports = Array.from({ length: MAX_PERSISTED_PORTS + 20 }, (_, i) => port(1000 + i));+ vi.mocked(deviceService.listListeningPorts).mockResolvedValue({ ports, supported: true });++ const { result } = renderHook(() => useFetchDeviceListeningPorts(DEVICE, '/repo'), {+ wrapper,+ });++ await waitFor(() => expect(result.current.isConfirmed).toBe(true));+ // Memory keeps the whole answer; storage keeps a bounded copy.+ expect(result.current.data?.ports.length).toBe(MAX_PERSISTED_PORTS + 20);+ await waitFor(async () =>+ expect((await storedPorts())?.ports.length).toBe(MAX_PERSISTED_PORTS),+ );+ });+});diff --git a/src/store/device/tunnel/store.ts b/src/store/device/tunnel/store.tsnew file mode 100644index 00000000000..c514601a82f--- /dev/null+++ b/src/store/device/tunnel/store.ts@@ -0,0 +1,133 @@+import type { DeviceListeningPortsResult } from '@lobechat/types';+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import {+ createReplicaSlice,+ createReplicaState,+ recordLens,+ type ReplicaState,+} from '@/libs/replica';+import { deviceService } from '@/services/device';+import { createDevtools } from '@/store/middleware/createDevtools';+import { expose } from '@/store/middleware/expose';++import {+ type DeviceListeningPortsParams,+ deviceListeningPortsResource,+ type DeviceTunnelLink,+ deviceTunnelsKey,+ type DeviceTunnelsParams,+ deviceTunnelsResource,+ toPersistedListeningPorts,+ toStoredTunnelLink,+} from './projection';++export interface DeviceTunnelStoreState {+ /** `deviceListeningPortsKey(params)` → ports at the last probe. */+ deviceListeningPortsMap: Record<string, DeviceListeningPortsResult>;+ deviceListeningPortsReplica: ReplicaState<DeviceListeningPortsResult>;+ /** `deviceTunnelsKey(params)` → the device's tunnel links. */+ deviceTunnelsMap: Record<string, DeviceTunnelLink[]>;+ deviceTunnelsReplica: ReplicaState<DeviceTunnelLink[]>;+}++export const initialDeviceTunnelState: DeviceTunnelStoreState = {+ deviceListeningPortsMap: {},+ deviceListeningPortsReplica: createReplicaState(),+ deviceTunnelsMap: {},+ deviceTunnelsReplica: createReplicaState(),+};++const createSlices = (+ set: (partial: Partial<DeviceTunnelStore>, replace?: false, action?: any) => void,+ get: () => DeviceTunnelStore,+) => ({+ listeningPorts: createReplicaSlice(deviceListeningPortsResource, {+ actionPrefix: 'deviceTunnel/listeningPorts',+ // `null` is the device failing to answer (offline, a client that predates+ // detection): an unknown result, not "nothing listens". Reject it so the+ // persisted ports stay in place — still unconfirmed — instead of being+ // overwritten by an empty answer.+ fetcher: async ({ cwd, deviceId }: DeviceListeningPortsParams) => {+ const result = await deviceService.listListeningPorts({ cwd, deviceId });+ if (!result) throw new Error('Unable to detect listening ports');+ return result;+ },+ get,+ set,+ stateKey: 'deviceListeningPortsReplica',+ toPersisted: toPersistedListeningPorts,+ view: recordLens<DeviceTunnelStore, DeviceListeningPortsResult>('deviceListeningPortsMap'),+ }),+ tunnels: createReplicaSlice(deviceTunnelsResource, {+ actionPrefix: 'deviceTunnel/tunnels',+ fetcher: async ({ deviceId }: DeviceTunnelsParams) =>+ (await deviceService.listTunnels({ deviceId })).map(toStoredTunnelLink),+ get,+ set,+ stateKey: 'deviceTunnelsReplica',+ view: recordLens<DeviceTunnelStore, DeviceTunnelLink[]>('deviceTunnelsMap'),+ }),+});++type DeviceTunnelSlices = ReturnType<typeof createSlices>;++export interface DeviceTunnelStore extends DeviceTunnelStoreState {+ /**+ * Fold a link the server just created into the device's list (memory and+ * storage; clean fields only, never the create response's `openUrl`), and+ * re-read the list in the background — opening the link must not wait on it.+ */+ addTunnelLink: (link: DeviceTunnelLink) => void;+ /** Re-read a device's links now (mounted or not); a failure keeps the list. */+ refreshTunnels: (deviceId: string) => Promise<void>;+ /**+ * Drop a link the server just revoked from the device's list — memory and+ * storage, so a reload cannot paint it back — and re-read the list in the+ * background.+ */+ removeTunnelLink: (deviceId: string, slug: string) => void;+ /** @internal The replica slices; read through the hooks in `tunnelHooks.ts`. */+ slices: DeviceTunnelSlices;+}++const devtools = createDevtools('deviceTunnel');++export const useDeviceTunnelStore = createWithEqualityFn<DeviceTunnelStore>()(+ devtools((set, get) => {+ const slices = createSlices(set, get);++ const refreshTunnels = async (deviceId: string) => {+ try {+ await slices.tunnels.fetch({ deviceId }, { fresh: true });+ } catch {+ // Keep the written list; the next read repairs it.+ }+ };++ return {+ ...initialDeviceTunnelState,+ addTunnelLink: (link) => {+ const key = deviceTunnelsKey({ deviceId: link.deviceId });+ slices.tunnels.update(key, (current) => [+ ...(current ?? []).filter((item) => item.slug !== link.slug),+ toStoredTunnelLink(link),+ ]);+ void refreshTunnels(link.deviceId);+ },+ refreshTunnels,+ removeTunnelLink: (deviceId, slug) => {+ const key = deviceTunnelsKey({ deviceId });+ slices.tunnels.update(key, (current) => (current ?? []).filter((l) => l.slug !== slug));+ void refreshTunnels(deviceId);+ },+ slices,+ };+ }),+ shallow,+);++expose('deviceTunnel', useDeviceTunnelStore);++export const getDeviceTunnelStoreState = () => useDeviceTunnelStore.getState();diff --git a/src/store/device/tunnelHooks.ts b/src/store/device/tunnelHooks.tsindex 3812bb3e9b0..9de7aa4f0b3 100644--- a/src/store/device/tunnelHooks.ts+++ b/src/store/device/tunnelHooks.ts@@ -1,54 +1,91 @@-import type { DeviceListeningPortsResult } from '@lobechat/types';+import { useMemo } from 'react';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { useClientDataSWR } from '@/libs/swr';-import { deviceKeys } from '@/libs/swr/keys';-import { deviceService } from '@/services/device';+import {+ deviceListeningPortsKey,+ type DeviceListeningPortsParams,+ deviceTunnelsKey,+} from './tunnel/projection';+import { useDeviceTunnelStore } from './tunnel/store';-export interface DeviceTunnelLink {- createdAt: number;- deviceId: string;- expiresAt?: number;- hostname: string;- port: number;- slug: string;- url: string;-}+export type { DeviceTunnelLink } from './tunnel/projection';++/**+ * The driver forwards SWR options as given: a failed device read (offline,+ * unreachable gateway) is not retried, like the SWR hooks these replaced.+ */+const noRetry = { shouldRetryOnError: false };+export { getDeviceTunnelStoreState, useDeviceTunnelStore } from './tunnel/store';/*** Tunnel links for one device: a port on that machine, reachable at* `https://<port>--<slug>.lobe.sh/`.*- * Read-only and on demand — no polling. A link's lifetime is measured in days,- * and the list only changes when this UI creates or revokes one, so the local- * mutations below refresh it rather than a background interval.+ * A replica: a reload paints the links persisted last session, and the read+ * confirms them. Read on demand — no polling, no focus revalidation: a link's+ * lifetime is measured in days and the list only changes when this UI creates+ * or revokes one, which writes the result into the replica (`addTunnelLink` /+ * `removeTunnelLink`). The 10s dedupe collapses readers mounting together.*/export const useFetchDeviceTunnels = (deviceId?: string, enabled = true) => {- const workspaceId = useActiveWorkspaceId();+ const params = useMemo(() => (enabled && deviceId ? { deviceId } : null), [enabled, deviceId]);+ const key = params ? deviceTunnelsKey(params) : undefined;+ const data = useDeviceTunnelStore((s) => (key ? s.deviceTunnelsMap[key] : undefined));+ const { error, isHydrated, isValidating, revalidate } = useDeviceTunnelStore+ .getState()+ .slices.tunnels.useSync(params, {+ dedupingInterval: 10 * 1000,+ revalidateOnFocus: false,+ ...noRetry,+ });- return useClientDataSWR<DeviceTunnelLink[]>(- enabled && deviceId ? deviceKeys.tunnels(workspaceId, deviceId) : null,- async () => deviceService.listTunnels({ deviceId }),- { revalidateOnFocus: false },- );+ return {+ data,+ error,+ isLoading: !!params && data === undefined && !error && (!isHydrated || isValidating),+ isValidating,+ mutate: revalidate,+ };};/*** Ports the device is listening on, for one-click exposure. Asked when the* working panel shows (and on focus) rather than polled: detection spawns a* process on the device, and a port that appears later is one click of- * "refresh" away. `null` data means the device couldn't answer.+ * "refresh" away.+ *+ * The persisted ports paint first, but whether they still listen is unknown+ * until the device answers this session: `isConfirmed` is false until then,+ * and the UI must not present a persisted port as running. A device that+ * cannot answer surfaces as `error`, and the persisted ports stay unconfirmed.*/export const useFetchDeviceListeningPorts = (deviceId: string | undefined,cwd: string | undefined,enabled = true,) => {- const workspaceId = useActiveWorkspaceId();-- return useClientDataSWR<DeviceListeningPortsResult | null>(- enabled && deviceId ? deviceKeys.listeningPorts(workspaceId, deviceId, cwd) : null,- async () => deviceService.listListeningPorts({ cwd, deviceId: deviceId! }),- { revalidateOnFocus: true },+ const params = useMemo<DeviceListeningPortsParams | null>(+ () => (enabled && deviceId ? { cwd, deviceId } : null),+ [enabled, deviceId, cwd],);+ const key = params ? deviceListeningPortsKey(params) : undefined;+ const data = useDeviceTunnelStore((s) => (key ? s.deviceListeningPortsMap[key] : undefined));+ const isConfirmed = useDeviceTunnelStore(+ (s) => !!key && s.deviceListeningPortsReplica.entries[key]?.source === 'server',+ );+ const { error, isHydrated, isValidating, revalidate } = useDeviceTunnelStore+ .getState()+ .slices.listeningPorts.useSync(params, {+ dedupingInterval: 10 * 1000,+ revalidateOnFocus: true,+ ...noRetry,+ });++ return {+ data,+ error,+ isConfirmed,+ isLoading: !!params && data === undefined && !error && (!isHydrated || isValidating),+ isValidating,+ mutate: revalidate,+ };};