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): 启动时提供一键继续上次中断的任务

Dash991c0b89fbdc
diff --git a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
index 208e5a8be6..0fcb90a56a 100644
--- a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
@@ -511,6 +511,37 @@ describe('sessionActiveTurn', () => {
]);
});
+ it('listInterruptedResumeCandidateRows reads the interrupted turn time and last tool use', async () => {
+ const { listInterruptedResumeCandidateRows } = await import('../interruptedResumeCandidates.js');
+ const client = createTestDbClient();
+ const startedAt = Date.now() - 10_000;
+ await seedSession(client, 's-tools', { startedAt });
+ await seedSession(client, 's-silent', { startedAt });
+ const insert = (id: string, sid: string, role: string, content: unknown, createdAt: number, rewindAt?: number) =>
+ client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at, rewind_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ [id, id, sid, role, JSON.stringify(content), createdAt, rewindAt ?? null],
+ );
+ // 上一轮的工具调用不属于被中断的这一轮。
+ await insert('m-old', 's-tools', 'tool_use', { toolName: 'Read', input: { file_path: '/a' } }, startedAt - 1);
+ await insert('m-1', 's-tools', 'tool_use', { toolName: 'Read', input: { file_path: '/b' } }, startedAt + 100);
+ await insert('m-2', 's-tools', 'tool_use', { toolName: 'Bash', input: { command: 'pnpm test' } }, startedAt + 200);
+ await insert('m-3', 's-tools', 'assistant', 'running tests', startedAt + 300);
+ // 被 rewind 的行既不算中断时间,也不算最后一次工具调用。
+ await insert('m-4', 's-tools', 'tool_use', { toolName: 'Write', input: {} }, startedAt + 400, startedAt + 500);
+ await insert('m-5', 's-silent', 'tool_use', { toolName: 'Read', input: {} }, startedAt - 1);
+
+ const rows = await listInterruptedResumeCandidateRows();
+ expect(rows.sort((a, b) => a.sessionId.localeCompare(b.sessionId))).toEqual([
+ { sessionId: 's-silent', interruptedAt: startedAt, lastToolUse: null },
+ {
+ sessionId: 's-tools',
+ interruptedAt: startedAt + 300,
+ lastToolUse: { toolName: 'Bash', input: { command: 'pnpm test' } },
+ },
+ ]);
+ });
+
it('excludes plugin background tasks from both red-dot legs', async () => {
const { listInterruptedPendingSessionIds, listErrorTailPendingSessionIds } = await import('../sessionActiveTurn.js');
const client = createTestDbClient();
diff --git a/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts b/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts
new file mode 100644
index 0000000000..7bfec5c31c
--- /dev/null
+++ b/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts
@@ -0,0 +1,79 @@
+/**
+ * 启动「继续上次中断的任务」弹窗的数据源。
+ *
+ * 中断判定完全复用 listInterruptedPendingRows(startedAt > endedAt 且早于本进程启动),
+ * 这里只为每个中断会话补两项展示素材:
+ * - interruptedAt:中断那一轮最后一条落库消息的时间(崩溃时刻无从得知,最后一次
+ * 落库是最接近的可观察值);该轮没有任何落库消息时回退到 turn 开始时间;
+ * - lastToolUse:中断那一轮最后一次工具调用的原始 toolName / input,由 IPC 层格式化成
+ * 与灵动岛同源的「正在做什么」文案。没有工具调用时为 null,界面只显示项目与时间。
+ *
+ * 必须走 `.select().from()` builder:生产 worker 模式的 drizzleProxy 只路由带 toSQL 的
+ * builder(同 sessionActiveTurn.ts 的说明)。
+ */
+
+import { and, desc, eq, gte, isNull, sql } from 'drizzle-orm';
+
+import { getDbClient } from './client/current';
+import { listInterruptedPendingRows } from './sessionActiveTurn';
+import { messages } from './schema';
+
+export interface InterruptedTurnToolUse {
+ toolName: string;
+ input: unknown;
+}
+
+export interface InterruptedResumeCandidateRow {
+ sessionId: string;
+ interruptedAt: number;
+ lastToolUse: InterruptedTurnToolUse | null;
+}
+
+/** 同毫秒批量落库时以 rowid 保持写入顺序(与 messages:list 口径一致)。 */
+const messageRowid = sql<number>`rowid`;
+
+function parseToolUse(raw: string | null): InterruptedTurnToolUse | null {
+ if (!raw) return null;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== 'object') return null;
+ const { toolName, input } = parsed as { toolName?: unknown; input?: unknown };
+ return typeof toolName === 'string' && toolName ? { toolName, input } : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function listInterruptedResumeCandidateRows(): Promise<
+ InterruptedResumeCandidateRow[]
+> {
+ const pending = await listInterruptedPendingRows();
+ if (pending.length === 0) return [];
+ const db = getDbClient().drizzle;
+ return Promise.all(
+ pending.map(async ({ sessionId, startedAt }) => {
+ const inTurn = and(
+ eq(messages.sessionId, sessionId),
+ isNull(messages.rewindAt),
+ gte(messages.createdAt, startedAt),
+ );
+ const [lastMessage] = await db
+ .select({ createdAt: messages.createdAt })
+ .from(messages)
+ .where(inTurn)
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
+ const [lastTool] = await db
+ .select({ content: messages.content })
+ .from(messages)
+ .where(and(inTurn, eq(messages.role, 'tool_use')))
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
+ return {
+ sessionId,
+ interruptedAt: lastMessage?.createdAt ?? startedAt,
+ lastToolUse: parseToolUse(lastTool?.content ?? null),
+ };
+ }),
+ );
+}
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 4d9d30c761..a8e5bdbcfb 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -92,6 +92,9 @@ import {
listInterruptedPendingSessionIds,
setOnSessionTurnEndedPersisted,
} from '../sessionActiveTurn';
+import { listInterruptedResumeCandidateRows } from '../interruptedResumeCandidates';
+import { formatIslandToolDetail } from '../../agent-island/toolDetail';
+import { createLocalizedToolRowWording } from '../../agent-island/toolWording';
import { dismissErrorMessage, rebroadcastAgentSwitchBoundary } from './messages';
import { SESSION_READ_BATCH_LIMIT } from '../../../shared/sessionRead';
import { isDeviceLinkInvoke } from '../../device-link/invoke-context.js';
@@ -1521,6 +1524,23 @@ export function registerSessionIpc(
return listInterruptedPendingSessionIds();
});
+ // 启动「继续上次中断的任务」弹窗:同一批中断会话,附中断时间与中断那一轮最后一次
+ // 工具调用的文案(与灵动岛同源)。查询带 bootAt 守卫,任何时刻调用都不会把本进程
+ // 正在跑的 turn 算进来。只服务本机顶层 renderer,不进 device-link allowlist。
+ ipcMain.handle('local-db:sessions:interrupted-resume-candidates', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const rows = await listInterruptedResumeCandidateRows();
+ const wording = createLocalizedToolRowWording();
+ return rows.map(({ sessionId, interruptedAt, lastToolUse }) => ({
+ sessionId,
+ interruptedAt,
+ activity: lastToolUse
+ ? (formatIslandToolDetail(lastToolUse.toolName, lastToolUse.input, { wording })
+ ?? lastToolUse.toolName)
+ : null,
+ }));
+ });
+
// 「尾部停在未 dismissed 错误行」的 active 会话 id —— 红点派生的周期性重算源。
// 与中断腿不同,这条判定与 turn 是否在跑无关(turn 一跑起来就会插入新的 user 行,
// error 行不再是尾行,自然不命中),因此可以在每个收敛触发点安全重跑。
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7e7c34bc1a..865dba980b 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5630,6 +5630,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** interrupted-turn-resume:「疑似中断」(startedAt > endedAt)的 active 会话 id。 */
interruptedPending: (): Promise<string[]> =>
ipcRenderer.invoke('local-db:sessions:interrupted-pending'),
+ /** 启动「继续上次中断的任务」弹窗:中断会话 + 中断时间 + 中断前正在做的事。 */
+ interruptedResumeCandidates: (): Promise<
+ { sessionId: string; interruptedAt: number; activity: string | null }[]
+ > => ipcRenderer.invoke('local-db:sessions:interrupted-resume-candidates'),
/** 红点派生的周期性重算源:尾部停在未 dismissed 错误行的 active 会话 id。
* 与 interruptedPending 分开消费——后者只在启动首拉一次(它对正在跑的 turn
* 天然成立,周期性重跑会把运行中的会话误判为中断)。 */
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 5fb0bafb56..f73660b053 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -30,6 +30,7 @@ import { BuiltinPanelBridgeProvider } from '@/panels/BuiltinPanelBridge';
import { WindowControls } from '@/components/title-bar/WindowControls';
import { UpdateNoticeDialog } from '@/components/UpdateNoticeDialog';
import { FeishuConflictDialogHost } from '@/components/feishuBot/FeishuConflictDialogHost';
+import { InterruptedTasksResumeDialog } from '@/features/cc-agent/InterruptedTasksResumeDialog';
import { GlobalDropImportListener } from '@/components/layout/GlobalDropImportListener';
import { SessionShareImportWizard } from '@/components/settings/SessionShareImportWizard';
import { ControlledBanner } from '@/features/remote-device/ControlledBanner';
@@ -1733,6 +1734,10 @@ export function MainLayout() {
onDismiss={dismissNotice}
/>
)}
+ {/* 意外退出后重启:列出被中断的任务供一键继续;更新说明弹窗关闭后再出现。 */}
+ {!isSecondaryWindow() && (
+ <InterruptedTasksResumeDialog suspended={Boolean(releaseNotes && noticeOpen)} />
+ )}
{/* FeiShu Bot conflict dialog -- subscribes to main process push and surfaces a global modal */}
<FeishuConflictDialogHost />
{/* 副窗支持管理页手动审批;自动提醒与受邀申请仍只由主窗口处理。 */}
diff --git a/apps/desktop/src/renderer/features/cc-agent/InterruptedTasksResumeDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/InterruptedTasksResumeDialog.tsx
new file mode 100644
index 0000000000..6efe8faf76
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/InterruptedTasksResumeDialog.tsx
@@ -0,0 +1,255 @@
+/**
+ * 启动时的「继续上次中断的任务」弹窗。
+ *
+ * 应用意外退出(崩溃 / 强杀 / 退出时仍有任务在跑)后,重启时把所有被中断的任务列出来,
+ * 默认全选,用户可以一键继续,也可以去掉不想继续的。
+ *
+ * 只是每个任务里「继续任务」横幅的批量入口,不引入新的状态:
+ * - 中断判定沿用 sessionActiveTurn 的 startedAt > endedAt,数据由
+ * local-db:sessions:interrupted-resume-candidates 提供(带 bootAt 守卫);
+ * - 「继续」对每个选中任务发与横幅相同的 CONTINUE_AFTER_APP_EXIT_PROMPT,中断标记由
+ * main 在续跑真正派发后确认,红点随 lastTurnEndedAt 广播熄灭;
+ * - 没勾选的任务和「暂不继续」不做任何写入,任务里的横幅与红点照常保留,之后仍可单独处理。
+ *
+ * 每个窗口生命周期只弹一次;更新说明弹窗打开期间先不弹,关掉后再出现。
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { VendorIcon, agentKindToVendor } from '@/components/sidebar/VendorIcon';
+import type { Session } from '@/lib/ccAgent.types';
+import { createLogger } from '@/lib/logger';
+import { makerChatStore } from '@/lib/makerChatStore';
+import { toast } from '@/lib/toast';
+import { cn } from '@/lib/utils';
+import { SESSION_READ_BATCH_LIMIT } from '../../../shared/sessionRead';
+import { CONTINUE_AFTER_APP_EXIT_PROMPT } from '../../../shared/interruptedTurn';
+import { formatSidebarTime } from './lib/formatSidebarTime';
+import { getSessionDisplayTitle } from './lib/sessionDisplayTitle';
+import { buildSessionSourceLabelMap } from './lib/sessionSourceLabel';
+
+const log = createLogger('interrupted-tasks-resume');
+
+/** localDb 登录后才 ready,首拉沿用 usePendingAlertAttention 的线性退避。 */
+const MAX_LOAD_ATTEMPTS = 5;
+
+/** 窗口级单例:布局重挂载不重复查询;弹窗关过一次后本窗口不再弹。 */
+let _loadPromise: Promise<InterruptedTask[]> | null = null;
+let _handledThisWindow = false;
+
+interface InterruptedTask {
+ session: Session;
+ interruptedAt: number;
+ activity: string | null;
+}
+
+async function loadInterruptedTasks(): Promise<InterruptedTask[]> {
+ const sessionsApi = window.electronAPI.localDb.sessions;
+ const candidates = await sessionsApi.interruptedResumeCandidates();
+ if (candidates.length === 0) return [];
+ const ids = candidates.map((c) => c.sessionId);
+ const batches: Promise<Session[]>[] = [];
+ for (let i = 0; i < ids.length; i += SESSION_READ_BATCH_LIMIT) {
+ batches.push(sessionsApi.getMany(ids.slice(i, i + SESSION_READ_BATCH_LIMIT)));
+ }
+ const byId = new Map((await Promise.all(batches)).flat().map((s) => [s.id, s]));
+ return candidates
+ .flatMap((c) => {
+ const session = byId.get(c.sessionId);
+ return session ? [{ session, interruptedAt: c.interruptedAt, activity: c.activity }] : [];
+ })
+ .sort((a, b) => b.interruptedAt - a.interruptedAt);
+}
+
+async function loadInterruptedTasksWithRetry(): Promise<InterruptedTask[]> {
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ return await loadInterruptedTasks();
+ } catch (err) {
+ if (attempt >= MAX_LOAD_ATTEMPTS) {
+ log.warn('interrupted tasks load gave up:', err);
+ return [];
+ }
+ await new Promise((resolve) => setTimeout(resolve, 2000 * attempt));
+ }
+ }
+}
+
+function TaskCheckbox({
+ checked,
+ indeterminate = false,
+ onChange,
+ ariaLabel,
+}: {
+ checked: boolean;
+ indeterminate?: boolean;
+ onChange: (checked: boolean) => void;
+ ariaLabel?: string;
+}) {
+ const ref = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ if (ref.current) ref.current.indeterminate = indeterminate;
+ }, [indeterminate]);
+ return (
+ <input
+ ref={ref}
+ type="checkbox"
+ checked={checked}
+ aria-label={ariaLabel}
+ onChange={(e) => onChange(e.target.checked)}
+ className="size-3.5 shrink-0 cursor-pointer accent-[var(--confirm-btn-primary-bg)]"
+ />
+ );
+}
+
+export function InterruptedTasksResumeDialog({ suspended = false }: { suspended?: boolean }) {
+ const { t } = useTranslation();
+ const [tasks, setTasks] = useState<InterruptedTask[]>([]);
+ const [deselected, setDeselected] = useState<ReadonlySet<string>>(() => new Set());
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+ _loadPromise ??= loadInterruptedTasksWithRetry();
+ void _loadPromise.then((loaded) => {
+ if (!active || _handledThisWindow || loaded.length === 0) return;
+ log.info(`found ${loaded.length} interrupted task(s) to offer for resume`);
+ setTasks(loaded);
+ setOpen(true);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+
+ const handleOpenChange = (next: boolean) => {
+ if (!next) _handledThisWindow = true;
+ setOpen(next);
+ };
+
+ const sourceLabels = useMemo(
+ () =>
+ buildSessionSourceLabelMap(
+ tasks.map((task) => task.session),
+ [],
+ t('ccAgent.sidebar.dialogues'),
+ t('settings.cindyMake.title'),
+ ),
+ [tasks, t],
+ );
+
+ const total = tasks.length;
+ const selectedIds = tasks.map((task) => task.session.id).filter((id) => !deselected.has(id));
+ const selectedCount = selectedIds.length;
+
+ const toggle = (id: string, checked: boolean) => {
+ setDeselected((prev) => {
+ const next = new Set(prev);
+ if (checked) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ };
+ const toggleAll = (checked: boolean) => {
+ setDeselected(checked ? new Set() : new Set(tasks.map((task) => task.session.id)));
+ };
+
+ const handleContinue = () => {
+ const ids = selectedIds;
+ void Promise.allSettled(
+ ids.map((id) => makerChatStore.sendUiTrigger(id, CONTINUE_AFTER_APP_EXIT_PROMPT)),
+ ).then((results) => {
+ const failed = results.filter((r) => r.status === 'rejected');
+ if (failed.length === 0) return;
+ log.warn(`failed to continue ${failed.length}/${ids.length} interrupted task(s)`);
+ toast.error(t('chat.interruptedResumeDialog.continueFailed', { count: failed.length }));
+ });
+ };
+
+ if (total === 0) return null;
+
+ const content = (
+ <div>
+ <div className="flex items-center justify-between px-2 pb-2 text-13">
+ <label className="flex cursor-pointer items-center gap-2.5 font-medium text-[var(--confirm-title)]">
+ <TaskCheckbox
+ checked={selectedCount === total}
+ indeterminate={selectedCount > 0 && selectedCount < total}
+ onChange={toggleAll}
+ />
+ {t('chat.interruptedResumeDialog.selectAll')}
+ </label>
+ <span className="text-12 text-[var(--confirm-desc)]">
+ {t('chat.interruptedResumeDialog.selectedCount', { selected: selectedCount, total })}
+ </span>
+ </div>
+ <ul className="border-y border-[var(--border-default)] py-1">
+ {tasks.map(({ session, interruptedAt, activity }) => {
+ const checked = !deselected.has(session.id);
+ const title = getSessionDisplayTitle(session, t('ccAgent.common.unnamedSession'), t);
+ const relative = formatSidebarTime(new Date(interruptedAt).toISOString(), t);
+ const meta = [
+ sourceLabels.get(session.id),
+ activity,
+ Date.now() - interruptedAt < 60_000
+ ? t('chat.interruptedResumeDialog.interruptedJustNow')
+ : t('chat.interruptedResumeDialog.interruptedAgo', { time: relative }),
+ ].filter(Boolean);
+ return (
+ <li key={session.id}>
+ <label
+ className={cn(
+ 'flex cursor-pointer items-center gap-2.5 rounded-lg p-2',
+ 'hover:bg-[var(--surface-hover)]',
+ )}
+ >
+ <TaskCheckbox
+ checked={checked}
+ ariaLabel={title}
+ onChange={(next) => toggle(session.id, next)}
+ />
+ <VendorIcon
+ vendor={agentKindToVendor(session.agentKind)}
+ size={14}
+ colorClassName="text-[var(--confirm-desc)]"
+ />
+ <span className={cn('min-w-0 flex-1', !checked && 'opacity-50')}>
+ <span className="block truncate text-13 text-[var(--confirm-title)]">
+ {title}
+ </span>
+ <span className="mt-0.5 block truncate text-12 text-[var(--confirm-desc)]">
+ {meta.join(' · ')}
+ </span>
+ </span>
+ </label>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+
+ return (
+ <ConfirmDialog
+ presentation="standard"
+ cancelFirst
+ autoFocusConfirm
+ open={open && !suspended}
+ onOpenChange={handleOpenChange}
+ maxWidth={460}
+ title={t('chat.interruptedResumeDialog.title')}
+ description={t('chat.interruptedResumeDialog.description', { count: total })}
+ content={content}
+ confirmText={
+ selectedCount > 0
+ ? t('chat.interruptedResumeDialog.continueSelected', { count: selectedCount })
+ : t('chat.interruptedResumeDialog.continueNone')
+ }
+ cancelText={t('chat.interruptedResumeDialog.later')}
+ confirmDisabled={selectedCount === 0}
+ onConfirm={handleContinue}
+ />
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/InterruptedTasksResumeDialog.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/InterruptedTasksResumeDialog.test.tsx
new file mode 100644
index 0000000000..6e40ba477b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/InterruptedTasksResumeDialog.test.tsx
@@ -0,0 +1,64 @@
+// @vitest-environment jsdom
+/**
+ * 启动「继续上次中断的任务」弹窗:只对仍勾选的任务发续跑指令。
+ *
+ * 依据:产品决策(2026-10-19)默认全选、可去掉不想继续的;没勾选的任务不得被续跑,
+ * 它们的中断横幅留给用户之后单独处理。续跑复用横幅的 CONTINUE_AFTER_APP_EXIT_PROMPT。
+ */
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { CONTINUE_AFTER_APP_EXIT_PROMPT } from '../../../../shared/interruptedTurn';
+import { InterruptedTasksResumeDialog } from '../InterruptedTasksResumeDialog';
+
+const sendUiTrigger = vi.hoisted(() => vi.fn(async () => {}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('@/lib/scrollbarAutoHide', () => ({ flashScrollbar: () => {} }));
+vi.mock('@/lib/makerChatStore', () => ({ makerChatStore: { sendUiTrigger } }));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+
+afterEach(cleanup);
+
+describe('InterruptedTasksResumeDialog', () => {
+ it('continues only the tasks that stay checked', async () => {
+ const now = Date.now();
+ const session = (id: string, title: string) => ({
+ id,
+ title,
+ source: 'desktop',
+ agentKind: 'cc',
+ workingDir: `/code/${id}`,
+ workspaceKind: 'project',
+ createdAt: new Date(now).toISOString(),
+ });
+ Object.assign(window, {
+ electronAPI: {
+ localDb: {
+ sessions: {
+ interruptedResumeCandidates: async () => [
+ { sessionId: 's-a', interruptedAt: now - 120_000, activity: '运行测试' },
+ { sessionId: 's-b', interruptedAt: now - 60_000, activity: null },
+ ],
+ getMany: async () => [session('s-a', '任务 A'), session('s-b', '任务 B')],
+ },
+ },
+ },
+ });
+
+ render(<InterruptedTasksResumeDialog />);
+
+ await screen.findByRole('alertdialog');
+ expect(screen.getByText('任务 A')).toBeTruthy();
+ expect(screen.getByText(/s-a · 运行测试/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('checkbox', { name: '任务 B' }));
+ fireEvent.click(
+ screen.getByRole('button', { name: 'chat.interruptedResumeDialog.continueSelected' }),
+ );
+
+ await waitFor(() => expect(sendUiTrigger).toHaveBeenCalledTimes(1));
+ expect(sendUiTrigger).toHaveBeenCalledWith('s-a', CONTINUE_AFTER_APP_EXIT_PROMPT);
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4180915775..4254fde039 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11221,6 +11221,21 @@
"continueTitle": "Continue from where the task left off (completed steps will not be repeated)",
"dismissTitle": "Dismiss this interruption notice"
},
+ "interruptedResumeDialog": {
+ "title": "Resume interrupted sessions",
+ "description_one": "{{appName}} quit unexpectedly and {{count}} session didn't finish. Selected sessions will check the conversation and pick up where they left off.",
+ "description_other": "{{appName}} quit unexpectedly and {{count}} sessions didn't finish. Selected sessions will check the conversation and pick up where they left off.",
+ "selectAll": "Select all",
+ "selectedCount": "{{selected}} of {{total}} selected",
+ "interruptedAgo": "interrupted {{time}} ago",
+ "interruptedJustNow": "interrupted just now",
+ "continueSelected_one": "Resume {{count}} session",
+ "continueSelected_other": "Resume {{count}} sessions",
+ "continueNone": "Resume",
+ "later": "Not now",
+ "continueFailed_one": "{{count}} session couldn't resume. Open it to try again.",
+ "continueFailed_other": "{{count}} sessions couldn't resume. Open them to try again."
+ },
"unreadFailedScheduleBanner": {
"text": "An automatic run failed.",
"precheck": "Automatic checks are temporarily blocked.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9c32d24d38..ed308cbc62 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11177,6 +11177,21 @@
"continueTitle": "中断した箇所からタスクを続行します(完了済みのステップは繰り返しません)",
"dismissTitle": "この中断通知を閉じる"
},
+ "interruptedResumeDialog": {
+ "title": "中断したタスクを再開",
+ "description_one": "{{appName}} が前回予期せず終了し、{{count}} 件のタスクが完了していません。選択したタスクは会話履歴から進捗を確認し、中断したところから再開します。",
+ "description_other": "{{appName}} が前回予期せず終了し、{{count}} 件のタスクが完了していません。選択したタスクは会話履歴から進捗を確認し、中断したところから再開します。",
+ "selectAll": "すべて選択",
+ "selectedCount": "{{selected}} / {{total}} 件を選択",
+ "interruptedAgo": "{{time}}前に中断",
+ "interruptedJustNow": "たった今中断",
+ "continueSelected_one": "{{count}} 件を再開",
+ "continueSelected_other": "{{count}} 件を再開",
+ "continueNone": "再開",
+ "later": "後で",
+ "continueFailed_one": "{{count}} 件のタスクを再開できませんでした。タスクを開いて再試行してください。",
+ "continueFailed_other": "{{count}} 件のタスクを再開できませんでした。タスクを開いて再試行してください。"
+ },
"unreadFailedScheduleBanner": {
"text": "自動実行に失敗した記録があります。",
"precheck": "自動チェックが一時的に停止しています。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 0d78614e69..9e13229dbc 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11177,6 +11177,21 @@
"continueTitle": "중단된 지점부터 작업을 계속합니다(완료된 단계는 반복하지 않습니다)",
"dismissTitle": "이 중단 알림 닫기"
},
+ "interruptedResumeDialog": {
+ "title": "중단된 작업 이어서 하기",
+ "description_one": "{{appName}}이(가) 지난번에 예기치 않게 종료되어 작업 {{count}}개가 끝나지 않았습니다. 선택한 작업은 대화 기록으로 진행 상황을 확인하고 중단된 곳부터 이어서 진행합니다.",
+ "description_other": "{{appName}}이(가) 지난번에 예기치 않게 종료되어 작업 {{count}}개가 끝나지 않았습니다. 선택한 작업은 대화 기록으로 진행 상황을 확인하고 중단된 곳부터 이어서 진행합니다.",
+ "selectAll": "모두 선택",
+ "selectedCount": "{{total}}개 중 {{selected}}개 선택",
+ "interruptedAgo": "{{time}} 전 중단",
+ "interruptedJustNow": "방금 중단",
+ "continueSelected_one": "작업 {{count}}개 이어서 하기",
+ "continueSelected_other": "작업 {{count}}개 이어서 하기",
+ "continueNone": "이어서 하기",
+ "later": "나중에",
+ "continueFailed_one": "작업 {{count}}개를 이어서 진행하지 못했습니다. 작업을 열어 다시 시도하세요.",
+ "continueFailed_other": "작업 {{count}}개를 이어서 진행하지 못했습니다. 작업을 열어 다시 시도하세요."
+ },
"unreadFailedScheduleBanner": {
"text": "실패한 자동 실행이 있습니다.",
"precheck": "자동 확인이 일시적으로 차단되었습니다.",
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 396c906213..fbadaa5bc4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11177,6 +11177,21 @@
"continueTitle": "从中断处继续完成任务(不会重复已完成的步骤)",
"dismissTitle": "关闭此中断提示"
},
+ "interruptedResumeDialog": {
+ "title": "继续上次中断的任务",
+ "description_one": "{{appName}} 上次意外退出,有 {{count}} 个任务没做完。选中的任务会根据对话记录判断进度,从中断的地方接着做。",
+ "description_other": "{{appName}} 上次意外退出,有 {{count}} 个任务没做完。选中的任务会根据对话记录判断进度,从中断的地方接着做。",
+ "selectAll": "全选",
+ "selectedCount": "已选 {{selected}} / {{total}}",
+ "interruptedAgo": "{{time}}前中断",
+ "interruptedJustNow": "刚刚中断",
+ "continueSelected_one": "继续 {{count}} 个任务",
+ "continueSelected_other": "继续 {{count}} 个任务",
+ "continueNone": "继续任务",
+ "later": "暂不继续",
+ "continueFailed_one": "有 {{count}} 个任务没能继续,可以打开任务后重试。",
+ "continueFailed_other": "有 {{count}} 个任务没能继续,可以打开任务后重试。"
+ },
"unreadFailedScheduleBanner": {
"text": "此前有自动运行失败。",
"precheck": "自动检查暂时受阻。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9ebd83bc41..cfdf5b43f1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11176,6 +11176,21 @@
"continueTitle": "從中斷處繼續完成任務(不會重複已完成的步驟)",
"dismissTitle": "關閉此中斷提示"
},
+ "interruptedResumeDialog": {
+ "title": "繼續上次中斷的任務",
+ "description_one": "{{appName}} 上次意外結束,有 {{count}} 個任務沒做完。選取的任務會根據對話紀錄判斷進度,從中斷的地方接著做。",
+ "description_other": "{{appName}} 上次意外結束,有 {{count}} 個任務沒做完。選取的任務會根據對話紀錄判斷進度,從中斷的地方接著做。",
+ "selectAll": "全選",
+ "selectedCount": "已選 {{selected}} / {{total}}",
+ "interruptedAgo": "{{time}}前中斷",
+ "interruptedJustNow": "剛剛中斷",
+ "continueSelected_one": "繼續 {{count}} 個任務",
+ "continueSelected_other": "繼續 {{count}} 個任務",
+ "continueNone": "繼續任務",
+ "later": "暫不繼續",
+ "continueFailed_one": "有 {{count}} 個任務未能繼續,可以開啟任務後重試。",
+ "continueFailed_other": "有 {{count}} 個任務未能繼續,可以開啟任務後重試。"
+ },
"unreadFailedScheduleBanner": {
"text": "先前有自動執行失敗。",
"precheck": "自動檢查暫時受阻。",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index d10bc10e6b..d9f25f6978 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4845,6 +4845,10 @@ interface ElectronAPI {
setPinnedCardSummaries: (enabled: boolean) => Promise<void>;
/** interrupted-turn-resume:「疑似中断」(startedAt > endedAt)的 active 会话 id。 */
interruptedPending: () => Promise<string[]>;
+ /** 启动「继续上次中断的任务」弹窗:中断会话 + 中断时间 + 中断前正在做的事。 */
+ interruptedResumeCandidates: () => Promise<
+ { sessionId: string; interruptedAt: number; activity: string | null }[]
+ >;
/** 红点派生的周期性重算源:尾部停在未 dismissed 错误行的 active 会话 id。 */
errorTailPending: () => Promise<string[]>;
/** 批量处置未处理告警(「全部标为已读」)。failed = 未处置成功的会话 id。 */