From 1079de19732a667f6613039d856e213ffd6e8998 Mon Sep 17 00:00:00 2001 From: amanayayatu-tech <267095040+amanayayatu-tech@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:10:05 +0100 Subject: [PATCH 1/2] fix(pi): return a receipt for companion self-compaction Signed-off-by: amanayayatu-tech <267095040+amanayayatu-tech@users.noreply.github.com> --- .../__tests__/sessionControlService.test.ts | 101 +++++++++++++++++- .../main/maker-ipc/deferredSessionCompact.ts | 90 ++++++++++++++++ apps/desktop/src/main/maker-ipc/register.ts | 30 +++++- .../main/maker-ipc/sessionControlService.ts | 21 +++- .../plugin-session-queue-control.md | 7 ++ .../lizi-mcps/src/xdt-helper/capabilities.ts | 1 + .../src/xdt-helper/session_control.ts | 15 ++- 7 files changed, 261 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/main/maker-ipc/deferredSessionCompact.ts diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts index 3eb26e92229..27d39524f4a 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts @@ -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, @@ -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[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[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 = 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) => { + 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' }, diff --git a/apps/desktop/src/main/maker-ipc/deferredSessionCompact.ts b/apps/desktop/src/main/maker-ipc/deferredSessionCompact.ts new file mode 100644 index 00000000000..6aceacabde0 --- /dev/null +++ b/apps/desktop/src/main/maker-ipc/deferredSessionCompact.ts @@ -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; + +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(); + return { + get: (session: CompactSession) => receipts.get(session), + request(session: CompactSession, input: { + turnGeneration: number; + isCurrent: () => boolean; + signal?: AbortSignal; + dispatch: (beforeDispatch: () => Promise, signal: AbortSignal) => Promise; + }): 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; + }, + }; +} diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts index 1313dc22620..e22d8107987 100644 --- a/apps/desktop/src/main/maker-ipc/register.ts +++ b/apps/desktop/src/main/maker-ipc/register.ts @@ -493,6 +493,7 @@ import { createSessionControlService, sessionQueueOriginForDispatcher, } from './sessionControlService.js'; +import { createDeferredSessionCompact } from './deferredSessionCompact.js'; import { runSessionExecutionAction } from './sessionExecutionActions.js'; import { createQueueReorderAdapter, @@ -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: { @@ -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, diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.ts index cecd6dcf266..fe2d33bff33 100644 --- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts +++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts @@ -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'; @@ -70,6 +71,7 @@ export interface SessionRuntimeDetails extends SessionActivitySnapshot { effectiveProfile: SessionRuntimeProfile; pendingMutation: SessionRuntimePendingProjection | null; fallbackEnabled: boolean; + manualCompact?: SessionCompactReceipt; } export type SessionRuntimeResult = @@ -116,6 +118,14 @@ export interface SessionControlServiceDeps { beforeMutation: () => Promise; beforeDelivery?: () => Promise; }): Promise<{ ok: true; result: unknown } | Failure>; + deferSelfPiCompact?(params: { + targetSessionId: string; + instanceId: string; + signal?: AbortSignal; + instructions?: string; + beforeMutation: () => Promise; + beforeDelivery: () => Promise; + }): Promise; sessionExists(sessionId: string): Promise; getLiveSession(sessionId: string): SessionControlLiveSession | null; getSessionActivitySnapshot(sessionId: string): Promise; @@ -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> { const plugin = deps.getPluginCaller?.(); await assertTaskActionCurrent(); @@ -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; diff --git a/docs/dev-rules/protocol-compatibility/plugin-session-queue-control.md b/docs/dev-rules/protocol-compatibility/plugin-session-queue-control.md index a21568967e4..c7609e0da70 100644 --- a/docs/dev-rules/protocol-compatibility/plugin-session-queue-control.md +++ b/docs/dev-rules/protocol-compatibility/plugin-session-queue-control.md @@ -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、 diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.ts index 4d385caab33..cf1ab7249bb 100644 --- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts +++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts @@ -159,6 +159,7 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [ '【授权】主人私聊输入及宿主实时核验的群内主人请求沿用普通任务权限流程,不另加行动确认卡。访客、转入消息及群授权核验暂不可用不算主人输入。自动唤醒、跟进责任与可用工具不增加操作授权。观察可以自动进行;发消息、插话、队列修改、停止、代答、恢复及模型/账号变更必须符合主人已委托的任务与动作范围,否则先展示目标、动作和内容并等待确认。', '【入口】cindy_helper 的 history 类 list_sessions / list_session_queue 提供 queuedCount、队列位置、来源、入队时间、正文摘要与 consuming 状态;control 类提供 update_session_queued_message、cancel_session_queued_message、steer_session_queued_message、move_session_queued_message、steer_session、stop_session_turn、get_session_runtime、control_session(暂停、恢复、重试、压缩,仅本机)。', '【伙伴入口】伙伴可发现通用 control 类;主人请求沿用普通权限流程,自动轮次的实际写入须通过 Host 行动授权。', + '【压缩回执】本机 Pi 伙伴压缩自己的活动会话时,带 operationId 的 requested 只代表已受理。等当前轮正常结束后,通过 get_session_runtime 的 manual_compact 核对同一 operationId。completed 保留原生估算或 noop;cancelled 表示未派发;failed 带 COMPACT_FAILED。', '【队列所有权】只能修改或撤回当前调用 session 自己通过 send_to_session 投递、且尚未进入 consuming 的消息;Orca、scheduler、用户或其它 session 的消息都会 fail-closed 拒绝。Orca worker 队列控制与这里复用同一底层生命周期实现。steer_session_queued_message / move_session_queued_message 把排队消息转为插话或调整顺序,可操作范围另含自己任务队列里由其它任务 / 协同成员发来的机器消息;没插成时消息留在队列并返回 reason。', '【插话】steer_session 只对正在运行且支持 same-turn steer 的 session 生效,在 provider 的下一个输入间隙注入当前 turn;若 turn 已结束会明确失败,不会退化成下一 turn。', '【停止】stop_session_turn 是请求式优雅停止:当前并行工具全部收尾后才发送 provider 软中断;不关闭 transport、不重建 session、不硬杀进程,超时未确认会返回 unconfirmed。', diff --git a/packages/lizi-mcps/src/xdt-helper/session_control.ts b/packages/lizi-mcps/src/xdt-helper/session_control.ts index 49dc2a5c80a..eb63438edf7 100644 --- a/packages/lizi-mcps/src/xdt-helper/session_control.ts +++ b/packages/lizi-mcps/src/xdt-helper/session_control.ts @@ -51,6 +51,7 @@ export interface SessionRuntimeSnapshot extends SessionActivitySnapshot { profile: SessionRuntimeProfile; } | null; fallbackEnabled?: boolean; + manualCompact?: { operationId: string; status: string; tokensBefore?: number; estimatedTokensAfter?: number; noop?: boolean; errorCode?: string }; } export interface SessionControlDeps { @@ -59,6 +60,7 @@ export interface SessionControlDeps { targetSessionId: string; action: 'pause' | 'resume' | 'retry' | 'compact'; instructions?: string; + selfPiCaller?: { instanceId: string; signal?: AbortSignal }; }): Promise>; updateQueuedMessage(params: { callerSessionId?: string; @@ -159,6 +161,8 @@ export function registerControlSessionTool(registry: XdtHelperToolRegistry, deps description: '控制本机指定任务:pause 暂停后续输入和待答交互的执行,不中止已在运行的模型或工具;' + '暂停不冻结 IM 渠道已发出提问的原有超时,到期按原逻辑取消。' + 'resume 解除执行暂停并恢复原队列;retry 复用原错误重试;compact 复用引擎原生手动压缩。' + + '本机 Pi 伙伴压缩自己的当前对话时,带 operationId 的 requested 表示已受理,将在本轮正常结束后执行。' + + '用 get_session_runtime 的 manual_compact 核对同一 operationId 的终态;受理后无需再调用 compact。' + '送达未知的消息不会自动重放;显式 resume/retry 沿用用户继续/重试入口,调用前须核实投递状态。' + '原生能力不支持时明确报错。Agent 与声明 control 的插件共用原生产事务。', inputShape: { @@ -166,10 +170,16 @@ export function registerControlSessionTool(registry: XdtHelperToolRegistry, deps action: z.enum(['pause', 'resume', 'retry', 'compact']), instructions: z.string().max(32768).optional().describe('仅 compact 支持的压缩说明。'), }, - handler: async ({ session_id, action, instructions }) => { + handler: async ({ session_id, action, instructions }, signal) => { if (instructions !== undefined && action !== 'compact') return errorPayload('INVALID_ARGS', 'instructions is only supported for compact'); + const caller = deps.getSessionContext(); + const selfPiCaller = action === 'compact' && caller.agentKind === 'pi' && !caller.remoteHostId + && caller.sessionId === session_id && caller.sessionInstanceId + && caller.mcpCallerAttested && caller.mcpCallerKind === 'root' + ? { instanceId: caller.sessionInstanceId, signal } : undefined; const result = await deps.controlSession!({ targetSessionId: session_id, action, + ...(selfPiCaller ? { selfPiCaller } : {}), ...(instructions !== undefined ? { instructions } : {}) }); return result.ok ? okPayload({ session_id, action, result: result.result }) : mapControlFailure(result); }, @@ -399,6 +409,7 @@ export function registerGetSessionRuntimeTool( description: '只读查询本机 session 的统一状态:记录生命周期、运行/等待/正常结束/出错结束、标题工作流语义、' + '开始时间、最后活动时间、动作摘要、优雅停止状态,以及运行时模型组合、待生效修改和 generation;' + + '查询自身会话时 manual_compact 可返回当前实例最近一次延后压缩的 operationId、状态、原生估算或错误码。' + 'pending.source=user 表示用户在面板里登记、下一条消息发送时才生效的选择。不返回提示词正文、工具参数或凭证。', inputShape: { session_id: z.string().min(1).optional().describe('目标 session id;省略时查询当前任务。'), @@ -437,6 +448,8 @@ export function registerGetSessionRuntimeTool( } : null, fallback_enabled: runtime.fallbackEnabled ?? false, + ...(targetSessionId === requireCallerSession(deps) && runtime.manualCompact + ? { manual_compact: runtime.manualCompact } : {}), }); }, }); From e470b935f9b16ec067cde37da34d0f633fb59c02 Mon Sep 17 00:00:00 2001 From: amanayayatu-tech <267095040+amanayayatu-tech@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:22:05 +0100 Subject: [PATCH 2/2] test(desktop): stub compact assembly in the send guard fixture Signed-off-by: amanayayatu-tech <267095040+amanayayatu-tech@users.noreply.github.com> --- .../__tests__/sendToSessionLazyResumePermission.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts index b15d37999f0..e327e3a5815 100644 --- a/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts +++ b/apps/desktop/src/main/maker-ipc/__tests__/sendToSessionLazyResumePermission.test.ts @@ -194,6 +194,8 @@ function botTaskDispatchHarness( }; const dbClient = { drizzle: { select: () => dbChain } }; const stubs: Record = { + // The slice initializes the compact service, but these fixtures only dispatch sends. + createDeferredSessionCompact: () => ({}), getPluginHostToolCaller: () => undefined, sanitizeSourceName, getInstalledGhostName: () => 'Dashboard',