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): Issue 页展示自己提交过的 Issue (#1103)

Dash42f21153f6c0
diff --git a/apps/desktop/src/main/appSessionState.ts b/apps/desktop/src/main/appSessionState.ts
index ad3f6e6e75..e4a858659a 100644
--- a/apps/desktop/src/main/appSessionState.ts
+++ b/apps/desktop/src/main/appSessionState.ts
@@ -97,6 +97,23 @@ export function getActiveAppSession(): ActiveAppSession {
return { ...ensureLoaded() };
}
+/**
+ * Opaque key identifying "which account is active right now".
+ *
+ * Any owner-scoped read or write that spans an `await` must capture this before
+ * the wait and re-check it after, then drop the operation when it no longer
+ * matches — otherwise account A's data lands in account B's storage or UI.
+ * `generation` advances on every mode/owner commit, so the key changes even if
+ * the same owner is re-committed.
+ *
+ * Single source of truth on purpose: this invariant was first fixed per-call-site
+ * and each missed call site became its own bug.
+ */
+export function activeOwnerScopeKey(): string {
+ const session = ensureLoaded();
+ return `${session.mode}:${session.dataOwnerId ?? 'none'}:${session.generation}`;
+}
+
/**
* Fail closed while owner-bound runtimes are being torn down or replaced.
* The returned release function is idempotent so error paths can safely use it
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 8820c6aa22..52e8c18e64 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -474,6 +474,7 @@ import { registerContactsIpc } from './maker-ipc/contacts-ipc.js';
import { disposeDesktopContactsManager } from './maker-host/maker-contacts-host.js';
import { registerMakerHelpIpc } from './maker-ipc/help.js';
import { registerHelpFeedbackIpc } from './maker-ipc/help-feedback.js';
+import { registerMyIssuesIpc } from './maker-ipc/my-issues.js';
import { registerMakerPlanWriteIpc } from './maker-ipc/plan-write.js';
import { registerMakerRewindIpc } from './maker-ipc/rewind.js';
import { registerMakerForkIpc } from './maker-ipc/fork.js';
@@ -5584,6 +5585,11 @@ app.on('ready', async () => {
// 本机 FS 目录浏览(项目选择器「添加远程项目」逐级浏览;device-link 经隧道在被控端执行)。
// 无 DB / 无登录依赖,随其它顶层 handler 一起注册即可。
registerFsBrowseIpc();
+ // 「我的 Issue」列表查询。刻意注册在这里而不是 registerMakerIpcsAfterSplash:
+ // 它不依赖 Maker 与 agent 二进制,而 /issues 在 splash check-environment 完成前
+ // (或二进制 provision 失败时)就可能被打开 —— 挂在 splash 之后会让页面拿到
+ // "No handler registered" 且不会自动恢复。
+ registerMyIssuesIpc();
// chat-data-localization F2/F5:注册 localDb IPC + 干净退出快照钩子。
// 不立即开 db;ensureReady 由 AuthContext 在登录成功后通过 IPC 触发。
// onReady 回调 → scheduler-host 启动重试入口 (Phase 3):splash 跑早于 user login
diff --git a/apps/desktop/src/main/git-context/ghCliTokenSource.ts b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
index d255b2537d..182e686dba 100644
--- a/apps/desktop/src/main/git-context/ghCliTokenSource.ts
+++ b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
@@ -111,3 +111,14 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
},
};
}
+
+let sharedSource: GhCliTokenSource | null = null;
+
+/**
+ * 进程内共享实例。多个消费方(PR 状态徽标、「我的 Issue」列表)各自 new 一份的话,
+ * 缓存互不可见 —— 同一段时间会重复 spawn `gh`,负缓存也各算一套。
+ */
+export function getSharedGhCliTokenSource(): GhCliTokenSource {
+ if (!sharedSource) sharedSource = createGhCliTokenSource();
+ return sharedSource;
+}
diff --git a/apps/desktop/src/main/git-context/ipc.ts b/apps/desktop/src/main/git-context/ipc.ts
index 309fd71a5c..172b24dfc6 100644
--- a/apps/desktop/src/main/git-context/ipc.ts
+++ b/apps/desktop/src/main/git-context/ipc.ts
@@ -25,7 +25,7 @@ import { createLogger } from '../logger.js';
import { getCurrentDbClientUserId } from '../localDb/client/current';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { requireString, throwIpcError } from '../utils/ipcValidate';
-import { createGhCliTokenSource } from './ghCliTokenSource.js';
+import { getSharedGhCliTokenSource } from './ghCliTokenSource.js';
import { GitContextService } from './GitContextService.js';
import { resolveSessionGitDirLive } from './sessionDirResolver.js';
import {
@@ -68,8 +68,8 @@ function broadcastToAllWindows(channel: string, payload: unknown): void {
}
}
-/** gh CLI 登录态来源(模块级单例,内置 5min 正/负缓存)。 */
-const ghCliTokenSource = createGhCliTokenSource();
+/** gh CLI 登录态来源(进程内共享单例,内置 5min 正 / 30s 负缓存)。 */
+const ghCliTokenSource = getSharedGhCliTokenSource();
async function readGithubToken(): Promise<string | null> {
return ghCliTokenSource.readToken();
diff --git a/apps/desktop/src/main/github-issue/__tests__/githubIssuePayload.test.ts b/apps/desktop/src/main/github-issue/__tests__/githubIssuePayload.test.ts
new file mode 100644
index 0000000000..8735fee7ca
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/__tests__/githubIssuePayload.test.ts
@@ -0,0 +1,139 @@
+/**
+ * Issue 响应解析:GitHub 原生形状与服务端可能用的 camelCase 形状都要吃,
+ * 缺字段降级、坏条目过滤、外层三种容器形状、404 识别。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ isGithubNotFoundMessage,
+ parseIssuePage,
+ parseRemoteIssue,
+} from '../githubIssuePayload';
+
+const RAW_ISSUE = {
+ number: 1061,
+ title: 'skill(browser-translate): share the Skill',
+ html_url: 'https://github.com/makecindy/cindy/issues/1061',
+ state: 'open',
+ labels: [{ id: 1, name: 'feature', color: 'ededed', description: '' }],
+ created_at: '2026-07-30T09:12:49Z',
+ updated_at: '2026-07-30T10:00:00Z',
+ comments: 2,
+};
+
+const PARSED = {
+ number: 1061,
+ title: 'skill(browser-translate): share the Skill',
+ htmlUrl: 'https://github.com/makecindy/cindy/issues/1061',
+ state: 'open',
+ labels: ['feature'],
+ createdAt: '2026-07-30T09:12:49Z',
+ updatedAt: '2026-07-30T10:00:00Z',
+ commentCount: 2,
+};
+
+describe('parseRemoteIssue', () => {
+ it('解析 GitHub 原生形状', () => {
+ expect(parseRemoteIssue(RAW_ISSUE)).toEqual(PARSED);
+ });
+
+ it('同样吃服务端可能用的 camelCase 形状', () => {
+ expect(
+ parseRemoteIssue({
+ number: 1061,
+ title: PARSED.title,
+ url: PARSED.htmlUrl,
+ state: 'open',
+ type: 'feature',
+ createdAt: PARSED.createdAt,
+ updatedAt: PARSED.updatedAt,
+ commentCount: 2,
+ }),
+ ).toEqual(PARSED);
+ });
+
+ it('labels 为字符串数组时同样识别', () => {
+ expect(parseRemoteIssue({ ...RAW_ISSUE, labels: ['bug', 42] })?.labels).toEqual(['bug']);
+ });
+
+ it('可选字段缺失时降级为 null,不整条丢弃', () => {
+ expect(
+ parseRemoteIssue({
+ number: 7,
+ title: 't',
+ html_url: 'u',
+ created_at: '2026-07-01T00:00:00Z',
+ }),
+ ).toMatchObject({ state: 'open', labels: [], updatedAt: null, commentCount: null });
+ });
+
+ it('state 非 closed 一律按 open', () => {
+ expect(parseRemoteIssue({ ...RAW_ISSUE, state: 'closed' })?.state).toBe('closed');
+ expect(parseRemoteIssue({ ...RAW_ISSUE, state: undefined })?.state).toBe('open');
+ });
+
+ it('关键字段缺失或类型不对时返回 null', () => {
+ for (const bad of [
+ null,
+ 'nope',
+ [],
+ { ...RAW_ISSUE, number: '1061' },
+ { ...RAW_ISSUE, number: 1.5 },
+ { ...RAW_ISSUE, title: null },
+ { ...RAW_ISSUE, html_url: undefined, url: undefined },
+ { ...RAW_ISSUE, created_at: 0 },
+ ]) {
+ expect(parseRemoteIssue(bad)).toBeNull();
+ }
+ });
+
+ it('createdAt 必须可解析,不只是非空字符串', () => {
+ // mergeIssues 的排序比较器直接 Date.parse 相减:不可解析会得到 NaN,让**整份**
+ // 列表顺序变成未定义(不是这一条排错位置)。账本清洗早就这样校验 submittedAt。
+ for (const bad of ['', 'not-a-date', '昨天', '2026-13-45T99:99:99Z']) {
+ expect(parseRemoteIssue({ ...RAW_ISSUE, created_at: bad })).toBeNull();
+ }
+ // 合法的非 ISO 写法照常接受 —— 收紧的是「能不能解析」,不是「必须长成 ISO」。
+ expect(parseRemoteIssue({ ...RAW_ISSUE, created_at: '2026-07-30' })?.createdAt).toBe(
+ '2026-07-30',
+ );
+ });
+});
+
+describe('parseIssuePage', () => {
+ it('接受 issues / items / 裸数组三种外层形状', () => {
+ for (const payload of [{ issues: [RAW_ISSUE] }, { items: [RAW_ISSUE] }, [RAW_ISSUE]]) {
+ expect(parseIssuePage(payload).issues).toEqual([PARSED]);
+ }
+ });
+
+ it('坏条目被过滤,好条目保留', () => {
+ const page = parseIssuePage({ issues: [RAW_ISSUE, { number: 'x' }, null] });
+ expect(page.issues).toHaveLength(1);
+ });
+
+ it('总数字段认 total_count / totalCount / total', () => {
+ expect(parseIssuePage({ total_count: 9, items: [RAW_ISSUE] }).totalCount).toBe(9);
+ expect(parseIssuePage({ totalCount: 8, issues: [RAW_ISSUE] }).totalCount).toBe(8);
+ expect(parseIssuePage({ total: 7, issues: [RAW_ISSUE] }).totalCount).toBe(7);
+ });
+
+ it('只给 hasMore 时也能表达「还有更多」', () => {
+ expect(parseIssuePage({ hasMore: true, issues: [RAW_ISSUE] }).totalCount).toBe(2);
+ expect(parseIssuePage({ hasMore: false, issues: [RAW_ISSUE] }).totalCount).toBeNull();
+ });
+
+ it('形状完全不对时返回空结果 + totalCount null', () => {
+ expect(parseIssuePage(undefined)).toEqual({ issues: [], totalCount: null });
+ expect(parseIssuePage({ items: 'nope' })).toEqual({ issues: [], totalCount: null });
+ });
+});
+
+describe('isGithubNotFoundMessage', () => {
+ it('识别两条通道的 404 文案', () => {
+ expect(isGithubNotFoundMessage('GitHub API HTTP 404: Not Found')).toBe(true);
+ expect(isGithubNotFoundMessage('not found')).toBe(true);
+ expect(isGithubNotFoundMessage('HTTP 403: rate limit exceeded')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts b/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts
index d7cd4aa74e..e86da81b5a 100644
--- a/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts
+++ b/apps/desktop/src/main/github-issue/__tests__/githubIssueSubmitService.test.ts
@@ -281,6 +281,104 @@ describe('submitGithubIssueWithConfirm', () => {
expect(postIssue).not.toHaveBeenCalled();
});
+ it('平台代发成功后记账,带公开署名、不带 githubLogin', async () => {
+ const onSubmitted = vi.fn();
+ const { deps } = makeDeps({ onSubmitted });
+ await expect(submitGithubIssueWithConfirm(deps, REQ)).resolves.toMatchObject({ ok: true });
+ expect(onSubmitted).toHaveBeenCalledTimes(1);
+ const record = onSubmitted.mock.calls[0]![0];
+ expect(record).toMatchObject({
+ number: 80,
+ url: 'https://github.com/makecindy/cindy/issues/80',
+ title: REQ.title,
+ type: 'bug',
+ identity: 'platform',
+ publicName: 'Carol',
+ });
+ expect(record).not.toHaveProperty('githubLogin');
+ expect(Number.isFinite(Date.parse(record.submittedAt))).toBe(true);
+ });
+
+ it('GitHub 用户直发成功后记账,带 login、不带公开署名', async () => {
+ const onSubmitted = vi.fn();
+ const { deps } = makeDeps({
+ resolveSubmissionIdentity: async () => ({ kind: 'github-user', login: 'octocat' }) as const,
+ onSubmitted,
+ });
+ await expect(submitGithubIssueWithConfirm(deps, REQ)).resolves.toMatchObject({ ok: true });
+ const record = onSubmitted.mock.calls[0]![0];
+ expect(record).toMatchObject({ identity: 'github-user', githubLogin: 'octocat' });
+ expect(record).not.toHaveProperty('publicName');
+ });
+
+ it('记账的 url 由 issue 号派生,不采纳 postIssue 返回的原值', async () => {
+ // 账本**读取**侧用 isMyIssueUrl 强校验(必须指向本仓这一号 issue)。写入侧存原值
+ // 就两侧口径不一:返回 API 链接或别的 host 时,这条记录写得进去、读出来却被当坏
+ // 数据过滤掉 —— 平台读接口未就绪 / 离线时,用户看不到自己刚提交的那条。
+ const onSubmitted = vi.fn();
+ const { deps } = makeDeps({
+ postIssue: vi.fn(async () => ({
+ githubIssue: { number: 80, url: 'https://api.github.com/repos/makecindy/cindy/issues/80' },
+ })),
+ onSubmitted,
+ });
+ await expect(submitGithubIssueWithConfirm(deps, REQ)).resolves.toMatchObject({ ok: true });
+ expect(onSubmitted.mock.calls[0]![0].url).toBe('https://github.com/makecindy/cindy/issues/80');
+ });
+
+ it('记账用的是用户确认版标题与类型,不是 agent 传入的', async () => {
+ const onSubmitted = vi.fn();
+ const { deps } = makeDeps({
+ confirm: vi.fn(async () => ({
+ confirmed: true as const,
+ title: '用户改过的标题',
+ body: '用户改过的正文',
+ type: 'feature' as const,
+ publicName: 'Carol',
+ })),
+ onSubmitted,
+ });
+ await submitGithubIssueWithConfirm(deps, REQ);
+ expect(onSubmitted.mock.calls[0]![0]).toMatchObject({
+ title: '用户改过的标题',
+ type: 'feature',
+ });
+ });
+
+ it('未提交(取消 / 提交失败)时不记账', async () => {
+ const cancelled = vi.fn();
+ await submitGithubIssueWithConfirm(
+ makeDeps({
+ confirm: vi.fn(async () => ({ confirmed: false as const, reason: 'cancelled' as const })),
+ onSubmitted: cancelled,
+ }).deps,
+ REQ,
+ );
+ expect(cancelled).not.toHaveBeenCalled();
+
+ const failed = vi.fn();
+ await submitGithubIssueWithConfirm(
+ makeDeps({
+ postIssue: vi.fn(async () => Promise.reject(Object.assign(new Error('x'), { statusCode: 500 }))),
+ onSubmitted: failed,
+ }).deps,
+ REQ,
+ );
+ expect(failed).not.toHaveBeenCalled();
+ });
+
+ it('记账抛错不影响已经成功的提交结果', async () => {
+ const { deps } = makeDeps({
+ onSubmitted: () => {
+ throw new Error('ledger disk full');
+ },
+ });
+ await expect(submitGithubIssueWithConfirm(deps, REQ)).resolves.toMatchObject({
+ ok: true,
+ issueNumber: 80,
+ });
+ });
+
it('用户身份提交失败时只调用一次该身份,不切换平台重试', async () => {
const identity = { kind: 'github-user', login: 'octocat' } as const;
const postIssue = vi.fn<GithubIssueSubmitServiceDeps['postIssue']>(async () => {
diff --git a/apps/desktop/src/main/github-issue/__tests__/myIssuesService.test.ts b/apps/desktop/src/main/github-issue/__tests__/myIssuesService.test.ts
new file mode 100644
index 0000000000..20a308e260
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/__tests__/myIssuesService.test.ts
@@ -0,0 +1,647 @@
+/**
+ * myIssuesService 单测 —— 三路输入合并、来源标记、平台通道降级、可选增强的独立性、缓存。
+ *
+ * 最重要的一条口径:**没有 GitHub 身份是正常状态**,列表必须照常出来,
+ * degraded 只由平台通道决定。依赖全注入,不碰网络 / electron。
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import type { SubmittedIssueRecord } from '../../../shared/myIssues';
+import {
+ MyIssuesService,
+ isStaleAccountScopeError,
+ issueTypeFromLabels,
+ mergeIssues,
+ type GithubEnhancementViewer,
+ type MyIssuesServiceDeps,
+ type RemoteIssue,
+} from '../myIssuesService';
+
+const GHOST_VIEWER: GithubEnhancementViewer = { source: 'ghost', login: 'octocat' };
+
+function ledgerRecord(over: Partial<SubmittedIssueRecord> = {}): SubmittedIssueRecord {
+ return {
+ number: 1001,
+ url: 'https://github.com/makecindy/cindy/issues/1001',
+ title: '账本里记的标题',
+ type: 'bug',
+ submittedAt: '2026-07-01T00:00:00.000Z',
+ identity: 'platform',
+ publicName: 'shuji',
+ ...over,
+ };
+}
+
+function remoteIssue(over: Partial<RemoteIssue> = {}): RemoteIssue {
+ return {
+ number: 2002,
+ title: 'GitHub 上的标题',
+ htmlUrl: 'https://github.com/makecindy/cindy/issues/2002',
+ state: 'open',
+ labels: ['feature'],
+ createdAt: '2026-07-10T00:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ commentCount: 3,
+ ...over,
+ };
+}
+
+function makeDeps(over: Partial<MyIssuesServiceDeps> = {}): MyIssuesServiceDeps {
+ return {
+ readLedger: () => [],
+ fetchPlatformIssues: async () => ({
+ ok: true,
+ page: { issues: [], totalCount: 0 },
+ }),
+ resolveGithubEnhancement: async () => null,
+ searchAuthoredIssues: async () => ({ issues: [], totalCount: 0 }),
+ readScope: () => 'owner-a:1',
+ ...over,
+ };
+}
+
+describe('mergeIssues', () => {
+ it('账本 only 的条目状态标 unknown,标题用账本记的那一版', () => {
+ const [item] = mergeIssues([ledgerRecord()], []);
+ expect(item).toMatchObject({
+ number: 1001,
+ title: '账本里记的标题',
+ state: 'unknown',
+ updatedAt: null,
+ commentCount: null,
+ sources: ['cindy-tool'],
+ });
+ });
+
+ it('平台通道返回的条目只打 cindy-tool —— 平台代发的 GitHub 作者不是本人', () => {
+ const [item] = mergeIssues(
+ [],
+ [],
+ [remoteIssue({ number: 9, state: 'closed', title: '远端标题' })],
+ );
+ expect(item).toMatchObject({ state: 'closed', title: '远端标题', sources: ['cindy-tool'] });
+ });
+
+ it('账本 + 平台同号时远端字段覆盖账本,标签被清掉时类型回退账本', () => {
+ const [item] = mergeIssues(
+ [ledgerRecord({ number: 5, title: '提交时的旧标题', type: 'bug' })],
+ [],
+ [remoteIssue({ number: 5, title: '被维护者改过的标题', state: 'closed', labels: [] })],
+ );
+ expect(item).toMatchObject({
+ title: '被维护者改过的标题',
+ state: 'closed',
+ type: 'bug',
+ sources: ['cindy-tool'],
+ });
+ });
+
+ it('author 搜到的打 github-account;同时命中两路时两个来源都标上且顺序稳定', () => {
+ const [onlyAuthored] = mergeIssues([], [remoteIssue({ number: 7 })]);
+ expect(onlyAuthored.sources).toEqual(['github-account']);
+
+ const [both] = mergeIssues(
+ [ledgerRecord({ number: 7 })],
+ [remoteIssue({ number: 7 })],
+ [remoteIssue({ number: 7 })],
+ );
+ expect(both.sources).toEqual(['cindy-tool', 'github-account']);
+ });
+
+ it('账本 identity=github-user 时保留 github-account —— 增强不可用也不丢已确认的来源', () => {
+ // 用自己 GitHub 身份提交的那条,两个来源都成立。硬编码 ['cindy-tool'] 会让同一条
+ // issue 的来源标记随插件状态漂移:插件开着显示两个,停用 / 超时 / 离线只显示一个。
+ const [asUser] = mergeIssues([ledgerRecord({ identity: 'github-user' })], []);
+ expect(asUser.sources).toEqual(['cindy-tool', 'github-account']);
+
+ // 平台代发的作者是 cindy-issue App、不是本人 —— 这一路仍然只打 cindy-tool。
+ const [asPlatform] = mergeIssues([ledgerRecord({ identity: 'platform' })], []);
+ expect(asPlatform.sources).toEqual(['cindy-tool']);
+ });
+
+ it('链接一律由 issue 号派生,不采纳任何来源给的原值', () => {
+ // 两个产出点都要钉住:远端 overlay 与账本兜底。整行点击直接走 openExternal,
+ // 任一处采纳外部 url,被篡改的账本或被伪造的响应就能把用户带去别的站点。
+ const [fromRemote] = mergeIssues(
+ [],
+ [remoteIssue({ number: 42, htmlUrl: 'https://evil.example.com/phish' })],
+ );
+ expect(fromRemote.url).toBe('https://github.com/makecindy/cindy/issues/42');
+
+ const [fromLedger] = mergeIssues(
+ [ledgerRecord({ number: 43, url: 'https://evil.example.com/phish' })],
+ [],
+ );
+ expect(fromLedger.url).toBe('https://github.com/makecindy/cindy/issues/43');
+
+ const [fromPlatform] = mergeIssues(
+ [],
+ [],
+ [remoteIssue({ number: 44, htmlUrl: 'https://evil.example.com/phish' })],
+ );
+ expect(fromPlatform.url).toBe('https://github.com/makecindy/cindy/issues/44');
+ });
+
+ it('按创建时间倒序;同一时间戳按 issue 号兜底,顺序稳定', () => {
+ const items = mergeIssues(
+ [],
+ [
+ remoteIssue({ number: 1, createdAt: '2026-07-01T00:00:00.000Z' }),
+ remoteIssue({ number: 3, createdAt: '2026-07-20T00:00:00.000Z' }),
+ remoteIssue({ number: 2, createdAt: '2026-07-20T00:00:00.000Z' }),
+ ],
+ );
+ expect(items.map((i) => i.number)).toEqual([3, 2, 1]);
+ });
+});
+
+describe('issueTypeFromLabels', () => {
+ it('识别 bug / feature,大小写不敏感;都没有时为 null', () => {
+ expect(issueTypeFromLabels(['Bug'])).toBe('bug');
+ expect(issueTypeFromLabels(['feature'])).toBe('feature');
+ expect(issueTypeFromLabels(['needs-triage'])).toBeNull();
+ expect(issueTypeFromLabels([])).toBeNull();
+ });
+});
+
+describe('MyIssuesService.list', () => {
+ it('平台通道就绪时给出实时状态,不需要任何 GitHub 身份', async () => {
+ const searchAuthoredIssues = vi.fn();
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => [ledgerRecord({ number: 1001 })],
+ fetchPlatformIssues: async () => ({
+ ok: true,
+ page: {
+ issues: [remoteIssue({ number: 1001, state: 'closed', title: '远端标题' })],
+ totalCount: 1,
+ },
+ }),
+ resolveGithubEnhancement: async () => null,
+ searchAuthoredIssues,
+ }),
+ );
+ const result = await service.list();
+ expect(result).toMatchObject({
+ githubEnhancement: null,
+ degraded: null,
+ truncated: false,
+ });
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0]).toMatchObject({ state: 'closed', title: '远端标题' });
+ // 没有 GitHub 身份时不该去搜 GitHub。
+ expect(searchAuthoredIssues).not.toHaveBeenCalled();
+ });
+
+ it('平台读接口未就绪时降级 platform-unavailable,账本记录照常渲染', async () => {
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => [ledgerRecord()],
+ fetchPlatformIssues: async () => ({ ok: false, reason: 'platform-unavailable' }),
+ }),
+ );
+ const result = await service.list();
+ expect(result.degraded).toBe('platform-unavailable');
+ expect(result.items).toHaveLength(1);
+ expect(result.items[0]!.state).toBe('unknown');
+ });
+
+ it('未登录 / 取数失败各自映射到对应 degraded', async () => {
+ for (const reason of ['not-signed-in', 'fetch-failed'] as const) {
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => [ledgerRecord()],
+ fetchPlatformIssues: async () => ({ ok: false, reason }),
+ }),
+ );
+ await expect(service.list()).resolves.toMatchObject({ degraded: reason });
+ }
+ });
+
+ it('账本读取抛错时不拖累另两路 —— 主来源好着就必须照常出数据', async () => {
+ // electron-store 初始化会同步抛(目录不可读 / 权限 / 磁盘错误)。放在 Promise.all
+ // 之前裸调用,一次抛出就让平台请求与增强都不再启动,整页只剩 unexpected ——
+ // 而平台通道才是主来源,账本只是它未就绪时的兜底,依赖方向不能反。
+ const fetchPlatformIssues = vi.fn(async () => ({
+ ok: true as const,
+ page: { issues: [remoteIssue({ number: 77 })], totalCount: 1 },
+ }));
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => {
+ throw new Error('ENOENT: no such file or directory');
+ },
+ fetchPlatformIssues,
+ }),
+ );
+
+ const result = await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(1);
+ expect(result.items.map((i) => i.number)).toEqual([77]);
+ // 账本读不到不是平台通道的状态,不占用那三个 reason。
+ expect(result.degraded).toBeNull();
+ });
+
+ it('平台通道意外抛错时归到 fetch-failed,不把整页打挂', async () => {
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => [ledgerRecord()],
+ fetchPlatformIssues: async () => {
+ throw new Error('boom');
+ },
+ }),
+ );
+ const result = await service.list();
+ expect(result.degraded).toBe('fetch-failed');
+ expect(result.items).toHaveLength(1);
+ });
+
+ it('deps 同步抛出时也走 deadline 的清理路径,不留下悬挂计时器', async () => {
+ // 裸 run() 的写法下,同步 throw 会越过 clearTimeout,留一个跑到 12s 才触发的
+ // 计时器。用假计时器断言:结果落地后已无待触发的计时器。
+ vi.useFakeTimers();
+ try {
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => [ledgerRecord()],
+ // 注意是**同步** throw,不是 rejected promise。
+ fetchPlatformIssues: (() => {
+ throw new Error('sync boom');
+ }) as MyIssuesServiceDeps['fetchPlatformIssues'],
+ }),
+ );
+ const result = await service.list();
+ expect(result.degraded).toBe('fetch-failed');
+ expect(result.items).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('可选增强把用户自己 GitHub 名下的 issue 并进来,并回传身份', async () => {
+ const service = new MyIssuesService(
+ makeDeps({
+ fetchPlatformIssues: async () => ({
+ ok: true,
+ page: { issues: [remoteIssue({ number: 1 })], totalCount: 1 },
+ }),
+ resolveGithubEnhancement: async () => GHOST_VIEWER,
+ searchAuthoredIssues: async () => ({
+ issues: [remoteIssue({ number: 2, createdAt: '2026-07-20T00:00:00.000Z' })],
+ totalCount: 1,
+ }),
+ }),
+ );
+ const result = await service.list();
+ expect(result.githubEnhancement).toEqual({ login: 'octocat', source: 'ghost' });
+ expect(result.items.map((i) => i.number)).toEqual([2, 1]);
+ expect(result.items.find((i) => i.number === 2)!.sources).toEqual(['github-account']);
+ });
+
+ it('增强身份解析或搜索失败都不算列表降级', async () => {
+ const throwingResolve = new MyIssuesService(
+ makeDeps({
+ resolveGithubEnhancement: async () => {
+ throw new Error('ghost pipe exploded');
+ },
+ }),
+ );
+ await expect(throwingResolve.list()).resolves.toMatchObject({
+ degraded: null,
+ githubEnhancement: null,
+ });
+
+ const throwingSearch = new MyIssuesService(
+ makeDeps({
+ resolveGithubEnhancement: async () => GHOST_VIEWER,
+ searchAuthoredIssues: async () => {
+ throw new Error('HTTP 403');
+ },
+ }),
+ );
+ const result = await throwingSearch.list();
+ expect(result.degraded).toBeNull();
+ // 身份查到了就如实回传,只是这一次没并进内容。
+ expect(result.githubEnhancement).toEqual({ login: 'octocat', source: 'ghost' });
+ expect(result.items).toEqual([]);
+ });
+
+ it('任一路远端总数多于返回条数时标 truncated', async () => {
+ const platformTruncated = new MyIssuesService(
+ makeDeps({
+ fetchPlatformIssues: async () => ({
+ ok: true,
+ page: { issues: [remoteIssue()], totalCount: 240 },
+ }),
+ }),
+ );
+ await expect(platformTruncated.list()).resolves.toMatchObject({ truncated: true });
+
+ const enhancementTruncated = new MyIssuesService(
+ makeDeps({
+ resolveGithubEnhancement: async () => GHOST_VIEWER,
+ searchAuthoredIssues: async () => ({ issues: [remoteIssue()], totalCount: 240 }),
+ }),
+ );
+ await expect(enhancementTruncated.list()).resolves.toMatchObject({ truncated: true });
+ });
+
+ it('TTL 内复用缓存;force 绕过 TTL;invalidate 后重新拉', async () => {
+ let clock = 0;
+ const fetchPlatformIssues = vi.fn(async () => ({
+ ok: true as const,
+ page: { issues: [remoteIssue()], totalCount: 1 },
+ }));
+ const service = new MyIssuesService(
+ makeDeps({ fetchPlatformIssues, cacheTtlMs: 1000, now: () => clock }),
+ );
+
+ await service.list();
+ await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(1);
+
+ await service.list({ force: true });
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(2);
+
+ service.invalidate();
+ await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(3);
+
+ clock += 2000;
+ await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(4);
+ });
+
+ it('并发调用只打一次远端(in-flight 去重)', async () => {
+ let release: (() => void) | null = null;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const fetchPlatformIssues = vi.fn(async () => {
+ await gate;
+ return { ok: true as const, page: { issues: [remoteIssue()], totalCount: 1 } };
+ });
+ const service = new MyIssuesService(makeDeps({ fetchPlatformIssues }));
+ const both = Promise.all([service.list(), service.list()]);
+ release!();
+ const [first, second] = await both;
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(1);
+ expect(first).toBe(second);
+ });
+});
+
+/**
+ * 账号边界 —— 服务是进程级单例,而 issue 列表(标题/编号/GitHub 用户名)是账号私有
+ * 数据。这一组用例是安全回归:任一条挂掉都意味着切号后可能看到别人的 issue。
+ */
+describe('MyIssuesService 的账号作用域隔离', () => {
+ it('切账号后不复用上一个账号的缓存', async () => {
+ let scope = 'owner-a:1';
+ const fetchPlatformIssues = vi.fn(async () => ({
+ ok: true as const,
+ page: {
+ issues: [remoteIssue({ number: scope === 'owner-a:1' ? 111 : 222 })],
+ totalCount: 1,
+ },
+ }));
+ const service = new MyIssuesService(makeDeps({ fetchPlatformIssues, readScope: () => scope }));
+
+ expect((await service.list()).items.map((i) => i.number)).toEqual([111]);
+
+ // TTL 远未到期,但账号换了 —— 必须重新取,绝不能回放账号 A 的结果。
+ scope = 'owner-b:2';
+ expect((await service.list()).items.map((i) => i.number)).toEqual([222]);
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(2);
+
+ // 切回账号 A 也不该命中账号 B 留下的那条缓存。
+ scope = 'owner-a:3';
+ await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(3);
+ });
+
+ it('切账号后不复用上一个账号的在途请求', async () => {
+ let scope = 'owner-a:1';
+ let release: (() => void) | null = null;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const fetchPlatformIssues = vi.fn(async () => {
+ await gate;
+ return { ok: true as const, page: { issues: [remoteIssue()], totalCount: 1 } };
+ });
+ const service = new MyIssuesService(makeDeps({ fetchPlatformIssues, readScope: () => scope }));
+
+ const first = service.list();
+ scope = 'owner-b:2';
+ const second = service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(2);
+ release!();
+ // 账号 A 发起的那次落地时已不是当前账号 → 拒绝交付;
+ // 账号 B 自己那次照常拿到结果。
+ await expect(first).rejects.toSatisfy(isStaleAccountScopeError);
+ await expect(second).resolves.toMatchObject({ degraded: null });
+ });
+
+ it('请求期间切了账号 → 缓存未被投毒,新账号下次必须重新取', async () => {
+ let scope = 'owner-a:1';
+ let release: (() => void) | null = null;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const fetchPlatformIssues = vi.fn(async () => {
+ await gate;
+ return { ok: true as const, page: { issues: [remoteIssue()], totalCount: 1 } };
+ });
+ const service = new MyIssuesService(makeDeps({ fetchPlatformIssues, readScope: () => scope }));
+
+ const pending = service.list();
+ scope = 'owner-b:2'; // 结果回来时已经不是发起时那个账号了
+ release!();
+ await expect(pending).rejects.toSatisfy(isStaleAccountScopeError);
+
+ // 关键:新账号读不到任何缓存,必须重新打远端(此前那份结果没被写进去)。
+ await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(2);
+ });
+
+ it('结果落地时账号已切换 → 拒绝交付,不把旧账号数据交给调用方', async () => {
+ // 这一条专门区分「只堵缓存」与「也堵返回值」两种修法:前者会让这里拿到 resolved
+ // 的旧账号结果,测试必挂。
+ let scope = 'owner-a:1';
+ let release: (() => void) | null = null;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const service = new MyIssuesService(
+ makeDeps({
+ readScope: () => scope,
+ fetchPlatformIssues: async () => {
+ await gate;
+ return {
+ ok: true as const,
+ page: { issues: [remoteIssue({ title: '账号 A 的私有标题' })], totalCount: 1 },
+ };
+ },
+ }),
+ );
+
+ const pending = service.list();
+ scope = 'owner-b:2';
+ release!();
+ await expect(pending).rejects.toSatisfy(isStaleAccountScopeError);
+ });
+
+ it('invalidate 让在飞的旧快照不可落缓存(提交成功后下次一定看到新记录)', async () => {
+ let ledger: SubmittedIssueRecord[] = [];
+ let release: (() => void) | null = null;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let gated = true;
+ const service = new MyIssuesService(
+ makeDeps({
+ readLedger: () => ledger,
+ fetchPlatformIssues: async () => {
+ if (gated) await gate;
+ return { ok: false as const, reason: 'platform-unavailable' as const };
+ },
+ }),
+ );
+
+ // 请求先读到空账本,期间另一个窗口提交成功 → invalidate()。
+ const pending = service.list();
+ ledger = [ledgerRecord({ number: 777 })];
+ service.invalidate();
+ release!();
+ gated = false;
+ await pending;
+
+ // 那份旧快照不得落缓存,否则接下来 60s 都看不到 #777。
+ const next = await service.list();
+ expect(next.items.map((i) => i.number)).toEqual([777]);
+ });
+
+ it('可选增强卡住时不拖累主列表:超时后当作没有增强,平台结果照常返回', async () => {
+ // 插件通道默认超时 330s,而增强与平台通道是并行 await 的 —— 没有短超时的话
+ // 这里会一直挂着,页面被加载态遮住。
+ const service = new MyIssuesService(
+ makeDeps({
+ enhancementTimeoutMs: 5,
+ fetchPlatformIssues: async () => ({
+ ok: true as const,
+ page: { issues: [remoteIssue({ number: 42 })], totalCount: 1 },
+ }),
+ resolveGithubEnhancement: async () => GHOST_VIEWER,
+ // 永不 resolve,模拟插件卡死
+ searchAuthoredIssues: () => new Promise(() => {}),
+ }),
+ );
+ const result = await service.list();
+ expect(result.items.map((i) => i.number)).toEqual([42]);
+ expect(result.degraded).toBeNull();
+ // 身份解析成功过,所以身份照常回传,只是这次没并进内容。
+ expect(result.githubEnhancement).toEqual({ login: 'octocat', source: 'ghost' });
+ });
+
+ it('增强的总时长有单一 deadline:两段各自不超时但累计超预算时也会被切断', async () => {
+ // 专门区分「分阶段各起一次计时器」与「整条路径一次 deadline」:前者会让第二段
+ // 重置 deadline,两段各 40ms 在 50ms 预算下都不超时,于是总共等 80ms 才返回。
+ const started = Date.now();
+ const slow = <T>(value: T) => new Promise<T>((r) => setTimeout(() => r(value), 40));
+ const service = new MyIssuesService(
+ makeDeps({
+ enhancementTimeoutMs: 50,
+ fetchPlatformIssues: async () => ({
+ ok: true as const,
+ page: { issues: [remoteIssue({ number: 9 })], totalCount: 1 },
+ }),
+ resolveGithubEnhancement: () => slow(GHOST_VIEWER),
+ searchAuthoredIssues: () => slow({ issues: [remoteIssue({ number: 8 })], totalCount: 1 }),
+ }),
+ );
+ const result = await service.list();
+ const elapsed = Date.now() - started;
+
+ // 总 deadline 生效:在 50ms 附近被切断,不会跑到两段之和(80ms+)。
+ expect(elapsed).toBeLessThan(75);
+ // 被切断时身份已解析成功 → 照常回传,只是这次没并进内容。
+ expect(result.githubEnhancement).toEqual({ login: 'octocat', source: 'ghost' });
+ expect(result.items.map((i) => i.number)).toEqual([9]);
+ expect(result.degraded).toBeNull();
+ });
+
+ it('平台通道卡住时有总 deadline,账本记录照常渲染', async () => {
+ // 覆盖 401 → authManager.refresh() 挂死这条链:runtime 侧给 serverApiFetch 的
+ // timeoutMs 只管单次 fetch,refresh 自己无上限,所以 service 层必须有总 deadline。
+ const service = new MyIssuesService(
+ makeDeps({
+ platformTimeoutMs: 5,
+ readLedger: () => [ledgerRecord({ number: 314 })],
+ fetchPlatformIssues: () => new Promise(() => {}),
+ }),
+ );
+ const result = await service.list();
+ expect(result.degraded).toBe('fetch-failed');
+ expect(result.items.map((i) => i.number)).toEqual([314]);
+ expect(result.items[0]!.state).toBe('unknown');
+ });
+
+ it('身份解析本身卡住时同样超时,不阻塞主列表', async () => {
+ const service = new MyIssuesService(
+ makeDeps({
+ enhancementTimeoutMs: 5,
+ fetchPlatformIssues: async () => ({
+ ok: true as const,
+ page: { issues: [remoteIssue({ number: 7 })], totalCount: 1 },
+ }),
+ resolveGithubEnhancement: () => new Promise(() => {}),
+ }),
+ );
+ const result = await service.list();
+ expect(result.items.map((i) => i.number)).toEqual([7]);
+ expect(result.githubEnhancement).toBeNull();
+ });
+
+ it('invalidate 之后发起的查询不复用更早的在途请求', async () => {
+ // 只用 epoch 阻止「旧结果落缓存」是不够的:失效后发起的调用若复用那个读了旧账本
+ // 的在途 Promise,拿回的仍是不含新 issue 的快照,而页面不会自动再查。
+ let ledger: SubmittedIssueRecord[] = [];
+ let release: (() => void) | null = null;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let gated = true;
+ const fetchPlatformIssues = vi.fn(async () => {
+ if (gated) await gate;
+ return { ok: false as const, reason: 'platform-unavailable' as const };
+ });
+ const service = new MyIssuesService(makeDeps({ readLedger: () => ledger, fetchPlatformIssues }));
+
+ const stale = service.list(); // 读到空账本后卡住
+ ledger = [ledgerRecord({ number: 555 })];
+ service.invalidate(); // 另一个窗口提交成功
+
+ gated = false;
+ const fresh = service.list(); // 失效后发起 —— 必须另起,不能复用上面那个
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(2);
+ expect((await fresh).items.map((i) => i.number)).toEqual([555]);
+
+ release!();
+ await stale;
+ });
+
+ it('同一账号内 TTL 与 in-flight 复用不受影响', async () => {
+ const fetchPlatformIssues = vi.fn(async () => ({
+ ok: true as const,
+ page: { issues: [remoteIssue()], totalCount: 1 },
+ }));
+ const service = new MyIssuesService(
+ makeDeps({ fetchPlatformIssues, readScope: () => 'owner-a:1' }),
+ );
+ await service.list();
+ await service.list();
+ expect(fetchPlatformIssues).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/github-issue/__tests__/submittedIssueLedger.test.ts b/apps/desktop/src/main/github-issue/__tests__/submittedIssueLedger.test.ts
new file mode 100644
index 0000000000..81efc1baff
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/__tests__/submittedIssueLedger.test.ts
@@ -0,0 +1,112 @@
+/**
+ * 提交账本的持久化清洗:形状校验、同号去重留最新、倒序、上限。
+ * 只测纯函数,不碰 electron-store(存储层只是 get/set 一个数组)。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import type { SubmittedIssueRecord } from '../../../shared/myIssues';
+import { normalizeSubmittedIssues } from '../submittedIssueLedger';
+
+/**
+ * url 默认跟着 number 走 —— 校验要求两者一致(显示 #N 就必须点开 #N),
+ * fixture 里各写一份必然对不上。要测不一致的场景就显式覆盖 url。
+ */
+function record(over: Partial<SubmittedIssueRecord> = {}): SubmittedIssueRecord {
+ const number = over.number ?? 1001;
+ return {
+ number,
+ url: `https://github.com/makecindy/cindy/issues/${number}`,
+ title: '标题',
+ type: 'bug',
+ submittedAt: '2026-07-01T00:00:00.000Z',
+ identity: 'platform',
+ publicName: 'shuji',
+ ...over,
+ };
+}
+
+describe('normalizeSubmittedIssues', () => {
+ it('非数组或空输入返回空列表', () => {
+ expect(normalizeSubmittedIssues(undefined)).toEqual([]);
+ expect(normalizeSubmittedIssues(null)).toEqual([]);
+ expect(normalizeSubmittedIssues({ issues: [] })).toEqual([]);
+ expect(normalizeSubmittedIssues([])).toEqual([]);
+ });
+
+ it('丢掉形状不对的条目', () => {
+ const kept = record();
+ const dropped = [
+ null,
+ 'nope',
+ { ...record(), number: 0 },
+ { ...record(), number: 1.5 },
+ { ...record(), url: '' },
+ { ...record(), type: 'question' },
+ { ...record(), submittedAt: 'not-a-date' },
+ { ...record(), identity: 'someone-else' },
+ { ...record(), title: 42 },
+ ];
+ expect(normalizeSubmittedIssues([...dropped, kept])).toEqual([kept]);
+ });
+
+ it('丢掉链接不指向本仓这一号 issue 的条目', () => {
+ // 落盘文件是不可信输入,而这一页每行都声称「你在本仓提的 issue」、整行可点开。
+ // 只查「非空字符串」的写法会把下面每一条都放行。
+ const dropped = [
+ { ...record(), url: 'https://evil.example.com/makecindy/cindy/issues/1001' },
+ { ...record(), url: 'https://github.com.evil.example/makecindy/cindy/issues/1001' },
+ { ...record(), url: 'http://github.com/makecindy/cindy/issues/1001' },
+ { ...record(), url: 'https://github.com/someone/else/issues/1001' },
+ // 编号对不上:显示 #1001 却点开另一条 issue
+ { ...record(), url: 'https://github.com/makecindy/cindy/issues/9999' },
+ { ...record(), url: 'https://github.com/makecindy/cindy/pull/1001' },
+ { ...record(), url: 'javascript:alert(1)' },
+ { ...record(), url: 'not-a-url' },
+ ];
+ expect(normalizeSubmittedIssues(dropped)).toEqual([]);
+ });
+
+ it('容忍尾斜杠 —— 不误杀用户真实的历史记录', () => {
+ const withSlash = record({ url: 'https://github.com/makecindy/cindy/issues/1001/' });
+ expect(normalizeSubmittedIssues([withSlash])).toEqual([withSlash]);
+ });
+
+ it('按提交时间倒序', () => {
+ const older = record({ number: 1, submittedAt: '2026-07-01T00:00:00.000Z' });
+ const newer = record({ number: 2, submittedAt: '2026-07-20T00:00:00.000Z' });
+ expect(normalizeSubmittedIssues([older, newer]).map((r) => r.number)).toEqual([2, 1]);
+ });
+
+ it('同一 issue 号只留提交时间最新的那条(与数组顺序无关)', () => {
+ const old = record({ number: 7, title: '旧标题', submittedAt: '2026-07-01T00:00:00.000Z' });
+ const fresh = record({ number: 7, title: '新标题', submittedAt: '2026-07-25T00:00:00.000Z' });
+ for (const input of [[old, fresh], [fresh, old]]) {
+ const result = normalizeSubmittedIssues(input);
+ expect(result).toHaveLength(1);
+ expect(result[0]!.title).toBe('新标题');
+ }
+ });
+
+ it('总量压在 500 条内,保留最新的那些', () => {
+ const many = Array.from({ length: 600 }, (_, index) =>
+ record({
+ number: index + 1,
+ // index 越大时间越新
+ submittedAt: new Date(Date.UTC(2026, 0, 1) + index * 60_000).toISOString(),
+ }),
+ );
+ const result = normalizeSubmittedIssues(many);
+ expect(result).toHaveLength(500);
+ expect(result[0]!.number).toBe(600);
+ expect(result.at(-1)!.number).toBe(101);
+ });
+
+ it('github-user 记录保留 login,platform 记录保留公开署名', () => {
+ const asUser = record({ number: 11, identity: 'github-user', githubLogin: 'octocat' });
+ const asPlatform = record({ number: 12, identity: 'platform', publicName: '匿名' });
+ const result = normalizeSubmittedIssues([asUser, asPlatform]);
+ expect(result.find((r) => r.number === 11)?.githubLogin).toBe('octocat');
+ expect(result.find((r) => r.number === 12)?.publicName).toBe('匿名');
+ });
+});
diff --git a/apps/desktop/src/main/github-issue/__tests__/submittedIssueLedgerScope.test.ts b/apps/desktop/src/main/github-issue/__tests__/submittedIssueLedgerScope.test.ts
new file mode 100644
index 0000000000..3f2f3b9b97
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/__tests__/submittedIssueLedgerScope.test.ts
@@ -0,0 +1,85 @@
+/**
+ * 账本写入的账号归属回归。
+ *
+ * 提交要等用户确认 + 一次网络往返,期间可能切号;而 getStore() 走
+ * ownerScopedUserDataPath() 读的是**落地时**的账号路径。不带发起时的作用域校验,
+ * 账号 A 的提交就会写进账号 B 的账本并出现在 B 的「我的 Issue」里。
+ *
+ * 这里只测「作用域不匹配就放弃写入」这一条判据 —— electron-store 与 electron 都被
+ * mock 掉,不碰真实文件系统。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { SubmittedIssueRecord } from '../../../shared/myIssues';
+
+const scopeRef = { value: 'owner-a:1' };
+const stored: Record<string, unknown> = {};
+
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => scopeRef.value,
+ ownerScopedUserDataPath: () => '/tmp/cindy-test-owner',
+}));
+
+vi.mock('electron-store', () => ({
+ default: class FakeStore {
+ get(key: string, fallback: unknown) {
+ return stored[key] ?? fallback;
+ }
+ set(key: string, value: unknown) {
+ stored[key] = value;
+ }
+ },
+}));
+
+const { listSubmittedIssues, recordSubmittedIssue } = await import('../submittedIssueLedger');
+
+/** url 跟着 number 走 —— 清洗要求两者指向同一条 issue(见 isMyIssueUrl)。 */
+function record(over: Partial<SubmittedIssueRecord> = {}): SubmittedIssueRecord {
+ const number = over.number ?? 1061;
+ return {
+ number,
+ url: `https://github.com/makecindy/cindy/issues/${number}`,
+ title: '账号 A 提交的 issue',
+ type: 'feature',
+ submittedAt: '2026-07-30T09:12:49.000Z',
+ identity: 'platform',
+ publicName: 'shuji',
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ for (const key of Object.keys(stored)) delete stored[key];
+ scopeRef.value = 'owner-a:1';
+});
+
+describe('recordSubmittedIssue 的账号归属校验', () => {
+ it('作用域一致时正常写入', () => {
+ const next = recordSubmittedIssue(record(), 'owner-a:1');
+ expect(next.map((r) => r.number)).toEqual([1061]);
+ expect(listSubmittedIssues().map((r) => r.number)).toEqual([1061]);
+ });
+
+ it('提交期间切了账号 → 放弃写入,不把 A 的提交记进 B 的账本', () => {
+ scopeRef.value = 'owner-b:2'; // 落地时已经是另一个账号
+ const next = recordSubmittedIssue(record(), 'owner-a:1');
+ expect(next).toEqual([]);
+ expect(listSubmittedIssues()).toEqual([]);
+ });
+
+ it('同一 owner 但 generation 变了(登出再登回)同样放弃写入', () => {
+ scopeRef.value = 'owner-a:3';
+ recordSubmittedIssue(record(), 'owner-a:1');
+ expect(listSubmittedIssues()).toEqual([]);
+ });
+
+ it('放弃写入时不破坏已有账本内容', () => {
+ recordSubmittedIssue(record({ number: 1 }), 'owner-a:1');
+ scopeRef.value = 'owner-b:2';
+ const next = recordSubmittedIssue(record({ number: 2 }), 'owner-a:1');
+ // 返回的是当前账号视角下的既有列表,且没有把 #2 混进去。
+ expect(next.map((r) => r.number)).toEqual([1]);
+ expect(listSubmittedIssues().map((r) => r.number)).toEqual([1]);
+ });
+});
diff --git a/apps/desktop/src/main/github-issue/cindyGithubGhostDeps.ts b/apps/desktop/src/main/github-issue/cindyGithubGhostDeps.ts
new file mode 100644
index 0000000000..e3a5c47451
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/cindyGithubGhostDeps.ts
@@ -0,0 +1,48 @@
+/**
+ * Cindy GitHub 插件通道的真实依赖构造。
+ *
+ * 提交路径(githubUserIssueSubmitter)与「我的 Issue」查询路径(myIssuesRuntime)共用
+ * 同一份判定与同一条管子,保证两边看到的 GitHub 身份口径一致 —— 插件未装、未启用、
+ * 当前 workdir 被停用或未配凭证时,两边都必须同样认为「不可用」。
+ *
+ * 独立成文件而不是放在 index.ts 里:index.ts 需要在提交成功后调 myIssuesRuntime
+ * 让列表缓存失效,而 myIssuesRuntime 又需要这份 deps,放一起会形成循环 import。
+ */
+
+import { getGhostManager, getGhostPipeDispatcher } from '../cindy-brain';
+import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
+import { ghostSecretSaved } from '../secrets/providerSecretStore';
+import {
+ CINDY_GITHUB_GHOST_ID,
+ CINDY_GITHUB_SECRET_KEY,
+ type GithubUserIssueSubmitterDeps,
+} from './githubUserIssueSubmitter';
+
+let sharedDeps: GithubUserIssueSubmitterDeps | null = null;
+
+/**
+ * 共享实例 —— 同一次「我的 Issue」查询里,身份解析与随后的搜索用同一个对象,
+ * 不必各建一份(模式同 git-context 的 getSharedGhCliTokenSource)。
+ *
+ * 单例安全的原因:下面每个成员都是**惰性闭包**,不捕获任何状态,都是被调用的那一刻
+ * 才去查插件启用状态 / 凭证 / 管子。也正因如此,复用同一实例**并不构成**「一致快照」——
+ * 真正的不一致来自两次**调用**之间插件被停用或换了凭证,而那种情况的正确行为已经
+ * 定好:搜索失败 → 静默降级为「这次没有增强」(见 myIssuesService 的可选增强口径)。
+ */
+export function getSharedGithubUserSubmitterDeps(): GithubUserIssueSubmitterDeps {
+ if (!sharedDeps) sharedDeps = buildGithubUserSubmitterDeps();
+ return sharedDeps;
+}
+
+export function buildGithubUserSubmitterDeps(): GithubUserIssueSubmitterDeps {
+ return {
+ isGithubGhostEnabled: () =>
+ getGhostManager()
+ .list()
+ .some((ghost) => ghost.manifest.id === CINDY_GITHUB_GHOST_ID && ghost.enabled),
+ isGithubCredentialSaved: () => ghostSecretSaved(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY),
+ isGithubGhostDisabledForWorkdir: (workdir) =>
+ isGhostDisabledForWorkdir(CINDY_GITHUB_GHOST_ID, workdir),
+ callGhostTool: (request) => getGhostPipeDispatcher().callGhostTool(request),
+ };
+}
diff --git a/apps/desktop/src/main/github-issue/githubIssuePayload.ts b/apps/desktop/src/main/github-issue/githubIssuePayload.ts
new file mode 100644
index 0000000000..6410b4a52a
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/githubIssuePayload.ts
@@ -0,0 +1,122 @@
+/**
+ * Issue 响应解析(纯函数,无 electron / 无网络)。
+ *
+ * 两条通道的响应都在这里落地:
+ * - 平台通道 —— 服务端(独立仓)返回的「我提交过的 issue」。它最省力的实现是透传
+ * GitHub 对象,但也可能改成 camelCase,所以两种命名都吃;
+ * - GitHub 通道 —— GitHub REST / 插件响应(插件只剥 API 链接类字段,保留 html_url)。
+ *
+ * 一律宽容:字段缺失就降级,绝不因为多了 / 少了字段让整张列表报废。
+ */
+
+import type { RemoteIssue, RemoteIssuePage } from './myIssuesService';
+
+/**
+ * 一页结果。接受三种外层形状:`{ issues: [...] }`、`{ items: [...] }`(GitHub search
+ * 的形状)、以及裸数组 —— 服务端用哪种都不用改客户端。
+ */
+export function parseIssuePage(value: unknown): RemoteIssuePage {
+ const record = asRecord(value);
+ const rawItems = Array.isArray(value)
+ ? value
+ : Array.isArray(record?.issues)
+ ? record.issues
+ : Array.isArray(record?.items)
+ ? record.items
+ : [];
+ const issues = rawItems
+ .map(parseRemoteIssue)
+ .filter((issue): issue is RemoteIssue => issue !== null);
+ return { issues, totalCount: readTotalCount(record) };
+}
+
+function readTotalCount(record: Record<string, unknown> | null): number | null {
+ for (const key of ['total_count', 'totalCount', 'total']) {
+ const value = record?.[key];
+ if (typeof value === 'number') return value;
+ }
+ // hasMore 是布尔而非计数;true 时用「比本页多一条」表达「还有更多」。
+ const hasMore = record?.hasMore ?? record?.has_more;
+ if (hasMore === true && Array.isArray(record?.issues)) return record.issues.length + 1;
+ if (hasMore === true && Array.isArray(record?.items)) return record.items.length + 1;
+ return null;
+}
+
+export function parseRemoteIssue(value: unknown): RemoteIssue | null {
+ const record = asRecord(value);
+ if (!record) return null;
+ const number = readNumber(record, ['number', 'issueNumber']);
+ const title = readString(record, ['title']);
+ const htmlUrl = readString(record, ['html_url', 'htmlUrl', 'url']);
+ const createdAt = readString(record, ['created_at', 'createdAt']);
+ // createdAt 必须**可解析**,不只是非空:mergeIssues 的排序比较器直接对它做
+ // Date.parse 相减,不可解析会得到 NaN,让整份列表的顺序变成未定义(不是"这条排错
+ // 位置",而是整体不稳定)。账本清洗早就这样校验 submittedAt 了 —— 这里补齐对称。
+ if (
+ number === null ||
+ !Number.isInteger(number) ||
+ !title ||
+ !htmlUrl ||
+ !createdAt ||
+ !Number.isFinite(Date.parse(createdAt))
+ ) {
+ return null;
+ }
+ return {
+ number,
+ title,
+ htmlUrl,
+ // GitHub 只有 open / closed 两态;非 closed 一律按 open 处理。
+ state: readString(record, ['state']) === 'closed' ? 'closed' : 'open',
+ labels: parseLabels(record.labels ?? record.type),
+ createdAt,
+ updatedAt: readString(record, ['updated_at', 'updatedAt']),
+ commentCount: readNumber(record, ['comments', 'commentCount']),
+ };
+}
+
+/**
+ * labels 可能是对象数组、纯字符串数组,也可能是服务端直接给的单个类型字符串
+ * (提交链路只打 bug / feature 两种标签,单值形态同样够用)。
+ */
+function parseLabels(value: unknown): string[] {
+ if (typeof value === 'string') return value ? [value] : [];
+ if (!Array.isArray(value)) return [];
+ const names: string[] = [];
+ for (const label of value) {
+ if (typeof label === 'string') {
+ names.push(label);
+ continue;
+ }
+ const name = asRecord(label)?.name;
+ if (typeof name === 'string') names.push(name);
+ }
+ return names;
+}
+
+/** 插件 / REST 的 404 文案都会命中;命中后调用方把这一条降级而不是整体失败。 */
+export function isGithubNotFoundMessage(message: string): boolean {
+ return /HTTP 404|not found/i.test(message);
+}
+
+function readString(record: Record<string, unknown>, keys: string[]): string | null {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === 'string' && value.length > 0) return value;
+ }
+ return null;
+}
+
+function readNumber(record: Record<string, unknown>, keys: string[]): number | null {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+ }
+ return null;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
diff --git a/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts b/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts
index 59a1d8a031..c86b0bc659 100644
--- a/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts
+++ b/apps/desktop/src/main/github-issue/githubIssueSubmitService.ts
@@ -14,6 +14,8 @@ import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
import { CINDY_REGION_CODE } from '../../shared/regionCode.js';
import { normalizeIssuePublicName } from '../../shared/issuePublicName.js';
+import type { SubmittedIssueRecord } from '../../shared/myIssues.js';
+import { myIssueUrl } from '../../shared/myIssues.js';
import type {
IssueConfirmDecision,
IssueDraft,
@@ -86,6 +88,12 @@ export interface GithubIssueSubmitServiceDeps {
getFallbackLocale: () => string;
/** 当前 Cindy membership 的展示名,仅用于 issue 正文标记提交人。 */
getSubmitterName: () => string | undefined;
+ /**
+ * 提交成功后记账(「我的 Issue」列表靠它认出平台代发的那一半)。
+ * 只在 postIssue 真正成功后调用一次,抛错由本模块吞掉 —— 记账失败绝不能把一次
+ * 已经成功的提交翻成失败,那会诱导用户重复提交。
+ */
+ onSubmitted?: (record: SubmittedIssueRecord) => void;
}
// server 侧 github.ts 的上限(TITLE_MAX=200 / DESC_MAX=5000),超限会被 400,这里主动 clamp。
@@ -175,6 +183,12 @@ export async function submitGithubIssueWithConfirm(
appVersion: env.appVersion,
...(confirmedPublicName ? { userName: confirmedPublicName } : {}),
}));
+ recordSubmission(deps, submissionIdentity, {
+ number: result.githubIssue.number,
+ title: finalTitle,
+ type: decision.type,
+ publicName: confirmedPublicName,
+ });
return {
ok: true,
issueNumber: result.githubIssue.number,
@@ -187,6 +201,40 @@ export async function submitGithubIssueWithConfirm(
}
}
+/** 记账是 best-effort:任何异常只吞掉,不影响已经成功的提交结果。 */
+function recordSubmission(
+ deps: GithubIssueSubmitServiceDeps,
+ submissionIdentity: IssueSubmissionIdentity,
+ submitted: {
+ number: number;
+ title: string;
+ type: 'bug' | 'feature';
+ publicName: string | null;
+ },
+): void {
+ if (!deps.onSubmitted) return;
+ try {
+ deps.onSubmitted({
+ number: submitted.number,
+ // 派生而不是存 postIssue 返回的原值:账本**读取**侧用 isMyIssueUrl 强校验
+ // (必须指向本仓这一号 issue)。写入侧存原值就会两侧口径不一 —— 返回的是 API
+ // 链接或别的 host 时,这条记录写得进去、读出来却被当坏数据过滤掉,平台读接口
+ // 未就绪 / 离线时用户看不到自己刚提交的那条。url 在系统里只有这一个产出方式。
+ url: myIssueUrl(submitted.number),
+ title: submitted.title,
+ type: submitted.type,
+ submittedAt: new Date().toISOString(),
+ identity: submissionIdentity.kind === 'github-user' ? 'github-user' : 'platform',
+ ...(submissionIdentity.kind === 'github-user'
+ ? { githubLogin: submissionIdentity.login }
+ : {}),
+ ...(submitted.publicName ? { publicName: submitted.publicName } : {}),
+ });
+ } catch {
+ // 交给注入方记日志;这里连 rethrow 都不做。
+ }
+}
+
/**
* 提交链路抛错映射。平台路径按 ServerApiError 的 statusCode 字段 duck-typing,
* 用户路径按 issueErrorCode 映射,避免本模块 import 真实网络实现。
diff --git a/apps/desktop/src/main/github-issue/githubUserIssueSubmitter.ts b/apps/desktop/src/main/github-issue/githubUserIssueSubmitter.ts
index 9131405c52..931b43f812 100644
--- a/apps/desktop/src/main/github-issue/githubUserIssueSubmitter.ts
+++ b/apps/desktop/src/main/github-issue/githubUserIssueSubmitter.ts
@@ -36,22 +36,59 @@ interface IssueSubmissionError extends Error {
issueErrorCode: 'AUTH_NOT_READY' | 'NETWORK_ERROR' | 'SERVER_ERROR';
}
-interface GithubOperationFailure {
+export interface GithubOperationFailure {
ok: false;
errorCode: string;
message: string;
}
+/**
+ * 插件通道是否可用(已装、已启用、当前 workdir 未停用、且保存了凭证)。
+ * 提交路径与「我的 Issue」查询路径共用这一份判定,避免两边口径漂移。
+ */
+export function isCindyGithubGhostUsable(
+ deps: GithubUserIssueSubmitterDeps,
+ workdir?: string | null,
+): boolean {
+ return (
+ !deps.isGithubGhostDisabledForWorkdir(workdir) &&
+ deps.isGithubGhostEnabled() &&
+ deps.isGithubCredentialSaved()
+ );
+}
+
+/**
+ * 本模块对外开放的只读操作名。收成联合类型而不是 string,是为了让拼错的 tool name
+ * 在编译期就挂掉 —— 否则 `search_issues_and_prs` 少个字母要等运行到插件通道才失败,
+ * 而那条路径的失败又是**静默降级**(可选增强拿不到就当没配),几乎不会被发现。
+ */
+export type CindyGithubReadOperation = 'get_current_user' | 'search_issues_and_prs';
+
+/**
+ * 插件通道支持的全部操作名 = 只读操作 + 提交。**通道函数一律用它,不要放宽成 string**:
+ * 加新操作时改这一处,拼错立刻是编译错误。
+ */
+type CindyGithubOperation = CindyGithubReadOperation | 'create_issue';
+
+/**
+ * 经插件通道调一个只读 GitHub 操作。失败返回结构化 failure(不抛),
+ * 响应形状不对时才抛 —— 与提交路径共用同一个通道与解包逻辑。
+ */
+export function callCindyGithubOperation(
+ deps: GithubUserIssueSubmitterDeps,
+ name: CindyGithubReadOperation,
+ args: Record<string, unknown>,
+ options: { timeoutMs?: number } = {},
+): Promise<{ ok: true; data: unknown } | GithubOperationFailure> {
+ return callGithubOperation(deps, name, args, options);
+}
+
/** 已装、启用且保存了凭证时验证 token;其余场景明确选择平台代提交。 */
export async function resolveGithubIssueSubmissionIdentity(
deps: GithubUserIssueSubmitterDeps,
workdir?: string | null,
): Promise<IssueSubmissionIdentity> {
- if (
- deps.isGithubGhostDisabledForWorkdir(workdir) ||
- !deps.isGithubGhostEnabled() ||
- !deps.isGithubCredentialSaved()
- ) {
+ if (!isCindyGithubGhostUsable(deps, workdir)) {
return PLATFORM_ISSUE_SUBMISSION_IDENTITY;
}
@@ -139,7 +176,7 @@ async function requireGithubOperation(
async function callGithubOperation(
deps: GithubUserIssueSubmitterDeps,
- name: 'get_current_user' | 'create_issue',
+ name: CindyGithubOperation,
args: Record<string, unknown>,
options: { timeoutMs?: number } = {},
): Promise<{ ok: true; data: unknown } | GithubOperationFailure> {
diff --git a/apps/desktop/src/main/github-issue/index.ts b/apps/desktop/src/main/github-issue/index.ts
index 77fb588ccb..dd207afd9f 100644
--- a/apps/desktop/src/main/github-issue/index.ts
+++ b/apps/desktop/src/main/github-issue/index.ts
@@ -11,22 +11,22 @@ import os from 'node:os';
import { app } from 'electron';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import { activeOwnerScopeKey } from '../appSessionState.js';
import { getCurrentMembershipDisplayName } from '../authManager';
-import { getGhostManager, getGhostPipeDispatcher } from '../cindy-brain';
-import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
-import { ghostSecretSaved } from '../secrets/providerSecretStore';
+import { createLogger } from '../logger.js';
import { serverApiFetch } from '../serverApiClient';
import { getClientEndpoint } from '../clientEndpointsService';
import type { IssueConfirmBridge } from './issueConfirmBridge';
import { getAppCapabilities } from '../appCapabilities.js';
+import { buildGithubUserSubmitterDeps } from './cindyGithubGhostDeps.js';
import {
submitGithubIssueWithConfirm,
type GithubIssueSubmitResult,
type SubmitIssueRequest,
} from './githubIssueSubmitService';
+import { invalidateMyIssuesCache } from './myIssuesRuntime.js';
+import { recordSubmittedIssue } from './submittedIssueLedger.js';
import {
- CINDY_GITHUB_GHOST_ID,
- CINDY_GITHUB_SECRET_KEY,
postGithubIssueAsUser,
resolveGithubIssueSubmissionIdentity,
type GithubUserIssueSubmitterDeps,
@@ -35,6 +35,8 @@ import {
export { IssueConfirmBridge } from './issueConfirmBridge';
export type { IssueConfirmDecision } from './issueConfirmBridge';
+const log = createLogger('github-issue');
+
let bridgeHolder: IssueConfirmBridge | null = null;
export function initGithubIssueSubmit(bridge: IssueConfirmBridge): void {
@@ -59,16 +61,10 @@ export async function submitGithubIssueForSession(
message: 'Cindy 主进程 issue 提交服务尚未就绪,请告知用户稍等几秒后重试。',
};
}
- const githubUserSubmitterDeps: GithubUserIssueSubmitterDeps = {
- isGithubGhostEnabled: () =>
- getGhostManager()
- .list()
- .some((ghost) => ghost.manifest.id === CINDY_GITHUB_GHOST_ID && ghost.enabled),
- isGithubCredentialSaved: () => ghostSecretSaved(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY),
- isGithubGhostDisabledForWorkdir: (workdir) =>
- isGhostDisabledForWorkdir(CINDY_GITHUB_GHOST_ID, workdir),
- callGhostTool: (request) => getGhostPipeDispatcher().callGhostTool(request),
- };
+ const githubUserSubmitterDeps: GithubUserIssueSubmitterDeps = buildGithubUserSubmitterDeps();
+ // 在**发起时**锁定账号作用域:提交要等用户确认 + 一次网络往返,期间完全可能切号。
+ // 记账时拿它核对,绝不把这条提交写进另一个账号的账本(见 recordSubmittedIssue)。
+ const submitScope = activeOwnerScopeKey();
return submitGithubIssueWithConfirm(
{
confirm: (sessionId, draft, env, submissionIdentity, suggestedPublicName) =>
@@ -100,6 +96,23 @@ export async function submitGithubIssueForSession(
getRegion: () => CURRENT_CINDY_REGION,
getFallbackLocale: () => app.getLocale(),
getSubmitterName: getCurrentMembershipDisplayName,
+ onSubmitted: (record) => {
+ try {
+ recordSubmittedIssue(record, submitScope);
+ } catch (err) {
+ // 账本只服务「我的 Issue」列表;写失败最多让这条不出现在列表里,
+ // 绝不能影响已经成功的提交。
+ log.warn('submitted issue ledger write failed', {
+ issueNumber: record.number,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ // **无论记账成功与否都要失效**:这两件事互相独立 —— 平台通道就绪时,列表
+ // 本来就能从服务端看到刚提交的那条,不该因为本机账本写失败而在 60s TTL 内
+ // 一直看不见。(放在同一个 try 里时,记账抛错会把它一起跳过。)
+ invalidateMyIssuesCache();
+ }
+ },
},
req,
);
diff --git a/apps/desktop/src/main/github-issue/myIssuesRuntime.ts b/apps/desktop/src/main/github-issue/myIssuesRuntime.ts
new file mode 100644
index 0000000000..19d807f48a
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/myIssuesRuntime.ts
@@ -0,0 +1,208 @@
+/**
+ * myIssuesRuntime —— 「我的 Issue」查询的真实依赖接线。
+ *
+ * 主通道 = 平台公共能力,与提交 issue 完全同源:同一个 github-server
+ * (`githubApiBaseUrl`)、同一份 Cindy 登录态。**不要求用户有 GitHub 账号**。
+ * 服务端(独立仓)尚未提供这条读接口时返回 404,这里归一成
+ * `platform-unavailable`,由 service 降级成「只展示本机账本」,接口上线后零改动生效。
+ *
+ * 可选增强 = 用户自己的 GitHub 身份,仅用于把他**直接在 GitHub 上**提的 issue 也并
+ * 进来。两条来源,都只是加成:
+ * 1. `ghost` —— Cindy GitHub 插件(PAT 存在加密 secret store,main 侧读不到明文,
+ * 只能经 call_tool 走);
+ * 2. `gh-cli` —— 本机 `gh auth token`(与 PR 状态徽标同一个来源)。
+ * 两者都没有属于正常状态,不去碰 GitHub 匿名额度(60 req/h,很快 403)。
+ */
+
+import { GithubClient } from '@cindy/github-client';
+
+import { MY_ISSUES_REPOSITORY, type MyIssuesDegradedReason } from '../../shared/myIssues.js';
+import { getAppCapabilities } from '../appCapabilities.js';
+import { activeOwnerScopeKey } from '../appSessionState.js';
+import { getClientEndpoint } from '../clientEndpointsService';
+import { getSharedGhCliTokenSource } from '../git-context/ghCliTokenSource.js';
+import { createLogger } from '../logger.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
+import { serverApiFetch } from '../serverApiClient';
+import { getSharedGithubUserSubmitterDeps } from './cindyGithubGhostDeps.js';
+import { parseIssuePage } from './githubIssuePayload.js';
+import {
+ callCindyGithubOperation,
+ isCindyGithubGhostUsable,
+ type GithubUserIssueSubmitterDeps,
+} from './githubUserIssueSubmitter.js';
+import {
+ MyIssuesService,
+ SEARCH_PAGE_SIZE,
+ type GithubEnhancementViewer,
+ type PlatformIssuesOutcome,
+ type RemoteIssuePage,
+} from './myIssuesService.js';
+import { listSubmittedIssues } from './submittedIssueLedger.js';
+
+const log = createLogger('github-issue/my-issues-runtime');
+
+/** 平台读接口。与 POST /api/github/issues 同一个服务,同一份登录态。 */
+const PLATFORM_MY_ISSUES_PATH = '/api/github/issues/mine';
+
+/** GitHub 用户名字符集。拼进 search q 前必须校验,否则 login 里的空格 / 冒号会变成查询限定符。 */
+const GITHUB_LOGIN_RE = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
+
+/**
+ * 平台列表请求的上限。serverApiFetch 默认不设 deadline,而这条是页面加载路径,
+ * 与增强分支并行 await —— 不设上限时服务端 hang 住会把整页钉在 loading。
+ */
+const PLATFORM_FETCH_TIMEOUT_MS = 10_000;
+
+const GHOST_IDENTITY_TIMEOUT_MS = 5_000;
+/**
+ * 增强搜索的插件通道超时。service 层另有一道整体超时兜着,但这里也必须传 ——
+ * 那道只是放弃等待,这道才真正让插件调用自己了结(通道默认 330s)。
+ */
+const GHOST_SEARCH_TIMEOUT_MS = 6_000;
+
+let serviceInstance: MyIssuesService | null = null;
+
+export function getMyIssuesService(): MyIssuesService {
+ if (!serviceInstance) {
+ serviceInstance = new MyIssuesService({
+ readLedger: listSubmittedIssues,
+ fetchPlatformIssues: fetchPlatformIssues,
+ resolveGithubEnhancement: resolveGithubEnhancement,
+ searchAuthoredIssues: searchAuthoredIssues,
+ readScope: activeOwnerScopeKey,
+ });
+ }
+ return serviceInstance;
+}
+
+/** 提交成功后让列表缓存立即失效,不然新提交的那条最多要等 60s 才出现。 */
+export function invalidateMyIssuesCache(): void {
+ serviceInstance?.invalidate();
+}
+
+
+/** 平台通道。约定不抛:所有失败归一成 reason,由 UI 如实说明。 */
+async function fetchPlatformIssues(): Promise<PlatformIssuesOutcome> {
+ if (!getAppCapabilities().canUseCindyAccountServices) {
+ return { ok: false, reason: 'not-signed-in' };
+ }
+ try {
+ const data = await serverApiFetch<unknown>(PLATFORM_MY_ISSUES_PATH, {
+ method: 'GET',
+ // 与提交路径同源;resolver 形态保证 401 refresh 切区域后重新读端点。
+ baseUrl: () => getClientEndpoint('githubApiBaseUrl'),
+ // 必须显式传:serverApiFetch 默认 timeoutMs=0 即**不设 deadline**。这是页面
+ // 加载路径,且与增强分支是并行 await 的 —— 服务端连上却不回时,不设上限会让
+ // 本机账本一直被 loading 遮住。超时按 fetch-failed 降级。
+ timeoutMs: PLATFORM_FETCH_TIMEOUT_MS,
+ });
+ return { ok: true, page: parseIssuePage(data) };
+ } catch (err) {
+ const reason = mapPlatformFailure(err);
+ log.debug('platform my-issues fetch failed', { reason, error: errorText(err) });
+ return { ok: false, reason };
+ }
+}
+
+/**
+ * 按 ServerApiError 的 statusCode duck-typing(不 import 网络实现的具体类型)。
+ * 404 / 501 = 服务端还没提供这条读接口,是**预期状态**而非故障。
+ */
+function mapPlatformFailure(err: unknown): MyIssuesDegradedReason {
+ const statusCode =
+ err && typeof err === 'object' && 'statusCode' in err
+ ? (err as { statusCode?: unknown }).statusCode
+ : undefined;
+ if (statusCode === 404 || statusCode === 501) return 'platform-unavailable';
+ if (statusCode === 401 || statusCode === 403) return 'not-signed-in';
+ return 'fetch-failed';
+}
+
+async function resolveGithubEnhancement(): Promise<GithubEnhancementViewer | null> {
+ const ghostDeps = getSharedGithubUserSubmitterDeps();
+ // workdir 传 null:/issues 是全局页面,没有会话工作目录上下文。
+ if (isCindyGithubGhostUsable(ghostDeps, null)) {
+ const login = await readGhostViewerLogin(ghostDeps);
+ if (login) return { source: 'ghost', login };
+ }
+
+ const token = await getSharedGhCliTokenSource().readToken();
+ if (!token) return null;
+ try {
+ const user = await userScopedClient(token).getCurrentUser();
+ if (typeof user.login === 'string' && user.login.length > 0) {
+ return { source: 'gh-cli', login: user.login, token };
+ }
+ } catch (err) {
+ log.debug('gh cli viewer lookup failed', { error: errorText(err) });
+ }
+ return null;
+}
+
+async function readGhostViewerLogin(
+ deps: GithubUserIssueSubmitterDeps,
+): Promise<string | null> {
+ try {
+ const operation = await callCindyGithubOperation(deps, 'get_current_user', {}, {
+ timeoutMs: GHOST_IDENTITY_TIMEOUT_MS,
+ });
+ if (!operation.ok) {
+ log.debug('ghost viewer lookup unavailable', { message: operation.message });
+ return null;
+ }
+ const login = (operation.data as { login?: unknown } | null)?.login;
+ return typeof login === 'string' && login.trim().length > 0 ? login.trim() : null;
+ } catch (err) {
+ log.debug('ghost viewer lookup threw', { error: errorText(err) });
+ return null;
+ }
+}
+
+async function searchAuthoredIssues(
+ viewer: GithubEnhancementViewer,
+ login: string,
+): Promise<RemoteIssuePage> {
+ if (!GITHUB_LOGIN_RE.test(login)) {
+ throw new Error(`refusing to search with a malformed GitHub login: ${login}`);
+ }
+ const { owner, repo } = MY_ISSUES_REPOSITORY;
+ const q = `repo:${owner}/${repo} is:issue author:${login}`;
+ const params = { q, sort: 'created', order: 'desc' as const, per_page: SEARCH_PAGE_SIZE };
+
+ if (viewer.source === 'ghost') {
+ const operation = await callCindyGithubOperation(
+ getSharedGithubUserSubmitterDeps(),
+ 'search_issues_and_prs',
+ params,
+ { timeoutMs: GHOST_SEARCH_TIMEOUT_MS },
+ );
+ if (!operation.ok) throw new Error(operation.message);
+ return parseIssuePage(operation.data);
+ }
+
+ return parseIssuePage(await repoScopedClient(requireToken(viewer)).searchIssuesAndPRs(params));
+}
+
+function requireToken(viewer: GithubEnhancementViewer): string {
+ if (!viewer.token) throw new Error('gh-cli viewer is missing its token');
+ return viewer.token;
+}
+
+/** fetchImpl:api.github.com 是境外端点,走吃系统代理的通道(同 git-context)。 */
+function repoScopedClient(token: string): GithubClient {
+ return new GithubClient({
+ token,
+ owner: MY_ISSUES_REPOSITORY.owner,
+ repo: MY_ISSUES_REPOSITORY.repo,
+ fetchImpl: outboundFetch,
+ });
+}
+
+function userScopedClient(token: string): GithubClient {
+ return new GithubClient({ token, fetchImpl: outboundFetch });
+}
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/apps/desktop/src/main/github-issue/myIssuesService.ts b/apps/desktop/src/main/github-issue/myIssuesService.ts
new file mode 100644
index 0000000000..8e1c8c97ac
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/myIssuesService.ts
@@ -0,0 +1,472 @@
+/**
+ * myIssuesService —— /issues 页面「我的 Issue」列表的业务体。
+ *
+ * 核心口径:**看自己的 issue 与提交 issue 走同一条公共能力**,只要 Cindy 登录态,
+ * 不要求用户有 GitHub 账号。三路输入:
+ * 1. 平台通道(主)—— 服务端按 Cindy 账号返回提交记录 + 实时状态,跨设备;
+ * 2. 本机账本 —— 产品内提交时落在本机的记录。平台接口未就绪 / 离线时是唯一来源,
+ * 此时状态标 unknown,但标题、编号、类型、时间、链接照常可见;
+ * 3. GitHub 账号(可选增强)—— 配了插件 / gh CLI 才有,把用户自己 GitHub 名下的
+ * issue 并进来。缺它只是少一部分内容,**不构成任何前提**。
+ *
+ * 其它设计约束:
+ * - 状态是易变远端数据,**不落库**;60s TTL 内存缓存 + in-flight 去重,
+ * 模式与 git-context/prStatusService 一致。
+ * - 结果超一页会截断,并在返回值里显式标出,不静默丢。
+ * - 依赖全注入、模块 electron-free,单测不碰网络与 Electron。
+ */
+
+import type {
+ GithubEnhancementSource,
+ MyIssueItem,
+ MyIssueSource,
+ MyIssuesDegradedReason,
+ MyIssuesResult,
+ SubmittedIssueRecord,
+} from '../../shared/myIssues.js';
+import { myIssueUrl } from '../../shared/myIssues.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('github-issue/my-issues');
+
+const DEFAULT_CACHE_TTL_MS = 60_000;
+/**
+ * 可选 GitHub 增强的整体超时。插件通道默认工具超时是 330s
+ * (cindy-brain/pipeDispatcher),而增强与平台通道是 Promise.all 并行等的 ——
+ * 不设短超时,插件卡住时账本与平台结果早已就绪也会被加载态遮上五分半。
+ * 增强只是加成,超时就当「没有增强」,绝不拖累主列表。
+ */
+const DEFAULT_ENHANCEMENT_TIMEOUT_MS = 8_000;
+
+/**
+ * 平台通道的整体超时。比 runtime 侧给 serverApiFetch 的单次 fetch 上限更长,
+ * 因为它要覆盖**整条调用链**:401 → authManager.refresh() → 重试。那次 refresh
+ * 自己是 `timeoutMs: 0`(无上限),所以只约束单次 fetch 挡不住整条链挂死。
+ */
+const DEFAULT_PLATFORM_TIMEOUT_MS = 12_000;
+/** 单次查询只取一页;更多就截断并让 UI 明说,不静默丢也不翻页打爆额度。 */
+export const SEARCH_PAGE_SIZE = 100;
+
+/** 可选增强的 GitHub 身份。token 只在 gh CLI 路径存在(插件路径拿不到明文)。 */
+export interface GithubEnhancementViewer {
+ source: GithubEnhancementSource;
+ login: string;
+ token?: string;
+}
+
+/** 远端 issue 的必要字段子集(平台响应与 GitHub 响应的公共部分)。 */
+export interface RemoteIssue {
+ number: number;
+ title: string;
+ htmlUrl: string;
+ state: 'open' | 'closed';
+ labels: string[];
+ createdAt: string;
+ updatedAt: string | null;
+ commentCount: number | null;
+}
+
+/** 一页远端结果 + 远端总数;拿不到总数时为 null。 */
+export interface RemoteIssuePage {
+ issues: RemoteIssue[];
+ totalCount: number | null;
+}
+
+/** 平台通道的结果。unavailable 表示服务端还没提供这条读接口。 */
+export type PlatformIssuesOutcome =
+ | { ok: true; page: RemoteIssuePage }
+ | { ok: false; reason: MyIssuesDegradedReason };
+
+export interface MyIssuesServiceDeps {
+ readLedger: () => SubmittedIssueRecord[];
+ /** 平台通道:按 Cindy 登录态取「我提交过的 issue」。永不抛,失败归一为 reason。 */
+ fetchPlatformIssues: () => Promise<PlatformIssuesOutcome>;
+ /** 可选增强的 GitHub 身份;没配返回 null(正常状态)。 */
+ resolveGithubEnhancement: () => Promise<GithubEnhancementViewer | null>;
+ /** 搜该 login 名下的 issue。抛错只丢掉增强部分,不影响主列表。 */
+ searchAuthoredIssues: (
+ viewer: GithubEnhancementViewer,
+ login: string,
+ ) => Promise<RemoteIssuePage>;
+ /**
+ * 当前账号作用域标识(data owner + session generation)。**这是安全边界**:
+ * issue 列表含标题、编号与 GitHub 用户名,属于账号私有数据。服务是进程级单例,
+ * 缓存与在途请求都必须按它键控,否则 60s TTL 内切号会让新账号看到上一个账号的
+ * issue 历史。切号时该值必须变化。
+ */
+ readScope: () => string;
+ cacheTtlMs?: number;
+ /** 可选增强整条路径的超时,默认 8s;<=0 关闭(仅测试用)。 */
+ enhancementTimeoutMs?: number;
+ /** 平台通道整条调用链的超时,默认 12s;<=0 关闭(仅测试用)。 */
+ platformTimeoutMs?: number;
+ now?: () => number;
+}
+
+/** 结果落地时账号已切换 —— 这份数据属于别人,拒绝交付。 */
+export const STALE_ACCOUNT_SCOPE_CODE = 'stale-account-scope';
+
+export function isStaleAccountScopeError(err: unknown): boolean {
+ return (
+ !!err &&
+ typeof err === 'object' &&
+ (err as { myIssuesErrorCode?: unknown }).myIssuesErrorCode === STALE_ACCOUNT_SCOPE_CODE
+ );
+}
+
+function staleAccountScopeError(): Error {
+ return Object.assign(
+ new Error('active account changed while the issue list was loading; result discarded'),
+ { myIssuesErrorCode: STALE_ACCOUNT_SCOPE_CODE },
+ );
+}
+
+interface CacheEntry {
+ at: number;
+ scope: string;
+ result: MyIssuesResult;
+}
+
+export class MyIssuesService {
+ private readonly deps: MyIssuesServiceDeps;
+ private readonly ttlMs: number;
+ private readonly now: () => number;
+ private cache: CacheEntry | null = null;
+ private inFlight: {
+ scope: string;
+ /** 发起时的账本世代。invalidate() 之后的调用不得复用更早的在途请求。 */
+ epoch: number;
+ promise: Promise<MyIssuesResult>;
+ } | null = null;
+ /** 账本世代。invalidate() 递增,使早于它发起的在途结果不再可缓存。 */
+ private cacheEpoch = 0;
+
+ constructor(deps: MyIssuesServiceDeps) {
+ this.deps = deps;
+ this.ttlMs = deps.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
+ this.now = deps.now ?? Date.now;
+ }
+
+ /** force=true 绕过 TTL(手动刷新按钮),但仍复用**同账号**正在飞的请求。 */
+ async list(options: { force?: boolean } = {}): Promise<MyIssuesResult> {
+ const scope = this.deps.readScope();
+ if (
+ !options.force &&
+ this.cache &&
+ this.cache.scope === scope &&
+ this.now() - this.cache.at < this.ttlMs
+ ) {
+ return this.cache.result;
+ }
+ // 发起时的账本世代。invalidate() 会递增它 —— 见 settle() 的两条不变量。
+ const epochAtStart = this.cacheEpoch;
+ // 复用在途请求要求**账号与世代都相同**:只比 scope 的话,提交成功
+ // (invalidate 递增世代)之后发起的查询会复用那个读了旧账本的在途请求,
+ // 拿回不含新 issue 的快照,而页面不会自动再查一次。
+ if (
+ this.inFlight &&
+ this.inFlight.scope === scope &&
+ this.inFlight.epoch === epochAtStart
+ ) {
+ return this.inFlight.promise;
+ }
+ const promise = this.load()
+ .then((result) => this.settle(result, scope, epochAtStart))
+ .finally(() => {
+ // 只清自己那条,别把切号后新起的在途请求误清掉。
+ if (this.inFlight?.promise === promise) this.inFlight = null;
+ });
+ this.inFlight = { scope, epoch: epochAtStart, promise };
+ return promise;
+ }
+
+ /**
+ * 结果落地的**唯一**收口。两条不变量刻意分开判,因为它们并不对称 ——
+ * 上一版把两者混成一个「不写缓存」的判断,于是漏掉了「也不能返回」这半条:
+ *
+ * 1. 归属(安全):结果只能交给发起它的那个账号。落地时 scope 变了说明期间切了号,
+ * 这份数据属于别人 —— **既不返回也不缓存**,直接拒绝,让调用方按新账号重取。
+ * 2. 新鲜度(正确性):落地时 epoch 变了说明期间有提交成功过。数据仍是本账号的,
+ * 所以照常**返回**(拒绝只会让刚提交完的用户看到一次假错误),但**不得落缓存** ——
+ * 否则接下来 60s 都会命中这个不含新 issue 的旧快照。
+ */
+ private settle(result: MyIssuesResult, scope: string, epochAtStart: number): MyIssuesResult {
+ if (this.deps.readScope() !== scope) {
+ throw staleAccountScopeError();
+ }
+ if (this.cacheEpoch === epochAtStart) {
+ this.cache = { at: this.now(), scope, result };
+ }
+ return result;
+ }
+
+ /**
+ * 提交成功后调用:账本变了,缓存立即失效,下次进页面能看到新提交的那条。
+ * 递增 epoch 是关键 —— 只清 cache 挡不住「早于本次提交发起、晚于本次提交完成」
+ * 的那个请求把旧快照写回来。
+ */
+ invalidate(): void {
+ this.cache = null;
+ this.cacheEpoch += 1;
+ }
+
+ private async load(): Promise<MyIssuesResult> {
+ const ledger = this.readLedgerSafely();
+
+ // 两路互不阻塞:平台通道挂了不能连可选增强一起拖掉,反之亦然。
+ const [platform, enhancement] = await Promise.all([
+ this.loadPlatform(),
+ this.loadGithubEnhancement(),
+ ]);
+
+ return {
+ items: mergeIssues(ledger, enhancement.issues, platform.issues),
+ githubEnhancement: enhancement.viewer
+ ? { login: enhancement.viewer.login, source: enhancement.viewer.source }
+ : null,
+ degraded: platform.degraded,
+ truncated: platform.truncated || enhancement.truncated,
+ };
+ }
+
+ /**
+ * 账本读取失败不得拖累另两路 —— **依赖方向不能反**:平台通道才是主来源,账本只是
+ * 它未就绪 / 离线时的兜底。
+ *
+ * electron-store 的初始化会同步抛出(目录不可读、权限、磁盘错误);裸调用放在
+ * Promise.all 之前,一次抛出就让平台请求与 GitHub 增强**都不再启动**,整页只剩
+ * unexpected —— 明明主来源好着,用户却什么都看不到。
+ *
+ * 不计入 degraded:那三个 reason 讲的都是平台通道的状态。账本读不到时,平台正常
+ * 就能给出完整列表(没有可见损失),平台也失败则用户已经看到对应提示。
+ */
+ private readLedgerSafely(): SubmittedIssueRecord[] {
+ try {
+ return this.deps.readLedger();
+ } catch (err) {
+ log.warn('reading the submitted-issue ledger failed; continuing without it', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return [];
+ }
+ }
+
+ private async loadPlatform(): Promise<{
+ issues: RemoteIssue[];
+ degraded: MyIssuesDegradedReason | null;
+ truncated: boolean;
+ }> {
+ let outcome: PlatformIssuesOutcome;
+ try {
+ // 总 deadline 覆盖整条调用链,不只是单次 fetch:401 之后 serverApiFetch 会等
+ // authManager.refresh(),而那次 refresh 自己无超时上限,只约束 fetch 挡不住
+ // 整条链挂死、把本机账本一直遮在 loading 后面。
+ outcome = await this.withDeadline(
+ () => this.deps.fetchPlatformIssues(),
+ this.deps.platformTimeoutMs ?? DEFAULT_PLATFORM_TIMEOUT_MS,
+ 'platform',
+ );
+ } catch (err) {
+ // fetchPlatformIssues 约定不抛;超时或它真抛了都不能把整页打挂。
+ log.warn('platform issues fetch failed', { error: errorText(err) });
+ return { issues: [], degraded: 'fetch-failed', truncated: false };
+ }
+ if (!outcome.ok) {
+ log.debug('platform issues unavailable', { reason: outcome.reason });
+ return { issues: [], degraded: outcome.reason, truncated: false };
+ }
+ return {
+ issues: outcome.page.issues,
+ degraded: null,
+ truncated: isTruncated(outcome.page),
+ };
+ }
+
+ /**
+ * 可选增强。整条路径(身份解析 + 搜索)共用**一次**总 deadline —— 分阶段各起一次
+ * 计时器会让第二段重置 deadline,页面最坏等两倍时长(#1103 review 实例:注释写
+ * 「整条路径 8s」,实现却是 8s + 8s)。
+ *
+ * 插件通道自己的默认超时长达 330s,而这一路与平台通道并行 await,卡住就等于把
+ * 整页遮住。超时、失败、没配置三种情况对用户是同一个结果 ——「这次没有增强」,
+ * 主列表照常出。
+ *
+ * 注:runtime 侧另给插件调用传了各自的 timeoutMs(身份 5s / 搜索 6s),那是让**通道
+ * 自己了结**,与这里的页面等待上限目的不同,不能互相替代。
+ */
+ private async loadGithubEnhancement(): Promise<{
+ viewer: GithubEnhancementViewer | null;
+ issues: RemoteIssue[];
+ truncated: boolean;
+ }> {
+ // 总超时触发时也要能回传已经解析成功的身份:header 照常显示并入了谁名下的 issue,
+ // 只是这一次没并进内容。所以把它记在闭包外。
+ let resolved: GithubEnhancementViewer | null = null;
+ try {
+ return await this.withDeadline(async () => {
+ resolved = await this.deps.resolveGithubEnhancement();
+ const viewer = resolved;
+ if (!viewer) return { viewer: null, issues: [], truncated: false };
+ try {
+ const page = await this.deps.searchAuthoredIssues(viewer, viewer.login);
+ return { viewer, issues: page.issues, truncated: isTruncated(page) };
+ } catch (err) {
+ // 搜索失败(非超时)不算列表降级 —— 主路径是平台通道。
+ log.debug('github enhancement search failed', { error: errorText(err) });
+ return { viewer, issues: [], truncated: false };
+ }
+ }, this.deps.enhancementTimeoutMs ?? DEFAULT_ENHANCEMENT_TIMEOUT_MS, 'enhancement');
+ } catch (err) {
+ // 没有 GitHub 身份是正常状态;解析失败与总超时同样只是「这次没有增强」。
+ log.debug('github enhancement unavailable', { error: errorText(err) });
+ return { viewer: resolved, issues: [], truncated: false };
+ }
+ }
+
+ /**
+ * `load()` 里**每一条**并行分支的总 deadline —— 唯一实现,新增分支照同一形状套。
+ *
+ * 「一条分支挂住就把整页钉在 loading」这个缺陷在 review 里出现过四次(增强身份、
+ * 增强搜索、平台单次 fetch、平台 401-refresh 链),每次都是某条路径没有上限。
+ * 所以 deadline 只留这一个入口:传 run + 预算,不要在分支内部各自 new 计时器
+ * (那样第二段还会重置前一段的 deadline)。`<=0` 关闭,仅测试用。
+ */
+ private withDeadline<T>(run: () => Promise<T>, timeoutMs: number, label: string): Promise<T> {
+ if (timeoutMs <= 0) return run();
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new Error(`my-issues ${label} timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ const settleOk = (value: T) => {
+ clearTimeout(timer);
+ resolve(value);
+ };
+ const settleErr = (err: unknown) => {
+ clearTimeout(timer);
+ reject(err);
+ };
+ // try/catch 而不是 Promise.resolve().then(run):run 若**同步**抛出(某个 deps
+ // 实现直接 throw 而非返回 rejected promise),裸 run() 会让异常越过清理路径,
+ // 留下一个跑到超时才触发的计时器。包一层微任务也能修,但那会把**所有**调用的
+ // 远端发起时刻推后一个微任务 —— 为一个边缘缺陷改掉全部时序,副作用比缺陷本身大
+ // (在途去重的语义就依赖「list() 同步就已发起请求」)。
+ try {
+ run().then(settleOk, settleErr);
+ } catch (err) {
+ settleErr(err);
+ }
+ });
+ }
+}
+
+/**
+ * 合并三路输入,按 issue 号去重、远端字段覆盖账本历史字段(标题会被维护者改),
+ * 按创建时间倒序。纯函数,单测直接调。
+ *
+ * 来源标记的区别是关键:
+ * - `authored` 是按 `author:<login>` 搜出来的,命中即证明是本人 GitHub 账号发的 →
+ * 打 github-account;
+ * - `platform` 是服务端按 Cindy 账号返回的产品内提交记录。平台代发的 issue 在
+ * GitHub 上作者是 cindy-issue App,**不是**本人 → 只打 cindy-tool。
+ */
+export function mergeIssues(
+ ledger: SubmittedIssueRecord[],
+ authored: RemoteIssue[],
+ platform: RemoteIssue[] = [],
+): MyIssueItem[] {
+ const byNumber = new Map<number, MyIssueItem>();
+
+ for (const record of ledger) {
+ byNumber.set(record.number, ledgerOnlyItem(record));
+ }
+ for (const issue of platform) {
+ byNumber.set(issue.number, overlayRemote(byNumber.get(issue.number), issue, 'cindy-tool'));
+ }
+ for (const issue of authored) {
+ byNumber.set(issue.number, overlayRemote(byNumber.get(issue.number), issue, 'github-account'));
+ }
+
+ return [...byNumber.values()].sort((a, b) => {
+ const delta = Date.parse(b.createdAt) - Date.parse(a.createdAt);
+ // 同一时间戳时按 issue 号兜底,保证顺序稳定、不随 Map 插入顺序抖。
+ return delta !== 0 ? delta : b.number - a.number;
+ });
+}
+
+function overlayRemote(
+ existing: MyIssueItem | undefined,
+ issue: RemoteIssue,
+ source: MyIssueSource,
+): MyIssueItem {
+ const sources: MyIssueSource[] = existing ? [...existing.sources] : [];
+ if (!sources.includes(source)) sources.push(source);
+ return {
+ number: issue.number,
+ // 派生,不用 issue.htmlUrl —— 见 shared/myIssues.ts 的 myIssueUrl 注释。
+ url: myIssueUrl(issue.number),
+ title: issue.title,
+ // 远端标签被人工清掉时回退账本记的类型,而不是莫名变成「无类型」。
+ type: issueTypeFromLabels(issue.labels) ?? existing?.type ?? null,
+ state: issue.state,
+ createdAt: issue.createdAt,
+ updatedAt: issue.updatedAt,
+ commentCount: issue.commentCount,
+ sources: sortSources(sources),
+ };
+}
+
+/** 固定「产品内提交」在前,保证同一条 issue 的来源顺序不随合并顺序抖。 */
+function sortSources(sources: MyIssueSource[]): MyIssueSource[] {
+ const order: MyIssueSource[] = ['cindy-tool', 'github-account'];
+ return order.filter((source) => sources.includes(source));
+}
+
+/** 拿不到远端数据时的形态:标题用账本记的那一版,状态明确标 unknown。 */
+function ledgerOnlyItem(record: SubmittedIssueRecord): MyIssueItem {
+ return {
+ number: record.number,
+ // 同上:账本落盘的 url 也不直接用,一律按 number 派生。
+ url: myIssueUrl(record.number),
+ title: record.title,
+ type: record.type,
+ state: 'unknown',
+ createdAt: record.submittedAt,
+ updatedAt: null,
+ commentCount: null,
+ sources: sourcesFromLedger(record),
+ };
+}
+
+/**
+ * 账本记录自带的来源。`identity` 是**提交那一刻**确定下来的事实,比事后按
+ * `author:` 搜索更可靠 —— 用自己 GitHub 身份提交的那条,两个来源都成立:
+ * 它确实经产品内 /issue 提交(cindy-tool),作者也确实是本人账号(github-account)。
+ *
+ * 硬编码成 ['cindy-tool'] 会造成同一条 issue 的来源标记随插件状态漂移:插件开着时
+ * (搜索命中)显示两个来源,插件停用 / 超时 / 离线时只显示「由 Cindy 提交」,丢掉一个
+ * 早已确认的事实。
+ *
+ * 注意与平台代发的区别:`identity === 'platform'` 时 GitHub 上的作者是 cindy-issue
+ * App、**不是**本人,所以只打 cindy-tool(同 mergeIssues 对 platform 那一路的口径)。
+ */
+function sourcesFromLedger(record: SubmittedIssueRecord): MyIssueSource[] {
+ return sortSources(
+ record.identity === 'github-user' ? ['cindy-tool', 'github-account'] : ['cindy-tool'],
+ );
+}
+
+/** 反馈 issue 由提交链路打 bug / feature 标签;人工改过标签时回退 null。 */
+export function issueTypeFromLabels(labels: string[]): 'bug' | 'feature' | null {
+ const lowered = labels.map((label) => label.toLowerCase());
+ if (lowered.includes('bug')) return 'bug';
+ if (lowered.includes('feature')) return 'feature';
+ return null;
+}
+
+function isTruncated(page: RemoteIssuePage): boolean {
+ return page.totalCount !== null && page.totalCount > page.issues.length;
+}
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/apps/desktop/src/main/github-issue/submittedIssueLedger.ts b/apps/desktop/src/main/github-issue/submittedIssueLedger.ts
new file mode 100644
index 0000000000..ecc0ac196f
--- /dev/null
+++ b/apps/desktop/src/main/github-issue/submittedIssueLedger.ts
@@ -0,0 +1,116 @@
+/**
+ * 本机「产品内提交过哪些 issue」的账本。
+ *
+ * 为什么需要它:平台代发路径在 GitHub 上的作者是 cindy-issue App,正文里只有一行
+ * 公开署名,而署名可编辑、可重名 —— 光靠 GitHub 侧数据无法可靠判断「这条是我提的」。
+ * 服务端(独立仓)也只有创建接口、没有「我的 issue」列表接口。所以提交成功的那一刻
+ * 在本机记一条,是这一半归属信息的唯一可靠来源。
+ *
+ * 存储走 electron-store + ownerScopedUserDataPath():账本天然按 Cindy 账号隔离,
+ * 换号后互不可见。跨设备不同步是这个方案已知的边界(换机 / 重装看不到旧记录)。
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
+ */
+
+import Store from 'electron-store';
+
+import type { SubmittedIssueRecord } from '../../shared/myIssues.js';
+import { isMyIssueUrl } from '../../shared/myIssues.js';
+import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../appSessionState.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('github-issue/ledger');
+
+interface SubmittedIssueLedgerShape {
+ issues: SubmittedIssueRecord[];
+}
+
+const MAX_SUBMITTED_ISSUES = 500;
+
+let storeInstance: Store<SubmittedIssueLedgerShape> | null = null;
+let storePath: string | null = null;
+
+function getStore(): Store<SubmittedIssueLedgerShape> {
+ const currentPath = ownerScopedUserDataPath();
+ if (!storeInstance || storePath !== currentPath) {
+ storeInstance = new Store<SubmittedIssueLedgerShape>({
+ name: 'submitted-issues',
+ cwd: currentPath,
+ defaults: { issues: [] },
+ schema: { issues: { type: 'array' } },
+ clearInvalidConfig: true,
+ });
+ storePath = currentPath;
+ }
+ return storeInstance;
+}
+
+function isValidRecord(value: unknown): value is SubmittedIssueRecord {
+ if (!value || typeof value !== 'object') return false;
+ const r = value as SubmittedIssueRecord;
+ return (
+ typeof r.number === 'number' &&
+ Number.isInteger(r.number) &&
+ r.number > 0 &&
+ // url 与其它字段一样按不可信输入清洗:它必须指向本仓这一号 issue。落盘文件
+ // 被篡改或损坏时,不让一条「你提交的 issue」把用户带去别处。
+ typeof r.url === 'string' &&
+ isMyIssueUrl(r.url, r.number) &&
+ typeof r.title === 'string' &&
+ (r.type === 'bug' || r.type === 'feature') &&
+ typeof r.submittedAt === 'string' &&
+ Number.isFinite(Date.parse(r.submittedAt)) &&
+ (r.identity === 'github-user' || r.identity === 'platform')
+ );
+}
+
+/**
+ * 清洗**读出来的**账本内容并返回,不回写 —— 落盘的坏数据不会被自动修好,每次读都
+ * 重新过滤一遍(真正改写只发生在 recordSubmittedIssue 那次 set)。
+ * 丢掉形状不对的条目,按提交时间倒序,同一 issue 号只留最新一条,并把总量压在上限内。
+ * 纯函数,单测直接调(不碰 electron-store)。
+ */
+export function normalizeSubmittedIssues(value: unknown): SubmittedIssueRecord[] {
+ if (!Array.isArray(value)) return [];
+ const valid = value.filter(isValidRecord);
+ // 倒序在前、去重在后 —— 保证同号冲突时留下的是提交时间更新的那条。
+ const sorted = [...valid].sort((a, b) => Date.parse(b.submittedAt) - Date.parse(a.submittedAt));
+ const seen = new Set<number>();
+ const records: SubmittedIssueRecord[] = [];
+ for (const record of sorted) {
+ if (seen.has(record.number)) continue;
+ seen.add(record.number);
+ records.push(record);
+ if (records.length >= MAX_SUBMITTED_ISSUES) break;
+ }
+ return records;
+}
+
+export function listSubmittedIssues(): SubmittedIssueRecord[] {
+ return normalizeSubmittedIssues(getStore().get('issues', []));
+}
+
+/**
+ * 记一条提交成功的 issue;同号重复提交按最新一条覆盖。
+ *
+ * `expectedScope` **必填**且必须是**提交发起时**取的 activeOwnerScopeKey():
+ * getStore() 走 ownerScopedUserDataPath(),读的是「此刻」的账号路径。提交请求在飞
+ * 期间切号,落地时写入就会把账号 A 的提交记进账号 B 的账本、出现在 B 的列表里。
+ * 参数设成必填而不是可选,是为了让新调用点不可能忘记带上作用域。
+ */
+export function recordSubmittedIssue(
+ record: SubmittedIssueRecord,
+ expectedScope: string,
+): SubmittedIssueRecord[] {
+ const currentScope = activeOwnerScopeKey();
+ if (currentScope !== expectedScope) {
+ // 放弃写入而不是写进别人的账本。这条提交在 GitHub 上已经成功,只是本机
+ // 少一条记录(平台读接口就绪后仍会出现在原账号的列表里)。
+ log.warn('dropping submitted-issue record: active account changed since submit started', {
+ issueNumber: record.number,
+ });
+ return listSubmittedIssues();
+ }
+ const next = normalizeSubmittedIssues([record, ...listSubmittedIssues()]);
+ getStore().set('issues', next);
+ return next;
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/myIssuesIpc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/myIssuesIpc.test.ts
new file mode 100644
index 0000000000..d7ade739b3
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/myIssuesIpc.test.ts
@@ -0,0 +1,85 @@
+/**
+ * 「我的 Issue」IPC adapter —— 失败时只回稳定脱敏码。
+ *
+ * 原始 Error.message 可能带 userData 绝对路径(electron-store 初始化失败)或上游响应
+ * 片段,不得跨 Main/Renderer 边界(engineering-conventions §2)。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import type { MyIssuesResult } from '../../../shared/myIssues';
+import { handleMyIssuesList } from '../my-issues';
+
+function emptyResult(): MyIssuesResult {
+ return { items: [], githubEnhancement: null, degraded: null, truncated: false };
+}
+
+describe('handleMyIssuesList', () => {
+ it('成功时原样透传服务结果', async () => {
+ const res = await handleMyIssuesList({}, { list: async () => (emptyResult()) });
+ expect(res).toMatchObject({ success: true, items: [], degraded: null });
+ });
+
+ it('force 透传给服务', async () => {
+ let seen: { force?: boolean } | null = null;
+ await handleMyIssuesList(
+ { force: true },
+ {
+ list: async (options) => {
+ seen = options;
+ return emptyResult();
+ },
+ },
+ );
+ expect(seen).toEqual({ force: true });
+ });
+
+ it('非法 / 缺省入参一律按 force=false 处理', async () => {
+ for (const raw of [undefined, null, 'nope', {}, { force: 'yes' }]) {
+ let seen: { force?: boolean } | null = null;
+ await handleMyIssuesList(raw, {
+ list: async (options) => {
+ seen = options;
+ return emptyResult();
+ },
+ });
+ expect(seen).toEqual({ force: false });
+ }
+ });
+
+ it('意外错误只回 unexpected,不泄漏路径与原文', async () => {
+ const leaky = new Error(
+ "ENOENT: no such file or directory, open '/Users/someone/Library/Application Support/Cindy/owners/abc/submitted-issues.json'",
+ );
+ const res = await handleMyIssuesList({}, {
+ list: async () => {
+ throw leaky;
+ },
+ });
+ expect(res).toEqual({
+ success: false,
+ error: 'unexpected',
+ items: [],
+ githubEnhancement: null,
+ degraded: null,
+ truncated: false,
+ });
+ // 任何形式的原始文本都不得出现在回给 renderer 的响应里。
+ const serialized = JSON.stringify(res);
+ expect(serialized).not.toContain('ENOENT');
+ expect(serialized).not.toContain('Application Support');
+ expect(serialized).not.toContain('submitted-issues.json');
+ });
+
+ it('切号导致结果作废时回专用码,便于 renderer 静默重取', async () => {
+ const stale = Object.assign(new Error('active account changed'), {
+ myIssuesErrorCode: 'stale-account-scope',
+ });
+ const res = await handleMyIssuesList({}, {
+ list: async () => {
+ throw stale;
+ },
+ });
+ expect(res).toMatchObject({ success: false, error: 'stale-account-scope' });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 5b600c7b1a..b4edf488a6 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -216,6 +216,16 @@ export const MAKER_INVOKE = {
* Phase 2 会加一个 submit-to-GitHub 动作(同 PAT 配置 + 去重相同 open issue)。
*/
HELP_FEEDBACK_CREATE: 'maker:help:feedback:create',
+ /**
+ * /issues 页面的「我的 Issue」列表。三路合并去重,主次不要记反:
+ * 平台通道(按 Cindy 登录态取「我提交过的 issue」,唯一给实时状态且跨设备的来源)
+ * + 本机提交账本(平台未就绪时的兜底)
+ * + 用户自己的 GitHub 身份(**可选增强**,没有时列表照常工作)。
+ *
+ * 查询型 handler,失败时 renderer 仍要靠账本渲染,故返回 { success }
+ * 风格而不是 throwIpcError(见 engineering-conventions §2 的例外)。
+ */
+ MY_ISSUES_LIST: 'maker:issues:list-mine',
WRITE_PLAN_FILE: 'maker:write-plan-file',
// Rewind / Fork (Stage 2 C2) — 取代老 cc-agent:rewind:* + local-db:sessions:fork
REWIND_PREVIEW: 'maker:rewind:preview',
diff --git a/apps/desktop/src/main/maker-ipc/my-issues.ts b/apps/desktop/src/main/maker-ipc/my-issues.ts
new file mode 100644
index 0000000000..dc37f6a831
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/my-issues.ts
@@ -0,0 +1,79 @@
+/**
+ * 「我的 Issue」列表 IPC —— /issues 页面的唯一数据入口。
+ *
+ * 本文件只做 adapter:参数校验 + 调 myIssuesRuntime 的服务。业务逻辑(两路数据合并、
+ * 降级、缓存)在 github-issue/myIssuesService.ts,单测直接打那一层。
+ *
+ * 返回 { success } 风格:查询失败时 renderer 仍要能渲染(至少给出错误态与空列表),
+ * 属于 engineering-conventions §2 明确允许的查询型例外。
+ */
+
+import { ipcMain } from 'electron';
+
+import type { MyIssuesErrorCode, MyIssuesResult } from '../../shared/myIssues.js';
+import { getMyIssuesService } from '../github-issue/myIssuesRuntime.js';
+import { isStaleAccountScopeError } from '../github-issue/myIssuesService.js';
+import { createLogger } from '../logger.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { MAKER_INVOKE } from './channels.js';
+
+const log = createLogger('maker-ipc/my-issues');
+
+export type MyIssuesListResponse =
+ | ({ success: true } & MyIssuesResult)
+ | {
+ success: false;
+ /** 稳定脱敏码,不是原始错误文本 —— renderer 只据它选 i18n 文案。 */
+ error: MyIssuesErrorCode;
+ items: [];
+ githubEnhancement: null;
+ degraded: null;
+ truncated: false;
+ };
+
+export interface MyIssuesListDeps {
+ list: (options: { force?: boolean }) => Promise<MyIssuesResult>;
+}
+
+/**
+ * 失败时**只回稳定错误码**。原始 Error.message 可能带 userData 绝对路径
+ * (electron-store 初始化失败)或上游响应片段,不得跨 Main/Renderer 边界 ——
+ * 细节只进 main 日志(engineering-conventions §2 的收尾要求)。
+ */
+export async function handleMyIssuesList(
+ raw: unknown,
+ deps: MyIssuesListDeps = { list: (options) => getMyIssuesService().list(options) },
+): Promise<MyIssuesListResponse> {
+ const force = !!(raw && typeof raw === 'object' && (raw as { force?: unknown }).force === true);
+ try {
+ const result = await deps.list({ force });
+ return { success: true, ...result };
+ } catch (err) {
+ // 切号导致结果作废是预期路径(renderer 会按新账号重取),记 debug 不记 warn。
+ const stale = isStaleAccountScopeError(err);
+ const detail = err instanceof Error ? err.message : String(err);
+ if (stale) {
+ log.debug('my issues list discarded after account switch', { detail });
+ } else {
+ log.warn('my issues list failed', { detail });
+ }
+ return {
+ success: false,
+ error: stale ? 'stale-account-scope' : 'unexpected',
+ items: [],
+ githubEnhancement: null,
+ degraded: null,
+ truncated: false,
+ };
+ }
+}
+
+export function registerMyIssuesIpc(): void {
+ ipcMain.handle(MAKER_INVOKE.MY_ISSUES_LIST, (event, raw: unknown) => {
+ // issue 列表含标题、编号与 GitHub 用户名,是账号私有数据,且这条 handler 会代为
+ // 发起带登录态的平台请求。只允许 Cindy 自有顶层页面调用:WebView、Ghost 页面、
+ // 子 frame 一律拒绝。不可信来源直接 throw,不给它降级数据。
+ assertTrustedAppRendererEvent(event);
+ return handleMyIssuesList(raw);
+ });
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 09a245be3c..714a01896c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4735,6 +4735,21 @@ contextBridge.exposeInMainWorld('electronAPI', {
input: import('../shared/helpTypes').HelpFeedbackDraftInput,
): Promise<import('../shared/helpTypes').HelpFeedbackDraft> =>
ipcRenderer.invoke('maker:help:feedback:create', input),
+ // /issues 页面的「我的 Issue」列表;force=true 绕过 main 侧 60s TTL(手动刷新)。
+ listMyIssues: (
+ options?: { force?: boolean },
+ ): Promise<
+ | ({ success: true } & import('../shared/myIssues').MyIssuesResult)
+ | {
+ success: false;
+ /** 稳定脱敏码,不是原始错误文本。 */
+ error: import('../shared/myIssues').MyIssuesErrorCode;
+ items: [];
+ githubEnhancement: null;
+ degraded: null;
+ truncated: false;
+ }
+ > => ipcRenderer.invoke('maker:issues:list-mine', options ?? {}),
writePlanFile: (params: {
requestId: string;
planFilePath: string;
diff --git a/apps/desktop/src/renderer/__tests__/newMakerDraftWorkspaceReset.test.ts b/apps/desktop/src/renderer/__tests__/newMakerDraftWorkspaceReset.test.ts
new file mode 100644
index 0000000000..0a178a936e
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/newMakerDraftWorkspaceReset.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+
+/**
+ * resetDraftWorkspaceTargets —— 「另起一段干净对话」的共享复位入口。
+ *
+ * 所有预填入口(/issue、通讯录引导、发送后复位)都走它。这里钉住它真的清干净:
+ * 尤其 extraDirs —— 那是单次草稿的**目录读取授权**,漏掉会让新会话悄悄继承对无关
+ * 本地目录的访问权(#1103 review:两个入口各自手写字段清单,都漏了它)。
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ __resetForTest,
+ getDraft,
+ patchCollab,
+ patchDraft,
+ resetDraftWorkspaceTargets,
+} from '@/state/newMakerDraft';
+
+beforeEach(() => {
+ __resetForTest();
+});
+
+describe('resetDraftWorkspaceTargets', () => {
+ it('清空额外目录授权', () => {
+ patchDraft({ workingDir: '/Users/someone/project', extraDirs: ['/Users/someone/secrets'] });
+ expect(getDraft().extraDirs).toEqual(['/Users/someone/secrets']);
+
+ resetDraftWorkspaceTargets();
+ expect(getDraft().extraDirs).toEqual([]);
+ });
+
+ it('清空工作目录,并级联清掉远程目标与协同开关', () => {
+ patchDraft({ workingDir: '/Users/someone/project' });
+ patchDraft({ remoteHostId: 'host-1' });
+ patchCollab({ enabled: true });
+ patchDraft({ workingDir: '/Users/someone/project', deviceLinkDeviceId: 'dev-1' });
+
+ resetDraftWorkspaceTargets();
+ const draft = getDraft();
+ expect(draft.workingDir).toBeNull();
+ expect(draft.remoteHostId).toBeNull();
+ expect(draft.deviceLinkDeviceId).toBeNull();
+ expect(draft.deviceLinkDeviceName).toBeNull();
+ expect(draft.collab.enabled).toBe(false);
+ });
+
+ it('不动模型 / agent 层偏好 —— 那是「我常用哪个」的记忆,与「这次跑在哪」正交', () => {
+ patchDraft({ vendor: 'codex', workingDir: '/tmp/x', extraDirs: ['/tmp/y'] });
+ const vendorBefore = getDraft().vendor;
+ const lastByVendorBefore = getDraft().lastByVendor;
+
+ resetDraftWorkspaceTargets();
+ expect(getDraft().vendor).toBe(vendorBefore);
+ expect(getDraft().lastByVendor).toEqual(lastByVendorBefore);
+ });
+
+ it('幂等:已经是干净对话态时再调一次没有副作用', () => {
+ resetDraftWorkspaceTargets();
+ const first = getDraft();
+ resetDraftWorkspaceTargets();
+ expect(getDraft()).toEqual(first);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts b/apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts
index 4d1fc478dd..f5a1856a5f 100644
--- a/apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts
+++ b/apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts
@@ -6,22 +6,21 @@
* navigate('/cc-agent/new'), 用户在那里用原生入口选 agent/模型后发送,
* 走正常建会话路径 — 不绕过任何会话创建逻辑。
*
- * 同时重置草稿的远程目标(workingDir/device-link): 通讯录是本机全局库,
- * 残留的远程草稿会把引导会话发到对端机器, 那边查到的是另一台机器的通讯录。
+ * 同时把草稿的工作区目标复位成干净的本机对话态(resetDraftWorkspaceTargets):
+ * 通讯录是本机全局库, 残留的远程草稿会把引导会话发到对端机器, 那边查到的是另一台
+ * 机器的通讯录; 残留的 extraDirs 还会让这段引导对话继承对无关本地目录的读取授权。
+ *
+ * 走共享函数而不是手写字段清单 —— 这里原先手抄的三个字段其实已由 patchDraft 的级联
+ * 处理, 真正需要清的 extraDirs 反而漏了(#1103 review 在同源的 issue 预填入口发现)。
*/
import { plainTextToTiptapDoc, saveDraft } from '@/lib/composerDraftStore';
import { NEW_MAKER_DRAFT_KEY } from '@/features/cc-agent/NewMakerDraftRoute';
-import { patchDraft } from '@/state/newMakerDraft';
+import { resetDraftWorkspaceTargets } from '@/state/newMakerDraft';
export function prefillContactsAiSessionDraft(promptText: string): void {
saveDraft(NEW_MAKER_DRAFT_KEY, {
text: plainTextToTiptapDoc(promptText),
attachments: [],
});
- patchDraft({
- workingDir: null,
- remoteHostId: null,
- deviceLinkDeviceId: null,
- deviceLinkDeviceName: null,
- });
+ resetDraftWorkspaceTargets();
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 88d290661d..12c5d153f8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -75,6 +75,7 @@ import {
patchDraft,
patchCollab,
patchCurrentVendorPrefs,
+ resetDraftWorkspaceTargets,
getFastModeForModel,
setFastModeForModel,
setEffortForModel,
@@ -412,12 +413,11 @@ function getCurrentRoutePath(): string {
/**
* 发送 / 建目标成功后调用:把草稿 store 的工作区选择复位到默认(对话态、无额外目录)。
- * workingDir=null 会通过 patchDraft 的兜底级联清掉 remoteHostId / deviceLink / collab.enabled,
- * 所以这里只需显式清 workingDir + extraDirs 两个字段。vendor / lastByVendor / fastModeByModel
- * 等模型/agent 层偏好保持不变(那是"我常用哪个"的记忆,和"这次要跑在哪"的工作区选择正交)。
+ * 具体清哪些字段、为什么只需两个,见 state/newMakerDraft 的 resetDraftWorkspaceTargets ——
+ * 该语义已提到 store 侧共享,其它「另起一段干净对话」的入口也走同一个函数。
*/
function resetDraftWorkspaceAfterSend(): void {
- patchDraft({ workingDir: null, extraDirs: [] });
+ resetDraftWorkspaceTargets();
}
/**
diff --git a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
index 0cbb41eeb3..86bd5a4523 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
@@ -1,63 +1,297 @@
/**
- * IssueTrackerFeatureLayout — GitHub Issues 引导页
+ * IssueTrackerFeatureLayout — 「我的 Issue」页
* ---------------------------------------------------------------------------
- * Issue 模块走 GitHub,此页面引导用户通过 /issue 命令发起 agent 对话式提交。
+ * Issue 本体在 GitHub 上;本页解决的是「提交完就再也看不到了」。
+ *
+ * 口径:看自己的 issue 与提交 issue 走**同一条公共能力**,只要 Cindy 登录态,
+ * 不要求用户有 GitHub 账号 —— 所以本页任何状态下都**不得**提示「你需要连接
+ * GitHub」。用户自己的 GitHub 身份只是可选增强(把他直接在 GitHub 上提的也并进来),
+ * 没有它页面照常工作,界面上也不提。
+ *
+ * 一条都没有时,页面退回原来的引导形态(告诉用户怎么用 /issue 提交)。
+ *
+ * **取数期间不换界面**(engineering-conventions §7):首屏加载不显示 loading 文案,
+ * 正文保持引导内容 —— 平台通道的总 deadline 可达 12s,换成一行「加载中」会造成
+ * 引导 → loading → 列表 两次跳变;而一条都没有的用户(最常见)看到的引导页更是
+ * 从头到尾不该动过。进度反馈只放在 header 的刷新图标上(零布局变化)。
+ *
* 左侧 app 侧栏沿用 cc-agent 项目/对话列表(显式注册,避免冷启动直接进 /issues
* 时左栏空白,详见 useRegisterCCAgentSidebar)。
*/
-import { Bug, ExternalLink } from 'lucide-react';
+import { useCallback } from 'react';
+import { Bug, ExternalLink, RefreshCw } from 'lucide-react';
+import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
+import type { MyIssuesResult } from '@/../shared/myIssues';
import { cn } from '@/lib/utils';
import { InvisibleWindowDragStrip } from '@/components/layout/windowDrag';
import { useRegisterCCAgentSidebar } from '@/features/cc-agent/useRegisterCCAgentSidebar';
+import { MyIssueList } from './MyIssueList';
+import { useMyIssues } from './hooks/useMyIssues';
+import { selectMyIssuesNotices } from './lib/myIssuesNotices';
+import { prefillIssueCommandDraft } from './lib/startIssueChat';
+
const GITHUB_ISSUES_URL = 'https://github.com/makecindy/cindy/issues';
export function IssueTrackerFeatureLayout() {
const { t } = useTranslation();
+ const navigate = useNavigate();
// 沿用 cc-agent 侧栏;冷启动直接进 /issues 时也能播种,不留空白左栏。
useRegisterCCAgentSidebar();
+ const { data, loading, refreshing, error, refresh } = useMyIssues();
+
+ const items = data?.items ?? [];
+ const hasItems = items.length > 0;
+
+ // 预填草稿 + 跳新建页,不自动发送 —— 用户还要在那条命令后面补描述。
+ const startIssueChat = useCallback(() => {
+ prefillIssueCommandDraft();
+ navigate('/cc-agent/new');
+ }, [navigate]);
+
return (
- <div className="relative flex h-full w-full items-center justify-center bg-content-area">
- {/* mac 上本页不渲染通用 ContentHeader 且顶部无交互元素,垫一条透明
- 窗口拖拽条(windowDrag.tsx 约定) */}
+ <div className="relative flex h-full w-full flex-col bg-content-area">
+ {/* mac 上本页不渲染通用 ContentHeader,顶部垫一条透明窗口拖拽条
+ (windowDrag.tsx 约定);它不吃点击,不挡下面的刷新按钮。 */}
<InvisibleWindowDragStrip />
- <div className="flex max-w-md flex-col items-center gap-4 px-8 text-center">
- {/* Icon */}
- <div className="flex size-16 items-center justify-center rounded-full bg-sidebar-item-hover">
- <Bug size={28} className="text-sidebar-muted" strokeWidth={1.5} />
- </div>
-
- {/* Title */}
- <h1 className="text-lg font-medium text-foreground">
- {t('issueAgent.redirect.title')}
- </h1>
-
- {/* Description */}
- <p className="text-sm text-sidebar-muted">
- {t('issueAgent.redirect.descriptionBefore')}
- <code className="rounded bg-sidebar-item-hover px-1.5 py-0.5 text-foreground">
- /issue
- </code>
- {t('issueAgent.redirect.descriptionAfter')}
- </p>
- {/* CTA */}
+ <header className="flex shrink-0 items-center gap-3 px-6 pb-3 pt-8">
+ <h1 className="text-15 font-medium text-foreground">{t('issueTracker.list.header')}</h1>
+ {data ? <ViewerLine data={data} /> : null}
+ <div className="flex-1" />
<button
type="button"
- onClick={() => window.electronAPI.openExternal(GITHUB_ISSUES_URL)}
+ onClick={refresh}
+ disabled={loading || refreshing}
+ title={t('issueTracker.mine.refresh')}
+ aria-label={t('issueTracker.mine.refresh')}
className={cn(
- 'mt-2 inline-flex h-9 items-center justify-center gap-1.5 rounded-full px-5',
- 'text-sm font-medium transition-colors',
- 'bg-foreground text-background hover:opacity-90',
+ 'flex size-7 items-center justify-center rounded-full text-sidebar-muted',
+ 'transition-colors hover:bg-sidebar-item-hover hover:text-foreground',
+ 'disabled:pointer-events-none disabled:opacity-50',
)}
>
- {t('issueAgent.redirect.cta')}
- <ExternalLink size={14} />
+ {/* 动画挂外层 span,SVG 保持静态:挂在 SVG 上会每帧惊动主线程
+ (engineering-conventions「常驻动画必须 compositor-only」)。
+ 首屏取数期间也转 —— 正文保持引导内容不动,这里是唯一的进度反馈,
+ 且它零布局变化、不构成跳变。 */}
+ <span className={cn('inline-flex', (loading || refreshing) && 'animate-spinner')}>
+ <RefreshCw size={14} />
+ </span>
</button>
+ </header>
+
+ {/* 「怎么提交」常驻在 header 下方、**滚动区之外**:issue 多的时候放列表末尾
+ 等于看不见。空态不渲染它 —— 那时 EmptyGuide 里已经有同一段说明。 */}
+ {hasItems ? <SubmitHintBar onStartIssueChat={startIssueChat} /> : null}
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pb-6 pt-2">
+ {error && !hasItems ? (
+ // 整页错误态只留给「从来没加载成功过」;已经有数据时刷新失败不能把列表
+ // 盖掉(useMyIssues 特意保留了旧 data),否则用户点一下刷新就丢失全部内容。
+ <LoadFailed onRetry={refresh} busy={refreshing} />
+ ) : hasItems ? (
+ <>
+ {error ? <RefreshFailedNotice onRetry={refresh} busy={refreshing} /> : null}
+ <Notices data={data} />
+ <MyIssueList items={items} />
+ </>
+ ) : (
+ <>
+ <Notices data={data} />
+ <EmptyGuide onStartIssueChat={startIssueChat} />
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * 说明文案里的 `/issue` —— 可点击,点了直接开一个预填好该命令的新对话。
+ * 两处说明(顶部条与空态)共用它,避免样式与行为各写一套;`size` 只差内边距,
+ * 视觉语言(等宽字 + 浅底 + hover 加深)一致。
+ */
+function IssueCommandButton({
+ onClick,
+ size = 'sm',
+}: {
+ onClick: () => void;
+ size?: 'sm' | 'lg';
+}) {
+ const { t } = useTranslation();
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={t('issueTracker.mine.startIssueChat')}
+ aria-label={t('issueTracker.mine.startIssueChat')}
+ className={cn(
+ 'rounded-full bg-sidebar-item-hover font-mono text-foreground',
+ 'transition-colors hover:bg-sidebar-item-active',
+ size === 'lg' ? 'px-1.5 py-0.5' : 'px-1 py-0.5',
+ )}
+ >
+ /issue
+ </button>
+ );
+}
+
+/**
+ * 只在「恰好配了 GitHub 身份」时说明列表额外并入了谁名下的 issue。
+ * 没配时**什么都不显示** —— 提示「未连接」会重新制造「必须有 GitHub 账号」的暗示。
+ */
+function ViewerLine({ data }: { data: MyIssuesResult }) {
+ const { t } = useTranslation();
+ if (!data.githubEnhancement) return null;
+ return (
+ <span className="truncate text-12 text-sidebar-muted">
+ {t('issueTracker.mine.viewerGithub', { login: data.githubEnhancement.login })}
+ </span>
+ );
+}
+
+/** 降级 / 截断提示:数据没给全时必须明说(选取规则见 lib/myIssuesNotices)。 */
+function Notices({ data }: { data: MyIssuesResult | null }) {
+ const { t } = useTranslation();
+ if (!data) return null;
+ const notices = selectMyIssuesNotices(data);
+ if (notices.length === 0) return null;
+ return (
+ <div className="mb-2 flex flex-col gap-1.5 rounded-xl bg-sidebar-item-hover px-3 py-2">
+ {notices.map((key) => (
+ <p key={key} className="text-11 leading-relaxed text-sidebar-muted">
+ {t(key)}
+ </p>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * 已有数据时刷新失败:降级成列表上方一条提示 + 重试,旧内容照常可读可点。
+ * 与整页 LoadFailed 复用同一组文案,只是不夺走内容区。
+ *
+ * 重试进行中**不清掉这条提示**:清了会让它消失、失败后又出现,两次跳变
+ * (engineering-conventions §7)。刷新状态由 header 图标表达,这里只把按钮禁用掉 ——
+ * 否则它看着可点、点了却被 useMyIssues 的 in-flight 静默挡掉,毫无反馈。
+ */
+function RefreshFailedNotice({ onRetry, busy }: { onRetry: () => void; busy: boolean }) {
+ const { t } = useTranslation();
+ return (
+ <div className="mb-2 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-xl bg-sidebar-item-hover px-3 py-2">
+ <p className="text-11 text-sidebar-muted">{t('issueTracker.list.loadFailed')}</p>
+ <button
+ type="button"
+ onClick={onRetry}
+ disabled={busy}
+ className={cn(
+ 'text-11 text-sidebar-muted underline-offset-2',
+ 'hover:text-foreground hover:underline',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ )}
+ >
+ {t('issueTracker.list.retry')}
+ </button>
+ </div>
+ );
+}
+
+function LoadFailed({ onRetry, busy }: { onRetry: () => void; busy: boolean }) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex flex-col items-start gap-2 px-3 py-2">
+ <p className="text-13 text-foreground">{t('issueTracker.list.loadFailed')}</p>
+ {/* 刻意不展示 main 侧错误原文:它可能带 userData 绝对路径,详情只进 main 日志。 */}
+ <button
+ type="button"
+ onClick={onRetry}
+ disabled={busy}
+ className={cn(
+ 'text-12 text-sidebar-muted underline-offset-2',
+ 'hover:text-foreground hover:underline',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ )}
+ >
+ {t('issueTracker.list.retry')}
+ </button>
+ </div>
+ );
+}
+
+/**
+ * 列表非空时的常驻说明条:同一段「怎么提交」的文案压成一行。
+ * 与空态的 EmptyGuide 共用同一组 i18n key,只是版式一个紧凑一个居中大版 ——
+ * 两处说法必须一致,不要各写一套。
+ *
+ * 它常驻占位,所以刻意压到最低存在感:11px 灰字 + 文字链,不用实心按钮
+ * (那是空态的主 CTA)。
+ */
+function SubmitHintBar({ onStartIssueChat }: { onStartIssueChat: () => void }) {
+ const { t } = useTranslation();
+ return (
+ <div
+ className={cn(
+ 'flex shrink-0 flex-wrap items-center gap-x-1.5 gap-y-1',
+ 'border-b border-border px-6 pb-2',
+ )}
+ >
+ <p className="text-11 leading-relaxed text-sidebar-muted">
+ {t('issueAgent.redirect.descriptionBefore')}
+ <IssueCommandButton onClick={onStartIssueChat} />
+ {t('issueAgent.redirect.descriptionAfter')}
+ </p>
+ <button
+ type="button"
+ onClick={() => window.electronAPI.openExternal(GITHUB_ISSUES_URL)}
+ className={cn(
+ 'inline-flex items-center gap-1 text-11 text-sidebar-muted',
+ 'underline-offset-2 transition-colors hover:text-foreground hover:underline',
+ )}
+ >
+ {t('issueAgent.redirect.cta')}
+ <ExternalLink size={11} />
+ </button>
+ </div>
+ );
+}
+
+/**
+ * 一条都没有时的引导:怎么提、去哪看。正文与 CTA 沿用改版前的整页引导;
+ * 标题换成空态该说的话 —— 原来那句「Issue 已迁移至 GitHub」是整页引导时代的说法,
+ * 现在这一页本身就是能用的列表,再说「已迁移」会让人以为页面没做。
+ */
+function EmptyGuide({ onStartIssueChat }: { onStartIssueChat: () => void }) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex flex-col items-center gap-4 px-8 py-16 text-center">
+ <div className="flex size-16 items-center justify-center rounded-full bg-sidebar-item-hover">
+ <Bug size={28} className="text-sidebar-muted" strokeWidth={1.5} />
</div>
+
+ <h2 className="text-lg font-medium text-foreground">{t('issueTracker.mine.emptyTitle')}</h2>
+
+ <p className="max-w-md text-sm text-sidebar-muted">
+ {t('issueAgent.redirect.descriptionBefore')}
+ <IssueCommandButton onClick={onStartIssueChat} size="lg" />
+ {t('issueAgent.redirect.descriptionAfter')}
+ </p>
+
+ <button
+ type="button"
+ onClick={() => window.electronAPI.openExternal(GITHUB_ISSUES_URL)}
+ className={cn(
+ 'mt-2 inline-flex h-9 items-center justify-center gap-1.5 rounded-full px-5',
+ 'text-sm font-medium transition-colors',
+ 'bg-foreground text-background hover:opacity-90',
+ )}
+ >
+ {t('issueAgent.redirect.cta')}
+ <ExternalLink size={14} />
+ </button>
</div>
);
}
diff --git a/apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx b/apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx
new file mode 100644
index 0000000000..7dd22fe55e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/MyIssueList.tsx
@@ -0,0 +1,123 @@
+/**
+ * MyIssueList —— 「我的 Issue」列表本体。
+ *
+ * 每行两段:标题一行 + 元信息一行(#编号 · 状态 · 类型 · 来源 · 日期 · 评论数)。
+ * 整行点击外链到 GitHub —— 详情、评论都在 GitHub 上,应用内不复刻。
+ *
+ * 配色严格灰度(DESIGN.md §2:非灰色需登记):open / closed / unknown 用实心点、
+ * 空心点、虚线点区分,并且**同时**给出状态文字 —— 不靠形状或颜色单独承载语义。
+ */
+
+import { ExternalLink } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import type { MyIssueItem } from '@/../shared/myIssues';
+import { cn } from '@/lib/utils';
+
+interface MyIssueListProps {
+ items: MyIssueItem[];
+}
+
+export function MyIssueList({ items }: MyIssueListProps) {
+ return (
+ <ul className="flex flex-col">
+ {items.map((item) => (
+ <MyIssueRow key={item.number} item={item} />
+ ))}
+ </ul>
+ );
+}
+
+function MyIssueRow({ item }: { item: MyIssueItem }) {
+ const { t, i18n } = useTranslation();
+
+ const statusLabel =
+ item.state === 'open'
+ ? t('issueTracker.status.open')
+ : item.state === 'closed'
+ ? t('issueTracker.status.closed')
+ : t('issueTracker.mine.statusUnknown');
+
+ const meta = [
+ `#${item.number}`,
+ statusLabel,
+ item.type ? t(`issueTracker.type.${item.type}`) : null,
+ ...item.sources.map((source) =>
+ source === 'cindy-tool'
+ ? t('issueTracker.mine.sourceCindy')
+ : t('issueTracker.mine.sourceGithub'),
+ ),
+ formatDate(item.createdAt, i18n.language),
+ // 显式判 null 而不是 falsy:0 是「已知 0 条」的有效值,不能和 null(未知)混为一谈。
+ // 判完再要求 > 0 —— 「0 条评论」对用户没有信息量,不占元信息行的位置(这是刻意的
+ // 展示取舍,不是把 0 当假值漏掉)。
+ item.commentCount !== null && item.commentCount > 0
+ ? t('issueTracker.mine.commentCount', { count: item.commentCount })
+ : null,
+ ].filter((part): part is string => !!part);
+
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={() => window.electronAPI.openExternal(item.url)}
+ title={t('issueTracker.mine.openOnGithub')}
+ className={cn(
+ 'group flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left',
+ 'transition-colors hover:bg-sidebar-item-hover',
+ )}
+ >
+ <StatusDot state={item.state} />
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
+ <span
+ className={cn(
+ 'truncate text-13 text-foreground',
+ // 已关闭的降一档存在感,但不靠它承载语义(状态文字在元信息里)。
+ item.state === 'closed' && 'text-sidebar-muted',
+ )}
+ >
+ {item.title}
+ </span>
+ <span className="truncate text-11 text-sidebar-muted">{meta.join(' · ')}</span>
+ </span>
+ <ExternalLink
+ size={13}
+ className="mt-0.5 shrink-0 text-sidebar-muted opacity-0 transition-opacity group-hover:opacity-100"
+ aria-hidden
+ />
+ </button>
+ </li>
+ );
+}
+
+function StatusDot({ state }: { state: MyIssueItem['state'] }) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ 'mt-[7px] size-2 shrink-0 rounded-full',
+ state === 'open' && 'bg-foreground',
+ state === 'closed' && 'border border-sidebar-muted',
+ state === 'unknown' && 'border border-dashed border-sidebar-muted',
+ )}
+ />
+ );
+}
+
+/** 列表跨月跨年,相对时间不如短日期好用;走 Intl 保证四种界面语言都读得通。 */
+function formatDate(iso: string, locale: string): string | null {
+ const ms = Date.parse(iso);
+ if (Number.isNaN(ms)) return null;
+ const date = new Date(ms);
+ const sameYear = date.getFullYear() === new Date().getFullYear();
+ try {
+ return new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ day: 'numeric',
+ ...(sameYear ? {} : { year: 'numeric' }),
+ }).format(date);
+ } catch {
+ // 非法 locale 标签时退回 ISO 日期段,不让一行日期把整页拖崩。
+ return iso.slice(0, 10);
+ }
+}
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx b/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx
new file mode 100644
index 0000000000..4b6892174c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx
@@ -0,0 +1,156 @@
+// @vitest-environment jsdom
+
+/**
+ * IssueTrackerFeatureLayout —— 内容区分支的回归。
+ *
+ * 重点钉住「刷新失败不得盖掉已加载的列表」:useMyIssues 刷新失败时刻意保留旧 data,
+ * 但 error 分支一旦优先于 hasItems,用户点一次刷新就会丢失整页内容。
+ */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { MyIssueItem, MyIssuesResult } from '@/../shared/myIssues';
+
+const useMyIssuesMock = vi.fn();
+
+vi.mock('../hooks/useMyIssues', () => ({
+ useMyIssues: () => useMyIssuesMock(),
+}));
+vi.mock('@/features/cc-agent/useRegisterCCAgentSidebar', () => ({
+ useRegisterCCAgentSidebar: () => undefined,
+}));
+vi.mock('@/components/layout/windowDrag', () => ({
+ InvisibleWindowDragStrip: () => null,
+ WINDOW_DRAG_STYLE: {},
+ WINDOW_NO_DRAG_STYLE: {},
+}));
+vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, vars?: Record<string, unknown>) =>
+ vars && 'count' in vars ? `${key}:${String(vars.count)}` : key,
+ i18n: { language: 'zh-CN' },
+ }),
+}));
+
+const { IssueTrackerFeatureLayout } = await import('../IssueTrackerFeatureLayout');
+
+function item(over: Partial<MyIssueItem> = {}): MyIssueItem {
+ return {
+ number: 1061,
+ url: 'https://github.com/makecindy/cindy/issues/1061',
+ title: '已经加载出来的那条 issue',
+ type: 'feature',
+ state: 'open',
+ createdAt: '2026-07-30T09:12:49Z',
+ updatedAt: null,
+ commentCount: null,
+ sources: ['cindy-tool'],
+ ...over,
+ };
+}
+
+function result(items: MyIssueItem[]): MyIssuesResult {
+ return { items, githubEnhancement: null, degraded: null, truncated: false };
+}
+
+function state(over: Record<string, unknown> = {}) {
+ return {
+ data: null,
+ loading: false,
+ refreshing: false,
+ error: null,
+ refresh: vi.fn(),
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ useMyIssuesMock.mockReset();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { openExternal: vi.fn() },
+ });
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('IssueTrackerFeatureLayout 内容区分支', () => {
+ it('刷新失败但已有数据:保留列表,错误降级成提示条', () => {
+ useMyIssuesMock.mockReturnValue(
+ state({ data: result([item()]), error: 'ECONNRESET' }),
+ );
+ render(<IssueTrackerFeatureLayout />);
+
+ // 列表还在,用户不丢内容。
+ expect(screen.getByText('已经加载出来的那条 issue')).toBeTruthy();
+ // 失败信息以提示条形式出现,而且不是整页错误态。
+ expect(screen.getAllByText('issueTracker.list.loadFailed').length).toBe(1);
+ expect(screen.getAllByText('issueTracker.list.retry').length).toBe(1);
+ });
+
+ it('重试进行中:保留失败提示但禁用重试按钮(不清 error,避免消失又出现两次跳变)', () => {
+ useMyIssuesMock.mockReturnValue(
+ state({ data: result([item()]), error: 'unexpected', refreshing: true }),
+ );
+ render(<IssueTrackerFeatureLayout />);
+
+ // 提示条仍在 —— 清掉它会让界面在刷新期间变一次、失败后再变回来。
+ expect(screen.getByText('issueTracker.list.loadFailed')).toBeTruthy();
+ // 但按钮不可再点:否则它看着可点、点了却被 in-flight 静默挡掉。
+ expect(screen.getByText('issueTracker.list.retry').hasAttribute('disabled')).toBe(true);
+ });
+
+ it('从未加载成功过:才用整页错误态', () => {
+ useMyIssuesMock.mockReturnValue(state({ data: null, error: 'ECONNRESET' }));
+ render(<IssueTrackerFeatureLayout />);
+
+ expect(screen.getByText('issueTracker.list.loadFailed')).toBeTruthy();
+ expect(screen.queryByText('已经加载出来的那条 issue')).toBeNull();
+ });
+
+ it('首屏取数期间保留引导内容,不换成 loading 文案(engineering-conventions §7)', () => {
+ // 平台通道总 deadline 可达 12s。换成一行「加载中」会造成 引导 → loading → 列表
+ // 两次跳变;而一条都没有的用户(最常见)看到的引导页本该从头到尾没动过。
+ useMyIssuesMock.mockReturnValue(state({ loading: true, data: null }));
+ render(<IssueTrackerFeatureLayout />);
+
+ expect(screen.getByText('issueTracker.mine.emptyTitle')).toBeTruthy();
+ expect(screen.queryByText('issueTracker.detail.loading')).toBeNull();
+ });
+
+ it('首屏取数完成后引导原子切成列表 —— 中间不经过第三种形态', () => {
+ useMyIssuesMock.mockReturnValue(state({ loading: true, data: null }));
+ const view = render(<IssueTrackerFeatureLayout />);
+ expect(screen.getByText('issueTracker.mine.emptyTitle')).toBeTruthy();
+
+ useMyIssuesMock.mockReturnValue(state({ loading: false, data: result([item()]) }));
+ view.rerender(<IssueTrackerFeatureLayout />);
+ expect(screen.queryByText('issueTracker.mine.emptyTitle')).toBeNull();
+ expect(screen.getByText('已经加载出来的那条 issue')).toBeTruthy();
+ });
+
+ it('一条都没有:显示空态引导,不显示常驻说明条(避免与引导里的说明重复)', () => {
+ useMyIssuesMock.mockReturnValue(state({ data: result([]) }));
+ render(<IssueTrackerFeatureLayout />);
+
+ expect(screen.getByText('issueTracker.mine.emptyTitle')).toBeTruthy();
+ // 空态与常驻条都含可点击的 /issue;空态时只应有一个。
+ expect(screen.getAllByRole('button', { name: 'issueTracker.mine.startIssueChat' }).length).toBe(
+ 1,
+ );
+ });
+
+ it('有数据:顶部常驻说明条在场', () => {
+ useMyIssuesMock.mockReturnValue(state({ data: result([item()]) }));
+ render(<IssueTrackerFeatureLayout />);
+
+ expect(screen.getAllByRole('button', { name: 'issueTracker.mine.startIssueChat' }).length).toBe(
+ 1,
+ );
+ expect(screen.queryByText('issueTracker.mine.emptyTitle')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/MyIssueList.test.tsx b/apps/desktop/src/renderer/features/issue-tracker/__tests__/MyIssueList.test.tsx
new file mode 100644
index 0000000000..2862398139
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/MyIssueList.test.tsx
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+
+/**
+ * MyIssueList —— 行内元信息拼装、来源标记、状态点形态、点击外链。
+ */
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { MyIssueItem } from '@/../shared/myIssues';
+
+import { MyIssueList } from '../MyIssueList';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ // 元信息断言直接看 key,避免绑死具体译文。
+ t: (key: string, vars?: Record<string, unknown>) =>
+ vars && 'count' in vars ? `${key}:${String(vars.count)}` : key,
+ i18n: { language: 'zh-CN' },
+ }),
+}));
+
+function item(over: Partial<MyIssueItem> = {}): MyIssueItem {
+ return {
+ number: 1061,
+ url: 'https://github.com/makecindy/cindy/issues/1061',
+ title: '内置浏览器翻译按钮',
+ type: 'feature',
+ state: 'open',
+ createdAt: '2026-07-30T09:12:49Z',
+ updatedAt: '2026-07-30T10:00:00Z',
+ commentCount: 2,
+ sources: ['github-account'],
+ ...over,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('MyIssueList', () => {
+ it('渲染标题与元信息(编号 / 状态 / 类型 / 来源 / 评论数)', () => {
+ render(<MyIssueList items={[item()]} />);
+ expect(screen.getByText('内置浏览器翻译按钮')).toBeTruthy();
+ const meta = screen.getByText(/#1061/).textContent!;
+ expect(meta).toContain('issueTracker.status.open');
+ expect(meta).toContain('issueTracker.type.feature');
+ expect(meta).toContain('issueTracker.mine.sourceGithub');
+ expect(meta).toContain('issueTracker.mine.commentCount:2');
+ });
+
+ it('平台代发(只在账本里)标 sourceCindy 且状态标未知', () => {
+ render(
+ <MyIssueList
+ items={[item({ state: 'unknown', commentCount: null, sources: ['cindy-tool'] })]}
+ />,
+ );
+ const meta = screen.getByText(/#1061/).textContent!;
+ expect(meta).toContain('issueTracker.mine.statusUnknown');
+ expect(meta).toContain('issueTracker.mine.sourceCindy');
+ // 拿不到评论数时不显示「0 条评论」这种误导信息。
+ expect(meta).not.toContain('commentCount');
+ });
+
+ it('评论数 0 与 null 都不渲染,但两者是不同语义(0 = 已知没人回复)', () => {
+ // 判据必须是显式的 !== null && > 0:写成 falsy 会让 0 与「未知」在代码里混为一谈,
+ // 后续要改成「0 也展示」时会踩空。
+ render(<MyIssueList items={[item({ commentCount: 0 })]} />);
+ expect(screen.getByText(/#1061/).textContent).not.toContain('commentCount');
+ cleanup();
+ render(<MyIssueList items={[item({ commentCount: 1 })]} />);
+ expect(screen.getByText(/#1061/).textContent).toContain('issueTracker.mine.commentCount:1');
+ });
+
+ it('同时命中两个来源时都标出来', () => {
+ render(<MyIssueList items={[item({ sources: ['cindy-tool', 'github-account'] })]} />);
+ const meta = screen.getByText(/#1061/).textContent!;
+ expect(meta).toContain('issueTracker.mine.sourceCindy');
+ expect(meta).toContain('issueTracker.mine.sourceGithub');
+ });
+
+ it('类型为 null 时不渲染类型段', () => {
+ render(<MyIssueList items={[item({ type: null })]} />);
+ expect(screen.getByText(/#1061/).textContent).not.toContain('issueTracker.type.');
+ });
+
+ it('点击整行走 openExternal 打开 GitHub', () => {
+ const openExternal = vi.fn();
+ (window as unknown as { electronAPI: { openExternal: typeof openExternal } }).electronAPI = {
+ openExternal,
+ };
+ render(<MyIssueList items={[item()]} />);
+ fireEvent.click(screen.getByRole('button'));
+ expect(openExternal).toHaveBeenCalledWith('https://github.com/makecindy/cindy/issues/1061');
+ });
+
+ it('每条 issue 一行,按传入顺序渲染', () => {
+ render(<MyIssueList items={[item({ number: 3 }), item({ number: 2 }), item({ number: 1 })]} />);
+ const rows = screen.getAllByRole('button');
+ expect(rows).toHaveLength(3);
+ expect(rows.map((row) => row.textContent!.match(/#\d+/)![0])).toEqual(['#3', '#2', '#1']);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/myIssuesNotices.test.ts b/apps/desktop/src/renderer/features/issue-tracker/__tests__/myIssuesNotices.test.ts
new file mode 100644
index 0000000000..3cea320b4b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/myIssuesNotices.test.ts
@@ -0,0 +1,137 @@
+/**
+ * 顶部提示的选取规则 —— 钉住「哪些降级值得打扰用户」这个产品判断。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import type { MyIssueItem, MyIssuesResult } from '@/../shared/myIssues';
+
+import { selectMyIssuesNotices } from '../lib/myIssuesNotices';
+
+function item(over: Partial<MyIssueItem> = {}): MyIssueItem {
+ return {
+ number: 1,
+ url: 'https://github.com/makecindy/cindy/issues/1',
+ title: 't',
+ type: 'bug',
+ state: 'unknown',
+ createdAt: '2026-07-01T00:00:00.000Z',
+ updatedAt: null,
+ commentCount: null,
+ sources: ['cindy-tool'],
+ ...over,
+ };
+}
+
+function result(over: Partial<MyIssuesResult> = {}): MyIssuesResult {
+ return {
+ items: [],
+ githubEnhancement: null,
+ degraded: null,
+ truncated: false,
+ ...over,
+ };
+}
+
+describe('selectMyIssuesNotices', () => {
+ it('一切正常时不打扰用户', () => {
+ expect(selectMyIssuesNotices(result({ items: [item()] }))).toEqual([]);
+ });
+
+ it('平台接口未就绪 + 列表只有本机账本:说「只显示本机记录」成立', () => {
+ expect(
+ selectMyIssuesNotices(
+ result({ degraded: 'platform-unavailable', items: [item({ state: 'unknown' })] }),
+ ),
+ ).toEqual(['issueTracker.mine.platformUnavailableHint']);
+ });
+
+ it('平台接口未就绪 + 一条都没有:**必须**提示 —— 空的本机兜底不能证明远端历史为空', () => {
+ // 曾经这里返回 [](想省掉接口上线前的常驻横幅),但那会让新设备 / 重装 / 提交早于
+ // 账本功能的用户直接看到「还没有提交过 Issue」,把「暂时查不到」说成「你从未提交」。
+ expect(selectMyIssuesNotices(result({ degraded: 'platform-unavailable' }))).toEqual([
+ 'issueTracker.mine.platformUnavailableHint',
+ ]);
+ });
+
+ it('平台接口未就绪但列表全部来自远端:提示历史可能不全,但不说「只显示本机记录」', () => {
+ expect(
+ selectMyIssuesNotices(
+ result({
+ degraded: 'platform-unavailable',
+ items: [
+ item({ number: 1, state: 'open', sources: ['github-account'] }),
+ item({ number: 2, state: 'closed', sources: ['github-account'] }),
+ ],
+ }),
+ ),
+ ).toEqual(['issueTracker.mine.platformUnavailablePartialHint']);
+ });
+
+ it('混合列表(增强有内容 + 账本里一条平台代发):不得谎称「只显示本机记录」', () => {
+ // 这正是读接口未上线时最常见的真实场景:平台 404、GitHub 增强并回几十条、账本里
+ // 有一条平台代发记录(作者是 cindy-issue App,不出现在 author: 搜索里 → 保持
+ // unknown)。旧判据 some(state === 'unknown') 在这里为真,于是推出「只显示本机
+ // 记录」——而同一页明明列着一堆 GitHub 账号名下的 issue。
+ expect(
+ selectMyIssuesNotices(
+ result({
+ degraded: 'platform-unavailable',
+ items: [
+ item({ number: 1, state: 'open', sources: ['github-account'] }),
+ item({ number: 2, state: 'unknown', sources: ['cindy-tool'] }),
+ ],
+ }),
+ ),
+ ).toEqual(['issueTracker.mine.platformUnavailablePartialHint']);
+ });
+
+ it('未登录 / 取数失败无条件提示,空列表时也要说清是「没查到」而不是「没有」', () => {
+ expect(selectMyIssuesNotices(result({ degraded: 'not-signed-in' }))).toEqual([
+ 'issueTracker.mine.notSignedInHint',
+ ]);
+ expect(selectMyIssuesNotices(result({ degraded: 'fetch-failed' }))).toEqual([
+ 'issueTracker.mine.fetchFailedHint',
+ ]);
+ });
+
+ it('取数失败但增强带回了远端条目:不说「只显示本机记录」(否则与同页列出的自相矛盾)', () => {
+ const withRemote = result({
+ degraded: 'fetch-failed',
+ items: [item({ state: 'open' }), item({ number: 2 })],
+ });
+ expect(selectMyIssuesNotices(withRemote)).toEqual([
+ 'issueTracker.mine.fetchFailedPartialHint',
+ ]);
+
+ // 全部条目都没有实时状态 → 列表确实只有本机账本,那句结论成立。
+ const ledgerOnly = result({ degraded: 'fetch-failed', items: [item(), item({ number: 2 })] });
+ expect(selectMyIssuesNotices(ledgerOnly)).toEqual(['issueTracker.mine.fetchFailedHint']);
+ });
+
+ it('判据看 state 而不是 sources —— 账本里 github-user 的记录也打 github-account', () => {
+ // 上一轮起,账本 identity=github-user 的条目会带 github-account 来源(提交时确认的
+ // 事实),所以 sources 不再等价于「来自远端」。用它当判据会误报成 partial。
+ const ledgerGithubUser = result({
+ degraded: 'fetch-failed',
+ items: [item({ sources: ['cindy-tool', 'github-account'], state: 'unknown' })],
+ });
+ expect(selectMyIssuesNotices(ledgerGithubUser)).toEqual(['issueTracker.mine.fetchFailedHint']);
+ });
+
+ it('截断与降级可以同时提示', () => {
+ expect(
+ selectMyIssuesNotices(result({ degraded: 'fetch-failed', truncated: true, items: [item()] })),
+ ).toEqual(['issueTracker.mine.fetchFailedHint', 'issueTracker.mine.truncatedHint']);
+ });
+
+ it('提示文案 key 与 UI 用的一致(没有 GitHub 身份时绝不提示连接 GitHub)', () => {
+ const keys = [
+ ...selectMyIssuesNotices(result({ degraded: 'platform-unavailable', items: [item()] })),
+ ...selectMyIssuesNotices(result({ degraded: 'not-signed-in' })),
+ ...selectMyIssuesNotices(result({ degraded: 'fetch-failed' })),
+ ...selectMyIssuesNotices(result({ truncated: true })),
+ ];
+ expect(keys.some((key) => /viewerNone|noToken|connectGithub/i.test(key))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/startIssueChat.test.ts b/apps/desktop/src/renderer/features/issue-tracker/__tests__/startIssueChat.test.ts
new file mode 100644
index 0000000000..63a6f07833
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/startIssueChat.test.ts
@@ -0,0 +1,64 @@
+/**
+ * 「点 /issue 开新对话」的草稿预填 —— 钉住两件事:
+ * 1. 写进去的必须是能被命令正则识别的纯文本(不是自然语言指令);
+ * 2. 必须把远程目标重置回本机 —— 否则会话会发到对端机器,issue 就成了用对端
+ * 账号提交的。
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const saveDraft = vi.fn();
+const resetDraftWorkspaceTargets = vi.fn();
+
+vi.mock('@/lib/composerDraftStore', () => ({
+ saveDraft: (...args: unknown[]) => saveDraft(...args),
+ // 只需保持「文本原样进、结构化出」的可断言形状,不测 tiptap 序列化本身。
+ plainTextToTiptapDoc: (text: string) => ({ type: 'doc', plain: text }),
+}));
+
+vi.mock('@/state/newMakerDraft', () => ({
+ resetDraftWorkspaceTargets: () => resetDraftWorkspaceTargets(),
+}));
+
+const { ISSUE_COMMAND_DRAFT_TEXT, prefillIssueCommandDraft } = await import('../lib/startIssueChat');
+
+describe('prefillIssueCommandDraft', () => {
+ beforeEach(() => {
+ saveDraft.mockClear();
+ resetDraftWorkspaceTargets.mockClear();
+ });
+
+ it('把 /issue 预填进 New Maker 草稿,不带附件', () => {
+ prefillIssueCommandDraft();
+ expect(saveDraft).toHaveBeenCalledTimes(1);
+ const [key, draft] = saveDraft.mock.calls[0]!;
+ expect(key).toBe('__new_maker_draft__');
+ expect(draft).toEqual({
+ text: { type: 'doc', plain: ISSUE_COMMAND_DRAFT_TEXT },
+ attachments: [],
+ });
+ });
+
+ it('预填文本能被发送路径的命令正则识别成 issue 命令', () => {
+ // 与 CCAgentSessionView.maybeDispatchDesktopSlashCommand 同一条正则。
+ const match = ISSUE_COMMAND_DRAFT_TEXT.match(/^\/(\S+)(?:\s+(.*))?$/s);
+ expect(match?.[1]).toBe('issue');
+ // 尾随空格不该被当成参数带进命令。
+ expect(match?.[2] ?? '').toBe('');
+ });
+
+ it('用户在命令后补描述时,描述作为 args 传下去', () => {
+ const match = `${ISSUE_COMMAND_DRAFT_TEXT}列表刷新按钮点了没反应`.match(
+ /^\/(\S+)(?:\s+(.*))?$/s,
+ );
+ expect(match?.[1]).toBe('issue');
+ expect(match?.[2]).toBe('列表刷新按钮点了没反应');
+ });
+
+ it('走共享的工作区复位入口(而不是手写字段清单)', () => {
+ // 手写清单正是漏掉 extraDirs 目录授权的原因;复位语义与字段覆盖由
+ // newMakerDraftWorkspaceReset.test.ts 单独钉住。
+ prefillIssueCommandDraft();
+ expect(resetDraftWorkspaceTargets).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts b/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
new file mode 100644
index 0000000000..10ddef9ca8
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
@@ -0,0 +1,90 @@
+/**
+ * useMyIssues —— /issues 列表的数据源。
+ *
+ * 进页面拉一次,之后只由用户点刷新触发(**禁** setInterval 轮询;main 侧本身有
+ * 60s TTL 缓存,重复进页面不会真去打 GitHub)。刷新期间保留旧数据,拿到新数据再
+ * 原子替换,不出现空白帧。
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type { MyIssuesErrorCode, MyIssuesResult } from '@/../shared/myIssues';
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('useMyIssues');
+
+export interface UseMyIssuesState {
+ data: MyIssuesResult | null;
+ /** 首屏加载中(有数据后的刷新走 refreshing,不让列表闪成骨架屏)。 */
+ loading: boolean;
+ refreshing: boolean;
+ /**
+ * 稳定错误码,不是 main 侧的原始错误文本 —— 后者可能带 userData 绝对路径。
+ * UI 只据它选 i18n 文案,不展示原文。
+ */
+ error: MyIssuesErrorCode | null;
+ refresh: () => void;
+}
+
+export function useMyIssues(): UseMyIssuesState {
+ const [data, setData] = useState<MyIssuesResult | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [refreshing, setRefreshing] = useState(false);
+ const [error, setError] = useState<MyIssuesErrorCode | null>(null);
+ const disposed = useRef(false);
+ const inFlight = useRef(false);
+
+ const load = useCallback(async (force: boolean) => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ if (force) setRefreshing(true);
+ try {
+ // 切号会让 main 侧把旧账号的结果作废(stale-account-scope),那不是用户该看到的
+ // 错误 —— 在同一次调用里按新账号重取。刻意不递归调 load:那样外层 finally 会
+ // 清掉内层的 in-flight 标志并提前关掉 loading。上限 2 次,连续切号时不打转。
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const response = await window.electronAPI.maker.listMyIssues({ force });
+ if (disposed.current) return;
+ if (response.success) {
+ setData({
+ items: response.items,
+ githubEnhancement: response.githubEnhancement,
+ degraded: response.degraded,
+ truncated: response.truncated,
+ });
+ setError(null);
+ return;
+ }
+ if (response.error === 'stale-account-scope' && attempt === 0) continue;
+ // 重试仍撞上切号:按通用错误处理,用户点一次刷新即可。
+ setError(response.error === 'stale-account-scope' ? 'unexpected' : response.error);
+ return;
+ }
+ } catch (err) {
+ if (disposed.current) return;
+ // IPC 层抛错(如来源校验拒绝)只记本地日志,UI 走统一的通用文案。
+ log.warn('listMyIssues failed', { error: err instanceof Error ? err.message : String(err) });
+ setError('unexpected');
+ } finally {
+ inFlight.current = false;
+ if (!disposed.current) {
+ setLoading(false);
+ setRefreshing(false);
+ }
+ }
+ }, []);
+
+ useEffect(() => {
+ disposed.current = false;
+ void load(false);
+ return () => {
+ disposed.current = true;
+ };
+ }, [load]);
+
+ const refresh = useCallback(() => {
+ void load(true);
+ }, [load]);
+
+ return { data, loading, refreshing, error, refresh };
+}
diff --git a/apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts b/apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts
new file mode 100644
index 0000000000..95779eb977
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/lib/myIssuesNotices.ts
@@ -0,0 +1,62 @@
+/**
+ * 「我的 Issue」页顶部提示的选取规则(纯函数,返回 i18n key)。
+ *
+ * 抽出来的原因:这里是产品判断而不是渲染细节 —— 哪些降级值得打扰用户、哪些不值得,
+ * 需要能被单测钉住,不该埋在组件里。
+ *
+ * 贯穿本文件的一条判据:**提示不得断言页面上不存在的数据范围**。「只显示本机记录」
+ * 这类结论必须先确认列表里真的没有远端内容,否则它会与同一页列出的东西自相矛盾。
+ */
+
+import type { MyIssuesResult } from '@/../shared/myIssues';
+
+/**
+ * 列表里是否有远端数据。判据用 state —— 账本兜底项一律 `unknown`,任何带真实状态的
+ * 条目都只能来自远端(平台通道或 GitHub 增强)。
+ *
+ * 刻意**不**看 `sources.includes('github-account')`:账本里 identity 为 github-user
+ * 的记录也会打这个来源(那是提交时就确认的事实),所以它不再等价于「来自远端」。
+ */
+function hasRemoteData(data: MyIssuesResult): boolean {
+ return data.items.some((item) => item.state !== 'unknown');
+}
+
+/**
+ * 平台那一路拿不到数据时的提示。`platform-unavailable`(接口还没上线)与 `fetch-failed`
+ * (网络 / 服务端异常)**结构完全相同** —— 都是「平台侧的历史与实时状态都拿不到」,
+ * 区别只在原因,所以共用一份逻辑,不各写一遍。
+ *
+ * 两条都**无条件提示**。先前 platform-unavailable 只在「列表里有 unknown 项」时才提示,
+ * 想省掉接口上线前的常驻横幅,但那个优化会造出更坏的结果:账本为空(新设备、重装、或
+ * 提交早于账本功能)时一条提示都没有,页面直接显示「还没有提交过 Issue」——
+ * 空的本机兜底**不能证明远端历史为空**,于是把「暂时查不到」说成了「你从未提交」。
+ * 噪音只是烦,错误信息是骗人的,后者更糟。
+ *
+ * 措辞按列表里有没有远端内容选:混合列表用不带「仅本机」结论的那版。
+ */
+function platformNoticeKey(data: MyIssuesResult, reason: 'unavailable' | 'fetchFailed'): string {
+ const suffix = hasRemoteData(data) ? 'PartialHint' : 'Hint';
+ const base = reason === 'unavailable' ? 'platformUnavailable' : 'fetchFailed';
+ return `issueTracker.mine.${base}${suffix}`;
+}
+
+export function selectMyIssuesNotices(data: MyIssuesResult): string[] {
+ const notices: string[] = [];
+
+ if (data.degraded === 'platform-unavailable') {
+ notices.push(platformNoticeKey(data, 'unavailable'));
+ }
+ // 未登录:文案讲的是「登录后能看到全部与最新状态」,不含「仅本机」结论,
+ // 无论列表里有没有远端内容都成立,所以只有这一条不需要分版本。
+ if (data.degraded === 'not-signed-in') {
+ notices.push('issueTracker.mine.notSignedInHint');
+ }
+ if (data.degraded === 'fetch-failed') {
+ notices.push(platformNoticeKey(data, 'fetchFailed'));
+ }
+ if (data.truncated) {
+ notices.push('issueTracker.mine.truncatedHint');
+ }
+
+ return notices;
+}
diff --git a/apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts b/apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts
new file mode 100644
index 0000000000..26691b2bd9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/lib/startIssueChat.ts
@@ -0,0 +1,34 @@
+/**
+ * startIssueChat —— 从 Issue 页一键开一个预填了 `/issue` 的新对话。
+ *
+ * 复用 contacts / Skillhub 的「不预创建会话」模式:只把命令预填进系统原生的
+ * New Maker 草稿(composerDraftStore 以 NEW_MAKER_DRAFT_KEY 为键),调用方随后
+ * navigate('/cc-agent/new')。用户在那里自己选 agent / 模型后回车,走正常建会话
+ * 路径 —— 不绕过任何会话创建逻辑,也**不自动发送**(他还要补充描述)。
+ *
+ * 为什么预填纯文本就够:命令识别是发送时对消息文本跑正则
+ * (`CCAgentSessionView.maybeDispatchDesktopSlashCommand`),不依赖编辑器里的
+ * 命令 mark;新会话的首条 pending 消息同样经过那条识别路径。
+ *
+ * 同时把草稿的工作区目标复位成干净的本机对话态(resetDraftWorkspaceTargets),原因有两条:
+ * 1. 残留的远程目标会把会话发到对端机器,issue 就成了用对端账号提交的 —— 用户在这台
+ * 机器上点的按钮,结果落到另一台;
+ * 2. 残留的 extraDirs 是**目录读取授权**,会让这段反馈对话悄悄继承对无关本地目录的
+ * 访问权(#1103 review)。
+ * 刻意调那个共享函数而不是在这里手写字段清单 —— 手写正是上一版漏掉 extraDirs 的原因。
+ */
+
+import { NEW_MAKER_DRAFT_KEY } from '@/features/cc-agent/newMakerDraftKeys';
+import { plainTextToTiptapDoc, saveDraft } from '@/lib/composerDraftStore';
+import { resetDraftWorkspaceTargets } from '@/state/newMakerDraft';
+
+/** 末尾留一个空格:光标停在命令后面,用户可以直接接着写描述。 */
+export const ISSUE_COMMAND_DRAFT_TEXT = '/issue ';
+
+export function prefillIssueCommandDraft(): void {
+ saveDraft(NEW_MAKER_DRAFT_KEY, {
+ text: plainTextToTiptapDoc(ISSUE_COMMAND_DRAFT_TEXT),
+ attachments: [],
+ });
+ resetDraftWorkspaceTargets();
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index bc3c428655..4a654074cc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6648,6 +6648,24 @@
"emptyFilter": "No matching issues",
"clearFilters": "Clear filters"
},
+ "mine": {
+ "refresh": "Refresh",
+ "emptyTitle": "No issues submitted yet",
+ "startIssueChat": "Start a new chat with /issue",
+ "statusUnknown": "Status unknown",
+ "sourceCindy": "Submitted from Cindy",
+ "sourceGithub": "GitHub account",
+ "commentCount_one": "{{count}} comment",
+ "commentCount_other": "{{count}} comments",
+ "openOnGithub": "Open on GitHub",
+ "viewerGithub": "GitHub account @{{login}}",
+ "platformUnavailableHint": "Showing only submissions recorded on this device. Issues you filed on other devices, and their live status on GitHub, aren't available in the app yet.",
+ "platformUnavailablePartialHint": "Issues you filed on other devices aren't available in the app yet, so this list may be incomplete.",
+ "notSignedInHint": "Sign in to your Cindy account to see every issue you've filed, along with its current status.",
+ "fetchFailedHint": "Couldn't load the latest status. Showing only submissions recorded on this device, so this list may be incomplete.",
+ "fetchFailedPartialHint": "Couldn't load the latest status, so some issues may show incomplete status.",
+ "truncatedHint": "There are more issues than shown here — open GitHub for the full list."
+ },
"redirect": {
"title": "Select an issue from the left",
"description": "Browse the list to view issues, or create a new one to report a bug or suggest a feature.",
@@ -6861,7 +6879,6 @@
"cancel": "Cancel"
},
"redirect": {
- "title": "Issues have moved to GitHub",
"descriptionBefore": "Type ",
"descriptionAfter": " in a chat to report a problem or suggestion — the AI will confirm the details with you before submitting.",
"cta": "View GitHub Issues"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 806578e7db..5e6dda695d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6638,6 +6638,23 @@
"emptyFilter": "一致する Issue がありません",
"clearFilters": "フィルターをクリア"
},
+ "mine": {
+ "refresh": "更新",
+ "emptyTitle": "送信した Issue はまだありません",
+ "startIssueChat": "/issue で新しいチャットを開始",
+ "statusUnknown": "ステータス不明",
+ "sourceCindy": "Cindy から送信",
+ "sourceGithub": "GitHub アカウント",
+ "commentCount_other": "コメント {{count}} 件",
+ "openOnGithub": "GitHub で開く",
+ "viewerGithub": "GitHub アカウント @{{login}}",
+ "platformUnavailableHint": "この端末に記録された送信分のみを表示しています。他の端末から送信した Issue と GitHub 上の最新ステータスは、まだアプリ内で表示できません。",
+ "platformUnavailablePartialHint": "他の端末から送信した Issue はまだアプリ内で表示できないため、一覧が不完全な場合があります。",
+ "notSignedInHint": "Cindy アカウントにサインインすると、送信したすべての Issue と最新のステータスを表示できます。",
+ "fetchFailedHint": "最新ステータスを取得できませんでした。この端末に記録された送信分のみを表示しているため、一覧が不完全な場合があります。",
+ "fetchFailedPartialHint": "最新ステータスを取得できませんでした。一部の Issue はステータスが不完全な場合があります。",
+ "truncatedHint": "Issue が多いため一部のみ表示しています。全件は GitHub で確認してください。"
+ },
"redirect": {
"title": "左から Issue を選択してください",
"description": "左のリストを参照するか、新しい Issue を作成してバグ報告や機能提案を行ってください。",
@@ -6851,7 +6868,6 @@
"cancel": "キャンセル"
},
"redirect": {
- "title": "Issue は GitHub に移行しました",
"descriptionBefore": "チャットで ",
"descriptionAfter": " と入力すると、AI が詳細を確認したうえで問題や提案を提出します。",
"cta": "GitHub Issues を見る"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b232083c9b..7aea1bf0f9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6638,6 +6638,23 @@
"emptyFilter": "일치하는 이슈가 없습니다",
"clearFilters": "필터 지우기"
},
+ "mine": {
+ "refresh": "새로 고침",
+ "emptyTitle": "아직 제출한 이슈가 없습니다",
+ "startIssueChat": "/issue 로 새 채팅 시작",
+ "statusUnknown": "상태 알 수 없음",
+ "sourceCindy": "Cindy에서 제출",
+ "sourceGithub": "GitHub 계정",
+ "commentCount_other": "댓글 {{count}}개",
+ "openOnGithub": "GitHub에서 열기",
+ "viewerGithub": "GitHub 계정 @{{login}}",
+ "platformUnavailableHint": "이 기기에 기록된 제출 항목만 표시합니다. 다른 기기에서 제출한 이슈와 GitHub의 최신 상태는 아직 앱에서 확인할 수 없습니다.",
+ "platformUnavailablePartialHint": "다른 기기에서 제출한 이슈는 아직 앱에서 확인할 수 없어 목록이 완전하지 않을 수 있습니다.",
+ "notSignedInHint": "Cindy 계정에 로그인하면 제출한 모든 이슈와 최신 상태를 볼 수 있습니다.",
+ "fetchFailedHint": "최신 상태를 가져오지 못했습니다. 이 기기에 기록된 제출 항목만 표시하므로 목록이 완전하지 않을 수 있습니다.",
+ "fetchFailedPartialHint": "최신 상태를 가져오지 못했습니다. 일부 이슈의 상태가 완전하지 않을 수 있습니다.",
+ "truncatedHint": "이슈가 많아 일부만 표시했습니다. 전체 목록은 GitHub에서 확인하세요."
+ },
"redirect": {
"title": "왼쪽에서 이슈를 선택하세요",
"description": "왼쪽 목록에서 이슈를 보거나, 새 이슈를 만들어 버그 보고 또는 기능 제안을 하세요.",
@@ -6851,7 +6868,6 @@
"cancel": "취소"
},
"redirect": {
- "title": "Issue가 GitHub로 이전되었습니다",
"descriptionBefore": "채팅에서 ",
"descriptionAfter": " 를 입력하면 AI가 세부 사항을 확인한 후 문제나 제안을 제출합니다.",
"cta": "GitHub Issues 보기"
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 0dea8213dc..3600881900 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6638,6 +6638,23 @@
"emptyFilter": "没有匹配的 Issue",
"clearFilters": "清空筛选"
},
+ "mine": {
+ "refresh": "刷新",
+ "emptyTitle": "还没有提交过 Issue",
+ "startIssueChat": "用 /issue 开始新对话",
+ "statusUnknown": "状态未知",
+ "sourceCindy": "由 Cindy 提交",
+ "sourceGithub": "GitHub 账号",
+ "commentCount_other": "{{count}} 条评论",
+ "openOnGithub": "在 GitHub 上打开",
+ "viewerGithub": "GitHub 账号 @{{login}}",
+ "platformUnavailableHint": "当前只显示本机记录的提交。在其它设备上提交过的 Issue、以及它们在 GitHub 上的最新状态,暂时无法在应用内查看。",
+ "platformUnavailablePartialHint": "在其它设备上提交过的 Issue 暂时无法在应用内查看,列表可能不完整。",
+ "notSignedInHint": "登录 Cindy 账号后,可以看到你提交过的全部 Issue 和它们的最新状态。",
+ "fetchFailedHint": "暂时取不到最新状态,当前只显示本机记录的提交,列表可能不完整。",
+ "fetchFailedPartialHint": "暂时取不到最新状态,部分 Issue 的状态可能显示不全。",
+ "truncatedHint": "Issue 较多,这里只列出了一部分,完整列表请在 GitHub 上查看。"
+ },
"redirect": {
"title": "从左侧选择一个 Issue",
"description": "浏览左侧列表查看 Issue,或者创建一个新 Issue 来报告 Bug 或提出功能建议。",
@@ -6851,7 +6868,6 @@
"cancel": "取消"
},
"redirect": {
- "title": "Issue 已迁移至 GitHub",
"descriptionBefore": "在对话中输入 ",
"descriptionAfter": " 即可提交问题或建议,AI 会与你确认细节后帮你提交。",
"cta": "查看 GitHub Issues"
diff --git a/apps/desktop/src/renderer/state/newMakerDraft.ts b/apps/desktop/src/renderer/state/newMakerDraft.ts
index e73b14abfe..ac6dde9840 100644
--- a/apps/desktop/src/renderer/state/newMakerDraft.ts
+++ b/apps/desktop/src/renderer/state/newMakerDraft.ts
@@ -425,6 +425,22 @@ export function patchDraft(patch: Partial<NewMakerDraft>): void {
emit();
}
+/**
+ * 把草稿的「这次要跑在哪」复位成干净的本机对话态。
+ *
+ * 只需这两个字段:workingDir=null 经上面的兜底级联同时清掉 remoteHostId /
+ * deviceLink* / collab.enabled。vendor / lastByVendor / fastModeByModel 等模型偏好
+ * 保持不变(那是「我常用哪个」的记忆,与「这次跑在哪」正交)。
+ *
+ * **任何「另起一段干净对话」的入口都必须走这里,不要各自手写字段清单。**
+ * extraDirs 是单次草稿的**目录读取授权**,漏掉它会让新会话悄悄继承对无关本地目录的
+ * 访问权(#1103 review 实例:两个预填入口都手写了清单,把级联已经处理的三个字段
+ * 抄了一遍,却都漏了真正需要清的这一个)。新增工作区字段时只改这一处。
+ */
+export function resetDraftWorkspaceTargets(): void {
+ patchDraft({ workingDir: null, extraDirs: [] });
+}
+
/** 单字段写入 collab(便捷 setter,语义比 patchDraft({ collab: ... }) 更直接)。 */
export function patchCollab(patch: Partial<CollabDraft>): void {
patchDraft({ collab: { ...currentDraft.collab, ...patch } });
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 26281666ca..f531f328fa 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4413,6 +4413,19 @@ interface ElectronAPI {
helpFeedbackCreate: (
input: import('../shared/helpTypes').HelpFeedbackDraftInput,
) => Promise<import('../shared/helpTypes').HelpFeedbackDraft>;
+ /** /issues 页面的「我的 Issue」列表;force=true 绕过 main 侧 60s TTL(手动刷新)。 */
+ listMyIssues: (options?: { force?: boolean }) => Promise<
+ | ({ success: true } & import('../shared/myIssues').MyIssuesResult)
+ | {
+ success: false;
+ /** 稳定脱敏码,不是原始错误文本。 */
+ error: import('../shared/myIssues').MyIssuesErrorCode;
+ items: [];
+ githubEnhancement: null;
+ degraded: null;
+ truncated: false;
+ }
+ >;
writePlanFile: (params: {
requestId: string;
planFilePath: string;
diff --git a/apps/desktop/src/shared/myIssues.ts b/apps/desktop/src/shared/myIssues.ts
new file mode 100644
index 0000000000..924f595c70
--- /dev/null
+++ b/apps/desktop/src/shared/myIssues.ts
@@ -0,0 +1,123 @@
+/**
+ * 「我的 Issue」列表的跨进程契约。
+ *
+ * 看自己的 issue 与提交 issue 走**同一条公共能力**:只要 Cindy 登录态,不要求用户
+ * 有 GitHub 账号。平台代发本来就是服务端在代提交,它天生知道「哪个 Cindy 账号提交
+ * 了哪条 issue」,所以「我的 issue 列表」由它出既准确、也跨设备。
+ *
+ * 三路输入合成一份列表:
+ * - 平台通道(主)—— 服务端按 Cindy 账号返回的提交记录 + 实时状态;
+ * - 本机账本 —— 产品内 /issue 工具提交成功时落在本机的记录。平台接口未就绪或
+ * 离线时是唯一来源,标题/编号/时间照常可见,只是没有实时状态;
+ * - GitHub 账号(可选增强)—— 仅当用户恰好配了 Cindy GitHub 插件或本机 gh CLI 时,
+ * 把他自己 GitHub 账号名下的 issue 也并进来。**它只是加成,绝不是前提**,
+ * 没有它列表照常工作。
+ */
+
+/** 反馈仓 —— 与 githubUserIssueSubmitter 的 FEEDBACK_REPOSITORY 同一个仓。 */
+export const MY_ISSUES_REPOSITORY = { owner: 'makecindy', repo: 'cindy' } as const;
+
+/**
+ * 列表项的链接**一律由 issue 号派生**,不采纳任何来源给的原值。
+ *
+ * 三路输入里的链接字段都是外部数据(本机账本 JSON 可被篡改或损坏、平台响应、
+ * 插件通道转发的 GitHub 响应),而这一页的每一行都在向用户声称「这是你在本仓提的
+ * issue」,整行点击直接交给 openExternal。派生而非校验,是因为产出点有两处
+ * (远端 overlay 与账本兜底),逐处校验总会漏掉新加的那处;`number` 在两条解析路径上
+ * 都已被钉成正整数,派生后链接就没有可被污染的余地。
+ *
+ * (全局 `shell:open-external` 另有一道 http(s) 白名单,挡的是 scheme 滥用;
+ * 这里挡的是「站内链接被换成任意站点」,两道各管一层。)
+ */
+export function myIssueUrl(issueNumber: number): string {
+ const { owner, repo } = MY_ISSUES_REPOSITORY;
+ return `https://github.com/${owner}/${repo}/issues/${issueNumber}`;
+}
+
+/**
+ * 账本落盘条目的链接是否指向本仓对应编号的 issue。
+ *
+ * 比对 host + path 而不是整串相等:提交链路存的是远端返回的 html_url,容忍尾斜杠
+ * 之类的无害差异,免得把用户真实的历史记录当垃圾清掉。
+ */
+export function isMyIssueUrl(url: string, issueNumber: number): boolean {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== 'https:' || parsed.host !== 'github.com') return false;
+ const { owner, repo } = MY_ISSUES_REPOSITORY;
+ return parsed.pathname.replace(/\/+$/, '') === `/${owner}/${repo}/issues/${issueNumber}`;
+}
+
+export type MyIssueSource = 'github-account' | 'cindy-tool';
+
+/** 拿不到实时状态时落在 'unknown',UI 只展示已知信息、不假装知道状态。 */
+export type MyIssueState = 'open' | 'closed' | 'unknown';
+
+export interface MyIssueItem {
+ number: number;
+ /** 由 number 派生(myIssueUrl),不是任何来源给的原值 —— 原因见 myIssueUrl 注释。 */
+ url: string;
+ title: string;
+ /** 由 labels 推断;两个标签都没有时为 null(例如 issue 被人工改过标签)。 */
+ type: 'bug' | 'feature' | null;
+ state: MyIssueState;
+ /** ISO 时间。查得到远端数据时用远端 created_at,否则回退账本记的提交时间。 */
+ createdAt: string;
+ /** ISO 时间;拿不到远端数据时为 null。 */
+ updatedAt: string | null;
+ /** 评论数;拿不到远端数据时为 null。 */
+ commentCount: number | null;
+ sources: MyIssueSource[];
+}
+
+/**
+ * 平台通道拿不到数据时的降级原因。三者都只影响「有没有实时状态」,
+ * 本机账本记录照常展示。
+ * - platform-unavailable:服务端还没提供这条读接口(404 / 501);
+ * - not-signed-in:Cindy 登录态不可用;
+ * - fetch-failed:网络或服务端异常。
+ */
+export type MyIssuesDegradedReason = 'platform-unavailable' | 'not-signed-in' | 'fetch-failed';
+
+/** 可选增强用到的 GitHub 身份来源:插件 PAT 优先,本机 gh CLI 兜底。 */
+export type GithubEnhancementSource = 'ghost' | 'gh-cli';
+
+export interface MyIssuesResult {
+ items: MyIssueItem[];
+ /**
+ * 可选增强的 GitHub 身份;null = 没配,属于**正常状态**,
+ * UI 不得因此提示「你需要 GitHub 账号」。
+ */
+ githubEnhancement: { login: string; source: GithubEnhancementSource } | null;
+ degraded: MyIssuesDegradedReason | null;
+ /** true = 结果超出单页上限被截断,UI 必须明说而不是静默丢。 */
+ truncated: boolean;
+}
+
+/**
+ * 查询失败时跨进程回传的**稳定脱敏码**。刻意不回原始 Error.message ——
+ * 它可能带 userData 绝对路径或上游响应片段,细节只留在 main 日志里。
+ * - stale-account-scope:请求期间切了账号,结果属于旧账号已被丢弃,重取即可;
+ * - unexpected:其余意外错误,详情看 main 日志。
+ */
+export type MyIssuesErrorCode = 'stale-account-scope' | 'unexpected';
+
+/** 本机账本里的一条提交记录。 */
+export interface SubmittedIssueRecord {
+ number: number;
+ url: string;
+ /** 提交时的最终标题(用户在确认卡片上确认的那一版)。 */
+ title: string;
+ type: 'bug' | 'feature';
+ /** ISO 时间。 */
+ submittedAt: string;
+ identity: 'github-user' | 'platform';
+ /** identity === 'github-user' 时的 GitHub 用户名。 */
+ githubLogin?: string;
+ /** identity === 'platform' 时写进 issue 正文的公开署名。 */
+ publicName?: string;
+}
diff --git a/packages/github-client/src/types.ts b/packages/github-client/src/types.ts
index e029bb1c5c..00a0a91ecb 100644
--- a/packages/github-client/src/types.ts
+++ b/packages/github-client/src/types.ts
@@ -75,6 +75,8 @@ export interface GithubIssue {
html_url: string;
created_at: string;
updated_at: string;
+ /** 评论数。声明为可选:老调用点不依赖它,search 结果里也不保证出现。 */
+ comments?: number;
/** issue 是 PR 时 GitHub 会带 pull_request 对象;纯 issue 时无此字段 */
pull_request?: { url: string; html_url: string } | null;
}