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。

fix(github): 修复下载排队与登录取消刷新生命周期

Dash305334856834
diff --git a/apps/desktop/src/main/__tests__/githubSetup.test.ts b/apps/desktop/src/main/__tests__/githubSetup.test.ts
index eaa3d80e37..ba4b8b832a 100644
--- a/apps/desktop/src/main/__tests__/githubSetup.test.ts
+++ b/apps/desktop/src/main/__tests__/githubSetup.test.ts
@@ -64,12 +64,22 @@ describe('GitHub setup', () => {
);
setup.start();
await vi.waitFor(() => expect(deps.install).toHaveBeenCalledOnce());
- setup.cancel();
+ const cancelled = setup.cancel();
+ let settled = false;
+ void cancelled.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
setup.start();
finish('/managed/gh');
await vi.waitFor(() => expect(setup.snapshot().phase).toBe('cancelled'));
expect(deps.login).not.toHaveBeenCalled();
expect(deps.connected).not.toHaveBeenCalled();
+ await cancelled;
+ deps.available.mockResolvedValue(true);
+ setup.start();
+ await vi.waitFor(() => expect(setup.snapshot().phase).toBe('connected'));
});
it('reads only a complete device code, including the clipboard configuration variant', () => {
expect(deviceCodeFromOutput('! First copy your one-time code: ABCD-123')).toBeUndefined();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts
index 53f60a6938..0ac5aae7d2 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/byokImageChannel.test.ts
@@ -3,7 +3,11 @@ import { readFileSync } from 'node:fs';
import { describe, expect, it, vi } from 'vitest';
import { isOrganizationManagedProvider, type Provider } from '@cindy/model-providers';
-import { createByokImageChannel, pruneDynamicImageChannels, registerByokImageChannels } from '../byokImageChannel.js';
+import {
+ createByokImageChannel,
+ pruneDynamicImageChannels,
+ registerByokImageChannels,
+} from '../byokImageChannel.js';
import { ImageChannelRegistry, type ImageChannel } from '../imageChannelRegistry.js';
const PROVIDER_ID = 'byok-a';
@@ -131,7 +135,9 @@ describe('createByokImageChannel', () => {
expect(channel.ready()).toBe(true);
key = null;
expect(channel.ready()).toBe(false);
- await expect(channel.generateImage({ model: MODEL, prompt: 'test' })).rejects.toThrow(/凭证未就绪/);
+ await expect(channel.generateImage({ model: MODEL, prompt: 'test' })).rejects.toThrow(
+ /凭证未就绪/,
+ );
expect(doFetch).not.toHaveBeenCalled();
});
@@ -212,12 +218,20 @@ describe('createByokImageChannel', () => {
describe('dynamic image channel lifecycle', () => {
const enterprise: Provider = {
...orgProvider([{ id: MODEL, name: 'Enterprise image' }]),
- auth: { method: 'managed' }, agents: [], routing: {}, models: {},
+ auth: { method: 'managed' },
+ agents: [],
+ routing: {},
+ models: {},
};
const personal: Provider = {
- id: PROVIDER_ID, name: 'Personal Codex', source: 'user',
- auth: { method: 'oauth', native: 'codex' }, agents: ['codex'],
- routing: {}, models: {}, imageModels: [{ id: 'personal-image', name: 'Personal image' }],
+ id: PROVIDER_ID,
+ name: 'Personal Codex',
+ source: 'user',
+ auth: { method: 'oauth', native: 'codex' },
+ agents: ['codex'],
+ routing: {},
+ models: {},
+ imageModels: [{ id: 'personal-image', name: 'Personal image' }],
};
function harness() {
@@ -230,7 +244,12 @@ describe('dynamic image channel lifecycle', () => {
const refresh = (providers: Provider[]) => {
pruneDynamicImageChannels(registry, providers, registeredCodex, registeredByok);
for (const provider of providers) {
- if (isOrganizationManagedProvider(provider) || provider.auth.native !== 'codex' || registeredCodex.has(provider.id)) continue;
+ if (
+ isOrganizationManagedProvider(provider) ||
+ provider.auth.native !== 'codex' ||
+ registeredCodex.has(provider.id)
+ )
+ continue;
registry.register(provider.id, createPersonal());
registeredCodex.add(provider.id);
}
@@ -239,21 +258,25 @@ describe('dynamic image channel lifecycle', () => {
return { registry, registeredCodex, registeredByok, createEnterprise, createPersonal, refresh };
}
- it.each(['enterprise-first', 'personal-first'] as const)('switches the same ID in both directions (%s)', (order) => {
- const h = harness();
- const sequence = order === 'enterprise-first'
- ? [enterprise, personal, enterprise]
- : [personal, enterprise, personal];
- for (const provider of sequence) {
- h.refresh([provider]);
- const managed = isOrganizationManagedProvider(provider);
- const factory = managed ? h.createEnterprise : h.createPersonal;
- expect(h.registry.resolve(PROVIDER_ID)).toBe(factory.mock.results.at(-1)?.value);
- expect(h.registeredByok.has(PROVIDER_ID)).toBe(managed);
- expect(h.registeredCodex.has(PROVIDER_ID)).toBe(!managed);
- }
- expect(h.createEnterprise.mock.calls.length + h.createPersonal.mock.calls.length).toBe(3);
- });
+ it.each(['enterprise-first', 'personal-first'] as const)(
+ 'switches the same ID in both directions (%s)',
+ (order) => {
+ const h = harness();
+ const sequence =
+ order === 'enterprise-first'
+ ? [enterprise, personal, enterprise]
+ : [personal, enterprise, personal];
+ for (const provider of sequence) {
+ h.refresh([provider]);
+ const managed = isOrganizationManagedProvider(provider);
+ const factory = managed ? h.createEnterprise : h.createPersonal;
+ expect(h.registry.resolve(PROVIDER_ID)).toBe(factory.mock.results.at(-1)?.value);
+ expect(h.registeredByok.has(PROVIDER_ID)).toBe(managed);
+ expect(h.registeredCodex.has(PROVIDER_ID)).toBe(!managed);
+ }
+ expect(h.createEnterprise.mock.calls.length + h.createPersonal.mock.calls.length).toBe(3);
+ },
+ );
it('removes image execution for chat-only providers and restores it when images return', () => {
const h = harness();
@@ -268,28 +291,34 @@ describe('dynamic image channel lifecycle', () => {
expect(h.createEnterprise).toHaveBeenCalledTimes(2);
});
- it.each([enterprise, personal])('removes the $source channel on logout without disturbing static channels', (provider) => {
- const h = harness();
- const statics = new Map(['xd', 'openai', 'gemini', 'xai'].map((id) => [id, stubChannel()]));
- for (const [id, channel] of statics) h.registry.register(id, channel);
- h.refresh([provider]);
- h.refresh([]);
- expect(h.registeredByok.size).toBe(0);
- expect(h.registeredCodex.size).toBe(0);
- expect(h.registry.isProviderReady(PROVIDER_ID)).toBe(false);
- expect(() => h.registry.resolve(PROVIDER_ID)).toThrow(/没有可用的执行通道/);
- for (const [id, channel] of statics) expect(h.registry.resolve(id)).toBe(channel);
- });
+ it.each([enterprise, personal])(
+ 'removes the $source channel on logout without disturbing static channels',
+ (provider) => {
+ const h = harness();
+ const statics = new Map(['xd', 'openai', 'gemini', 'xai'].map((id) => [id, stubChannel()]));
+ for (const [id, channel] of statics) h.registry.register(id, channel);
+ h.refresh([provider]);
+ h.refresh([]);
+ expect(h.registeredByok.size).toBe(0);
+ expect(h.registeredCodex.size).toBe(0);
+ expect(h.registry.isProviderReady(PROVIDER_ID)).toBe(false);
+ expect(() => h.registry.resolve(PROVIDER_ID)).toThrow(/没有可用的执行通道/);
+ for (const [id, channel] of statics) expect(h.registry.resolve(id)).toBe(channel);
+ },
+ );
- it.each([enterprise, personal])('keeps unchanged $source channels registered only once', (provider) => {
- const h = harness();
- h.refresh([provider]);
- const channel = h.registry.resolve(PROVIDER_ID);
- h.refresh([provider]);
- expect(h.registry.resolve(PROVIDER_ID)).toBe(channel);
- expect(h.createEnterprise.mock.calls.length + h.createPersonal.mock.calls.length).toBe(1);
- expect(() => h.registry.register(PROVIDER_ID, stubChannel())).toThrow(/already registered/);
- });
+ it.each([enterprise, personal])(
+ 'keeps unchanged $source channels registered only once',
+ (provider) => {
+ const h = harness();
+ h.refresh([provider]);
+ const channel = h.registry.resolve(PROVIDER_ID);
+ h.refresh([provider]);
+ expect(h.registry.resolve(PROVIDER_ID)).toBe(channel);
+ expect(h.createEnterprise.mock.calls.length + h.createPersonal.mock.calls.length).toBe(1);
+ expect(() => h.registry.register(PROVIDER_ID, stubChannel())).toThrow(/already registered/);
+ },
+ );
});
describe('Art BYOK image channel host wiring', () => {
@@ -322,7 +351,9 @@ describe('Art BYOK image channel host wiring', () => {
it('prunes stale accounts before either dynamic registration loop runs', () => {
const prune = body.indexOf('pruneDynamicImageChannels(');
expect(prune).toBeGreaterThan(body.indexOf('imageChannelRegistrySingleton = registry;'));
- expect(prune).toBeLessThan(body.indexOf('imageChannelRegistrySingleton.register(providerId'));
+ expect(prune).toBeLessThan(
+ body.search(/imageChannelRegistrySingleton\.register\(\s*providerId/),
+ );
expect(prune).toBeLessThan(body.indexOf('registerByokImageChannels('));
});
});
diff --git a/apps/desktop/src/main/downloader/__tests__/download.test.ts b/apps/desktop/src/main/downloader/__tests__/download.test.ts
index 8652047baa..73c3f1ae20 100644
--- a/apps/desktop/src/main/downloader/__tests__/download.test.ts
+++ b/apps/desktop/src/main/downloader/__tests__/download.test.ts
@@ -197,7 +197,7 @@ describe('shared verified downloads', () => {
).rejects.toMatchObject({ code: 'ABORTED' });
expect(fs.existsSync(opts.targetPath)).toBe(false);
});
- it('applies a total deadline while queued without cancelling the active download', async () => {
+ it('allows a queued download its full active budget without cancelling the current download', async () => {
vi.useFakeTimers();
let release!: (response: Response) => void;
fetchMock.mockImplementationOnce(
@@ -208,14 +208,13 @@ describe('shared verified downloads', () => {
);
const first = download(options());
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
- const second = expect(
- download({ ...options(), timeout: { totalMs: 100 } }),
- ).rejects.toMatchObject({ code: 'TIMEOUT' });
+ fetchMock.mockResolvedValueOnce(new Response('abcdef'));
+ const second = download({ ...options(), timeout: { totalMs: 100 } });
await vi.advanceTimersByTimeAsync(100);
- await second;
expect(fetchMock).toHaveBeenCalledOnce();
release(new Response('abcdef'));
await first;
+ await expect(second).resolves.toMatchObject({ size: 6 });
expect(getActive()).toEqual([]);
expect(vi.getTimerCount()).toBe(0);
});
diff --git a/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts b/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts
index c4ab6c66f1..ba3fa34db0 100644
--- a/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts
+++ b/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts
@@ -30,6 +30,45 @@ function options(url: string, targetPath: string, sha256: string, signal?: Abort
}
describe('downloader scheduler queued cancellation', () => {
+ it('starts the total timeout only when a queued transfer obtains its slot', async () => {
+ vi.useFakeTimers();
+ try {
+ let finish!: () => void;
+ mocks.executeOnce
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = () => resolve({ size: 1, sha256: HASH_A });
+ }),
+ )
+ .mockImplementationOnce(
+ ({ signal }) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
+ }),
+ );
+ mocks.withRetry.mockImplementation(async (run: () => Promise<unknown>) => run());
+ const scheduler = new Scheduler({ maxConcurrent: 1 });
+ const first = scheduler.enqueue(
+ options('https://first.invalid', path.join(root, 'first'), HASH_A),
+ );
+ const second = scheduler.enqueue({
+ ...options('https://second.invalid', path.join(root, 'second'), HASH_B),
+ timeout: { totalMs: 120_000 },
+ });
+ const rejected = expect(second).rejects.toMatchObject({ code: 'TIMEOUT' });
+ await vi.advanceTimersByTimeAsync(180_000);
+ expect(mocks.executeOnce).toHaveBeenCalledTimes(1);
+ finish();
+ await first;
+ expect(mocks.executeOnce).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(120_000);
+ await rejected;
+ expect(scheduler.listActive()).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-scheduler-'));
vi.resetAllMocks();
diff --git a/apps/desktop/src/main/downloader/index.ts b/apps/desktop/src/main/downloader/index.ts
index ccc5ff34c4..e662d41a41 100644
--- a/apps/desktop/src/main/downloader/index.ts
+++ b/apps/desktop/src/main/downloader/index.ts
@@ -61,26 +61,7 @@ export function download(opts: DownloadOptions): Promise<DownloadResult> {
targetPath: path.resolve(opts.targetPath),
sha256: opts.sha256.toLowerCase(),
};
- if (!opts.timeout?.totalMs) return getScheduler().enqueue(normalized);
- const controller = new AbortController();
- let timedOut = false;
- const abort = () => controller.abort();
- opts.signal?.addEventListener('abort', abort, { once: true });
- if (opts.signal?.aborted) abort();
- const timer = setTimeout(() => {
- timedOut = true;
- controller.abort();
- }, opts.timeout.totalMs);
- return getScheduler()
- .enqueue({ ...normalized, signal: controller.signal })
- .catch((error) => {
- if (timedOut) throw new DownloadError('TIMEOUT', 'Download total time limit exceeded');
- throw error;
- })
- .finally(() => {
- clearTimeout(timer);
- opts.signal?.removeEventListener('abort', abort);
- });
+ return getScheduler().enqueue(normalized);
}
/**
diff --git a/apps/desktop/src/main/downloader/scheduler.ts b/apps/desktop/src/main/downloader/scheduler.ts
index 5a3f29b663..fba52a5e38 100644
--- a/apps/desktop/src/main/downloader/scheduler.ts
+++ b/apps/desktop/src/main/downloader/scheduler.ts
@@ -156,6 +156,18 @@ export class Scheduler {
private async run(task: QueuedTask): Promise<void> {
const startedAt = Date.now();
const logger: Logger = task.opts.logger ?? defaultLogger;
+ // Queue time does not consume the active transfer/retry budget.
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ task.opts.signal?.addEventListener('abort', abort, { once: true });
+ if (task.opts.signal?.aborted) abort();
+ let timedOut = false;
+ const timer = task.opts.timeout?.totalMs
+ ? setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, task.opts.timeout.totalMs)
+ : undefined;
// Reserve the slot BEFORE asynchronous cache hashing, including cache hits.
this.active.set(task.key, { url: task.opts.url, targetPath: task.opts.targetPath, loaded: 0 });
@@ -169,7 +181,7 @@ export class Scheduler {
if (fs.existsSync(task.opts.targetPath)) {
const hash = await computeHash(task.opts.targetPath);
const size = fs.statSync(task.opts.targetPath).size;
- if (task.opts.signal?.aborted) throw new DownloadError('ABORTED', 'Download aborted');
+ if (controller.signal.aborted) throw new DownloadError('ABORTED', 'Download aborted');
if (
hash === task.opts.sha256 &&
size <= (task.opts.maxBytes ?? Infinity) &&
@@ -196,6 +208,7 @@ export class Scheduler {
const ctx: TransportContext = {
opts: {
...task.opts,
+ signal: controller.signal,
onProgress: (event) => {
const active = this.active.get(task.key);
if (active) active.loaded = event.loaded;
@@ -203,13 +216,13 @@ export class Scheduler {
},
},
logger,
- signal: task.opts.signal,
+ signal: controller.signal,
resumedFromBytes: 0,
};
const result = await withRetry(() => executeOnce(ctx), {
config: task.opts.retry,
- signal: task.opts.signal,
+ signal: controller.signal,
logger,
onRetry: task.opts.onRetry,
});
@@ -222,8 +235,14 @@ export class Scheduler {
resumedFromBytes: ctx.resumedFromBytes,
});
} catch (err) {
- task.reject(err as Error);
+ task.reject(
+ timedOut
+ ? new DownloadError('TIMEOUT', 'Download total time limit exceeded')
+ : (err as Error),
+ );
} finally {
+ clearTimeout(timer);
+ task.opts.signal?.removeEventListener('abort', abort);
this.active.delete(task.key);
this.tryStart();
}
diff --git a/apps/desktop/src/main/downloader/types.ts b/apps/desktop/src/main/downloader/types.ts
index 3d5bcbe078..f89886a284 100644
--- a/apps/desktop/src/main/downloader/types.ts
+++ b/apps/desktop/src/main/downloader/types.ts
@@ -127,7 +127,7 @@ export interface TimeoutConfig {
connectMs: number;
/** Default 30000 — max gap between data chunks before treating as dead. */
idleMs: number;
- /** Optional total budget, including queue and retry waits. */
+ /** Optional active budget, including retry waits but excluding queue time. */
totalMs?: number;
}
diff --git a/apps/desktop/src/main/git-context/githubSetup.ts b/apps/desktop/src/main/git-context/githubSetup.ts
index 545d673819..b4edfdd06f 100644
--- a/apps/desktop/src/main/git-context/githubSetup.ts
+++ b/apps/desktop/src/main/git-context/githubSetup.ts
@@ -23,6 +23,7 @@ interface SetupDeps {
export class GithubSetup {
private state: GithubSetupState = { phase: 'idle' };
private controller?: AbortController;
+ private operation?: Promise<void>;
constructor(private readonly deps: SetupDeps) {}
snapshot(): GithubSetupState {
return { ...this.state };
@@ -32,13 +33,14 @@ export class GithubSetup {
const controller = new AbortController();
this.controller = controller;
this.state = { phase: 'checking' };
- void this.run(controller).finally(() => {
+ this.operation = this.run(controller).finally(() => {
this.controller = undefined;
});
return this.snapshot();
}
- cancel(): GithubSetupState {
+ async cancel(): Promise<GithubSetupState> {
this.controller?.abort();
+ await this.operation;
return this.snapshot();
}
private async run(controller: AbortController): Promise<void> {
diff --git a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
index 2d738a0690..0adbe8c4a2 100644
--- a/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
+++ b/apps/desktop/src/renderer/__tests__/accountUsageSnapshot.test.ts
@@ -237,7 +237,10 @@ describe('mergeCodexAccountUsageSnapshot', () => {
new URL('../../preload/preload.ts', import.meta.url),
'utf8',
);
- const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');
+ const hookSource = readFileSync(
+ new URL('../hooks/useAccountUsage.ts', import.meta.url),
+ 'utf8',
+ );
expect(mainSource).toContain("USAGE_CODEX_ACCOUNT_CHANGED = 'usage:codex-account-changed'");
expect(mainSource).toContain('broadcastCodexAccountUsage(payload, providerId);');
@@ -245,7 +248,9 @@ describe('mergeCodexAccountUsageSnapshot', () => {
expect(mainSource).toContain('isCodexWindowlessFallback(incoming)');
expect(mainSource).toContain('broadcastCodexAccountUsage(null, providerId);');
expect(preloadSource).toContain("createIpcFanOut('usage:codex-account-changed')");
- expect(preloadSource).toContain("providerId === 'openai' ? fanOutMakerUsageCodexAccount(cb)");
+ expect(preloadSource).toMatch(
+ /providerId === 'openai'\s*\? fanOutMakerUsageCodexAccount\(cb\)/,
+ );
expect(hookSource).toContain('api.onCodexAccountChanged');
expect(hookSource).toContain('options: { clearOnNull?: boolean } = {}');
expect(hookSource).toContain('selectCodexSlot(quotaSource');
@@ -274,20 +279,23 @@ describe('splitCodexAccountUsagePayload', () => {
webSnapshot: { primary: { usedPercent: 0 }, source: 'openai-web' },
} as never);
expect(parts.appServer?.primary?.usedPercent).toBe(82);
- expect((parts.appServer as { webSnapshot?: unknown } | undefined)?.webSnapshot)
- .toBeUndefined();
+ expect((parts.appServer as { webSnapshot?: unknown } | undefined)?.webSnapshot).toBeUndefined();
expect(parts.web?.primary?.usedPercent).toBe(0);
});
it('routes bare snapshots by their source field (per-turn events vs WHAM)', () => {
- expect(splitCodexAccountUsagePayload({
- primary: { usedPercent: 40 },
- source: 'codex-app-server',
- }).appServer?.primary?.usedPercent).toBe(40);
- expect(splitCodexAccountUsagePayload({
- primary: { usedPercent: 5 },
- source: 'openai-web',
- }).web?.primary?.usedPercent).toBe(5);
+ expect(
+ splitCodexAccountUsagePayload({
+ primary: { usedPercent: 40 },
+ source: 'codex-app-server',
+ }).appServer?.primary?.usedPercent,
+ ).toBe(40);
+ expect(
+ splitCodexAccountUsagePayload({
+ primary: { usedPercent: 5 },
+ source: 'openai-web',
+ }).web?.primary?.usedPercent,
+ ).toBe(5);
});
it('treats combined payloads as authoritative: empty slots clear explicitly', () => {
@@ -336,7 +344,9 @@ describe('module subscription install (behavior)', () => {
},
};
try {
- const { resetModules } = await import('vitest').then((m) => ({ resetModules: m.vi.resetModules }));
+ const { resetModules } = await import('vitest').then((m) => ({
+ resetModules: m.vi.resetModules,
+ }));
resetModules();
const [{ useAccountUsage: freshUseAccountUsage }, { renderToString }, React] =
await Promise.all([
@@ -460,7 +470,10 @@ describe('bucket key safety and authoritative top-level slot', () => {
it('marks combined payloads authoritative so the top-level slot is replaced, not merged', () => {
// 跨桶 merge 会造出「B 的 limitId + A 的窗口」杂交体(windowless 兜底保留旧窗口),
// 冷启动会话回退顶层时显示错桶数据(review 反馈)。组合 payload 必须直接替换。
- const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');
+ const hookSource = readFileSync(
+ new URL('../hooks/useAccountUsage.ts', import.meta.url),
+ 'utf8',
+ );
expect(hookSource).toContain("const isAuthoritative = 'appServerBuckets' in parts;");
expect(hookSource).toContain('? parts.appServer');
});
@@ -508,8 +521,9 @@ describe('bucket selection safety (review follow-up)', () => {
expect(isCodexBucketStale(expiredSpark, NOW)).toBe(true);
expect(isCodexBucketStale(MAIN, NOW)).toBe(false);
// 促销结束后的过期 Spark 桶不再被同名模型选中
- expect(matchCodexBucketForModel({ codex_bengalfox: expiredSpark }, 'gpt-5.3-codex-spark', NOW))
- .toBeNull();
+ expect(
+ matchCodexBucketForModel({ codex_bengalfox: expiredSpark }, 'gpt-5.3-codex-spark', NOW),
+ ).toBeNull();
});
it('does not treat window-less or reset-less buckets as stale', () => {
@@ -541,14 +555,23 @@ describe('nextCodexBucketStaleAtMs', () => {
const resetsAtSec = (offsetMs: number) => Math.floor((NOW + offsetMs) / 1000);
it('returns the soonest upcoming stale moment (reset + 24h grace)', () => {
- const soon = { limitId: 'codex_bengalfox', primary: { usedPercent: 0, resetsAt: resetsAtSec(60_000) } };
- const later = { limitId: 'codex', primary: { usedPercent: 30, resetsAt: resetsAtSec(10 * 60_000) } };
+ const soon = {
+ limitId: 'codex_bengalfox',
+ primary: { usedPercent: 0, resetsAt: resetsAtSec(60_000) },
+ };
+ const later = {
+ limitId: 'codex',
+ primary: { usedPercent: 30, resetsAt: resetsAtSec(10 * 60_000) },
+ };
const staleAt = nextCodexBucketStaleAtMs({ a: soon, b: later }, NOW);
expect(staleAt).toBe(resetsAtSec(60_000) * 1000 + DAY_MS);
});
it('ignores already-stale buckets and reset-less windows', () => {
- const alreadyStale = { limitId: 'x', primary: { usedPercent: 0, resetsAt: resetsAtSec(-3 * DAY_MS) } };
+ const alreadyStale = {
+ limitId: 'x',
+ primary: { usedPercent: 0, resetsAt: resetsAtSec(-3 * DAY_MS) },
+ };
const resetless = { limitId: 'y', primary: { usedPercent: 10 } };
expect(nextCodexBucketStaleAtMs({ a: alreadyStale }, NOW)).toBeNull();
expect(nextCodexBucketStaleAtMs({ b: resetless }, NOW)).toBeNull();
@@ -570,7 +593,10 @@ describe('bucket table keeps a null prototype across incremental updates', () =>
it('never re-attaches Object.prototype when merging a turn event bucket', () => {
// sanitize 建立 null 原型后, 增量写入若用对象字面量 spread 会把原型换回来,
// 削弱防御(review 反馈)。这里用源码断言锁定实现选择。
- const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');
+ const hookSource = readFileSync(
+ new URL('../hooks/useAccountUsage.ts', import.meta.url),
+ 'utf8',
+ );
expect(hookSource).toContain('function emptyBucketTable(');
expect(hookSource).toContain('function withCodexBucket(');
// 增量分支不得再出现桶表字面量 spread
@@ -584,12 +610,17 @@ describe('renderer sparse update bucket routing', () => {
// main 侧已按 app-server 契约把缺 limitId 的稀疏更新并入最近观察到的桶;
// renderer 增量路径若仍按缺省桶归类, 模型专属窗口会被当通用桶暴露给其它
// 会话(review 反馈)。这里锁定实现选择。
- const hookSource = readFileSync(new URL('../hooks/useAccountUsage.ts', import.meta.url), 'utf8');
+ const hookSource = readFileSync(
+ new URL('../hooks/useAccountUsage.ts', import.meta.url),
+ 'utf8',
+ );
expect(hookSource).toContain('latestBucketKey: string | null;');
expect(hookSource).toContain('function resolveIncrementalBucketKey(');
expect(hookSource).toContain('return state.latestBucketKey ?? codexLimitBucketKey(incoming);');
// 增量分支必须走 resolveIncrementalBucketKey, 不能直接用 codexLimitBucketKey
expect(hookSource).toContain('resolveIncrementalBucketKey(parts.appServer, state),');
- expect(hookSource).not.toContain('codexLimitBucketKey(parts.appServer),\n parts.appServer,');
+ expect(hookSource).not.toContain(
+ 'codexLimitBucketKey(parts.appServer),\n parts.appServer,',
+ );
});
});
diff --git a/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx b/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx
index 0ded7b33b8..33d66f4bd6 100644
--- a/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx
@@ -23,6 +23,20 @@ afterEach(cleanup);
const key = 'ccAgent.gitContext.pr.setup';
describe('GitHub setup UI', () => {
+ it('recovers polling after a transient status failure without restarting authorization', async () => {
+ const status = vi
+ .fn()
+ .mockResolvedValueOnce({ phase: 'authorizing' })
+ .mockRejectedValueOnce(new Error('IPC unavailable'))
+ .mockResolvedValue({ phase: 'connected' });
+ const connected = vi.fn();
+ window.electronAPI = { gitContext: { githubSetupStatus: status } } as any;
+ render(<GithubSetupDialog onClose={() => {}} onConnected={connected} />);
+ await screen.findByText(`${key}.stages.preparing.title`);
+ await screen.findByText(`${key}.stages.unavailable.title`);
+ await screen.findByText(`${key}.done`, {}, { timeout: 2000 });
+ expect(connected).toHaveBeenCalledOnce();
+ });
it('ignores outside clicks during authorization but still allows explicit cancellation', async () => {
const close = vi.fn();
const cancel = vi.fn(async () => ({ phase: 'cancelled' }));
diff --git a/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx
index 32a970e61d..922fbe0533 100644
--- a/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx
@@ -49,18 +49,21 @@ export function GithubSetupDialog({
if (isRunning(next.phase)) tracking.current = true;
// A previous run's terminal state does not validate a new attempt.
if (tracking.current) setState(next);
- setFailed(false);
+ if (tracking.current && next.phase !== 'idle') setFailed(false);
if (isRunning(next.phase)) timer = setTimeout(() => void poll(), 750);
} catch {
- if (!stopped) setFailed(true);
+ if (!stopped) {
+ setFailed(true);
+ timer = setTimeout(() => void poll(), 750);
+ }
}
};
- if (!pending && !failed) void poll();
+ if (!pending) void poll();
return () => {
stopped = true;
clearTimeout(timer);
};
- }, [pending, failed]);
+ }, [pending]);
const start = async () => {
tracking.current = true;
@@ -170,7 +173,7 @@ export function GithubSetupDialog({
{copy('deviceCode')}
</div>
<div className="flex items-center justify-between gap-3">
- <code className="select-all whitespace-nowrap font-mono text-xl tracking-widest text-[var(--text-primary)]">
+ <code className="select-all whitespace-nowrap font-mono text-18 tracking-widest text-[var(--text-primary)]">
{state.userCode}
</code>
<button
diff --git a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
index 4694e54352..2fda74a318 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
@@ -69,7 +69,6 @@ export function IssueTrackerFeatureLayout() {
<div className="flex-1" />
<GithubConnectButton
visible={!loading && (!data?.githubEnhancement || data.githubEnhancementFailed)}
- onConnected={refresh}
/>
<button
type="button"
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx b/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx
index b96bda892c..a511921218 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx
@@ -24,14 +24,24 @@ it('rechecks after connection when an older issues request is still running', as
}),
)
.mockResolvedValue({ ...response, githubEnhancement: { source: 'gh-cli', login: 'test' } });
+ let connected!: () => void;
+ const unsubscribe = vi.fn();
window.electronAPI = {
+ gitContext: {
+ onGithubConnected: (listener: () => void) => {
+ connected = listener;
+ return unsubscribe;
+ },
+ },
maker: { listMyIssues: list, getMyIssuesSnapshot: async () => null },
} as any;
- const { result } = renderHook(() => useMyIssues());
+ const { result, unmount } = renderHook(() => useMyIssues());
await waitFor(() => expect(list).toHaveBeenCalledOnce());
- act(() => result.current.refresh());
+ act(() => connected());
await act(async () => finish(response));
await waitFor(() => expect(result.current.data?.githubEnhancement?.login).toBe('test'));
expect(list).toHaveBeenCalledTimes(2);
expect(list).toHaveBeenLastCalledWith({ force: true });
+ unmount();
+ expect(unsubscribe).toHaveBeenCalledOnce();
});
diff --git a/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts b/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
index b05bd0fdcc..b513851e8e 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
+++ b/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
@@ -1,7 +1,7 @@
/**
* useMyIssues —— /issues 列表的数据源。
*
- * 进页面拉一次,之后只由用户点刷新触发(**禁** setInterval 轮询;main 侧本身有
+ * 进页面拉一次,之后由用户刷新或 GitHub 凭据变更触发(**禁** setInterval 轮询;main 侧本身有
* 60s TTL 缓存,重复进页面不会真去打 GitHub)。刷新期间保留旧数据,拿到新数据再
* 原子替换,不出现空白帧。
*
@@ -138,6 +138,8 @@ export function useMyIssues(): UseMyIssuesState {
void load(true);
}, [load]);
+ useEffect(() => window.electronAPI.gitContext?.onGithubConnected?.(refresh), [refresh]);
+
const data = fresh ?? (snapshot ? snapshotAsResult(snapshot) : null);
return { data, hasFreshData: fresh !== null, loading, refreshing, error, refresh };
}