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): 恢复刷新后遗漏的确认卡 (#1251)

Dash718090474475
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index a53368b364..536dcbd04f 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -1870,6 +1870,29 @@ describe('被控端订阅 registry + topic 转发', () => {
});
});
+ it.each([
+ 'issue_confirm',
+ 'rename_sessions_confirm',
+ 'ghost_grant_confirm',
+ ])('device-link does not forward Desktop-only %s live pushes', (kind) => {
+ remoteControlEnabled = true;
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ feed(subFrame('ctrl-a', SUB, ['session:s1']));
+
+ tapWindowBroadcast(MAKER_PUSH.INTERACTION_REQUEST, {
+ sessionId: 's1',
+ request: {
+ kind,
+ requestId: `${kind}-1`,
+ absPath: '/Users/me/private.png',
+ previewDataUrl: 'data:image/png;base64,private',
+ },
+ });
+
+ expect(calls.push).toEqual([]);
+ });
+
it('unsubscribe 移除 topic;registry 空后停 tap', () => {
remoteControlEnabled = true;
const { client, feed } = makeFakeClient();
diff --git a/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts b/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts
index e94b94a987..864c709bfd 100644
--- a/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts
@@ -8,26 +8,67 @@ const registerSource = readFileSync(
'utf8',
).replace(/\r\n/g, '\n');
-describe('plugin setup interaction lifecycle contract', () => {
- it('counts Setup snapshots in queue busy and zombie-turn reconciliation', () => {
+describe('host-owned interaction lifecycle contract', () => {
+ it('recovers every Host-owned snapshot without treating Desktop confirms as Agent busy state', () => {
+ const snapshotHelperStart = registerSource.indexOf(
+ 'function getPendingInteractionsForSession(',
+ );
+ const snapshotHelperEnd = registerSource.indexOf('\n}\n', snapshotHelperStart) + 2;
+ const snapshotHelper = registerSource.slice(snapshotHelperStart, snapshotHelperEnd);
const helperStart = registerSource.indexOf(
- 'function hasPendingInteractionForSession(sessionId: string): boolean',
+ 'function hasPendingAgentInteractionForSession(sessionId: string): boolean',
);
const helperEnd = registerSource.indexOf('\n}\n', helperStart) + 2;
const helper = registerSource.slice(helperStart, helperEnd);
- expect(helper).toContain(
- 'ghostSetupInteractionBridge.pendingSnapshots(sessionId).length > 0',
+ for (const bridgeName of [
+ 'issueConfirmBridge',
+ 'renameSessionsConfirmBridge',
+ 'ghostGrantConfirmBridge',
+ 'ghostSetupInteractionBridge',
+ ]) {
+ expect(snapshotHelper).toMatch(
+ new RegExp(`${bridgeName}\\s*\\.pendingSnapshots\\(sessionId\\)`),
+ );
+ }
+ expect(helper).toMatch(
+ /ghostSetupInteractionBridge\s*\.pendingSnapshots\(sessionId\)\.length > 0/,
);
+ for (const bridgeName of [
+ 'issueConfirmBridge',
+ 'renameSessionsConfirmBridge',
+ 'ghostGrantConfirmBridge',
+ ]) {
+ expect(helper).not.toContain(bridgeName);
+ }
expect(registerSource).toContain(
- 'const hadZombieInteraction = hasPendingInteractionForSession(sessionId);',
+ 'const hadZombieInteraction = hasPendingAgentInteractionForSession(sessionId);',
);
expect(registerSource).toContain(
- 'hasPendingInteraction: hasPendingInteractionForSession,',
+ 'hasPendingInteraction: hasPendingAgentInteractionForSession,',
);
expect(registerSource).toContain(
+ "cleanupPendingAgentInteractionsForSession(sessionId, 'turn_idle_reconcile');",
+ );
+ expect(registerSource).not.toContain(
"cleanupPendingInteractionsForSession(sessionId, 'turn_idle_reconcile');",
);
+
+ const ownershipHelperStart = registerSource.indexOf(
+ 'function isPendingDesktopOnlyConfirmation(requestId: string): boolean',
+ );
+ const ownershipHelperEnd = registerSource.indexOf('\n}\n', ownershipHelperStart) + 2;
+ const ownershipHelper = registerSource.slice(ownershipHelperStart, ownershipHelperEnd);
+ for (const bridgeName of [
+ 'issueConfirmBridge',
+ 'renameSessionsConfirmBridge',
+ 'ghostGrantConfirmBridge',
+ ]) {
+ expect(ownershipHelper).toContain(bridgeName);
+ }
+ expect(registerSource).toMatch(
+ /assertResolveInteractionOrigin\(\s*decision,\s*isPendingDesktopOnlyConfirmation\(requestId\),\s*\);/,
+ );
});
it('applies the Agent Island session policy before forwarding Setup snapshots', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts
index ca508c2f17..36769ec766 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts
@@ -56,6 +56,10 @@ describe('GhostGrantConfirmBridge', () => {
},
});
expect((payload as { request: { requestId: string } }).request.requestId).toBeTruthy();
+ expect(bridge.pendingSnapshots('other-session')).toEqual([]);
+ expect(bridge.pendingSnapshots('sess-1')).toEqual([
+ { sessionId: 'sess-1', request: (payload as { request: unknown }).request },
+ ]);
});
it('resolve 允许 → promise settle 为 confirmed:true,并广播 DISMISSED(allow)', async () => {
@@ -75,7 +79,9 @@ describe('GhostGrantConfirmBridge', () => {
const broadcast = vi.fn();
const bridge = new GhostGrantConfirmBridge({ broadcast });
const promise = bridge.request('sess-1', PAYLOAD);
- expect(bridge.resolve(lastRequestId(broadcast), { confirmed: true, allowDirs: true })).toBe(true);
+ expect(bridge.resolve(lastRequestId(broadcast), { confirmed: true, allowDirs: true })).toBe(
+ true,
+ );
await expect(promise).resolves.toEqual({ confirmed: true, allowDirs: true });
});
@@ -110,6 +116,7 @@ describe('GhostGrantConfirmBridge', () => {
const promise = bridge.request('sess-1', PAYLOAD);
vi.advanceTimersByTime(1001);
await expect(promise).resolves.toEqual({ confirmed: false, reason: 'timeout' });
+ expect(bridge.pendingSnapshots()).toEqual([]);
});
it('cleanupForSession 只清本会话的 pending', async () => {
@@ -119,6 +126,8 @@ describe('GhostGrantConfirmBridge', () => {
const p2 = bridge.request('sess-2', PAYLOAD);
bridge.cleanupForSession('sess-1', 'session_closed');
await expect(p1).resolves.toEqual({ confirmed: false, reason: 'session_closed' });
+ expect(bridge.pendingSnapshots('sess-1')).toEqual([]);
+ expect(bridge.pendingSnapshots('sess-2')).toHaveLength(1);
// sess-2 仍挂起:resolve 它以免测试悬挂。
const requestId2 = lastRequestId(broadcast);
expect(bridge.resolve(requestId2, { confirmed: true })).toBe(true);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
index 170273b638..f280506190 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
@@ -91,10 +91,9 @@ describe('GhostSetupInteractionBridge', () => {
}),
).toBe(false);
expect(onCommand).not.toHaveBeenCalled();
- expect(logger.warn).toHaveBeenCalledWith(
- 'plugin setup interaction received invalid command',
- { requestId: 'request-1' },
- );
+ expect(logger.warn).toHaveBeenCalledWith('plugin setup interaction received invalid command', {
+ requestId: 'request-1',
+ });
});
it('restores pending snapshots and dismisses only when Main closes it', () => {
@@ -337,7 +336,31 @@ describe('sanitizeGhostSetupSnapshotForRemote', () => {
},
};
const permission = { request: { kind: 'permission', requestId: 'permission-1' } };
- const pending = [localSetup, permission];
+ const future = { request: { kind: 'future_kind', requestId: 'future-1' } };
+ const issue = {
+ request: {
+ kind: 'issue_confirm',
+ requestId: 'issue-1',
+ draft: { title: 'private draft' },
+ },
+ };
+ const rename = {
+ request: {
+ kind: 'rename_sessions_confirm',
+ requestId: 'rename-1',
+ changes: [{ sessionId: 'private-session', title: 'private title' }],
+ },
+ };
+ const grant = {
+ request: {
+ kind: 'ghost_grant_confirm',
+ requestId: 'grant-1',
+ items: [
+ { absPath: '/Users/me/private.png', previewDataUrl: 'data:image/png;base64,private' },
+ ],
+ },
+ };
+ const pending = [localSetup, permission, future, issue, rename, grant];
const local = projectPendingInteractionsForRemote(pending, false);
expect(local).toBe(pending);
@@ -345,11 +368,16 @@ describe('sanitizeGhostSetupSnapshotForRemote', () => {
const remote = projectPendingInteractionsForRemote(pending, true);
expect(remote).not.toBe(pending);
+ expect(remote).toHaveLength(3);
expect(JSON.stringify(remote[0])).not.toContain('desktop-only.example');
expect(remote[1].request).toBe(permission.request);
+ expect(remote[2].request).toBe(future.request);
+ expect(JSON.stringify(remote)).not.toContain('private');
+ expect(JSON.stringify(remote)).not.toContain('/Users/me/private.png');
expect(localSetup.request.steps[0].action.form.fields[0].externalLink).toEqual({
url: 'https://desktop-only.example/keys',
});
+ expect(local).toEqual(pending);
});
});
diff --git a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
index dde1d5091d..546427ba04 100644
--- a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
@@ -21,6 +21,7 @@
import { randomUUID } from 'node:crypto';
import { MAKER_PUSH } from '../maker-ipc/channels';
+import { HOST_CONFIRM_TIMEOUT_MS } from '../maker-ipc/hostConfirmTiming.js';
/**
* 过户通道:attachments = 媒体文件进总仓;dir = 上行读票据;save_dir = 下行
@@ -67,19 +68,24 @@ export type GhostGrantConfirmDecision =
}
| { confirmed: false; reason: 'cancelled' | 'timeout' | 'session_closed' | 'session_aborted' };
+/** Renderer 可重放的文件授权确认请求;主进程持有它直到确认流程 settle。 */
+export interface GhostGrantConfirmInteractionSnapshot extends GhostGrantConfirmPayload {
+ kind: 'ghost_grant_confirm';
+ requestId: string;
+}
+
export interface GhostGrantConfirmBridgeDeps {
broadcast: (channel: string, payload: unknown) => void;
- /** 确认超时,默认 10 分钟(对齐 permission prompt / issue 确认卡)。测试注小值。 */
+ /** 确认超时,默认 9 分钟,须早于外层 MCP 的 10 分钟 deadline。测试注小值。 */
timeoutMs?: number;
logger?: { warn: (...args: unknown[]) => void };
/** 同 IssueConfirmBridgeDeps.onDesktopOnlyConfirmPending(#926):IM 侧「去桌面确认」提示。 */
onDesktopOnlyConfirmPending?: (sessionId: string) => void;
}
-const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
-
interface PendingGrantEntry {
sessionId: string;
+ request: GhostGrantConfirmInteractionSnapshot;
resolve: (decision: GhostGrantConfirmDecision) => void;
timeoutId: ReturnType<typeof setTimeout>;
}
@@ -90,17 +96,25 @@ export class GhostGrantConfirmBridge {
constructor(private readonly deps: GhostGrantConfirmBridgeDeps) {}
/** 向 renderer 派发确认卡片,挂起直到用户响应/超时/会话清理。 */
- request(sessionId: string, payload: GhostGrantConfirmPayload): Promise<GhostGrantConfirmDecision> {
+ request(
+ sessionId: string,
+ payload: GhostGrantConfirmPayload,
+ ): Promise<GhostGrantConfirmDecision> {
const requestId = randomUUID();
+ const request: GhostGrantConfirmInteractionSnapshot = {
+ kind: 'ghost_grant_confirm',
+ requestId,
+ ...payload,
+ };
return new Promise<GhostGrantConfirmDecision>((resolve) => {
- const timeoutMs = this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const timeoutMs = this.deps.timeoutMs ?? HOST_CONFIRM_TIMEOUT_MS;
const timeoutId = setTimeout(() => {
this.settle(requestId, { confirmed: false, reason: 'timeout' }, 'timeout');
}, timeoutMs);
- this.pending.set(requestId, { sessionId, resolve, timeoutId });
+ this.pending.set(requestId, { sessionId, request, resolve, timeoutId });
this.deps.broadcast(MAKER_PUSH.INTERACTION_REQUEST, {
sessionId,
- request: { kind: 'ghost_grant_confirm', requestId, ...payload },
+ request,
});
try {
this.deps.onDesktopOnlyConfirmPending?.(sessionId);
@@ -115,6 +129,16 @@ export class GhostGrantConfirmBridge {
});
}
+ /** 打开、重连或刷新会话时供 renderer 补回错过的确认卡。 */
+ pendingSnapshots(sessionId?: string): Array<{
+ sessionId: string;
+ request: GhostGrantConfirmInteractionSnapshot;
+ }> {
+ return Array.from(this.pending.values())
+ .filter((entry) => sessionId === undefined || entry.sessionId === sessionId)
+ .map((entry) => ({ sessionId: entry.sessionId, request: entry.request }));
+ }
+
/**
* renderer 经 RESOLVE_INTERACTION 回包。返回是否命中本桥的 pending
* (false = requestId 不属于本桥,调用方继续走其它桥/resolver)。
@@ -193,7 +217,9 @@ let bridgeSingleton: GhostGrantConfirmBridge | null = null;
* getGhostGrantConfirmBridge 消费;未初始化(极早期/单测环境)时返回 null,
* 调用方按「确认通道未就绪」拒绝,不抛。
*/
-export function initGhostGrantConfirmBridge(deps: GhostGrantConfirmBridgeDeps): GhostGrantConfirmBridge {
+export function initGhostGrantConfirmBridge(
+ deps: GhostGrantConfirmBridgeDeps,
+): GhostGrantConfirmBridge {
bridgeSingleton = new GhostGrantConfirmBridge(deps);
return bridgeSingleton;
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
index e625f8534f..e73a423448 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
@@ -338,15 +338,34 @@ export function sanitizeGhostSetupRequestForRemote<T>(request: T): T {
) as T;
}
+function isDesktopOnlyConfirmationRequest(request: unknown): boolean {
+ if (!request || typeof request !== 'object' || Array.isArray(request)) return false;
+ const kind = (request as { kind?: unknown }).kind;
+ return (
+ kind === 'issue_confirm' || kind === 'rename_sessions_confirm' || kind === 'ghost_grant_confirm'
+ );
+}
+
+/**
+ * Host-owned confirmations stay on the trusted Desktop. This keeps their
+ * request ids and local payload details (for example file paths and previews)
+ * out of Device Link while preserving the existing sanitized plugin-setup
+ * projection used for remote status/cancellation.
+ */
+export function projectInteractionRequestForRemote<T>(request: T): T | null {
+ if (isDesktopOnlyConfirmationRequest(request)) return null;
+ return sanitizeGhostSetupRequestForRemote(request);
+}
+
export function projectPendingInteractionsForRemote<T extends { request: unknown }>(
pending: T[],
remote: boolean,
): T[] {
if (!remote) return pending;
- return pending.map((entry) => ({
- ...entry,
- request: sanitizeGhostSetupRequestForRemote(entry.request),
- }));
+ return pending.flatMap((entry) => {
+ const request = projectInteractionRequestForRemote(entry.request);
+ return request === null ? [] : [{ ...entry, request }];
+ });
}
export function parseGhostSetupInteractionCommand(
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index a5e886ac39..f866866096 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -66,7 +66,7 @@ import { setBroadcastTapListener } from './broadcast-tap';
import * as subscriptions from './subscriptions';
import { LEGACY_TOPIC, type ActiveController } from './subscriptions';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
-import { sanitizeGhostSetupRequestForRemote } from '../cindy-brain/ghostSetupInteractionBridge.js';
+import { projectInteractionRequestForRemote } from '../cindy-brain/ghostSetupInteractionBridge.js';
import {
remoteWorkingDirRejectionToIpcError,
type RemoteWorkingDirCheckResult,
@@ -493,18 +493,19 @@ function forwardPush(channel: string, payload: unknown): void {
if (!activeClient) return;
const topic = topicForPush(channel, payload);
if (!topic) return;
- const remotePayload =
+ let remotePayload = payload;
+ if (
channel === MAKER_PUSH.INTERACTION_REQUEST &&
payload &&
typeof payload === 'object' &&
'request' in payload
- ? {
- ...payload,
- request: sanitizeGhostSetupRequestForRemote(
- (payload as { request: unknown }).request,
- ),
- }
- : payload;
+ ) {
+ const request = projectInteractionRequestForRemote(
+ (payload as { request: unknown }).request,
+ );
+ if (request === null) return;
+ remotePayload = { ...payload, request };
+ }
const dsts = subscriptions.getControllersForTopic(topic);
for (const dst of dsts) {
// 转发是尽力而为的旁路:单个控制端的帧超限(PAYLOAD_TOO_LARGE,如大 tool 输出)/ 连接异常
diff --git a/apps/desktop/src/main/github-issue/__tests__/issueConfirmBridge.test.ts b/apps/desktop/src/main/github-issue/__tests__/issueConfirmBridge.test.ts
index cbdfc85119..68af64e851 100644
--- a/apps/desktop/src/main/github-issue/__tests__/issueConfirmBridge.test.ts
+++ b/apps/desktop/src/main/github-issue/__tests__/issueConfirmBridge.test.ts
@@ -51,6 +51,10 @@ describe('IssueConfirmBridge', () => {
},
});
expect((payload as { request: { requestId: string } }).request.requestId).toBeTruthy();
+ expect(bridge.pendingSnapshots('other-session')).toEqual([]);
+ expect(bridge.pendingSnapshots('sess-1')).toEqual([
+ { sessionId: 'sess-1', request: (payload as { request: unknown }).request },
+ ]);
});
it('resolve 确认 decision → promise settle 为 confirmed,值取卡片当前版', async () => {
@@ -184,6 +188,7 @@ describe('IssueConfirmBridge', () => {
const requestId = lastRequestId(broadcast);
vi.advanceTimersByTime(1001);
await expect(promise).resolves.toEqual({ confirmed: false, reason: 'timeout' });
+ expect(bridge.pendingSnapshots()).toEqual([]);
expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.INTERACTION_DISMISSED, {
sessionId: 'sess-1',
requestId,
@@ -192,6 +197,18 @@ describe('IssueConfirmBridge', () => {
});
});
+ it('默认确认超时早于 600 秒 MCP deadline', async () => {
+ const bridge = new IssueConfirmBridge({ broadcast: vi.fn() });
+ const promise = bridge.request('sess-1', DRAFT, ENV, IDENTITY);
+
+ vi.advanceTimersByTime(9 * 60 * 1000 - 1);
+ expect(bridge.pendingSnapshots('sess-1')).toHaveLength(1);
+ vi.advanceTimersByTime(1);
+
+ await expect(promise).resolves.toEqual({ confirmed: false, reason: 'timeout' });
+ expect(bridge.pendingSnapshots()).toEqual([]);
+ });
+
it('cleanupForSession 只清目标会话的 pending,并广播收卡', async () => {
const broadcast = vi.fn();
const bridge = new IssueConfirmBridge({ broadcast });
@@ -199,6 +216,8 @@ describe('IssueConfirmBridge', () => {
const p2 = bridge.request('sess-2', DRAFT, ENV, IDENTITY);
bridge.cleanupForSession('sess-1', 'session_aborted');
await expect(p1).resolves.toEqual({ confirmed: false, reason: 'session_aborted' });
+ expect(bridge.pendingSnapshots('sess-1')).toEqual([]);
+ expect(bridge.pendingSnapshots('sess-2')).toHaveLength(1);
const dismissed = broadcast.mock.calls.filter(
([channel]) => channel === MAKER_PUSH.INTERACTION_DISMISSED,
);
diff --git a/apps/desktop/src/main/github-issue/index.ts b/apps/desktop/src/main/github-issue/index.ts
index dd207afd9f..b65bd63729 100644
--- a/apps/desktop/src/main/github-issue/index.ts
+++ b/apps/desktop/src/main/github-issue/index.ts
@@ -33,7 +33,7 @@ import {
} from './githubUserIssueSubmitter';
export { IssueConfirmBridge } from './issueConfirmBridge';
-export type { IssueConfirmDecision } from './issueConfirmBridge';
+export type { IssueConfirmDecision, IssueConfirmInteractionSnapshot } from './issueConfirmBridge';
const log = createLogger('github-issue');
diff --git a/apps/desktop/src/main/github-issue/issueConfirmBridge.ts b/apps/desktop/src/main/github-issue/issueConfirmBridge.ts
index 3ebdf25868..6aab41a255 100644
--- a/apps/desktop/src/main/github-issue/issueConfirmBridge.ts
+++ b/apps/desktop/src/main/github-issue/issueConfirmBridge.ts
@@ -23,6 +23,7 @@ import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
import { normalizeIssuePublicName } from '../../shared/issuePublicName.js';
import { MAKER_PUSH } from '../maker-ipc/channels';
+import { HOST_CONFIRM_TIMEOUT_MS } from '../maker-ipc/hostConfirmTiming.js';
export interface IssueDraft {
title: string;
@@ -64,9 +65,19 @@ export type IssueConfirmDecision =
reason: 'cancelled' | 'timeout' | 'session_closed' | 'session_aborted';
};
+/** Renderer 可重放的提交确认请求;主进程持有它直到确认流程 settle。 */
+export interface IssueConfirmInteractionSnapshot {
+ kind: 'issue_confirm';
+ requestId: string;
+ draft: IssueDraft;
+ env: IssueEnvInfo;
+ submissionIdentity: IssueSubmissionIdentity;
+ suggestedPublicName?: string;
+}
+
export interface IssueConfirmBridgeDeps {
broadcast: (channel: string, payload: unknown) => void;
- /** 确认超时,默认 10 分钟(对齐 permission prompt 的超时语义)。测试注小值。 */
+ /** 确认超时,默认 9 分钟,须早于外层 MCP 的 10 分钟 deadline。测试注小值。 */
timeoutMs?: number;
logger?: { warn: (...args: unknown[]) => void };
/**
@@ -77,10 +88,9 @@ export interface IssueConfirmBridgeDeps {
onDesktopOnlyConfirmPending?: (sessionId: string) => void;
}
-const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
-
interface PendingConfirmEntry {
sessionId: string;
+ request: IssueConfirmInteractionSnapshot;
requiresPublicName: boolean;
resolve: (decision: IssueConfirmDecision) => void;
timeoutId: ReturnType<typeof setTimeout>;
@@ -100,27 +110,29 @@ export class IssueConfirmBridge {
suggestedPublicName?: string,
): Promise<IssueConfirmDecision> {
const requestId = randomUUID();
+ const request: IssueConfirmInteractionSnapshot = {
+ kind: 'issue_confirm',
+ requestId,
+ draft,
+ env,
+ submissionIdentity,
+ suggestedPublicName,
+ };
return new Promise<IssueConfirmDecision>((resolve) => {
- const timeoutMs = this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const timeoutMs = this.deps.timeoutMs ?? HOST_CONFIRM_TIMEOUT_MS;
const timeoutId = setTimeout(() => {
this.settle(requestId, { confirmed: false, reason: 'timeout' }, 'timeout');
}, timeoutMs);
this.pending.set(requestId, {
sessionId,
+ request,
requiresPublicName: submissionIdentity.kind === 'platform',
resolve,
timeoutId,
});
this.deps.broadcast(MAKER_PUSH.INTERACTION_REQUEST, {
sessionId,
- request: {
- kind: 'issue_confirm',
- requestId,
- draft,
- env,
- submissionIdentity,
- suggestedPublicName,
- },
+ request,
});
try {
this.deps.onDesktopOnlyConfirmPending?.(sessionId);
@@ -135,6 +147,16 @@ export class IssueConfirmBridge {
});
}
+ /** 打开、重连或刷新会话时供 renderer 补回错过的确认卡。 */
+ pendingSnapshots(sessionId?: string): Array<{
+ sessionId: string;
+ request: IssueConfirmInteractionSnapshot;
+ }> {
+ return Array.from(this.pending.values())
+ .filter((entry) => sessionId === undefined || entry.sessionId === sessionId)
+ .map((entry) => ({ sessionId: entry.sessionId, request: entry.request }));
+ }
+
/**
* renderer 经 RESOLVE_INTERACTION 回包。返回是否命中本桥的 pending
* (false = requestId 不属于本桥,调用方继续走原有 resolver 查找/告警)。
@@ -164,10 +186,7 @@ export class IssueConfirmBridge {
}
/** 会话关闭/中止时清掉该会话所有 pending,并让 renderer 收卡。 */
- cleanupForSession(
- sessionId: string,
- reason: 'session_closed' | 'session_aborted',
- ): void {
+ cleanupForSession(sessionId: string, reason: 'session_closed' | 'session_aborted'): void {
for (const [requestId, entry] of Array.from(this.pending.entries())) {
if (entry.sessionId !== sessionId) continue;
this.settle(requestId, { confirmed: false, reason }, reason);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interactionResolveOrigin.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interactionResolveOrigin.test.ts
index 968f41abb9..b8ba3ee0ab 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interactionResolveOrigin.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interactionResolveOrigin.test.ts
@@ -6,10 +6,10 @@ import {
} from '../../device-link/invoke-context.js';
import { assertResolveInteractionOrigin } from '../interactionResolveOrigin.js';
-function fromDeviceLink(decision: unknown): void {
+function fromDeviceLink(decision: unknown, desktopOnlyConfirmationPending = false): void {
runDeviceLinkInvokeContext(
{ controllerDeviceId: 'controller-1', channel: 'maker:resolve-interaction' },
- () => assertResolveInteractionOrigin(decision),
+ () => assertResolveInteractionOrigin(decision, desktopOnlyConfirmationPending),
);
}
@@ -32,14 +32,29 @@ describe('resolve interaction source boundary', () => {
);
});
- it('keeps the same plugin setup decisions available to the trusted local Renderer', () => {
+ it.each([
+ { kind: 'issue_confirm', confirmed: true },
+ { kind: 'rename_sessions_confirm', confirmed: true },
+ { kind: 'ghost_grant_confirm', confirmed: true },
+ ])('rejects remote Desktop-only $kind decisions', (decision) => {
+ expect(() => fromDeviceLink(decision)).toThrow(
+ '[PERMISSION_DENIED] desktop-only confirmations must be completed on the controlled Desktop',
+ );
+ });
+
+ it('rejects a remote decision by pending request ownership even when its payload has no kind', () => {
+ expect(() => fromDeviceLink({ confirmed: true }, true)).toThrow(
+ '[PERMISSION_DENIED] desktop-only confirmations must be completed on the controlled Desktop',
+ );
+ });
+
+ it.each([
+ { kind: 'plugin_setup', action: 'run_action', actionId: 'oauth:account' },
+ { kind: 'issue_confirm', confirmed: true },
+ { kind: 'rename_sessions_confirm', confirmed: true },
+ { kind: 'ghost_grant_confirm', confirmed: true },
+ ])('keeps the same $kind decision available to the trusted local Renderer', (decision) => {
expect(isDeviceLinkInvoke()).toBe(false);
- expect(() =>
- assertResolveInteractionOrigin({
- kind: 'plugin_setup',
- action: 'run_action',
- actionId: 'oauth:account',
- }),
- ).not.toThrow();
+ expect(() => assertResolveInteractionOrigin(decision)).not.toThrow();
});
});
diff --git a/apps/desktop/src/main/maker-ipc/hostConfirmTiming.ts b/apps/desktop/src/main/maker-ipc/hostConfirmTiming.ts
new file mode 100644
index 0000000000..871492cc51
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/hostConfirmTiming.ts
@@ -0,0 +1,6 @@
+/**
+ * Host-owned confirmation cards must settle before the 600-second MCP tool deadline.
+ * The grace period lets the structured timeout result reach the Agent instead of racing
+ * the transport's generic timeout.
+ */
+export const HOST_CONFIRM_TIMEOUT_MS = 9 * 60 * 1000;
diff --git a/apps/desktop/src/main/maker-ipc/interactionResolveOrigin.ts b/apps/desktop/src/main/maker-ipc/interactionResolveOrigin.ts
index 456ba6fb69..7d24b15ea0 100644
--- a/apps/desktop/src/main/maker-ipc/interactionResolveOrigin.ts
+++ b/apps/desktop/src/main/maker-ipc/interactionResolveOrigin.ts
@@ -2,10 +2,10 @@
* Source boundary for the generic interaction resolver.
*
* Device-link intentionally reuses maker:resolve-interaction for permission,
- * ask and plan decisions. Plugin setup's primary actions open OAuth or trusted
- * local Settings on the controlled Desktop, so they must remain local even
- * when a remote controller knows the pending request/action ids. Cancel only
- * detaches the caller's waiter and remains remotely available.
+ * ask and plan decisions. Plugin setup's primary actions and Host-owned
+ * confirmations must remain local even when a remote controller guesses or
+ * learned a pending request id. Plugin setup cancel only detaches the caller's
+ * waiter and remains remotely available.
*/
import { isDeviceLinkInvoke } from '../device-link/invoke-context.js';
@@ -22,8 +22,26 @@ export function isPluginSetupInteractionDecision(
);
}
-export function assertResolveInteractionOrigin(decision: unknown): void {
+export function assertResolveInteractionOrigin(
+ decision: unknown,
+ desktopOnlyConfirmationPending = false,
+): void {
if (!isDeviceLinkInvoke()) return;
+ const kind =
+ decision && typeof decision === 'object' && !Array.isArray(decision)
+ ? (decision as Record<string, unknown>).kind
+ : undefined;
+ if (
+ desktopOnlyConfirmationPending ||
+ kind === 'issue_confirm' ||
+ kind === 'rename_sessions_confirm' ||
+ kind === 'ghost_grant_confirm'
+ ) {
+ throwIpcError(
+ 'PERMISSION_DENIED',
+ 'desktop-only confirmations must be completed on the controlled Desktop',
+ );
+ }
if (
isPluginSetupInteractionDecision(decision) &&
(decision as Record<string, unknown>).action !== 'cancel'
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 37aa4b846e..a5d64a30cc 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -49,8 +49,15 @@ import { normalizeWorkingDirForProjectSettings } from '../../shared/workingDir.j
import { buildTurnUsageDetails } from '../../shared/turnUsageDetails.js';
import type { DesktopCommandContext } from '../commands/index.js';
import { getDesktopCommandRegistry } from '../commands/index.js';
-import { initGithubIssueSubmit, IssueConfirmBridge } from '../github-issue/index.js';
-import { initGhostGrantConfirmBridge } from '../cindy-brain/ghostGrantConfirmBridge.js';
+import {
+ initGithubIssueSubmit,
+ IssueConfirmBridge,
+ type IssueConfirmInteractionSnapshot,
+} from '../github-issue/index.js';
+import {
+ initGhostGrantConfirmBridge,
+ type GhostGrantConfirmInteractionSnapshot,
+} from '../cindy-brain/ghostGrantConfirmBridge.js';
import { createFeishuDesktopConfirmNotifier } from '../im/desktopConfirmNoticeWiring.js';
import {
initGhostSetupInteractionBridge,
@@ -78,6 +85,7 @@ import {
import {
initRenameSessionsConfirm,
RenameSessionsConfirmBridge,
+ type RenameSessionsConfirmInteractionSnapshot,
} from '../session-title-rename/index.js';
import {
getBrowserAvailability,
@@ -1464,23 +1472,39 @@ function clearPendingInteraction(requestId: string): PendingInteractionEntry | n
return entry;
}
+type RecoverableInteractionSnapshot =
+ | InteractionRequest
+ | GhostSetupInteractionSnapshot
+ | IssueConfirmInteractionSnapshot
+ | RenameSessionsConfirmInteractionSnapshot
+ | GhostGrantConfirmInteractionSnapshot;
+
+type PendingInteractionSnapshotEntry = {
+ request: RecoverableInteractionSnapshot;
+ persistId?: string;
+};
+
/**
- * 快照:某会话当前所有挂起的 agent interaction(permission / ask_user / plan_review)。
+ * 快照:某会话当前所有挂起的 agent interaction 与 Host-owned 确认卡。
* 供 renderer 在「打开 / 重连 / 刷新」会话时重建可操作面板 —— pending 状态原本只由实时
* INTERACTION_REQUEST push 设置,后加入的窗口会错过那条 push,靠这个查询补回。
* 纯内存读;O(N) 其中 N = 全局挂起交互数(极小)。
*/
function getPendingInteractionsForSession(
sessionId: string,
-): Array<{ request: InteractionRequest | GhostSetupInteractionSnapshot; persistId?: string }> {
- const out: Array<{
- request: InteractionRequest | GhostSetupInteractionSnapshot;
- persistId?: string;
- }> = [];
+): PendingInteractionSnapshotEntry[] {
+ const out: PendingInteractionSnapshotEntry[] = [];
for (const entry of pendingInteractionResolvers.values()) {
if (entry.sessionId === sessionId) out.push({ request: entry.request, persistId: entry.persistId });
}
out.push(
+ ...issueConfirmBridge.pendingSnapshots(sessionId).map(({ request }) => ({ request })),
+ ...renameSessionsConfirmBridge
+ .pendingSnapshots(sessionId)
+ .map(({ request }) => ({ request })),
+ ...ghostGrantConfirmBridge
+ .pendingSnapshots(sessionId)
+ .map(({ request }) => ({ request })),
...ghostSetupInteractionBridge
.pendingSnapshots(sessionId)
.map(({ request }) => ({ request })),
@@ -1488,13 +1512,32 @@ function getPendingInteractionsForSession(
return out;
}
-function hasPendingInteractionForSession(sessionId: string): boolean {
+/**
+ * Agent-owned interactions are queue/zombie boundaries. Desktop-only confirms
+ * are Host tool waiters: they are recoverable UI state, but must not block a
+ * later user turn or be cleared by turn-idle reconciliation.
+ */
+function hasPendingAgentInteractionForSession(sessionId: string): boolean {
return (
Array.from(pendingInteractionResolvers.values()).some((entry) => entry.sessionId === sessionId) ||
ghostSetupInteractionBridge.pendingSnapshots(sessionId).length > 0
);
}
+function isPendingDesktopOnlyConfirmation(requestId: string): boolean {
+ return (
+ issueConfirmBridge
+ .pendingSnapshots()
+ .some(({ request }) => request.requestId === requestId) ||
+ renameSessionsConfirmBridge
+ .pendingSnapshots()
+ .some(({ request }) => request.requestId === requestId) ||
+ ghostGrantConfirmBridge
+ .pendingSnapshots()
+ .some(({ request }) => request.requestId === requestId)
+ );
+}
+
function dismissRendererInteraction(
entry: PendingInteractionEntry,
requestId: string,
@@ -1591,7 +1634,7 @@ function defaultDecisionForPending(kind: InteractionRequest['kind'], reason: str
return { kind, behavior: 'deny', reason } as InteractionDecision;
}
-function cleanupPendingInteractionsForSession(sessionId: string, reason: string): void {
+function cleanupPendingAgentInteractionsForSession(sessionId: string, reason: string): void {
const entries = Array.from(pendingInteractionResolvers.entries())
.filter(([, entry]) => entry.sessionId === sessionId);
for (const [requestId, entry] of entries) {
@@ -1600,27 +1643,31 @@ function cleanupPendingInteractionsForSession(sessionId: string, reason: string)
entry.resolve(defaultDecisionForPending(entry.kind, reason));
dismissRendererInteraction(entry, requestId, reason, 'deny');
}
- // issue 确认卡同会话清理(单点收口,覆盖 session_closed / session_aborted /
- // orca_disable / turn_idle_reconcile 全部调用方)。
- issueConfirmBridge.cleanupForSession(
+ ghostSetupInteractionBridge.cleanupForSession(
sessionId,
reason === 'session_closed' ? 'session_closed' : 'session_aborted',
);
- renameSessionsConfirmBridge.cleanupForSession(
+}
+
+function cleanupPendingInteractionsForSession(sessionId: string, reason: string): void {
+ cleanupPendingAgentInteractionsForSession(sessionId, reason);
+ // Desktop-only 确认只跟随真实会话终止/中止清理。权威 NO_ACTIVE_TURN 的
+ // turn-idle reconcile 只处理 Agent-owned 僵尸,不能取消仍有效的 Host 工具等待。
+ issueConfirmBridge.cleanupForSession(
sessionId,
reason === 'session_closed' ? 'session_closed' : 'session_aborted',
);
- ghostGrantConfirmBridge.cleanupForSession(
+ renameSessionsConfirmBridge.cleanupForSession(
sessionId,
reason === 'session_closed' ? 'session_closed' : 'session_aborted',
);
- ghostSetupInteractionBridge.cleanupForSession(
+ ghostGrantConfirmBridge.cleanupForSession(
sessionId,
reason === 'session_closed' ? 'session_closed' : 'session_aborted',
);
// fs 槽 workdir 写确认的会话级记忆只在会话真正关闭时清(防 Set 无界增长)。
- // 本函数在 session_aborted(用户点停止)/ turn_idle_reconcile 等瞬态也会被
- // 调,那些场景确认卡该收、但"同目录本会话免弹"的记忆要保住——否则用户每
+ // 本函数在 session_aborted(用户点停止)等瞬态也会被调,那些场景确认卡该收、
+ // 但"同目录本会话免弹"的记忆要保住——否则用户每
// 次 Stop 后同目录又要重新点一遍允许,与卡片文案承诺不符(review P2)。
if (reason === 'session_closed') {
getGhostFsSlot().cleanupForSession(sessionId);
@@ -7319,7 +7366,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (sess?.isTurnRunning()) return;
const trackerStale = sessionTurnActivityTracker.isSessionInTurn(sessionId) ||
sessionTurnActivityTracker.isSessionTurnDispatchBoundaryBusy(sessionId);
- const hadZombieInteraction = hasPendingInteractionForSession(sessionId);
+ const hadZombieInteraction = hasPendingAgentInteractionForSession(sessionId);
if (!trackerStale && !hadZombieInteraction) return;
log.warn('reconcileTurnIdle: clearing stale busy state after authoritative NO_ACTIVE_TURN', {
sessionId,
@@ -7330,10 +7377,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
markSessionTurnEnded(sessionId);
noteClaudeSessionTurnState(sessionId, false);
if (hadZombieInteraction) {
- cleanupPendingInteractionsForSession(sessionId, 'turn_idle_reconcile');
+ cleanupPendingAgentInteractionsForSession(sessionId, 'turn_idle_reconcile');
}
},
- hasPendingInteraction: hasPendingInteractionForSession,
+ hasPendingInteraction: hasPendingAgentInteractionForSession,
getAgentKind: (sessionId) => maker.getSession(sessionId)?.agentKind ?? null,
getSdkSessionId: async (sessionId) => {
const meta = await maker.getSessionMeta(sessionId).catch(() => null);
@@ -8159,9 +8206,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('INVALID_PARAMS', 'invalid plugin setup decision');
}
// permission / ask / plan and setup cancellation remain remotely
- // resolvable, but Host-owned setup side effects may only originate from
- // the trusted local Desktop.
- assertResolveInteractionOrigin(decision);
+ // resolvable. Host-owned setup side effects and Desktop-only confirmations
+ // may only originate from the trusted local Desktop.
+ assertResolveInteractionOrigin(
+ decision,
+ isPendingDesktopOnlyConfirmation(requestId),
+ );
let pluginSetupResponseTarget: GhostSetupInteractionResponseTarget | undefined;
if (isPluginSetupInteractionDecision(decision) && !isDeviceLinkInvoke()) {
assertTrustedAppRendererEvent(event);
diff --git a/apps/desktop/src/main/session-title-rename/__tests__/renameSessionsConfirmBridge.test.ts b/apps/desktop/src/main/session-title-rename/__tests__/renameSessionsConfirmBridge.test.ts
index ec67de3677..115e51bcb6 100644
--- a/apps/desktop/src/main/session-title-rename/__tests__/renameSessionsConfirmBridge.test.ts
+++ b/apps/desktop/src/main/session-title-rename/__tests__/renameSessionsConfirmBridge.test.ts
@@ -46,6 +46,10 @@ describe('RenameSessionsConfirmBridge', () => {
request: { kind: 'rename_sessions_confirm', changes: CHANGES },
});
expect((payload as { request: { requestId: string } }).request.requestId).toBeTruthy();
+ expect(bridge.pendingSnapshots('other-session')).toEqual([]);
+ expect(bridge.pendingSnapshots('sess-1')).toEqual([
+ { sessionId: 'sess-1', request: (payload as { request: unknown }).request },
+ ]);
});
it('resolve 确认 decision → promise settle 为 confirmed', async () => {
@@ -97,6 +101,7 @@ describe('RenameSessionsConfirmBridge', () => {
const requestId = lastRequestId(broadcast);
vi.advanceTimersByTime(1001);
await expect(promise).resolves.toEqual({ confirmed: false, reason: 'timeout' });
+ expect(bridge.pendingSnapshots()).toEqual([]);
expect(broadcast).toHaveBeenCalledWith(MAKER_PUSH.INTERACTION_DISMISSED, {
sessionId: 'sess-1',
requestId,
@@ -112,6 +117,8 @@ describe('RenameSessionsConfirmBridge', () => {
const p2 = bridge.request('sess-2', CHANGES);
bridge.cleanupForSession('sess-1', 'session_aborted');
await expect(p1).resolves.toEqual({ confirmed: false, reason: 'session_aborted' });
+ expect(bridge.pendingSnapshots('sess-1')).toEqual([]);
+ expect(bridge.pendingSnapshots('sess-2')).toHaveLength(1);
const dismissed = broadcast.mock.calls.filter(
([channel]) => channel === MAKER_PUSH.INTERACTION_DISMISSED,
);
diff --git a/apps/desktop/src/main/session-title-rename/index.ts b/apps/desktop/src/main/session-title-rename/index.ts
index e291474543..8afc4fb68a 100644
--- a/apps/desktop/src/main/session-title-rename/index.ts
+++ b/apps/desktop/src/main/session-title-rename/index.ts
@@ -8,7 +8,10 @@ import type {
} from './renameSessionsConfirmBridge';
export { RenameSessionsConfirmBridge } from './renameSessionsConfirmBridge';
-export type { RenameSessionsConfirmDecision } from './renameSessionsConfirmBridge';
+export type {
+ RenameSessionsConfirmDecision,
+ RenameSessionsConfirmInteractionSnapshot,
+} from './renameSessionsConfirmBridge';
let bridgeHolder: RenameSessionsConfirmBridge | null = null;
diff --git a/apps/desktop/src/main/session-title-rename/renameSessionsConfirmBridge.ts b/apps/desktop/src/main/session-title-rename/renameSessionsConfirmBridge.ts
index bded27aced..03a93f8e81 100644
--- a/apps/desktop/src/main/session-title-rename/renameSessionsConfirmBridge.ts
+++ b/apps/desktop/src/main/session-title-rename/renameSessionsConfirmBridge.ts
@@ -10,6 +10,7 @@
import { randomUUID } from 'node:crypto';
import { MAKER_PUSH } from '../maker-ipc/channels';
+import { HOST_CONFIRM_TIMEOUT_MS } from '../maker-ipc/hostConfirmTiming.js';
export interface RenameSessionsConfirmItem {
sessionId: string;
@@ -26,18 +27,25 @@ export type RenameSessionsConfirmDecision =
reason: 'cancelled' | 'timeout' | 'session_closed' | 'session_aborted';
};
+/** Renderer 可重放的批量改名确认请求;主进程持有它直到确认流程 settle。 */
+export interface RenameSessionsConfirmInteractionSnapshot {
+ kind: 'rename_sessions_confirm';
+ requestId: string;
+ changes: RenameSessionsConfirmItem[];
+}
+
export interface RenameSessionsConfirmBridgeDeps {
broadcast: (channel: string, payload: unknown) => void;
+ /** 确认超时,默认 9 分钟,须早于外层 MCP 的 10 分钟 deadline。测试注小值。 */
timeoutMs?: number;
logger?: { warn: (...args: unknown[]) => void };
/** 同 IssueConfirmBridgeDeps.onDesktopOnlyConfirmPending(#926):IM 侧「去桌面确认」提示。 */
onDesktopOnlyConfirmPending?: (sessionId: string) => void;
}
-const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
-
interface PendingConfirmEntry {
sessionId: string;
+ request: RenameSessionsConfirmInteractionSnapshot;
resolve: (decision: RenameSessionsConfirmDecision) => void;
timeoutId: ReturnType<typeof setTimeout>;
}
@@ -52,15 +60,20 @@ export class RenameSessionsConfirmBridge {
changes: RenameSessionsConfirmItem[],
): Promise<RenameSessionsConfirmDecision> {
const requestId = randomUUID();
+ const request: RenameSessionsConfirmInteractionSnapshot = {
+ kind: 'rename_sessions_confirm',
+ requestId,
+ changes,
+ };
return new Promise<RenameSessionsConfirmDecision>((resolve) => {
- const timeoutMs = this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const timeoutMs = this.deps.timeoutMs ?? HOST_CONFIRM_TIMEOUT_MS;
const timeoutId = setTimeout(() => {
this.settle(requestId, { confirmed: false, reason: 'timeout' }, 'timeout');
}, timeoutMs);
- this.pending.set(requestId, { sessionId, resolve, timeoutId });
+ this.pending.set(requestId, { sessionId, request, resolve, timeoutId });
this.deps.broadcast(MAKER_PUSH.INTERACTION_REQUEST, {
sessionId,
- request: { kind: 'rename_sessions_confirm', requestId, changes },
+ request,
});
try {
this.deps.onDesktopOnlyConfirmPending?.(sessionId);
@@ -75,14 +88,27 @@ export class RenameSessionsConfirmBridge {
});
}
+ /** 打开、重连或刷新会话时供 renderer 补回错过的确认卡。 */
+ pendingSnapshots(sessionId?: string): Array<{
+ sessionId: string;
+ request: RenameSessionsConfirmInteractionSnapshot;
+ }> {
+ return Array.from(this.pending.values())
+ .filter((entry) => sessionId === undefined || entry.sessionId === sessionId)
+ .map((entry) => ({ sessionId: entry.sessionId, request: entry.request }));
+ }
+
resolve(requestId: string, rawDecision: unknown): boolean {
const entry = this.pending.get(requestId);
if (!entry) return false;
let decision = parseDecision(rawDecision);
if (!decision) {
- this.deps.logger?.warn('rename-sessions-confirm: invalid decision shape, fallback to cancelled', {
- requestId,
- });
+ this.deps.logger?.warn(
+ 'rename-sessions-confirm: invalid decision shape, fallback to cancelled',
+ {
+ requestId,
+ },
+ );
decision = { confirmed: false, reason: 'cancelled' };
}
this.settlePending(requestId, entry, decision);
@@ -95,10 +121,7 @@ export class RenameSessionsConfirmBridge {
return true;
}
- cleanupForSession(
- sessionId: string,
- reason: 'session_closed' | 'session_aborted',
- ): void {
+ cleanupForSession(sessionId: string, reason: 'session_closed' | 'session_aborted'): void {
for (const [requestId, entry] of Array.from(this.pending.entries())) {
if (entry.sessionId !== sessionId) continue;
this.settle(requestId, { confirmed: false, reason }, reason);
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index 4811f98320..713bf832ff 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -50,10 +50,7 @@ vi.mock('@/lib/composerDraftStore', () => ({
import { makerChatStore } from '@/lib/makerChatStore';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import * as messageService from '@/lib/messageService';
-import {
- getIssueConfirmDraft,
- saveIssueConfirmDraft,
-} from '@/lib/issueConfirmDraftStore';
+import { getIssueConfirmDraft, saveIssueConfirmDraft } from '@/lib/issueConfirmDraftStore';
type RemotePush = { deviceId: string; channel: string; payload: unknown };
type ResolveCall = { requestId: string; decision: Record<string, unknown> };
@@ -140,7 +137,11 @@ function stubElectronApi(host: FakeHost) {
const localSetPermissionMode = vi.fn(async () => {});
const localSetFastMode = vi.fn(async () => {});
const localGetPendingInteractions = vi.fn(
- async () => [] as Array<{ request: { kind: string; requestId: string }; persistId?: string }>,
+ async () =>
+ [] as Array<{
+ request: { kind: string; requestId: string; [key: string]: unknown };
+ persistId?: string;
+ }>,
);
(globalThis as { window?: unknown }).window = {
electronAPI: {
@@ -620,6 +621,50 @@ describe('device-link 远程交互 — dismissed / 顺序 / 本机零回归', ()
});
describe('device-link 交互快照重建 — 窗口在交互挂起之后才打开(无 live push)', () => {
+ it('本机 issue_confirm:无 push → 快照重建确认卡,重复重放保留用户草稿', async () => {
+ const s = sid();
+ local.localGetPendingInteractions.mockResolvedValue([
+ {
+ request: {
+ kind: 'issue_confirm',
+ requestId: 'issue-mid',
+ draft: { title: '原始标题', body: '原始正文', type: 'bug' },
+ env: {
+ appVersion: '0.1.23',
+ platform: 'darwin',
+ arch: 'arm64',
+ osVersion: '25.0',
+ region: 'cn',
+ },
+ submissionIdentity: { kind: 'platform', login: 'cindy-issue' },
+ suggestedPublicName: '当前昵称',
+ },
+ },
+ ]);
+
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ await flush();
+ expect(makerChatStore.getSnapshot(s).pendingIssueConfirm?.requestId).toBe('issue-mid');
+ expect(local.localGetPendingInteractions).toHaveBeenCalledWith(s);
+ expect(host.invoke).not.toHaveBeenCalledWith(DEVICE_ID, 'maker:get-pending-interactions', [s]);
+
+ saveIssueConfirmDraft(s, 'issue-mid', {
+ title: '用户编辑后的标题',
+ body: '用户编辑后的正文',
+ type: 'feature',
+ publicName: '匿名',
+ });
+ await makerChatStore.reconcilePendingInteractions(s);
+ expect(getIssueConfirmDraft(s, 'issue-mid')).toMatchObject({
+ title: '用户编辑后的标题',
+ body: '用户编辑后的正文',
+ type: 'feature',
+ publicName: '匿名',
+ });
+ makerChatStore.purgeSession(s);
+ });
+
it('permission:被控端已挂起 + 不发 push → ensureInitialMessages 后重建 pendingPermission', async () => {
const s = openRemoteSession();
host.seedPending(s, {