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): retain queued completions and remote chat opt-in

zqchris3ccea2978dfc
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
new file mode 100644
index 0000000000..882c7b96c1
--- /dev/null
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
@@ -0,0 +1,63 @@
+/* Unit regression for cindy-bots-runtime §6.3: persisted queued completions must
+ * survive watch eviction/restart, but current opt-out still revokes owner events.
+ * Existing runtime tests inject dispatch and cannot exercise the hub's durable
+ * authorization. Minimal input: empty watch + completed event + durable active
+ * task/assignment. This owner-scoped IO fixture is separate from runtime's injected
+ * watch fixture. Actual production hub is loaded once; only host IO is replaced.
+ */
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { BotAutonomyRuntime } from '../runtime.js';
+import type { RoutineEngine } from '@cindy/maker-scheduler';
+import type { LocalSessionMeta } from '../taskWatch.js';
+
+const h = vi.hoisted(() => ({
+ scope: 'a', scheduler: 'sched' as string | null,
+ readMetas: vi.fn(), readOwnership: vi.fn(),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => h.scope, isAppSessionBoundaryPending: () => false,
+ ownerScopedUserDataPath: () => '/unused-owner-root',
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ info() {}, warn() {} }) }));
+vi.mock('../../maker-host/bot-autonomy-settings-store.js', () => ({
+ readBotAutonomySettingsOverride: () => ({ customized: true, schedulerBotId: h.scheduler }),
+ resetBotAutonomySettings: vi.fn(), writeBotAutonomySchedulerBotId: vi.fn(),
+}));
+vi.mock('../hostData.js', () => ({
+ readLocalSessionMetas: h.readMetas, readTaskOwnership: h.readOwnership, readBotDirectory: vi.fn(),
+}));
+import { currentFollowUpEvents, setActiveBotAutonomy } from '../hub.js';
+
+const meta = (id: string, source = 'desktop'): LocalSessionMeta => ({
+ id, source, title: 'Completed task', workingDir: null, status: 'active', hiddenAt: null,
+ orcaRole: null, laneRole: null, laneBotId: null, interrupted: false,
+ activeTurnStartedAt: 1, lastTurnEndedAt: 2,
+});
+const events = ['mine', 'delegated', 'shared', 'deleted'].map(subject => ({
+ sourceId: 'host:sessions', event: { id: subject, type: 'finished', subject, occurredAt: 2, data: {} },
+}));
+beforeEach(() => {
+ h.scope = 'a'; h.scheduler = 'sched';
+ const bots = new Map([['sched', { status: 'active', allowSchedulerFollow: false }]]);
+ h.readMetas.mockReset().mockResolvedValue([meta('mine'), meta('delegated'), meta('shared', 'shared')]);
+ h.readOwnership.mockReset().mockResolvedValue({ bots, creatorBySession: new Map([['delegated', 'sched']]), responsibleByBot: new Map() });
+ setActiveBotAutonomy({ scope: 'a', engine: {} as RoutineEngine,
+ runtime: { watch: { isReady: () => true, list: () => [], getBots: () => bots } } as unknown as BotAutonomyRuntime });
+});
+afterEach(() => setActiveBotAutonomy(null));
+
+it('dispatches persisted completions after restart without watch rows, but enforces current consent', async () => {
+ const batch = await currentFollowUpEvents('sched', events);
+ expect(batch?.events).toEqual([events[0], events[1]]);
+ expect(batch?.canDispatch()).toBe(true);
+ h.scheduler = null;
+ expect(batch?.canDispatch()).toBe(false);
+ const revoked = await currentFollowUpEvents('sched', events);
+ expect(revoked?.events.map(item => item.event.subject)).toEqual(['delegated']);
+ expect(revoked?.canDispatch()).toBe(true);
+});
+
+it('defers rather than authorizing a durable read that crossed the account boundary', async () => {
+ h.readMetas.mockImplementationOnce(async () => { h.scope = 'b'; return [meta('mine')]; });
+ expect(await currentFollowUpEvents('sched', events)).toBeNull();
+});
diff --git a/apps/desktop/src/main/bot-autonomy/follower.ts b/apps/desktop/src/main/bot-autonomy/follower.ts
index 7f37c2adfe..72b9a15c54 100644
--- a/apps/desktop/src/main/bot-autonomy/follower.ts
+++ b/apps/desktop/src/main/bot-autonomy/follower.ts
@@ -74,6 +74,8 @@ export function readAllowSchedulerFollow(capabilitiesJson: string | null | undef
}
/** Recheck queued events against current ownership/consent before sending any data to a model. */
+export type FollowUpSubject = Pick<WatchedSession, 'sessionId' | 'deviceId' | 'shared' | 'canonicalOfBotId' | 'creatorBotId'>;
+
export function filterFollowUpEvents(
botId: string,
events: RoutineRun['events'],
@@ -81,14 +83,15 @@ export function filterFollowUpEvents(
schedulerBotId: string | null,
bots: FollowerBotDirectory,
now: number,
+ subjects: readonly FollowUpSubject[] = rows,
): RoutineRun['events'] {
- const allowed = rows.filter((row) => row.deviceId === null && !row.shared
+ const isAllowed = (row: FollowUpSubject) => row.deviceId === null && !row.shared
&& row.canonicalOfBotId !== botId
- && deriveFollowerBotId({ creatorBotId: row.creatorBotId, schedulerBotId, bots }) === botId);
- const ids = new Set(allowed.map((row) => row.sessionId));
+ && deriveFollowerBotId({ creatorBotId: row.creatorBotId, schedulerBotId, bots }) === botId;
+ const ids = new Set(subjects.filter(isAllowed).map((row) => row.sessionId));
return events.filter(({ sourceId, event }) => sourceId === HOST_SESSIONS_SOURCE_ID && (
event.type === 'sweep'
- ? allowed.some((row) => isPendingForFallback(row, now))
+ ? rows.some((row) => isAllowed(row) && isPendingForFallback(row, now))
: typeof event.subject === 'string' && ids.has(event.subject)
));
}
diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.ts
index 5f6d23d04c..df90990362 100644
--- a/apps/desktop/src/main/bot-autonomy/hub.ts
+++ b/apps/desktop/src/main/bot-autonomy/hub.ts
@@ -11,7 +11,7 @@ import {
type BotAutonomySettingsView,
type BotGlance,
} from '../../shared/botAutonomy.js';
-import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
import { createLogger } from '../logger.js';
import {
readBotAutonomySettingsOverride,
@@ -19,8 +19,8 @@ import {
writeBotAutonomySchedulerBotId,
} from '../maker-host/bot-autonomy-settings-store.js';
import { throwIpcError } from '../utils/ipcValidate.js';
-import { filterFollowUpEvents, resolveSchedulerBotId } from './follower.js';
-import { readBotDirectory } from './hostData.js';
+import { filterFollowUpEvents, resolveSchedulerBotId, type FollowUpSubject } from './follower.js';
+import { readBotDirectory, readLocalSessionMetas, readTaskOwnership } from './hostData.js';
import type { BotAutonomyRuntime, GlanceOptions } from './runtime.js';
import { errorCode, type BotAutonomyInputProjection } from './taskWatch.js';
@@ -120,12 +120,32 @@ async function afterSettingsChange(scope: string): Promise<BotAutonomySettingsVi
}
/** null means startup is not ready; an empty batch has lost its authorization. */
-export function currentFollowUpEvents(botId: string, events: RoutineRun['events']): RoutineRun['events'] | null {
+export async function currentFollowUpEvents(botId: string, events: RoutineRun['events']): Promise<{
+ events: RoutineRun['events']; canDispatch(): boolean;
+} | null> {
const active = current;
if (!active || !scopeIsCurrent(active.scope) || !active.runtime.watch.isReady()) return null;
const watch = active.runtime.watch;
- const bots = watch.getBots();
- // Read the persisted choice, not the watch's cached scheduler: disabling must take effect immediately.
- const scheduler = resolveSchedulerBotId(readBotAutonomySettingsOverride(), bots);
- return filterFollowUpEvents(botId, events, watch.list(), scheduler, bots, Date.now());
+ const botsAtRead = watch.getBots();
+ // The queue outlives watched rows (including across restarts). Read current durable
+ // ownership for event subjects; only sweep needs the transient pending-state table.
+ const [metas, ownership] = await Promise.all([
+ readLocalSessionMetas(events.flatMap(({ event }) => event.type !== 'sweep' && typeof event.subject === 'string' ? [event.subject] : [])),
+ readTaskOwnership(ownerScopedUserDataPath()),
+ ]);
+ if (current !== active || !scopeIsCurrent(active.scope) || watch.getBots() !== botsAtRead) return null;
+ const subjects: FollowUpSubject[] = metas.filter(meta => meta.status === 'active' && meta.hiddenAt === null
+ && meta.orcaRole !== 'worker' && meta.source !== 'review'
+ && !['history', 'group', 'channel'].includes(meta.laneRole ?? '')).map(meta => {
+ const canonical = [...ownership.bots].find(([, bot]) => bot.canonicalSessionId === meta.id)?.[0]
+ ?? (meta.laneRole === 'canonical' ? meta.laneBotId : null);
+ const creator = ownership.creatorBySession.get(meta.id) ?? null;
+ return { sessionId: meta.id, deviceId: null, shared: meta.source === 'shared',
+ canonicalOfBotId: canonical, creatorBotId: creator === canonical ? null : creator };
+ });
+ const allowedNow = () => filterFollowUpEvents(botId, events, watch.list(),
+ resolveSchedulerBotId(readBotAutonomySettingsOverride(), ownership.bots), ownership.bots, Date.now(), subjects);
+ const allowed = allowedNow();
+ return { events: allowed, canDispatch: () => current === active && scopeIsCurrent(active.scope) && watch.isReady()
+ && watch.getBots() === botsAtRead && allowedNow().length === allowed.length };
}
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index 934371f838..b34f79f65d 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -26,7 +26,10 @@ const mock = vi.hoisted(() => ({
delete: vi.fn(async () => {}),
},
}));
-vi.mock('../../bot-autonomy/hub.js', () => ({ currentFollowUpEvents: mock.followUpEvents }));
+vi.mock('../../bot-autonomy/hub.js', () => ({ currentFollowUpEvents: async (botId: string, input: RoutineRun['events']) => {
+ const events = mock.followUpEvents(botId, input);
+ return events === null ? null : { events, canDispatch: () => mock.followUpEvents(botId, input)?.length === events.length };
+} }));
vi.mock('../../appSessionState.js', () => ({
activeOwnerScopeKey: () => mock.scope,
getActiveAppSession: () => ({ dataOwnerId: mock.scope }),
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 9a66d6efb7..100e8c83bd 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -152,13 +152,13 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
// task summaries under an obsolete follow-up choice. Manual runs remain explicit actions.
let events = run.events;
if (routine.builtin === 'follow-up' && events.length > 0) {
- const allowed = currentFollowUpEvents(routine.botId, events);
+ const allowed = await currentFollowUpEvents(routine.botId, events);
+ assertScope(scope);
if (allowed === null) return { deferred: true };
- if (allowed.length === 0) return { skipped: true };
- events = allowed;
+ if (allowed.events.length === 0) return { skipped: true };
+ events = allowed.events;
const engineCanDispatch = canDispatch;
- canDispatch = () => engineCanDispatch()
- && currentFollowUpEvents(routine.botId, events)?.length === events.length;
+ canDispatch = () => engineCanDispatch() && allowed.canDispatch();
}
const root = ownerScopedUserDataPath();
const imported = await getRoutineHost().prepareImportedAutomation?.(root, routine, run.id, signal, () => assertScope(scope));
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
index 7f221bd240..857525ad1b 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
@@ -30,7 +30,7 @@ export function RemoteBotSessionView() {
const bot = bots.find((row) => row.id === botId && row.deviceId === deviceId);
const cloud = useCompanionCloud();
const cloudActor = cloudCompanionAt(cloud, deviceId, botId);
- const [ready, setReady] = useState<(RemoteBot & { sessionId: string }) | null>(null);
+ const [ready, setReady] = useState<(RemoteBot & { sessionId: string; canonicalChat: true }) | null>(null);
const [validatedSessionId, setValidatedSessionId] = useState<string | null | undefined>(null);
const [failed, setFailed] = useState(false);
const [retry, setRetry] = useState(0);
@@ -82,7 +82,7 @@ export function RemoteBotSessionView() {
isSessionReadCurrent.mergeActivity(session),
]);
readOwner.current = owner;
- setReady({ ...resolved, sessionId: canonicalId });
+ setReady({ ...resolved, sessionId: canonicalId, canonicalChat: true });
setValidatedSessionId(sessionId);
})().catch(() => {
if (!disposed) setFailed(true);
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
index ca5127215c..dc5196ba31 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
@@ -2,6 +2,8 @@
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { parseRemoteResourceGetRequest } from '@cindy/device-link';
+import { resolveBotChatIdentity } from '../botChatPresentation';
+import type { BotChatBinding } from '../botChatPresentation';
const h = vi.hoisted(() => ({
invoke: vi.fn(),
markRead: vi.fn(),
@@ -76,7 +78,9 @@ beforeEach(() => {
window.electronAPI = { deviceLink: { invoke: h.invoke } } as unknown as Window['electronAPI'];
});
afterEach(cleanup);
-it('resolves the latest canonical task and pins its host before mounting writable chat', async () => {
+// Unit regression: a host conversation link + active bot session must reach the shared
+// parent chat as canonical, or its post-send follow-up invitation can never appear.
+it('resolves the latest canonical task and passes its verified identity to writable chat', async () => {
const { rerender } = render(<RemoteBotSessionView />);
await screen.findByText('remote-conversation');
expect(h.merge).toHaveBeenCalledWith('home', 'Home', [
@@ -85,11 +89,12 @@ it('resolves the latest canonical task and pins its host before mounting writabl
expect(h.view).toHaveBeenLastCalledWith(
expect.objectContaining({
sessionIdProp: 'new-canonical', routeOwner: true, readOnly: false,
- botIdentity: expect.objectContaining({ id: 'writer', sessionId: 'new-canonical' }),
+ botIdentity: expect.objectContaining({ id: 'writer', sessionId: 'new-canonical', canonicalChat: true }),
}),
);
expect(h.markRead).not.toHaveBeenCalled();
const identity = h.view.mock.lastCall![0].botIdentity;
+ expect(resolveBotChatIdentity(identity as BotChatBinding, 'new-canonical')?.canonicalChat).toBe(true);
const requestCount = h.invoke.mock.calls.length;
h.lastReplyAt = 123;
rerender(<RemoteBotSessionView />);