Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ function botTaskDispatchHarness(
};
const dbClient = { drizzle: { select: () => dbChain } };
const stubs: Record<string, unknown> = {
// The slice initializes the compact service, but these fixtures only dispatch sends.
createDeferredSessionCompact: () => ({}),
getPluginHostToolCaller: () => undefined,
sanitizeSourceName,
getInstalledGhostName: () => 'Dashboard',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { formatForwardedRequest } from '../../../shared/forwardedRequest.js';
import { describe, expect, it, vi } from 'vitest';
import { createXdtHelperMcpServer } from '@cindy/mcps';
import type { AgentEvent, Session } from '@cindy/maker-core';
import { createDeferredSessionCompact } from '../deferredSessionCompact.js';
import { handlePluginHostToolRequest } from '../../cindy-brain/hostToolSlot.js';
import { authorizePluginHostToolCall, getPluginHostToolCaller } from '../../mcp-integrations/hostToolCaller.js';
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';

import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
import { admitPluginTaskAction, admitTaskAction } from '../taskActionAuthorization.js';
import { admitPluginTaskAction, admitTaskAction, createTaskActionAuthorizer } from '../taskActionAuthorization.js';
import {
authorizeSessionQueueReorder,
createSessionControlService,
Expand Down Expand Up @@ -259,6 +261,103 @@ describe('session control domain service', () => {
}));
});

// #12170 / unit: an authorized helper call targeting its own running Pi turn must get
// a trackable receipt before native compact can abort anything. Plugin probes only test
// external delivery. The minimum reproducer is one compact call in one live turn.
it.each(['complete', 'noop', 'native error', 'stop', 'newer turn', 'external'] as const)(
'reports self-compaction through the helper boundary (%s)', async outcome => {
const { deps, live } = setup();
const operation = createDeferredSessionCompact();
let running = true;
let generation = 3;
let onEvent: Parameters<Session['onEvent']>[0] | undefined;
const session = {
...live,
sdkSessionId: '/fixture/pi-session.jsonl',
isTurnRunning: () => running,
getTurnGeneration: () => generation,
stablePermissionModeState: { mode: 'bypassPermissions' as const, generation: 0 },
stablePlanModeState: { enabled: false, generation: 0 },
onEvent: (listener: Parameters<Session['onEvent']>[0]) => {
onEvent = listener;
return () => { onEvent = undefined; };
},
onStatusChange: () => () => {},
};
const dispatchNative = vi.fn(async () => {
if (outcome === 'native error') throw new Error('native compaction failed');
return outcome === 'noop' ? { noop: true } : { tokensBefore: 120, estimatedTokensAfter: 30 };
});
const deferSelfPiCompact: NonNullable<SessionControlServiceDeps['deferSelfPiCompact']> = async params => {
expect(params.instanceId).toBe('pi-instance');
await params.beforeMutation();
return operation.request(session, {
turnGeneration: generation, signal: params.signal, isCurrent: () => true,
dispatch: async checkBoundary => {
await params.beforeDelivery();
await checkBoundary();
return dispatchNative();
},
});
};
const service = createSessionControlService({
...deps, deferSelfPiCompact,
getSessionRuntimeDetails: async sessionId => ({
...await deps.getSessionRuntimeDetails(), manualCompact: sessionId === 'target' ? operation.get(session) : undefined,
}),
});
const server = createXdtHelperMcpServer({
sessionControl: service,
authorizeCall: createTaskActionAuthorizer({ confirm: async () => true, capture: async () => ({
key: 'current-turn', ownerInput: true, delegated: false, assertCurrent: async () => {},
assertDeliveryCurrent: async () => {},
}) }),
}, { agentKind: 'pi', sessionId: 'target', workingDir: '/fixture', getSessionContext: () => ({
agentKind: 'pi', sessionId: 'target', workingDir: '/fixture', sessionInstanceId: 'pi-instance',
mcpCallerKind: 'root', mcpCallerAttested: true,
}) });
const call = async (tool: string, args: Record<string, unknown>) => {
const result = await server.hostTools.call(tool, args);
const content = result.content[0];
return JSON.parse(content.type === 'text' ? content.text : '{}');
};
try {
const requested = await call('control_session', {
action: 'compact', session_id: outcome === 'external' ? 'other' : 'target', instructions: 'Keep the decision',
});
if (outcome === 'external') {
expect(requested).toMatchObject({ ok: true, result: { executionPaused: true } });
expect(operation.get(session)).toBeUndefined();
expect(deps.runSessionAction).toHaveBeenCalledTimes(1);
return;
}
expect(requested).toMatchObject({ ok: true, result: { status: 'requested', operationId: expect.any(String) } });
expect(deps.runSessionAction).not.toHaveBeenCalled();
expect(dispatchNative).not.toHaveBeenCalled();

running = false;
const done = { type: 'done', sessionTurnGeneration: generation, source: 'pi',
data: { status: outcome === 'stop' ? 'cancelled' : 'completed' } } satisfies AgentEvent;
if (outcome === 'newer turn') generation += 1;
onEvent?.(done);
onEvent?.(done);

const expected = outcome === 'native error' ? { status: 'failed', errorCode: 'COMPACT_FAILED' }
: outcome === 'stop' || outcome === 'newer turn' ? { status: 'cancelled' }
: outcome === 'noop' ? { status: 'completed', noop: true }
: { status: 'completed', tokensBefore: 120, estimatedTokensAfter: 30 };
await vi.waitFor(async () => {
expect(await call('get_session_runtime', {})).toMatchObject({
manual_compact: { ...expected, operationId: requested.result.operationId },
});
});
expect(dispatchNative).toHaveBeenCalledTimes(outcome === 'stop' || outcome === 'newer turn' ? 0 : 1);
} finally {
await server.close();
}
},
);

// UI parity: machine-generated rows are not editable, even with plugin control.
it.each([
{ kind: 'session' as const, senderSessionId: 'other', displayText: 'before' },
Expand Down
90 changes: 90 additions & 0 deletions apps/desktop/src/main/maker-ipc/deferredSessionCompact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { randomUUID } from 'node:crypto';
import { isTaskActionRevoked } from './taskActionAuthorization.js';
import { isTerminalAgentErrorEvent, type ManualCompactResult, type Session } from '@cindy/maker-core';

type CompactSession = Pick<Session, 'getTurnGeneration' | 'isTurnRunning' | 'onEvent' | 'onStatusChange'
| 'stablePermissionModeState' | 'stablePlanModeState' | 'sdkSessionId'>;

export type SessionCompactReceipt = { operationId: string } & (
| { status: 'requested' | 'cancelled' }
| ({ status: 'completed' } & ManualCompactResult)
| { status: 'failed'; errorCode: 'COMPACT_FAILED' }
);

const MAX_WAIT_FOR_COMPACT_BOUNDARY_MS = 10 * 60_000;

/** Pi's native compact aborts its active turn. Let a self-call return before it can do so. */
export function createDeferredSessionCompact() {
const receipts = new WeakMap<CompactSession, SessionCompactReceipt>();
return {
get: (session: CompactSession) => receipts.get(session),
request(session: CompactSession, input: {
turnGeneration: number;
isCurrent: () => boolean;
signal?: AbortSignal;
dispatch: (beforeDispatch: () => Promise<void>, signal: AbortSignal) => Promise<ManualCompactResult>;
}): SessionCompactReceipt | null {
const permission = session.stablePermissionModeState;
const plan = session.stablePlanModeState;
const nativeSessionId = session.sdkSessionId;
if (input.signal?.aborted || !input.isCurrent() || !permission || permission.mode === 'plan' || !plan || plan.enabled
|| session.getTurnGeneration() !== input.turnGeneration || !session.isTurnRunning()
|| receipts.get(session)?.status === 'requested') return null;

const operationId = randomUUID();
const receipt = { operationId, status: 'requested' } as const;
const controller = new AbortController();
let settled = false;
const settle = (result: SessionCompactReceipt) => {
if (settled) return;
settled = true;
clearTimeout(deadline);
offEvent();
offStatus();
receipts.set(session, result);
};
const cancel = () => {
controller.abort();
settle({ operationId, status: 'cancelled' });
};
const dispatch = async () => {
let admitted = false;
try {
const native = await input.dispatch(async () => {
const currentPermission = session.stablePermissionModeState;
const currentPlan = session.stablePlanModeState;
if (!input.isCurrent() || session.sdkSessionId !== nativeSessionId
|| session.getTurnGeneration() !== input.turnGeneration || session.isTurnRunning()
|| currentPermission?.generation !== permission.generation
|| !currentPlan || currentPlan.enabled || currentPlan.generation !== plan.generation) cancel();
controller.signal.throwIfAborted();
admitted = true;
// After the actual RPC is admitted, only its result can settle this receipt.
clearTimeout(deadline);
offStatus();
}, controller.signal);
settle({ operationId, status: 'completed', ...native });
} catch (error) {
if (controller.signal.aborted) return;
if (!admitted && isTaskActionRevoked(error)) cancel();
else settle({ operationId, status: 'failed', errorCode: 'COMPACT_FAILED' });
}
};
const offEvent = session.onEvent(event => {
if (event.sessionTurnGeneration !== input.turnGeneration || event.turnScope === 'background') return;
if (isTerminalAgentErrorEvent(event)) {
cancel();
} else if (event.type === 'done' && event.turnContinuationId === undefined) {
offEvent();
if ((event.data as { status?: string } | undefined)?.status === 'completed') void dispatch();
else cancel();
}
});
const offStatus = session.onStatusChange(status => { if (status !== 'active') cancel(); });
const deadline = setTimeout(cancel, MAX_WAIT_FOR_COMPACT_BOUNDARY_MS);
deadline.unref?.();
receipts.set(session, receipt);
return receipt;
},
};
}
30 changes: 29 additions & 1 deletion apps/desktop/src/main/maker-ipc/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,7 @@ import {
createSessionControlService,
sessionQueueOriginForDispatcher,
} from './sessionControlService.js';
import { createDeferredSessionCompact } from './deferredSessionCompact.js';
import { runSessionExecutionAction } from './sessionExecutionActions.js';
import {
createQueueReorderAdapter,
Expand Down Expand Up @@ -17584,7 +17585,31 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return { pluginId, ...(name ? { name } : {}) };
}

const deferredCompact = createDeferredSessionCompact();
const sessionControlService = createSessionControlService({
deferSelfPiCompact: async ({ targetSessionId: id, instanceId, signal, instructions, beforeMutation, beforeDelivery }) => {
const sess = maker.getSession(id);
if (!sess || sess.instanceId !== instanceId || !sess.isTurnRunning() || sess.agentKind !== 'pi') return null;
const turnGeneration = sess.getTurnGeneration();
const companion = await readCompanionFailoverSnapshot(id);
if (companion?.role !== 'canonical' && companion?.role !== 'thread') return null;
await beforeMutation();
if (!sess.capabilities.manualCompact?.supported) {
throwIpcError('UNSUPPORTED_CAPABILITY', 'This agent does not support manual context compaction');
}
if (signal?.aborted) throwIpcError('PRECONDITION_FAILED', 'Request cancelled before compact was scheduled');
const result = deferredCompact.request(sess, {
turnGeneration, signal, isCurrent: () => maker.getSession(id) === sess,
dispatch: (checkBoundary, signal) => withSendToSessionLock(id, () => sess.compactSession(instructions, async () => {
signal.throwIfAborted();
await beforeDelivery();
// Recheck in the native RPC lane. A newer turn must never be interrupted.
await checkBoundary();
}), () => 'self-pi-compact', signal),
});
if (!result) throwIpcError('SESSION_RUNNING', 'The turn changed or a compaction is already pending');
return result;
},
runSessionAction: params => runSessionExecutionAction(params, {
coordinator: inputCoordinator, persist: awaitAgentInputQueueSnapshotPersistence,
interactions: {
Expand Down Expand Up @@ -17617,11 +17642,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const profiles = await readSessionRuntimeProfiles(sessionId);
if (!profiles) throw new Error(`session ${sessionId} not found`);
const activity = await readCanonicalSessionActivity(sessionId);
const turnControl = maker.getSession(sessionId)?.getTurnControlSnapshot();
const liveSession = maker.getSession(sessionId);
const turnControl = liveSession?.getTurnControlSnapshot();
const manualCompact = liveSession && deferredCompact.get(liveSession);
const botFallback = await readBotFallbackCandidate(sessionId, profiles.effective);
return {
...activity,
permissionMode: (await maker.getSessionMeta(sessionId))?.permissionMode,
...(manualCompact ? { manualCompact } : {}),
turnGeneration: turnControl?.turnGeneration ?? null,
gracefulStopState: turnControl?.gracefulStopState ?? 'none',
runtimeGeneration: profiles.control.generation,
Expand Down
21 changes: 20 additions & 1 deletion apps/desktop/src/main/maker-ipc/sessionControlService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
SessionTurnControlSnapshot,
} from '@cindy/maker-core';
import { assertTaskActionCurrent, bindTaskActionInput, captureTaskActionGuard, captureTaskActionDeliveryGuard, combineInputGuards, hasTaskActionAuthorization } from './taskActionAuthorization.js';
import type { SessionCompactReceipt } from './deferredSessionCompact.js';
import { revokeTrustedDesktopQueuedOrigin } from './queuedInputOrigin.js';
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';

Expand Down Expand Up @@ -70,6 +71,7 @@ export interface SessionRuntimeDetails extends SessionActivitySnapshot {
effectiveProfile: SessionRuntimeProfile;
pendingMutation: SessionRuntimePendingProjection | null;
fallbackEnabled: boolean;
manualCompact?: SessionCompactReceipt;
}

export type SessionRuntimeResult =
Expand Down Expand Up @@ -116,6 +118,14 @@ export interface SessionControlServiceDeps {
beforeMutation: () => Promise<void>;
beforeDelivery?: () => Promise<void>;
}): Promise<{ ok: true; result: unknown } | Failure<string>>;
deferSelfPiCompact?(params: {
targetSessionId: string;
instanceId: string;
signal?: AbortSignal;
instructions?: string;
beforeMutation: () => Promise<void>;
beforeDelivery: () => Promise<void>;
}): Promise<SessionCompactReceipt | null>;
sessionExists(sessionId: string): Promise<boolean>;
getLiveSession(sessionId: string): SessionControlLiveSession | null;
getSessionActivitySnapshot(sessionId: string): Promise<SessionActivitySnapshot>;
Expand Down Expand Up @@ -188,6 +198,7 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {
targetSessionId: string;
action: 'pause' | 'resume' | 'retry' | 'compact';
instructions?: string;
selfPiCaller?: { instanceId: string; signal?: AbortSignal };
}): Promise<{ ok: true; result: unknown } | Failure<string>> {
const plugin = deps.getPluginCaller?.();
await assertTaskActionCurrent();
Expand All @@ -202,7 +213,15 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {
await deps.assertExternalInputAllowed(params.targetSessionId);
await beforeMutation();
try {
return await deps.runSessionAction({ ...params, beforeMutation, beforeDelivery });
const { selfPiCaller, ...action } = params;
if (action.action === 'compact' && selfPiCaller && !plugin && deliveryGuard) {
const result = await deps.deferSelfPiCompact?.({
targetSessionId: action.targetSessionId, instructions: action.instructions,
...selfPiCaller, beforeMutation, beforeDelivery,
});
if (result) return { ok: true, result };
}
return await deps.runSessionAction({ ...action, beforeMutation, beforeDelivery });
} catch (error) {
const code = error instanceof Error && error.name === 'NotSupportedError' && params.action === 'compact'
? 'UNSUPPORTED_CAPABILITY' : (error as { code?: unknown } | null)?.code;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ Claude 复用原 `/compact`,Codex/Pi 复用原生压缩及既有锁与临时
发送前复核原派发授权。成功沿用原生估算值,`noop:true` 表示未压缩,实际 RPC 失败返回
`COMPACT_FAILED`。仅 Pi 接受非空压缩说明;现有 `retry` 按任务错误恢复事务执行。

本机 Pi 伙伴直聊通过 `control_session` 压缩自身正在执行的会话时,`requested` 带
`operationId`,表示宿主已受理。宿主等原轮次正常结束并复核实例、权限与派发授权,再发送一次
原生 `compact`。原轮次取消、会话切换或等待超过十分钟时取消派发。调用方通过
`get_session_runtime.manual_compact` 查看当前运行实例最近一次回执,按同一 `operationId` 核对。
`completed` 可带原生估算或 `noop`,`cancelled` 表示尚未派发,`failed` 带 `COMPACT_FAILED`。
插件与外部目标沿用原回执。

存量插件影响:无,不更改原声明、批准和安装数据,无需迁移。
不增加 Device Link channel、relay kind 或跨电脑操作;自建中转仍透传原有 Host 请求,无需适配。
验证:sessionControlTools、sessionControlService、sessionQueueInspection、sessionQueueControl、
Expand Down
Loading
Loading