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): 上下文环压缩入口按 agent 能力分流,pi 走 compact-session 通道 (#1933)

KingSystemHaiGo5c09a225f650
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index 690664ea7f..442aae98c7 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -1195,7 +1195,9 @@ describe('被控端控制链路生命周期', () => {
expect(hasInFlightRemoteInvokes()).toBe(true);
expect(busyChanges).toEqual([true]);
- await vi.advanceTimersByTimeAsync(dispatchTesting.remoteInvokeOrphanTimeoutMs);
+ await vi.advanceTimersByTimeAsync(
+ dispatchTesting.remoteInvokeOrphanTimeoutForChannelMs('maker:list-active'),
+ );
expect(calls.invokeResult).toContainEqual({
dst: 'ctrl-a',
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index 5202a51263..fe859873ce 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -460,3 +460,15 @@ describe('[3] outbox 保留时长按 channel 收窄', () => {
expect(__testing.remoteInvokeResultOutboxSize()).toBe(0); // 121s:worktree 也到期
});
});
+
+describe('[5] orphan 截止时间按 channel 收窄', () => {
+ it('默认 invoke 保持 60s,只有 compact 使用 22min 长预算', () => {
+ const compactBudget = INVOKE_TIMEOUT_OVERRIDES_MS['maker:compact-session'];
+ expect(compactBudget).toBe(11 * 60_000);
+ expect(__testing.remoteInvokeOrphanTimeoutForChannelMs(undefined)).toBe(60_000);
+ expect(__testing.remoteInvokeOrphanTimeoutForChannelMs('maker:list-active')).toBe(60_000);
+ expect(__testing.remoteInvokeOrphanTimeoutForChannelMs('maker:compact-session')).toBe(
+ compactBudget * 2,
+ );
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index a250b16eb2..2c706fc087 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -473,8 +473,10 @@ const REMOTE_INVOKE_RESULT_OUTBOX_RETRY_MS = 500;
* subscribe 定向 flush(已有)。
*/
const REMOTE_INVOKE_RESULT_OUTBOX_OFFLINE_SWEEP_MS = 5_000;
+/** 默认远程调用客户端等待预算(缺省 30s;无超时覆盖的 channel 用此值,与 allowlist 注释一致)。 */
+const DEFAULT_REMOTE_INVOKE_CLIENT_WAIT_MS = 30_000;
const REMOTE_INVOKE_MAX_CLIENT_WAIT_MS = Math.max(
- 30_000,
+ DEFAULT_REMOTE_INVOKE_CLIENT_WAIT_MS,
...Object.values(INVOKE_TIMEOUT_OVERRIDES_MS),
);
/** 再保留一轮同等重连窗口后才放弃无人等待的回包(全局上限;逐条按 channel 收窄)。 */
@@ -482,13 +484,14 @@ const REMOTE_INVOKE_RESULT_OUTBOX_MAX_AGE_MS = REMOTE_INVOKE_MAX_CLIENT_WAIT_MS
/**
* outbox 条目的逐 channel 保留时长:控制端对该 channel 的等待预算(两端共享
- * INVOKE_TIMEOUT_OVERRIDES_MS,缺省 30s)× 2(再留一轮重连窗口),封顶全局上限。
+ * INVOKE_TIMEOUT_OVERRIDES_MS,缺省默认预算)× 2(再留一轮重连窗口),封顶全局上限。
* 控制端超时后不会再认领旧 requestId 的回包(重发用新 id),listing 类回包在
* 弱网时段最多占 outbox 两分钟纯属浪费配额;长任务 channel(60s 预算)自动保留
* 更久。控制端可能配置更短的超时(mobile 15s),推断值只偏保守、不早丢。
*/
function outboxEntryMaxAgeMs(channel: string | undefined): number {
- const budgetMs = (channel && INVOKE_TIMEOUT_OVERRIDES_MS[channel]) || 30_000;
+ const budgetMs =
+ (channel && INVOKE_TIMEOUT_OVERRIDES_MS[channel]) || DEFAULT_REMOTE_INVOKE_CLIENT_WAIT_MS;
return Math.min(budgetMs * 2, REMOTE_INVOKE_RESULT_OUTBOX_MAX_AGE_MS);
}
/**
@@ -496,6 +499,18 @@ function outboxEntryMaxAgeMs(channel: string | undefined): number {
* 这里只在远超控制端等待窗后回收本地 bookkeeping;底层 Promise 仍带 catch 并允许自行收尾。
*/
const REMOTE_INVOKE_ORPHAN_TIMEOUT_MS = REMOTE_INVOKE_MAX_CLIENT_WAIT_MS * 2;
+/**
+ * 逐 channel 收窄(codex P2):orphan 截止时间按「该 channel 的控制端等待预算 × 2」取,
+ * 被全局上限(REMOTE_INVOKE_ORPHAN_TIMEOUT_MS)封顶,与 outboxEntryMaxAgeMs 同款。
+ * 否则 maker:compact-session 的 11min 覆盖会把全局 orphan 拉高到 22min——任何挂起的
+ * 默认 30s handler 都会占满 controller 的 in-flight 配额整整 22 分钟,后续远程控制
+ * 动作看起来卡住(BACKPRESSURE)。
+ */
+function remoteInvokeOrphanTimeoutMs(channel: string | undefined): number {
+ const budgetMs =
+ (channel && INVOKE_TIMEOUT_OVERRIDES_MS[channel]) || DEFAULT_REMOTE_INVOKE_CLIENT_WAIT_MS;
+ return Math.min(budgetMs * 2, REMOTE_INVOKE_ORPHAN_TIMEOUT_MS);
+}
interface CachedRemoteInvokeResult {
result: InvokeResultPayload;
bytes: number;
@@ -1839,6 +1854,7 @@ function settleRemoteInvokeWithOrphanDeadline(
channel: string | undefined,
): Promise<InvokeResultPayload> {
let timer: ReturnType<typeof setTimeout> | null = null;
+ const orphanMs = remoteInvokeOrphanTimeoutMs(channel);
const timeout = new Promise<InvokeResultPayload>((resolve) => {
timer = setTimeout(() => {
timer = null;
@@ -1851,11 +1867,11 @@ function settleRemoteInvokeWithOrphanDeadline(
error: {
code: 'IPC_ERROR',
message:
- `[TIMEOUT] remote invoke exceeded ${REMOTE_INVOKE_ORPHAN_TIMEOUT_MS}ms; ` +
+ `[TIMEOUT] remote invoke exceeded ${orphanMs}ms; ` +
'the underlying operation may still be running',
},
});
- }, REMOTE_INVOKE_ORPHAN_TIMEOUT_MS);
+ }, orphanMs);
(timer as unknown as { unref?: () => void }).unref?.();
});
return Promise.race([execution, timeout]).finally(() => {
@@ -2873,6 +2889,7 @@ export const __testing = {
remoteInvokeInFlightLimit: REMOTE_INVOKE_IN_FLIGHT_LIMIT,
remoteInvokeInFlightPerControllerLimit: REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT,
remoteInvokeOrphanTimeoutMs: REMOTE_INVOKE_ORPHAN_TIMEOUT_MS,
+ remoteInvokeOrphanTimeoutForChannelMs: remoteInvokeOrphanTimeoutMs,
remoteInvokeResultOutboxLimit: REMOTE_INVOKE_RESULT_OUTBOX_LIMIT,
remoteInvokeResultOutboxPerControllerLimit: REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_LIMIT,
remoteInvokeResultOutboxSize: () => remoteInvokeResultOutbox.size,
diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
index f2b04543f0..6f06d6cde2 100644
--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
@@ -22,6 +22,7 @@ function stubElectron() {
getContextUsage: vi.fn(),
setExtraDirs: vi.fn(),
closeSession: vi.fn(),
+ compactSession: vi.fn().mockResolvedValue({ tokensBefore: 100, estimatedTokensAfter: 20 }),
enableOrca: vi.fn(),
disableOrca: vi.fn(),
regenerateSessionTitle: vi.fn().mockResolvedValue({ title: 'local title' }),
@@ -70,6 +71,7 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
api.getContextUsage('rs', { agentKind: 'codex', workingDir: '/w', model: 'm' });
api.setExtraDirs('rs', ['/a']);
api.closeSession('rs');
+ api.compactSession('rs', 'focus on API design');
api.enableOrca('rs', { workerAgent: 'codex' });
api.disableOrca('rs');
api.input.compact(
@@ -89,6 +91,7 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
]);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:set-extra-dirs', ['rs', ['/a']]);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:close-session', ['rs']);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:compact-session', ['rs', 'focus on API design']);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:session:enable-orca', [
'rs',
{ workerAgent: 'codex' },
@@ -116,6 +119,18 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
expect(makerSpies.setEffort).not.toHaveBeenCalled();
});
+ it('远程 compactSession 裁掉尾部 undefined,同时保留显式空 instructions', async () => {
+ const { invoke } = stubElectron();
+ const { makerApiForDevice } = await import('@/lib/makerTransport');
+ const api = makerApiForDevice('dev-wire');
+
+ await api.compactSession('rs');
+ await api.compactSession('rs', '');
+
+ expect(invoke).toHaveBeenNthCalledWith(1, 'dev-wire', 'maker:compact-session', ['rs']);
+ expect(invoke).toHaveBeenNthCalledWith(2, 'dev-wire', 'maker:compact-session', ['rs', '']);
+ });
+
it('远程 setModel 压缩 JSON 可选参数,保留中间占位且裁掉尾部 null', async () => {
const { invoke } = stubElectron();
const { makerApiForDevice } = await import('@/lib/makerTransport');
@@ -328,12 +343,21 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
invoke.mockClear();
makerSpies.enableOrca.mockClear();
+ makerSpies.compactSession.mockClear();
await makerApiForSticky('lead').enableOrca('lead', { workerAgent: 'codex' });
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:session:enable-orca', [
'lead',
{ workerAgent: 'codex' },
]);
expect(makerSpies.enableOrca).not.toHaveBeenCalled();
+ // 手动压缩同属「误判本机会静默失败」的 mutation(greptile P1):远程 pi 压缩必须
+ // 隧道到被控端,重连窗口内不退回控制端本机 maker(本机无该 live 会话 → null)。
+ await makerApiForSticky('lead').compactSession('lead', 'focus on API design');
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:compact-session', [
+ 'lead',
+ 'focus on API design',
+ ]);
+ expect(makerSpies.compactSession).not.toHaveBeenCalled();
});
it('makerApiForSticky:从未解析过归属的本机会话仍走本机(零回归)', async () => {
@@ -343,6 +367,8 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
await makerApiForSticky('local-only').disableOrca('local-only');
expect(makerSpies.disableOrca).toHaveBeenCalledWith('local-only');
expect(invoke).not.toHaveBeenCalled();
+ await makerApiForSticky('local-only').compactSession('local-only');
+ expect(makerSpies.compactSession).toHaveBeenCalledWith('local-only');
});
// issue #1170:协同入口的项目级 collab 开关此前一律查控制端本机 —— 拿被控端的路径查
diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
index f081badf83..4cd93cabad 100644
--- a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
@@ -13,6 +13,8 @@ import { resolve } from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
+import { resolveManualCompactChannel } from '@/hooks/useAgentCapabilities';
+import { createSessionScopedRequestGuard } from '@/features/cc-agent/sessionScopedRequestGuard';
const sess = (id: string): Session => ({ id }) as unknown as Session;
@@ -900,3 +902,167 @@ describe('ChatInput 的入口门控与调用路由', () => {
);
});
});
+
+describe('CCAgentSessionView 上下文环压缩入口按 agent 能力分流(#1927)', () => {
+ const viewSource = readFileSync(
+ resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+
+ it('onCompact 门控:通道存在 + pi 排除 SSH 远程(remoteHostId) + pi running 禁用,codex 无通道不开放', () => {
+ // 门控不再硬编码 agentKind 排除列表:以 compactChannel(能力判定)为准;
+ // pi 的 SSH 远程会话(remoteHostId)无 compact-session 路由 → 显式排除
+ // (与 SessionContentHeader 压缩菜单仅本地/device-link 一致,Copilot P2)。
+ expect(viewSource).toContain('compactChannel !== null');
+ expect(viewSource).toContain("!(realAgentKind === 'pi' && !!session?.remoteHostId)");
+ // pi 回合运行中会拒绝压缩 → compact-session 通道 running 时禁用(与
+ // SessionContentHeader 的 runningSessionIds 一致,codex P1);claude-input 保留旧行为。
+ expect(viewSource).toContain(
+ "!(compactChannel === 'compact-session' && agentStatus.isRunning)",
+ );
+ // codex(无 manualCompact)→ compactChannel null → 不开放(纯展示)。
+ });
+
+ it('compact-session 分支:粘滞路由 + 确认框后重新分流 + 失败反馈', () => {
+ // 分流以当前 render 的 compactChannel 判定(channelNow),确认框返回后重新解析——
+ // 同会话在其它窗口/远程被切换 agent 时捕获值会过期(codex P1)。
+ expect(viewSource).toContain("if (channelNow === 'compact-session') {");
+ // workingDir 只对 claude-input 是硬前提:compact-session(pi 原生压缩)不依赖它。
+ expect(viewSource).toContain(
+ "if (sourceCompactChannel === 'claude-input' && !sourceSession.workingDir) return;",
+ );
+ // device-link 远程 pi:粘滞归属路由到被控端,relay 重连窗口内不退回本机(greptile P1)。
+ expect(viewSource).toContain('const sourceSessionId = sourceSession.id;');
+ expect(viewSource).toContain('const maker = makerApiForSticky(sourceSessionId);');
+ expect(viewSource).toContain('await maker.compactSession(sourceSessionId)');
+ // 在途期间切换会话 / 登出 / 切回(换代):旧响应不得在当前视图弹 toast(并发收口)。
+ expect(viewSource).toContain('const committedSessionId = sessionId ?? null;');
+ expect(viewSource).toContain('compactRequestGuard.setCurrentSession(committedSessionId)');
+ // 代校验:sessionId 当前 + 请求代一致;finally 里 release(不再按 sessionId finish)。
+ expect(viewSource).toContain('const begun = compactRequestGuard.tryBegin(sourceSessionId);');
+ expect(viewSource).toContain('if (!begun) return;');
+ expect(viewSource).toContain('compactRequestGuard.isCurrent(sourceSessionId, begun.epoch)');
+ expect(viewSource).toContain('begun.release();');
+ // 真实 reject 必须 catch 并显示 compactFailed(与 SessionContentHeader 一致)。
+ expect(viewSource).toContain("toast.warning(t('ccAgent.sidebar.sessionMenu.compactFailed'))");
+ });
+
+ it('claude-code 分支保持 inputCoordinator compactSession(model,...),不误入 compact-session', () => {
+ // compact-session 分支以 return 结束;return 之前只有 makerApiForSticky 通道,
+ // 不调用 inputCoordinator 的 compactSession(model, effort, ...)(即 maker:input:compact)。
+ const csStart = viewSource.indexOf("if (channelNow === 'compact-session')");
+ expect(csStart).toBeGreaterThan(-1); // 定位必须命中,否则断言形同虚设(copilot review)
+ const csEnd = viewSource.indexOf('return;', csStart);
+ const csBranch = viewSource.slice(csStart, csEnd);
+ expect(csBranch).not.toContain('await compactSession(');
+ // 确认框返回后若 channel 已消失(能力被撤/agent 切换)则放弃,不静默误调。
+ // 关键:重分流必须读 compactChannelRef.current(useCallback 闭包固定捕获旧值,
+ // 旧 async 函数 await 期间重新 render 也不会更新闭包——greptile review)。
+ expect(viewSource).toContain('const compactChannelRef = useRef(compactChannel);');
+ expect(viewSource).toContain('compactChannelRef.current = compactChannel;');
+ expect(viewSource).toContain('const channelNow = compactChannelRef.current;');
+ expect(viewSource).toContain('if (channelNow === null) return;');
+ // claude 通道执行前才校验 workingDir(输入协调器硬前提),且参数必须来自**最新**
+ // session 快照——同会话切换 agent 后 model/effort/permission/workingDir 已变化,
+ // 旧快照会按错误配置执行(greptile P1 / codex P2)。
+ expect(viewSource).toContain('const sessionRef = useRef(session);');
+ expect(viewSource).toContain('sessionRef.current = session;');
+ expect(viewSource).toContain('const sessionNow = sessionRef.current;');
+ expect(viewSource).toContain("if (channelNow !== 'claude-input') return;");
+ expect(viewSource).toContain('if (!sessionNow?.workingDir) return;');
+ expect(viewSource).toContain('sessionNow.model,');
+ // 确认框期间 turn 可能已从其它窗口/远程启动:render 时 isRunning 守卫失效,重读
+ // 最新 running ref,活跃 turn 的 pi 拒绝压缩 → 放弃(codex P2);claude-input 保留旧行为。
+ expect(viewSource).toContain('const isRunningRef = useRef(agentStatus.isRunning);');
+ expect(viewSource).toContain('isRunningRef.current = agentStatus.isRunning;');
+ expect(viewSource).toContain(
+ "if (channelNow === 'compact-session' && isRunningRef.current) return;",
+ );
+ });
+});
+
+describe('上下文环压缩请求按 sessionId 隔离(#1927 并发/生命周期回归)', () => {
+ it('A 在途时 B 可独立开始,A 的迟到 release 不会清掉 B 的锁', () => {
+ const guard = createSessionScopedRequestGuard();
+ guard.setCurrentSession('A');
+ const beginA = guard.tryBegin('A');
+ expect(beginA).not.toBeNull();
+ expect(guard.tryBegin('A')).toBeNull(); // 同代同会话防重
+
+ guard.setCurrentSession('B');
+ expect(guard.isCurrent('A')).toBe(false);
+ const beginB = guard.tryBegin('B');
+ expect(beginB).not.toBeNull();
+
+ beginA!.release();
+ expect(guard.tryBegin('B')).toBeNull(); // B 的锁还在
+ beginB!.release();
+ expect(guard.tryBegin('B')).not.toBeNull();
+ });
+
+ it('A 在途切 B 再切回 A(换代):旧请求失效,且新点击不被旧锁挡住', () => {
+ // greptile P1:守卫只按 sessionId 判断时,切回 A 后旧 A 请求会重新通过 isCurrent
+ // (迟到 toast),旧锁还会让新点击被静默丢弃。代(epoch)语义修复两者。
+ const guard = createSessionScopedRequestGuard();
+ guard.setCurrentSession('A');
+ const oldA = guard.tryBegin('A');
+ expect(oldA).not.toBeNull();
+ const oldEpoch = oldA!.epoch;
+
+ guard.setCurrentSession('B');
+ guard.setCurrentSession('A'); // 切回 A → 换代
+
+ // 旧 A 请求:sessionId 当前但代不匹配 → 失效(不弹迟到 toast)。
+ expect(guard.isCurrent('A', oldEpoch)).toBe(false);
+ expect(guard.isCurrent('A')).toBe(true); // 无代校验时仍视为当前展示会话
+ // 新点击:同会话但新代 → 不被旧锁挡住,可独立开始。
+ const newA = guard.tryBegin('A');
+ expect(newA).not.toBeNull();
+ expect(newA!.epoch).not.toBe(oldEpoch);
+ newA!.release();
+ oldA!.release();
+ });
+
+ it('切换会话或登出会让确认框/迟到响应的旧 scope 失效', () => {
+ const guard = createSessionScopedRequestGuard();
+ guard.setCurrentSession('A');
+ const beginA = guard.tryBegin('A');
+ expect(beginA).not.toBeNull();
+ const epochA = beginA!.epoch;
+ guard.setCurrentSession('B');
+ expect(guard.isCurrent('A', epochA)).toBe(false);
+ expect(guard.isCurrent('B')).toBe(true);
+ guard.setCurrentSession(null);
+ expect(guard.isCurrent('B')).toBe(false);
+ });
+});
+
+describe('resolveManualCompactChannel(#1927 压缩通道判定,行为测试)', () => {
+ // zqchris 要求按行为覆盖而非源码字符串匹配:共享判定收敛成纯函数,直接测语义。
+ it('真实 Claude Code → claude-input(maker:input:compact),与 capability 无关', () => {
+ expect(resolveManualCompactChannel('claude-code', null)).toBe('claude-input');
+ expect(
+ resolveManualCompactChannel('claude-code', {
+ manualCompact: { supported: false, reason: 'sdk-missing' },
+ }),
+ ).toBe('claude-input');
+ });
+
+ it('声明 manualCompact.supported(当前仅 pi)→ compact-session(capability-aware 通道)', () => {
+ expect(resolveManualCompactChannel('pi', { manualCompact: { supported: true } })).toBe(
+ 'compact-session',
+ );
+ });
+
+ it('无能力(Codex / 能力快照缺失)→ 无入口,不按 agentKind 扩排除列表', () => {
+ expect(resolveManualCompactChannel('codex', null)).toBeNull();
+ expect(
+ resolveManualCompactChannel('codex', {
+ manualCompact: { supported: false, reason: 'sdk-missing' },
+ }),
+ ).toBeNull();
+ // 能力快照未命中(缓存未就绪)保守关闭入口,而不是猜能力。
+ expect(resolveManualCompactChannel('pi', null)).toBeNull();
+ expect(resolveManualCompactChannel(undefined, null)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 9681e8d27a..e54b5c064f 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -115,10 +115,14 @@ import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import { canAccessBillingSettings } from '@/components/settings/billingVisibility';
import { useDeviceProviders } from '@/hooks/useDeviceProviders';
-import { useAgentCapabilities } from '@/hooks/useAgentCapabilities';
+import { useAgentCapabilities, resolveManualCompactChannel } from '@/hooks/useAgentCapabilities';
import { useLiveErrorSourceProvider } from '@/hooks/useLiveErrorSourceProvider';
import { resolveFastSupported } from '@/lib/providerModels';
import { useRemoteSessionSync } from '@/features/cc-agent/hooks/useRemoteSessionSync';
+import {
+ createSessionScopedRequestGuard,
+ type SessionScopedRequestGuard,
+} from './sessionScopedRequestGuard';
import {
useDeviceLinkConnectionIssue,
useRemoteSessionConnection,
@@ -178,6 +182,7 @@ import { extractIpcError } from '@/utils/ipcError';
import { listActiveRunsForSession } from '@/features/learn/useLearnRun';
import { subscribeLearnEvents } from '@/features/learn/learnTransport';
import { getUserPrompt } from '@/lib/userPromptStore';
+import { makerApiForSticky } from '@/lib/makerTransport';
import {
consumePending,
consumePendingGoal,
@@ -1349,7 +1354,37 @@ export function CCAgentSessionView({
} = useCCAgentChat(sessionId, handleTitleUpdate, { chatRealtime });
// 展示引擎可乐观跟随 intent;真实 event reducer 仍只读 store.agentKind。
const displayAgentKind = agentSwitchIntent?.target ?? dbToMakerAgentKind(session?.agentKind);
+ // 真实会话 agentKind(pending switch intent 不影响)——压缩分流必须用它,
+ // 否则 intent 乐观切到 pi 但真实会话仍在跑 claude-code 时会错调 compact-session(#1933 review)。
+ const realAgentKind = dbToMakerAgentKind(session?.agentKind);
const isCodex = displayAgentKind === 'codex';
+ // 手动压缩通道判定(#1927/#1933 review):真实 Claude Code → maker:input:compact;
+ // 其余 agent 声明 manualCompact.supported(当前仅 pi)→ maker:compact-session;其余无入口。
+ // 能力取**真实 agent**(displayAgentKind 在 pending switch 期间可能乐观指向目标 agent,
+ // 用它判定会与 realAgentKind 分流不一致);remoteDeviceId 让远程 pi 取被控端能力。
+ const { capabilities: realSessionCaps } = useAgentCapabilities(realAgentKind, remoteDeviceId);
+ const compactChannel = useMemo(
+ () => resolveManualCompactChannel(realAgentKind, realSessionCaps),
+ [realAgentKind, realSessionCaps],
+ );
+ // 最新 channel 的可变镜像:useCallback 闭包在创建后固定捕获 compactChannel,确认框
+ // await 期间同会话切换 agent(跨窗口/远程,sessionId 不变)会产生新 render 但旧 async
+ // 闭包还在跑——从闭包读到的还是旧 channel(greptile review)。ref 每次 render 同步,
+ // 异步执行中读 ref.current 才能拿到切换后的最新通道,且无需重建回调。
+ const compactChannelRef = useRef(compactChannel);
+ compactChannelRef.current = compactChannel;
+ // 最新 session 快照的可变镜像(与 compactChannelRef 同款):确认框 await 期间同会话
+ // 切换 agent 后,model/effort/permissionMode/workingDir 全部可能变化——claude-input
+ // 分支必须用切换后的快照,否则会用旧 Pi 的模型/权限去执行 Claude 的 /compact
+ // (greptile P1 / codex P2 review)。compact-session 分支只依赖 sessionId,无需此快照。
+ const sessionRef = useRef(session);
+ sessionRef.current = session;
+ // 最新 running 状态的可变镜像(与 compactChannelRef / sessionRef 同款):render 闭包
+ // 固定捕获 agentStatus.isRunning——确认框 await 期间 turn 可能已从其它窗口 / 远程
+ // 启动,旧 async 闭包读不到;ref 每次 render 同步,确认后重读才能拦住「活跃 turn
+ // 仍调 compact-session → pi 拒绝 → confirm 后吃 rejection toast」(codex P2)。
+ const isRunningRef = useRef(agentStatus.isRunning);
+ isRunningRef.current = agentStatus.isRunning;
// live 供应商目录(含内置 + 自定义,按 agent 挂模型)—— vendor↔model 一致性校验的真源,
// 与模型选择器同源(见下方 M35 vendor fallback effect)。本地 IPC 极快返回,有模块级缓存。
// device-link 远程会话用被控端经隧道带来的 providers(per-provider,fast 判定与本地同口径)。
@@ -2890,19 +2925,45 @@ export function CCAgentSessionView({
const { confirm: confirmDialog } = useConfirmDialog();
// 防双击重入:ConfirmDialogProvider 是队列语义,弹窗 mount 前的连续点击会入队
- // 多个 confirm,逐个确认就会发多次 compact 请求。in-flight 期间后续点击直接 no-op。
- const compactRequestInFlightRef = useRef(false);
+ // 多个 confirm,逐个确认就会发多次 compact 请求。锁按 sessionId 隔离:A 的长请求不
+ // 阻塞切换后的 B,A 的迟到 finally 也不能清掉 B 的锁。
+ const compactRequestGuardRef = useRef<SessionScopedRequestGuard | null>(null);
+ if (!compactRequestGuardRef.current) {
+ compactRequestGuardRef.current = createSessionScopedRequestGuard();
+ }
+ const compactRequestGuard = compactRequestGuardRef.current;
+ // commit 阶段切换当前会话:中断 render 不应提前作废旧视图请求;layout effect 又早于用户
+ // 交互与异步回调。setup 也要重写 sessionId,确保 React StrictMode 的 setup→cleanup→setup
+ // 重放后不会停在 null。
+ useLayoutEffect(() => {
+ const committedSessionId = sessionId ?? null;
+ compactRequestGuard.setCurrentSession(committedSessionId);
+ return () => {
+ // session 变更 / 路由离开 / 登出后旧请求的确认结果与迟到响应立即失效。
+ if (committedSessionId && compactRequestGuard.isCurrent(committedSessionId)) {
+ compactRequestGuard.setCurrentSession(null);
+ }
+ };
+ }, [compactRequestGuard, sessionId]);
const handleCompactRequest = useCallback(async () => {
- if (!session) return;
- if (!session.workingDir) return;
- if (compactRequestInFlightRef.current) return;
- compactRequestInFlightRef.current = true;
+ const sourceSession = session;
+ if (!sourceSession) return;
+ // 必须在第一个 await 前捕获 scope/channel。确认框打开期间路由切换时,旧闭包不得
+ // 从可变 ref 读取到新 sessionId 后把旧请求误认成当前请求。
+ const sourceSessionId = sourceSession.id;
+ const sourceCompactChannel = compactChannel;
+ // 无通道(Codex 等)不弹确认框;workingDir 只对 claude-input 是硬前提——
+ // compact-session(pi 原生压缩)不依赖 workingDir,不能被它挡掉(copilot review)。
+ if (sourceCompactChannel === null) return;
+ if (sourceCompactChannel === 'claude-input' && !sourceSession.workingDir) return;
+ const begun = compactRequestGuard.tryBegin(sourceSessionId);
+ if (!begun) return;
try {
const contextWindow = resolveDisplayContextWindow({
sdkContextWindow: agentStatus.contextWindow,
modelContextWindow: getModelContextWindow(
- session.model,
- session.agentKind ?? 'cc',
+ sourceSession.model,
+ sourceSession.agentKind ?? 'cc',
remoteDeviceId,
),
});
@@ -2918,19 +2979,67 @@ export function CCAgentSessionView({
confirmText: t('ccAgent.layout.contextRing.confirmAction'),
cancelText: t('ccAgent.layout.contextRing.confirmCancel'),
});
- if (!ok) return;
+ // 代校验:sessionId 当前 + 请求代一致——切走再切回(换代)后旧请求不再生效
+ // (greptile P1:否则旧确认结果/迟到 toast 会在重新进入的视图里弹)。
+ if (!ok || !compactRequestGuard.isCurrent(sourceSessionId, begun.epoch)) return;
+ // 确认框打开期间,同一会话可能已在其它窗口 / 远程控制器被切换 agent(sessionId
+ // 不变):捕获的 sourceCompactChannel 已过期。必须读**最新** channel —— 从
+ // compactChannelRef.current 取(useCallback 闭包固定捕获旧值,重新 render 也不影响
+ // 正在 await 的旧 async 函数;ref 每次 render 同步,这里拿到的是切换后的通道)。
+ // 否则 Pi→Claude 会静默 null、Claude→Pi 会误走 claude 专用通道(codex P1 / greptile)。
+ const channelNow = compactChannelRef.current;
+ if (channelNow === null) return;
+ // 确认框期间 turn 可能已从其它窗口 / 远程启动:render 时的 isRunning 守卫已失效,
+ // 重读最新 running——活跃 turn 的 pi 会拒绝压缩,直接放弃,避免 confirm 后吃
+ // rejection toast(codex P2)。claude-input 保留旧行为。
+ if (channelNow === 'compact-session' && isRunningRef.current) return;
+ if (channelNow === 'compact-session') {
+ // capability-aware 通道(pi 原生 compact):本地 IPC / device-link 隧道均可路由。
+ // 用粘滞归属(makerApiForSticky)——relay 瞬时重连清空 origin 的窗口内仍隧道到
+ // 被控端,不退回控制端本机(本机无该 live 会话,固定调本机必 null 静默失败,
+ // greptile P1)。claude-code 分支继续走 inputCoordinator,不在此通道内。
+ // pi 原生压缩不依赖 workingDir,这里不再校验(copilot review)。
+ const maker = makerApiForSticky(sourceSessionId);
+ try {
+ const result = await maker.compactSession(sourceSessionId);
+ // 在途期间切换会话 / 登出 / 切回(换代):旧响应不得在当前视图弹 toast。
+ if (!compactRequestGuard.isCurrent(sourceSessionId, begun.epoch)) return;
+ if (result?.noop) {
+ // 良性:上下文太小,无可压缩内容。信息性提示,不是失败。
+ toast.info(t('ccAgent.sidebar.sessionMenu.compactNothing'));
+ } else if (result) {
+ toast.success(t('ccAgent.sidebar.sessionMenu.compactSuccess'));
+ }
+ // null:会话无 live 进程 / 不支持(入口已按 gate 隐藏,极少走到)。静默即可。
+ } catch (err) {
+ if (!compactRequestGuard.isCurrent(sourceSessionId, begun.epoch)) return;
+ // 与 SessionContentHeader 的手动压缩一致:失败给可理解提示,不泄漏裸 IPC 错误。
+ log.warn('context ring compact-session failed', err);
+ toast.warning(t('ccAgent.sidebar.sessionMenu.compactFailed'));
+ }
+ return;
+ }
+ // 真实 Claude Code:输入协调器的 maker:input:compact(旧行为不变)。
+ if (channelNow !== 'claude-input') return;
+ // 参数必须用**最新** session 快照(与 channel 同源):同会话切换 agent 后
+ // model/effort/permissionMode/workingDir 已变化,旧快照会按错误配置执行压缩,
+ // 且旧快照 workingDir 缺失时会在用户确认后静默放弃(greptile P1 / codex P2)。
+ const sessionNow = sessionRef.current;
+ if (!sessionNow?.workingDir) return; // claude 通道硬前提:输入协调器需要工作目录
await compactSession(
- session.model,
- session.effort as Effort,
- session.permissionMode as PermissionMode,
- session.workingDir,
+ sessionNow.model,
+ sessionNow.effort as Effort,
+ sessionNow.permissionMode as PermissionMode,
+ sessionNow.workingDir,
);
} finally {
- compactRequestInFlightRef.current = false;
+ begun.release();
}
}, [
agentStatus.contextTokens,
agentStatus.contextWindow,
+ compactChannel,
+ compactRequestGuard,
compactSession,
confirmDialog,
remoteDeviceId,
@@ -4286,8 +4395,18 @@ export function CCAgentSessionView({
sdkContextWindow={agentStatus.contextWindow}
deviceId={remoteDeviceId}
onCompact={
- // codex 无手动 compact;context 为 0 时压缩无意义 → 两种情况保持纯展示
- !isCodex && session != null && agentStatus.contextTokens > 0
+ // 按 agent 能力分流(#1927/#1933 review):claude-code 走 inputCoordinator,
+ // 其余声明 manualCompact.supported(当前仅 pi)走 compact-session 通道;
+ // codex 无手动 compact(上游自动压缩)保持纯展示。pi 的 SSH 远程会话
+ // (remoteHostId)无 compact-session 路由 → 不开放(与 SessionContentHeader
+ // 压缩菜单仅本地/device-link 一致);device-link 远程 pi 走隧道,照常开放。
+ // pi 回合运行中会拒绝压缩 → compact-session 通道在 running 时禁用
+ // (与 SessionContentHeader 的 runningSessionIds 一致,codex P1);
+ // claude-input 保留旧行为(turn 中可走 inputCoordinator)。
+ compactChannel !== null
+ && !(realAgentKind === 'pi' && !!session?.remoteHostId)
+ && session != null && agentStatus.contextTokens > 0
+ && !(compactChannel === 'compact-session' && agentStatus.isRunning)
? handleCompactRequest
: undefined
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sessionScopedRequestGuard.ts b/apps/desktop/src/renderer/features/cc-agent/sessionScopedRequestGuard.ts
new file mode 100644
index 0000000000..01d12181c0
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sessionScopedRequestGuard.ts
@@ -0,0 +1,52 @@
+/**
+ * 长耗时会话操作的 renderer 侧作用域守卫。
+ *
+ * 同一视图组件可在请求尚未结束时切换 session;锁必须按 sessionId 隔离,且迟到响应
+ * 只能影响当前仍展示的会话。Set 允许 A/B 请求短暂重叠,A 的 finally 只释放 A,绝不
+ * 清掉 B 的锁。
+ *
+ * 代(epoch)语义(#1927 / greptile review):每次 setCurrentSession 都换代。A 在途时
+ * 切到 B 再切回 A,旧 A 请求(旧代)不得再视为当前——迟到 toast 不弹;新点击按新代
+ * 登记,不被旧请求的锁挡住(否则 pi 长压缩数分钟内新点击会静默丢弃)。
+ */
+export interface SessionScopedRequestGuard {
+ setCurrentSession(sessionId: string | null): void;
+ /**
+ * 尝试登记一次请求;返回 `{ release, epoch }` 表示成功(调用方在 finally 里 release),
+ * 返回 null 表示同代同会话已有 in-flight(防重复点击)。
+ */
+ tryBegin(sessionId: string): { release: () => void; epoch: number } | null;
+ /**
+ * sessionId 仍是当前展示会话;传 epoch 时额外要求请求代与当前代一致
+ * (切走再切回后旧代请求返回 false,迟到响应/确认结果不再生效)。
+ */
+ isCurrent(sessionId: string, epoch?: number): boolean;
+}
+
+export function createSessionScopedRequestGuard(): SessionScopedRequestGuard {
+ const inFlightKeys = new Set<string>();
+ let currentSessionId: string | null = null;
+ let epoch = 0;
+
+ return {
+ setCurrentSession(sessionId) {
+ currentSessionId = sessionId;
+ epoch += 1; // 每次进入(含从 B 切回 A)换代:旧代请求不再匹配当前作用域
+ },
+ tryBegin(sessionId) {
+ const key = `${sessionId}#${epoch}`;
+ if (inFlightKeys.has(key)) return null;
+ inFlightKeys.add(key);
+ return {
+ release: () => {
+ inFlightKeys.delete(key);
+ },
+ epoch,
+ };
+ },
+ isCurrent(sessionId, sinceEpoch) {
+ if (currentSessionId !== sessionId) return false;
+ return sinceEpoch === undefined || sinceEpoch === epoch;
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
index d07e854f39..c9cf6e3b3f 100644
--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
@@ -115,6 +115,12 @@ export interface AgentCapabilities {
* device-link 老被控端无此字段 → undefined,控制端必须阻止开启协同并提示升级。
*/
supportsOrcaWorkerPermissionMode?: boolean;
+ /**
+ * 手动压缩会话上下文能力(pi 原生 compact)。与 maker-core Capabilities.manualCompact
+ * 同形;device-link 老被控端序列化的 capabilities 无此字段 → undefined = 不支持。
+ * 上下文环压缩入口据此判定(见 resolveManualCompactChannel),不再硬编码 agentKind 列表。
+ */
+ manualCompact?: CapabilityStatus;
/**
* 每轮 host 权限策略能力门:未声明或 supported.supported !== true 的 Agent 无法
* 用于「无条件挂逐条权限确认」的渠道(如个人微信)。与 maker-core 的
@@ -127,6 +133,25 @@ export interface AgentCapabilities {
};
}
+/**
+ * 手动压缩调用通道判定 —— 上下文环压缩入口与请求分流的唯一判据(#1927 / #1933 review):
+ * - 真实 Claude Code 会话 → `claude-input`(输入协调器 maker:input:compact,SDK 斜杠命令通道);
+ * - 其余 agent 声明 manualCompact.supported(当前仅 pi)→ `compact-session`
+ * (capability-aware 通用通道 maker:compact-session,本地 IPC / device-link 隧道均可路由);
+ * - 其余(Codex 等无手动压缩能力)→ null = 无入口。
+ * 刻意不按 agentKind 扩排除列表:新 agent 只需在 maker-core 声明能力即可自动接入。
+ */
+export type CompactChannel = 'claude-input' | 'compact-session';
+
+export function resolveManualCompactChannel(
+ agentKind: AgentKind | null | undefined,
+ capabilities: Pick<AgentCapabilities, 'manualCompact'> | null | undefined,
+): CompactChannel | null {
+ if (agentKind === 'claude-code') return 'claude-input';
+ if (capabilities?.manualCompact?.supported) return 'compact-session';
+ return null;
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
@@ -143,6 +168,22 @@ function isOptionalBoolean(value: unknown): boolean {
return value === undefined || typeof value === 'boolean';
}
+/** CapabilityStatus 形状校验(与 maker-core types/capabilities.ts 对齐)。 */
+function isCapabilityStatus(value: unknown): boolean {
+ if (!isRecord(value)) return false;
+ // supported 必须是布尔;两种分支下可选字段统一只接受 string(undefined 允许)。
+ if (typeof value.supported !== 'boolean') return false;
+ return (
+ (value.reason === undefined || typeof value.reason === 'string') &&
+ (value.upstreamRef === undefined || typeof value.upstreamRef === 'string') &&
+ (value.message === undefined || typeof value.message === 'string')
+ );
+}
+
+function isOptionalCapabilityStatus(value: unknown): boolean {
+ return value === undefined || isCapabilityStatus(value);
+}
+
function isOptionalFiniteNumber(value: unknown): boolean {
return value === undefined || (typeof value === 'number' && Number.isFinite(value));
}
@@ -219,7 +260,8 @@ function parseAgentCapabilities(value: unknown): AgentCapabilities {
!value.permissionModes.every(isNamedDescriptor) ||
!isOptionalBoolean(value.supportsSessionAgentSwitch) ||
!isOptionalBoolean(value.supportsSessionAgentSwitchCas) ||
- !isOptionalBoolean(value.supportsOrcaWorkerPermissionMode)
+ !isOptionalBoolean(value.supportsOrcaWorkerPermissionMode) ||
+ !isOptionalCapabilityStatus(value.manualCompact)
) {
throw new Error('Invalid agent capabilities response');
}
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index f46ad43e83..9cc4a355d7 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -67,6 +67,10 @@ export interface RoutableMaker {
getContextUsage: FullMaker['getContextUsage'];
setExtraDirs: FullMaker['setExtraDirs'];
closeSession: FullMaker['closeSession'];
+ // 手动压缩(pi 原生 compact,capability-aware 的 maker:compact-session):
+ // 上下文环 / 会话菜单对 device-link 远程 pi 会话也要隧道到被控端执行
+ // (压缩的是被控端的会话上下文,控制端本机无该 live 会话,固定调本机必 null 静默失败)。
+ compactSession: FullMaker['compactSession'];
enableOrca: FullMaker['enableOrca'];
disableOrca: FullMaker['disableOrca'];
input: Pick<
@@ -163,6 +167,12 @@ function remoteMakerApi(deviceId: string): RoutableMaker {
getContextUsage: t('maker:get-context-usage') as FullMaker['getContextUsage'],
setExtraDirs: t('maker:set-extra-dirs') as FullMaker['setExtraDirs'],
closeSession: t('maker:close-session') as FullMaker['closeSession'],
+ compactSession: ((sessionId, instructions) =>
+ invokeRemote(
+ deviceId,
+ 'maker:compact-session',
+ instructions === undefined ? [sessionId] : [sessionId, instructions],
+ )) as FullMaker['compactSession'],
enableOrca: t('maker:session:enable-orca') as FullMaker['enableOrca'],
disableOrca: t('maker:session:disable-orca') as FullMaker['disableOrca'],
input: {
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 6717804511..134763d87c 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -96,6 +96,7 @@ describe('mobile maker transport', () => {
'maker:input:get-projection',
'maker:input:enqueue',
'maker:input:compact',
+ 'maker:compact-session',
'maker:input:steer',
'maker:input:stop',
'maker:input:resume',
@@ -295,6 +296,9 @@ describe('mobile maker transport', () => {
await maker.getVoiceDictionary();
await maker.input.stop('s1', { pauseQueue: true });
await maker.input.compact('s1');
+ await maker.compactSession('s1');
+ await maker.compactSession('s1', '');
+ await maker.compactSession('s1', 'focus on API design');
await maker.input.retryLastError('s1');
await maker.input.clearError('s1');
await maker.input.updateText('s1', 'queued-1', 'updated');
@@ -337,6 +341,9 @@ describe('mobile maker transport', () => {
['device-link:voice:dictionary:get', []],
['maker:input:stop', ['s1', { pauseQueue: true }]],
['maker:input:compact', ['s1']],
+ ['maker:compact-session', ['s1']],
+ ['maker:compact-session', ['s1', '']],
+ ['maker:compact-session', ['s1', 'focus on API design']],
['maker:input:retry-last-error', ['s1']],
['maker:input:clear-error', ['s1']],
['maker:input:update-text', ['s1', 'queued-1', 'updated']],
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 63819a59a0..aaee4370db 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -568,6 +568,12 @@ export interface MobileMakerTransport {
projectAutomation: {
removeSchedule(input: { workingDir: string; id: string }): Promise<unknown>;
};
+ /** 手动压缩会话上下文(pi 原生 compact,capability-aware 的 maker:compact-session;
+ * input.compact 是 Claude Code 专用的 maker:input:compact,两者不混)。 */
+ compactSession(
+ sessionId: string,
+ instructions?: string,
+ ): Promise<{ tokensBefore?: number; estimatedTokensAfter?: number; noop?: boolean } | null>;
input: {
getProjection(sessionId: string): Promise<InputProjection>;
enqueue(sessionId: string, item: QueuedRemoteMessage, opts?: { sendAtMs?: number }): Promise<InputProjection>;
@@ -769,6 +775,11 @@ export function createMobileMakerTransport({
projectAutomation: {
removeSchedule: (input) => call('maker:project-automation:remove-schedule', [input]),
},
+ compactSession: (sessionId, instructions) =>
+ call(
+ 'maker:compact-session',
+ instructions === undefined ? [sessionId] : [sessionId, instructions],
+ ),
input: {
getProjection: (sessionId) => call('maker:input:get-projection', [sessionId]),
enqueue: (sessionId, item, opts) => call('maker:input:enqueue', [sessionId, item, opts]),
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index e4449e587c..14fe5958b0 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -29,6 +29,7 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {
'maker:resolve-interaction',
'maker:get-pending-interactions',
'maker:input:compact',
+ 'maker:compact-session',
'maker:set-model',
'maker:switch-session-agent',
'maker:get-session-agent-switch-intent',
@@ -369,6 +370,13 @@ describe('INVOKE_TIMEOUT_OVERRIDES_MS', () => {
it('worktree:discard-precreated 可等待同 session 创建锁且不沿用默认 30s', () => {
expect(INVOKE_TIMEOUT_OVERRIDES_MS['worktree:discard-precreated']).toBeGreaterThan(30_000);
});
+
+ it('maker:compact-session 隧道超时必须大于 pi 压缩执行预算(10min + 回程余量,不 30s 截断)', () => {
+ // 被控端在请求穿过 relay 后才开始跑 PI_COMPACT_TIMEOUT_MS(10min);控制端若只给
+ // 相同预算,压缩恰好到上限时会先 INVOKE_TIMEOUT 并被误判为设备无响应(codex P2)。
+ // 严格大于 10min,锁住「带余量」的语义,防止回退成无余量的同值。
+ expect(INVOKE_TIMEOUT_OVERRIDES_MS['maker:compact-session']).toBeGreaterThan(10 * 60_000);
+ });
});
describe('computeAllowlistHash', () => {
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 7932340c37..ee0e37be82 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -159,6 +159,10 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
'maker:input:get-projection',
'maker:input:enqueue',
'maker:input:compact',
+ // 手动压缩(pi 原生 compact,capability-aware):上下文环 / 会话菜单对远程 pi 会话
+ // 隧道到被控端执行。业务 handler 无 sender / 本机 UI 副作用,真相在被控端。
+ // 长 LLM 摘要请求可能远超默认 30s → INVOKE_TIMEOUT_OVERRIDES_MS 覆盖(见下)。
+ 'maker:compact-session',
'maker:input:steer',
'maker:input:stop',
'maker:input:resume',
@@ -572,6 +576,13 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {
'worktree:create': 60_000,
// 可能先等待同 sessionId 的晚到 create 释放互斥锁,再执行 git worktree remove。
'worktree:discard-precreated': 60_000,
+ // pi 手动压缩调 LLM 生成摘要,大上下文 + 网关排队可达分钟级(core 侧
+ // PI_COMPACT_TIMEOUT_MS = 10min);默认 30s 隧道超时会截断远程压缩请求,
+ // 用户在控制端看到的就是「无反馈失败」。给足执行预算 + 回程余量:
+ // 被控端在请求穿过 relay 后才开始跑 PI_COMPACT_TIMEOUT_MS,控制端若只给相同
+ // 10min,压缩恰好到预算上限时会先 INVOKE_TIMEOUT,被误判为「设备无响应」并
+ // 可能触发 peer-link 恢复(codex P2)——同 desktop-cmd:run 模式加 1min 余量。
+ 'maker:compact-session': 11 * 60_000,
// listing tier 轻量 DB 读:毫秒级查询,12s 仍等不到只能是链路问题,快速失败喂给熔断器。
// 12s 同时覆盖被控端冷启动 DB 迁移的常见时长(那类失败是快速返回的 DbClient not ready,
// 不吃满超时),不会误伤首拉重试。
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index 3b647a4bfe..5370f493d9 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@ -106,6 +106,56 @@ describe('pi translator', () => {
expect((cb!.data as { trigger: string }).trigger).toBe('manual');
});
+ it('#1933 review:manual compaction 事件闭环 —— 收口 running 并把新 contextTokens 送回 renderer', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ const { queue, events } = makeQueue();
+ // compaction_start 先把 running 置 true(与 pi 事件流一致)。
+ translatePiEvent(ev({ type: 'compaction_start' }), queue, ctx);
+ const startStatus = events.find(
+ (e) => e.type === 'status' && (e.data as { isRunning?: boolean }).isRunning === true,
+ );
+ expect(startStatus).toBeDefined();
+
+ translatePiEvent(
+ ev({ type: 'compaction_end', reason: 'manual', result: { tokensBefore: 100, estimatedTokensAfter: 20 } }),
+ queue,
+ ctx,
+ );
+ // 闭环:manual compaction_end 必须补发 status(isRunning=false, Done),
+ // 携带压缩后的 contextTokens —— 否则 renderer 圆环永久卡 running、token 不刷新。
+ const endStatus = events.find(
+ (e) => e.type === 'status' && (e.data as { isRunning?: boolean }).isRunning === false,
+ );
+ expect(endStatus).toBeDefined();
+ const endData = endStatus!.data as { status: string; contextTokens?: number };
+ expect(endData.status).toBe('Done');
+ expect(endData.contextTokens).toBe(20);
+ });
+
+ it('#1933 review:auto compaction 在活跃 turn 内不补发 status(false)(不得误收口 turn)', () => {
+ const ctx = createPiTranslateContext(noopLogger);
+ ctx.isStreaming = true; // auto compaction 发生在活跃 turn 内
+ const { queue, events } = makeQueue();
+ translatePiEvent(
+ ev({ type: 'compaction_end', reason: 'threshold', result: { tokensBefore: 150000, estimatedTokensAfter: 32000 } }),
+ queue,
+ ctx,
+ );
+ // 只有 compact_boundary,没有 status 收口(turn 结束经 agent_settled 自然收口)。
+ expect(events.filter((e) => e.type === 'status')).toHaveLength(0);
+ expect(events.some((e) => e.type === 'compact_boundary')).toBe(true);
+ // 即便 manual 压缩期间用户已开始新 turn(isStreaming),也不收口。
+ const ctx2 = createPiTranslateContext(noopLogger);
+ ctx2.isStreaming = true;
+ const { queue: q2, events: ev2 } = makeQueue();
+ translatePiEvent(
+ ev({ type: 'compaction_end', reason: 'manual', result: { tokensBefore: 100, estimatedTokensAfter: 20 } }),
+ q2,
+ ctx2,
+ );
+ expect(ev2.filter((e) => e.type === 'status')).toHaveLength(0);
+ });
+
it('accumulates turn usage and attaches it to the done event on agent_settled', () => {
const ctx = createPiTranslateContext(noopLogger);
const { queue, events } = makeQueue();
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index 7f98fa56db..e51b60863c 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -496,6 +496,13 @@ export function translatePiEvent(
if (result && typeof result.estimatedTokensAfter === 'number') {
ctx.contextTokens = result.estimatedTokensAfter;
}
+ // #1933 review:手动压缩事件必须闭环。compaction_start 已把 isRunning 置 true,
+ // 若不收口,renderer 圆环会永久卡 running、新 contextTokens 也送不回去。
+ // 仅 manual 收口:auto 压缩发生在活跃 turn 内(turn 结束经 agent_settled 自然收口),
+ // 且若压缩期间用户已开始新 turn(ctx.isStreaming)也不能收口,否则会误杀新 turn。
+ if (event.reason === 'manual' && !ctx.isStreaming) {
+ pushStatus(queue, ctx, 'Done', false);
+ }
return;
}
diff --git a/packages/maker-shared/src/deviceLinkContract.ts b/packages/maker-shared/src/deviceLinkContract.ts
index 868c4a1333..89cf014a83 100644
--- a/packages/maker-shared/src/deviceLinkContract.ts
+++ b/packages/maker-shared/src/deviceLinkContract.ts
@@ -345,6 +345,9 @@ export const MOBILE_REMOTE_INVOKE_CHANNELS = [
'maker:input:get-projection',
'maker:input:enqueue',
'maker:input:compact',
+ // 手动压缩(pi 原生 compact,capability-aware):移动端控制远程 pi 会话同样隧道到
+ // 被控端执行;长 LLM 摘要请求的超时覆盖见 INVOKE_TIMEOUT_OVERRIDES_MS。
+ 'maker:compact-session',
'maker:input:steer',
'maker:input:stop',
'maker:input:resume',