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(bots): 群任务进行中卡在任务进行期间持续重试并在重启后补发;主人从群任务卡停止任务不再要求群执行仍在进行

Chris0b416e76fceb
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index 40cbb014f6..32ed70e09c 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -4288,6 +4288,76 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { release(); runtime.dispose(); }
});
+ it('lets the owner stop a group task from its card after the group reply that started it has ended', async () => {
+ await seedPair(); seedGroupLane();
+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });
+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => ({ ok: true as const, messageId: `posted:${input.clientId}` }));
+ const runtime = createDelegationRuntime({ postGroupTaskMessage });
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Long-running work' });
+ if (!task.ok) throw new Error(task.message);
+ // The group reply that started the task has ended: its execution authority is gone.
+ release();
+ // A group tool call still needs a live execution; the owner's stop button does not.
+ expect(await runtime.delegation.cancelDelegation('group-lane', task.delegationId)).toMatchObject({ ok: false, errorCode: 'GROUP_AUTHORIZATION_REQUIRED' });
+ // Another group's lane cannot reach the task either way.
+ seedGroupLane('other-group', 'group:other:access:owner:2');
+ expect(await runtime.delegation.cancelDelegationFromOwner('other-group', task.delegationId)).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });
+ expect(await runtime.delegation.cancelDelegationFromOwner('group-lane', task.delegationId)).toMatchObject({ ok: true, delegationId: task.delegationId });
+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).toBe('cancelled');
+ } finally { release(); runtime.dispose(); }
+ });
+
+ it('keeps re-posting the start card while the group task runs, and stops once it has ended', async () => {
+ await seedPair(); seedGroupLane();
+ vi.useFakeTimers();
+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });
+ // The group channel is down for the whole run; only the start card is affected here.
+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => input.clientId.endsWith(':started')
+ ? { ok: false as const, errorCode: 'GROUP_CHANNEL_UNAVAILABLE', retryable: true }
+ : { ok: true as const, messageId: `posted:${input.clientId}` });
+ const runtime = createDelegationRuntime({ postGroupTaskMessage });
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Long work', timeoutMs: 60 * 60_000 });
+ if (!task.ok) throw new Error(task.message);
+ const startAttempts = () => postGroupTaskMessage.mock.calls.filter(([input]) => input.clientId.endsWith(':started')).length;
+ // Backoff 1, 2, 4, 8, 16, 32 s, then once a minute: the outage outlasts the former seven tries.
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(startAttempts()).toBeGreaterThanOrEqual(14);
+ await runtime.runPendingTurns();
+ const afterEnd = startAttempts();
+ // The task ended: no 「进行中」 card may land under its result.
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(startAttempts()).toBe(afterEnd);
+ } finally { release(); runtime.dispose(); vi.useRealTimers(); }
+ });
+
+ it('posts a running group task\'s start card again after a restart when it never reached the group', async () => {
+ await seedPair(); seedGroupLane();
+ const release = registerGroupToolAuthority('group-lane', { botId: 'bot-a', mode: 'owner', isCurrent: () => true, validate: async () => {} });
+ let groupDown = true;
+ const postGroupTaskMessage = vi.fn(async (input: { clientId: string }) => groupDown
+ ? { ok: false as const, errorCode: 'GROUP_CHANNEL_UNAVAILABLE', retryable: true }
+ : { ok: true as const, messageId: `posted:${input.clientId}` });
+ let runtime = createDelegationRuntime({ postGroupTaskMessage });
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'group-lane', objective: 'Long work' });
+ if (!task.ok) throw new Error(task.message);
+ expect(postGroupTaskMessage).toHaveBeenCalledTimes(1);
+ runtime.dispose();
+ groupDown = false;
+ runtime = createDelegationRuntime({ postGroupTaskMessage });
+ await runtime.delegation.restore();
+ // A second post, from the restored runtime: the same idempotent card, now accepted.
+ await vi.waitFor(() => expect(postGroupTaskMessage).toHaveBeenCalledTimes(2));
+ expect(postGroupTaskMessage).toHaveBeenLastCalledWith(expect.objectContaining({
+ groupId: 'fixture', clientId: `bot-delegation-task:${task.delegationId}:started`,
+ card: expect.objectContaining({ data: expect.objectContaining({ state: 'started' }) }),
+ }));
+ expect(h.sqlite!.prepare('SELECT status FROM bot_delegations WHERE id=?').pluck().get(task.delegationId)).toBe('running');
+ } finally { release(); runtime.dispose(); }
+ });
+
it('posts a timed-out group task to the group as timed out, in the sender\'s language, not as failed', async () => {
await seedPair(); seedGroupLane();
vi.useFakeTimers();
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index a7c854e7d7..bb5397e72b 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -854,7 +854,12 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
const groupPostTimers = new Set<ReturnType<typeof setTimeout>>();
/** Start-card posts still on their way, by task: a later card waits for them (see `afterGroupTaskStart`). */
const groupStartPosts = new Map<string, Promise<void>>();
- /** The start card is best effort with backoff; the result message carries the card again. */
+ /**
+ * The 「进行中」 card is posted with backoff for as long as the task runs (a group outage may
+ * outlast any fixed number of tries); `restore` posts it again after a restart. The post is
+ * idempotent by client id, so a card already in the group is never repeated, and a retry
+ * after the task ended stays away. The result message carries the card again.
+ */
const postGroupTaskStart = (home: { groupId: string }, row: GroupTaskRow, attempt = 0): Promise<void> => {
const run = (async () => {
try {
@@ -873,11 +878,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
} catch (error) {
log.warn('Bot task group card deferred', { delegationId: row.id, error: error instanceof Error ? error.message : String(error) });
}
- if (attempt >= 6) return;
const timer = setTimeout(() => {
groupPostTimers.delete(timer);
void postGroupTaskStart(home, row, attempt + 1);
- }, Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** attempt));
+ }, Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** Math.min(attempt, 10)));
timer.unref?.();
groupPostTimers.add(timer);
})().finally(() => {
@@ -1537,7 +1541,14 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
return link ?? null;
};
- const resolveCaller = async (callerSessionId: string) => {
+ /**
+ * `ownerUi`: the owner's own UI (the desktop, or the phone over device-link) stopping a task
+ * from its card. A group lane still only scopes which tasks it may touch (`callerTaskScope`),
+ * but the live execution authority a group tool call needs is not required, since the group
+ * reply that started the task is usually long over while the task still runs
+ * (bot-group-chat.md §10).
+ */
+ const resolveCaller = async (callerSessionId: string, { ownerUi = false }: { ownerUi?: boolean } = {}) => {
const link = await resolveLinkedSession(callerSessionId);
if (
!link
@@ -1548,7 +1559,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
|| !['canonical', 'delegation', 'group'].includes(link.role)
) return null;
// Delegating full independent work is an owner action, not a guest tool grant.
- const groupAuthority = link.role === 'group'
+ const groupAuthority = link.role === 'group' && !ownerUi
? await authorizeGroupTool(callerSessionId, link.botId, 'owner-action') : null;
return { ...link, groupAuthority };
};
@@ -2877,8 +2888,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
callerSessionId: string,
delegationId: string,
inheritedAuthority?: Awaited<ReturnType<typeof authorizeGroupTool>> | null,
+ { ownerUi = false }: { ownerUi?: boolean } = {},
): Promise<BotDelegationResult<{ delegationId: string; childSessionId: string | null; control?: { state: string; queue_held: boolean; stop_status: string } }>> => {
- const caller = await resolveCaller(callerSessionId);
+ const caller = await resolveCaller(callerSessionId, { ownerUi });
if (!caller) {
return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };
}
@@ -4382,6 +4394,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
}
return;
}
+ // A running task's 「进行中」 card may still be on its way when the app stopped: post it
+ // again (idempotent by client id), with the same backoff as at creation.
+ const groupHome = groupHomeOf(row.permissionSnapshotJson);
+ if (groupHome) void postGroupTaskStart(groupHome, row);
if (readTaskPause(row)) {
if (row.childSessionId) holdTaskInput(row.childSessionId, true);
return;
@@ -4449,6 +4465,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
messageSessionTask: expose(messageSessionTask),
stopSessionTask: expose(stopSessionTask),
cancelDelegation: expose((callerSessionId: string, delegationId: string) => withTaskOperation(delegationId, () => cancelDelegation(callerSessionId, delegationId))),
+ /** The owner stopping a task from its card (IPC / device-link), from any lane that shows the card. */
+ cancelDelegationFromOwner: expose((callerSessionId: string, delegationId: string) => withTaskOperation(delegationId,
+ () => cancelDelegation(callerSessionId, delegationId, undefined, { ownerUi: true }))),
cancelDelegationsForParentSession,
cancelDelegationsForBot,
settleSession,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 46ab25a1f8..3a097a9a06 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -12258,7 +12258,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
) {
throwIpcError('INVALID_PARAMS', 'parentSessionId + delegationId required');
}
- return delegationForRestore.cancelDelegation(parentSessionId, delegationId);
+ // The owner's own stop button: not a group tool call, so no live group execution is needed.
+ return delegationForRestore.cancelDelegationFromOwner(parentSessionId, delegationId);
},
);
const captureSessionOwner = () => {
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index d211ecb2e7..1dfcc0bce1 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -349,7 +349,7 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授
群专线的 `role=group` 是来源身份,不等于只读历史任务,也不单独构成授权。读取自己的 Profile、能力与 Skill 目录时,必须核对活跃执行、伙伴归属、成员状态、授权版本及执行租约;只聊天的专线仍不可读取私人资料。群主身份不能替代伙伴主人身份。
-只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。**从群里启动的任务住在这个群里**:父任务就是发起它的群专线,不再改挂或新建私聊。任务一建立,伙伴就以自己的身份在群里发一条带任务卡(`cindy.task` 卡片块,带 fallback 文字;fallback 由发送端按本机界面语言生成,卡片数据本身不含语言)的消息;子任务要确认时再发一条「等你确认」的卡(权限请求只说需要批准,不带工具名和参数;提问带问题原文),主人从卡片打开任务作答;任务结束后结果正文、终态卡与交付文件作为伙伴的群消息回到群里。终态卡与主人实时任务卡同一口径:超时任务显示「已超时」,不是「失败了」。交付文件逐个上传,本机发不出去的文件(空文件、超过 100 MB)和服务端明确拒绝的文件跳过并记日志,其余照常送达;只有临时故障才整条稍后重试。超过一条消息 20 个附件上限的文件,与超长正文一样,在同一幂等 ID 家族的后续消息里继续发,不截断。这些消息在任何执行之外以伙伴 actor 发出,不唤醒群专线,也不唤醒私聊;工具返回 `completion_destination=group`,伙伴只需告诉群里开了什么。群的消息通道明确拒绝(伙伴已不在群、群已归档、本机旧式群)时,结果退回该主人与该伙伴的私聊,不丢失。主人的桌面与手机看到的是实时任务卡(读本机委派行;手机直接从 Chat Server 进入的群没有电脑路由,按该伙伴的主力电脑读,主力电脑未知时退回快照),其他成员看到卡片发出时的标题与状态。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。
+只有伙伴主人发起且当前授权有效的执行,才能从群里启动独立开发任务或发送私聊。独立任务保留群内调用身份与来源范围,沿用普通任务的权限档、审批、隔离目录和工作目录注册。**从群里启动的任务住在这个群里**:父任务就是发起它的群专线,不再改挂或新建私聊。任务一建立,伙伴就以自己的身份在群里发一条带任务卡(`cindy.task` 卡片块,带 fallback 文字;fallback 由发送端按本机界面语言生成,卡片数据本身不含语言)的消息;群通道暂时不可用时,这条「进行中」卡在任务仍在进行期间按退避持续重试,应用重启后由启动恢复再发一次(按幂等 ID 去重,不会重复出现),任务已结束就不再补发;子任务要确认时再发一条「等你确认」的卡(权限请求只说需要批准,不带工具名和参数;提问带问题原文),主人从卡片打开任务作答;任务结束后结果正文、终态卡与交付文件作为伙伴的群消息回到群里。终态卡与主人实时任务卡同一口径:超时任务显示「已超时」,不是「失败了」。交付文件逐个上传,本机发不出去的文件(空文件、超过 100 MB)和服务端明确拒绝的文件跳过并记日志,其余照常送达;只有临时故障才整条稍后重试。超过一条消息 20 个附件上限的文件,与超长正文一样,在同一幂等 ID 家族的后续消息里继续发,不截断。这些消息在任何执行之外以伙伴 actor 发出,不唤醒群专线,也不唤醒私聊;工具返回 `completion_destination=group`,伙伴只需告诉群里开了什么。群的消息通道明确拒绝(伙伴已不在群、群已归档、本机旧式群)时,结果退回该主人与该伙伴的私聊,不丢失。主人的桌面与手机看到的是实时任务卡(读本机委派行;手机直接从 Chat Server 进入的群没有电脑路由,按该伙伴的主力电脑读,主力电脑未知时退回快照),其他成员看到卡片发出时的标题与状态。非主人获得的群工具授权不包含此独立任务能力。群内只能查询或控制由同一授权专线创建的独立任务;主人仍可从私聊管理已启动的任务。群执行结束不会取消已经正式启动的独立任务,后续群内操作必须重新验证当前执行。主人在桌面或手机上从群里的实时任务卡点「停止任务」是主人自己的操作,不是群工具调用:只要求这张卡所在的专线能看到该任务,不要求发起它的群执行仍在进行。
非主人群工具授权仅允许读取伙伴自身资料、已选能力和自己的技能;应用级能力目录与默认模型查询仍须当前主人执行授权。