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。

feat(desktop): PR 徽标在本机 gh 缺失/未登录时点击引导 Agent 安装或登录 (#3877)

Dashc4033acd0791
diff --git a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
index 37b7281891..c18475a598 100644
--- a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts
@@ -150,4 +150,68 @@ describe('createGhCliTokenSource', () => {
expect(await src.probeAvailability()).toBe(false);
expect(execFileFn).toHaveBeenCalledTimes(1);
});
+
+ describe('readTokenDetailed 保留失败原因', () => {
+ function errWith(extra: Record<string, unknown>): Error {
+ return Object.assign(new Error('gh failed'), extra);
+ }
+
+ it('ENOENT → gh-missing;spawn 抛错也归为 gh-missing', async () => {
+ const enoent = createGhCliTokenSource({
+ execFileFn: execMock((_f, cb) => cb(errWith({ code: 'ENOENT' }), '', '')),
+ existsFn: () => false,
+ });
+ expect(await enoent.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-missing' });
+
+ const thrown = createGhCliTokenSource({
+ execFileFn: vi.fn(() => {
+ throw new Error('spawn EACCES');
+ }),
+ existsFn: () => false,
+ });
+ expect(await thrown.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-missing' });
+ });
+
+ it('非零退出(exit 1)与空输出 → gh-not-logged-in', async () => {
+ const exit1 = createGhCliTokenSource({
+ execFileFn: execMock((_f, cb) => cb(errWith({ code: 1 }), '', 'not logged in')),
+ existsFn: () => false,
+ });
+ expect(await exit1.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-not-logged-in' });
+
+ const empty = createGhCliTokenSource({
+ execFileFn: execMock((_f, cb) => cb(null, '\n', '')),
+ existsFn: () => false,
+ });
+ expect(await empty.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-not-logged-in' });
+ });
+
+ it('子进程超时(killed + signal)→ gh-timeout', async () => {
+ const src = createGhCliTokenSource({
+ execFileFn: execMock((_f, cb) => cb(errWith({ killed: true, signal: 'SIGTERM' }), '', '')),
+ existsFn: () => false,
+ });
+ expect(await src.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-timeout' });
+ });
+
+ it('EACCES / ENOEXEC 等 spawn 字符串错误 → gh-exec-failed,不当成未登录', async () => {
+ for (const code of ['EACCES', 'ENOEXEC'] as const) {
+ const src = createGhCliTokenSource({
+ execFileFn: execMock((_f, cb) => cb(errWith({ code }), '', '')),
+ existsFn: () => false,
+ });
+ expect(await src.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-exec-failed' });
+ }
+ });
+
+ it('与 readToken 共享同一份缓存与 in-flight:两种读法交替调用只 spawn 一次', async () => {
+ const execFileFn = execMock((_f, cb) => cb(errWith({ code: 1 }), '', ''));
+ const src = createGhCliTokenSource({ execFileFn, existsFn: () => false });
+ const [detailed, plain] = await Promise.all([src.readTokenDetailed(), src.readToken()]);
+ expect(detailed).toEqual({ ok: false, reason: 'gh-not-logged-in' });
+ expect(plain).toBeNull();
+ expect(await src.readTokenDetailed()).toEqual({ ok: false, reason: 'gh-not-logged-in' });
+ expect(execFileFn).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts
index 1fecab2a2d..5954c46d88 100644
--- a/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextIpcSecurity.test.ts
@@ -34,7 +34,9 @@ describe('git-context remote IPC security contract', () => {
it('fails closed when device-link PR refs lookup is unavailable', () => {
const lookup = ipcSource.indexOf('const refs = await listPrRefs(remoteSessionId);');
const clear = ipcSource.indexOf('return [];', lookup);
- const statusQuery = ipcSource.indexOf('return prStatusService!.getStatuses(parsed);');
+ const statusQuery = ipcSource.indexOf(
+ 'return prStatusService!.getStatuses(parsed, { remote: remoteSessionId !== null });',
+ );
expect(ipcSource).toContain("log.warn('remote PR refs lookup failed (fail closed)'");
expect(lookup).toBeGreaterThanOrEqual(0);
diff --git a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
index f050f31ac1..08205e6c92 100644
--- a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
@@ -1,6 +1,6 @@
/**
* git-context/prStatusService 单测 — 状态映射、TTL 缓存、in-flight 去重、
- * no-token 降级(不缓存)、404/网络错误映射。依赖全注入,零网络零 Electron。
+ * gh 缺失/未登录降级(不缓存,远端归一 no-token)、404/网络错误映射。依赖全注入,零网络零 Electron。
*/
import { describe, it, expect, vi } from 'vitest';
@@ -11,8 +11,10 @@ import {
mapRemoteToStatus,
type PrRemoteState,
} from '../git-context/prStatusService';
+import type { GhCliTokenReadResult } from '../git-context/ghCliTokenSource';
const Q = { owner: 'makecindy', repo: 'cindy', prNumber: 85 };
+const TOKEN_OK = async (): Promise<GhCliTokenReadResult> => ({ ok: true, token: 'ghp_x' });
function remote(partial: Partial<PrRemoteState>): PrRemoteState {
return {
@@ -51,7 +53,7 @@ describe('filterPrStatusQueriesForRefs', () => {
describe('PrStatusService', () => {
it('正常查询返回状态与标题', async () => {
const svc = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr: async () => remote({ merged: true, state: 'closed' }),
});
const [r] = await svc.getStatuses([Q]);
@@ -60,7 +62,7 @@ describe('PrStatusService', () => {
it('PR 源分支(head.ref)透传到结果', async () => {
const svc = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr: async () => remote({ branch: 'fix/voice-input-enter-send' }),
});
expect((await svc.getStatuses([Q]))[0]).toMatchObject({
@@ -71,13 +73,13 @@ describe('PrStatusService', () => {
it('未解决 review thread 数透传;fetch 端缺省时归一为 null', async () => {
const withCount = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr: async () => remote({ unresolved_count: 3 }),
});
expect((await withCount.getStatuses([Q]))[0]).toMatchObject({ ok: true, unresolvedCount: 3 });
const withoutCount = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr: async () => remote({}),
});
expect((await withoutCount.getStatuses([Q]))[0]).toMatchObject({ ok: true, unresolvedCount: null });
@@ -87,7 +89,7 @@ describe('PrStatusService', () => {
let now = 0;
const fetchPr = vi.fn(async () => remote({}));
const svc = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr,
cacheTtlMs: 100,
now: () => now,
@@ -105,7 +107,7 @@ describe('PrStatusService', () => {
const fetchPr = vi.fn(
() => new Promise<PrRemoteState>((res) => (resolveFetch = res)),
);
- const svc = new PrStatusService({ readToken: async () => 'ghp_x', fetchPr });
+ const svc = new PrStatusService({ readToken: TOKEN_OK, fetchPr });
const p1 = svc.getStatuses([Q]);
const p2 = svc.getStatuses([Q]);
// readToken 是 async,等微任务推进到 fetchPr 真正被调用后再放行
@@ -115,24 +117,73 @@ describe('PrStatusService', () => {
expect(fetchPr).toHaveBeenCalledTimes(1);
});
- it('无 token 返回 no-token 且不缓存(配完 PAT 立即生效)', async () => {
- let token: string | null = null;
+ it('gh 未登录返回 gh-not-logged-in 且不缓存(登录完立即生效)', async () => {
+ let read: GhCliTokenReadResult = { ok: false, reason: 'gh-not-logged-in' };
const fetchPr = vi.fn(async () => remote({}));
- const svc = new PrStatusService({ readToken: async () => token, fetchPr });
+ const svc = new PrStatusService({ readToken: async () => read, fetchPr });
const [r1] = await svc.getStatuses([Q]);
- expect(r1).toMatchObject({ ok: false, reason: 'no-token' });
- token = 'ghp_x';
+ expect(r1).toMatchObject({ ok: false, reason: 'gh-not-logged-in' });
+ read = { ok: true, token: 'ghp_x' };
const [r2] = await svc.getStatuses([Q]);
expect(r2).toMatchObject({ ok: true, status: 'open' });
});
+ it('gh 未安装透传 gh-missing;超时 / 执行故障 / readToken 抛错归为 no-token', async () => {
+ const fetchPr = vi.fn(async () => remote({}));
+ const missing = new PrStatusService({
+ readToken: async () => ({ ok: false, reason: 'gh-missing' }),
+ fetchPr,
+ });
+ expect((await missing.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason: 'gh-missing' });
+
+ const timeout = new PrStatusService({
+ readToken: async () => ({ ok: false, reason: 'gh-timeout' }),
+ fetchPr,
+ });
+ expect((await timeout.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason: 'no-token' });
+
+ const execFailed = new PrStatusService({
+ readToken: async () => ({ ok: false, reason: 'gh-exec-failed' }),
+ fetchPr,
+ });
+ expect((await execFailed.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason: 'no-token' });
+
+ const thrown = new PrStatusService({
+ readToken: async () => {
+ throw new Error('boom');
+ },
+ fetchPr,
+ });
+ expect((await thrown.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason: 'no-token' });
+ expect(fetchPr).not.toHaveBeenCalled();
+ });
+
+ it('remote 查询把 gh-missing / gh-not-logged-in 归一为 no-token,其它 reason 不变', async () => {
+ const fetchPr = vi.fn(async () => {
+ throw Object.assign(new Error('nf'), { status: 404 });
+ });
+ for (const reason of ['gh-missing', 'gh-not-logged-in'] as const) {
+ const svc = new PrStatusService({ readToken: async () => ({ ok: false, reason }), fetchPr });
+ expect((await svc.getStatuses([Q], { remote: true }))[0]).toMatchObject({
+ ok: false,
+ reason: 'no-token',
+ });
+ expect((await svc.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason });
+ }
+ const nf = new PrStatusService({ readToken: TOKEN_OK, fetchPr });
+ expect((await nf.getStatuses([Q], { remote: true }))[0]).toMatchObject({
+ ok: false,
+ reason: 'not-found',
+ });
+ });
+
it('fetch-failed 不缓存:瞬时网络错误后下一次查询立即重试', async () => {
let failing = true;
const fetchPr = vi.fn(async () => {
if (failing) throw new Error('ECONNRESET');
return remote({});
});
- const svc = new PrStatusService({ readToken: async () => 'ghp_x', fetchPr });
+ const svc = new PrStatusService({ readToken: TOKEN_OK, fetchPr });
expect((await svc.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason: 'fetch-failed' });
// 网络恢复后,无需等 TTL,下一次查询直接成功
failing = false;
@@ -144,7 +195,7 @@ describe('PrStatusService', () => {
const fetchPr = vi.fn(async () => {
throw Object.assign(new Error('nf'), { status: 404 });
});
- const svc = new PrStatusService({ readToken: async () => 'ghp_x', fetchPr });
+ const svc = new PrStatusService({ readToken: TOKEN_OK, fetchPr });
await svc.getStatuses([Q]);
await svc.getStatuses([Q]);
expect(fetchPr).toHaveBeenCalledTimes(1);
@@ -152,7 +203,7 @@ describe('PrStatusService', () => {
it('404 映射 not-found,其它错误映射 fetch-failed', async () => {
const svc404 = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr: async () => {
throw Object.assign(new Error('nf'), { status: 404 });
},
@@ -160,7 +211,7 @@ describe('PrStatusService', () => {
expect((await svc404.getStatuses([Q]))[0]).toMatchObject({ ok: false, reason: 'not-found' });
const svcNet = new PrStatusService({
- readToken: async () => 'ghp_x',
+ readToken: TOKEN_OK,
fetchPr: async () => {
throw new Error('ECONNRESET');
},
@@ -170,7 +221,7 @@ describe('PrStatusService', () => {
it('批量查询上限 10 条,超出忽略', async () => {
const fetchPr = vi.fn(async () => remote({}));
- const svc = new PrStatusService({ readToken: async () => 'ghp_x', fetchPr });
+ const svc = new PrStatusService({ readToken: TOKEN_OK, fetchPr });
const queries = Array.from({ length: 15 }, (_, i) => ({
owner: 'o',
repo: 'r',
diff --git a/apps/desktop/src/main/git-context/ghCliTokenSource.ts b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
index 95c1fc895d..afaa4bf4e3 100644
--- a/apps/desktop/src/main/git-context/ghCliTokenSource.ts
+++ b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
@@ -27,10 +27,7 @@ const log = createLogger('git-context/gh-cli');
const GH_CANDIDATES: Record<string, string[]> = {
darwin: ['/opt/homebrew/bin/gh', '/usr/local/bin/gh'],
linux: ['/usr/bin/gh', '/usr/local/bin/gh', '/home/linuxbrew/.linuxbrew/bin/gh'],
- win32: [
- 'C:\\Program Files\\GitHub CLI\\gh.exe',
- 'C:\\Program Files (x86)\\GitHub CLI\\gh.exe',
- ],
+ win32: ['C:\\Program Files\\GitHub CLI\\gh.exe', 'C:\\Program Files (x86)\\GitHub CLI\\gh.exe'],
};
const DEFAULT_CACHE_TTL_MS = 5 * 60_000;
@@ -53,13 +50,41 @@ export interface GhCliTokenSourceDeps {
now?: () => number;
}
+/**
+ * 拿不到 token 的原因。UI 按它决定引导动作:
+ * gh-missing = 二进制不存在(ENOENT / spawn 抛错)→ 引导安装
+ * gh-not-logged-in = gh 在但 `auth token` 非零退出或输出为空 → 引导登录
+ * gh-timeout = 子进程超时 → 用户做不了什么,当瞬时失败
+ * gh-exec-failed = 文件在但跑不起来(EACCES / ENOEXEC 等)→ 同超时,不引导
+ */
+export type GhCliTokenUnavailableReason =
+ 'gh-missing' | 'gh-not-logged-in' | 'gh-timeout' | 'gh-exec-failed';
+
+export type GhCliTokenReadResult =
+ { ok: true; token: string } | { ok: false; reason: GhCliTokenUnavailableReason };
+
export interface GhCliTokenSource {
/** 返回本地 gh 登录 token;未安装 / 未登录 / 超时返回 null,永不抛错。 */
readToken(): Promise<string | null>;
+ /** 同 readToken,但保留拿不到 token 的原因(共享同一份缓存)。永不抛错。 */
+ readTokenDetailed(): Promise<GhCliTokenReadResult>;
/** 只探测 github.com 登录可用性,不读取或缓存 token。 */
probeAvailability(): Promise<boolean>;
}
+/**
+ * execFile 回调 err 的分类。
+ * Node:子进程非零退出时 `code` 是数字;spawn/exec 失败时 `code` 是字符串
+ * (ENOENT / EACCES / ENOEXEC …)。只有真正跑起来再失败才算未登录。
+ */
+function classifyExecError(err: Error): GhCliTokenUnavailableReason {
+ const e = err as Error & { code?: unknown; killed?: boolean; signal?: unknown };
+ if (e.code === 'ENOENT') return 'gh-missing';
+ if (e.killed && typeof e.signal === 'string') return 'gh-timeout';
+ if (typeof e.code === 'string') return 'gh-exec-failed';
+ return 'gh-not-logged-in';
+}
+
export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTokenSource {
const execFileFn = deps.execFileFn ?? execFile;
const existsFn = deps.existsFn ?? fs.existsSync;
@@ -68,8 +93,8 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
const negativeTtl = deps.negativeCacheTtlMs ?? DEFAULT_NEGATIVE_CACHE_TTL_MS;
const now = deps.now ?? Date.now;
- let cached: { token: string | null; expiresAt: number } | null = null;
- let inFlight: Promise<string | null> | null = null;
+ let cached: { result: GhCliTokenReadResult; expiresAt: number } | null = null;
+ let inFlight: Promise<GhCliTokenReadResult> | null = null;
function resolveGhBinary(): string {
for (const candidate of GH_CANDIDATES[platform] ?? []) {
@@ -78,27 +103,44 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
return platform === 'win32' ? 'gh.exe' : 'gh';
}
- async function fetchToken(): Promise<string | null> {
+ async function fetchToken(): Promise<GhCliTokenReadResult> {
const bin = resolveGhBinary();
- return new Promise<string | null>((resolve) => {
+ return new Promise<GhCliTokenReadResult>((resolve) => {
try {
execFileFn(bin, ['auth', 'token'], { timeout: GH_TIMEOUT_MS }, (err, stdout) => {
if (err) {
- // 未安装(ENOENT)/ 未登录(exit 1)/ 超时都归一为 null,只 debug 级记录。
- log.debug('gh auth token unavailable', { bin, err: String(err) });
- resolve(null);
+ // 失败只 debug 级记录;原因分类留给 UI 决定引导动作。
+ const reason = classifyExecError(err);
+ log.debug('gh auth token unavailable', { bin, reason, err: String(err) });
+ resolve({ ok: false, reason });
return;
}
const token = stdout.trim();
- resolve(token.length > 0 ? token : null);
+ resolve(
+ token.length > 0 ? { ok: true, token } : { ok: false, reason: 'gh-not-logged-in' },
+ );
});
} catch (err) {
log.debug('gh spawn threw', { err: String(err) });
- resolve(null);
+ resolve({ ok: false, reason: 'gh-missing' });
}
});
}
+ async function readTokenDetailed(): Promise<GhCliTokenReadResult> {
+ if (cached && cached.expiresAt > now()) return cached.result;
+ if (inFlight) return inFlight;
+ inFlight = fetchToken()
+ .then((result) => {
+ cached = { result, expiresAt: now() + (result.ok ? ttl : negativeTtl) };
+ return result;
+ })
+ .finally(() => {
+ inFlight = null;
+ });
+ return inFlight;
+ }
+
async function probeAvailability(): Promise<boolean> {
const bin = resolveGhBinary();
return new Promise<boolean>((resolve) => {
@@ -118,18 +160,10 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
return {
probeAvailability,
+ readTokenDetailed,
async readToken(): Promise<string | null> {
- if (cached && cached.expiresAt > now()) return cached.token;
- if (inFlight) return inFlight;
- inFlight = fetchToken()
- .then((token) => {
- cached = { token, expiresAt: now() + (token ? ttl : negativeTtl) };
- return token;
- })
- .finally(() => {
- inFlight = null;
- });
- return inFlight;
+ const result = await readTokenDetailed();
+ return result.ok ? result.token : null;
},
};
}
diff --git a/apps/desktop/src/main/git-context/ipc.ts b/apps/desktop/src/main/git-context/ipc.ts
index 56738f1e93..30efb540d6 100644
--- a/apps/desktop/src/main/git-context/ipc.ts
+++ b/apps/desktop/src/main/git-context/ipc.ts
@@ -14,8 +14,8 @@
* git-context:pr-refs-changed { sessionId }
*
* GitHub token 只用本地 gh CLI 登录态(`gh auth token`,零配置)——agent 干活
- * 本来就靠 gh,凭证天然就有;未登录时降级 no-token,UI 提示让 agent 跑一次
- * gh auth login 即可。不做 app 级 PAT 绑定(设计收敛,见 PR #94 讨论)。
+ * 本来就靠 gh,凭证天然就有;拿不到时按原因降级 gh-missing / gh-not-logged-in,
+ * 徽标点击引导 agent 安装或登录。不做 app 级 PAT 绑定(设计收敛,见 PR #94 讨论)。
*/
import { BrowserWindow, ipcMain } from 'electron';
@@ -88,8 +88,8 @@ function broadcastToAllWindows(channel: string, payload: unknown): void {
/** gh CLI 登录态来源(进程内共享单例,内置 5min 正 / 30s 负缓存)。 */
const ghCliTokenSource = getSharedGhCliTokenSource();
-async function readGithubToken(): Promise<string | null> {
- return ghCliTokenSource.readToken();
+async function readGithubToken() {
+ return ghCliTokenSource.readTokenDetailed();
}
/** GraphQL 查未解决 review thread 数(REST 不暴露 isResolved)。上限 100。 */
@@ -323,7 +323,7 @@ export function registerGitContextIpc(): void {
return [];
}
}
- return prStatusService!.getStatuses(parsed);
+ return prStatusService!.getStatuses(parsed, { remote: remoteSessionId !== null });
});
}
diff --git a/apps/desktop/src/main/git-context/prStatusService.ts b/apps/desktop/src/main/git-context/prStatusService.ts
index 1afefb986d..8d3aefbe19 100644
--- a/apps/desktop/src/main/git-context/prStatusService.ts
+++ b/apps/desktop/src/main/git-context/prStatusService.ts
@@ -8,12 +8,16 @@
* 设计约束:
* - 状态是易变远端数据,**不落库**;60s TTL 内存缓存 + in-flight 去重,
* 防止徽标重渲染打爆 API(PAT 限额 5000 req/h)。
- * - 未配置 GitHub PAT 时优雅降级:返回 'no-token',renderer 只显示 PR 号
- * 不显示状态点(不要拿匿名额度 60 req/h 去碰运气,很快会 403 连号都查不了)。
+ * - 拿不到 GitHub token 时优雅降级:按 gh CLI 的失败原因返回
+ * 'gh-missing' / 'gh-not-logged-in',renderer 据此把徽标点击变成引导动作;
+ * 只显示 PR 号不显示状态点(不要拿匿名额度 60 req/h 去碰运气,很快会 403
+ * 连号都查不了)。device-link 远端查询统一归为 'no-token':远端控制器不该
+ * 指导被控机装 gh 或登录。
* - 依赖(token 读取 / PR 查询)构造时注入,单测不碰网络与 Electron。
*/
import { createLogger } from '../logger.js';
+import type { GhCliTokenReadResult } from './ghCliTokenSource.js';
const log = createLogger('git-context/pr-status');
@@ -61,10 +65,20 @@ export type PrStatusResult =
owner: string;
repo: string;
prNumber: number;
- /** no-token = 未配 PAT;not-found = PR 不存在/无权限;fetch-failed = 网络等其它错误。 */
- reason: 'no-token' | 'not-found' | 'fetch-failed';
+ reason: PrStatusFailureReason;
};
+/**
+ * 查询失败原因:
+ * gh-missing = 本机没有 gh CLI(UI:点击引导 Agent 安装并登录)
+ * gh-not-logged-in = gh 在但未登录 github.com(UI:点击引导 Agent 登录)
+ * no-token = 拿不到 token 但不告诉原因——device-link 远端查询、或 gh 子进程超时
+ * not-found = PR 不存在 / 无权限(404)
+ * fetch-failed = 网络等其它错误
+ */
+export type PrStatusFailureReason =
+ 'gh-missing' | 'gh-not-logged-in' | 'no-token' | 'not-found' | 'fetch-failed';
+
/** 单条 PR 的远端原始字段(github-client GithubPullRequest 的子集 + thread 统计)。 */
export interface PrRemoteState {
state: 'open' | 'closed';
@@ -80,8 +94,8 @@ export interface PrRemoteState {
}
export interface PrStatusServiceDeps {
- /** 读当前 GitHub PAT;null = 未配置。 */
- readToken: () => Promise<string | null>;
+ /** 读本机 gh 登录 token,拿不到时带原因(见 ghCliTokenSource.readTokenDetailed)。 */
+ readToken: () => Promise<GhCliTokenReadResult>;
/** 查单条 PR。404 等错误直接抛(带 status 的错误对象)。 */
fetchPr: (token: string, q: PrStatusQuery) => Promise<PrRemoteState>;
/** 缓存 TTL,默认 60s。测试可注小值。 */
@@ -120,10 +134,23 @@ export class PrStatusService {
this.now = deps.now ?? Date.now;
}
- /** 批量查询(上限 MAX_BATCH,超出部分忽略)。永不抛错,失败映射为 reason。 */
- async getStatuses(queries: PrStatusQuery[]): Promise<PrStatusResult[]> {
+ /**
+ * 批量查询(上限 MAX_BATCH,超出部分忽略)。永不抛错,失败映射为 reason。
+ * opts.remote = device-link 远端发起:gh 缺失 / 未登录一律归为 no-token,
+ * 不把被控机的本地环境细节交给远端 UI 去引导。
+ */
+ async getStatuses(
+ queries: PrStatusQuery[],
+ opts: { remote?: boolean } = {},
+ ): Promise<PrStatusResult[]> {
const bounded = queries.slice(0, MAX_BATCH);
- return Promise.all(bounded.map((q) => this.getOne(q)));
+ const results = await Promise.all(bounded.map((q) => this.getOne(q)));
+ if (!opts.remote) return results;
+ return results.map((r) =>
+ !r.ok && (r.reason === 'gh-missing' || r.reason === 'gh-not-logged-in')
+ ? { ...r, reason: 'no-token' }
+ : r,
+ );
}
private async getOne(q: PrStatusQuery): Promise<PrStatusResult> {
@@ -136,8 +163,9 @@ export class PrStatusService {
const p = this.fetchOne(q)
.then((result) => {
- // 只缓存确定性结果(ok / not-found)。两类失败都不缓存:
- // - no-token:设置页配完 PAT 后下一次查询应立即生效;
+ // 只缓存确定性结果(ok / not-found)。其余失败都不缓存:
+ // - gh-missing / gh-not-logged-in / no-token:用户装完 gh 或登录后,
+ // 下一次查询应立即生效(token source 自带 30s 负缓存兜底);
// - fetch-failed:瞬时网络抖动 / 临时 5xx 不该把失败钉死满 TTL,
// 下次渲染触发查询时立即重试(review 反馈)。
if (result.ok || result.reason === 'not-found') {
@@ -154,13 +182,25 @@ export class PrStatusService {
private async fetchOne(q: PrStatusQuery): Promise<PrStatusResult> {
const base = { owner: q.owner, repo: q.repo, prNumber: q.prNumber };
- let token: string | null = null;
+ let read: GhCliTokenReadResult;
try {
- token = await this.deps.readToken();
+ read = await this.deps.readToken();
} catch (err) {
- log.warn('read github pat failed', { err: String(err) });
+ log.warn('read github token failed', { err: String(err) });
+ return { ok: false, ...base, reason: 'no-token' };
+ }
+ if (!read.ok) {
+ // 超时 / 执行故障用户做不了什么,不引导;缺失与未登录交给 UI 引导。
+ return {
+ ok: false,
+ ...base,
+ reason:
+ read.reason === 'gh-timeout' || read.reason === 'gh-exec-failed'
+ ? 'no-token'
+ : read.reason,
+ };
}
- if (!token) return { ok: false, ...base, reason: 'no-token' };
+ const token = read.token;
try {
const remote = await this.deps.fetchPr(token, q);
diff --git a/apps/desktop/src/renderer/__tests__/prGuidance.test.ts b/apps/desktop/src/renderer/__tests__/prGuidance.test.ts
new file mode 100644
index 0000000000..4ba6a6a1d2
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/prGuidance.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment jsdom
+/**
+ * PR 徽标在本机 gh 缺失 / 未登录时的引导判定(prGuidanceFor / prFailureCopyKey)
+ * 与输入框预填事件总线(insertPromptIntoComposer / subscribePromptInsert)。
+ *
+ * 不变量:只有本机、可写输入框的任务上,gh-missing / gh-not-logged-in 才把点击变成引导;
+ * SSH / device-link / review 只读与其余失败点击仍打开 PR。
+ * 预填提示词在已有草稿时必须先 splitBlock,不得拼到最后一个字符后面。
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { prFailureCopyKey, prGuidanceFor } from '../features/cc-agent/gitContextPrVisuals';
+import {
+ hasPromptInsertSubscriber,
+ insertPromptIntoComposer,
+ insertPromptIntoEditor,
+ subscribePromptInsert,
+} from '../lib/composerActionsBus';
+import type { PrStatusFailureReason, PrStatusResult } from '../lib/gitContext.types';
+
+const base = { owner: 'makecindy', repo: 'cindy', prNumber: 3821 };
+
+function failed(reason: PrStatusFailureReason): PrStatusResult {
+ return { ok: false, ...base, reason };
+}
+
+const ok: PrStatusResult = {
+ ok: true,
+ ...base,
+ status: 'open',
+ title: 't',
+ htmlUrl: 'https://github.com/makecindy/cindy/pull/3821',
+ branch: 'fix/x',
+ unresolvedCount: 0,
+};
+
+describe('prGuidanceFor', () => {
+ it('gh 未安装 → install;gh 未登录 → login', () => {
+ expect(prGuidanceFor(failed('gh-missing'))).toBe('install');
+ expect(prGuidanceFor(failed('gh-not-logged-in'))).toBe('login');
+ });
+
+ it('用户做不了什么的失败、成功态与加载中都不引导(点击仍是打开 PR)', () => {
+ for (const reason of ['no-token', 'not-found', 'fetch-failed'] as const) {
+ expect(prGuidanceFor(failed(reason))).toBeNull();
+ }
+ expect(prGuidanceFor(ok)).toBeNull();
+ expect(prGuidanceFor(undefined)).toBeNull();
+ });
+
+ it('点击无法兑现引导时退回打开 PR:远端 Agent 或只读输入框', () => {
+ expect(prGuidanceFor(failed('gh-missing'), { remoteHostId: 'host-1' })).toBeNull();
+ expect(prGuidanceFor(failed('gh-not-logged-in'), { remoteHostId: 'host-1' })).toBeNull();
+ expect(prGuidanceFor(failed('gh-missing'), { deviceLinkDeviceId: 'dev-1' })).toBeNull();
+ expect(prGuidanceFor(failed('gh-not-logged-in'), { deviceLinkDeviceId: 'dev-1' })).toBeNull();
+ expect(prGuidanceFor(failed('gh-missing'), { readOnly: true })).toBeNull();
+ expect(prGuidanceFor(failed('gh-not-logged-in'), { readOnly: true })).toBeNull();
+ expect(prGuidanceFor(failed('gh-missing'), { remoteHostId: null, readOnly: false })).toBe(
+ 'install',
+ );
+ expect(prGuidanceFor(failed('gh-not-logged-in'), { deviceLinkDeviceId: undefined })).toBe(
+ 'login',
+ );
+ });
+});
+
+describe('prFailureCopyKey', () => {
+ it('每种失败原因映射到独立文案 key;no-token / fetch-failed 共用 statusUnknown', () => {
+ expect(prFailureCopyKey(failed('gh-missing'))).toBe('ccAgent.gitContext.pr.ghMissing');
+ expect(prFailureCopyKey(failed('gh-not-logged-in'))).toBe(
+ 'ccAgent.gitContext.pr.ghNotLoggedIn',
+ );
+ expect(prFailureCopyKey(failed('not-found'))).toBe('ccAgent.gitContext.pr.notFound');
+ expect(prFailureCopyKey(failed('no-token'))).toBe('ccAgent.gitContext.pr.statusUnknown');
+ expect(prFailureCopyKey(failed('fetch-failed'))).toBe('ccAgent.gitContext.pr.statusUnknown');
+ });
+
+ it('成功态与加载中不给失败文案', () => {
+ expect(prFailureCopyKey(ok)).toBeNull();
+ expect(prFailureCopyKey(undefined)).toBeNull();
+ });
+});
+
+describe('composerActionsBus prompt insert', () => {
+ it('订阅方收到 targetSessionId + text;取消订阅后不再收到', () => {
+ const handler = vi.fn(() => true);
+ const unsubscribe = subscribePromptInsert('s1', handler);
+ expect(insertPromptIntoComposer({ targetSessionId: 's1', text: 'gh auth login' })).toBe(true);
+ expect(handler).toHaveBeenCalledWith({ targetSessionId: 's1', text: 'gh auth login' });
+ unsubscribe();
+ expect(insertPromptIntoComposer({ targetSessionId: 's1', text: 'again' })).toBe(false);
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('没人接住才退回打开 PR;有订阅但拒绝写入则保持引导、不改动作', () => {
+ expect(hasPromptInsertSubscriber('s1')).toBe(false);
+ expect(insertPromptIntoComposer({ targetSessionId: 's1', text: 'x' })).toBe(false);
+ const reject = subscribePromptInsert('s1', () => false);
+ expect(hasPromptInsertSubscriber('s1')).toBe(true);
+ expect(insertPromptIntoComposer({ targetSessionId: 's1', text: 'x' })).toBe(false);
+ reject();
+ expect(hasPromptInsertSubscriber('s1')).toBe(false);
+ const accept = subscribePromptInsert('s1', () => true);
+ expect(insertPromptIntoComposer({ targetSessionId: 's1', text: 'x' })).toBe(true);
+ accept();
+ });
+
+ it('空输入框直接 insertContent;已有草稿先 splitBlock 再插入,避免粘连', () => {
+ function makeChain() {
+ const chain = {
+ focus: vi.fn(),
+ splitBlock: vi.fn(),
+ insertContent: vi.fn(),
+ run: vi.fn(),
+ };
+ chain.focus.mockReturnValue(chain);
+ chain.splitBlock.mockReturnValue(chain);
+ chain.insertContent.mockReturnValue(chain);
+ return chain;
+ }
+
+ const empty = makeChain();
+ insertPromptIntoEditor(empty, { isEmpty: true, text: 'gh auth login' });
+ expect(empty.splitBlock).not.toHaveBeenCalled();
+ expect(empty.insertContent).toHaveBeenCalledWith('gh auth login');
+ expect(empty.run).toHaveBeenCalledTimes(1);
+
+ const occupied = makeChain();
+ insertPromptIntoEditor(occupied, { isEmpty: false, text: 'gh auth login' });
+ expect(occupied.splitBlock).toHaveBeenCalledTimes(1);
+ expect(occupied.insertContent).toHaveBeenCalledWith('gh auth login');
+ expect(occupied.run).toHaveBeenCalledTimes(1);
+ expect(occupied.splitBlock.mock.invocationCallOrder[0]).toBeLessThan(
+ occupied.insertContent.mock.invocationCallOrder[0],
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx b/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx
index 02e0822a33..f4c84c289f 100644
--- a/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/prRefsGranularity.test.tsx
@@ -181,7 +181,7 @@ describe('PrRefsProvider owner 切换的在飞隔离', () => {
const { result, rerender } = renderHook(
() => {
const { registerPrConsumer } = usePrActions();
- const status = usePrStatus('octo/repo#9');
+ const status = usePrStatus('session-s', 'octo/repo#9');
return { registerPrConsumer, status };
},
{ wrapper },
diff --git a/apps/desktop/src/renderer/__tests__/prRefsRefreshGating.test.ts b/apps/desktop/src/renderer/__tests__/prRefsRefreshGating.test.ts
index ae4e70a3c5..cfffd2365d 100644
--- a/apps/desktop/src/renderer/__tests__/prRefsRefreshGating.test.ts
+++ b/apps/desktop/src/renderer/__tests__/prRefsRefreshGating.test.ts
@@ -45,7 +45,7 @@ describe('PR 状态刷新的省流门控', () => {
expect(prRefsSource).toContain(
'if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) return;',
);
- expect(prRefsSource).toContain('if (prev?.ok === true && result.ok === false) continue;');
+ expect(prRefsSource).toContain('store.applyStatuses(sessionId, results)');
});
it('断线判定只认明确的 disconnected 标记(fail-open)', () => {
diff --git a/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts b/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts
index a14da1441d..3349144d99 100644
--- a/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionContentHeaderDragRegion.test.ts
@@ -21,8 +21,10 @@ describe('SessionContentHeader window drag region', () => {
expect(sessionHeaderSource).toMatch(
/aria-label=\{t\('ccAgent\.sessionHeader\.moreActions'\)\}[\s\S]{0,120}style=\{WINDOW_NO_DRAG_STYLE\}/,
);
+ // PR chip 的 onClick 按 gh 可用性二选一(打开 PR / 引导 Agent),但按钮本身
+ // 必须始终在 no-drag 区,否则两种点击都会被窗口拖拽区吞掉。
expect(gitContextBadgeSource).toMatch(
- /onClick=\{\(\) => void window\.electronAPI\.openExternal\(prRef\.url\)\}[\s\S]{0,180}style=\{WINDOW_NO_DRAG_STYLE\}/,
+ /onClick=\{handleClick\}[\s\S]{0,180}style=\{WINDOW_NO_DRAG_STYLE\}/,
);
});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 742b6f8f5b..5fceb9d0ab 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -104,7 +104,11 @@ import {
isDataOwnerGenerationCurrent,
isDataOwnerIdCurrent,
} from '@/contexts/dataOwnerGeneration';
-import { subscribeSessionLinkInsert } from '@/lib/composerActionsBus';
+import {
+ insertPromptIntoEditor,
+ subscribePromptInsert,
+ subscribeSessionLinkInsert,
+} from '@/lib/composerActionsBus';
import {
ModelSelector,
resolveRemoteModelListStatus,
@@ -2832,6 +2836,19 @@ export function ChatInput({
});
}, [editor, sessionId]);
+ // 徽标类引导动作(如 PR 徽标在 gh 未登录时点击):把一句现成提示词填进
+ // 输入框并聚焦,只填不发。发送中 / 语音占用时与键盘输入同锁,静默忽略。
+ useEffect(() => {
+ if (!editor || !sessionId) return;
+ return subscribePromptInsert(sessionId, ({ targetSessionId, text }) => {
+ if (targetSessionId !== sessionId || editor.isDestroyed) return false;
+ if (composerMutationLockedRef.current) return false;
+ insertPromptIntoEditor(editor.chain(), { isEmpty: editor.isEmpty, text });
+ lastComposerSelectionFromRef.current = editor.state.selection.from;
+ return true;
+ });
+ }, [editor, sessionId]);
+
const handleSavePastedText = useCallback(
(text: string) => {
const currentEditor = editorRef.current;
diff --git a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
index 0bdaf5c9f9..297c1b8993 100644
--- a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
+++ b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
@@ -14,9 +14,9 @@
* 正是 SessionItem 头注明令禁止的"整张表订阅"。
* - usePrRefsForSession(sessionId):按会话精准订阅,bulk 加载时逐会话做
* 内容比对保引用稳定,没变的行不醒。
- * - usePrStatus(key):单个 PR 徽标按 key 精准订阅(状态对象未变时保引用)。
- * - usePrStatuses():整表快照,**只给聚合消费方**(打开中的 tooltip、顶栏
- * 单会话视图)——任何状态变化都会重渲染订阅者,列表行禁止用。
+ * - usePrStatus(sessionId, key):单个 PR 徽标按会话+PR 键订阅。
+ * - usePrStatuses(sessionId):该会话的状态快照。状态按会话隔离,本机与
+ * device-link 不再抢同一把 PR 键。
*
* PR 状态(open/merged/...)是远端易变数据,不在启动期预取;main 侧本就有
* 60s TTL + in-flight 去重,这里只做轻量去重,不再加 TTL。
@@ -46,6 +46,7 @@ import { createLogger } from '@/lib/logger';
const log = createLogger('PrRefsContext');
const EMPTY_REFS: SessionPrRef[] = [];
+const EMPTY_STATUSES: ReadonlyMap<string, PrStatusResult> = new Map();
/** 同一会话的引用列表内容未变 → 复用旧数组引用(逐行订阅的快照比较基石)。 */
function sameRefList(
@@ -72,9 +73,9 @@ function sameStatus(a: PrStatusResult | undefined, b: PrStatusResult): boolean {
interface PrCacheStore {
subscribe: (listener: () => void) => () => void;
getRefs: (sessionId: string) => SessionPrRef[];
- getStatus: (key: string) => PrStatusResult | undefined;
- /** 整表快照(引用仅在状态真实变化时更换)——聚合消费方专用。 */
- getStatusesSnapshot: () => ReadonlyMap<string, PrStatusResult>;
+ getStatus: (sessionId: string, key: string) => PrStatusResult | undefined;
+ /** 单会话状态快照(该会话未变时引用稳定)。 */
+ getStatusesForSession: (sessionId: string) => ReadonlyMap<string, PrStatusResult>;
/** 本地全量加载:整表替换,但保住 keep 判定为真的既有条目(远程先到的)与未变引用。 */
mergeLocalRefs: (
grouped: Map<string, SessionPrRef[]>,
@@ -82,15 +83,15 @@ interface PrCacheStore {
) => void;
/** 单会话 refs 覆盖(空列表 = 删除)。内容未变不通知。 */
setSessionRefs: (sessionId: string, refs: readonly SessionPrRef[]) => void;
- /** 批量落状态结果。全部未变不通知。 */
- applyStatuses: (results: readonly PrStatusResult[]) => void;
+ /** 批量落入指定会话的状态。同会话后写覆盖前写;跨会话互不干扰。 */
+ applyStatuses: (sessionId: string, results: readonly PrStatusResult[]) => void;
clearAll: () => void;
}
function createPrCacheStore(): PrCacheStore {
const refsBySession = new Map<string, SessionPrRef[]>();
- const statuses = new Map<string, PrStatusResult>();
- let statusesSnapshot: ReadonlyMap<string, PrStatusResult> = new Map();
+ const statusesBySession = new Map<string, Map<string, PrStatusResult>>();
+ const statusSnapshots = new Map<string, ReadonlyMap<string, PrStatusResult>>();
const listeners = new Set<() => void>();
const notify = () => {
for (const listener of listeners) listener();
@@ -105,11 +106,11 @@ function createPrCacheStore(): PrCacheStore {
getRefs(sessionId) {
return refsBySession.get(sessionId) ?? EMPTY_REFS;
},
- getStatus(key) {
- return statuses.get(key);
+ getStatus(sessionId, key) {
+ return statusesBySession.get(sessionId)?.get(key);
},
- getStatusesSnapshot() {
- return statusesSnapshot;
+ getStatusesForSession(sessionId) {
+ return statusSnapshots.get(sessionId) ?? EMPTY_STATUSES;
},
mergeLocalRefs(grouped, keep) {
let changed = false;
@@ -139,27 +140,29 @@ function createPrCacheStore(): PrCacheStore {
refsBySession.set(sessionId, [...refs]);
notify();
},
- applyStatuses(results) {
+ applyStatuses(sessionId, results) {
+ let map = statusesBySession.get(sessionId);
+ if (!map) {
+ map = new Map();
+ statusesBySession.set(sessionId, map);
+ }
let changed = false;
for (const result of results) {
const key = prStatusKey(result);
- const prev = statuses.get(key);
- // 本机成功与远端 no-token/not-found 会写同一把 PR 键。失败结果不得覆盖
- // 已有成功态,否则徽标会随两端轮询来回降级。
- if (prev?.ok === true && result.ok === false) continue;
+ const prev = map.get(key);
if (sameStatus(prev, result)) continue;
- statuses.set(key, result);
+ map.set(key, result);
changed = true;
}
if (!changed) return;
- statusesSnapshot = new Map(statuses);
+ statusSnapshots.set(sessionId, new Map(map));
notify();
},
clearAll() {
- if (refsBySession.size === 0 && statuses.size === 0) return;
+ if (refsBySession.size === 0 && statusesBySession.size === 0) return;
refsBySession.clear();
- statuses.clear();
- statusesSnapshot = new Map();
+ statusesBySession.clear();
+ statusSnapshots.clear();
notify();
},
};
@@ -365,7 +368,7 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
: await window.electronAPI.gitContext.getPrStatuses(queries);
if (gen !== ownerGenRef.current) return; // owner 已切换:旧账号结果整体丢弃
if (!Array.isArray(results)) return;
- store.applyStatuses(results);
+ store.applyStatuses(sessionId, results);
} catch (err) {
log.warn('pr statuses fetch failed', String(err));
} finally {
@@ -528,31 +531,30 @@ export function usePrRefsForSession(sessionId: string): SessionPrRef[] {
);
}
-/** 单个 PR 的状态(按 prStatusKey 精准订阅;结果未变时引用稳定)。列表行徽标专用。 */
-export function usePrStatus(key: string): PrStatusResult | undefined {
+/** 单个 PR 的状态(按会话 + prStatusKey 订阅;结果未变时引用稳定)。列表行徽标专用。 */
+export function usePrStatus(sessionId: string, key: string): PrStatusResult | undefined {
const store = useContext(PrStoreContext);
return useSyncExternalStore(
store.subscribe,
- () => store.getStatus(key),
- () => store.getStatus(key),
+ () => store.getStatus(sessionId, key),
+ () => store.getStatus(sessionId, key),
);
}
interface PrStatusesContextValue {
- /** prStatusKey(ref) → 状态查询结果(整表快照)。 */
+ /** prStatusKey(ref) → 该会话的状态查询结果。 */
statuses: ReadonlyMap<string, PrStatusResult>;
fetchStatusesForSession: (sessionId: string) => void;
}
-/** 整表状态消费:**只给聚合消费方**(打开中的 tooltip、顶栏单会话视图)——任何
- * 状态变化都会重渲染订阅者。列表行禁止用(改用 usePrStatus)。 */
-export function usePrStatuses(): PrStatusesContextValue {
+/** 单会话状态消费:打开中的 tooltip、顶栏单会话视图。列表行用 usePrStatus。 */
+export function usePrStatuses(sessionId: string): PrStatusesContextValue {
const store = useContext(PrStoreContext);
const { fetchStatusesForSession } = useContext(PrActionsContext);
const statuses = useSyncExternalStore(
store.subscribe,
- store.getStatusesSnapshot,
- store.getStatusesSnapshot,
+ () => store.getStatusesForSession(sessionId),
+ () => store.getStatusesForSession(sessionId),
);
return useMemo(
() => ({ statuses, fetchStatusesForSession }),
diff --git a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
index 4f3cab3a7d..d159cb5614 100644
--- a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
@@ -14,7 +14,12 @@
* draft GitPullRequestDraft --text-tertiary
* merged GitMerge --focus-ring(语义蓝;项目无紫 token,不为此新增)
* closed GitPullRequestClosed --error-fg(语义红)
- * 未知(no-token / 查询失败) GitPullRequest + --text-tertiary,tooltip 给提示
+ * 未知(查询失败) GitPullRequest + --text-tertiary,tooltip 给原因
+ *
+ * 本机 gh 缺失 / 未登录时(prGuidanceFor):点击把安装 / 登录提示词填进当前任务
+ * 输入框交给 Agent;tooltip 写明点击后果。不复用 unresolved 的
+ * `--status-bar-accent` 5px 角点(DESIGN.md 该点只表示未解决 review)。
+ * SSH / device-link / review 只读任务不提供引导——点击无法兑现时仍打开 PR。
*/
import { GitBranch, GitPullRequest, MessageSquare } from 'lucide-react';
@@ -26,8 +31,15 @@ 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 } from '@/hooks/useSessionGitContext';
+import { hasPromptInsertSubscriber, insertPromptIntoComposer } from '@/lib/composerActionsBus';
import { prStatusKey, MAX_STATUS_QUERIES } from '@/lib/prStatus';
-import { PR_STATUS_COLOR, PR_STATUS_ICON, pickBranchLabel } from './gitContextPrVisuals';
+import {
+ PR_STATUS_COLOR,
+ PR_STATUS_ICON,
+ pickBranchLabel,
+ prFailureCopyKey,
+ prGuidanceFor,
+} from './gitContextPrVisuals';
export function GitContextBadge({ session }: { session: Session }) {
const { t } = useTranslation();
@@ -78,24 +90,69 @@ export function GitContextBadge({ session }: { session: Session }) {
)}
{prRefs.slice(0, MAX_STATUS_QUERIES).map((ref) => (
- <PrChip key={ref.id} prRef={ref} status={prStatuses.get(prStatusKey(ref))} />
+ <PrChip
+ key={ref.id}
+ sessionId={session.id}
+ remoteHostId={session.remoteHostId}
+ deviceLinkDeviceId={session.deviceLinkDeviceId}
+ readOnly={session.source === 'review'}
+ prRef={ref}
+ status={prStatuses.get(prStatusKey(ref))}
+ />
))}
</div>
);
}
-function PrChip({ prRef, status }: { prRef: SessionPrRef; status: PrStatusResult | undefined }) {
+function PrChip({
+ sessionId,
+ remoteHostId,
+ deviceLinkDeviceId,
+ readOnly,
+ prRef,
+ status,
+}: {
+ sessionId: string;
+ remoteHostId?: string | null;
+ deviceLinkDeviceId?: string | null;
+ readOnly?: boolean;
+ prRef: SessionPrRef;
+ status: PrStatusResult | undefined;
+}) {
const { t } = useTranslation();
const kind: PrStatusKind | null = status?.ok ? status.status : null;
const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;
const color = kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)';
+ const guidance = prGuidanceFor(status, { remoteHostId, deviceLinkDeviceId, readOnly });
+ const failureCopyKey = prFailureCopyKey(status);
const statusLine = kind
? t(`ccAgent.gitContext.pr.status.${kind}`)
- : status && !status.ok && status.reason === 'no-token'
- ? t('ccAgent.gitContext.pr.needsToken')
+ : failureCopyKey
+ ? t(failureCopyKey)
: t('ccAgent.gitContext.pr.statusUnknown');
+ // 引导只在 Composer 真正写入后独占点击;没人接住(确认卡/接管/准备 worktree 等
+ // 把 ChatInput 卸掉)必须退回打开 PR,不能空点。
+ const actionLine = guidance
+ ? t(`ccAgent.gitContext.pr.guidance.${guidance}.hint`)
+ : t('ccAgent.gitContext.pr.clickToOpen');
+ const ariaLabel = guidance
+ ? t(`ccAgent.gitContext.pr.guidance.${guidance}.aria`, { number: prRef.prNumber })
+ : t('ccAgent.gitContext.pr.openAria', { number: prRef.prNumber });
+
+ const handleClick = () => {
+ if (guidance) {
+ const accepted = insertPromptIntoComposer({
+ targetSessionId: sessionId,
+ text: t(`ccAgent.gitContext.pr.guidance.${guidance}.prompt`),
+ });
+ if (accepted) return;
+ // Composer 挂着但拒绝写入(发送中 / 语音占用):保持已广告的引导动作,不改打开 PR。
+ if (hasPromptInsertSubscriber(sessionId)) return;
+ }
+ void window.electronAPI.openExternal(prRef.url);
+ };
// 未解决 review thread 数:>0 才显示;GraphQL 拿不到(null)时整个信号隐藏。
const unresolved = status?.ok && status.unresolvedCount ? status.unresolvedCount : 0;
@@ -105,8 +162,9 @@ function PrChip({ prRef, status }: { prRef: SessionPrRef; status: PrStatusResult
<Tooltip.Trigger asChild>
<button
type="button"
- onClick={() => void window.electronAPI.openExternal(prRef.url)}
- aria-label={t('ccAgent.gitContext.pr.openAria', { number: prRef.prNumber })}
+ onClick={handleClick}
+ aria-label={ariaLabel}
+ data-pr-guidance={guidance ?? undefined}
style={WINDOW_NO_DRAG_STYLE}
className={cn(
'inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5',
@@ -139,6 +197,8 @@ function PrChip({ prRef, status }: { prRef: SessionPrRef; status: PrStatusResult
{unresolved > 0 && (
<span>{t('ccAgent.gitContext.pr.unresolved', { count: unresolved })}</span>
)}
+ {/* tooltip 两模式都是深底白字(--tooltip-text),次级信息用透明度而不是页面级 token。 */}
+ <span className="opacity-70">{actionLine}</span>
</div>
</Tooltip.Content>
</Tooltip.Root>
diff --git a/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts b/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts
index ee3f855961..b7ef624292 100644
--- a/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts
@@ -7,7 +7,60 @@
import { GitMerge, GitPullRequest, GitPullRequestClosed, GitPullRequestDraft } from 'lucide-react';
-import type { GitContextDirSource, PrStatusKind } from '@/lib/gitContext.types';
+import type { GitContextDirSource, PrStatusKind, PrStatusResult } from '@/lib/gitContext.types';
+
+/**
+ * 本机 gh 不可用时徽标承担的引导动作。tooltip 是非交互浮层放不了按钮,
+ * 所以动作落在 chip 点击上:点击把对应提示词填进当前任务输入框(只填不发),
+ * **不再**打开 PR——gh 问题解决之前一个 chip 只有一个动作。
+ * install = gh 未安装 → 让 Agent 安装并登录
+ * login = gh 未登录 → 让 Agent 登录
+ * 其它失败(no-token / not-found / fetch-failed)用户做不了什么,返回 null,
+ * 点击仍是打开 PR。
+ */
+export type PrGuidanceAction = 'install' | 'login';
+
+export type PrGuidanceSessionOpts = {
+ /** Codex SSH:Agent 跑在远端机器。 */
+ remoteHostId?: string | null;
+ /** device-link:本 session 归属被控设备。与 remoteHostId 互不相干,必须同时钳。 */
+ deviceLinkDeviceId?: string | null;
+ /** review 等只读任务:ChatInput 永久 disabled,插入会被静默丢掉。 */
+ readOnly?: boolean;
+};
+
+/**
+ * 点击会独占 chip(不再打开 PR),所以只有动作能兑现才引导:
+ * 1. 当前任务的 Agent 就在本机(非 SSH / 非 device-link)
+ * 2. 输入框能收下提示词(非 review 只读)
+ * 任一不成立 → 不引导,点击仍打开 PR。
+ */
+export function prGuidanceFor(
+ status: PrStatusResult | undefined,
+ opts?: PrGuidanceSessionOpts,
+): PrGuidanceAction | null {
+ if (opts?.remoteHostId || opts?.deviceLinkDeviceId || opts?.readOnly) return null;
+ if (!status || status.ok) return null;
+ if (status.reason === 'gh-missing') return 'install';
+ if (status.reason === 'gh-not-logged-in') return 'login';
+ return null;
+}
+
+/** 失败态 tooltip 的原因文案 key(ccAgent.gitContext.pr.*)。加载中(undefined)不给。 */
+export function prFailureCopyKey(status: PrStatusResult | undefined): string | null {
+ if (!status || status.ok) return null;
+ switch (status.reason) {
+ case 'gh-missing':
+ return 'ccAgent.gitContext.pr.ghMissing';
+ case 'gh-not-logged-in':
+ return 'ccAgent.gitContext.pr.ghNotLoggedIn';
+ case 'not-found':
+ return 'ccAgent.gitContext.pr.notFound';
+ case 'no-token':
+ case 'fetch-failed':
+ return 'ccAgent.gitContext.pr.statusUnknown';
+ }
+}
/**
* 决定分支 chip 显示哪条分支。优先级:
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 9054050743..e416ef34c3 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
@@ -180,7 +180,7 @@ function PrNumberPiece({ prRef, isActive }: { prRef: SessionPrRef; isActive?: bo
}, [fetchStatusesForSession, prRef.sessionId]);
// 按 key 精准订阅(2026-08-13 review P1):整表快照会让任一 PR 的刷新惊动
// 全部已挂载徽标;usePrStatus 在本 PR 结果未变时快照引用不变、不重渲染。
- const status = usePrStatus(prStatusKey(prRef));
+ const status = usePrStatus(prRef.sessionId, prStatusKey(prRef));
const kind = status?.ok ? status.status : null;
const unresolvedCount = status?.ok ? status.unresolvedCount : null;
const showDot = shouldShowPrUnresolvedDot(kind, unresolvedCount);
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 2030a124e9..e025c26613 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionTooltip.tsx
@@ -23,7 +23,7 @@ import { Tooltip } from '@/components/ui/tooltip';
import type { PrStatusResult, SessionPrRef } from '@/lib/gitContext.types';
import { prStatusKey, MAX_STATUS_QUERIES } from '@/lib/prStatus';
import { usePrStatuses } from '@/contexts/PrRefsContext';
-import { PR_STATUS_COLOR, PR_STATUS_ICON } from '../gitContextPrVisuals';
+import { PR_STATUS_COLOR, PR_STATUS_ICON, prFailureCopyKey } from '../gitContextPrVisuals';
import { formatSidebarFutureTime } from '../lib/formatSidebarTime';
import {
findLatestSidebarIndexRunForSession,
@@ -103,7 +103,7 @@ function PrTooltip({
controlledOpen?: boolean;
children: ReactNode;
}) {
- const { statuses, fetchStatusesForSession } = usePrStatuses();
+ const { statuses, fetchStatusesForSession } = usePrStatuses(sessionId);
useEffect(() => {
if (controlledOpen) fetchStatusesForSession(sessionId);
@@ -238,6 +238,9 @@ function PrLine({ prRef, status }: { prRef: SessionPrRef; status: PrStatusResult
const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;
const color = kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)';
const unresolved = status?.ok && status.unresolvedCount ? status.unresolvedCount : 0;
+ // 失败态与顶栏徽标同一句原因(gh 未登录 / 未安装 / 404 …),不再静默。
+ // 侧栏行本身不承担引导动作,所以只说原因,不说"点击"。
+ const failureCopyKey = prFailureCopyKey(status);
return (
<div className="flex min-w-0 max-w-80 items-center gap-1.5">
@@ -250,6 +253,9 @@ function PrLine({ prRef, status }: { prRef: SessionPrRef; status: PrStatusResult
· {t(`ccAgent.gitContext.pr.status.${kind}`)}
</span>
)}
+ {!kind && failureCopyKey && (
+ <span className="min-w-0 truncate text-[var(--text-tertiary)]">· {t(failureCopyKey)}</span>
+ )}
{unresolved > 0 && (
<span
className="inline-flex shrink-0 items-center gap-0.5"
diff --git a/apps/desktop/src/renderer/hooks/useSessionGitContext.ts b/apps/desktop/src/renderer/hooks/useSessionGitContext.ts
index 65580b0c1e..d1d12030c0 100644
--- a/apps/desktop/src/renderer/hooks/useSessionGitContext.ts
+++ b/apps/desktop/src/renderer/hooks/useSessionGitContext.ts
@@ -213,15 +213,15 @@ export function useSessionGitContext(session: Session): SessionGitContext {
// 新会话查询失败 → 缓存无条目 → 返回空,与旧实现的"清空"语义一致。
const { registerPrConsumer } = usePrActions();
const sharedPrRefs = usePrRefsForSession(sessionId);
- const { statuses: allStatuses } = usePrStatuses();
+ const { statuses: allStatuses } = usePrStatuses(sessionId);
useEffect(() => {
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 判断)。
+ // 状态已按会话隔离;再按本会话前 MAX_STATUS_QUERIES 条引用过滤,
+ // 保住旧契约「prStatuses 只含本会话条目」(消费方有 size 判断)。
const prStatuses = useMemo(() => {
const map = new Map<string, PrStatusResult>();
for (const ref of prRefs.slice(0, MAX_STATUS_QUERIES)) {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 90d9678536..efa8439346 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9112,9 +9112,24 @@
"merged": "Merged",
"closed": "Closed"
},
- "needsToken": "gh CLI not logged in — ask the agent to run gh auth login once to show PR status",
+ "ghNotLoggedIn": "gh is not signed in to GitHub on this machine, so PR status is unavailable",
+ "ghMissing": "GitHub CLI (gh) not found on this machine, so PR status is unavailable",
+ "notFound": "PR not found, or the current account cannot view it",
"statusUnknown": "Failed to fetch status",
"openAria": "Open PR #{{number}} in browser",
+ "clickToOpen": "Click to open the PR in your browser",
+ "guidance": {
+ "login": {
+ "hint": "Click to have the agent sign you in",
+ "aria": "PR #{{number}} status unavailable: have the agent sign in to GitHub",
+ "prompt": "Please sign me in to the GitHub CLI: run `gh auth login -h github.com -w`, tell me the one-time device code and URL it shows, and after I authorize in the browser, confirm with `gh auth status` that the login succeeded."
+ },
+ "install": {
+ "hint": "Click to have the agent install it and sign you in",
+ "aria": "PR #{{number}} status unavailable: have the agent install and sign in to GitHub CLI",
+ "prompt": "Please install the GitHub CLI (gh; `brew install gh` on macOS, `winget install GitHub.cli` on Windows), then run `gh auth login -h github.com -w` to sign in, tell me the one-time device code and URL it shows, and after I authorize in the browser, confirm with `gh auth status` that the login succeeded."
+ }
+ },
"unresolved": "Unresolved review threads: {{count}}"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d410a9c8db..d3e7f103f1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9097,9 +9097,24 @@
"merged": "マージ済み",
"closed": "クローズ済み"
},
- "needsToken": "ローカルの gh CLI が未ログインです。Agent に gh auth login を一度実行させると PR の状態が表示されます",
+ "ghNotLoggedIn": "このマシンの gh は GitHub にログインしていないため、PR の状態を表示できません",
+ "ghMissing": "GitHub CLI(gh)が見つからないため、PR の状態を表示できません",
+ "notFound": "PR が存在しないか、現在のアカウントでは閲覧できません",
"statusUnknown": "状態の取得に失敗しました",
"openAria": "PR #{{number}} をブラウザで開く",
+ "clickToOpen": "クリックしてブラウザで PR を開く",
+ "guidance": {
+ "login": {
+ "hint": "クリックすると Agent がログインを手伝います",
+ "aria": "PR #{{number}} の状態を取得できません:Agent に GitHub へのログインを任せる",
+ "prompt": "GitHub CLI にログインしてください:`gh auth login -h github.com -w` を実行し、表示されたワンタイムのデバイスコードと URL を教えてください。ブラウザで認可したら、`gh auth status` でログイン成功を確認してください。"
+ },
+ "install": {
+ "hint": "クリックすると Agent がインストールとログインを手伝います",
+ "aria": "PR #{{number}} の状態を取得できません:Agent に GitHub CLI のインストールとログインを任せる",
+ "prompt": "GitHub CLI(gh)をインストールしてください(macOS は `brew install gh`、Windows は `winget install GitHub.cli`)。その後 `gh auth login -h github.com -w` を実行してログインし、表示されたワンタイムのデバイスコードと URL を教えてください。ブラウザで認可したら、`gh auth status` でログイン成功を確認してください。"
+ }
+ },
"unresolved": "未解決のレビューコメント: {{count}} 件"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index af2be80296..9c92387acf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9097,9 +9097,24 @@
"merged": "병합됨",
"closed": "닫힘"
},
- "needsToken": "로컬 gh CLI가 로그인되어 있지 않습니다. Agent에게 gh auth login을 한 번 실행하게 하면 PR 상태가 표시됩니다",
+ "ghNotLoggedIn": "이 컴퓨터의 gh가 GitHub에 로그인되어 있지 않아 PR 상태를 볼 수 없습니다",
+ "ghMissing": "GitHub CLI(gh)를 찾을 수 없어 PR 상태를 볼 수 없습니다",
+ "notFound": "PR이 없거나 현재 계정으로는 볼 수 없습니다",
"statusUnknown": "상태를 가져오지 못했습니다",
"openAria": "브라우저에서 PR #{{number}} 열기",
+ "clickToOpen": "클릭하여 브라우저에서 PR 열기",
+ "guidance": {
+ "login": {
+ "hint": "클릭하면 Agent가 로그인을 도와줍니다",
+ "aria": "PR #{{number}} 상태를 가져올 수 없음: Agent에게 GitHub 로그인 맡기기",
+ "prompt": "GitHub CLI에 로그인해 주세요: `gh auth login -h github.com -w`를 실행하고 표시되는 일회용 기기 코드와 URL을 알려 주세요. 제가 브라우저에서 승인한 뒤 `gh auth status`로 로그인 성공 여부를 확인해 주세요."
+ },
+ "install": {
+ "hint": "클릭하면 Agent가 설치와 로그인을 도와줍니다",
+ "aria": "PR #{{number}} 상태를 가져올 수 없음: Agent에게 GitHub CLI 설치와 로그인 맡기기",
+ "prompt": "GitHub CLI(gh)를 설치해 주세요(macOS는 `brew install gh`, Windows는 `winget install GitHub.cli`). 그다음 `gh auth login -h github.com -w`를 실행해 로그인하고, 표시되는 일회용 기기 코드와 URL을 알려 주세요. 제가 브라우저에서 승인한 뒤 `gh auth status`로 로그인 성공 여부를 확인해 주세요."
+ }
+ },
"unresolved": "미해결 리뷰 코멘트: {{count}}건"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e1d060e7bc..11137b42b2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9097,9 +9097,24 @@
"merged": "已合并",
"closed": "已关闭"
},
- "needsToken": "本地 gh CLI 未登录——让 Agent 执行一次 gh auth login 即可显示 PR 状态",
+ "ghNotLoggedIn": "本机 gh 尚未登录 GitHub,看不到 PR 状态",
+ "ghMissing": "未检测到 GitHub CLI(gh),看不到 PR 状态",
+ "notFound": "PR 不存在,或当前账号无权限查看",
"statusUnknown": "状态获取失败",
"openAria": "在浏览器打开 PR #{{number}}",
+ "clickToOpen": "点击在浏览器打开 PR",
+ "guidance": {
+ "login": {
+ "hint": "点击让 Agent 帮你登录",
+ "aria": "PR #{{number}} 状态不可用:让 Agent 登录 GitHub",
+ "prompt": "请帮我登录 GitHub CLI:运行 `gh auth login -h github.com -w`,把出现的一次性设备码和网址告诉我;我在浏览器完成授权后,你再用 `gh auth status` 确认登录成功。"
+ },
+ "install": {
+ "hint": "点击让 Agent 帮你安装并登录",
+ "aria": "PR #{{number}} 状态不可用:让 Agent 安装并登录 GitHub CLI",
+ "prompt": "请帮我安装 GitHub CLI(gh,macOS 用 `brew install gh`,Windows 用 `winget install GitHub.cli`),然后运行 `gh auth login -h github.com -w` 登录,把出现的一次性设备码和网址告诉我;我在浏览器完成授权后,你再用 `gh auth status` 确认登录成功。"
+ }
+ },
"unresolved": "{{count}} 条未解决的 review 评论"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 0d845e3df8..f461ac7b92 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9097,9 +9097,24 @@
"merged": "已合併",
"closed": "已關閉"
},
- "needsToken": "本地 gh CLI 未登入——讓 Agent 執行一次 gh auth login 即可顯示 PR 狀態",
+ "ghNotLoggedIn": "本機 gh 尚未登入 GitHub,看不到 PR 狀態",
+ "ghMissing": "未偵測到 GitHub CLI(gh),看不到 PR 狀態",
+ "notFound": "PR 不存在,或目前帳號無權限檢視",
"statusUnknown": "狀態獲取失敗",
"openAria": "在瀏覽器開啟 PR #{{number}}",
+ "clickToOpen": "點擊在瀏覽器開啟 PR",
+ "guidance": {
+ "login": {
+ "hint": "點擊讓 Agent 幫你登入",
+ "aria": "PR #{{number}} 狀態不可用:讓 Agent 登入 GitHub",
+ "prompt": "請幫我登入 GitHub CLI:執行 `gh auth login -h github.com -w`,把出現的一次性裝置碼和網址告訴我;我在瀏覽器完成授權後,你再用 `gh auth status` 確認登入成功。"
+ },
+ "install": {
+ "hint": "點擊讓 Agent 幫你安裝並登入",
+ "aria": "PR #{{number}} 狀態不可用:讓 Agent 安裝並登入 GitHub CLI",
+ "prompt": "請幫我安裝 GitHub CLI(gh,macOS 用 `brew install gh`,Windows 用 `winget install GitHub.cli`),然後執行 `gh auth login -h github.com -w` 登入,把出現的一次性裝置碼和網址告訴我;我在瀏覽器完成授權後,你再用 `gh auth status` 確認登入成功。"
+ }
+ },
"unresolved": "{{count}} 條未解決的 review 評論"
}
},
diff --git a/apps/desktop/src/renderer/lib/composerActionsBus.ts b/apps/desktop/src/renderer/lib/composerActionsBus.ts
index 1870d8d809..9e5ed49a7b 100644
--- a/apps/desktop/src/renderer/lib/composerActionsBus.ts
+++ b/apps/desktop/src/renderer/lib/composerActionsBus.ts
@@ -27,3 +27,71 @@ export function subscribeSessionLinkInsert(
window.addEventListener(INSERT_SESSION_LINK_EVENT, wrapped);
return () => window.removeEventListener(INSERT_SESSION_LINK_EVENT, wrapped);
}
+
+/**
+ * A request to prefill plain prompt text into a composer. The composer only
+ * inserts and focuses; the user still decides whether to send.
+ */
+export interface InsertPromptDetail {
+ targetSessionId: string;
+ text: string;
+}
+
+type PromptInsertHandler = (detail: InsertPromptDetail) => boolean;
+
+const promptInsertHandlersBySession = new Map<string, Set<PromptInsertHandler>>();
+
+/**
+ * 预填提示词。返回 true = 有订阅方实际写入了输入框。
+ * Chip 点击:写入成功则结束;有订阅但拒绝(发送中/语音占用)则不改动作;
+ * 完全没人接住才退回打开 PR。
+ */
+export function insertPromptIntoComposer(detail: InsertPromptDetail): boolean {
+ const handlers = promptInsertHandlersBySession.get(detail.targetSessionId);
+ if (!handlers) return false;
+ let accepted = false;
+ for (const handler of handlers) {
+ if (handler(detail)) accepted = true;
+ }
+ return accepted;
+}
+
+export function hasPromptInsertSubscriber(sessionId: string): boolean {
+ return (promptInsertHandlersBySession.get(sessionId)?.size ?? 0) > 0;
+}
+
+export function subscribePromptInsert(
+ sessionId: string,
+ handler: PromptInsertHandler,
+): () => void {
+ let handlers = promptInsertHandlersBySession.get(sessionId);
+ if (!handlers) {
+ handlers = new Set();
+ promptInsertHandlersBySession.set(sessionId, handlers);
+ }
+ handlers.add(handler);
+ return () => {
+ handlers.delete(handler);
+ if (handlers.size === 0) promptInsertHandlersBySession.delete(sessionId);
+ };
+}
+
+/** TipTap chain 里预填提示词需要的最小表面,避免 composerActionsBus 依赖 Editor 类型。 */
+export interface PromptInsertChain {
+ focus: (pos: 'end') => PromptInsertChain;
+ splitBlock: () => PromptInsertChain;
+ insertContent: (text: string) => PromptInsertChain;
+ run: () => void;
+}
+
+/**
+ * 把引导提示词写成独立一段。输入框已有草稿时先 splitBlock,绝不拼到最后一个字符后面。
+ */
+export function insertPromptIntoEditor(
+ chain: PromptInsertChain,
+ opts: { isEmpty: boolean; text: string },
+): void {
+ chain.focus('end');
+ if (!opts.isEmpty) chain.splitBlock();
+ chain.insertContent(opts.text).run();
+}
diff --git a/apps/desktop/src/renderer/lib/gitContext.types.ts b/apps/desktop/src/renderer/lib/gitContext.types.ts
index b32f114e96..7d52531093 100644
--- a/apps/desktop/src/renderer/lib/gitContext.types.ts
+++ b/apps/desktop/src/renderer/lib/gitContext.types.ts
@@ -68,5 +68,14 @@ export type PrStatusResult =
owner: string;
repo: string;
prNumber: number;
- reason: 'no-token' | 'not-found' | 'fetch-failed';
+ reason: PrStatusFailureReason;
};
+
+/**
+ * 镜像 main/git-context/prStatusService.ts 的 PrStatusFailureReason:
+ * gh-missing / gh-not-logged-in = 本机 gh 缺失 / 未登录,徽标点击引导 Agent 处理
+ * no-token = 拿不到 token 且不给原因(device-link 远端结果、gh 子进程超时)
+ * not-found = 404;fetch-failed = 网络等其它错误
+ */
+export type PrStatusFailureReason =
+ 'gh-missing' | 'gh-not-logged-in' | 'no-token' | 'not-found' | 'fetch-failed';