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。

refactor(desktop): 重启提示的伙伴任务可继续判定复用发送路径守卫

Dash024a307c9bdc
diff --git a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
index c37518f758..4badf7e2b1 100644
--- a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts
@@ -555,7 +555,7 @@ describe('sessionActiveTurn', () => {
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();
+ const rows = await listInterruptedResumeCandidateRows(() => true);
expect(rows.sort((a, b) => a.sessionId.localeCompare(b.sessionId))).toEqual([
{ sessionId: 's-silent', interruptedAt: startedAt, lastToolUse: null },
{
@@ -569,9 +569,14 @@ describe('sessionActiveTurn', () => {
it('offers interrupted companion tasks for resume but keeps hidden lanes and red dots out', async () => {
const { listInterruptedResumeCandidateRows } = await import('../interruptedResumeCandidates.js');
const { listInterruptedPendingSessionIds } = await import('../sessionActiveTurn.js');
+ const { botSessionInputBlockReason, isShadowedCompanionSession } = await import('../../maker-ipc/botSessionInputGuard.js');
+ // 与 sessions:interrupted-resume-candidates 注入的守卫同构:伙伴降级到别的电脑时 shadowed。
+ const canResume = ({ botId, role, profileStatus }: { botId: string; role: string; profileStatus: string }) =>
+ botSessionInputBlockReason({ source: 'bot', role, profileStatus }) === null
+ && !isShadowedCompanionSession({ role, botId }, (id) => id === 'bot-shadowed');
const client = createTestDbClient();
const startedAt = Date.now() - 10_000;
- await client.exec("INSERT INTO bot_profiles (id, status) VALUES ('bot-1', 'active'), ('bot-paused', 'paused')");
+ await client.exec("INSERT INTO bot_profiles (id, status) VALUES ('bot-1', 'active'), ('bot-paused', 'paused'), ('bot-shadowed', 'active')");
await seedSession(client, 's-desktop', { startedAt });
for (const role of ['canonical', 'delegation', 'routine', 'channel', 'history', 'group', 'thread']) {
await seedSession(client, `bot-${role}`, { startedAt, source: 'bot' });
@@ -586,10 +591,16 @@ describe('sessionActiveTurn', () => {
'INSERT INTO bot_session_links (id, bot_id, session_id, role, created_at) VALUES (?, ?, ?, ?, ?)',
['link-paused', 'bot-paused', 'bot-paused-canonical', 'canonical', startedAt],
);
+ // 伙伴已降级到别的电脑:本机副本的主对话 / 例行发送一律被拒,不提示。
+ await seedSession(client, 'bot-shadowed-canonical', { startedAt, source: 'bot' });
+ await client.exec(
+ 'INSERT INTO bot_session_links (id, bot_id, session_id, role, created_at) VALUES (?, ?, ?, ?, ?)',
+ ['link-shadowed', 'bot-shadowed', 'bot-shadowed-canonical', 'canonical', startedAt],
+ );
// 没有伙伴关联的 bot 来源会话无处打开,不提示。
await seedSession(client, 'bot-unlinked', { startedAt, source: 'bot' });
- expect((await listInterruptedResumeCandidateRows()).map((r) => r.sessionId).sort()).toEqual([
+ expect((await listInterruptedResumeCandidateRows(canResume)).map((r) => r.sessionId).sort()).toEqual([
'bot-canonical',
'bot-channel',
'bot-delegation',
diff --git a/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts b/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts
index 48c04ef66b..142dd52686 100644
--- a/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts
+++ b/apps/desktop/src/main/localDb/interruptedResumeCandidates.ts
@@ -16,7 +16,7 @@
import { and, desc, eq, gte, isNull, sql } from 'drizzle-orm';
import { getDbClient } from './client/current';
-import { listInterruptedPendingRows } from './sessionActiveTurn';
+import { listInterruptedPendingRows, type InterruptedBotTaskLink } from './sessionActiveTurn';
import { messages } from './schema';
export interface InterruptedTurnToolUse {
@@ -45,10 +45,16 @@ function parseToolUse(raw: string | null): InterruptedTurnToolUse | null {
}
}
-export async function listInterruptedResumeCandidateRows(): Promise<
- InterruptedResumeCandidateRow[]
-> {
- const pending = await listInterruptedPendingRows({ includeBotTasks: true });
+/**
+ * `canResumeBotTask` 必须复用「继续」发送路径同一套守卫(伙伴启用、未降级到别的电脑等),
+ * 候选不再自己复刻判据 —— 弹窗默认勾选候选,列出点了必失败的任务只会留下一条失败提示。
+ */
+export async function listInterruptedResumeCandidateRows(
+ canResumeBotTask: (task: InterruptedBotTaskLink) => boolean,
+): Promise<InterruptedResumeCandidateRow[]> {
+ const pending = (await listInterruptedPendingRows({ includeBotTasks: true })).filter(
+ (row) => !row.botTask || canResumeBotTask(row.botTask),
+ );
if (pending.length === 0) return [];
const db = getDbClient().drizzle;
return Promise.all(
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 1faa181352..6cc289eab5 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -144,6 +144,8 @@ import { recycleCindyMakeTask } from '../../cindy-make/taskManagement.js';
import { broadcastSubagentRunsInvalidated } from './subagentRuns.js';
import { compactSessionToolResultsBestEffort } from '../toolResultCompaction.js';
import { consumeWritableDirectoryPickerGrants } from '../../maker-ipc/writableDirectoryPickerGrant.js';
+import { botSessionInputBlockReason, isShadowedCompanionSession } from '../../maker-ipc/botSessionInputGuard.js';
+import { isCompanionShadowed } from '../../companion-cloud/homes.js';
export { setSessionRuntimeCleanup } from '../sessionRuntimeCleanup.js';
@@ -1863,7 +1865,11 @@ export function registerSessionIpc(
// 正在跑的 turn 算进来。只服务本机顶层 renderer,不进 device-link allowlist。
ipcMain.handle('local-db:sessions:interrupted-resume-candidates', async (event) => {
assertTrustedAppRendererEvent(event);
- const rows = await listInterruptedResumeCandidateRows();
+ const rows = await listInterruptedResumeCandidateRows(
+ ({ botId, role, profileStatus }) =>
+ botSessionInputBlockReason({ source: 'bot', role, profileStatus }) === null
+ && !isShadowedCompanionSession({ role, botId }, isCompanionShadowed),
+ );
const wording = createLocalizedToolRowWording();
return rows.map(({ sessionId, interruptedAt, lastToolUse }) => ({
sessionId,
diff --git a/apps/desktop/src/main/localDb/sessionActiveTurn.ts b/apps/desktop/src/main/localDb/sessionActiveTurn.ts
index f49503be94..d44f9897e7 100644
--- a/apps/desktop/src/main/localDb/sessionActiveTurn.ts
+++ b/apps/desktop/src/main/localDb/sessionActiveTurn.ts
@@ -375,34 +375,45 @@ export function _setBootAtMsForTests(ms: number): void {
* 启动首拉消费它(见下方两条腿消费周期的说明);但 startedAt < bootAt 的守卫让它
* 在任何时刻调用都不会把运行中的会话算进来,批量处置因此也可以安全复用。
*/
+export interface InterruptedBotTaskLink {
+ botId: string;
+ role: string;
+ profileStatus: string;
+}
+
export async function listInterruptedPendingRows(
options: { includeBotTasks?: boolean } = {},
-): Promise<{ sessionId: string; startedAt: number }[]> {
+): Promise<{ sessionId: string; startedAt: number; botTask?: InterruptedBotTaskLink }[]> {
const db = getDbClient().drizzle;
// 只统计桌面 sidebar 可见来源(含 feishu/slack 等 IM 渠道)——
// 不可见来源的红点无处展示也无法清除。
const listedSource = inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES);
+ // 伙伴任务只给启动弹窗用(includeBotTasks):范围只收有页面 / 列在普通任务列表的角色
+ // (主对话、委派、例行、渠道);group 与私聊话题专线是隐藏专线,history 只读。能不能
+ // 真正继续(伙伴启用、未降级)不在这里重写判据,由调用方用发送路径同一套守卫判定。
+ const visibleBotRole = inArray(botSessionLinks.role, [
+ 'canonical',
+ 'delegation',
+ 'routine',
+ 'channel',
+ ]);
const rows = await db
- .select({ id: sessions.id, startedAt: sessions.activeTurnStartedAt })
+ .select({
+ id: sessions.id,
+ source: sessions.source,
+ startedAt: sessions.activeTurnStartedAt,
+ botId: botSessionLinks.botId,
+ botRole: botSessionLinks.role,
+ botStatus: botProfiles.status,
+ })
.from(sessions)
+ .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
+ .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
.where(
and(
eq(sessions.status, 'active'),
options.includeBotTasks
- ? or(
- listedSource,
- // 能走普通「继续」路径的伙伴任务:主对话、委派任务有自己的页面,例行与渠道
- // 专线列在普通任务列表里。history 只读、伙伴未启用(botSessionInputGuard 拒绝发送),群与
- // 私聊话题专线是隐藏专线,由群聊 / 私聊收口,都不提示。
- and(
- eq(sessions.source, 'bot'),
- sql`EXISTS (SELECT 1 FROM ${botSessionLinks}
- JOIN ${botProfiles} ON ${botProfiles.id} = ${botSessionLinks.botId}
- WHERE ${botSessionLinks.sessionId} = ${sessions.id}
- AND ${botSessionLinks.role} IN ('canonical', 'delegation', 'routine', 'channel')
- AND ${botProfiles.status} = 'active')`,
- ),
- )
+ ? or(listedSource, and(eq(sessions.source, 'bot'), visibleBotRole))
: listedSource,
// 插件后台隐藏任务不在侧栏展示,红点无处展示也无法清除。
isNull(sessions.hiddenAt),
@@ -414,7 +425,17 @@ export async function listInterruptedPendingRows(
);
// startedAt 必非 null(上面的 gt/lt 比较已排除),类型收窄用于批量处置的 CAS。
return rows.flatMap((r) =>
- r.startedAt == null ? [] : [{ sessionId: r.id, startedAt: r.startedAt }],
+ r.startedAt == null
+ ? []
+ : [
+ {
+ sessionId: r.id,
+ startedAt: r.startedAt,
+ ...(r.source === 'bot' && r.botId && r.botRole && r.botStatus
+ ? { botTask: { botId: r.botId, role: r.botRole, profileStatus: r.botStatus } }
+ : {}),
+ },
+ ],
);
}