Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持用量恢复后继续任务 (#1162)
wang20d09b84294a7
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.tsindex 809ebad582..7422f310b6 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts@@ -221,6 +221,7 @@ describe('applyInputProjection 自愈进行中提示', () => {makerChatStore.__teardownGlobalListeners();delete (globalThis as { window?: unknown }).window;inputProjectionCb = null;+ vi.useRealTimers();vi.clearAllMocks();});@@ -265,6 +266,23 @@ describe('applyInputProjection 自愈进行中提示', () => {expect(cards).toHaveLength(1);});+ it('重复投影同一条相对时间限额错误时复用首次解析结果', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-24T10:00:00.000Z'));+ const error = 'Usage limit reached. Try again in 1h.';++ inputProjectionCb!(projection({ error }));+ const first = makerChatStore.getSnapshot(SID).usageLimitRecovery;+ expect(first?.resetAtMs).toBe(Date.parse('2026-01-24T11:00:00.000Z'));++ vi.setSystemTime(new Date('2026-01-24T10:15:00.000Z'));+ inputProjectionCb!(projection({ error }));+ const second = makerChatStore.getSnapshot(SID).usageLimitRecovery;++ expect(second).toBe(first);+ expect(second?.resetAtMs).toBe(Date.parse('2026-01-24T11:00:00.000Z'));+ });+it('接管结束后撤掉提示卡', () => {inputProjectionCb!(projection({ autoResumePending: PENDING_INFO }));expect(diff --git a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.tsindex d2181ffcd8..a3e55e0ad3 100644--- a/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts+++ b/apps/desktop/src/renderer/__tests__/schedulerTemplateEntry.test.ts@@ -6,9 +6,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ScheduleTemplate } from '@cindy/maker-scheduler';import { SchedulerPage } from '@/features/scheduler/SchedulerPage';+import {+ oneTimeCronAfterUsageReset,+ systemTimeZone,+ usageLimitScheduleNavigationState,+} from '@/features/scheduler/lib/usageLimitScheduleCreateIntent';const createSchedule = vi.fn();const localStorageData = new Map<string, string>();+const routerMocks = vi.hoisted(() => ({+ location: {+ pathname: '/cc-agent/scheduled',+ search: '',+ state: null as unknown,+ },+ navigate: vi.fn(),+}));const template: ScheduleTemplate = {id: 'review-template',@@ -40,8 +53,8 @@ vi.mock('react-i18next', () => ({}));vi.mock('react-router-dom', () => ({- useLocation: () => ({ search: '' }),- useNavigate: () => vi.fn(),+ useLocation: () => routerMocks.location,+ useNavigate: () => routerMocks.navigate,}));vi.mock('@radix-ui/react-dialog', async () => {@@ -111,6 +124,10 @@ vi.mock('@/features/scheduler/hooks/useScheduleCostSummaries', () => ({useScheduleCostSummaries: () => ({ summaries: new Map(), loaded: true }),}));+vi.mock('@/features/scheduler/hooks/useSessionReferences', () => ({+ useSessionReferences: () => new Map(),+}));+vi.mock('@/hooks/useFeishuBot', () => ({useFeishuBot: () => ({ status: 'disconnected' }),}));@@ -160,6 +177,9 @@ vi.mock('@/features/scheduler/components/ScheduleChips', async () => {beforeEach(() => {createSchedule.mockImplementation(async (input) => ({ id: 'created-schedule', ...input }));+ routerMocks.location.pathname = '/cc-agent/scheduled';+ routerMocks.location.search = '';+ routerMocks.location.state = null;localStorageData.clear();Object.defineProperty(window, 'localStorage', {configurable: true,@@ -226,4 +246,51 @@ describe('Scheduler template entry', () => {}),);});++ it('opens a usage-limit recovery Automation for confirmation without creating it', async () => {+ const resetAtMs = Date.parse('2027-01-24T10:30:00.000Z');+ routerMocks.location.state = usageLimitScheduleNavigationState({+ kind: 'usage-limit-recovery',+ requestId: 'request-1',+ sessionId: 'session-1',+ agentKind: 'codex',+ resetAtMs,+ });++ render(createElement(SchedulerPage));++ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());+ expect(+ screen.getByDisplayValue('scheduler.usageLimitRecovery.name'),+ ).toBeTruthy();+ expect(+ screen.getByDisplayValue('scheduler.usageLimitRecovery.prompt'),+ ).toBeTruthy();+ expect(screen.getByTestId('cron-expr').textContent).toBe(+ oneTimeCronAfterUsageReset(resetAtMs, systemTimeZone()),+ );+ expect(screen.getByTestId('agent-kind').textContent).toBe('codex');+ expect(createSchedule).not.toHaveBeenCalled();+ expect(routerMocks.navigate).toHaveBeenCalledWith('/cc-agent/scheduled', {+ replace: true,+ state: null,+ });+ });++ it('opens the same confirmation form with a blank schedule when reset time is unknown', async () => {+ routerMocks.location.state = usageLimitScheduleNavigationState({+ kind: 'usage-limit-recovery',+ requestId: 'request-unknown-time',+ sessionId: 'session-2',+ agentKind: 'claude-code',+ resetAtMs: null,+ });++ render(createElement(SchedulerPage));++ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());+ expect(screen.getByTestId('cron-expr').textContent).toBe('');+ expect(screen.getByTestId('agent-kind').textContent).toBe('claude-code');+ expect(createSchedule).not.toHaveBeenCalled();+ });});diff --git a/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.ts b/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.tsnew file mode 100644index 0000000000..82f8acab02--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/usageLimitRecovery.test.ts@@ -0,0 +1,113 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { extractUsageLimitRecoveryHint } from '@/lib/usageLimitRecovery';++const NOW = Date.parse('2026-01-24T10:00:00.000Z');++afterEach(() => {+ vi.restoreAllMocks();+});++describe('usage limit recovery detection', () => {+ it('uses Claude structured rate-limit data and a structured reset timestamp', () => {+ expect(+ extractUsageLimitRecoveryHint(+ {+ sdkError: 'rate_limit',+ message: 'Rate limit reached',+ resetAt: '2026-01-24T12:30:00.000Z',+ },+ NOW,+ ),+ ).toEqual({ resetAtMs: Date.parse('2026-01-24T12:30:00.000Z') });+ });++ it('recognizes Codex usage-limit signals and relative retry times', () => {+ expect(+ extractUsageLimitRecoveryHint(+ {+ codexErrorInfo: 'usageLimitExceeded',+ message: 'Usage limit reached. Try again in 1h 15m.',+ },+ NOW,+ ),+ ).toEqual({ resetAtMs: NOW + 75 * 60_000 });+ });++ it('parses the real Claude session-limit wording with a named timezone', () => {+ expect(+ extractUsageLimitRecoveryHint(+ {+ message: "You've hit your session limit · resets 9:10pm (Asia/Shanghai)",+ },+ NOW,+ ),+ ).toEqual({ resetAtMs: Date.parse('2026-01-24T13:10:00.000Z') });+ });++ it('normalizes Intl midnight hour 24 while parsing a time-of-day reset', () => {+ const originalFormatToParts = Intl.DateTimeFormat.prototype.formatToParts;+ vi.spyOn(Intl.DateTimeFormat.prototype, 'formatToParts').mockImplementation(function (+ this: Intl.DateTimeFormat,+ date,+ ) {+ return [+ ...originalFormatToParts+ .call(this, date)+ .map((part) =>+ part.type === 'hour' && part.value === '00' ? { ...part, value: '24' } : part,+ ),+ { type: 'weekday', value: 'not-a-number' },+ ];+ });++ expect(+ extractUsageLimitRecoveryHint(+ {+ sdkError: 'rate_limit',+ message: "You've hit your session limit · resets 12:00am (UTC)",+ },+ Date.parse('2026-01-24T23:00:00.000Z'),+ ),+ ).toEqual({ resetAtMs: Date.parse('2026-01-25T00:00:00.000Z') });+ });++ it('keeps weekly limits actionable without guessing an unsupported weekday reset time', () => {+ expect(+ extractUsageLimitRecoveryHint(+ {+ message: "You've hit your weekly limit · resets Mon 12:00am (Asia/Shanghai)",+ },+ NOW,+ ),+ ).toEqual({ resetAtMs: null });+ });++ it('keeps a restorable limit actionable when the reset time is unknown', () => {+ expect(+ extractUsageLimitRecoveryHint({ errorStatus: 429, message: 'Too many requests' }, NOW),+ ).toEqual({ resetAtMs: null });+ });++ it('excludes billing depletion and temporary upstream overload', () => {+ expect(+ extractUsageLimitRecoveryHint(+ { sdkError: 'billing_error', message: 'Credit balance too low' },+ NOW,+ ),+ ).toBeNull();+ expect(+ extractUsageLimitRecoveryHint(+ {+ errorStatus: 529,+ codexErrorInfo: 'serverOverloaded',+ message: 'Selected model is at capacity',+ },+ NOW,+ ),+ ).toBeNull();+ expect(+ extractUsageLimitRecoveryHint({ message: 'insufficient_quota: add billing credits' }, NOW),+ ).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsxindex 4680bdbad9..c6707f66cf 100644--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx@@ -13,7 +13,7 @@*/import { useEffect, useState } from 'react';-import { AlertCircle, Check, GitFork, Play, RotateCcw, RefreshCw, X } from 'lucide-react';+import { AlertCircle, Check, GitFork, Play, RotateCcw, RefreshCw, Timer, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';import { Spinner } from '@/components/ui/spinner';@@ -41,6 +41,8 @@ interface ErrorBannerProps {onCancel?: () => void;/** silent-stop 耗尽横幅「继续」:清横幅 + 发隐藏续跑指令(见 makerChatStore)。 */onSilentStopContinue?: () => void;+ /** 账号用量限制:打开预填好的一次性 Automation,由用户确认后创建。 */+ onContinueAfterUsageReset?: () => void;/** 当前 session 的 agent kind。codex 的 401 / Missing bearer 必须 hide Retry,* 否则 retry 撞同一个 in-memory auth retry-loop 产生重复失败 turn。 */agentKind?: 'cc' | 'codex';@@ -75,6 +77,7 @@ export function ErrorBanner({onRetry,onCancel,onSilentStopContinue,+ onContinueAfterUsageReset,agentKind,remoteHostId,deviceLinkDeviceId,@@ -450,6 +453,21 @@ export function ErrorBanner({{t('chat.errorBanner.silentStopContinue')}</button>)}+ {onContinueAfterUsageReset && (+ <button+ type="button"+ onClick={onContinueAfterUsageReset}+ className={cn(+ 'shrink-0 flex items-center gap-1 text-xs font-medium',+ 'text-[var(--error-fg)]',+ 'hover:opacity-70 transition-opacity',+ )}+ title={t('chat.errorBanner.continueAfterResetTitle')}+ >+ <Timer size={12} />+ {t('chat.errorBanner.continueAfterReset')}+ </button>+ )}{safeRetryText && (<buttontype="button"diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsxindex 45c0bbb1b5..8aaf9936c3 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx@@ -533,4 +533,32 @@ describe('ErrorBanner OpenAI connection recovery', () => {expect(mocks.triggerLogin).not.toHaveBeenCalled();expect(mocks.cancelLogin).not.toHaveBeenCalled();});++ it('exposes the explicit Continue After Reset action only when provided', () => {+ const onContinueAfterUsageReset = vi.fn();+ const { rerender } = render(+ <ErrorBanner+ error="Usage limit reached"+ retryText="retry this turn"+ onRetry={vi.fn()}+ onContinueAfterUsageReset={onContinueAfterUsageReset}+ />,+ );++ fireEvent.click(+ screen.getByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),+ );+ expect(onContinueAfterUsageReset).toHaveBeenCalledOnce();++ rerender(+ <ErrorBanner+ error="A normal failure"+ retryText="retry this turn"+ onRetry={vi.fn()}+ />,+ );+ expect(+ screen.queryByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),+ ).toBeNull();+ });});diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex 9615354eee..c6e8fcf452 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -174,6 +174,7 @@ import {shouldRevealOrcaWorkersBeforeFirstPaint,} from './lib/orcaPassiveReveal';import { didOpenOrcaWorkersTab, revealOrcaWorkersWithRetry } from './lib/orcaWorkersRevealRetry';+import { usageLimitScheduleNavigationState } from '@/features/scheduler/lib/usageLimitScheduleCreateIntent';import {closeOrcaWorkersTabAfterTeamEnd,ensureOrcaWorkersTab,@@ -1162,6 +1163,7 @@ export function CCAgentSessionView({insertSystemCard,updateSystemCardData,error,+ usageLimitRecovery,errorIsRecoverable,errorRetryText,credentialSwitchWait,@@ -2513,6 +2515,23 @@ export function CCAgentSessionView({continueAfterSilentStop();}, [continueAfterSilentStop]);+ const handleContinueAfterUsageReset = useCallback(() => {+ if (!sessionId || !usageLimitRecovery || remoteDeviceId) return;+ const requestId =+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'+ ? crypto.randomUUID()+ : `${sessionId}:${Date.now()}`;+ navigate('/cc-agent/scheduled', {+ state: usageLimitScheduleNavigationState({+ kind: 'usage-limit-recovery',+ requestId,+ sessionId,+ agentKind: session?.agentKind === 'codex' ? 'codex' : 'claude-code',+ resetAtMs: usageLimitRecovery.resetAtMs,+ }),+ });+ }, [navigate, remoteDeviceId, session?.agentKind, sessionId, usageLimitRecovery]);+// 点击 Cancel 关闭报错 banner 同样是处置(用户选择不管它了)。const handleDismissError = useCallback(() => {if (sessionId) ackErrorAlertHandled(sessionId);@@ -3097,6 +3116,11 @@ export function CCAgentSessionView({retryText={errorRetryText}onRetry={handleRetry}onSilentStopContinue={handleSilentStopContinue}+ onContinueAfterUsageReset={+ usageLimitRecovery && !remoteDeviceId+ ? handleContinueAfterUsageReset+ : undefined+ }onCancel={handleDismissError}agentKind={session?.agentKind}remoteHostId={session?.remoteHostId ?? undefined}diff --git a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsxindex 53da500703..5eebfeee07 100644--- a/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx+++ b/apps/desktop/src/renderer/features/scheduler/SchedulerPage.tsx@@ -26,7 +26,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Plus, Timer } from 'lucide-react';-import { useLocation } from 'react-router-dom';+import { useLocation, useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';@@ -59,6 +59,11 @@ import {projectAutomationConfigPath,scheduleToProjectConfig,} from './lib/projectAutomationConfig';+import type { ScheduleFormState } from './lib/scheduleFormLogic';+import {+ buildUsageLimitScheduleFormOverrides,+ readUsageLimitScheduleCreateIntent,+} from './lib/usageLimitScheduleCreateIntent';function scheduleToUserCreateInput(schedule: Schedule,@@ -130,6 +135,7 @@ export function SchedulerPage() {onDeleted: () => refresh(),});const location = useLocation();+ const navigate = useNavigate();// 跨 pane 共享的 runNow「派发窗口」busy 守卫:TaskListCell(行按钮) 与 RunHistoryPane// (detail 按钮)共用同一份,防止同一 schedule 在派发窗口内被双发。守卫只覆盖"点击 →@@ -143,6 +149,8 @@ export function SchedulerPage() {const [formOpen, setFormOpen] = useState(false);const [editing, setEditing] = useState<Schedule | null>(null);const [createInitialTemplate, setCreateInitialTemplate] = useState<ScheduleTemplate | null>(null);+ const [createInitialValues, setCreateInitialValues] =+ useState<Partial<ScheduleFormState> | null>(null);// 项目分组"+"按钮的预填 workingDir:用户级 schedule,仅省去选项目目录这一步,// 不强制写 schedules.json(要"提升为项目自动化"走右键菜单 promoteToProject)。const [createPrefillWorkingDir, setCreatePrefillWorkingDir] = useState<string | null>(null);@@ -156,6 +164,7 @@ export function SchedulerPage() {const pendingSelectIdRef = useRef<string | null>(null);const statusSyncedFocusIdRef = useRef<string | null>(null);const handledEditTokenRef = useRef<string | null>(null);+ const handledScheduleCreateRequestRef = useRef<string | null>(null);// 左侧任务列表 pane 拖拽 resize(与主侧边栏同套机制 → useHorizontalResize)// 默认 300,min 240(保证 cell 标题不太早被截),max 480(与主侧边栏对齐)@@ -203,10 +212,31 @@ export function SchedulerPage() {handledEditTokenRef.current = editToken;setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);+ setCreateInitialValues(null);setEditing(focused);setFormOpen(true);}, [editToken, focusId, schedules]);+ useEffect(() => {+ const intent = readUsageLimitScheduleCreateIntent(location.state);+ if (!intent || handledScheduleCreateRequestRef.current === intent.requestId) return;+ handledScheduleCreateRequestRef.current = intent.requestId;+ setCreatePrefillWorkingDir(null);+ setCreateInitialTemplate(null);+ setEditing(null);+ setCreateInitialValues(+ buildUsageLimitScheduleFormOverrides(intent, {+ name: t('scheduler.usageLimitRecovery.name'),+ prompt: t('scheduler.usageLimitRecovery.prompt'),+ }),+ );+ setFormOpen(true);+ // Consume the one-shot navigation intent so revisiting Automations does not+ // reopen the modal. Creation still happens only after the user submits.+ const path = `${location.pathname || '/cc-agent/scheduled'}${location.search}`;+ navigate(path, { replace: true, state: null });+ }, [location.pathname, location.search, location.state, navigate, t]);+// workingDir filter(URL ?workingDir=...)const scopedByDir = useMemo(() => {if (!filterWorkingDir) return schedules;@@ -268,6 +298,7 @@ export function SchedulerPage() {const handleCreate = useCallback(() => {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);+ setCreateInitialValues(null);setEditing(null);setFormOpen(true);}, []);@@ -275,6 +306,7 @@ export function SchedulerPage() {const handleCreateFromTemplate = useCallback((template: ScheduleTemplate) => {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(template);+ setCreateInitialValues(null);setEditing(null);setFormOpen(true);}, []);@@ -282,6 +314,7 @@ export function SchedulerPage() {const handleEdit = useCallback((s: Schedule) => {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);+ setCreateInitialValues(null);setEditing(s);setFormOpen(true);}, []);@@ -289,6 +322,7 @@ export function SchedulerPage() {const handleCreateProjectSchedule = useCallback((workingDir: string) => {setEditing(null);setCreateInitialTemplate(null);+ setCreateInitialValues(null);setCreatePrefillWorkingDir(workingDir);setFormOpen(true);}, []);@@ -603,10 +637,12 @@ export function SchedulerPage() {if (!open) {setCreatePrefillWorkingDir(null);setCreateInitialTemplate(null);+ setCreateInitialValues(null);}}}initial={editing}initialTemplate={createInitialTemplate}+ initialValues={createInitialValues}initialWorkingDir={createPrefillWorkingDir}editProjectSchedule={editing?.source === 'project'}onSubmit={handleSubmit}diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsxindex eab226b3fe..ffb95b54a1 100644--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleChips.tsx@@ -386,10 +386,13 @@ export function ScheduleChip({: INTERVAL_MENU_MODES): SCHEDULE_MENU_MODES;const intervalIsPreset = timingPresentation.kind !== 'intervalExact';+ const scheduleUnset = intervalMs === undefined && cronExpr.trim() === '';const scheduleSummary = intervalMs === undefined? summarizeConfig(normalizeScheduleConfig(config)): formatIntervalDuration(intervalMs, i18n.resolvedLanguage ?? i18n.language);- const chipLabel = t(`scheduler.chips.timingMode.${timingMode}Chip`, { schedule: scheduleSummary });+ const chipLabel = scheduleUnset+ ? t('scheduler.chips.chooseTime')+ : t(`scheduler.chips.timingMode.${timingMode}Chip`, { schedule: scheduleSummary });const update = (patch: Partial<CodexScheduleConfig>) => {const next = normalizeScheduleConfig({ ...config, ...patch });diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsxindex 6a92106fbb..48f2ffd0b5 100644--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx@@ -36,7 +36,7 @@ import {resolveScheduleGenerationProviderId,shouldFollowBoundSessionGenerationRoute,} from '../lib/scheduleFormLogic';-import type { RunMode } from '../hooks/useScheduleForm';+import type { RunMode, ScheduleFormState } from '../hooks/useScheduleForm';import { BoundSessionCard } from './BoundSessionCard';import { TemplateGallery } from './TemplateGallery';import { TemplateParamForm } from './TemplateParamForm';@@ -97,6 +97,8 @@ interface Props {initial: Schedule | null;/** 从外部推荐卡片进入新建弹窗时,直接把对应模板应用到表单。 */initialTemplate?: ScheduleTemplate | null;+ /** 外部快捷入口的新建表单覆写;只负责预填,仍须用户主动提交。 */+ initialValues?: Partial<ScheduleFormState> | null;onSubmit: (input: CreateScheduleInput | UpdateScheduleInput, isEdit: boolean) => Promise<void>;/** 项目分组里"+"按钮的便捷入口:仅预填 workingDir,等同于普通新建(用户级 schedule,* 不写 schedules.json,可继续选模板、改项目)。 */@@ -110,6 +112,7 @@ export function ScheduleFormDialog({onOpenChange,initial,initialTemplate = null,+ initialValues = null,onSubmit,initialWorkingDir = null,editProjectSchedule = false,@@ -197,7 +200,7 @@ export function ScheduleFormDialog({const initialId = initial?.id;useEffect(() => {if (!open) return;- reset(initial);+ reset(initial, initialValues ?? undefined);setMode('form');setSelectedTemplate(null);setParamValues({});@@ -215,7 +218,17 @@ export function ScheduleFormDialog({setField('workspaceKind', 'project');setField('workingDir', prefill);}- }, [open, initialId, reset, initial, isProjectAutomationMode, projectWorkingDir, initialWorkingDir, setField]);+ }, [+ open,+ initialId,+ reset,+ initial,+ initialValues,+ isProjectAutomationMode,+ projectWorkingDir,+ initialWorkingDir,+ setField,+ ]);/** 前置检查「AI 生成」:描述 → utility model 生成脚本落盘 → 命令回填输入框。 */const runHookGenerate = useCallback(async () => {diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.tsindex beb94b3343..ef0f6e55f6 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts@@ -265,7 +265,7 @@ export interface UseScheduleFormResult {selectBoundSession: (session: Session | null) => void;/** 应用模板里的 agent/model/provider/effort/fast 字段,并在跨 agent 时重建成目标 agent 的默认组合。 */applyTemplateAgentFields: (template: ScheduleTemplate) => void;- reset: (s?: Schedule | null) => void;+ reset: (s?: Schedule | null, overrides?: Partial<ScheduleFormState>) => void;/*** 把表单转成 CreateScheduleInput;* heartbeat 模式(targetSessionId 非空)只跳过 workingDir/useWorktree@@ -297,8 +297,8 @@ export function useScheduleForm(initial: Schedule | null = null): UseScheduleFor[],);- const reset = useCallback((s: Schedule | null = null) => {- const next = makeFormFromSchedule(s);+ const reset = useCallback((s: Schedule | null = null, overrides?: Partial<ScheduleFormState>) => {+ const next = { ...makeFormFromSchedule(s), ...overrides };lastBindingRef.current = captureBinding(next);setForm(next);}, []);diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/usageLimitScheduleCreateIntent.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/usageLimitScheduleCreateIntent.test.tsnew file mode 100644index 0000000000..884c0016f0--- /dev/null+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/usageLimitScheduleCreateIntent.test.ts@@ -0,0 +1,83 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ buildUsageLimitScheduleFormOverrides,+ oneTimeCronAfterUsageReset,+ readUsageLimitScheduleCreateIntent,+ usageLimitScheduleNavigationState,+ type UsageLimitScheduleCreateIntent,+} from '../usageLimitScheduleCreateIntent';++const intent: UsageLimitScheduleCreateIntent = {+ kind: 'usage-limit-recovery',+ requestId: 'request-1',+ sessionId: 'session-1',+ agentKind: 'codex',+ resetAtMs: Date.parse('2026-01-24T10:30:00.000Z'),+};++afterEach(() => {+ vi.restoreAllMocks();+});++describe('usage-limit Automation create intent', () => {+ it('formats reset plus one minute as a one-shot cron expression', () => {+ expect(+ oneTimeCronAfterUsageReset(+ Date.parse('2026-01-24T10:30:00.000Z'),+ 'UTC',+ Date.parse('2026-01-24T10:00:00.000Z'),+ ),+ ).toBe('31 10 24 1 *');+ });++ it('normalizes Intl midnight hour 24 before building the cron expression', () => {+ const originalFormatToParts = Intl.DateTimeFormat.prototype.formatToParts;+ vi.spyOn(Intl.DateTimeFormat.prototype, 'formatToParts').mockImplementation(function (+ this: Intl.DateTimeFormat,+ date,+ ) {+ return originalFormatToParts+ .call(this, date)+ .map((part) =>+ part.type === 'hour' && part.value === '00' ? { ...part, value: '24' } : part,+ );+ });++ expect(+ oneTimeCronAfterUsageReset(+ Date.parse('2026-01-24T23:59:00.000Z'),+ 'UTC',+ Date.parse('2026-01-24T23:00:00.000Z'),+ ),+ ).toBe('0 0 25 1 *');+ });++ it('leaves the schedule blank when no reset time can be identified', () => {+ expect(oneTimeCronAfterUsageReset(null, 'UTC')).toBe('');+ const form = buildUsageLimitScheduleFormOverrides(+ { ...intent, resetAtMs: null },+ { name: 'Continue later', prompt: 'Continue the task.' },+ );+ expect(form).toMatchObject({+ name: 'Continue later',+ prompt: 'Continue the task.',+ cronExpr: '',+ recurring: false,+ targetSessionId: 'session-1',+ agentKind: 'codex',+ });+ });++ it('round-trips a valid navigation intent and rejects malformed state', () => {+ expect(readUsageLimitScheduleCreateIntent(usageLimitScheduleNavigationState(intent))).toEqual(+ intent,+ );+ expect(+ readUsageLimitScheduleCreateIntent({+ scheduleCreateIntent: { ...intent, sessionId: '', resetAtMs: 'tomorrow' },+ }),+ ).toBeNull();+ expect(readUsageLimitScheduleCreateIntent(null)).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts b/apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.tsnew file mode 100644index 0000000000..14526e8e2d--- /dev/null+++ b/apps/desktop/src/renderer/features/scheduler/lib/usageLimitScheduleCreateIntent.ts@@ -0,0 +1,134 @@+import type { ScheduleFormState } from './scheduleFormLogic';++export interface UsageLimitScheduleCreateIntent {+ kind: 'usage-limit-recovery';+ requestId: string;+ sessionId: string;+ agentKind: 'claude-code' | 'codex';+ resetAtMs: number | null;+}++export interface UsageLimitScheduleLabels {+ name: string;+ prompt: string;+}++export function usageLimitScheduleNavigationState(intent: UsageLimitScheduleCreateIntent): {+ scheduleCreateIntent: UsageLimitScheduleCreateIntent;+} {+ return { scheduleCreateIntent: intent };+}++export function readUsageLimitScheduleCreateIntent(+ state: unknown,+): UsageLimitScheduleCreateIntent | null {+ if (!state || typeof state !== 'object') return null;+ const candidate = (state as { scheduleCreateIntent?: unknown }).scheduleCreateIntent;+ if (!candidate || typeof candidate !== 'object') return null;+ const value = candidate as Partial<UsageLimitScheduleCreateIntent>;+ if (+ value.kind !== 'usage-limit-recovery' ||+ typeof value.requestId !== 'string' ||+ !value.requestId ||+ typeof value.sessionId !== 'string' ||+ !value.sessionId ||+ (value.agentKind !== 'claude-code' && value.agentKind !== 'codex') ||+ (value.resetAtMs !== null &&+ (typeof value.resetAtMs !== 'number' || !Number.isFinite(value.resetAtMs)))+ ) {+ return null;+ }+ return value as UsageLimitScheduleCreateIntent;+}++export function systemTimeZone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';+ } catch {+ return 'UTC';+ }+}++function timePartsAt(+ timestamp: number,+ timeZone: string,+): { month: number; day: number; hour: number; minute: number } | null {+ try {+ const formatter = new Intl.DateTimeFormat('en-US', {+ timeZone,+ month: 'numeric',+ day: 'numeric',+ hour: 'numeric',+ minute: 'numeric',+ hourCycle: 'h23',+ });+ const parts: Partial<Record<'month' | 'day' | 'hour' | 'minute', number>> = {};+ for (const part of formatter.formatToParts(new Date(timestamp))) {+ if (+ part.type === 'month' ||+ part.type === 'day' ||+ part.type === 'hour' ||+ part.type === 'minute'+ ) {+ const value = Number(part.value);+ if (!Number.isFinite(value)) continue;+ // Keep parity with maker-scheduler's wallClock(): some Intl+ // implementations report midnight as 24 even with hourCycle=h23.+ parts[part.type] = part.type === 'hour' && value === 24 ? 0 : value;+ }+ }+ if (+ parts.month === undefined ||+ parts.day === undefined ||+ parts.hour === undefined ||+ parts.minute === undefined+ ) {+ return null;+ }+ return parts as { month: number; day: number; hour: number; minute: number };+ } catch {+ return null;+ }+}++/** Convert reset + one minute into the existing scheduler's one-shot cron shape. */+export function oneTimeCronAfterUsageReset(+ resetAtMs: number | null,+ timeZone: string,+ nowMs = Date.now(),+): string {+ if (resetAtMs === null || !Number.isFinite(resetAtMs)) return '';+ const runAtMs = resetAtMs + 60_000;+ if (runAtMs <= nowMs) return '';+ const parts = timePartsAt(runAtMs, timeZone);+ if (!parts) return '';+ return `${parts.minute} ${parts.hour} ${parts.day} ${parts.month} *`;+}++export function buildUsageLimitScheduleFormOverrides(+ intent: UsageLimitScheduleCreateIntent,+ labels: UsageLimitScheduleLabels,+ nowMs = Date.now(),+): Partial<ScheduleFormState> {+ const timezone = systemTimeZone();+ return {+ name: labels.name,+ prompt: labels.prompt,+ executionMode: 'agent',+ cronExpr: oneTimeCronAfterUsageReset(intent.resetAtMs, timezone, nowMs),+ intervalMs: undefined,+ timezone,+ recurring: false,+ manual: false,+ agentKind: intent.agentKind,+ model: '',+ providerId: '',+ effort: '',+ fastMode: false,+ workspaceKind: 'dialogue',+ workingDir: '',+ useWorktree: false,+ targetSessionId: intent.sessionId,+ persistentSession: false,+ };+}diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.tsindex 17b54b6ecd..b1aaf7f06a 100644--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts@@ -54,6 +54,7 @@ import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';import { createLogger } from '@/lib/logger';+import type { UsageLimitRecoveryHint } from '@/lib/usageLimitRecovery';const log = createLogger('UseCCAgentChat');@@ -169,6 +170,8 @@ interface UseCCAgentChatReturn {/** F-CMD: Patch a specific local-only system card in place */updateSystemCardData: (clientId: string, patch: Record<string, unknown>) => void;error: string | null;+ /** 可恢复的账号用量限制;resetAtMs 识别失败时为 null。 */+ usageLimitRecovery: UsageLimitRecoveryHint | null;/** 当前 terminal error 的稳定 reason key(如 'silent-stop-exhausted');ErrorBanner* 据此渲染专用 action。仅 error 非空时有意义。 */errorReason: string | null;@@ -815,6 +818,7 @@ export function useCCAgentChat(updateLastSystemCardData,updateSystemCardData,error: lightState.error ?? lightState.recoverableError,+ usageLimitRecovery: lightState.error ? (lightState.usageLimitRecovery ?? null) : null,// 终止型沿用原语义(reason 只在 error 非空时有意义)。非终止型此前恒给 null ——// 那时 store 侧非终止分支也恒清 reason, 两边一致; 现在过载重投会在非终止态带上// 稳定 reason key(ErrorBanner 靠它渲染本地化重试进度), 必须透出, 否则 UI 只能diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 5d8cd730b5..06ffc92660 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4955,6 +4955,8 @@"retryTitle": "Resend the last message","cancelTitle": "Dismiss error","retry": "Retry",+ "continueAfterReset": "Continue After Reset",+ "continueAfterResetTitle": "Create a one-time Automation to continue this task after usage resets","credentialSwitchBusy": "Another Codex task is still running, so the provider for this session can't be applied yet (the shared Codex process needs a restart). Retry after those tasks finish.","codexThreadStale": "Codex auth mode changed — this session can't continue. Start a new session to apply it.","budgetModelHint": "If this keeps failing, try switching to the standard GPT model.",@@ -6200,6 +6202,10 @@"promptHeading": "No Automations yet","promptDescription": "Create a cron Automation to let Claude Code or Codex run your prompt on a schedule."},+ "usageLimitRecovery": {+ "name": "Continue Task After Usage Resets",+ "prompt": "Continue the current task from where it stopped."+ },"template": {"useTemplate": "Getting Started","blank": "Blank",@@ -6510,6 +6516,7 @@},"chips": {"selectProject": "Select project",+ "chooseTime": "Choose time","recent": "Recent","browseFolder": "Choose a different folder","advanced": "Advanced",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 65bf1ff759..a2067b2f3a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4954,6 +4954,8 @@"retryTitle": "最後のメッセージを再送信","cancelTitle": "エラーを閉じる","retry": "再試行",+ "continueAfterReset": "リセット後に続行",+ "continueAfterResetTitle": "利用上限のリセット後にこのタスクを続行する一回限りの自動化を作成","credentialSwitchBusy": "他の Codex タスクが実行中のため、この会話で選択したプロバイダーへまだ切り替えられません(共有 Codex プロセスの再起動が必要です)。他のタスクの終了後に「再試行」を押してください。","codexThreadStale": "Codex の認証モードが切り替わりました。この会話は続行できません。新しい会話を開始してください。","budgetModelHint": "繰り返し失敗する場合は、通常版 GPT モデルに切り替えてお試しください。",@@ -6190,6 +6192,10 @@"promptHeading": "自動化がまだありません","promptDescription": "cron 自動化を作成して、Claude Code または Codex にプロンプトをスケジュール実行させましょう。"},+ "usageLimitRecovery": {+ "name": "利用上限リセット後にタスクを続行",+ "prompt": "中断したところから現在のタスクを続行してください。"+ },"template": {"useTemplate": "初心者ヘルプ","blank": "空白",@@ -6500,6 +6506,7 @@},"chips": {"selectProject": "プロジェクトを選択",+ "chooseTime": "時刻を選択","recent": "最近","browseFolder": "別のフォルダを選択","advanced": "詳細設定",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 13f41644d8..c671101650 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4954,6 +4954,8 @@"retryTitle": "마지막 메시지 다시 보내기","cancelTitle": "오류 알림 닫기","retry": "다시 시도",+ "continueAfterReset": "재설정 후 계속",+ "continueAfterResetTitle": "사용량 제한 재설정 후 현재 작업을 계속할 일회성 자동화 만들기","credentialSwitchBusy": "다른 Codex 작업이 실행 중이어서 이 대화에서 선택한 제공자로 아직 전환할 수 없습니다(공유 Codex 프로세스 재시작 필요). 다른 작업이 끝난 후 ‘재시도’를 눌러 주세요.","codexThreadStale": "Codex 인증 모드가 변경되었습니다. 이 대화는 계속할 수 없습니다. 새 대화를 시작하세요.","budgetModelHint": "계속 실패하면 일반 GPT 모델로 전환해 보세요.",@@ -6190,6 +6192,10 @@"promptHeading": "자동화가 아직 없습니다","promptDescription": "cron 자동화를 만들어 Claude Code 또는 Codex로 프롬프트를 일정에 따라 실행하세요."},+ "usageLimitRecovery": {+ "name": "사용량 제한 재설정 후 작업 계속",+ "prompt": "중단된 지점부터 현재 작업을 계속하세요."+ },"template": {"useTemplate": "초보자 도움말","blank": "빈 항목",@@ -6500,6 +6506,7 @@},"chips": {"selectProject": "프로젝트 선택",+ "chooseTime": "시간 선택","recent": "최근","browseFolder": "다른 폴더 선택","advanced": "고급",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ee56927b22..dd1738377c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4954,6 +4954,8 @@"retryTitle": "重新发送最后一条消息","cancelTitle": "关闭错误提示","retry": "重试",+ "continueAfterReset": "恢复后继续",+ "continueAfterResetTitle": "创建一次性自动化,在用量恢复后继续当前任务","credentialSwitchBusy": "其他 Codex 任务正在运行,暂时无法按本对话选择的模型来源切换(需要重启共享的 Codex 后台进程)。等其他任务结束后点「重试」即可。","codexThreadStale": "Codex 鉴权模式已切换,当前对话无法继续 —— 请新建对话后生效。","budgetModelHint": "如果反复失败,可以切换到普通版 GPT 再试试。",@@ -6190,6 +6192,10 @@"promptHeading": "暂无自动化任务","promptDescription": "创建一个 cron 自动化任务,让 Claude Code 或 Codex 按计划执行你的 Prompt。"},+ "usageLimitRecovery": {+ "name": "用量恢复后继续任务",+ "prompt": "从中断的位置继续完成当前任务。"+ },"template": {"useTemplate": "新手帮助","blank": "空白",@@ -6500,6 +6506,7 @@},"chips": {"selectProject": "选择项目",+ "chooseTime": "选择时间","recent": "最近","browseFolder": "选择其他文件夹","advanced": "高级",diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 91a3b34db9..9c7fc2d715 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -121,6 +121,10 @@ import { i18n } from '@/i18n';import { toast } from '@/lib/toast';import { openUrlInSidebarBrowser } from '@/features/right-sidebar/lib/openInSidebarBrowser';import { isSidebarWindow } from '@/lib/sidebarWindow';+import {+ extractUsageLimitRecoveryHint,+ type UsageLimitRecoveryHint,+} from '@/lib/usageLimitRecovery';import {materializeAnnotatedAttachmentsForSend,@@ -770,6 +774,8 @@ export interface SessionChatState {isStreaming: boolean;agentStatus: AgentStatus;error: string | null;+ /** 当前 terminal error 是否为可恢复的账号用量限制,以及可识别的重置时刻。 */+ usageLimitRecovery?: UsageLimitRecoveryHint | null;/*** 当前 terminal error 的稳定 reason key(maker-core/main 下发,如* 'silent-stop-exhausted')。ErrorBanner 据此渲染专用 action(「继续」按钮);@@ -999,6 +1005,7 @@ export type SessionChatLightState = Pick<| 'agentStatus'| 'isStreaming'| 'error'+ | 'usageLimitRecovery'| 'errorReason'| 'recoverableError'| 'errorRetryText'@@ -1048,6 +1055,7 @@ function createInitialState(): SessionChatState {startedAt: null,},error: null,+ usageLimitRecovery: null,errorReason: null,recoverableError: null,activeTurnRetryText: null,@@ -1111,6 +1119,7 @@ export const EMPTY_SESSION_STATE: SessionChatState = Object.freeze({startedAt: null,},error: null,+ usageLimitRecovery: null,errorReason: null,recoverableError: null,activeTurnRetryText: null,@@ -1419,7 +1428,9 @@ function leaveView(sessionId: string): void {setState(sessionId, (s) => ({...s,...(s.historyLoaded ? { historyLoaded: false } : {}),- ...(s.error ? { error: null, errorRetryText: null } : {}),+ ...(s.error+ ? { error: null, usageLimitRecovery: null, errorRetryText: null }+ : {}),}));}_trimMessagesIfNeeded(sessionId);@@ -1600,6 +1611,13 @@ function applyInputProjection(projection: AgentInputProjection): void {// 折叠:同一次中断事件里,ephemeral 进行中行与它前面那些已落库的重连行只显示最新// 一条(否则第 2 次重连时会看到「未成功」+「重新连接中 2/5」两行并存)。const messages = collapseConsecutiveAutoResumeRows(withPendingCard);+ // main 可能重复投影同一条 error。相对时间(如 "Try again in 1h")只能在错误首次出现+ // 时锚定;每次都按新的 Date.now() 重算会让恢复时间持续后移,也会制造无意义的新对象。+ const usageLimitRecovery = !projection.error+ ? null+ : projection.error === s.error+ ? s.usageLimitRecovery+ : extractUsageLimitRecoveryHint({ message: projection.error });return {...s,messages,@@ -1611,6 +1629,7 @@ function applyInputProjection(projection: AgentInputProjection): void {queueEditLocks: projection.queueEditLocks,queueAbortPending: projection.queueAbortPending,error: projection.error,+ usageLimitRecovery,// projection 覆盖 error(dispatch 失败等,无 reason 语义)→ reason 一并清,// 避免 silent-stop 的「继续」按钮挂在一条不相干的错误上。errorReason: null,@@ -2613,6 +2632,7 @@ export function handleStreamEvent(return {...state,error: null,+ usageLimitRecovery: null,// 非终止 error 此前恒清 reason(那时没有任何非终止 error 带 reason)。过载// 重投是第一个需要它的: renderer 靠 reason 判定"是否过载"来渲染本地化的// 重试进度, 而重投恰恰只在**非终止**态发生 —— 清掉就等于 UI 侧只能回退@@ -2649,6 +2669,9 @@ export function handleStreamEvent(return {...finalized,error: isPlannedUpgradeClose ? null : errMsg,+ usageLimitRecovery: isPlannedUpgradeClose+ ? null+ : extractUsageLimitRecoveryHint(event.data),errorReason: isPlannedUpgradeClose ? null : (reason ?? null),recoverableError: null,errorRetryText: derivedRetryText ?? preservedRetryText,@@ -3194,6 +3217,7 @@ function handleStatusUpdate(// 的后台 turn 误报成「执行失败」通知(bot review P2)。skipTurnReset 的// side-channel running 信号已在上方早退,不会误清。error: isTurnStart ? null : state.error,+ usageLimitRecovery: isTurnStart ? null : state.usageLimitRecovery,errorReason: isTurnStart ? null : state.errorReason,errorRetryText: isTurnStart || (isTurnComplete && !state.error) ? null : state.errorRetryText,recoverableError: isTurnComplete ? null : state.recoverableError,@@ -4341,7 +4365,9 @@ function initGlobalListeners(): void {setState(ep.sessionId, (s) => ({...s,...(s.historyLoaded ? { historyLoaded: false } : {}),- ...(s.error ? { error: null, errorRetryText: null } : {}),+ ...(s.error+ ? { error: null, usageLimitRecovery: null, errorRetryText: null }+ : {}),}));}}@@ -4432,7 +4458,9 @@ function initGlobalListeners(): void {setState(p.sessionId, (s) => ({...s,...(s.historyLoaded ? { historyLoaded: false } : {}),- ...(s.error ? { error: null, errorRetryText: null } : {}),+ ...(s.error+ ? { error: null, usageLimitRecovery: null, errorRetryText: null }+ : {}),}));},'local-db-session-error-persisted',@@ -4683,6 +4711,7 @@ function selectLightState(state: SessionChatState): SessionChatLightState {agentStatus: state.agentStatus,isStreaming: state.isStreaming,error: state.error,+ usageLimitRecovery: state.usageLimitRecovery,errorReason: state.errorReason,recoverableError: state.recoverableError,errorRetryText: state.errorRetryText,@@ -4720,6 +4749,7 @@ function lightStateEquals(a: SessionChatLightState, b: SessionChatLightState): ba.agentStatus === b.agentStatus &&a.isStreaming === b.isStreaming &&a.error === b.error &&+ a.usageLimitRecovery === b.usageLimitRecovery &&a.errorReason === b.errorReason &&a.recoverableError === b.recoverableError &&a.errorRetryText === b.errorRetryText &&@@ -5050,6 +5080,7 @@ function syncActiveTurnsFromMain(): void {...(agentKindPatch ? { agentKind: agentKindPatch } : {}),isStreaming: true,error: null,+ usageLimitRecovery: null,errorReason: null,recoverableError: null,activeTurnRetryText: null,@@ -7284,6 +7315,7 @@ async function sendMessageCore(? s.messages.filter((m) => !(m.clientId === queued.clientId && m.isPendingPersist)): s.messages,error: message,+ usageLimitRecovery: null,errorReason: null,recoverableError: null,errorRetryText: null,@@ -7325,6 +7357,7 @@ function compactSession(setState(sessionId, (s) => ({...s,error: message,+ usageLimitRecovery: null,recoverableError: null,errorRetryText: null,}));@@ -7467,6 +7500,7 @@ function steerMessageCore(setState(sessionId, (s) => ({...s,error: message,+ usageLimitRecovery: null,recoverableError: null,errorRetryText: null,}));@@ -7591,6 +7625,7 @@ function steerQueuedMessage(sessionId: string, clientId: string): Promise<booleasetState(sessionId, (s) => ({...s,error: message,+ usageLimitRecovery: null,recoverableError: null,errorRetryText: null,}));@@ -7724,8 +7759,22 @@ function clearError(sessionId: string): void {.then(applyInputProjection).catch((err) => log.warn('clearError failed:', err));setState(sessionId, (s) => {- if (s.error == null && s.recoverableError == null && s.errorRetryText == null) return s;- return { ...s, error: null, errorReason: null, recoverableError: null, errorRetryText: null };+ if (+ s.error == null &&+ s.usageLimitRecovery == null &&+ s.recoverableError == null &&+ s.errorRetryText == null+ ) {+ return s;+ }+ return {+ ...s,+ error: null,+ usageLimitRecovery: null,+ errorReason: null,+ recoverableError: null,+ errorRetryText: null,+ };});}@@ -7752,7 +7801,13 @@ function continueAfterSilentStop(sessionId: string): void {if (!sessionId) return;void sendUiTrigger(sessionId, CONTINUE_AFTER_ERROR_PROMPT).then(() => {- setState(sessionId, (s) => ({ ...s, error: null, errorReason: null, errorRetryText: null }));+ setState(sessionId, (s) => ({+ ...s,+ error: null,+ usageLimitRecovery: null,+ errorReason: null,+ errorRetryText: null,+ }));},(err) => {log.warn('continueAfterSilentStop failed:', err);@@ -7892,6 +7947,7 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Pro// 卡住(#676 review)。isLoadingMore: false,error: null,+ usageLimitRecovery: null,errorReason: null,recoverableError: null,activeTurnRetryText: null,diff --git a/apps/desktop/src/renderer/lib/usageLimitRecovery.ts b/apps/desktop/src/renderer/lib/usageLimitRecovery.tsnew file mode 100644index 0000000000..6c8b73d260--- /dev/null+++ b/apps/desktop/src/renderer/lib/usageLimitRecovery.ts@@ -0,0 +1,285 @@+/**+ * Renderer-side usage-limit detection.+ *+ * The live maker event is the most precise signal available to the chat UI:+ * Claude normally supplies sdkError='rate_limit', while Codex may only supply+ * an HTTP status / codexErrorInfo / human-readable message. Keep this+ * deliberately conservative because this result exposes an Automation action.+ */++export interface UsageLimitRecoveryHint {+ resetAtMs: number | null;+}++type UnknownRecord = Record<string, unknown>;++const ABSOLUTE_RESET_KEYS = new Set([+ 'resetat',+ 'resetatms',+ 'reset_at',+ 'resetsat',+ 'resets_at',+ 'usageresetat',+ 'usageresetatms',+ 'usage_reset_at',+]);++const RETRY_AFTER_MS_KEYS = new Set(['retryafterms', 'retry_after_ms']);+const RETRY_AFTER_SECONDS_KEYS = new Set([+ 'retryafter',+ 'retryafterseconds',+ 'retry_after',+ 'retry_after_seconds',+]);++function asRecord(value: unknown): UnknownRecord | null {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+ ? (value as UnknownRecord)+ : null;+}++function collectRecords(root: UnknownRecord): UnknownRecord[] {+ const records: UnknownRecord[] = [];+ const queue: Array<{ record: UnknownRecord; depth: number }> = [{ record: root, depth: 0 }];+ const seen = new Set<UnknownRecord>();+ while (queue.length > 0) {+ const current = queue.shift();+ if (!current || seen.has(current.record)) continue;+ seen.add(current.record);+ records.push(current.record);+ if (current.depth >= 2) continue;+ for (const value of Object.values(current.record)) {+ const nested = asRecord(value);+ if (nested) queue.push({ record: nested, depth: current.depth + 1 });+ }+ }+ return records;+}++function collectText(records: readonly UnknownRecord[]): string {+ const parts: string[] = [];+ for (const record of records) {+ for (const value of Object.values(record)) {+ if (typeof value === 'string') parts.push(value);+ }+ }+ return parts.join('\n');+}++function finiteNumber(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (typeof value === 'string' && value.trim()) {+ const parsed = Number(value.trim());+ if (Number.isFinite(parsed)) return parsed;+ }+ return null;+}++function normalizeAbsoluteTimestamp(value: unknown, nowMs: number): number | null {+ const numeric = finiteNumber(value);+ if (numeric !== null) {+ // Epoch seconds are currently around 1e9; epoch milliseconds around 1e12.+ const timestamp = numeric >= 100_000_000_000 ? numeric : numeric * 1000;+ return timestamp > nowMs ? timestamp : null;+ }+ if (typeof value !== 'string') return null;+ const parsed = Date.parse(value);+ return Number.isFinite(parsed) && parsed > nowMs ? parsed : null;+}++function parseStructuredResetAt(records: readonly UnknownRecord[], nowMs: number): number | null {+ for (const record of records) {+ for (const [rawKey, value] of Object.entries(record)) {+ const key = rawKey.toLowerCase();+ if (ABSOLUTE_RESET_KEYS.has(key)) {+ const parsed = normalizeAbsoluteTimestamp(value, nowMs);+ if (parsed !== null) return parsed;+ }+ if (RETRY_AFTER_MS_KEYS.has(key)) {+ const delay = finiteNumber(value);+ if (delay !== null && delay > 0) return nowMs + delay;+ }+ if (RETRY_AFTER_SECONDS_KEYS.has(key)) {+ const delay = finiteNumber(value);+ if (delay !== null && delay > 0) return nowMs + delay * 1000;+ }+ }+ }+ return null;+}++function parseRelativeResetAt(text: string, nowMs: number): number | null {+ const relative = text.match(+ /(?:resets?|retry(?:\s+after)?|try\s+again)\s+(?:in\s+)?(?:(\d+)\s*d(?:ays?)?\s*)?(?:(\d+)\s*h(?:ours?)?\s*)?(?:(\d+)\s*m(?:in(?:ute)?s?)?\s*)?(?:(\d+)\s*s(?:ec(?:ond)?s?)?)?/i,+ );+ if (!relative) return null;+ const days = Number(relative[1] ?? 0);+ const hours = Number(relative[2] ?? 0);+ const minutes = Number(relative[3] ?? 0);+ const seconds = Number(relative[4] ?? 0);+ const delayMs = (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;+ return delayMs > 0 ? nowMs + delayMs : null;+}++function partsInTimeZone(timestamp: number, timeZone: string): Record<string, number> | null {+ try {+ const formatter = new Intl.DateTimeFormat('en-US', {+ timeZone,+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ hour: 'numeric',+ minute: 'numeric',+ second: 'numeric',+ hourCycle: 'h23',+ });+ const parts: Record<string, number> = {};+ for (const part of formatter.formatToParts(new Date(timestamp))) {+ if (+ part.type !== 'year' &&+ part.type !== 'month' &&+ part.type !== 'day' &&+ part.type !== 'hour' &&+ part.type !== 'minute' &&+ part.type !== 'second'+ ) {+ continue;+ }+ const value = Number(part.value);+ if (!Number.isFinite(value)) continue;+ // Keep parity with maker-scheduler's wallClock(): some Intl+ // implementations report midnight as 24 even with hourCycle=h23.+ parts[part.type] = part.type === 'hour' && value === 24 ? 0 : value;+ }+ return parts;+ } catch {+ return null;+ }+}++function zonedDateTimeToMs(+ input: { year: number; month: number; day: number; hour: number; minute: number },+ timeZone: string,+): number | null {+ const targetAsUtc = Date.UTC(input.year, input.month - 1, input.day, input.hour, input.minute, 0);+ let guess = targetAsUtc;+ for (let i = 0; i < 3; i += 1) {+ const actual = partsInTimeZone(guess, timeZone);+ if (!actual) return null;+ const actualAsUtc = Date.UTC(+ actual.year,+ actual.month - 1,+ actual.day,+ actual.hour,+ actual.minute,+ actual.second,+ );+ guess += targetAsUtc - actualAsUtc;+ }+ const verified = partsInTimeZone(guess, timeZone);+ if (+ !verified ||+ verified.year !== input.year ||+ verified.month !== input.month ||+ verified.day !== input.day ||+ verified.hour !== input.hour ||+ verified.minute !== input.minute+ ) {+ return null;+ }+ return guess;+}++function parseTimeOfDayResetAt(text: string, nowMs: number): number | null {+ const match = text.match(+ /\bresets?(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^)]+)\))?/i,+ );+ if (!match) return null;+ let hour = Number(match[1]);+ const minute = Number(match[2] ?? 0);+ if (hour < 1 || hour > 12 || minute > 59) return null;+ const meridiem = match[3].toLowerCase();+ if (hour === 12) hour = 0;+ if (meridiem === 'pm') hour += 12;+ const fallbackTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';+ const timeZone = match[4]?.trim() || fallbackTimeZone;+ const current = partsInTimeZone(nowMs, timeZone);+ if (!current) return null;++ for (let dayOffset = 0; dayOffset <= 1; dayOffset += 1) {+ const date = new Date(Date.UTC(current.year, current.month - 1, current.day + dayOffset));+ const candidate = zonedDateTimeToMs(+ {+ year: date.getUTCFullYear(),+ month: date.getUTCMonth() + 1,+ day: date.getUTCDate(),+ hour,+ minute,+ },+ timeZone,+ );+ if (candidate !== null && candidate > nowMs) return candidate;+ }+ return null;+}++function parseTextResetAt(text: string, nowMs: number): number | null {+ const isoMatches = text.match(+ /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})\b/g,+ );+ for (const value of isoMatches ?? []) {+ const parsed = Date.parse(value);+ if (Number.isFinite(parsed) && parsed > nowMs) return parsed;+ }++ const labeledEpoch = text.match(/(?:reset(?:s|_at|At)?|retry[_\s-]*after)\D{0,12}(\d{10,13})\b/i);+ if (labeledEpoch) {+ const parsed = normalizeAbsoluteTimestamp(labeledEpoch[1], nowMs);+ if (parsed !== null) return parsed;+ }++ return parseRelativeResetAt(text, nowMs) ?? parseTimeOfDayResetAt(text, nowMs);+}++/**+ * Returns a hint only for a restorable account usage/rate limit. Billing+ * depletion and temporary upstream overload are intentionally excluded.+ */+export function extractUsageLimitRecoveryHint(+ data: unknown,+ nowMs = Date.now(),+): UsageLimitRecoveryHint | null {+ const root = asRecord(data);+ if (!root) return null;+ const records = collectRecords(root);+ const text = collectText(records);++ const sdkError = typeof root.sdkError === 'string' ? root.sdkError : '';+ const codexErrorInfo = typeof root.codexErrorInfo === 'string' ? root.codexErrorInfo : '';+ const status = finiteNumber(root.errorStatus ?? root.status);++ if (+ sdkError === 'billing_error' ||+ codexErrorInfo === 'serverOverloaded' ||+ status === 529 ||+ /\b(?:insufficient_quota|billing_error|credit(?:s| balance)?\s+(?:depleted|exhausted|too low)|at capacity|overloaded_error)\b/i.test(+ text,+ )+ ) {+ return null;+ }++ const isUsageLimit =+ sdkError === 'rate_limit' ||+ codexErrorInfo === 'usageLimitExceeded' ||+ root.usageLimit === true ||+ status === 429 ||+ /\b(?:rate.?limit|usage.?limit|too\s+many\s+requests|quota\s+(?:exceeded|exhausted)|you(?:'|’)ve\s+hit\s+your\s+(?:(?:session|weekly)\s+)?limit)\b/i.test(+ text,+ );+ if (!isUsageLimit) return null;++ return {+ resetAtMs: parseStructuredResetAt(records, nowMs) ?? parseTextResetAt(text, nowMs),+ };+}