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): 清理远程旧问题并修复跳过后的回执处理 (#5556)

Dash19bbcebf727d
diff --git a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts
index e35ffb947f..81cc8371a7 100644
--- a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts
+++ b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts
@@ -362,6 +362,10 @@ describe('ask_user 与 done 的时序', () => {
emitDone('codex');
const original = action === 'ask' ? makerChatStore.getSnapshot(SESSION_ID).pendingAskUser
: makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview;
+ // Rejection can mean execution is paused: the Host still owns this request.
+ getPendingInteractions.mockResolvedValue([{ request: {
+ kind: action === 'ask' ? 'ask_user_question' : 'plan_review', ...original,
+ }, persistId: action === 'ask' ? 'persist-receipt' : 'receipt-message' }]);
const resolveInteraction = vi.mocked(window.electronAPI.maker.resolveInteraction);
let resolve!: (receipt: { accepted: boolean }) => void;
resolveInteraction.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
@@ -377,7 +381,7 @@ describe('ask_user 与 done 的时序', () => {
expect(pending()).toBe(original);
resolve({ accepted: false });
await new Promise((done) => setTimeout(done, 0));
- expect(pending()).toBe(original);
+ expect(pending()).toEqual(original);
expect(updateMessageContent).not.toHaveBeenCalled();
submit();
await vi.waitFor(() => expect(pending()).toBeNull());
@@ -388,6 +392,9 @@ describe('ask_user 与 done 的时序', () => {
it.each(['reject', 'missing', 'timeout'] as const)('retains an unanswered card after a %s receipt and can retry', async (failure) => {
makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });
emitAskUserRequest('failed-receipt');
+ getPendingInteractions.mockResolvedValue([{ request: {
+ kind: 'ask_user_question', ...makerChatStore.getSnapshot(SESSION_ID).pendingAskUser,
+ }, persistId: 'persist-failed-receipt' }]);
const resolveInteraction = vi.mocked(window.electronAPI.maker.resolveInteraction);
if (failure === 'reject') resolveInteraction.mockRejectedValueOnce(new Error('offline'));
if (failure === 'missing') resolveInteraction.mockResolvedValueOnce(undefined as never);
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index d67739f81b..0c949fa4ea 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -806,6 +806,185 @@ describe('device-link 远程交互 — dismissed / 顺序 / 本机零回归', ()
});
});
+describe('device-link 失效问题与计划收口', () => {
+ const ask = {
+ kind: 'ask_user_question', requestId: 'stale-ask',
+ questions: [{ question: 'X?', header: 'h', options: [{ label: 'A' }], multiSelect: false }],
+ };
+ const plan = { kind: 'plan_review', requestId: 'stale-plan', plan: '# Plan', planFilePath: '' };
+
+ it.each(['rejected', 'lost', 'timeout', 'snapshot', 'push'] as const)(
+ '%s 后同一计划保留本地编辑,再次批准发送草稿', async (trigger) => {
+ vi.useFakeTimers();
+ try {
+ const s = openRemoteSession();
+ host.hostInteraction(s, plan, 'persist-edited-plan');
+ host.seedPending(s, plan, 'persist-edited-plan');
+ makerChatStore.updatePendingPlanReviewContent(s, plan.requestId, '# My edited plan');
+ makerChatStore.setPlanViewerState(s, 'edit');
+ if (trigger === 'snapshot') await makerChatStore.reconcilePendingInteractions(s);
+ else if (trigger === 'push') host.hostInteraction(s, plan, 'persist-edited-plan');
+ else {
+ if (trigger === 'rejected') host.invoke.mockResolvedValueOnce({ accepted: false });
+ if (trigger === 'lost') host.invoke.mockRejectedValueOnce(new Error('receipt lost'));
+ if (trigger === 'timeout') host.invoke.mockImplementationOnce(() => new Promise(() => {}));
+ makerChatStore.respondToPlanReview(s, plan.requestId, true);
+ await vi.advanceTimersByTimeAsync(trigger === 'timeout' ? 15_001 : 0);
+ }
+ const state = makerChatStore.getSnapshot(s);
+ expect(state.pendingPlanReview?.plan).toBe('# My edited plan');
+ expect(state.planViewerState).toBe('edit');
+ expect(state.lastExpandedPlanViewerState).toBe('edit');
+ expect(state.messages.find(m => m.planReviewRequestId === plan.requestId)?.planReviewPlan).toBe('# My edited plan');
+ makerChatStore.respondToPlanReview(s, plan.requestId, true);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(host.resolved).toEqual([{ requestId: plan.requestId, decision: {
+ kind: 'plan_review', behavior: 'allow', editedPlan: '# My edited plan',
+ } }]);
+ expect(makerChatStore.getSnapshot(s).pendingPlanReview).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
+ it('本机重查保留收起的编辑草稿,新请求不会继承草稿或显示状态', async () => {
+ const s = sid();
+ local.localGetPendingInteractions.mockResolvedValue([{ request: plan, persistId: 'local-plan' }]);
+ await makerChatStore.reconcilePendingInteractions(s);
+ makerChatStore.updatePendingPlanReviewContent(s, plan.requestId, '# Local draft');
+ makerChatStore.setPlanViewerState(s, 'edit');
+ makerChatStore.setPlanViewerState(s, 'minimized');
+ await makerChatStore.reconcilePendingInteractions(s);
+ expect(makerChatStore.getSnapshot(s)).toMatchObject({
+ pendingPlanReview: { plan: '# Local draft' }, planViewerState: 'minimized', lastExpandedPlanViewerState: 'edit',
+ });
+ local.localGetPendingInteractions.mockResolvedValue([{ request: { ...plan, requestId: 'new-plan', plan: '# New plan' }, persistId: 'new-plan' }]);
+ await makerChatStore.reconcilePendingInteractions(s);
+ expect(makerChatStore.getSnapshot(s)).toMatchObject({
+ pendingPlanReview: { requestId: 'new-plan', plan: '# New plan' }, planViewerState: 'expanded', lastExpandedPlanViewerState: 'expanded',
+ });
+ expect(makerChatStore.getSnapshot(s).messages.find(m => m.planReviewRequestId === plan.requestId)?.planReviewStatus).toBe('expired');
+ });
+
+ it('重连后的空快照清掉错过撤回通知的卡片、草稿和历史待回答状态', async () => {
+ const s = openRemoteSession();
+ host.hostInteraction(s, ask, 'persist-stale-ask');
+ host.hostInteraction(s, plan, 'persist-stale-plan');
+ makerChatStore.setAskUserDraft(s, { requestId: ask.requestId, currentIndex: 0, answers: { 'X?': 'A' } });
+ makerChatStore.setAskUserViewerState(s, 'minimized');
+ makerChatStore.setPlanViewerState(s, 'minimized');
+
+ await makerChatStore.reconcilePendingInteractions(s);
+
+ const state = makerChatStore.getSnapshot(s);
+ expect(state.pendingAskUser).toBeNull();
+ expect(state.pendingPlanReview).toBeNull();
+ expect(state.askUserDraft).toBeNull();
+ expect(state.askUserViewerState).toBe('expanded');
+ expect(state.planViewerState).toBe('expanded');
+ expect(state.messages.find(m => m.askUserRequestId === ask.requestId)?.askUserStatus).toBe('expired');
+ expect(state.messages.find(m => m.planReviewRequestId === plan.requestId)?.planReviewStatus).toBe('expired');
+ expect(host.resolved).toEqual([]);
+ });
+
+ it.each(['rejected', 'lost'] as const)('%s 回执后重查主机,过期问题不再卡住跳过', async (failure) => {
+ const s = openRemoteSession();
+ host.hostInteraction(s, ask, 'persist-stale-ask');
+ if (failure === 'rejected') host.invoke.mockResolvedValueOnce({ accepted: false });
+ else host.invoke.mockRejectedValueOnce(new Error('receipt lost'));
+
+ makerChatStore.answerUserQuestion(s, ask.requestId, { 'X?': '' });
+ await flush();
+
+ expect(host.invoke).toHaveBeenCalledWith(DEVICE_ID, 'maker:get-pending-interactions', [s]);
+ expect(makerChatStore.getSnapshot(s).pendingAskUser).toBeNull();
+ expect(makerChatStore.getSnapshot(s).messages.find(m => m.askUserRequestId === ask.requestId)?.askUserStatus).toBe('expired');
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'maker:resolve-interaction')).toHaveLength(1);
+ expect(local.localResolveInteraction).not.toHaveBeenCalled();
+ });
+
+ it('计划拒绝回执也重查并清掉失效确认', async () => {
+ const s = openRemoteSession();
+ host.hostInteraction(s, plan, 'persist-stale-plan');
+ host.invoke.mockResolvedValueOnce({ accepted: false });
+ makerChatStore.respondToPlanReview(s, plan.requestId, true);
+ await flush();
+ expect(makerChatStore.getSnapshot(s).pendingPlanReview).toBeNull();
+ expect(makerChatStore.getSnapshot(s).messages.find(m => m.planReviewRequestId === plan.requestId)?.planReviewStatus).toBe('expired');
+ });
+
+ it.each(['pending', 'unreachable'] as const)('主机 %s 时保留问题和草稿,可再次提交', async (hostState) => {
+ const s = openRemoteSession();
+ host.hostInteraction(s, ask, 'persist-stale-ask');
+ host.seedPending(s, ask, 'persist-stale-ask');
+ const draft = { requestId: ask.requestId, currentIndex: 0, answers: { 'X?': 'A' } };
+ makerChatStore.setAskUserDraft(s, draft);
+ host.invoke.mockResolvedValueOnce({ accepted: false });
+ if (hostState === 'unreachable') host.invoke.mockRejectedValueOnce(new Error('offline'));
+ makerChatStore.answerUserQuestion(s, ask.requestId, draft.answers);
+ await flush();
+ expect(makerChatStore.getSnapshot(s).pendingAskUser?.requestId).toBe(ask.requestId);
+ expect(makerChatStore.getSnapshot(s).askUserDraft).toEqual(draft);
+ makerChatStore.answerUserQuestion(s, ask.requestId, draft.answers);
+ await flush();
+ expect(makerChatStore.getSnapshot(s).pendingAskUser).toBeNull();
+ expect(host.resolved).toHaveLength(1);
+ });
+
+ it('旧快照不能删除读取期间新到的问题或覆盖已回答的历史', async () => {
+ const s = openRemoteSession();
+ host.hostInteraction(s, ask, 'persist-stale-ask');
+ let finish!: () => void;
+ host.invoke.mockReturnValueOnce(new Promise(resolve => { finish = () => resolve([]); }));
+ const reconcile = makerChatStore.reconcilePendingInteractions(s);
+ host.hostDismiss(s, ask.requestId, 'resolved', { kind: 'ask_user_question', answers: { 'X?': 'A' } });
+ const nextAsk = { ...ask, requestId: 'next-ask' };
+ host.hostInteraction(s, nextAsk, 'persist-next-ask');
+ finish();
+ await reconcile;
+ expect(makerChatStore.getSnapshot(s).pendingAskUser?.requestId).toBe(nextAsk.requestId);
+ host.seedPending(s, nextAsk, 'persist-next-ask');
+ await makerChatStore.reconcilePendingInteractions(s);
+ expect(makerChatStore.getSnapshot(s).messages.find(m => m.askUserRequestId === ask.requestId)).toMatchObject({ askUserStatus: 'answered', askUserAnswers: { 'X?': 'A' } });
+ });
+
+ it('提交和重查都无响应时恢复可提交状态,迟到快照不能删除新问题', async () => {
+ vi.useFakeTimers();
+ try {
+ const s = openRemoteSession();
+ host.hostInteraction(s, ask, 'persist-stale-ask');
+ let finish!: () => void;
+ host.invoke.mockImplementationOnce(() => new Promise(() => {}));
+ host.invoke.mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve([]); }));
+ makerChatStore.answerUserQuestion(s, ask.requestId, { 'X?': '' });
+ await vi.advanceTimersByTimeAsync(30_001);
+ expect(makerChatStore.getSnapshot(s).pendingAskUser?.requestId).toBe(ask.requestId);
+ makerChatStore.answerUserQuestion(s, ask.requestId, { 'X?': 'A' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(makerChatStore.getSnapshot(s).pendingAskUser).toBeNull();
+ const nextAsk = { ...ask, requestId: 'after-timeout' };
+ host.hostInteraction(s, nextAsk, 'persist-after-timeout');
+ finish();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(makerChatStore.getSnapshot(s).pendingAskUser?.requestId).toBe(nextAsk.requestId);
+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'maker:resolve-interaction')).toHaveLength(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('本机也按成功快照收口,不向其它设备发请求', async () => {
+ const s = sid();
+ local.localGetPendingInteractions.mockResolvedValueOnce([{ request: ask }]);
+ await makerChatStore.reconcilePendingInteractions(s);
+ expect(makerChatStore.getSnapshot(s).pendingAskUser?.requestId).toBe(ask.requestId);
+ await makerChatStore.reconcilePendingInteractions(s);
+ expect(makerChatStore.getSnapshot(s).pendingAskUser).toBeNull();
+ expect(host.invoke).not.toHaveBeenCalled();
+ });
+});
+
describe('device-link 交互快照重建 — 窗口在交互挂起之后才打开(无 live push)', () => {
it('本机 issue_confirm:无 push → 快照重建确认卡,重复重放保留用户草稿', async () => {
const s = sid();
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index bba1e34d66..c409b2ce13 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -6771,6 +6771,15 @@ export function handleStreamEvent(
// Guard against malformed events (Minor #6): empty requestId or plan
// would produce an un-resolvable pending review. Drop on the floor.
if (!data.requestId || !data.plan) return state;
+ // Host snapshots and duplicate pushes carry the original request, while
+ // remote plan edits only live here. Replaying the same pending request
+ // must preserve its draft and viewer state until a decision or dismissal.
+ const keepPlanProgress = state.pendingPlanReview?.requestId === data.requestId;
+ const pendingPlan = keepPlanProgress ? state.pendingPlanReview! : {
+ requestId: data.requestId,
+ plan: data.plan,
+ planFilePath: data.planFilePath,
+ };
// F1-a: plan_review 消息的落库(+ 在飞 assistant flush)已收口 main
// (onInteractionMessage),renderer 只做 UI:finalize + 用 main 下发的 persistId 建
// plan_review 气泡(onCreated dedup;answered/feedback 回写命中这条 persistId 单行)。
@@ -6789,8 +6798,8 @@ export function handleStreamEvent(
...m,
isStreaming: false,
planReviewStatus: 'pending' as const,
- planReviewPlan: data.plan,
- planReviewFilePath: data.planFilePath,
+ planReviewPlan: pendingPlan.plan,
+ planReviewFilePath: pendingPlan.planFilePath,
planReviewFeedback: undefined,
}
: m,
@@ -6807,22 +6816,18 @@ export function handleStreamEvent(
isStreaming: false,
planReviewStatus: 'pending' as const,
planReviewRequestId: data.requestId,
- planReviewPlan: data.plan,
- planReviewFilePath: data.planFilePath,
+ planReviewPlan: pendingPlan.plan,
+ planReviewFilePath: pendingPlan.planFilePath,
createdAt: new Date().toISOString(),
},
];
return {
...finalized,
- pendingPlanReview: {
- requestId: data.requestId,
- plan: data.plan,
- planFilePath: data.planFilePath,
- },
+ pendingPlanReview: pendingPlan,
// Default to expanded + remember as the restore target for minimized
- planViewerState: 'expanded',
- lastExpandedPlanViewerState: 'expanded',
+ planViewerState: keepPlanProgress ? state.planViewerState : 'expanded',
+ lastExpandedPlanViewerState: keepPlanProgress ? state.lastExpandedPlanViewerState : 'expanded',
messages: planMessages,
};
}
@@ -10276,12 +10281,20 @@ function reconcilePendingInteractions(
// Permissions also need subtraction after a lost decision receipt.
const authoritativePluginSetupIds = new Set<string>();
const authoritativePermissionIds = new Set<string>();
+ const authoritativeQuestionIds = new Set<string>();
+ const authoritativePlanIds = new Set<string>();
const authoritativeRemoteDesktopConfirmationIds = new Set<string>();
for (const item of list) {
const request = item?.request;
if (request?.kind === 'permission' && typeof request.requestId === 'string') {
authoritativePermissionIds.add(request.requestId);
}
+ if (request?.kind === 'ask_user_question' && typeof request.requestId === 'string') {
+ authoritativeQuestionIds.add(request.requestId);
+ }
+ if (request?.kind === 'plan_review' && typeof request.requestId === 'string') {
+ authoritativePlanIds.add(request.requestId);
+ }
if (
request?.kind === 'plugin_setup' &&
typeof request.requestId === 'string' &&
@@ -10301,6 +10314,28 @@ function reconcilePendingInteractions(
}
if (!isCurrentInteractionReconcile()) return 0;
setState(sessionId, (state) => {
+ // Missing dismissal pushes must not leave old questions blocking the
+ // composer. Only a successful, current Host snapshot can retire them.
+ const nextAskUser = state.pendingAskUser &&
+ authoritativeQuestionIds.has(state.pendingAskUser.requestId)
+ ? state.pendingAskUser : null;
+ const nextPlanReview = state.pendingPlanReview &&
+ authoritativePlanIds.has(state.pendingPlanReview.requestId)
+ ? state.pendingPlanReview : null;
+ let messagesChanged = false;
+ const messages = state.messages.map((message) => {
+ if (message.askUserStatus === 'pending' && message.askUserRequestId &&
+ !authoritativeQuestionIds.has(message.askUserRequestId)) {
+ messagesChanged = true;
+ return { ...message, askUserStatus: 'expired' as const };
+ }
+ if (message.planReviewStatus === 'pending' && message.planReviewRequestId &&
+ !authoritativePlanIds.has(message.planReviewRequestId)) {
+ messagesChanged = true;
+ return { ...message, planReviewStatus: 'expired' as const };
+ }
+ return message;
+ });
const nextPermission = state.pendingPermission &&
authoritativePermissionIds.has(state.pendingPermission.requestId)
? state.pendingPermission : null;
@@ -10354,6 +10389,9 @@ function reconcilePendingInteractions(
if (
!currentChanged &&
!queueChanged &&
+ !messagesChanged &&
+ nextAskUser === state.pendingAskUser &&
+ nextPlanReview === state.pendingPlanReview &&
nextPermission === state.pendingPermission &&
nextCommand === state.pluginSetupCommandInFlight &&
promotedRemoteDesktopConfirmation === state.pendingRemoteDesktopConfirmation &&
@@ -10363,6 +10401,13 @@ function reconcilePendingInteractions(
}
return {
...state,
+ messages: messagesChanged ? messages : state.messages,
+ pendingAskUser: nextAskUser,
+ askUserDraft: nextAskUser ? state.askUserDraft : null,
+ askUserViewerState: nextAskUser ? state.askUserViewerState : 'expanded',
+ pendingPlanReview: nextPlanReview,
+ planViewerState: nextPlanReview ? state.planViewerState : 'expanded',
+ lastExpandedPlanViewerState: nextPlanReview ? state.lastExpandedPlanViewerState : 'expanded',
pendingPermission: nextPermission,
pendingPluginSetup: nextCurrent,
pendingPluginSetupQueue: survivingQueue,
@@ -16208,7 +16253,7 @@ function updateSystemCardData(
}
// Only an accepted Host receipt may commit a question/plan decision. A rejected
-// or lost receipt leaves the existing card and its draft available for retry.
+// or lost receipt rechecks Host state, keeping a still-pending card and draft.
const questionDecisionsInFlight = new Set<string>();
function submitQuestionDecision(
@@ -16249,6 +16294,24 @@ function submitQuestionDecision(
if (state?.pendingAskUser?.requestId !== requestId &&
state?.pendingPlanReview?.requestId !== requestId) return;
log.warn('Question decision receipt unavailable', error);
+ // A rejection may mean either an ended request or paused execution.
+ // Read the authoritative snapshot; never infer completion or resend the
+ // answer from a missing receipt. Bound this read just like the submission.
+ if (timer) clearTimeout(timer);
+ try {
+ await Promise.race([
+ reconcilePendingInteractions(sessionId, isCurrent),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Interaction reconciliation timeout')), 15_000);
+ }),
+ ]);
+ } catch {
+ // A disconnected Host cannot prove that the request has ended.
+ }
+ if (!isCurrent()) return;
+ const current = sessions.get(sessionId);
+ if (current?.pendingAskUser?.requestId !== requestId &&
+ current?.pendingPlanReview?.requestId !== requestId) return;
toast.warning(i18n.t('newChat.permissionPrompt.submissionFailed'));
} finally {
if (timer) clearTimeout(timer);