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): 后台任务归属小标只认委派子任务;本机群 lastReplyAt 把安排卡算进来

Chrisc6dc9baac1d0
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index d16b3ec2ae..183f19770b 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -75,6 +75,7 @@ import {
import {
listBotWorkbenchCandidatesForOwner,
readBotWorkbenchTaskForOwner,
+ readBotResponsibilityScope,
readBotResponsibleSessionIds,
} from '../../maker-ipc/botWorkbenchTools.js';
import {
@@ -2180,7 +2181,7 @@ export function registerBotIpc(): void {
// Older renderers receive empty directories rather than claiming projects.
const scopes = await collectTaskResponsibilityScopes(
bots.map((bot) => bot.id),
- (botId) => readBotResponsibleSessionIds(owner.userDataDir, botId),
+ (botId) => readBotResponsibilityScope(owner.userDataDir, botId),
);
owner.assertCurrent();
return scopes;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
index efbe8b55b2..d1d44a6b33 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
@@ -290,7 +290,7 @@ describe('botGroupChatService', () => {
});
}
const group = await waitForIdle(harness, groupId);
- expect(group.lastReplyAt).toBe(Math.max(...group.messages.filter(m => m.authorKind === 'bot' && m.kind === 'message').map(m => m.createdAt)));
+ expect(group.lastReplyAt).toBe(Math.max(...group.messages.filter(m => m.authorKind === 'bot' && (m.kind === 'message' || m.kind === 'plan')).map(m => m.createdAt)));
// Incoming times are the Bots' messages, oldest first, without the owner's own or notices.
const incoming = group.messages.filter(m => m.authorKind === 'bot' && (m.kind === 'message' || m.kind === 'plan'))
.sort((a, b) => a.sequence - b.sequence).map(m => new Date(m.createdAt).toISOString());
@@ -654,6 +654,13 @@ describe('botGroupChatService 分工', () => {
const plan = await proposePlan(harness, groupId);
const group = await detailOf(harness, groupId);
+ // The plan card is the newest incoming item: the read position seeded from lastReplyAt
+ // covers it, and the unread list counts it (bot-group-chat.md §5 未读).
+ const planMessage = group.messages.filter(m => m.authorKind === 'bot').sort((a, b) => b.sequence - a.sequence)[0]!;
+ expect(planMessage.kind).toBe('plan');
+ expect(group.lastReplyAt).toBe(planMessage.createdAt);
+ expect(group.incomingMessageTimes?.at(-1)).toBe(new Date(planMessage.createdAt).toISOString());
+
expect(decidePlan).toHaveBeenCalledTimes(1);
expect(decidePlan.mock.calls[0]![0]).toMatchObject({
mode: 'auto',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
index e99c71a047..8c2d185e8c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
@@ -57,8 +57,11 @@ it('keeps healthy companions visible while failing closed for a damaged release
await setTaskResponsibility(root, 'damaged', 'created', false, () => {});
const file = path.join(botProfileDir(root, 'damaged'), 'task-responsibility.v1.json');
await fs.writeFile(file, '{broken');
- const scopes = await collectTaskResponsibilityScopes(['damaged', 'healthy'], async (botId) =>
- responsibleSessionIds(botId === 'damaged' ? ['created'] : [], await readTaskResponsibilities(root, botId)));
- expect(scopes).toEqual([{ botId: 'healthy', directories: [], sessionIds: ['owned'] }]);
+ const scopes = await collectTaskResponsibilityScopes(['damaged', 'healthy'], async (botId) => ({
+ sessionIds: responsibleSessionIds(botId === 'damaged' ? ['created'] : [], await readTaskResponsibilities(root, botId)),
+ delegatedSessionIds: botId === 'damaged' ? ['created'] : [],
+ }));
+ // A taken-over task is a responsibility, not one of the Bot's own background tasks.
+ expect(scopes).toEqual([{ botId: 'healthy', directories: [], sessionIds: ['owned'], delegatedSessionIds: [] }]);
expect(await fs.readFile(file, 'utf8')).toBe('{broken');
});
diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
index 590c22657e..2e3a6cd2d9 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
@@ -737,18 +737,15 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
.where(and(eq(botGroupMessages.groupId, groupId), eq(botGroupMessages.kind, 'message')))
.orderBy(desc(botGroupMessages.sequence))
.limit(1);
- const [latestReply] = await db.select({ createdAt: botGroupMessages.createdAt })
- .from(botGroupMessages)
- .where(and(eq(botGroupMessages.groupId, groupId), eq(botGroupMessages.authorKind, 'bot'),
- eq(botGroupMessages.kind, 'message')))
- .orderBy(desc(botGroupMessages.sequence)).limit(1);
- // A local group's only person is its owner, so incoming messages are the Bots' messages.
+ // A local group's only person is its owner, so incoming messages are the Bots' messages:
+ // replies and plan cards alike. `lastReplyAt` is the newest of them, so a read position
+ // seeded from it never leaves the latest plan card looking unread.
const incoming = await db.select({ createdAt: botGroupMessages.createdAt })
.from(botGroupMessages)
.where(and(eq(botGroupMessages.groupId, groupId), eq(botGroupMessages.authorKind, 'bot'),
inArray(botGroupMessages.kind, ['message', 'plan'])))
.orderBy(desc(botGroupMessages.sequence)).limit(99);
- return { latest, latestSpoken, lastReplyAt: latestReply?.createdAt ?? 0,
+ return { latest, latestSpoken, lastReplyAt: incoming[0]?.createdAt ?? 0,
incomingMessageTimes: incoming.reverse().map((row) => new Date(row.createdAt).toISOString()) };
};
diff --git a/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts b/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
index 045f201823..cf58c447fb 100644
--- a/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
+++ b/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
@@ -71,16 +71,27 @@ export async function setTaskResponsibility(
});
}
+export interface TaskResponsibilityScope {
+ botId: string;
+ directories: string[];
+ /** Every task this Bot is responsible for: its own background tasks plus the ones it took over. */
+ sessionIds: string[];
+ /** Only the background tasks this Bot started itself (delegation children). */
+ delegatedSessionIds: string[];
+}
+
/** Fail closed for a damaged companion, without removing other companions' marks. */
export async function collectTaskResponsibilityScopes(
- botIds: readonly string[], readIds: (botId: string) => Promise<string[]>,
-): Promise<Array<{ botId: string; directories: string[]; sessionIds: string[] }>> {
- const scopes = await Promise.all(botIds.map(async (botId) => {
+ botIds: readonly string[],
+ readScope: (botId: string) => Promise<{ sessionIds: string[]; delegatedSessionIds?: string[] }>,
+): Promise<TaskResponsibilityScope[]> {
+ const scopes = await Promise.all(botIds.map(async (botId): Promise<TaskResponsibilityScope> => {
try {
- return { botId, directories: [], sessionIds: await readIds(botId) };
+ const scope = await readScope(botId);
+ return { botId, directories: [], sessionIds: scope.sessionIds, delegatedSessionIds: scope.delegatedSessionIds ?? [] };
} catch {
// Do not fall back to creation evidence: a damaged file may contain releases.
- return { botId, directories: [], sessionIds: [] };
+ return { botId, directories: [], sessionIds: [], delegatedSessionIds: [] };
}
}));
return scopes.filter((scope) => scope.sessionIds.length > 0);
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
index 19c3fb0233..fdd5729315 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchTools.ts
@@ -234,6 +234,21 @@ export async function readBotResponsibleSessionIds(userDataDir: string, botId: s
);
}
+/**
+ * The same responsibility, split: `delegatedSessionIds` are the background tasks this Bot
+ * started itself (delegation children); `sessionIds` adds the ordinary tasks it explicitly
+ * took over. The owner chip reads the first, the sidebar follow mark the second.
+ */
+export async function readBotResponsibilityScope(
+ userDataDir: string, botId: string,
+): Promise<{ sessionIds: string[]; delegatedSessionIds: string[] }> {
+ const delegated = [...(await listBotDelegationChildren(botId)).keys()].sort();
+ return {
+ sessionIds: responsibleSessionIds(delegated, await readTaskResponsibilities(userDataDir, botId)),
+ delegatedSessionIds: delegated,
+ };
+}
+
/** Capture the creator before a generic create-mode handoff crosses async boundaries. */
export async function captureBotCreatedTaskResponsibility(callerSessionId?: string) {
if (!callerSessionId || isAppSessionBoundaryPending()) return null;
diff --git a/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx b/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx
index a461b36e1f..2924f6788d 100644
--- a/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx
@@ -5,14 +5,14 @@ import { useNavigate } from 'react-router-dom';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import type { Session } from '@/lib/ccAgent.types';
import { BotAvatar } from './BotAvatar';
-import { useSessionFollowers } from './botFollowScopes';
+import { useSessionDelegatingBot } from './botFollowScopes';
import { ensureBotProfilesLoaded } from './botStore';
/**
* A Bot's background task opens in the ordinary task view; this quiet chip in
- * its header says whose task it is and leads back to that Bot. Ownership is the
- * same verifiable per-task responsibility the sidebar mark uses (the Bot that
- * created the task, or explicitly took it over), never a guess from the session row.
+ * its header says whose task it is and leads back to that Bot. Only a task the
+ * Bot started itself (a delegation child) is its background task; an ordinary
+ * task the Bot took over keeps the sidebar's follow mark and no chip.
*/
export function BotTaskOwnerChip({ session }: { session: Session }) {
const { t } = useTranslation();
@@ -20,7 +20,7 @@ export function BotTaskOwnerChip({ session }: { session: Session }) {
useEffect(() => {
void ensureBotProfilesLoaded().catch(() => {});
}, []);
- const bot = useSessionFollowers(session)[0];
+ const bot = useSessionDelegatingBot(session);
if (!bot) return null;
return (
<button
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx
index 29b7588598..e0e5969862 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotTaskOwnerChip.test.tsx
@@ -6,22 +6,22 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { BotTaskOwnerChip } from '../BotTaskOwnerChip';
-const mocks = vi.hoisted(() => ({ navigate: vi.fn(), ensure: vi.fn(), followers: new Map<string, unknown[]>() }));
+const mocks = vi.hoisted(() => ({ navigate: vi.fn(), ensure: vi.fn(), delegators: new Map<string, unknown>() }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string, options?: Record<string, unknown>) => `${key}:${JSON.stringify(options)}` }),
}));
vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));
vi.mock('../BotAvatar', () => ({ BotAvatar: ({ bot }: any) => <span data-avatar={bot.name} /> }));
vi.mock('../botStore', () => ({ ensureBotProfilesLoaded: mocks.ensure }));
-// The same per-task responsibility the sidebar mark reads; the chip adds no second ownership rule.
+// The delegation projection of the same follow scopes the sidebar mark reads; the chip adds no second ownership rule.
vi.mock('../botFollowScopes', () => ({
- useSessionFollowers: (session: { id: string }) => mocks.followers.get(session.id) ?? [],
+ useSessionDelegatingBot: (session: { id: string }) => mocks.delegators.get(session.id) ?? null,
}));
const lizi = { id: 'bot/a', name: 'LiZi' };
const session = (id: string) => ({ id, status: 'active', source: 'desktop' }) as any;
beforeEach(() => {
- mocks.followers = new Map([['task', [lizi]]]);
+ mocks.delegators = new Map([['task', lizi]]);
mocks.ensure.mockReset().mockResolvedValue([]);
mocks.navigate.mockReset();
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx
index fbcadfd206..9bd7d2cd2b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx
@@ -22,7 +22,7 @@ vi.mock('../botStore', () => ({
}));
import { BotFollowMark, useSessionFollowers } from '../BotFollowMark';
-import { __testing } from '../botFollowScopes';
+import { __testing, useSessionDelegatingBot } from '../botFollowScopes';
import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
function Row({ session: value }: { session: Session }) {
@@ -37,7 +37,8 @@ const session = (patch: Partial<Session> = {}) => ({
}) as Session;
let changed: (() => void) | null = null;
-const followScopes = vi.fn(async () => [{ botId: 'bot-1', sessionIds: ['s1', 's2'] }]);
+const followScopes = vi.fn(async (): Promise<Array<{ botId: string; sessionIds?: string[]; delegatedSessionIds?: string[] }>> =>
+ [{ botId: 'bot-1', sessionIds: ['s1', 's2'] }]);
beforeEach(() => {
__testing.reset();
@@ -116,6 +117,29 @@ it('does not infer responsibility from an older host directory-only payload', as
await act(async () => render(<Row session={session()} />));
expect(screen.queryByTestId('bot-follow-mark')).toBeNull();
});
+describe('useSessionDelegatingBot', () => {
+ function Owner({ session: value }: { session: Session }) {
+ const bot = useSessionDelegatingBot(value);
+ return <span data-testid="owner">{bot ? bot.name : 'none'}</span>;
+ }
+
+ it("names the Bot only for its own background task, not for an ordinary task it took over", async () => {
+ followScopes.mockResolvedValueOnce([
+ { botId: 'bot-1', sessionIds: ['s1', 's2'], delegatedSessionIds: ['s2'] },
+ { botId: 'bot-2', sessionIds: ['s1'], delegatedSessionIds: [] },
+ ]);
+ await act(async () => render(<><Owner session={session()} /><Owner session={session({ id: 's2' })} /></>));
+ // s1 is the owner's task both Bots follow; s2 is Dash's background task.
+ expect(screen.getAllByTestId('owner').map((node) => node.textContent)).toEqual(['none', 'Dash']);
+ expect(followScopes).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not guess from an older host that only lists responsibilities', async () => {
+ await act(async () => render(<Owner session={session()} />));
+ expect(screen.getByTestId('owner').textContent).toBe('none');
+ });
+});
+
it('removes marks when a task is released', async () => {
await act(async () => render(<Row session={session()} />));
expect(screen.getByTestId('bot-follow-mark')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts b/apps/desktop/src/renderer/features/bots/botFollowScopes.ts
index 4f190ccc24..9389b3851e 100644
--- a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts
+++ b/apps/desktop/src/renderer/features/bots/botFollowScopes.ts
@@ -14,7 +14,10 @@ const log = createLogger('BotFollowScopes');
export interface BotFollowScope {
botId: string;
+ /** Every task the Bot is responsible for: its own background tasks and the ones it took over. */
sessionIds?: readonly string[];
+ /** Only the background tasks the Bot started itself; older hosts omit it. */
+ delegatedSessionIds?: readonly string[];
}
const EMPTY: readonly BotFollowScope[] = [];
@@ -113,25 +116,40 @@ function isFollowableSession(session: Session): boolean {
return isWorkbenchTaskSource(session.source);
}
-/** 正在负责这件任务的伙伴(按名字排序;隐藏、停用的伙伴不显示)。 */
-export function useSessionFollowers(session: Session): BotProfile[] {
+function useScopedBots(session: Session, ids: (scope: BotFollowScope) => readonly string[] | undefined): BotProfile[] {
const followScopes = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
const profiles = useBotProfiles();
const followable = isFollowableSession(session);
const sessionId = session.id;
return useMemo(() => {
if (!followable || followScopes.length === 0) return [];
- const following = new Set(
+ const matching = new Set(
followScopes
- .filter((scope) => Array.isArray(scope.sessionIds) && scope.sessionIds.includes(sessionId))
+ .filter((scope) => { const list = ids(scope); return Array.isArray(list) && list.includes(sessionId); })
.map((scope) => scope.botId),
);
- if (following.size === 0) return [];
+ if (matching.size === 0) return [];
return profiles
- .filter((bot) => following.has(bot.id) && bot.enabled && !bot.hiddenAt
+ .filter((bot) => matching.has(bot.id) && bot.enabled && !bot.hiddenAt
&& (bot.status === undefined || bot.status === 'active'))
.sort((a, b) => a.name.localeCompare(b.name));
- }, [followable, followScopes, profiles, sessionId]);
+ }, [followable, followScopes, ids, profiles, sessionId]);
+}
+
+const responsibleIds = (scope: BotFollowScope) => scope.sessionIds;
+const delegatedIds = (scope: BotFollowScope) => scope.delegatedSessionIds;
+
+/** 正在负责这件任务的伙伴(按名字排序;隐藏、停用的伙伴不显示)。 */
+export function useSessionFollowers(session: Session): BotProfile[] {
+ return useScopedBots(session, responsibleIds);
+}
+
+/**
+ * 这件任务是哪位伙伴自己开的后台任务(委派子任务);主人的任务被伙伴接手只算「在跟进」,
+ * 不算伙伴的后台任务。旧宿主没有这份投影时不猜。
+ */
+export function useSessionDelegatingBot(session: Session): BotProfile | null {
+ return useScopedBots(session, delegatedIds)[0] ?? null;
}
export const __testing = {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 75f2c031a3..d6f98cad92 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4852,8 +4852,8 @@ interface ElectronAPI {
}
| { ok: false; errorCode: string; message: string }
>;
- /** 每个在用本机伙伴的逐任务责任 ID;旧宿主缺字段时不推断。 */
- followScopes: () => Promise<Array<{ botId: string; sessionIds?: string[] }>>;
+ /** 每个在用本机伙伴的逐任务责任 ID;旧宿主缺字段时不推断。`delegatedSessionIds` 只含伙伴自己开的后台任务。 */
+ followScopes: () => Promise<Array<{ botId: string; sessionIds?: string[]; delegatedSessionIds?: string[] }>>;
};
listSkills: (botId: string) => Promise<import('../shared/botSkill').BotSkillSummary[]>;
memory: {
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 018e343546..e1b01bcbaa 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -155,7 +155,8 @@
- 伙伴侧栏在「伙伴」分组下方增加「群聊」分组,带新建按钮;群行显示两位成员的叠放头像、群名与最近一条消息,
有伙伴正在发言时显示运行中标记。未读角标是真实条数:宿主随摘要给出最近(至多 99 条)别人发来的消息时间
- (`incomingMessageTimes`),与本机读位比较;旧宿主没有这份列表时只显示 1。
+ (`incomingMessageTimes`),与本机读位比较;旧宿主没有这份列表时只显示 1。伙伴发的安排卡与回复同样算来信:
+ 本机群的 `lastReplyAt` 取两者里最新的一条,首次种读位时不会把最新的安排卡留成未读。
- 群聊页(2026-10-15 按 Telegram / Slack 的密度重做):顶部为成员头像、群名、成员名单(负责人带标)与此刻谁在做什么
(「X 正在做第 2 步」「X 正在说…」「X 正在安排…」),右侧为群设置入口。时间线:自己的消息靠右浅色气泡;
伙伴与别人的消息靠左平铺(28px 头像 + 名字 + 时刻),同一作者五分钟内的连续消息合并——后续行不再带头像和名字,