Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

refactor(desktop): 顶栏与侧栏 PR 统一到 PrRefsContext 单一缓存

Dashae6c5bbc7a36
diff --git a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
index 77c5201269..76619e1c16 100644
--- a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
+++ b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
@@ -26,11 +26,7 @@ import {
} from 'react';
import type { PrStatusResult, SessionPrRef } from '@/lib/gitContext.types';
-import {
- prStatusKey,
- MAX_STATUS_QUERIES,
- PR_STATUS_REFRESH_INTERVAL_MS,
-} from '@/hooks/useSessionGitContext';
+import { prStatusKey, MAX_STATUS_QUERIES, PR_STATUS_REFRESH_INTERVAL_MS } from '@/lib/prStatus';
import { useAuth } from '@/contexts/AuthContext';
import { createLogger } from '@/lib/logger';
@@ -107,14 +103,29 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
const remoteRefsInFlight = useRef(new Set<string>());
const remoteRefsFetchedAt = useRef(new Map<string, number>());
const remoteDeviceBySession = useRef(new Map<string, string>());
+ // 正在展示 PR 信息的会话(sessionId → {deviceId?, count})。顶栏(打开的会话)
+ // 与侧栏行(勾选 pr)都注册到这里;引用计数支持同一会话多处并存。refs 异步
+ // 到位(全量加载 / 远程补拉 / 引用变化推送)后,对注册中的会话立即补状态查询。
+ const prConsumers = useRef(new Map<string, { deviceId?: string; count: number }>());
+
+ // owner 边界判定:首挂载**不清**——React 子 effect 先于父 effect 运行,行组件的
+ // 注册与远程簿记(remoteDeviceBySession 等)此时已写入,首挂载清空会把它们连同
+ // 全量加载的合并保护一起打掉(实测:状态查询错落到本地路径)。只有 owner 真正
+ // 切换(上一个值存在且不同)才需要丢弃上一账号的缓存。
+ const prevOwnerRef = useRef<string | null | undefined>(undefined);
useEffect(() => {
- // owner 切换边界:先清掉上一 owner 的缓存,无 owner 时保持空、不发 IPC。
- setRefsBySession(new Map());
- setStatuses(new Map());
- remoteRefsInFlight.current.clear();
- remoteRefsFetchedAt.current.clear();
- remoteDeviceBySession.current.clear();
+ const prevOwner = prevOwnerRef.current;
+ prevOwnerRef.current = dataOwnerId;
+ if (prevOwner !== undefined && prevOwner !== dataOwnerId) {
+ // owner 切换边界:清掉上一 owner 的缓存与远程簿记(prConsumers 保留——
+ // 行组件仍挂着,新 owner 下由周期刷新按注册表重建缓存)。
+ setRefsBySession(new Map());
+ setStatuses(new Map());
+ remoteRefsInFlight.current.clear();
+ remoteRefsFetchedAt.current.clear();
+ remoteDeviceBySession.current.clear();
+ }
if (dataOwnerId === null) return;
let cancelled = false;
@@ -134,7 +145,22 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
scheduleRetry();
return;
}
- setRefsBySession(groupBySession(rows));
+ // 合并而非整体替换:listAllPrRefs 只覆盖本地会话;远程(device-link)会话
+ // 的条目可能已先一步拉到,整体替换会把它们冲掉(启动时序竞态)。
+ const grouped = groupBySession(rows);
+ setRefsBySession((prev) => {
+ const next = new Map(grouped);
+ for (const [sid, refs] of prev) {
+ if (remoteDeviceBySession.current.has(sid) && !next.has(sid)) next.set(sid, refs);
+ }
+ return next;
+ });
+ // 已注册消费者(顶栏/侧栏正在展示的会话)拿到引用后立即补状态,
+ // 不等 90s 周期——覆盖「先注册、后加载完成」的启动时序。
+ for (const [sid] of prConsumers.current) {
+ const refs = grouped.get(sid);
+ if (refs) fetchStatusesForRefs(sid, refs);
+ }
} catch (err) {
log.warn('pr refs load failed, will retry', String(err));
scheduleRetry();
@@ -153,6 +179,11 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
else next.delete(data.sessionId);
return next;
});
+ // 该会话有消费者在展示(顶栏/侧栏徽标)→ 引用变化后立即刷状态,
+ // 不等 90s 周期(对齐顶栏旧行为:引用变化即时补状态)。
+ if (refs.length > 0 && prConsumers.current.has(data.sessionId)) {
+ fetchStatusesForRefs(data.sessionId, refs);
+ }
} catch (err) {
log.warn('pr refs refresh failed', String(err));
}
@@ -166,24 +197,29 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
};
}, [dataOwnerId]);
- // 回调身份稳定(空闭包依赖):refs 经 refsRef 读,statuses 经函数式 setState 写。
- // 远程会话(remoteDeviceBySession 命中)状态改走 device-link 通道——被控端持有
- // gh token,且 main 侧按该会话已提取的引用过滤查询(git-context/ipc.ts 的
- // fail-closed 逻辑),与聊天顶栏同一条安全路径。
- const fetchStatusesForSession = useRef((sessionId: string) => {
- const refs = refsRef.current.get(sessionId)?.slice(0, MAX_STATUS_QUERIES);
- if (!refs || refs.length === 0) return;
+ // 回调身份稳定(空闭包依赖):refs 显式传入或经 refsRef 读,statuses 经函数式
+ // setState 写。远程会话(remoteDeviceBySession 命中)状态改走 device-link 通道
+ // ——被控端持有 gh token,且 main 侧按该会话已提取的引用过滤查询
+ // (git-context/ipc.ts 的 fail-closed 逻辑),与聊天顶栏同一条安全路径。
+ const fetchStatusesForRefs = useRef((sessionId: string, refsInput: readonly SessionPrRef[]) => {
+ const refs = refsInput.slice(0, MAX_STATUS_QUERIES);
+ if (refs.length === 0) return;
if (inFlightSessions.current.has(sessionId)) return;
inFlightSessions.current.add(sessionId);
void (async () => {
try {
const queries = refs.map((r) => ({ owner: r.owner, repo: r.repo, prNumber: r.prNumber }));
- const deviceId = remoteDeviceBySession.current.get(sessionId);
+ // 远程路由的 deviceId 兜底顺序:簿记表 → 消费者注册表(owner 切换清簿记后,
+ // 注册表仍保有 deviceId,避免远程会话错落到本机查询)。
+ const deviceId =
+ remoteDeviceBySession.current.get(sessionId) ??
+ prConsumers.current.get(sessionId)?.deviceId;
const results = deviceId
? ((await window.electronAPI.deviceLink.invoke(deviceId, 'git-context:pr-status', [
{ sessionId, queries },
])) as PrStatusResult[])
: await window.electronAPI.gitContext.getPrStatuses(queries);
+ if (!Array.isArray(results)) return;
setStatuses((prev) => {
const next = new Map(prev);
for (const r of results) next.set(prStatusKey(r), r);
@@ -197,6 +233,10 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
})();
}).current;
+ const fetchStatusesForSession = useRef((sessionId: string) => {
+ fetchStatusesForRefs(sessionId, refsRef.current.get(sessionId) ?? []);
+ }).current;
+
// 远程会话 PR 引用按需拉取(回调身份稳定)。结果进共享 refs 映射,渲染路径
// (usePrRefsForSession)对本地/远程一视同仁。空结果同样写入 TTL 时间戳,
// 但**不是终态**:下个周期重查(远端新增 PR / 短暂竞态都靠这条自愈)。
@@ -224,6 +264,11 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
else next.delete(sessionId);
return next;
});
+ // 该会话仍有消费者在展示 → 引用到位后立即补状态,不等 90s 周期
+ // (顶栏没有徽标挂载 effect,只读缓存,必须由这里主动触发)。
+ if (refs.length > 0 && prConsumers.current.has(sessionId)) {
+ fetchStatusesForRefs(sessionId, refs);
+ }
} catch (err) {
// 断链/超时:不写时间戳,下个刷新周期(或行重挂载)立即重试。
log.warn('remote pr refs fetch failed', String(err));
@@ -233,10 +278,6 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
})();
}).current;
- // 正在展示 PR 信息的行(sessionId → {deviceId?, count}),引用计数支持同一
- // 会话同时出现在置顶与主列表。注册即拉一次;周期/聚焦刷新遍历本表。
- const prConsumers = useRef(new Map<string, { deviceId?: string; count: number }>());
-
const refreshConsumer = useRef((sessionId: string, deviceId?: string) => {
// 远程行:引用可能还没拉到(或上次失败)——先补引用,再查状态。
// fetchRefsForRemoteSession 成功后幂等,fetchStatusesForSession 无引用时早退。
diff --git a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
index c52fef79d2..4f3cab3a7d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
@@ -25,11 +25,8 @@ import { Tooltip } from '@/components/ui/tooltip';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import type { Session } from '@/lib/ccAgent.types';
import type { PrStatusKind, PrStatusResult, SessionPrRef } from '@/lib/gitContext.types';
-import {
- useSessionGitContext,
- prStatusKey,
- MAX_STATUS_QUERIES,
-} from '@/hooks/useSessionGitContext';
+import { useSessionGitContext } from '@/hooks/useSessionGitContext';
+import { prStatusKey, MAX_STATUS_QUERIES } from '@/lib/prStatus';
import { PR_STATUS_COLOR, PR_STATUS_ICON, pickBranchLabel } from './gitContextPrVisuals';
export function GitContextBadge({ session }: { session: Session }) {
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
index 87904e5502..79b3ce1ead 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
@@ -34,7 +34,7 @@ import { cn } from '@/lib/utils';
import type { Session } from '@/lib/ccAgent.types';
import type { SessionPrRef } from '@/lib/gitContext.types';
import { formatMoney, formatUsd } from '@/lib/usageFormat';
-import { prStatusKey } from '@/hooks/useSessionGitContext';
+import { prStatusKey } from '@/lib/prStatus';
import { usePrStatuses } from '@/contexts/PrRefsContext';
import { PR_STATUS_COLOR } from '../gitContextPrVisuals';
import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
index 8751fec20b..2aefef6a2a 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
@@ -21,7 +21,7 @@ import { useEffect, useState, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { Tooltip } from '@/components/ui/tooltip';
import type { PrStatusResult, SessionPrRef } from '@/lib/gitContext.types';
-import { prStatusKey, MAX_STATUS_QUERIES } from '@/hooks/useSessionGitContext';
+import { prStatusKey, MAX_STATUS_QUERIES } from '@/lib/prStatus';
import { usePrStatuses } from '@/contexts/PrRefsContext';
import { PR_STATUS_COLOR, PR_STATUS_ICON } from '../gitContextPrVisuals';
import { formatSidebarFutureTime } from '../lib/formatSidebarTime';
@@ -89,33 +89,33 @@ function PrTooltip({
// 独立 Provider + delayDuration=0:hover 立即弹出,不吃 sidebar 顶层 Provider
// 的 500ms 默认延迟。skipDelayDuration 也归零,行间移动同样无跳变。
<Tooltip.Provider delayDuration={0} skipDelayDuration={0}>
- <Tooltip.Root
- onOpenChange={(open) => {
- if (open) fetchStatusesForSession(sessionId);
- }}
- >
- <Tooltip.Trigger
- asChild
- // PR tip 是 sidebar 密集列表里的 hover-only 信息。SessionItem 本身可聚焦,
- // 窗口重新 focus 时浏览器会把焦点还给它;阻止 Radix 的 focus-open,避免无 hover 复活。
- onFocus={(event) => event.preventDefault()}
+ <Tooltip.Root
+ onOpenChange={(open) => {
+ if (open) fetchStatusesForSession(sessionId);
+ }}
>
- {children}
- </Tooltip.Trigger>
- <Tooltip.Content
- side="right"
- align="start"
- sideOffset={8}
- variant="mono"
- className={CONTENT_SURFACE_CLASS}
- >
- <div className="flex flex-col gap-1">
- {prRefs.slice(0, MAX_STATUS_QUERIES).map((ref) => (
- <PrLine key={ref.id} prRef={ref} status={statuses.get(prStatusKey(ref))} />
- ))}
- </div>
- </Tooltip.Content>
- </Tooltip.Root>
+ <Tooltip.Trigger
+ asChild
+ // PR tip 是 sidebar 密集列表里的 hover-only 信息。SessionItem 本身可聚焦,
+ // 窗口重新 focus 时浏览器会把焦点还给它;阻止 Radix 的 focus-open,避免无 hover 复活。
+ onFocus={(event) => event.preventDefault()}
+ >
+ {children}
+ </Tooltip.Trigger>
+ <Tooltip.Content
+ side="right"
+ align="start"
+ sideOffset={8}
+ variant="mono"
+ className={CONTENT_SURFACE_CLASS}
+ >
+ <div className="flex flex-col gap-1">
+ {prRefs.slice(0, MAX_STATUS_QUERIES).map((ref) => (
+ <PrLine key={ref.id} prRef={ref} status={statuses.get(prStatusKey(ref))} />
+ ))}
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Root>
</Tooltip.Provider>
);
}
@@ -129,13 +129,7 @@ function PrTooltip({
* 拉到的 nextFireAt 用一次性 formatSidebarFutureTime 转成 "N 分钟后运行",不做秒级 tick
* (tooltip 通常只停留几秒,静态文案够用)。
*/
-function AutomationTooltip({
- sessionId,
- children,
-}: {
- sessionId: string;
- children: ReactNode;
-}) {
+function AutomationTooltip({ sessionId, children }: { sessionId: string; children: ReactNode }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [runs, setRuns] = useState<ScheduleSidebarIndexRun[] | null>(null);
@@ -155,15 +149,15 @@ function AutomationTooltip({
}, [open, runs]);
const hit = runs?.find((r) => r.sessionId === sessionId) ?? null;
- const countdownText = hit && hit.scheduleStatus === 'active' && typeof hit.nextFireAt === 'number'
- ? formatSidebarFutureTime(hit.nextFireAt, t)
- : '';
+ const countdownText =
+ hit && hit.scheduleStatus === 'active' && typeof hit.nextFireAt === 'number'
+ ? formatSidebarFutureTime(hit.nextFireAt, t)
+ : '';
const isStopped = hit?.scheduleStatus === 'paused' || hit?.scheduleStatus === 'expired';
const stoppedText = isStopped ? t('ccAgent.sidebar.automationGroup.stopped') : '';
const runCount = hit ? runs!.filter((r) => r.scheduleId === hit.scheduleId).length : 0;
- const runCountText = runCount > 0
- ? t('ccAgent.sidebar.automationGroup.runCount', { count: runCount })
- : '';
+ const runCountText =
+ runCount > 0 ? t('ccAgent.sidebar.automationGroup.runCount', { count: runCount }) : '';
const hasContent = countdownText || stoppedText || runCountText;
return (
@@ -186,13 +180,7 @@ function AutomationTooltip({
);
}
-function SourceTooltip({
- sourceLabel,
- children,
-}: {
- sourceLabel: string;
- children: ReactNode;
-}) {
+function SourceTooltip({ sourceLabel, children }: { sourceLabel: string; children: ReactNode }) {
return (
// 独立 Provider + delayDuration=0:与 PrTooltip 同规,hover 立即弹出。
<Tooltip.Provider delayDuration={0} skipDelayDuration={0}>
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.ts
index 24188077af..84c6d7dffa 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useSessionGitContext.remote.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
+import { createElement, type ReactNode } from 'react';
import { renderHook, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -11,8 +12,17 @@ vi.mock('@/contexts/WorktreeContext', () => ({
vi.mock('@/features/device-link/stickySessionOrigin', () => ({
getStickySessionDeviceId: () => undefined,
}));
+// PR 缓存统一后 hook 消费 PrRefsProvider;provider 需要 owner id 才开始加载。
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ dataOwnerId: 'owner-1' }),
+}));
import { useSessionGitContext } from '../useSessionGitContext';
+import { PrRefsProvider } from '@/contexts/PrRefsContext';
+
+/** 统一管线经 PrRefsProvider 拉取 PR;hook 测试统一套一层 provider。 */
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(PrRefsProvider, null, children);
const sessionBase: Session = {
id: 'session-1',
@@ -47,6 +57,8 @@ function makeGitContext() {
unwatch: vi.fn().mockResolvedValue(undefined),
onChanged: vi.fn(() => () => undefined),
listPrRefs: vi.fn(),
+ // PrRefsProvider 挂载即全量加载本地引用(统一缓存管线)。
+ listAllPrRefs: vi.fn().mockResolvedValue([]),
getPrStatuses: vi.fn(),
onPrRefsChanged: vi.fn(() => () => undefined),
};
@@ -72,7 +84,7 @@ describe('useSessionGitContext remote routing', () => {
} as never;
const session = { ...sessionBase, remoteHostId: 'ssh-1' };
- const { result, unmount } = renderHook(() => useSessionGitContext(session));
+ const { result, unmount } = renderHook(() => useSessionGitContext(session), { wrapper });
await waitFor(() => expect(result.current.head?.branch).toBe('feature/ssh'));
expect(gitContext.getForSession).toHaveBeenCalledWith({
@@ -83,7 +95,8 @@ describe('useSessionGitContext remote routing', () => {
});
expect(gitContext.onChanged).not.toHaveBeenCalled();
expect(gitContext.watch).not.toHaveBeenCalled();
- expect(gitContext.listPrRefs).toHaveBeenCalledWith('session-1');
+ // SSH 会话的引用在本地 db,由统一缓存的全量加载覆盖(不再逐会话查询)。
+ expect(gitContext.listAllPrRefs).toHaveBeenCalled();
unmount();
expect(gitContext.unwatch).not.toHaveBeenCalled();
});
@@ -135,24 +148,25 @@ describe('useSessionGitContext remote routing', () => {
} as never;
const session = { ...sessionBase, deviceLinkDeviceId: 'device-1', remoteHostId: 'ssh-1' };
- const { result, unmount } = renderHook(() => useSessionGitContext(session));
+ const { result, unmount } = renderHook(() => useSessionGitContext(session), { wrapper });
await waitFor(() => {
expect(result.current.head?.branch).toBe('feature/device');
expect(result.current.prRefs).toHaveLength(1);
expect(result.current.prStatuses.size).toBe(1);
});
- expect(invoke).toHaveBeenCalledWith(
- 'device-1',
- 'git-context:get-for-session',
- [expect.objectContaining({ sessionId: 'session-1', remoteHostId: 'ssh-1' })],
- );
+ expect(invoke).toHaveBeenCalledWith('device-1', 'git-context:get-for-session', [
+ expect.objectContaining({ sessionId: 'session-1', remoteHostId: 'ssh-1' }),
+ ]);
expect(invoke).toHaveBeenCalledWith('device-1', 'git-context:pr-refs:list', ['session-1']);
expect(invoke).toHaveBeenCalledWith('device-1', 'git-context:pr-status', [
{ sessionId: 'session-1', queries: [{ owner: 'octo', repo: 'repo', prNumber: 42 }] },
]);
+ // 被控端引用/状态不得走本机 gitContext 直查(mockRejected 的三个方法未被吞错误)。
expect(gitContext.onChanged).not.toHaveBeenCalled();
- expect(gitContext.onPrRefsChanged).not.toHaveBeenCalled();
+ // 注:onPrRefsChanged 由 PrRefsProvider 全局订阅一次(本地会话增量刷新),
+ // 不再作为「device-link 不订阅本地事件」的判据;device-link 的隔离由
+ // 「refs/状态经 deviceLink.invoke 而非本机 gitContext」两条断言保证。
unmount();
expect(gitContext.watch).not.toHaveBeenCalled();
expect(gitContext.unwatch).not.toHaveBeenCalled();
@@ -206,7 +220,7 @@ describe('useSessionGitContext remote routing', () => {
const first = { ...sessionBase, deviceLinkDeviceId: 'device-1' };
const { result, rerender, unmount } = renderHook(
({ session }: { session: Session }) => useSessionGitContext(session),
- { initialProps: { session: first } },
+ { initialProps: { session: first }, wrapper },
);
await waitFor(() => {
expect(result.current.head?.branch).toBe('feature/device');
diff --git a/apps/desktop/src/renderer/hooks/useSessionGitContext.ts b/apps/desktop/src/renderer/hooks/useSessionGitContext.ts
index 2cd83efbed..65580b0c1e 100644
--- a/apps/desktop/src/renderer/hooks/useSessionGitContext.ts
+++ b/apps/desktop/src/renderer/hooks/useSessionGitContext.ts
@@ -8,18 +8,17 @@
* 拿到 workdir 后 gitContext.watch 开启 HEAD 监听;对话中途换 worktree 靠
* focus + 周期 tick 再解析并切换监听目标。SSH / device-link 会话在真实执行端
* 查询,不在控制端注册本地 watcher,改用 focus + 周期 tick。
- * - PR 引用:listPrRefs(sessionId) + git-context:pr-refs-changed 推送刷新(本机/SSH);
- * device-link 使用被控端查询 + focus/周期 polling,避免把控制端本地事件
- * 错当成被控端事件。
- * - PR 状态:引用变化后对前 MAX_STATUS_QUERIES 条批量查一次(main 60s TTL 缓存,
- * 重复查询便宜);未配 PAT 时返回 no-token,UI 显示 PR 号不显示状态。结果含
- * PR 源分支 branch:遥测拿不到本地目录时,徽标用它兜底显示分支。
+ * - PR 引用与状态:**消费 PrRefsContext 的共享缓存**(2026-08-12 统一:此前顶栏
+ * 自持一份 refs/状态与拉取管线,与侧栏徽标各查各的、显示还会不同步)。本 hook
+ * 只向共享缓存注册消费者(registerPrConsumer),拉取、周期/聚焦刷新、device-link
+ * 远程路由、失败自愈全部由 PrRefsContext 单点负责;返回值按当前会话过滤,
+ * 语义与旧实现一致(切会话/断链即空)。
*
* 约束:dialogue 会话(workspaceKind !== 'project')不启用——workingDir 是对话自有目录,
* 分支语义无意义。SSH 与 device-link 远程会话则把查询发往真实执行端。
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import type { Session } from '@/lib/ccAgent.types';
import type {
@@ -31,22 +30,15 @@ import type {
PrStatusResult,
} from '@/lib/gitContext.types';
import { useWorktreeForSession } from '@/contexts/WorktreeContext';
+import { usePrActions, usePrRefsForSession, usePrStatuses } from '@/contexts/PrRefsContext';
import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
+import { MAX_STATUS_QUERIES, PR_STATUS_REFRESH_INTERVAL_MS, prStatusKey } from '@/lib/prStatus';
import { createLogger } from '@/lib/logger';
const log = createLogger('useSessionGitContext');
-/** 只对最近的几条 PR 引用查状态(徽标也只展示这几条)。 */
-export const MAX_STATUS_QUERIES = 3;
-
-/**
- * PR 状态周期刷新间隔。GitHub 侧 open→merged / review 评论 resolve 这类变化
- * 不会产生本地 pr-refs-changed 事件,长开会话只靠初次加载会一直显示旧状态
- * (review 反馈)。取值刻意 > main 侧 60s TTL,保证每次 tick 都真的打到远端。
- */
-/** PR 状态的兜底刷新周期——聊天顶栏与侧栏徽标(PrRefsContext)共用同一节拍。 */
-export const PR_STATUS_REFRESH_INTERVAL_MS = 90_000;
-const STATUS_REFRESH_INTERVAL_MS = PR_STATUS_REFRESH_INTERVAL_MS;
+// 正本在 lib/prStatus(避免与 PrRefsContext 循环导入);re-export 兼容存量 import 方。
+export { MAX_STATUS_QUERIES, PR_STATUS_REFRESH_INTERVAL_MS, prStatusKey } from '@/lib/prStatus';
/**
* 「对话真实工作目录」再解析间隔。对话中途 agent `cd` 进新 worktree 不产生本地事件,
@@ -56,8 +48,6 @@ const STATUS_REFRESH_INTERVAL_MS = PR_STATUS_REFRESH_INTERVAL_MS;
const DIR_RERESOLVE_INTERVAL_MS = 60_000;
const GET_FOR_SESSION_CHANNEL = 'git-context:get-for-session';
-const PR_REFS_LIST_CHANNEL = 'git-context:pr-refs:list';
-const PR_STATUS_CHANNEL = 'git-context:pr-status';
async function invokeRemoteGitContext<T>(
deviceId: string,
@@ -74,14 +64,10 @@ export interface SessionGitContext {
branchSource: GitContextDirSource;
/** 关联 PR 引用,lastSeenAt 降序。 */
prRefs: SessionPrRef[];
- /** key = `${owner}/${repo}#${prNumber}`(小写 owner/repo)。 */
+ /** key = `${owner}/${repo}#${prNumber}`(小写 owner/repo)。仅含本会话引用的条目。 */
prStatuses: Map<string, PrStatusResult>;
}
-export function prStatusKey(ref: { owner: string; repo: string; prNumber: number }): string {
- return `${ref.owner.toLowerCase()}/${ref.repo.toLowerCase()}#${ref.prNumber}`;
-}
-
const EMPTY: SessionGitContext = {
head: null,
branchSource: null,
@@ -113,8 +99,6 @@ export function useSessionGitContext(session: Session): SessionGitContext {
const [head, setHead] = useState<GitHeadInfo | null>(null);
const [branchSource, setBranchSource] = useState<GitContextDirSource>(null);
- const [prRefs, setPrRefs] = useState<SessionPrRef[]>([]);
- const [prStatuses, setPrStatuses] = useState<Map<string, PrStatusResult>>(new Map());
// ── 分支:getForSession 解析真实工作目录 + 可换目录的 HEAD watch ──
useEffect(() => {
@@ -223,80 +207,30 @@ export function useSessionGitContext(session: Session): SessionGitContext {
worktreePath,
]);
- // ── PR 引用 + 状态 ──
+ // ── PR 引用 + 状态:消费 PrRefsContext 共享缓存(与侧栏徽标同一份)──
+ // 注册消费者即触发拉取;周期/聚焦刷新、device-link 远程路由、失败自愈由
+ // Provider 单点负责。切会话 = 换 key 读缓存(天然隔离,无需清空);断链后
+ // 新会话查询失败 → 缓存无条目 → 返回空,与旧实现的"清空"语义一致。
+ const { registerPrConsumer } = usePrActions();
+ const sharedPrRefs = usePrRefsForSession(sessionId);
+ const { statuses: allStatuses } = usePrStatuses();
useEffect(() => {
- if (!isProjectSession) {
- setPrRefs([]);
- setPrStatuses(new Map());
- return;
+ if (!isProjectSession) return undefined;
+ return registerPrConsumer(sessionId, deviceLinkDeviceId ?? undefined);
+ }, [isProjectSession, sessionId, deviceLinkDeviceId, registerPrConsumer]);
+
+ const prRefs = isProjectSession ? sharedPrRefs : EMPTY.prRefs;
+ // statuses 是全局缓存(含其它会话的 PR);按本会话前 MAX_STATUS_QUERIES 条
+ // 引用过滤,保住旧契约「prStatuses 只含本会话条目」(消费方有 size 判断)。
+ const prStatuses = useMemo(() => {
+ const map = new Map<string, PrStatusResult>();
+ for (const ref of prRefs.slice(0, MAX_STATUS_QUERIES)) {
+ const key = prStatusKey(ref);
+ const status = allStatuses.get(key);
+ if (status) map.set(key, status);
}
- // The header can remain mounted while the selected task changes. Drop the
- // previous task's PR chips before the new remote read settles.
- setPrRefs([]);
- setPrStatuses(new Map());
- let cancelled = false;
- let loadGen = 0;
-
- const loadRefs = async () => {
- const gen = ++loadGen;
- let refsLoaded = false;
- try {
- const refs = isDeviceLinkSession
- ? await invokeRemoteGitContext<SessionPrRef[]>(
- deviceLinkDeviceId as string,
- PR_REFS_LIST_CHANNEL,
- [sessionId],
- )
- : await window.electronAPI.gitContext.listPrRefs(sessionId);
- if (cancelled || gen !== loadGen) return;
- setPrRefs(refs);
- refsLoaded = true;
- const queries = refs.slice(0, MAX_STATUS_QUERIES).map((r) => ({
- owner: r.owner,
- repo: r.repo,
- prNumber: r.prNumber,
- }));
- if (queries.length === 0) {
- setPrStatuses(new Map());
- return;
- }
- const results = isDeviceLinkSession
- ? await invokeRemoteGitContext<PrStatusResult[]>(
- deviceLinkDeviceId as string,
- PR_STATUS_CHANNEL,
- [{ sessionId, queries }],
- )
- : await window.electronAPI.gitContext.getPrStatuses(queries);
- if (cancelled || gen !== loadGen) return;
- setPrStatuses(new Map(results.map((r) => [prStatusKey(r), r])));
- } catch (err) {
- log.warn('pr refs load failed', String(err));
- if (!cancelled && gen === loadGen) {
- if (!refsLoaded) setPrRefs([]);
- setPrStatuses(new Map());
- }
- }
- };
-
- void loadRefs();
- const unsubscribe = isDeviceLinkSession
- ? () => undefined
- : window.electronAPI.gitContext.onPrRefsChanged((data) => {
- if (data.sessionId === sessionId) void loadRefs();
- });
- // 远端状态变化(merged / closed / review resolve)没有本地事件可订阅,
- // 用周期 tick + 窗口聚焦兜底刷新;批量上限 3 条 + main 侧缓存,开销可忽略。
- const interval = setInterval(() => void loadRefs(), STATUS_REFRESH_INTERVAL_MS);
- const onFocus = () => void loadRefs();
- window.addEventListener('focus', onFocus);
-
- return () => {
- cancelled = true;
- unsubscribe();
- clearInterval(interval);
- window.removeEventListener('focus', onFocus);
- };
- }, [sessionId, isProjectSession, isDeviceLinkSession, deviceLinkDeviceId]);
+ return map;
+ }, [prRefs, allStatuses]);
if (!isProjectSession) return EMPTY;
return { head, branchSource, prRefs, prStatuses };
diff --git a/apps/desktop/src/renderer/lib/prStatus.ts b/apps/desktop/src/renderer/lib/prStatus.ts
new file mode 100644
index 0000000000..b7b77fe692
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/prStatus.ts
@@ -0,0 +1,25 @@
+/**
+ * prStatus — PR 状态展示的共享原语(聊天顶栏 + 侧栏徽标共用)。
+ * ---------------------------------------------------------------------------
+ * 单独成模块是为了斩断 useSessionGitContext ↔ PrRefsContext 的循环导入:
+ * 顶栏 hook 消费共享缓存(PrRefsContext),缓存又需要这些常量——常量放任一侧
+ * 都会成环(HMR 下曾以 `PR_STATUS_REFRESH_INTERVAL_MS is not defined` 的 TDZ
+ * 崩溃现形)。本模块零依赖,两边都从这里 import;useSessionGitContext 保留
+ * re-export 兼容存量 import 方。
+ */
+
+/** 只对最近的几条 PR 引用查状态(徽标也只展示这几条)。 */
+export const MAX_STATUS_QUERIES = 3;
+
+/**
+ * PR 状态的兜底刷新周期——聊天顶栏与侧栏徽标(PrRefsContext)共用同一节拍。
+ * GitHub 侧 open→merged / review 评论 resolve 这类变化不会产生本地
+ * pr-refs-changed 事件,只靠初次加载会一直显示旧状态。取值刻意 > main 侧
+ * 60s TTL,保证每次 tick 都真的打到远端。
+ */
+export const PR_STATUS_REFRESH_INTERVAL_MS = 90_000;
+
+/** statuses 缓存的 key:`owner/repo#N`(小写 owner/repo)。 */
+export function prStatusKey(ref: { owner: string; repo: string; prNumber: number }): string {
+ return `${ref.owner.toLowerCase()}/${ref.repo.toLowerCase()}#${ref.prNumber}`;
+}