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(desktop): 补齐直发消息变更捕获

DavidShen4f60e09ea810
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index 00c7124e18..6779db9104 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -63,18 +63,21 @@ describe('sendToSession ordering', () => {
'async function createWorker',
);
- expect(helperBlock).toContain('return resolveCollabDispatchResult(');
+ expect(helperBlock).toContain('const result = await resolveCollabDispatchResult(');
expect(helperBlock).toContain('() => session.send(agentMessage, {');
expect(helperBlock).toContain('planMode: false,');
expect(helperBlock).toContain('throwOnStartFailure: true,');
expect(helperBlock).toContain('onAccepted: async () => {');
expect(helperBlock).toContain('await deps.createDbMessage(session.id, {');
+ expect(helperBlock).toContain('await deps.beginDirectTurnChangeSet(session.id, clientId);');
+ expect(helperBlock).toContain('deps.abortDirectTurnChangeSet(session.id);');
expect(helperBlock).toContain('{ source, context },');
expectOrder(helperBlock, 'onAccepted: async () => {', 'await deps.createDbMessage(session.id, {');
// 顺序硬约束: 先落库再跑 accepted 副作用。createDbMessage 失败时 Session.send 按
// 派发前失败处理不启动 turn, 副作用若先跑会留下没有 terminal event 清理的幽灵
// running/autoBridgePending 状态(Codex review P2)。
- expectOrder(helperBlock, 'await deps.createDbMessage(session.id, {', 'await runAcceptedCallback(onAccepted, session.id, clientId, deps.log ?? defaultLog);');
+ expectOrder(helperBlock, 'await deps.createDbMessage(session.id, {', 'await deps.beginDirectTurnChangeSet(session.id, clientId);');
+ expectOrder(helperBlock, 'await deps.beginDirectTurnChangeSet(session.id, clientId);', 'await runAcceptedCallback(onAccepted, session.id, clientId, deps.log ?? defaultLog);');
expect(source).not.toContain('async function dispatchInitialTaskToOrcaWorker');
expect(serviceDispatchBlock).toContain('result = await deps.dispatchWorkerMessage({');
@@ -285,28 +288,35 @@ describe('sendToSession ordering', () => {
expect(source).toContain('assertDesktopSendDispatched');
expect(orcaInterAgentDispatcherSource).toContain('resolveCollabDispatchResult');
expect(helperBlock).toContain('Promise<CollabDirectDispatchResult>');
- expect(helperBlock).toContain('return resolveCollabDispatchResult(');
+ expect(helperBlock).toContain('const result = await resolveCollabDispatchResult(');
expect(helperBlock).toContain('() => session.send(agentMessage, {');
expect(helperBlock).toContain('planMode: false,');
expect(helperBlock).toContain('throwOnStartFailure: true,');
expect(helperBlock).not.toContain('await session.send(agentMessage, {');
expect(helperBlock).not.toContain('assertDesktopSendDispatched(sendResult');
- expect(createBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, {');
+ expect(createBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, clientId, {');
expect(createBranch).toContain('planMode: false,');
expect(createBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session create');");
expect(liveBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(');
expect(liveBranch).toContain('live,');
+ expectOrder(liveBranch, 'message,', 'clientId,');
expect(liveBranch).toContain('onAccepted: persistUserMessage,');
expect(liveBranch).toContain('onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),');
expect(liveBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session live');");
expect(resumedBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(');
expect(resumedBranch).toContain('session,');
+ expectOrder(resumedBranch, 'message,', 'clientId,');
expect(resumedBranch).toContain('onAccepted: persistUserMessage,');
expect(resumedBranch).toContain('onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),');
expect(resumedBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session resumed');");
});
it('awaits Git baseline capture after send_to_session user row persistence and before dispatch', () => {
+ const changeSetBlock = extractBetween(
+ source,
+ 'async function beginTurnChangeSetAtDispatch',
+ 'async function sendUserMessageWithAwaitedGitBaseline',
+ );
const helperBlock = extractBetween(
source,
'async function sendUserMessageWithAwaitedGitBaseline',
@@ -316,16 +326,39 @@ describe('sendToSession ordering', () => {
expect(helperBlock).toContain('onAccepted: async () => {');
expect(helperBlock).toContain('await opts.onAccepted?.();');
+ expect(helperBlock).toContain('await beginTurnChangeSetAtDispatch(session, anchorClientId);');
expect(helperBlock).toContain('await gitSnapshotCoordinator.onTurnStart(session.id);');
expect(helperBlock).toContain('const pendingHandoff = await agentHandoffPending.peek(session.id);');
- expect(helperBlock).toContain('prependHandoffToUserMessage({ type: \'user\', content: message }, pendingHandoff)');
+ expect(helperBlock).toContain('prependHandoffToUserMessage(');
+ expect(helperBlock).toContain("{ type: 'user', content: message },");
expect(helperBlock).toContain('const sendResult = await session.send(outgoingMessage, {');
expect(helperBlock).toContain('agentHandoffPending.consume(session.id);');
+ expect(helperBlock).toContain('if (turnChangeSetStarted && !sendResult.accepted) {');
+ expect(helperBlock).toContain('clearPendingTurnChangeSets(session.id);');
expect(helperBlock).toContain('if (baselineStarted && !sendResult.accepted) {');
expect(helperBlock).toContain('gitSnapshotCoordinator?.onTurnAbort(session.id);');
+ expect(changeSetBlock).toContain('await waitForTurnChangeSetSeal(session.id);');
+ expect(changeSetBlock).toContain("await finalizeTurnChangeSet(session.id, null, 'partial');");
+ expect(changeSetBlock).toContain('anchorClientId,');
+ expect(changeSetBlock).toContain('provider: session.agentKind,');
+ expect(changeSetBlock).toContain('cwd: session.workDir,');
+ expect(changeSetBlock).toContain('remote: session.remoteHostId !== null,');
+ const firstSeal = changeSetBlock.indexOf('await waitForTurnChangeSetSeal(session.id);');
+ const finalize = changeSetBlock.indexOf("await finalizeTurnChangeSet(session.id, null, 'partial');");
+ const secondSeal = changeSetBlock.indexOf('await waitForTurnChangeSetSeal(session.id);', firstSeal + 1);
+ const begin = changeSetBlock.indexOf('await beginTurnChangeSet({');
+ expect(firstSeal).toBeGreaterThanOrEqual(0);
+ expect(finalize).toBeGreaterThan(firstSeal);
+ expect(secondSeal).toBeGreaterThan(finalize);
+ expect(begin).toBeGreaterThan(secondSeal);
expectOrder(
helperBlock,
'await opts.onAccepted?.();',
+ 'await beginTurnChangeSetAtDispatch(session, anchorClientId);',
+ );
+ expectOrder(
+ helperBlock,
+ 'await beginTurnChangeSetAtDispatch(session, anchorClientId);',
'await gitSnapshotCoordinator.onTurnStart(session.id);',
);
expect(countOccurrences(block, 'sendUserMessageWithAwaitedGitBaseline(')).toBe(3);
@@ -342,7 +375,7 @@ describe('sendToSession ordering', () => {
);
expect(createBranch).toContain('onAccepted: async () => {');
- expect(createBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, {');
+ expect(createBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, clientId, {');
expect(createBranch).toContain('planMode: false,');
expectOrder(createBranch, 'onAccepted: async () => {', 'notifyAgentIslandUserPrompt(session, persistedContent ?? message, {');
expectOrder(createBranch, 'notifyAgentIslandUserPrompt(session, persistedContent ?? message, {', 'await createDbMessage(session.id, {');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
index e9ed86f5d7..c71801aab1 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
@@ -82,6 +82,12 @@ function createHarness(overrides: Partial<OrcaInterAgentDispatcherDeps<TestSessi
createDbMessage: vi.fn(async () => {
order.push('db');
}),
+ beginDirectTurnChangeSet: vi.fn(async () => {
+ order.push('change-set');
+ }),
+ abortDirectTurnChangeSet: vi.fn(() => {
+ order.push('abort-change-set');
+ }),
resolveWorkerSenderLabel: vi.fn(async (_workerId, fallback) => fallback),
isSessionRunningError: vi.fn((err) =>
err instanceof Error && (err as { code?: string }).code === 'SESSION_RUNNING'
@@ -128,7 +134,9 @@ describe('Orca lead/worker dispatcher', () => {
targetTitle: 'Target Session',
targetLastUserSendAt: '2026-06-12T01:02:03.000Z',
});
- expect(h.order).toEqual(['send-called', 'db', 'accepted', 'vendor-released']);
+ expect(h.order).toEqual(['send-called', 'db', 'change-set', 'accepted', 'vendor-released']);
+ expect(h.deps.beginDirectTurnChangeSet).toHaveBeenCalledWith('target-session', 'client-1');
+ expect(h.deps.abortDirectTurnChangeSet).not.toHaveBeenCalled();
expect(h.deps.createDbMessage).toHaveBeenCalledWith('target-session', {
clientId: 'client-1',
role: 'user',
@@ -162,6 +170,7 @@ describe('Orca lead/worker dispatcher', () => {
expect(result).toMatchObject({ ok: true, mode: 'queued' });
expect(accepted).not.toHaveBeenCalled();
expect(h.queuedItems).toHaveLength(1);
+ expect(h.deps.beginDirectTurnChangeSet).not.toHaveBeenCalled();
await h.dispatcher.runQueuedOrcaInterAgentAcceptedCallback('target-session', firstQueuedItem(h.queuedItems));
@@ -267,10 +276,41 @@ describe('Orca lead/worker dispatcher', () => {
reason: 'cancelled-before-dispatch',
},
});
- expect(h.order).toEqual(['send-called', 'db', 'accepted', 'send-returned-cancelled', 'rollback']);
+ expect(h.order).toEqual([
+ 'send-called',
+ 'db',
+ 'change-set',
+ 'accepted',
+ 'send-returned-cancelled',
+ 'abort-change-set',
+ 'rollback',
+ ]);
+ expect(h.deps.abortDirectTurnChangeSet).toHaveBeenCalledWith('target-session');
expect(rollback).toHaveBeenCalledTimes(1);
});
+ it('leaves lazy-resume turn capture to sendToSessionInternal', async () => {
+ const h = createHarness({
+ getLiveSession: vi.fn(() => null),
+ });
+
+ const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
+ targetSessionId: 'target-session',
+ rawContent: 'Resume target',
+ source: 'lead',
+ senderLabel: 'Lead',
+ meta: { source: 'orca', context: 'resume-test' },
+ });
+
+ expect(result).toMatchObject({ ok: true, mode: 'dispatched' });
+ expect(h.deps.sendToSessionInternal).toHaveBeenCalledWith(expect.objectContaining({
+ targetSessionId: 'target-session',
+ clientId: 'client-1',
+ }));
+ expect(h.deps.beginDirectTurnChangeSet).not.toHaveBeenCalled();
+ expect(h.deps.abortDirectTurnChangeSet).not.toHaveBeenCalled();
+ });
+
it('rolls back queued accepted side effects when dispatch settles as not dispatched', async () => {
const accepted = vi.fn();
const rollback = vi.fn();
diff --git a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
index b75d88bbc3..20ec616985 100644
--- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
@@ -143,6 +143,8 @@ export interface OrcaInterAgentDispatcherDeps<TSessionMeta> {
sessionId: string,
message: { clientId: string; role: 'user'; content: string },
) => Promise<unknown>;
+ beginDirectTurnChangeSet: (sessionId: string, clientId: string) => Promise<void>;
+ abortDirectTurnChangeSet: (sessionId: string) => void;
resolveWorkerSenderLabel: (workerId: string, fallback: string) => Promise<string>;
isSessionRunningError: (err: unknown) => boolean;
log?: OrcaInterAgentDispatcherLogger;
@@ -424,7 +426,8 @@ async function sendPersistedUserMessageToSession<TSessionMeta>(
},
): Promise<CollabDirectDispatchResult> {
const { session, dbContent, agentMessage, clientId = deps.createId(), source, context, onAccepted } = params;
- return resolveCollabDispatchResult(
+ let turnChangeSetStarted = false;
+ const result = await resolveCollabDispatchResult(
() => session.send(agentMessage, {
planMode: false,
throwOnStartFailure: true,
@@ -435,11 +438,17 @@ async function sendPersistedUserMessageToSession<TSessionMeta>(
role: 'user',
content: dbContent,
});
+ await deps.beginDirectTurnChangeSet(session.id, clientId);
+ turnChangeSetStarted = true;
await runAcceptedCallback(onAccepted, session.id, clientId, deps.log ?? defaultLog);
},
}),
{ source, context },
);
+ if (turnChangeSetStarted && !result.dispatched) {
+ deps.abortDirectTurnChangeSet(session.id);
+ }
+ return result;
}
function makeQueuedDispatchOutcome(source: string): CollabDispatchQueuedOutcome {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index e4140a70ad..59cdf06219 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -6603,15 +6603,36 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
type SendToSessionDispatchSession = {
id: string;
+ agentKind: AgentKind;
+ workDir: string;
+ remoteHostId: string | null;
send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult>;
};
+ async function beginTurnChangeSetAtDispatch(
+ session: SendToSessionDispatchSession,
+ anchorClientId: string,
+ ): Promise<void> {
+ await waitForTurnChangeSetSeal(session.id);
+ await finalizeTurnChangeSet(session.id, null, 'partial');
+ await waitForTurnChangeSetSeal(session.id);
+ await beginTurnChangeSet({
+ sessionId: session.id,
+ anchorClientId,
+ provider: session.agentKind,
+ cwd: session.workDir,
+ remote: session.remoteHostId !== null,
+ });
+ }
+
async function sendUserMessageWithAwaitedGitBaseline(
session: SendToSessionDispatchSession,
message: string,
+ anchorClientId: string,
opts: SessionSendOptions,
): Promise<SessionSendResult> {
let baselineStarted = false;
+ let turnChangeSetStarted = false;
const pendingHandoff = await agentHandoffPending.peek(session.id);
const outgoingMessage: UserMessage = pendingHandoff
? (prependHandoffToUserMessage(
@@ -6624,12 +6645,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
...opts,
onAccepted: async () => {
await opts.onAccepted?.();
+ await beginTurnChangeSetAtDispatch(session, anchorClientId);
+ turnChangeSetStarted = true;
if (gitSnapshotCoordinator) {
await gitSnapshotCoordinator.onTurnStart(session.id);
baselineStarted = true;
}
},
});
+ if (turnChangeSetStarted && !sendResult.accepted) {
+ clearPendingTurnChangeSets(session.id);
+ }
if (baselineStarted && !sendResult.accepted) {
gitSnapshotCoordinator?.onTurnAbort(session.id);
}
@@ -6638,6 +6664,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
return sendResult;
} catch (err) {
+ if (turnChangeSetStarted) {
+ clearPendingTurnChangeSets(session.id);
+ }
if (baselineStarted) {
gitSnapshotCoordinator?.onTurnAbort(session.id);
}
@@ -6835,7 +6864,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const clientId = createId();
createdPreviewSessionId = session.id;
createdPreviewClientId = clientId;
- const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, {
+ const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, clientId, {
planMode: false,
onAccepted: async () => {
notifyAgentIslandUserPrompt(session, persistedContent ?? message, {
@@ -7091,11 +7120,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
if (live) {
try {
- const sendResult = await sendUserMessageWithAwaitedGitBaseline(live, message, {
- planMode: false,
- onAccepted: persistUserMessage,
- onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),
- });
+ const sendResult = await sendUserMessageWithAwaitedGitBaseline(
+ live,
+ message,
+ clientId,
+ {
+ planMode: false,
+ onAccepted: persistUserMessage,
+ onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),
+ },
+ );
if (userPromptPreviewStarted) {
if (sendResult.accepted) {
commitAgentIslandUserPrompt(targetSessionId, clientId);
@@ -7189,11 +7223,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await ensureRemoteReadyForSessionStart({ createOpts });
const { session } = await bootstrapSession(createOpts);
await markOrcaRoleIfNeeded(session.id, createOpts.orcaRole);
- const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, {
- planMode: false,
- onAccepted: persistUserMessage,
- onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),
- });
+ const sendResult = await sendUserMessageWithAwaitedGitBaseline(
+ session,
+ message,
+ clientId,
+ {
+ planMode: false,
+ onAccepted: persistUserMessage,
+ onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),
+ },
+ );
if (userPromptPreviewStarted) {
if (sendResult.accepted) {
commitAgentIslandUserPrompt(targetSessionId, clientId);
@@ -7624,6 +7663,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
sendToSessionInternal,
createDbMessage,
+ beginDirectTurnChangeSet: async (sessionId, clientId) => {
+ const liveSession = maker.getSession(sessionId);
+ if (!liveSession) {
+ throw new Error('Target session became unavailable before direct turn dispatch.');
+ }
+ await beginTurnChangeSetAtDispatch(liveSession, clientId);
+ },
+ abortDirectTurnChangeSet: clearPendingTurnChangeSets,
resolveWorkerSenderLabel: async (workerId, fallback) => {
const link = await getWorkerLink({ workerId });
if (!link) return fallback;
@@ -9728,18 +9775,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info }),
beforeDispatchUserTurn: async (sessionId, item) => {
autoResumeBookkeeping.markReplacementDispatching(sessionId, item.clientId);
- await waitForTurnChangeSetSeal(sessionId);
- await finalizeTurnChangeSet(sessionId, null, 'partial');
- await waitForTurnChangeSetSeal(sessionId);
const liveSession = maker.getSession(sessionId);
if (liveSession) {
- await beginTurnChangeSet({
- sessionId,
- anchorClientId: item.clientId,
- provider: liveSession.agentKind,
- cwd: liveSession.workDir,
- remote: liveSession.remoteHostId !== null,
- });
+ await beginTurnChangeSetAtDispatch(liveSession, item.clientId);
}
// hook 续跑回流的**权威归属点**: 在 vendor dispatch 之前(本回调被 await), 所以
// 观察器挂上就不丢正文开头, 而 live session 此刻必然已就绪。clientId 对得上的